fsanyoto commited on
Commit
b36e641
Β·
verified Β·
1 Parent(s): a08464c

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "v12 (4908f39)",
3
  "releases": [
4
  {
5
  "version": "v12",
 
1
  {
2
+ "current": "325ac93",
3
  "releases": [
4
  {
5
  "version": "v12",
VERSION CHANGED
@@ -1 +1 @@
1
- v12 (4908f39)
 
1
+ 325ac93
api/automation_engine.py CHANGED
The diff for this file is too large to render. See raw diff
 
api/routes_automation.py CHANGED
@@ -108,12 +108,43 @@ def _triggers_vocab(session):
108
  "webhook": (True, ""),
109
  "email": (email_ready, email_needs),
110
  "form_submitted": (True, ""),
 
 
 
 
 
 
111
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  out = []
113
  for k in engine.TRIGGER_KEYS:
114
- ready, needs = per[k]
 
 
 
 
 
 
115
  row = {"key": k, "label": engine.TRIGGER_LABELS[k], "ready": ready, "needs": needs,
116
- "planned": False,
117
  # A3(3): the connect affordance is SERVER-COMPOSED β€” the client never maps a
118
  # `needs` token to a route, so B's CONNECT_PROVIDERS shim deletes itself.
119
  "connect": None}
@@ -123,7 +154,8 @@ def _triggers_vocab(session):
123
  out.append(row)
124
  for k in engine.TRIGGER_PLANNED:
125
  out.append({"key": k, "label": engine.TRIGGER_LABELS[k], "ready": False,
126
- "needs": "coming_soon", "planned": True, "connect": None})
 
127
  return out
128
 
129
 
@@ -164,9 +196,14 @@ def list_automations(session: Session = Depends(_GATE)):
164
  items = [_wire(d, session.tenant) for _, d in
165
  sorted(defs.items(), key=lambda kv: (kv[1].get("name") or "").lower())]
166
  return {"automations": items,
167
- "kinds": [{"key": "scrape_db", "label": "Web page to database"},
168
- {"key": "field_instagram", "label": "Instagram profile column"},
169
- {"key": "discover_instagram", "label": "Find Instagram profiles"}],
 
 
 
 
 
170
  "cronPresets": engine.CRON_PRESETS,
171
  # ⚠ A BOOLEAN, NEVER THE KEY. The surface needs to say "the paid rung is not
172
  # configured" honestly instead of offering a tier that will silently refuse β€” and
@@ -249,6 +286,50 @@ def discover_estimate(body: dict = Body(default=None), session: Session = Depend
249
  _C8_MIGRATED = set()
250
 
251
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
  @router.get("/automations/tables")
253
  def automation_tables(session: Session = Depends(_GATE)):
254
  """The blank databases an automation can target, with their fields.
@@ -283,13 +364,17 @@ def automation_tables(session: Session = Depends(_GATE)):
283
  key=lambda kv: (kv[1].get("label") or "").lower()):
284
  if not user_tables.may_open(key, session.uname, session.admin, st=session.runtime):
285
  continue
286
- out.append({"key": key, "label": t.get("label") or key,
287
- "source": t.get("source") or "Blank",
288
- "rowCount": len(t.get("rows") or {}),
289
- "fields": [{"key": f.get("key"), "label": f.get("label"),
290
- "type": f.get("type") or "text",
291
- "automation": f.get("automation") or None}
292
- for f in (t.get("fields") or [])]})
 
 
 
 
293
  return {"tables": out}
294
 
295
 
@@ -420,28 +505,52 @@ def toggle_automation_node(auto_id: str, node_id: str, session: Session = Depend
420
 
421
 
422
  @router.post("/automations/{auto_id}/hook/{token}")
423
- def automation_hook(auto_id: str, token: str):
424
  """C3's webhook trigger β€” the tick-endpoint pattern one level down: unauthenticated BY
425
  DESIGN (the external caller has no cookie), gated on a per-automation token minted when the
426
  trigger was configured, constant-time compared. The tenant is FOUND by the (id, token)
427
  pair β€” a wrong token answers 403 for every tenant, so the route confirms nothing about
428
- which slugs exist."""
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  from harness import runtime as _rt
430
 
431
- last = (404, {"error": "unknown_automation",
432
- "message": "no automation with that id and token"})
433
- for slug in _rt.known_tenants():
434
- try:
435
- rt = _rt.get_runtime(slug)
436
- except Exception: # noqa: BLE001
437
- continue
438
- status, payload = engine.hook_fire(rt, slug, auto_id, token)
439
- if status == 200:
440
- return payload
441
- if status != 404:
442
- last = (status, payload)
443
- raise err(last[0], str(last[1].get("error") or "refused"),
444
- str(last[1].get("message") or "refused"))
 
 
 
 
 
 
 
 
 
 
 
445
 
446
 
447
  @router.post("/automations/tick")
 
108
  "webhook": (True, ""),
109
  "email": (email_ready, email_needs),
110
  "form_submitted": (True, ""),
111
+ # ⭐ WAVE 24 (C-TRIG) β€” Instagram discovery, now a trigger. Readiness is the vendor key,
112
+ # the same bit `paidReady` carries: with no key the search door is closed and the picker
113
+ # must say so rather than offering a control that silently finds nothing. `clean_trigger`
114
+ # still ACCEPTS it either way β€” readiness is a deployment fact, not a validity one, which
115
+ # is the same split `email` already makes.
116
+ "ig_profile_match": (engine.bd_ready(), "" if engine.bd_ready() else "configure_brightdata"),
117
  }
118
+ #: ⭐ WAVE 24 β€” the server's own one-line description per trigger. C-TYPES: the picker renders
119
+ #: THIS under the option, because a CLIENT paraphrase of a server vocabulary is a second copy
120
+ #: of it, free to drift. Absent = the client shows nothing, never something invented.
121
+ detail = {
122
+ "manual": "It runs only when you press Run now",
123
+ "schedule": "It runs on a repeating schedule",
124
+ "event_field": "A record in the database starts matching a condition you set",
125
+ "record_updated": "Any of the columns you watch is changed",
126
+ "record_created": "A new record is added to the database",
127
+ "enters_view": "A record starts appearing in a saved view",
128
+ "webhook": "Something outside calls this automation's URL",
129
+ "email": "A message arrives in the connected mailbox",
130
+ "form_submitted": "Somebody submits one of this database's forms",
131
+ "ig_profile_match": "Search Instagram for profiles matching your filters, on a schedule",
132
+ "button_clicked": "Somebody presses a button on a record",
133
+ "comment_added": "Somebody comments on a record",
134
+ }
135
+ #: Which section of the picker a trigger belongs to. Absent = "Standard" (C-TYPES).
136
+ group = {"ig_profile_match": "Sources"}
137
  out = []
138
  for k in engine.TRIGGER_KEYS:
139
+ # ⚠ `.get` WITH A DEFAULT, NOT `per[k]`. This loop walks the ENGINE's vocabulary and
140
+ # indexed a hand-maintained dict beside it: adding a key to `TRIGGER_KEYS` without
141
+ # remembering this dict raised KeyError and 500'd `GET /automations` β€” the payload the
142
+ # whole automation surface polls every 2.5 s β€” with every gate and `tsc` still green.
143
+ # Defaulting to "ready, needs nothing" is the honest fallback: a trigger the engine
144
+ # offers and this route has no readiness opinion about is simply available.
145
+ ready, needs = per.get(k, (True, ""))
146
  row = {"key": k, "label": engine.TRIGGER_LABELS[k], "ready": ready, "needs": needs,
147
+ "planned": False, "detail": detail.get(k, ""), "group": group.get(k, "Standard"),
148
  # A3(3): the connect affordance is SERVER-COMPOSED β€” the client never maps a
149
  # `needs` token to a route, so B's CONNECT_PROVIDERS shim deletes itself.
150
  "connect": None}
 
154
  out.append(row)
155
  for k in engine.TRIGGER_PLANNED:
156
  out.append({"key": k, "label": engine.TRIGGER_LABELS[k], "ready": False,
157
+ "needs": "coming_soon", "planned": True, "connect": None,
158
+ "detail": detail.get(k, ""), "group": group.get(k, "Standard")})
159
  return out
160
 
161
 
 
196
  items = [_wire(d, session.tenant) for _, d in
197
  sorted(defs.items(), key=lambda kv: (kv[1].get("name") or "").lower())]
198
  return {"automations": items,
199
+ # ⭐ WAVE 24 β€” DERIVED from the engine's own `KINDS`, not a hand-written trio. It was
200
+ # three literals that happened to match, which is a second copy of a server
201
+ # vocabulary; R6 has just made two of them uncreatable and `plain` has joined, so a
202
+ # hand list would now be wrong in three ways at once. `creatable` carries R6 onto the
203
+ # wire, so the ruling is a fact the client can read rather than one it must remember.
204
+ "kinds": [{"key": k, "label": engine.KIND_LABELS.get(k, k),
205
+ "creatable": k not in engine.RETIRED_KINDS}
206
+ for k in engine.KINDS],
207
  "cronPresets": engine.CRON_PRESETS,
208
  # ⚠ A BOOLEAN, NEVER THE KEY. The surface needs to say "the paid rung is not
209
  # configured" honestly instead of offering a tier that will silently refuse β€” and
 
286
  _C8_MIGRATED = set()
287
 
288
 
289
+ def _table_views(session, key):
290
+ """⭐ WAVE 24 (item 8) β€” the saved views on ONE user table as `[{id, label}]`, or **None**
291
+ when the workspace bucket could not be read at all.
292
+
293
+ The client said "This server did not offer a view list" because the payload genuinely had
294
+ no `views` key. C-TYPES: **absent stays ABSENT.** `[]` is a MEASUREMENT ("this database has
295
+ no saved views") and `None` is a STATE ("nobody looked") β€” collapsing them is precisely how
296
+ an empty picker comes to read as a claim about the database.
297
+
298
+ β›” SOURCED FROM `core.table_store`, WHICH IS THE READER `view_filter` ALREADY USES β€” not a
299
+ second one, the same one, listed instead of looked up. The brief said to source it the way
300
+ the grid does; the grid's projection (`aios_grid.views_from_defs`) is the wrong list HERE and
301
+ the difference matters: it INJECTS the system view ("All records") and PROJECTS cohorts as
302
+ views, and neither of those lives in the stored bucket β€” so `view_filter` answers "view no
303
+ longer exists" for every one of them. A picker built from that projection would offer options
304
+ the `enters_view` trigger cannot resolve, which is a worse bug than the missing key it fixes.
305
+ (An `enters_view` trigger on "All records" would also mean "fire on every record", so its
306
+ absence is correct rather than a gap.)
307
+
308
+ ⚠ `consume_corrections=False`: this is a READ for a picker, and the default MUTATES β€” it
309
+ takes and clears the pending field-correction acknowledgement, so listing views would eat a
310
+ protocol message meant for the grid.
311
+ """
312
+ try:
313
+ import core.table_store as table_store
314
+ # β›” THE REACHABILITY PROBE IS NOT REDUNDANT, and leaving it out was a real defect this
315
+ # gate's own NC caught: EVERY `TableStore` accessor wraps its store read in `try/except`
316
+ # and returns `{}` on failure. So a bucket that could not be read is indistinguishable
317
+ # from one with no views β€” which collapses exactly the ABSENT/EMPTY distinction this
318
+ # function exists to preserve, and the caller would ship `views: []` as a measurement
319
+ # nobody took. The one read that is allowed to raise has to be ours.
320
+ session.runtime.get(f"{key}_table_workspace")
321
+ tops = table_store.make(f"{key}_table_workspace", st=session.runtime)
322
+ own = (tops.workspace(session.uname, consume_corrections=False) or {}).get("views") or {}
323
+ shared = tops.shared_views(session.uname, session.admin) or {}
324
+ except Exception: # noqa: BLE001
325
+ return None
326
+ merged = {**shared, **own} # a view lives in ONE home; the merge is belt-and-braces
327
+ return sorted(
328
+ ({"id": str(vid), "label": str((v or {}).get("name") or vid)}
329
+ for vid, v in merged.items() if isinstance(v, dict)),
330
+ key=lambda r: r["label"].lower())
331
+
332
+
333
  @router.get("/automations/tables")
334
  def automation_tables(session: Session = Depends(_GATE)):
335
  """The blank databases an automation can target, with their fields.
 
364
  key=lambda kv: (kv[1].get("label") or "").lower()):
365
  if not user_tables.may_open(key, session.uname, session.admin, st=session.runtime):
366
  continue
367
+ row = {"key": key, "label": t.get("label") or key,
368
+ "source": t.get("source") or "Blank",
369
+ "rowCount": len(t.get("rows") or {}),
370
+ "fields": [{"key": f.get("key"), "label": f.get("label"),
371
+ "type": f.get("type") or "text",
372
+ "automation": f.get("automation") or None}
373
+ for f in (t.get("fields") or [])]}
374
+ views = _table_views(session, key)
375
+ if views is not None:
376
+ row["views"] = views # absent when the bucket did not answer β€” never []
377
+ out.append(row)
378
  return {"tables": out}
379
 
380
 
 
505
 
506
 
507
  @router.post("/automations/{auto_id}/hook/{token}")
508
+ async def automation_hook(auto_id: str, token: str, request: Request):
509
  """C3's webhook trigger β€” the tick-endpoint pattern one level down: unauthenticated BY
510
  DESIGN (the external caller has no cookie), gated on a per-automation token minted when the
511
  trigger was configured, constant-time compared. The tenant is FOUND by the (id, token)
512
  pair β€” a wrong token answers 403 for every tenant, so the route confirms nothing about
513
+ which slugs exist.
514
+
515
+ ⭐ WAVE 24 (D-41) β€” THE BODY IS READ DEFENSIVELY AND IS NEVER A REASON TO REFUSE.
516
+ β›” It is deliberately NOT declared as `body: dict = Body(...)`, which is the obvious way to
517
+ write this and would be a live regression: FastAPI would then VALIDATE the payload, so an
518
+ existing caller posting text, form-encoding, an empty body or slightly malformed JSON would
519
+ start getting a 422 from a door that has accepted anything since wave 22. A webhook sender is
520
+ somebody else's system; we do not get to change what it must send in order to fire a flow.
521
+ An unreadable body simply maps nothing β€” the flow still fires, exactly as it did before.
522
+
523
+ `run_in_threadpool` keeps the store I/O off the event loop: `hook_fire` walks every tenant
524
+ and may commit a row, and this handler had to become `async` only to read the request body.
525
+ """
526
+ from starlette.concurrency import run_in_threadpool
527
  from harness import runtime as _rt
528
 
529
+ try:
530
+ payload_in = await request.json()
531
+ except Exception: # noqa: BLE001
532
+ payload_in = None
533
+
534
+ def _fire():
535
+ last = (404, {"error": "unknown_automation",
536
+ "message": "no automation with that id and token"})
537
+ for slug in _rt.known_tenants():
538
+ try:
539
+ rt = _rt.get_runtime(slug)
540
+ except Exception: # noqa: BLE001
541
+ continue
542
+ status, payload = engine.hook_fire(rt, slug, auto_id, token, body=payload_in)
543
+ if status == 200:
544
+ return 200, payload
545
+ if status != 404:
546
+ last = (status, payload)
547
+ return last
548
+
549
+ status, payload = await run_in_threadpool(_fire)
550
+ if status == 200:
551
+ return payload
552
+ raise err(status, str(payload.get("error") or "refused"),
553
+ str(payload.get("message") or "refused"))
554
 
555
 
556
  @router.post("/automations/tick")
api/routes_keychain.py CHANGED
@@ -1,244 +1,260 @@
1
- """routes_keychain.py β€” Keychains + Connectors admin surfaces (wave 18, C7 / R3).
2
-
3
- Keychain: encrypted per-tenant credential entries (`core/keychain.py`). The routes NEVER
4
- return a decrypted field β€” list rows carry a masked preview, and the decrypt function is a
5
- connector-layer internal. Connectors: the tenant's data sources as STATUS rows β€” Royal's
6
- env-configured Odoo, keychain-held sources β€” plus R3's guardrail: the **Unsynced records**
7
- count (rows holding overlay data whose pids the current pool no longer serves; counted and
8
- drillable, never silently dropped) and a pause toggle whose v1 semantics are stated honestly
9
- in the payload (`pausedNote`): pausing marks intent and warns; the source cutover ships with
10
- the keychain cutover wave R3 staged.
11
- """
12
- import os
13
-
14
- from fastapi import Body, Depends
15
- from fastapi import APIRouter
16
-
17
- from deps import Session, err
18
- from routes_admin import admin_gate
19
-
20
- router = APIRouter(prefix="/api/v1")
21
-
22
- _CONNECTOR_FLAGS_KEY = "connectors"
23
- #: DEBT-2 (2026-08-04): the last-successful-sync snapshot bucket. Written when the RESOLVED
24
- #: odoo connector is paused; read by the pool path while paused; survives a Space restart.
25
- SNAPSHOT_KEY = "connector_snapshots"
26
-
27
-
28
- def _kc():
29
- import core.keychain as keychain
30
- return keychain
31
-
32
-
33
- def _resolved_odoo_key(rt):
34
- """Which source would serve this tenant's Odoo queries β€” the ROUTE-LEVEL mirror of
35
- TenantRuntime.odoo_source(): first unlocked keychain odoo entry, else env for tenant #0
36
- only, else None. Takes the runtime (not the session) so the pool path can ask too."""
37
- kc = _kc()
38
- try:
39
- entries = kc.list_entries(rt)
40
- except Exception:
41
- entries = []
42
- first_odoo = next((e["id"] for e in entries if e["type"] == "odoo"), None)
43
- if first_odoo and kc.unlocked():
44
- return f"keychain:{first_odoo}", first_odoo
45
- if rt.key == "royal-imports" and os.environ.get("ODOO_URL"):
46
- return "env", "odoo-env"
47
- return None, None
48
-
49
-
50
- def odoo_paused(rt):
51
- """True when the tenant's RESOLVED Odoo source carries the pause flag. Pausing an entry
52
- that is not the resolved source freezes nothing β€” it serves nothing."""
53
- try:
54
- _, flag_key = _resolved_odoo_key(rt)
55
- if not flag_key:
56
- return False
57
- flags = rt.get(_CONNECTOR_FLAGS_KEY) or {}
58
- return bool((flags.get(flag_key) or {}).get("paused"))
59
- except Exception:
60
- return False # an unreachable flags bucket must never freeze a live surface
61
-
62
-
63
- def _snap_scope_key(team_id, agent):
64
- return f"t={team_id}|a={agent}"
65
-
66
-
67
- def load_pool_snapshot(rt, team_id, agent):
68
- """(ts, rows) from the persisted snapshot for this exact scope, or None. NEVER a wider
69
- scope's rows β€” serving the consolidated snapshot to a scoped user would widen their book."""
70
- try:
71
- snap = (rt.get(SNAPSHOT_KEY) or {}).get("odoo_pool") or {}
72
- e = snap.get(_snap_scope_key(team_id, agent))
73
- if isinstance(e, dict) and isinstance(e.get("rows"), list):
74
- return float(e.get("ts") or 0), e["rows"]
75
- except Exception:
76
- pass
77
- return None
78
-
79
-
80
- def save_pool_snapshots(rt, taken_by=""):
81
- """Persist every currently-cached pool scope as the pause-time snapshot ('the last
82
- successful sync', made concrete). Ensures the consolidated default scope exists first so
83
- a pause on a cold process still captures something to serve."""
84
- import time as _time
85
- import routes_customers as _rc
86
- try:
87
- _rc._pool_for(rt, None, None) # the scope every admin/all-BU account lands on
88
- except Exception:
89
- pass # cold + Odoo down: persist whatever IS cached
90
- pools = {}
91
- for key, entry in list(rt.pool_cache.items()):
92
- if (isinstance(key, tuple) and len(key) == 3 and key[0] == "pool"
93
- and isinstance(entry, tuple) and len(entry) == 2
94
- and isinstance(entry[1], list)):
95
- pools[_snap_scope_key(key[1], key[2])] = {"ts": entry[0], "rows": entry[1]}
96
- if not pools:
97
- return 0
98
-
99
- def _up(cur):
100
- cur["odoo_pool"] = pools
101
- cur["taken"] = _time.strftime("%Y-%m-%dT%H:%M:%S")
102
- cur["takenBy"] = str(taken_by or "")
103
- return cur
104
-
105
- rt.update(SNAPSHOT_KEY, _up, flush="sync")
106
- return len(pools)
107
-
108
-
109
- @router.get("/admin/keychain")
110
- def list_keychain(session: Session = Depends(admin_gate)):
111
- kc = _kc()
112
- return {"entries": kc.list_entries(session.runtime), "locked": not kc.unlocked()}
113
-
114
-
115
- @router.post("/admin/keychain", status_code=201)
116
- def add_key(body: dict = Body(default=None), session: Session = Depends(admin_gate)):
117
- kc = _kc()
118
- body = body or {}
119
- if not session.runtime.available():
120
- raise err(503, "store_unavailable", "the tenant store is unavailable")
121
- try:
122
- row = kc.add_entry(session.runtime, body.get("label"), body.get("type"),
123
- body.get("fields"), session.uname)
124
- except kc.KeychainLocked as e:
125
- raise err(503, "keychain_locked",
126
- f"the keychain is locked β€” {e}. A secret is never stored unencrypted.")
127
- except ValueError as e:
128
- raise err(400, "bad_entry", str(e))
129
- except Exception:
130
- raise err(503, "store_unavailable", "the entry was not saved β€” try again")
131
- return {"entry": row}
132
-
133
-
134
- @router.delete("/admin/keychain/{entry_id}")
135
- def delete_key(entry_id: str, session: Session = Depends(admin_gate)):
136
- try:
137
- _kc().delete_entry(session.runtime, entry_id)
138
- except Exception:
139
- raise err(503, "store_unavailable", "the delete did not land β€” try again")
140
- return {"ok": True}
141
-
142
-
143
- @router.post("/admin/keychain/{entry_id}/test")
144
- def test_key(entry_id: str, session: Session = Depends(admin_gate)):
145
- return _kc().test_entry(session.runtime, entry_id)
146
-
147
-
148
- def _unsynced_customer_records(session):
149
- """R3's guardrail, tenant #0's customer topic: overlay-holding pids the CURRENT pool no
150
- longer serves. Overlays are unioned across EVERY user of the table (the guardrail is a
151
- tenant fact, not a per-user one). Honest degradation: when the pool cannot be built the
152
- answer is `known: False`, never a fabricated zero."""
153
- try:
154
- import core.table_store as table_store
155
- bucket = session.runtime.get("customer_table_workspace") or {}
156
- overlay_pids = {}
157
- for uname, ws in bucket.items():
158
- if uname == table_store.SHARED_KEY or not isinstance(ws, dict):
159
- continue
160
- for pid, cells in (ws.get("overlays") or {}).items():
161
- if isinstance(cells, dict) and cells:
162
- overlay_pids.setdefault(str(pid), cells)
163
- if not overlay_pids:
164
- return {"known": True, "count": 0, "rows": []}
165
- from routes_customers import allowed_pids
166
- pool = {str(p) for p in allowed_pids(session)}
167
- orphans = sorted((p for p in overlay_pids if p not in pool), key=lambda x: int(x)
168
- if str(x).isdigit() else 0)
169
- rows = []
170
- for p in orphans[:50]:
171
- cells = overlay_pids[p]
172
- hint = next((str(v) for v in cells.values() if str(v).strip()), "")
173
- rows.append({"pid": int(p) if str(p).isdigit() else p,
174
- "fields": len(cells), "hint": hint[:80]})
175
- return {"known": True, "count": len(orphans), "rows": rows,
176
- "shown": min(len(orphans), 50)}
177
- except Exception as e:
178
- return {"known": False, "count": None, "rows": [],
179
- "note": f"pool unavailable β€” {type(e).__name__}"}
180
-
181
-
182
- @router.get("/admin/connectors")
183
- def connectors(session: Session = Depends(admin_gate)):
184
- kc = _kc()
185
- flags = session.runtime.get(_CONNECTOR_FLAGS_KEY) or {}
186
- entries = kc.list_entries(session.runtime)
187
- # R3 cutover (2026-08-04): which source would actually serve this tenant's Odoo queries β€”
188
- # mirrors TenantRuntime.odoo_source() exactly: first unlocked keychain odoo entry, else env
189
- # for tenant #0 only, else nothing (fail closed β€” never another tenant's environment).
190
- first_odoo = next((e["id"] for e in entries if e["type"] == "odoo"), None)
191
- if first_odoo and kc.unlocked():
192
- resolved = f"keychain:{first_odoo}"
193
- elif session.tenant == "royal-imports" and os.environ.get("ODOO_URL"):
194
- resolved = "env"
195
- else:
196
- resolved = None
197
- rows = []
198
- if session.tenant == "royal-imports" and os.environ.get("ODOO_URL"):
199
- rows.append({"key": "odoo-env", "label": "Odoo (environment)", "type": "odoo",
200
- "source": "env", "active": resolved == "env",
201
- "paused": bool((flags.get("odoo-env") or {}).get("paused"))})
202
- for e in entries:
203
- rows.append({"key": e["id"], "label": e["label"], "type": e["type"],
204
- "source": "keychain", "preview": e["preview"],
205
- "active": (e["type"] == "odoo" and resolved == f"keychain:{e['id']}"),
206
- "paused": bool((flags.get(e["id"]) or {}).get("paused"))})
207
- out = {"connectors": rows, "locked": not kc.unlocked(), "resolved": resolved,
208
- # DEBT-2 (2026-08-04): pause now MEANS something β€” the customer pool freezes on the
209
- # pause-time snapshot (persisted, restart-safe) and Unsynced records counts against
210
- # that snapshot. Stated honestly: measure/page computations still reach the source
211
- # for questions not already memoized; their full freeze rides the module cutovers.
212
- "pausedNote": ("Pausing a connector never deletes data β€” notes, custom fields and "
213
- "views stay. While paused, the customer workspace serves the "
214
- "pause-time snapshot instead of reading live; measures not already "
215
- "computed may still reach the source until their cutover.")}
216
- if session.tenant == "royal-imports":
217
- out["unsynced"] = _unsynced_customer_records(session)
218
- return out
219
-
220
-
221
- @router.post("/admin/connectors/{key}/pause")
222
- def pause_connector(key: str, body: dict = Body(default=None),
223
- session: Session = Depends(admin_gate)):
224
- paused = bool((body or {}).get("paused"))
225
- if not session.runtime.available():
226
- raise err(503, "store_unavailable", "the tenant store is unavailable")
227
-
228
- # DEBT-2: pausing the RESOLVED Odoo source captures the snapshot FIRST, so there is a
229
- # "last successful sync" to serve before the freeze takes effect. Capturing before the
230
- # flag flips means a failed capture leaves the connector live (never paused-with-nothing).
231
- snapshots = 0
232
- _, flag_key = _resolved_odoo_key(session.runtime)
233
- if paused and flag_key and str(key) == flag_key:
234
- snapshots = save_pool_snapshots(session.runtime, taken_by=session.uname)
235
-
236
- def _up(cur):
237
- cur[str(key)] = {"paused": paused}
238
- return cur
239
-
240
- try:
241
- session.runtime.update(_CONNECTOR_FLAGS_KEY, _up)
242
- except Exception:
243
- raise err(503, "store_unavailable", "the change was not saved β€” try again")
244
- return {"key": key, "paused": paused, "snapshots": snapshots}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """routes_keychain.py β€” Keychains + Connectors admin surfaces (wave 18, C7 / R3).
2
+
3
+ Keychain: encrypted per-tenant credential entries (`core/keychain.py`). The routes NEVER
4
+ return a decrypted field β€” list rows carry a masked preview, and the decrypt function is a
5
+ connector-layer internal. Connectors: the tenant's data sources as STATUS rows β€” Royal's
6
+ env-configured Odoo, keychain-held sources β€” plus R3's guardrail: the **Unsynced records**
7
+ count (rows holding overlay data whose pids the current pool no longer serves; counted and
8
+ drillable, never silently dropped) and a pause toggle whose v1 semantics are stated honestly
9
+ in the payload (`pausedNote`): pausing marks intent and warns; the source cutover ships with
10
+ the keychain cutover wave R3 staged.
11
+ """
12
+ import os
13
+
14
+ from fastapi import Body, Depends
15
+ from fastapi import APIRouter
16
+
17
+ from deps import Session, err
18
+ from routes_admin import admin_gate
19
+
20
+ router = APIRouter(prefix="/api/v1")
21
+
22
+ #: ⭐ D-10 (wave 24): ONE literal, owned by the harness. It was spelled here AND implied by
23
+ #: `harness/runtime.py`'s reader; a pause flag written under one spelling and read under another
24
+ #: freezes nothing while reporting success, which is the shape of the bug D-10 books.
25
+ from harness.runtime import (CONNECTOR_FLAGS_KEY as _CONNECTOR_FLAGS_KEY, # noqa: E402
26
+ ENV_ODOO_FLAG_KEY as _ENV_ODOO_FLAG_KEY)
27
+ #: DEBT-2 (2026-08-04): the last-successful-sync snapshot bucket. Written when the RESOLVED
28
+ #: odoo connector is paused; read by the pool path while paused; survives a Space restart.
29
+ SNAPSHOT_KEY = "connector_snapshots"
30
+
31
+
32
+ def _kc():
33
+ import core.keychain as keychain
34
+ return keychain
35
+
36
+
37
+ def _resolved_odoo_key(rt):
38
+ """`(source, flag_key)` β€” which source would serve this tenant's Odoo queries, in both the
39
+ shapes this module needs: the display string (`env` / `keychain:<id>`) and the key the pause
40
+ flag is stored under.
41
+
42
+ ⭐ D-10 (wave 24): THE RESOLUTION ITSELF NOW LIVES IN ONE PLACE, `TenantRuntime.odoo_flag_key`,
43
+ beside the `odoo_source()` it must agree with. This function had its own copy of the same
44
+ three rules β€” first unlocked keychain odoo entry, else env for tenant #0, else nothing β€” and
45
+ a second copy is exactly how a pause flag comes to be written against one resolution and read
46
+ against another, freezing nothing while the UI reports success. The two SHAPES stay here
47
+ because they are this module's presentation concern; the DECISION does not.
48
+ """
49
+ flag_key = rt.odoo_flag_key()
50
+ if not flag_key:
51
+ return None, None
52
+ return ("env" if flag_key == _ENV_ODOO_FLAG_KEY else f"keychain:{flag_key}"), flag_key
53
+
54
+
55
+ def odoo_paused(rt):
56
+ """True when the tenant's RESOLVED Odoo source carries the pause flag. Pausing an entry
57
+ that is not the resolved source freezes nothing β€” it serves nothing.
58
+
59
+ ⭐ D-10: a thin delegate now. The implementation moved to `TenantRuntime.odoo_paused` so the
60
+ measure mirror (`harness/datastore.py`, which cannot import this layer) asks the SAME question
61
+ the customer pool does. This name stays because `routes_customers`, `routes_products` and
62
+ `verify_api` all call it β€” moving the logic without moving the door keeps one answer and
63
+ costs no caller a change.
64
+ """
65
+ return bool(rt.odoo_paused())
66
+
67
+
68
+ def _snap_scope_key(team_id, agent):
69
+ return f"t={team_id}|a={agent}"
70
+
71
+
72
+ def load_pool_snapshot(rt, team_id, agent):
73
+ """(ts, rows) from the persisted snapshot for this exact scope, or None. NEVER a wider
74
+ scope's rows β€” serving the consolidated snapshot to a scoped user would widen their book."""
75
+ try:
76
+ snap = (rt.get(SNAPSHOT_KEY) or {}).get("odoo_pool") or {}
77
+ e = snap.get(_snap_scope_key(team_id, agent))
78
+ if isinstance(e, dict) and isinstance(e.get("rows"), list):
79
+ return float(e.get("ts") or 0), e["rows"]
80
+ except Exception:
81
+ pass
82
+ return None
83
+
84
+
85
+ def save_pool_snapshots(rt, taken_by=""):
86
+ """Persist every currently-cached pool scope as the pause-time snapshot ('the last
87
+ successful sync', made concrete). Ensures the consolidated default scope exists first so
88
+ a pause on a cold process still captures something to serve."""
89
+ import time as _time
90
+ import routes_customers as _rc
91
+ try:
92
+ _rc._pool_for(rt, None, None) # the scope every admin/all-BU account lands on
93
+ except Exception:
94
+ pass # cold + Odoo down: persist whatever IS cached
95
+ pools = {}
96
+ for key, entry in list(rt.pool_cache.items()):
97
+ if (isinstance(key, tuple) and len(key) == 3 and key[0] == "pool"
98
+ and isinstance(entry, tuple) and len(entry) == 2
99
+ and isinstance(entry[1], list)):
100
+ pools[_snap_scope_key(key[1], key[2])] = {"ts": entry[0], "rows": entry[1]}
101
+ if not pools:
102
+ return 0
103
+
104
+ def _up(cur):
105
+ cur["odoo_pool"] = pools
106
+ cur["taken"] = _time.strftime("%Y-%m-%dT%H:%M:%S")
107
+ cur["takenBy"] = str(taken_by or "")
108
+ return cur
109
+
110
+ rt.update(SNAPSHOT_KEY, _up, flush="sync")
111
+ return len(pools)
112
+
113
+
114
+ @router.get("/admin/keychain")
115
+ def list_keychain(session: Session = Depends(admin_gate)):
116
+ kc = _kc()
117
+ return {"entries": kc.list_entries(session.runtime), "locked": not kc.unlocked()}
118
+
119
+
120
+ @router.post("/admin/keychain", status_code=201)
121
+ def add_key(body: dict = Body(default=None), session: Session = Depends(admin_gate)):
122
+ kc = _kc()
123
+ body = body or {}
124
+ if not session.runtime.available():
125
+ raise err(503, "store_unavailable", "the tenant store is unavailable")
126
+ try:
127
+ row = kc.add_entry(session.runtime, body.get("label"), body.get("type"),
128
+ body.get("fields"), session.uname)
129
+ except kc.KeychainLocked as e:
130
+ raise err(503, "keychain_locked",
131
+ f"the keychain is locked β€” {e}. A secret is never stored unencrypted.")
132
+ except ValueError as e:
133
+ raise err(400, "bad_entry", str(e))
134
+ except Exception:
135
+ raise err(503, "store_unavailable", "the entry was not saved β€” try again")
136
+ return {"entry": row}
137
+
138
+
139
+ @router.delete("/admin/keychain/{entry_id}")
140
+ def delete_key(entry_id: str, session: Session = Depends(admin_gate)):
141
+ try:
142
+ _kc().delete_entry(session.runtime, entry_id)
143
+ except Exception:
144
+ raise err(503, "store_unavailable", "the delete did not land β€” try again")
145
+ return {"ok": True}
146
+
147
+
148
+ @router.post("/admin/keychain/{entry_id}/test")
149
+ def test_key(entry_id: str, session: Session = Depends(admin_gate)):
150
+ return _kc().test_entry(session.runtime, entry_id)
151
+
152
+
153
+ def _unsynced_customer_records(session):
154
+ """R3's guardrail, tenant #0's customer topic: overlay-holding pids the CURRENT pool no
155
+ longer serves. Overlays are unioned across EVERY user of the table (the guardrail is a
156
+ tenant fact, not a per-user one). Honest degradation: when the pool cannot be built the
157
+ answer is `known: False`, never a fabricated zero."""
158
+ try:
159
+ import core.table_store as table_store
160
+ bucket = session.runtime.get("customer_table_workspace") or {}
161
+ overlay_pids = {}
162
+ for uname, ws in bucket.items():
163
+ if uname == table_store.SHARED_KEY or not isinstance(ws, dict):
164
+ continue
165
+ for pid, cells in (ws.get("overlays") or {}).items():
166
+ if isinstance(cells, dict) and cells:
167
+ overlay_pids.setdefault(str(pid), cells)
168
+ if not overlay_pids:
169
+ return {"known": True, "count": 0, "rows": []}
170
+ from routes_customers import allowed_pids
171
+ pool = {str(p) for p in allowed_pids(session)}
172
+ orphans = sorted((p for p in overlay_pids if p not in pool), key=lambda x: int(x)
173
+ if str(x).isdigit() else 0)
174
+ rows = []
175
+ for p in orphans[:50]:
176
+ cells = overlay_pids[p]
177
+ hint = next((str(v) for v in cells.values() if str(v).strip()), "")
178
+ rows.append({"pid": int(p) if str(p).isdigit() else p,
179
+ "fields": len(cells), "hint": hint[:80]})
180
+ return {"known": True, "count": len(orphans), "rows": rows,
181
+ "shown": min(len(orphans), 50)}
182
+ except Exception as e:
183
+ return {"known": False, "count": None, "rows": [],
184
+ "note": f"pool unavailable β€” {type(e).__name__}"}
185
+
186
+
187
+ @router.get("/admin/connectors")
188
+ def connectors(session: Session = Depends(admin_gate)):
189
+ kc = _kc()
190
+ flags = session.runtime.get(_CONNECTOR_FLAGS_KEY) or {}
191
+ entries = kc.list_entries(session.runtime)
192
+ # R3 cutover (2026-08-04): which source would actually serve this tenant's Odoo queries β€”
193
+ # mirrors TenantRuntime.odoo_source() exactly: first unlocked keychain odoo entry, else env
194
+ # for tenant #0 only, else nothing (fail closed β€” never another tenant's environment).
195
+ first_odoo = next((e["id"] for e in entries if e["type"] == "odoo"), None)
196
+ if first_odoo and kc.unlocked():
197
+ resolved = f"keychain:{first_odoo}"
198
+ elif session.tenant == "royal-imports" and os.environ.get("ODOO_URL"):
199
+ resolved = "env"
200
+ else:
201
+ resolved = None
202
+ rows = []
203
+ if session.tenant == "royal-imports" and os.environ.get("ODOO_URL"):
204
+ rows.append({"key": _ENV_ODOO_FLAG_KEY, "label": "Odoo (environment)", "type": "odoo",
205
+ "source": "env", "active": resolved == "env",
206
+ "paused": bool((flags.get(_ENV_ODOO_FLAG_KEY) or {}).get("paused"))})
207
+ for e in entries:
208
+ rows.append({"key": e["id"], "label": e["label"], "type": e["type"],
209
+ "source": "keychain", "preview": e["preview"],
210
+ "active": (e["type"] == "odoo" and resolved == f"keychain:{e['id']}"),
211
+ "paused": bool((flags.get(e["id"]) or {}).get("paused"))})
212
+ out = {"connectors": rows, "locked": not kc.unlocked(), "resolved": resolved,
213
+ # ⭐ D-10 (wave 24) β€” THIS SENTENCE IS NOW TRUE OF EVERY PATH, which it was not before.
214
+ # DEBT-2 (2026-08-04) froze the CUSTOMER pool and this note honestly disclosed the
215
+ # hole it left: "measures not already computed may still reach the source". D-10
216
+ # closed that hole β€” `harness/datastore.py` (the mirror every measure column is
217
+ # answered from) refuses to sync while paused, and `routes_products._pool_for` got the
218
+ # guard its customer sibling has had since DEBT-2. So the caveat is deleted rather
219
+ # than left standing, because a warning that outlives its defect teaches the reader to
220
+ # ignore warnings.
221
+ # ⚠ THE THREE BEHAVIOURS ARE NAMED SEPARATELY on purpose: they are genuinely
222
+ # different answers (a persisted snapshot, an in-process cache, a frozen mirror), and
223
+ # collapsing them into "everything freezes" would be the kind of tidy summary that
224
+ # stops being true the first time one of them changes.
225
+ "pausedNote": ("Pausing a connector never deletes data β€” notes, custom fields and "
226
+ "views stay, and nothing reaches the source while it is paused. The "
227
+ "customer workspace serves its pause-time snapshot, the product list "
228
+ "serves the last copy this server read, and measure columns keep "
229
+ "answering from the mirror as it stood when you paused β€” so figures "
230
+ "stop moving rather than going blank. Resume to start reading live "
231
+ "again.")}
232
+ if session.tenant == "royal-imports":
233
+ out["unsynced"] = _unsynced_customer_records(session)
234
+ return out
235
+
236
+
237
+ @router.post("/admin/connectors/{key}/pause")
238
+ def pause_connector(key: str, body: dict = Body(default=None),
239
+ session: Session = Depends(admin_gate)):
240
+ paused = bool((body or {}).get("paused"))
241
+ if not session.runtime.available():
242
+ raise err(503, "store_unavailable", "the tenant store is unavailable")
243
+
244
+ # DEBT-2: pausing the RESOLVED Odoo source captures the snapshot FIRST, so there is a
245
+ # "last successful sync" to serve before the freeze takes effect. Capturing before the
246
+ # flag flips means a failed capture leaves the connector live (never paused-with-nothing).
247
+ snapshots = 0
248
+ _, flag_key = _resolved_odoo_key(session.runtime)
249
+ if paused and flag_key and str(key) == flag_key:
250
+ snapshots = save_pool_snapshots(session.runtime, taken_by=session.uname)
251
+
252
+ def _up(cur):
253
+ cur[str(key)] = {"paused": paused}
254
+ return cur
255
+
256
+ try:
257
+ session.runtime.update(_CONNECTOR_FLAGS_KEY, _up)
258
+ except Exception:
259
+ raise err(503, "store_unavailable", "the change was not saved β€” try again")
260
+ return {"key": key, "paused": paused, "snapshots": snapshots}
api/routes_products.py CHANGED
@@ -48,7 +48,31 @@ def _pool_for(rt, team_id):
48
  # after the build lambda and DIED on every call ("multiple values for 'ttl'"). Latent until
49
  # wave 16 because nothing drove this route end-to-end: verify_perm_scope's section H stubs
50
  # the pool a layer below. verify_api's W16 section now exercises the real call.
51
- return scope_cache.get(rt.pool_cache, ("product_pool", team_id), _CACHE_TTL,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  lambda: pd.pool(team_id=team_id))
53
 
54
 
 
48
  # after the build lambda and DIED on every call ("multiple values for 'ttl'"). Latent until
49
  # wave 16 because nothing drove this route end-to-end: verify_perm_scope's section H stubs
50
  # the pool a layer below. verify_api's W16 section now exercises the real call.
51
+ key = ("product_pool", team_id)
52
+
53
+ # ⭐ D-10 (wave 24) β€” THE PRODUCT POOL HONOURS THE CONNECTOR PAUSE. It did not, and that was
54
+ # a shipped defect on a live surface: the CUSTOMER pool got this guard at DEBT-2 and its
55
+ # sibling β€” written from the same template, four files away β€” never did. So pausing Odoo
56
+ # froze the Customer grid and the Product grid kept reading live, with the Settings toggle
57
+ # reporting success. Sibling caches diverge exactly this way and nothing greps for
58
+ # "the other one".
59
+ #
60
+ # ⚠ NO SNAPSHOT LEG, and that is the honest difference from the customer path rather than an
61
+ # omission: `save_pool_snapshots` persists the `odoo_pool` scopes only β€” there is no product
62
+ # snapshot bucket to serve. So this serves the in-process copy AT ANY AGE, and answers 503
63
+ # naming the pause when there is none. Minting a product snapshot here would be a new
64
+ # persistence format at a wave tail; refusing with a sentence is the answer the user can act
65
+ # on, and it is the same 503 the customer path already gives for an unsnapshotted scope.
66
+ import routes_keychain
67
+ if routes_keychain.odoo_paused(rt):
68
+ hit = rt.pool_cache.get(key)
69
+ if hit:
70
+ return hit[1]
71
+ raise err(503, "connector_paused",
72
+ "this data source is paused and nothing has been read since β€” "
73
+ "an admin can resume it under Settings β†’ Connectors")
74
+
75
+ return scope_cache.get(rt.pool_cache, key, _CACHE_TTL,
76
  lambda: pd.pool(team_id=team_id))
77
 
78
 
platform/harness/datastore.py CHANGED
@@ -38,6 +38,67 @@ _STORE_DIR = Path(__file__).resolve().parents[1] / "data" / "store"
38
  DB_PATH = Path(os.environ.get("AIOS_DUCKDB_PATH") or (_STORE_DIR / "royal.duckdb"))
39
 
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  def path_for(tenant_key):
42
  """The canonical DuckDB file for a tenant slug. `royal-imports` keeps the historical
43
  `royal.duckdb` name so tenant #0's existing 175 MB file is not orphaned by a rename.
@@ -516,7 +577,16 @@ def _base_domain(spec):
516
 
517
  def sync_entity(key, max_batches=200, batch=BATCH, log=print):
518
  """One bounded, resumable sync pass for an entity. Backfill (by id) β†’ live (by write_date).
519
- Returns (phase, pulled_rows)."""
 
 
 
 
 
 
 
 
 
520
  spec = ENTITIES[key]
521
  con = connect()
522
  _ensure_table(con, key, spec)
@@ -624,6 +694,14 @@ def _already(con, key, rec):
624
 
625
 
626
  def sync_all(entities=None, max_batches=200, log=print):
 
 
 
 
 
 
 
 
627
  out = {}
628
  for key in (entities or list(ENTITIES)):
629
  t0 = time.time()
@@ -641,7 +719,14 @@ def reconcile_deletes(entities=None, log=print):
641
  sync can never see a deletion β€” the count parity DETECTS the drift (by design); this repairs
642
  it. Pulls the full live id set per entity in bounded id-ascending pages (id-only reads are
643
  cheap) and deletes store ids not present live. Run from sync_runner / maintenance, not the
644
- app's frequent passes."""
 
 
 
 
 
 
 
645
  con = connect()
646
  try:
647
  out = {}
@@ -690,7 +775,21 @@ def _check(name, ours, live, tol=0.01):
690
 
691
  def validate(pre=None, months=("2026-01-01", "2026-07-01")):
692
  """Raw-fidelity parity: the store must mirror live Odoo β€” row counts per synced entity +
693
- unscoped monetary sums over a window, to the cent. Only checks entities in LIVE phase."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
694
  con = connect()
695
  out = []
696
  try:
 
38
  DB_PATH = Path(os.environ.get("AIOS_DUCKDB_PATH") or (_STORE_DIR / "royal.duckdb"))
39
 
40
 
41
+ # ─────────────────────────────────────────────────────────────────────────────────────────────
42
+ # ⭐ DEBT D-10 (wave 24) β€” THE CONNECTOR PAUSE REACHES THE MEASURE MIRROR.
43
+ #
44
+ # WHAT THE BUG WAS. Pausing a tenant's Odoo connector froze the CUSTOMER POOL (DEBT-2 built that:
45
+ # `routes_customers._pool_for` serves the pause-time snapshot) and nothing else. Every measure
46
+ # column and condition in the product is answered from THIS store, and this store kept pulling
47
+ # from Odoo the entire time a connector was paused β€” 12 sync passes at boot and another every
48
+ # 1800 s, hundreds of `search_read`s each. The Settings copy said so out loud ("measures not
49
+ # already computed may still reach the source until their cutover") and that sentence was the
50
+ # debt row.
51
+ #
52
+ # β›” WHY A PROBE AND NOT AN IMPORT. The pause flag lives in the tenant's store bucket, which is
53
+ # `harness.runtime`'s to read β€” and `runtime` already imports THIS module (`_ds.DB_PATH`), so an
54
+ # import back would be a cycle. The harness installs the probe at its own import instead. Nothing
55
+ # else changes: with no probe installed (every gate, every ops script, `sync_runner`) the answer
56
+ # is False and this module behaves exactly as it did.
57
+ #
58
+ # ⚠ IT FAILS TOWARDS "NOT PAUSED", deliberately and consistently with the shipped decision one
59
+ # layer up (`routes_keychain.odoo_paused`: "an unreachable flags bucket must never freeze a live
60
+ # surface"). The alternative β€” assume paused when the answer cannot be resolved β€” turns any
61
+ # transient store glitch into a mirror that silently stops advancing, which is the failure mode
62
+ # nobody notices for a week. Two copies of that policy would be worse than one; this is the same
63
+ # one.
64
+ _paused_probe = None
65
+
66
+
67
+ def set_paused_probe(fn):
68
+ """Install the callable that answers 'is the connector paused for the tenant whose store this
69
+ process has open?'. `harness.runtime` installs the real one; pass None to remove it."""
70
+ global _paused_probe
71
+ _paused_probe = fn
72
+
73
+
74
+ def source_paused():
75
+ """True when this store's tenant has its Odoo connector paused. Never raises."""
76
+ try:
77
+ return bool(_paused_probe and _paused_probe())
78
+ except Exception:
79
+ return False
80
+
81
+
82
+ #: What a sync entry point answers instead of reaching Odoo. A PHASE WORD, not an exception and
83
+ #: not a silent zero-row success: `status()` keeps whatever the last real pass wrote, so the
84
+ #: mirror still reports the age it genuinely has ([[no-unverifiable-aggregates]] β€” a paused
85
+ #: mirror that reported itself as freshly synced would be the unverifiable claim).
86
+ PAUSED_PHASE = "paused"
87
+
88
+
89
+ def _paused_notice(what, log):
90
+ # Printed as well as logged, and that is deliberate: `api/main.py` passes a swallowing
91
+ # `log=lambda *a, **k: None`, so the log-only version of this line would never be seen by
92
+ # the one caller that runs it unattended every 30 minutes.
93
+ msg = (f"[datastore] {what} skipped - the tenant's Odoo connector is PAUSED; the mirror is "
94
+ f"serving its pause-time state. Resume it under Settings > Connectors.")
95
+ try:
96
+ log(msg)
97
+ except Exception:
98
+ pass
99
+ print(msg)
100
+
101
+
102
  def path_for(tenant_key):
103
  """The canonical DuckDB file for a tenant slug. `royal-imports` keeps the historical
104
  `royal.duckdb` name so tenant #0's existing 175 MB file is not orphaned by a rename.
 
577
 
578
  def sync_entity(key, max_batches=200, batch=BATCH, log=print):
579
  """One bounded, resumable sync pass for an entity. Backfill (by id) β†’ live (by write_date).
580
+ Returns (phase, pulled_rows).
581
+
582
+ ⭐ D-10: refuses BEFORE opening a cursor or touching Odoo while the connector is paused. The
583
+ guard is here β€” the innermost function that reads from `O` β€” rather than only in `sync_all`,
584
+ so a caller that syncs ONE entity is covered by construction instead of by remembering to
585
+ add the same check. `sync_all` short-circuits too, but only to avoid eight identical notices.
586
+ """
587
+ if source_paused():
588
+ _paused_notice(f"sync of {key}", log)
589
+ return PAUSED_PHASE, 0
590
  spec = ENTITIES[key]
591
  con = connect()
592
  _ensure_table(con, key, spec)
 
694
 
695
 
696
  def sync_all(entities=None, max_batches=200, log=print):
697
+ # ⭐ D-10. `{}` rather than a dict of paused phases, and the caller decides why that matters:
698
+ # `api/main.py:354` loops up to 12 times until `all(phase == "live")`, and `all()` over an
699
+ # empty dict is True β€” so a paused store costs ONE pass instead of twelve rounds of the same
700
+ # refusal. A dict of `"paused"` phases would fail that test every time and turn the boot
701
+ # sprint into a busy-wait against a connector nobody has resumed.
702
+ if source_paused():
703
+ _paused_notice("sync", log)
704
+ return {}
705
  out = {}
706
  for key in (entities or list(ENTITIES)):
707
  t0 = time.time()
 
719
  sync can never see a deletion β€” the count parity DETECTS the drift (by design); this repairs
720
  it. Pulls the full live id set per entity in bounded id-ascending pages (id-only reads are
721
  cheap) and deletes store ids not present live. Run from sync_runner / maintenance, not the
722
+ app's frequent passes.
723
+
724
+ ⭐ D-10: it pulls the FULL live id set per entity, so it is the single largest Odoo read in
725
+ this module and it runs unattended at boot and every fourth resync pass. Paused means paused.
726
+ """
727
+ if source_paused():
728
+ _paused_notice("delete reconcile", log)
729
+ return {}
730
  con = connect()
731
  try:
732
  out = {}
 
775
 
776
  def validate(pre=None, months=("2026-01-01", "2026-07-01")):
777
  """Raw-fidelity parity: the store must mirror live Odoo β€” row counts per synced entity +
778
+ unscoped monetary sums over a window, to the cent. Only checks entities in LIVE phase.
779
+
780
+ ⭐ D-10 REFUSES LOUDLY HERE rather than skipping quietly, and the difference matters. Every
781
+ other paused path has a correct silent answer β€” serve the mirror β€” because the mirror is the
782
+ thing being asked for. This function's ENTIRE contract is "compare me against live Odoo", so
783
+ a paused version of it has no honest result: skipping would return an empty pass, and
784
+ proceeding would make the live call the pause forbids. An operator running a reconciliation
785
+ against a paused connector has asked a question that cannot be answered, and being told so is
786
+ the only outcome that is not a lie. (Operator-invoked only β€” nothing in the serving path
787
+ calls it, so this raises for a person, never inside a request.)
788
+ """
789
+ if source_paused():
790
+ raise RuntimeError(
791
+ "the tenant's Odoo connector is PAUSED, so the store cannot be validated against "
792
+ "live Odoo - resume it under Settings > Connectors and run this again")
793
  con = connect()
794
  out = []
795
  try:
platform/harness/runtime.py CHANGED
@@ -36,6 +36,7 @@ import os
36
  import threading
37
  from collections import OrderedDict
38
  from dataclasses import dataclass, field
 
39
 
40
  import core.store as store
41
  from harness import datastore as _ds
@@ -61,6 +62,15 @@ _CACHE: "OrderedDict[str, TenantRuntime]" = OrderedDict()
61
  _LOCK = threading.RLock()
62
 
63
 
 
 
 
 
 
 
 
 
 
64
  @dataclass
65
  class TenantRuntime:
66
  """Everything a request needs to serve ONE tenant, and nothing about any other.
@@ -155,6 +165,47 @@ class TenantRuntime:
155
  return (getattr(self.tenant, "sources", {}) or {}).get("odoo")
156
  return None
157
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  def assert_datastore_matches(self):
159
  """RAISE if the process-wide DuckDB file is not this tenant's.
160
 
@@ -292,3 +343,47 @@ def resident():
292
  measurement and for asserting the bound actually binds."""
293
  with _LOCK:
294
  return list(_CACHE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  import threading
37
  from collections import OrderedDict
38
  from dataclasses import dataclass, field
39
+ from pathlib import Path
40
 
41
  import core.store as store
42
  from harness import datastore as _ds
 
62
  _LOCK = threading.RLock()
63
 
64
 
65
+ #: The store bucket Settings > Connectors writes pause flags into. ONE literal, shared with the
66
+ #: API layer (`routes_keychain` aliases this) β€” the flag is written by one module and read by
67
+ #: three, and two spellings of the key would be a pause that silently freezes nothing.
68
+ CONNECTOR_FLAGS_KEY = "connectors"
69
+ #: The flag key tenant #0's compiled ENV Odoo source is stored under. It is not a keychain entry
70
+ #: id, so it needs a name of its own; `routes_keychain`'s connector row uses the same literal.
71
+ ENV_ODOO_FLAG_KEY = "odoo-env"
72
+
73
+
74
  @dataclass
75
  class TenantRuntime:
76
  """Everything a request needs to serve ONE tenant, and nothing about any other.
 
165
  return (getattr(self.tenant, "sources", {}) or {}).get("odoo")
166
  return None
167
 
168
+ # ------------------------------------------------------- the connector PAUSE (D-10, wave 24)
169
+ def odoo_flag_key(self):
170
+ """WHICH connector flag governs this tenant's Odoo β€” the key `connectors[<k>].paused`
171
+ is stored under, or None when nothing would serve.
172
+
173
+ THE SAME RESOLUTION AS `odoo_source()` ABOVE, expressed as an identity instead of a
174
+ client: first unlocked keychain `odoo` entry, else tenant #0's compiled env source, else
175
+ nothing. It lives here so there is ONE resolver β€” `routes_keychain._resolved_odoo_key`
176
+ was a second copy of these three rules in the API layer, and a pause flag written against
177
+ one resolution and read against the other freezes nothing while reporting success.
178
+ """
179
+ import core.keychain as keychain
180
+ try:
181
+ entries = keychain.list_entries(self)
182
+ except Exception:
183
+ entries = []
184
+ first_odoo = next((e["id"] for e in entries if e.get("type") == "odoo"), None)
185
+ if first_odoo and keychain.unlocked():
186
+ return first_odoo
187
+ if self.key == "royal-imports" and os.environ.get("ODOO_URL"):
188
+ return ENV_ODOO_FLAG_KEY
189
+ return None
190
+
191
+ def odoo_paused(self):
192
+ """Is THIS tenant's RESOLVED Odoo source paused?
193
+
194
+ ⚠ RESOLVED, not "any entry" β€” pausing an entry that is not the one serving freezes
195
+ nothing, because it serves nothing. Never raises: an unreachable flags bucket answers
196
+ False, because a store hiccup must not freeze a live surface. That policy is inherited
197
+ from the API-layer function this one replaced, deliberately, so there is one answer to
198
+ "what happens when we cannot tell" rather than two that can disagree.
199
+ """
200
+ try:
201
+ flag_key = self.odoo_flag_key()
202
+ if not flag_key:
203
+ return False
204
+ flags = self.get(CONNECTOR_FLAGS_KEY) or {}
205
+ return bool((flags.get(flag_key) or {}).get("paused"))
206
+ except Exception:
207
+ return False
208
+
209
  def assert_datastore_matches(self):
210
  """RAISE if the process-wide DuckDB file is not this tenant's.
211
 
 
343
  measurement and for asserting the bound actually binds."""
344
  with _LOCK:
345
  return list(_CACHE)
346
+
347
+
348
+ # ─────────────────────────────────────────────────────────────────────────────────────────────
349
+ # ⭐ DEBT D-10 (wave 24) β€” TEACHING THE MEASURE MIRROR ABOUT THE CONNECTOR PAUSE.
350
+ #
351
+ # `harness.datastore` is the store every measure column and condition is answered from, and it
352
+ # pulled from Odoo straight through a pause: 12 sync passes at boot and one every 1800 s. It
353
+ # cannot ask the question itself β€” the flag lives in a tenant's store bucket, which is this
354
+ # module's to read, and this module already imports datastore, so an import back would be a
355
+ # cycle. So datastore exposes a probe slot and this module fills it, once, at import.
356
+
357
+
358
+ def tenant_for_store_path(path=None):
359
+ """Which tenant owns the DuckDB file currently open (or `path`)? `""` when nothing matches.
360
+
361
+ β›” RESOLVED BY FORWARD-MAPPING every known tenant, never by parsing the filename, and that is
362
+ a correctness point rather than a style one: `datastore.path_for` substitutes `_` for every
363
+ non-alphanumeric character and truncates at 60, so the name is genuinely NOT invertible β€”
364
+ `a.b` and `a_b` produce the same file. Guessing the slug back out of it would eventually name
365
+ the wrong tenant, and this answer decides whether another tenant's connector freezes ours.
366
+ """
367
+ want = Path(path or _ds.DB_PATH).resolve()
368
+ # Tenant #0 first: it is the only tenant the unattended sync actually runs for today (see
369
+ # D-29 β€” the resync loop prewarms `royal-imports` hardcoded), so this is the hot answer.
370
+ for key in ["royal-imports"] + [k for k in known_tenants() if k != "royal-imports"]:
371
+ try:
372
+ if _ds.path_for(key).resolve() == want:
373
+ return key
374
+ except Exception:
375
+ continue
376
+ return ""
377
+
378
+
379
+ def store_source_paused():
380
+ """The probe `harness.datastore` calls before reaching Odoo. Never raises; False when the
381
+ tenant cannot be resolved, matching the fail-towards-live policy `odoo_paused` documents."""
382
+ try:
383
+ key = tenant_for_store_path()
384
+ return bool(key) and get_runtime(key).odoo_paused()
385
+ except Exception:
386
+ return False
387
+
388
+
389
+ _ds.set_paused_probe(store_source_paused)
web/src/automation/AutomationBoard.tsx CHANGED
@@ -1,420 +1,396 @@
1
- // ---------------------------------------------------------------------------
2
- // automation/AutomationBoard.tsx β€” the automation AS A BOARD (owner ruling R1).
3
- //
4
- // THE MODEL, and it is the whole point of the wave: the columns are the flow's
5
- // stages and THE CARDS ARE RECORDS. A record walks left to right; where it
6
- // currently is lives in a single-select stage field on the target database, so
7
- // the same field drives an ordinary Kanban view of that database and this board
8
- // is not a second, private opinion about where anything is. A REVIEW stage holds
9
- // its cards until a person clicks them along, and that click IS the promotion β€”
10
- // on the discovery flow it is literally the `tracked` tick (R6, R7-W20), not a
11
- // UI gesture that later gets synced.
12
- //
13
- // β›” IT RENDERS ONLY WHAT RIDES THE PAYLOAD (C1). Stages, their order, their
14
- // switches, their dots, the routes between them, which cards exist, which of
15
- // them may move and where to β€” all of it is `GET /automations/{id}/board`. This
16
- // file decides pixels. It cannot show a stage the engine stopped running, and it
17
- // does not decide whether a move is legal: it posts the drop it was given and
18
- // prints the server's refusal verbatim.
19
- //
20
- // WHAT IT COPIES AND WHAT IT DOES NOT. The look is `customer-grid`'s KanbanView
21
- // β€” tinted lane pill, count beside it, a column of quiet cards, drag with
22
- // post-drag click suppression β€” because two boards in one product that look like
23
- // two products is the defect DESIGN.md calls variety. It copies the LOOK and
24
- // shares no code: the grid tree is the asset that also ships inside the embed,
25
- // and an automation surface must not grow an edge into it (the same rule
26
- // `automationApi.ts` is built on).
27
- //
28
- // TWO TRAPS, both paid for already ([[ui-invisible-to-assertions]]):
29
- // 1. A FINISHED DRAG MUST NOT FIRE A CLICK. Browsers can deliver a click after
30
- // `dragend`, and the thing under the pointer here is an advance button β€”
31
- // i.e. a promotion nobody asked for. One drag suppresses exactly one click.
32
- // 2. A CAPPED LANE MUST SAY SO. `counts` is the true per-stage total and
33
- // `cards` may be shorter β€” server-side or by this file's own page size β€” so
34
- // a lane whose list is shorter than its count discloses the difference. A
35
- // silent `[:N]` is a defect, not a rendering detail
36
- // ([[no-unverifiable-aggregates]]).
37
- // ---------------------------------------------------------------------------
38
- import type { DragEvent as ReactDragEvent } from "react";
39
- import { useRef, useState } from "react";
40
-
41
- import type { Board, BoardCard, BoardStage } from "./automationApi";
42
-
43
- /** How many cards a lane paints before it offers the rest. Disclosed, never silent. */
44
- const LANE_PAGE = 25;
45
-
46
- interface Props {
47
- board: Board;
48
- /** The selected STAGE id β€” the right-hand panel shows that stage's config. */
49
- selected: string;
50
- onSelect: (stageId: string) => void;
51
- onToggle: (stageId: string) => void;
52
- busyStage: string;
53
- /** Post a card move. The caller answers with a fresh board (or a refusal). */
54
- onMove: (rowId: string, to: string) => void;
55
- movingRow: string;
56
- }
57
-
58
- /**
59
- * A stage's tint class.
60
- *
61
- * DESIGN.md 3's fixed semantics, applied: yellow = attention, and a review stage
62
- * is the one that is WAITING FOR A PERSON; purple = group/routing controls, which
63
- * is what a branch is; blue = the ordinary interactive body of the flow. Anything
64
- * the server names that this file has never heard of lands on the neutral face
65
- * and is still drawn β€” a stage that renders plainly is visible, a stage that
66
- * renders as nothing is the silent drop this codebase keeps paying for.
67
- */
68
- function tintOf(stage: BoardStage): string {
69
- if (stage.kind === "review" || stage.posture === "strict") return " is-review";
70
- if (stage.kind === "branch") return " is-branch";
71
- if (stage.kind === "action") return " is-action";
72
- return "";
73
- }
74
-
75
- function postureTitle(stage: BoardStage): string {
76
- if (stage.posture === "strict")
77
- return `${stage.label} β€” holds each record until a person moves it along`;
78
- if (stage.posture === "auto") return `${stage.label} β€” the automation moves records through`;
79
- return stage.label;
80
- }
81
-
82
- /** A timestamp trimmed to the minute. Never a record VALUE β€” those arrive composed (C1). */
83
- function whenText(iso: string): string {
84
- const raw = String(iso || "");
85
- return raw ? raw.replace("T", " ").slice(0, 16) : "";
86
- }
87
-
88
- export default function AutomationBoard({
89
- board,
90
- selected,
91
- onSelect,
92
- onToggle,
93
- busyStage,
94
- onMove,
95
- movingRow,
96
- }: Props) {
97
- const [expanded, setExpanded] = useState<Set<string>>(new Set());
98
- const [dragging, setDragging] = useState<BoardCard | null>(null);
99
- const draggedRef = useRef(false);
100
-
101
- const stages = board?.stages || [];
102
- const labels = new Map(stages.map((s) => [s.id, s.label]));
103
- // ⚠ NOT EVERY STAGE IS A PLACE. Two kinds of stage cannot hold a record and must not
104
- // be drawn as lanes:
105
- // Β· the TRIGGER β€” a record is never "at" the trigger; the trigger is what puts one
106
- // on the board. Its configuration lives in the trigger face above this component.
107
- // Β· anything the server marks `record: false` β€” the things the automation DOES
108
- // (find, collect, write). On a real discovery flow that is three of six stages, so
109
- // drawing them as lanes puts three permanently empty columns between the trigger
110
- // and the first column that ever holds anything.
111
- // They render as the PROCESS STRIP: still clickable, still switchable, still carrying
112
- // their own dot β€” everything except a column of cards they can never contain.
113
- //
114
- // `record` is OPTIONAL and absent means LANE (see its note in automationApi): only an
115
- // explicit `false` moves a stage into the strip, so a server that ships C1's contract
116
- // text and not this field still draws the board it describes.
117
- const boardStages = stages.filter((s) => s.kind !== "trigger");
118
- const stripStages = boardStages.filter((s) => s.record === false);
119
- const laneStages = boardStages.filter((s) => s.record !== false);
120
- const cols = [...new Set(laneStages.map((s) => s.col))].sort((a, b) => a - b);
121
-
122
- const byStage = new Map<string, BoardCard[]>();
123
- for (const c of board?.cards || []) {
124
- const list = byStage.get(c.stageId);
125
- if (list) list.push(c);
126
- else byStage.set(c.stageId, [c]);
127
- }
128
-
129
- const advance = (card: BoardCard, to: string) => {
130
- // Trap 1: swallow the click a finished drag can produce.
131
- if (draggedRef.current) return;
132
- onMove(card.rowId, to);
133
- };
134
-
135
- const onDrop = (stage: BoardStage) => (e: ReactDragEvent<HTMLDivElement>) => {
136
- e.preventDefault();
137
- const rowId = e.dataTransfer.getData("text/plain");
138
- setDragging(null);
139
- if (!rowId) return;
140
- const card = (board.cards || []).find((c) => c.rowId === rowId);
141
- if (!card || card.stageId === stage.id) return;
142
- onMove(rowId, stage.id);
143
- };
144
-
145
- const cardBox = (card: BoardCard) => {
146
- const moving = movingRow === card.rowId;
147
- const nexts = card.canAdvance ? card.next || [] : [];
148
- return (
149
- <div
150
- key={card.rowId}
151
- className={
152
- "autob-card" +
153
- (card.canAdvance ? " is-draggable" : "") +
154
- (moving ? " is-moving" : "")
155
- }
156
- draggable={card.canAdvance && !moving}
157
- title={
158
- card.canAdvance
159
- ? undefined
160
- : "The server does not allow you to move this card."
161
- }
162
- onDragStart={
163
- card.canAdvance
164
- ? (e) => {
165
- draggedRef.current = true;
166
- setDragging(card);
167
- e.dataTransfer.setData("text/plain", card.rowId);
168
- }
169
- : undefined
170
- }
171
- onDragEnd={() => {
172
- setDragging(null);
173
- // Cleared a tick later: the post-drag click arrives before this fires.
174
- window.setTimeout(() => {
175
- draggedRef.current = false;
176
- }, 0);
177
- }}
178
- >
179
- <span className="autob-card-title">
180
- {card.title}
181
- {/*
182
- ⭐ C5's CYCLE BADGE. A record that has been round the flow more than once is a
183
- different fact from a record on its first pass β€” on a reset-mode automation it is
184
- the difference between "working" and "looping" β€” so the card says so.
185
- ⚠ FROM 2 UPWARDS ONLY, and that is what makes an ABSENT count safe: every card
186
- would otherwise wear "x1", which is noise on the common case and, worse, a claim
187
- about a number the server has not sent yet (see `BoardCard.cycles`).
188
- */}
189
- {typeof card.cycles === "number" && card.cycles >= 2 ? (
190
- <span
191
- className="autob-card-cycles"
192
- title={`This record has been round this flow ${card.cycles} times`}
193
- >
194
- &times;{card.cycles}
195
- </span>
196
- ) : null}
197
- </span>
198
- {card.sub ? <span className="autob-card-sub">{card.sub}</span> : null}
199
- {card.movedAt ? (
200
- <span className="autob-card-when">{whenText(card.movedAt)}</span>
201
- ) : null}
202
- {nexts.length ? (
203
- <div className="autob-card-moves">
204
- {nexts.map((to) => (
205
- <button
206
- key={to}
207
- type="button"
208
- className="autob-card-advance"
209
- disabled={moving}
210
- title={`Move ${card.title} to ${labels.get(to) || to}`}
211
- onClick={() => advance(card, to)}
212
- >
213
- {nexts.length === 1 ? "Move on" : labels.get(to) || to}
214
- <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
215
- <path
216
- d="M3.4 8h9.2M9 4.4 12.6 8 9 11.6"
217
- stroke="currentColor"
218
- strokeWidth="1.5"
219
- strokeLinecap="round"
220
- strokeLinejoin="round"
221
- />
222
- </svg>
223
- </button>
224
- ))}
225
- </div>
226
- ) : null}
227
- </div>
228
- );
229
- };
230
-
231
- const lane = (stage: BoardStage) => {
232
- const all = byStage.get(stage.id) || [];
233
- const open = expanded.has(stage.id);
234
- const shown = open ? all : all.slice(0, LANE_PAGE);
235
- // The TRUE total is the server's count; the list may be shorter for two
236
- // independent reasons, and the disclosure covers both without pretending to
237
- // know which one applied.
238
- const total = typeof board.counts?.[stage.id] === "number"
239
- ? board.counts[stage.id]
240
- : all.length;
241
- // TWO independent caps, and they need different controls. This file hiding
242
- // cards it HAS is expandable; the server not having SENT them is not β€” and an
243
- // expander offered for the second case is a control that lies.
244
- const clientCapped = shown.length < all.length;
245
- // A DERIVED bucket takes no drop: `record && !assignable` means cards appear there
246
- // from what is true about the row, and nothing may stamp one in. The server would
247
- // refuse it anyway β€” this just stops the board from inviting the refusal.
248
- const droppable = stage.assignable !== false;
249
- const legal = droppable && !!dragging && (dragging.next || []).includes(stage.id);
250
- const outgoing = (board.routes || []).filter((r) => r.from === stage.id && r.condition);
251
-
252
- return (
253
- <div
254
- key={stage.id}
255
- className={
256
- "autob-lane" +
257
- tintOf(stage) +
258
- (stage.id === selected ? " is-selected" : "") +
259
- (stage.enabled ? "" : " is-off") +
260
- (legal ? " is-target" : "")
261
- }
262
- onDragOver={droppable ? (e) => e.preventDefault() : undefined}
263
- onDrop={droppable ? onDrop(stage) : undefined}
264
- >
265
- <div className="autob-lane-head">
266
- <button
267
- type="button"
268
- className="autob-lane-hit"
269
- aria-pressed={stage.id === selected}
270
- title={postureTitle(stage)}
271
- onClick={() => onSelect(stage.id)}
272
- >
273
- <span className="autob-lane-pill">{stage.label}</span>
274
- <span className="autob-lane-count">{total.toLocaleString()}</span>
275
- <span
276
- className={`auto-dot is-${stage.status}`}
277
- title={`Last run: ${stage.status}`}
278
- aria-label={`Last run: ${stage.status}`}
279
- />
280
- </button>
281
- {stage.toggle ? (
282
- <button
283
- type="button"
284
- className={"auto-step-switch autob-lane-switch" + (stage.enabled ? " is-on" : "")}
285
- disabled={busyStage === stage.id}
286
- aria-pressed={stage.enabled}
287
- aria-label={`${stage.enabled ? "Turn off" : "Turn on"} ${stage.label}`}
288
- title={`${stage.enabled ? "Turn off" : "Turn on"} ${stage.label}`}
289
- onClick={() => onToggle(stage.id)}
290
- >
291
- <span className="auto-step-switch-knob" />
292
- </button>
293
- ) : null}
294
- </div>
295
-
296
- <div className="autob-lane-cards">{shown.map(cardBox)}</div>
297
-
298
- {clientCapped ? (
299
- <button
300
- type="button"
301
- className="autob-lane-more"
302
- onClick={() => setExpanded((prev) => new Set(prev).add(stage.id))}
303
- >
304
- Showing {shown.length.toLocaleString()} of {total.toLocaleString()} β€” show all
305
- </button>
306
- ) : shown.length < total ? (
307
- // The rest were never sent, so there is nothing here to expand. `truncated` is
308
- // the server saying so in its own words; the arithmetic agrees either way, and
309
- // the field is what makes the sentence a quotation rather than a deduction.
310
- <p
311
- className="autob-lane-more is-flat"
312
- title={
313
- (board.truncated || []).includes(stage.id)
314
- ? "The server sent the first batch for this stage; the count is the true total."
315
- : undefined
316
- }
317
- >
318
- Showing {shown.length.toLocaleString()} of {total.toLocaleString()}
319
- </p>
320
- ) : null}
321
-
322
- {outgoing.length ? (
323
- <div className="autob-lane-routes">
324
- {outgoing.map((r) => (
325
- <span key={`${r.from}-${r.to}`} className="autob-route" title="Records matching this go there next">
326
- {r.label ||
327
- `${r.condition?.field} ${r.condition?.op} ${r.condition?.value ?? ""}`.trim()}
328
- {" β†’ "}
329
- {labels.get(r.to) || r.to}
330
- </span>
331
- ))}
332
- </div>
333
- ) : null}
334
- </div>
335
- );
336
- };
337
-
338
- if (!boardStages.length) {
339
- return (
340
- <div className="autob-board">
341
- <p className="autob-board-note">This automation has no stages yet.</p>
342
- </div>
343
- );
344
- }
345
-
346
- return (
347
- <div className="autob-board">
348
- {!board.stageField ? (
349
- <p className="autob-board-note">
350
- Records appear here once this flow is bound to a database.
351
- </p>
352
- ) : null}
353
- {stripStages.length ? (
354
- <div className="autob-strip">
355
- {stripStages.map((st) => (
356
- /*
357
- ⚠ A WRAPPER, NOT ONE BUTTON, and the switch is the reason. `write` carries a
358
- toggle β€” it is the DRY-RUN control, the difference between a run that writes
359
- and a run that only reports what it would have written β€” and the strip is now
360
- the only place that stage appears. A chip that dropped it would have deleted a
361
- shipped control from the product while every gate stayed green. (Nesting the
362
- switch inside the chip's own button is not the fix: a button inside a button
363
- is invalid, and browsers un-nest it in ways that lose the inner click.)
364
- */
365
- <div
366
- key={st.id}
367
- className={
368
- "autob-strip-step" +
369
- (st.id === selected ? " is-selected" : "") +
370
- (st.enabled ? "" : " is-off")
371
- }
372
- >
373
- <button
374
- type="button"
375
- className="autob-strip-hit"
376
- aria-pressed={st.id === selected}
377
- title={st.detail || st.label}
378
- onClick={() => onSelect(st.id)}
379
- >
380
- <span className="autob-strip-label">{st.label}</span>
381
- <span
382
- className={`auto-dot is-${st.status}`}
383
- title={`Last run: ${st.status}`}
384
- aria-label={`Last run: ${st.status}`}
385
- />
386
- </button>
387
- {st.toggle ? (
388
- <button
389
- type="button"
390
- className={"auto-step-switch autob-strip-switch" + (st.enabled ? " is-on" : "")}
391
- disabled={busyStage === st.id}
392
- aria-pressed={st.enabled}
393
- aria-label={`${st.enabled ? "Turn off" : "Turn on"} ${st.label}`}
394
- title={`${st.enabled ? "Turn off" : "Turn on"} ${st.label}`}
395
- onClick={() => onToggle(st.id)}
396
- >
397
- <span className="auto-step-switch-knob" />
398
- </button>
399
- ) : null}
400
- </div>
401
- ))}
402
- </div>
403
- ) : null}
404
- <div className="autob-cols">
405
- {cols.map((col) => (
406
- <div className="autob-col" key={col}>
407
- {/* STACKED LANES ARE THE BRANCH PATHS (R5). Two stages at the same column
408
- are two places a record can be at the same point in the flow β€” the
409
- routing decides which β€” so they stack rather than sitting side by side,
410
- which would read as "then". */}
411
- {laneStages
412
- .filter((s) => s.col === col)
413
- .sort((a, b) => a.row - b.row)
414
- .map(lane)}
415
- </div>
416
- ))}
417
- </div>
418
- </div>
419
- );
420
- }
 
1
+ // ---------------------------------------------------------------------------
2
+ // automation/AutomationBoard.tsx β€” the automation AS A BOARD (owner ruling R1).
3
+ //
4
+ // THE MODEL, and it is the whole point of the wave: the columns are the flow's
5
+ // stages and THE CARDS ARE RECORDS. A record walks left to right; where it
6
+ // currently is lives in a single-select stage field on the target database, so
7
+ // the same field drives an ordinary Kanban view of that database and this board
8
+ // is not a second, private opinion about where anything is. A REVIEW stage holds
9
+ // its cards until a person clicks them along, and that click IS the promotion β€”
10
+ // on the discovery flow it is literally the `tracked` tick (R6, R7-W20), not a
11
+ // UI gesture that later gets synced.
12
+ //
13
+ // β›” IT RENDERS ONLY WHAT RIDES THE PAYLOAD (C1). Stages, their order, their
14
+ // switches, their dots, the routes between them, which cards exist, which of
15
+ // them may move and where to β€” all of it is `GET /automations/{id}/board`. This
16
+ // file decides pixels. It cannot show a stage the engine stopped running, and it
17
+ // does not decide whether a move is legal: it posts the drop it was given and
18
+ // prints the server's refusal verbatim.
19
+ //
20
+ // WHAT IT COPIES AND WHAT IT DOES NOT. The look is `customer-grid`'s KanbanView
21
+ // β€” tinted lane pill, count beside it, a column of quiet cards, drag with
22
+ // post-drag click suppression β€” because two boards in one product that look like
23
+ // two products is the defect DESIGN.md calls variety. It copies the LOOK and
24
+ // shares no code: the grid tree is the asset that also ships inside the embed,
25
+ // and an automation surface must not grow an edge into it (the same rule
26
+ // `automationApi.ts` is built on).
27
+ //
28
+ // TWO TRAPS, both paid for already ([[ui-invisible-to-assertions]]):
29
+ // 1. A FINISHED DRAG MUST NOT FIRE A CLICK. Browsers can deliver a click after
30
+ // `dragend`, and the thing under the pointer here is an advance button β€”
31
+ // i.e. a promotion nobody asked for. One drag suppresses exactly one click.
32
+ // 2. A CAPPED LANE MUST SAY SO. `counts` is the true per-stage total and
33
+ // `cards` may be shorter οΏ½οΏ½ server-side or by this file's own page size β€” so
34
+ // a lane whose list is shorter than its count discloses the difference. A
35
+ // silent `[:N]` is a defect, not a rendering detail
36
+ // ([[no-unverifiable-aggregates]]).
37
+ // ---------------------------------------------------------------------------
38
+ import type { DragEvent as ReactDragEvent } from "react";
39
+ import { useRef, useState } from "react";
40
+
41
+ import type { Board, BoardCard, BoardStage } from "./automationApi";
42
+
43
+ /** How many cards a lane paints before it offers the rest. Disclosed, never silent. */
44
+ const LANE_PAGE = 25;
45
+
46
+ interface Props {
47
+ board: Board;
48
+ /** The selected STAGE id β€” the right-hand panel shows that stage's config. */
49
+ selected: string;
50
+ onSelect: (stageId: string) => void;
51
+ onToggle: (stageId: string) => void;
52
+ busyStage: string;
53
+ /** Post a card move. The caller answers with a fresh board (or a refusal). */
54
+ onMove: (rowId: string, to: string) => void;
55
+ movingRow: string;
56
+ }
57
+
58
+ /**
59
+ * A stage's tint class.
60
+ *
61
+ * DESIGN.md 3's fixed semantics, applied: yellow = attention, and a review stage
62
+ * is the one that is WAITING FOR A PERSON; purple = group/routing controls, which
63
+ * is what a branch is; blue = the ordinary interactive body of the flow. Anything
64
+ * the server names that this file has never heard of lands on the neutral face
65
+ * and is still drawn β€” a stage that renders plainly is visible, a stage that
66
+ * renders as nothing is the silent drop this codebase keeps paying for.
67
+ */
68
+ function tintOf(stage: BoardStage): string {
69
+ if (stage.kind === "review" || stage.posture === "strict") return " is-review";
70
+ if (stage.kind === "branch") return " is-branch";
71
+ if (stage.kind === "action") return " is-action";
72
+ return "";
73
+ }
74
+
75
+ function postureTitle(stage: BoardStage): string {
76
+ if (stage.posture === "strict")
77
+ return `${stage.label} β€” holds each record until a person moves it along`;
78
+ if (stage.posture === "auto") return `${stage.label} β€” the automation moves records through`;
79
+ return stage.label;
80
+ }
81
+
82
+ /** A timestamp trimmed to the minute. Never a record VALUE β€” those arrive composed (C1). */
83
+ function whenText(iso: string): string {
84
+ const raw = String(iso || "");
85
+ return raw ? raw.replace("T", " ").slice(0, 16) : "";
86
+ }
87
+
88
+ export default function AutomationBoard({
89
+ board,
90
+ selected,
91
+ onSelect,
92
+ onToggle,
93
+ busyStage,
94
+ onMove,
95
+ movingRow,
96
+ }: Props) {
97
+ const [expanded, setExpanded] = useState<Set<string>>(new Set());
98
+ const [dragging, setDragging] = useState<BoardCard | null>(null);
99
+ const draggedRef = useRef(false);
100
+
101
+ const stages = board?.stages || [];
102
+ const labels = new Map(stages.map((s) => [s.id, s.label]));
103
+ // ⚠ NOT EVERY STAGE IS A PLACE. Two kinds of stage cannot hold a record and must not
104
+ // be drawn as lanes:
105
+ // Β· the TRIGGER β€” a record is never "at" the trigger; the trigger is what puts one
106
+ // on the board. Its configuration lives in the trigger face above this component.
107
+ // Β· anything the server marks `record: false` β€” the things the automation DOES
108
+ // (find, collect, write). On a real discovery flow that is three of six stages, so
109
+ // drawing them as lanes puts three permanently empty columns between the trigger
110
+ // and the first column that ever holds anything.
111
+ // They render as the PROCESS STRIP: still clickable, still switchable, still carrying
112
+ // their own dot β€” everything except a column of cards they can never contain.
113
+ //
114
+ // `record` is OPTIONAL and absent means LANE (see its note in automationApi): only an
115
+ // explicit `false` moves a stage into the strip, so a server that ships C1's contract
116
+ // text and not this field still draws the board it describes.
117
+ const boardStages = stages.filter((s) => s.kind !== "trigger");
118
+ /*
119
+ * ⭐ WAVE 24 (owner item 9) β€” THE PROCESS STRIP IS GONE, AND `record` IS NOT.
120
+ *
121
+ * The strip drew the things the automation DOES β€” Capture / Bright Data / Anonymous / Post
122
+ * engagement / Write β€” as chips above the lanes. C-CFG moves every one of those bodies, and
123
+ * the FOUR switches they carried (`capture_paid`, `capture_anon`, `capture_metrics` and
124
+ * `write`'s dry run), into Properties β†’ Configuration β†’ "How this fetches". The board is for
125
+ * reading where records ARE; a stage that can never hold one was never a place.
126
+ *
127
+ * β›” THE `record` FIELD STAYS IN THE TYPE AND THIS FILTER STAYS IN THE CODE. The server still
128
+ * sends `record: false` stages β€” `graph()` still emits those nodes and the engine still RUNS
129
+ * them; only the drawing stopped. Deleting the field would be a CLIENT UNION OVER A SERVER
130
+ * VOCABULARY, and the failure mode is the silent one this file's own header warns about: with
131
+ * no `record` to test, every one of those stages would come back as a LANE, and a discovery
132
+ * flow would paint three permanently empty columns between the trigger and the first real one.
133
+ * So `record === false` still means "not a lane" β€” it just no longer means "a chip" either.
134
+ */
135
+ const laneStages = boardStages.filter((s) => s.record !== false);
136
+ const cols = [...new Set(laneStages.map((s) => s.col))].sort((a, b) => a - b);
137
+
138
+ const byStage = new Map<string, BoardCard[]>();
139
+ for (const c of board?.cards || []) {
140
+ const list = byStage.get(c.stageId);
141
+ if (list) list.push(c);
142
+ else byStage.set(c.stageId, [c]);
143
+ }
144
+
145
+ const advance = (card: BoardCard, to: string) => {
146
+ // Trap 1: swallow the click a finished drag can produce.
147
+ if (draggedRef.current) return;
148
+ onMove(card.rowId, to);
149
+ };
150
+
151
+ const onDrop = (stage: BoardStage) => (e: ReactDragEvent<HTMLDivElement>) => {
152
+ e.preventDefault();
153
+ const rowId = e.dataTransfer.getData("text/plain");
154
+ setDragging(null);
155
+ if (!rowId) return;
156
+ const card = (board.cards || []).find((c) => c.rowId === rowId);
157
+ if (!card || card.stageId === stage.id) return;
158
+ onMove(rowId, stage.id);
159
+ };
160
+
161
+ const cardBox = (card: BoardCard) => {
162
+ const moving = movingRow === card.rowId;
163
+ const nexts = card.canAdvance ? card.next || [] : [];
164
+ return (
165
+ <div
166
+ key={card.rowId}
167
+ className={
168
+ "autob-card" +
169
+ (card.canAdvance ? " is-draggable" : "") +
170
+ (moving ? " is-moving" : "")
171
+ }
172
+ draggable={card.canAdvance && !moving}
173
+ title={
174
+ card.canAdvance
175
+ ? undefined
176
+ : "The server does not allow you to move this card."
177
+ }
178
+ onDragStart={
179
+ card.canAdvance
180
+ ? (e) => {
181
+ draggedRef.current = true;
182
+ setDragging(card);
183
+ e.dataTransfer.setData("text/plain", card.rowId);
184
+ }
185
+ : undefined
186
+ }
187
+ onDragEnd={() => {
188
+ setDragging(null);
189
+ // Cleared a tick later: the post-drag click arrives before this fires.
190
+ window.setTimeout(() => {
191
+ draggedRef.current = false;
192
+ }, 0);
193
+ }}
194
+ >
195
+ <span className="autob-card-title">
196
+ {card.title}
197
+ {/*
198
+ ⭐ C5's CYCLE BADGE. A record that has been round the flow more than once is a
199
+ different fact from a record on its first pass β€” on a reset-mode automation it is
200
+ the difference between "working" and "looping" β€” so the card says so.
201
+ ⚠ FROM 2 UPWARDS ONLY, and that is what makes an ABSENT count safe: every card
202
+ would otherwise wear "x1", which is noise on the common case and, worse, a claim
203
+ about a number the server has not sent yet (see `BoardCard.cycles`).
204
+ */}
205
+ {typeof card.cycles === "number" && card.cycles >= 2 ? (
206
+ <span
207
+ className="autob-card-cycles"
208
+ title={`This record has been round this flow ${card.cycles} times`}
209
+ >
210
+ &times;{card.cycles}
211
+ </span>
212
+ ) : null}
213
+ </span>
214
+ {card.sub ? <span className="autob-card-sub">{card.sub}</span> : null}
215
+ {card.movedAt ? (
216
+ <span className="autob-card-when">{whenText(card.movedAt)}</span>
217
+ ) : null}
218
+ {nexts.length ? (
219
+ <div className="autob-card-moves">
220
+ {nexts.map((to) => (
221
+ <button
222
+ key={to}
223
+ type="button"
224
+ className="autob-card-advance"
225
+ disabled={moving}
226
+ title={`Move ${card.title} to ${labels.get(to) || to}`}
227
+ onClick={() => advance(card, to)}
228
+ >
229
+ {nexts.length === 1 ? "Move on" : labels.get(to) || to}
230
+ <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
231
+ <path
232
+ d="M3.4 8h9.2M9 4.4 12.6 8 9 11.6"
233
+ stroke="currentColor"
234
+ strokeWidth="1.5"
235
+ strokeLinecap="round"
236
+ strokeLinejoin="round"
237
+ />
238
+ </svg>
239
+ </button>
240
+ ))}
241
+ </div>
242
+ ) : null}
243
+ </div>
244
+ );
245
+ };
246
+
247
+ const lane = (stage: BoardStage) => {
248
+ const all = byStage.get(stage.id) || [];
249
+ const open = expanded.has(stage.id);
250
+ const shown = open ? all : all.slice(0, LANE_PAGE);
251
+ // The TRUE total is the server's count; the list may be shorter for two
252
+ // independent reasons, and the disclosure covers both without pretending to
253
+ // know which one applied.
254
+ const total = typeof board.counts?.[stage.id] === "number"
255
+ ? board.counts[stage.id]
256
+ : all.length;
257
+ // TWO independent caps, and they need different controls. This file hiding
258
+ // cards it HAS is expandable; the server not having SENT them is not β€” and an
259
+ // expander offered for the second case is a control that lies.
260
+ const clientCapped = shown.length < all.length;
261
+ // A DERIVED bucket takes no drop: `record && !assignable` means cards appear there
262
+ // from what is true about the row, and nothing may stamp one in. The server would
263
+ // refuse it anyway β€” this just stops the board from inviting the refusal.
264
+ const droppable = stage.assignable !== false;
265
+ const legal = droppable && !!dragging && (dragging.next || []).includes(stage.id);
266
+ const outgoing = (board.routes || []).filter((r) => r.from === stage.id && r.condition);
267
+
268
+ return (
269
+ <div
270
+ key={stage.id}
271
+ className={
272
+ "autob-lane" +
273
+ tintOf(stage) +
274
+ (stage.id === selected ? " is-selected" : "") +
275
+ (stage.enabled ? "" : " is-off") +
276
+ (legal ? " is-target" : "")
277
+ }
278
+ onDragOver={droppable ? (e) => e.preventDefault() : undefined}
279
+ onDrop={droppable ? onDrop(stage) : undefined}
280
+ >
281
+ <div className="autob-lane-head">
282
+ <button
283
+ type="button"
284
+ className="autob-lane-hit"
285
+ aria-pressed={stage.id === selected}
286
+ title={postureTitle(stage)}
287
+ onClick={() => onSelect(stage.id)}
288
+ >
289
+ <span className="autob-lane-pill">{stage.label}</span>
290
+ <span className="autob-lane-count">{total.toLocaleString()}</span>
291
+ <span
292
+ className={`auto-dot is-${stage.status}`}
293
+ title={`Last run: ${stage.status}`}
294
+ aria-label={`Last run: ${stage.status}`}
295
+ />
296
+ </button>
297
+ {stage.toggle ? (
298
+ <button
299
+ type="button"
300
+ className={"auto-step-switch autob-lane-switch" + (stage.enabled ? " is-on" : "")}
301
+ disabled={busyStage === stage.id}
302
+ aria-pressed={stage.enabled}
303
+ aria-label={`${stage.enabled ? "Turn off" : "Turn on"} ${stage.label}`}
304
+ title={`${stage.enabled ? "Turn off" : "Turn on"} ${stage.label}`}
305
+ onClick={() => onToggle(stage.id)}
306
+ >
307
+ <span className="auto-step-switch-knob" />
308
+ </button>
309
+ ) : null}
310
+ </div>
311
+
312
+ <div className="autob-lane-cards">{shown.map(cardBox)}</div>
313
+
314
+ {clientCapped ? (
315
+ <button
316
+ type="button"
317
+ className="autob-lane-more"
318
+ onClick={() => setExpanded((prev) => new Set(prev).add(stage.id))}
319
+ >
320
+ Showing {shown.length.toLocaleString()} of {total.toLocaleString()} β€” show all
321
+ </button>
322
+ ) : shown.length < total ? (
323
+ // The rest were never sent, so there is nothing here to expand. `truncated` is
324
+ // the server saying so in its own words; the arithmetic agrees either way, and
325
+ // the field is what makes the sentence a quotation rather than a deduction.
326
+ <p
327
+ className="autob-lane-more is-flat"
328
+ title={
329
+ (board.truncated || []).includes(stage.id)
330
+ ? "The server sent the first batch for this stage; the count is the true total."
331
+ : undefined
332
+ }
333
+ >
334
+ Showing {shown.length.toLocaleString()} of {total.toLocaleString()}
335
+ </p>
336
+ ) : null}
337
+
338
+ {outgoing.length ? (
339
+ <div className="autob-lane-routes">
340
+ {outgoing.map((r) => (
341
+ <span key={`${r.from}-${r.to}`} className="autob-route" title="Records matching this go there next">
342
+ {r.label ||
343
+ `${r.condition?.field} ${r.condition?.op} ${r.condition?.value ?? ""}`.trim()}
344
+ {" β†’ "}
345
+ {labels.get(r.to) || r.to}
346
+ </span>
347
+ ))}
348
+ </div>
349
+ ) : null}
350
+ </div>
351
+ );
352
+ };
353
+
354
+ if (!boardStages.length) {
355
+ return (
356
+ <div className="autob-board">
357
+ <p className="autob-board-note">This automation has no stages yet.</p>
358
+ </div>
359
+ );
360
+ }
361
+
362
+ return (
363
+ <div className="autob-board">
364
+ {!board.stageField ? (
365
+ <p className="autob-board-note">
366
+ Records appear here once this flow is bound to a database.
367
+ </p>
368
+ ) : null}
369
+ {/*
370
+ β›” THE PROCESS STRIP WAS RENDERED HERE AND IS DELETED (wave 24, owner item 9).
371
+ Capture / Bright Data / Anonymous / Post engagement / Write drew as chips above the
372
+ lanes. Their bodies AND their four switches now live in Properties > Configuration >
373
+ "How this fetches" (C-CFG); session B confirmed both R7 switches β€” Bright Data's paid
374
+ rung and Write's dry run β€” arrived there before this was removed, because the strip was
375
+ the ONLY surface either of them appeared on and deleting it first would have taken a
376
+ money control and a write-vs-report control out of the product with every gate green.
377
+ The `record === false` filter above survives and must: it still keeps those stages out
378
+ of the LANES.
379
+ */}
380
+ <div className="autob-cols">
381
+ {cols.map((col) => (
382
+ <div className="autob-col" key={col}>
383
+ {/* STACKED LANES ARE THE BRANCH PATHS (R5). Two stages at the same column
384
+ are two places a record can be at the same point in the flow β€” the
385
+ routing decides which β€” so they stack rather than sitting side by side,
386
+ which would read as "then". */}
387
+ {laneStages
388
+ .filter((s) => s.col === col)
389
+ .sort((a, b) => a.row - b.row)
390
+ .map(lane)}
391
+ </div>
392
+ ))}
393
+ </div>
394
+ </div>
395
+ );
396
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/automation/AutomationBuilder.tsx CHANGED
@@ -31,7 +31,7 @@
31
  // AutomationTrigger).
32
  // ---------------------------------------------------------------------------
33
  import type { ReactNode } from "react";
34
- import { useState } from "react";
35
 
36
  import type {
37
  Action,
@@ -45,9 +45,36 @@ import type {
45
  UserTable,
46
  } from "./automationApi";
47
  import CondBuilder, { condComplete } from "./CondBuilder";
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  interface Props {
50
  automation: Automation;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  /** The server's trigger vocabulary (C3). Absent is a state this file states, never fills in. */
52
  triggers?: TriggerOption[];
53
  catalog: ActionCatalogRow[];
@@ -70,11 +97,16 @@ interface Props {
70
  onRunNow: () => void;
71
  /**
72
  * The MACHINE steps' config bodies (source / columns / capture / find / write). They live in
73
- * `AutomationDetail` and are unchanged by this wave, so they are passed IN rather than moved:
74
- * a builder that re-implemented them would be a second copy of five panels whose only job is
75
- * to agree with the engine.
 
 
 
 
 
76
  */
77
- renderNodePanel: (node: GraphNode) => ReactNode;
78
  /**
79
  * The SCHEDULE half of the trigger face (`AutomationTrigger` with its picker hidden). Passed
80
  * in for the same reason the node panels are: the cron round-trip, the server's preset list
@@ -82,9 +114,34 @@ interface Props {
82
  * same element rather than two copies of three things that go wrong invisibly.
83
  */
84
  scheduleFace: ReactNode;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  }
86
 
87
- type Sel = { kind: "trigger" | "action" | "node"; id: string };
 
 
 
 
 
88
 
89
  /** Airtable phrases the empty state's shortcuts; ours come from the SERVER's own list (image 1). */
90
  const SUGGESTED = 6;
@@ -172,6 +229,22 @@ function TriggerMark({ kind = "" }: { kind?: string }) {
172
  <path d="M13.4 9.4a1.6 1.6 0 0 1-1.6 1.6H5.4L2.6 13.4V4.2a1.6 1.6 0 0 1 1.6-1.6h7.6a1.6 1.6 0 0 1 1.6 1.6z" />
173
  </svg>
174
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  return (
176
  <svg {...common}>
177
  <path d="M3 3v6.2a2 2 0 0 0 2 2h7.4" />
@@ -311,6 +384,9 @@ function tableLabel(tables: UserTable[], key: string): string {
311
 
312
  export default function AutomationBuilder({
313
  automation,
 
 
 
314
  triggers,
315
  catalog,
316
  vocab,
@@ -321,14 +397,27 @@ export default function AutomationBuilder({
321
  onToggleNode,
322
  onPickTrigger,
323
  onRunNow,
324
- renderNodePanel,
325
  scheduleFace,
 
 
 
326
  }: Props) {
327
  const [sel, setSel] = useState<Sel>({ kind: "trigger", id: "" });
328
  const [picking, setPicking] = useState(false);
329
  const [adding, setAdding] = useState(false);
330
  /** The trigger key awaiting confirmation (image 6) β€” a change that can invalidate config. */
331
  const [confirmKey, setConfirmKey] = useState("");
 
 
 
 
 
 
 
 
 
 
332
 
333
  const trigger = automation.trigger || null;
334
  const triggerKey = trigger?.key || (automation.schedule?.enabled ? "schedule" : "manual");
@@ -365,33 +454,67 @@ export default function AutomationBuilder({
365
  const patchFlow = (next: Action[]) =>
366
  onPatch({ flow: { actions: next, ending: automation.flow?.ending || { mode: "terminal" } } });
367
 
368
- /** Replace one action anywhere in the tree, groups included β€” ids are stable server-side. */
369
- const editAction = (id: string, change: (a: Action) => Action) => {
370
- const walk = (list: Action[]): Action[] =>
371
- list.map((a) => {
372
- if (a.id === id) return change(a);
373
- const kids = (a.config as { actions?: Action[] })?.actions;
374
- if (a.kind === "group" && Array.isArray(kids))
375
- return { ...a, config: { ...a.config, actions: walk(kids) } };
376
- return a;
377
- });
378
- patchFlow(walk(actions));
379
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
380
 
381
  const dropAction = (id: string) => {
382
- const walk = (list: Action[]): Action[] =>
383
- list
384
- .filter((a) => a.id !== id)
385
- .map((a) => {
386
- const kids = (a.config as { actions?: Action[] })?.actions;
387
- return a.kind === "group" && Array.isArray(kids)
388
- ? { ...a, config: { ...a.config, actions: walk(kids) } }
389
- : a;
390
- });
391
- patchFlow(walk(actions));
392
  if (sel.kind === "action" && sel.id === id) setSel({ kind: "trigger", id: "" });
393
  };
394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395
  /**
396
  * β›” A NEW ACTION'S CONFIG MUST BE ONE THE SERVER ACCEPTS β€” and the first version of this
397
  * function got it wrong for FOUR of the five kinds, which is worth writing down because every
@@ -411,7 +534,17 @@ export default function AutomationBuilder({
411
  * the reason, rather than offered and refused: the two states look identical to a user and
412
  * only one of them is honest.
413
  */
414
- const walkFields = table?.fields || [];
 
 
 
 
 
 
 
 
 
 
415
  const firstField = walkFields[0]?.key || "";
416
  const firstTable = tables[0] || null;
417
  const firstTableField = firstTable?.fields?.[0]?.key || "";
@@ -428,13 +561,38 @@ export default function AutomationBuilder({
428
  if (kind === "find_records")
429
  return firstTable ? { table: firstTable.key, cond: null, limit: 25 } : null;
430
  if (kind === "group")
431
- // A group with no children "does nothing" and is refused, so it is born with one β€” the
432
- // cheapest legal child, not a review, because a review would also mint a board stage that
433
- // nobody asked for by clicking "Conditional logic".
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434
  return firstField
435
- ? { cond: null,
436
- actions: [{ id: "", kind: "update_record", enabled: true, when: null,
437
- config: { values: { [firstField]: "" } } }] }
 
 
 
 
 
 
 
 
 
 
438
  : null;
439
  return null;
440
  };
@@ -448,24 +606,116 @@ export default function AutomationBuilder({
448
  return "";
449
  };
450
 
451
- const addAction = (kind: string, into?: string) => {
 
 
 
 
 
452
  const seed = seedFor(kind);
453
  if (!seed) return;
454
  const fresh: Action = { id: "", kind, enabled: true, when: null, config: seed };
455
  if (!into) {
456
  patchFlow([...actions, fresh]);
457
  } else {
458
- editAction(into, (a) => ({
459
- ...a,
460
- config: {
461
- ...a.config,
462
- actions: [...(((a.config as { actions?: Action[] }).actions) || []), fresh],
463
- },
464
- }));
 
 
 
 
 
 
 
 
 
465
  }
466
  setAdding(false);
467
  };
468
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
469
  // ── the centre column ────────────────────────────────────────────────────────────────────
470
  const chip = () => {
471
  if (!chosen) return null;
@@ -489,10 +739,12 @@ export default function AutomationBuilder({
489
  return null;
490
  };
491
 
492
- const actionCard = (a: Action, depth: number): ReactNode => {
493
  const row = catalog.find((c) => c.kind === a.kind);
494
- const kids = ((a.config as { actions?: Action[] }).actions) || [];
495
  const isGroup = a.kind === "group";
 
 
 
496
  return (
497
  <div className="autox-actionwrap" key={a.id}>
498
  <div
@@ -500,23 +752,100 @@ export default function AutomationBuilder({
500
  "autox-card" +
501
  (sel.kind === "action" && sel.id === a.id ? " is-selected" : "") +
502
  (a.enabled ? "" : " is-off") +
503
- (isGroup ? " is-group" : "")
 
 
 
 
 
 
504
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505
  >
506
  <button
507
  type="button"
508
  className="autox-card-hit"
509
  aria-pressed={sel.kind === "action" && sel.id === a.id}
510
- onClick={() => setSel({ kind: "action", id: a.id })}
 
 
 
 
511
  >
 
 
 
 
 
512
  <span className="autox-card-mark">
513
  <ActionMark kind={a.kind} />
514
  </span>
515
  <span className="autox-card-text">
516
  <span className="autox-card-title">
517
- {isGroup ? "If conditions are met" : row?.label || a.kind}
 
 
 
 
 
518
  </span>
519
- {isGroup ? null : (
 
 
 
 
 
 
520
  <span className="autox-card-sub">{actionSub(a, tables)}</span>
521
  )}
522
  </span>
@@ -536,23 +865,87 @@ export default function AutomationBuilder({
536
  </button>
537
  </div>
538
 
539
- {/* A GROUP HOLDS ITS OWN COLUMN (image 9) β€” nested cards and their own dashed add. The
540
- nesting ceiling is the SERVER's `maxGroupDepth`, so this affordance disappears at
541
- exactly the depth `clean_actions` refuses. */}
 
 
 
 
 
 
 
 
542
  {isGroup ? (
543
- <div className="autox-nest">
544
- {kids.map((k) => actionCard(k, depth + 1))}
545
- {depth + 1 < (vocab?.maxGroupDepth ?? 2) || !kids.length ? (
546
- <button
547
- type="button"
548
- className="autox-add is-nested"
549
- disabled={busy || !seedFor("update_record")}
550
- title={seedFor("update_record") ? undefined : seedBlock("update_record")}
551
- onClick={() => addAction("update_record", a.id)}
552
- >
553
- + Add an action in this group
554
- </button>
555
- ) : null}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
556
  </div>
557
  ) : null}
558
  </div>
@@ -652,52 +1045,22 @@ export default function AutomationBuilder({
652
  <span className="autox-tag">Actions</span>
653
  </div>
654
  <div className="autox-main">
655
- {actions.map((a) => actionCard(a, 0))}
656
 
657
- {/* THE MACHINE STEPS (C1) β€” engine-derived, read-only cards. They are what this
658
- automation IS (fetch a page, write a database); the flow's actions are what the
659
- owner adds on top. Rendering them from `graph()` is the same law the numbered
660
- steps were built on: the surface cannot show a step the engine stopped running. */}
661
- {nodes.map((n) => (
662
- <div
663
- key={n.id}
664
- className={
665
- "autox-card is-machine" +
666
- (sel.kind === "node" && sel.id === n.id ? " is-selected" : "") +
667
- (n.enabled ? "" : " is-off")
668
- }
669
- >
670
- <button
671
- type="button"
672
- className="autox-card-hit"
673
- aria-pressed={sel.kind === "node" && sel.id === n.id}
674
- title={n.detail || n.subtitle}
675
- onClick={() => setSel({ kind: "node", id: n.id })}
676
- >
677
- <span className="autox-card-mark">
678
- <ActionMark kind={n.kind} />
679
- </span>
680
- <span className="autox-card-text">
681
- <span className="autox-card-title">{n.title}</span>
682
- <span className="autox-card-sub">{n.subtitle}</span>
683
- </span>
684
- <span className={`auto-dot is-${n.status}`} aria-label={`Last run: ${n.status}`} />
685
- </button>
686
- {n.toggle ? (
687
- <button
688
- type="button"
689
- className={"auto-step-switch" + (n.enabled ? " is-on" : "")}
690
- disabled={busy}
691
- aria-pressed={n.enabled}
692
- aria-label={`${n.enabled ? "Turn off" : "Turn on"} ${n.title}`}
693
- title={`${n.enabled ? "Turn off" : "Turn on"} ${n.title}`}
694
- onClick={() => onToggleNode(n.id)}
695
- >
696
- <span className="auto-step-switch-knob" />
697
- </button>
698
- ) : null}
699
- </div>
700
- ))}
701
 
702
  <button
703
  type="button"
@@ -715,7 +1078,7 @@ export default function AutomationBuilder({
715
  wall rather than a decoration. */}
716
  {adding ? (
717
  <div className="autox-menu" role="menu">
718
- {[...new Set(catalog.map((c) => c.group))].map((group) => (
719
  <div className="autox-menu-group" key={group}>
720
  <p className="autox-menu-head">{group}</p>
721
  {catalog
@@ -765,11 +1128,39 @@ export default function AutomationBuilder({
765
  <aside className="auto-panel autox-props" aria-label="Properties">
766
  <div className="auto-panel-head">
767
  <h2>Properties</h2>
768
- <span className={"autox-saved" + (busy ? " is-busy" : "")}>
769
- {busy ? "Saving…" : "All changes saved"}
 
 
 
 
 
 
 
 
 
770
  </span>
771
  </div>
772
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
773
  {sel.kind === "trigger" ? (
774
  <TriggerProps
775
  automation={automation}
@@ -783,13 +1174,17 @@ export default function AutomationBuilder({
783
  vocab={vocab}
784
  oauth={oauth}
785
  busy={busy}
 
 
 
786
  onAskChange={setConfirmKey}
787
  onPatchTrigger={patchTrigger}
788
  onPickTrigger={onPickTrigger}
789
  onRunNow={onRunNow}
790
  scheduleFace={scheduleFace}
 
791
  />
792
- ) : sel.kind === "action" ? (
793
  <ActionProps
794
  action={findAction(actions, sel.id)}
795
  catalog={catalog}
@@ -801,8 +1196,6 @@ export default function AutomationBuilder({
801
  busy={busy}
802
  onEdit={(change) => editAction(sel.id, change)}
803
  />
804
- ) : (
805
- nodePanel(nodes, sel.id, renderNodePanel)
806
  )}
807
  </aside>
808
 
@@ -892,30 +1285,25 @@ function actionSub(a: Action, tables: UserTable[]): string {
892
  function findAction(list: Action[], id: string): Action | null {
893
  for (const a of list) {
894
  if (a.id === id) return a;
895
- const kids = (a.config as { actions?: Action[] })?.actions;
896
- if (a.kind === "group" && Array.isArray(kids)) {
897
- const hit = findAction(kids, id);
898
- if (hit) return hit;
899
- }
 
 
 
900
  }
901
  return null;
902
  }
903
 
904
- function nodePanel(
905
- nodes: GraphNode[],
906
- id: string,
907
- render: (node: GraphNode) => ReactNode
908
- ): ReactNode {
909
- const node = nodes.find((n) => n.id === id);
910
- if (!node) return <p className="auto-note">That step is no longer part of this automation.</p>;
911
- return (
912
- <>
913
- <h3>{node.title}</h3>
914
- {node.detail ? <p className="auto-hint">{node.detail}</p> : null}
915
- {render(node)}
916
- </>
917
- );
918
- }
919
 
920
  // ── the Properties panel's two faces ─────────────────────────────────────────────────────────
921
 
@@ -931,11 +1319,15 @@ function TriggerProps({
931
  vocab,
932
  oauth,
933
  busy,
 
 
 
934
  onAskChange,
935
  onPatchTrigger,
936
  onPickTrigger,
937
  onRunNow,
938
  scheduleFace,
 
939
  }: {
940
  automation: Automation;
941
  triggerKey: string;
@@ -948,12 +1340,17 @@ function TriggerProps({
948
  vocab?: FlowVocab;
949
  oauth: OAuthStatus | null;
950
  busy: boolean;
 
 
 
 
951
  /** Ask before a trigger change that can invalidate the config under it (image 6). */
952
  onAskChange: (key: string) => void;
953
  onPatchTrigger: (patch: Record<string, unknown>) => void;
954
  onPickTrigger: (key: string) => void;
955
  onRunNow: () => void;
956
  scheduleFace: ReactNode;
 
957
  }) {
958
  const trigger = automation.trigger || null;
959
  const provider = picked?.connect?.provider || "";
@@ -984,25 +1381,44 @@ function TriggerProps({
984
  {triggerKey && !options.some((t) => t.key === triggerKey) ? (
985
  <option value={triggerKey}>{triggerKey} (not offered here)</option>
986
  ) : null}
987
- {options.map((t) => (
988
- <option key={t.key} value={t.key} disabled={!!t.planned}>
989
- {t.planned
990
- ? `${t.label} β€” coming soon`
991
- : t.ready === false
992
- ? `${t.label} β€” needs setting up`
993
- : t.label}
994
- </option>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
995
  ))}
996
  </select>
997
  </div>
998
  {/*
999
- β›” NO DESCRIPTION PARAGRAPH HERE, and its absence is deliberate. Airtable prints two
1000
- sentences under this select (image 3). Ours would be a CLIENT paraphrase of a server
1001
- vocabulary β€” the thing DESIGN.md 4 calls a hand copy of a registry that goes stale in
1002
- silence the day the engine changes what a trigger does. A one-line `detail` on the
1003
- server's own `TriggerOption` is asked for in the wave mailbox; when it rides, it renders
1004
- here and cannot disagree with the engine.
1005
  */}
 
1006
  {picked && picked.ready === false && !picked.planned ? (
1007
  <div className="autob-needs">
1008
  <span className="autob-needs-text">
@@ -1046,25 +1462,19 @@ function TriggerProps({
1046
 
1047
  {triggerKey === "event_field" ? (
1048
  <>
1049
- <div className="auto-field">
1050
- <label htmlFor="autox-tfield">Watched column</label>
1051
- <select
1052
- id="autox-tfield"
1053
- className="auto-input"
1054
- value={trigger?.field || ""}
1055
- disabled={busy}
1056
- onChange={(e) => onPatchTrigger({ field: e.target.value })}
1057
- >
1058
- {/* EMPTY IS A REAL CHOICE, not a missing one: unnamed means "any column", which is
1059
- Airtable's plain condition trigger and the engine's own default. */}
1060
- <option value="">Any column</option>
1061
- {(table?.fields || []).map((f) => (
1062
- <option key={f.key} value={f.key}>
1063
- {f.label}
1064
- </option>
1065
- ))}
1066
- </select>
1067
- </div>
1068
  <p className="auto-field-label">
1069
  <span className="autox-req">*</span> Conditions
1070
  </p>
@@ -1112,7 +1522,29 @@ function TriggerProps({
1112
  <label htmlFor="autox-tview">
1113
  <span className="autox-req">*</span> View
1114
  </label>
1115
- {table?.views?.length ? (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1116
  <select
1117
  id="autox-tview"
1118
  className="auto-input"
@@ -1121,25 +1553,25 @@ function TriggerProps({
1121
  onChange={(e) => onPatchTrigger({ viewId: e.target.value })}
1122
  >
1123
  <option value="">Select a view…</option>
 
 
 
 
 
 
 
 
 
 
 
 
 
1124
  {table.views.map((v) => (
1125
  <option key={v.id} value={v.id}>
1126
  {v.label}
1127
  </option>
1128
  ))}
1129
  </select>
1130
- ) : (
1131
- /*
1132
- ⚠ ABSENT IS A STATE, NOT AN EMPTY PICKER. `GET /automations/tables` does not carry
1133
- views yet (asked of the engine session in the wave mailbox). An empty dropdown here
1134
- would read as "this database has no views", which is a claim nobody measured β€” so
1135
- the surface says what is actually true and the control lights up the day the list
1136
- rides, with no change on this side.
1137
- */
1138
- <p className="auto-note">
1139
- {table
1140
- ? "This server did not offer a view list for that database yet."
1141
- : "Choose a database first."}
1142
- </p>
1143
  )}
1144
  </div>
1145
  ) : null}
@@ -1172,14 +1604,79 @@ function TriggerProps({
1172
  </div>
1173
  ) : null}
1174
 
1175
- {/* THE SCHEDULE, rendered by the one component that owns the cron round-trip. */}
1176
- {triggerKey === "schedule" ? scheduleFace : null}
 
 
 
1177
  {triggerKey === "manual" ? (
1178
  <p className="auto-hint">
1179
  It runs when you press Run once now, and nothing else starts it.
1180
  </p>
1181
  ) : null}
1182
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1183
  <h3>Test step</h3>
1184
  {/*
1185
  β›” HONEST TO OUR SEMANTICS, not to Airtable's. Airtable's "Test step" replays one step
@@ -1255,23 +1752,49 @@ function ActionProps({
1255
 
1256
  {action.kind === "group" ? (
1257
  <>
1258
- <p className="auto-field-label">Run these actions if…</p>
1259
- <CondBuilder
1260
- cond={(cfg as { cond?: Cond | null }).cond || null}
1261
- onChange={(next) => setCfg({ cond: next })}
1262
- fields={walkFields}
1263
- ops={ops}
1264
- nullaryOps={nullaryOps}
1265
- maxDepth={vocab?.maxCondDepth ?? 3}
1266
- maxChildren={vocab?.maxCondChildren ?? 12}
1267
- lead=""
1268
- disabled={busy}
1269
- />
1270
- {/* ⚠ THE FIELD LIST IS THE WALKING RECORD'S, and this panel does not know which
1271
- database that is β€” the trigger decides it and a group can sit under any of them.
1272
- So the field picker offers the stored key rather than a list it would have to
1273
- guess at; a wrong list is worse than a typed key, because it looks authoritative.
1274
- Booked for the wave that gives an action its own resolved table. */}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1275
  </>
1276
  ) : null}
1277
 
 
31
  // AutomationTrigger).
32
  // ---------------------------------------------------------------------------
33
  import type { ReactNode } from "react";
34
+ import { useRef, useState } from "react";
35
 
36
  import type {
37
  Action,
 
45
  UserTable,
46
  } from "./automationApi";
47
  import CondBuilder, { condComplete } from "./CondBuilder";
48
+ import { groupBranches, groupByPanel, numberActions, reorderList } from "./steps";
49
+
50
+ /**
51
+ * β›” A PRIVATE MIME, AND `text/plain` IS NEVER SET (owner item 11; the wave-13 C-LAYOUT scar).
52
+ * A drag carrying `text/plain` is a drag the whole operating system understands: drop it on any
53
+ * input, textarea or contenteditable β€” this builder is full of them β€” and the browser TYPES the
54
+ * payload in, so a mis-aimed reorder silently writes an action id into somebody's condition
55
+ * value. A private type is inert everywhere except the drop targets below, which is why the nav
56
+ * rail's own drag uses one (`Shell.tsx:90 NAV_DRAG_TYPE`).
57
+ * ⚠ The board's card drag still uses `text/plain` (`AutomationBoard.tsx:167`) β€” noted, not fixed
58
+ * here: that file belongs to another session this wave.
59
+ */
60
+ const ACTION_DRAG_TYPE = "application/x-loopable-action";
61
 
62
  interface Props {
63
  automation: Automation;
64
+ /**
65
+ * THE AUTOMATION'S NAME (item 15b, C-DETAIL) β€” it left the page header and Properties is where
66
+ * it went, at the top, above whatever step is selected. REQUIRED, all three: an optional prop
67
+ * degrades to "the field does not exist", which looks exactly like never having built it.
68
+ *
69
+ * ⚠ TEXT AND COMMIT ARE SEPARATE ON PURPOSE. This is the cron field's shape
70
+ * (`AutomationTrigger`'s `onCronText` / `onSchedule`): free text stays controlled while typing
71
+ * and writes ONCE on blur, because per-keystroke would PATCH a half-typed name. Folding them
72
+ * into one callback would force a choice between a laggy controlled input and a save per
73
+ * keystroke, and this file has already paid for both.
74
+ */
75
+ name: string;
76
+ onNameText: (v: string) => void;
77
+ onNameCommit: () => void;
78
  /** The server's trigger vocabulary (C3). Absent is a state this file states, never fills in. */
79
  triggers?: TriggerOption[];
80
  catalog: ActionCatalogRow[];
 
97
  onRunNow: () => void;
98
  /**
99
  * The MACHINE steps' config bodies (source / columns / capture / find / write). They live in
100
+ * `AutomationDetail`, so they are passed IN rather than moved: a builder that re-implemented
101
+ * them would be a second copy of five panels whose only job is to agree with the engine.
102
+ *
103
+ * ⚠ IT TAKES A PANEL KEY, NOT A NODE (item 5, C-CFG). It used to be
104
+ * `(node: GraphNode) => ReactNode`, and the caller's whole body was `panelBody(node.panel)` β€”
105
+ * so the node was only ever a wrapper around the key. Now that Properties renders the panels
106
+ * GROUPED BY that key, taking a node would invite the caller to pass one node of a group and
107
+ * quietly imply the body belongs to it alone.
108
  */
109
+ renderNodeBody: (panel: string) => ReactNode;
110
  /**
111
  * The SCHEDULE half of the trigger face (`AutomationTrigger` with its picker hidden). Passed
112
  * in for the same reason the node panels are: the cron round-trip, the server's preset list
 
114
  * same element rather than two copies of three things that go wrong invisibly.
115
  */
116
  scheduleFace: ReactNode;
117
+ /**
118
+ * Does the cron drive the CURRENT trigger (owner item 7)? REQUIRED, and decided by the caller
119
+ * for the reason `AutomationTrigger.schedules` gives: which keys the cron drives is a per-key
120
+ * fact, and no component below the detail is entitled to name trigger keys.
121
+ */
122
+ schedules: boolean;
123
+ /**
124
+ * ⭐ THE DATABASE THE FLOW'S RECORDS WALK (owner item 12a) β€” the trigger's table, or the
125
+ * automation's own target, resolved by the caller the way `automation_engine._flow_table` does.
126
+ * REQUIRED: an absent one degrades to an empty field list, which is the exact defect this prop
127
+ * exists to fix and is indistinguishable from "this database has no columns".
128
+ */
129
+ walkTable: string;
130
+ /**
131
+ * Is there an edit the HEADER's Save still owns? REQUIRED, and it exists so the panel's
132
+ * "All changes saved" stamp can stop being a claim about fields it does not cover β€” the
133
+ * machine steps' panels moved into Properties this wave and they commit with Save, not on
134
+ * change.
135
+ */
136
+ dirty: boolean;
137
  }
138
 
139
+ /*
140
+ * ⚠ `"node"` LEFT THIS UNION WITH THE MACHINE CARDS (item 5). It existed so a click on one of
141
+ * those cards could open its panel; with the cards gone nothing can set it, and a variant no
142
+ * code path can reach is a branch that reads as supported and is not.
143
+ */
144
+ type Sel = { kind: "trigger" | "action"; id: string };
145
 
146
  /** Airtable phrases the empty state's shortcuts; ours come from the SERVER's own list (image 1). */
147
  const SUGGESTED = 6;
 
229
  <path d="M13.4 9.4a1.6 1.6 0 0 1-1.6 1.6H5.4L2.6 13.4V4.2a1.6 1.6 0 0 1 1.6-1.6h7.6a1.6 1.6 0 0 1 1.6 1.6z" />
230
  </svg>
231
  );
232
+ /*
233
+ WAVE 24 β€” the only "Sources" trigger (C-TRIG). A magnifier with a PERSON inside it: this one
234
+ does not watch a database, it searches a corpus of profiles and makes rows out of what fits.
235
+ ⚠ Deliberately not the bare magnifier β€” `ActionMark`'s `find_records` already owns that shape
236
+ for "search a database", and two searches drawn identically would be the six-identical-arrows
237
+ problem this component's header talks itself out of.
238
+ */
239
+ if (kind === "ig_profile_match")
240
+ return (
241
+ <svg {...common}>
242
+ <circle cx="7" cy="7" r="4.4" />
243
+ <path d="m10.4 10.4 3.2 3.2" />
244
+ <circle cx="7" cy="5.9" r="1.3" />
245
+ <path d="M4.9 9.7c.4-1.1 1.2-1.7 2.1-1.7s1.7.6 2.1 1.7" />
246
+ </svg>
247
+ );
248
  return (
249
  <svg {...common}>
250
  <path d="M3 3v6.2a2 2 0 0 0 2 2h7.4" />
 
384
 
385
  export default function AutomationBuilder({
386
  automation,
387
+ name,
388
+ onNameText,
389
+ onNameCommit,
390
  triggers,
391
  catalog,
392
  vocab,
 
397
  onToggleNode,
398
  onPickTrigger,
399
  onRunNow,
400
+ renderNodeBody,
401
  scheduleFace,
402
+ schedules,
403
+ walkTable,
404
+ dirty,
405
  }: Props) {
406
  const [sel, setSel] = useState<Sel>({ kind: "trigger", id: "" });
407
  const [picking, setPicking] = useState(false);
408
  const [adding, setAdding] = useState(false);
409
  /** The trigger key awaiting confirmation (image 6) β€” a change that can invalidate config. */
410
  const [confirmKey, setConfirmKey] = useState("");
411
+ /** The card a reorder is hovering over (item 11). `""` = nothing is being dragged. */
412
+ const [dragOver, setDragOver] = useState("");
413
+ /**
414
+ * β›” ONE DRAG SUPPRESSES EXACTLY ONE CLICK (item 11; `AutomationBoard`'s trap 1, which this
415
+ * repo has already paid for once). Browsers can deliver a `click` after `dragend`, and the
416
+ * thing under the pointer here is the card's own selector β€” so a finished reorder would ALSO
417
+ * change which step the Properties panel is showing, which reads as the panel jumping on its
418
+ * own. A ref and not state, because the click arrives before a re-render would land.
419
+ */
420
+ const draggedRef = useRef(false);
421
 
422
  const trigger = automation.trigger || null;
423
  const triggerKey = trigger?.key || (automation.schedule?.enabled ? "schedule" : "manual");
 
454
  const patchFlow = (next: Action[]) =>
455
  onPatch({ flow: { actions: next, ending: automation.flow?.ending || { mode: "terminal" } } });
456
 
457
+ /**
458
+ * ⭐ ONE TREE WALKER (wave 24, C-FORK). Rewrite or drop any action anywhere, branches included:
459
+ * `f` returns a replacement, or `null` to remove it.
460
+ *
461
+ * β›” THIS REPLACED FOUR HAND-ROLLED WALKS, and they were four places to forget the same thing.
462
+ * A group's children moved from `config.actions` to `config.branches[].actions` this wave, so
463
+ * every one of them would have quietly stopped descending into a fork β€” editing, deleting or
464
+ * counting nothing inside it, with `tsc` perfectly happy because `config` is
465
+ * `Record<string, unknown>` and an absent key is just `undefined`. The failure would have been
466
+ * "the card is there and the delete button does nothing", per action, per fork.
467
+ */
468
+ const mapTree = (list: Action[], f: (a: Action) => Action | null): Action[] =>
469
+ (list || [])
470
+ .map((a) => {
471
+ const next = f(a);
472
+ if (next === null) return null;
473
+ if (next.kind !== "group") return next;
474
+ const brs = groupBranches(next);
475
+ if (!brs.length) return next;
476
+ return {
477
+ ...next,
478
+ config: {
479
+ ...next.config,
480
+ branches: brs.map((br) => ({ ...br, actions: mapTree(br.actions || [], f) })),
481
+ },
482
+ };
483
+ })
484
+ .filter((a): a is Action => a !== null);
485
+
486
+ /** Replace one action anywhere in the tree, forks included β€” ids are stable server-side. */
487
+ const editAction = (id: string, change: (a: Action) => Action) =>
488
+ patchFlow(mapTree(actions, (a) => (a.id === id ? change(a) : a)));
489
 
490
  const dropAction = (id: string) => {
491
+ // ⚠ REMOVING THE LAST ACTION IN A BRANCH IS REFUSED BY THE SERVER ("a branch with no actions
492
+ // inside it does nothing") and the refusal is printed verbatim, as every other one is. Not
493
+ // pre-empted here: a client that predicted it would be a second validator, and the honest
494
+ // repair β€” delete the branch, not its last child β€” is one the reader can act on.
495
+ patchFlow(mapTree(actions, (a) => (a.id === id ? null : a)));
 
 
 
 
 
496
  if (sel.kind === "action" && sel.id === id) setSel({ kind: "trigger", id: "" });
497
  };
498
 
499
+ /**
500
+ * REORDER (owner item 11). The whole `flow.actions` list goes back through `patchFlow` β€” the
501
+ * same door every other edit uses β€” rather than a bespoke move endpoint, because the engine
502
+ * already validates a whole flow and a second write path would be a second thing to keep
503
+ * agreeing with `clean_actions`.
504
+ *
505
+ * ⚠ TOP-LEVEL SIBLINGS ONLY, deliberately, and it is a SCOPE rather than an oversight: a card
506
+ * inside a conditional group is not `draggable` at all, so there is no affordance that quietly
507
+ * does nothing. Group children are about to stop living under `config.actions` and start living
508
+ * under `config.branches[].actions` (C-FORK), and building a tree-walking reorder against a
509
+ * shape this same wave replaces would be work done twice with a window of wrongness in between.
510
+ */
511
+ const moveAction = (dragId: string, dropId: string) => {
512
+ const next = reorderList(actions, dragId, dropId);
513
+ // `null` = same card, or one of them is not a top-level sibling. Nothing moved, so nothing
514
+ // is written β€” an aborted drag must not PATCH the flow back over itself.
515
+ if (next) patchFlow(next);
516
+ };
517
+
518
  /**
519
  * β›” A NEW ACTION'S CONFIG MUST BE ONE THE SERVER ACCEPTS β€” and the first version of this
520
  * function got it wrong for FOUR of the five kinds, which is worth writing down because every
 
534
  * the reason, rather than offered and refused: the two states look identical to a user and
535
  * only one of them is honest.
536
  */
537
+ /**
538
+ * ⭐ THE WALKING RECORD'S COLUMNS (item 12a). Read off `walkTable`, NOT off `table`.
539
+ *
540
+ * `table` is the TRIGGER's database and it answers a different question β€” which columns the
541
+ * trigger may watch or test. This one answers what the ACTIONS write to and what a branch's
542
+ * condition compares, and on any automation without an event trigger (manual, schedule,
543
+ * `ig_profile_match`) the two are not the same table at all: the first is empty and the second
544
+ * is where all the records are. Reading actions' fields off the trigger is why every condition
545
+ * inside a fork offered an empty picker.
546
+ */
547
+ const walkFields = (tables.find((t) => t.key === walkTable) || null)?.fields || [];
548
  const firstField = walkFields[0]?.key || "";
549
  const firstTable = tables[0] || null;
550
  const firstTableField = firstTable?.fields?.[0]?.key || "";
 
561
  if (kind === "find_records")
562
  return firstTable ? { table: firstTable.key, cond: null, limit: 25 } : null;
563
  if (kind === "group")
564
+ /*
565
+ ⭐ RE-SEEDED FOR C-FORK, and the old seed would now be REFUSED. It was
566
+ `{cond: null, actions: [child]}` β€” the pre-wave-24 shape, which `clean_actions` no longer
567
+ accepts as a config: the fork's legs live under `branches` and `cond`/`actions` are gone
568
+ from the group's own config entirely. Clicking "If / then" would have produced a red
569
+ banner and no card, which is precisely the illegal-default-seed defect this function's
570
+ header was written about, reproduced by the wave that quotes it.
571
+
572
+ MEASURED against `clean_actions` rather than reasoned:
573
+ Β· a branch with no actions -> "a branch with no actions inside it does nothing"
574
+ Β· so the one branch is born with the cheapest legal child, exactly as before β€” not a
575
+ review, which would also mint a board stage nobody asked for by clicking "If / then".
576
+ β›” `label: ""` ON PURPOSE. The SERVER letters the branches by index and calls a null-cond
577
+ last leg "Otherwise", but it PRESERVES any label the client sends β€” so sending one would
578
+ freeze it, and a branch labelled "A" would still say "A" after the branch above it was
579
+ deleted. Sending nothing keeps the lettering correct by construction, and this fresh
580
+ single branch reads "Otherwise" until it is given a condition, which is what it is.
581
+ */
582
  return firstField
583
+ ? {
584
+ branches: [
585
+ {
586
+ id: "b1",
587
+ label: "",
588
+ cond: null,
589
+ actions: [
590
+ { id: "", kind: "update_record", enabled: true, when: null,
591
+ config: { values: { [firstField]: "" } } },
592
+ ],
593
+ },
594
+ ],
595
+ }
596
  : null;
597
  return null;
598
  };
 
606
  return "";
607
  };
608
 
609
+ /**
610
+ * ⚠ `into` NAMES A BRANCH NOW, not just a group (C-FORK). A fork has several legs and "add an
611
+ * action to this group" stopped being a complete instruction the moment it did β€” putting it in
612
+ * the first branch by default would silently attach work to whichever leg happens to be first.
613
+ */
614
+ const addAction = (kind: string, into?: { actionId: string; branchId: string }) => {
615
  const seed = seedFor(kind);
616
  if (!seed) return;
617
  const fresh: Action = { id: "", kind, enabled: true, when: null, config: seed };
618
  if (!into) {
619
  patchFlow([...actions, fresh]);
620
  } else {
621
+ patchFlow(
622
+ mapTree(actions, (a) => {
623
+ if (a.id !== into.actionId) return a;
624
+ return {
625
+ ...a,
626
+ config: {
627
+ ...a.config,
628
+ branches: groupBranches(a).map((br) =>
629
+ br.id === into.branchId
630
+ ? { ...br, actions: [...(br.actions || []), fresh] }
631
+ : br
632
+ ),
633
+ },
634
+ };
635
+ })
636
+ );
637
  }
638
  setAdding(false);
639
  };
640
 
641
+ /** Add an empty-conditioned leg to a fork. The server letters it and enforces the ceiling. */
642
+ const addBranch = (actionId: string) => {
643
+ const seedChild = seedFor("update_record");
644
+ if (!seedChild) return;
645
+ patchFlow(
646
+ mapTree(actions, (a) => {
647
+ if (a.id !== actionId) return a;
648
+ const brs = groupBranches(a);
649
+ return {
650
+ ...a,
651
+ config: {
652
+ ...a.config,
653
+ // ⚠ APPENDED LAST, and the server refuses a null-cond branch that is not last β€” so a
654
+ // fork that already ends in an Otherwise leg refuses this with its own sentence
655
+ // rather than silently burying the catch-all in the middle, where every branch below
656
+ // it would be dead code.
657
+ branches: [
658
+ ...brs,
659
+ { id: "", label: "", cond: null,
660
+ actions: [{ id: "", kind: "update_record", enabled: true, when: null,
661
+ config: seedChild }] },
662
+ ],
663
+ },
664
+ };
665
+ })
666
+ );
667
+ };
668
+
669
+ const dropBranch = (actionId: string, branchId: string) =>
670
+ patchFlow(
671
+ mapTree(actions, (a) => {
672
+ if (a.id !== actionId) return a;
673
+ const kept = groupBranches(a).filter((br) => br.id !== branchId);
674
+ // A fork with no legs at all "does nothing" β€” the server says so; do not send an empty
675
+ // list dressed up as an edit.
676
+ if (!kept.length) return a;
677
+ return { ...a, config: { ...a.config, branches: kept } };
678
+ })
679
+ );
680
+
681
+ /**
682
+ * R8's numbers for the whole flow, computed ONCE per render rather than per card β€” the map is
683
+ * built by walking the tree, so asking it per card would be quadratic in a deep fork, and more
684
+ * importantly a per-card computation could not see its siblings and would have to re-derive
685
+ * the position it is being told.
686
+ */
687
+ const stepNos = numberActions(actions);
688
+
689
+ /**
690
+ * ⭐ THE ACTION MENU'S GROUP ORDER, FROM THE SERVER (owner item 12b, contract C-ACT).
691
+ *
692
+ * β›” NEVER A LITERAL LIST OF GROUP NAMES HERE. The server ships `groupOrder` on every catalog
693
+ * row (1 Web action Β· 2 Database Β· 3 Connected Β· 4 Advanced logic, derived server-side from one
694
+ * table so two rows cannot disagree about their own group). A client
695
+ * `["Web action", "Database", …]` would be a second copy of the catalog's structure, and the
696
+ * day the engine adds or renames a group the client drops it off the end β€” or drops it
697
+ * entirely β€” without anything going red.
698
+ *
699
+ * ⚠ AN UNORDERED GROUP SORTS LAST, NOT FIRST, which the server's own gate asserts. `Infinity`
700
+ * and not `0`: a missing number meant "before everything" under a naive `|| 0`, so a server
701
+ * older than this client would have led its menu with whatever it had failed to classify.
702
+ * ⚠ The sort is STABLE over first appearance, so two groups sharing an order keep the payload's
703
+ * sequence rather than an arbitrary one.
704
+ */
705
+ const menuGroups = (() => {
706
+ const order = new Map<string, number>();
707
+ const seen: string[] = [];
708
+ for (const c of catalog) {
709
+ if (!order.has(c.group)) {
710
+ order.set(c.group, typeof c.groupOrder === "number" ? c.groupOrder : Infinity);
711
+ seen.push(c.group);
712
+ }
713
+ }
714
+ return [...seen].sort(
715
+ (a, b) => (order.get(a) ?? Infinity) - (order.get(b) ?? Infinity)
716
+ );
717
+ })();
718
+
719
  // ── the centre column ────────────────────────────────────────────────────────────────────
720
  const chip = () => {
721
  if (!chosen) return null;
 
739
  return null;
740
  };
741
 
742
+ const actionCard = (a: Action, depth: number, hasNext = false): ReactNode => {
743
  const row = catalog.find((c) => c.kind === a.kind);
 
744
  const isGroup = a.kind === "group";
745
+ const branches = isGroup ? groupBranches(a) : [];
746
+ /** Only TOP-LEVEL cards reorder (see `moveAction`) β€” depth 0, and never while a write is up. */
747
+ const canDrag = depth === 0 && !busy;
748
  return (
749
  <div className="autox-actionwrap" key={a.id}>
750
  <div
 
752
  "autox-card" +
753
  (sel.kind === "action" && sel.id === a.id ? " is-selected" : "") +
754
  (a.enabled ? "" : " is-off") +
755
+ (isGroup ? " is-group" : "") +
756
+ /* ⚠ THE GUARD IS NOT DECORATION. `dragOver` idles at `""` and a fresh action carries
757
+ `id: ""` until the server names it, so a bare `dragOver === a.id` would be
758
+ `"" === ""` β€” TRUE AT REST β€” and every new card would paint as a drop target from
759
+ its first frame. That is wave 20's `is-folddrag` defect exactly, which shipped and
760
+ was seen by the owner before any gate noticed. */
761
+ (dragOver && dragOver === a.id ? " is-dropinto" : "")
762
  }
763
+ draggable={canDrag}
764
+ onDragStart={
765
+ canDrag
766
+ ? (e) => {
767
+ draggedRef.current = true;
768
+ e.dataTransfer.effectAllowed = "move";
769
+ e.dataTransfer.setData(ACTION_DRAG_TYPE, a.id);
770
+ }
771
+ : undefined
772
+ }
773
+ onDragOver={
774
+ canDrag
775
+ ? (e) => {
776
+ // Somebody else's drag β€” a file, a nav row, selected text β€” is not ours to
777
+ // accept. Without this test the card would light up for anything dragged over
778
+ // it and then swallow the drop.
779
+ if (!e.dataTransfer.types.includes(ACTION_DRAG_TYPE)) return;
780
+ e.preventDefault();
781
+ e.dataTransfer.dropEffect = "move";
782
+ setDragOver(a.id);
783
+ }
784
+ : undefined
785
+ }
786
+ onDragLeave={
787
+ canDrag
788
+ ? (e) => {
789
+ // Moving onto a CHILD of this card is not leaving it; without this the
790
+ // highlight flickers off every time the pointer crosses the title.
791
+ if (e.currentTarget.contains(e.relatedTarget as Node)) return;
792
+ setDragOver((cur) => (cur === a.id ? "" : cur));
793
+ }
794
+ : undefined
795
+ }
796
+ onDrop={
797
+ canDrag
798
+ ? (e) => {
799
+ const dragId = e.dataTransfer.getData(ACTION_DRAG_TYPE);
800
+ setDragOver("");
801
+ if (!dragId) return;
802
+ e.preventDefault();
803
+ moveAction(dragId, a.id);
804
+ }
805
+ : undefined
806
+ }
807
+ onDragEnd={() => {
808
+ setDragOver("");
809
+ // Cleared a tick later: the post-drag click arrives BEFORE this would run.
810
+ window.setTimeout(() => {
811
+ draggedRef.current = false;
812
+ }, 0);
813
+ }}
814
  >
815
  <button
816
  type="button"
817
  className="autox-card-hit"
818
  aria-pressed={sel.kind === "action" && sel.id === a.id}
819
+ onClick={() => {
820
+ // The one click a finished drag is allowed to cost is this one.
821
+ if (draggedRef.current) return;
822
+ setSel({ kind: "action", id: a.id });
823
+ }}
824
  >
825
+ {/* ⭐ R8's STEP NUMBER, computed once for the whole flow (`numberActions`). The
826
+ TRIGGER carries no number at all β€” that is the ruling, and it reverses wave 21's
827
+ "Step 1 is always the Trigger" β€” so the numbers here start at 1 on the first
828
+ ACTION. A fork occupies one number and its branches consume none. */}
829
+ <span className="autox-card-n">{stepNos.get(a.id) || ""}</span>
830
  <span className="autox-card-mark">
831
  <ActionMark kind={a.kind} />
832
  </span>
833
  <span className="autox-card-text">
834
  <span className="autox-card-title">
835
+ {/* β›” NOT "If conditions are met" ANY MORE, and the literal was the problem
836
+ rather than the wording. C-ACT relabels the `group` kind to "If / then" on
837
+ the SERVER, so a hard-coded title here was a client paraphrase of a server
838
+ vocabulary β€” it would have gone on saying the old words after the catalog
839
+ changed, which is the one failure this file's header names twice. */}
840
+ {row?.label || a.kind}
841
  </span>
842
+ {isGroup ? (
843
+ <span className="autox-card-sub">
844
+ {branches.length === 1
845
+ ? "1 branch"
846
+ : `${branches.length} branches`}
847
+ </span>
848
+ ) : (
849
  <span className="autox-card-sub">{actionSub(a, tables)}</span>
850
  )}
851
  </span>
 
865
  </button>
866
  </div>
867
 
868
+ {/*
869
+ ⭐ THE FORK (owner item 12a, ruling R8, contract C-FORK). A group used to hold ONE
870
+ nested column; it now holds a LETTERED LANE PER BRANCH, because R8 rules that a fork
871
+ occupies one step number and its legs are alternatives rather than later steps.
872
+
873
+ THE LETTER AND THE "Otherwise" ARE THE SERVER'S WORDS β€” `br.label`, printed, never
874
+ composed. `clean_actions` letters by index and names a null-cond last leg "Otherwise",
875
+ so the lanes re-letter themselves correctly when one is deleted.
876
+ The nesting ceiling is still the SERVER's `maxGroupDepth`, so the add-here affordance
877
+ disappears at exactly the depth `clean_actions` refuses.
878
+ */}
879
  {isGroup ? (
880
+ <div className="autox-branches">
881
+ {branches.map((br) => (
882
+ <div className="autox-branch" key={br.id || br.label}>
883
+ <div className="autox-branch-head">
884
+ <span className="autox-branch-letter">{br.label}</span>
885
+ <span className="autox-branch-cond">
886
+ {/* ⚠ NOT A RENDERED CONDITION β€” the tree is edited in Properties, and a
887
+ second editable copy here would be two controls for one fact. This says
888
+ only WHICH leg you are looking at. A null cond is the catch-all, and the
889
+ server has already labelled it, so this says nothing twice. */}
890
+ {br.cond ? "when its conditions match" : "everything else"}
891
+ </span>
892
+ {branches.length > 1 ? (
893
+ <button
894
+ type="button"
895
+ className="autox-branch-x"
896
+ disabled={busy}
897
+ aria-label={`Remove branch ${br.label}`}
898
+ title={`Remove branch ${br.label}`}
899
+ onClick={() => dropBranch(a.id, br.id)}
900
+ >
901
+ <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
902
+ <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
903
+ strokeLinecap="round" />
904
+ </svg>
905
+ </button>
906
+ ) : null}
907
+ </div>
908
+ <div className="autox-nest">
909
+ {(br.actions || []).map((k) => actionCard(k, depth + 1))}
910
+ {depth + 1 < (vocab?.maxGroupDepth ?? 2) || !(br.actions || []).length ? (
911
+ <button
912
+ type="button"
913
+ className="autox-add is-nested"
914
+ disabled={busy || !seedFor("update_record")}
915
+ title={seedFor("update_record") ? undefined : seedBlock("update_record")}
916
+ onClick={() => addAction("update_record", { actionId: a.id, branchId: br.id })}
917
+ >
918
+ + Add an action in {br.label}
919
+ </button>
920
+ ) : null}
921
+ </div>
922
+ </div>
923
+ ))}
924
+ <button
925
+ type="button"
926
+ className="autox-add is-nested"
927
+ disabled={busy || !seedFor("update_record")}
928
+ title={seedFor("update_record") ? undefined : seedBlock("update_record")}
929
+ onClick={() => addBranch(a.id)}
930
+ >
931
+ + Add a branch
932
+ </button>
933
+ </div>
934
+ ) : null}
935
+
936
+ {/*
937
+ THE ARROW BACK INTO THE FLOW (item 12a). The lanes are alternatives and exactly one of
938
+ them runs β€” the engine takes the first matching branch and breaks β€” so they REJOIN, and
939
+ without a mark saying so a fork at the end of a column reads as several parallel endings.
940
+ Drawn only when there IS a next step to rejoin: an arrow into nothing is a promise the
941
+ flow does not keep.
942
+ */}
943
+ {isGroup && hasNext ? (
944
+ <div className="autox-merge" aria-hidden="true">
945
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor"
946
+ strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
947
+ <path d="M8 2.6v10.8M5.2 10.6 8 13.4l2.8-2.8" />
948
+ </svg>
949
  </div>
950
  ) : null}
951
  </div>
 
1045
  <span className="autox-tag">Actions</span>
1046
  </div>
1047
  <div className="autox-main">
1048
+ {actions.map((a, i) => actionCard(a, 0, i < actions.length - 1))}
1049
 
1050
+ {/*
1051
+ β›” THE MACHINE STEPS ARE NOT CARDS ANY MORE (owner item 5, contract C-CFG). They
1052
+ were engine-derived read-only cards sitting under the owner's own actions β€” "fetch
1053
+ the page", "Bright Data", "Anonymous", "Write" β€” so the centre column mixed two
1054
+ different things: what the AUTOMATION is, which nobody chose and nobody can reorder,
1055
+ and what the OWNER added, which is the whole subject of this builder. Their
1056
+ configuration and their switches moved to Properties β†’ Configuration β†’
1057
+ "How this fetches", one section per panel.
1058
+
1059
+ ⚠ THE ENGINE STILL RUNS THEM. `graph()` emits the same nodes; this surface simply
1060
+ stops DRAWING them, which is why the switches had to move rather than go β€” R7 names
1061
+ Bright Data (money) and Write's dry run (reads and reports without writing a row) as
1062
+ controls that must survive the cards that carried them.
1063
+ */}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1064
 
1065
  <button
1066
  type="button"
 
1078
  wall rather than a decoration. */}
1079
  {adding ? (
1080
  <div className="autox-menu" role="menu">
1081
+ {menuGroups.map((group) => (
1082
  <div className="autox-menu-group" key={group}>
1083
  <p className="autox-menu-head">{group}</p>
1084
  {catalog
 
1128
  <aside className="auto-panel autox-props" aria-label="Properties">
1129
  <div className="auto-panel-head">
1130
  <h2>Properties</h2>
1131
+ {/*
1132
+ THREE STATES, because this panel now holds two save disciplines. The discrete choices
1133
+ (a trigger, an action, a switch, a branch) persist as they are made; the machine
1134
+ steps' fields, which moved in here with item 5, commit with the header's Save. A
1135
+ two-state stamp had to be wrong about one of them, and "All changes saved" printed
1136
+ over an unsaved column map is the direction that loses work.
1137
+ */}
1138
+ <span
1139
+ className={"autox-saved" + (busy ? " is-busy" : dirty ? " is-dirty" : "")}
1140
+ >
1141
+ {busy ? "Saving…" : dirty ? "Unsaved changes β€” press Save" : "All changes saved"}
1142
  </span>
1143
  </div>
1144
 
1145
+ {/*
1146
+ ⭐ THE NAME (item 15b). It is ABOVE the selection-dependent body rather than inside the
1147
+ trigger's face, because it is a property of the AUTOMATION and not of whichever step
1148
+ happens to be selected β€” clicking an action card must not make the name disappear.
1149
+ It commits on blur; the caller writes it and prints any refusal.
1150
+ */}
1151
+ <div className="auto-field">
1152
+ <label htmlFor="autox-name">Name</label>
1153
+ <input
1154
+ id="autox-name"
1155
+ className="auto-input"
1156
+ value={name}
1157
+ disabled={busy}
1158
+ placeholder="Name this automation"
1159
+ onChange={(e) => onNameText(e.target.value)}
1160
+ onBlur={() => onNameCommit()}
1161
+ />
1162
+ </div>
1163
+
1164
  {sel.kind === "trigger" ? (
1165
  <TriggerProps
1166
  automation={automation}
 
1174
  vocab={vocab}
1175
  oauth={oauth}
1176
  busy={busy}
1177
+ nodes={nodes}
1178
+ onToggleNode={onToggleNode}
1179
+ renderNodeBody={renderNodeBody}
1180
  onAskChange={setConfirmKey}
1181
  onPatchTrigger={patchTrigger}
1182
  onPickTrigger={onPickTrigger}
1183
  onRunNow={onRunNow}
1184
  scheduleFace={scheduleFace}
1185
+ schedules={schedules}
1186
  />
1187
+ ) : (
1188
  <ActionProps
1189
  action={findAction(actions, sel.id)}
1190
  catalog={catalog}
 
1196
  busy={busy}
1197
  onEdit={(change) => editAction(sel.id, change)}
1198
  />
 
 
1199
  )}
1200
  </aside>
1201
 
 
1285
  function findAction(list: Action[], id: string): Action | null {
1286
  for (const a of list) {
1287
  if (a.id === id) return a;
1288
+ // ⚠ THROUGH THE BRANCHES (C-FORK). This read `config.actions`, which a fork no longer has β€”
1289
+ // so selecting any action inside one would have found nothing and the Properties panel would
1290
+ // have said "that action is no longer part of this flow" about a card visibly on screen.
1291
+ if (a.kind === "group")
1292
+ for (const br of groupBranches(a)) {
1293
+ const hit = findAction(br.actions || [], id);
1294
+ if (hit) return hit;
1295
+ }
1296
  }
1297
  return null;
1298
  }
1299
 
1300
+ /*
1301
+ * β›” `nodePanel()` IS GONE (item 5). It rendered ONE machine node's panel, chosen by the card the
1302
+ * reader had clicked, and included a "that step is no longer part of this automation" branch for
1303
+ * a selection the graph had since dropped. Both facts died with the cards: the panels are now
1304
+ * rendered together under "How this fetches", keyed by PANEL rather than by node id, so there is
1305
+ * no selection left to go stale.
1306
+ */
 
 
 
 
 
 
 
 
1307
 
1308
  // ── the Properties panel's two faces ─────────────────────────────────────────────────────────
1309
 
 
1319
  vocab,
1320
  oauth,
1321
  busy,
1322
+ nodes,
1323
+ onToggleNode,
1324
+ renderNodeBody,
1325
  onAskChange,
1326
  onPatchTrigger,
1327
  onPickTrigger,
1328
  onRunNow,
1329
  scheduleFace,
1330
+ schedules,
1331
  }: {
1332
  automation: Automation;
1333
  triggerKey: string;
 
1340
  vocab?: FlowVocab;
1341
  oauth: OAuthStatus | null;
1342
  busy: boolean;
1343
+ /** The engine's machine steps (item 5) β€” their switches and bodies live under Configuration. */
1344
+ nodes: GraphNode[];
1345
+ onToggleNode: (nodeId: string) => void;
1346
+ renderNodeBody: (panel: string) => ReactNode;
1347
  /** Ask before a trigger change that can invalidate the config under it (image 6). */
1348
  onAskChange: (key: string) => void;
1349
  onPatchTrigger: (patch: Record<string, unknown>) => void;
1350
  onPickTrigger: (key: string) => void;
1351
  onRunNow: () => void;
1352
  scheduleFace: ReactNode;
1353
+ schedules: boolean;
1354
  }) {
1355
  const trigger = automation.trigger || null;
1356
  const provider = picked?.connect?.provider || "";
 
1381
  {triggerKey && !options.some((t) => t.key === triggerKey) ? (
1382
  <option value={triggerKey}>{triggerKey} (not offered here)</option>
1383
  ) : null}
1384
+ {/*
1385
+ ⭐ GROUPED BY THE SERVER'S OWN `group` (C-TYPES). `ig_profile_match` is a "Sources"
1386
+ trigger β€” it MAKES rows rather than watching them β€” and burying it among the record
1387
+ triggers is what made the wizard look like the only way to reach discovery.
1388
+ β›” THE GROUP ORDER IS FIRST-APPEARANCE IN THE SERVER'S ARRAY, never a literal list of
1389
+ group names here. `TriggerOption` carries no `groupOrder` (only `ActionCatalogRow`
1390
+ does), so the array's own order is the only ordering the server has expressed β€” and a
1391
+ client `["Standard", "Sources"]` would drop a third group off the end, silently, on
1392
+ the day the engine adds one.
1393
+ ⚠ `group` absent reads as "Standard" per the contract, which keeps a server older
1394
+ than this client rendering one ungrouped-looking list rather than a blank optgroup.
1395
+ */}
1396
+ {[...new Set(options.map((t) => t.group || "Standard"))].map((group) => (
1397
+ <optgroup key={group} label={group}>
1398
+ {options
1399
+ .filter((t) => (t.group || "Standard") === group)
1400
+ .map((t) => (
1401
+ <option key={t.key} value={t.key} disabled={!!t.planned}>
1402
+ {t.planned
1403
+ ? `${t.label} β€” coming soon`
1404
+ : t.ready === false
1405
+ ? `${t.label} β€” needs setting up`
1406
+ : t.label}
1407
+ </option>
1408
+ ))}
1409
+ </optgroup>
1410
  ))}
1411
  </select>
1412
  </div>
1413
  {/*
1414
+ ⭐ THE DESCRIPTION IS THE SERVER'S, AND IT RIDES NOW (wave 24, C-TYPES). This block used
1415
+ to be a comment explaining why there was NO paragraph here: Airtable prints two sentences
1416
+ under this select (image 3), ours would have been a client paraphrase of a server
1417
+ vocabulary, and the note said "when `detail` rides, it renders here and cannot disagree
1418
+ with the engine". `TriggerOption.detail` landed this wave, so the paragraph is the
1419
+ engine's own sentence, printed verbatim and never composed with anything.
1420
  */}
1421
+ {picked?.detail ? <p className="auto-hint">{picked.detail}</p> : null}
1422
  {picked && picked.ready === false && !picked.planned ? (
1423
  <div className="autob-needs">
1424
  <span className="autob-needs-text">
 
1462
 
1463
  {triggerKey === "event_field" ? (
1464
  <>
1465
+ {/*
1466
+ β›” "WATCHED COLUMN" IS GONE (owner item 7, C-TRIG law 4). "When a record matches
1467
+ conditions" is a FILTER, and a watched column was a second, different question
1468
+ answered in the same box β€” the trigger fired on a column changing AND on the
1469
+ conditions holding, which is two triggers wearing one name.
1470
+ ⚠ THE SERVER WENT FIRST, and that ordering was the point: `clean_trigger` stopped
1471
+ reading `field` (C posted law 4 done) BEFORE this control came out. Deleting the
1472
+ control while the validator still read the key would have left a stored watched
1473
+ column that nothing displays and nothing can clear β€” and deleting the key while the
1474
+ control still showed it would have made every Save silently drop what the user
1475
+ picked. The CONDITION is what completes this trigger now: with none, it rides
1476
+ `configured:false` and says so.
1477
+ */}
 
 
 
 
 
 
1478
  <p className="auto-field-label">
1479
  <span className="autox-req">*</span> Conditions
1480
  </p>
 
1522
  <label htmlFor="autox-tview">
1523
  <span className="autox-req">*</span> View
1524
  </label>
1525
+ {/*
1526
+ ⭐ FOUR STATES, AND THREE OF THEM ARE SENTENCES (owner item 8, C-TYPES).
1527
+ `views` now rides `GET /automations/tables`, so this control is live β€” but "drop the
1528
+ note" would have collapsed it to two states and rebuilt the exact defect the contract
1529
+ forbids. Absent and empty are DIFFERENT FACTS:
1530
+ Β· no database chosen -> choose one first
1531
+ Β· `views` ABSENT -> the server offered nothing (a server older than this
1532
+ client). Saying "no views" here would be a claim
1533
+ nobody measured.
1534
+ Β· `views` present and [] -> this database genuinely has none. That IS measured,
1535
+ and it is the one that tells the reader to go and
1536
+ make a view rather than to go and find an admin.
1537
+ Β· non-empty -> the picker.
1538
+ */}
1539
+ {!table ? (
1540
+ <p className="auto-note">Choose a database first.</p>
1541
+ ) : !table.views ? (
1542
+ <p className="auto-note">This server did not offer a view list for that database.</p>
1543
+ ) : !table.views.length ? (
1544
+ <p className="auto-note">
1545
+ That database has no saved views yet β€” make one on its grid and it appears here.
1546
+ </p>
1547
+ ) : (
1548
  <select
1549
  id="autox-tview"
1550
  className="auto-input"
 
1553
  onChange={(e) => onPatchTrigger({ viewId: e.target.value })}
1554
  >
1555
  <option value="">Select a view…</option>
1556
+ {/*
1557
+ ⚠ THE STORED VALUE IS ALWAYS AN OPTION, and this control did not have that guard.
1558
+ A <select> whose `value` matches no <option> renders the FIRST one β€” here
1559
+ "Select a view…", whose value is `""` β€” so an `enters_view` trigger pointed at a
1560
+ view that has since been deleted, or at one the server deliberately withholds
1561
+ (another user's personal view, a share that does not name this viewer), would have
1562
+ LOOKED unconfigured and the next patch would have written the blank over it. This
1563
+ repo has paid for that twice; the two "(not in this database)" options elsewhere
1564
+ in this file exist for the same reason.
1565
+ */}
1566
+ {trigger?.viewId && !table.views.some((v) => v.id === trigger.viewId) ? (
1567
+ <option value={trigger.viewId}>{trigger.viewId} (not offered here)</option>
1568
+ ) : null}
1569
  {table.views.map((v) => (
1570
  <option key={v.id} value={v.id}>
1571
  {v.label}
1572
  </option>
1573
  ))}
1574
  </select>
 
 
 
 
 
 
 
 
 
 
 
 
 
1575
  )}
1576
  </div>
1577
  ) : null}
 
1604
  </div>
1605
  ) : null}
1606
 
1607
+ {/* THE SCHEDULE, rendered by the one component that owns the cron round-trip.
1608
+ ⚠ NOT `triggerKey === "schedule"` ANY MORE (item 7, C-TRIG). `ig_profile_match` watches
1609
+ nothing β€” it MAKES rows, on the cron β€” so its Configuration carries these controls
1610
+ "always", and the caller says which keys those are. */}
1611
+ {schedules ? scheduleFace : null}
1612
  {triggerKey === "manual" ? (
1613
  <p className="auto-hint">
1614
  It runs when you press Run once now, and nothing else starts it.
1615
  </p>
1616
  ) : null}
1617
 
1618
+ {/*
1619
+ ⭐ HOW THIS FETCHES (owner item 5, contract C-CFG) β€” the machine steps' switches and
1620
+ config bodies, below the trigger's own fields, under ONE sub-heading.
1621
+
1622
+ β›” ONE SECTION PER PANEL, NOT PER NODE (`groupByPanel`, and its note is the reason). Four
1623
+ of `field_instagram`'s nodes share `panel: "capture"` and both of `discover_instagram`'s
1624
+ share `panel: "find"`, so a section per node would print one body four times and mount the
1625
+ discovery filter twice against a single `preds` array.
1626
+
1627
+ β›” AND THE SWITCHES ARE THE POINT, not a leftover. R7: Bright Data buys exact counts with
1628
+ MONEY and Write's switch is the difference between a run that writes rows and one that
1629
+ reads and reports. They were on the cards this wave deleted, so deleting the cards without
1630
+ moving them would have retired two shipped controls silently. Each still posts to the
1631
+ node-toggle door β€” the server decides what a switch means, this only says which node.
1632
+
1633
+ `plain` automations have no machine nodes at all, so the whole section is absent for them
1634
+ rather than an empty heading (R6 makes that the common case from now on).
1635
+ */}
1636
+ {nodes.length ? (
1637
+ <>
1638
+ <h3>How this fetches</h3>
1639
+ {groupByPanel(nodes).map((g) => (
1640
+ <div className="autox-machine" key={g.panel}>
1641
+ {g.nodes.map((n) => (
1642
+ <div className="autox-machine-row" key={n.id}>
1643
+ <span className="autox-card-mark">
1644
+ <ActionMark kind={n.kind} />
1645
+ </span>
1646
+ <span className="autox-machine-text">
1647
+ <span className="autox-machine-title">{n.title}</span>
1648
+ <span className="autox-machine-sub">{n.subtitle}</span>
1649
+ </span>
1650
+ <span
1651
+ className={`auto-dot is-${n.status}`}
1652
+ aria-label={`Last run: ${n.status}`}
1653
+ />
1654
+ {n.toggle ? (
1655
+ <button
1656
+ type="button"
1657
+ className={"auto-step-switch" + (n.enabled ? " is-on" : "")}
1658
+ disabled={busy}
1659
+ aria-pressed={n.enabled}
1660
+ aria-label={`${n.enabled ? "Turn off" : "Turn on"} ${n.title}`}
1661
+ title={`${n.enabled ? "Turn off" : "Turn on"} ${n.title}`}
1662
+ onClick={() => onToggleNode(n.id)}
1663
+ >
1664
+ <span className="auto-step-switch-knob" />
1665
+ </button>
1666
+ ) : null}
1667
+ </div>
1668
+ ))}
1669
+ {/* The engine's own sentence about the step, where it wrote one β€” never a client
1670
+ paraphrase of what a node does. */}
1671
+ {g.nodes[0]?.detail ? (
1672
+ <p className="auto-hint">{g.nodes[0].detail}</p>
1673
+ ) : null}
1674
+ {renderNodeBody(g.panel)}
1675
+ </div>
1676
+ ))}
1677
+ </>
1678
+ ) : null}
1679
+
1680
  <h3>Test step</h3>
1681
  {/*
1682
  β›” HONEST TO OUR SEMANTICS, not to Airtable's. Airtable's "Test step" replays one step
 
1752
 
1753
  {action.kind === "group" ? (
1754
  <>
1755
+ {/*
1756
+ ⭐ ONE CONDITION EDITOR PER BRANCH (C-FORK). The group's own `config.cond` is GONE β€”
1757
+ a fork has a condition per leg, not one for the whole thing β€” so an editor bound to
1758
+ `cfg.cond` would now write a key `clean_actions` drops on the floor: the tree would
1759
+ look saved, survive a reload from local state, and be absent the next time anyone
1760
+ opened the automation.
1761
+ THE HEADING IS THE SERVER'S LABEL. The last leg may carry no condition, and the
1762
+ server has already named it "Otherwise" β€” giving it one here turns it into a lettered
1763
+ branch, which is a real thing to want and needs no separate control.
1764
+ */}
1765
+ {groupBranches(action).map((br, i) => (
1766
+ <div key={br.id || i}>
1767
+ <p className="auto-field-label">
1768
+ {br.label}
1769
+ {br.cond ? " β€” run these actions if…" : " β€” everything that reaches here"}
1770
+ </p>
1771
+ <CondBuilder
1772
+ cond={br.cond}
1773
+ onChange={(next) =>
1774
+ onEdit((a) => ({
1775
+ ...a,
1776
+ config: {
1777
+ ...a.config,
1778
+ branches: groupBranches(a).map((x) =>
1779
+ x.id === br.id ? { ...x, cond: next } : x
1780
+ ),
1781
+ },
1782
+ }))
1783
+ }
1784
+ fields={walkFields}
1785
+ ops={ops}
1786
+ nullaryOps={nullaryOps}
1787
+ maxDepth={vocab?.maxCondDepth ?? 3}
1788
+ maxChildren={vocab?.maxCondChildren ?? 12}
1789
+ lead=""
1790
+ disabled={busy}
1791
+ />
1792
+ </div>
1793
+ ))}
1794
+ <p className="auto-hint">
1795
+ The first branch whose conditions match is the one that runs β€” the record does not go
1796
+ down two of them.
1797
+ </p>
1798
  </>
1799
  ) : null}
1800
 
web/src/automation/AutomationDetail.tsx CHANGED
@@ -64,6 +64,13 @@ import {
64
 
65
  interface Props {
66
  automation: Automation;
 
 
 
 
 
 
 
67
  kinds: { key: AutomationKind; label: string }[];
68
  /** The server's schedule vocabulary, forwarded to Step 1's Custom face. */
69
  cronPresets: { cron: string; label: string }[];
@@ -88,24 +95,60 @@ interface Props {
88
  * every selection change (`key={active.id}`), so this is read once, at mount, by design.
89
  */
90
  initialStage?: string;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  onSaved: (id?: string) => void | Promise<void>;
92
  onDeleted: () => void | Promise<void>;
93
  }
94
 
 
 
 
 
 
 
 
 
 
 
95
  /**
96
- * The run-state chip's WORDS. The chip printed the stored enum straight β€” a header
97
- * reading "ok" beside the automation's name, which is a value from a state machine
98
- * rather than a sentence anybody would write. Sentence case, and "Succeeded"/"Failed"
99
- * rather than "ok"/"error" so the chip agrees with the rail's own tooltip, which has
100
- * always said "Last run succeeded".
 
 
 
 
 
 
 
 
 
 
 
 
101
  */
102
- const STATE_LABELS: Record<string, string> = {
103
- idle: "Not run yet",
104
- running: "Running",
105
- ok: "Succeeded",
106
- partial: "Partial",
107
- error: "Failed",
108
- };
109
 
110
  interface ColumnPlan {
111
  column: string;
@@ -115,7 +158,6 @@ interface ColumnPlan {
115
 
116
  export default function AutomationDetail({
117
  automation,
118
- kinds,
119
  cronPresets,
120
  paidReady,
121
  discover,
@@ -124,6 +166,7 @@ export default function AutomationDetail({
124
  vocab,
125
  tick,
126
  initialStage,
 
127
  onSaved,
128
  onDeleted,
129
  }: Props) {
@@ -279,6 +322,30 @@ export default function AutomationDetail({
279
 
280
  const table = tables.find((t) => t.key === targetTable) || null;
281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  /**
283
  * WHICH CONFIG PANEL IS OPEN β€” and the join is on `panel`, never on id equality.
284
  *
@@ -388,7 +455,30 @@ export default function AutomationDetail({
388
  targetTable: String(cfg.targetTable || ""),
389
  };
390
  }
391
- return { targetTable, fieldKey, urlField, maxPosts };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
  };
393
 
394
  const persist = async (announce = true, sched?: { cron: string; enabled: boolean }) => {
@@ -577,14 +667,18 @@ export default function AutomationDetail({
577
  }
578
  };
579
 
580
- const state = automation.running ? "running" : automation.status?.state || "idle";
581
-
582
  /**
583
- * The trigger controls, built ONCE and rendered by whichever frame is mounted.
584
- * `AutomationTrigger` owns the vocabulary (C3), the cron round-trip and the tick
585
  * honesty note; this file owns only what a change should WRITE.
 
 
 
 
 
 
586
  */
587
- const triggerFaceWith = (hidePicker: boolean) => (
588
  <AutomationTrigger
589
  triggers={triggers}
590
  current={triggerKey}
@@ -600,12 +694,10 @@ export default function AutomationDetail({
600
  oauth={oauth}
601
  showCron={showCron}
602
  onShowCron={setShowCron}
603
- hidePicker={hidePicker}
 
604
  />
605
  );
606
- const triggerFace = triggerFaceWith(false);
607
- /** The same element with its picker suppressed β€” the Builder's Properties panel owns that. */
608
- const scheduleFace = triggerFaceWith(true);
609
 
610
  /**
611
  * The Builder's writer (C4). It PATCHES a PARTIAL definition β€” `{trigger}` or `{flow}` β€” and
@@ -633,6 +725,41 @@ export default function AutomationDetail({
633
  }
634
  };
635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
636
  /**
637
  * THE MACHINE STEPS' CONFIG BODIES, joined on `panel` (C1 amendment 1) and rendered by
638
  * BOTH views.
@@ -985,22 +1112,25 @@ export default function AutomationDetail({
985
  return (
986
  <div className="auto-detail">
987
  <header className="auto-head">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
988
  <div className="auto-head-title">
989
- <input
990
- className="auto-name"
991
- value={name}
992
- placeholder="Name this automation"
993
- aria-label="Automation name"
994
- onChange={(e) => edit(setName)(e.target.value)}
995
- />
996
- <span className={`auto-chip is-${state}`}>
997
- {STATE_LABELS[state] || state}
998
- </span>
999
- <span className="auto-kindtag">
1000
- {kinds.find((k) => k.key === kind)?.label || kind}
1001
- </span>
1002
- </div>
1003
- <div className="auto-head-actions">
1004
  {/* TWO VIEWS OF ONE AUTOMATION (C1): what it DOES, and where its records ARE. The
1005
  switch is a segmented control rather than a tab strip because the page below it
1006
  does not change identity β€” it is the same automation, read two ways. */}
@@ -1017,6 +1147,21 @@ export default function AutomationDetail({
1017
  </button>
1018
  ))}
1019
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1020
  <button
1021
  type="button"
1022
  className="auto-btn"
@@ -1066,6 +1211,25 @@ export default function AutomationDetail({
1066
  {view === "builder" ? (
1067
  <AutomationBuilder
1068
  automation={automation}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1069
  {...(triggers ? { triggers } : {})}
1070
  catalog={catalog || []}
1071
  {...(vocab ? { vocab } : {})}
@@ -1080,7 +1244,18 @@ export default function AutomationDetail({
1080
  // scheduled time" selected on an automation with the cron switched off.
1081
  onPickTrigger={(key) => void pickTrigger(key)}
1082
  onRunNow={() => void start()}
1083
- renderNodePanel={(node) => panelBody(node.panel)}
 
 
 
 
 
 
 
 
 
 
 
1084
  // ONE cron round-trip, rendered inside the Properties panel with its own picker
1085
  // suppressed β€” the builder supplies the "Trigger type" select above it.
1086
  scheduleFace={scheduleFace}
@@ -1088,10 +1263,18 @@ export default function AutomationDetail({
1088
  ) : (
1089
  <>
1090
  <div className="autob-flow">
1091
- <div className="autob-triggerbar">
1092
- <span className="autob-triggerbar-tag">Trigger</span>
1093
- {triggerFace}
1094
- </div>
 
 
 
 
 
 
 
 
1095
  {board ? (
1096
  <AutomationBoard
1097
  board={board}
 
64
 
65
  interface Props {
66
  automation: Automation;
67
+ /**
68
+ * ⚠ STILL REQUIRED, NO LONGER READ HERE (item 15b). `.auto-kindtag` was its only consumer and
69
+ * the header lost it, but the prop stays: `AutomationSurface` passes `kinds={data?.kinds || []}`
70
+ * and that file belongs to another session this wave, so deleting the field would turn an
71
+ * excess-property error on somebody else's call site into this session's problem. Retiring it
72
+ * is a two-file change, booked in the B mailbox rather than done unilaterally.
73
+ */
74
  kinds: { key: AutomationKind; label: string }[];
75
  /** The server's schedule vocabulary, forwarded to Step 1's Custom face. */
76
  cronPresets: { cron: string; label: string }[];
 
95
  * every selection change (`key={active.id}`), so this is read once, at mount, by design.
96
  */
97
  initialStage?: string;
98
+ /**
99
+ * ⭐ W24-W1 β€” WHAT THE RUN IS DOING RIGHT NOW, and it is the honest half of owner item 6
100
+ * ("Run once now is laggy / looks stuck").
101
+ *
102
+ * MEASURED by the session that owns the surface: the engine work item 6 blamed is ~0.9 ms of a
103
+ * ~23 ms request, so there is no performance defect to fix. What IS true is that a
104
+ * `discover_instagram` run legitimately blocks up to `BD_FILTER_WAIT` = 120 s at the vendor,
105
+ * and the engine has been publishing a live step text the whole time that NOTHING has ever
106
+ * rendered β€” so a two-minute vendor wait and a genuinely hung thread have been pixel-identical.
107
+ * They are not the same thing and the server already knows which one it is.
108
+ *
109
+ * REQUIRED, not optional: an optional prop degrades to "the feature does not exist", which is
110
+ * exactly what shipped for the last four releases and is indistinguishable from never having
111
+ * built it. `""` while nothing is running is a real value and the honest one β€” a step text left
112
+ * over from a finished run is a worse answer than no answer.
113
+ * β›” Filled from `liveStepOf(a)`, never from `automation.liveStep`: there is no such field on
114
+ * the wire (C-TYPES amendment A2) and reading one would compile, type-check and be `undefined`
115
+ * forever.
116
+ */
117
+ liveStep: string;
118
  onSaved: (id?: string) => void | Promise<void>;
119
  onDeleted: () => void | Promise<void>;
120
  }
121
 
122
+ /*
123
+ * β›” `STATE_LABELS` IS GONE WITH THE HEADER CHIP IT WORDED (item 15b, C-DETAIL). It mapped the
124
+ * stored run enum to a sentence for `.auto-chip`, and the chip left the title row so that
125
+ * Builder/Board could have that space. The FACT it carried is not lost and was never only here:
126
+ * the builder's own `chip()` says "Last run succeeded / failed / Paused / Not set up / Finish
127
+ * configuration" on the trigger step, the header's Run-now button says "Running…", and the rail
128
+ * carries a status dot per automation. A second wording of the same enum in this file would have
129
+ * been a third place for the three to disagree.
130
+ */
131
+
132
  /**
133
+ * ⚠ THE ONLY CLIENT-SIDE COPY OF A SERVER FACT IN THIS FILE, named so it can be deleted in one
134
+ * edit the day the wire carries it (asked of the engine session in the wave mailbox).
135
+ *
136
+ * WHICH TRIGGERS THE CRON DRIVES. `is_due` (`automation_engine.py:523`) reads `schedule.enabled`
137
+ * and the cron and NOTHING ELSE β€” it never looks at the trigger key β€” so any trigger the engine
138
+ * calls schedule-driven fires exactly this way. The engine's own set is `TRIGGER_SCHEDULE_KEYS`
139
+ * (`:5010`), and it is NOT the right thing to ship verbatim: it includes `manual`, which is in it
140
+ * only to decide which side the trigger node's switch flips, and a manual trigger showing a cron
141
+ * face would contradict its own sentence ("nothing else starts it").
142
+ *
143
+ * β›” SO THIS IS NOT A COPY OF THE TRIGGER VOCABULARY, which would be the forbidden thing β€” the
144
+ * LIST of what triggers exist still comes wholly from `triggers` on the payload, and an unknown
145
+ * key still renders. This names which of them wear the schedule controls, which is a per-key
146
+ * config decision this file already makes for `event_field`, `record_updated`, `enters_view`,
147
+ * `email` and `webhook`. It goes stale in exactly one way β€” a NEW cron-driven trigger would show
148
+ * no schedule face β€” which is visible on screen rather than silent, and is why it is one
149
+ * constant with one name instead of two inline comparisons.
150
  */
151
+ const CRON_DRIVEN_TRIGGERS = ["schedule", "ig_profile_match"];
 
 
 
 
 
 
152
 
153
  interface ColumnPlan {
154
  column: string;
 
158
 
159
  export default function AutomationDetail({
160
  automation,
 
161
  cronPresets,
162
  paidReady,
163
  discover,
 
166
  vocab,
167
  tick,
168
  initialStage,
169
+ liveStep,
170
  onSaved,
171
  onDeleted,
172
  }: Props) {
 
322
 
323
  const table = tables.find((t) => t.key === targetTable) || null;
324
 
325
+ /**
326
+ * ⭐ THE WALKING RECORD'S DATABASE β€” the root cause of "the condition on the group names no
327
+ * field" (owner item 12a), and it was never a condition bug.
328
+ *
329
+ * `AutomationBuilder` resolved the field list from `trigger.table` ALONE. Every trigger without
330
+ * a table β€” manual, schedule, and the new `ig_profile_match`, which watches nothing because it
331
+ * MAKES rows β€” therefore handed `CondBuilder` an empty list, so the field picker offered
332
+ * "Choose a field…" and nothing else, and any condition saved against it named no field. The
333
+ * picker looked broken; the automation simply had no table for it to read.
334
+ *
335
+ * β›” MIRRORS `automation_engine._flow_table` (`:4319`) RATHER THAN INVENTING A SECOND RULE, and
336
+ * the ORDER is the part worth copying: the automation's own `targetTable` WINS over the
337
+ * trigger's table, not the other way round. A flow whose actions walk one database while its
338
+ * trigger watches another is a real shape, and getting the precedence backwards would offer the
339
+ * columns of the database the actions do not touch β€” a wrong list that looks authoritative,
340
+ * which this file already says is worse than no list.
341
+ * ⚠ The trigger's OWN pickers keep using the trigger's own table; these are two different
342
+ * questions and answering both from one variable is what produced the bug.
343
+ */
344
+ const walkTable =
345
+ kind === "discover_instagram"
346
+ ? String(cfg.targetTable || "") || String(discover?.table || "")
347
+ : String(cfg.targetTable || "") || String(automation.trigger?.table || "");
348
+
349
  /**
350
  * WHICH CONFIG PANEL IS OPEN β€” and the join is on `panel`, never on id equality.
351
  *
 
455
  targetTable: String(cfg.targetTable || ""),
456
  };
457
  }
458
+ if (kind === "field_instagram") {
459
+ return { targetTable, fieldKey, urlField, maxPosts };
460
+ }
461
+ /*
462
+ β›” EVERY ARM IS EXPLICIT AND THE FALL-THROUGH IS THE MINIMUM (wave 24, R6).
463
+ This used to END at `field_instagram`'s shape, as a bare `return` β€” so it was not a default,
464
+ it was a SILENT DEFAULT KIND, and R6 made `plain` the kind of every new automation. Picking
465
+ a trigger (the first thing anyone does now) called this and sent
466
+ `{targetTable, fieldKey, urlField, maxPosts}` for an automation that has no Instagram column
467
+ and no posts. It happens to be harmless today β€” `clean_config`'s `plain` arm reads only
468
+ `targetTable` and `lanes`, and falls back to the stored `lanes` β€” so nothing is lost and
469
+ nothing 400s. It is fixed anyway, because "harmless" here is luck rather than design: the
470
+ keys are dropped by a validator that was written independently, and the day `plain` grows a
471
+ key this shape happens to contain, a Save from any panel would write a value nobody chose.
472
+
473
+ This is the same defect C found twice in the engine on the same day β€” `graph()`'s final
474
+ `else` is `scrape_db`'s branch and `compose_sentence`'s is `discover_instagram`'s β€” so a new
475
+ kind silently inherited another kind's whole description. A last bare `else` is not a
476
+ default; it is whichever arm happened to be written last.
477
+
478
+ `targetTable` is the one key EVERY kind shares (it is what `_flow_table` resolves), so the
479
+ remaining fall-through carries that and nothing else.
480
+ */
481
+ return { targetTable };
482
  };
483
 
484
  const persist = async (announce = true, sched?: { cron: string; enabled: boolean }) => {
 
667
  }
668
  };
669
 
 
 
670
  /**
671
+ * The SCHEDULE half of the trigger face, built once and rendered by the Builder's Properties
672
+ * panel. `AutomationTrigger` owns the vocabulary (C3), the cron round-trip and the tick
673
  * honesty note; this file owns only what a change should WRITE.
674
+ *
675
+ * β›” ONE FACE NOW, NOT TWO (item 10). There used to be a second copy with its picker SHOWN,
676
+ * rendered by the board's `.autob-triggerbar`. The board is for reading where records ARE β€”
677
+ * the trigger belongs to the Builder β€” so the bar is gone and with it the only caller that
678
+ * ever wanted the picker from this file. `hidePicker` survives because it is what makes ONE
679
+ * cron round-trip serve the Properties panel without a second trigger dropdown above it.
680
  */
681
+ const scheduleFace = (
682
  <AutomationTrigger
683
  triggers={triggers}
684
  current={triggerKey}
 
694
  oauth={oauth}
695
  showCron={showCron}
696
  onShowCron={setShowCron}
697
+ hidePicker
698
+ schedules={CRON_DRIVEN_TRIGGERS.includes(triggerKey)}
699
  />
700
  );
 
 
 
701
 
702
  /**
703
  * The Builder's writer (C4). It PATCHES a PARTIAL definition β€” `{trigger}` or `{flow}` β€” and
 
725
  }
726
  };
727
 
728
+ /**
729
+ * THE NAME, now that it lives at the top of Properties instead of in the page header
730
+ * (item 15b, C-DETAIL).
731
+ *
732
+ * β›” IT COMMITS ON BLUR AND WRITES IMMEDIATELY, like every other free-text field in that
733
+ * panel (the Gmail query, the review prompt, a value). That is not a style choice: the panel
734
+ * stamps "All changes saved", which is its receipt for the immediate-write discipline β€” a
735
+ * name sitting unsaved underneath it would make the stamp a lie. It is the cron field's exact
736
+ * shape (controlled while typing, one write on blur), because per-keystroke would PATCH a
737
+ * half-typed name.
738
+ *
739
+ * ⚠ A BLANK NAME IS NOT A NAME, and the header's Save has always refused one
740
+ * (`disabled={… || !name.trim()}`). Blurring an emptied box therefore RESTORES the stored
741
+ * name rather than writing an empty string or leaving the box contradicting the store β€” the
742
+ * two states a bare early-return would have left behind.
743
+ */
744
+ const commitName = async () => {
745
+ const next = name.trim();
746
+ const stored = automation.name || "";
747
+ if (!next) {
748
+ setName(stored);
749
+ return;
750
+ }
751
+ // Whitespace-only edits still normalise the box; they just have nothing to write.
752
+ if (next === stored) {
753
+ if (next !== name) setName(next);
754
+ return;
755
+ }
756
+ setName(next);
757
+ // ⚠ `{name}` ALONE IS A LEGAL PATCH β€” `engine.patch` merges by key over the stored
758
+ // definition (`automation_engine.py:1176` lists `name` among the patchable six), so this
759
+ // cannot blank the config, the schedule, the trigger or the flow.
760
+ await writeDefinition({ name: next });
761
+ };
762
+
763
  /**
764
  * THE MACHINE STEPS' CONFIG BODIES, joined on `panel` (C1 amendment 1) and rendered by
765
  * BOTH views.
 
1112
  return (
1113
  <div className="auto-detail">
1114
  <header className="auto-head">
1115
+ {/*
1116
+ ⭐ ITEM 15b β€” THE TITLE ROW IS THE VIEW SWITCH NOW. It held an editable name, a run-state
1117
+ chip and a kind tag; all three left and Builder/Board took the space, left-aligned, with
1118
+ Run now / Save / Delete still on the right.
1119
+
1120
+ WHERE EACH ONE WENT, because "removed" and "lost" are different claims:
1121
+ Β· the NAME is the first field of the Builder's Properties panel, writing on blur;
1122
+ Β· the STATE is the builder's own step chip, the Run-now button's "Running…", and the
1123
+ rail's per-automation dot β€” three surfaces that were already saying it;
1124
+ Β· the KIND stops being a user-facing fact at all this wave (R6: every new automation
1125
+ is `plain`), and the two legacy machine kinds describe themselves in Properties β†’
1126
+ Configuration β†’ "How this fetches".
1127
+
1128
+ ⚠ AND THE PAGE TITLE IS NOT DRAWN HERE EITHER WAY. The shell's `DbHead` (W23-W1) draws
1129
+ the SURFACE's name β€” the literal "Automation" off the nav payload β€” never this
1130
+ automation's. See the dated amendment under C-DETAIL: the contract's premise was wrong
1131
+ on that point and the consequence (no name in the Board view) is booked, not patched.
1132
+ */}
1133
  <div className="auto-head-title">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1134
  {/* TWO VIEWS OF ONE AUTOMATION (C1): what it DOES, and where its records ARE. The
1135
  switch is a segmented control rather than a tab strip because the page below it
1136
  does not change identity β€” it is the same automation, read two ways. */}
 
1147
  </button>
1148
  ))}
1149
  </div>
1150
+ </div>
1151
+ <div className="auto-head-actions">
1152
+ {/*
1153
+ ⭐ W24-W1 β€” WHAT IT IS DOING, beside the button that started it. This is the whole of
1154
+ item 6's honest fix: "Running…" for two minutes is indistinguishable from a hung
1155
+ thread, and the engine has been publishing the step text the entire time.
1156
+ ⚠ IT IS A STATEMENT, NOT A CONTROL, and it renders only while there is something to
1157
+ say β€” `liveStepOf` returns `""` unless the automation is running, so this never shows
1158
+ a step left over from a run that finished.
1159
+ */}
1160
+ {liveStep ? (
1161
+ <span className="auto-livestep" role="status">
1162
+ {liveStep}
1163
+ </span>
1164
+ ) : null}
1165
  <button
1166
  type="button"
1167
  className="auto-btn"
 
1211
  {view === "builder" ? (
1212
  <AutomationBuilder
1213
  automation={automation}
1214
+ // ITEM 15b β€” the name left the header, and this is where it went. Three REQUIRED
1215
+ // props rather than one: the cron field's shape (controlled while typing, one write
1216
+ // on blur) needs the text and the commit to be separable, and an OPTIONAL name would
1217
+ // degrade to "the field does not exist", which is indistinguishable from never
1218
+ // having built it.
1219
+ name={name}
1220
+ // ⚠ NOT `edit(setName)` β€” the name has its own immediate write (`commitName`), so
1221
+ // marking the whole FORM dirty for it would leave `touched` true forever after a
1222
+ // name edit and make the panel's stamp say "unsaved changes" about something it had
1223
+ // just saved. `touched` now means exactly "a field the header's Save owns has been
1224
+ // edited", which is what the stamp below reports.
1225
+ onNameText={setName}
1226
+ onNameCommit={() => void commitName()}
1227
+ // ⭐ THE PANEL'S STAMP MUST NOT LIE, and item 5 is what made this urgent. "All changes
1228
+ // saved" was honest while Properties held only immediate-write controls; the machine
1229
+ // steps' panels moved in this wave and THOSE commit with the header's Save (url,
1230
+ // extract, the column map, the discovery filters). A stamp promising they are saved,
1231
+ // above the fields that are not, is the same defect as an unsaved name under it.
1232
+ dirty={touched}
1233
  {...(triggers ? { triggers } : {})}
1234
  catalog={catalog || []}
1235
  {...(vocab ? { vocab } : {})}
 
1244
  // scheduled time" selected on an automation with the cron switched off.
1245
  onPickTrigger={(key) => void pickTrigger(key)}
1246
  onRunNow={() => void start()}
1247
+ // Item 7's third clause: the IG trigger's Configuration carries the Scheduled-run
1248
+ // controls too, so the builder needs to know when to render the face it was handed.
1249
+ schedules={CRON_DRIVEN_TRIGGERS.includes(triggerKey)}
1250
+ // Item 12a's root-cause fix β€” resolved HERE because it needs `discover.table`, which
1251
+ // is this component's prop and has no business being threaded into the builder just
1252
+ // to be read once.
1253
+ walkTable={walkTable}
1254
+ // ITEM 5 / C-CFG β€” handed over DIRECTLY now, not wrapped in `(node) => panelBody(
1255
+ // node.panel)`. The builder renders these grouped by panel key under "How this
1256
+ // fetches", so a wrapper taking a node would have to pick one node of a group and
1257
+ // imply the body belonged to it.
1258
+ renderNodeBody={panelBody}
1259
  // ONE cron round-trip, rendered inside the Properties panel with its own picker
1260
  // suppressed β€” the builder supplies the "Trigger type" select above it.
1261
  scheduleFace={scheduleFace}
 
1263
  ) : (
1264
  <>
1265
  <div className="autob-flow">
1266
+ {/*
1267
+ β›” THE TRIGGER BAR IS GONE (item 10). `.autob-triggerbar` sat above the lanes with
1268
+ a full copy of the trigger face β€” picker included β€” so the same fact had two
1269
+ controls on two views, which is the defect this file's header forbids. The board
1270
+ answers "where are the records"; what starts the run is the Builder's question,
1271
+ and its Properties panel is the one place that answers it now.
1272
+ ⚠ Their CSS is SWEPT too β€” `.autob-triggerbar`, `.autob-triggerbar .auto-field`
1273
+ and `.autob-triggerbar-tag` are deleted from the WAVE22 region by the session that
1274
+ owns it, with a tombstone in their place. (This note said they were "left in the
1275
+ stylesheet"; that was true for about an hour. A comment describing residue that
1276
+ has since been cleaned sends the next reader looking for it.)
1277
+ */}
1278
  {board ? (
1279
  <AutomationBoard
1280
  board={board}
web/src/automation/AutomationFind.tsx CHANGED
@@ -51,6 +51,151 @@ interface Props {
51
  onEstimate: () => void;
52
  }
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  /** One field's line in the list, with everything known about it. */
55
  interface FieldRow {
56
  name: string;
@@ -226,6 +371,9 @@ export default function AutomationFind({
226
  >
227
  <span className="auto-step-switch-knob" />
228
  </button>
 
 
 
229
  {/* The VENDOR'S OWN NAME, verbatim. Not prettified: every refusal the
230
  server sends names the field exactly like this ("'x' cannot be used
231
  to search β€” the searchable fields are: …"), and a label that reads
@@ -345,6 +493,14 @@ export default function AutomationFind({
345
  {strays.map(({ p, i }) => (
346
  <div className="autob-tgl is-on is-stray" key={`stray-${i}`}>
347
  <div className="autob-tgl-head">
 
 
 
 
 
 
 
 
348
  <span className="autob-tgl-name">{p.name}</span>
349
  <span className="autob-tgl-flag is-stray" title="The server will refuse this condition by name.">
350
  not searchable
 
51
  onEstimate: () => void;
52
  }
53
 
54
+ /**
55
+ * A FILTER FIELD'S ICON (owner item 5). Drawn, `currentColor`, never an emoji β€” and in the
56
+ * existing `TriggerMark`/`ActionMark` language rather than a new one: same 16 viewBox, same 15px
57
+ * box, same 1.4 stroke, so a row here and a card in the builder read as one product.
58
+ *
59
+ * ⚠ SHARED SHAPES WHERE THE FIELDS SHARE A MEANING, distinct everywhere else. `TriggerMark`'s
60
+ * note settled the principle β€” a column of identical glyphs is decoration, the eye learns nothing
61
+ * β€” but its converse matters just as much here: `bio_hashtags` and `post_hashtags` ARE both
62
+ * hashtags, and drawing two different marks for them would invent a distinction the vendor does
63
+ * not make. Twenty-one contrived glyphs would be twenty-one things to misread.
64
+ *
65
+ * β›” THE FALLBACK IS NOT A MEMBER OF THE SET, which is the `ActionMark` scar exactly: its default
66
+ * used to BE the pencil, a real member, so every unmatched kind silently borrowed "edit" and a
67
+ * fallback could not be told from a match. The vocabulary is the SERVER's β€” it can grow a field
68
+ * tomorrow β€” so an unmatched name draws a neutral mark that is deliberately meaningless.
69
+ */
70
+ function FilterMark({ name }: { name: string }) {
71
+ const common = {
72
+ width: 15, height: 15, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor",
73
+ strokeWidth: 1.4, strokeLinecap: "round" as const, strokeLinejoin: "round" as const,
74
+ "aria-hidden": true,
75
+ };
76
+ // Audience size β€” two figures, one behind the other.
77
+ if (name === "followers")
78
+ return (
79
+ <svg {...common}>
80
+ <circle cx="6.2" cy="5.6" r="2.4" />
81
+ <path d="M2.2 13c.5-2 2.1-3.2 4-3.2s3.5 1.2 4 3.2" />
82
+ <path d="M10.6 3.6a2.4 2.4 0 0 1 0 4M11.4 9.9c1.4.4 2.4 1.5 2.8 3.1" />
83
+ </svg>
84
+ );
85
+ // Who this account follows β€” a figure with an outbound arrow.
86
+ if (name === "following")
87
+ return (
88
+ <svg {...common}>
89
+ <circle cx="6" cy="5.6" r="2.4" />
90
+ <path d="M1.8 13c.5-2 2.1-3.2 4.2-3.2 .6 0 1.2.1 1.7.3" />
91
+ <path d="M9.8 10.6h4.2M12.2 8.8l1.8 1.8-1.8 1.8" />
92
+ </svg>
93
+ );
94
+ if (name === "posts_count")
95
+ return (
96
+ <svg {...common}>
97
+ <rect x="2.6" y="2.6" width="4.6" height="4.6" rx="1" />
98
+ <rect x="8.8" y="2.6" width="4.6" height="4.6" rx="1" />
99
+ <rect x="2.6" y="8.8" width="4.6" height="4.6" rx="1" />
100
+ <rect x="8.8" y="8.8" width="4.6" height="4.6" rx="1" />
101
+ </svg>
102
+ );
103
+ // A story highlight β€” the ring Instagram draws around one.
104
+ if (name === "highlights_count")
105
+ return (
106
+ <svg {...common}>
107
+ <circle cx="8" cy="8" r="5.6" strokeDasharray="2.6 1.8" />
108
+ <circle cx="8" cy="8" r="2.2" />
109
+ </svg>
110
+ );
111
+ if (name === "avg_engagement")
112
+ return (
113
+ <svg {...common}>
114
+ <path d="M8 13.2 3.4 8.8a2.9 2.9 0 0 1 4.6-3.4 2.9 2.9 0 0 1 4.6 3.4z" />
115
+ </svg>
116
+ );
117
+ if (name === "biography")
118
+ return (
119
+ <svg {...common}>
120
+ <rect x="2.4" y="2.8" width="11.2" height="10.4" rx="1.6" />
121
+ <path d="M4.8 6h6.4M4.8 8.4h6.4M4.8 10.8h3.6" />
122
+ </svg>
123
+ );
124
+ if (name === "category_name" || name === "business_category_name")
125
+ return (
126
+ <svg {...common}>
127
+ <path d="M8.4 2.6H13v4.6l-6.2 6.2-4.6-4.6z" />
128
+ <circle cx="10.8" cy="5.2" r="0.9" />
129
+ </svg>
130
+ );
131
+ if (name === "is_business_account" || name === "is_professional_account")
132
+ return (
133
+ <svg {...common}>
134
+ <rect x="2.2" y="5" width="11.6" height="8.2" rx="1.6" />
135
+ <path d="M6 5V3.6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1V5" />
136
+ </svg>
137
+ );
138
+ if (name === "is_verified")
139
+ return (
140
+ <svg {...common}>
141
+ <path d="M8 2.2l1.7 1.2 2-.2.6 2 1.7 1.1-.9 1.9.9 1.9-1.7 1.1-.6 2-2-.2L8 14.2l-1.7-1.2-2 .2-.6-2L2 10.1l.9-1.9L2 6.3l1.7-1.1.6-2 2 .2z" />
142
+ <path d="m5.8 8.1 1.5 1.5 3-3.1" />
143
+ </svg>
144
+ );
145
+ // The handle, and the display name it is written under.
146
+ if (name === "account" || name === "profile_name")
147
+ return (
148
+ <svg {...common}>
149
+ <circle cx="8" cy="8" r="2.4" />
150
+ <path d="M10.4 5.6v3.2a1.9 1.9 0 0 0 3.2 1.3A5.8 5.8 0 1 0 11 13.1" />
151
+ </svg>
152
+ );
153
+ if (name === "full_name")
154
+ return (
155
+ <svg {...common}>
156
+ <circle cx="8" cy="5.6" r="2.6" />
157
+ <path d="M3 13.4c.7-2.3 2.6-3.6 5-3.6s4.3 1.3 5 3.6" />
158
+ </svg>
159
+ );
160
+ if (name === "external_url" || name === "profile_url")
161
+ return (
162
+ <svg {...common}>
163
+ <path d="M6.6 9.4 4.9 11a2.6 2.6 0 1 1-1.5-4.4" />
164
+ <path d="M9.4 6.6 11.1 5a2.6 2.6 0 1 1 1.5 4.4" />
165
+ <path d="M6.2 8h3.6" />
166
+ </svg>
167
+ );
168
+ if (name === "bio_hashtags" || name === "post_hashtags")
169
+ return (
170
+ <svg {...common}>
171
+ <path d="M6.2 2.8 4.8 13.2M11.2 2.8 9.8 13.2M2.8 6h10.4M2.2 10h10.4" />
172
+ </svg>
173
+ );
174
+ if (name === "related_accounts")
175
+ return (
176
+ <svg {...common}>
177
+ <circle cx="8" cy="3.6" r="1.8" />
178
+ <circle cx="3.6" cy="12" r="1.8" />
179
+ <circle cx="12.4" cy="12" r="1.8" />
180
+ <path d="M6.8 5.2 4.6 10.4M9.2 5.2l2.2 5.2M5.4 12h5.2" />
181
+ </svg>
182
+ );
183
+ // The vendor's own record keys β€” the thing you hold to open exactly one row.
184
+ if (name === "id" || name === "fbid")
185
+ return (
186
+ <svg {...common}>
187
+ <circle cx="5.4" cy="10.6" r="2.6" />
188
+ <path d="M7.2 8.8 13 3M10.6 5.4l1.6 1.6M9.2 6.8l1.6 1.6" />
189
+ </svg>
190
+ );
191
+ return (
192
+ <svg {...common}>
193
+ <rect x="3.2" y="3.2" width="9.6" height="9.6" rx="2.2" />
194
+ <circle cx="8" cy="8" r="1.4" />
195
+ </svg>
196
+ );
197
+ }
198
+
199
  /** One field's line in the list, with everything known about it. */
200
  interface FieldRow {
201
  name: string;
 
371
  >
372
  <span className="auto-step-switch-knob" />
373
  </button>
374
+ <span className="autob-tgl-mark">
375
+ <FilterMark name={row.name} />
376
+ </span>
377
  {/* The VENDOR'S OWN NAME, verbatim. Not prettified: every refusal the
378
  server sends names the field exactly like this ("'x' cannot be used
379
  to search β€” the searchable fields are: …"), and a label that reads
 
493
  {strays.map(({ p, i }) => (
494
  <div className="autob-tgl is-on is-stray" key={`stray-${i}`}>
495
  <div className="autob-tgl-head">
496
+ {/* A stray gets a mark too β€” "every filter row" includes the ones the vendor no
497
+ longer offers, and a row missing the icon its neighbours have would read as a
498
+ different KIND of thing rather than as a field that fell out of the list. It
499
+ draws the neutral fallback by construction: a stray is, by definition, not in
500
+ the vocabulary this component has arms for. */}
501
+ <span className="autob-tgl-mark">
502
+ <FilterMark name={p.name} />
503
+ </span>
504
  <span className="autob-tgl-name">{p.name}</span>
505
  <span className="autob-tgl-flag is-stray" title="The server will refuse this condition by name.">
506
  not searchable
web/src/automation/AutomationSurface.tsx CHANGED
@@ -17,21 +17,36 @@ import type { KeyboardEvent as ReactKeyboardEvent } from "react";
17
  import { useCallback, useEffect, useRef, useState } from "react";
18
 
19
  import type { AutomationOpenDetail } from "../apiContract";
20
- import { AUTOMATION_OPEN_EVENT } from "../apiContract";
21
- import AutomationCreate from "./AutomationCreate";
22
  import AutomationDetail from "./AutomationDetail";
23
  import type { Automation, AutomationList } from "./automationApi";
24
  import {
25
  AutomationError,
 
26
  listAutomations,
 
27
  patchAutomation,
28
  stateOf,
29
  } from "./automationApi";
30
 
 
 
 
 
 
 
 
 
31
  /** The status dot's title β€” the rail says WHY it is that colour, not just that it is. */
32
  function stateTitle(a: Automation): string {
33
  const s = stateOf(a);
34
- if (s === "running") return "Running now";
 
 
 
 
 
 
35
  if (s === "ok") return `Last run succeeded β€” ${a.status?.lastSummary || ""}`;
36
  if (s === "partial") return `Last run was partial β€” ${a.status?.lastSummary || ""}`;
37
  if (s === "error") return `Last run failed β€” ${a.status?.lastSummary || ""}`;
@@ -52,6 +67,23 @@ function stateTitle(a: Automation): string {
52
  * its job. [[ui-invisible-to-assertions]] β€” judge the pixels even when everything is green.
53
  */
54
  function railSubtitle(a: Automation): string {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  if (a.schedule?.enabled) return a.nextRunAt ? `Next ${a.nextRunAt}` : "Scheduled";
56
  const last = a.status?.lastRunAt ? a.status.lastRunAt.replace("T", " ").slice(0, 16) : "";
57
  return last ? `Last run ${last}` : "Manual only";
@@ -90,17 +122,77 @@ if (typeof window !== "undefined") {
90
  });
91
  }
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  export default function AutomationSurface() {
94
  const [data, setData] = useState<AutomationList | null>(null);
95
  const [error, setError] = useState("");
96
  const [activeId, setActiveId] = useState<string>("");
97
- const [creating, setCreating] = useState(false);
98
  const [railShut, setRailShut] = useState(false);
99
  const [busy, setBusy] = useState("");
 
 
 
 
 
 
 
100
  /** W23-W5's advisory half: which stage's panel the click-through asked for, if any. */
101
  const [openStage, setOpenStage] = useState("");
102
  /** An open request waiting for the list to arrive (see the resolver below). */
103
  const [openRequest, setOpenRequest] = useState<AutomationOpenDetail | null>(null);
 
 
104
  const listRef = useRef<HTMLDivElement | null>(null);
105
 
106
  /**
@@ -167,6 +259,45 @@ export default function AutomationSurface() {
167
  return () => ac.abort();
168
  }, [load]);
169
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  // A run is a background thread on the server, so the surface has to ASK whether it
171
  // finished. Polling only while something is actually running keeps an idle surface
172
  // silent β€” a fixed interval would be a request every few seconds forever, for a page
@@ -177,16 +308,59 @@ export default function AutomationSurface() {
177
  // owned it was gone. One controller per effect run, aborted with the interval, means a poll
178
  // cannot outlive the condition that justified it. The generation guard inside `load` covers
179
  // the rest: a response that survives the abort still cannot repaint over a newer one.
180
- const anyRunning = (data?.automations || []).some((a) => a.running);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  useEffect(() => {
182
- if (!anyRunning) return undefined;
183
  const ac = new AbortController();
184
- const t = window.setInterval(() => void load(ac.signal), 2500);
 
 
 
 
 
 
 
185
  return () => {
186
- window.clearInterval(t);
187
  ac.abort();
188
  };
189
- }, [anyRunning, load]);
190
 
191
  // ── W23-W5, the surface's half: hear the request, then answer it when we CAN ──────────
192
  useEffect(() => {
@@ -202,6 +376,34 @@ export default function AutomationSurface() {
202
  };
203
  }, []);
204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  /**
206
  * ⚠ THE REQUEST OUTLIVES THE FETCH, and it has to. The reader clicks a notification from
207
  * another page, so this surface is mounting WITH AN EMPTY LIST β€” "select it if it is in the
@@ -216,7 +418,6 @@ export default function AutomationSurface() {
216
  if (!openRequest || !data) return;
217
  const found = (data.automations || []).some((a) => a.id === openRequest.autoId);
218
  if (found) {
219
- setCreating(false);
220
  select(openRequest.autoId, openRequest.stageId || "");
221
  }
222
  setOpenRequest(null);
@@ -284,10 +485,8 @@ export default function AutomationSurface() {
284
  <button
285
  type="button"
286
  className="auto-create-btn"
287
- onClick={() => {
288
- setCreating(true);
289
- select("");
290
- }}
291
  >
292
  <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
293
  <path
@@ -312,10 +511,7 @@ export default function AutomationSurface() {
312
  <button
313
  type="button"
314
  className="auto-row-main"
315
- onClick={() => {
316
- select(a.id);
317
- setCreating(false);
318
- }}
319
  >
320
  <span
321
  className={`auto-dot is-${s}`}
@@ -367,20 +563,18 @@ export default function AutomationSurface() {
367
  </div>
368
  ) : null}
369
 
370
- {creating ? (
371
- <AutomationCreate
372
- kinds={data?.kinds || []}
373
- onCreated={async (id) => {
374
- setCreating(false);
375
- // THE CREATE FLOW IS THE ONE CALLER ALLOWED TO NAME A DIFFERENT ID (C14 leg 2),
376
- // and it is a different PROP for exactly that reason β€” the guard below does not
377
- // have to make an exception it could get wrong.
378
- const next = await load();
379
- if (id && next) select(id);
380
- }}
381
- onCancel={() => setCreating(false)}
382
- />
383
- ) : active ? (
384
  <AutomationDetail
385
  key={active.id}
386
  automation={active}
@@ -406,6 +600,16 @@ export default function AutomationSurface() {
406
  // is the difference between "here is the thing" and "here is the thing you were
407
  // told about". Absent for every other way of arriving.
408
  initialStage={openStage}
 
 
 
 
 
 
 
 
 
 
409
  /*
410
  * β›” C14 LEG 2 β€” THE STALE-ID WRITE-BACK, and this is the ghost's second cause.
411
  *
@@ -465,10 +669,8 @@ export default function AutomationSurface() {
465
  <button
466
  type="button"
467
  className="auto-btn is-primary"
468
- onClick={() => {
469
- setCreating(true);
470
- select("");
471
- }}
472
  >
473
  New automation
474
  </button>
 
17
  import { useCallback, useEffect, useRef, useState } from "react";
18
 
19
  import type { AutomationOpenDetail } from "../apiContract";
20
+ import { AUTOMATION_CREATE_EVENT, AUTOMATION_OPEN_EVENT } from "../apiContract";
 
21
  import AutomationDetail from "./AutomationDetail";
22
  import type { Automation, AutomationList } from "./automationApi";
23
  import {
24
  AutomationError,
25
+ createAutomation,
26
  listAutomations,
27
+ liveStepOf,
28
  patchAutomation,
29
  stateOf,
30
  } from "./automationApi";
31
 
32
+ /**
33
+ * The run poll's cadence (item 6). Named constants because they are a MEASURED trade-off, not a
34
+ * taste: `POLL_MAX_MS` is the longest a finished run can still look live, and it is the only
35
+ * cost the backoff has.
36
+ */
37
+ const POLL_MIN_MS = 2500;
38
+ const POLL_MAX_MS = 8000;
39
+
40
  /** The status dot's title β€” the rail says WHY it is that colour, not just that it is. */
41
  function stateTitle(a: Automation): string {
42
  const s = stateOf(a);
43
+ // ⭐ WAVE 24 (item 6). "Running now" was the whole answer for a run that can legitimately
44
+ // block 120 s at the vendor, so the tooltip said no more than the colour did. The step is
45
+ // the server's own word for what it is doing.
46
+ if (s === "running") {
47
+ const step = liveStepOf(a);
48
+ return step ? `Running now β€” ${step}` : "Running now";
49
+ }
50
  if (s === "ok") return `Last run succeeded β€” ${a.status?.lastSummary || ""}`;
51
  if (s === "partial") return `Last run was partial β€” ${a.status?.lastSummary || ""}`;
52
  if (s === "error") return `Last run failed β€” ${a.status?.lastSummary || ""}`;
 
67
  * its job. [[ui-invisible-to-assertions]] β€” judge the pixels even when everything is green.
68
  */
69
  function railSubtitle(a: Automation): string {
70
+ /*
71
+ * ⭐ WAVE 24 (owner item 6, "Run once now is laggy / looks stuck") β€” WHILE IT IS RUNNING,
72
+ * THE ONE FACT WORTH THE LINE IS WHAT IT IS DOING.
73
+ *
74
+ * MEASURED, not guessed (`scratchpad/perf_automations.py`, mailbox D-5): the engine has been
75
+ * publishing a live step the whole time (`status.step`, `routes_automation.py:50-51`) and NO
76
+ * SURFACE HAS EVER RENDERED IT. So a `discover_instagram` run parked in its legitimate
77
+ * `BD_FILTER_WAIT = 120 s` vendor wait and a genuinely hung thread were pixel-identical: a
78
+ * pulsing blue dot and a subtitle still reciting the schedule. "Looks stuck" was not a
79
+ * performance problem β€” the poll costs 23 ms β€” it was the product declining to say.
80
+ *
81
+ * It takes the line rather than joining it, for the reason this function's note already
82
+ * gives: the rail is `--lp-rail-w` wide and two facts that both truncate are worth less than
83
+ * one that fits. The schedule is still one click away and the dot's `title` carries both.
84
+ */
85
+ const step = liveStepOf(a);
86
+ if (step) return step;
87
  if (a.schedule?.enabled) return a.nextRunAt ? `Next ${a.nextRunAt}` : "Scheduled";
88
  const last = a.status?.lastRunAt ? a.status.lastRunAt.replace("T", " ").slice(0, 16) : "";
89
  return last ? `Last run ${last}` : "Manual only";
 
122
  });
123
  }
124
 
125
+ /*
126
+ * ⭐⭐ WAVE 24 / C-CREATE (b) β€” `AUTOMATION_CREATE_EVENT` GETS ITS FIRST LISTENER, EVER.
127
+ *
128
+ * β›” THIS CLOSES A DEFECT THAT IS LIVE IN v12 TODAY, found while planning this wave and verified
129
+ * by grep rather than reasoned: the event is declared (`apiContract.ts:149`), imported and
130
+ * signalled (`Shell.tsx:1142`), and **nothing anywhere in `src/` consumed it.** So all THREE
131
+ * "Automated database" doors β€” the Database flyout's footer, Home's card, and the New-database
132
+ * dialog's third row β€” navigated to `#/automation` and then did nothing at all. An affordance
133
+ * that quietly does not exist, with every gate green: the wave-20 item-25 class exactly, which is
134
+ * the very failure the contract note above this file's OPEN listener was written about. It
135
+ * happened again anyway, one event over, because a declared event and a consumed one look
136
+ * identical from every direction except a grep for the listener.
137
+ *
138
+ * MODULE SCOPE WITH A LATCH, for the reason spelled out above and not as a style choice: a
139
+ * `useEffect` listener subscribes only after the hash write, the router update and a React
140
+ * render β€” so it misses EVERY click that arrives from another page, which is every real click.
141
+ *
142
+ * The event carries NO detail by contract ("open the create flow" is the whole message), so the
143
+ * latch is a boolean rather than a one-slot mailbox. Its meaning is now what all three doors
144
+ * always promised: **create a `plain` automation and select it.**
145
+ */
146
+ let pendingCreate = false;
147
+ const createSubscribers = new Set<() => void>();
148
+
149
+ if (typeof window !== "undefined") {
150
+ window.addEventListener(AUTOMATION_CREATE_EVENT, () => {
151
+ if (createSubscribers.size) {
152
+ for (const notify of createSubscribers) notify();
153
+ return;
154
+ }
155
+ pendingCreate = true;
156
+ });
157
+ }
158
+
159
+ /**
160
+ * A default name for a brand-new automation, and it has to be one the server ACCEPTS.
161
+ *
162
+ * MEASURED against the live route rather than assumed (`scratchpad/probe_names.py`): a create
163
+ * with no name is a 400 (`name the automation`), and duplicate names are ALLOWED. So the name
164
+ * cannot be omitted, and a fixed literal would stack "New automation" three deep in a rail that
165
+ * sorts by name with nothing to tell the rows apart. Numbering from the existing list is a
166
+ * client-side convenience over a server that does not care: if two tabs race, the loser gets a
167
+ * duplicate name, which is legal, visible and renameable β€” never an error the user has to read.
168
+ */
169
+ function nextAutomationName(existing: Automation[]): string {
170
+ const taken = new Set(existing.map((a) => (a.name || "").trim().toLowerCase()));
171
+ for (let n = existing.length + 1; ; n += 1) {
172
+ const candidate = `Automation ${n}`;
173
+ if (!taken.has(candidate.toLowerCase())) return candidate;
174
+ }
175
+ }
176
+
177
  export default function AutomationSurface() {
178
  const [data, setData] = useState<AutomationList | null>(null);
179
  const [error, setError] = useState("");
180
  const [activeId, setActiveId] = useState<string>("");
 
181
  const [railShut, setRailShut] = useState(false);
182
  const [busy, setBusy] = useState("");
183
+ /**
184
+ * ⭐ WAVE 24 / C-CREATE β€” a create is now a ROUND TRIP, not a local wizard, so the door has to
185
+ * say it is busy. Without this a second click while the POST is in flight makes a second
186
+ * automation, and the server allows duplicate names, so the user gets two rows that look
187
+ * identical and no error to explain either of them.
188
+ */
189
+ const [creatingNow, setCreatingNow] = useState(false);
190
  /** W23-W5's advisory half: which stage's panel the click-through asked for, if any. */
191
  const [openStage, setOpenStage] = useState("");
192
  /** An open request waiting for the list to arrive (see the resolver below). */
193
  const [openRequest, setOpenRequest] = useState<AutomationOpenDetail | null>(null);
194
+ /** A CREATE request from outside this surface (C-CREATE b), waiting for the list to arrive. */
195
+ const [createRequest, setCreateRequest] = useState(false);
196
  const listRef = useRef<HTMLDivElement | null>(null);
197
 
198
  /**
 
259
  return () => ac.abort();
260
  }, [load]);
261
 
262
+ /**
263
+ * ⭐⭐ WAVE 24 / C-CREATE (a) β€” CREATE AND OPEN. This REPLACED the three-step wizard.
264
+ *
265
+ * R6 is what makes it possible: `plain` is a real kind with no machine graph nodes, and it is
266
+ * what `POST /automations` stores when the body names none. So "new automation" stopped being
267
+ * a question ("which of three kinds?" β€” two of which can no longer be created at all) and
268
+ * became what it says: a new automation, open, on its trigger picker. Choosing a SOURCE is now
269
+ * picking the `ig_profile_match` trigger, which is where that choice belongs.
270
+ *
271
+ * β›” THE GUARD IS A REF, not the `creatingNow` state, and this file already carries the scar
272
+ * that explains why (C14 leg 2): a state read inside a click closure is the value from the
273
+ * last render, so two fast clicks both see `false` and both POST. Duplicate names are legal
274
+ * server-side, so the user would get two identical rows and no error. The ref is written
275
+ * synchronously, inside the click, before anything can await.
276
+ */
277
+ const creatingRef = useRef(false);
278
+ const createAndOpen = useCallback(async () => {
279
+ if (creatingRef.current) return;
280
+ creatingRef.current = true;
281
+ setCreatingNow(true);
282
+ try {
283
+ const res = await createAutomation({
284
+ name: nextAutomationName(data?.automations || []),
285
+ });
286
+ const id = res?.automation?.id || "";
287
+ // The create flow is the one caller allowed to name a different id (C14 leg 2) β€” the
288
+ // automation did not exist when the click happened, so there is nothing to race with.
289
+ const next = await load();
290
+ if (id && next) select(id);
291
+ } catch (e) {
292
+ setError(
293
+ e instanceof AutomationError ? e.message : "The automation was not created."
294
+ );
295
+ } finally {
296
+ creatingRef.current = false;
297
+ setCreatingNow(false);
298
+ }
299
+ }, [data, load, select]);
300
+
301
  // A run is a background thread on the server, so the surface has to ASK whether it
302
  // finished. Polling only while something is actually running keeps an idle surface
303
  // silent β€” a fixed interval would be a request every few seconds forever, for a page
 
308
  // owned it was gone. One controller per effect run, aborted with the interval, means a poll
309
  // cannot outlive the condition that justified it. The generation guard inside `load` covers
310
  // the rest: a response that survives the abort still cannot repaint over a newer one.
311
+ //
312
+ // ⭐ WAVE 24 (item 6, C-PERF) β€” THE INTERVAL BECAME A BACKOFF, and the measurement is why it is
313
+ // a SMALL change rather than the big one the contract's hypothesis 2 asked for.
314
+ //
315
+ // MEASURED (`scratchpad/perf_automations.py`, mailbox D-5): this poll costs ~23 ms and 24 KB
316
+ // for a ten-automation tenant, and the engine work the hypothesis blamed β€” a `graph()` rebuild
317
+ // per automation β€” is **41 Β΅s each**, i.e. under 4% of the request. The payload was never the
318
+ // problem, so nothing here gets a cheaper endpoint.
319
+ //
320
+ // What the numbers DO indict is the aggregate: a discovery run legitimately blocks up to
321
+ // `BD_FILTER_WAIT` = 120 s, and two independent 2.5 s polls across this file and the detail
322
+ // spend ~96 requests and ~2.3 MB over that window β€” in the same single process the run itself
323
+ // is a thread in. So the delay grows 2.5 β†’ 5 β†’ 8 s and stops there.
324
+ //
325
+ // ⚠ NOT "to learn nothing", and the distinction is the whole justification. That WAS true when
326
+ // this file rendered no live step: the poll's only observable effect was a dot that had already
327
+ // been pulsing for two minutes. It stopped being true in this same change β€” `liveStepOf` now
328
+ // paints `status.step`, so a poll carries the one fact worth having. The backoff is therefore
329
+ // NOT "stop asking a pointless question"; it is FEWER ROUND TRIPS FOR THE SAME INFORMATION, on
330
+ // a step text that changes every few seconds at most, not every 2.5.
331
+ // The cap is deliberately low: it bounds how long a FINISHED run can still look live, which is
332
+ // the only thing a backoff can make worse, and 8 s of that is worth ~β…” fewer requests.
333
+ //
334
+ // β›” THE KEY IS THE RUNNING SET, NOT A BOOLEAN, and that is what makes the reset correct: the
335
+ // effect re-runs β€” and the delay drops back to 2.5 s β€” the moment a run starts or finishes, so
336
+ // a user who clicks Run now gets the fast cadence again instead of inheriting the tail of the
337
+ // previous run's backoff. A bare `anyRunning` boolean cannot see the second run start.
338
+ // A step text changing does NOT re-key it, so the interval never thrashes.
339
+ //
340
+ // C14 LEG 3 (the abort half) is unchanged and still load-bearing: one controller per effect
341
+ // run, aborted with the timer, so a poll cannot outlive the condition that justified it. The
342
+ // generation guard inside `load` covers the rest.
343
+ const runningKey = (data?.automations || [])
344
+ .filter((a) => a.running)
345
+ .map((a) => a.id)
346
+ .sort()
347
+ .join(",");
348
  useEffect(() => {
349
+ if (!runningKey) return undefined;
350
  const ac = new AbortController();
351
+ let delay = POLL_MIN_MS;
352
+ let timer = 0;
353
+ const tick = () => {
354
+ void load(ac.signal);
355
+ delay = Math.min(delay * 2, POLL_MAX_MS);
356
+ timer = window.setTimeout(tick, delay);
357
+ };
358
+ timer = window.setTimeout(tick, delay);
359
  return () => {
360
+ window.clearTimeout(timer);
361
  ac.abort();
362
  };
363
+ }, [runningKey, load]);
364
 
365
  // ── W23-W5, the surface's half: hear the request, then answer it when we CAN ──────────
366
  useEffect(() => {
 
376
  };
377
  }, []);
378
 
379
+ // ── C-CREATE (b), the surface's half: hear the request, then answer it when we CAN ──────────
380
+ useEffect(() => {
381
+ const notify = () => setCreateRequest(true);
382
+ createSubscribers.add(notify);
383
+ if (pendingCreate) {
384
+ pendingCreate = false;
385
+ setCreateRequest(true);
386
+ }
387
+ return () => {
388
+ createSubscribers.delete(notify);
389
+ };
390
+ }, []);
391
+
392
+ /**
393
+ * ⚠ THE REQUEST WAITS FOR THE LIST, exactly as the open request does β€” and here it is not just
394
+ * symmetry: the default name is numbered off the current automations, so creating before the
395
+ * list has arrived would name every one of them "Automation 1".
396
+ *
397
+ * The flag is cleared BEFORE the await, not after it. `createAndOpen`'s identity changes on
398
+ * every poll (it closes over `data`), so this effect re-runs constantly; clearing first is what
399
+ * makes the second run a no-op instead of a second automation.
400
+ */
401
+ useEffect(() => {
402
+ if (!createRequest || !data) return;
403
+ setCreateRequest(false);
404
+ void createAndOpen();
405
+ }, [createRequest, data, createAndOpen]);
406
+
407
  /**
408
  * ⚠ THE REQUEST OUTLIVES THE FETCH, and it has to. The reader clicks a notification from
409
  * another page, so this surface is mounting WITH AN EMPTY LIST β€” "select it if it is in the
 
418
  if (!openRequest || !data) return;
419
  const found = (data.automations || []).some((a) => a.id === openRequest.autoId);
420
  if (found) {
 
421
  select(openRequest.autoId, openRequest.stageId || "");
422
  }
423
  setOpenRequest(null);
 
485
  <button
486
  type="button"
487
  className="auto-create-btn"
488
+ disabled={creatingNow}
489
+ onClick={() => void createAndOpen()}
 
 
490
  >
491
  <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
492
  <path
 
511
  <button
512
  type="button"
513
  className="auto-row-main"
514
+ onClick={() => select(a.id)}
 
 
 
515
  >
516
  <span
517
  className={`auto-dot is-${s}`}
 
563
  </div>
564
  ) : null}
565
 
566
+ {/*
567
+ β›” THE `creating` BRANCH IS GONE (wave 24, C-CREATE a / owner items 3 + 4).
568
+ `AutomationCreate` used to render here β€” a three-step wizard whose first step asked
569
+ "existing / new / automated database" and whose second asked which of three KINDS.
570
+ R6 retires that question at the root: two of the three kinds can no longer be created
571
+ at all, and the third is now reached by picking a trigger. A new automation is created
572
+ the moment it is asked for (`createAndOpen`) and opens on its own Builder, so there is
573
+ no intermediate face left to render and no `creating` state to hold.
574
+ The import went with it β€” it is what would break `npx tsc -b` for the WHOLE client the
575
+ moment session B deletes the file, which is why this deletion is sequenced first.
576
+ */}
577
+ {active ? (
 
 
578
  <AutomationDetail
579
  key={active.id}
580
  automation={active}
 
600
  // is the difference between "here is the thing" and "here is the thing you were
601
  // told about". Absent for every other way of arriving.
602
  initialStage={openStage}
603
+ /*
604
+ * ⭐ W24-W1 (item 6) β€” WHAT THIS RUN IS DOING, on the one surface that survives in
605
+ * BOTH views. REQUIRED on the far side deliberately: an optional prop that nobody
606
+ * passes degrades to "the feature does not exist", which is indistinguishable from
607
+ * "it was never built" β€” and this whole item exists because a live step text rode
608
+ * the wire for three waves with nothing rendering it.
609
+ * `liveStepOf` returns the step ONLY while the automation is running; a stale step
610
+ * from a finished run is a worse answer than none.
611
+ */
612
+ liveStep={liveStepOf(active)}
613
  /*
614
  * β›” C14 LEG 2 β€” THE STALE-ID WRITE-BACK, and this is the ghost's second cause.
615
  *
 
669
  <button
670
  type="button"
671
  className="auto-btn is-primary"
672
+ disabled={creatingNow}
673
+ onClick={() => void createAndOpen()}
 
 
674
  >
675
  New automation
676
  </button>
web/src/automation/AutomationTrigger.tsx CHANGED
@@ -61,6 +61,15 @@ interface Props {
61
  * wrong invisibly. Two pickers for one fact is the defect this file's header forbids.
62
  */
63
  hidePicker?: boolean;
 
 
 
 
 
 
 
 
 
64
  }
65
 
66
  /*
@@ -145,12 +154,30 @@ export default function AutomationTrigger({
145
  showCron,
146
  onShowCron,
147
  hidePicker,
 
148
  }: Props) {
149
  // β›” THE SERVER'S LIST OR NOTHING (D-43). An empty array is not a fallback trigger to
150
  // invent β€” it is the one honest thing to say, and it is said below.
151
  const options = triggers || [];
152
  const picked = options.find((t) => t.key === current) || null;
153
- const isSchedule = current === "schedule";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  const shape = readCron(cron);
155
  const note = tickNote(tick);
156
  const every = showCron ? "custom" : shape.every;
@@ -211,6 +238,24 @@ export default function AutomationTrigger({
211
  </div>
212
  )}
213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  {isSchedule ? (
215
  <>
216
  <div className="auto-field">
 
61
  * wrong invisibly. Two pickers for one fact is the defect this file's header forbids.
62
  */
63
  hidePicker?: boolean;
64
+ /**
65
+ * WAVE 24, owner item 7 β€” DOES THE CRON DRIVE THIS TRIGGER? REQUIRED, and it is a fact the
66
+ * CALLER establishes rather than one this component derives, because deriving it means naming
67
+ * keys and this file's header forbids a client union over the trigger vocabulary.
68
+ *
69
+ * `schedule` is no longer the only answer: `ig_profile_match` watches nothing β€” it MAKES rows,
70
+ * on the cron β€” so C-TRIG gives it the Scheduled-run controls "always".
71
+ */
72
+ schedules: boolean;
73
  }
74
 
75
  /*
 
154
  showCron,
155
  onShowCron,
156
  hidePicker,
157
+ schedules,
158
  }: Props) {
159
  // β›” THE SERVER'S LIST OR NOTHING (D-43). An empty array is not a fallback trigger to
160
  // invent β€” it is the one honest thing to say, and it is said below.
161
  const options = triggers || [];
162
  const picked = options.find((t) => t.key === current) || null;
163
+ /**
164
+ * ⚠ RENAMED FROM `current === "schedule"` (item 7). The cron face belongs to any trigger the
165
+ * cron DRIVES, which is now more than one key β€” and the caller is the only thing entitled to
166
+ * say which, so this reads the prop rather than the key it used to test.
167
+ */
168
+ const isSchedule = schedules;
169
+ /**
170
+ * ⭐ THE ARM SWITCH, and without it item 7's third clause ships a dead control.
171
+ *
172
+ * For the `schedule` trigger the PICKER is the on/off β€” choosing it writes
173
+ * `schedule.enabled: true` and choosing anything else writes false β€” so a switch there would be
174
+ * two controls for one fact, which this component's siblings forbid. For every OTHER cron-driven
175
+ * trigger the picker cannot be that: picking `ig_profile_match` deliberately stores
176
+ * `enabled: false`, because arming a cron the moment somebody chooses a trigger would put a
177
+ * BILLED vendor run on a timer nobody asked for (C's amendment A1: "the seed cannot spend …
178
+ * runs only when a person presses Run now or arms the schedule"). This is the arming.
179
+ */
180
+ const showArm = schedules && current !== "schedule";
181
  const shape = readCron(cron);
182
  const note = tickNote(tick);
183
  const every = showCron ? "custom" : shape.every;
 
238
  </div>
239
  )}
240
 
241
+ {showArm ? (
242
+ <div className="auto-field">
243
+ <label htmlFor="auto-trigger-arm">Run on this schedule</label>
244
+ <button
245
+ id="auto-trigger-arm"
246
+ type="button"
247
+ className={"auto-step-switch" + (enabled ? " is-on" : "")}
248
+ disabled={busy}
249
+ aria-pressed={enabled}
250
+ aria-label={enabled ? "Stop running this on a schedule" : "Run this on a schedule"}
251
+ title={enabled ? "Stop running this on a schedule" : "Run this on a schedule"}
252
+ onClick={() => onSchedule({ cron, enabled: !enabled })}
253
+ >
254
+ <span className="auto-step-switch-knob" />
255
+ </button>
256
+ </div>
257
+ ) : null}
258
+
259
  {isSchedule ? (
260
  <>
261
  <div className="auto-field">
web/src/automation/automationApi.ts CHANGED
@@ -16,7 +16,20 @@
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.
@@ -220,6 +233,24 @@ export interface TriggerOption {
220
  * instead of drawing a button that goes nowhere.
221
  */
222
  connect?: { provider: string; startUrl: string } | null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  }
224
 
225
  // ── WAVE 23 / contracts C4 + C5: CONDITION TREES, ACTIONS, ENDINGS ───────────────────────────
@@ -257,12 +288,40 @@ export function groupParts(c: Cond): { join: "all" | "any"; children: Cond[] } {
257
  * validates it and REFUSES rather than coercing, so a client-side shape would be a second
258
  * validator free to disagree with the one that decides.
259
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  export interface Action {
261
  id: string;
262
  kind: string;
263
  enabled: boolean;
264
- /** Run this action only when the walking record matches. `null` = always. */
265
- when?: Cond | null;
 
 
 
 
 
 
 
 
266
  config: Record<string, unknown>;
267
  }
268
 
@@ -289,6 +348,15 @@ export interface ActionCatalogRow {
289
  group: string;
290
  ready: boolean;
291
  detail: string;
 
 
 
 
 
 
 
 
 
292
  }
293
 
294
  /** The builder's own ceilings, server-declared so the client never hard-codes the same numbers. */
@@ -438,7 +506,13 @@ export interface UserTable {
438
  label: string;
439
  source: string;
440
  rowCount: number;
441
- fields: { key: string; label: string; type: string; automation?: unknown }[];
 
 
 
 
 
 
442
  /**
443
  * The table's saved views β€” what `enters_view` names (C3). ABSENT until the server sends it,
444
  * and absent is a third state, not an empty list: the trigger's view control says the list was
@@ -776,6 +850,30 @@ export function stateOf(a: Automation): RunState {
776
  return a.running ? "running" : (a.status?.state as RunState) || "idle";
777
  }
778
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
779
  /**
780
  * A run's counts as ordered label/value pairs. The ORDER is the sentence the
781
  * numbers make β€” new, updated, unchanged, then the ones that need explaining β€”
 
16
  // ---------------------------------------------------------------------------
17
  import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, signal } from "../apiContract";
18
 
19
+ /**
20
+ * ⭐ WAVE 24 / R6 β€” `plain` IS A REAL KIND, and it is the default for every new automation.
21
+ * No machine graph nodes: the flow's ACTIONS are the whole automation. It exists because
22
+ * `clean_definition` refuses a definition with no kind, so "an automation that is just a
23
+ * trigger and some steps" needed a name at the door rather than a special case behind it.
24
+ * `scrape_db` and `field_instagram` survive on the two automations that already use them and
25
+ * no new one can be created (R6); `discover_instagram` is now reached by PICKING the
26
+ * `ig_profile_match` trigger rather than by a wizard.
27
+ */
28
+ export type AutomationKind =
29
+ | "scrape_db"
30
+ | "field_instagram"
31
+ | "discover_instagram"
32
+ | "plain";
33
  export type RunState = "idle" | "running" | "ok" | "error" | "partial";
34
  /**
35
  * ⚠ `hiker` is NOT in this union any more (wave 20, D-21) β€” the vendor moved.
 
233
  * instead of drawing a button that goes nowhere.
234
  */
235
  connect?: { provider: string; startUrl: string } | null;
236
+ /**
237
+ * WAVE 24 / C-TYPES β€” THE SERVER'S OWN ONE-LINE DESCRIPTION, rendered under the picker.
238
+ *
239
+ * β›” A CLIENT PARAPHRASE OF A SERVER VOCABULARY IS FORBIDDEN, which is the whole reason this
240
+ * key exists rather than a `TRIGGER_BLURBS` table next to `TriggerMark`. The engine decides
241
+ * what a trigger DOES; a second sentence written here would be free to describe a behaviour
242
+ * the engine stopped having, and nothing would go red. Same rule as `cronPresets`, one field
243
+ * further in. Absent = the picker prints no description, never an invented one.
244
+ */
245
+ detail?: string;
246
+ /**
247
+ * WAVE 24 / C-TYPES β€” which SECTION of the picker this trigger sits in ("Standard" |
248
+ * "Sources"). Typed `string` and not a union for the reason the header gives about `key`: a
249
+ * client union over a server enumeration diverges silently. **Absent = "Standard"** β€” that
250
+ * default is stated here so the picker does not have to invent a third bucket for a server
251
+ * older than this client.
252
+ */
253
+ group?: string;
254
  }
255
 
256
  // ── WAVE 23 / contracts C4 + C5: CONDITION TREES, ACTIONS, ENDINGS ───────────────────────────
 
288
  * validates it and REFUSES rather than coercing, so a client-side shape would be a second
289
  * validator free to disagree with the one that decides.
290
  */
291
+ /**
292
+ * ⭐ WAVE 24 / C-FORK (owner ruling R8, item 12a) β€” ONE LEG OF AN IF FORK.
293
+ *
294
+ * A group action's `config` is `{ branches: Branch[] }`. The LAST branch may carry
295
+ * `cond: null` β€” that is the **Otherwise** leg, and there is at most one of them; every other
296
+ * branch names a condition. `label` is the branch's LETTER ("A", "B", …), because R8 rules a
297
+ * fork occupies ONE step number and its legs are lettered: a branch is an alternative, not a
298
+ * later step.
299
+ *
300
+ * ⚠ THE ENGINE MIGRATES THE OLD SHAPE, it does not refuse it: a stored `{cond, actions}`
301
+ * becomes `{branches:[{id:"b1", label:"A", cond, actions}]}` on the next clean. The live
302
+ * automations use the old shape, so a refusal here would break them.
303
+ */
304
+ export interface Branch {
305
+ id: string;
306
+ label: string;
307
+ cond: Cond | null;
308
+ actions: Action[];
309
+ }
310
+
311
  export interface Action {
312
  id: string;
313
  kind: string;
314
  enabled: boolean;
315
+ /**
316
+ * Run this action only when the walking record matches. `null` = always.
317
+ *
318
+ * ⚠ REQUIRED, and that is a MEASURED claim rather than a tidy one: `clean_actions` emits
319
+ * `"when"` on every action it returns (`automation_engine.py:3713`), null included, so an
320
+ * action on the wire always carries the key. Typing it optional would let a caller build one
321
+ * without it and let a reader treat "absent" as a third state the server cannot produce.
322
+ */
323
+ when: Cond | null;
324
+ /** Per-kind. For `kind === "group"` this is `{ branches: Branch[] }` (C-FORK). */
325
  config: Record<string, unknown>;
326
  }
327
 
 
348
  group: string;
349
  ready: boolean;
350
  detail: string;
351
+ /**
352
+ * ⭐ WAVE 24 / C-ACT β€” THE SERVER DECIDES THE MENU'S GROUP ORDER, and the client sorts by
353
+ * this number and **never by a literal list of group names**. A hard-coded
354
+ * `["Web action", "Database", …]` in the client is a second copy of the catalog's own
355
+ * structure: the day the server adds or renames a group, the client either drops it off the
356
+ * end or drops it entirely, silently. Absent sorts last β€” a server older than this client
357
+ * still renders every group it sends.
358
+ */
359
+ groupOrder?: number;
360
  }
361
 
362
  /** The builder's own ceilings, server-declared so the client never hard-codes the same numbers. */
 
506
  label: string;
507
  source: string;
508
  rowCount: number;
509
+ /**
510
+ * `automation` is the machine-owner TAG (W23/R9's grey columns) β€” the id of the automation
511
+ * that owns the column, or `null`. Narrowed from `unknown` in wave 24 against the route that
512
+ * composes it: `routes_automation.py:291` sends `f.get("automation") or None`, so `string`
513
+ * and `null` are the only two values that ride.
514
+ */
515
+ fields: { key: string; label: string; type: string; automation?: string | null }[];
516
  /**
517
  * The table's saved views β€” what `enters_view` names (C3). ABSENT until the server sends it,
518
  * and absent is a third state, not an empty list: the trigger's view control says the list was
 
850
  return a.running ? "running" : (a.status?.state as RunState) || "idle";
851
  }
852
 
853
+ /**
854
+ * ⭐ WAVE 24 / C-TYPES + C-PERF (item 6) β€” WHAT THIS RUN IS DOING RIGHT NOW, or `""`.
855
+ *
856
+ * This is the honest half of "Run once now looks stuck": the engine has been publishing a live
857
+ * step text the whole time and **nothing has ever rendered it**, so a 120-second Bright Data
858
+ * wait and a hung thread look identical from the outside. They are not the same thing, and the
859
+ * server already knows which one it is.
860
+ *
861
+ * β›” WHY A FUNCTION AND NOT A FIELD β€” C-TYPES AMENDMENT A2 (2026-08-06, session D).
862
+ * The contract block writes `liveStep?: string` on `interface Automation`. Measured against the
863
+ * route that composes the payload: `_wire()` (`routes_automation.py:52-81`) emits `status` with
864
+ * `step` inside it (`:50-51`) and emits **no top-level `liveStep` at all**. Declaring the field
865
+ * would put a key on the `Automation` interface that no server sends β€” so `automation.liveStep`
866
+ * would compile, type-check, and be `undefined` forever. That is this codebase's own
867
+ * silent-drop class pointing the other way: the whole file is built on "absent must stay
868
+ * absent", and inventing a present-looking field is the same defect with the sign flipped.
869
+ * `step` is ALREADY typed on `status` (see `Automation.status`), so nothing is lost β€” this
870
+ * function is the greppable name the contract wanted, reading the key that actually rides.
871
+ * The W24-W1 hand-off is unaffected: it is a PROP called `liveStep`, and this is what fills it.
872
+ */
873
+ export function liveStepOf(a: Automation): string {
874
+ return stateOf(a) === "running" ? String(a.status?.step || "") : "";
875
+ }
876
+
877
  /**
878
  * A run's counts as ordered label/value pairs. The ORDER is the sentence the
879
  * numbers make β€” new, updated, unchanged, then the ones that need explaining β€”
web/src/automation/steps.ts CHANGED
@@ -11,7 +11,67 @@
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;
@@ -44,6 +104,82 @@ export function numberSteps(nodes: GraphNode[]): Step[] {
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. */
 
11
  // steps are is the exact drift the split was built to prevent; the rationale is
12
  // written at AutomationCreate.tsx:1-13.
13
  // ---------------------------------------------------------------------------
14
+ import type { Action, Branch, Cond, GraphNode } from "./automationApi";
15
+
16
+ /**
17
+ * The branches of an If / then, TOLERATING the pre-wave-24 `{cond, actions}` shape on READ.
18
+ *
19
+ * ⚠ THIS MIRRORS `automation_engine.group_branches` AND THE DUPLICATION IS DELIBERATE, which is
20
+ * worth defending because this file's own header forbids a second idea of the server's data. It
21
+ * is a READ-SIDE TOLERANCE, not a second validator: it never decides what is legal, and every
22
+ * write still goes to `clean_actions`, which returns the one canonical shape. The alternative is
23
+ * strictly worse β€” a group stored in the old shape would render with no branches and no children,
24
+ * so a live automation's actions would simply VANISH from the screen while running perfectly.
25
+ * A migration the server performs on write and the client tolerates on read is the pair that has
26
+ * no window; trusting `branches` alone has one, for exactly as long as a definition sits unsaved.
27
+ */
28
+ export function groupBranches(a: Action): Branch[] {
29
+ const cfg = (a?.config || {}) as {
30
+ branches?: Branch[];
31
+ cond?: Cond | null;
32
+ actions?: Action[];
33
+ };
34
+ if (Array.isArray(cfg.branches)) return cfg.branches;
35
+ // The pre-wave-24 shape, read as the one branch the engine migrates it to.
36
+ if (Array.isArray(cfg.actions))
37
+ return [{ id: "b1", label: "A", cond: cfg.cond ?? null, actions: cfg.actions }];
38
+ return [];
39
+ }
40
+
41
+ /**
42
+ * R8's STEP NUMBERS for a whole flow, keyed by action id.
43
+ *
44
+ * THE RULING, and each clause is a line here:
45
+ * Β· the TRIGGER is unnumbered β€” it is not in this map at all, and the card carries the word
46
+ * "Trigger" instead. (This REVERSES wave 21's R9, "Step 1 is always the Trigger".)
47
+ * Β· the first action is 1, the second 2, …
48
+ * Β· an If / then occupies ONE number. Its branches are alternatives, not later steps, so they
49
+ * consume no numbers of their own.
50
+ * Β· a branch's children are numbered RELATIVE TO THEIR BRANCH β€” the fork at step 2 gives every
51
+ * one of its branches a `2.1`, a `2.2`, and so on. Two branches therefore both contain a
52
+ * `2.1`, which is correct rather than colliding: they are alternatives in lettered lanes and
53
+ * only one of them ever runs (the engine takes the first matching branch and breaks).
54
+ *
55
+ * β›” IT DOES NOT LETTER THE BRANCHES, and that is a change from the contract text. `clean_actions`
56
+ * assigns the letter server-side (`_branch_letter`, and "Otherwise" for the null-cond last leg),
57
+ * preserving any label the client sends β€” so the letter rides on `Branch.label` and a second
58
+ * lettering here would be exactly the client-copy-of-a-server-vocabulary this wave keeps deleting.
59
+ * The client sends an EMPTY label and renders what comes back, which also means letters re-flow
60
+ * correctly when a branch is deleted instead of going stale.
61
+ */
62
+ export function numberActions(actions: Action[]): Map<string, string> {
63
+ const out = new Map<string, string>();
64
+ const walk = (list: Action[], prefix: string) => {
65
+ (list || []).forEach((a, i) => {
66
+ const n = prefix ? `${prefix}.${i + 1}` : String(i + 1);
67
+ out.set(a.id, n);
68
+ if (a.kind === "group")
69
+ for (const br of groupBranches(a)) walk(br.actions || [], n);
70
+ });
71
+ };
72
+ walk(actions || [], "");
73
+ return out;
74
+ }
75
 
76
  export interface Step {
77
  node: GraphNode;
 
104
  });
105
  }
106
 
107
+ /**
108
+ * Move `dragId` into `dropId`'s position within one list (owner item 11).
109
+ *
110
+ * β›” IT RETURNS `null` RATHER THAN THE LIST UNCHANGED, and the distinction is what keeps a
111
+ * pointless PATCH off the wire: "these two are the same card", "one of them is not in this list"
112
+ * and "here is your new order" are three different answers, and collapsing the first two into
113
+ * "the order you already had" would have the caller write the flow back to the server on every
114
+ * aborted drag. The caller writes only when this says something happened.
115
+ *
116
+ * THE CARD LANDS EXACTLY WHERE THE TARGET WAS, in both directions β€” splice out, then splice in at
117
+ * the target's ORIGINAL index. Dragging down, the target shifts up; dragging up, it shifts down.
118
+ * (The tempting version β€” insert at the target's index *after* the removal β€” is off by one when
119
+ * dragging downwards and drops the card one slot short of where the pointer is, which reads as
120
+ * the drag not having worked.)
121
+ */
122
+ export function reorderList<T extends { id: string }>(
123
+ list: T[],
124
+ dragId: string,
125
+ dropId: string
126
+ ): T[] | null {
127
+ if (!dragId || !dropId || dragId === dropId) return null;
128
+ const src = list || [];
129
+ const from = src.findIndex((x) => x.id === dragId);
130
+ const to = src.findIndex((x) => x.id === dropId);
131
+ if (from < 0 || to < 0) return null;
132
+ const next = [...src];
133
+ const [moved] = next.splice(from, 1);
134
+ if (!moved) return null;
135
+ next.splice(to, 0, moved);
136
+ return next;
137
+ }
138
+
139
+ /** One Properties section under "How this fetches": a panel, and every node that opens it. */
140
+ export interface PanelGroup {
141
+ /** The panel key β€” what the caller passes to `renderNodeBody`. */
142
+ panel: string;
143
+ /** Every machine node whose `panel` is this one, in the server's own order. */
144
+ nodes: GraphNode[];
145
+ }
146
+
147
+ /**
148
+ * The machine steps, GROUPED BY PANEL (item 5, contract C-CFG).
149
+ *
150
+ * β›” GROUPED, NEVER MAPPED ONE-TO-ONE, and the difference is a defect rather than a nicety.
151
+ * `panel` is MANY-TO-ONE over nodes, which is easy to miss because the old surface hid it: you
152
+ * clicked ONE card and got ONE panel. `field_instagram` gives `capture`, `capture_paid`,
153
+ * `capture_anon` AND `capture_metrics` all `panel: "capture"` (`automation_engine.py:3334-3352`),
154
+ * and `discover_instagram` gives both of its nodes `panel: "find"` (`:3381`/`:3387`). So a body
155
+ * rendered per NODE would print the capture prose four times over, and β€” the one that actually
156
+ * loses work β€” mount the 21-toggle discovery filter TWICE against a single `preds` array, two
157
+ * editors writing one piece of state where whichever blurred last silently wins.
158
+ *
159
+ * The detail panel has always joined on `panel` and never on node id (`AutomationDetail`'s own
160
+ * note says so); this keeps that law now that the panels are no longer reached by clicking a card.
161
+ *
162
+ * ORDER IS THE SERVER'S β€” first appearance wins, so the sections read in flow order rather than
163
+ * in whatever order a Map or a sort would produce.
164
+ */
165
+ export function groupByPanel(nodes: GraphNode[]): PanelGroup[] {
166
+ const order: string[] = [];
167
+ const byPanel = new Map<string, GraphNode[]>();
168
+ for (const n of nodes || []) {
169
+ // `panel` falls back to the id exactly as `graph()`'s own `node()` does (`panel or nid`),
170
+ // so a node the engine ships without one still gets its own section instead of joining
171
+ // every other panel-less node under the empty string.
172
+ const key = n.panel || n.id;
173
+ const seen = byPanel.get(key);
174
+ if (seen) seen.push(n);
175
+ else {
176
+ byPanel.set(key, [n]);
177
+ order.push(key);
178
+ }
179
+ }
180
+ return order.map((panel) => ({ panel, nodes: byPanel.get(panel) || [] }));
181
+ }
182
+
183
  /** How the Step-1 card is currently set: what it repeats on, and at what time. */
184
  export interface TriggerShape {
185
  /** `day` = every day Β· `0`..`6` = that weekday (cron numbering, 0 = Sunday) Β· `custom` = a cron only. */
web/src/home/HomePage.tsx CHANGED
@@ -26,10 +26,10 @@ import { dbChipClass } from "../shell/nav";
26
  import type { NavEntry, Recent } from "../shell/nav";
27
  import {
28
  HOME_LAYOUT_KEY,
29
- groupRecents,
30
  parseLayout,
31
  } from "./homeModel";
32
- import type { HomeLayout } from "./homeModel";
33
 
34
  // ── the four quick-start marks ───────────────────────────────────────────────────────────────
35
  //
@@ -137,18 +137,35 @@ function QuickCard({
137
  export default function HomePage({
138
  entries,
139
  recents,
 
140
  onTemplates,
141
  onNewDatabase,
142
  onAutomated,
143
  onConnectors,
 
144
  }: {
145
  /** The SHAPED, server-filtered nav. The only thing a tile may be drawn from. */
146
  entries: NavEntry[];
147
  recents: Recent[];
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  onTemplates: () => void;
149
  onNewDatabase: () => void;
150
  onAutomated: () => void;
151
  onConnectors: () => void;
 
 
152
  }) {
153
  const [layout, setLayout] = useState<HomeLayout>(() => {
154
  try {
@@ -165,14 +182,14 @@ export default function HomePage({
165
  }
166
  }, [layout]);
167
 
168
- // ⚠ THE CLOCK IS READ ONCE, HERE, AND HANDED IN AS NUMBERS. `homeModel` is pure so a gate can
169
- // assert the boundaries (23:59 vs 00:01, exactly seven days) rather than whatever today is.
170
- // `todayStart` is the reader's LOCAL midnight β€” "Today" means the reader's today, which is the
171
- // one clock this feature is allowed to consult (see the model's header note).
 
 
172
  const now = Math.floor(Date.now() / 1000);
173
- const midnight = new Date();
174
- midnight.setHours(0, 0, 0, 0);
175
- const sections = groupRecents(recents, entries, now, Math.floor(midnight.getTime() / 1000));
176
 
177
  return (
178
  <div className="shell-home">
@@ -188,6 +205,16 @@ export default function HomePage({
188
  The TITLES do differ, and that is a register difference the reference makes too: a
189
  card is an invitation ("Start with templates"), a menu row is a choice ("From a
190
  template"). */}
 
 
 
 
 
 
 
 
 
 
191
  <QuickCard
192
  icon={<TemplateIcon />}
193
  title="Start with templates"
@@ -242,18 +269,19 @@ export default function HomePage({
242
  </div>
243
  </div>
244
 
245
- {sections.length === 0 ? (
246
  // β›” ONE LINE, AND IT NAMES THE DOOR THAT FILLS IT (DESIGN.md 4 / R13). This is also
247
  // where wave 18's tenant hero went: a workspace with no databases lands here, and the
248
  // cards above ARE the "create your first database" affordance the hero carried. Two
249
- // welcome messages on one screen is the bug Shell.tsx:1321-1326 already documents.
 
 
 
250
  <p className="home-empty">
251
- {entries.length === 0
252
- ? "This workspace has no databases yet β€” create one above, or connect a source."
253
- : "Nothing opened yet. The databases you open appear here."}
254
  </p>
255
  ) : (
256
- sections.map((section) => (
257
  <section key={section.id} className="home-section">
258
  <h2 className="home-section-title">{section.title}</h2>
259
  <div className={"home-tiles is-" + layout}>
@@ -286,7 +314,12 @@ export default function HomePage({
286
  </span>
287
  <span className="home-tile-text">
288
  <span className="home-tile-name">{tile.label}</span>
289
- <span className="home-tile-ago">{tile.ago}</span>
 
 
 
 
 
290
  </span>
291
  </a>
292
  ))}
@@ -294,6 +327,42 @@ export default function HomePage({
294
  </section>
295
  ))
296
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297
  </div>
298
  );
299
  }
 
26
  import type { NavEntry, Recent } from "../shell/nav";
27
  import {
28
  HOME_LAYOUT_KEY,
29
+ allDatabases,
30
  parseLayout,
31
  } from "./homeModel";
32
+ import type { AutomationTile, HomeLayout } from "./homeModel";
33
 
34
  // ── the four quick-start marks ───────────────────────────────────────────────────────────────
35
  //
 
137
  export default function HomePage({
138
  entries,
139
  recents,
140
+ automations,
141
  onTemplates,
142
  onNewDatabase,
143
  onAutomated,
144
  onConnectors,
145
+ onOpenAutomation,
146
  }: {
147
  /** The SHAPED, server-filtered nav. The only thing a tile may be drawn from. */
148
  entries: NavEntry[];
149
  recents: Recent[];
150
+ /**
151
+ * ⭐ WAVE 24 item 13 (R10, wiring W24-W3) β€” every automation this account may open.
152
+ *
153
+ * A REQUIRED prop, never optional: an optional one degrades to "the section does not exist",
154
+ * which is indistinguishable from "it was never built" and is precisely the wave-20 failure
155
+ * this repo shipped four times. `[]` is a legitimate value and renders no section; ABSENT is
156
+ * not a state the type allows.
157
+ *
158
+ * ⚠ An account without the automation grant gets a 403 from `/automations`, and the FRAME
159
+ * turns that into `[]` β€” the section then simply does not render, which is the correct answer
160
+ * rather than an error card about a surface they may not have.
161
+ */
162
+ automations: AutomationTile[];
163
  onTemplates: () => void;
164
  onNewDatabase: () => void;
165
  onAutomated: () => void;
166
  onConnectors: () => void;
167
+ /** Open one automation: the frame owns the hash, the surface owns which one is selected. */
168
+ onOpenAutomation: (id: string) => void;
169
  }) {
170
  const [layout, setLayout] = useState<HomeLayout>(() => {
171
  try {
 
182
  }
183
  }, [layout]);
184
 
185
+ // ⚠ THE CLOCK IS READ ONCE, HERE, AND HANDED IN AS A NUMBER. `homeModel` stays pure so a gate
186
+ // can assert the ordering rather than whatever today happens to be.
187
+ // ⭐ WAVE 24 item 13 (R10) β€” `groupRecents`' Today / Past 7 days / Older buckets are GONE, and
188
+ // with them the reason a database you had never opened was invisible here. `allDatabases` draws
189
+ // every entry the server granted and uses the recents stamps only to ORDER them. The local
190
+ // midnight this used to compute has no remaining reader, so it is not computed.
191
  const now = Math.floor(Date.now() / 1000);
192
+ const databases = allDatabases(entries, recents, now);
 
 
193
 
194
  return (
195
  <div className="shell-home">
 
205
  The TITLES do differ, and that is a register difference the reference makes too: a
206
  card is an invitation ("Start with templates"), a menu row is a choice ("From a
207
  template"). */}
208
+ {/* ⭐ WAVE 24 item 14 β€” this card now opens an UNDER-CONSTRUCTION note, not the picker.
209
+ ⚠ THE CARD ONLY, AND THE ASYMMETRY IS DELIBERATE (see the wave doc's C-HOME note):
210
+ ruling R9 KEEPS "From a template" working inside the Database flyout's create menu, and
211
+ item 14 names this card by its exact title. Both instructions are followed literally,
212
+ which does mean one template door is boarded while another works. Written down so the
213
+ next session does not "fix" it in either direction β€” if it reads wrong live, it goes
214
+ back to the owner, not to a session's judgement.
215
+ The detail line is unchanged: it still describes what the feature WILL do, and the note
216
+ behind the click is what says it is not ready. A card that described its own
217
+ unavailability would be the tour DESIGN.md 4 forbids. */}
218
  <QuickCard
219
  icon={<TemplateIcon />}
220
  title="Start with templates"
 
269
  </div>
270
  </div>
271
 
272
+ {databases.length === 0 ? (
273
  // β›” ONE LINE, AND IT NAMES THE DOOR THAT FILLS IT (DESIGN.md 4 / R13). This is also
274
  // where wave 18's tenant hero went: a workspace with no databases lands here, and the
275
  // cards above ARE the "create your first database" affordance the hero carried. Two
276
+ // welcome messages on one screen is the bug Shell.tsx's empty-nav note already documents.
277
+ // ⭐ WAVE 24: the second sentence is GONE with the recency buckets. "Nothing opened yet"
278
+ // described a state that can no longer exist β€” every granted database is drawn whether it
279
+ // has been opened or not, so an empty list now means exactly one thing.
280
  <p className="home-empty">
281
+ This workspace has no databases yet β€” create one above, or connect a source.
 
 
282
  </p>
283
  ) : (
284
+ [{ id: "databases", title: "Databases", tiles: databases }].map((section) => (
285
  <section key={section.id} className="home-section">
286
  <h2 className="home-section-title">{section.title}</h2>
287
  <div className={"home-tiles is-" + layout}>
 
314
  </span>
315
  <span className="home-tile-text">
316
  <span className="home-tile-name">{tile.label}</span>
317
+ {/* ⚠ CONDITIONAL, because `ago` is EMPTY for a database nobody has opened β€”
318
+ the state R10 makes visible for the first time. An unconditional span
319
+ would render an empty line and push every tile in the row taller than the
320
+ ones beside it; and `agoText` clamps a missing stamp to "Opened just now",
321
+ so printing it would be the surface stating a fact nobody measured. */}
322
+ {tile.ago ? <span className="home-tile-ago">{tile.ago}</span> : null}
323
  </span>
324
  </a>
325
  ))}
 
327
  </section>
328
  ))
329
  )}
330
+
331
+ {/* ⭐ WAVE 24 item 13 (R10) β€” THE AUTOMATIONS SECTION.
332
+ Same tiles, same rhythm, one extra fact: the run-state dot the rail already draws
333
+ (`.auto-dot is-*`, the ONE status vocabulary this product has β€” DESIGN.md 1's "variety
334
+ is a defect", so this borrows the class rather than inventing a second dot).
335
+ ⚠ A BUTTON, NOT A LINK. Opening an automation is a hash change PLUS a request to the
336
+ surface for which one is selected β€” `AutomationSurface` owns `activeId` and this page
337
+ cannot see it. An `<a href="#/automation">` would land the reader on the surface with
338
+ whatever was selected last, which is the wrong automation and looks like a bug.
339
+ ⚠ EMPTY RENDERS NOTHING. `[]` is a real answer β€” no automations, or no grant (the frame
340
+ turns a 403 into `[]`) β€” and a heading over nothing says "there should be something
341
+ here", which is a different and false statement. */}
342
+ {automations.length ? (
343
+ <section className="home-section">
344
+ <h2 className="home-section-title">Automations</h2>
345
+ <div className={"home-tiles is-" + layout}>
346
+ {automations.map((a) => (
347
+ <button
348
+ key={a.id}
349
+ type="button"
350
+ className="home-tile home-tile-auto"
351
+ onClick={() => onOpenAutomation(a.id)}
352
+ >
353
+ <span className="home-tile-chip shell-db-chip" aria-hidden="true">
354
+ <AutomatedIcon />
355
+ </span>
356
+ <span className="home-tile-text">
357
+ <span className="home-tile-name">{a.name}</span>
358
+ {a.sub ? <span className="home-tile-ago">{a.sub}</span> : null}
359
+ </span>
360
+ <span className={`auto-dot is-${a.state}`} aria-label={`Last run: ${a.state}`} />
361
+ </button>
362
+ ))}
363
+ </div>
364
+ </section>
365
+ ) : null}
366
  </div>
367
  );
368
  }
web/src/home/homeModel.ts CHANGED
@@ -1,208 +1,201 @@
1
- // ---------------------------------------------------------------------------
2
- // home/homeModel.ts β€” WAVE 23 item 9 (ruling R7, contract C10): the Home
3
- // landing's PURE half. React-free and fetch-free, so `verify_home.py` can run it
4
- // under node the way `verify_alerts.py` runs the inbox model.
5
- //
6
- // Everything here is a function of values that were passed in β€” including the
7
- // clock. `todayStart` and `now` are PARAMETERS, never `Date.now()` calls, for two
8
- // reasons that pull the same way:
9
- //
10
- // Β· a gate can then assert the boundary cases (23:59 vs 00:01, exactly seven
11
- // days) instead of asserting whatever today happens to be;
12
- // Β· [[date-window-vocabulary]]'s standing rule β€” `today` is a parameter β€” was
13
- // written for the server's window vocabulary and holds just as well here.
14
- //
15
- // ⚠ THE ONE CLOCK THIS FEATURE MAY READ IS THE READER'S OWN, and that is not a
16
- // contradiction of `alertsModel.stampText`'s "never touch a clock". Two different
17
- // statements: a notification re-states WHEN A SERVER EVENT HAPPENED (re-deriving
18
- // it in the browser is how a tenant a day ahead gets told an event happened
19
- // tomorrow), while "Opened 30 minutes ago" states HOW LONG AGO THE READER
20
- // THEMSELVES DID SOMETHING, and the Today bucket means the reader's today. The
21
- // component reads the clock once and hands the numbers in here.
22
- // ---------------------------------------------------------------------------
23
-
24
- import type { NavEntry, Recent } from "../shell/nav";
25
- import type { FolderIcon } from "../customer-grid/types";
26
-
27
- /** One rendered recents tile: the RESOLVED database, never the raw stamp. */
28
- export interface RecentTile {
29
- key: string;
30
- label: string;
31
- icon?: FolderIcon;
32
- /** Epoch seconds, as stored. Kept so a tile can be re-sorted without re-fetching. */
33
- at: number;
34
- /** "Opened 30 minutes ago" β€” already assembled, so the component holds no clock logic. */
35
- ago: string;
36
- /** The chip's two letters. */
37
- initials: string;
38
- /**
39
- * The entry's OWN href, carried through rather than rebuilt as `#/${key}`.
40
- *
41
- * β›” A TILE THAT REBUILDS ITS OWN LINK IS A SECOND ROUTER. `shapeNav` already decided what a
42
- * key resolves to β€” `#/key` for a native surface, the current application's deep link for a
43
- * hand-off β€” and a `#/${key}` assembled here would send a hand-off row to a hash this shell
44
- * cannot render. Today only native keys are ever stamped (the frame stamps `active.kind ===
45
- * "native"` alone), so this is defence rather than a fix; it costs one field and removes the
46
- * class.
47
- */
48
- href: string;
49
- /** A hand-off opens the current application in a new tab, and the tile says so. */
50
- external: boolean;
51
- }
52
-
53
- /** One section of the recents list. `title` is the heading; an EMPTY section is never emitted. */
54
- export interface RecentSection {
55
- id: "today" | "week" | "older";
56
- title: string;
57
- tiles: RecentTile[];
58
- }
59
-
60
- const SECOND = 1;
61
- const MINUTE = 60 * SECOND;
62
- const HOUR = 60 * MINUTE;
63
- export const DAY = 24 * HOUR;
64
-
65
- /** "Past 7 days" means the seven days BEFORE today β€” today has its own section above it. */
66
- export const WEEK_DAYS = 7;
67
-
68
- /**
69
- * The chip's two letters.
70
- *
71
- * ⚠ `\p{L}\p{N}` AND NOT `[A-Za-z0-9]`, and this shell has already paid for that once: the
72
- * account monogram at `Shell.tsx:299` carries the same note, because the Streamlit host's
73
- * `_account_css` uses Python's `str.isalnum()` and an ASCII-only class here would give a
74
- * non-Latin name an initial in one shell and a blank circle in the other. A database called
75
- * "ΠšΠ»ΠΈΠ΅Π½Ρ‚Ρ‹" gets "ΠšΠ›", not an empty tile.
76
- *
77
- * Two letters, not one: the reference tiles read "Un" / "Aa", and a single letter over a 26px
78
- * chip is a bullet point rather than a name.
79
- */
80
- export function initials(label: string): string {
81
- const chars = String(label ?? "").match(/[\p{L}\p{N}]/gu) ?? [];
82
- return chars.slice(0, 2).join("").toUpperCase();
83
- }
84
-
85
- /**
86
- * "Opened N ago", in the largest unit that is still true.
87
- *
88
- * Rounds DOWN throughout (`Math.floor`), so a tile never claims more time has passed than has:
89
- * at 119 minutes this says "1 hour ago", never "2 hours ago". A stamp in the FUTURE β€” a clock
90
- * skew between the browser and the host β€” clamps to "just now" rather than rendering a negative
91
- * count, which is the only honest thing a relative label can say about it.
92
- */
93
- export function agoText(at: number, now: number): string {
94
- const d = Math.max(0, Math.floor(now) - Math.floor(at));
95
- if (d < MINUTE) return "Opened just now";
96
- const unit = (n: number, one: string) => `Opened ${n} ${one}${n === 1 ? "" : "s"} ago`;
97
- if (d < HOUR) return unit(Math.floor(d / MINUTE), "minute");
98
- if (d < DAY) return unit(Math.floor(d / HOUR), "hour");
99
- return unit(Math.floor(d / DAY), "day");
100
- }
101
-
102
- /**
103
- * Which section a stamp belongs to.
104
- *
105
- * `todayStart` is the epoch second of the reader's LOCAL midnight β€” computed once by the
106
- * component, so the boundary is the reader's calendar day rather than UTC's. Anything at or
107
- * after it is Today; the seven days before that are the week; everything else is Older.
108
- */
109
- export function bucketOf(at: number, todayStart: number): RecentSection["id"] {
110
- if (at >= todayStart) return "today";
111
- if (at >= todayStart - WEEK_DAYS * DAY) return "week";
112
- return "older";
113
- }
114
-
115
- const TITLES: Record<RecentSection["id"], string> = {
116
- today: "Today",
117
- week: "Past 7 days",
118
- older: "Older",
119
- };
120
-
121
- /**
122
- * ⭐ THE C10 LAW, AS CODE: Home renders ONLY what `/nav` already granted.
123
- *
124
- * A recent is a KEY and a TIME. Everything a tile shows β€” its name, its chosen mark, whether it
125
- * exists at all β€” is resolved from `entries`, which is the shaped, server-filtered nav payload.
126
- * So a database that was revoked, deleted, or never belonged to this account cannot appear on
127
- * Home even though its stamp is still in the reader's own recents bucket: there is nothing here
128
- * to draw it FROM.
129
- *
130
- * That is what makes `#/home` chrome rather than a surface. The server prunes on read as well
131
- * (`routes_nav._read_recents`), so this is the second of two walls rather than the only one β€”
132
- * but it is the one that would still hold if the payload ever widened.
133
- *
134
- * β›” GROUP HEADS ARE EXCLUDED. A `kind: "group"` entry is a folder label with no destination;
135
- * a tile for one would be a card you cannot open. `defaultRoute` makes the same distinction.
136
- */
137
- export function groupRecents(
138
- recents: Recent[],
139
- entries: NavEntry[],
140
- now: number,
141
- todayStart: number
142
- ): RecentSection[] {
143
- const byKey = new Map(entries.filter((e) => e.kind !== "group").map((e) => [e.key, e]));
144
- const buckets: Record<RecentSection["id"], RecentTile[]> = { today: [], week: [], older: [] };
145
- for (const r of [...recents].sort((a, b) => b.at - a.at)) {
146
- const entry = byKey.get(r.key);
147
- // No entry, or an entry with nowhere to go: not a tile. `href` is absent only on a group
148
- // head, which the map above already excluded β€” this is the type-level restatement of that,
149
- // and it means a tile always has a destination rather than being a card that does nothing.
150
- if (!entry || !entry.href) continue;
151
- buckets[bucketOf(r.at, todayStart)].push({
152
- key: entry.key,
153
- label: entry.label,
154
- ...(entry.icon ? { icon: entry.icon } : {}),
155
- at: r.at,
156
- ago: agoText(r.at, now),
157
- initials: initials(entry.label),
158
- href: entry.href,
159
- external: entry.kind === "handoff",
160
- });
161
- }
162
- const out: RecentSection[] = [];
163
- for (const id of ["today", "week", "older"] as const) {
164
- // An empty section is not rendered. A heading with nothing under it says "there should be
165
- // something here", which is a different (and false) statement from "you have not opened
166
- // anything today".
167
- if (buckets[id].length) out.push({ id, title: TITLES[id], tiles: buckets[id] });
168
- }
169
- return out;
170
- }
171
-
172
- /**
173
- * The server's recents, plus the stamps THIS SESSION made since the nav was fetched.
174
- *
175
- * β›” WITHOUT THIS, HOME IS ALWAYS ONE NAVIGATION STALE β€” and it is the wave's headline feature
176
- * that would be stale. `recents` rides the `GET /nav` payload (one round trip per sign-in, per
177
- * `navEpoch` bump), while the stamp is a fire-and-forget POST that changes nothing the client
178
- * holds. So: open a database, go Home, and the database you just opened is not in Today. The
179
- * alternative β€” refetching the whole nav on every route change to pick up one integer β€” is a
180
- * request per navigation for a decoration.
181
- *
182
- * LOCAL WINS ON A KEY, always: it is strictly newer by construction (it happened after the
183
- * fetch). And it is deliberately NOT persisted anywhere β€” a reload re-asks the server, which is
184
- * the only end that actually knows.
185
- */
186
- export function mergeRecents(server: Recent[], local: Record<string, number>): Recent[] {
187
- const byKey = new Map<string, number>();
188
- for (const r of server) byKey.set(r.key, r.at);
189
- for (const [key, at] of Object.entries(local)) {
190
- const cur = byKey.get(key);
191
- if (cur === undefined || at > cur) byKey.set(key, at);
192
- }
193
- return [...byKey.entries()]
194
- .map(([key, at]) => ({ key, at }))
195
- .sort((a, b) => b.at - a.at);
196
- }
197
-
198
- // ── the list/grid toggle ────────────────────────────────────────────────────────────────────
199
-
200
- export type HomeLayout = "grid" | "list";
201
-
202
- /** Per-browser, like the nav's collapsed state β€” a display preference, not account state. */
203
- export const HOME_LAYOUT_KEY = "aios-home-layout";
204
-
205
- /** Anything unrecognised reads as `grid`, which is the reference layout and the denser one. */
206
- export function parseLayout(raw: unknown): HomeLayout {
207
- return raw === "list" ? "list" : "grid";
208
- }
 
1
+ // ---------------------------------------------------------------------------
2
+ // home/homeModel.ts β€” WAVE 23 item 9 (ruling R7, contract C10): the Home
3
+ // landing's PURE half. React-free and fetch-free, so `verify_home.py` can run it
4
+ // under node the way `verify_alerts.py` runs the inbox model.
5
+ //
6
+ // Everything here is a function of values that were passed in β€” including the
7
+ // clock. `todayStart` and `now` are PARAMETERS, never `Date.now()` calls, for two
8
+ // reasons that pull the same way:
9
+ //
10
+ // Β· a gate can then assert the boundary cases (23:59 vs 00:01, exactly seven
11
+ // days) instead of asserting whatever today happens to be;
12
+ // Β· [[date-window-vocabulary]]'s standing rule β€” `today` is a parameter β€” was
13
+ // written for the server's window vocabulary and holds just as well here.
14
+ //
15
+ // ⚠ THE ONE CLOCK THIS FEATURE MAY READ IS THE READER'S OWN, and that is not a
16
+ // contradiction of `alertsModel.stampText`'s "never touch a clock". Two different
17
+ // statements: a notification re-states WHEN A SERVER EVENT HAPPENED (re-deriving
18
+ // it in the browser is how a tenant a day ahead gets told an event happened
19
+ // tomorrow), while "Opened 30 minutes ago" states HOW LONG AGO THE READER
20
+ // THEMSELVES DID SOMETHING, and the Today bucket means the reader's today. The
21
+ // component reads the clock once and hands the numbers in here.
22
+ // ---------------------------------------------------------------------------
23
+
24
+ import type { NavEntry, Recent } from "../shell/nav";
25
+ import type { FolderIcon } from "../customer-grid/types";
26
+
27
+ /** One rendered recents tile: the RESOLVED database, never the raw stamp. */
28
+ export interface RecentTile {
29
+ key: string;
30
+ label: string;
31
+ icon?: FolderIcon;
32
+ /** Epoch seconds, as stored. Kept so a tile can be re-sorted without re-fetching. */
33
+ at: number;
34
+ /** "Opened 30 minutes ago" β€” already assembled, so the component holds no clock logic. */
35
+ ago: string;
36
+ /** The chip's two letters. */
37
+ initials: string;
38
+ /**
39
+ * The entry's OWN href, carried through rather than rebuilt as `#/${key}`.
40
+ *
41
+ * β›” A TILE THAT REBUILDS ITS OWN LINK IS A SECOND ROUTER. `shapeNav` already decided what a
42
+ * key resolves to β€” `#/key` for a native surface, the current application's deep link for a
43
+ * hand-off β€” and a `#/${key}` assembled here would send a hand-off row to a hash this shell
44
+ * cannot render. Today only native keys are ever stamped (the frame stamps `active.kind ===
45
+ * "native"` alone), so this is defence rather than a fix; it costs one field and removes the
46
+ * class.
47
+ */
48
+ href: string;
49
+ /** A hand-off opens the current application in a new tab, and the tile says so. */
50
+ external: boolean;
51
+ }
52
+
53
+ /* β›” `RecentSection` (today | week | older) IS DELETED WITH ITS BUCKETS β€” wave 24 item 13 / R10.
54
+ Home has ONE database section now, so a section id and a title lookup were two pieces of
55
+ machinery describing a shape that no longer varies. */
56
+
57
+ const SECOND = 1;
58
+ const MINUTE = 60 * SECOND;
59
+ const HOUR = 60 * MINUTE;
60
+ export const DAY = 24 * HOUR;
61
+
62
+ /* β›” `WEEK_DAYS` deleted with the buckets (item 13 / R10). */
63
+
64
+ /**
65
+ * The chip's two letters.
66
+ *
67
+ * ⚠ `\p{L}\p{N}` AND NOT `[A-Za-z0-9]`, and this shell has already paid for that once: the
68
+ * account monogram at `Shell.tsx:299` carries the same note, because the Streamlit host's
69
+ * `_account_css` uses Python's `str.isalnum()` and an ASCII-only class here would give a
70
+ * non-Latin name an initial in one shell and a blank circle in the other. A database called
71
+ * "ΠšΠ»ΠΈΠ΅Π½Ρ‚Ρ‹" gets "ΠšΠ›", not an empty tile.
72
+ *
73
+ * Two letters, not one: the reference tiles read "Un" / "Aa", and a single letter over a 26px
74
+ * chip is a bullet point rather than a name.
75
+ */
76
+ export function initials(label: string): string {
77
+ const chars = String(label ?? "").match(/[\p{L}\p{N}]/gu) ?? [];
78
+ return chars.slice(0, 2).join("").toUpperCase();
79
+ }
80
+
81
+ /**
82
+ * "Opened N ago", in the largest unit that is still true.
83
+ *
84
+ * Rounds DOWN throughout (`Math.floor`), so a tile never claims more time has passed than has:
85
+ * at 119 minutes this says "1 hour ago", never "2 hours ago". A stamp in the FUTURE β€” a clock
86
+ * skew between the browser and the host β€” clamps to "just now" rather than rendering a negative
87
+ * count, which is the only honest thing a relative label can say about it.
88
+ */
89
+ export function agoText(at: number, now: number): string {
90
+ const d = Math.max(0, Math.floor(now) - Math.floor(at));
91
+ if (d < MINUTE) return "Opened just now";
92
+ const unit = (n: number, one: string) => `Opened ${n} ${one}${n === 1 ? "" : "s"} ago`;
93
+ if (d < HOUR) return unit(Math.floor(d / MINUTE), "minute");
94
+ if (d < DAY) return unit(Math.floor(d / HOUR), "hour");
95
+ return unit(Math.floor(d / DAY), "day");
96
+ }
97
+
98
+ /* β›” `bucketOf`, `TITLES` and `groupRecents` STOOD HERE AND ARE DELETED (wave 24 item 13, R10).
99
+ They bucketed the recents into Today / Past 7 days / Older -- and bucketing RECENTS is exactly
100
+ what made a database you had never opened invisible on Home, which is the complaint item 13
101
+ answers. `allDatabases` below replaces them: it starts from `entries` (so the C10 law is
102
+ STRUCTURAL now rather than a dropped-key `if`) and uses the stamps only to order.
103
+ ⚠ SWEPT IN THE SAME CHANGE that removed the last call site, and its TESTS retargeted with it.
104
+ `verify_home` stayed 107/107 green over this whole edit because its node section still ran
105
+ `groupRecents` directly -- a gate passing on a function the product no longer calls. That is
106
+ the GATE-DELTA tell, caught here rather than at close-out. */
107
+
108
+ // ── WAVE 24 item 13 (ruling R10): EVERY database, and EVERY automation ──────────────────────
109
+ //
110
+ // β›” WHY THE DATE BUCKETS WENT. The deleted `groupRecents` only ever emitted a tile for a key
111
+ // already in the reader's RECENTS bucket, so a database you had never opened did not appear on
112
+ // Home at all β€” which is exactly the complaint. Sorting is the part worth keeping:
113
+ // most-recently-opened first is a real ranking and costs nothing.
114
+ //
115
+ // ⚠ THE CLOCK IS STILL A PARAMETER and the C10 law still holds: every tile is resolved from
116
+ // `entries`, the shaped server-filtered nav, so Home cannot name a database `/nav` did not send.
117
+ // What changed is which of those entries get drawn β€” all of them now, not just the stamped ones.
118
+
119
+ /** One automation, as Home draws it. The shape `AutomationSurface`'s rail already computes. */
120
+ export interface AutomationTile {
121
+ id: string;
122
+ name: string;
123
+ /** `ok` | `error` | `partial` | `running` | `idle` β€” the dot's vocabulary, server-derived. */
124
+ state: string;
125
+ /** The rail's own second line: "Next …" when scheduled, else "Last run …", else "Manual only". */
126
+ sub: string;
127
+ }
128
+
129
+ /**
130
+ * Every database this account may open, most-recently-opened first, then alphabetical.
131
+ *
132
+ * β›” NOT `recents` DRIVEN β€” `recents` only ORDERS it. A key with no stamp sorts after every
133
+ * stamped one and keeps its place alphabetically, which is what makes a never-opened database
134
+ * visible for the first time (R10's whole point).
135
+ *
136
+ * ⚠ `ago` IS EMPTY FOR AN UNSTAMPED TILE, deliberately: "Opened just now" is what `agoText`
137
+ * returns for a missing stamp (it clamps), and printing that under a database nobody has ever
138
+ * opened would be the surface inventing a fact. An empty string renders no line at all.
139
+ */
140
+ export function allDatabases(
141
+ entries: NavEntry[],
142
+ recents: Recent[],
143
+ now: number
144
+ ): RecentTile[] {
145
+ const at = new Map(recents.map((r) => [r.key, r.at]));
146
+ return entries
147
+ .filter((e) => e.kind !== "group" && !!e.href)
148
+ .map((e) => {
149
+ const stamp = at.get(e.key);
150
+ return {
151
+ key: e.key,
152
+ label: e.label,
153
+ ...(e.icon ? { icon: e.icon } : {}),
154
+ at: stamp ?? 0,
155
+ ago: stamp === undefined ? "" : agoText(stamp, now),
156
+ initials: initials(e.label),
157
+ href: e.href as string,
158
+ external: e.kind === "handoff",
159
+ };
160
+ })
161
+ .sort((a, b) => (b.at - a.at) || a.label.localeCompare(b.label));
162
+ }
163
+
164
+
165
+ /**
166
+ * The server's recents, plus the stamps THIS SESSION made since the nav was fetched.
167
+ *
168
+ * β›” WITHOUT THIS, HOME IS ALWAYS ONE NAVIGATION STALE β€” and it is the wave's headline feature
169
+ * that would be stale. `recents` rides the `GET /nav` payload (one round trip per sign-in, per
170
+ * `navEpoch` bump), while the stamp is a fire-and-forget POST that changes nothing the client
171
+ * holds. So: open a database, go Home, and the database you just opened is not in Today. The
172
+ * alternative β€” refetching the whole nav on every route change to pick up one integer β€” is a
173
+ * request per navigation for a decoration.
174
+ *
175
+ * LOCAL WINS ON A KEY, always: it is strictly newer by construction (it happened after the
176
+ * fetch). And it is deliberately NOT persisted anywhere β€” a reload re-asks the server, which is
177
+ * the only end that actually knows.
178
+ */
179
+ export function mergeRecents(server: Recent[], local: Record<string, number>): Recent[] {
180
+ const byKey = new Map<string, number>();
181
+ for (const r of server) byKey.set(r.key, r.at);
182
+ for (const [key, at] of Object.entries(local)) {
183
+ const cur = byKey.get(key);
184
+ if (cur === undefined || at > cur) byKey.set(key, at);
185
+ }
186
+ return [...byKey.entries()]
187
+ .map(([key, at]) => ({ key, at }))
188
+ .sort((a, b) => b.at - a.at);
189
+ }
190
+
191
+ // ── the list/grid toggle ────────────────────────────────────────────────────────────────────
192
+
193
+ export type HomeLayout = "grid" | "list";
194
+
195
+ /** Per-browser, like the nav's collapsed state β€” a display preference, not account state. */
196
+ export const HOME_LAYOUT_KEY = "aios-home-layout";
197
+
198
+ /** Anything unrecognised reads as `grid`, which is the reference layout and the denser one. */
199
+ export function parseLayout(raw: unknown): HomeLayout {
200
+ return raw === "list" ? "list" : "grid";
201
+ }
 
 
 
 
 
 
 
web/src/index.css CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/shell/NavExtras.tsx CHANGED
@@ -561,23 +561,36 @@ function PlusIcon() {
561
 
562
  /**
563
  * Wave 14 C-NAVFOLD gave the list's bottom a quiet "+ New folder" (the Views-rail
564
- * precedent). WAVE 19 R11 makes it "+ Create new…" and puts BOTH creatable things
565
- * behind it β€” Folder | Database β€” folding away the standalone "+ New database"
566
- * button that used to sit below the rail with its own odd chrome.
567
  *
568
- * ⚠ IT RENDERS FOR A TENANT WITH NO DATABASES AT ALL, which the row it replaced
569
- * did and the row it grew out of did not. "+ New folder" was gated on
570
- * `entries.length > 0` (folders over nothing are pointless); "+ New database" was
571
- * not, deliberately β€” a freshly provisioned tenant's rail has nothing else to
572
- * offer, and Shell.tsx's own note calls it "the honest affordance in the tenant
573
- * case". Folding the second into the first without moving that gate would have
574
- * left a brand-new workspace with a rail you cannot create anything from.
 
 
 
 
 
 
 
 
 
 
 
 
 
575
  */
576
  export function CreateNewRow({
577
  collapsed,
578
  onExpand,
579
  onCreateFolder,
580
  onNewDatabase,
 
 
581
  canFolder,
582
  }: {
583
  collapsed: boolean;
@@ -585,7 +598,12 @@ export function CreateNewRow({
585
  onExpand: () => void;
586
  onCreateFolder: (name: string) => void;
587
  onNewDatabase: () => void;
588
- /** Folders over an empty list are an empty gesture β€” Database only, then. */
 
 
 
 
 
589
  canFolder: boolean;
590
  }) {
591
  const { at, ref, openFrom, close } = useMenu();
@@ -601,6 +619,12 @@ export function CreateNewRow({
601
  // β›” The 56px strip cannot hold a popover β€” the same reason the account row
602
  // expands instead of opening its menu. Preserved from the button this row
603
  // replaced, which did exactly this before opening its dialog.
 
 
 
 
 
 
604
  if (collapsed) {
605
  return (
606
  <button
@@ -617,24 +641,18 @@ export function CreateNewRow({
617
  if (!naming) {
618
  return (
619
  <>
620
- {/* ⚠ THE ROW SAYS WHAT IT WILL DO. With no databases yet there is nothing
621
- to file, so the chooser has one real branch β€” and "+ Create new…"
622
- beside a `aria-haspopup` that opens a dialog instead of a menu is a
623
- control promising a choice it is not about to offer. The label and the
624
- popup hint both follow `canFolder`. */}
625
  <button
626
  type="button"
627
  className="shell-newfolder"
628
- {...(canFolder ? { "aria-haspopup": "menu" as const } : {})}
629
- onClick={(e) => {
630
- if (!canFolder) {
631
- onNewDatabase();
632
- return;
633
- }
634
- openFrom(e.currentTarget);
635
- }}
636
  >
637
- {canFolder ? "+ Create new…" : "+ New database"}
638
  </button>
639
  {at && (
640
  <MenuShell at={at} menuRef={ref}>
@@ -643,21 +661,43 @@ export function CreateNewRow({
643
  className="shell-navmenu-item"
644
  onClick={() => {
645
  close();
646
- setNaming(true);
647
  }}
648
  >
649
- New folder
650
  </button>
651
  <button
652
  type="button"
653
  className="shell-navmenu-item"
654
  onClick={() => {
655
  close();
656
- onNewDatabase();
657
  }}
658
  >
659
- New database
660
  </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
661
  </MenuShell>
662
  )}
663
  </>
 
561
 
562
  /**
563
  * Wave 14 C-NAVFOLD gave the list's bottom a quiet "+ New folder" (the Views-rail
564
+ * precedent). WAVE 19 R11 made it "+ Create new…" with Folder | Database behind it.
 
 
565
  *
566
+ * ⭐ WAVE 24 items 1 + 15a (ruling R9) β€” IT LEAVES THE RAIL AND BECOMES THE DATABASE
567
+ * FLYOUT'S FOOTER, and it now carries ALL FOUR creatable things: New database Β·
568
+ * From a template Β· Automated database Β· New folder. The flyout's three standalone
569
+ * `.shell-dbfly-make` buttons are deleted; this one control replaces them.
570
+ *
571
+ * ⭐ AND IT IS ALSO ITEM 1's FIX, which is worth stating because it does not look
572
+ * like a typography change. MEASURED on staging v12: the six rail rows all render
573
+ * 13.8125px / w500 / Inter / rgb(32,36,51) β€” identical, `<a>` and `<button>` alike.
574
+ * The ONE row in that band that differed was this one: `.shell-newfolder` declares
575
+ * `--lp-fs-2xs` (12.75px) with no `font-weight` (so 400, inherited) and
576
+ * `--lp-muted`. Taking it out of the rail is what makes the band read as one set;
577
+ * nothing about the other six needed changing, and changing them would have been a
578
+ * fix aimed at the wrong row.
579
+ *
580
+ * ⚠ THE `canFolder` GATE SURVIVES THE MOVE, and it has to. Wave 19's note: folders
581
+ * over an empty list are an empty gesture, but a freshly provisioned tenant must
582
+ * still be able to create a DATABASE. So with no entries the menu simply omits its
583
+ * folder row rather than the control collapsing to a single-purpose button β€” inside
584
+ * a panel there is room for a menu whatever the tenant has, which is the one thing
585
+ * the 236px rail could not say.
586
  */
587
  export function CreateNewRow({
588
  collapsed,
589
  onExpand,
590
  onCreateFolder,
591
  onNewDatabase,
592
+ onFromTemplate,
593
+ onAutomated,
594
  canFolder,
595
  }: {
596
  collapsed: boolean;
 
598
  onExpand: () => void;
599
  onCreateFolder: (name: string) => void;
600
  onNewDatabase: () => void;
601
+ /** R9's second row β€” the template picker, over a database you already have. */
602
+ onFromTemplate: () => void;
603
+ /** R9's third row β€” hands off to the automation wizard; an automated database is
604
+ * CREATED BY the automation that fills it, not by a name box. */
605
+ onAutomated: () => void;
606
+ /** Folders over an empty list are an empty gesture β€” the row is omitted, not the menu. */
607
  canFolder: boolean;
608
  }) {
609
  const { at, ref, openFrom, close } = useMenu();
 
619
  // β›” The 56px strip cannot hold a popover β€” the same reason the account row
620
  // expands instead of opening its menu. Preserved from the button this row
621
  // replaced, which did exactly this before opening its dialog.
622
+ //
623
+ // ⚠ WAVE 24: this branch is now UNREACHABLE FROM THE RAIL (the row is not there
624
+ // any more) but it is NOT dead β€” the flyout can be opened with the rail folded,
625
+ // and `collapsed` is still passed. Kept rather than deleted, because the panel's
626
+ // own note says the folded rail is exactly the state a user who opened it is most
627
+ // likely to be in.
628
  if (collapsed) {
629
  return (
630
  <button
 
641
  if (!naming) {
642
  return (
643
  <>
644
+ {/* THE LABEL NO LONGER FOLLOWS `canFolder`. In the rail it had to: with one
645
+ real branch, "+ Create new…" beside an `aria-haspopup` was a control
646
+ promising a choice it was not about to offer. In the footer there are
647
+ always at least three (database / template / automated), so the menu is
648
+ real whatever the tenant has and the label can simply be true. */}
649
  <button
650
  type="button"
651
  className="shell-newfolder"
652
+ aria-haspopup="menu"
653
+ onClick={(e) => openFrom(e.currentTarget)}
 
 
 
 
 
 
654
  >
655
+ + Create new…
656
  </button>
657
  {at && (
658
  <MenuShell at={at} menuRef={ref}>
 
661
  className="shell-navmenu-item"
662
  onClick={() => {
663
  close();
664
+ onNewDatabase();
665
  }}
666
  >
667
+ New database
668
  </button>
669
  <button
670
  type="button"
671
  className="shell-navmenu-item"
672
  onClick={() => {
673
  close();
674
+ onFromTemplate();
675
  }}
676
  >
677
+ From a template
678
  </button>
679
+ <button
680
+ type="button"
681
+ className="shell-navmenu-item"
682
+ onClick={() => {
683
+ close();
684
+ onAutomated();
685
+ }}
686
+ >
687
+ Automated database
688
+ </button>
689
+ {canFolder ? (
690
+ <button
691
+ type="button"
692
+ className="shell-navmenu-item"
693
+ onClick={() => {
694
+ close();
695
+ setNaming(true);
696
+ }}
697
+ >
698
+ New folder
699
+ </button>
700
+ ) : null}
701
  </MenuShell>
702
  )}
703
  </>
web/src/shell/Shell.tsx CHANGED
@@ -55,6 +55,13 @@ import ConnectorsPage from "../connectors/ConnectorsPage";
55
  // difference between a mount and an intention (verify_wiring's header).
56
  import FormPublic from "../forms/FormPublic";
57
  import { mergeRecents } from "../home/homeModel";
 
 
 
 
 
 
 
58
  import { CreateNewRow, FolderHead, RowMenu, SchemaDrawer } from "./NavExtras";
59
  import AlertsPane from "../alerts/AlertsPane";
60
  import { createAlert, fetchInbox } from "../alerts/alertsApi";
@@ -355,16 +362,13 @@ function PlugIcon() {
355
  );
356
  }
357
 
358
- /** WAVE 23 C10 β€” the flyout footer's plus. Same geometry as `NavExtras`' own `PlusIcon` (which
359
- * is private to that file); drawn rather than imported, the way this tree already draws two
360
- * bells. */
361
- function PlusMark() {
362
- return (
363
- <svg className="shell-dbfly-plus" viewBox="0 0 16 16" aria-hidden="true">
364
- <path d="M8 3.4v9.2M3.4 8h9.2" />
365
- </svg>
366
- );
367
- }
368
 
369
  /** WAVE 23 R7 β€” the disclosure caret on the "Database" row: this opens a panel, and the mark
370
  * says so before the click does (the same job `ExtIcon` does for a hand-off). */
@@ -1056,6 +1060,56 @@ export default function Shell() {
1056
  }
1057
  }, [session.phase, route, entries, formToken]);
1058
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1059
  // WAVE 23 C10 β€” stamp the route as opened, for Home's recents.
1060
  //
1061
  // ⚠ ABOVE THE EARLY RETURNS with every other hook (the React #310 scar at the block below),
@@ -1099,7 +1153,12 @@ export default function Shell() {
1099
  // a component whose hook count changes between renders. Every hook in this component stays
1100
  // above `if (session.phase …) return`, whatever lands here next wave.
1101
  // (owner item 3): the assistant's under-construction note.
1102
- const [assistOpen, setAssistOpen] = useState(false);
 
 
 
 
 
1103
  // β›” ESCAPE CLOSES A MODAL, or its scrim becomes a trap. The assistant note shipped with only
1104
  // a scrim-click and a Close button, and the first close-out probe to press Escape found every
1105
  // subsequent click swallowed by an invisible full-screen div β€” the
@@ -1340,7 +1399,7 @@ export default function Shell() {
1340
  <button
1341
  type="button"
1342
  className="shell-nav-item shell-nav-assist"
1343
- onClick={() => setAssistOpen(true)}
1344
  onMouseEnter={navCollapsed ? tipEnter("AI assistant") : undefined}
1345
  onMouseLeave={navCollapsed ? tipLeave : undefined}
1346
  >
@@ -1349,45 +1408,15 @@ export default function Shell() {
1349
  </button>
1350
  ) : null}
1351
 
1352
- {/* WAVE 19 R10 / C3 β€” Automation, directly under "AI assistant" and
1353
- above the hairline that opens the database band. An `<a>` to the
1354
- route it already had: the surface, its rail and its editor are
1355
- another session's tree this wave and are not touched by any of
1356
- this. The LABEL comes off the payload, never a literal here β€” the
1357
- registry owns what this surface is called, and a client that
1358
- hard-codes the word is the drift that outlives the row. */}
1359
- {automation ? (
1360
- <a
1361
- className={
1362
- "shell-nav-item shell-nav-auto" +
1363
- (active && active.key === automation.key ? " is-active" : "")
1364
- }
1365
- href={automation.href}
1366
- onMouseEnter={navCollapsed ? tipEnter(automation.label) : undefined}
1367
- onMouseLeave={navCollapsed ? tipLeave : undefined}
1368
- >
1369
- {/* ⚠ R8 lists Automation among the databases that get an icon
1370
- ("Customer/Product/Automation/custom"); R10 moves it out of the
1371
- list where the β‹― that SETS one lives. So it DISPLAYS a chosen
1372
- mark β€” the store and the route already accept `automation` as a
1373
- key β€” while the entry point to choose one is the open question
1374
- booked as amendment 6 for the integrator. Rendering the default
1375
- glyph unconditionally would have made this the one database
1376
- that could never show an icon, which is the half of R8 a client
1377
- has no business deciding. */}
1378
- {automation.icon ? (
1379
- <span className="shell-nav-mark" aria-hidden="true">
1380
- <FolderMark icon={automation.icon} size={16} />
1381
- </span>
1382
- ) : (
1383
- <AutoIcon />
1384
- )}
1385
- <span className="shell-nav-label">{automation.label}</span>
1386
- </a>
1387
- ) : null}
1388
-
1389
- {/* WAVE 20 item 25 (C-ALERT) β€” "Alerts", directly under Automation and above
1390
- the database band, with the unread count on it.
1391
  β›” A BUTTON, NOT A NAV LINK, and the distinction is this shell's oldest
1392
  rule: the nav is server-filtered and an undeclared surface is denied, so a
1393
  client-invented `#/alerts` route would be exactly the hard-coded surface
@@ -1417,22 +1446,40 @@ export default function Shell() {
1417
  ) : null}
1418
  </button>
1419
 
1420
- {/* ⭐ WAVE 23 item 10 (R8, contract C11, wiring W23-W3) β€” CONNECTORS, directly below
1421
- Alerts, exactly where R8 puts it. A chrome route like Home: the DIRECTORY it renders
1422
- is composed by the server and session-gated, so this row can no more invent a
1423
- connector than Home can invent a database. */}
1424
- <a
1425
- className={
1426
- "shell-nav-item shell-nav-connectors" +
1427
- (route === CONNECTORS_ROUTE ? " is-active" : "")
1428
- }
1429
- href={`#/${CONNECTORS_ROUTE}`}
1430
- onMouseEnter={navCollapsed ? tipEnter("Connectors") : undefined}
1431
- onMouseLeave={navCollapsed ? tipLeave : undefined}
1432
- >
1433
- <PlugIcon />
1434
- <span className="shell-nav-label">Connectors</span>
1435
- </a>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1436
 
1437
  {/* ⭐ WAVE 23 item 9 (R7) β€” THE DATABASE BUTTON, and the end of the always-on band.
1438
  R7: "databases LEAVE the always-on rail; a 'Database' nav button opens the flyout".
@@ -1463,19 +1510,30 @@ export default function Shell() {
1463
  <CaretIcon />
1464
  </button>
1465
 
1466
- {/* Wave 14 C-NAVFOLD / WAVE 19 R11 β€” "+ Create new…", now a RAIL row rather than the
1467
- foot of a list that no longer lives here. C10 pins it between Database and the
1468
- account corner, which is where R11 always meant it to read: the last thing in the
1469
- rail is the thing that adds to it. */}
1470
- {nav.phase === "ready" ? (
1471
- <CreateNewRow
1472
- collapsed={navCollapsed}
1473
- onExpand={() => setNavCollapsed(false)}
1474
- onCreateFolder={createFolder}
1475
- onNewDatabase={() => openNewDb("blank")}
1476
- canFolder={entries.length > 0}
1477
- />
1478
- ) : null}
 
 
 
 
 
 
 
 
 
 
 
1479
 
1480
  {/* ── THE DATABASE FLYOUT (C10) ────────────────────────────────────────────────────
1481
  β›” PORTALLED TO `<body>`, and it has to be. Left inside the `<aside>` it would be a
@@ -1752,45 +1810,44 @@ export default function Shell() {
1752
  </p>
1753
  ) : null}
1754
  </div>
1755
- {/* ── the create footer (C10) β€” three doors, ONE dialog ──────────────────
1756
- Blank and template open the same New-database dialog with the choice
1757
- pre-selected; automated hands off to the automation wizard, because an
1758
- automated database is CREATED BY the automation that fills it (C2's
1759
- `target.mode`), not by a name box that then needs one. */}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1760
  <div className="shell-dbfly-foot">
1761
- <button
1762
- type="button"
1763
- className="shell-dbfly-make"
1764
- onClick={() => {
 
1765
  closeDbFly();
1766
  openNewDb("blank");
1767
  }}
1768
- >
1769
- <PlusMark />
1770
- Blank database
1771
- </button>
1772
- <button
1773
- type="button"
1774
- className="shell-dbfly-make"
1775
- onClick={() => {
1776
  closeDbFly();
1777
  openNewDb("template");
1778
  }}
1779
- >
1780
- <PlusMark />
1781
- From a template
1782
- </button>
1783
- <button
1784
- type="button"
1785
- className="shell-dbfly-make"
1786
- onClick={() => {
1787
  closeDbFly();
1788
  openAutomated();
1789
  }}
1790
- >
1791
- <PlusMark />
1792
- Automated database
1793
- </button>
1794
  </div>
1795
  </div>,
1796
  document.body
@@ -1973,14 +2030,33 @@ export default function Shell() {
1973
  // `home-empty`, which branches on `entries.length === 0` for exactly this reason).
1974
  // Booked as a dated amendment in the wave doc, since it moves an R4 surface.
1975
  <HomePage
1976
- entries={entries}
 
 
 
 
 
 
 
 
1977
  recents={recents}
1978
- onTemplates={() => openNewDb("template")}
 
 
 
 
 
1979
  onNewDatabase={() => openNewDb("blank")}
1980
  onAutomated={openAutomated}
1981
  onConnectors={() => {
1982
  window.location.hash = `#/${CONNECTORS_ROUTE}`;
1983
  }}
 
 
 
 
 
 
1984
  />
1985
  ) : nav.phase === "error" ? (
1986
  // ⚠ WAVE 17 ITEM 4 (R6) β€” THE ERROR AND THE EMPTY ARE DIFFERENT SENTENCES, and this
@@ -2011,16 +2087,28 @@ export default function Shell() {
2011
  <div
2012
  className="shell-newdb shell-assist-note"
2013
  role="dialog"
2014
- aria-label="AI assistant"
2015
  onClick={(e) => e.stopPropagation()}
2016
  >
2017
- <h2>
2018
- <SparkIcon /> AI assistant
2019
- </h2>
2020
- <p className="shell-newdb-sub">
2021
- Under construction. The assistant is being trained on this workspace's data
2022
- model and will open here in a later release.
2023
- </p>
 
 
 
 
 
 
 
 
 
 
 
 
2024
  <div className="shell-newdb-actions">
2025
  <button type="button" className="login-submit" onClick={() => setAssistOpen(false)}>
2026
  Close
 
55
  // difference between a mount and an intention (verify_wiring's header).
56
  import FormPublic from "../forms/FormPublic";
57
  import { mergeRecents } from "../home/homeModel";
58
+ import type { AutomationTile } from "../home/homeModel";
59
+ // ⭐ WAVE 24 item 13 (R10, wiring W24-W3) β€” Home's Automations section.
60
+ // β›” IMPORTED, NOT RE-DERIVED. `stateOf` is the ONE place "is this running" is decided
61
+ // (`a.running ? "running" : status.state`), and a second copy here would be a client union over
62
+ // a server vocabulary β€” the thing this tree forbids everywhere else. `listAutomations` brings the
63
+ // credentials and the error shape with it, so the frame adds a fetch, not a protocol.
64
+ import { listAutomations, stateOf } from "../automation/automationApi";
65
  import { CreateNewRow, FolderHead, RowMenu, SchemaDrawer } from "./NavExtras";
66
  import AlertsPane from "../alerts/AlertsPane";
67
  import { createAlert, fetchInbox } from "../alerts/alertsApi";
 
362
  );
363
  }
364
 
365
+ /* β›” `PlusMark` LIVED HERE AND IS DELETED WITH THE THREE BUTTONS THAT DREW IT (wave 24 item 15a,
366
+ ruling R9). It was the flyout footer's plus, used by nothing else β€” `CreateNewRow` brings its
367
+ own `PlusIcon`, which is private to `NavExtras`. `tsc` named it the moment the last call site
368
+ went (TS6133), which is the argument for a REQUIRED prop and an unused-locals check doing the
369
+ remembering: the CSS twins `.shell-dbfly-make` and `.shell-dbfly-plus` went to zero call sites
370
+ in the same edit and no compiler says a word about those β€” they are swept by hand below, in
371
+ this session's own index.css region, rather than left as the D-42 residue class. */
 
 
 
372
 
373
  /** WAVE 23 R7 β€” the disclosure caret on the "Database" row: this opens a panel, and the mark
374
  * says so before the click does (the same job `ExtIcon` does for a hand-off). */
 
1060
  }
1061
  }, [session.phase, route, entries, formToken]);
1062
 
1063
+ // ── WAVE 24 item 13 (R10, wiring W24-W3): Home's automations ────────────────────────────
1064
+ //
1065
+ // ⚠ FETCHED HERE, NOT IN `HomePage`. Home holds no state of its own by contract β€” its whole
1066
+ // C10 argument for being CHROME rather than a granted surface is that it draws only what the
1067
+ // frame already has. A fetch inside it would make it a surface with a data contract.
1068
+ //
1069
+ // β›” A 403 BECOMES `[]`, NOT AN ERROR. An account without the automation grant is not a
1070
+ // failure β€” it is an account that has no automations to show, and the section simply does not
1071
+ // render. Raising DATA_ERROR_EVENT here would put an error card over Home for every member of
1072
+ // a tenant whose automations they were never granted.
1073
+ //
1074
+ // ⚠ RE-ASKED ON `navEpoch`, which is what makes "create an automated database" land: the
1075
+ // create door bumps the nav, so returning to Home shows the automation that was just made.
1076
+ const [autoTiles, setAutoTiles] = useState<AutomationTile[]>([]);
1077
+ useEffect(() => {
1078
+ if (who === null) {
1079
+ setAutoTiles([]);
1080
+ return;
1081
+ }
1082
+ const ac = new AbortController();
1083
+ let dead = false;
1084
+ void listAutomations(ac.signal)
1085
+ .then((r) => {
1086
+ if (dead) return;
1087
+ setAutoTiles(
1088
+ (r.automations || []).map((a) => ({
1089
+ id: a.id,
1090
+ name: a.name,
1091
+ state: stateOf(a),
1092
+ // The rail's own second line, one fact not two: the forward-looking one when a
1093
+ // schedule exists (it answers "does this run itself?"), the last run otherwise.
1094
+ sub: a.schedule?.enabled
1095
+ ? a.nextRunAt
1096
+ ? `Next ${a.nextRunAt}`
1097
+ : "Scheduled"
1098
+ : a.status?.lastRunAt
1099
+ ? `Last run ${a.status.lastRunAt.replace("T", " ").slice(0, 16)}`
1100
+ : "Manual only",
1101
+ }))
1102
+ );
1103
+ })
1104
+ .catch(() => {
1105
+ if (!dead) setAutoTiles([]);
1106
+ });
1107
+ return () => {
1108
+ dead = true;
1109
+ ac.abort();
1110
+ };
1111
+ }, [who, navEpoch]);
1112
+
1113
  // WAVE 23 C10 β€” stamp the route as opened, for Home's recents.
1114
  //
1115
  // ⚠ ABOVE THE EARLY RETURNS with every other hook (the React #310 scar at the block below),
 
1153
  // a component whose hook count changes between renders. Every hook in this component stays
1154
  // above `if (session.phase …) return`, whatever lands here next wave.
1155
  // (owner item 3): the assistant's under-construction note.
1156
+ // ⭐ WAVE 24 item 14 β€” it carries WHICH boarded door was knocked on, not just "open". Two
1157
+ // surfaces are now under construction (the assistant, and Home's templates card) and they are
1158
+ // the same dialog with a different sentence β€” a second near-identical modal would be the
1159
+ // "variety is a defect" failure, and a shared one that could not say which door you came
1160
+ // through would tell a reader about the wrong feature.
1161
+ const [assistOpen, setAssistOpen] = useState<false | "assistant" | "templates">(false);
1162
  // β›” ESCAPE CLOSES A MODAL, or its scrim becomes a trap. The assistant note shipped with only
1163
  // a scrim-click and a Close button, and the first close-out probe to press Escape found every
1164
  // subsequent click swallowed by an invisible full-screen div β€” the
 
1399
  <button
1400
  type="button"
1401
  className="shell-nav-item shell-nav-assist"
1402
+ onClick={() => setAssistOpen("assistant")}
1403
  onMouseEnter={navCollapsed ? tipEnter("AI assistant") : undefined}
1404
  onMouseLeave={navCollapsed ? tipLeave : undefined}
1405
  >
 
1408
  </button>
1409
  ) : null}
1410
 
1411
+ {/* WAVE 20 item 25 (C-ALERT) β€” "Alerts".
1412
+ ⭐ WAVE 24 item 1 β€” IT MOVED UP, above Automation. The owner's order is
1413
+ Home / AI assistant / Alerts / Automation / Database / Connectors, and the
1414
+ two pairs that swapped are Alerts↔Automation here and Database↔Connectors
1415
+ below. Nothing else about these rows changed: MEASURED on staging v12, all
1416
+ six already render 13.8125px / w500 / Inter / rgb(32,36,51), `<a>` and
1417
+ `<button>` alike (wave 19 R11's reset holding). The one row in this band
1418
+ that differed was "+ Create new…" (12.75px / w400 / muted), and item 15a
1419
+ takes it out of the rail entirely β€” see `CreateNewRow`'s own note.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1420
  β›” A BUTTON, NOT A NAV LINK, and the distinction is this shell's oldest
1421
  rule: the nav is server-filtered and an undeclared surface is denied, so a
1422
  client-invented `#/alerts` route would be exactly the hard-coded surface
 
1446
  ) : null}
1447
  </button>
1448
 
1449
+ {/* WAVE 19 R10 / C3 β€” Automation. An `<a>` to the route it already had: the
1450
+ surface, its rail and its editor are another session's tree this wave and
1451
+ are not touched by any of this. The LABEL comes off the payload, never a
1452
+ literal here β€” the registry owns what this surface is called, and a client
1453
+ that hard-codes the word is the drift that outlives the row. */}
1454
+ {automation ? (
1455
+ <a
1456
+ className={
1457
+ "shell-nav-item shell-nav-auto" +
1458
+ (active && active.key === automation.key ? " is-active" : "")
1459
+ }
1460
+ href={automation.href}
1461
+ onMouseEnter={navCollapsed ? tipEnter(automation.label) : undefined}
1462
+ onMouseLeave={navCollapsed ? tipLeave : undefined}
1463
+ >
1464
+ {/* ⚠ R8 lists Automation among the databases that get an icon
1465
+ ("Customer/Product/Automation/custom"); R10 moves it out of the
1466
+ list where the β‹― that SETS one lives. So it DISPLAYS a chosen
1467
+ mark β€” the store and the route already accept `automation` as a
1468
+ key β€” while the entry point to choose one is the open question
1469
+ booked as amendment 6 for the integrator. Rendering the default
1470
+ glyph unconditionally would have made this the one database
1471
+ that could never show an icon, which is the half of R8 a client
1472
+ has no business deciding. */}
1473
+ {automation.icon ? (
1474
+ <span className="shell-nav-mark" aria-hidden="true">
1475
+ <FolderMark icon={automation.icon} size={16} />
1476
+ </span>
1477
+ ) : (
1478
+ <AutoIcon />
1479
+ )}
1480
+ <span className="shell-nav-label">{automation.label}</span>
1481
+ </a>
1482
+ ) : null}
1483
 
1484
  {/* ⭐ WAVE 23 item 9 (R7) β€” THE DATABASE BUTTON, and the end of the always-on band.
1485
  R7: "databases LEAVE the always-on rail; a 'Database' nav button opens the flyout".
 
1510
  <CaretIcon />
1511
  </button>
1512
 
1513
+ {/* ⭐ WAVE 23 item 10 (R8, contract C11, wiring W23-W3) β€” CONNECTORS.
1514
+ ⭐ WAVE 24 item 1 β€” it moved BELOW Database. R8 put it above; the owner's wave-24
1515
+ order puts the two destinations that open panels-over-server-data (Database, then
1516
+ Connectors) at the foot of the rail. A chrome route like Home: the DIRECTORY it
1517
+ renders is composed by the server and session-gated, so this row can no more invent
1518
+ a connector than Home can invent a database. */}
1519
+ <a
1520
+ className={
1521
+ "shell-nav-item shell-nav-connectors" +
1522
+ (route === CONNECTORS_ROUTE ? " is-active" : "")
1523
+ }
1524
+ href={`#/${CONNECTORS_ROUTE}`}
1525
+ onMouseEnter={navCollapsed ? tipEnter("Connectors") : undefined}
1526
+ onMouseLeave={navCollapsed ? tipLeave : undefined}
1527
+ >
1528
+ <PlugIcon />
1529
+ <span className="shell-nav-label">Connectors</span>
1530
+ </a>
1531
+
1532
+ {/* β›” "+ Create new…" IS NO LONGER A RAIL ROW (item 15a, ruling R9). It moved into the
1533
+ Database flyout's footer, where the things it creates actually live β€” and where the
1534
+ three `.shell-dbfly-make` buttons used to be. See the footer below, and
1535
+ `CreateNewRow`'s own note for why this is also item 1's fix rather than a separate
1536
+ cosmetic change: it was the one row in this band whose type differed. */}
1537
 
1538
  {/* ── THE DATABASE FLYOUT (C10) ────────────────────────────────────────────────────
1539
  β›” PORTALLED TO `<body>`, and it has to be. Left inside the `<aside>` it would be a
 
1810
  </p>
1811
  ) : null}
1812
  </div>
1813
+ {/* ── the create footer ─────────────────────────────────────────────────
1814
+ ⭐ WAVE 24 item 15a (ruling R9, wiring W24-W4) β€” ONE CONTROL, FOUR DOORS.
1815
+ C10's three `.shell-dbfly-make` buttons are deleted and "+ Create new…"
1816
+ moves here from the rail, carrying New database Β· From a template Β·
1817
+ Automated database Β· New folder.
1818
+
1819
+ ⚠ NOTHING THE THREE BUTTONS OPENED IS LOST, and that was the constraint:
1820
+ blank and template still open the same New-database dialog with the choice
1821
+ pre-selected, automated still hands off to the automation wizard (an
1822
+ automated database is CREATED BY the automation that fills it, not by a
1823
+ name box that then needs one) β€” and FOLDERS, which the rail row owned and
1824
+ the three buttons never offered, keep their only creation door.
1825
+
1826
+ ⚠ EACH DOOR CLOSES THE PANEL FIRST, exactly as the buttons did. `New
1827
+ folder` is the one that must NOT: it opens an inline naming form inside
1828
+ this footer, and `createFolder` re-opens the panel so the new folder is
1829
+ visible (C10's own fix for an affordance whose effect was invisible).
1830
+ `CreateNewRow` keeps that form internal, so closing here would unmount the
1831
+ thing the user is typing into. */}
1832
  <div className="shell-dbfly-foot">
1833
+ <CreateNewRow
1834
+ collapsed={navCollapsed}
1835
+ onExpand={() => setNavCollapsed(false)}
1836
+ onCreateFolder={createFolder}
1837
+ onNewDatabase={() => {
1838
  closeDbFly();
1839
  openNewDb("blank");
1840
  }}
1841
+ onFromTemplate={() => {
 
 
 
 
 
 
 
1842
  closeDbFly();
1843
  openNewDb("template");
1844
  }}
1845
+ onAutomated={() => {
 
 
 
 
 
 
 
1846
  closeDbFly();
1847
  openAutomated();
1848
  }}
1849
+ canFolder={entries.length > 0}
1850
+ />
 
 
1851
  </div>
1852
  </div>,
1853
  document.body
 
2030
  // `home-empty`, which branches on `entries.length === 0` for exactly this reason).
2031
  // Booked as a dated amendment in the wave doc, since it moves an R4 surface.
2032
  <HomePage
2033
+ // ⭐ `dbEntries`, NOT `entries` β€” found by LOOKING at it (wave 24 close-out visual
2034
+ // pass), which is the only way it could have been found. The Automation SURFACE is a
2035
+ // granted nav entry with an href, so `allDatabases` drew it a tile under the heading
2036
+ // "Databases" β€” beside an "Automations" section listing the things it contains. The
2037
+ // rail has excluded it since wave 19 R10 for exactly this reason (`dbEntries`, :1261);
2038
+ // Home was drawing the unfiltered list.
2039
+ // ⚠ STILL THE GRANTED NAV, so the C10 law is untouched: `dbEntries` is `entries` minus
2040
+ // one key, not a list this frame invented.
2041
+ entries={dbEntries}
2042
  recents={recents}
2043
+ automations={autoTiles}
2044
+ // ⭐ WAVE 24 item 14 β€” the templates CARD is boarded. It opens the same
2045
+ // under-construction note the AI assistant uses, rather than the picker.
2046
+ // ⚠ The flyout's "From a template" row is UNAFFECTED (R9 keeps it working) β€” see
2047
+ // HomePage's own note on why that asymmetry is deliberate rather than a miss.
2048
+ onTemplates={() => setAssistOpen("templates")}
2049
  onNewDatabase={() => openNewDb("blank")}
2050
  onAutomated={openAutomated}
2051
  onConnectors={() => {
2052
  window.location.hash = `#/${CONNECTORS_ROUTE}`;
2053
  }}
2054
+ // The same two-part move every click-through in this frame makes: the frame owns the
2055
+ // hash, the surface owns which automation is selected. Route, then ASK.
2056
+ onOpenAutomation={(autoId) => {
2057
+ window.location.hash = "#/automation";
2058
+ signal(AUTOMATION_OPEN_EVENT, { autoId });
2059
+ }}
2060
  />
2061
  ) : nav.phase === "error" ? (
2062
  // ⚠ WAVE 17 ITEM 4 (R6) β€” THE ERROR AND THE EMPTY ARE DIFFERENT SENTENCES, and this
 
2087
  <div
2088
  className="shell-newdb shell-assist-note"
2089
  role="dialog"
2090
+ aria-label={assistOpen === "templates" ? "Templates" : "AI assistant"}
2091
  onClick={(e) => e.stopPropagation()}
2092
  >
2093
+ {assistOpen === "templates" ? (
2094
+ <>
2095
+ <h2>Templates</h2>
2096
+ <p className="shell-newdb-sub">
2097
+ Under construction. Curated template sets are being built and will open here in
2098
+ a later release.
2099
+ </p>
2100
+ </>
2101
+ ) : (
2102
+ <>
2103
+ <h2>
2104
+ <SparkIcon /> AI assistant
2105
+ </h2>
2106
+ <p className="shell-newdb-sub">
2107
+ Under construction. The assistant is being trained on this workspace's data
2108
+ model and will open here in a later release.
2109
+ </p>
2110
+ </>
2111
+ )}
2112
  <div className="shell-newdb-actions">
2113
  <button type="button" className="login-submit" onClick={() => setAssistOpen(false)}>
2114
  Close