fsanyoto commited on
Commit
ef68ae0
Β·
verified Β·
1 Parent(s): 7c8e2fa

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
Files changed (45) hide show
  1. RELEASES.json +7 -1
  2. VERSION +1 -1
  3. api/automation_engine.py +25 -0
  4. api/main.py +18 -0
  5. api/routes_automation.py +19 -1
  6. api/routes_grid.py +27 -8
  7. api/routes_nav.py +19 -5
  8. api/routes_records.py +8 -0
  9. api/routes_shares.py +24 -4
  10. api/routes_tables.py +54 -15
  11. api/routes_uploads.py +98 -0
  12. platform/aios_grid.py +8 -0
  13. platform/aios_grid_fields.json +12 -2
  14. platform/core/alerts.py +18 -0
  15. platform/core/grid_events.py +97 -4
  16. platform/core/shares.py +24 -0
  17. platform/core/table_store.py +28 -0
  18. platform/core/user_tables.py +63 -7
  19. platform/harness/measure_filter.py +10 -2
  20. platform/harness/semantic.py +8 -1
  21. platform/model/metrics/sales.yml +24 -0
  22. platform/modules/customer_data.py +11 -2
  23. requirements.txt +6 -1
  24. web/public/sample_customers.json +32 -14
  25. web/src/automation/AutomationCanvas.tsx +7 -0
  26. web/src/automation/AutomationCreate.tsx +430 -425
  27. web/src/automation/AutomationDetail.tsx +1025 -999
  28. web/src/automation/AutomationSteps.tsx +407 -0
  29. web/src/automation/AutomationSurface.tsx +311 -307
  30. web/src/automation/automationApi.ts +378 -357
  31. web/src/automation/steps.ts +112 -0
  32. web/src/customer-grid/CustomerGrid.tsx +0 -0
  33. web/src/customer-grid/RecordDetail.css +4 -4
  34. web/src/customer-grid/SelectFromFile.tsx +244 -0
  35. web/src/customer-grid/ViewSidebar.tsx +87 -17
  36. web/src/customer-grid/apiBridge.ts +187 -13
  37. web/src/customer-grid/fileSelect.ts +184 -0
  38. web/src/customer-grid/folders.ts +39 -1
  39. web/src/customer-grid/types.ts +82 -3
  40. web/src/customer-grid/useCustomerData.ts +27 -1
  41. web/src/index.css +0 -0
  42. web/src/shell/NavExtras.tsx +220 -9
  43. web/src/shell/Shell.tsx +53 -1
  44. web/src/shell/nav.ts +124 -0
  45. web/src/shell/navExtras.css +79 -1
RELEASES.json CHANGED
@@ -1,6 +1,12 @@
1
  {
2
- "current": "v5 (c0b0fbb)",
3
  "releases": [
 
 
 
 
 
 
4
  {
5
  "version": "v5",
6
  "sha": "c0b0fbb",
 
1
  {
2
+ "current": "v6 (a344020)",
3
  "releases": [
4
+ {
5
+ "version": "v6",
6
+ "sha": "a344020",
7
+ "date": "2026-08-05",
8
+ "subject": "release v6"
9
+ },
10
  {
11
  "version": "v5",
12
  "sha": "c0b0fbb",
VERSION CHANGED
@@ -1 +1 @@
1
- v5 (c0b0fbb)
 
1
+ v6 (a344020)
api/automation_engine.py CHANGED
@@ -643,6 +643,31 @@ def ut_all(rt):
643
  return {}
644
 
645
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
646
  def ut_get(rt, key):
647
  return ut_all(rt).get(str(key))
648
 
 
643
  return {}
644
 
645
 
646
+ def disable_for_table(rt, table_key, note="target database deleted"):
647
+ """Wave 21 (item 6a, C3): a deleted table's automations are DISABLED loudly, never deleted.
648
+
649
+ The definition survives with `schedule.enabled = False` + a `statusNote`, so the rail still
650
+ shows what existed and why it stopped β€” silently deleting a user's automation because its
651
+ target died would read as data loss. Returns the ids it touched."""
652
+ key = str(table_key or "")
653
+ touched = []
654
+
655
+ def _up(cur):
656
+ for aid, d in (cur or {}).items():
657
+ if isinstance(d, dict) and (d.get("config") or {}).get("targetTable") == key:
658
+ sch = d.get("schedule")
659
+ if not isinstance(sch, dict):
660
+ sch = d["schedule"] = {}
661
+ sch["enabled"] = False
662
+ d["statusNote"] = note
663
+ touched.append(str(aid))
664
+ return cur
665
+
666
+ if key:
667
+ rt.update(STORE_KEY, _up, flush="sync")
668
+ return touched
669
+
670
+
671
  def ut_get(rt, key):
672
  return ut_all(rt).get(str(key))
673
 
api/main.py CHANGED
@@ -69,6 +69,7 @@ import routes_platform_admin # noqa: E402 (wave 19 R3/R4 β€” the Loopable cros
69
  import routes_products # noqa: E402 (wave 15 C-TOPIC β€” gated, not yet in the nav)
70
  import routes_records # noqa: E402
71
  import routes_shares # noqa: E402 (wave 20 R10 β€” grants for views, folders and databases)
 
72
  import routes_tables # noqa: E402 (wave 18 C3-UT β€” user-created databases over the wire)
73
  from core import grid_events # noqa: E402
74
  from deps import Session, module_gate # noqa: E402
@@ -200,6 +201,7 @@ app.include_router(routes_platform_admin.router)
200
  # something every user does with their own views/folders/databases.
201
  app.include_router(routes_alerts.router)
202
  app.include_router(routes_shares.router)
 
203
 
204
 
205
  # --- DEPRECATED ALIASES (removed when S2's shell flips; kept so the current bundle keeps working)
@@ -334,6 +336,15 @@ def _seed_and_sync_store():
334
  + ", ".join(f"{k}={v.get('phase')}" for k, v in sorted(res.items())))
335
  if all(v.get("phase") == "live" for v in res.values()):
336
  break
 
 
 
 
 
 
 
 
 
337
  print(f"[aios-api] datastore sync done in {_t.time() - t0:.1f}s "
338
  f"(ready={_ds.ready()})")
339
  except Exception as e: # noqa: BLE001
@@ -345,8 +356,10 @@ def _store_resync_loop():
345
  Streamlit app piggybacks on page renders. Measure memos key on the pool stamp, so a
346
  refreshed pool re-reads the freshly synced store."""
347
  import time as _t
 
348
  while True:
349
  _t.sleep(1800)
 
350
  try:
351
  from harness import datastore as _ds
352
  import core.odoo as _odoo
@@ -355,6 +368,11 @@ def _store_resync_loop():
355
  except Exception:
356
  pass
357
  _ds.sync_all(log=lambda *a, **k: None)
 
 
 
 
 
358
  except Exception as e: # noqa: BLE001
359
  print(f"[aios-api] store resync failed: {e}")
360
 
 
69
  import routes_products # noqa: E402 (wave 15 C-TOPIC β€” gated, not yet in the nav)
70
  import routes_records # noqa: E402
71
  import routes_shares # noqa: E402 (wave 20 R10 β€” grants for views, folders and databases)
72
+ import routes_uploads # noqa: E402 (wave 21 C5 β€” tabular preview for Select-from-file)
73
  import routes_tables # noqa: E402 (wave 18 C3-UT β€” user-created databases over the wire)
74
  from core import grid_events # noqa: E402
75
  from deps import Session, module_gate # noqa: E402
 
201
  # something every user does with their own views/folders/databases.
202
  app.include_router(routes_alerts.router)
203
  app.include_router(routes_shares.router)
204
+ app.include_router(routes_uploads.router)
205
 
206
 
207
  # --- DEPRECATED ALIASES (removed when S2's shell flips; kept so the current bundle keeps working)
 
336
  + ", ".join(f"{k}={v.get('phase')}" for k, v in sorted(res.items())))
337
  if all(v.get("phase") == "live" for v in res.values()):
338
  break
339
+ # ⭐ Wave 21 (item 2, "make sure the metrics are correct"): a cursor sync can never see
340
+ # a HARD DELETE, and the downloaded seed carries whatever was deleted since it was cut β€”
341
+ # one reconcile pass at boot removes both classes of phantom row before the first
342
+ # measure is served. MEASURED 2026-08-05: five deleted sale_order_line rows = $284.25 of
343
+ # phantom YTD revenue, stable across re-syncs, zero the moment reconcile ran.
344
+ try:
345
+ _ds.reconcile_deletes(log=lambda *a, **k: None)
346
+ except Exception:
347
+ pass
348
  print(f"[aios-api] datastore sync done in {_t.time() - t0:.1f}s "
349
  f"(ready={_ds.ready()})")
350
  except Exception as e: # noqa: BLE001
 
356
  Streamlit app piggybacks on page renders. Measure memos key on the pool stamp, so a
357
  refreshed pool re-reads the freshly synced store."""
358
  import time as _t
359
+ passes = 0
360
  while True:
361
  _t.sleep(1800)
362
+ passes += 1
363
  try:
364
  from harness import datastore as _ds
365
  import core.odoo as _odoo
 
368
  except Exception:
369
  pass
370
  _ds.sync_all(log=lambda *a, **k: None)
371
+ # Wave 21 β€” every 4th pass (~2h): purge hard-deleted rows the cursor sync cannot
372
+ # see (the boot pass's comment has the measured case). Cheap id-sweep per entity;
373
+ # without it deleted Odoo lines inflate every sum on the mirror FOREVER.
374
+ if passes % 4 == 0:
375
+ _ds.reconcile_deletes(log=lambda *a, **k: None)
376
  except Exception as e: # noqa: BLE001
377
  print(f"[aios-api] store resync failed: {e}")
378
 
api/routes_automation.py CHANGED
@@ -52,6 +52,21 @@ def _wire(defn, tenant):
52
  }
53
 
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  @router.get("/automations")
56
  def list_automations(session: Session = Depends(_GATE)):
57
  """`{automations: [...], kinds: [...], cronPresets: [...]}` β€” the rail's whole payload.
@@ -85,7 +100,10 @@ def list_automations(session: Session = Depends(_GATE)):
85
  "nullaryOperators": list(engine.BD_NULLARY_OPS),
86
  "maxRecords": engine.BD_MAX_RECORDS,
87
  "table": engine.DISCOVER_TABLE},
88
- "storeAvailable": bool(session.runtime.available())}
 
 
 
89
 
90
 
91
  @router.post("/automations/discover/estimate")
 
52
  }
53
 
54
 
55
+ def _tick_state():
56
+ """⭐ WAVE 21 (C6 amendment A1) β€” can a SCHEDULE fire on this deployment?
57
+
58
+ TWO independent paths can: the in-process scheduler (`AIOS_AUTOMATIONS=1`,
59
+ `automation_engine.py` module bottom) and an external cron POSTing `/automations/tick`,
60
+ gated on `AIOS_AUTOMATION_TICK_TOKEN` (AWS EventBridge in production). The Step-1 Trigger
61
+ card must be honest in both directions: "schedules won't fire" on a deployment where
62
+ EventBridge demonstrably fires them daily is the exact lie R9 forbids. `external` means
63
+ "the door is OPEN", never "the caller is alive" β€” the client's copy says so."""
64
+ inproc = os.environ.get("AIOS_AUTOMATIONS") == "1"
65
+ ext = bool(os.environ.get("AIOS_AUTOMATION_TICK_TOKEN"))
66
+ return {"enabled": bool(inproc or ext),
67
+ "source": "in-process" if inproc else ("external" if ext else "")}
68
+
69
+
70
  @router.get("/automations")
71
  def list_automations(session: Session = Depends(_GATE)):
72
  """`{automations: [...], kinds: [...], cronPresets: [...]}` β€” the rail's whole payload.
 
100
  "nullaryOperators": list(engine.BD_NULLARY_OPS),
101
  "maxRecords": engine.BD_MAX_RECORDS,
102
  "table": engine.DISCOVER_TABLE},
103
+ "storeAvailable": bool(session.runtime.available()),
104
+ # Wave 21 C6-A1: {"enabled": bool, "source": "in-process"|"external"|""} β€” see
105
+ # `_tick_state` for why one boolean off AIOS_AUTOMATIONS alone would lie.
106
+ "tick": _tick_state()}
107
 
108
 
109
  @router.post("/automations/discover/estimate")
api/routes_grid.py CHANGED
@@ -26,7 +26,7 @@ import time
26
 
27
  from fastapi import APIRouter, Body, Depends
28
 
29
- from deps import Session, err, module_gate, perms
30
 
31
  router = APIRouter(prefix="/api/v1")
32
 
@@ -103,9 +103,17 @@ def _scope_or_400(raw):
103
 
104
  @router.get("/workspace")
105
  def workspace(scope: str = "customer",
106
- session: Session = Depends(module_gate(MODULE))):
107
  """The durable table workspace for this session: views, fields, overlays, folders.
108
 
 
 
 
 
 
 
 
 
109
  ⚠ WHY THIS EXISTS (S1↔S2, 2026-07-30 β€” an X2 AMENDMENT, see the split doc). X2 fixes
110
  `/customers` at the exact shape `verify_fields_contract.py` referees, so the workspace cannot
111
  ride along in it without forking the thing that gate keeps single-sourced. Without a
@@ -121,6 +129,11 @@ def workspace(scope: str = "customer",
121
  from routes_customers import grid_assembly
122
 
123
  scope = _scope_or_400(scope)
 
 
 
 
 
124
  # ── Wave 18 C3-UT: a USER TABLE'S workspace β€” the third topic through the one wire. The
125
  # storage key has no (bu, agent) because a user table has no Odoo scope; per-user by the
126
  # table's own wall (creator or admin, `user_tables.may_open`).
@@ -167,9 +180,8 @@ def workspace(scope: str = "customer",
167
  if scope == "product":
168
  from routes_products import MODULE as PRODUCT_MODULE, product_assembly
169
 
170
- # β›” THE GATE CHANGES WITH THE SCOPE. This route's dependency asserts the CUSTOMER
171
- # grant; a caller asking for the product surface must hold the PRODUCT grant too, or a
172
- # customer-only account could read product workspaces through this one door.
173
  session.require(PRODUCT_MODULE)
174
  storage_key = f"{session.tenant}:product-list:{session.uname}:all:all"
175
  try:
@@ -696,8 +708,12 @@ def grid_calendar_metrics(body: dict = Body(default=None), scope: str = "custome
696
 
697
  @router.post("/grid/events")
698
  def grid_events_route(body: dict = Body(default=None),
699
- session: Session = Depends(module_gate(MODULE))):
700
- """`{events: [<component event objects, verbatim>]}` β†’ `{results, doc?, toast?}`."""
 
 
 
 
701
  from core import grid_events
702
  from routes_customers import grid_assembly
703
 
@@ -715,6 +731,9 @@ def grid_events_route(body: dict = Body(default=None),
715
  # typo degraded silently to customer-scope behaviour on a WRITE. Read and write must agree on
716
  # what a scope is, or the surface you read is not the surface you wrote.
717
  scope = _scope_or_400((body or {}).get("scopeKey"))
 
 
 
718
  # This assembly validates the write; it is not a payload the browser will render. Leave
719
  # one-shot field-name correction acks queued for the subsequent /workspace refresh.
720
  # Wave 16 C-TOPIC: the PRODUCT topic gets the product assembly β€” product field contract,
@@ -725,7 +744,7 @@ def grid_events_route(body: dict = Body(default=None),
725
  if scope == "product":
726
  from routes_products import MODULE as PRODUCT_MODULE, product_assembly
727
 
728
- session.require(PRODUCT_MODULE) # the route's own dependency asserts only customer_data
729
  g = product_assembly(session, consume_corrections=False)
730
  elif scope.startswith("ut_"):
731
  # Wave 18 C3-UT β€” the user-table wall (creator/admin) is inside the assembly; the
 
26
 
27
  from fastapi import APIRouter, Body, Depends
28
 
29
+ from deps import Session, err, module_gate, perms, require_session
30
 
31
  router = APIRouter(prefix="/api/v1")
32
 
 
103
 
104
  @router.get("/workspace")
105
  def workspace(scope: str = "customer",
106
+ session: Session = Depends(require_session)):
107
  """The durable table workspace for this session: views, fields, overlays, folders.
108
 
109
+ β›” WAVE 21 (C4): the wall is TOPIC-SHAPED, so the DEPENDENCY is session-only and each scope
110
+ asserts its own gate below. The old `module_gate("customer_data")` dependency 403'd a
111
+ `ut_*` workspace for any tenant whose catalogue omits the customer module (loopable/
112
+ nurilab/gtmlab ship modules w/o it) β€” and the client then fell back to the shared
113
+ localStorage bucket + demo data, which is exactly the "new database shows RI's customer
114
+ fields" defect. A user table's real wall is `user_tables.may_open`, enforced inside
115
+ `ut_assembly` (404/403, one layer down where the store can be consulted).
116
+
117
  ⚠ WHY THIS EXISTS (S1↔S2, 2026-07-30 β€” an X2 AMENDMENT, see the split doc). X2 fixes
118
  `/customers` at the exact shape `verify_fields_contract.py` referees, so the workspace cannot
119
  ride along in it without forking the thing that gate keeps single-sourced. Without a
 
129
  from routes_customers import grid_assembly
130
 
131
  scope = _scope_or_400(scope)
132
+ # Wave 21 C4 β€” the per-scope gate the dependency no longer asserts: customer/cohort need
133
+ # the customer module; product asserts PRODUCT_MODULE in its branch; ut_* needs only a
134
+ # session (its wall is the table's own, inside the assembly).
135
+ if not (scope == "product" or scope.startswith("ut_")):
136
+ session.require(MODULE)
137
  # ── Wave 18 C3-UT: a USER TABLE'S workspace β€” the third topic through the one wire. The
138
  # storage key has no (bu, agent) because a user table has no Odoo scope; per-user by the
139
  # table's own wall (creator or admin, `user_tables.may_open`).
 
180
  if scope == "product":
181
  from routes_products import MODULE as PRODUCT_MODULE, product_assembly
182
 
183
+ # β›” THE GATE CHANGES WITH THE SCOPE (wave 21 C4: the dependency is session-only now,
184
+ # so this line IS the product wall β€” not a second one on top of customer_data).
 
185
  session.require(PRODUCT_MODULE)
186
  storage_key = f"{session.tenant}:product-list:{session.uname}:all:all"
187
  try:
 
708
 
709
  @router.post("/grid/events")
710
  def grid_events_route(body: dict = Body(default=None),
711
+ session: Session = Depends(require_session)):
712
+ """`{events: [<component event objects, verbatim>]}` β†’ `{results, doc?, toast?}`.
713
+
714
+ Wave 21 C4: session-only dependency, per-scope gate below β€” the write door must admit the
715
+ same sessions the read door (`/workspace`) admits, or a tenant without the customer module
716
+ can SEE its own user tables and not write to them."""
717
  from core import grid_events
718
  from routes_customers import grid_assembly
719
 
 
731
  # typo degraded silently to customer-scope behaviour on a WRITE. Read and write must agree on
732
  # what a scope is, or the surface you read is not the surface you wrote.
733
  scope = _scope_or_400((body or {}).get("scopeKey"))
734
+ # Wave 21 C4 β€” same per-scope gate as /workspace (read and write doors must agree).
735
+ if not (scope == "product" or scope.startswith("ut_")):
736
+ session.require(MODULE)
737
  # This assembly validates the write; it is not a payload the browser will render. Leave
738
  # one-shot field-name correction acks queued for the subsequent /workspace refresh.
739
  # Wave 16 C-TOPIC: the PRODUCT topic gets the product assembly β€” product field contract,
 
744
  if scope == "product":
745
  from routes_products import MODULE as PRODUCT_MODULE, product_assembly
746
 
747
+ session.require(PRODUCT_MODULE) # the product wall (dependency is session-only, C4)
748
  g = product_assembly(session, consume_corrections=False)
749
  elif scope.startswith("ut_"):
750
  # Wave 18 C3-UT β€” the user-table wall (creator/admin) is inside the assembly; the
api/routes_nav.py CHANGED
@@ -184,17 +184,31 @@ def nav(session: Session = Depends(require_session)):
184
  # leak with no symptom until two tenants rename the same registry key. Copy the rows before
185
  # merging on the day that invariant changes.
186
  meta = _read_nav_meta(session.runtime)
 
 
 
 
 
 
187
  for p in pages:
188
  # `manage` (R14): may THIS session change this row's icon/name? Answered HERE because
189
  # the server is the only end that knows β€” the client cannot see who created a user
190
  # table. Additive and FAIL-CLOSED (absent reads as "no"), so the rail offers a control
191
  # only where the write would actually land, and the route re-checks it regardless.
192
  #
193
- # ⚠ A `ut_` row's presence IS the answer: `user_tables.nav_entries` above filters by
194
- # `may_open`, so a user table this session cannot manage never reached this list. That
195
- # is why this line needs no second lookup β€” and why it must move if that filter ever
196
- # widens to include tables a viewer may READ but not own.
197
- if str(p.get("key", "")).startswith("ut_") or session.admin:
 
 
 
 
 
 
 
 
198
  p["manage"] = True
199
  entry = meta.get(p.get("key")) if meta else None
200
  if not entry:
 
184
  # leak with no symptom until two tenants rename the same registry key. Copy the rows before
185
  # merging on the day that invariant changes.
186
  meta = _read_nav_meta(session.runtime)
187
+ # Wave 21 (C3): the definitions, once β€” `manage`/`canDelete` below answer from `createdBy`.
188
+ try:
189
+ import core.user_tables as _ut_mod
190
+ _ut_defs = _ut_mod.all_tables(st=session.runtime) or {}
191
+ except Exception:
192
+ _ut_defs = {}
193
  for p in pages:
194
  # `manage` (R14): may THIS session change this row's icon/name? Answered HERE because
195
  # the server is the only end that knows β€” the client cannot see who created a user
196
  # table. Additive and FAIL-CLOSED (absent reads as "no"), so the rail offers a control
197
  # only where the write would actually land, and the route re-checks it regardless.
198
  #
199
+ # β›” WAVE 21 (C3/W-5): the "presence IS the answer" shortcut DIED in wave 20 β€” the
200
+ # de5037f share-grant admission widened `may_open`, so a row's presence now includes
201
+ # databases merely SHARED to this viewer. `manage` (rename/icon) and `canDelete` are
202
+ # therefore answered from the DEFINITION: creator-or-admin strictly, matching the
203
+ # walls the PATCH and DELETE routes actually enforce. A grantee sees the row and no
204
+ # controls β€” the honest shape (the old code offered rename to users the route 403'd).
205
+ key = str(p.get("key", ""))
206
+ if key.startswith("ut_"):
207
+ _creator = str((_ut_defs.get(key) or {}).get("createdBy") or "")
208
+ _mine = bool(session.admin or (_creator and _creator == session.uname))
209
+ p["manage"] = _mine
210
+ p["canDelete"] = _mine
211
+ elif session.admin:
212
  p["manage"] = True
213
  entry = meta.get(p.get("key")) if meta else None
214
  if not entry:
api/routes_records.py CHANGED
@@ -86,6 +86,12 @@ def _unavailable():
86
  )
87
 
88
 
 
 
 
 
 
 
89
  @router.get("/customers/{pid}/comments")
90
  def comments(pid: int, scope: str = Query(default="customer"),
91
  session: Session = Depends(require_session)):
@@ -100,6 +106,7 @@ def comments(pid: int, scope: str = Query(default="customer"),
100
  return {"comments": rows}
101
 
102
 
 
103
  @router.post("/customers/{pid}/comments", status_code=201)
104
  def create_comment(
105
  pid: int,
@@ -127,6 +134,7 @@ def create_comment(
127
  return {"comment": comment}
128
 
129
 
 
130
  @router.delete("/customers/{pid}/comments/{comment_id}")
131
  def remove_comment(
132
  pid: int,
 
86
  )
87
 
88
 
89
+ # ⭐ WAVE 21 (D-17): the CANONICAL path is /records/{pid}/comments β€” comments hang off a RECORD
90
+ # in whatever topic `?scope=` names, and the customer-flavoured noun was wave-19 residue (the
91
+ # wall was always the query param). The old path stays as an ALIAS because the shipped client
92
+ # still calls it; verify_api pins the canonical path AND that the alias answers, so removing
93
+ # the alias later is a decision, never an accident.
94
+ @router.get("/records/{pid}/comments")
95
  @router.get("/customers/{pid}/comments")
96
  def comments(pid: int, scope: str = Query(default="customer"),
97
  session: Session = Depends(require_session)):
 
106
  return {"comments": rows}
107
 
108
 
109
+ @router.post("/records/{pid}/comments", status_code=201)
110
  @router.post("/customers/{pid}/comments", status_code=201)
111
  def create_comment(
112
  pid: int,
 
134
  return {"comment": comment}
135
 
136
 
137
+ @router.delete("/records/{pid}/comments/{comment_id}")
138
  @router.delete("/customers/{pid}/comments/{comment_id}")
139
  def remove_comment(
140
  pid: int,
api/routes_shares.py CHANGED
@@ -56,13 +56,33 @@ def get_share(kind: str, oid: str, session: Session = Depends(require_session)):
56
  st=session.runtime),
57
  "mayAdminister": shares.may_administer(kind, oid, session.uname, is_admin=session.admin,
58
  st=session.runtime),
59
- # The people this account may share WITH β€” reusing the ONE definition of an assignable
60
- # person (`core.users.assignable_people`, the same list the `user` field kind offers), so
61
- # the share picker and the assignee picker can never disagree about who exists.
62
- "people": users.assignable_people(tenant=session.tenant),
 
 
63
  }
64
 
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  @router.put("/share/{kind}/{oid}")
67
  def put_share(kind: str, oid: str, body: dict = Body(default=None),
68
  session: Session = Depends(require_session)):
 
56
  st=session.runtime),
57
  "mayAdminister": shares.may_administer(kind, oid, session.uname, is_admin=session.admin,
58
  st=session.runtime),
59
+ # ⚠ WAVE 21 (C1 identity fix): grant entries BIND on USERNAMES, so the picker must carry
60
+ # them. `assignable_people` serves bare display names because `user`-kind CELLS store
61
+ # display names β€” that list's shape cannot change without migrating cell values β€” so
62
+ # this route serves objects of its own. Existing grants that were written as lowercased
63
+ # display names are normalised by the wave-21 cleanup script.
64
+ "people": _people(session.tenant),
65
  }
66
 
67
 
68
+ def _people(tenant):
69
+ """[{username, name}] for this tenant β€” same population as `assignable_people`, with the
70
+ BINDING identity alongside the display one."""
71
+ try:
72
+ reg = users.registry() or {}
73
+ except Exception:
74
+ return []
75
+ want = str(tenant or '').strip().lower()
76
+ out = []
77
+ for uname, u in reg.items():
78
+ if not isinstance(u, dict) or u.get('active') is False:
79
+ continue
80
+ if want and str(u.get('tenant') or 'royal-imports').strip().lower() != want:
81
+ continue
82
+ out.append({"username": str(uname), "name": str(u.get('name') or uname)})
83
+ return sorted(out, key=lambda p: p["name"].lower())
84
+
85
+
86
  @router.put("/share/{kind}/{oid}")
87
  def put_share(kind: str, oid: str, body: dict = Body(default=None),
88
  session: Session = Depends(require_session)):
api/routes_tables.py CHANGED
@@ -197,27 +197,66 @@ def patch_table(table_key: str, body: dict = Body(default=None),
197
  return {"key": table_key, "label": label}
198
 
199
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  @router.delete("/tables/{table_key}")
201
  def delete_table(table_key: str, session: Session = Depends(require_session)):
202
- """Creator or admin only β€” the same actors `may_open` admits, and deletion is the one
203
- operation the client must confirm explicitly (the server cannot tell a click from a plan).
204
-
205
- ⚠ WAVE 20, item 3 β€” THE OWNER'S "an admin cannot delete a database" IS NOT A WALL BUG HERE.
206
- Measured: **no client calls this route at all.** The React shell POSTs `/tables` to create
207
- one and has no delete affordance anywhere, so the endpoint is live, correct and unreachable.
208
- The wall's real defect was next door and is fixed: `routes_automation` carried a SECOND,
209
- wider ownership rule, and the engine stamped `createdBy: "scheduler"` on tables a cron
210
- created first β€” which made a table's owner depend on a race, and left it admin-only forever
211
- after. See `user_tables.MACHINE_OWNERS` and `automation_engine.ut_ensure`.
212
- """
213
- _defn_or_refuse(session, table_key)
 
 
 
 
 
 
 
214
  try:
215
  _ut().delete(table_key, st=session.runtime)
216
  except Exception:
217
  raise err(503, "store_unavailable", "the delete did not land β€” try again")
218
- # The workspace bucket (views/custom fields/overlays) is left in place: a delete that also
219
- # destroyed per-user state would make an accidental delete unrecoverable, and the bucket is
220
- # invisible without its definition. Booked, not hidden.
221
  return {"ok": True}
222
 
223
 
 
197
  return {"key": table_key, "label": label}
198
 
199
 
200
+ @router.get("/tables/{table_key}/footprint")
201
+ def table_footprint(table_key: str, session: Session = Depends(require_session)):
202
+ """What dies with this database β€” the confirm dialog's disclosure (wave 21, item 6a / C3).
203
+
204
+ Counts drill to the SAME buckets `user_tables.delete` cleans; a dialog listing categories
205
+ without numbers would break [[no-unverifiable-aggregates]] at the scariest moment. Walled
206
+ like the delete itself: only someone who could delete may case the joint."""
207
+ defn = _defn_or_refuse(session, table_key)
208
+ if not (session.admin or defn.get("createdBy") == session.uname):
209
+ raise err(403, "forbidden", "only the database's creator or an admin can delete it")
210
+ s = session.runtime
211
+ views, fields = set(), len(defn.get("fields") or [])
212
+ try:
213
+ bucket = s.get(f"{table_key}_table_workspace") or {}
214
+ for _u, ws in bucket.items():
215
+ if isinstance(ws, dict):
216
+ views |= set((ws.get("views") or {}).keys())
217
+ fields += len(ws.get("fields") or {}) # per-user custom/measure strata
218
+ except Exception:
219
+ pass
220
+ import core.shares as shares
221
+ g = shares.grants("database", table_key, st=s)
222
+ auto = []
223
+ try:
224
+ import automation_engine as engine
225
+ for aid, d in (engine.all_definitions(s) or {}).items():
226
+ if (d.get("config") or {}).get("targetTable") == str(table_key):
227
+ auto.append({"id": str(aid), "name": d.get("name") or str(aid)})
228
+ except Exception:
229
+ pass
230
+ return {"rows": len(defn.get("rows") or {}), "fields": fields, "views": len(views),
231
+ "sharedUsers": len(g.get("entries") or []),
232
+ "automations": sorted(auto, key=lambda a: a["name"].lower())}
233
+
234
+
235
  @router.delete("/tables/{table_key}")
236
  def delete_table(table_key: str, session: Session = Depends(require_session)):
237
+ """CREATOR OR ADMIN β€” checked explicitly (wave 21, item 6a / C3).
238
+
239
+ β›” The wave-20 docstring said "the same actors may_open admits" and that stopped being the
240
+ creator-or-admin set the day de5037f taught `may_open` to admit share GRANTEES: a view-role
241
+ grantee could reach this route and delete the database somebody shared with them. The wall
242
+ is now the definition's own `createdBy`, the same check the rename route always had.
243
+
244
+ Deletion cleans the artifact families server-side (`user_tables.delete` lists them) and
245
+ DISABLES bound automations with a status note β€” never deletes them. The client's confirm
246
+ dialog disclosed `/footprint` first; the server cannot tell a click from a plan, so the
247
+ dialog is a product requirement, not a formality."""
248
+ defn = _defn_or_refuse(session, table_key)
249
+ if not (session.admin or defn.get("createdBy") == session.uname):
250
+ raise err(403, "forbidden", "only the database's creator or an admin can delete it")
251
+ try:
252
+ import automation_engine as engine
253
+ engine.disable_for_table(session.runtime, table_key)
254
+ except Exception:
255
+ pass
256
  try:
257
  _ut().delete(table_key, st=session.runtime)
258
  except Exception:
259
  raise err(503, "store_unavailable", "the delete did not land β€” try again")
 
 
 
260
  return {"ok": True}
261
 
262
 
api/routes_uploads.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """routes_uploads.py β€” ONE tabular-file preview endpoint (wave 21, item 11 / C5, ruling R10).
2
+
3
+ POST /api/v1/uploads/tabular multipart `file` = .xlsx | .csv, <= 5 MB
4
+ -> {"columns": [str], "rows": int, "values": {col: [str, ...]}, "truncated": bool}
5
+
6
+ The grid's "Select from file..." dialog uploads a spreadsheet, offers its columns, and matches
7
+ the chosen column's VALUES against a grid column client-side (exact match after trim+casefold;
8
+ the matches become the grid selection, which feeds the existing bulk actions). This route's
9
+ whole job is honest parsing:
10
+
11
+ * FIRST sheet only (xlsx). Silently unioning sheets would "find" rows the user can see are
12
+ not on the sheet they meant.
13
+ * Every cell STRINGIFIED + trimmed. Matching is string matching by contract, so the wire
14
+ carries strings, never spreadsheet cell types.
15
+ * <= 20,000 data rows, and the cap is DISCLOSED (`truncated: true`), never silent
16
+ ([[no-unverifiable-aggregates]] β€” a silently clipped file would report "6 not found"
17
+ against a tail that was never read).
18
+ * Fully blank rows are padding, not data β€” skipped without counting.
19
+ * The PASTE path never reaches the server at all.
20
+
21
+ β›” openpyxl is imported INSIDE the handler, deliberately. `verify_no_streamlit` boots the whole
22
+ API with openpyxl blocked at sys.meta_path β€” the API must serve every non-upload route without
23
+ it β€” and the manifest half of that gate now asserts the package IS declared in both
24
+ requirements files ([[pin-deps-space-rebuilds]]): absent there, the first upload on a fresh
25
+ container is a 500.
26
+ """
27
+ import csv
28
+ import io
29
+
30
+ from fastapi import APIRouter, Depends, File, UploadFile
31
+
32
+ from deps import Session, err, require_session
33
+
34
+ router = APIRouter(prefix="/api/v1")
35
+
36
+ MAX_BYTES = 5 * 1024 * 1024
37
+ MAX_ROWS = 20_000
38
+
39
+
40
+ def _cell(v):
41
+ return "" if v is None else str(v).strip()
42
+
43
+
44
+ def _headers(row):
45
+ """Stringified, blank-filled, DEDUPED header names β€” two 'SKU' columns must not silently
46
+ merge their values into one list."""
47
+ out, seen = [], {}
48
+ for i, cell in enumerate(row):
49
+ name = _cell(cell) or f"Column {i + 1}"
50
+ n = seen.get(name, 0)
51
+ seen[name] = n + 1
52
+ out.append(name if n == 0 else f"{name} ({n + 1})")
53
+ return out
54
+
55
+
56
+ @router.post("/uploads/tabular")
57
+ async def tabular_preview(file: UploadFile = File(...),
58
+ session: Session = Depends(require_session)):
59
+ name = (file.filename or "").lower()
60
+ data = await file.read()
61
+ if len(data) > MAX_BYTES:
62
+ raise err(400, "too_large",
63
+ "that file is over 5 MB β€” export just the column you need and retry")
64
+ if name.endswith(".csv"):
65
+ text = data.decode("utf-8-sig", errors="replace")
66
+ rows = iter(csv.reader(io.StringIO(text)))
67
+ elif name.endswith(".xlsx"):
68
+ try:
69
+ import openpyxl # lazy BY CONTRACT β€” see the module docstring
70
+ wb = openpyxl.load_workbook(io.BytesIO(data), read_only=True, data_only=True)
71
+ ws = wb.worksheets[0]
72
+ except Exception:
73
+ raise err(400, "bad_file", "that workbook could not be read β€” is it a real .xlsx?")
74
+ rows = ws.iter_rows(values_only=True)
75
+ else:
76
+ raise err(400, "bad_type",
77
+ "upload a .xlsx or .csv file (or paste the values into the dialog instead)")
78
+
79
+ try:
80
+ first = next(iter(rows))
81
+ except StopIteration:
82
+ raise err(400, "empty_file", "that file has no rows")
83
+ except Exception:
84
+ raise err(400, "bad_file", "that file could not be read")
85
+ columns = _headers(list(first))
86
+ values = {c: [] for c in columns}
87
+ count, truncated = 0, False
88
+ for row in rows:
89
+ cells = list(row)
90
+ if not any(_cell(c) for c in cells):
91
+ continue
92
+ if count >= MAX_ROWS:
93
+ truncated = True
94
+ break
95
+ count += 1
96
+ for i, col in enumerate(columns):
97
+ values[col].append(_cell(cells[i]) if i < len(cells) else "")
98
+ return {"columns": columns, "rows": count, "values": values, "truncated": truncated}
platform/aios_grid.py CHANGED
@@ -1690,7 +1690,15 @@ def workspace_wire(ws, uname, pool_pids, defs=None, scope_key='customer', storag
1690
  fields = fields_from_workspace(ws, cohorts=bool(cohort_lists), scope_key=scope_key,
1691
  fields_base=fields_base)
1692
  views = views_from_defs(defs or {}, ws.get('views'), fields,
 
 
 
 
 
 
1693
  system_name=("All products" if scope_key == 'product'
 
 
1694
  else "All customers"),
1695
  locked_lists=cohort_lists)
1696
  workspace = {'storageKey': storage_key, 'views': views, 'lists': cohort_lists}
 
1690
  fields = fields_from_workspace(ws, cohorts=bool(cohort_lists), scope_key=scope_key,
1691
  fields_base=fields_base)
1692
  views = views_from_defs(defs or {}, ws.get('views'), fields,
1693
+ # Wave 21 (item 3, R6): the system view's name is TOPIC-DERIVED. A
1694
+ # user database's default view used to read "All customers" β€” a
1695
+ # compiled customer literal minted on every topic, one half of the
1696
+ # owner's "my new database looks like RI's Customer table". The ID
1697
+ # stays 'all-customers' everywhere (pinned client+server β€” the
1698
+ # client's UNDELETABLE set and the view pin both name it).
1699
  system_name=("All products" if scope_key == 'product'
1700
+ else "All records"
1701
+ if str(scope_key or '').startswith('ut_')
1702
  else "All customers"),
1703
  locked_lists=cohort_lists)
1704
  workspace = {'storageKey': storage_key, 'views': views, 'lists': cohort_lists}
platform/aios_grid_fields.json CHANGED
@@ -139,12 +139,13 @@
139
  "description": "Estimated sales missed while quiet: missed orders (capped at 3) times average order value. An estimate, not money owed."
140
  },
141
  {
 
142
  "key": "ar_open",
143
- "label": "AR open $",
144
  "type": "currency",
145
  "source": "odoo",
146
  "default": false,
147
- "description": "Invoiced money owed, not yet overdue."
148
  },
149
  {
150
  "key": "ar_overdue",
@@ -154,6 +155,15 @@
154
  "default": false,
155
  "description": "Invoiced money past due \u2014 same basis as the Collections page."
156
  },
 
 
 
 
 
 
 
 
 
157
  {
158
  "key": "ar_exposure",
159
  "label": "Credit exposure $",
 
139
  "description": "Estimated sales missed while quiet: missed orders (capped at 3) times average order value. An estimate, not money owed."
140
  },
141
  {
142
+ "_note": "wave 21 R1 \u2014 KEY UNCHANGED, LABEL RENAMED. The computation is a DISJOINT split (ar.py credit_exposure): this column is only the not-yet-due residual, its sibling is the past-grace residual, and the two sum to the total. Under the label 'AR open $' the majority-late book read as 'Overdue > Open', which is nonsense in AR vocabulary \u2014 'open' universally means the total. The label now says what the number is; the key stays so saved views and filters keep working.",
143
  "key": "ar_open",
144
+ "label": "AR current $",
145
  "type": "currency",
146
  "source": "odoo",
147
  "default": false,
148
+ "description": "Invoiced money owed but not yet due (a 5-day grace applies before it counts as overdue)."
149
  },
150
  {
151
  "key": "ar_overdue",
 
155
  "default": false,
156
  "description": "Invoiced money past due \u2014 same basis as the Collections page."
157
  },
158
+ {
159
+ "_note": "wave 21 R1 \u2014 the TOTAL, added beside the rename above. AR current $ + AR overdue $, i.e. what most people mean by 'open AR'. Composed from the same ar.credit_exposure rows the siblings use, so it is transitively reconciled by ar.validate()'s residual read_group tie \u2014 no second oracle.",
160
+ "key": "ar_outstanding",
161
+ "label": "AR outstanding $",
162
+ "type": "currency",
163
+ "source": "odoo",
164
+ "default": false,
165
+ "description": "Total invoiced money owed right now: AR current $ plus AR overdue $."
166
+ },
167
  {
168
  "key": "ar_exposure",
169
  "label": "Credit exposure $",
platform/core/alerts.py CHANGED
@@ -104,6 +104,24 @@ def create(alert_id, *, view_id, topic, owner, label='', st=None):
104
  return rec
105
 
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  def delete(alert_id, st=None):
108
  def _apply(data):
109
  data.pop(str(alert_id), None)
 
104
  return rec
105
 
106
 
107
+ def drop_topic(topic, st=None):
108
+ """Delete every alert DEFINITION on a topic (wave 21, item 6a / C3 β€” a deleted database's
109
+ alerts die with it; an alert on a view that no longer exists can only ever error).
110
+ Notifications already delivered are left in inboxes: they are history, and history is the
111
+ one thing a delete must not rewrite."""
112
+ t = str(topic or '')
113
+ if not t:
114
+ return
115
+
116
+ def _apply(data):
117
+ for aid in [k for k, r in (data or {}).items()
118
+ if isinstance(r, dict) and str(r.get('topic') or '') == t]:
119
+ data.pop(aid, None)
120
+ return data
121
+
122
+ _st(st).update(ALERTS_KEY, _apply, flush='async')
123
+
124
+
125
  def delete(alert_id, st=None):
126
  def _apply(data):
127
  data.pop(str(alert_id), None)
platform/core/grid_events.py CHANGED
@@ -208,8 +208,17 @@ def table_workspace(ctx, allowed_pids=None, consume_corrections=True):
208
  except Exception as _se:
209
  _tel.error('sharedviews:read', _se)
210
  shared = {}
211
- if shared:
212
- merged = dict(shared)
 
 
 
 
 
 
 
 
 
213
  merged.update(ws.get('views') or {}) # own views win the id collision
214
  ws['views'] = {vid: scope_view(v, uname, allowed_pids)
215
  for vid, v in merged.items()}
@@ -222,6 +231,41 @@ def table_workspace(ctx, allowed_pids=None, consume_corrections=True):
222
  uname, {'views': {}, 'fields': {}, 'overlays': {}})
223
 
224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  def scope_view(view, uname, allowed_pids):
226
  """Re-scope a view to the READER. A no-op for a view the reader created.
227
 
@@ -696,11 +740,42 @@ def handle_one(event, ctx):
696
  if (isinstance(value, dict) and value.get('id') != view_id
697
  and value.get('kind') in ('system', 'list'))
698
  ]
 
 
 
 
 
 
699
  if view_id != 'all-customers':
700
- _reserved_view_names.append('All customers')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
701
  if store.available():
702
  view = (_tops(ctx).save_view(
703
- uname, view, reserved_names=_reserved_view_names, is_admin=admin) or view)
704
  else:
705
  _session_ready()
706
  _view_names = list(_reserved_view_names)
@@ -759,6 +834,24 @@ def handle_one(event, ctx):
759
  if _raw_shared is not None and not _tstore._may_administer(
760
  _raw_shared, uname, admin):
761
  return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
762
  _tops(ctx).delete_view(uname, view_id)
763
  else:
764
  _session_ready()
 
208
  except Exception as _se:
209
  _tel.error('sharedviews:read', _se)
210
  shared = {}
211
+ # ⭐ WAVE 21 (item 9, C1): the R10 registry's named-user grants, PROJECTED at last.
212
+ # Wave 20 wrote view grants and no reader ever consulted them β€” "Share view…" recorded
213
+ # a row and changed nothing on the receiver's screen.
214
+ try:
215
+ granted = _granted_views(ctx, uname)
216
+ except Exception as _ge:
217
+ _tel.error('sharedviews:granted', _ge)
218
+ granted = {}
219
+ if shared or granted:
220
+ merged = dict(granted)
221
+ merged.update(shared) # the everyone-bucket outranks a grant
222
  merged.update(ws.get('views') or {}) # own views win the id collision
223
  ws['views'] = {vid: scope_view(v, uname, allowed_pids)
224
  for vid, v in merged.items()}
 
231
  uname, {'views': {}, 'fields': {}, 'overlays': {}})
232
 
233
 
234
+ def _granted_views(ctx, uname):
235
+ """{view_id: STAMPED view} for every view GRANTED to `uname` by name (wave 21, item 9, C1).
236
+
237
+ The R10 registry stores bare ids, tenant-scoped through the SAME store handle this topic's
238
+ bucket uses; the record itself is fetched out of the OWNER's personal stratum of THIS
239
+ bucket. An id granted on another topic simply finds nothing here and contributes nothing
240
+ (fail-closed). Each projected view is stamped `shared` / `sharedRole` / `owner` so the
241
+ client can synthesise the "Shared with me" group and disable edit affordances for
242
+ role=view β€” the stamps live on the PROJECTION only, never written back to the store.
243
+ `role_for` is asked with is_admin=False deliberately: the stamp reports the GRANT (the
244
+ registry listed only explicit entries), not the caller's rank.
245
+ """
246
+ import core.shares as shares
247
+ tops = _tops(ctx)
248
+ st = getattr(tops, 'st', None)
249
+ ids = (shares.shared_with(uname, kind='view', st=st) or {}).get('view') or []
250
+ out = {}
251
+ for vid in ids:
252
+ found = tops.find_view(vid) if hasattr(tops, 'find_view') else None
253
+ if not found:
254
+ continue
255
+ owner, view = found
256
+ if owner == uname:
257
+ continue
258
+ role = shares.role_for('view', vid, uname, st=st)
259
+ if role not in ('view', 'edit'):
260
+ continue
261
+ v = dict(view)
262
+ v['shared'] = True
263
+ v['sharedRole'] = role
264
+ v['owner'] = owner
265
+ out[str(vid)] = v
266
+ return out
267
+
268
+
269
  def scope_view(view, uname, allowed_pids):
270
  """Re-scope a view to the READER. A no-op for a view the reader created.
271
 
 
740
  if (isinstance(value, dict) and value.get('id') != view_id
741
  and value.get('kind') in ('system', 'list'))
742
  ]
743
+ # Wave 21 (item 3, R6): the reserved SYSTEM name is PER-TOPIC β€” a ut_ database's system
744
+ # view is "All records", and reserving the customer literal there uniquified a user's
745
+ # honest "All customers" view name against a string that never appears on that topic.
746
+ _scope = str(getattr(ctx, 'scope_key', '') or 'customer').strip().lower()
747
+ _sys_name = ('All products' if _scope == 'product'
748
+ else 'All records' if _scope.startswith('ut_') else 'All customers')
749
  if view_id != 'all-customers':
750
+ _reserved_view_names.append(_sys_name)
751
+ # ⭐ WAVE 21 (item 9, C1) β€” THE FOREIGN-VIEW WALL. A granted view is projected into the
752
+ # receiver's rail, so their autosave can now emit an upsert carrying an id they do not
753
+ # own. Silently saving that into the RECEIVER's stratum would FORK the view (own views
754
+ # win the merge, so the receiver sees their private copy forever and calls sharing
755
+ # broken). Role `edit` (or admin) writes THROUGH to the owner's record β€” config only,
756
+ # never identity or reach: `createdBy`/`permissions` are pinned from the stored record.
757
+ # Role `view` (or no grant) refuses with a toast instead of forking.
758
+ _save_as = uname
759
+ if store.available():
760
+ _foreign = _tops(ctx).find_view(view_id)
761
+ if _foreign and _foreign[0] != uname:
762
+ _o_uname, _stored = _foreign
763
+ if not admin:
764
+ import core.shares as _shares
765
+ if _shares.role_for('view', view_id, uname,
766
+ st=getattr(_tops(ctx), 'st', None)) != 'edit':
767
+ ctx.out.toast = ('That view is shared with you read-only β€” ask its '
768
+ 'owner for edit access.')
769
+ return False
770
+ view['createdBy'] = _stored.get('createdBy', _o_uname)
771
+ if _stored.get('permissions') is not None:
772
+ view['permissions'] = _stored.get('permissions')
773
+ else:
774
+ view.pop('permissions', None)
775
+ _save_as = _o_uname
776
  if store.available():
777
  view = (_tops(ctx).save_view(
778
+ _save_as, view, reserved_names=_reserved_view_names, is_admin=admin) or view)
779
  else:
780
  _session_ready()
781
  _view_names = list(_reserved_view_names)
 
834
  if _raw_shared is not None and not _tstore._may_administer(
835
  _raw_shared, uname, admin):
836
  return False
837
+ # ⭐ WAVE 21 (item 9, C1) β€” the foreign wall, delete half. Contract: a grant of
838
+ # `edit` may delete (there is only one copy and the owner handed over its content);
839
+ # `view` or no grant refuses. The dead grant record is emptied afterwards so the
840
+ # receiver's "Shared with me" heals instead of listing a ghost id forever.
841
+ _foreign = _tops(ctx).find_view(view_id)
842
+ if _foreign and _foreign[0] != uname:
843
+ import core.shares as _shares
844
+ _sst = getattr(_tops(ctx), 'st', None)
845
+ if not admin and _shares.role_for('view', view_id, uname,
846
+ st=_sst) != 'edit':
847
+ ctx.out.toast = 'That view is shared with you read-only.'
848
+ return False
849
+ _tops(ctx).delete_view(_foreign[0], view_id)
850
+ try:
851
+ _shares.set_grants('view', view_id, [], st=_sst)
852
+ except Exception:
853
+ pass
854
+ return False
855
  _tops(ctx).delete_view(uname, view_id)
856
  else:
857
  _session_ready()
platform/core/shares.py CHANGED
@@ -198,3 +198,27 @@ def shared_with(user, kind=None, st=None):
198
  break
199
  out[k] = sorted(hits)
200
  return out if kind is None else {_check_kind(kind): out[_check_kind(kind)]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  break
199
  out[k] = sorted(hits)
200
  return out if kind is None else {_check_kind(kind): out[_check_kind(kind)]}
201
+
202
+
203
+ def drop_objects(pairs, st=None):
204
+ """Remove whole grant RECORDS, owner husk included β€” wave 21, item 6a (C3).
205
+
206
+ A deleted object's grants must die with it: `shared_with` would otherwise serve ghost ids
207
+ into every receiver's "Shared with me" forever, and the ghost would 404 on open. One
208
+ transaction for the whole sweep β€” a table delete drops its database grant plus a view
209
+ grant per view that lived in its bucket."""
210
+ want = {}
211
+ for kind, oid in pairs or ():
212
+ want.setdefault(_check_kind(kind), set()).add(str(oid))
213
+ if not want:
214
+ return
215
+
216
+ def _apply(data):
217
+ for kind, oids in want.items():
218
+ by_kind = data.get(kind)
219
+ if isinstance(by_kind, dict):
220
+ for oid in oids:
221
+ by_kind.pop(oid, None)
222
+ return data
223
+
224
+ _st(st).update(SHARES_KEY, _apply, flush='async')
platform/core/table_store.py CHANGED
@@ -113,6 +113,34 @@ class TableStore:
113
  self.table_key = table_key
114
  self._st = st if st is not None else store
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  # ---------------------------------------------------------------- read
117
  def workspace(self, username, consume_corrections=True):
118
  """One user's durable workspace: always the full three-strata shape."""
 
113
  self.table_key = table_key
114
  self._st = st if st is not None else store
115
 
116
+ @property
117
+ def st(self):
118
+ """The bound store handle β€” for SIBLING registries (core/shares) that must read the
119
+ same tenant's buckets this workspace lives in (wave 21, C1)."""
120
+ return self._st
121
+
122
+ def find_view(self, view_id):
123
+ """`(owner_username, view)` for a view living in ANY personal stratum, else None.
124
+
125
+ ⭐ Wave 21 (item 9, C1): the R10 grant registry names bare ids, so projecting a granted
126
+ view means locating the OWNER's record inside this topic's bucket. Personal strata
127
+ only β€” the `__shared__` bucket has its own read path (`shared_views`), and serving one
128
+ view from two finders is how two copies drift."""
129
+ vid = str(view_id or '').strip()
130
+ if not vid:
131
+ return None
132
+ try:
133
+ data = self._st.get(self.table_key) or {}
134
+ except Exception:
135
+ return None
136
+ for username, ws in data.items():
137
+ if username == SHARED_KEY or not isinstance(ws, dict):
138
+ continue
139
+ v = (ws.get('views') or {}).get(vid)
140
+ if isinstance(v, dict):
141
+ return str(username), dict(v)
142
+ return None
143
+
144
  # ---------------------------------------------------------------- read
145
  def workspace(self, username, consume_corrections=True):
146
  """One user's durable workspace: always the full three-strata shape."""
platform/core/user_tables.py CHANGED
@@ -49,12 +49,17 @@ AUTOMATION_SOURCE = 'Automation'
49
  KEY_PREFIX = 'ut_'
50
 
51
  #: The field types a user table may declare. ⚠ Kept a SUBSET of
52
- #: `aios_grid.CUSTOM_FIELD_TYPES` (gated in verify_api's W18-UT section) β€” minus the two
53
- #: machine-written kinds (`formula` computes client-side over a workspace stratum; a base
54
- #: column of that type would have no author). Local literal rather than an aios_grid import so
55
- #: this module stays dependency-light for the API's boot path.
 
 
 
 
 
56
  UT_FIELD_TYPES = {'text', 'select', 'multiselect', 'user', 'int', 'currency', 'pct', 'date',
57
- 'checkbox', 'phone', 'email', 'url', 'rating'}
58
 
59
 
60
  def _st(st):
@@ -155,10 +160,61 @@ def create(label, username, fields=None, source=None, st=None):
155
 
156
 
157
  def delete(table_key, st=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  def _drop(cur):
159
- cur.pop(str(table_key), None)
160
  return cur
161
- _st(st).update(STORE_KEY, _drop, flush='sync')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
 
163
 
164
  def set_fields(table_key, fields, st=None):
 
49
  KEY_PREFIX = 'ut_'
50
 
51
  #: The field types a user table may declare. ⚠ Kept a SUBSET of
52
+ #: `aios_grid.CUSTOM_FIELD_TYPES` (gated in verify_api's W18-UT section). `formula` and
53
+ #: `created_time` stay out (client-computed / row-datum kinds β€” a base column of either would
54
+ #: have no author); `image` is unchanged this wave. `automation` JOINED in WAVE 21 (item 7a,
55
+ #: contract C2): the engine and the automation-column picker read the DEFINITION, so a
56
+ #: grid-created automation column must be able to live there β€” the column's CELLS stay
57
+ #: machine-written (the engine is the writer). Before this, the grid's automation columns
58
+ #: landed in the per-user workspace stratum and the picker could not see them β€” the owner's
59
+ #: "Choose a column..." stays empty. Local literal rather than an aios_grid import so this
60
+ #: module stays dependency-light for the API's boot path.
61
  UT_FIELD_TYPES = {'text', 'select', 'multiselect', 'user', 'int', 'currency', 'pct', 'date',
62
+ 'checkbox', 'phone', 'email', 'url', 'rating', 'automation'}
63
 
64
 
65
  def _st(st):
 
160
 
161
 
162
  def delete(table_key, st=None):
163
+ """Delete a user table AND its artifact families (wave 21, item 6a / C3).
164
+
165
+ Wave 20 popped the definition alone and booked ten orphan families; the owner then ruled a
166
+ real Delete (R3) with the footprint disclosed in the confirm dialog first, so the cleanup
167
+ is no longer optional. Cleaned here, in one place: definition (`user_tables`) Β· the
168
+ workspace bucket (`<key>_table_workspace`, every stratum incl. `__shared__` β€” views,
169
+ custom fields, overlays, folders) Β· cohorts (`<key>_cohorts`) Β· record comments
170
+ (`<key>_record_comments`) Β· docs metadata (`<key>_docs`; dataset BYTES under
171
+ `docs/<key>/…` become unreachable and are left to storage β€” disclosed, not hidden) Β·
172
+ `nav_meta[<key>]` Β· share grants (the database grant plus a view grant per view that
173
+ lived in this bucket, via `shares.drop_objects`) Β· alert definitions on this topic.
174
+ Bound AUTOMATIONS are the API layer's to disable (platform must not import the engine).
175
+ Every family after the definition is best-effort: a store blip mid-sweep must not resurrect
176
+ the table, and an orphaned empty bucket is residue, not a leak."""
177
+ key = str(table_key)
178
+ s = _st(st)
179
+
180
  def _drop(cur):
181
+ cur.pop(key, None)
182
  return cur
183
+ s.update(STORE_KEY, _drop, flush='sync')
184
+
185
+ ws_key = f'{key}_table_workspace'
186
+ view_ids = set()
187
+ try:
188
+ bucket = s.get(ws_key) or {}
189
+ for _u, ws in bucket.items():
190
+ if isinstance(ws, dict):
191
+ view_ids |= set((ws.get('views') or {}).keys())
192
+ except Exception:
193
+ pass
194
+ for b in (ws_key, f'{key}_cohorts', f'{key}_record_comments', f'{key}_docs'):
195
+ try:
196
+ s.update(b, lambda cur: {}, flush='async')
197
+ except Exception:
198
+ pass
199
+
200
+ def _drop_meta(cur):
201
+ if isinstance(cur, dict):
202
+ cur.pop(key, None)
203
+ return cur
204
+ try:
205
+ s.update('nav_meta', _drop_meta, flush='async')
206
+ except Exception:
207
+ pass
208
+ try:
209
+ import core.shares as shares
210
+ shares.drop_objects([('database', key)] + [('view', v) for v in view_ids], st=s)
211
+ except Exception:
212
+ pass
213
+ try:
214
+ import core.alerts as alerts
215
+ alerts.drop_topic(key, st=s)
216
+ except Exception:
217
+ pass
218
 
219
 
220
  def set_fields(table_key, fields, st=None):
platform/harness/measure_filter.py CHANGED
@@ -33,7 +33,7 @@ Three properties that fall out, none incidental:
33
  `countLabel` keeps counting what it actually has (CG-3 `whole-book` mode).
34
 
35
  ⚠ WHAT MAY BE OFFERED, AND WHY IT IS AN ALLOWLIST
36
- `store_parity()` validates exactly five metrics against live Odoo. Every OTHER sum-metric on the
37
  topic would get an expression with no independent check behind it β€” self-consistent with the rest
38
  of the app and still wrong if the expression is wrong. Against "robust for EVERY numerically
39
  driven object", that gap is load-bearing, so admission is gated on HAVING A CONTRACT and spelled
@@ -89,6 +89,12 @@ ADMITTED = {
89
  # is what `filterable: false` already does for columns.
90
  'returns': {'label': 'Returns $', 'topic': 'credit_notes'},
91
  'returns_pct': {'label': 'Return %', 'topic': 'credit_notes', 'input_scale': 100.0},
 
 
 
 
 
 
92
  }
93
 
94
  #: The metrics `semantic.store_parity()` actually exercises against live Odoo. ADMITTED must be
@@ -96,7 +102,9 @@ ADMITTED = {
96
  #: validation contract"), and stating it as data lets the gate assert it instead of trusting the
97
  #: comment above. Adding a measure here without adding it to store_parity's loop fails the gate.
98
  PARITY_CHECKED = frozenset({'revenue', 'margin', 'units', 'orders', 'customers',
99
- 'returns', 'invoiced'})
 
 
100
 
101
  #: numeric comparison ops, mirroring filter_sql._NUM_CMP. `between` is expressed as two
102
  #: conditions by the caller rather than a third operator shape.
 
33
  `countLabel` keeps counting what it actually has (CG-3 `whole-book` mode).
34
 
35
  ⚠ WHAT MAY BE OFFERED, AND WHY IT IS AN ALLOWLIST
36
+ `store_parity()` validates exactly the PARITY_CHECKED set against live Odoo. Every OTHER sum-metric on the
37
  topic would get an expression with no independent check behind it β€” self-consistent with the rest
38
  of the app and still wrong if the expression is wrong. Against "robust for EVERY numerically
39
  driven object", that gap is load-bearing, so admission is gated on HAVING A CONTRACT and spelled
 
89
  # is what `filterable: false` already does for columns.
90
  'returns': {'label': 'Returns $', 'topic': 'credit_notes'},
91
  'returns_pct': {'label': 'Return %', 'topic': 'credit_notes', 'input_scale': 100.0},
92
+ # ⭐ Wave 21 R2 β€” the FULLY-INVOICED basis as separate entries (owner ruling: entries, not a
93
+ # basis dropdown). Labels follow the picker's existing vocabulary ('Sales', not 'Revenue').
94
+ # Both carry the full contract: store_filter_sql on the store path, live_domain on the live
95
+ # path, and membership in PARITY_CHECKED + store_parity's loop β€” added in the same change.
96
+ 'revenue_invoiced': {'label': 'Sales β€” fully invoiced', 'topic': 'sales_lines'},
97
+ 'orders_invoiced': {'label': 'Orders β€” fully invoiced', 'topic': 'sales_orders'},
98
  }
99
 
100
  #: The metrics `semantic.store_parity()` actually exercises against live Odoo. ADMITTED must be
 
102
  #: validation contract"), and stating it as data lets the gate assert it instead of trusting the
103
  #: comment above. Adding a measure here without adding it to store_parity's loop fails the gate.
104
  PARITY_CHECKED = frozenset({'revenue', 'margin', 'units', 'orders', 'customers',
105
+ 'returns', 'invoiced',
106
+ # wave 21 R2 β€” the invoiced-basis pair, in store_parity's loop
107
+ 'revenue_invoiced', 'orders_invoiced'})
108
 
109
  #: numeric comparison ops, mirroring filter_sql._NUM_CMP. `between` is expressed as two
110
  #: conditions by the caller rather than a third operator shape.
platform/harness/semantic.py CHANGED
@@ -211,6 +211,12 @@ def metric(key, date_from=None, date_to=None, team_id=None, _seen=None):
211
  return _eval_expr(m["expr"], lambda k: metric(k, date_from, date_to, team_id, _seen))
212
  t = _model()["topics"][m["topic"]]
213
  dom = _domain(t, date_from, date_to, team_id)
 
 
 
 
 
 
214
  if agg == "sum":
215
  # ⚠ `negate` applies HERE too, not only in `_measure_sql`. It existed for GL income on a
216
  # STORE-ONLY topic, so the live path never met it β€” the first metric that is both negated
@@ -895,7 +901,8 @@ def store_parity(date_from=None, date_to=None):
895
  if not date_from:
896
  date_from, date_to = P.ytd()
897
  out = []
898
- for key in ("revenue", "margin", "units", "orders", "customers", "returns", "invoiced"):
 
899
  m = _model()["metrics"][key]
900
  # ⚠ A COMPANY-LEVEL topic is checked at company scope ONLY. `store_query` RAISES when a
901
  # team is asked of a topic with no team_col, and the live builder refuses too β€” so
 
211
  return _eval_expr(m["expr"], lambda k: metric(k, date_from, date_to, team_id, _seen))
212
  t = _model()["topics"][m["topic"]]
213
  dom = _domain(t, date_from, date_to, team_id)
214
+ # Wave 21 R2 β€” the LIVE twin of `store_filter_sql`. A filtered metric must filter BOTH
215
+ # paths, or store_parity would compare a narrowed store number against an unfiltered live
216
+ # one and the "parity failure" would read as a data problem. YAML shape:
217
+ # live_domain: [[field, op, value], ...] β€” appended verbatim to the topic domain.
218
+ for c in (m.get("live_domain") or []):
219
+ dom = dom + [tuple(c)]
220
  if agg == "sum":
221
  # ⚠ `negate` applies HERE too, not only in `_measure_sql`. It existed for GL income on a
222
  # STORE-ONLY topic, so the live path never met it β€” the first metric that is both negated
 
901
  if not date_from:
902
  date_from, date_to = P.ytd()
903
  out = []
904
+ for key in ("revenue", "margin", "units", "orders", "customers", "returns", "invoiced",
905
+ "revenue_invoiced", "orders_invoiced"): # wave 21 R2 β€” both filtered paths
906
  m = _model()["metrics"][key]
907
  # ⚠ A COMPANY-LEVEL topic is checked at company scope ONLY. `store_query` RAISES when a
908
  # team is asked of a topic with no team_col, and the live builder refuses too β€” so
platform/model/metrics/sales.yml CHANGED
@@ -82,3 +82,27 @@ metrics:
82
  format: usd
83
  description: "Revenue per distinct order."
84
  ai_context: "Ratio of two registered metrics at identical scope; never average per-order averages."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  format: usd
83
  description: "Revenue per distinct order."
84
  ai_context: "Ratio of two registered metrics at identical scope; never average per-order averages."
85
+
86
+ # ⭐ Wave 21 R2 β€” the FULLY-INVOICED basis, as separate metrics (owner ruling: picker entries,
87
+ # not a basis dropdown). Same topics, same scope, ONE predicate narrower: the order's Odoo
88
+ # invoice_status = 'invoiced'. `store_filter_sql` filters the store path (sum/count CASE);
89
+ # `live_domain` filters the live path β€” BOTH or store_parity compares two different questions.
90
+ - key: revenue_invoiced
91
+ label: Sales β€” fully invoiced
92
+ agg: sum
93
+ field: price_subtotal
94
+ store_filter_sql: "o.invoice_status = 'invoiced'"
95
+ live_domain: [["order_id.invoice_status", "=", "invoiced"]]
96
+ format: usd
97
+ description: "Untaxed revenue of confirmed wholesale order lines whose parent order Odoo marks fully invoiced (invoice_status = invoiced)."
98
+ ai_context: "Same scope as revenue, narrowed by the ORDER-level fully-invoiced flag. This is NOT posted-invoice-line revenue: a partially invoiced order is excluded entirely until Odoo flips the flag. Reconciled store-vs-live per BU by store_parity."
99
+
100
+ - key: orders_invoiced
101
+ label: Orders β€” fully invoiced
102
+ topic: sales_orders
103
+ agg: count
104
+ store_filter_sql: "o.invoice_status = 'invoiced'"
105
+ live_domain: [["invoice_status", "=", "invoiced"]]
106
+ format: int
107
+ description: "Confirmed wholesale orders Odoo marks fully invoiced (invoice_status = invoiced)."
108
+ ai_context: "Order-header count under the orders scope plus the fully-invoiced flag; partially invoiced and not-yet-invoiced orders are excluded. Reconciled store-vs-live per BU by store_parity."
platform/modules/customer_data.py CHANGED
@@ -65,7 +65,11 @@ AR_BUCKET_FIELDS = {'1-30': 'ar_aged_1_30', '31-60': 'ar_aged_31_60',
65
 
66
 
67
  def _ar_attrs(t=None):
68
- """{pid: {ar_open, ar_overdue, ar_exposure}} β€” the AR / credit-exposure family.
 
 
 
 
69
 
70
  Composed from `modules/ar.credit_exposure()`, NOT re-derived: it is already reconciled to
71
  Odoo by `ar.validate()`, so the Customer table and the Collections page cannot disagree about
@@ -91,6 +95,9 @@ def _ar_attrs(t=None):
91
  out[r['pid']] = {
92
  'ar_open': r.get('open', 0.0) or 0.0,
93
  'ar_overdue': r.get('overdue', 0.0) or 0.0,
 
 
 
94
  'ar_exposure': r.get('exposure', 0.0) or 0.0,
95
  # Wave 17 R2 β€” the aging split, so a saved VIEW can be the collections
96
  # worklist. Keys mirror `ar.OVERDUE_BUCKETS` through AR_BUCKET_FIELDS; the four
@@ -445,6 +452,7 @@ def _pool_build(agent_name, team_id, limit, fast=False):
445
  # Customer table and the Collections page cannot disagree.
446
  'ar_open': (ar_a.get(pid) or {}).get('ar_open', 0.0),
447
  'ar_overdue': (ar_a.get(pid) or {}).get('ar_overdue', 0.0),
 
448
  'ar_exposure': (ar_a.get(pid) or {}).get('ar_exposure', 0.0),
449
  'days_to_pay': (ar_a.get(pid) or {}).get('days_to_pay'),
450
  **{k: (ar_a.get(pid) or {}).get(k, 0.0) for k in AR_BUCKET_FIELDS.values()},
@@ -536,7 +544,8 @@ def _reconcile_ledger(rows, total, agent_name, team_id):
536
  'agent': '(none)', 'city': '(none)', 'state': '(none)', 'country': '(none)',
537
  'zip': '(none)', 'payment_terms': '(none)', 'customer_since': '',
538
  '_created': '', 'tags': '(none)', 'pricelist': '(none)',
539
- 'ar_open': 0.0, 'ar_overdue': 0.0, 'ar_exposure': 0.0, 'days_to_pay': None,
 
540
  **{k: 0.0 for k in AR_BUCKET_FIELDS.values()},
541
  'top_category': '(none)', 'top_category_pct': None, 'sku_count': 0,
542
  'top_sku': '(none)', 'salesperson': '(none)', 'lat': None, 'lon': None,
 
65
 
66
 
67
  def _ar_attrs(t=None):
68
+ """{pid: {ar_open, ar_overdue, ar_outstanding, ar_exposure}} β€” the AR family.
69
+
70
+ Wave 21 R1: `ar_open` is the NOT-YET-DUE half of a disjoint split (label "AR current $" β€”
71
+ key kept so saved views keep working); `ar_outstanding` is the total (current + overdue),
72
+ which is what "open AR" means everywhere else.
73
 
74
  Composed from `modules/ar.credit_exposure()`, NOT re-derived: it is already reconciled to
75
  Odoo by `ar.validate()`, so the Customer table and the Collections page cannot disagree about
 
95
  out[r['pid']] = {
96
  'ar_open': r.get('open', 0.0) or 0.0,
97
  'ar_overdue': r.get('overdue', 0.0) or 0.0,
98
+ # Wave 21 R1 β€” the TOTAL owed. Sum of the two halves ar.credit_exposure already
99
+ # reconciles to Odoo's residual read_group (ar.py validate), so no second oracle.
100
+ 'ar_outstanding': (r.get('open', 0.0) or 0.0) + (r.get('overdue', 0.0) or 0.0),
101
  'ar_exposure': r.get('exposure', 0.0) or 0.0,
102
  # Wave 17 R2 β€” the aging split, so a saved VIEW can be the collections
103
  # worklist. Keys mirror `ar.OVERDUE_BUCKETS` through AR_BUCKET_FIELDS; the four
 
452
  # Customer table and the Collections page cannot disagree.
453
  'ar_open': (ar_a.get(pid) or {}).get('ar_open', 0.0),
454
  'ar_overdue': (ar_a.get(pid) or {}).get('ar_overdue', 0.0),
455
+ 'ar_outstanding': (ar_a.get(pid) or {}).get('ar_outstanding', 0.0),
456
  'ar_exposure': (ar_a.get(pid) or {}).get('ar_exposure', 0.0),
457
  'days_to_pay': (ar_a.get(pid) or {}).get('days_to_pay'),
458
  **{k: (ar_a.get(pid) or {}).get(k, 0.0) for k in AR_BUCKET_FIELDS.values()},
 
544
  'agent': '(none)', 'city': '(none)', 'state': '(none)', 'country': '(none)',
545
  'zip': '(none)', 'payment_terms': '(none)', 'customer_since': '',
546
  '_created': '', 'tags': '(none)', 'pricelist': '(none)',
547
+ 'ar_open': 0.0, 'ar_overdue': 0.0, 'ar_outstanding': 0.0, 'ar_exposure': 0.0,
548
+ 'days_to_pay': None,
549
  **{k: 0.0 for k in AR_BUCKET_FIELDS.values()},
550
  'top_category': '(none)', 'top_category_pct': None, 'sku_count': 0,
551
  'top_sku': '(none)', 'salesperson': '(none)', 'lat': None, 'lon': None,
requirements.txt CHANGED
@@ -11,7 +11,9 @@
11
  # different documents, and checking only the one you wrote is how the other rots.
12
  # `api/verify_no_streamlit.py` now checks BOTH, and proves the API imports with streamlit,
13
  # plotly, altair, openpyxl, reportlab and jinja2 all blocked at sys.meta_path.
14
- # No altair/plotly/openpyxl/reportlab either β€” those were Streamlit UI/export only.
 
 
15
  fastapi>=0.139
16
  uvicorn[standard]>=0.30
17
  python-dotenv>=1.0
@@ -35,3 +37,6 @@ cryptography>=42.0
35
  # is the same defect in the other direction β€” the pinned intent and the shipped manifest are two
36
  # documents. psycopg is now in BOTH, and `ops/verify_portability.py` gates the pair.
37
  psycopg[binary,pool]>=3.2
 
 
 
 
11
  # different documents, and checking only the one you wrote is how the other rots.
12
  # `api/verify_no_streamlit.py` now checks BOTH, and proves the API imports with streamlit,
13
  # plotly, altair, openpyxl, reportlab and jinja2 all blocked at sys.meta_path.
14
+ # No altair/plotly/reportlab either β€” those were Streamlit UI/export only. openpyxl RETURNED in
15
+ # wave 21 (C5) as a LAZY dep of routes_uploads.py β€” the boot proof above still holds because the
16
+ # import lives inside the handler, and the gate now asserts this line exists here.
17
  fastapi>=0.139
18
  uvicorn[standard]>=0.30
19
  python-dotenv>=1.0
 
37
  # is the same defect in the other direction β€” the pinned intent and the shipped manifest are two
38
  # documents. psycopg is now in BOTH, and `ops/verify_portability.py` gates the pair.
39
  psycopg[binary,pool]>=3.2
40
+ # ⭐ WAVE 21 (item 11, C5) β€” .xlsx preview for Select-from-file; lazy-imported in
41
+ # routes_uploads.py only. verify_no_streamlit asserts this line in BOTH manifests.
42
+ openpyxl>=3.1
web/public/sample_customers.json CHANGED
@@ -44,7 +44,7 @@
44
  "type": "text",
45
  "source": "odoo",
46
  "default": false,
47
- "description": "Who keyed in most of this customer's orders \u2014 not the Agent, who owns the account."
48
  },
49
  {
50
  "key": "city",
@@ -108,7 +108,7 @@
108
  "type": "text",
109
  "source": "odoo",
110
  "default": false,
111
- "description": "Payment terms on this customer's account \u2014 Net 30, for example."
112
  },
113
  {
114
  "key": "last_order",
@@ -127,7 +127,7 @@
127
  "description": "How many days late this customer is running against their own usual ordering rhythm."
128
  },
129
  {
130
- "_note": "filterable:false \u2014 DERIVED ANALYTIC: est_missed is min(cycles missed, 3) x AOV, a score we compute rather than an object the business has, so a condition on it would read as a fact about the customer when it is a fact about our arithmetic. It still displays and still sorts. Until wave 6 this flag also covered the frozen-window presets (revenue_ytd / revenue_ly / orders_24m / aov / yoy_pct); those are now DELETED outright under the owner's no-buildable-presets rule \u2014 see _comment. est_missed itself STAYS: no creatable measure or formula reproduces the cadence model behind it.",
131
  "key": "est_missed",
132
  "label": "Est. missed $",
133
  "type": "currency",
@@ -138,12 +138,13 @@
138
  "description": "Estimated sales missed while quiet: missed orders (capped at 3) times average order value. An estimate, not money owed."
139
  },
140
  {
 
141
  "key": "ar_open",
142
- "label": "AR open $",
143
  "type": "currency",
144
  "source": "odoo",
145
  "default": false,
146
- "description": "Invoiced money owed, not yet overdue."
147
  },
148
  {
149
  "key": "ar_overdue",
@@ -151,7 +152,16 @@
151
  "type": "currency",
152
  "source": "odoo",
153
  "default": false,
154
- "description": "Invoiced money past due \u2014 same basis as the Collections page."
 
 
 
 
 
 
 
 
 
155
  },
156
  {
157
  "key": "ar_exposure",
@@ -288,7 +298,8 @@
288
  "lat": 25.7617,
289
  "lon": -80.1918,
290
  "odoo_status": "Archived",
291
- "dba": "Royal"
 
292
  },
293
  {
294
  "pid": 102,
@@ -319,7 +330,8 @@
319
  "lat": 27.9506,
320
  "lon": -82.4572,
321
  "odoo_status": "Active",
322
- "dba": "Fisch"
 
323
  },
324
  {
325
  "pid": 103,
@@ -350,7 +362,8 @@
350
  "lat": 28.5384,
351
  "lon": -81.3789,
352
  "odoo_status": "Active",
353
- "dba": "Both"
 
354
  },
355
  {
356
  "pid": 104,
@@ -381,7 +394,8 @@
381
  "lat": 30.3322,
382
  "lon": -81.6557,
383
  "odoo_status": "Active",
384
- "dba": "Royal"
 
385
  },
386
  {
387
  "pid": 105,
@@ -412,7 +426,8 @@
412
  "lat": 26.1224,
413
  "lon": -80.1373,
414
  "odoo_status": "Active",
415
- "dba": ""
 
416
  },
417
  {
418
  "pid": 106,
@@ -443,7 +458,8 @@
443
  "lat": 27.3364,
444
  "lon": -82.5307,
445
  "odoo_status": "Active",
446
- "dba": "Fisch"
 
447
  },
448
  {
449
  "pid": 107,
@@ -474,7 +490,8 @@
474
  "lat": null,
475
  "lon": null,
476
  "odoo_status": "Active",
477
- "dba": "Both"
 
478
  },
479
  {
480
  "pid": 108,
@@ -505,7 +522,8 @@
505
  "lat": 33.749,
506
  "lon": -84.388,
507
  "odoo_status": "Active",
508
- "dba": "Royal"
 
509
  }
510
  ]
511
  }
 
44
  "type": "text",
45
  "source": "odoo",
46
  "default": false,
47
+ "description": "Who keyed in most of this customer's orders β€” not the Agent, who owns the account."
48
  },
49
  {
50
  "key": "city",
 
108
  "type": "text",
109
  "source": "odoo",
110
  "default": false,
111
+ "description": "Payment terms on this customer's account β€” Net 30, for example."
112
  },
113
  {
114
  "key": "last_order",
 
127
  "description": "How many days late this customer is running against their own usual ordering rhythm."
128
  },
129
  {
130
+ "_note": "filterable:false β€” DERIVED ANALYTIC: est_missed is min(cycles missed, 3) x AOV, a score we compute rather than an object the business has, so a condition on it would read as a fact about the customer when it is a fact about our arithmetic. It still displays and still sorts. Until wave 6 this flag also covered the frozen-window presets (revenue_ytd / revenue_ly / orders_24m / aov / yoy_pct); those are now DELETED outright under the owner's no-buildable-presets rule β€” see _comment. est_missed itself STAYS: no creatable measure or formula reproduces the cadence model behind it.",
131
  "key": "est_missed",
132
  "label": "Est. missed $",
133
  "type": "currency",
 
138
  "description": "Estimated sales missed while quiet: missed orders (capped at 3) times average order value. An estimate, not money owed."
139
  },
140
  {
141
+ "_note": "wave 21 R1 β€” KEY UNCHANGED, LABEL RENAMED. The computation is a DISJOINT split (ar.py credit_exposure): this column is only the not-yet-due residual, its sibling is the past-grace residual, and the two sum to the total. Under the label 'AR open $' the majority-late book read as 'Overdue > Open', which is nonsense in AR vocabulary β€” 'open' universally means the total. The label now says what the number is; the key stays so saved views and filters keep working.",
142
  "key": "ar_open",
143
+ "label": "AR current $",
144
  "type": "currency",
145
  "source": "odoo",
146
  "default": false,
147
+ "description": "Invoiced money owed but not yet due (a 5-day grace applies before it counts as overdue)."
148
  },
149
  {
150
  "key": "ar_overdue",
 
152
  "type": "currency",
153
  "source": "odoo",
154
  "default": false,
155
+ "description": "Invoiced money past due β€” same basis as the Collections page."
156
+ },
157
+ {
158
+ "_note": "wave 21 R1 β€” the TOTAL, added beside the rename above. AR current $ + AR overdue $, i.e. what most people mean by 'open AR'. Composed from the same ar.credit_exposure rows the siblings use, so it is transitively reconciled by ar.validate()'s residual read_group tie β€” no second oracle.",
159
+ "key": "ar_outstanding",
160
+ "label": "AR outstanding $",
161
+ "type": "currency",
162
+ "source": "odoo",
163
+ "default": false,
164
+ "description": "Total invoiced money owed right now: AR current $ plus AR overdue $."
165
  },
166
  {
167
  "key": "ar_exposure",
 
298
  "lat": 25.7617,
299
  "lon": -80.1918,
300
  "odoo_status": "Archived",
301
+ "dba": "Royal",
302
+ "ar_outstanding": 0
303
  },
304
  {
305
  "pid": 102,
 
330
  "lat": 27.9506,
331
  "lon": -82.4572,
332
  "odoo_status": "Active",
333
+ "dba": "Fisch",
334
+ "ar_outstanding": 1240.5
335
  },
336
  {
337
  "pid": 103,
 
362
  "lat": 28.5384,
363
  "lon": -81.3789,
364
  "odoo_status": "Active",
365
+ "dba": "Both",
366
+ "ar_outstanding": 5120.25
367
  },
368
  {
369
  "pid": 104,
 
394
  "lat": 30.3322,
395
  "lon": -81.6557,
396
  "odoo_status": "Active",
397
+ "dba": "Royal",
398
+ "ar_outstanding": 9240
399
  },
400
  {
401
  "pid": 105,
 
426
  "lat": 26.1224,
427
  "lon": -80.1373,
428
  "odoo_status": "Active",
429
+ "dba": "",
430
+ "ar_outstanding": 0
431
  },
432
  {
433
  "pid": 106,
 
458
  "lat": 27.3364,
459
  "lon": -82.5307,
460
  "odoo_status": "Active",
461
+ "dba": "Fisch",
462
+ "ar_outstanding": 1240.5
463
  },
464
  {
465
  "pid": 107,
 
490
  "lat": null,
491
  "lon": null,
492
  "odoo_status": "Active",
493
+ "dba": "Both",
494
+ "ar_outstanding": 5120.25
495
  },
496
  {
497
  "pid": 108,
 
522
  "lat": 33.749,
523
  "lon": -84.388,
524
  "odoo_status": "Active",
525
+ "dba": "Royal",
526
+ "ar_outstanding": 9240
527
  }
528
  ]
529
  }
web/src/automation/AutomationCanvas.tsx CHANGED
@@ -1,6 +1,13 @@
1
  // ---------------------------------------------------------------------------
2
  // automation/AutomationCanvas.tsx β€” the flow, drawn (owner ruling R5).
3
  //
 
 
 
 
 
 
 
4
  // Hand-rolled SVG + CSS, no new dependency: the repo already draws its own
5
  // charts and maps this way (`web/src/viz/`), and a flow of four to six nodes is
6
  // not worth a graph library's bundle, its theming fight, or its opinion about
 
1
  // ---------------------------------------------------------------------------
2
  // automation/AutomationCanvas.tsx β€” the flow, drawn (owner ruling R5).
3
  //
4
+ // β›” UNMOUNTED SINCE WAVE 21 (owner ruling R9 β€” "trigger-first Steps"). Nothing
5
+ // imports this file: `AutomationDetail` renders `AutomationSteps` instead, and
6
+ // the `.auto-canvas* / .auto-node* / .auto-wire* / .auto-zoom*` CSS was removed
7
+ // from `index.css` with the mount. It is kept rather than deleted because R9
8
+ // named a rebuild and not a deletion β€” but REMOUNTING IT WOULD PAINT AN UNSTYLED
9
+ // FLOW: its stylesheet comes back with it. Booked in the wave-21 mailbox.
10
+ //
11
  // Hand-rolled SVG + CSS, no new dependency: the repo already draws its own
12
  // charts and maps this way (`web/src/viz/`), and a flow of four to six nodes is
13
  // not worth a graph library's bundle, its theming fight, or its opinion about
web/src/automation/AutomationCreate.tsx CHANGED
@@ -1,425 +1,430 @@
1
- // ---------------------------------------------------------------------------
2
- // automation/AutomationCreate.tsx β€” the one form that is NOT a canvas.
3
- //
4
- // WHY A FORM AND NOT AN EMPTY CANVAS. The node graph is derived by the server
5
- // from a stored definition (`engine.graph`), which is what stops the drawing
6
- // from ever describing a step the engine no longer runs. An automation that does
7
- // not exist yet has no definition, so drawing it would mean a SECOND, client-side
8
- // idea of what the steps are β€” exactly the drift the split was built to prevent.
9
- //
10
- // So creation is a short form and everything after it is the canvas. That is also
11
- // how the two kinds actually differ: you cannot map columns you have not seen, so
12
- // "Read the page" has to happen before a scrape can be created at all.
13
- // ---------------------------------------------------------------------------
14
- import { useCallback, useEffect, useState } from "react";
15
-
16
- import type { AutomationKind, SourcePreview, UserTable } from "./automationApi";
17
- import {
18
- AutomationError,
19
- createAutomation,
20
- fieldKeyFor,
21
- listTables,
22
- previewSource,
23
- } from "./automationApi";
24
-
25
- interface Props {
26
- kinds: { key: AutomationKind; label: string }[];
27
- onCreated: (id: string) => void | Promise<void>;
28
- onCancel: () => void;
29
- }
30
-
31
- interface ColumnPlan {
32
- column: string;
33
- include: boolean;
34
- key: string;
35
- }
36
-
37
- export default function AutomationCreate({ kinds, onCreated, onCancel }: Props) {
38
- const [name, setName] = useState("");
39
- const [kind, setKind] = useState<AutomationKind>("scrape_db");
40
- const [problem, setProblem] = useState("");
41
- const [message, setMessage] = useState("");
42
- const [saving, setSaving] = useState(false);
43
-
44
- const [url, setUrl] = useState("");
45
- const [extract, setExtract] = useState("table");
46
- const [tableIndex, setTableIndex] = useState(0);
47
- const [targetLabel, setTargetLabel] = useState("");
48
- const [preview, setPreview] = useState<SourcePreview | null>(null);
49
- const [reading, setReading] = useState(false);
50
- const [plan, setPlan] = useState<ColumnPlan[]>([]);
51
- const [keyField, setKeyField] = useState("");
52
-
53
- const [tables, setTables] = useState<UserTable[]>([]);
54
- const [targetTable, setTargetTable] = useState("");
55
- const [fieldKey, setFieldKey] = useState("");
56
- const [urlField, setUrlField] = useState("");
57
-
58
- useEffect(() => {
59
- const ac = new AbortController();
60
- listTables(ac.signal)
61
- .then((r) => setTables(r.tables))
62
- .catch(() => setTables([]));
63
- return () => ac.abort();
64
- }, []);
65
-
66
- const table = tables.find((t) => t.key === targetTable) || null;
67
-
68
- const readPage = useCallback(async () => {
69
- setReading(true);
70
- setProblem("");
71
- try {
72
- const p = await previewSource(url, extract, tableIndex);
73
- setPreview(p);
74
- if (!p.ok) {
75
- setProblem(p.note || `That page answered ${p.status}.`);
76
- return;
77
- }
78
- setPlan(
79
- p.columns.map((column) => ({ column, include: true, key: fieldKeyFor(column) }))
80
- );
81
- setKeyField(fieldKeyFor(p.columns[0] || ""));
82
- if (!targetLabel) setTargetLabel(p.title || "Scraped table");
83
- setMessage(
84
- `Read ${p.rowCount} rows and ${p.columns.length} columns` +
85
- (p.tableCount && p.tableCount > 1 ? ` (of ${p.tableCount} tables on the page)` : "")
86
- );
87
- } catch (e) {
88
- setProblem(e instanceof AutomationError ? e.message : "That page could not be read.");
89
- } finally {
90
- setReading(false);
91
- }
92
- }, [url, extract, tableIndex, targetLabel]);
93
-
94
- const create = async () => {
95
- setSaving(true);
96
- setProblem("");
97
- try {
98
- const fieldMap: Record<string, string> = {};
99
- for (const c of plan) if (c.include && c.key) fieldMap[c.column] = c.key;
100
- const res = await createAutomation({
101
- name,
102
- kind,
103
- schedule: { cron: "0 6 * * *", enabled: false },
104
- config:
105
- kind === "scrape_db"
106
- ? { url, extract, tableIndex, fieldMap, keyField, targetLabel }
107
- : kind === "discover_instagram"
108
- ? {
109
- // A search is created with a SMALL, NARROW default and no schedule, then
110
- // widened on the canvas where the cost estimate is. The one shape that must
111
- // never be the default is the expensive one.
112
- recordsLimit: 25,
113
- operator: "and",
114
- predicates: [
115
- { name: "followers", operator: ">=", value: 10000 },
116
- { name: "biography", operator: "includes", value: "" },
117
- ],
118
- }
119
- : { targetTable, fieldKey, urlField, maxPosts: 24, tier: "anonymous" },
120
- });
121
- await onCreated(res.automation.id);
122
- } catch (e) {
123
- setProblem(e instanceof AutomationError ? e.message : "That could not be created.");
124
- } finally {
125
- setSaving(false);
126
- }
127
- };
128
-
129
- const canCreate =
130
- !!name.trim() &&
131
- (kind === "scrape_db"
132
- ? !!url.trim() && plan.some((c) => c.include && c.key === keyField)
133
- : kind === "discover_instagram"
134
- ? true
135
- : !!targetTable && !!fieldKey);
136
-
137
- return (
138
- <div className="auto-create-pane">
139
- <div className="auto-create-card">
140
- <h1>New automation</h1>
141
- <p className="auto-hint">
142
- Pick what it does. Once it exists you configure it on the canvas, one step at a time.
143
- </p>
144
-
145
- {problem ? (
146
- <div className="auto-banner is-error" role="alert">
147
- {problem}
148
- </div>
149
- ) : null}
150
- {message ? (
151
- <div className="auto-banner is-ok" role="status">
152
- {message}
153
- </div>
154
- ) : null}
155
-
156
- <div className="auto-field">
157
- <label htmlFor="auto-new-name">Name</label>
158
- <input
159
- id="auto-new-name"
160
- className="auto-input"
161
- value={name}
162
- placeholder="S&P 500 companies"
163
- onChange={(e) => setName(e.target.value)}
164
- />
165
- </div>
166
-
167
- <div className="auto-kinds">
168
- {kinds.map((k) => (
169
- <label key={k.key} className={"auto-kind" + (kind === k.key ? " is-on" : "")}>
170
- <input
171
- type="radio"
172
- name="auto-kind"
173
- checked={kind === k.key}
174
- onChange={() => setKind(k.key)}
175
- />
176
- <span>{k.label}</span>
177
- </label>
178
- ))}
179
- </div>
180
-
181
- {kind === "discover_instagram" ? (
182
- <>
183
- <p className="auto-hint">
184
- It searches a corpus of pre-collected public Instagram profiles for accounts you
185
- have never heard of, and collects the matches into a candidates database. You set
186
- the conditions and how many profiles to fetch on the canvas, where the cost
187
- estimate is β€” searching is the one thing this workspace does that spends money per
188
- run.
189
- </p>
190
- <p className="auto-hint">
191
- It starts with a narrow default and no schedule. Nothing it finds is ever tracked
192
- automatically; you tick the accounts you want.
193
- </p>
194
- </>
195
- ) : kind === "scrape_db" ? (
196
- <>
197
- <div className="auto-field">
198
- <label htmlFor="auto-new-url">Page URL</label>
199
- <div className="auto-row-inline">
200
- <input
201
- id="auto-new-url"
202
- className="auto-input"
203
- value={url}
204
- placeholder="https://en.wikipedia.org/wiki/List_of_S%26P_500_companies"
205
- onChange={(e) => setUrl(e.target.value)}
206
- />
207
- <button
208
- type="button"
209
- className="auto-btn"
210
- disabled={!url.trim() || reading}
211
- onClick={() => void readPage()}
212
- >
213
- {reading ? "Reading…" : "Read the page"}
214
- </button>
215
- </div>
216
- <p className="auto-hint">
217
- Public web pages only. Private, loopback and link-local addresses are refused β€”
218
- including a public URL that redirects to one.
219
- </p>
220
- </div>
221
- <div className="auto-field-row">
222
- <div className="auto-field">
223
- <label htmlFor="auto-new-extract">Read</label>
224
- <select
225
- id="auto-new-extract"
226
- className="auto-input"
227
- value={extract}
228
- onChange={(e) => setExtract(e.target.value)}
229
- >
230
- <option value="table">An HTML table</option>
231
- <option value="jsonld">Structured data (JSON-LD)</option>
232
- </select>
233
- </div>
234
- {extract === "table" ? (
235
- <div className="auto-field">
236
- <label htmlFor="auto-new-tidx">Which table</label>
237
- <input
238
- id="auto-new-tidx"
239
- className="auto-input"
240
- type="number"
241
- min={0}
242
- value={tableIndex}
243
- onChange={(e) => setTableIndex(Number(e.target.value) || 0)}
244
- />
245
- </div>
246
- ) : null}
247
- <div className="auto-field">
248
- <label htmlFor="auto-new-tlabel">Database name</label>
249
- <input
250
- id="auto-new-tlabel"
251
- className="auto-input"
252
- value={targetLabel}
253
- placeholder="S&P 500 companies"
254
- onChange={(e) => setTargetLabel(e.target.value)}
255
- />
256
- </div>
257
- </div>
258
-
259
- {plan.length ? (
260
- <div className="auto-map">
261
- <h3>Columns</h3>
262
- <p className="auto-hint">
263
- Pick the key β€” the column that identifies a row. On every re-run, a row whose
264
- key already exists is updated; a new key is inserted; a key that has stopped
265
- appearing is counted and kept.
266
- </p>
267
- <div className="auto-drill-scroll">
268
- <table className="auto-table">
269
- <thead>
270
- <tr>
271
- <th>Use</th>
272
- <th>Source column</th>
273
- <th>Field key</th>
274
- <th>Key</th>
275
- {preview?.sample?.length ? <th>First value</th> : null}
276
- </tr>
277
- </thead>
278
- <tbody>
279
- {plan.map((c, i) => (
280
- <tr key={c.column}>
281
- <td>
282
- <input
283
- type="checkbox"
284
- checked={c.include}
285
- aria-label={`Include ${c.column}`}
286
- onChange={(e) =>
287
- setPlan((p) =>
288
- p.map((x, j) =>
289
- j === i ? { ...x, include: e.target.checked } : x
290
- )
291
- )
292
- }
293
- />
294
- </td>
295
- <td className="auto-cell-name">{c.column}</td>
296
- <td>
297
- <input
298
- className="auto-input is-small"
299
- value={c.key}
300
- aria-label={`Field key for ${c.column}`}
301
- onChange={(e) =>
302
- setPlan((p) =>
303
- p.map((x, j) =>
304
- j === i ? { ...x, key: fieldKeyFor(e.target.value) } : x
305
- )
306
- )
307
- }
308
- />
309
- </td>
310
- <td>
311
- <input
312
- type="radio"
313
- name="auto-new-keyfield"
314
- checked={keyField === c.key && c.include}
315
- disabled={!c.include}
316
- aria-label={`Use ${c.column} as the key`}
317
- onChange={() => setKeyField(c.key)}
318
- />
319
- </td>
320
- {preview?.sample?.length ? (
321
- <td className="auto-cell-sample">
322
- {String(preview.sample[0]?.[c.column] ?? "")}
323
- </td>
324
- ) : null}
325
- </tr>
326
- ))}
327
- </tbody>
328
- </table>
329
- </div>
330
- </div>
331
- ) : (
332
- <p className="auto-note">Read the page to see what columns it offers.</p>
333
- )}
334
- </>
335
- ) : (
336
- <>
337
- <div className="auto-field-row">
338
- <div className="auto-field">
339
- <label htmlFor="auto-new-table">Database</label>
340
- <select
341
- id="auto-new-table"
342
- className="auto-input"
343
- value={targetTable}
344
- onChange={(e) => {
345
- setTargetTable(e.target.value);
346
- setFieldKey("");
347
- setUrlField("");
348
- }}
349
- >
350
- <option value="">Choose a database…</option>
351
- {tables.map((t) => (
352
- <option key={t.key} value={t.key}>
353
- {t.label} ({t.rowCount} {t.rowCount === 1 ? "row" : "rows"})
354
- </option>
355
- ))}
356
- </select>
357
- </div>
358
- <div className="auto-field">
359
- <label htmlFor="auto-new-fieldkey">Automation column</label>
360
- <select
361
- id="auto-new-fieldkey"
362
- className="auto-input"
363
- value={fieldKey}
364
- onChange={(e) => setFieldKey(e.target.value)}
365
- >
366
- <option value="">Choose a column…</option>
367
- {(table?.fields || [])
368
- .filter((f) => f.type === "automation")
369
- .map((f) => (
370
- <option key={f.key} value={f.key}>
371
- {f.label}
372
- </option>
373
- ))}
374
- </select>
375
- </div>
376
- <div className="auto-field">
377
- <label htmlFor="auto-new-urlfield">Profile URL column</label>
378
- <select
379
- id="auto-new-urlfield"
380
- className="auto-input"
381
- value={urlField}
382
- onChange={(e) => setUrlField(e.target.value)}
383
- >
384
- <option value="">The column the field is bound to</option>
385
- {(table?.fields || []).map((f) => (
386
- <option key={f.key} value={f.key}>
387
- {f.label}
388
- </option>
389
- ))}
390
- </select>
391
- </div>
392
- </div>
393
- <p className="auto-hint">
394
- It starts on the free anonymous rung. The canvas&rsquo;s Bright Data step turns on
395
- the paid one, which returns exact counts and the profile&rsquo;s top posts, and
396
- works from a datacenter. Likes and comments per post are a separate step again β€”
397
- they cost one record per post rather than one per profile, so they are off until
398
- you turn them on.
399
- </p>
400
- {table && !(table.fields || []).some((f) => f.type === "automation") ? (
401
- <p className="auto-note">
402
- That database has no automation column yet. Add one from the grid&rsquo;s column
403
- menu, then choose it here.
404
- </p>
405
- ) : null}
406
- </>
407
- )}
408
-
409
- <div className="auto-head-actions">
410
- <button
411
- type="button"
412
- className="auto-btn is-primary"
413
- disabled={!canCreate || saving}
414
- onClick={() => void create()}
415
- >
416
- {saving ? "Creating…" : "Create"}
417
- </button>
418
- <button type="button" className="auto-btn" onClick={onCancel}>
419
- Cancel
420
- </button>
421
- </div>
422
- </div>
423
- </div>
424
- );
425
- }
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // automation/AutomationCreate.tsx β€” the one form that is NOT a step list.
3
+ //
4
+ // WHY A FORM AND NOT AN EMPTY CANVAS. The node graph is derived by the server
5
+ // from a stored definition (`engine.graph`), which is what stops the drawing
6
+ // from ever describing a step the engine no longer runs. An automation that does
7
+ // not exist yet has no definition, so drawing it would mean a SECOND, client-side
8
+ // idea of what the steps are β€” exactly the drift the split was built to prevent.
9
+ //
10
+ // So creation is a short form and everything after it is the numbered steps. That is also
11
+ // how the two kinds actually differ: you cannot map columns you have not seen, so
12
+ // "Read the page" has to happen before a scrape can be created at all.
13
+ // ---------------------------------------------------------------------------
14
+ import { useCallback, useEffect, useState } from "react";
15
+
16
+ import type { AutomationKind, SourcePreview, UserTable } from "./automationApi";
17
+ import {
18
+ AutomationError,
19
+ createAutomation,
20
+ fieldKeyFor,
21
+ listTables,
22
+ previewSource,
23
+ } from "./automationApi";
24
+
25
+ interface Props {
26
+ kinds: { key: AutomationKind; label: string }[];
27
+ onCreated: (id: string) => void | Promise<void>;
28
+ onCancel: () => void;
29
+ }
30
+
31
+ interface ColumnPlan {
32
+ column: string;
33
+ include: boolean;
34
+ key: string;
35
+ }
36
+
37
+ export default function AutomationCreate({ kinds, onCreated, onCancel }: Props) {
38
+ const [name, setName] = useState("");
39
+ const [kind, setKind] = useState<AutomationKind>("scrape_db");
40
+ const [problem, setProblem] = useState("");
41
+ const [message, setMessage] = useState("");
42
+ const [saving, setSaving] = useState(false);
43
+
44
+ const [url, setUrl] = useState("");
45
+ const [extract, setExtract] = useState("table");
46
+ const [tableIndex, setTableIndex] = useState(0);
47
+ const [targetLabel, setTargetLabel] = useState("");
48
+ const [preview, setPreview] = useState<SourcePreview | null>(null);
49
+ const [reading, setReading] = useState(false);
50
+ const [plan, setPlan] = useState<ColumnPlan[]>([]);
51
+ const [keyField, setKeyField] = useState("");
52
+
53
+ const [tables, setTables] = useState<UserTable[]>([]);
54
+ const [targetTable, setTargetTable] = useState("");
55
+ const [fieldKey, setFieldKey] = useState("");
56
+ const [urlField, setUrlField] = useState("");
57
+
58
+ useEffect(() => {
59
+ const ac = new AbortController();
60
+ listTables(ac.signal)
61
+ .then((r) => setTables(r.tables))
62
+ .catch(() => setTables([]));
63
+ return () => ac.abort();
64
+ }, []);
65
+
66
+ const table = tables.find((t) => t.key === targetTable) || null;
67
+
68
+ const readPage = useCallback(async () => {
69
+ setReading(true);
70
+ setProblem("");
71
+ try {
72
+ const p = await previewSource(url, extract, tableIndex);
73
+ setPreview(p);
74
+ if (!p.ok) {
75
+ setProblem(p.note || `That page answered ${p.status}.`);
76
+ return;
77
+ }
78
+ setPlan(
79
+ p.columns.map((column) => ({ column, include: true, key: fieldKeyFor(column) }))
80
+ );
81
+ setKeyField(fieldKeyFor(p.columns[0] || ""));
82
+ if (!targetLabel) setTargetLabel(p.title || "Scraped table");
83
+ setMessage(
84
+ `Read ${p.rowCount} rows and ${p.columns.length} columns` +
85
+ (p.tableCount && p.tableCount > 1 ? ` (of ${p.tableCount} tables on the page)` : "")
86
+ );
87
+ } catch (e) {
88
+ setProblem(e instanceof AutomationError ? e.message : "That page could not be read.");
89
+ } finally {
90
+ setReading(false);
91
+ }
92
+ }, [url, extract, tableIndex, targetLabel]);
93
+
94
+ const create = async () => {
95
+ setSaving(true);
96
+ setProblem("");
97
+ try {
98
+ const fieldMap: Record<string, string> = {};
99
+ for (const c of plan) if (c.include && c.key) fieldMap[c.column] = c.key;
100
+ const res = await createAutomation({
101
+ name,
102
+ kind,
103
+ schedule: { cron: "0 6 * * *", enabled: false },
104
+ config:
105
+ kind === "scrape_db"
106
+ ? { url, extract, tableIndex, fieldMap, keyField, targetLabel }
107
+ : kind === "discover_instagram"
108
+ ? {
109
+ // A search is created with a SMALL, NARROW default and no schedule, then
110
+ // widened in the steps, where the cost estimate is. The one shape that must
111
+ // never be the default is the expensive one.
112
+ recordsLimit: 25,
113
+ operator: "and",
114
+ // ⚠ EVERY DEFAULT PREDICATE MUST BE ONE THE SERVER ACCEPTS (item 8). This
115
+ // list carried `{biography includes ""}` β€” a condition with no value, which
116
+ // `clean_predicates` refuses by design ("give a value to compare
117
+ // 'biography' against"), so EVERY attempt to create a search failed on a
118
+ // condition nobody had typed and the form gave no way to remove. The
119
+ // opposite mistake is just as easy: an EMPTY list is refused too (an empty
120
+ // filter matches the whole corpus), so this is one valid condition, never
121
+ // none.
122
+ predicates: [{ name: "followers", operator: ">=", value: 10000 }],
123
+ }
124
+ : { targetTable, fieldKey, urlField, maxPosts: 24, tier: "anonymous" },
125
+ });
126
+ await onCreated(res.automation.id);
127
+ } catch (e) {
128
+ setProblem(e instanceof AutomationError ? e.message : "That could not be created.");
129
+ } finally {
130
+ setSaving(false);
131
+ }
132
+ };
133
+
134
+ const canCreate =
135
+ !!name.trim() &&
136
+ (kind === "scrape_db"
137
+ ? !!url.trim() && plan.some((c) => c.include && c.key === keyField)
138
+ : kind === "discover_instagram"
139
+ ? true
140
+ : !!targetTable && !!fieldKey);
141
+
142
+ return (
143
+ <div className="auto-create-pane">
144
+ <div className="auto-create-card">
145
+ <h1>New automation</h1>
146
+ <p className="auto-hint">
147
+ Pick what it does. Once it exists you configure it one step at a time.
148
+ </p>
149
+
150
+ {problem ? (
151
+ <div className="auto-banner is-error" role="alert">
152
+ {problem}
153
+ </div>
154
+ ) : null}
155
+ {message ? (
156
+ <div className="auto-banner is-ok" role="status">
157
+ {message}
158
+ </div>
159
+ ) : null}
160
+
161
+ <div className="auto-field">
162
+ <label htmlFor="auto-new-name">Name</label>
163
+ <input
164
+ id="auto-new-name"
165
+ className="auto-input"
166
+ value={name}
167
+ placeholder="S&P 500 companies"
168
+ onChange={(e) => setName(e.target.value)}
169
+ />
170
+ </div>
171
+
172
+ <div className="auto-kinds">
173
+ {kinds.map((k) => (
174
+ <label key={k.key} className={"auto-kind" + (kind === k.key ? " is-on" : "")}>
175
+ <input
176
+ type="radio"
177
+ name="auto-kind"
178
+ checked={kind === k.key}
179
+ onChange={() => setKind(k.key)}
180
+ />
181
+ <span>{k.label}</span>
182
+ </label>
183
+ ))}
184
+ </div>
185
+
186
+ {kind === "discover_instagram" ? (
187
+ <>
188
+ <p className="auto-hint">
189
+ It searches a corpus of pre-collected public Instagram profiles for accounts you
190
+ have never heard of, and collects the matches into a candidates database. You set
191
+ the conditions and how many profiles to fetch in its steps, where the cost
192
+ estimate is β€” searching is the one thing this workspace does that spends money per
193
+ run.
194
+ </p>
195
+ <p className="auto-hint">
196
+ It starts with a narrow default and no schedule. Nothing it finds is ever tracked
197
+ automatically; you tick the accounts you want.
198
+ </p>
199
+ </>
200
+ ) : kind === "scrape_db" ? (
201
+ <>
202
+ <div className="auto-field">
203
+ <label htmlFor="auto-new-url">Page URL</label>
204
+ <div className="auto-row-inline">
205
+ <input
206
+ id="auto-new-url"
207
+ className="auto-input"
208
+ value={url}
209
+ placeholder="https://en.wikipedia.org/wiki/List_of_S%26P_500_companies"
210
+ onChange={(e) => setUrl(e.target.value)}
211
+ />
212
+ <button
213
+ type="button"
214
+ className="auto-btn"
215
+ disabled={!url.trim() || reading}
216
+ onClick={() => void readPage()}
217
+ >
218
+ {reading ? "Reading…" : "Read the page"}
219
+ </button>
220
+ </div>
221
+ <p className="auto-hint">
222
+ Public web pages only. Private, loopback and link-local addresses are refused β€”
223
+ including a public URL that redirects to one.
224
+ </p>
225
+ </div>
226
+ <div className="auto-field-row">
227
+ <div className="auto-field">
228
+ <label htmlFor="auto-new-extract">Read</label>
229
+ <select
230
+ id="auto-new-extract"
231
+ className="auto-input"
232
+ value={extract}
233
+ onChange={(e) => setExtract(e.target.value)}
234
+ >
235
+ <option value="table">An HTML table</option>
236
+ <option value="jsonld">Structured data (JSON-LD)</option>
237
+ </select>
238
+ </div>
239
+ {extract === "table" ? (
240
+ <div className="auto-field">
241
+ <label htmlFor="auto-new-tidx">Which table</label>
242
+ <input
243
+ id="auto-new-tidx"
244
+ className="auto-input"
245
+ type="number"
246
+ min={0}
247
+ value={tableIndex}
248
+ onChange={(e) => setTableIndex(Number(e.target.value) || 0)}
249
+ />
250
+ </div>
251
+ ) : null}
252
+ <div className="auto-field">
253
+ <label htmlFor="auto-new-tlabel">Database name</label>
254
+ <input
255
+ id="auto-new-tlabel"
256
+ className="auto-input"
257
+ value={targetLabel}
258
+ placeholder="S&P 500 companies"
259
+ onChange={(e) => setTargetLabel(e.target.value)}
260
+ />
261
+ </div>
262
+ </div>
263
+
264
+ {plan.length ? (
265
+ <div className="auto-map">
266
+ <h3>Columns</h3>
267
+ <p className="auto-hint">
268
+ Pick the key β€” the column that identifies a row. On every re-run, a row whose
269
+ key already exists is updated; a new key is inserted; a key that has stopped
270
+ appearing is counted and kept.
271
+ </p>
272
+ <div className="auto-drill-scroll">
273
+ <table className="auto-table">
274
+ <thead>
275
+ <tr>
276
+ <th>Use</th>
277
+ <th>Source column</th>
278
+ <th>Field key</th>
279
+ <th>Key</th>
280
+ {preview?.sample?.length ? <th>First value</th> : null}
281
+ </tr>
282
+ </thead>
283
+ <tbody>
284
+ {plan.map((c, i) => (
285
+ <tr key={c.column}>
286
+ <td>
287
+ <input
288
+ type="checkbox"
289
+ checked={c.include}
290
+ aria-label={`Include ${c.column}`}
291
+ onChange={(e) =>
292
+ setPlan((p) =>
293
+ p.map((x, j) =>
294
+ j === i ? { ...x, include: e.target.checked } : x
295
+ )
296
+ )
297
+ }
298
+ />
299
+ </td>
300
+ <td className="auto-cell-name">{c.column}</td>
301
+ <td>
302
+ <input
303
+ className="auto-input is-small"
304
+ value={c.key}
305
+ aria-label={`Field key for ${c.column}`}
306
+ onChange={(e) =>
307
+ setPlan((p) =>
308
+ p.map((x, j) =>
309
+ j === i ? { ...x, key: fieldKeyFor(e.target.value) } : x
310
+ )
311
+ )
312
+ }
313
+ />
314
+ </td>
315
+ <td>
316
+ <input
317
+ type="radio"
318
+ name="auto-new-keyfield"
319
+ checked={keyField === c.key && c.include}
320
+ disabled={!c.include}
321
+ aria-label={`Use ${c.column} as the key`}
322
+ onChange={() => setKeyField(c.key)}
323
+ />
324
+ </td>
325
+ {preview?.sample?.length ? (
326
+ <td className="auto-cell-sample">
327
+ {String(preview.sample[0]?.[c.column] ?? "")}
328
+ </td>
329
+ ) : null}
330
+ </tr>
331
+ ))}
332
+ </tbody>
333
+ </table>
334
+ </div>
335
+ </div>
336
+ ) : (
337
+ <p className="auto-note">Read the page to see what columns it offers.</p>
338
+ )}
339
+ </>
340
+ ) : (
341
+ <>
342
+ <div className="auto-field-row">
343
+ <div className="auto-field">
344
+ <label htmlFor="auto-new-table">Database</label>
345
+ <select
346
+ id="auto-new-table"
347
+ className="auto-input"
348
+ value={targetTable}
349
+ onChange={(e) => {
350
+ setTargetTable(e.target.value);
351
+ setFieldKey("");
352
+ setUrlField("");
353
+ }}
354
+ >
355
+ <option value="">Choose a database…</option>
356
+ {tables.map((t) => (
357
+ <option key={t.key} value={t.key}>
358
+ {t.label} ({t.rowCount} {t.rowCount === 1 ? "row" : "rows"})
359
+ </option>
360
+ ))}
361
+ </select>
362
+ </div>
363
+ <div className="auto-field">
364
+ <label htmlFor="auto-new-fieldkey">Automation column</label>
365
+ <select
366
+ id="auto-new-fieldkey"
367
+ className="auto-input"
368
+ value={fieldKey}
369
+ onChange={(e) => setFieldKey(e.target.value)}
370
+ >
371
+ <option value="">Choose a column…</option>
372
+ {(table?.fields || [])
373
+ .filter((f) => f.type === "automation")
374
+ .map((f) => (
375
+ <option key={f.key} value={f.key}>
376
+ {f.label}
377
+ </option>
378
+ ))}
379
+ </select>
380
+ </div>
381
+ <div className="auto-field">
382
+ <label htmlFor="auto-new-urlfield">Profile URL column</label>
383
+ <select
384
+ id="auto-new-urlfield"
385
+ className="auto-input"
386
+ value={urlField}
387
+ onChange={(e) => setUrlField(e.target.value)}
388
+ >
389
+ <option value="">The column the field is bound to</option>
390
+ {(table?.fields || []).map((f) => (
391
+ <option key={f.key} value={f.key}>
392
+ {f.label}
393
+ </option>
394
+ ))}
395
+ </select>
396
+ </div>
397
+ </div>
398
+ <p className="auto-hint">
399
+ It starts on the free anonymous rung. The Bright Data step turns on
400
+ the paid one, which returns exact counts and the profile&rsquo;s top posts, and
401
+ works from a datacenter. Likes and comments per post are a separate step again β€”
402
+ they cost one record per post rather than one per profile, so they are off until
403
+ you turn them on.
404
+ </p>
405
+ {table && !(table.fields || []).some((f) => f.type === "automation") ? (
406
+ <p className="auto-note">
407
+ That database has no automation column yet. Add one from the grid&rsquo;s column
408
+ menu, then choose it here.
409
+ </p>
410
+ ) : null}
411
+ </>
412
+ )}
413
+
414
+ <div className="auto-head-actions">
415
+ <button
416
+ type="button"
417
+ className="auto-btn is-primary"
418
+ disabled={!canCreate || saving}
419
+ onClick={() => void create()}
420
+ >
421
+ {saving ? "Creating…" : "Create"}
422
+ </button>
423
+ <button type="button" className="auto-btn" onClick={onCancel}>
424
+ Cancel
425
+ </button>
426
+ </div>
427
+ </div>
428
+ </div>
429
+ );
430
+ }
web/src/automation/AutomationDetail.tsx CHANGED
@@ -1,999 +1,1025 @@
1
- // ---------------------------------------------------------------------------
2
- // automation/AutomationDetail.tsx β€” one automation, as a flow you can walk.
3
- //
4
- // THE SHAPE, and what changed from the stacked-cards editor it replaces (R5):
5
- // the automation is now a CANVAS of nodes, and the right-hand panel shows the
6
- // configuration of whichever node you clicked. The two halves answer different
7
- // questions and neither used to be answerable at a glance β€” the canvas answers
8
- // "what does this thing do, in what order, and which step went wrong last
9
- // night", the panel answers "what exactly is step 3 configured to do".
10
- //
11
- // ONE CONTROL PER FACT. A node's SWITCH is the only way to turn that step on or
12
- // off; the panel never carries a second checkbox for the same flag. The schedule
13
- // panel therefore edits the cron STRING and nothing else β€” whether the schedule
14
- // is live is the Trigger node's switch. Two controls for one boolean is how a UI
15
- // starts disagreeing with itself.
16
- //
17
- // EVERY COUNT DRILLS TO ROWS. A run that says "412 updated" opens the 412
18
- // ([[no-unverifiable-aggregates]]) β€” a number with no way back to its records is
19
- // what this codebase treats as a defect rather than a summary.
20
- // ---------------------------------------------------------------------------
21
- import { useCallback, useEffect, useMemo, useState } from "react";
22
-
23
- import AutomationCanvas from "./AutomationCanvas";
24
- import type {
25
- Automation,
26
- AutomationKind,
27
- GraphNode,
28
- RunEntry,
29
- RunRows,
30
- DiscoverEstimate,
31
- DiscoverVocab,
32
- SourcePreview,
33
- UserTable,
34
- } from "./automationApi";
35
- import {
36
- AutomationError,
37
- COUNT_LABELS,
38
- deleteAutomation,
39
- discoverEstimate,
40
- fieldKeyFor,
41
- listTables,
42
- patchAutomation,
43
- previewSource,
44
- runAutomation,
45
- runRows,
46
- toggleNode,
47
- } from "./automationApi";
48
-
49
- interface Props {
50
- automation: Automation;
51
- kinds: { key: AutomationKind; label: string }[];
52
- cronPresets: { cron: string; label: string }[];
53
- paidReady: boolean;
54
- /** The server-declared discovery vocabulary (absent until the list loads). */
55
- discover?: DiscoverVocab;
56
- onSaved: (id?: string) => void | Promise<void>;
57
- onDeleted: () => void | Promise<void>;
58
- }
59
-
60
- interface ColumnPlan {
61
- column: string;
62
- include: boolean;
63
- key: string;
64
- }
65
-
66
- /** One condition of a corpus search. Mirrors the server's `clean_predicates`. */
67
- interface Predicate {
68
- name: string;
69
- operator: string;
70
- value?: string | number;
71
- }
72
-
73
- export default function AutomationDetail({
74
- automation,
75
- kinds,
76
- cronPresets,
77
- paidReady,
78
- discover,
79
- onSaved,
80
- onDeleted,
81
- }: Props) {
82
- const cfg = (automation.config || {}) as Record<string, string | number | boolean>;
83
- const kind = automation.kind;
84
-
85
- const [name, setName] = useState(automation.name || "");
86
- const [cron, setCron] = useState(automation.schedule?.cron || "0 6 * * *");
87
- const [message, setMessage] = useState("");
88
- const [problem, setProblem] = useState("");
89
- const [saving, setSaving] = useState(false);
90
- const [touched, setTouched] = useState(false);
91
- const [busyNode, setBusyNode] = useState("");
92
- const [selected, setSelected] = useState("");
93
-
94
- // --- scrape_db half
95
- const [url, setUrl] = useState(String(cfg.url || ""));
96
- const [extract, setExtract] = useState(String(cfg.extract || "table"));
97
- const [tableIndex, setTableIndex] = useState(Number(cfg.tableIndex || 0));
98
- const [targetLabel, setTargetLabel] = useState(String(cfg.targetLabel || ""));
99
- const [preview, setPreview] = useState<SourcePreview | null>(null);
100
- const [reading, setReading] = useState(false);
101
- const [plan, setPlan] = useState<ColumnPlan[]>(() =>
102
- Object.entries((automation.config as { fieldMap?: Record<string, string> })?.fieldMap || {})
103
- .map(([column, key]) => ({ column, include: true, key }))
104
- );
105
- const [keyField, setKeyField] = useState(String(cfg.keyField || ""));
106
-
107
- // --- field_instagram half
108
- const [tables, setTables] = useState<UserTable[]>([]);
109
- const [targetTable, setTargetTable] = useState(String(cfg.targetTable || ""));
110
- const [fieldKey, setFieldKey] = useState(String(cfg.fieldKey || ""));
111
- const [urlField, setUrlField] = useState(String(cfg.urlField || ""));
112
- const [maxPosts, setMaxPosts] = useState(Number(cfg.maxPosts || 24));
113
-
114
- // --- discover_instagram half (R7)
115
- const [recordsLimit, setRecordsLimit] = useState(Number(cfg.recordsLimit || 25));
116
- const [joinOp, setJoinOp] = useState(String(cfg.operator || "and"));
117
- const [preds, setPreds] = useState<Predicate[]>(() => {
118
- const stored = (automation.config as { predicates?: Predicate[] })?.predicates;
119
- return stored && stored.length
120
- ? stored.map((p) => ({ ...p }))
121
- : [{ name: "followers", operator: ">=", value: 10000 }];
122
- });
123
- const [estimate, setEstimate] = useState<DiscoverEstimate | null>(null);
124
-
125
- // --- run history drill
126
- const [drill, setDrill] = useState<RunRows | null>(null);
127
- const [drillFor, setDrillFor] = useState("");
128
-
129
- useEffect(() => {
130
- const ac = new AbortController();
131
- listTables(ac.signal)
132
- .then((r) => setTables(r.tables))
133
- .catch(() => setTables([]));
134
- return () => ac.abort();
135
- }, []);
136
-
137
- const table = tables.find((t) => t.key === targetTable) || null;
138
- const node: GraphNode | null =
139
- (automation.graph?.nodes || []).find((n) => n.id === selected) || null;
140
-
141
- const edit = <T,>(set: (v: T) => void) => (v: T) => {
142
- setTouched(true);
143
- set(v);
144
- };
145
-
146
- const readPage = useCallback(async () => {
147
- setReading(true);
148
- setProblem("");
149
- try {
150
- const p = await previewSource(url, extract, tableIndex);
151
- setPreview(p);
152
- if (!p.ok) {
153
- setProblem(p.note || `That page answered ${p.status}.`);
154
- return;
155
- }
156
- // Seed the plan from what the page ACTUALLY offers, keeping any mapping the
157
- // user already made for a column that is still there β€” re-reading a page
158
- // must not throw away the work of mapping it.
159
- setPlan((prev) => {
160
- const had = new Map(prev.map((c) => [c.column, c]));
161
- return p.columns.map((column) => {
162
- const before = had.get(column);
163
- return {
164
- column,
165
- include: before ? before.include : true,
166
- key: before ? before.key : fieldKeyFor(column),
167
- };
168
- });
169
- });
170
- setKeyField((k) =>
171
- k && p.columns.some((c) => fieldKeyFor(c) === k) ? k : fieldKeyFor(p.columns[0] || "")
172
- );
173
- if (!targetLabel) setTargetLabel(p.title || "Scraped table");
174
- setTouched(true);
175
- setMessage(
176
- `Read ${p.rowCount} rows and ${p.columns.length} columns` +
177
- (p.tableCount && p.tableCount > 1 ? ` (of ${p.tableCount} tables on the page)` : "")
178
- );
179
- } catch (e) {
180
- setProblem(e instanceof AutomationError ? e.message : "That page could not be read.");
181
- } finally {
182
- setReading(false);
183
- }
184
- }, [url, extract, tableIndex, targetLabel]);
185
-
186
- /**
187
- * ⚠ The switch flags (`tier`, `noFallback`, `dryRun`) are DELIBERATELY absent.
188
- * They are node switches, not panel fields, and the server keeps the stored
189
- * value for any flag a config omits β€” so a Save from here can never quietly
190
- * turn the paid rung off. (`clean_config`'s `flag()`, asserted in section N.)
191
- */
192
- const buildConfig = (): Record<string, unknown> => {
193
- if (kind === "scrape_db") {
194
- const fieldMap: Record<string, string> = {};
195
- for (const c of plan) if (c.include && c.key) fieldMap[c.column] = c.key;
196
- return {
197
- url,
198
- extract,
199
- tableIndex,
200
- fieldMap,
201
- keyField,
202
- targetTable: String(cfg.targetTable || ""),
203
- targetLabel,
204
- };
205
- }
206
- if (kind === "discover_instagram") {
207
- return {
208
- recordsLimit,
209
- operator: joinOp,
210
- predicates: preds.filter((p) => p.name && p.operator),
211
- targetTable: String(cfg.targetTable || ""),
212
- };
213
- }
214
- return { targetTable, fieldKey, urlField, maxPosts };
215
- };
216
-
217
- const persist = async (announce = true) => {
218
- const res = await patchAutomation(automation.id, {
219
- name,
220
- kind,
221
- config: buildConfig(),
222
- schedule: { cron, enabled: !!automation.schedule?.enabled },
223
- });
224
- setTouched(false);
225
- if (announce) setMessage("Saved.");
226
- return res.automation.id;
227
- };
228
-
229
- const save = async () => {
230
- setSaving(true);
231
- setProblem("");
232
- setMessage("");
233
- try {
234
- const id = await persist();
235
- await onSaved(id);
236
- } catch (e) {
237
- setProblem(e instanceof AutomationError ? e.message : "That could not be saved.");
238
- } finally {
239
- setSaving(false);
240
- }
241
- };
242
-
243
- /**
244
- * A node switch is immediate β€” a switch that needs a separate Save is not a
245
- * switch. Unsaved panel edits are persisted FIRST rather than being discarded
246
- * by the reload that follows, which is the one way this could lose work.
247
- */
248
- const flip = async (nodeId: string) => {
249
- setBusyNode(nodeId);
250
- setProblem("");
251
- setMessage("");
252
- try {
253
- if (touched) await persist(false);
254
- await toggleNode(automation.id, nodeId);
255
- await onSaved(automation.id);
256
- } catch (e) {
257
- setProblem(e instanceof AutomationError ? e.message : "That step was not changed.");
258
- } finally {
259
- setBusyNode("");
260
- }
261
- };
262
-
263
- const start = async () => {
264
- setProblem("");
265
- try {
266
- await runAutomation(automation.id);
267
- setMessage("Started. The node dots follow it.");
268
- await onSaved(automation.id);
269
- } catch (e) {
270
- setProblem(e instanceof AutomationError ? e.message : "It did not start.");
271
- }
272
- };
273
-
274
- const remove = async () => {
275
- setProblem("");
276
- try {
277
- await deleteAutomation(automation.id);
278
- await onDeleted();
279
- } catch (e) {
280
- setProblem(e instanceof AutomationError ? e.message : "It was not deleted.");
281
- }
282
- };
283
-
284
- const openDrill = async (entry: RunEntry) => {
285
- if (drillFor === entry.ts) {
286
- setDrill(null);
287
- setDrillFor("");
288
- return;
289
- }
290
- try {
291
- const rows = await runRows(automation.id);
292
- setDrill(rows);
293
- setDrillFor(entry.ts);
294
- } catch (e) {
295
- setProblem(e instanceof AutomationError ? e.message : "Those rows could not be read.");
296
- }
297
- };
298
-
299
- const presetMatch = useMemo(
300
- () => cronPresets.find((p) => p.cron === cron)?.cron || "",
301
- [cronPresets, cron]
302
- );
303
- const state = automation.running ? "running" : automation.status?.state || "idle";
304
-
305
- return (
306
- <div className="auto-detail">
307
- <header className="auto-head">
308
- <div className="auto-head-title">
309
- <input
310
- className="auto-name"
311
- value={name}
312
- placeholder="Name this automation"
313
- aria-label="Automation name"
314
- onChange={(e) => edit(setName)(e.target.value)}
315
- />
316
- <span className={`auto-chip is-${state}`}>
317
- {automation.running ? "Running" : state}
318
- </span>
319
- <span className="auto-kindtag">
320
- {kinds.find((k) => k.key === kind)?.label || kind}
321
- </span>
322
- </div>
323
- <div className="auto-head-actions">
324
- <button
325
- type="button"
326
- className="auto-btn"
327
- disabled={!!automation.running}
328
- onClick={() => void start()}
329
- >
330
- {automation.running ? "Running…" : "Run now"}
331
- </button>
332
- <button
333
- type="button"
334
- className="auto-btn is-primary"
335
- disabled={saving || !name.trim()}
336
- onClick={() => void save()}
337
- >
338
- {saving ? "Saving…" : "Save"}
339
- </button>
340
- <button type="button" className="auto-btn is-danger" onClick={() => void remove()}>
341
- Delete
342
- </button>
343
- </div>
344
- </header>
345
-
346
- {problem ? (
347
- <div className="auto-banner is-error" role="alert">
348
- {problem}
349
- </div>
350
- ) : null}
351
- {message ? (
352
- <div className="auto-banner is-ok" role="status">
353
- {message}
354
- </div>
355
- ) : null}
356
-
357
- <div className="auto-work">
358
- <AutomationCanvas
359
- graph={automation.graph}
360
- selected={selected}
361
- onSelect={setSelected}
362
- onToggle={(id) => void flip(id)}
363
- busyNode={busyNode}
364
- nextRunAt={automation.nextRunAt}
365
- />
366
-
367
- <aside className="auto-panel" aria-label={node ? `${node.title} settings` : "Run history"}>
368
- {node ? (
369
- <>
370
- <div className="auto-panel-head">
371
- <h2>{node.title}</h2>
372
- <button
373
- type="button"
374
- className="auto-panel-close"
375
- aria-label="Back to run history"
376
- title="Back to run history"
377
- onClick={() => setSelected("")}
378
- >
379
- <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
380
- <path
381
- d="M4 4l8 8M12 4l-8 8"
382
- stroke="currentColor"
383
- strokeWidth="1.5"
384
- strokeLinecap="round"
385
- />
386
- </svg>
387
- </button>
388
- </div>
389
- {!node.enabled ? (
390
- <p className="auto-note is-off">
391
- This step is switched off. Its card on the canvas carries the switch that turns
392
- it back on.
393
- </p>
394
- ) : null}
395
-
396
- {node.panel === "schedule" ? (
397
- <>
398
- <div className="auto-field">
399
- <label htmlFor="auto-preset">Schedule</label>
400
- <select
401
- id="auto-preset"
402
- className="auto-input"
403
- value={presetMatch}
404
- onChange={(e) => e.target.value && edit(setCron)(e.target.value)}
405
- >
406
- <option value="">Custom…</option>
407
- {cronPresets.map((p) => (
408
- <option key={p.cron} value={p.cron}>
409
- {p.label}
410
- </option>
411
- ))}
412
- </select>
413
- </div>
414
- <div className="auto-field">
415
- <label htmlFor="auto-cron">Cron (minute hour day month weekday)</label>
416
- <input
417
- id="auto-cron"
418
- className="auto-input is-mono"
419
- value={cron}
420
- onChange={(e) => edit(setCron)(e.target.value)}
421
- />
422
- </div>
423
- <p className="auto-hint">
424
- {automation.nextRunAt
425
- ? `Next run ${automation.nextRunAt}.`
426
- : automation.schedule?.enabled
427
- ? "Schedules start from the moment they are switched on β€” turning on a daily job after today's time does not fire it immediately."
428
- : "Not scheduled. It still runs when you press Run now, and the node's switch turns the schedule on."}
429
- </p>
430
- </>
431
- ) : null}
432
-
433
- {node.panel === "source" && kind === "scrape_db" ? (
434
- <>
435
- <div className="auto-field">
436
- <label htmlFor="auto-url">Page URL</label>
437
- <input
438
- id="auto-url"
439
- className="auto-input"
440
- value={url}
441
- placeholder="https://en.wikipedia.org/wiki/List_of_S%26P_500_companies"
442
- onChange={(e) => edit(setUrl)(e.target.value)}
443
- />
444
- </div>
445
- <button
446
- type="button"
447
- className="auto-btn"
448
- disabled={!url.trim() || reading}
449
- onClick={() => void readPage()}
450
- >
451
- {reading ? "Reading…" : "Read the page"}
452
- </button>
453
- <div className="auto-field">
454
- <label htmlFor="auto-extract">Read</label>
455
- <select
456
- id="auto-extract"
457
- className="auto-input"
458
- value={extract}
459
- onChange={(e) => edit(setExtract)(e.target.value)}
460
- >
461
- <option value="table">An HTML table</option>
462
- <option value="jsonld">Structured data (JSON-LD)</option>
463
- </select>
464
- </div>
465
- {extract === "table" ? (
466
- <div className="auto-field">
467
- <label htmlFor="auto-tidx">Which table</label>
468
- <input
469
- id="auto-tidx"
470
- className="auto-input"
471
- type="number"
472
- min={0}
473
- value={tableIndex}
474
- onChange={(e) => edit(setTableIndex)(Number(e.target.value) || 0)}
475
- />
476
- </div>
477
- ) : null}
478
- <p className="auto-hint">
479
- Public web pages only. Private, loopback and link-local addresses are refused
480
- β€” including a public URL that redirects to one.
481
- </p>
482
- </>
483
- ) : null}
484
-
485
- {node.panel === "columns" ? (
486
- plan.length ? (
487
- <>
488
- <p className="auto-hint">
489
- Pick the key β€” the column that identifies a row. On every re-run, a row
490
- whose key already exists is updated; a new key is inserted; a key that has
491
- stopped appearing is counted and kept.
492
- </p>
493
- <div className="auto-panel-scroll">
494
- <table className="auto-table">
495
- <thead>
496
- <tr>
497
- <th>Use</th>
498
- <th>Source column</th>
499
- <th>Field key</th>
500
- <th>Key</th>
501
- </tr>
502
- </thead>
503
- <tbody>
504
- {plan.map((c, i) => (
505
- <tr key={c.column}>
506
- <td>
507
- <input
508
- type="checkbox"
509
- checked={c.include}
510
- aria-label={`Include ${c.column}`}
511
- onChange={(e) =>
512
- edit(setPlan)(
513
- plan.map((x, j) =>
514
- j === i ? { ...x, include: e.target.checked } : x
515
- )
516
- )
517
- }
518
- />
519
- </td>
520
- <td className="auto-cell-name">{c.column}</td>
521
- <td>
522
- <input
523
- className="auto-input is-small"
524
- value={c.key}
525
- aria-label={`Field key for ${c.column}`}
526
- onChange={(e) =>
527
- edit(setPlan)(
528
- plan.map((x, j) =>
529
- j === i
530
- ? { ...x, key: fieldKeyFor(e.target.value) }
531
- : x
532
- )
533
- )
534
- }
535
- />
536
- </td>
537
- <td>
538
- <input
539
- type="radio"
540
- name="auto-keyfield"
541
- checked={keyField === c.key && c.include}
542
- disabled={!c.include}
543
- aria-label={`Use ${c.column} as the key`}
544
- onChange={() => edit(setKeyField)(c.key)}
545
- />
546
- </td>
547
- </tr>
548
- ))}
549
- </tbody>
550
- </table>
551
- </div>
552
- {preview?.sample?.length ? (
553
- <p className="auto-hint">
554
- First row read: {Object.values(preview.sample[0]).slice(0, 4).join(" Β· ")}
555
- </p>
556
- ) : null}
557
- </>
558
- ) : (
559
- <p className="auto-note">
560
- Open the Fetch step and read the page to see what columns it offers.
561
- </p>
562
- )
563
- ) : null}
564
-
565
- {node.panel === "source" && kind === "field_instagram" ? (
566
- <>
567
- <div className="auto-field">
568
- <label htmlFor="auto-table">Database</label>
569
- <select
570
- id="auto-table"
571
- className="auto-input"
572
- value={targetTable}
573
- onChange={(e) => {
574
- edit(setTargetTable)(e.target.value);
575
- setFieldKey("");
576
- setUrlField("");
577
- }}
578
- >
579
- <option value="">Choose a database…</option>
580
- {targetTable && !tables.some((t) => t.key === targetTable) ? (
581
- <option value={targetTable}>{targetTable} (not visible to you)</option>
582
- ) : null}
583
- {tables.map((t) => (
584
- <option key={t.key} value={t.key}>
585
- {t.label} ({t.rowCount} {t.rowCount === 1 ? "row" : "rows"})
586
- </option>
587
- ))}
588
- </select>
589
- </div>
590
- <div className="auto-field">
591
- <label htmlFor="auto-urlfield">Profile URL column</label>
592
- <select
593
- id="auto-urlfield"
594
- className="auto-input"
595
- value={urlField}
596
- onChange={(e) => edit(setUrlField)(e.target.value)}
597
- >
598
- <option value="">The column the field is bound to</option>
599
- {(table?.fields || []).map((f) => (
600
- <option key={f.key} value={f.key}>
601
- {f.label}
602
- </option>
603
- ))}
604
- </select>
605
- </div>
606
- <div className="auto-field">
607
- <label htmlFor="auto-fieldkey">Automation column</label>
608
- <select
609
- id="auto-fieldkey"
610
- className="auto-input"
611
- value={fieldKey}
612
- onChange={(e) => edit(setFieldKey)(e.target.value)}
613
- >
614
- <option value="">Choose a column…</option>
615
- {/*
616
- ⚠ THE STORED VALUE IS ALWAYS AN OPTION, even when the list
617
- below does not contain it. A <select> whose `value` matches
618
- no <option> renders the FIRST one β€” so a column the server
619
- knows about but this list has not caught up with would look
620
- like a DIFFERENT column, and the next Save would write that
621
- different column without anybody choosing it. Showing it as
622
- "(not in this database)" is the honest version.
623
- */}
624
- {fieldKey && !(table?.fields || []).some((f) => f.key === fieldKey) ? (
625
- <option value={fieldKey}>{fieldKey} (not in this database)</option>
626
- ) : null}
627
- {(table?.fields || [])
628
- .filter((f) => f.type === "automation")
629
- .map((f) => (
630
- <option key={f.key} value={f.key}>
631
- {f.label}
632
- </option>
633
- ))}
634
- </select>
635
- </div>
636
- {table && !(table.fields || []).some((f) => f.type === "automation") ? (
637
- <p className="auto-note">
638
- That database has no automation column yet. Add one from the grid&rsquo;s
639
- column menu, then choose it here.
640
- </p>
641
- ) : null}
642
- </>
643
- ) : null}
644
-
645
- {node.panel === "capture" ? (
646
- <>
647
- <div className="auto-field">
648
- <label htmlFor="auto-maxposts">Posts per pull</label>
649
- <input
650
- id="auto-maxposts"
651
- className="auto-input"
652
- type="number"
653
- min={1}
654
- max={200}
655
- value={maxPosts}
656
- onChange={(e) => edit(setMaxPosts)(Number(e.target.value) || 24)}
657
- />
658
- </div>
659
- <h3>Bright Data β€” the paid rung</h3>
660
- <p className="auto-hint">
661
- Exact follower counts and the profile&rsquo;s top posts, and it works from a
662
- datacenter. Its node&rsquo;s switch turns it on.
663
- {paidReady
664
- ? " A key is configured on this deployment."
665
- : " No key is configured on this deployment yet, so it will report itself blocked and the anonymous rung will answer instead."}
666
- </p>
667
- <h3>Post engagement β€” the per-post rung</h3>
668
- <p className="auto-hint">
669
- Likes and comments for each post. It is a separate step because it is a
670
- separate bill: the profile read costs one record, and engagement costs{" "}
671
- <strong>one record per post</strong>. With it off, the posts database still
672
- grows but the engagement series does not β€” and no empty rows are appended to
673
- stand in for the numbers nobody bought.
674
- </p>
675
- <h3>Anonymous β€” the free rung</h3>
676
- <p className="auto-hint">
677
- No login and no credentials. Instagram blocks datacenter addresses and has
678
- closed most of its anonymous surface, so this rung is honest rather than
679
- reliable: counts come from the page&rsquo;s own abbreviations (204K, not
680
- 204,312) and are marked approximate. Turning it off means{" "}
681
- <strong>exact numbers or nothing</strong> β€” a run reports blocked rather than
682
- quietly writing a rounded number.
683
- </p>
684
- <p className="auto-hint">
685
- A pull reports what it actually got: <strong>ok</strong> (profile and posts),{" "}
686
- <strong>partial</strong> (profile only), or <strong>blocked</strong>. It never
687
- reports success on nothing.
688
- </p>
689
- </>
690
- ) : null}
691
-
692
- {node.panel === "find" ? (
693
- <>
694
- <div className="auto-field">
695
- <label htmlFor="auto-records">How many profiles to fetch</label>
696
- <input
697
- id="auto-records"
698
- className="auto-input"
699
- type="number"
700
- min={1}
701
- max={discover?.maxRecords || 1000}
702
- value={recordsLimit}
703
- onChange={(e) => {
704
- edit(setRecordsLimit)(Number(e.target.value) || 1);
705
- setEstimate(null);
706
- }}
707
- />
708
- </div>
709
- <p className="auto-hint">
710
- A search must be bounded. An unbounded one matches a share of a corpus of
711
- hundreds of millions of profiles, and the vendor refuses it outright rather
712
- than delivering it.
713
- </p>
714
-
715
- <h3>Conditions</h3>
716
- {preds.map((pr, i) => (
717
- <div className="auto-field-row" key={i}>
718
- <div className="auto-field">
719
- <label htmlFor={"auto-pred-f-" + i}>Field</label>
720
- <select
721
- id={"auto-pred-f-" + i}
722
- className="auto-input"
723
- value={pr.name}
724
- onChange={(e) =>
725
- edit(setPreds)(
726
- preds.map((q, j) => (j === i ? { ...q, name: e.target.value } : q))
727
- )
728
- }
729
- >
730
- {/*
731
- The stored value is ALWAYS an option β€” see the note on the
732
- automation-column picker. A select whose value matches no option
733
- renders the first one, which silently changes what a Save writes.
734
- */}
735
- {pr.name && !(discover?.fields || []).includes(pr.name) ? (
736
- <option value={pr.name}>{pr.name}</option>
737
- ) : null}
738
- {(discover?.fields || []).map((f) => (
739
- <option key={f} value={f}>
740
- {f}
741
- {(discover?.lead || []).includes(f) ? " (has values)" : ""}
742
- </option>
743
- ))}
744
- </select>
745
- </div>
746
- <div className="auto-field">
747
- <label htmlFor={"auto-pred-o-" + i}>Comparison</label>
748
- <select
749
- id={"auto-pred-o-" + i}
750
- className="auto-input"
751
- value={pr.operator}
752
- onChange={(e) =>
753
- edit(setPreds)(
754
- preds.map((q, j) =>
755
- j === i ? { ...q, operator: e.target.value } : q
756
- )
757
- )
758
- }
759
- >
760
- {pr.operator && !(discover?.operators || []).includes(pr.operator) ? (
761
- <option value={pr.operator}>{pr.operator}</option>
762
- ) : null}
763
- {(discover?.operators || []).map((o) => (
764
- <option key={o} value={o}>
765
- {o}
766
- </option>
767
- ))}
768
- </select>
769
- </div>
770
- {(discover?.nullaryOperators || []).includes(pr.operator) ? null : (
771
- <div className="auto-field">
772
- <label htmlFor={"auto-pred-v-" + i}>Value</label>
773
- <input
774
- id={"auto-pred-v-" + i}
775
- className="auto-input"
776
- value={pr.value === undefined ? "" : String(pr.value)}
777
- onChange={(e) =>
778
- edit(setPreds)(
779
- preds.map((q, j) => (j === i ? { ...q, value: e.target.value } : q))
780
- )
781
- }
782
- />
783
- </div>
784
- )}
785
- <div className="auto-field">
786
- <label htmlFor={"auto-pred-x-" + i}>&nbsp;</label>
787
- <button
788
- id={"auto-pred-x-" + i}
789
- type="button"
790
- className="auto-btn"
791
- disabled={preds.length < 2}
792
- onClick={() => edit(setPreds)(preds.filter((_q, j) => j !== i))}
793
- >
794
- Remove
795
- </button>
796
- </div>
797
- </div>
798
- ))}
799
- <div className="auto-head-actions">
800
- <button
801
- type="button"
802
- className="auto-btn"
803
- onClick={() =>
804
- edit(setPreds)([
805
- ...preds,
806
- { name: "biography", operator: "includes", value: "" },
807
- ])
808
- }
809
- >
810
- Add a condition
811
- </button>
812
- <div className="auto-field">
813
- <label htmlFor="auto-joinop">Match</label>
814
- <select
815
- id="auto-joinop"
816
- className="auto-input"
817
- value={joinOp}
818
- onChange={(e) => edit(setJoinOp)(e.target.value)}
819
- >
820
- <option value="and">All of them</option>
821
- <option value="or">Any of them</option>
822
- </select>
823
- </div>
824
- </div>
825
- <p className="auto-hint">
826
- Fields marked <em>has values</em> are the ones we have actually seen carrying
827
- data. The others can be searched, but were empty on every profile we have
828
- looked at β€” and a condition on an empty field returns nothing while looking
829
- exactly like &ldquo;no such accounts exist&rdquo;.
830
- </p>
831
- <p className="auto-hint">
832
- Narrow conditions matter more than a small limit. The search reads the whole
833
- corpus either way, so a broad condition is slow and expensive however few rows
834
- you ask to keep. A search normally takes about twenty minutes; a run that
835
- finds one still going says so and the next run collects it.
836
- </p>
837
-
838
- <h3>What it costs</h3>
839
- <div className="auto-head-actions">
840
- <button
841
- type="button"
842
- className="auto-btn"
843
- onClick={() => {
844
- void discoverEstimate(recordsLimit)
845
- .then(setEstimate)
846
- .catch(() => setEstimate(null));
847
- }}
848
- >
849
- Estimate this search
850
- </button>
851
- </div>
852
- {estimate ? (
853
- <p className="auto-hint">
854
- About <strong>${estimate.usd}</strong> for {estimate.records} profiles, at $
855
- {estimate.unitUsd} each.{" "}
856
- {/*
857
- THE CAVEAT IS NOT OPTIONAL. The vendor never quotes a price before a run
858
- and this deployment cannot read its own balance, so presenting this as a
859
- billed figure would be inventing a measurement.
860
- */}
861
- <strong>This is an estimate</strong> β€” {estimate.note}.
862
- </p>
863
- ) : null}
864
- </>
865
- ) : null}
866
-
867
- {node.panel === "write" ? (
868
- <>
869
- {kind === "scrape_db" ? (
870
- <div className="auto-field">
871
- <label htmlFor="auto-tlabel">Database name</label>
872
- <input
873
- id="auto-tlabel"
874
- className="auto-input"
875
- value={targetLabel}
876
- placeholder="S&P 500 companies"
877
- onChange={(e) => edit(setTargetLabel)(e.target.value)}
878
- />
879
- </div>
880
- ) : kind === "discover_instagram" ? (
881
- <p className="auto-hint">
882
- Matches are collected into{" "}
883
- <code>{discover?.table || "ut_ig_candidates"}</code>, upserted by handle β€” so
884
- re-finding an account costs nothing and its <em>Times found</em> count grows.{" "}
885
- <strong>Nothing found is ever tracked automatically.</strong> Tick the ones
886
- you want; a later search can never un-tick them.
887
- </p>
888
- ) : (
889
- <p className="auto-hint">
890
- Each pull appends a timestamped row to <code>ut_ig_snapshots</code> and, when
891
- the post-engagement step is on, one per post to{" "}
892
- <code>ut_ig_post_snapshots</code> β€” so the history is a time series you can
893
- filter by date rather than a single current value.{" "}
894
- <code>ut_ig_posts</code> holds one row per post, ever.
895
- </p>
896
- )}
897
- <p className="auto-hint">
898
- Turning this step off makes the automation a <strong>dry run</strong>: it
899
- reads everything and reports exactly what it would have written, without
900
- creating or changing a single row.
901
- </p>
902
- {kind === "field_instagram" ? (
903
- <p className="auto-hint">
904
- {/*
905
- ⚠ "Writes nothing" and "costs nothing" are DIFFERENT CLAIMS, and only the
906
- first one is true. A dry run still READS β€” so with the paid steps on it
907
- bills exactly what a real run bills. Saying so here is the only place a
908
- user finds out before the invoice.
909
- */}
910
- A dry run still <strong>reads</strong>. With the Bright Data step on it
911
- costs what a real run costs, and with post engagement on that is one
912
- charged record per post. Turn those steps off too if you want a free
913
- rehearsal.
914
- </p>
915
- ) : null}
916
- <p className="auto-hint">
917
- A row that stops appearing at the source is counted and kept, never deleted.
918
- </p>
919
- </>
920
- ) : null}
921
- </>
922
- ) : (
923
- <>
924
- <div className="auto-panel-head">
925
- <h2>Run history</h2>
926
- </div>
927
- {!automation.runs?.length ? (
928
- <p className="auto-note">
929
- It has not run yet. Press Run now, or switch on the Trigger step.
930
- </p>
931
- ) : (
932
- <ol className="auto-runs">
933
- {automation.runs.map((r) => (
934
- <li key={r.ts} className={"auto-run is-" + (r.ok ? "ok" : "error")}>
935
- <button
936
- type="button"
937
- className="auto-run-head"
938
- onClick={() => void openDrill(r)}
939
- aria-expanded={drillFor === r.ts}
940
- >
941
- <span className="auto-run-ts">{r.ts.replace("T", " ")}</span>
942
- <span className="auto-run-summary">{r.summary}</span>
943
- </button>
944
- <div className="auto-counts">
945
- {COUNT_LABELS.filter(([k]) => typeof r.counts?.[k] === "number").map(
946
- ([k, label]) => (
947
- <span
948
- key={k}
949
- className={
950
- "auto-count" + (k === "capped" && r.counts[k] ? " is-warn" : "")
951
- }
952
- >
953
- <b>{r.counts[k]}</b> {label}
954
- </span>
955
- )
956
- )}
957
- </div>
958
- {drillFor === r.ts && drill ? (
959
- <div className="auto-drill">
960
- <p className="auto-hint">
961
- The rows this run touched in {drill.label}
962
- {drill.truncated ? " (first 200)" : ""}.
963
- </p>
964
- <div className="auto-drill-scroll">
965
- <table className="auto-table">
966
- <thead>
967
- <tr>
968
- {drill.fields.map((f) => (
969
- <th key={f.key}>{f.label}</th>
970
- ))}
971
- </tr>
972
- </thead>
973
- <tbody>
974
- {drill.rows.slice(0, 50).map((row) => (
975
- <tr key={String(row.id)}>
976
- {drill.fields.map((f) => (
977
- <td key={f.key}>{String(row[f.key] ?? "")}</td>
978
- ))}
979
- </tr>
980
- ))}
981
- </tbody>
982
- </table>
983
- </div>
984
- </div>
985
- ) : null}
986
- </li>
987
- ))}
988
- </ol>
989
- )}
990
- <p className="auto-hint">
991
- Click any step on the canvas to see and change what it does.
992
- </p>
993
- </>
994
- )}
995
- </aside>
996
- </div>
997
- </div>
998
- );
999
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // automation/AutomationDetail.tsx β€” one automation, as a flow you can walk.
3
+ //
4
+ // THE SHAPE (wave-21 R9, replacing the W19 canvas): the automation is a column of
5
+ // NUMBERED STEPS, trigger first, and the right-hand panel shows the configuration
6
+ // of whichever step you clicked. The two halves answer different questions and
7
+ // neither used to be answerable at a glance β€” the steps answer "what does this
8
+ // thing do, in what order, and which step went wrong last night", the panel
9
+ // answers "what exactly is step 3 configured to do". The canvas answered the
10
+ // first question as a SHAPE; the engine executes a list, and a list is what the
11
+ // owner asked to read.
12
+ //
13
+ // ONE CONTROL PER FACT. A step's SWITCH is the only way to turn it on or off; the
14
+ // panel never carries a second checkbox for the same flag. STEP 1 IS THE ONE
15
+ // EXCEPTION AND IT IS THE SAME RULE: the trigger's picker IS its on/off, so the
16
+ // panel has no schedule face at all any more. Two controls for one boolean is how
17
+ // a UI starts disagreeing with itself.
18
+ //
19
+ // EVERY COUNT DRILLS TO ROWS. A run that says "412 updated" opens the 412
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 AutomationSteps from "./AutomationSteps";
26
+ import type {
27
+ Automation,
28
+ AutomationKind,
29
+ GraphNode,
30
+ RunEntry,
31
+ RunRows,
32
+ DiscoverEstimate,
33
+ DiscoverVocab,
34
+ SourcePreview,
35
+ TickState,
36
+ UserTable,
37
+ } from "./automationApi";
38
+ import {
39
+ AutomationError,
40
+ COUNT_LABELS,
41
+ deleteAutomation,
42
+ discoverEstimate,
43
+ fieldKeyFor,
44
+ listTables,
45
+ patchAutomation,
46
+ previewSource,
47
+ runAutomation,
48
+ runRows,
49
+ toggleNode,
50
+ } from "./automationApi";
51
+
52
+ interface Props {
53
+ automation: Automation;
54
+ kinds: { key: AutomationKind; label: string }[];
55
+ /** The server's schedule vocabulary, forwarded to Step 1's Custom face. */
56
+ cronPresets: { cron: string; label: string }[];
57
+ paidReady: boolean;
58
+ /** The server-declared discovery vocabulary (absent until the list loads). */
59
+ discover?: DiscoverVocab;
60
+ /**
61
+ * Can a schedule fire here? `null` = the server did not say (C6 amendment #1 is not live
62
+ * yet) β€” a REQUIRED key so an unmounted prop fails `tsc` rather than silently reading as
63
+ * "off", which would make Step 1 state a measurement nobody made.
64
+ */
65
+ tick: TickState | null;
66
+ onSaved: (id?: string) => void | Promise<void>;
67
+ onDeleted: () => void | Promise<void>;
68
+ }
69
+
70
+ interface ColumnPlan {
71
+ column: string;
72
+ include: boolean;
73
+ key: string;
74
+ }
75
+
76
+ /** One condition of a corpus search. Mirrors the server's `clean_predicates`. */
77
+ interface Predicate {
78
+ name: string;
79
+ operator: string;
80
+ value?: string | number;
81
+ }
82
+
83
+ export default function AutomationDetail({
84
+ automation,
85
+ kinds,
86
+ cronPresets,
87
+ paidReady,
88
+ discover,
89
+ tick,
90
+ onSaved,
91
+ onDeleted,
92
+ }: Props) {
93
+ const cfg = (automation.config || {}) as Record<string, string | number | boolean>;
94
+ const kind = automation.kind;
95
+
96
+ const [name, setName] = useState(automation.name || "");
97
+ const [cron, setCron] = useState(automation.schedule?.cron || "0 6 * * *");
98
+ const [message, setMessage] = useState("");
99
+ const [problem, setProblem] = useState("");
100
+ const [saving, setSaving] = useState(false);
101
+ const [touched, setTouched] = useState(false);
102
+ const [busyNode, setBusyNode] = useState("");
103
+ const [triggerBusy, setTriggerBusy] = useState(false);
104
+ const [selected, setSelected] = useState("");
105
+
106
+ // --- scrape_db half
107
+ const [url, setUrl] = useState(String(cfg.url || ""));
108
+ const [extract, setExtract] = useState(String(cfg.extract || "table"));
109
+ const [tableIndex, setTableIndex] = useState(Number(cfg.tableIndex || 0));
110
+ const [targetLabel, setTargetLabel] = useState(String(cfg.targetLabel || ""));
111
+ const [preview, setPreview] = useState<SourcePreview | null>(null);
112
+ const [reading, setReading] = useState(false);
113
+ const [plan, setPlan] = useState<ColumnPlan[]>(() =>
114
+ Object.entries((automation.config as { fieldMap?: Record<string, string> })?.fieldMap || {})
115
+ .map(([column, key]) => ({ column, include: true, key }))
116
+ );
117
+ const [keyField, setKeyField] = useState(String(cfg.keyField || ""));
118
+
119
+ // --- field_instagram half
120
+ const [tables, setTables] = useState<UserTable[]>([]);
121
+ const [targetTable, setTargetTable] = useState(String(cfg.targetTable || ""));
122
+ const [fieldKey, setFieldKey] = useState(String(cfg.fieldKey || ""));
123
+ const [urlField, setUrlField] = useState(String(cfg.urlField || ""));
124
+ const [maxPosts, setMaxPosts] = useState(Number(cfg.maxPosts || 24));
125
+
126
+ // --- discover_instagram half (R7)
127
+ const [recordsLimit, setRecordsLimit] = useState(Number(cfg.recordsLimit || 25));
128
+ const [joinOp, setJoinOp] = useState(String(cfg.operator || "and"));
129
+ const [preds, setPreds] = useState<Predicate[]>(() => {
130
+ const stored = (automation.config as { predicates?: Predicate[] })?.predicates;
131
+ return stored && stored.length
132
+ ? stored.map((p) => ({ ...p }))
133
+ : [{ name: "followers", operator: ">=", value: 10000 }];
134
+ });
135
+ const [estimate, setEstimate] = useState<DiscoverEstimate | null>(null);
136
+
137
+ // --- run history drill
138
+ const [drill, setDrill] = useState<RunRows | null>(null);
139
+ const [drillFor, setDrillFor] = useState("");
140
+
141
+ useEffect(() => {
142
+ const ac = new AbortController();
143
+ listTables(ac.signal)
144
+ .then((r) => setTables(r.tables))
145
+ .catch(() => setTables([]));
146
+ return () => ac.abort();
147
+ }, []);
148
+
149
+ const table = tables.find((t) => t.key === targetTable) || null;
150
+ const node: GraphNode | null =
151
+ (automation.graph?.nodes || []).find((n) => n.id === selected) || null;
152
+
153
+ const edit = <T,>(set: (v: T) => void) => (v: T) => {
154
+ setTouched(true);
155
+ set(v);
156
+ };
157
+
158
+ const readPage = useCallback(async () => {
159
+ setReading(true);
160
+ setProblem("");
161
+ try {
162
+ const p = await previewSource(url, extract, tableIndex);
163
+ setPreview(p);
164
+ if (!p.ok) {
165
+ setProblem(p.note || `That page answered ${p.status}.`);
166
+ return;
167
+ }
168
+ // Seed the plan from what the page ACTUALLY offers, keeping any mapping the
169
+ // user already made for a column that is still there β€” re-reading a page
170
+ // must not throw away the work of mapping it.
171
+ setPlan((prev) => {
172
+ const had = new Map(prev.map((c) => [c.column, c]));
173
+ return p.columns.map((column) => {
174
+ const before = had.get(column);
175
+ return {
176
+ column,
177
+ include: before ? before.include : true,
178
+ key: before ? before.key : fieldKeyFor(column),
179
+ };
180
+ });
181
+ });
182
+ setKeyField((k) =>
183
+ k && p.columns.some((c) => fieldKeyFor(c) === k) ? k : fieldKeyFor(p.columns[0] || "")
184
+ );
185
+ if (!targetLabel) setTargetLabel(p.title || "Scraped table");
186
+ setTouched(true);
187
+ setMessage(
188
+ `Read ${p.rowCount} rows and ${p.columns.length} columns` +
189
+ (p.tableCount && p.tableCount > 1 ? ` (of ${p.tableCount} tables on the page)` : "")
190
+ );
191
+ } catch (e) {
192
+ setProblem(e instanceof AutomationError ? e.message : "That page could not be read.");
193
+ } finally {
194
+ setReading(false);
195
+ }
196
+ }, [url, extract, tableIndex, targetLabel]);
197
+
198
+ /**
199
+ * ⚠ The switch flags (`tier`, `noFallback`, `dryRun`) are DELIBERATELY absent.
200
+ * They are node switches, not panel fields, and the server keeps the stored
201
+ * value for any flag a config omits β€” so a Save from here can never quietly
202
+ * turn the paid rung off. (`clean_config`'s `flag()`, asserted in section N.)
203
+ */
204
+ const buildConfig = (): Record<string, unknown> => {
205
+ if (kind === "scrape_db") {
206
+ const fieldMap: Record<string, string> = {};
207
+ for (const c of plan) if (c.include && c.key) fieldMap[c.column] = c.key;
208
+ return {
209
+ url,
210
+ extract,
211
+ tableIndex,
212
+ fieldMap,
213
+ keyField,
214
+ targetTable: String(cfg.targetTable || ""),
215
+ targetLabel,
216
+ };
217
+ }
218
+ if (kind === "discover_instagram") {
219
+ return {
220
+ recordsLimit,
221
+ operator: joinOp,
222
+ predicates: preds.filter((p) => p.name && p.operator),
223
+ targetTable: String(cfg.targetTable || ""),
224
+ };
225
+ }
226
+ return { targetTable, fieldKey, urlField, maxPosts };
227
+ };
228
+
229
+ const persist = async (announce = true, sched?: { cron: string; enabled: boolean }) => {
230
+ const res = await patchAutomation(automation.id, {
231
+ name,
232
+ kind,
233
+ config: buildConfig(),
234
+ schedule: sched || { cron, enabled: !!automation.schedule?.enabled },
235
+ });
236
+ setTouched(false);
237
+ if (announce) setMessage("Saved.");
238
+ return res.automation.id;
239
+ };
240
+
241
+ /**
242
+ * Step 1's controls persist IMMEDIATELY (R9). A trigger you have to remember to Save is the
243
+ * same defect as a switch you have to remember to Save β€” the node switches next to it are
244
+ * immediate, and two save disciplines in one column is how a user ends up with an automation
245
+ * that says "every Monday" and runs every day.
246
+ *
247
+ * ⚠ The CUSTOM CRON STRING is the exception, and deliberately: it is free text, so persisting
248
+ * per keystroke would PATCH a half-typed schedule five times. It marks the editor touched and
249
+ * rides the header's Save β€” and because every immediate write goes through `persist()`, an
250
+ * unsaved cron edit is written with it rather than being discarded by the reload.
251
+ */
252
+ const saveTrigger = async (next: { cron: string; enabled: boolean }) => {
253
+ setTriggerBusy(true);
254
+ setProblem("");
255
+ setMessage("");
256
+ setCron(next.cron);
257
+ try {
258
+ await patchAutomation(automation.id, {
259
+ name,
260
+ kind,
261
+ config: buildConfig(),
262
+ schedule: { cron: next.cron, enabled: next.enabled },
263
+ });
264
+ setTouched(false);
265
+ await onSaved(automation.id);
266
+ } catch (e) {
267
+ setProblem(e instanceof AutomationError ? e.message : "That schedule was not saved.");
268
+ } finally {
269
+ setTriggerBusy(false);
270
+ }
271
+ };
272
+
273
+ const save = async () => {
274
+ setSaving(true);
275
+ setProblem("");
276
+ setMessage("");
277
+ try {
278
+ const id = await persist();
279
+ await onSaved(id);
280
+ } catch (e) {
281
+ setProblem(e instanceof AutomationError ? e.message : "That could not be saved.");
282
+ } finally {
283
+ setSaving(false);
284
+ }
285
+ };
286
+
287
+ /**
288
+ * A node switch is immediate β€” a switch that needs a separate Save is not a
289
+ * switch. Unsaved panel edits are persisted FIRST rather than being discarded
290
+ * by the reload that follows, which is the one way this could lose work.
291
+ */
292
+ const flip = async (nodeId: string) => {
293
+ setBusyNode(nodeId);
294
+ setProblem("");
295
+ setMessage("");
296
+ try {
297
+ if (touched) await persist(false);
298
+ await toggleNode(automation.id, nodeId);
299
+ await onSaved(automation.id);
300
+ } catch (e) {
301
+ setProblem(e instanceof AutomationError ? e.message : "That step was not changed.");
302
+ } finally {
303
+ setBusyNode("");
304
+ }
305
+ };
306
+
307
+ const start = async () => {
308
+ setProblem("");
309
+ try {
310
+ await runAutomation(automation.id);
311
+ setMessage("Started. The node dots follow it.");
312
+ await onSaved(automation.id);
313
+ } catch (e) {
314
+ setProblem(e instanceof AutomationError ? e.message : "It did not start.");
315
+ }
316
+ };
317
+
318
+ const remove = async () => {
319
+ setProblem("");
320
+ try {
321
+ await deleteAutomation(automation.id);
322
+ await onDeleted();
323
+ } catch (e) {
324
+ setProblem(e instanceof AutomationError ? e.message : "It was not deleted.");
325
+ }
326
+ };
327
+
328
+ const openDrill = async (entry: RunEntry) => {
329
+ if (drillFor === entry.ts) {
330
+ setDrill(null);
331
+ setDrillFor("");
332
+ return;
333
+ }
334
+ try {
335
+ const rows = await runRows(automation.id);
336
+ setDrill(rows);
337
+ setDrillFor(entry.ts);
338
+ } catch (e) {
339
+ setProblem(e instanceof AutomationError ? e.message : "Those rows could not be read.");
340
+ }
341
+ };
342
+
343
+ const state = automation.running ? "running" : automation.status?.state || "idle";
344
+
345
+ return (
346
+ <div className="auto-detail">
347
+ <header className="auto-head">
348
+ <div className="auto-head-title">
349
+ <input
350
+ className="auto-name"
351
+ value={name}
352
+ placeholder="Name this automation"
353
+ aria-label="Automation name"
354
+ onChange={(e) => edit(setName)(e.target.value)}
355
+ />
356
+ <span className={`auto-chip is-${state}`}>
357
+ {automation.running ? "Running" : state}
358
+ </span>
359
+ <span className="auto-kindtag">
360
+ {kinds.find((k) => k.key === kind)?.label || kind}
361
+ </span>
362
+ </div>
363
+ <div className="auto-head-actions">
364
+ <button
365
+ type="button"
366
+ className="auto-btn"
367
+ disabled={!!automation.running}
368
+ onClick={() => void start()}
369
+ >
370
+ {automation.running ? "Running…" : "Run now"}
371
+ </button>
372
+ <button
373
+ type="button"
374
+ className="auto-btn is-primary"
375
+ disabled={saving || !name.trim()}
376
+ onClick={() => void save()}
377
+ >
378
+ {saving ? "Saving…" : "Save"}
379
+ </button>
380
+ <button type="button" className="auto-btn is-danger" onClick={() => void remove()}>
381
+ Delete
382
+ </button>
383
+ </div>
384
+ </header>
385
+
386
+ {problem ? (
387
+ <div className="auto-banner is-error" role="alert">
388
+ {problem}
389
+ </div>
390
+ ) : null}
391
+ {message ? (
392
+ <div className="auto-banner is-ok" role="status">
393
+ {message}
394
+ </div>
395
+ ) : null}
396
+
397
+ <div className="auto-work">
398
+ <AutomationSteps
399
+ graph={automation.graph}
400
+ selected={selected}
401
+ onSelect={setSelected}
402
+ onToggle={(id) => void flip(id)}
403
+ busyNode={busyNode}
404
+ nextRunAt={automation.nextRunAt}
405
+ cron={cron}
406
+ enabled={!!automation.schedule?.enabled}
407
+ tick={tick}
408
+ onTrigger={(next) => void saveTrigger(next)}
409
+ onCronText={(next) => edit(setCron)(next)}
410
+ cronPresets={cronPresets}
411
+ triggerBusy={triggerBusy}
412
+ />
413
+
414
+ <aside className="auto-panel" aria-label={node ? `${node.title} settings` : "Run history"}>
415
+ {node ? (
416
+ <>
417
+ <div className="auto-panel-head">
418
+ <h2>{node.title}</h2>
419
+ <button
420
+ type="button"
421
+ className="auto-panel-close"
422
+ aria-label="Back to run history"
423
+ title="Back to run history"
424
+ onClick={() => setSelected("")}
425
+ >
426
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
427
+ <path
428
+ d="M4 4l8 8M12 4l-8 8"
429
+ stroke="currentColor"
430
+ strokeWidth="1.5"
431
+ strokeLinecap="round"
432
+ />
433
+ </svg>
434
+ </button>
435
+ </div>
436
+ {!node.enabled ? (
437
+ <p className="auto-note is-off">
438
+ This step is switched off. Its own card carries the switch that turns it back on.
439
+ </p>
440
+ ) : null}
441
+
442
+ {/*
443
+ β›” THE SCHEDULE FACE IS GONE FROM THIS PANEL (R9), and its absence is the
444
+ point. Step 1 now carries the trigger's on/off AND its shape, so a second
445
+ cron control here would be two controls for one fact β€” the thing this file's
446
+ header forbids, and the way a UI starts disagreeing with itself. The trigger
447
+ step is not selectable for the same reason: there is nothing left to show
448
+ here that the card does not already say.
449
+ */}
450
+
451
+ {node.panel === "source" && kind === "scrape_db" ? (
452
+ <>
453
+ <div className="auto-field">
454
+ <label htmlFor="auto-url">Page URL</label>
455
+ <input
456
+ id="auto-url"
457
+ className="auto-input"
458
+ value={url}
459
+ placeholder="https://en.wikipedia.org/wiki/List_of_S%26P_500_companies"
460
+ onChange={(e) => edit(setUrl)(e.target.value)}
461
+ />
462
+ </div>
463
+ <button
464
+ type="button"
465
+ className="auto-btn"
466
+ disabled={!url.trim() || reading}
467
+ onClick={() => void readPage()}
468
+ >
469
+ {reading ? "Reading…" : "Read the page"}
470
+ </button>
471
+ <div className="auto-field">
472
+ <label htmlFor="auto-extract">Read</label>
473
+ <select
474
+ id="auto-extract"
475
+ className="auto-input"
476
+ value={extract}
477
+ onChange={(e) => edit(setExtract)(e.target.value)}
478
+ >
479
+ <option value="table">An HTML table</option>
480
+ <option value="jsonld">Structured data (JSON-LD)</option>
481
+ </select>
482
+ </div>
483
+ {extract === "table" ? (
484
+ <div className="auto-field">
485
+ <label htmlFor="auto-tidx">Which table</label>
486
+ <input
487
+ id="auto-tidx"
488
+ className="auto-input"
489
+ type="number"
490
+ min={0}
491
+ value={tableIndex}
492
+ onChange={(e) => edit(setTableIndex)(Number(e.target.value) || 0)}
493
+ />
494
+ </div>
495
+ ) : null}
496
+ <p className="auto-hint">
497
+ Public web pages only. Private, loopback and link-local addresses are refused
498
+ β€” including a public URL that redirects to one.
499
+ </p>
500
+ </>
501
+ ) : null}
502
+
503
+ {node.panel === "columns" ? (
504
+ plan.length ? (
505
+ <>
506
+ <p className="auto-hint">
507
+ Pick the key β€” the column that identifies a row. On every re-run, a row
508
+ whose key already exists is updated; a new key is inserted; a key that has
509
+ stopped appearing is counted and kept.
510
+ </p>
511
+ <div className="auto-panel-scroll">
512
+ <table className="auto-table">
513
+ <thead>
514
+ <tr>
515
+ <th>Use</th>
516
+ <th>Source column</th>
517
+ <th>Field key</th>
518
+ <th>Key</th>
519
+ </tr>
520
+ </thead>
521
+ <tbody>
522
+ {plan.map((c, i) => (
523
+ <tr key={c.column}>
524
+ <td>
525
+ <input
526
+ type="checkbox"
527
+ checked={c.include}
528
+ aria-label={`Include ${c.column}`}
529
+ onChange={(e) =>
530
+ edit(setPlan)(
531
+ plan.map((x, j) =>
532
+ j === i ? { ...x, include: e.target.checked } : x
533
+ )
534
+ )
535
+ }
536
+ />
537
+ </td>
538
+ <td className="auto-cell-name">{c.column}</td>
539
+ <td>
540
+ <input
541
+ className="auto-input is-small"
542
+ value={c.key}
543
+ aria-label={`Field key for ${c.column}`}
544
+ onChange={(e) =>
545
+ edit(setPlan)(
546
+ plan.map((x, j) =>
547
+ j === i
548
+ ? { ...x, key: fieldKeyFor(e.target.value) }
549
+ : x
550
+ )
551
+ )
552
+ }
553
+ />
554
+ </td>
555
+ <td>
556
+ <input
557
+ type="radio"
558
+ name="auto-keyfield"
559
+ checked={keyField === c.key && c.include}
560
+ disabled={!c.include}
561
+ aria-label={`Use ${c.column} as the key`}
562
+ onChange={() => edit(setKeyField)(c.key)}
563
+ />
564
+ </td>
565
+ </tr>
566
+ ))}
567
+ </tbody>
568
+ </table>
569
+ </div>
570
+ {preview?.sample?.length ? (
571
+ <p className="auto-hint">
572
+ First row read: {Object.values(preview.sample[0]).slice(0, 4).join(" Β· ")}
573
+ </p>
574
+ ) : null}
575
+ </>
576
+ ) : (
577
+ <p className="auto-note">
578
+ Open the Fetch step and read the page to see what columns it offers.
579
+ </p>
580
+ )
581
+ ) : null}
582
+
583
+ {node.panel === "source" && kind === "field_instagram" ? (
584
+ <>
585
+ <div className="auto-field">
586
+ <label htmlFor="auto-table">Database</label>
587
+ <select
588
+ id="auto-table"
589
+ className="auto-input"
590
+ value={targetTable}
591
+ onChange={(e) => {
592
+ edit(setTargetTable)(e.target.value);
593
+ setFieldKey("");
594
+ setUrlField("");
595
+ }}
596
+ >
597
+ <option value="">Choose a database…</option>
598
+ {targetTable && !tables.some((t) => t.key === targetTable) ? (
599
+ <option value={targetTable}>{targetTable} (not visible to you)</option>
600
+ ) : null}
601
+ {tables.map((t) => (
602
+ <option key={t.key} value={t.key}>
603
+ {t.label} ({t.rowCount} {t.rowCount === 1 ? "row" : "rows"})
604
+ </option>
605
+ ))}
606
+ </select>
607
+ </div>
608
+ <div className="auto-field">
609
+ <label htmlFor="auto-urlfield">Profile URL column</label>
610
+ <select
611
+ id="auto-urlfield"
612
+ className="auto-input"
613
+ value={urlField}
614
+ onChange={(e) => edit(setUrlField)(e.target.value)}
615
+ >
616
+ <option value="">The column the field is bound to</option>
617
+ {(table?.fields || []).map((f) => (
618
+ <option key={f.key} value={f.key}>
619
+ {f.label}
620
+ </option>
621
+ ))}
622
+ </select>
623
+ </div>
624
+ <div className="auto-field">
625
+ <label htmlFor="auto-fieldkey">Automation column</label>
626
+ <select
627
+ id="auto-fieldkey"
628
+ className="auto-input"
629
+ value={fieldKey}
630
+ onChange={(e) => edit(setFieldKey)(e.target.value)}
631
+ >
632
+ <option value="">Choose a column…</option>
633
+ {/*
634
+ ⚠ THE STORED VALUE IS ALWAYS AN OPTION, even when the list
635
+ below does not contain it. A <select> whose `value` matches
636
+ no <option> renders the FIRST one β€” so a column the server
637
+ knows about but this list has not caught up with would look
638
+ like a DIFFERENT column, and the next Save would write that
639
+ different column without anybody choosing it. Showing it as
640
+ "(not in this database)" is the honest version.
641
+ */}
642
+ {fieldKey && !(table?.fields || []).some((f) => f.key === fieldKey) ? (
643
+ <option value={fieldKey}>{fieldKey} (not in this database)</option>
644
+ ) : null}
645
+ {(table?.fields || [])
646
+ .filter((f) => f.type === "automation")
647
+ .map((f) => (
648
+ <option key={f.key} value={f.key}>
649
+ {f.label}
650
+ </option>
651
+ ))}
652
+ </select>
653
+ </div>
654
+ {table && !(table.fields || []).some((f) => f.type === "automation") ? (
655
+ <p className="auto-note">
656
+ That database has no automation column yet. Add one from the grid&rsquo;s
657
+ column menu, then choose it here.
658
+ </p>
659
+ ) : null}
660
+ </>
661
+ ) : null}
662
+
663
+ {node.panel === "capture" ? (
664
+ <>
665
+ <div className="auto-field">
666
+ <label htmlFor="auto-maxposts">Posts per pull</label>
667
+ <input
668
+ id="auto-maxposts"
669
+ className="auto-input"
670
+ type="number"
671
+ min={1}
672
+ max={200}
673
+ value={maxPosts}
674
+ onChange={(e) => edit(setMaxPosts)(Number(e.target.value) || 24)}
675
+ />
676
+ </div>
677
+ <h3>Bright Data β€” the paid rung</h3>
678
+ <p className="auto-hint">
679
+ Exact follower counts and the profile&rsquo;s top posts, and it works from a
680
+ datacenter. Its node&rsquo;s switch turns it on.
681
+ {paidReady
682
+ ? " A key is configured on this deployment."
683
+ : " No key is configured on this deployment yet, so it will report itself blocked and the anonymous rung will answer instead."}
684
+ </p>
685
+ <h3>Post engagement β€” the per-post rung</h3>
686
+ <p className="auto-hint">
687
+ Likes and comments for each post. It is a separate step because it is a
688
+ separate bill: the profile read costs one record, and engagement costs{" "}
689
+ <strong>one record per post</strong>. With it off, the posts database still
690
+ grows but the engagement series does not β€” and no empty rows are appended to
691
+ stand in for the numbers nobody bought.
692
+ </p>
693
+ <h3>Anonymous β€” the free rung</h3>
694
+ <p className="auto-hint">
695
+ No login and no credentials. Instagram blocks datacenter addresses and has
696
+ closed most of its anonymous surface, so this rung is honest rather than
697
+ reliable: counts come from the page&rsquo;s own abbreviations (204K, not
698
+ 204,312) and are marked approximate. Turning it off means{" "}
699
+ <strong>exact numbers or nothing</strong> β€” a run reports blocked rather than
700
+ quietly writing a rounded number.
701
+ </p>
702
+ <p className="auto-hint">
703
+ A pull reports what it actually got: <strong>ok</strong> (profile and posts),{" "}
704
+ <strong>partial</strong> (profile only), or <strong>blocked</strong>. It never
705
+ reports success on nothing.
706
+ </p>
707
+ </>
708
+ ) : null}
709
+
710
+ {node.panel === "find" ? (
711
+ <>
712
+ <div className="auto-field">
713
+ <label htmlFor="auto-records">How many profiles to fetch</label>
714
+ <input
715
+ id="auto-records"
716
+ className="auto-input"
717
+ type="number"
718
+ min={1}
719
+ max={discover?.maxRecords || 1000}
720
+ value={recordsLimit}
721
+ onChange={(e) => {
722
+ edit(setRecordsLimit)(Number(e.target.value) || 1);
723
+ setEstimate(null);
724
+ }}
725
+ />
726
+ </div>
727
+ <p className="auto-hint">
728
+ A search must be bounded. An unbounded one matches a share of a corpus of
729
+ hundreds of millions of profiles, and the vendor refuses it outright rather
730
+ than delivering it.
731
+ </p>
732
+
733
+ <h3>Conditions</h3>
734
+ {preds.map((pr, i) => (
735
+ <div className="auto-field-row" key={i}>
736
+ <div className="auto-field">
737
+ <label htmlFor={"auto-pred-f-" + i}>Field</label>
738
+ <select
739
+ id={"auto-pred-f-" + i}
740
+ className="auto-input"
741
+ value={pr.name}
742
+ onChange={(e) =>
743
+ edit(setPreds)(
744
+ preds.map((q, j) => (j === i ? { ...q, name: e.target.value } : q))
745
+ )
746
+ }
747
+ >
748
+ {/*
749
+ The stored value is ALWAYS an option β€” see the note on the
750
+ automation-column picker. A select whose value matches no option
751
+ renders the first one, which silently changes what a Save writes.
752
+ */}
753
+ {pr.name && !(discover?.fields || []).includes(pr.name) ? (
754
+ <option value={pr.name}>{pr.name}</option>
755
+ ) : null}
756
+ {(discover?.fields || []).map((f) => (
757
+ <option key={f} value={f}>
758
+ {f}
759
+ {(discover?.lead || []).includes(f) ? " (has values)" : ""}
760
+ </option>
761
+ ))}
762
+ </select>
763
+ </div>
764
+ <div className="auto-field">
765
+ <label htmlFor={"auto-pred-o-" + i}>Comparison</label>
766
+ <select
767
+ id={"auto-pred-o-" + i}
768
+ className="auto-input"
769
+ value={pr.operator}
770
+ onChange={(e) =>
771
+ edit(setPreds)(
772
+ preds.map((q, j) =>
773
+ j === i ? { ...q, operator: e.target.value } : q
774
+ )
775
+ )
776
+ }
777
+ >
778
+ {pr.operator && !(discover?.operators || []).includes(pr.operator) ? (
779
+ <option value={pr.operator}>{pr.operator}</option>
780
+ ) : null}
781
+ {(discover?.operators || []).map((o) => (
782
+ <option key={o} value={o}>
783
+ {o}
784
+ </option>
785
+ ))}
786
+ </select>
787
+ </div>
788
+ {(discover?.nullaryOperators || []).includes(pr.operator) ? null : (
789
+ <div className="auto-field">
790
+ <label htmlFor={"auto-pred-v-" + i}>Value</label>
791
+ <input
792
+ id={"auto-pred-v-" + i}
793
+ className="auto-input"
794
+ value={pr.value === undefined ? "" : String(pr.value)}
795
+ onChange={(e) =>
796
+ edit(setPreds)(
797
+ preds.map((q, j) => (j === i ? { ...q, value: e.target.value } : q))
798
+ )
799
+ }
800
+ />
801
+ </div>
802
+ )}
803
+ <div className="auto-field">
804
+ <label htmlFor={"auto-pred-x-" + i}>&nbsp;</label>
805
+ <button
806
+ id={"auto-pred-x-" + i}
807
+ type="button"
808
+ className="auto-btn"
809
+ disabled={preds.length < 2}
810
+ onClick={() => edit(setPreds)(preds.filter((_q, j) => j !== i))}
811
+ >
812
+ Remove
813
+ </button>
814
+ </div>
815
+ </div>
816
+ ))}
817
+ <div className="auto-head-actions">
818
+ <button
819
+ type="button"
820
+ className="auto-btn"
821
+ onClick={() =>
822
+ edit(setPreds)([
823
+ ...preds,
824
+ // ⚠ A NEW CONDITION MUST BE SAVEABLE THE MOMENT IT APPEARS (item 8,
825
+ // same defect as the create form's hardcoded default). This appended
826
+ // `{biography includes ""}` β€” a value-less comparison that
827
+ // `clean_predicates` refuses outright β€” so adding a condition and
828
+ // pressing Save returned "give a value to compare 'biography'
829
+ // against" for a condition the user had not finished writing. A
830
+ // NULLARY operator needs no value, so the row is valid on arrival
831
+ // and narrows the search rather than blocking it.
832
+ { name: "biography", operator: "is_not_null" },
833
+ ])
834
+ }
835
+ >
836
+ Add a condition
837
+ </button>
838
+ <div className="auto-field">
839
+ <label htmlFor="auto-joinop">Match</label>
840
+ <select
841
+ id="auto-joinop"
842
+ className="auto-input"
843
+ value={joinOp}
844
+ onChange={(e) => edit(setJoinOp)(e.target.value)}
845
+ >
846
+ <option value="and">All of them</option>
847
+ <option value="or">Any of them</option>
848
+ </select>
849
+ </div>
850
+ </div>
851
+ <p className="auto-hint">
852
+ Fields marked <em>has values</em> are the ones we have actually seen carrying
853
+ data. The others can be searched, but were empty on every profile we have
854
+ looked at β€” and a condition on an empty field returns nothing while looking
855
+ exactly like &ldquo;no such accounts exist&rdquo;.
856
+ </p>
857
+ <p className="auto-hint">
858
+ Narrow conditions matter more than a small limit. The search reads the whole
859
+ corpus either way, so a broad condition is slow and expensive however few rows
860
+ you ask to keep. A search normally takes about twenty minutes; a run that
861
+ finds one still going says so and the next run collects it.
862
+ </p>
863
+
864
+ <h3>What it costs</h3>
865
+ <div className="auto-head-actions">
866
+ <button
867
+ type="button"
868
+ className="auto-btn"
869
+ onClick={() => {
870
+ void discoverEstimate(recordsLimit)
871
+ .then(setEstimate)
872
+ .catch(() => setEstimate(null));
873
+ }}
874
+ >
875
+ Estimate this search
876
+ </button>
877
+ </div>
878
+ {estimate ? (
879
+ <p className="auto-hint">
880
+ About <strong>${estimate.usd}</strong> for {estimate.records} profiles, at $
881
+ {estimate.unitUsd} each.{" "}
882
+ {/*
883
+ THE CAVEAT IS NOT OPTIONAL. The vendor never quotes a price before a run
884
+ and this deployment cannot read its own balance, so presenting this as a
885
+ billed figure would be inventing a measurement.
886
+ */}
887
+ <strong>This is an estimate</strong> β€” {estimate.note}.
888
+ </p>
889
+ ) : null}
890
+ </>
891
+ ) : null}
892
+
893
+ {node.panel === "write" ? (
894
+ <>
895
+ {kind === "scrape_db" ? (
896
+ <div className="auto-field">
897
+ <label htmlFor="auto-tlabel">Database name</label>
898
+ <input
899
+ id="auto-tlabel"
900
+ className="auto-input"
901
+ value={targetLabel}
902
+ placeholder="S&P 500 companies"
903
+ onChange={(e) => edit(setTargetLabel)(e.target.value)}
904
+ />
905
+ </div>
906
+ ) : kind === "discover_instagram" ? (
907
+ <p className="auto-hint">
908
+ Matches are collected into{" "}
909
+ <code>{discover?.table || "ut_ig_candidates"}</code>, upserted by handle β€” so
910
+ re-finding an account costs nothing and its <em>Times found</em> count grows.{" "}
911
+ <strong>Nothing found is ever tracked automatically.</strong> Tick the ones
912
+ you want; a later search can never un-tick them.
913
+ </p>
914
+ ) : (
915
+ <p className="auto-hint">
916
+ Each pull appends a timestamped row to <code>ut_ig_snapshots</code> and, when
917
+ the post-engagement step is on, one per post to{" "}
918
+ <code>ut_ig_post_snapshots</code> β€” so the history is a time series you can
919
+ filter by date rather than a single current value.{" "}
920
+ <code>ut_ig_posts</code> holds one row per post, ever.
921
+ </p>
922
+ )}
923
+ <p className="auto-hint">
924
+ Turning this step off makes the automation a <strong>dry run</strong>: it
925
+ reads everything and reports exactly what it would have written, without
926
+ creating or changing a single row.
927
+ </p>
928
+ {kind === "field_instagram" ? (
929
+ <p className="auto-hint">
930
+ {/*
931
+ ⚠ "Writes nothing" and "costs nothing" are DIFFERENT CLAIMS, and only the
932
+ first one is true. A dry run still READS β€” so with the paid steps on it
933
+ bills exactly what a real run bills. Saying so here is the only place a
934
+ user finds out before the invoice.
935
+ */}
936
+ A dry run still <strong>reads</strong>. With the Bright Data step on it
937
+ costs what a real run costs, and with post engagement on that is one
938
+ charged record per post. Turn those steps off too if you want a free
939
+ rehearsal.
940
+ </p>
941
+ ) : null}
942
+ <p className="auto-hint">
943
+ A row that stops appearing at the source is counted and kept, never deleted.
944
+ </p>
945
+ </>
946
+ ) : null}
947
+ </>
948
+ ) : (
949
+ <>
950
+ <div className="auto-panel-head">
951
+ <h2>Run history</h2>
952
+ </div>
953
+ {!automation.runs?.length ? (
954
+ <p className="auto-note">
955
+ It has not run yet. Press Run now, or switch on the Trigger step.
956
+ </p>
957
+ ) : (
958
+ <ol className="auto-runs">
959
+ {automation.runs.map((r) => (
960
+ <li key={r.ts} className={"auto-run is-" + (r.ok ? "ok" : "error")}>
961
+ <button
962
+ type="button"
963
+ className="auto-run-head"
964
+ onClick={() => void openDrill(r)}
965
+ aria-expanded={drillFor === r.ts}
966
+ >
967
+ <span className="auto-run-ts">{r.ts.replace("T", " ")}</span>
968
+ <span className="auto-run-summary">{r.summary}</span>
969
+ </button>
970
+ <div className="auto-counts">
971
+ {COUNT_LABELS.filter(([k]) => typeof r.counts?.[k] === "number").map(
972
+ ([k, label]) => (
973
+ <span
974
+ key={k}
975
+ className={
976
+ "auto-count" + (k === "capped" && r.counts[k] ? " is-warn" : "")
977
+ }
978
+ >
979
+ <b>{r.counts[k]}</b> {label}
980
+ </span>
981
+ )
982
+ )}
983
+ </div>
984
+ {drillFor === r.ts && drill ? (
985
+ <div className="auto-drill">
986
+ <p className="auto-hint">
987
+ The rows this run touched in {drill.label}
988
+ {drill.truncated ? " (first 200)" : ""}.
989
+ </p>
990
+ <div className="auto-drill-scroll">
991
+ <table className="auto-table">
992
+ <thead>
993
+ <tr>
994
+ {drill.fields.map((f) => (
995
+ <th key={f.key}>{f.label}</th>
996
+ ))}
997
+ </tr>
998
+ </thead>
999
+ <tbody>
1000
+ {drill.rows.slice(0, 50).map((row) => (
1001
+ <tr key={String(row.id)}>
1002
+ {drill.fields.map((f) => (
1003
+ <td key={f.key}>{String(row[f.key] ?? "")}</td>
1004
+ ))}
1005
+ </tr>
1006
+ ))}
1007
+ </tbody>
1008
+ </table>
1009
+ </div>
1010
+ </div>
1011
+ ) : null}
1012
+ </li>
1013
+ ))}
1014
+ </ol>
1015
+ )}
1016
+ <p className="auto-hint">
1017
+ Click any step to see and change what it does.
1018
+ </p>
1019
+ </>
1020
+ )}
1021
+ </aside>
1022
+ </div>
1023
+ </div>
1024
+ );
1025
+ }
web/src/automation/AutomationSteps.tsx ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // automation/AutomationSteps.tsx β€” one automation as NUMBERED STEPS (owner ruling R9).
3
+ //
4
+ // WHAT THIS REPLACES, AND WHY. It replaces the pan/zoom canvas as the work
5
+ // surface. The owner asked for "trigger-first Steps": a job you read top to
6
+ // bottom, starting with what makes it happen. A canvas answers "what shape is
7
+ // this flow"; a numbered list answers "what does it do, in what order, and what
8
+ // is step 3" β€” and the engine EXECUTES a list, not a graph. `capture_paid` and
9
+ // `capture_anon` render as a fork and are walked linearly (DEBT D-7), so a list
10
+ // that shows them as ALTERNATIVES AT ONE NUMBER is closer to what happens than
11
+ // two boxes with an arrow between them ever was.
12
+ //
13
+ // ⚠ EVERY STEP COMES FROM THE SERVER (contract C6). The nodes, their order,
14
+ // their titles, their switches and their dots are `engine.graph()`'s β€” this file
15
+ // numbers them (`steps.ts`) and paints them. It may not add a step, hide a step,
16
+ // or rename one: a client-side second idea of the steps is drift that is
17
+ // invisible until an automation stops doing what the picture says.
18
+ //
19
+ // ONE CONTROL PER FACT, and R9 moved one. The trigger's on/off used to be the
20
+ // canvas node's switch while the cron string lived in the panel. Step 1 now owns
21
+ // BOTH β€” the picker IS the on/off β€” and the panel's schedule face is gone, so
22
+ // there is exactly one place that decides when this runs.
23
+ // ---------------------------------------------------------------------------
24
+ import { useState } from "react";
25
+
26
+ import type { AutomationGraph, GraphNode, TickState } from "./automationApi";
27
+ import { WEEKDAYS, numberSteps, readCron, writeCron } from "./steps";
28
+
29
+ interface Props {
30
+ graph: AutomationGraph;
31
+ selected: string;
32
+ onSelect: (nodeId: string) => void;
33
+ onToggle: (nodeId: string) => void;
34
+ busyNode: string;
35
+ /** The server's next fire time β€” shown on step 1 when there is one. */
36
+ nextRunAt?: string;
37
+ cron: string;
38
+ enabled: boolean;
39
+ /**
40
+ * The tick bit, or `null` when the server does not report it. REQUIRED as a key
41
+ * (an absent prop would compile) and nullable as a value, because "we were not
42
+ * told" is a state this card prints rather than guesses at.
43
+ */
44
+ tick: TickState | null;
45
+ /** Persisting a trigger change is IMMEDIATE β€” a trigger that needs a Save is not a switch. */
46
+ onTrigger: (next: { cron: string; enabled: boolean }) => void;
47
+ /** Free-text cron edits: local only, committed on blur. See the input's note. */
48
+ onCronText: (cron: string) => void;
49
+ /** The server's schedule vocabulary β€” never a client copy (`automationApi.ts:11-15`). */
50
+ cronPresets: { cron: string; label: string }[];
51
+ triggerBusy: boolean;
52
+ }
53
+
54
+ /** Step 1's icon vocabulary, drawn (owner constant: no emojis). */
55
+ function KindMark({ kind }: { kind: GraphNode["kind"] }) {
56
+ const common = {
57
+ width: 15,
58
+ height: 15,
59
+ viewBox: "0 0 16 16",
60
+ fill: "none",
61
+ stroke: "currentColor",
62
+ strokeWidth: 1.4,
63
+ strokeLinecap: "round" as const,
64
+ strokeLinejoin: "round" as const,
65
+ "aria-hidden": true,
66
+ };
67
+ if (kind === "trigger")
68
+ return (
69
+ <svg {...common}>
70
+ <circle cx="8" cy="8" r="5.6" />
71
+ <path d="M8 5.2V8l2 1.4" />
72
+ </svg>
73
+ );
74
+ if (kind === "source")
75
+ return (
76
+ <svg {...common}>
77
+ <circle cx="8" cy="8" r="5.6" />
78
+ <path d="M2.6 8h10.8M8 2.4c1.5 1.7 2.2 3.6 2.2 5.6S9.5 12.3 8 13.6C6.5 12.3 5.8 10 5.8 8s.7-3.9 2.2-5.6z" />
79
+ </svg>
80
+ );
81
+ if (kind === "branch")
82
+ return (
83
+ <svg {...common}>
84
+ <path d="M2.6 8h3.2l2.6-3.6h5M8.4 11.6H5.8m2.6 0h5" />
85
+ <path d="M11.6 2.6 13.4 4.4 11.6 6.2M11.6 9.8l1.8 1.8-1.8 1.8" />
86
+ </svg>
87
+ );
88
+ if (kind === "write")
89
+ return (
90
+ <svg {...common}>
91
+ <ellipse cx="8" cy="4.2" rx="4.8" ry="1.9" />
92
+ <path d="M3.2 4.2v7.6c0 1 2.1 1.9 4.8 1.9s4.8-.9 4.8-1.9V4.2M3.2 8c0 1 2.1 1.9 4.8 1.9s4.8-.9 4.8-1.9" />
93
+ </svg>
94
+ );
95
+ return (
96
+ <svg {...common}>
97
+ <path d="M8 2.6v7.2M5.2 7l2.8 2.8L10.8 7M3 12.4h10" />
98
+ </svg>
99
+ );
100
+ }
101
+
102
+ /**
103
+ * What the deployment will actually do with a schedule.
104
+ *
105
+ * β›” THREE ANSWERS, AND ONE OF THEM IS "WE WERE NOT TOLD". A card that said
106
+ * "schedules won't fire" because a field was missing would be inventing a
107
+ * measurement, and it would be WRONG on this product's own production: the
108
+ * external EventBridge tick fires schedules on a deployment whose in-process
109
+ * scheduler is off ([[aws-automation-cron]]). So `external` says the door is open,
110
+ * not that the caller is alive β€” the server can only prove the first.
111
+ */
112
+ function tickNote(tick: TickState | null): { text: string; tone: string } {
113
+ // ⚠ AN EXPLICIT BOOLEAN OR NOTHING. `!tick` alone was not enough: a payload carrying
114
+ // `"tick": {}` β€” a half-shipped field, a serialiser that dropped a false, a version skew β€”
115
+ // has no `enabled` at all, and reading `undefined` as "off" printed "schedules won't fire"
116
+ // as though it had been measured. Caught by the probe's absent-state check, which is the
117
+ // whole reason the third state exists.
118
+ if (!tick || typeof tick.enabled !== "boolean") {
119
+ return {
120
+ text: "Whether this deployment runs schedules is not reported here yet β€” press Run now if you need it now.",
121
+ tone: "is-unknown",
122
+ };
123
+ }
124
+ if (!tick.enabled) {
125
+ return {
126
+ text: "Schedules won't fire on this deployment β€” ask your admin to switch the scheduler on. Run now still works.",
127
+ tone: "is-off",
128
+ };
129
+ }
130
+ if (tick.source === "external") {
131
+ return {
132
+ text: "Schedules fire when the external scheduler calls in. This deployment does not run them itself.",
133
+ tone: "is-on",
134
+ };
135
+ }
136
+ return { text: "This deployment runs schedules itself.", tone: "is-on" };
137
+ }
138
+
139
+ export default function AutomationSteps({
140
+ graph,
141
+ selected,
142
+ onSelect,
143
+ onToggle,
144
+ busyNode,
145
+ nextRunAt,
146
+ cron,
147
+ enabled,
148
+ tick,
149
+ onTrigger,
150
+ onCronText,
151
+ cronPresets,
152
+ triggerBusy,
153
+ }: Props) {
154
+ const steps = numberSteps(graph?.nodes || []);
155
+ const shape = readCron(cron);
156
+ const note = tickNote(tick);
157
+ const trigger = steps.length && steps[0].node.kind === "trigger" ? steps[0] : null;
158
+ const rest = trigger ? steps.slice(1) : steps;
159
+
160
+ /**
161
+ * ⚠ "SHOW ME THE CRON" IS A VIEW CHOICE, NOT A SCHEDULE CHANGE β€” and forgetting that made
162
+ * the Custom option DEAD. Everything else on this card is derived from the stored cron, so
163
+ * picking "Custom (cron)" wrote… the same cron, which `readCron` then read back as "every
164
+ * Wednesday" and the select snapped straight back. The custom face was reachable only by
165
+ * already having an inexpressible schedule.
166
+ *
167
+ * So the choice is remembered here, and ONLY here: no PATCH fires when you ask to see the
168
+ * string (nothing about the schedule changed), and an inexpressible stored cron still forces
169
+ * the face open on its own. Found by the probe check that types a bad cron β€” which could not
170
+ * reach the input at all.
171
+ */
172
+ const [showCron, setShowCron] = useState(false);
173
+ const every = showCron ? "custom" : shape.every;
174
+
175
+ const pickEvery = (next: string) => {
176
+ setShowCron(next === "custom");
177
+ if (next !== "custom") onTrigger({ cron: writeCron(next, shape.time || "06:00", cron), enabled });
178
+ };
179
+ const setTime = (time: string) => onTrigger({ cron: writeCron(shape.every, time, cron), enabled });
180
+
181
+ return (
182
+ <div className="auto-steps-wrap">
183
+ <ol className="auto-steps">
184
+ {trigger ? (
185
+ <li className={"auto-step is-trigger" + (enabled ? "" : " is-off")}>
186
+ <div className="auto-step-rail">
187
+ <span className="auto-step-n">{trigger.n}</span>
188
+ </div>
189
+ <div className="auto-step-card">
190
+ <div className="auto-step-head">
191
+ <span className="auto-step-mark">
192
+ <KindMark kind={trigger.node.kind} />
193
+ </span>
194
+ <span className="auto-step-title">{trigger.node.title}</span>
195
+ <span className="auto-step-tag">Trigger</span>
196
+ </div>
197
+
198
+ <div className="auto-field-row">
199
+ <div className="auto-field">
200
+ <label htmlFor="auto-trigger-kind">When it runs</label>
201
+ <select
202
+ id="auto-trigger-kind"
203
+ className="auto-input"
204
+ value={enabled ? "schedule" : "manual"}
205
+ disabled={triggerBusy}
206
+ onChange={(e) => onTrigger({ cron, enabled: e.target.value === "schedule" })}
207
+ >
208
+ {/* Short labels: at the width this select gets, "Manual only β€” I press Run
209
+ now" truncated to "Manual only β€” I press Run no…". What it MEANS is on
210
+ the line below the card, in full, where it has room. */}
211
+ <option value="manual">Manual only</option>
212
+ <option value="schedule">On a schedule</option>
213
+ {/*
214
+ R9's designed, DISABLED slot. It is here rather than absent because the
215
+ question "can it run when a record changes?" has an answer, and the
216
+ honest one is "not yet" β€” an option nobody can pick says that, while a
217
+ missing option says nothing and gets asked again. DEBT: the engine has no
218
+ event triggers at all (`automation_engine.graph()` emits one trigger node,
219
+ always a schedule); the exit condition is in the wave mailbox.
220
+ */}
221
+ <option value="event" disabled>
222
+ When a field changes β€” coming soon
223
+ </option>
224
+ </select>
225
+ </div>
226
+ <div className="auto-field">
227
+ <label htmlFor="auto-trigger-every">Repeat</label>
228
+ <select
229
+ id="auto-trigger-every"
230
+ className="auto-input"
231
+ value={every}
232
+ disabled={triggerBusy || !enabled}
233
+ onChange={(e) => pickEvery(e.target.value)}
234
+ >
235
+ <option value="day">Every day</option>
236
+ {WEEKDAYS.map((d) => (
237
+ <option key={d.value} value={d.value}>
238
+ {d.label}
239
+ </option>
240
+ ))}
241
+ {/*
242
+ THE ESCAPE HATCH, AND IT IS LOAD-BEARING. Daily and weekly do not cover
243
+ the schedules the engine accepts (hourly, every 15 minutes, monthly, a
244
+ weekday range), and a picker that cannot express a stored cron would
245
+ render its FIRST option instead β€” so the next Save would write "every
246
+ day at 06:00" over a schedule nobody changed. `readCron` returns
247
+ `custom` for anything it cannot express, and this option is where that
248
+ lands, with the string itself editable beside it.
249
+ */}
250
+ <option value="custom">Custom (cron)</option>
251
+ </select>
252
+ </div>
253
+ {every === "custom" ? (
254
+ <>
255
+ <div className="auto-field">
256
+ <label htmlFor="auto-trigger-preset">Or a preset</label>
257
+ {/*
258
+ ⚠ THE PRESET LIST IS THE SERVER'S, and it is here because daily/weekly
259
+ (R9) are not everything the engine runs β€” hourly, quarter-hourly and
260
+ monthly are `CRON_PRESETS` and the old panel offered them. Dropping the
261
+ list would have made those schedules reachable only by typing raw cron.
262
+ It stays SERVER-SUPPLIED for the reason `automationApi.ts:11-15` gives:
263
+ the parser that accepts a cron lives in Python, and a client-invented
264
+ preset is a schedule the server can refuse while the UI looks fine.
265
+ */}
266
+ <select
267
+ id="auto-trigger-preset"
268
+ className="auto-input"
269
+ value={cronPresets.some((p) => p.cron === cron) ? cron : ""}
270
+ disabled={triggerBusy || !enabled}
271
+ onChange={(e) => e.target.value && onTrigger({ cron: e.target.value, enabled })}
272
+ >
273
+ <option value="">Typed below</option>
274
+ {cronPresets.map((p) => (
275
+ <option key={p.cron} value={p.cron}>
276
+ {p.label}
277
+ </option>
278
+ ))}
279
+ </select>
280
+ </div>
281
+ <div className="auto-field">
282
+ <label htmlFor="auto-trigger-custom">Cron (minute hour day month weekday)</label>
283
+ {/*
284
+ ⚠ TYPING DOES NOT PATCH. Every other control here persists on change
285
+ because each is one discrete decision; a cron STRING is free text, so
286
+ per-keystroke saving would PATCH a half-typed schedule five times and
287
+ the server would refuse most of them out loud. It edits locally and
288
+ commits on BLUR (and rides the header's Save either way, because every
289
+ immediate write persists the pending edit first).
290
+ */}
291
+ <input
292
+ id="auto-trigger-custom"
293
+ className="auto-input is-mono"
294
+ value={cron}
295
+ disabled={triggerBusy || !enabled}
296
+ onChange={(e) => onCronText(e.target.value)}
297
+ onBlur={() => onTrigger({ cron, enabled })}
298
+ />
299
+ </div>
300
+ </>
301
+ ) : (
302
+ <div className="auto-field">
303
+ <label htmlFor="auto-trigger-time">At</label>
304
+ <input
305
+ id="auto-trigger-time"
306
+ className="auto-input"
307
+ type="time"
308
+ value={shape.time || "06:00"}
309
+ disabled={triggerBusy || !enabled}
310
+ onChange={(e) => setTime(e.target.value)}
311
+ />
312
+ </div>
313
+ )}
314
+ </div>
315
+
316
+ <p className={"auto-tick-note " + note.tone}>{note.text}</p>
317
+ <p className="auto-step-detail">
318
+ {/*
319
+ ⚠ "NEXT RUN 12:30" IS A PROMISE, AND IT IS ONLY TRUE IF SOMETHING TICKS. The
320
+ server computes the next fire from the cron alone β€” it does not know whether a
321
+ scheduler is running β€” so printing it flat beside a card that has just said
322
+ "schedules won't fire" is the surface contradicting itself in two lines. When
323
+ the tick is KNOWN off, the same time is stated as the conditional it is.
324
+ */}
325
+ {enabled
326
+ ? nextRunAt
327
+ ? tick && tick.enabled === false
328
+ ? `It would run next at ${nextRunAt}, once a scheduler is running.`
329
+ : `Next run ${nextRunAt}.`
330
+ : "Schedules start from the moment they are switched on β€” turning on a daily job after today's time does not fire it today."
331
+ : "It runs when you press Run now, and nothing else starts it."}
332
+ </p>
333
+ </div>
334
+ </li>
335
+ ) : null}
336
+
337
+ {rest.map((s) => (
338
+ <li
339
+ key={s.node.id}
340
+ className={
341
+ "auto-step" +
342
+ (s.node.id === selected ? " is-selected" : "") +
343
+ (s.node.enabled ? "" : " is-off") +
344
+ (s.alt ? " is-alt" : "") +
345
+ ` is-${s.node.kind}`
346
+ }
347
+ >
348
+ <div className="auto-step-rail">
349
+ {/* An alternative shares the number of the step it is an alternative TO β€” the
350
+ fork is a choice at one position, not two things that both happen. */}
351
+ <span className={"auto-step-n" + (s.alt ? " is-alt" : "")}>{s.n}</span>
352
+ {s.alt ? <span className="auto-step-or">or</span> : null}
353
+ </div>
354
+ <div className="auto-step-card">
355
+ <button
356
+ type="button"
357
+ className="auto-step-hit"
358
+ aria-pressed={s.node.id === selected}
359
+ title={`${s.node.title} β€” ${s.node.subtitle}`}
360
+ onClick={() => onSelect(s.node.id)}
361
+ >
362
+ <span className="auto-step-head">
363
+ <span className="auto-step-mark">
364
+ <KindMark kind={s.node.kind} />
365
+ </span>
366
+ <span className="auto-step-title">{s.node.title}</span>
367
+ <span
368
+ className={`auto-dot is-${s.node.status}`}
369
+ title={`Last run: ${s.node.status}`}
370
+ aria-label={`Last run: ${s.node.status}`}
371
+ />
372
+ </span>
373
+ <span className="auto-step-sub">{s.node.subtitle}</span>
374
+ {s.node.detail ? (
375
+ <span className="auto-step-detail">{s.node.detail}</span>
376
+ ) : null}
377
+ </button>
378
+ {s.node.toggle ? (
379
+ <button
380
+ type="button"
381
+ className={"auto-step-switch" + (s.node.enabled ? " is-on" : "")}
382
+ disabled={busyNode === s.node.id}
383
+ aria-pressed={s.node.enabled}
384
+ aria-label={`${s.node.enabled ? "Turn off" : "Turn on"} ${s.node.title}`}
385
+ title={`${s.node.enabled ? "Turn off" : "Turn on"} ${s.node.title}`}
386
+ onClick={(e) => {
387
+ e.stopPropagation();
388
+ onToggle(s.node.id);
389
+ }}
390
+ >
391
+ <span className="auto-step-switch-knob" />
392
+ </button>
393
+ ) : (
394
+ // A step with no honest switch says so rather than carrying a control that
395
+ // would do nothing β€” "every step toggleable" ends where a real behaviour
396
+ // change ends.
397
+ <span className="auto-step-always" title="This step is what the automation is">
398
+ Always
399
+ </span>
400
+ )}
401
+ </div>
402
+ </li>
403
+ ))}
404
+ </ol>
405
+ </div>
406
+ );
407
+ }
web/src/automation/AutomationSurface.tsx CHANGED
@@ -1,307 +1,311 @@
1
- // ---------------------------------------------------------------------------
2
- // automation/AutomationSurface.tsx β€” the Automation surface (contract C-AUTONAV).
3
- //
4
- // β›” THE CONTRACT THIS FILE GUARANTEES, verbatim: this module path, a DEFAULT
5
- // export, and NO PROPS. The shell mounts `<AutomationSurface />` and hands it
6
- // nothing; it fetches its own data from `/api/v1/automations`. That is the whole
7
- // interface, and it is stated here because the mount line lives in a file this
8
- // session does not own β€” a named export would cost a cross-session round trip.
9
- //
10
- // "Automation replaces the Views rail" (owner) is implemented the way the wave
11
- // scout established: the secondary rail is NOT a shell concept β€” each surface
12
- // owns its own. So this renders a sibling of `.cg-views` built from the same
13
- // `--lp-rail-w` tokens and the same fold behaviour, and the Views rail is
14
- // untouched.
15
- // ---------------------------------------------------------------------------
16
- import type { KeyboardEvent as ReactKeyboardEvent } from "react";
17
- import { useCallback, useEffect, useRef, useState } from "react";
18
-
19
- import AutomationCreate from "./AutomationCreate";
20
- import AutomationDetail from "./AutomationDetail";
21
- import type { Automation, AutomationList } from "./automationApi";
22
- import {
23
- AutomationError,
24
- listAutomations,
25
- patchAutomation,
26
- stateOf,
27
- } from "./automationApi";
28
-
29
- /** The status dot's title β€” the rail says WHY it is that colour, not just that it is. */
30
- function stateTitle(a: Automation): string {
31
- const s = stateOf(a);
32
- if (s === "running") return "Running now";
33
- if (s === "ok") return `Last run succeeded β€” ${a.status?.lastSummary || ""}`;
34
- if (s === "partial") return `Last run was partial β€” ${a.status?.lastSummary || ""}`;
35
- if (s === "error") return `Last run failed β€” ${a.status?.lastSummary || ""}`;
36
- return "Has not run yet";
37
- }
38
-
39
- /**
40
- * The rail's second line β€” ONE fact, not two.
41
- *
42
- * ⚠ It carried "Next 2026-08-04 06:00 · last 2026-08-04 00:20", and the rail is `--lp-rail-w`
43
- * wide, so it rendered as "Next 2026-08-04 06:00 Β· l…" β€” a second line whose only complete word
44
- * was "Next". Two facts that both truncate are worth less than one that fits. The forward-looking
45
- * one wins when a schedule exists (it is the question the rail answers: does this run itself?),
46
- * the last run otherwise. The full picture is one click away in the editor's run history, and the
47
- * row's `title` already says both.
48
- *
49
- * Caught by READING the screenshot: the DOM was correct and the CSS ellipsis was doing exactly
50
- * its job. [[ui-invisible-to-assertions]] β€” judge the pixels even when everything is green.
51
- */
52
- function railSubtitle(a: Automation): string {
53
- if (a.schedule?.enabled) return a.nextRunAt ? `Next ${a.nextRunAt}` : "Scheduled";
54
- const last = a.status?.lastRunAt ? a.status.lastRunAt.replace("T", " ").slice(0, 16) : "";
55
- return last ? `Last run ${last}` : "Manual only";
56
- }
57
-
58
- export default function AutomationSurface() {
59
- const [data, setData] = useState<AutomationList | null>(null);
60
- const [error, setError] = useState("");
61
- const [activeId, setActiveId] = useState<string>("");
62
- const [creating, setCreating] = useState(false);
63
- const [railShut, setRailShut] = useState(false);
64
- const [busy, setBusy] = useState("");
65
- const listRef = useRef<HTMLDivElement | null>(null);
66
-
67
- const load = useCallback(async (abort?: AbortSignal) => {
68
- try {
69
- const next = await listAutomations(abort);
70
- setData(next);
71
- setError("");
72
- return next;
73
- } catch (e) {
74
- if ((e as Error)?.name === "AbortError") return null;
75
- setError(
76
- e instanceof AutomationError
77
- ? e.message
78
- : "The automation service did not answer."
79
- );
80
- return null;
81
- }
82
- }, []);
83
-
84
- useEffect(() => {
85
- const ac = new AbortController();
86
- void load(ac.signal);
87
- return () => ac.abort();
88
- }, [load]);
89
-
90
- // A run is a background thread on the server, so the surface has to ASK whether it
91
- // finished. Polling only while something is actually running keeps an idle surface
92
- // silent β€” a fixed interval would be a request every few seconds forever, for a page
93
- // whose contents change a handful of times a day.
94
- const anyRunning = (data?.automations || []).some((a) => a.running);
95
- useEffect(() => {
96
- if (!anyRunning) return undefined;
97
- const t = window.setInterval(() => void load(), 2500);
98
- return () => window.clearInterval(t);
99
- }, [anyRunning, load]);
100
-
101
- const items = data?.automations || [];
102
- const active = items.find((a) => a.id === activeId) || null;
103
-
104
- const toggleEnabled = async (a: Automation) => {
105
- setBusy(a.id);
106
- try {
107
- await patchAutomation(a.id, {
108
- schedule: { cron: a.schedule.cron, enabled: !a.schedule.enabled },
109
- });
110
- await load();
111
- } catch (e) {
112
- setError(e instanceof AutomationError ? e.message : "That change was not saved.");
113
- } finally {
114
- setBusy("");
115
- }
116
- };
117
-
118
- const onRailKey = (event: ReactKeyboardEvent<HTMLDivElement>) => {
119
- if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
120
- const rows = Array.from(
121
- listRef.current?.querySelectorAll<HTMLButtonElement>(".auto-row-main") || []
122
- );
123
- if (!rows.length) return;
124
- event.preventDefault();
125
- const at = rows.indexOf(document.activeElement as HTMLButtonElement);
126
- const next = event.key === "ArrowDown" ? (at + 1) % rows.length
127
- : (at - 1 + rows.length) % rows.length;
128
- rows[next < 0 ? 0 : next]?.focus();
129
- };
130
-
131
- return (
132
- <div className="auto-surface">
133
- <aside
134
- className={"auto-rail" + (railShut ? " is-collapsed" : "")}
135
- aria-label="Automations"
136
- >
137
- {/* The same three-bars fold control the Views rail carries β€” the two rails are
138
- one idea, so they must not fold with two different affordances. */}
139
- <div className="auto-rail-top">
140
- <button
141
- type="button"
142
- className="cg-rail-toggle"
143
- aria-label={railShut ? "Expand automations" : "Minimize automations"}
144
- aria-expanded={!railShut}
145
- title={railShut ? "Expand automations" : "Minimize automations"}
146
- onClick={() => setRailShut((v) => !v)}
147
- >
148
- <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
149
- <path
150
- d="M2.5 4.4h11M2.5 8h11M2.5 11.6h11"
151
- stroke="currentColor"
152
- strokeWidth="1.35"
153
- strokeLinecap="round"
154
- />
155
- </svg>
156
- </button>
157
- </div>
158
-
159
- <div className="auto-create">
160
- <button
161
- type="button"
162
- className="auto-create-btn"
163
- onClick={() => {
164
- setCreating(true);
165
- setActiveId("");
166
- }}
167
- >
168
- <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
169
- <path
170
- d="M8 3.4v9.2M3.4 8h9.2"
171
- stroke="currentColor"
172
- strokeWidth="1.5"
173
- strokeLinecap="round"
174
- />
175
- </svg>
176
- New automation
177
- </button>
178
- </div>
179
-
180
- <div className="auto-list" ref={listRef} onKeyDown={onRailKey}>
181
- {items.map((a) => {
182
- const s = stateOf(a);
183
- return (
184
- <div
185
- key={a.id}
186
- className={"auto-row" + (a.id === activeId ? " is-active" : "")}
187
- >
188
- <button
189
- type="button"
190
- className="auto-row-main"
191
- onClick={() => {
192
- setActiveId(a.id);
193
- setCreating(false);
194
- }}
195
- >
196
- <span
197
- className={`auto-dot is-${s}`}
198
- title={stateTitle(a)}
199
- aria-label={stateTitle(a)}
200
- />
201
- <span className="auto-row-text">
202
- <span className="auto-row-name">{a.name}</span>
203
- <span className="auto-row-desc">{railSubtitle(a)}</span>
204
- </span>
205
- </button>
206
- <button
207
- type="button"
208
- className={"auto-row-switch" + (a.schedule?.enabled ? " is-on" : "")}
209
- disabled={busy === a.id}
210
- aria-pressed={!!a.schedule?.enabled}
211
- title={
212
- a.schedule?.enabled
213
- ? `Scheduled: ${a.schedule.cron}. Click to pause.`
214
- : "Not scheduled. Click to enable."
215
- }
216
- onClick={() => void toggleEnabled(a)}
217
- >
218
- <span className="auto-row-switch-knob" />
219
- </button>
220
- </div>
221
- );
222
- })}
223
- {!items.length && !error ? (
224
- <p className="auto-rail-empty">
225
- No automations yet. One reads a public web page into a database on a
226
- schedule; the other fills an automation column from a public profile.
227
- </p>
228
- ) : null}
229
- </div>
230
- </aside>
231
-
232
- <section className="auto-main">
233
- {error ? (
234
- <div className="auto-banner is-error" role="alert">
235
- {error}
236
- </div>
237
- ) : null}
238
- {data && !data.storeAvailable ? (
239
- <div className="auto-banner is-warn" role="status">
240
- The tenant store is unavailable, so nothing can be saved right now.
241
- </div>
242
- ) : null}
243
-
244
- {creating ? (
245
- <AutomationCreate
246
- kinds={data?.kinds || []}
247
- onCreated={async (id) => {
248
- setCreating(false);
249
- const next = await load();
250
- if (id && next) setActiveId(id);
251
- }}
252
- onCancel={() => setCreating(false)}
253
- />
254
- ) : active ? (
255
- <AutomationDetail
256
- key={active.id}
257
- automation={active}
258
- kinds={data?.kinds || []}
259
- cronPresets={data?.cronPresets || []}
260
- paidReady={!!data?.paidReady}
261
- discover={data?.discover}
262
- onSaved={async (id) => {
263
- const next = await load();
264
- if (id && next) setActiveId(id);
265
- }}
266
- onDeleted={async () => {
267
- setActiveId("");
268
- await load();
269
- }}
270
- />
271
- ) : (
272
- <div className="auto-empty">
273
- <h1>Automations</h1>
274
- <p>
275
- An automation is a job this workspace runs for you β€” on demand, or on a
276
- schedule. Each one is a flow: a trigger, the steps it walks, and the database
277
- it writes. Pick one on the left, or create a new one.
278
- </p>
279
- <ul className="auto-empty-kinds">
280
- <li>
281
- <strong>Web page to database.</strong> Read a public page, map its columns
282
- to fields, and keep a database in step with it. Re-runs update matched rows
283
- by key and insert new ones; a row that stops appearing is counted and kept,
284
- never deleted.
285
- </li>
286
- <li>
287
- <strong>Instagram profile column.</strong> For every record carrying a
288
- public profile URL, read the profile β€” exactly, through Bright Data, or
289
- approximately on the free anonymous rung β€” and append a timestamped row per
290
- pull, so followers become a series you can filter by date rather than a
291
- single current number.
292
- </li>
293
- <li>
294
- <strong>Find Instagram profiles.</strong> Search a corpus of pre-collected
295
- public profiles for accounts you have never heard of β€” a follower band, a
296
- phrase in the bio, an engagement floor β€” and collect the matches into a
297
- candidates database. Searching costs money, so every run is bounded by a
298
- profile count you set and shows an estimate first. Nothing found is ever
299
- tracked automatically; you tick the ones you want.
300
- </li>
301
- </ul>
302
- </div>
303
- )}
304
- </section>
305
- </div>
306
- );
307
- }
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // automation/AutomationSurface.tsx β€” the Automation surface (contract C-AUTONAV).
3
+ //
4
+ // β›” THE CONTRACT THIS FILE GUARANTEES, verbatim: this module path, a DEFAULT
5
+ // export, and NO PROPS. The shell mounts `<AutomationSurface />` and hands it
6
+ // nothing; it fetches its own data from `/api/v1/automations`. That is the whole
7
+ // interface, and it is stated here because the mount line lives in a file this
8
+ // session does not own β€” a named export would cost a cross-session round trip.
9
+ //
10
+ // "Automation replaces the Views rail" (owner) is implemented the way the wave
11
+ // scout established: the secondary rail is NOT a shell concept β€” each surface
12
+ // owns its own. So this renders a sibling of `.cg-views` built from the same
13
+ // `--lp-rail-w` tokens and the same fold behaviour, and the Views rail is
14
+ // untouched.
15
+ // ---------------------------------------------------------------------------
16
+ import type { KeyboardEvent as ReactKeyboardEvent } from "react";
17
+ import { useCallback, useEffect, useRef, useState } from "react";
18
+
19
+ import AutomationCreate from "./AutomationCreate";
20
+ import AutomationDetail from "./AutomationDetail";
21
+ import type { Automation, AutomationList } from "./automationApi";
22
+ import {
23
+ AutomationError,
24
+ listAutomations,
25
+ patchAutomation,
26
+ stateOf,
27
+ } from "./automationApi";
28
+
29
+ /** The status dot's title β€” the rail says WHY it is that colour, not just that it is. */
30
+ function stateTitle(a: Automation): string {
31
+ const s = stateOf(a);
32
+ if (s === "running") return "Running now";
33
+ if (s === "ok") return `Last run succeeded β€” ${a.status?.lastSummary || ""}`;
34
+ if (s === "partial") return `Last run was partial β€” ${a.status?.lastSummary || ""}`;
35
+ if (s === "error") return `Last run failed β€” ${a.status?.lastSummary || ""}`;
36
+ return "Has not run yet";
37
+ }
38
+
39
+ /**
40
+ * The rail's second line β€” ONE fact, not two.
41
+ *
42
+ * ⚠ It carried "Next 2026-08-04 06:00 · last 2026-08-04 00:20", and the rail is `--lp-rail-w`
43
+ * wide, so it rendered as "Next 2026-08-04 06:00 Β· l…" β€” a second line whose only complete word
44
+ * was "Next". Two facts that both truncate are worth less than one that fits. The forward-looking
45
+ * one wins when a schedule exists (it is the question the rail answers: does this run itself?),
46
+ * the last run otherwise. The full picture is one click away in the editor's run history, and the
47
+ * row's `title` already says both.
48
+ *
49
+ * Caught by READING the screenshot: the DOM was correct and the CSS ellipsis was doing exactly
50
+ * its job. [[ui-invisible-to-assertions]] β€” judge the pixels even when everything is green.
51
+ */
52
+ function railSubtitle(a: Automation): string {
53
+ if (a.schedule?.enabled) return a.nextRunAt ? `Next ${a.nextRunAt}` : "Scheduled";
54
+ const last = a.status?.lastRunAt ? a.status.lastRunAt.replace("T", " ").slice(0, 16) : "";
55
+ return last ? `Last run ${last}` : "Manual only";
56
+ }
57
+
58
+ export default function AutomationSurface() {
59
+ const [data, setData] = useState<AutomationList | null>(null);
60
+ const [error, setError] = useState("");
61
+ const [activeId, setActiveId] = useState<string>("");
62
+ const [creating, setCreating] = useState(false);
63
+ const [railShut, setRailShut] = useState(false);
64
+ const [busy, setBusy] = useState("");
65
+ const listRef = useRef<HTMLDivElement | null>(null);
66
+
67
+ const load = useCallback(async (abort?: AbortSignal) => {
68
+ try {
69
+ const next = await listAutomations(abort);
70
+ setData(next);
71
+ setError("");
72
+ return next;
73
+ } catch (e) {
74
+ if ((e as Error)?.name === "AbortError") return null;
75
+ setError(
76
+ e instanceof AutomationError
77
+ ? e.message
78
+ : "The automation service did not answer."
79
+ );
80
+ return null;
81
+ }
82
+ }, []);
83
+
84
+ useEffect(() => {
85
+ const ac = new AbortController();
86
+ void load(ac.signal);
87
+ return () => ac.abort();
88
+ }, [load]);
89
+
90
+ // A run is a background thread on the server, so the surface has to ASK whether it
91
+ // finished. Polling only while something is actually running keeps an idle surface
92
+ // silent β€” a fixed interval would be a request every few seconds forever, for a page
93
+ // whose contents change a handful of times a day.
94
+ const anyRunning = (data?.automations || []).some((a) => a.running);
95
+ useEffect(() => {
96
+ if (!anyRunning) return undefined;
97
+ const t = window.setInterval(() => void load(), 2500);
98
+ return () => window.clearInterval(t);
99
+ }, [anyRunning, load]);
100
+
101
+ const items = data?.automations || [];
102
+ const active = items.find((a) => a.id === activeId) || null;
103
+
104
+ const toggleEnabled = async (a: Automation) => {
105
+ setBusy(a.id);
106
+ try {
107
+ await patchAutomation(a.id, {
108
+ schedule: { cron: a.schedule.cron, enabled: !a.schedule.enabled },
109
+ });
110
+ await load();
111
+ } catch (e) {
112
+ setError(e instanceof AutomationError ? e.message : "That change was not saved.");
113
+ } finally {
114
+ setBusy("");
115
+ }
116
+ };
117
+
118
+ const onRailKey = (event: ReactKeyboardEvent<HTMLDivElement>) => {
119
+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
120
+ const rows = Array.from(
121
+ listRef.current?.querySelectorAll<HTMLButtonElement>(".auto-row-main") || []
122
+ );
123
+ if (!rows.length) return;
124
+ event.preventDefault();
125
+ const at = rows.indexOf(document.activeElement as HTMLButtonElement);
126
+ const next = event.key === "ArrowDown" ? (at + 1) % rows.length
127
+ : (at - 1 + rows.length) % rows.length;
128
+ rows[next < 0 ? 0 : next]?.focus();
129
+ };
130
+
131
+ return (
132
+ <div className="auto-surface">
133
+ <aside
134
+ className={"auto-rail" + (railShut ? " is-collapsed" : "")}
135
+ aria-label="Automations"
136
+ >
137
+ {/* The same three-bars fold control the Views rail carries β€” the two rails are
138
+ one idea, so they must not fold with two different affordances. */}
139
+ <div className="auto-rail-top">
140
+ <button
141
+ type="button"
142
+ className="cg-rail-toggle"
143
+ aria-label={railShut ? "Expand automations" : "Minimize automations"}
144
+ aria-expanded={!railShut}
145
+ title={railShut ? "Expand automations" : "Minimize automations"}
146
+ onClick={() => setRailShut((v) => !v)}
147
+ >
148
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
149
+ <path
150
+ d="M2.5 4.4h11M2.5 8h11M2.5 11.6h11"
151
+ stroke="currentColor"
152
+ strokeWidth="1.35"
153
+ strokeLinecap="round"
154
+ />
155
+ </svg>
156
+ </button>
157
+ </div>
158
+
159
+ <div className="auto-create">
160
+ <button
161
+ type="button"
162
+ className="auto-create-btn"
163
+ onClick={() => {
164
+ setCreating(true);
165
+ setActiveId("");
166
+ }}
167
+ >
168
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
169
+ <path
170
+ d="M8 3.4v9.2M3.4 8h9.2"
171
+ stroke="currentColor"
172
+ strokeWidth="1.5"
173
+ strokeLinecap="round"
174
+ />
175
+ </svg>
176
+ New automation
177
+ </button>
178
+ </div>
179
+
180
+ <div className="auto-list" ref={listRef} onKeyDown={onRailKey}>
181
+ {items.map((a) => {
182
+ const s = stateOf(a);
183
+ return (
184
+ <div
185
+ key={a.id}
186
+ className={"auto-row" + (a.id === activeId ? " is-active" : "")}
187
+ >
188
+ <button
189
+ type="button"
190
+ className="auto-row-main"
191
+ onClick={() => {
192
+ setActiveId(a.id);
193
+ setCreating(false);
194
+ }}
195
+ >
196
+ <span
197
+ className={`auto-dot is-${s}`}
198
+ title={stateTitle(a)}
199
+ aria-label={stateTitle(a)}
200
+ />
201
+ <span className="auto-row-text">
202
+ <span className="auto-row-name">{a.name}</span>
203
+ <span className="auto-row-desc">{railSubtitle(a)}</span>
204
+ </span>
205
+ </button>
206
+ <button
207
+ type="button"
208
+ className={"auto-row-switch" + (a.schedule?.enabled ? " is-on" : "")}
209
+ disabled={busy === a.id}
210
+ aria-pressed={!!a.schedule?.enabled}
211
+ title={
212
+ a.schedule?.enabled
213
+ ? `Scheduled: ${a.schedule.cron}. Click to pause.`
214
+ : "Not scheduled. Click to enable."
215
+ }
216
+ onClick={() => void toggleEnabled(a)}
217
+ >
218
+ <span className="auto-row-switch-knob" />
219
+ </button>
220
+ </div>
221
+ );
222
+ })}
223
+ {!items.length && !error ? (
224
+ <p className="auto-rail-empty">
225
+ No automations yet. One reads a public web page into a database on a
226
+ schedule; the other fills an automation column from a public profile.
227
+ </p>
228
+ ) : null}
229
+ </div>
230
+ </aside>
231
+
232
+ <section className="auto-main">
233
+ {error ? (
234
+ <div className="auto-banner is-error" role="alert">
235
+ {error}
236
+ </div>
237
+ ) : null}
238
+ {data && !data.storeAvailable ? (
239
+ <div className="auto-banner is-warn" role="status">
240
+ The tenant store is unavailable, so nothing can be saved right now.
241
+ </div>
242
+ ) : null}
243
+
244
+ {creating ? (
245
+ <AutomationCreate
246
+ kinds={data?.kinds || []}
247
+ onCreated={async (id) => {
248
+ setCreating(false);
249
+ const next = await load();
250
+ if (id && next) setActiveId(id);
251
+ }}
252
+ onCancel={() => setCreating(false)}
253
+ />
254
+ ) : active ? (
255
+ <AutomationDetail
256
+ key={active.id}
257
+ automation={active}
258
+ kinds={data?.kinds || []}
259
+ cronPresets={data?.cronPresets || []}
260
+ paidReady={!!data?.paidReady}
261
+ discover={data?.discover}
262
+ // `?? null` and never `|| {enabled:false}`: an absent tick bit is "the server did
263
+ // not say", which Step 1 prints as its own sentence. Defaulting it here would
264
+ // turn a missing field into a claim about production (C6 amendment #1).
265
+ tick={data?.tick ?? null}
266
+ onSaved={async (id) => {
267
+ const next = await load();
268
+ if (id && next) setActiveId(id);
269
+ }}
270
+ onDeleted={async () => {
271
+ setActiveId("");
272
+ await load();
273
+ }}
274
+ />
275
+ ) : (
276
+ <div className="auto-empty">
277
+ <h1>Automations</h1>
278
+ <p>
279
+ An automation is a job this workspace runs for you β€” on demand, or on a
280
+ schedule. Each one is a flow: a trigger, the steps it walks, and the database
281
+ it writes. Pick one on the left, or create a new one.
282
+ </p>
283
+ <ul className="auto-empty-kinds">
284
+ <li>
285
+ <strong>Web page to database.</strong> Read a public page, map its columns
286
+ to fields, and keep a database in step with it. Re-runs update matched rows
287
+ by key and insert new ones; a row that stops appearing is counted and kept,
288
+ never deleted.
289
+ </li>
290
+ <li>
291
+ <strong>Instagram profile column.</strong> For every record carrying a
292
+ public profile URL, read the profile β€” exactly, through Bright Data, or
293
+ approximately on the free anonymous rung β€” and append a timestamped row per
294
+ pull, so followers become a series you can filter by date rather than a
295
+ single current number.
296
+ </li>
297
+ <li>
298
+ <strong>Find Instagram profiles.</strong> Search a corpus of pre-collected
299
+ public profiles for accounts you have never heard of β€” a follower band, a
300
+ phrase in the bio, an engagement floor β€” and collect the matches into a
301
+ candidates database. Searching costs money, so every run is bounded by a
302
+ profile count you set and shows an estimate first. Nothing found is ever
303
+ tracked automatically; you tick the ones you want.
304
+ </li>
305
+ </ul>
306
+ </div>
307
+ )}
308
+ </section>
309
+ </div>
310
+ );
311
+ }
web/src/automation/automationApi.ts CHANGED
@@ -1,357 +1,378 @@
1
- // ---------------------------------------------------------------------------
2
- // automation/automationApi.ts β€” the Automation surface's whole data layer.
3
- //
4
- // Wave-18 item 5 (contracts C4-AUTO + C-AUTONAV). Deliberately its own leaf
5
- // rather than an addition to `customer-grid/apiBridge.ts`: the grid tree is the
6
- // ASSET that also ships inside the Streamlit embed, and an automation surface
7
- // that only the standalone shell mounts must not grow an edge into it. It
8
- // imports `apiContract` (the shared leaf both trees already read) and nothing
9
- // else.
10
- //
11
- // ⚠ EVERY VOCABULARY HERE COMES FROM THE SERVER. The kind list and the cron
12
- // presets ride on `GET /automations` rather than sitting in a client constant,
13
- // because the parser that accepts a cron string lives in Python β€” a client copy
14
- // of the preset list is a list that can offer a schedule the server rejects,
15
- // and the user would see the refusal as "it just doesn't save".
16
- // ---------------------------------------------------------------------------
17
- import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, signal } from "../apiContract";
18
-
19
- export type AutomationKind = "scrape_db" | "field_instagram" | "discover_instagram";
20
- export type RunState = "idle" | "running" | "ok" | "error" | "partial";
21
- /**
22
- * ⚠ `hiker` is NOT in this union any more (wave 20, D-21) β€” the vendor moved.
23
- * Stored configs still SAY `hiker` and the server maps them forward
24
- * (`TIER_ALIASES`), so nothing in this client should ever write that word.
25
- */
26
- export type CaptureTier = "anonymous" | "brightdata";
27
-
28
- /**
29
- * A node's dot. Deliberately WIDER than `RunState` β€” a single step can be
30
- * `blocked` (a rung refused) or `skipped` (a switch is off) in ways a whole run
31
- * cannot, and folding those into `partial` would throw away the only thing the
32
- * dot is there to say.
33
- */
34
- export type NodeState = "idle" | "ok" | "partial" | "error" | "blocked" | "skipped";
35
-
36
- /**
37
- * ⚠ THE GRAPH IS THE SERVER'S, not this client's. `engine.graph()` derives it
38
- * from the definition, in the same module that RUNS the steps β€” so the canvas
39
- * cannot draw a step the engine stopped executing. This file only types it and
40
- * `canvasLayout.ts` only positions it; nothing here decides what the nodes are.
41
- * (Same rule as `cronPresets` and `kinds`, for the same reason.)
42
- */
43
- export interface GraphNode {
44
- id: string;
45
- kind: "trigger" | "source" | "capture" | "branch" | "write";
46
- title: string;
47
- subtitle: string;
48
- detail: string;
49
- col: number;
50
- row: number;
51
- /** Which config panel this node opens. */
52
- panel: string;
53
- enabled: boolean;
54
- /** Non-empty = this node has a REAL switch. Empty = it is always on, by nature. */
55
- toggle: string;
56
- status: NodeState;
57
- }
58
-
59
- export interface GraphEdge {
60
- from: string;
61
- to: string;
62
- label: string;
63
- }
64
-
65
- export interface AutomationGraph {
66
- nodes: GraphNode[];
67
- edges: GraphEdge[];
68
- }
69
-
70
- export interface RunEntry {
71
- ts: string;
72
- ok: boolean;
73
- summary: string;
74
- counts: Record<string, number>;
75
- /** Per-node outcomes, MEASURED as the run walked. Absent on runs stored before W19-C. */
76
- steps?: Record<string, NodeState>;
77
- affected?: string[];
78
- }
79
-
80
- export interface Automation {
81
- id: string;
82
- name: string;
83
- kind: AutomationKind;
84
- config: Record<string, unknown>;
85
- schedule: { cron: string; enabled: boolean; enabledAt?: string };
86
- status: { state: RunState; lastRunAt?: string; lastSummary?: string; step?: string };
87
- runs: RunEntry[];
88
- created?: string;
89
- createdBy?: string;
90
- nextRunAt?: string;
91
- running?: boolean;
92
- graph: AutomationGraph;
93
- }
94
-
95
- export interface AutomationList {
96
- automations: Automation[];
97
- kinds: { key: AutomationKind; label: string }[];
98
- cronPresets: { cron: string; label: string }[];
99
- /**
100
- * Is `AIOS_BRIGHTDATA_KEY` configured on the server? A BOOLEAN, never the key β€”
101
- * the surface needs to say "the paid rung is not configured" honestly rather
102
- * than offering a tier that will silently refuse.
103
- */
104
- paidReady: boolean;
105
- /**
106
- * THE SOURCE REGISTRY (DEBT D-9's seam). Server-declared, for the reason
107
- * `cronPresets` is: the module that RUNS a source is the only thing entitled
108
- * to say what it can do, and a client copy of "Instagram can discover,
109
- * TikTok cannot" goes stale in silence. `canDiscover: false` is an honest
110
- * statement, not a gap β€” offering the button anyway offers a refusal.
111
- */
112
- sources: SourceStatus[];
113
- /** The discovery vocabulary β€” every name MEASURED-accepted by the vendor. */
114
- discover: DiscoverVocab;
115
- storeAvailable: boolean;
116
- }
117
-
118
- export interface SourceStatus {
119
- key: string;
120
- label: string;
121
- vendor: string;
122
- ready: boolean;
123
- canDiscover: boolean;
124
- }
125
-
126
- export interface DiscoverVocab {
127
- fields: string[];
128
- /**
129
- * The subset seen carrying VALUES on real corpus rows. The others are
130
- * filterable and were null on every row measured β€” and a filter on an
131
- * unpopulated field returns nothing while looking exactly like "no such
132
- * influencers exist".
133
- */
134
- lead: string[];
135
- operators: string[];
136
- nullaryOperators: string[];
137
- maxRecords: number;
138
- table: string;
139
- }
140
-
141
- /**
142
- * ⚠ AN ESTIMATE, AND IT CARRIES ITS OWN CAVEAT (`basis: "SPEC"`). Bright Data
143
- * never quotes a price before a run, and this account's token cannot read a
144
- * balance β€” so no surface may present this as a billed figure.
145
- */
146
- export interface DiscoverEstimate {
147
- records: number;
148
- usd: number;
149
- unitUsd: number;
150
- basis: string;
151
- note: string;
152
- }
153
-
154
- export interface UserTable {
155
- key: string;
156
- label: string;
157
- source: string;
158
- rowCount: number;
159
- fields: { key: string; label: string; type: string; automation?: unknown }[];
160
- }
161
-
162
- export interface SourcePreview {
163
- ok: boolean;
164
- status: number;
165
- url: string;
166
- title?: string;
167
- note?: string;
168
- columns: string[];
169
- sample: Record<string, string>[];
170
- rowCount: number;
171
- tableCount?: number;
172
- }
173
-
174
- export interface RunRows {
175
- table: string;
176
- label: string;
177
- fields: { key: string; label: string }[];
178
- rows: Record<string, string>[];
179
- truncated: boolean;
180
- }
181
-
182
- export class AutomationError extends Error {
183
- status: number;
184
-
185
- constructor(message: string, status: number) {
186
- super(message);
187
- this.name = "AutomationError";
188
- this.status = status;
189
- }
190
- }
191
-
192
- async function result<T>(response: Response): Promise<T> {
193
- let body: unknown = null;
194
- try {
195
- body = await response.json();
196
- } catch {
197
- // The status is still an honest answer; the message below says so.
198
- }
199
- if (response.status === 401) signal(UNAUTHORIZED_EVENT);
200
- if (!response.ok) {
201
- const shaped = body as { error?: { message?: string } } | null;
202
- throw new AutomationError(
203
- shaped?.error?.message || `The server answered ${response.status}.`,
204
- response.status
205
- );
206
- }
207
- return body as T;
208
- }
209
-
210
- function send<T>(path: string, init?: RequestInit): Promise<T> {
211
- return fetch(`${API_V1}${path}`, {
212
- credentials: CREDENTIALS,
213
- headers: init?.body ? { "Content-Type": "application/json" } : undefined,
214
- ...init,
215
- }).then((r) => result<T>(r));
216
- }
217
-
218
- export function listAutomations(abort?: AbortSignal): Promise<AutomationList> {
219
- return send<AutomationList>("/automations", { signal: abort });
220
- }
221
-
222
- export function listTables(abort?: AbortSignal): Promise<{ tables: UserTable[] }> {
223
- return send<{ tables: UserTable[] }>("/automations/tables", { signal: abort });
224
- }
225
-
226
- export function createAutomation(body: unknown): Promise<{ automation: Automation }> {
227
- return send("/automations", { method: "POST", body: JSON.stringify(body) });
228
- }
229
-
230
- export function patchAutomation(
231
- id: string,
232
- body: unknown
233
- ): Promise<{ automation: Automation }> {
234
- return send(`/automations/${encodeURIComponent(id)}`, {
235
- method: "PATCH",
236
- body: JSON.stringify(body),
237
- });
238
- }
239
-
240
- export function deleteAutomation(id: string): Promise<{ deleted: string }> {
241
- return send(`/automations/${encodeURIComponent(id)}`, { method: "DELETE" });
242
- }
243
-
244
- export function runAutomation(id: string): Promise<{ started: string }> {
245
- return send(`/automations/${encodeURIComponent(id)}/run`, { method: "POST" });
246
- }
247
-
248
- /**
249
- * Flip one canvas node's switch.
250
- *
251
- * The client says WHICH NODE was clicked and nothing else β€” the server owns what
252
- * each switch means (`engine.NODE_TOGGLES`). A client that knew "the Bright Data
253
- * node writes config.tier" would be a second copy of that knowledge, free to
254
- * drift from the engine that reads it β€” and it would have had to be rewritten
255
- * when the vendor changed. It did not.
256
- */
257
- export function toggleNode(
258
- id: string,
259
- nodeId: string
260
- ): Promise<{ automation: Automation }> {
261
- return send(
262
- `/automations/${encodeURIComponent(id)}/nodes/${encodeURIComponent(nodeId)}/toggle`,
263
- { method: "POST" }
264
- );
265
- }
266
-
267
- export function getAutomation(id: string): Promise<{ automation: Automation }> {
268
- return send(`/automations/${encodeURIComponent(id)}`);
269
- }
270
-
271
- export function runRows(id: string): Promise<RunRows> {
272
- return send(`/automations/${encodeURIComponent(id)}/rows`);
273
- }
274
-
275
- /** What would a search of this size cost? Asked BEFORE the run, never after. */
276
- export function discoverEstimate(recordsLimit: number): Promise<DiscoverEstimate> {
277
- return send("/automations/discover/estimate", {
278
- method: "POST",
279
- body: JSON.stringify({ recordsLimit }),
280
- });
281
- }
282
-
283
- export function previewSource(
284
- url: string,
285
- extract: string,
286
- tableIndex: number
287
- ): Promise<SourcePreview> {
288
- return send("/automations/preview", {
289
- method: "POST",
290
- body: JSON.stringify({ url, extract, tableIndex }),
291
- });
292
- }
293
-
294
- /**
295
- * A source column name β†’ a storable field key. Mirrors the server's own
296
- * normalisation (`clean_config`) so the key the UI shows is the key that gets
297
- * stored β€” a preview that promised `gics_sector` and a store that wrote
298
- * `gics__sector` would look like data loss.
299
- */
300
- export function fieldKeyFor(column: string): string {
301
- return (column || "")
302
- .toLowerCase()
303
- .replace(/[^a-z0-9_]+/g, "_")
304
- .replace(/^_+|_+$/g, "")
305
- .slice(0, 60);
306
- }
307
-
308
- /** The state word a status dot / chip paints from. */
309
- export function stateOf(a: Automation): RunState {
310
- return a.running ? "running" : (a.status?.state as RunState) || "idle";
311
- }
312
-
313
- /**
314
- * A run's counts as ordered label/value pairs. The ORDER is the sentence the
315
- * numbers make β€” new, updated, unchanged, then the ones that need explaining β€”
316
- * and `orphans` is spelled out rather than abbreviated because a bare number
317
- * next to the word "orphans" is the one count a user must not have to guess at.
318
- */
319
- export const COUNT_LABELS: [string, string][] = [
320
- ["inserted", "New"],
321
- ["updated", "Updated"],
322
- ["unchanged", "Unchanged"],
323
- ["orphans", "No longer on the page (kept)"],
324
- ["duplicates", "Duplicate keys"],
325
- ["skipped", "Skipped (no key)"],
326
- // ⚠ ITS OWN CHIP, next to `skipped` but never merged with it. "Skipped" is a
327
- // property of the data and usually benign; "not written β€” the database is
328
- // full" is a property of the system and never is. One chip for both is how a
329
- // time series stops growing without anybody being told.
330
- ["capped", "Not written β€” the database is full"],
331
- ["source_rows", "Rows read"],
332
- ["profiles", "Profiles"],
333
- ["ok", "Read in full"],
334
- // ⚠ ADDED after reading the first live screenshot. The engine counts `partial` separately
335
- // (profile read, media not anonymously readable) but this table did not, so a run whose
336
- // summary said "1/1 profiles read" showed a chip row reading "0 Read" β€” the chips
337
- // contradicting the sentence directly above them. A count the summary names must have a chip.
338
- ["partial", "Profile only"],
339
- ["blocked", "Blocked"],
340
- ["error", "Errors"],
341
- ["paid", "Exact via Bright Data"],
342
- ["posts", "Posts"],
343
- ["new_posts", "New posts"],
344
- // The engagement series only grows while the per-post rung is on, so its
345
- // count is its own chip β€” "12 posts" and "0 engagement snapshots" together
346
- // are the honest picture of a profile-only run.
347
- ["metrics", "Engagement snapshots"],
348
- // Discovery.
349
- ["asked", "Asked for"],
350
- ["found", "Profiles found"],
351
- ["new", "New to us"],
352
- ["seen_again", "Seen before"],
353
- ["dropped", "Returned but unusable (no handle)"],
354
- // ⚠ Its own chip for the same reason `capped` has one: a database that could
355
- // not be CREATED is a system fact, and the run that hit it wrote nothing.
356
- ["missing_tables", "Databases that could not be created"],
357
- ];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // automation/automationApi.ts β€” the Automation surface's whole data layer.
3
+ //
4
+ // Wave-18 item 5 (contracts C4-AUTO + C-AUTONAV). Deliberately its own leaf
5
+ // rather than an addition to `customer-grid/apiBridge.ts`: the grid tree is the
6
+ // ASSET that also ships inside the Streamlit embed, and an automation surface
7
+ // that only the standalone shell mounts must not grow an edge into it. It
8
+ // imports `apiContract` (the shared leaf both trees already read) and nothing
9
+ // else.
10
+ //
11
+ // ⚠ EVERY VOCABULARY HERE COMES FROM THE SERVER. The kind list and the cron
12
+ // presets ride on `GET /automations` rather than sitting in a client constant,
13
+ // because the parser that accepts a cron string lives in Python β€” a client copy
14
+ // of the preset list is a list that can offer a schedule the server rejects,
15
+ // and the user would see the refusal as "it just doesn't save".
16
+ // ---------------------------------------------------------------------------
17
+ import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, signal } from "../apiContract";
18
+
19
+ export type AutomationKind = "scrape_db" | "field_instagram" | "discover_instagram";
20
+ export type RunState = "idle" | "running" | "ok" | "error" | "partial";
21
+ /**
22
+ * ⚠ `hiker` is NOT in this union any more (wave 20, D-21) β€” the vendor moved.
23
+ * Stored configs still SAY `hiker` and the server maps them forward
24
+ * (`TIER_ALIASES`), so nothing in this client should ever write that word.
25
+ */
26
+ export type CaptureTier = "anonymous" | "brightdata";
27
+
28
+ /**
29
+ * A node's dot. Deliberately WIDER than `RunState` β€” a single step can be
30
+ * `blocked` (a rung refused) or `skipped` (a switch is off) in ways a whole run
31
+ * cannot, and folding those into `partial` would throw away the only thing the
32
+ * dot is there to say.
33
+ */
34
+ export type NodeState = "idle" | "ok" | "partial" | "error" | "blocked" | "skipped";
35
+
36
+ /**
37
+ * ⚠ THE GRAPH IS THE SERVER'S, not this client's. `engine.graph()` derives it
38
+ * from the definition, in the same module that RUNS the steps β€” so the surface
39
+ * cannot show a step the engine stopped executing. This file only types it and
40
+ * `steps.ts` only numbers it; nothing here decides what the nodes are.
41
+ * (It said `canvasLayout.ts` until wave 21 replaced the canvas with numbered
42
+ * Steps β€” R9. Stale prose about a deleted mount is a hazard, not a footnote.)
43
+ * (Same rule as `cronPresets` and `kinds`, for the same reason.)
44
+ */
45
+ export interface GraphNode {
46
+ id: string;
47
+ kind: "trigger" | "source" | "capture" | "branch" | "write";
48
+ title: string;
49
+ subtitle: string;
50
+ detail: string;
51
+ col: number;
52
+ row: number;
53
+ /** Which config panel this node opens. */
54
+ panel: string;
55
+ enabled: boolean;
56
+ /** Non-empty = this node has a REAL switch. Empty = it is always on, by nature. */
57
+ toggle: string;
58
+ status: NodeState;
59
+ }
60
+
61
+ export interface GraphEdge {
62
+ from: string;
63
+ to: string;
64
+ label: string;
65
+ }
66
+
67
+ export interface AutomationGraph {
68
+ nodes: GraphNode[];
69
+ edges: GraphEdge[];
70
+ }
71
+
72
+ export interface RunEntry {
73
+ ts: string;
74
+ ok: boolean;
75
+ summary: string;
76
+ counts: Record<string, number>;
77
+ /** Per-node outcomes, MEASURED as the run walked. Absent on runs stored before W19-C. */
78
+ steps?: Record<string, NodeState>;
79
+ affected?: string[];
80
+ }
81
+
82
+ export interface Automation {
83
+ id: string;
84
+ name: string;
85
+ kind: AutomationKind;
86
+ config: Record<string, unknown>;
87
+ schedule: { cron: string; enabled: boolean; enabledAt?: string };
88
+ status: { state: RunState; lastRunAt?: string; lastSummary?: string; step?: string };
89
+ runs: RunEntry[];
90
+ created?: string;
91
+ createdBy?: string;
92
+ nextRunAt?: string;
93
+ running?: boolean;
94
+ graph: AutomationGraph;
95
+ }
96
+
97
+ export interface AutomationList {
98
+ automations: Automation[];
99
+ kinds: { key: AutomationKind; label: string }[];
100
+ cronPresets: { cron: string; label: string }[];
101
+ /**
102
+ * Is `AIOS_BRIGHTDATA_KEY` configured on the server? A BOOLEAN, never the key β€”
103
+ * the surface needs to say "the paid rung is not configured" honestly rather
104
+ * than offering a tier that will silently refuse.
105
+ */
106
+ paidReady: boolean;
107
+ /**
108
+ * THE SOURCE REGISTRY (DEBT D-9's seam). Server-declared, for the reason
109
+ * `cronPresets` is: the module that RUNS a source is the only thing entitled
110
+ * to say what it can do, and a client copy of "Instagram can discover,
111
+ * TikTok cannot" goes stale in silence. `canDiscover: false` is an honest
112
+ * statement, not a gap β€” offering the button anyway offers a refusal.
113
+ */
114
+ sources: SourceStatus[];
115
+ /** The discovery vocabulary β€” every name MEASURED-accepted by the vendor. */
116
+ discover: DiscoverVocab;
117
+ /**
118
+ * ⚠ CAN A SCHEDULE ACTUALLY FIRE ON THIS DEPLOYMENT? (R9's honest switch; wave-21 C6
119
+ * amendment #1.) OPTIONAL because it is genuinely absent until the server ships it β€” and
120
+ * that absence is a THIRD state the card prints out loud ("not reported"), never a silent
121
+ * fallback to either answer. An optional field that a UI treats as `false` is how a page
122
+ * starts stating a measurement nobody made.
123
+ *
124
+ * TWO independent paths fire schedules and a single boolean cannot describe them: the
125
+ * in-process scheduler (`AIOS_AUTOMATIONS=1`) and an external cron POSTing
126
+ * `/automations/tick` with the shared token β€” the AWS EventBridge tick is live
127
+ * ([[aws-automation-cron]]), so "the in-process one is off" is not "schedules won't fire".
128
+ */
129
+ tick?: TickState;
130
+ storeAvailable: boolean;
131
+ }
132
+
133
+ export interface TickState {
134
+ enabled: boolean;
135
+ /** Which path. `external` means the door is OPEN, never that the caller is alive. */
136
+ source?: "in-process" | "external" | "";
137
+ }
138
+
139
+ export interface SourceStatus {
140
+ key: string;
141
+ label: string;
142
+ vendor: string;
143
+ ready: boolean;
144
+ canDiscover: boolean;
145
+ }
146
+
147
+ export interface DiscoverVocab {
148
+ fields: string[];
149
+ /**
150
+ * The subset seen carrying VALUES on real corpus rows. The others are
151
+ * filterable and were null on every row measured β€” and a filter on an
152
+ * unpopulated field returns nothing while looking exactly like "no such
153
+ * influencers exist".
154
+ */
155
+ lead: string[];
156
+ operators: string[];
157
+ nullaryOperators: string[];
158
+ maxRecords: number;
159
+ table: string;
160
+ }
161
+
162
+ /**
163
+ * ⚠ AN ESTIMATE, AND IT CARRIES ITS OWN CAVEAT (`basis: "SPEC"`). Bright Data
164
+ * never quotes a price before a run, and this account's token cannot read a
165
+ * balance β€” so no surface may present this as a billed figure.
166
+ */
167
+ export interface DiscoverEstimate {
168
+ records: number;
169
+ usd: number;
170
+ unitUsd: number;
171
+ basis: string;
172
+ note: string;
173
+ }
174
+
175
+ export interface UserTable {
176
+ key: string;
177
+ label: string;
178
+ source: string;
179
+ rowCount: number;
180
+ fields: { key: string; label: string; type: string; automation?: unknown }[];
181
+ }
182
+
183
+ export interface SourcePreview {
184
+ ok: boolean;
185
+ status: number;
186
+ url: string;
187
+ title?: string;
188
+ note?: string;
189
+ columns: string[];
190
+ sample: Record<string, string>[];
191
+ rowCount: number;
192
+ tableCount?: number;
193
+ }
194
+
195
+ export interface RunRows {
196
+ table: string;
197
+ label: string;
198
+ fields: { key: string; label: string }[];
199
+ rows: Record<string, string>[];
200
+ truncated: boolean;
201
+ }
202
+
203
+ export class AutomationError extends Error {
204
+ status: number;
205
+
206
+ constructor(message: string, status: number) {
207
+ super(message);
208
+ this.name = "AutomationError";
209
+ this.status = status;
210
+ }
211
+ }
212
+
213
+ async function result<T>(response: Response): Promise<T> {
214
+ let body: unknown = null;
215
+ try {
216
+ body = await response.json();
217
+ } catch {
218
+ // The status is still an honest answer; the message below says so.
219
+ }
220
+ if (response.status === 401) signal(UNAUTHORIZED_EVENT);
221
+ if (!response.ok) {
222
+ const shaped = body as { error?: { message?: string } } | null;
223
+ throw new AutomationError(
224
+ shaped?.error?.message || `The server answered ${response.status}.`,
225
+ response.status
226
+ );
227
+ }
228
+ return body as T;
229
+ }
230
+
231
+ function send<T>(path: string, init?: RequestInit): Promise<T> {
232
+ return fetch(`${API_V1}${path}`, {
233
+ credentials: CREDENTIALS,
234
+ headers: init?.body ? { "Content-Type": "application/json" } : undefined,
235
+ ...init,
236
+ }).then((r) => result<T>(r));
237
+ }
238
+
239
+ export function listAutomations(abort?: AbortSignal): Promise<AutomationList> {
240
+ return send<AutomationList>("/automations", { signal: abort });
241
+ }
242
+
243
+ export function listTables(abort?: AbortSignal): Promise<{ tables: UserTable[] }> {
244
+ return send<{ tables: UserTable[] }>("/automations/tables", { signal: abort });
245
+ }
246
+
247
+ export function createAutomation(body: unknown): Promise<{ automation: Automation }> {
248
+ return send("/automations", { method: "POST", body: JSON.stringify(body) });
249
+ }
250
+
251
+ export function patchAutomation(
252
+ id: string,
253
+ body: unknown
254
+ ): Promise<{ automation: Automation }> {
255
+ return send(`/automations/${encodeURIComponent(id)}`, {
256
+ method: "PATCH",
257
+ body: JSON.stringify(body),
258
+ });
259
+ }
260
+
261
+ export function deleteAutomation(id: string): Promise<{ deleted: string }> {
262
+ return send(`/automations/${encodeURIComponent(id)}`, { method: "DELETE" });
263
+ }
264
+
265
+ export function runAutomation(id: string): Promise<{ started: string }> {
266
+ return send(`/automations/${encodeURIComponent(id)}/run`, { method: "POST" });
267
+ }
268
+
269
+ /**
270
+ * Flip one step's switch.
271
+ *
272
+ * The client says WHICH NODE was clicked and nothing else β€” the server owns what
273
+ * each switch means (`engine.NODE_TOGGLES`). A client that knew "the Bright Data
274
+ * node writes config.tier" would be a second copy of that knowledge, free to
275
+ * drift from the engine that reads it β€” and it would have had to be rewritten
276
+ * when the vendor changed. It did not.
277
+ */
278
+ export function toggleNode(
279
+ id: string,
280
+ nodeId: string
281
+ ): Promise<{ automation: Automation }> {
282
+ return send(
283
+ `/automations/${encodeURIComponent(id)}/nodes/${encodeURIComponent(nodeId)}/toggle`,
284
+ { method: "POST" }
285
+ );
286
+ }
287
+
288
+ export function getAutomation(id: string): Promise<{ automation: Automation }> {
289
+ return send(`/automations/${encodeURIComponent(id)}`);
290
+ }
291
+
292
+ export function runRows(id: string): Promise<RunRows> {
293
+ return send(`/automations/${encodeURIComponent(id)}/rows`);
294
+ }
295
+
296
+ /** What would a search of this size cost? Asked BEFORE the run, never after. */
297
+ export function discoverEstimate(recordsLimit: number): Promise<DiscoverEstimate> {
298
+ return send("/automations/discover/estimate", {
299
+ method: "POST",
300
+ body: JSON.stringify({ recordsLimit }),
301
+ });
302
+ }
303
+
304
+ export function previewSource(
305
+ url: string,
306
+ extract: string,
307
+ tableIndex: number
308
+ ): Promise<SourcePreview> {
309
+ return send("/automations/preview", {
310
+ method: "POST",
311
+ body: JSON.stringify({ url, extract, tableIndex }),
312
+ });
313
+ }
314
+
315
+ /**
316
+ * A source column name β†’ a storable field key. Mirrors the server's own
317
+ * normalisation (`clean_config`) so the key the UI shows is the key that gets
318
+ * stored β€” a preview that promised `gics_sector` and a store that wrote
319
+ * `gics__sector` would look like data loss.
320
+ */
321
+ export function fieldKeyFor(column: string): string {
322
+ return (column || "")
323
+ .toLowerCase()
324
+ .replace(/[^a-z0-9_]+/g, "_")
325
+ .replace(/^_+|_+$/g, "")
326
+ .slice(0, 60);
327
+ }
328
+
329
+ /** The state word a status dot / chip paints from. */
330
+ export function stateOf(a: Automation): RunState {
331
+ return a.running ? "running" : (a.status?.state as RunState) || "idle";
332
+ }
333
+
334
+ /**
335
+ * A run's counts as ordered label/value pairs. The ORDER is the sentence the
336
+ * numbers make β€” new, updated, unchanged, then the ones that need explaining β€”
337
+ * and `orphans` is spelled out rather than abbreviated because a bare number
338
+ * next to the word "orphans" is the one count a user must not have to guess at.
339
+ */
340
+ export const COUNT_LABELS: [string, string][] = [
341
+ ["inserted", "New"],
342
+ ["updated", "Updated"],
343
+ ["unchanged", "Unchanged"],
344
+ ["orphans", "No longer on the page (kept)"],
345
+ ["duplicates", "Duplicate keys"],
346
+ ["skipped", "Skipped (no key)"],
347
+ // ⚠ ITS OWN CHIP, next to `skipped` but never merged with it. "Skipped" is a
348
+ // property of the data and usually benign; "not written β€” the database is
349
+ // full" is a property of the system and never is. One chip for both is how a
350
+ // time series stops growing without anybody being told.
351
+ ["capped", "Not written β€” the database is full"],
352
+ ["source_rows", "Rows read"],
353
+ ["profiles", "Profiles"],
354
+ ["ok", "Read in full"],
355
+ // ⚠ ADDED after reading the first live screenshot. The engine counts `partial` separately
356
+ // (profile read, media not anonymously readable) but this table did not, so a run whose
357
+ // summary said "1/1 profiles read" showed a chip row reading "0 Read" β€” the chips
358
+ // contradicting the sentence directly above them. A count the summary names must have a chip.
359
+ ["partial", "Profile only"],
360
+ ["blocked", "Blocked"],
361
+ ["error", "Errors"],
362
+ ["paid", "Exact via Bright Data"],
363
+ ["posts", "Posts"],
364
+ ["new_posts", "New posts"],
365
+ // The engagement series only grows while the per-post rung is on, so its
366
+ // count is its own chip β€” "12 posts" and "0 engagement snapshots" together
367
+ // are the honest picture of a profile-only run.
368
+ ["metrics", "Engagement snapshots"],
369
+ // Discovery.
370
+ ["asked", "Asked for"],
371
+ ["found", "Profiles found"],
372
+ ["new", "New to us"],
373
+ ["seen_again", "Seen before"],
374
+ ["dropped", "Returned but unusable (no handle)"],
375
+ // ⚠ Its own chip for the same reason `capped` has one: a database that could
376
+ // not be CREATED is a system fact, and the run that hit it wrote nothing.
377
+ ["missing_tables", "Databases that could not be created"],
378
+ ];
web/src/automation/steps.ts ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { GraphNode } from "./automationApi";
15
+
16
+ export interface Step {
17
+ node: GraphNode;
18
+ /** The number the card carries. */
19
+ n: number;
20
+ /** True when this node shares its position with the one before it β€” an ALTERNATIVE, not a next. */
21
+ alt: boolean;
22
+ }
23
+
24
+ /**
25
+ * Number the server's nodes for display.
26
+ *
27
+ * ⭐ THE NUMBER IS `col + 1`, NOT the array index, and that is the honest one. The
28
+ * `field_instagram` graph forks: `capture_paid` and `capture_anon` both sit at
29
+ * `col: 3` because they are the SAME position in the flow reached two ways (the
30
+ * paid rung answers, or the anonymous ladder does). Numbering them 4 and 5 would
31
+ * state a sequence that never happens. They share a number and the second is
32
+ * marked `alt`, so the list says "either of these" rather than "then".
33
+ *
34
+ * "Step 1 is always the Trigger" (R9) therefore falls out of the payload β€” the
35
+ * trigger is the node at `col: 0` β€” instead of being asserted by this client. If
36
+ * the engine ever emits something else first, the UI shows what the engine does.
37
+ */
38
+ export function numberSteps(nodes: GraphNode[]): Step[] {
39
+ return (nodes || []).map((node, i) => {
40
+ const col = typeof node.col === "number" ? node.col : i;
41
+ const before = i > 0 ? nodes[i - 1] : null;
42
+ const beforeCol = before && typeof before.col === "number" ? before.col : -1;
43
+ return { node, n: col + 1, alt: i > 0 && beforeCol === col };
44
+ });
45
+ }
46
+
47
+ /** How the Step-1 card is currently set: what it repeats on, and at what time. */
48
+ export interface TriggerShape {
49
+ /** `day` = every day Β· `0`..`6` = that weekday (cron numbering, 0 = Sunday) Β· `custom` = a cron only. */
50
+ every: string;
51
+ /** `HH:MM`, empty when the cron does not express a single fire time. */
52
+ time: string;
53
+ }
54
+
55
+ const DAILY = /^(\d{1,2}) (\d{1,2}) \* \* \*$/;
56
+ const WEEKLY = /^(\d{1,2}) (\d{1,2}) \* \* ([0-7])$/;
57
+
58
+ function two(n: number): string {
59
+ return String(n).padStart(2, "0");
60
+ }
61
+
62
+ /**
63
+ * A stored cron β†’ the controls that can express it.
64
+ *
65
+ * β›” ANYTHING THIS CANNOT EXPRESS COMES BACK AS `custom`, NEVER AS THE FIRST OPTION.
66
+ * A `<select>` whose value matches no `<option>` renders the first one, and the next
67
+ * Save then writes a schedule nobody chose β€” the defect this codebase has already
68
+ * paid for twice ([[cg-condition-builder-items]]; the two `(not in this database)`
69
+ * options in AutomationDetail exist for the same reason). A quarter-hourly weekday
70
+ * cron is a legal schedule the engine runs happily; the editor's job is to leave it
71
+ * alone, not to quietly turn it into "every day at 08:00".
72
+ *
73
+ * (Written without the literal cron string on purpose β€” a step-slash inside a block
74
+ * comment ENDS the comment, and the compiler's 20 cascading errors say nothing about
75
+ * the cron.)
76
+ */
77
+ export function readCron(cron: string): TriggerShape {
78
+ const raw = String(cron || "").trim();
79
+ const daily = DAILY.exec(raw);
80
+ if (daily) {
81
+ const [, m, h] = daily;
82
+ if (Number(h) <= 23 && Number(m) <= 59) return { every: "day", time: `${two(Number(h))}:${two(Number(m))}` };
83
+ }
84
+ const weekly = WEEKLY.exec(raw);
85
+ if (weekly) {
86
+ const [, m, h, d] = weekly;
87
+ if (Number(h) <= 23 && Number(m) <= 59) {
88
+ return { every: String(Number(d) % 7), time: `${two(Number(h))}:${two(Number(m))}` };
89
+ }
90
+ }
91
+ return { every: "custom", time: "" };
92
+ }
93
+
94
+ /** The controls β†’ a cron string. `custom` keeps whatever the user typed, untouched. */
95
+ export function writeCron(every: string, time: string, custom: string): string {
96
+ if (every === "custom") return String(custom || "").trim();
97
+ const [h, m] = String(time || "06:00").split(":");
98
+ const hh = Math.min(23, Math.max(0, Number(h) || 0));
99
+ const mm = Math.min(59, Math.max(0, Number(m) || 0));
100
+ return every === "day" ? `${mm} ${hh} * * *` : `${mm} ${hh} * * ${Number(every) || 0}`;
101
+ }
102
+
103
+ /** The weekday options, in the order a week is read rather than in cron's 0-first order. */
104
+ export const WEEKDAYS: { value: string; label: string }[] = [
105
+ { value: "1", label: "Every Monday" },
106
+ { value: "2", label: "Every Tuesday" },
107
+ { value: "3", label: "Every Wednesday" },
108
+ { value: "4", label: "Every Thursday" },
109
+ { value: "5", label: "Every Friday" },
110
+ { value: "6", label: "Every Saturday" },
111
+ { value: "0", label: "Every Sunday" },
112
+ ];
web/src/customer-grid/CustomerGrid.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/RecordDetail.css CHANGED
@@ -492,7 +492,7 @@
492
  place-items: center;
493
  border-radius: 50%;
494
  object-fit: cover;
495
- font-size: 9px;
496
  font-weight: 700;
497
  letter-spacing: 0.01em;
498
  line-height: 1;
@@ -685,7 +685,7 @@
685
  border-radius: 50%;
686
  background: var(--lp-blue-tint);
687
  color: var(--lp-blue-solid);
688
- font-size: 10px;
689
  font-weight: 700;
690
  letter-spacing: 0.01em;
691
  }
@@ -713,7 +713,7 @@
713
  .cg-record-comment-meta time {
714
  flex: 0 0 auto;
715
  color: var(--lp-muted);
716
- font-size: 10px;
717
  }
718
 
719
  .cg-record-comment-delete {
@@ -799,7 +799,7 @@
799
 
800
  .cg-record-comment-compose-foot span {
801
  color: var(--lp-muted);
802
- font-size: 10px;
803
  }
804
 
805
  .cg-record-comment-compose-foot button {
 
492
  place-items: center;
493
  border-radius: 50%;
494
  object-fit: cover;
495
+ font-size: var(--lp-fs-4xs);
496
  font-weight: 700;
497
  letter-spacing: 0.01em;
498
  line-height: 1;
 
685
  border-radius: 50%;
686
  background: var(--lp-blue-tint);
687
  color: var(--lp-blue-solid);
688
+ font-size: var(--lp-fs-4xs);
689
  font-weight: 700;
690
  letter-spacing: 0.01em;
691
  }
 
713
  .cg-record-comment-meta time {
714
  flex: 0 0 auto;
715
  color: var(--lp-muted);
716
+ font-size: var(--lp-fs-4xs);
717
  }
718
 
719
  .cg-record-comment-delete {
 
799
 
800
  .cg-record-comment-compose-foot span {
801
  color: var(--lp-muted);
802
+ font-size: var(--lp-fs-4xs);
803
  }
804
 
805
  .cg-record-comment-compose-foot button {
web/src/customer-grid/SelectFromFile.tsx ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / SelectFromFile.tsx β€” WAVE 21 item 11 (R10, contract C5).
3
+ //
4
+ // "Select from file…": paste a list or upload a sheet, say which column holds
5
+ // the names, and the grid ticks those records.
6
+ //
7
+ // The dialog decides NOTHING. Parsing a paste, matching, and the three-bucket
8
+ // result all live in `fileSelect.ts` where a gate runs them under node; this is
9
+ // the renderer and the file-picker chrome around them.
10
+ // ---------------------------------------------------------------------------
11
+
12
+ import { useMemo, useRef, useState } from "react";
13
+ import { uploadTabular } from "./apiBridge";
14
+ import type { TabularUpload } from "./apiBridge";
15
+ import { matchRowsByValue, matchSummary, parsePastedList } from "./fileSelect";
16
+ import type { MatchResult, MatchRow } from "./fileSelect";
17
+ import type { Field } from "./types";
18
+
19
+ /** The kinds a name can plausibly live in. A rating or a checkbox column is not
20
+ * something anyone pastes a list of, and offering all 27 field types makes the
21
+ * useful three hard to find. */
22
+ const MATCHABLE = new Set([
23
+ "text", "longtext", "select", "multiselect", "email", "url", "phone", "int",
24
+ "currency", "number", "date", "user", "automation", "formula",
25
+ ]);
26
+
27
+ export interface SelectFromFileProps {
28
+ /** Columns the user may match ON β€” the grid's fields, in grid order. */
29
+ fields: Field[];
30
+ /** The identity column: the default grid column, and the one that makes this
31
+ * feature obvious ("paste customer names"). */
32
+ primaryKey: string;
33
+ /** ⚠ The rows the VIEW MATCHED β€” never the painted slice. See fileSelect.ts. */
34
+ inView: MatchRow[];
35
+ /** Every row in this table, for the "in the table but not in this view" bucket. */
36
+ wholeTable: MatchRow[];
37
+ /** The view being selected in, named in the dialog so the counts have a subject. */
38
+ viewName: string;
39
+ onSelect: (pids: number[]) => void;
40
+ onClose: () => void;
41
+ }
42
+
43
+ export default function SelectFromFile({
44
+ fields,
45
+ primaryKey,
46
+ inView,
47
+ wholeTable,
48
+ viewName,
49
+ onSelect,
50
+ onClose,
51
+ }: SelectFromFileProps) {
52
+ const matchable = useMemo(
53
+ () => fields.filter((f) => MATCHABLE.has(f.type) || f.key === primaryKey),
54
+ [fields, primaryKey]
55
+ );
56
+ const [gridKey, setGridKey] = useState(primaryKey);
57
+ const [paste, setPaste] = useState("");
58
+ const [upload, setUpload] = useState<TabularUpload | null>(null);
59
+ const [fileName, setFileName] = useState("");
60
+ const [fileCol, setFileCol] = useState("");
61
+ const [busy, setBusy] = useState(false);
62
+ const [result, setResult] = useState<MatchResult | null>(null);
63
+ const fileRef = useRef<HTMLInputElement>(null);
64
+
65
+ const pasted = useMemo(() => parsePastedList(paste), [paste]);
66
+ // The upload wins when there is one: the user picked a file most recently, and
67
+ // a dialog that matched a stale paste behind an uploaded sheet would be
68
+ // answering a question nobody asked.
69
+ const values = upload ? upload.values[fileCol] ?? [] : pasted.values;
70
+ const canRun = values.length > 0 && !!gridKey;
71
+
72
+ const run = () => {
73
+ const r = matchRowsByValue(values, gridKey, inView, wholeTable);
74
+ setResult(r);
75
+ onSelect(r.pids);
76
+ };
77
+
78
+ const takeFile = async (file: File | undefined) => {
79
+ if (!file) return;
80
+ setBusy(true);
81
+ setResult(null);
82
+ const parsed = await uploadTabular(file);
83
+ setBusy(false);
84
+ if (!parsed) return; // the bridge has already said why
85
+ setUpload(parsed);
86
+ setFileName(file.name);
87
+ setFileCol(parsed.columns[0] ?? "");
88
+ setPaste("");
89
+ };
90
+
91
+ /** The misses, ready to paste back into whatever the list came from. Every
92
+ * value, never a "…and 40 more" β€” the whole point of listing them is that the
93
+ * user has to go and fix them. */
94
+ const copyList = (list: string[]) => {
95
+ void navigator.clipboard?.writeText(list.join("\n"));
96
+ };
97
+
98
+ return (
99
+ <div className="cg-cat-modal-wrap" role="dialog" aria-modal="true"
100
+ aria-label="Select records from a file">
101
+ <div className="cg-cat-modal cg-sff">
102
+ <h3>Select records from a list</h3>
103
+ <p>
104
+ Paste a list or upload a sheet, and the matching records in{" "}
105
+ <strong>{viewName}</strong> are ticked. Values are compared exactly, ignoring
106
+ case and surrounding spaces.
107
+ </p>
108
+
109
+ <div className="cg-sff-row">
110
+ <label className="cg-sff-label" htmlFor="cg-sff-paste">Paste a list</label>
111
+ <textarea
112
+ id="cg-sff-paste"
113
+ className="cg-sff-area"
114
+ value={paste}
115
+ placeholder={"One value per line"}
116
+ onChange={(e) => {
117
+ setPaste(e.target.value);
118
+ setUpload(null);
119
+ setFileName("");
120
+ setResult(null);
121
+ }}
122
+ />
123
+ </div>
124
+
125
+ <div className="cg-sff-row">
126
+ <span className="cg-sff-label">…or upload</span>
127
+ <div className="cg-sff-file">
128
+ <input
129
+ ref={fileRef}
130
+ type="file"
131
+ accept=".xlsx,.csv"
132
+ className="cg-sff-input"
133
+ onChange={(e) => void takeFile(e.target.files?.[0])}
134
+ />
135
+ {fileName ? <span className="cg-sff-note">{fileName}</span> : null}
136
+ {busy ? <span className="cg-sff-note">Reading…</span> : null}
137
+ </div>
138
+ </div>
139
+
140
+ {/* The column pair. The file side exists only for an upload β€” a pasted
141
+ list IS one column, and a picker offering one option is furniture. */}
142
+ <div className="cg-sff-pair">
143
+ {upload ? (
144
+ <label className="cg-sff-pick">
145
+ <span className="cg-sff-label">Column in the file</span>
146
+ <select
147
+ className="cg-input"
148
+ value={fileCol}
149
+ onChange={(e) => {
150
+ setFileCol(e.target.value);
151
+ setResult(null);
152
+ }}
153
+ >
154
+ {upload.columns.map((c) => (
155
+ <option key={c} value={c}>{c}</option>
156
+ ))}
157
+ </select>
158
+ </label>
159
+ ) : null}
160
+ <label className="cg-sff-pick">
161
+ <span className="cg-sff-label">Column in the grid</span>
162
+ <select
163
+ className="cg-input"
164
+ value={gridKey}
165
+ onChange={(e) => {
166
+ setGridKey(e.target.value);
167
+ setResult(null);
168
+ }}
169
+ >
170
+ {matchable.map((f) => (
171
+ <option key={f.key} value={f.key}>{f.label}</option>
172
+ ))}
173
+ </select>
174
+ </label>
175
+ </div>
176
+
177
+ {/* ── every disclosure the inputs owe, before the button ─────────────── */}
178
+ {upload?.truncated ? (
179
+ <p className="cg-sff-warn">
180
+ This file is longer than the {(20000).toLocaleString()}-value limit β€” only the
181
+ first {(20000).toLocaleString()} values in each column were read. Anything past
182
+ that is not being matched.
183
+ </p>
184
+ ) : null}
185
+ {!upload && pasted.extraColumns ? (
186
+ <p className="cg-sff-warn">
187
+ The pasted text has more than one column β€” only the first is being matched.
188
+ </p>
189
+ ) : null}
190
+ {!upload && pasted.blanks > 0 ? (
191
+ <p className="cg-sff-note">
192
+ {pasted.blanks.toLocaleString()} empty line{pasted.blanks === 1 ? "" : "s"} skipped.
193
+ </p>
194
+ ) : null}
195
+ {values.length > 0 ? (
196
+ <p className="cg-sff-note">
197
+ {values.length.toLocaleString()} value{values.length === 1 ? "" : "s"} to match.
198
+ </p>
199
+ ) : null}
200
+
201
+ {result ? (
202
+ <div className="cg-sff-result">
203
+ <strong>{matchSummary(result)}</strong>
204
+ {result.outsideView.length ? (
205
+ <div className="cg-sff-misses">
206
+ <span>
207
+ In this table, but not shown by <strong>{viewName}</strong> β€” clear the
208
+ view&rsquo;s filters to reach them:
209
+ </span>
210
+ <textarea readOnly className="cg-sff-area cg-sff-missarea"
211
+ value={result.outsideView.join("\n")} />
212
+ <button type="button" className="cg-btn"
213
+ onClick={() => copyList(result.outsideView)}>
214
+ Copy these
215
+ </button>
216
+ </div>
217
+ ) : null}
218
+ {result.missing.length ? (
219
+ <div className="cg-sff-misses">
220
+ <span>Not found in this table at all:</span>
221
+ <textarea readOnly className="cg-sff-area cg-sff-missarea"
222
+ value={result.missing.join("\n")} />
223
+ <button type="button" className="cg-btn"
224
+ onClick={() => copyList(result.missing)}>
225
+ Copy these
226
+ </button>
227
+ </div>
228
+ ) : null}
229
+ </div>
230
+ ) : null}
231
+
232
+ <div className="cg-sff-actions">
233
+ <button type="button" className="cg-btn cg-btn--primary" disabled={!canRun || busy}
234
+ onClick={run}>
235
+ {result ? "Select again" : "Select"}
236
+ </button>
237
+ <button type="button" className="cg-btn" onClick={onClose}>
238
+ {result ? "Done" : "Cancel"}
239
+ </button>
240
+ </div>
241
+ </div>
242
+ </div>
243
+ );
244
+ }
web/src/customer-grid/ViewSidebar.tsx CHANGED
@@ -37,14 +37,13 @@ import {
37
  MODE_TONE,
38
  } from "./iconShapes";
39
  import { FolderMark, LockMark, MenuLabel, ModeIcon, ToneModeIcon } from "./icons";
40
- import { groupByFolder, reorderFolderIds } from "./folders";
41
 
42
- /**
43
- * WAVE 20 item 18 (C-SHARE) β€” the system folder every view shared WITH you lands in
44
- * until you file it somewhere of your own. The id is the CONTRACT's, not this file's
45
- * invention, and it is the only folder id this component ever recognises by name.
46
- */
47
- const SHARED_FOLDER_ID = "__shared__";
48
 
49
  interface ViewSidebarProps {
50
  views: SavedView[];
@@ -66,6 +65,16 @@ interface ViewSidebarProps {
66
  /** Add the customers THIS view currently matches to a cohort. `cohortId` empty = create one
67
  * called `name`. The view need not be the active one β€” the caller re-runs the engine for it. */
68
  onAddToList?: (viewId: string, cohortId: string, name: string) => void;
 
 
 
 
 
 
 
 
 
 
69
  /**
70
  * Item 12 (contract C-LOCK) β€” lock a view to a cohort, or `null` to unlock.
71
  *
@@ -158,6 +167,7 @@ export default function ViewSidebar({
158
  onDelete,
159
  lists = [],
160
  onAddToList,
 
161
  onCohortLock,
162
  today,
163
  onExport,
@@ -305,7 +315,17 @@ export default function ViewSidebar({
305
  const groups = groupByFolder(
306
  shownViews,
307
  foldersOn ? (folders as GridFolder[]) : [],
308
- (v) => (folderIdOf ? folderIdOf(v.id) : null)
 
 
 
 
 
 
 
 
 
 
309
  );
310
  const folderMenuF = folderMenu ? folders?.find((f) => f.id === folderMenu.id) : undefined;
311
  const addPreview = addTarget && folderAddPreview ? folderAddPreview(addTarget) : null;
@@ -813,6 +833,18 @@ export default function ViewSidebar({
813
  // Item 9 β€” while a search is live, a folder with no matches is noise, not a target.
814
  if (viewNeedle && group.folder && group.items.length === 0) return null;
815
  const isRoot = gid === null;
 
 
 
 
 
 
 
 
 
 
 
 
816
  const shut = gid != null && collapsed.has(gid);
817
  return (
818
  <div
@@ -836,7 +868,9 @@ export default function ViewSidebar({
836
  // tell: two conditions written minutes apart, one guarded and one not.
837
  (foldDrag !== null && foldDrag === gid ? " is-folddrag" : "")
838
  }
839
- {...dropHandlers(gid)}
 
 
840
  >
841
  {group.folder && (
842
  <div
@@ -845,7 +879,7 @@ export default function ViewSidebar({
845
  // Draggable only while it is renameable-idle: a `draggable` ancestor eats
846
  // the text selection inside an input, so dragging would win over editing
847
  // the name you just opened.
848
- draggable={foldsReorderable && renamingFolder !== group.folder.id}
849
  onDragStart={(e) => {
850
  e.dataTransfer.setData(FOLD_DRAG_TYPE, group.folder!.id);
851
  e.dataTransfer.effectAllowed = "move";
@@ -1041,16 +1075,29 @@ export default function ViewSidebar({
1041
  view someone shared with you is one you can be looking at without
1042
  having made it β€” the single most useful thing the rail can tell you
1043
  before the click.
1044
- ⚠ `shared` is not on `SavedView` yet (S3, amendment A-S4-4). Read
1045
- through ONE narrowed cast, here, rather than loosening the type
1046
- everywhere: an absent flag reads as false, which is exactly right
1047
- until the server projects it. */}
1048
- {(view as { shared?: boolean }).shared ? (
 
 
1049
  <span
1050
  className="cg-view-shared"
1051
  role="img"
1052
- aria-label={`${view.name}, shared with you`}
1053
- title="Shared with you β€” someone gave you access to this view."
 
 
 
 
 
 
 
 
 
 
 
1054
  >
1055
  <svg width="13" height="13" viewBox="0 0 16 16" aria-hidden>
1056
  <circle cx="5.6" cy="5.6" r="2.2" fill="none" stroke="currentColor"
@@ -1487,6 +1534,29 @@ export default function ViewSidebar({
1487
  >
1488
  <MenuLabel icon="cohortAdd" text="Alert me about new records…" />
1489
  </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1490
  {onAddToList && (
1491
  <button
1492
  type="button"
 
37
  MODE_TONE,
38
  } from "./iconShapes";
39
  import { FolderMark, LockMark, MenuLabel, ModeIcon, ToneModeIcon } from "./icons";
40
+ import { SHARED_FOLDER_ID, groupByFolder, reorderFolderIds } from "./folders";
41
 
42
+ /* WAVE 20 item 18 (C-SHARE) β€” the system folder every view shared WITH you lands in until
43
+ you file it somewhere of your own. It is the only folder id this component recognises by
44
+ name, and as of wave 21 (item 9) it is DECLARED IN `folders.ts` beside the synthesis that
45
+ produces it β€” a component-local copy of a contract id is a copy that can drift from the
46
+ rule, and the rule is the half a gate can run. */
 
47
 
48
  interface ViewSidebarProps {
49
  views: SavedView[];
 
65
  /** Add the customers THIS view currently matches to a cohort. `cohortId` empty = create one
66
  * called `name`. The view need not be the active one β€” the caller re-runs the engine for it. */
67
  onAddToList?: (viewId: string, cohortId: string, name: string) => void;
68
+ /**
69
+ * ⭐ WAVE 21 item 11 (ruling R10) β€” open "Select from file…" for the ACTIVE view.
70
+ *
71
+ * β›” NO ARGUMENTS, and that is the contract rather than an omission. The dialog matches
72
+ * over the rows the GRID holds, which are the active view's; passing a view id here
73
+ * would invite a caller to match one view's list against another's rows and report the
74
+ * difference as missing records. The menu switches views first (see its own note) so
75
+ * this can stay a verb with one subject.
76
+ */
77
+ onSelectFromFile?: () => void;
78
  /**
79
  * Item 12 (contract C-LOCK) β€” lock a view to a cohort, or `null` to unlock.
80
  *
 
167
  onDelete,
168
  lists = [],
169
  onAddToList,
170
+ onSelectFromFile,
171
  onCohortLock,
172
  today,
173
  onExport,
 
315
  const groups = groupByFolder(
316
  shownViews,
317
  foldersOn ? (folders as GridFolder[]) : [],
318
+ (v) => (folderIdOf ? folderIdOf(v.id) : null),
319
+ /**
320
+ * ⭐ WAVE 21 item 9 (R12 / contract C1) β€” THE CONSUMER of `shared`.
321
+ *
322
+ * The wire marks each granted view `shared: true` (C1); this is where that mark becomes
323
+ * a place on screen. Passed unconditionally β€” NOT gated on `foldersOn` β€” because the
324
+ * folder machinery is an opt-in feature of the views rail and "who shared this with me"
325
+ * is not: a surface with folders switched off must still be able to show you somebody
326
+ * else's view under a heading that says whose it is.
327
+ */
328
+ (v) => v.shared === true
329
  );
330
  const folderMenuF = folderMenu ? folders?.find((f) => f.id === folderMenu.id) : undefined;
331
  const addPreview = addTarget && folderAddPreview ? folderAddPreview(addTarget) : null;
 
833
  // Item 9 β€” while a search is live, a folder with no matches is noise, not a target.
834
  if (viewNeedle && group.folder && group.items.length === 0) return null;
835
  const isRoot = gid === null;
836
+ /**
837
+ * ⭐ WAVE 21 item 9 (R12/C1) β€” "Shared with me" IS NOT A STORED FOLDER, and every
838
+ * folder affordance below has to know it.
839
+ *
840
+ * The group is synthesised from `shared: true` views (`folders.ts`), so there is no
841
+ * record behind it: a drop would emit `item_move(viewId, "__shared__")` and persist
842
+ * a folderId naming a folder that does not exist, and a folder-drag would send an
843
+ * order containing an id `reorderFolderIds` was never given. Both write nonsense the
844
+ * server would store. The row menu was already suppressed for this id in wave 20;
845
+ * the DRAG surfaces were not, because nothing ever constructed the group.
846
+ */
847
+ const isSynthetic = gid === SHARED_FOLDER_ID;
848
  const shut = gid != null && collapsed.has(gid);
849
  return (
850
  <div
 
868
  // tell: two conditions written minutes apart, one guarded and one not.
869
  (foldDrag !== null && foldDrag === gid ? " is-folddrag" : "")
870
  }
871
+ {/* No drop handlers on the synthetic group β€” see `isSynthetic`. Spreading `{}`
872
+ rather than branching the element keeps ONE render path for every group. */
873
+ ...(isSynthetic ? {} : dropHandlers(gid))}
874
  >
875
  {group.folder && (
876
  <div
 
879
  // Draggable only while it is renameable-idle: a `draggable` ancestor eats
880
  // the text selection inside an input, so dragging would win over editing
881
  // the name you just opened.
882
+ draggable={foldsReorderable && !isSynthetic && renamingFolder !== group.folder.id}
883
  onDragStart={(e) => {
884
  e.dataTransfer.setData(FOLD_DRAG_TYPE, group.folder!.id);
885
  e.dataTransfer.effectAllowed = "move";
 
1075
  view someone shared with you is one you can be looking at without
1076
  having made it β€” the single most useful thing the rail can tell you
1077
  before the click.
1078
+ ⚠ WAVE 21 (item 9, R12/C1): the narrowed cast this used to need is
1079
+ gone β€” `shared`, `sharedRole` and `owner` are declared on `SavedView`
1080
+ and the server now projects them. The mark also says WHICH GRANT: a
1081
+ read-only share and an editable one look identical in the rail
1082
+ otherwise, and the reader's first question on finding a menu with no
1083
+ Rename in it is why. */}
1084
+ {view.shared ? (
1085
  <span
1086
  className="cg-view-shared"
1087
  role="img"
1088
+ aria-label={
1089
+ view.owner
1090
+ ? `${view.name}, shared with you by ${view.owner}`
1091
+ : `${view.name}, shared with you`
1092
+ }
1093
+ title={
1094
+ (view.owner
1095
+ ? `Shared with you by ${view.owner}.`
1096
+ : "Shared with you β€” someone gave you access to this view.") +
1097
+ (view.sharedRole === "edit"
1098
+ ? " You can edit it."
1099
+ : " You can view it, not change it.")
1100
+ }
1101
  >
1102
  <svg width="13" height="13" viewBox="0 0 16 16" aria-hidden>
1103
  <circle cx="5.6" cy="5.6" r="2.2" fill="none" stroke="currentColor"
 
1534
  >
1535
  <MenuLabel icon="cohortAdd" text="Alert me about new records…" />
1536
  </button>
1537
+ {/* ⭐ WAVE 21 item 11 (ruling R10) β€” "paste a list of names and tick those
1538
+ records". It belongs in the VIEW's menu because the view is what decides
1539
+ which records are on the table to be found, and the result says so.
1540
+
1541
+ ⚠ IT SELECTS THE VIEW FIRST when this is not the active one. The dialog
1542
+ matches over the rows the grid currently holds, so offering it on a view
1543
+ nobody is looking at would tick records in a DIFFERENT view's row set and
1544
+ report misses against the wrong table. Switching first makes the menu's
1545
+ subject and the dialog's subject the same object β€” and it is what clicking
1546
+ the row would have done anyway. */}
1547
+ {onSelectFromFile && (
1548
+ <button
1549
+ type="button"
1550
+ role="menuitem"
1551
+ onClick={() => {
1552
+ if (menuView.id !== activeViewId) onSelect(menuView.id);
1553
+ onSelectFromFile();
1554
+ setMenu(null);
1555
+ }}
1556
+ >
1557
+ <MenuLabel icon="cohortAdd" text="Select from file…" />
1558
+ </button>
1559
+ )}
1560
  {onAddToList && (
1561
  <button
1562
  type="button"
web/src/customer-grid/apiBridge.ts CHANGED
@@ -52,7 +52,7 @@ import {
52
  } from "../apiContract";
53
  import { setStandaloneSink } from "./hostBridge";
54
  import { CUSTOMER_TOPIC } from "./types";
55
- import type { CustomersPayload, GridWorkspace, HostEvent, Row, TopicConfig } from "./types";
56
  import type { TsPayload, TsRequest } from "./timeSeriesData";
57
 
58
  const JSON_HEADERS = { "Content-Type": "application/json" };
@@ -154,27 +154,63 @@ export function fetchCustomers(): Promise<CustomersPayload | null> {
154
  * The body is `{workspace: GridWorkspace}` β€” the client's own built type
155
  * (types.ts `GridWorkspace`), which is what the embed's host already projects.
156
  *
157
- * ⚠ ABSENT IS FINE AND MEANS TODAY'S BEHAVIOUR. A 404 (route not shipped),
158
- * a 500, or an unreadable body all return null and the grid runs exactly as it
159
- * does now β€” views in memory, no `storageKey`, nothing durable. It degrades to
160
- * the honest gap rather than failing the whole read, because the workspace is
161
- * an enhancement of the table, not a precondition for it. A 401 still ends the
162
  * session: that is the one status that is never about this route.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  */
164
  export async function fetchWorkspace(
165
  scope: SurfaceScope = "customer",
 
166
  ): Promise<GridWorkspace | null> {
 
 
167
  try {
168
- const res = await fetch(`${API_V1}/workspace?scope=${encodeURIComponent(scope)}`,
169
- { credentials: CREDENTIALS });
170
- if (handledUnauthorized(res.status)) return null;
171
- if (!res.ok) return null;
172
- const ws = (await readJson(res)) as { workspace?: GridWorkspace } | null;
173
- const w = ws?.workspace;
174
- return w && typeof w.storageKey === "string" && Array.isArray(w.views) ? w : null;
175
  } catch {
 
 
 
 
 
 
 
 
 
 
 
176
  return null;
177
  }
 
 
 
 
 
178
  }
179
 
180
  /**
@@ -273,6 +309,144 @@ export async function addTableRow(
273
  }
274
  }
275
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
  /** C-UNDO's other half: drop a row this session just added. Same cache rule as the append. */
277
  export async function deleteTableRow(
278
  tableKey: string,
 
52
  } from "../apiContract";
53
  import { setStandaloneSink } from "./hostBridge";
54
  import { CUSTOMER_TOPIC } from "./types";
55
+ import type { CustomersPayload, Field, GridWorkspace, HostEvent, Row, TopicConfig } from "./types";
56
  import type { TsPayload, TsRequest } from "./timeSeriesData";
57
 
58
  const JSON_HEADERS = { "Content-Type": "application/json" };
 
154
  * The body is `{workspace: GridWorkspace}` β€” the client's own built type
155
  * (types.ts `GridWorkspace`), which is what the embed's host already projects.
156
  *
157
+ * ⚠ ABSENT IS FINE AND MEANS TODAY'S BEHAVIOUR. A 404 (route not shipped) or a
158
+ * body carrying no workspace return null and the grid runs exactly as it does
159
+ * now β€” views in memory, no `storageKey`, nothing durable. It degrades to the
160
+ * honest gap rather than failing the whole read, because the workspace is an
161
+ * enhancement of the table, not a precondition for it. A 401 still ends the
162
  * session: that is the one status that is never about this route.
163
+ *
164
+ * β›” WAVE 21 item 3 (3c) β€” BUT A REFUSAL IS NOT AN ABSENCE, and conflating the
165
+ * two is half of the "RI fields on a new database" report.
166
+ *
167
+ * This used to answer `null` to every unhappy path alike: route-not-shipped,
168
+ * 403, 500, connection refused, garbage body. The caller cannot tell those
169
+ * apart, so it did the only thing it could β€” carried on without a workspace β€”
170
+ * and `CustomerGrid` then had no `storageKey` and fell back to a bucket shared
171
+ * with every other surface (see the note at its `storageKey`). A tenant whose
172
+ * `/workspace` 403s for `ut_*` therefore got ANOTHER TABLE'S views and fields,
173
+ * silently, with the grid looking entirely healthy.
174
+ *
175
+ * `announceFailure` is the caller saying "I am the INITIAL load; if this fails
176
+ * for a reason that is not 'no workspace here', say so". It raises the same
177
+ * `DATA_ERROR_EVENT` a failed rows read raises, so the frame renders its honest
178
+ * failure card instead of a grid furnished with somebody else's schema.
179
+ *
180
+ * ⚠ IT IS OFF BY DEFAULT, and that is load-bearing rather than cautious.
181
+ * `reread()` calls this on every workspace-stale signal, and its own rule is
182
+ * "absent stays absent β€” never blank a live panel"; a signal from there would
183
+ * let one dropped packet replace a working table with an error card. The flag
184
+ * is passed explicitly at the one call site that owns the first paint.
185
  */
186
  export async function fetchWorkspace(
187
  scope: SurfaceScope = "customer",
188
+ opts: { announceFailure?: boolean } = {},
189
  ): Promise<GridWorkspace | null> {
190
+ const loud = opts.announceFailure === true;
191
+ let res: Response;
192
  try {
193
+ res = await fetch(`${API_V1}/workspace?scope=${encodeURIComponent(scope)}`,
194
+ { credentials: CREDENTIALS });
 
 
 
 
 
195
  } catch {
196
+ if (loud) signal(DATA_ERROR_EVENT, "Cannot reach the server.");
197
+ return null;
198
+ }
199
+ if (handledUnauthorized(res.status)) return null;
200
+ if (!res.ok) {
201
+ // 404 is the ONE status that means "this host does not serve a workspace",
202
+ // which is the enhancement posture above and stays quiet. Everything else
203
+ // is a server that had an answer and would not give it.
204
+ if (loud && res.status !== 404)
205
+ signal(DATA_ERROR_EVENT,
206
+ `The server answered ${res.status} for this table's saved views and columns.`);
207
  return null;
208
  }
209
+ const ws = (await readJson(res)) as { workspace?: GridWorkspace } | null;
210
+ const w = ws?.workspace;
211
+ // A 200 carrying no workspace is still an ABSENCE, not a refusal β€” an older
212
+ // host, or a scope this one has nothing stored for. Unchanged, and quiet.
213
+ return w && typeof w.storageKey === "string" && Array.isArray(w.views) ? w : null;
214
  }
215
 
216
  /**
 
309
  }
310
  }
311
 
312
+ /**
313
+ * ⭐ WAVE 21 item 7 (contract C2) β€” ADD A COLUMN TO A USER DATABASE'S **DEFINITION**,
314
+ * not to this user's overlay.
315
+ *
316
+ * β›” THE BUG THIS EXISTS FOR. Every column the grid creates has always gone out as a
317
+ * `field_upsert` EVENT, which lands in the per-user workspace stratum
318
+ * (`<key>_table_workspace`). That is right for the connector surfaces, where a custom
319
+ * column IS one person's annotation of somebody else's data. It is wrong for a user
320
+ * database, where the columns ARE the table β€” and it is why the automation editor's
321
+ * "Automation column" picker was empty by construction: that picker reads the DEFINITION
322
+ * (`user_tables`), which the grid had never written to. Two stores, one word, and the two
323
+ * surfaces disagreed with no error anywhere. The route has existed since wave 18 with no
324
+ * client caller; this is that caller, and `routes_tables.py`'s own comment above it names
325
+ * this exact defect.
326
+ *
327
+ * ⚠ SCOPED TO THE AUTOMATION KIND THIS WAVE (C2, deliberately narrow). Moving EVERY kind
328
+ * onto the definition is the right end state and is booked as debt: it changes who can see
329
+ * a column (everyone with the table, not just its author), which is a visible change to
330
+ * shipped behaviour on three surfaces and does not belong in a wave that is fixing this
331
+ * one's blindness.
332
+ *
333
+ * ⚠ THE SERVER'S FIELD IS THE ANSWER, never the request. `add_field` re-slugs and
334
+ * re-types on the way in, so the caller inserts what came BACK β€” a column ordered under a
335
+ * key the store does not hold is a column that renders nowhere.
336
+ */
337
+ export async function addTableField(
338
+ tableKey: string,
339
+ field: { key: string; label: string; type: string }
340
+ ): Promise<Field | null> {
341
+ try {
342
+ const res = await fetch(`${API_V1}/tables/${encodeURIComponent(tableKey)}/fields`, {
343
+ method: "POST",
344
+ credentials: CREDENTIALS,
345
+ headers: JSON_HEADERS,
346
+ body: JSON.stringify(field),
347
+ });
348
+ if (handledUnauthorized(res.status)) return null;
349
+ const body = (await readJson(res)) as
350
+ | { field?: Field; detail?: { message?: string } }
351
+ | null;
352
+ if (!res.ok) {
353
+ // The server states WHY β€” the column cap, an unknown type (this is the 400 to expect
354
+ // until `UT_FIELD_TYPES` learns `automation`, C2's other half), a wall refusal. Its
355
+ // sentence beats anything invented here.
356
+ const why = typeof body?.detail?.message === "string"
357
+ ? body.detail.message
358
+ : `The server answered ${res.status}.`;
359
+ signal(TOAST_EVENT, why);
360
+ return null;
361
+ }
362
+ const made = body?.field;
363
+ if (!made || typeof made.key !== "string") {
364
+ signal(DATA_ERROR_EVENT, "The server did not say which column it created.");
365
+ return null;
366
+ }
367
+ // The definition feeds BOTH payloads for a user table (`ut_assembly` builds the rows
368
+ // envelope and `/workspace` from the same `fields_base`), so the cached rows are now a
369
+ // schema behind. Cheap to drop, and a stale schema is not a stale number β€” it is a
370
+ // column that exists on the server and nowhere on screen.
371
+ rowsCache.delete(`tables/${tableKey}/rows`);
372
+ return made;
373
+ } catch {
374
+ signal(DATA_ERROR_EVENT, "Cannot reach the server.");
375
+ return null;
376
+ }
377
+ }
378
+
379
+ /**
380
+ * ⭐ WAVE 21 item 11 (ruling R10, contract C5) β€” parse an uploaded `.xlsx`/`.csv` and
381
+ * hand back its COLUMNS AND VALUES as strings.
382
+ *
383
+ * β›” THE FILE NEVER BECOMES DATA. This reads a spreadsheet to find out which records the
384
+ * user means; nothing here writes a row, creates a field, or keeps the file. The server
385
+ * parses (openpyxl is not a thing a browser has) and answers with strings β€” the matching
386
+ * itself is client-side, over rows this browser already holds (`fileSelect.ts`).
387
+ *
388
+ * ⚠ `truncated` IS THE CONTRACT'S POINT. C5 caps a column at 20k values, and a cap the
389
+ * caller cannot see is a silent wrong answer: a 30k-row file would report ten thousand
390
+ * records "not found" that are simply past the cap. The dialog surfaces this flag as its
391
+ * own sentence, never folded into the miss count ([[no-unverifiable-aggregates]]).
392
+ */
393
+ export interface TabularUpload {
394
+ columns: string[];
395
+ rows: number;
396
+ values: Record<string, string[]>;
397
+ truncated: boolean;
398
+ }
399
+
400
+ export async function uploadTabular(file: File): Promise<TabularUpload | null> {
401
+ const form = new FormData();
402
+ form.append("file", file);
403
+ try {
404
+ // ⚠ NO Content-Type HEADER. The browser must set it, because only the browser knows
405
+ // the multipart boundary it generated β€” writing `multipart/form-data` by hand omits
406
+ // the boundary and the server cannot parse the body at all.
407
+ const res = await fetch(`${API_V1}/uploads/tabular`, {
408
+ method: "POST",
409
+ credentials: CREDENTIALS,
410
+ body: form,
411
+ });
412
+ if (handledUnauthorized(res.status)) return null;
413
+ const body = (await readJson(res)) as
414
+ | { columns?: unknown; rows?: unknown; values?: unknown; truncated?: unknown;
415
+ detail?: { message?: string } }
416
+ | null;
417
+ if (!res.ok) {
418
+ const why = typeof body?.detail?.message === "string"
419
+ ? body.detail.message
420
+ : `The file could not be read (the server answered ${res.status}).`;
421
+ signal(TOAST_EVENT, why);
422
+ return null;
423
+ }
424
+ const columns = Array.isArray(body?.columns)
425
+ ? body.columns.filter((c): c is string => typeof c === "string")
426
+ : [];
427
+ const rawValues = (body?.values && typeof body.values === "object" ? body.values : {}) as
428
+ Record<string, unknown>;
429
+ const values: Record<string, string[]> = {};
430
+ for (const col of columns)
431
+ values[col] = Array.isArray(rawValues[col])
432
+ ? (rawValues[col] as unknown[]).map((v) => (v === null || v === undefined ? "" : String(v)))
433
+ : [];
434
+ if (!columns.length) {
435
+ signal(TOAST_EVENT, "That file has no readable columns.");
436
+ return null;
437
+ }
438
+ return {
439
+ columns,
440
+ rows: typeof body?.rows === "number" ? body.rows : 0,
441
+ values,
442
+ truncated: body?.truncated === true,
443
+ };
444
+ } catch {
445
+ signal(DATA_ERROR_EVENT, "Cannot reach the server.");
446
+ return null;
447
+ }
448
+ }
449
+
450
  /** C-UNDO's other half: drop a row this session just added. Same cache rule as the append. */
451
  export async function deleteTableRow(
452
  tableKey: string,
web/src/customer-grid/fileSelect.ts ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / fileSelect.ts β€” WAVE 21 item 11 (ruling R10, contract C5):
3
+ // "Select from file…", the PURE half.
4
+ //
5
+ // The owner's ask is small to describe and easy to get quietly wrong: paste or
6
+ // upload a list of names, and have the grid tick those records. Every way it
7
+ // fails is silent β€”
8
+ //
9
+ // Β· matching over the ROWS GLIDE HAS PAINTED rather than the rows the view
10
+ // matched. `displayRows` is a capped slice (`DISPLAY_PAGE`); a list of 900
11
+ // names would report ~200 selected and hundreds "not found", all of which
12
+ // exist. This module never sees the slice.
13
+ // Β· reporting a count without the misses. "812 selected" out of a 900-row
14
+ // file is a number nobody can act on; the 88 that did not match are the
15
+ // whole reason someone runs this ([[no-unverifiable-aggregates]]).
16
+ // Β· conflating "not in this view" with "not in this table". A filtered view
17
+ // turns half a correct file into apparent garbage, and the user goes
18
+ // looking for a data problem that is a filter.
19
+ //
20
+ // So this returns THREE buckets, not a count, and the dialog renders what it is
21
+ // given. React-free so `verify_grid_ux.py` can run it under node.
22
+ // ---------------------------------------------------------------------------
23
+
24
+ /** The one comparison rule (R10): trim, then casefold. Nothing else β€” no
25
+ * punctuation stripping, no number parsing, no fuzzy anything. A match a user
26
+ * cannot predict is worse than a miss they can see and fix. */
27
+ export function normalizeKey(value: unknown): string {
28
+ if (value === null || value === undefined) return "";
29
+ return String(value).trim().toLowerCase();
30
+ }
31
+
32
+ export interface PastedList {
33
+ /** The candidate values, in the order pasted, blanks dropped. */
34
+ values: string[];
35
+ /** How many lines were dropped for being empty. Reported, never hidden. */
36
+ blanks: number;
37
+ /**
38
+ * The paste carried MORE THAN ONE COLUMN (tab-separated) and only the first
39
+ * is being matched. Disclosed in the dialog β€” a range copied out of Excel is
40
+ * the common case, and silently reading one column of it is the kind of
41
+ * helpfulness that becomes a support question.
42
+ */
43
+ extraColumns: boolean;
44
+ }
45
+
46
+ /**
47
+ * Read a pasted list.
48
+ *
49
+ * ⚠ SPLIT ON NEWLINES AND TABS ONLY β€” never commas. "Acme, Inc." is a company
50
+ * name, and a comma split would turn one customer into two values, one of which
51
+ * can never match anything. A CSV file goes through the UPLOAD path, where the
52
+ * server parses it properly (C5).
53
+ */
54
+ export function parsePastedList(text: string): PastedList {
55
+ const lines = String(text ?? "").split(/\r?\n/);
56
+ const values: string[] = [];
57
+ let blanks = 0;
58
+ let extraColumns = false;
59
+ for (const line of lines) {
60
+ const cells = line.split("\t");
61
+ if (cells.length > 1 && cells.slice(1).some((c) => c.trim() !== "")) extraColumns = true;
62
+ const first = (cells[0] ?? "").trim();
63
+ if (!first) {
64
+ // A trailing newline is not a blank the user needs told about; a gap in
65
+ // the middle of a pasted column is. Both are counted the same way here
66
+ // and the dialog only mentions the total when it is non-zero.
67
+ if (line.trim() === "" && cells.length === 1) blanks += 1;
68
+ else blanks += 1;
69
+ continue;
70
+ }
71
+ values.push(first);
72
+ }
73
+ // The trailing newline every "copy a column" produces would otherwise report
74
+ // one phantom blank on every paste.
75
+ if (blanks > 0 && text.endsWith("\n")) blanks -= 1;
76
+ return { values, blanks, extraColumns };
77
+ }
78
+
79
+ /** The minimum a row must look like for this module. */
80
+ export interface MatchRow {
81
+ pid: number;
82
+ [key: string]: unknown;
83
+ }
84
+
85
+ export interface MatchResult {
86
+ /** Records to tick, de-duplicated, in the order the file named them. */
87
+ pids: number[];
88
+ /** File values that matched at least one row IN THE VIEW. */
89
+ matched: string[];
90
+ /**
91
+ * File values that name a record in this TABLE that the current view does not
92
+ * show. A filter, not a data problem β€” and the difference is the single most
93
+ * useful thing this result carries.
94
+ */
95
+ outsideView: string[];
96
+ /** File values with no record anywhere in this table. */
97
+ missing: string[];
98
+ /** File values that appeared more than once in the file. */
99
+ duplicates: number;
100
+ /**
101
+ * Values matching MORE THAN ONE record. All of them are selected (dropping
102
+ * the ambiguity would be a silent cap), and the count is disclosed so
103
+ * "40 values, 47 selected" is explained rather than mysterious.
104
+ */
105
+ ambiguous: number;
106
+ }
107
+
108
+ /**
109
+ * Match `values` against `columnKey` over the rows the view matched, with the
110
+ * whole table as the second opinion.
111
+ *
112
+ * ⚠ `inView` MUST be the full matched set (`visibleRows`), never the painted
113
+ * slice (`displayRows`). Passing the slice compiles, runs, and lies.
114
+ */
115
+ export function matchRowsByValue(
116
+ values: string[],
117
+ columnKey: string,
118
+ inView: MatchRow[],
119
+ wholeTable: MatchRow[]
120
+ ): MatchResult {
121
+ const index = new Map<string, number[]>();
122
+ for (const row of inView) {
123
+ const k = normalizeKey(row[columnKey]);
124
+ if (!k) continue;
125
+ const at = index.get(k);
126
+ if (at) at.push(row.pid);
127
+ else index.set(k, [row.pid]);
128
+ }
129
+ const elsewhere = new Set<string>();
130
+ for (const row of wholeTable) {
131
+ const k = normalizeKey(row[columnKey]);
132
+ if (k && !index.has(k)) elsewhere.add(k);
133
+ }
134
+
135
+ const pids: number[] = [];
136
+ const seenPid = new Set<number>();
137
+ const matched: string[] = [];
138
+ const outsideView: string[] = [];
139
+ const missing: string[] = [];
140
+ const seenValue = new Set<string>();
141
+ let duplicates = 0;
142
+ let ambiguous = 0;
143
+
144
+ for (const raw of values) {
145
+ const k = normalizeKey(raw);
146
+ if (!k) continue;
147
+ if (seenValue.has(k)) {
148
+ duplicates += 1;
149
+ continue;
150
+ }
151
+ seenValue.add(k);
152
+ const hits = index.get(k);
153
+ if (hits) {
154
+ matched.push(raw);
155
+ if (hits.length > 1) ambiguous += 1;
156
+ for (const pid of hits)
157
+ if (!seenPid.has(pid)) {
158
+ seenPid.add(pid);
159
+ pids.push(pid);
160
+ }
161
+ } else if (elsewhere.has(k)) {
162
+ outsideView.push(raw);
163
+ } else {
164
+ missing.push(raw);
165
+ }
166
+ }
167
+ return { pids, matched, outsideView, missing, duplicates, ambiguous };
168
+ }
169
+
170
+ /**
171
+ * The result, in one sentence β€” R10's "N selected Β· M not found", with the two
172
+ * facts that ruling could not have anticipated folded in only when they are
173
+ * non-zero (a sentence that always recites five clauses is one nobody reads).
174
+ */
175
+ export function matchSummary(r: MatchResult): string {
176
+ const parts = [`${r.pids.length.toLocaleString()} selected`];
177
+ if (r.outsideView.length)
178
+ parts.push(`${r.outsideView.length.toLocaleString()} not in this view`);
179
+ if (r.missing.length) parts.push(`${r.missing.length.toLocaleString()} not found`);
180
+ if (r.duplicates) parts.push(`${r.duplicates.toLocaleString()} repeated in the file`);
181
+ if (r.ambiguous)
182
+ parts.push(`${r.ambiguous.toLocaleString()} matched more than one record`);
183
+ return parts.join(" Β· ");
184
+ }
web/src/customer-grid/folders.ts CHANGED
@@ -167,28 +167,66 @@ export interface FolderGroup<T> {
167
  items: T[];
168
  }
169
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  /**
171
  * Group items into folders + a root bucket, in folder order, root LAST.
172
  *
173
  * Root last because the rails are read top-down and folders are the structure
174
  * the user made; ungrouped items are the leftovers. Every item appears exactly
175
  * once β€” a grouping that can drop an item would make a view look deleted.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  */
177
  export function groupByFolder<T>(
178
  items: T[],
179
  folders: GridFolder[],
180
- folderIdOf: (item: T) => string | null
 
181
  ): FolderGroup<T>[] {
182
  const buckets = new Map<string, T[]>(folders.map((f) => [f.id, []]));
183
  const root: T[] = [];
 
184
  for (const item of items) {
185
  const id = folderIdOf(item);
186
  const bucket = id == null ? undefined : buckets.get(id);
187
  if (bucket) bucket.push(item);
 
188
  else root.push(item);
189
  }
190
  const out: FolderGroup<T>[] = folders.map((f) => ({ folder: f, items: buckets.get(f.id) ?? [] }));
191
  out.push({ folder: null, items: root });
 
 
192
  return out;
193
  }
194
 
 
167
  items: T[];
168
  }
169
 
170
+ /**
171
+ * WAVE 20 item 18 / WAVE 21 item 9 (ruling R12, contract C1) β€” the SYNTHETIC folder
172
+ * that every view shared WITH you appears under.
173
+ *
174
+ * β›” IT IS NOT A STORED FOLDER, and nothing may ever write one with this id. It has no
175
+ * record in `folders`, no `order`, no icon, and the rail refuses every action on it
176
+ * (`ViewSidebar` suppresses the row menu for exactly this id): it cannot be renamed into
177
+ * something else, duplicated into a second copy of other people's work, or deleted. It is a
178
+ * READING of the view list β€” "these arrived by grant" β€” rendered as a group because that is
179
+ * the only shape this rail has for "a set of views with something in common".
180
+ *
181
+ * Declared HERE rather than in the component (where it lived through wave 20) so the
182
+ * synthesis below is pure, and `verify_folders.py` can run it under node like every other
183
+ * rule in this file. A constant a gate cannot reach is a contract nobody checks.
184
+ */
185
+ export const SHARED_FOLDER_ID = "__shared__";
186
+ export const SHARED_FOLDER_NAME = "Shared with me";
187
+
188
  /**
189
  * Group items into folders + a root bucket, in folder order, root LAST.
190
  *
191
  * Root last because the rails are read top-down and folders are the structure
192
  * the user made; ungrouped items are the leftovers. Every item appears exactly
193
  * once β€” a grouping that can drop an item would make a view look deleted.
194
+ *
195
+ * ⭐ WAVE 21 item 9 (R12/C1) β€” `isShared` adds the synthetic "Shared with me" group,
196
+ * AFTER root, and three things about it are deliberate:
197
+ *
198
+ * Β· **After root, not before it.** C1 says LAST in as many words. It reads correctly
199
+ * too: the rail is "my folders, my loose views, and then other people's".
200
+ * Β· **A shared view the receiver has FILED still goes to their folder.** The `__shared__`
201
+ * group is where a grant LANDS, not a cage it stays in β€” the rail's own note calls
202
+ * moving out "per-receiver placement" and that must keep working. So the synthetic
203
+ * group collects only the shared views that resolved to ROOT.
204
+ * Β· **An empty group does not render.** A folder head with nothing under it says "here is
205
+ * something you cannot reach" β€” the same reason `foldNav` drops empty nav folders.
206
+ *
207
+ * Omitting `isShared` leaves the function byte-identical to the pre-wave-21 one, which is
208
+ * what every existing caller (the cohort rail, the tests) still gets.
209
  */
210
  export function groupByFolder<T>(
211
  items: T[],
212
  folders: GridFolder[],
213
+ folderIdOf: (item: T) => string | null,
214
+ isShared?: (item: T) => boolean
215
  ): FolderGroup<T>[] {
216
  const buckets = new Map<string, T[]>(folders.map((f) => [f.id, []]));
217
  const root: T[] = [];
218
+ const shared: T[] = [];
219
  for (const item of items) {
220
  const id = folderIdOf(item);
221
  const bucket = id == null ? undefined : buckets.get(id);
222
  if (bucket) bucket.push(item);
223
+ else if (isShared?.(item)) shared.push(item);
224
  else root.push(item);
225
  }
226
  const out: FolderGroup<T>[] = folders.map((f) => ({ folder: f, items: buckets.get(f.id) ?? [] }));
227
  out.push({ folder: null, items: root });
228
+ if (shared.length)
229
+ out.push({ folder: { id: SHARED_FOLDER_ID, name: SHARED_FOLDER_NAME }, items: shared });
230
  return out;
231
  }
232
 
web/src/customer-grid/types.ts CHANGED
@@ -1870,8 +1870,29 @@ export type ViewKind = "system" | "list" | "custom" | "locked";
1870
 
1871
  export interface SavedView {
1872
  /** C-SHARE (wave 20, item 23) β€” this view reached me through a GRANT rather than by
1873
- * being mine. Drives the second mark beside the padlock in the rail. */
 
 
 
 
 
1874
  shared?: boolean;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1875
  /** C4 β€” the folder this view sits in; null/absent = root. */
1876
  folderId?: string | null;
1877
  id: string;
@@ -1919,13 +1940,46 @@ export interface SavedView {
1919
  note?: string;
1920
  }
1921
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1922
  /**
1923
  * The ONE rule for "this view cannot be deleted", mirroring what the host actually enforces
1924
  * (`app.py:5410` refuses `view_delete` for `all-customers`). The client hides exactly what
1925
  * the host refuses β€” a menu entry that emits an event the host silently drops is worse than
1926
  * no entry at all, because it reads as success.
1927
  */
1928
- export const UNDELETABLE_VIEW_IDS = new Set(["all-customers"]);
1929
 
1930
  // ─────────────────────────────────────────────── wave 16 C-TOPIC: the grid's TOPIC
1931
  /**
@@ -2157,9 +2211,34 @@ export function viewEditMode(view: Pick<SavedView, "permissions">): ViewEditMode
2157
  * at the host, not merely hidden here.
2158
  */
2159
  export function mayEditView(
2160
- view: Pick<SavedView, "permissions" | "createdBy">,
2161
  viewer: Viewer | undefined
2162
  ): boolean {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2163
  const mode = viewEditMode(view);
2164
  // Every pre-wave-9 view is collaborative and stays editable by anyone who can see it β€”
2165
  // C4's "never retro-restrict". No viewer info needed, because no restriction applies.
 
1870
 
1871
  export interface SavedView {
1872
  /** C-SHARE (wave 20, item 23) β€” this view reached me through a GRANT rather than by
1873
+ * being mine. Drives the second mark beside the padlock in the rail.
1874
+ *
1875
+ * ⚠ WAVE 21 (item 9, R12/C1): wave 20 declared this and NO SERVER CODE EVER SET IT β€”
1876
+ * the mark could not appear, because the projection that would produce these views did
1877
+ * not exist. C1 builds that projection; the wiring row `W-1` in verify_wiring.py is what
1878
+ * keeps producer and consumer from drifting apart again. */
1879
  shared?: boolean;
1880
+ /**
1881
+ * WAVE 21 item 9 (ruling R12, contract C1) β€” WHAT THE GRANT LETS ME DO.
1882
+ *
1883
+ * `"view"` is read-only and `"edit"` is not; absent on a shared view reads as `"view"`,
1884
+ * because a grant whose role did not survive the wire is not one to act on
1885
+ * (`mayEditView` fail-closes on it). On a view that is MINE this is absent and means
1886
+ * nothing at all β€” ownership is not a grant.
1887
+ *
1888
+ * β›” THE CLIENT HALF IS COURTESY, NEVER THE WALL. C1 requires the server to refuse a
1889
+ * `view_upsert`/`view_delete` on a foreign id unless the grant says `edit`. This decides
1890
+ * which controls render; that decides what happens.
1891
+ */
1892
+ sharedRole?: "view" | "edit";
1893
+ /** C1 β€” whose view this is, when it is not mine. The username, so it matches what every
1894
+ * grant is stored against (see `shareModel.parsePeople`'s note on the two shapes). */
1895
+ owner?: string;
1896
  /** C4 β€” the folder this view sits in; null/absent = root. */
1897
  folderId?: string | null;
1898
  id: string;
 
1940
  note?: string;
1941
  }
1942
 
1943
+ /**
1944
+ * The id of the pinned system view, on EVERY topic.
1945
+ *
1946
+ * ⚠ The id does not vary by surface and must not start to. The client pins it (the landing
1947
+ * default, `UNDELETABLE_VIEW_IDS` below), the host mints it under the same literal
1948
+ * (`aios_grid.views_from_defs`), and every stored `activeViewId` in every tenant's workspace
1949
+ * bucket names it. R6 renames what it is CALLED and says so in as many words: "NAME only β€”
1950
+ * id stays `all-customers`, it is pinned client+server".
1951
+ */
1952
+ export const ALL_VIEW_ID = "all-customers";
1953
+
1954
+ /**
1955
+ * WAVE 21 item 3 (ruling R6) β€” what that view is CALLED, which IS per topic.
1956
+ *
1957
+ * "All customers" on a table of purchase orders is the wrong noun, and on a `ut_*` database
1958
+ * the owner made it is not even a guess β€” the table can hold anything. R6: `All records`
1959
+ * there, the existing topic nouns elsewhere.
1960
+ *
1961
+ * β›” THIS MINT MIRRORS THE HOST'S, it does not replace it. `views_from_defs(system_name=…)`
1962
+ * is the durable name; this is what the client shows when no host workspace has arrived
1963
+ * (the standalone bundle, and β€” until C4 lands β€” a `ut_*` scope whose `/workspace` 403s).
1964
+ * The two must produce the SAME STRING: a client mint that disagreed would repaint the rail
1965
+ * on every echo, which reads as a flicker nobody can attribute. Kept as a function of the
1966
+ * scope rather than a constant so the "which noun" decision has exactly one home on this
1967
+ * side of the wire, and takes a plain `string` (like `topicForScope`) so this module never
1968
+ * needs `SurfaceScope` from `apiBridge` β€” that import would point the dependency edge back
1969
+ * into the transport.
1970
+ */
1971
+ export function allViewName(scope: string): string {
1972
+ if (scope.startsWith("ut_")) return "All records";
1973
+ return scope === "product" ? "All products" : "All customers";
1974
+ }
1975
+
1976
  /**
1977
  * The ONE rule for "this view cannot be deleted", mirroring what the host actually enforces
1978
  * (`app.py:5410` refuses `view_delete` for `all-customers`). The client hides exactly what
1979
  * the host refuses β€” a menu entry that emits an event the host silently drops is worse than
1980
  * no entry at all, because it reads as success.
1981
  */
1982
+ export const UNDELETABLE_VIEW_IDS = new Set([ALL_VIEW_ID]);
1983
 
1984
  // ─────────────────────────────────────────────── wave 16 C-TOPIC: the grid's TOPIC
1985
  /**
 
2211
  * at the host, not merely hidden here.
2212
  */
2213
  export function mayEditView(
2214
+ view: Pick<SavedView, "permissions" | "createdBy" | "shared" | "sharedRole">,
2215
  viewer: Viewer | undefined
2216
  ): boolean {
2217
+ /**
2218
+ * ⭐ WAVE 21 item 9 (ruling R12, contract C1) β€” A READ-ONLY GRANT, FIRST AND ABOVE
2219
+ * EVERYTHING.
2220
+ *
2221
+ * R12: role `view` is read-only "enforced BOTH sides (client affordances + server wall)".
2222
+ * This is the client side, and it is placed at the very top of the function on purpose β€”
2223
+ * every rule below it can say YES for a reason that has nothing to do with the grant:
2224
+ * `collaborative` (the default for every pre-wave-9 view, so most shared views would hit
2225
+ * it), the un-stamped-`createdBy` escape hatch, `viewer.isAdmin`. A shared view is
2226
+ * somebody else's, and the terms it arrived on outrank all of them.
2227
+ *
2228
+ * ⚠ ABSENT ROLE ON A SHARED VIEW READS AS READ-ONLY. The alternative β€” treating a
2229
+ * missing role as `edit` β€” would turn one dropped key on the wire into write access to
2230
+ * another person's saved view. Fail-closed, like every other permission decision here.
2231
+ *
2232
+ * ⚠ ADMINS TOO. An admin's power is over the TENANT's objects through the admin
2233
+ * surfaces, not over a colleague's view through a grant that says "can view" β€” and the
2234
+ * server refuses the write regardless (C1), so relaxing it here would only render
2235
+ * controls whose every use bounced.
2236
+ *
2237
+ * ONE place, three consumers: the rail's row menu, the rail's drag, and the grid's own
2238
+ * delete/config-write guards all ask this function. Putting the rule in any one of them
2239
+ * would leave the other two offering an edit the server refuses.
2240
+ */
2241
+ if (view.shared && (view.sharedRole ?? "view") !== "edit") return false;
2242
  const mode = viewEditMode(view);
2243
  // Every pre-wave-9 view is collaborative and stays editable by anyone who can see it β€”
2244
  // C4's "never retro-restrict". No viewer info needed, because no restriction applies.
web/src/customer-grid/useCustomerData.ts CHANGED
@@ -184,6 +184,10 @@ export function useCustomerData(scope: SurfaceScope = "customer"): CustomerData
184
  // something OUTSIDE the grid's own write path changed rows (shell Add-record, an automation
185
  // run). Senders clear the rows cache first, so the refetch cannot be served from the memo.
186
  const [rowsBump, setRowsBump] = useState(0);
 
 
 
 
187
  useEffect(() => {
188
  if (STREAMLIT_COMPONENT) return; // embed rows arrive from the host, not this path
189
  const onStale = () => setRowsBump((b) => b + 1);
@@ -233,10 +237,32 @@ export function useCustomerData(scope: SurfaceScope = "customer"): CustomerData
233
  // or not-yet-shipped `/workspace` leaves the grid running exactly as it does
234
  // today rather than failing the read. Parallel, not sequential β€” the table
235
  // must not wait on the smaller call.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  async function load() {
237
  const [payload, workspace] = await Promise.all([
238
  fetchTopicRows(topic),
239
- fetchWorkspace(scope),
 
 
 
240
  ]);
241
  if (cancelled || !payload) return;
242
  setData(workspace ? withWorkspace(payload, workspace) : payload);
 
184
  // something OUTSIDE the grid's own write path changed rows (shell Add-record, an automation
185
  // run). Senders clear the rows cache first, so the refetch cannot be served from the memo.
186
  const [rowsBump, setRowsBump] = useState(0);
187
+ /** Item 3 (3c) β€” the LAST scope whose first paint has already been attempted. See the
188
+ * `firstPaint` note in the load effect: this is what keeps a workspace failure loud on
189
+ * arrival and silent on every refetch afterwards. */
190
+ const loudScope = useRef<string | null>(null);
191
  useEffect(() => {
192
  if (STREAMLIT_COMPONENT) return; // embed rows arrive from the host, not this path
193
  const onStale = () => setRowsBump((b) => b + 1);
 
237
  // or not-yet-shipped `/workspace` leaves the grid running exactly as it does
238
  // today rather than failing the read. Parallel, not sequential β€” the table
239
  // must not wait on the smaller call.
240
+ /**
241
+ * Item 3 (3c) β€” IS THIS THE FIRST PAINT OF THIS SURFACE?
242
+ *
243
+ * β›” NOT "is this the load effect", which is what the first version of this asked and
244
+ * it was wrong in the dangerous direction. This effect ALSO re-runs on `rowsBump` β€”
245
+ * a shell add-record, an automation run, this file's own automation-column create β€”
246
+ * so a transient `/workspace` 500 during any ordinary write would have raised
247
+ * `DATA_ERROR_EVENT`, and the frame REPLACES the whole surface with its error card
248
+ * (and only clears it on a session change). That is exactly the "absent stays absent,
249
+ * never blank a live panel" rule this code sets out to protect, coming back in
250
+ * through the other door.
251
+ *
252
+ * Keyed by SCOPE rather than by a boolean: opening a DIFFERENT table is a first paint
253
+ * too, and it is the case item 3 is actually about β€” a `ut_*` surface whose workspace
254
+ * 403s must say so, not silently furnish itself from another table's leftovers.
255
+ */
256
+ const firstPaint = loudScope.current !== scope;
257
+ loudScope.current = scope;
258
+
259
  async function load() {
260
  const [payload, workspace] = await Promise.all([
261
  fetchTopicRows(topic),
262
+ // A workspace that cannot be read at first paint is not "a table with no saved
263
+ // views" β€” it is a table whose schema we do not have, and the grid used to fill
264
+ // that hole from a localStorage bucket shared with every other surface.
265
+ fetchWorkspace(scope, { announceFailure: firstPaint }),
266
  ]);
267
  if (cancelled || !payload) return;
268
  setData(workspace ? withWorkspace(payload, workspace) : payload);
web/src/index.css CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/shell/NavExtras.tsx CHANGED
@@ -13,7 +13,7 @@
13
  import { useEffect, useRef, useState } from "react";
14
  import type { ReactNode } from "react";
15
  import { fetchSchema } from "./nav";
16
- import type { NavFolder, SchemaPayload } from "./nav";
17
  // ⚠ WAVE 19 R8 / C1 β€” IMPORTED, NEVER REDEFINED, and the contract says so in as
18
  // many words ("Shapes/tones = the grid's existing vocabulary verbatim (12
19
  // shapes, 5 tones); B imports, never redefines"). A second copy of this
@@ -33,12 +33,24 @@ import {
33
  import type { FolderIcon } from "../customer-grid/types";
34
  import "./navExtras.css";
35
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  function DotsIcon() {
37
  return (
38
  <svg viewBox="0 0 16 16" aria-hidden="true" className="shell-dots-icon">
39
- <circle cx="8" cy="3.2" r="1.35" />
40
  <circle cx="8" cy="8" r="1.35" />
41
- <circle cx="8" cy="12.8" r="1.35" />
42
  </svg>
43
  );
44
  }
@@ -82,19 +94,31 @@ function useMenu() {
82
  function MenuShell({
83
  at,
84
  menuRef,
 
85
  children,
86
  }: {
87
  at: { x: number; y: number };
88
  menuRef: React.RefObject<HTMLDivElement>;
 
 
 
 
 
89
  children: ReactNode;
90
  }) {
91
  // Clamp to the viewport so a row near the bottom does not spill the menu off it.
 
92
  const style = {
93
- left: Math.min(at.x, Math.max(8, window.innerWidth - 248)),
94
  top: Math.min(at.y, Math.max(8, window.innerHeight - 260)),
95
  };
96
  return (
97
- <div className="shell-navmenu" style={style} ref={menuRef} role="menu">
 
 
 
 
 
98
  {children}
99
  </div>
100
  );
@@ -181,6 +205,9 @@ export function RowMenu({
181
  onIcon,
182
  onIconClear,
183
  onShare,
 
 
 
184
  }: {
185
  entryLabel: string;
186
  canSchema: boolean;
@@ -203,6 +230,26 @@ export function RowMenu({
203
  /** WAVE 20 item 18 (C-SHARE) β€” open the access editor for THIS database.
204
  * Absent = the row does not offer sharing (a group head has nothing to share). */
205
  onShare?: () => void;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  }) {
207
  // Wave 14 C-NAVFOLD (ruling R10): the three-dots kept "View schema" ONLY.
208
  // Wave 19 (R8/C1) adds Rename and Change icon β€” the first two things a
@@ -210,16 +257,53 @@ export function RowMenu({
210
  const { at, ref, openFrom, close } = useMenu();
211
  // Which face the popover is showing. Reset on every open, so a menu that was
212
  // left mid-rename does not reopen into somebody else's half-typed name.
213
- const [mode, setMode] = useState<"menu" | "rename" | "icon">("menu");
214
  const [name, setName] = useState(entryLabel);
 
 
 
 
 
 
 
 
 
 
215
  const renameOn = !!canRename && !!onRename;
216
  const iconOn = !!canIcon && !!onIcon;
217
- if (!canSchema && !renameOn && !iconOn && !onShare) return null;
218
  const submitRename = () => {
219
  const clean = name.trim().replace(/\s+/g, " ");
220
  if (clean && clean !== entryLabel) onRename?.(clean);
221
  close();
222
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  return (
224
  <>
225
  <button
@@ -238,8 +322,15 @@ export function RowMenu({
238
  <DotsIcon />
239
  </button>
240
  {at && (
241
- <MenuShell at={at} menuRef={ref}>
242
- {mode === "rename" && renameOn ? (
 
 
 
 
 
 
 
243
  <form
244
  className="shell-navmenu-form"
245
  onSubmit={(e) => {
@@ -332,6 +423,22 @@ export function RowMenu({
332
  Share…
333
  </button>
334
  ) : null}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
335
  </>
336
  )}
337
  </MenuShell>
@@ -340,6 +447,110 @@ export function RowMenu({
340
  );
341
  }
342
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
343
  function PlusIcon() {
344
  return (
345
  <svg viewBox="0 0 16 16" aria-hidden="true" className="shell-newthing-plus">
 
13
  import { useEffect, useRef, useState } from "react";
14
  import type { ReactNode } from "react";
15
  import { fetchSchema } from "./nav";
16
+ import type { NavFolder, SchemaPayload, TableFootprint } from "./nav";
17
  // ⚠ WAVE 19 R8 / C1 β€” IMPORTED, NEVER REDEFINED, and the contract says so in as
18
  // many words ("Shapes/tones = the grid's existing vocabulary verbatim (12
19
  // shapes, 5 tones); B imports, never redefines"). A second copy of this
 
33
  import type { FolderIcon } from "../customer-grid/types";
34
  import "./navExtras.css";
35
 
36
+ /**
37
+ * WAVE 21 item 12 (ruling R11) β€” HORIZONTAL, and it is the same three dots turned
38
+ * 90Β°, not a different mark.
39
+ *
40
+ * The rail and the views list are read as one surface, and they were drawing the
41
+ * "there is a menu here" affordance two different ways: this glyph stacked its
42
+ * circles (cx fixed, cy walking) while `ViewSidebar`'s row buttons have always
43
+ * rendered three MIDDLE DOTs on the baseline. Same promise, two pictures β€” the
44
+ * thing R11 names. Only the axis moves: radius, viewBox and the 14px box in
45
+ * `navExtras.css` are untouched, so the hit target and the optical weight are
46
+ * exactly what shipped.
47
+ */
48
  function DotsIcon() {
49
  return (
50
  <svg viewBox="0 0 16 16" aria-hidden="true" className="shell-dots-icon">
51
+ <circle cx="3.2" cy="8" r="1.35" />
52
  <circle cx="8" cy="8" r="1.35" />
53
+ <circle cx="12.8" cy="8" r="1.35" />
54
  </svg>
55
  );
56
  }
 
94
  function MenuShell({
95
  at,
96
  menuRef,
97
+ wide,
98
  children,
99
  }: {
100
  at: { x: number; y: number };
101
  menuRef: React.RefObject<HTMLDivElement>;
102
+ /** WAVE 21 item 6 β€” the delete confirm needs prose width; a menu of one-line
103
+ * actions does not. The CLAMP moves with the class, because a wider panel
104
+ * clamped at the narrow width spills off the right edge on exactly the rows
105
+ * furthest from it. */
106
+ wide?: boolean;
107
  children: ReactNode;
108
  }) {
109
  // Clamp to the viewport so a row near the bottom does not spill the menu off it.
110
+ const width = wide ? 320 : 248;
111
  const style = {
112
+ left: Math.min(at.x, Math.max(8, window.innerWidth - width)),
113
  top: Math.min(at.y, Math.max(8, window.innerHeight - 260)),
114
  };
115
  return (
116
+ <div
117
+ className={"shell-navmenu" + (wide ? " is-wide" : "")}
118
+ style={style}
119
+ ref={menuRef}
120
+ role="menu"
121
+ >
122
  {children}
123
  </div>
124
  );
 
205
  onIcon,
206
  onIconClear,
207
  onShare,
208
+ canDelete,
209
+ onLoadFootprint,
210
+ onDelete,
211
  }: {
212
  entryLabel: string;
213
  canSchema: boolean;
 
230
  /** WAVE 20 item 18 (C-SHARE) β€” open the access editor for THIS database.
231
  * Absent = the row does not offer sharing (a group head has nothing to share). */
232
  onShare?: () => void;
233
+ /**
234
+ * ⭐ WAVE 21 item 6 (ruling R3, contract C3, wiring W-5) β€” may this session
235
+ * DELETE this database?
236
+ *
237
+ * β›” REQUIRED, NOT OPTIONAL, and that is the wave-20 lesson written into a type.
238
+ * Four features shipped dead behind 43 green gates because the prop that carried
239
+ * them across an ownership fence was `?`-marked: an unmounted optional prop is
240
+ * `undefined`, which reads as "the feature is off" and is indistinguishable from
241
+ * "the feature was never built". A required prop makes the unmounted case a
242
+ * COMPILE ERROR. The value is the server's (`NavPage.canDelete`), narrower than
243
+ * `manage` on purpose β€” see the note there.
244
+ */
245
+ canDelete: boolean;
246
+ /** What deleting would destroy. Resolves null when the server would not say β€”
247
+ * the face then asks WITHOUT counts rather than inventing zeros. */
248
+ onLoadFootprint: () => Promise<TableFootprint | null>;
249
+ /** Do it. Resolves the server's own words on refusal, which the face shows in
250
+ * place of the confirmation β€” a delete that failed must never look like one
251
+ * that worked. */
252
+ onDelete: () => Promise<{ ok: boolean; error?: string }>;
253
  }) {
254
  // Wave 14 C-NAVFOLD (ruling R10): the three-dots kept "View schema" ONLY.
255
  // Wave 19 (R8/C1) adds Rename and Change icon β€” the first two things a
 
257
  const { at, ref, openFrom, close } = useMenu();
258
  // Which face the popover is showing. Reset on every open, so a menu that was
259
  // left mid-rename does not reopen into somebody else's half-typed name.
260
+ const [mode, setMode] = useState<"menu" | "rename" | "icon" | "delete">("menu");
261
  const [name, setName] = useState(entryLabel);
262
+ /**
263
+ * WAVE 21 item 6 β€” the delete face's own state. `footprint: undefined` means
264
+ * "still asking", `null` means "the server would not say" β€” two different
265
+ * things the face words differently, which is why it is not a plain object.
266
+ */
267
+ const [del, setDel] = useState<{
268
+ footprint?: TableFootprint | null;
269
+ busy: boolean;
270
+ error: string;
271
+ }>({ busy: false, error: "" });
272
  const renameOn = !!canRename && !!onRename;
273
  const iconOn = !!canIcon && !!onIcon;
274
+ if (!canSchema && !renameOn && !iconOn && !onShare && !canDelete) return null;
275
  const submitRename = () => {
276
  const clean = name.trim().replace(/\s+/g, " ");
277
  if (clean && clean !== entryLabel) onRename?.(clean);
278
  close();
279
  };
280
+ /**
281
+ * ⚠ THE FOOTPRINT IS FETCHED WHEN THE FACE OPENS, NOT WHEN THE MENU DOES.
282
+ * Same reasoning as `PermsEditor.prepareCopy` ("the targets are fetched BEFORE
283
+ * the confirm"): the question has to name what is being destroyed, and a
284
+ * confirm written from the rail's own knowledge can only name the table. The
285
+ * cost is paid by the person who clicked Delete, never by everyone who opened
286
+ * a menu.
287
+ */
288
+ const openDelete = () => {
289
+ setDel({ busy: false, error: "" });
290
+ setMode("delete");
291
+ void onLoadFootprint().then((f) => setDel((cur) => ({ ...cur, footprint: f })));
292
+ };
293
+ const runDelete = () => {
294
+ setDel((cur) => ({ ...cur, busy: true, error: "" }));
295
+ void onDelete().then((r) => {
296
+ if (r.ok) {
297
+ close();
298
+ setDel({ busy: false, error: "" });
299
+ return;
300
+ }
301
+ // β›” THE MENU STAYS OPEN ON A REFUSAL. Closing it would leave a rail whose
302
+ // row is still there and no statement anywhere about why β€” which reads as
303
+ // "the click did nothing" and invites a second one.
304
+ setDel((cur) => ({ ...cur, busy: false, error: r.error || "It could not be deleted." }));
305
+ });
306
+ };
307
  return (
308
  <>
309
  <button
 
322
  <DotsIcon />
323
  </button>
324
  {at && (
325
+ <MenuShell at={at} menuRef={ref} wide={mode === "delete"}>
326
+ {mode === "delete" && canDelete ? (
327
+ <DeleteFace
328
+ entryLabel={entryLabel}
329
+ state={del}
330
+ onCancel={() => setMode("menu")}
331
+ onConfirm={runDelete}
332
+ />
333
+ ) : mode === "rename" && renameOn ? (
334
  <form
335
  className="shell-navmenu-form"
336
  onSubmit={(e) => {
 
423
  Share…
424
  </button>
425
  ) : null}
426
+ {/* ⭐ WAVE 21 item 6 (R3) β€” LAST, and the only destructive row in this
427
+ menu. Gated on the server's `canDelete` alone: R3 scopes the verb to
428
+ the CREATOR or an admin and refuses it outright for connector-backed
429
+ databases, so a row that may not be deleted does not say so β€” it
430
+ simply has nothing here to click. (An entry that explains why it is
431
+ disabled is the right pattern for a thing you could earn; this one
432
+ you cannot.) */}
433
+ {canDelete ? (
434
+ <button
435
+ type="button"
436
+ className="shell-navmenu-item is-danger"
437
+ onClick={openDelete}
438
+ >
439
+ Delete database…
440
+ </button>
441
+ ) : null}
442
  </>
443
  )}
444
  </MenuShell>
 
447
  );
448
  }
449
 
450
+ /** One footprint line: "12 records", "1 view". Singular/plural is the whole of
451
+ * the formatting, because a count with the wrong noun reads as a bug in the
452
+ * count. */
453
+ function countLine(n: number, one: string, many: string): string {
454
+ return `${n.toLocaleString()} ${n === 1 ? one : many}`;
455
+ }
456
+
457
+ /**
458
+ * ⭐ WAVE 21 item 6 (R3, contract C3) β€” the confirm face: what deleting this
459
+ * database destroys, stated before the button that does it.
460
+ *
461
+ * Shaped after `PermsEditor`'s confirm (`.set-confirm`, the strongest one this
462
+ * codebase has) and not after a `window.confirm`: the browser dialog cannot say
463
+ * anything specific, and a destructive question whose answer depends on facts
464
+ * the asker has not been given is not really being asked.
465
+ *
466
+ * THREE STATES, worded differently on purpose:
467
+ * Β· footprint undefined β€” still asking the server. The button is disabled;
468
+ * confirming against numbers that have not arrived is confirming against
469
+ * nothing.
470
+ * Β· footprint null β€” the server would not say. The question is put
471
+ * WITHOUT counts and says so. Inventing zeros here would be a specific,
472
+ * checkable claim about the user's data that nobody verified
473
+ * ([[no-unverifiable-aggregates]]).
474
+ * Β· footprint present β€” every family it names, listed.
475
+ *
476
+ * ⚠ The automations line is the one that is NOT about destruction: C3 pauses
477
+ * bound automations and stamps them "target deleted" rather than removing them,
478
+ * so it names them (they will still be there afterwards, switched off) instead
479
+ * of counting them away.
480
+ */
481
+ function DeleteFace({
482
+ entryLabel,
483
+ state,
484
+ onCancel,
485
+ onConfirm,
486
+ }: {
487
+ entryLabel: string;
488
+ state: { footprint?: TableFootprint | null; busy: boolean; error: string };
489
+ onCancel: () => void;
490
+ onConfirm: () => void;
491
+ }) {
492
+ const f = state.footprint;
493
+ const asking = f === undefined;
494
+ return (
495
+ <div className="shell-navconfirm" role="alertdialog" aria-modal="true"
496
+ aria-label={`Delete ${entryLabel}`}>
497
+ <h4 className="shell-navconfirm-h">Delete β€œ{entryLabel}”?</h4>
498
+ {asking ? (
499
+ <p className="shell-navmenu-note">Checking what this database holds…</p>
500
+ ) : f === null ? (
501
+ <p className="shell-navmenu-note">
502
+ The server did not say what this database holds. Deleting it removes its records,
503
+ columns, views, comments, documents and sharing β€” permanently.
504
+ </p>
505
+ ) : (
506
+ <>
507
+ <p className="shell-navmenu-note">This cannot be undone. It permanently removes:</p>
508
+ <ul className="shell-navconfirm-list">
509
+ <li>{countLine(f.rows, "record", "records")}</li>
510
+ <li>{countLine(f.fields, "column", "columns")}</li>
511
+ <li>{countLine(f.views, "view", "views")}</li>
512
+ <li>
513
+ {countLine(f.sharedUsers, "person it is shared with",
514
+ "people it is shared with")}
515
+ </li>
516
+ </ul>
517
+ {f.automations.length ? (
518
+ <p className="shell-navmenu-note">
519
+ {/* The VERB agrees too. "1 automation write here" was on screen before the
520
+ first screenshot was read β€” the kind of thing every assertion passes. */}
521
+ {countLine(f.automations.length, "automation", "automations")}{" "}
522
+ {f.automations.length === 1 ? "writes" : "write"} here (
523
+ {f.automations.map((a) => a.name).join(", ")}) β€” {f.automations.length === 1
524
+ ? "it is"
525
+ : "they are"}{" "}
526
+ switched off, not deleted.
527
+ </p>
528
+ ) : null}
529
+ </>
530
+ )}
531
+ {state.error ? <p className="shell-navconfirm-err">{state.error}</p> : null}
532
+ <div className="shell-navconfirm-actions">
533
+ <button
534
+ type="button"
535
+ className="shell-navconfirm-go"
536
+ disabled={asking || state.busy}
537
+ onClick={onConfirm}
538
+ >
539
+ {state.busy ? "Deleting…" : "Delete"}
540
+ </button>
541
+ <button
542
+ type="button"
543
+ className="shell-navmenu-item is-quiet"
544
+ disabled={state.busy}
545
+ onClick={onCancel}
546
+ >
547
+ Keep it
548
+ </button>
549
+ </div>
550
+ </div>
551
+ );
552
+ }
553
+
554
  function PlusIcon() {
555
  return (
556
  <svg viewBox="0 0 16 16" aria-hidden="true" className="shell-newthing-plus">
web/src/shell/Shell.tsx CHANGED
@@ -44,7 +44,7 @@ import { SettingsModal } from "../settings/SettingsModal";
44
  import type { SettingsSection } from "../settings/SettingsModal";
45
  import { Brand } from "./Brand";
46
  import LoginPage from "./LoginPage";
47
- import { EMPTY_NAV_PREFS, ENVELOPE_KEYS, MAX_NAV_FOLDERS, appLink, dbChipClass, defaultRoute, fetchNav, fetchNavPrefs, foldNav, resolveRoute, saveNavMeta, saveNavPrefs, shapeNav, splitChrome } from "./nav";
48
  import type { NavEntry, NavMetaPatch, NavPage, NavPrefs } from "./nav";
49
  import { CreateNewRow, FolderHead, RowMenu, SchemaDrawer } from "./NavExtras";
50
  import AlertsPane from "../alerts/AlertsPane";
@@ -761,6 +761,43 @@ export default function Shell() {
761
  else setToast("That change was not saved β€” the store refused the write.");
762
  }, []);
763
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
764
  // Keep the URL honest in both directions: an anonymous shell sits on
765
  // `#/login`, and a signed-in one never does.
766
  useEffect(() => {
@@ -1220,6 +1257,21 @@ export default function Shell() {
1220
  }),
1221
  }
1222
  : {})}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1223
  />
1224
  )}
1225
  </div>
 
44
  import type { SettingsSection } from "../settings/SettingsModal";
45
  import { Brand } from "./Brand";
46
  import LoginPage from "./LoginPage";
47
+ import { EMPTY_NAV_PREFS, ENVELOPE_KEYS, MAX_NAV_FOLDERS, appLink, dbChipClass, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchTableFootprint, foldNav, resolveRoute, saveNavMeta, saveNavPrefs, shapeNav, splitChrome } from "./nav";
48
  import type { NavEntry, NavMetaPatch, NavPage, NavPrefs } from "./nav";
49
  import { CreateNewRow, FolderHead, RowMenu, SchemaDrawer } from "./NavExtras";
50
  import AlertsPane from "../alerts/AlertsPane";
 
761
  else setToast("That change was not saved β€” the store refused the write.");
762
  }, []);
763
 
764
+ /**
765
+ * ⭐ WAVE 21 item 6 (R3, contract C3) β€” delete a user database, and then leave.
766
+ *
767
+ * The confirm face owns the QUESTION; this owns the round trip and the two
768
+ * things that have to happen after a yes:
769
+ *
770
+ * Β· the nav is refetched (`navEpoch`), because the row must go β€” and because
771
+ * the server is the only end that knows what else went with it;
772
+ * Β· if the deleted table is the one on screen, the route moves. The hash
773
+ * would otherwise still name a key the payload no longer carries, and
774
+ * `resolveRoute` answers that with a blank main pane β€” a shell that looks
775
+ * broken as the reward for a successful delete.
776
+ *
777
+ * The route change is deliberately NOT optimistic. It fires after the server
778
+ * confirms, so a refused delete leaves the user exactly where they were, still
779
+ * looking at the table they asked about.
780
+ */
781
+ const removeDatabase = useCallback(
782
+ async (key: string): Promise<{ ok: boolean; error?: string }> => {
783
+ const r = await deleteTable(key);
784
+ if (!r.ok) return r;
785
+ // The grid's cached rows for THIS table die with it: a remount inside the
786
+ // cache window would otherwise re-paint a table that no longer exists.
787
+ clearCustomersCache();
788
+ setNavEpoch((e) => e + 1);
789
+ setToast("Database deleted.");
790
+ // An EMPTY hash, not a computed one: `resolveRoute` answers "" with
791
+ // `defaultRoute(entries)`, so the landing surface is chosen by the same
792
+ // rule a fresh sign-in uses β€” and it is chosen from the REFETCHED nav,
793
+ // which a key computed here (from the list still holding the dead row)
794
+ // could not be.
795
+ if (route === key) window.location.hash = "";
796
+ return { ok: true };
797
+ },
798
+ [route]
799
+ );
800
+
801
  // Keep the URL honest in both directions: an anonymous shell sits on
802
  // `#/login`, and a signed-in one never does.
803
  useEffect(() => {
 
1257
  }),
1258
  }
1259
  : {})}
1260
+ // ⭐ WAVE 21 item 6 (R3, C3, wiring W-5) β€” THE MOUNT.
1261
+ //
1262
+ // `canDelete` is the SERVER's answer and a REQUIRED prop, so
1263
+ // this expression not being here is a compile error rather
1264
+ // than a feature that quietly does not exist (wave 20's
1265
+ // lesson, written into the type β€” see RowMenu's own note).
1266
+ //
1267
+ // β›” NOT `manage`, and the difference is the whole ruling.
1268
+ // `manage` rides `may_open`, which R14/D-32 widened to
1269
+ // everyone the table is SHARED with; R3 puts delete on the
1270
+ // creator or an admin alone, and refuses it outright for
1271
+ // connector-backed databases. Two questions, two flags.
1272
+ canDelete={!!item.canDelete}
1273
+ onLoadFootprint={() => fetchTableFootprint(item.key)}
1274
+ onDelete={() => removeDatabase(item.key)}
1275
  />
1276
  )}
1277
  </div>
web/src/shell/nav.ts CHANGED
@@ -79,6 +79,23 @@ export interface NavPage {
79
  * hides, the server forbids", never the wall.
80
  */
81
  manage?: boolean;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  }
83
 
84
  /**
@@ -150,6 +167,9 @@ export function parsePages(body: unknown): NavPage[] {
150
  ...(p.chrome === "main" || p.chrome === "utility" ? { chrome: p.chrome } : {}),
151
  ...(parseNavIcon(p.icon) ? { icon: parseNavIcon(p.icon)! } : {}),
152
  ...(p.manage === true ? { manage: true } : {}),
 
 
 
153
  });
154
  }
155
  return out;
@@ -302,6 +322,101 @@ export async function saveNavMeta(key: string, patch: NavMetaPatch): Promise<boo
302
  }
303
  }
304
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
  /** One rendered row of the folded nav: a folder head, or an entry (optionally inside one). */
306
  export type NavRow =
307
  | { kind: "folder"; folder: NavFolder; count: number; open: boolean }
@@ -450,6 +565,10 @@ export interface NavEntry {
450
  /** WAVE 19 R14 β€” the server's answer to "may this session rename/re-icon it".
451
  * Absent β‡’ no, and the route refuses independently. */
452
  manage?: boolean;
 
 
 
 
453
  }
454
 
455
  /**
@@ -541,6 +660,11 @@ export function shapeNav(pages: NavPage[], appBase: string): NavEntry[] {
541
  ...(p.source ? { source: p.source } : {}),
542
  ...(p.icon ? { icon: p.icon } : {}),
543
  ...(p.manage ? { manage: true } : {}),
 
 
 
 
 
544
  kind,
545
  depth,
546
  ...(kind === "group"
 
79
  * hides, the server forbids", never the wall.
80
  */
81
  manage?: boolean;
82
+ /**
83
+ * WAVE 21 item 6 (ruling R3, contract C3) β€” may THIS session DELETE this
84
+ * database?
85
+ *
86
+ * β›” A SEPARATE FLAG FROM `manage`, deliberately, and reusing that one would
87
+ * have been the bug. `manage` rides `user_tables.may_open` β€” which R14 widened
88
+ * to include everyone a table has been SHARED with (D-32, `user_tables.py:511`).
89
+ * That is the right reach for renaming and re-iconing; it is far too wide for
90
+ * a verb that destroys ten artifact families. R3 scopes delete to the CREATOR
91
+ * or a tenant admin, so the server answers a second, narrower question and
92
+ * this is where the answer lands.
93
+ *
94
+ * Absent β‡’ no, like every flag here. Connector-backed databases never carry
95
+ * it (R3: "NO delete verb for connector-backed databases β€” Pause stays their
96
+ * only off-switch"), so the entry is absent rather than refused.
97
+ */
98
+ canDelete?: boolean;
99
  }
100
 
101
  /**
 
167
  ...(p.chrome === "main" || p.chrome === "utility" ? { chrome: p.chrome } : {}),
168
  ...(parseNavIcon(p.icon) ? { icon: parseNavIcon(p.icon)! } : {}),
169
  ...(p.manage === true ? { manage: true } : {}),
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;
 
322
  }
323
  }
324
 
325
+ // ───────────────────────────── WAVE 21 item 6 (R3, contract C3): delete a database
326
+ /**
327
+ * What deleting this database would actually destroy.
328
+ *
329
+ * β›” EVERY FIELD IS A COUNT THE USER CAN ACT ON, which is the whole reason the
330
+ * confirm face exists. R3: "Confirm dialog discloses the footprint (rows/fields/
331
+ * views/shared users/bound automations) before DELETE." A dialog that said only
332
+ * "are you sure?" would be asking about a thing whose size nobody can see β€” and
333
+ * the thing that makes a user-table delete different from a view delete is that
334
+ * nine other artifact families go with it (cohorts, comments, docs + their
335
+ * dataset bytes, asset refs, grants, nav meta, alerts, automations).
336
+ *
337
+ * `automations` are NAMED, not counted, and that asymmetry is deliberate: they
338
+ * are the only footprint entry that keeps existing after the delete (C3 pauses
339
+ * them and stamps "target deleted" rather than removing them), so the user has
340
+ * to be able to go and find them.
341
+ */
342
+ export interface TableFootprint {
343
+ rows: number;
344
+ fields: number;
345
+ views: number;
346
+ sharedUsers: number;
347
+ automations: { id: string; name: string }[];
348
+ }
349
+
350
+ const intOf = (v: unknown): number =>
351
+ typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0;
352
+
353
+ /**
354
+ * `GET /api/v1/tables/{key}/footprint` (C3, A serves).
355
+ *
356
+ * Returns null when the server would not or could not answer. The caller shows
357
+ * the confirm face WITHOUT counts in that case rather than substituting zeros:
358
+ * "0 rows" is a specific, checkable claim about the user's data, and inventing
359
+ * it to keep a dialog tidy is the fabrication this repo's counts rule forbids
360
+ * ([[no-unverifiable-aggregates]]).
361
+ */
362
+ export async function fetchTableFootprint(key: string): Promise<TableFootprint | null> {
363
+ try {
364
+ const res = await fetch(`${API_V1}/tables/${encodeURIComponent(key)}/footprint`, {
365
+ credentials: CREDENTIALS,
366
+ });
367
+ if (!res.ok) return null;
368
+ const raw = (await res.json()) as Record<string, unknown> | null;
369
+ if (!raw || typeof raw !== "object") return null;
370
+ const autos: { id: string; name: string }[] = [];
371
+ for (const item of Array.isArray(raw.automations) ? raw.automations : []) {
372
+ if (!item || typeof item !== "object") continue;
373
+ const a = item as Record<string, unknown>;
374
+ const id = typeof a.id === "string" ? a.id : String(a.id ?? "");
375
+ const name = typeof a.name === "string" && a.name.trim() ? a.name.trim() : id;
376
+ if (id) autos.push({ id, name });
377
+ }
378
+ return {
379
+ rows: intOf(raw.rows),
380
+ fields: intOf(raw.fields),
381
+ views: intOf(raw.views),
382
+ sharedUsers: intOf(raw.sharedUsers),
383
+ automations: autos,
384
+ };
385
+ } catch {
386
+ return null;
387
+ }
388
+ }
389
+
390
+ /**
391
+ * `DELETE /api/v1/tables/{key}` (C3). The route has existed since wave 18 with
392
+ * NO client caller at all β€” this is that caller.
393
+ *
394
+ * Resolves the server's own message on failure so the rail can say why, and
395
+ * `true` only on a 2xx. The nav is refetched by the caller either way: a delete
396
+ * that half-succeeded server-side must not leave a row on screen whose absence
397
+ * is the only evidence anything happened.
398
+ */
399
+ export async function deleteTable(key: string): Promise<{ ok: boolean; error?: string }> {
400
+ try {
401
+ const res = await fetch(`${API_V1}/tables/${encodeURIComponent(key)}`, {
402
+ method: "DELETE",
403
+ credentials: CREDENTIALS,
404
+ });
405
+ if (res.ok) return { ok: true };
406
+ let detail = "";
407
+ try {
408
+ const body = (await res.json()) as { detail?: unknown; error?: unknown } | null;
409
+ const d = body?.detail ?? body?.error;
410
+ if (typeof d === "string") detail = d;
411
+ } catch {
412
+ /* a non-JSON error body is not itself an error worth surfacing */
413
+ }
414
+ return { ok: false, error: detail || `The server answered ${res.status}.` };
415
+ } catch {
416
+ return { ok: false, error: "Cannot reach the server." };
417
+ }
418
+ }
419
+
420
  /** One rendered row of the folded nav: a folder head, or an entry (optionally inside one). */
421
  export type NavRow =
422
  | { kind: "folder"; folder: NavFolder; count: number; open: boolean }
 
565
  /** WAVE 19 R14 β€” the server's answer to "may this session rename/re-icon it".
566
  * Absent β‡’ no, and the route refuses independently. */
567
  manage?: boolean;
568
+ /** WAVE 21 R3/C3 β€” the server's answer to "may this session DELETE it": the
569
+ * CREATOR or an admin, never the whole `may_open` set `manage` rides on (see
570
+ * the long note on `NavPage.canDelete`). Absent β‡’ no. */
571
+ canDelete?: boolean;
572
  }
573
 
574
  /**
 
660
  ...(p.source ? { source: p.source } : {}),
661
  ...(p.icon ? { icon: p.icon } : {}),
662
  ...(p.manage ? { manage: true } : {}),
663
+ // C3 (W-5) β€” carried through `shapeNav` beside `manage`. THE SECOND HALF
664
+ // OF THE SAME FLAG: `parseNav` reading it and this dropping it would put
665
+ // the answer on the payload and never on the row the rail renders, which
666
+ // is precisely how wave 20 shipped four wirings that went nowhere.
667
+ ...(p.canDelete ? { canDelete: true } : {}),
668
  kind,
669
  depth,
670
  ...(kind === "group"
web/src/shell/navExtras.css CHANGED
@@ -357,6 +357,84 @@
357
  cursor: default;
358
  }
359
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
  /* ── the schema drawer ────────────────────────────────────────────────────── */
361
 
362
  .shell-schema-backdrop {
@@ -411,7 +489,7 @@
411
  .shell-schema-close {
412
  border: 0;
413
  background: transparent;
414
- font-size: 19px;
415
  line-height: 1;
416
  color: var(--lp-muted);
417
  cursor: pointer;
 
357
  cursor: default;
358
  }
359
 
360
+ /* ── WAVE 21 item 6 (R3 / C3): the delete-database confirm face ─────────────
361
+ Wider than the action menu, and only while it is showing: the panel's job
362
+ changes from "pick one of four one-line verbs" to "read what is about to be
363
+ destroyed", and R7's one-line law is about MENU ROWS, not about prose. The
364
+ width is matched in `MenuShell`'s viewport clamp β€” a wider panel clamped at
365
+ the narrow number spills off the right edge on precisely the rows nearest
366
+ it. */
367
+ .shell-navmenu.is-wide {
368
+ max-width: 312px;
369
+ }
370
+
371
+ .shell-navconfirm {
372
+ padding: 3px 2px 2px;
373
+ }
374
+
375
+ .shell-navconfirm-h {
376
+ margin: 0;
377
+ padding: 5px 8px 2px;
378
+ font-size: var(--lp-fs-xs);
379
+ font-weight: 600;
380
+ color: var(--lp-ink);
381
+ }
382
+
383
+ /* The footprint. `disc` rather than the app's usual bare rows because these ARE
384
+ a list of things and reading them as one takes a mark β€” this is the one place
385
+ in the nav chrome where the user is counting. */
386
+ .shell-navconfirm-list {
387
+ margin: 0;
388
+ padding: 0 8px 4px 24px;
389
+ font-size: var(--lp-fs-3xs);
390
+ color: var(--lp-ink);
391
+ line-height: 1.55;
392
+ }
393
+
394
+ .shell-navconfirm-err {
395
+ margin: 0;
396
+ padding: 2px 8px 4px;
397
+ font-size: var(--lp-fs-3xs);
398
+ color: var(--lp-red-deep);
399
+ }
400
+
401
+ .shell-navconfirm-actions {
402
+ display: flex;
403
+ align-items: center;
404
+ gap: 6px;
405
+ padding: 4px 6px 4px;
406
+ }
407
+
408
+ /* ⚠ THE DESTRUCTIVE BUTTON IS FILLED, and the way back is the quiet one. The
409
+ opposite arrangement (a quiet Delete beside a filled Cancel) is the pattern
410
+ that makes people click twice: the eye lands on the filled control, and if
411
+ that control is the one that does nothing the second click goes to the one
412
+ that does. Weight follows CONSEQUENCE here, not safety β€” the safety is the
413
+ sentence above it. */
414
+ .shell-navconfirm-go {
415
+ flex: 0 0 auto;
416
+ border: 1px solid var(--lp-red-deep);
417
+ border-radius: 6px;
418
+ background: var(--lp-red-deep);
419
+ padding: 4px 11px;
420
+ font: inherit;
421
+ font-size: var(--lp-fs-xs);
422
+ color: var(--lp-surface);
423
+ cursor: pointer;
424
+ }
425
+
426
+ .shell-navconfirm-go:disabled {
427
+ border-color: var(--lp-line);
428
+ background: var(--lp-wash);
429
+ color: var(--lp-muted);
430
+ cursor: default;
431
+ }
432
+
433
+ .shell-navconfirm-actions .shell-navmenu-item.is-quiet {
434
+ width: auto;
435
+ margin-top: 0;
436
+ }
437
+
438
  /* ── the schema drawer ────────────────────────────────────────────────────── */
439
 
440
  .shell-schema-backdrop {
 
489
  .shell-schema-close {
490
  border: 0;
491
  background: transparent;
492
+ font-size: var(--lp-fs-md);
493
  line-height: 1;
494
  color: var(--lp-muted);
495
  cursor: pointer;