fsanyoto commited on
Commit
e45ce07
Β·
verified Β·
1 Parent(s): b64a941

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
This view is limited to 50 files because it contains too many changes. Β  See raw diff
Files changed (50) hide show
  1. RELEASES.json +13 -1
  2. VERSION +1 -1
  3. api/ai_review.py +207 -0
  4. api/automation_engine.py +0 -0
  5. api/main.py +21 -0
  6. api/routes_automation.py +202 -30
  7. api/routes_connectors.py +176 -0
  8. api/routes_forms.py +399 -0
  9. api/routes_keychain.py +49 -33
  10. api/routes_nav.py +132 -1
  11. api/routes_products.py +25 -1
  12. api/routes_tables.py +28 -4
  13. api/routes_templates.py +148 -0
  14. platform/aios_grid.py +7 -1
  15. platform/core/alerts.py +38 -0
  16. platform/core/grid_events.py +22 -0
  17. platform/core/keychain.py +7 -1
  18. platform/core/user_tables.py +33 -3
  19. platform/core/view_templates.py +296 -0
  20. platform/harness/datastore.py +102 -3
  21. platform/harness/runtime.py +95 -0
  22. web/src/alerts/AlertsPane.tsx +38 -3
  23. web/src/alerts/alertsModel.ts +49 -0
  24. web/src/apiContract.ts +46 -0
  25. web/src/automation/AutomationBoard.tsx +47 -53
  26. web/src/automation/AutomationBuilder.tsx +2097 -0
  27. web/src/automation/AutomationDetail.tsx +793 -411
  28. web/src/automation/AutomationFind.tsx +282 -55
  29. web/src/automation/AutomationSurface.tsx +405 -41
  30. web/src/automation/AutomationTrigger.tsx +110 -24
  31. web/src/automation/CondBuilder.tsx +344 -0
  32. web/src/automation/automationApi.ts +323 -26
  33. web/src/automation/steps.ts +137 -1
  34. web/src/connectors/ConnectorsPage.tsx +274 -0
  35. web/src/customer-grid/ColumnMenu.tsx +12 -3
  36. web/src/customer-grid/CustomerGrid.tsx +47 -0
  37. web/src/customer-grid/JsonViewer.tsx +361 -0
  38. web/src/customer-grid/RecordDetail.css +46 -0
  39. web/src/customer-grid/RecordDetail.tsx +60 -1
  40. web/src/customer-grid/cells.ts +64 -2
  41. web/src/customer-grid/display.ts +92 -0
  42. web/src/customer-grid/iconShapes.ts +35 -0
  43. web/src/customer-grid/theme.ts +75 -0
  44. web/src/customer-grid/types.ts +81 -4
  45. web/src/filter-kit/ops.ts +14 -0
  46. web/src/forms/FormPublic.tsx +266 -0
  47. web/src/home/HomePage.tsx +368 -0
  48. web/src/home/TemplatePicker.tsx +217 -0
  49. web/src/home/homeModel.ts +201 -0
  50. web/src/index.css +0 -0
RELEASES.json CHANGED
@@ -1,6 +1,18 @@
1
  {
2
- "current": "v11 (3126617)",
3
  "releases": [
 
 
 
 
 
 
 
 
 
 
 
 
4
  {
5
  "version": "v11",
6
  "sha": "3126617",
 
1
  {
2
+ "current": "v13 (314c0e3)",
3
  "releases": [
4
+ {
5
+ "version": "v13",
6
+ "sha": "314c0e3",
7
+ "date": "2026-08-06",
8
+ "subject": "release v13"
9
+ },
10
+ {
11
+ "version": "v12",
12
+ "sha": "4908f39",
13
+ "date": "2026-08-06",
14
+ "subject": "release v12"
15
+ },
16
  {
17
  "version": "v11",
18
  "sha": "3126617",
VERSION CHANGED
@@ -1 +1 @@
1
- v11 (3126617)
 
1
+ v13 (314c0e3)
api/ai_review.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AI REVIEW β€” let a model decide which stage a card moves to (wave 23, owner ruling R4/R14).
2
+
3
+ ⭐ WHAT THIS IS. A review stage holds a record until somebody decides where it goes next. R4 made
4
+ that somebody optionally a MODEL: the engine hands over the record's own values, the review's
5
+ prompt, and the list of stages the review is allowed to send a card to, and gets back ONE of
6
+ those stage labels plus a one-line reason. Every decision is written to the same `reviews` audit
7
+ log a human click writes to, tagged `by: "ai"` with the provider and model that made it.
8
+
9
+ β›” FAIL-CLOSED IN EVERY DIRECTION, and this is the whole safety story. No key configured, a
10
+ network failure, a slow answer, a malformed answer, or an answer naming a stage the review does
11
+ not offer β€” all return `("", {...})`, and the caller leaves the card exactly where a human would
12
+ have found it. The feature can be absent, broken or wrong and the worst outcome is a person doing
13
+ the work. Nothing here can move a card somewhere the review does not already permit.
14
+
15
+ ⭐ CHEAP FIRST (owner R14, verbatim: *"Claude is a bit too expensive"*). The ladder is
16
+ `groq β†’ cerebras β†’ openrouter β†’ anthropic`; the first CONFIGURED provider wins, and Anthropic is
17
+ last rather than absent β€” it is the quality backstop, not the default. `AIOS_AI_REVIEW_PROVIDER`
18
+ pins one; `AIOS_AI_MODEL` overrides the model.
19
+
20
+ ⚠ WHY RAW HTTP RATHER THAN THE `anthropic` SDK, stated because it is a deliberate deviation from
21
+ the /claude-api skill's default and not an oversight. Three of the four legs are OpenAI-chat-shaped
22
+ endpoints with no shared SDK, so a ladder built on the SDK would be one SDK leg beside three
23
+ hand-rolled ones β€” two implementations of the same call, the seam this repo keeps closing. And
24
+ `aios-web/api/requirements.txt` is PINNED to what the verify battery proves ([[pin-deps-space-
25
+ rebuilds]]): adding a dependency there rebuilds the container, which is a real deploy risk to take
26
+ for one leg of an optional feature. `requests` is already a dependency and `harness/analyst.py`
27
+ established per-provider raw HTTP as the house pattern. Booked as a DEBT line so the integrator
28
+ can overturn it deliberately rather than by drift.
29
+
30
+ The Messages shape below is the current one: `x-api-key` + `anthropic-version: 2023-06-01`, and
31
+ `stop_reason: "refusal"` is checked BEFORE reading `content` β€” a refusal answers HTTP 200 with an
32
+ empty content list, so code that indexes `content[0]` unconditionally breaks on it.
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import json
37
+ import os
38
+ import re
39
+
40
+ import requests
41
+
42
+ #: The ladder. Order IS the policy (R14) β€” cheapest capable first, Anthropic last.
43
+ PROVIDERS = [
44
+ {"name": "groq", "env": "GROQ_API_KEY", "shape": "openai",
45
+ "url": "https://api.groq.com/openai/v1/chat/completions",
46
+ "model": "llama-3.3-70b-versatile"},
47
+ {"name": "cerebras", "env": "CEREBRAS_API_KEY", "shape": "openai",
48
+ "url": "https://api.cerebras.ai/v1/chat/completions",
49
+ "model": "gpt-oss-120b"},
50
+ {"name": "openrouter", "env": "OPENROUTER_API_KEY", "shape": "openai",
51
+ "url": "https://openrouter.ai/api/v1/chat/completions",
52
+ "model": "openai/gpt-4o-mini"},
53
+ # ⚠ haiku-class DELIBERATELY, not the default Opus tier: R14 put Anthropic on this ladder as
54
+ # the backstop for a one-line classification, and this is the cheapest current Claude that
55
+ # does it well. A bigger model here would be spending the owner's money to pick between two
56
+ # labels it already has in front of it.
57
+ {"name": "anthropic", "env": "ANTHROPIC_API_KEY", "shape": "anthropic",
58
+ "url": "https://api.anthropic.com/v1/messages",
59
+ "model": "claude-haiku-4-5"},
60
+ ]
61
+ ANTHROPIC_VERSION = "2023-06-01"
62
+ TIMEOUT_SECONDS = float(os.environ.get("AIOS_AI_REVIEW_TIMEOUT") or 20)
63
+ MAX_FIELD_CHARS = 200 # per value handed to the model
64
+ MAX_FIELDS = 30 # columns handed to the model
65
+ MAX_REASON = 200
66
+
67
+
68
+ def ladder():
69
+ """The providers that are actually usable here, in order. Empty = the feature is off."""
70
+ pin = (os.environ.get("AIOS_AI_REVIEW_PROVIDER") or "").strip().lower()
71
+ live = [p for p in PROVIDERS if (os.environ.get(p["env"]) or "").strip()]
72
+ if pin:
73
+ live = [p for p in live if p["name"] == pin]
74
+ return live
75
+
76
+
77
+ def configured():
78
+ return bool(ladder())
79
+
80
+
81
+ def _record_text(row, fields):
82
+ """The record, as the model sees it. Values are truncated and the column set is bounded β€”
83
+ an automation table can carry a 32 KB JSON blob per row (C7) and a review decision does not
84
+ need it. Machine bookkeeping columns are dropped: a stage cell naming the stage the card is
85
+ sitting at would be the model reading its own question back."""
86
+ keys = [k for k in (fields or list((row or {}).keys()))
87
+ if not str(k).startswith("stage_")][:MAX_FIELDS]
88
+ lines = []
89
+ for k in keys:
90
+ v = (row or {}).get(k)
91
+ if v is None or str(v).strip() == "":
92
+ continue
93
+ lines.append(f"{k}: {str(v)[:MAX_FIELD_CHARS]}")
94
+ return "\n".join(lines) or "(this record has no filled-in values)"
95
+
96
+
97
+ def _instruction(prompt, options, label):
98
+ return (
99
+ f"You are deciding what happens to one record waiting at a review step called "
100
+ f"{label!r} in a workflow.\n\n"
101
+ f"The person who built this workflow told you: {prompt}\n\n"
102
+ f"Choose EXACTLY ONE of these next steps, by its exact name:\n"
103
+ + "\n".join(f"- {o}" for o in options)
104
+ + "\n\nAnswer with one line of JSON and nothing else:\n"
105
+ '{"choice": "<one name from the list above>", "reason": "<one short sentence>"}\n'
106
+ "If the record does not give you enough to decide, answer "
107
+ '{"choice": "", "reason": "why not"} and a person will decide instead.'
108
+ )
109
+
110
+
111
+ def _parse(text, options):
112
+ """The model's line β†’ `(choice, reason)`. A choice that is not one of the offered stages is
113
+ DISCARDED, not fuzzy-matched: the offered list is a permission boundary, and a near-miss
114
+ resolved by string distance is how a card ends up somewhere nobody authorised."""
115
+ raw = str(text or "").strip()
116
+ obj = None
117
+ m = re.search(r"\{.*\}", raw, re.S)
118
+ if m:
119
+ try:
120
+ obj = json.loads(m.group(0))
121
+ except (ValueError, TypeError):
122
+ obj = None
123
+ if not isinstance(obj, dict):
124
+ return "", ""
125
+ choice = str(obj.get("choice") or "").strip()
126
+ reason = str(obj.get("reason") or "").strip()[:MAX_REASON]
127
+ for opt in options:
128
+ if choice.lower() == str(opt).lower():
129
+ return str(opt), reason # the OFFERED spelling wins, never the model's
130
+ return "", reason
131
+
132
+
133
+ def _call_openai(p, model, system, user, timeout):
134
+ r = requests.post(p["url"], timeout=timeout,
135
+ headers={"Authorization": f"Bearer {os.environ[p['env']].strip()}",
136
+ "Content-Type": "application/json"},
137
+ json={"model": model, "max_tokens": 300, "temperature": 0,
138
+ "messages": [{"role": "system", "content": system},
139
+ {"role": "user", "content": user}]})
140
+ if r.status_code >= 400:
141
+ return "", f"{p['name']} answered {r.status_code}"
142
+ body = r.json()
143
+ choices = body.get("choices") or []
144
+ if not choices:
145
+ return "", f"{p['name']} returned no choices"
146
+ return str(((choices[0] or {}).get("message") or {}).get("content") or ""), ""
147
+
148
+
149
+ def _call_anthropic(p, model, system, user, timeout):
150
+ r = requests.post(p["url"], timeout=timeout,
151
+ headers={"x-api-key": os.environ[p["env"]].strip(),
152
+ "anthropic-version": ANTHROPIC_VERSION,
153
+ "content-type": "application/json"},
154
+ json={"model": model, "max_tokens": 300, "system": system,
155
+ "messages": [{"role": "user", "content": user}]})
156
+ if r.status_code >= 400:
157
+ return "", f"anthropic answered {r.status_code}"
158
+ body = r.json()
159
+ # β›” stop_reason FIRST. A safety refusal is a successful 200 with an EMPTY content list, so
160
+ # reading content[0] before this check turns a refusal into an IndexError inside a run.
161
+ if body.get("stop_reason") == "refusal":
162
+ return "", "anthropic declined to answer this record"
163
+ parts = [b.get("text") or "" for b in (body.get("content") or [])
164
+ if isinstance(b, dict) and b.get("type") == "text"]
165
+ if not parts:
166
+ return "", "anthropic returned no text"
167
+ return "".join(parts), ""
168
+
169
+
170
+ def decide(*, prompt, options, row, fields=(), label="Review", timeout=None):
171
+ """Pick this record's next stage. Returns `(choice, meta)`.
172
+
173
+ `choice` is "" whenever a person should decide β€” which is every failure mode there is.
174
+ `meta` carries `provider`, `model`, `reason` on success, and `problem` on refusal to answer.
175
+ """
176
+ opts = [str(o) for o in (options or []) if str(o).strip()]
177
+ if not opts:
178
+ return "", {"problem": "the review offers no next stages"}
179
+ if not str(prompt or "").strip():
180
+ return "", {"problem": "the review has no prompt for the model to follow"}
181
+ live = ladder()
182
+ if not live:
183
+ return "", {"problem": "no AI provider is configured on this deployment"}
184
+ system = _instruction(prompt, opts, label)
185
+ user = "Here is the record:\n\n" + _record_text(row, fields)
186
+ tmo = float(timeout or TIMEOUT_SECONDS)
187
+ override = (os.environ.get("AIOS_AI_MODEL") or "").strip()
188
+ problems = []
189
+ for p in live:
190
+ model = override or p["model"]
191
+ try:
192
+ text, err = (_call_anthropic if p["shape"] == "anthropic" else _call_openai)(
193
+ p, model, system, user, tmo)
194
+ except Exception as e: # noqa: BLE001
195
+ text, err = "", f"{p['name']} failed: {type(e).__name__}"
196
+ if err:
197
+ problems.append(err)
198
+ continue # ladder: a dead provider degrades to the next one
199
+ choice, reason = _parse(text, opts)
200
+ if not choice:
201
+ # The provider ANSWERED and declined (or answered unusably). That is a decision about
202
+ # this record, not a fault in the provider, so it does NOT fall through to a more
203
+ # expensive one β€” the card goes to a human, which is what the model just asked for.
204
+ return "", {"provider": p["name"], "model": model,
205
+ "problem": reason or "the model did not choose one of the stages"}
206
+ return choice, {"provider": p["name"], "model": model, "reason": reason}
207
+ return "", {"problem": "; ".join(problems)[:300] or "no provider answered"}
api/automation_engine.py CHANGED
The diff for this file is too large to render. See raw diff
 
api/main.py CHANGED
@@ -71,6 +71,9 @@ import routes_records # noqa: E402
71
  import routes_shares # noqa: E402 (wave 20 R10 β€” grants for views, folders and databases)
72
  import routes_uploads # noqa: E402 (wave 21 C5 β€” tabular preview for Select-from-file)
73
  import routes_tables # noqa: E402 (wave 18 C3-UT β€” user-created databases over the wire)
 
 
 
74
  from core import grid_events # noqa: E402
75
  from deps import Session, module_gate # noqa: E402
76
 
@@ -202,6 +205,24 @@ app.include_router(routes_platform_admin.router)
202
  app.include_router(routes_alerts.router)
203
  app.include_router(routes_shares.router)
204
  app.include_router(routes_uploads.router)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
 
207
  # --- DEPRECATED ALIASES (removed when S2's shell flips; kept so the current bundle keeps working)
 
71
  import routes_shares # noqa: E402 (wave 20 R10 β€” grants for views, folders and databases)
72
  import routes_uploads # noqa: E402 (wave 21 C5 β€” tabular preview for Select-from-file)
73
  import routes_tables # noqa: E402 (wave 18 C3-UT β€” user-created databases over the wire)
74
+ import routes_connectors # noqa: E402 (wave 23 C11 β€” the connectors directory; SESSION A's router)
75
+ import routes_forms # noqa: E402 (wave 23 C9 β€” the PUBLIC form door; SESSION D's router)
76
+ import routes_templates # noqa: E402 (wave 23 C12 β€” template apply doors; SESSION E's router)
77
  from core import grid_events # noqa: E402
78
  from deps import Session, module_gate # noqa: E402
79
 
 
205
  app.include_router(routes_alerts.router)
206
  app.include_router(routes_shares.router)
207
  app.include_router(routes_uploads.router)
208
+ # ⭐ WAVE 23 β€” THE THREE NEW ROUTERS. Mounted here, above the static catch-all at the bottom of this
209
+ # file, because `app.mount("/", _AppStatic(...), html=True)` swallows everything it is reached by:
210
+ # a router included AFTER it answers 404 forever while importing fine, type-checking fine and
211
+ # passing its own gate. That is the wave-20 declared-but-unmounted shape with a different cause.
212
+ #
213
+ # β›” ALL THREE EXISTED, COMPLETE AND GATED, WITH NO MOUNT until the close-out audit β€” three finished
214
+ # features that would have shipped dead. The workers each posted a mount ask and said they would
215
+ # signal "ready" first; C waited for a signal that never came while the files landed anyway. **The
216
+ # lesson is not "read the mailbox harder": `verify_api`'s enumeration is what caught it, so the
217
+ # control is that the enumeration must NAME every router in this file.**
218
+ app.include_router(routes_templates.router) # item 7 / C12 β€” template registry, session-gated
219
+ app.include_router(routes_connectors.router) # item 10 / C11 β€” the connectors directory
220
+ # ⚠ routes_forms is the FIRST NEW PUBLIC DOOR since the `_DEV_FIXTURES` scar (see :257 below). Its
221
+ # two paths are DELIBERATELY unauthenticated β€” a form is filled in by someone with no account β€” so
222
+ # it joins `/api/health`, the automation hook and the tick on the exempt list. It resolves a token
223
+ # by scanning tenants with a constant-time compare and answers a uniform 403, so a bad token cannot
224
+ # distinguish "no such form" from "not yours", and it never echoes a tenant, table or slug.
225
+ app.include_router(routes_forms.router) # item 8 / C9 β€” the PUBLIC form door
226
 
227
 
228
  # --- DEPRECATED ALIASES (removed when S2's shell flips; kept so the current bundle keeps working)
api/routes_automation.py CHANGED
@@ -26,6 +26,11 @@ router = APIRouter(prefix="/api/v1")
26
  # C5 (wave 22): the OAuth connector surface rides INSIDE this router β€” main.py belongs to no
27
  # session this wave, and this router is already mounted there. `/api/v1` + `/oauth/...`.
28
  router.include_router(routes_oauth.router)
 
 
 
 
 
29
 
30
  #: The registry key this surface carries (C-AUTONAV β€” A adds the row; the gate is live now, so
31
  #: the day the row lands the wall is already the one that was tested).
@@ -66,13 +71,27 @@ def _wire(defn, tenant):
66
  # client, for the same reason `cronPresets` does: the engine that RUNS the steps is the
67
  # only thing entitled to say what the steps are.
68
  "graph": engine.graph(defn),
 
 
 
 
 
 
 
69
  }
70
 
71
 
72
  def _triggers_vocab(session):
73
- """C3's server-owned trigger list: `[{key, label, ready, needs}]`, keys EXACTLY
74
- `engine.TRIGGER_KEYS`. `ready:false` + `needs` renders as a not-configured state β€” never a
75
- dead control, never a client-side union."""
 
 
 
 
 
 
 
76
  tick_on = _tick_state()["enabled"]
77
  g = oauth_connect.status(session.runtime, session.uname).get("google") or {}
78
  email_ready = bool(g.get("configured")) and bool(g.get("connected")) \
@@ -83,14 +102,49 @@ def _triggers_vocab(session):
83
  "manual": (True, ""),
84
  "schedule": (tick_on, "" if tick_on else "arm_tick"),
85
  "event_field": (True, ""),
 
86
  "record_created": (True, ""),
 
87
  "webhook": (True, ""),
88
  "email": (email_ready, email_needs),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  }
 
 
90
  out = []
91
  for k in engine.TRIGGER_KEYS:
92
- ready, needs = per[k]
 
 
 
 
 
 
93
  row = {"key": k, "label": engine.TRIGGER_LABELS[k], "ready": ready, "needs": needs,
 
94
  # A3(3): the connect affordance is SERVER-COMPOSED β€” the client never maps a
95
  # `needs` token to a route, so B's CONNECT_PROVIDERS shim deletes itself.
96
  "connect": None}
@@ -98,9 +152,24 @@ def _triggers_vocab(session):
98
  row["connect"] = {"provider": "google",
99
  "startUrl": "/api/v1/oauth/google/start"}
100
  out.append(row)
 
 
 
 
101
  return out
102
 
103
 
 
 
 
 
 
 
 
 
 
 
 
104
  def _tick_state():
105
  """⭐ WAVE 21 (C6 amendment A1) β€” can a SCHEDULE fire on this deployment?
106
 
@@ -127,9 +196,14 @@ def list_automations(session: Session = Depends(_GATE)):
127
  items = [_wire(d, session.tenant) for _, d in
128
  sorted(defs.items(), key=lambda kv: (kv[1].get("name") or "").lower())]
129
  return {"automations": items,
130
- "kinds": [{"key": "scrape_db", "label": "Web page to database"},
131
- {"key": "field_instagram", "label": "Instagram profile column"},
132
- {"key": "discover_instagram", "label": "Find Instagram profiles"}],
 
 
 
 
 
133
  "cronPresets": engine.CRON_PRESETS,
134
  # ⚠ A BOOLEAN, NEVER THE KEY. The surface needs to say "the paid rung is not
135
  # configured" honestly instead of offering a tier that will silently refuse β€” and
@@ -167,6 +241,28 @@ def list_automations(session: Session = Depends(_GATE)):
167
  "nullaryLaneOps": list(engine.LANE_NULLARY_OPS),
168
  "maxLanes": engine.MAX_LANES,
169
  "cardCap": engine.BOARD_CARD_CAP},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  # Wave 21 C6-A1: {"enabled": bool, "source": "in-process"|"external"|""} β€” see
171
  # `_tick_state` for why one boolean off AIOS_AUTOMATIONS alone would lie.
172
  "tick": _tick_state()}
@@ -190,6 +286,50 @@ def discover_estimate(body: dict = Body(default=None), session: Session = Depend
190
  _C8_MIGRATED = set()
191
 
192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  @router.get("/automations/tables")
194
  def automation_tables(session: Session = Depends(_GATE)):
195
  """The blank databases an automation can target, with their fields.
@@ -224,13 +364,17 @@ def automation_tables(session: Session = Depends(_GATE)):
224
  key=lambda kv: (kv[1].get("label") or "").lower()):
225
  if not user_tables.may_open(key, session.uname, session.admin, st=session.runtime):
226
  continue
227
- out.append({"key": key, "label": t.get("label") or key,
228
- "source": t.get("source") or "Blank",
229
- "rowCount": len(t.get("rows") or {}),
230
- "fields": [{"key": f.get("key"), "label": f.get("label"),
231
- "type": f.get("type") or "text",
232
- "automation": f.get("automation") or None}
233
- for f in (t.get("fields") or [])]})
 
 
 
 
234
  return {"tables": out}
235
 
236
 
@@ -244,6 +388,10 @@ def get_automation(auto_id: str, session: Session = Depends(_GATE)):
244
 
245
  @router.post("/automations")
246
  def create_automation(body: dict = Body(default=None), session: Session = Depends(_GATE)):
 
 
 
 
247
  if not session.runtime.available():
248
  raise err(503, "store_unavailable", "the tenant store is unavailable β€” nothing was saved")
249
  defn, error = engine.create(session.runtime, body or {}, username=session.uname)
@@ -357,28 +505,52 @@ def toggle_automation_node(auto_id: str, node_id: str, session: Session = Depend
357
 
358
 
359
  @router.post("/automations/{auto_id}/hook/{token}")
360
- def automation_hook(auto_id: str, token: str):
361
  """C3's webhook trigger β€” the tick-endpoint pattern one level down: unauthenticated BY
362
  DESIGN (the external caller has no cookie), gated on a per-automation token minted when the
363
  trigger was configured, constant-time compared. The tenant is FOUND by the (id, token)
364
  pair β€” a wrong token answers 403 for every tenant, so the route confirms nothing about
365
- which slugs exist."""
 
 
 
 
 
 
 
 
 
 
 
 
 
366
  from harness import runtime as _rt
367
 
368
- last = (404, {"error": "unknown_automation",
369
- "message": "no automation with that id and token"})
370
- for slug in _rt.known_tenants():
371
- try:
372
- rt = _rt.get_runtime(slug)
373
- except Exception: # noqa: BLE001
374
- continue
375
- status, payload = engine.hook_fire(rt, slug, auto_id, token)
376
- if status == 200:
377
- return payload
378
- if status != 404:
379
- last = (status, payload)
380
- raise err(last[0], str(last[1].get("error") or "refused"),
381
- str(last[1].get("message") or "refused"))
 
 
 
 
 
 
 
 
 
 
 
382
 
383
 
384
  @router.post("/automations/tick")
 
26
  # C5 (wave 22): the OAuth connector surface rides INSIDE this router β€” main.py belongs to no
27
  # session this wave, and this router is already mounted there. `/api/v1` + `/oauth/...`.
28
  router.include_router(routes_oauth.router)
29
+ # ⭐ WAVE 23 (C11): the connectors directory rides this router for the same reason the OAuth
30
+ # routes do β€” it is mounted already, so E's page needs no main.py change to reach it. (C still
31
+ # owns main.py; this avoids an unnecessary ask across a fence.)
32
+ import routes_connectors # noqa: E402
33
+ router.include_router(routes_connectors.router)
34
 
35
  #: The registry key this surface carries (C-AUTONAV β€” A adds the row; the gate is live now, so
36
  #: the day the row lands the wall is already the one that was tested).
 
71
  # client, for the same reason `cronPresets` does: the engine that RUNS the steps is the
72
  # only thing entitled to say what the steps are.
73
  "graph": engine.graph(defn),
74
+ # ⭐ WAVE 23 (C4/C5) β€” THE BUILDER'S OWN STATE, and its absence here was a silent-drop
75
+ # bug caught in review rather than by a gate: `flow` was stored, patchable and validated,
76
+ # but never sent back. B would have saved a flow through PATCH, got a 200, and watched
77
+ # every action vanish on reload β€” the classic "it didn't save" with nothing red anywhere.
78
+ # Defaulted rather than conditional so a pre-wave definition reads as an empty flow with
79
+ # a terminal ending instead of `undefined`, which the client would have to special-case.
80
+ "flow": defn.get("flow") or {"actions": [], "ending": {"mode": "terminal"}},
81
  }
82
 
83
 
84
  def _triggers_vocab(session):
85
+ """C3's server-owned trigger list: `[{key, label, ready, needs, planned}]`, keys EXACTLY
86
+ `engine.TRIGGER_KEYS` + `engine.TRIGGER_PLANNED`. `ready:false` + `needs` renders as a
87
+ not-configured state β€” never a dead control, never a client-side union.
88
+
89
+ ⭐ WAVE 23 (R2): the list is the WHOLE Airtable-parity vocabulary, and the two triggers we
90
+ have not built ride it with `planned: true`. That is the honest version of "show all, wire
91
+ eight": the picker paints them faded with a reason instead of a shorter list that quietly
92
+ implies the missing ones do not exist. `clean_trigger` refuses them, so the faded state is
93
+ enforced at the door and not merely in the client's `disabled` attribute.
94
+ """
95
  tick_on = _tick_state()["enabled"]
96
  g = oauth_connect.status(session.runtime, session.uname).get("google") or {}
97
  email_ready = bool(g.get("configured")) and bool(g.get("connected")) \
 
102
  "manual": (True, ""),
103
  "schedule": (tick_on, "" if tick_on else "arm_tick"),
104
  "event_field": (True, ""),
105
+ "record_updated": (True, ""),
106
  "record_created": (True, ""),
107
+ "enters_view": (True, ""),
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}
 
152
  row["connect"] = {"provider": "google",
153
  "startUrl": "/api/v1/oauth/google/start"}
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
 
162
+ def _ai_ready():
163
+ """Can an AI review actually decide on this deployment? (C6/R14.) A boolean, never the
164
+ provider list and never a key β€” the surface needs to say "not configured" honestly, and that
165
+ needs exactly one bit."""
166
+ try:
167
+ import ai_review
168
+ return bool(ai_review.configured())
169
+ except Exception: # noqa: BLE001
170
+ return False
171
+
172
+
173
  def _tick_state():
174
  """⭐ WAVE 21 (C6 amendment A1) β€” can a SCHEDULE fire on this deployment?
175
 
 
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
 
241
  "nullaryLaneOps": list(engine.LANE_NULLARY_OPS),
242
  "maxLanes": engine.MAX_LANES,
243
  "cardCap": engine.BOARD_CARD_CAP},
244
+ # ⭐ WAVE 23 C4 (R3) β€” the ACTION MENU, including what we have not built. Each row
245
+ # carries `ready`, so B paints "Send email" and "Run script" faded with the server's
246
+ # own reason instead of omitting them β€” the owner asked for Airtable's full menu, and
247
+ # a shorter list would imply those actions do not exist. `clean_actions` REFUSES an
248
+ # unready kind, so the faded state is a wall rather than a styling choice.
249
+ "actionsCatalog": engine.action_catalog(),
250
+ # The builder's own vocabulary: how deep a condition tree may nest, how deep groups
251
+ # may nest, and the ceilings. B reads these instead of hard-coding the same numbers
252
+ # into its "+ Add condition" affordance.
253
+ "flow": {"condOps": list(engine.LANE_OPS),
254
+ "nullaryCondOps": list(engine.LANE_NULLARY_OPS),
255
+ "maxCondDepth": engine.MAX_COND_DEPTH,
256
+ "maxCondChildren": engine.MAX_COND_CHILDREN,
257
+ "maxGroupDepth": engine.MAX_GROUP_DEPTH,
258
+ "maxActions": engine.MAX_ACTIONS,
259
+ "endingModes": list(engine.ENDING_MODES),
260
+ "maxResetHours": engine.MAX_RESET_HOURS,
261
+ "reviewDeciders": list(engine.REVIEW_DECIDERS),
262
+ # Honest, per-deployment: with no LLM key configured the AI-review option
263
+ # renders as not-configured rather than as a control that silently holds
264
+ # every card for a human (C6's fail-closed path, made visible).
265
+ "aiReady": _ai_ready()},
266
  # Wave 21 C6-A1: {"enabled": bool, "source": "in-process"|"external"|""} β€” see
267
  # `_tick_state` for why one boolean off AIOS_AUTOMATIONS alone would lie.
268
  "tick": _tick_state()}
 
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
 
 
388
 
389
  @router.post("/automations")
390
  def create_automation(body: dict = Body(default=None), session: Session = Depends(_GATE)):
391
+ """Create an automation. ⭐ WAVE 23 (C2): the body may carry
392
+ `target: {mode: "existing"|"new"|"automated", table?, label?}` β€” the wizard's FIRST question,
393
+ answered before the kind. `new` mints the blank database in the same call, so the automation
394
+ is never saved pointing at a table that does not exist yet."""
395
  if not session.runtime.available():
396
  raise err(503, "store_unavailable", "the tenant store is unavailable β€” nothing was saved")
397
  defn, error = engine.create(session.runtime, body or {}, username=session.uname)
 
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_connectors.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """THE CONNECTORS DIRECTORY (wave 23, contract C11 / owner ruling R8).
2
+
3
+ ⭐ WHAT THE OWNER ASKED FOR, verbatim: *"Build a connector module where it stores everything… BUT
4
+ if its not yet integrated make it faded grey or something so i can use it as a to-do list for
5
+ integrations."* So this endpoint deliberately answers with things we have NOT built. A directory
6
+ that listed only working connectors would be honest about each row and dishonest about the shape
7
+ of the product β€” the owner wants to see the map, including the empty parts.
8
+
9
+ β›” THE ROW SET IS COMPOSED HERE, ONCE, FROM THE REGISTRIES THAT ALREADY EXIST β€” the OAuth
10
+ provider registry (`oauth_connect.PROVIDERS`), the keychain's entry types, the automation source
11
+ registry, and the env-configured built-ins. It is NOT a hand-written list of cards. That matters
12
+ because the alternative rots in a specific way: a provider gets wired up somewhere and the
13
+ directory keeps calling it "planned" for a wave or two, which is exactly the misinformation this
14
+ surface exists to prevent. The only hand-written part is `PLANNED` β€” the things that have no
15
+ registry entry anywhere yet, which is precisely what "not yet integrated" means.
16
+
17
+ ⚠ STATE IS PER-READER. `connected` is a fact about THIS user for a per-user credential (OAuth
18
+ slots are per-user by R7) and about the tenant for a shared one (Odoo, Bright Data). A directory
19
+ that reported another user's Gmail as "connected" would be both wrong and a small disclosure.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import os
24
+
25
+ from fastapi import APIRouter, Depends
26
+
27
+ import oauth_connect
28
+ from deps import Session, require_session
29
+
30
+ # β›” THE PREFIX IS LOAD-BEARING AND IT WAS MISSING (found at the wave-23 close-out audit).
31
+ # This router declared a bare `APIRouter()`, so its one path was served at `/connectors/directory`
32
+ # while `ConnectorsPage.tsx` fetches `${API_V1}/connectors/directory` β€” the directory would have
33
+ # 404'd in production with every gate green. Every other router in this package self-declares
34
+ # `prefix="/api/v1"`; this was the only one that did not.
35
+ #
36
+ # ⚠ AND THE WIRING GATE COULD NOT SEE IT. `verify_wiring`'s W23-W4 row matches the SERVER side on
37
+ # the substring `connectors/directory` and the CLIENT side on `${API_V1}/connectors/directory` β€”
38
+ # both matched, both sides "wired", prefixes disagreeing. A cross-fence row that greps each side
39
+ # independently proves the two files mention the same path SEGMENT, never that they agree on the
40
+ # same URL. `verify_api` now asserts the prefix on every mounted router instead.
41
+ router = APIRouter(prefix="/api/v1")
42
+
43
+ #: The to-do list (R8). Order is the owner's reading order, not alphabetical: the things most
44
+ #: likely to come next first. `queue` mirrors the standing provider queue in wave22-split C5-A2
45
+ #: so the two cannot drift into disagreeing about what is coming.
46
+ PLANNED = [
47
+ {"key": "slack", "label": "Slack", "kind": "oauth",
48
+ "desc": "Send messages into a channel when an automation reaches a step."},
49
+ {"key": "airtable", "label": "Airtable", "kind": "oauth",
50
+ "desc": "Import an existing base as a database."},
51
+ {"key": "outlook", "label": "Microsoft Outlook", "kind": "oauth",
52
+ "desc": "The Outlook half of the email trigger."},
53
+ {"key": "quickbooks", "label": "QuickBooks", "kind": "oauth",
54
+ "desc": "Accounting actuals beside the Odoo sales data."},
55
+ {"key": "xero", "label": "Xero", "kind": "oauth",
56
+ "desc": "Accounting actuals for tenants who do not use QuickBooks."},
57
+ {"key": "google_sheets", "label": "Google Sheets", "kind": "oauth",
58
+ "desc": "Read a sheet as a database; the Google connection already exists."},
59
+ {"key": "google_drive", "label": "Google Drive", "kind": "oauth",
60
+ "desc": "Attach files from Drive to records."},
61
+ {"key": "google_calendar", "label": "Google Calendar", "kind": "oauth",
62
+ "desc": "Turn dated records into calendar entries."},
63
+ {"key": "tiktok", "label": "TikTok", "kind": "token",
64
+ "desc": "The second social source beside Instagram."},
65
+ {"key": "meta", "label": "WhatsApp and Instagram (Meta)", "kind": "oauth",
66
+ "desc": "Blocked on Meta business verification; Instagram data comes via Bright Data."},
67
+ ]
68
+
69
+ #: Token connectors an admin can wire up TODAY by pasting a key β€” no OAuth client, no app review.
70
+ TOKEN_CONNECTORS = [
71
+ {"key": "stripe", "label": "Stripe", "entry": "stripe",
72
+ "desc": "Payments and payouts against your customer records.",
73
+ "hint": "Create a restricted key with read access in the Stripe dashboard."},
74
+ {"key": "shopify", "label": "Shopify", "entry": "shopify",
75
+ "desc": "Orders and products from a Shopify storefront.",
76
+ "hint": "Create a custom app in your store admin and copy its Admin API token."},
77
+ ]
78
+
79
+
80
+ def _entry_types(rt):
81
+ """Which keychain entry types this tenant has actually stored. One read, and it never raises
82
+ β€” a LOCKED keychain must degrade to "nothing connected", never to a 500 on a page whose whole
83
+ job is to tell you what is connected."""
84
+ try:
85
+ import core.keychain as kc
86
+ return {str(e.get("type") or "") for e in (kc.list_entries(rt) or [])}
87
+ except Exception: # noqa: BLE001
88
+ return set()
89
+
90
+
91
+ def directory(rt, uname, is_admin=False):
92
+ """The composed row set. Pure over the session, so the gate drives it without a request."""
93
+ rows = []
94
+ have = _entry_types(rt)
95
+
96
+ # --- Odoo: the reference connector. Env credentials are tenant #0's only (the R3 rule), so
97
+ # a stored keychain entry is what makes it connected for anybody else.
98
+ rows.append({
99
+ "key": "odoo", "label": "Odoo", "kind": "builtin",
100
+ "desc": "Sales, invoices, products and customers from your Odoo ERP.",
101
+ "state": "connected" if ("odoo" in have or os.environ.get("ODOO_URL")) else "available",
102
+ "manage": "keychain" if is_admin else "",
103
+ })
104
+
105
+ # --- OAuth providers, straight off the registry (so a new entry appears here for free).
106
+ st = oauth_connect.status(rt, uname)
107
+ for slug, meta in oauth_connect.PROVIDERS.items():
108
+ row_st = st.get(slug) or {}
109
+ rows.append({
110
+ "key": slug, "label": meta.get("label") or slug.title(), "kind": "oauth",
111
+ "desc": "Gmail for the email trigger; the same connection unlocks Sheets, Drive "
112
+ "and Calendar later." if slug == "google" else "",
113
+ # THREE distinct states, and the distinction is the point: a provider nobody has
114
+ # configured on this deployment is not the same as one this user has not connected,
115
+ # and until now both rendered identically (the C11 status() gap).
116
+ "state": ("connected" if row_st.get("connected") and not row_st.get("reconnect")
117
+ else "reconnect" if row_st.get("reconnect")
118
+ else "available" if row_st.get("configured")
119
+ else "unconfigured"),
120
+ "connectedAs": row_st.get("email") or "",
121
+ "startUrl": f"/api/v1/oauth/{slug}/start",
122
+ "manage": "oauth",
123
+ "needs": "" if row_st.get("configured") else "the owner registers the client",
124
+ })
125
+
126
+ # --- Token connectors (R8): connectable today, and honest that data flows arrive later.
127
+ for t in TOKEN_CONNECTORS:
128
+ rows.append({
129
+ "key": t["key"], "label": t["label"], "kind": "token", "desc": t["desc"],
130
+ "hint": t["hint"],
131
+ "state": "connected" if t["entry"] in have else "available",
132
+ "manage": "keychain" if is_admin else "",
133
+ # Said once, on the row, rather than in a paragraph somewhere (R13): storing the key
134
+ # is real and useful, and it is not the same as the data being on screen.
135
+ "note": "Storing the key connects the account; reading its data lands in a later "
136
+ "release.",
137
+ })
138
+
139
+ # --- Built-ins that are configuration, not credentials.
140
+ import automation_engine as _eng
141
+ rows.append({
142
+ "key": "brightdata", "label": "Bright Data", "kind": "builtin",
143
+ "desc": "Instagram profile and post capture for the discovery automations.",
144
+ "state": "connected" if _eng.bd_ready() else "unconfigured",
145
+ "needs": "" if _eng.bd_ready() else "AIOS_BRIGHTDATA_KEY is not set on this deployment",
146
+ "manage": "",
147
+ })
148
+ rows.append({
149
+ "key": "webhooks", "label": "Webhooks", "kind": "builtin",
150
+ "desc": "Let another system start an automation by calling a URL.",
151
+ "state": "connected", "manage": "automation",
152
+ })
153
+
154
+ for p in PLANNED:
155
+ rows.append({**p, "state": "planned",
156
+ "needs": "not built yet", "manage": ""})
157
+ return rows
158
+
159
+
160
+ @router.get("/connectors/directory")
161
+ def connectors_directory(session: Session = Depends(require_session)):
162
+ """C11: every connector this platform knows about, with its state for THIS reader.
163
+
164
+ Session-gated rather than admin-gated on purpose: a non-admin should be able to see what the
165
+ workspace is connected to (and connect their OWN per-user accounts, which is the whole point
166
+ of R7's per-user slots). `manage` is what carries admin-ness β€” it is empty for a non-admin,
167
+ so the client renders the card without an action rather than offering a door that 403s.
168
+ """
169
+ # ⚠ `session.admin`, NOT `is_admin`. A `getattr(session, "is_admin", False)` here reads as
170
+ # careful and is silently False for every admin on earth β€” the manage actions would simply
171
+ # never appear, with nothing to catch it. Attribute name checked against `deps.Session`.
172
+ rows = directory(session.runtime, session.uname, bool(session.admin))
173
+ return {"connectors": rows,
174
+ "counts": {"connected": sum(1 for r in rows if r["state"] == "connected"),
175
+ "available": sum(1 for r in rows if r["state"] == "available"),
176
+ "planned": sum(1 for r in rows if r["state"] == "planned")}}
api/routes_forms.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """routes_forms.py β€” ⭐ wave-23 item 8 (contract W23-C9): THE PUBLIC FORM DOOR.
2
+
3
+ β›” BOTH ROUTES HERE ARE UNAUTHENTICATED, AND THAT IS THE POINT. A form link goes to somebody who
4
+ has no account β€” a supplier, a lead, a warehouse hand with a phone β€” so `Depends(require_session)`
5
+ is exactly what must NOT be on them. Everything that would normally be decided by a session is
6
+ therefore decided by the TOKEN, and this file is the whole of that decision:
7
+
8
+ * the token is minted server-side (`secrets.token_urlsafe(24)` β€” 192 bits) and stored on ONE
9
+ view. There is no enumeration to brute-force and no id in the URL to increment.
10
+ * a wrong token answers ONE thing for every tenant, every table and every typo: 403
11
+ `bad_form_token`. It never leaks whether a form exists, whether a tenant exists, or which of
12
+ the two you got wrong β€” the automation-hook pattern (`routes_automation.py:359-381`) one
13
+ level up, because a public door that answers 404-vs-403 is an oracle.
14
+ * the payload a valid token buys is the SMALLEST thing that can render a form: title,
15
+ description, submit label, and the fields with their labels, types and options. No tenant
16
+ slug, no table key, no row count, no field key that is not on the form, no username.
17
+
18
+ WHAT AN ATTACKER WITH A VALID TOKEN CAN DO, stated plainly because it is the honest boundary:
19
+ append rows to ONE user table, up to the per-token daily cap, with values that pass this file's
20
+ validation. They cannot read a row, cannot see any other field, cannot reach another table, and
21
+ cannot cause an automation to run as anybody (`form_fired` is a HUMAN door by A's design β€” see
22
+ its contract note in the split doc).
23
+
24
+ ⚠ THE `_DEV_FIXTURES` AUDIT (main.py:257-295) applied to this router, because that scar is
25
+ exactly "a thing became publicly reachable and nobody looked": the only bytes these routes can
26
+ return are the ones assembled in `_public_form` below, field by field. There is no passthrough of
27
+ a stored dict anywhere in this file β€” every response is built from named keys.
28
+
29
+ ⚠ PROTECTIONS ARE IN-PROCESS AND THEREFORE PER WORKER. One Space process today, so the sliding
30
+ window is real; the day there are two, both halves of a limit are halved-per-worker rather than
31
+ bypassed. Booked as DEBT rather than described as a guarantee β€” a rate limit that quietly stops
32
+ being one is worse than none.
33
+ """
34
+ import hmac
35
+ import secrets
36
+ import time
37
+
38
+ from fastapi import APIRouter, Request
39
+
40
+ from deps import err
41
+
42
+ router = APIRouter(prefix="/api/v1")
43
+
44
+ #: The mint. 24 bytes url-safe = 32 characters, 192 bits β€” the same shape the automation hook's
45
+ #: per-automation token uses, so there is ONE token strength in the product rather than two.
46
+ TOKEN_BYTES = 24
47
+
48
+ #: The honeypot's field name. It is rendered by `FormPublic.tsx` as a real input, visually
49
+ #: hidden and `autocomplete="off"` + `tabIndex={-1}` β€” a human never sees it and a keyboard user
50
+ #: never lands on it, so anything that fills it is a script walking the DOM. ⚠ Named for
51
+ #: something a bot WANTS to fill; a field called `honeypot` is one `if` away from being skipped.
52
+ HONEYPOT_FIELD = "website_url"
53
+
54
+ #: v1 request protections (contract C9). Per IP and per token respectively.
55
+ RATE_WINDOW_S = 60
56
+ RATE_PER_WINDOW = 30
57
+ DAILY_PER_TOKEN = 500
58
+ MAX_BODY_BYTES = 16 * 1024
59
+ #: One text answer's ceiling. Generous for a paragraph, far below the body cap, and it exists so
60
+ #: a single 15 KB answer cannot be smuggled past a body check that only measures the whole.
61
+ MAX_VALUE_LEN = 4000
62
+
63
+ #: `{ip: [timestamps]}` and `{token: (day, count)}`. Module-level and unbounded-by-design within
64
+ #: a day: an IP list is pruned to the window on every touch, and the token map holds one small
65
+ #: tuple per form that was submitted to today.
66
+ _HITS: dict = {}
67
+ _DAILY: dict = {}
68
+
69
+
70
+ def _rate_ok(ip: str, now: float) -> bool:
71
+ """A sliding window, not a fixed bucket. A fixed one lets a caller spend the whole allowance
72
+ at 11:59:59 and the whole next allowance at 12:00:00 β€” double the rate at the boundary,
73
+ which is the moment a script is most likely to be hammering."""
74
+ seen = [t for t in _HITS.get(ip, ()) if now - t < RATE_WINDOW_S]
75
+ seen.append(now)
76
+ _HITS[ip] = seen
77
+ # ⚠ Prune the WHOLE map occasionally, or a process that has served a million IPs holds a
78
+ # million lists forever. Cheap and amortised: only when the map is already large.
79
+ if len(_HITS) > 4096:
80
+ for k in [k for k, v in _HITS.items() if not v or now - v[-1] > RATE_WINDOW_S]:
81
+ _HITS.pop(k, None)
82
+ return len(seen) <= RATE_PER_WINDOW
83
+
84
+
85
+ def _daily_ok(token: str, now: float) -> bool:
86
+ day = int(now // 86400)
87
+ d, n = _DAILY.get(token, (day, 0))
88
+ if d != day:
89
+ d, n = day, 0
90
+ n += 1
91
+ _DAILY[token] = (d, n)
92
+ return n <= DAILY_PER_TOKEN
93
+
94
+
95
+ def _client_ip(request: Request) -> str:
96
+ """⚠ `X-Forwarded-For`'s FIRST entry, and only because this app runs behind exactly one
97
+ proxy (the HF Space router). It is caller-controlled, so it is a rate-limit key and NOTHING
98
+ else β€” never a permission input. Falls back to the socket peer."""
99
+ fwd = request.headers.get("x-forwarded-for") or ""
100
+ first = fwd.split(",")[0].strip()
101
+ return first or (request.client.host if request.client else "?")
102
+
103
+
104
+ def _refuse():
105
+ """THE ONE REFUSAL. Every failure to resolve a token answers this β€” wrong token, disabled
106
+ form, deleted view, deleted table, a tenant whose store is down. Callers must not branch a
107
+ more specific message out of it: the difference between "no such form" and "that form is
108
+ disabled" tells an enumerator which tokens are real."""
109
+ return err(403, "bad_form_token", "that form link is not valid")
110
+
111
+
112
+ def _same(a: str, b: str) -> bool:
113
+ """Constant-time. A `==` here leaks a token's prefix through timing, one character at a
114
+ time, which is the whole reason the automation hook compares this way too."""
115
+ return hmac.compare_digest(str(a or ""), str(b or ""))
116
+
117
+
118
+ # --- resolution ------------------------------------------------------------------------------
119
+ #
120
+ # ⚠ A FULL SCAN, deliberately, and its cost is BOOKED (DEBT β€” "the form-token index"). The
121
+ # automation hook resolves the same way (`routes_automation.py:370` walks `known_tenants()`)
122
+ # because the alternative — a global token→tenant map — is a second index that has to be written
123
+ # on every mint, regenerate, view delete and table delete, and an index that misses one of those
124
+ # is a live form that answers 403 or, far worse, a dead token that still resolves. With one
125
+ # process, a handful of tenants and a 30/min ceiling in front of it, the scan is affordable; the
126
+ # index becomes worth its risk when either number grows.
127
+
128
+
129
+ def _iter_form_views(rt):
130
+ """Yield `(table_key, view_id, form_spec)` for every form-enabled view in one tenant.
131
+
132
+ A form spec lives at `view.config.display.form` and carries the token β€” see W23-C9. Reads
133
+ only; nothing here writes, so a malformed stratum is skipped rather than repaired.
134
+ """
135
+ import core.user_tables as user_tables
136
+
137
+ try:
138
+ tables = user_tables.all_tables(st=rt) or {}
139
+ except Exception: # noqa: BLE001
140
+ return
141
+ for key in list(tables):
142
+ try:
143
+ bucket = rt.get(f"{key}_table_workspace") or {}
144
+ except Exception: # noqa: BLE001
145
+ continue
146
+ if not isinstance(bucket, dict):
147
+ continue
148
+ for ws in bucket.values():
149
+ if not isinstance(ws, dict):
150
+ continue
151
+ for view_id, view in (ws.get("views") or {}).items():
152
+ if not isinstance(view, dict):
153
+ continue
154
+ display = ((view.get("config") or {}).get("display") or {})
155
+ spec = display.get("form")
156
+ if isinstance(spec, dict) and spec.get("token"):
157
+ yield str(key), str(view_id), spec
158
+
159
+
160
+ def _resolve(token: str):
161
+ """`(runtime, tenant_slug, table_key, form_spec)` for a token, or None.
162
+
163
+ ⚠ THE LOOP DOES NOT SHORT-CIRCUIT ON THE TENANT, only on the match. A `break` on the first
164
+ tenant whose store answered would make "the third tenant's form" depend on the first two
165
+ being healthy, and a form that stops working because somebody else's store blipped is the
166
+ kind of failure nobody can reproduce.
167
+ """
168
+ from harness import runtime as _rt
169
+
170
+ if not token or len(token) < 16:
171
+ return None
172
+ for slug in _rt.known_tenants():
173
+ try:
174
+ rt = _rt.get_runtime(slug)
175
+ except Exception: # noqa: BLE001
176
+ continue
177
+ for table_key, _view_id, spec in _iter_form_views(rt):
178
+ if _same(str(spec.get("token") or ""), token):
179
+ return rt, slug, table_key, spec
180
+ return None
181
+
182
+
183
+ # --- the public shape -------------------------------------------------------------------------
184
+
185
+
186
+ def _public_form(rt, table_key: str, spec: dict) -> dict:
187
+ """The ONLY bytes a valid token buys. Built key by key β€” there is no `**stored` anywhere in
188
+ this function, which is what makes "nothing else leaks" a property of the code rather than a
189
+ promise about what happens to be in the bag today.
190
+
191
+ ⚠ The field ORDER is the form's own (`spec['fields']`), not the table's: the builder let
192
+ somebody arrange these questions, and re-deriving the order from the schema would silently
193
+ rearrange a form every time a column was added.
194
+ """
195
+ import core.user_tables as user_tables
196
+
197
+ defn = user_tables.get(table_key, st=rt) or {}
198
+ by_key = {f.get("key"): f for f in (defn.get("fields") or []) if isinstance(f, dict)}
199
+ required = {str(k) for k in (spec.get("required") or [])}
200
+ out = []
201
+ for key in (spec.get("fields") or []):
202
+ f = by_key.get(str(key))
203
+ # A field deleted since the form was built is DROPPED, never rendered as a dead input β€”
204
+ # and never an error: losing one column must not take a live form offline.
205
+ if not f or f.get("source") not in (None, "overlay"):
206
+ continue
207
+ row = {"key": str(f.get("key")), "label": str(f.get("label") or f.get("key")),
208
+ "type": str(f.get("type") or "text"), "required": str(key) in required}
209
+ options = f.get("options")
210
+ if isinstance(options, list) and options:
211
+ row["options"] = [str(o) for o in options][:200]
212
+ if f.get("type") == "rating":
213
+ row["max"] = int(f.get("max") or 5)
214
+ out.append(row)
215
+ return {
216
+ "title": str(spec.get("title") or "")[:200],
217
+ "desc": str(spec.get("desc") or "")[:1000],
218
+ "submitLabel": str(spec.get("submitLabel") or "")[:60] or "Submit",
219
+ "fields": out,
220
+ "honeypot": HONEYPOT_FIELD,
221
+ }
222
+
223
+
224
+ # --- validation -------------------------------------------------------------------------------
225
+
226
+
227
+ def _clean_values(fields: list, raw: dict):
228
+ """`(values, error_sentence)` β€” REFUSE, NEVER COERCE (C9, and the engine's own law).
229
+
230
+ The temptation with a public form is to be forgiving: read "12 units" as 12, "yes" as
231
+ checked, "tomorrow" as a date. Every one of those writes a number nobody typed into somebody
232
+ else's database, and the person who submitted the form is not there to see it happen. So a
233
+ value that does not answer its own field's question is refused with a sentence naming the
234
+ FIELD LABEL β€” the only name the submitter has ever seen.
235
+ """
236
+ out = {}
237
+ for f in fields:
238
+ key, label, ftype = f["key"], f["label"], f["type"]
239
+ v = raw.get(key)
240
+ text = "" if v is None else str(v)
241
+ text = text.strip() if isinstance(v, str) else text
242
+ if len(text) > MAX_VALUE_LEN:
243
+ return None, f"β€œ{label}” is too long β€” {MAX_VALUE_LEN} characters at most."
244
+ if text == "":
245
+ if f.get("required"):
246
+ return None, f"β€œ{label}” is required."
247
+ continue
248
+ if ftype in ("int", "currency", "pct", "rating"):
249
+ try:
250
+ num = float(text.replace(",", ""))
251
+ except ValueError:
252
+ return None, f"β€œ{label}” must be a number."
253
+ if ftype == "rating":
254
+ top = int(f.get("max") or 5)
255
+ if not (1 <= num <= top) or num != int(num):
256
+ return None, f"β€œ{label}” must be a whole number from 1 to {top}."
257
+ text = str(int(num)) if ftype in ("int", "rating") else str(num)
258
+ elif ftype == "checkbox":
259
+ # The storage contract is '1' or blank (types.ts). Anything a checkbox can actually
260
+ # send is one of these four spellings; anything else is not a checkbox answer.
261
+ if text.lower() not in ("1", "true", "on", "yes", "0", "false", "off", "no"):
262
+ return None, f"β€œ{label}” must be checked or unchecked."
263
+ text = "1" if text.lower() in ("1", "true", "on", "yes") else ""
264
+ elif ftype in ("select", "status"):
265
+ options = f.get("options") or []
266
+ if options and text not in options:
267
+ return None, f"β€œ{label}” must be one of the listed choices."
268
+ elif ftype == "multiselect":
269
+ options = f.get("options") or []
270
+ parts = [p.strip() for p in text.split(",") if p.strip()]
271
+ if options and any(p not in options for p in parts):
272
+ return None, f"β€œ{label}” must be chosen from the listed choices."
273
+ text = ", ".join(parts)
274
+ elif ftype == "date":
275
+ # ISO only. A public form has no timezone, no locale and no user to ask, so
276
+ # "03/04/2026" is genuinely ambiguous and guessing it wrong is a silent data error.
277
+ if len(text) != 10 or text[4] != "-" or text[7] != "-":
278
+ return None, f"β€œ{label}” must be a date."
279
+ try:
280
+ time.strptime(text, "%Y-%m-%d")
281
+ except ValueError:
282
+ return None, f"β€œ{label}” must be a real date."
283
+ elif ftype == "email":
284
+ if "@" not in text or text.startswith("@") or text.endswith("@"):
285
+ return None, f"β€œ{label}” must be an email address."
286
+ out[key] = text
287
+ return out, ""
288
+
289
+
290
+ # --- the routes -------------------------------------------------------------------------------
291
+
292
+
293
+ @router.get("/forms/{token}")
294
+ def get_form(token: str, request: Request):
295
+ """Render-time payload for a public form. Rate-limited like the POST: an unauthenticated GET
296
+ that walks every tenant's workspace is the cheapest way to make this process do work."""
297
+ if not _rate_ok(_client_ip(request), time.time()):
298
+ raise err(429, "too_many_requests", "too many requests β€” wait a moment and try again")
299
+ found = _resolve(token)
300
+ if not found:
301
+ raise _refuse()
302
+ rt, _slug, table_key, spec = found
303
+ return _public_form(rt, table_key, spec)
304
+
305
+
306
+ async def _bounded_body(request: Request) -> dict:
307
+ """The request body, READ WITH A BOUND β€” never `Body(...)`, never `await request.body()`.
308
+
309
+ β›” THE FIRST VERSION OF THIS ROUTE TOOK `body: dict = Body(default=None)` AND ITS 16 KB CAP
310
+ CAPPED NOTHING. FastAPI reads and JSON-parses the WHOLE body before the handler's first line
311
+ runs, so a `content-length` check inside the handler is inspected after the allocation it
312
+ claims to prevent β€” and `content-length` is caller-supplied anyway, so omitting it or sending
313
+ chunked left no bound at all. On the one unauthenticated write path in the product.
314
+
315
+ ⚠ It was GREEN, and that is the part worth remembering: the gate leg set the header itself,
316
+ so it only ever exercised the honest path. A protection whose test supplies the very value it
317
+ is protecting against is testing its own politeness.
318
+
319
+ Streaming with a running total is the actual bound: the read STOPS at the ceiling rather than
320
+ discovering afterwards that it should have.
321
+ """
322
+ size, chunks = 0, []
323
+ async for chunk in request.stream():
324
+ size += len(chunk)
325
+ if size > MAX_BODY_BYTES:
326
+ raise err(413, "body_too_large", "that submission is too large")
327
+ chunks.append(chunk)
328
+ import json
329
+ try:
330
+ parsed = json.loads(b"".join(chunks) or b"{}")
331
+ except ValueError:
332
+ raise err(400, "no_values", "that submission could not be read")
333
+ return parsed if isinstance(parsed, dict) else {}
334
+
335
+
336
+ @router.post("/forms/{token}")
337
+ async def submit_form(token: str, request: Request):
338
+ """One submission: validate, append the row, fire `form_submitted`.
339
+
340
+ ⚠ THE ORDER IS LOAD-BEARING. The row is written FIRST and the trigger fired second, off the
341
+ id the write returned β€” so an automation can never run against a record that does not exist,
342
+ and a trigger that raises cannot cost the submitter the answer they just typed.
343
+ """
344
+ now = time.time()
345
+ if not _rate_ok(_client_ip(request), now):
346
+ raise err(429, "too_many_requests", "too many requests β€” wait a moment and try again")
347
+ body = await _bounded_body(request)
348
+ found = _resolve(token)
349
+ if not found:
350
+ raise _refuse()
351
+ rt, _slug, table_key, spec = found
352
+
353
+ values = (body or {}).get("values")
354
+ if not isinstance(values, dict):
355
+ raise err(400, "no_values", "that submission was empty")
356
+
357
+ # β›” THE HONEYPOT ANSWERS 200 AND WRITES NOTHING. A 403 would tell the script it was
358
+ # detected, and the next version of it simply stops filling the field. A success it can
359
+ # never verify is the only answer that costs the operator nothing to give.
360
+ if str(values.get(HONEYPOT_FIELD) or "").strip():
361
+ return {"ok": True}
362
+
363
+ form = _public_form(rt, table_key, spec)
364
+ if not form["fields"]:
365
+ raise _refuse()
366
+ clean, problem = _clean_values(form["fields"], values)
367
+ if problem:
368
+ raise err(400, "invalid_submission", problem)
369
+
370
+ # ⚠ THE DAILY CAP IS SPENT ON A WRITE, NOT ON A REQUEST, and the order is the whole point.
371
+ # Counted before validation β€” where it was first β€” 500 malformed POSTs take a LIVE form
372
+ # offline for 24 hours, and one address can send them in about 17 minutes under the per-IP
373
+ # window. The cap exists to bound what reaches the tenant's table; pacing abuse is the
374
+ # window's job, and a refusal costs the attacker the same either way.
375
+ if not _daily_ok(token, time.time()):
376
+ raise err(429, "form_daily_cap",
377
+ "this form has reached today's submission limit β€” try again tomorrow")
378
+
379
+ import core.user_tables as user_tables
380
+
381
+ # ⚠ THE STAMP. `user_tables.add_row` filters values to the table's own field keys, so a
382
+ # `created_by` pair passed in `values` would simply be dropped β€” the row itself has no meta
383
+ # slot today. The `username` argument is the channel that DOES survive: it rides the
384
+ # `record_created` row event, so every trigger and audit downstream sees `form:<prefix>`
385
+ # rather than a blank actor. Booked as a dated amendment in the split doc; a persistent
386
+ # per-row stamp needs `add_row` to grow one, which is SESSION A's file.
387
+ actor = f"form:{token[:8]}"
388
+ row_id = user_tables.add_row(table_key, clean, username=actor, st=rt)
389
+ if not row_id:
390
+ raise err(409, "not_accepted", "that submission could not be saved β€” try again later")
391
+
392
+ # W23-W7 β€” A's FROZEN signature, called verbatim (CP1-a). Failure here must not turn a
393
+ # SAVED row into an error for the submitter: the answer is theirs and it is already stored.
394
+ try:
395
+ import automation_engine as engine
396
+ engine.form_fired(rt, table_key, row_id, values=clean, form_token=token)
397
+ except Exception: # noqa: BLE001
398
+ pass
399
+ return {"ok": True}
api/routes_keychain.py CHANGED
@@ -19,7 +19,11 @@ 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"
@@ -31,33 +35,34 @@ def _kc():
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):
@@ -196,23 +201,34 @@ def connectors(session: Session = Depends(admin_gate)):
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
 
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"
 
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):
 
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
api/routes_nav.py CHANGED
@@ -10,6 +10,8 @@ The full rule set β€” archived is invisible to everyone, `group_only` rows are e
10
  `prefs.json` Library preference is deliberately NOT applied β€” is documented on
11
  `core.perms.nav_pages`, which is where it belongs: one place, both callers.
12
  """
 
 
13
  from fastapi import APIRouter, Body, Depends
14
 
15
  from deps import Session, err, perms, require_session
@@ -50,6 +52,33 @@ _ICON_SHAPES = frozenset({"folder", "star", "flag", "tag", "bookmark", "grid",
50
  _ICON_TONES = frozenset({"neutral", "blue", "green", "yellow", "red"})
51
  _MAX_NAV_NAME = 60
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
  def _clean_nav_prefs(raw, page_keys):
55
  """Validated wholesale replacement, the `clean_folders` posture: prune, never invent.
@@ -131,6 +160,43 @@ def _read_nav_meta(runtime):
131
  return out
132
 
133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  @router.get("/nav")
135
  def nav(session: Session = Depends(require_session)):
136
  """`{pages: [{key,label,source?,chrome}], landing}`.
@@ -220,7 +286,72 @@ def nav(session: Session = Depends(require_session)):
220
  landing = perms.landing_page(session.user)
221
  if landing and not any(p.get("key") == landing for p in pages):
222
  landing = pages[0].get("key")
223
- return {"pages": pages, "landing": landing}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
 
226
  @router.post("/nav/meta")
 
10
  `prefs.json` Library preference is deliberately NOT applied β€” is documented on
11
  `core.perms.nav_pages`, which is where it belongs: one place, both callers.
12
  """
13
+ import time
14
+
15
  from fastapi import APIRouter, Body, Depends
16
 
17
  from deps import Session, err, perms, require_session
 
52
  _ICON_TONES = frozenset({"neutral", "blue", "green", "yellow", "red"})
53
  _MAX_NAV_NAME = 60
54
 
55
+ #: WAVE 23 (contract C10 / ruling R7) β€” the Home landing's RECENTS.
56
+ #:
57
+ #: PER-USER, like `nav_prefs` two buckets up and unlike `nav_meta`: what I opened last is
58
+ #: nobody else's business, and a tenant-wide "recently opened" would be a surveillance feature
59
+ #: rather than a convenience one.
60
+ #:
61
+ #: β›” A MAP KEYED BY PAGE, NOT AN APPEND LOG, and the difference is the whole feature.
62
+ #: `{username: {pageKey: <epoch seconds>}}` β€” re-opening a database OVERWRITES its stamp. An
63
+ #: append-only list capped at 50 fills with fifty copies of the same ten databases inside one
64
+ #: working session, and the cap then evicts OLDEST-FIRST: the tenth database you touched falls
65
+ #: off the list while forty slots hold repeat visits to the first. Keying by page makes
66
+ #: "recent" mean what the word means, and makes the cap bound the number of DATABASES
67
+ #: remembered rather than the number of clicks.
68
+ _NAV_RECENTS_KEY = "nav_recents"
69
+ _MAX_RECENTS = 50
70
+
71
+ #: ⚠ EPOCH SECONDS (UTC by definition), never a formatted stamp β€” and this is a correction of a
72
+ #: precedent, not a preference. `user_tables.create` writes
73
+ #: `datetime.now().strftime('%Y-%m-%dT%H:%M:%S')`: naive LOCAL time, no offset. A browser parses
74
+ #: that string as its OWN local time, so on a UTC host read by a non-UTC reader "opened 30
75
+ #: minutes ago" renders as "opened 7 hours ago" and the Today / Past-7-days buckets misfile β€”
76
+ #: with nothing to go red, because both ends are internally consistent. An integer instant has
77
+ #: no such reading. (D-18 made the same correction for notification stamps AFTER the defect
78
+ #: shipped; this is that lesson applied before it.)
79
+ def _now() -> int:
80
+ return int(time.time())
81
+
82
 
83
  def _clean_nav_prefs(raw, page_keys):
84
  """Validated wholesale replacement, the `clean_folders` posture: prune, never invent.
 
160
  return out
161
 
162
 
163
+ def _read_recents(runtime, uname, allowed):
164
+ """This user's recents, newest first, PRUNED to what they may currently see.
165
+
166
+ ⚠ PRUNED ON READ, never on write, and both halves of that are deliberate:
167
+
168
+ Β· the WRITE happens on every route open β€” it is the one hot path this file has β€” so it
169
+ must not build the whole nav to validate one key;
170
+ Β· a key whose grant was REVOKED must stop being offered without anyone running a
171
+ migration, and must come back if the grant does. That is `_clean_nav_prefs`' own
172
+ prune-never-invent posture, applied to a second bucket for the same reason.
173
+
174
+ A key that is not in `allowed` therefore reaches the store and never reaches a screen β€”
175
+ which also means a stuffed key cannot be used to discover what exists: it comes back only
176
+ if the session could already see it.
177
+ """
178
+ try:
179
+ stored = (runtime.get(_NAV_RECENTS_KEY) or {}).get(uname) or {}
180
+ except Exception:
181
+ return [] # a store blip must not take the nav down with it
182
+ if not isinstance(stored, dict):
183
+ return []
184
+ out = []
185
+ for key, at in stored.items():
186
+ key = str(key)
187
+ if allowed is not None and key not in allowed:
188
+ continue
189
+ try:
190
+ at = int(at)
191
+ except (TypeError, ValueError):
192
+ continue # a stamp this build cannot read is not a stamp
193
+ if at <= 0:
194
+ continue
195
+ out.append({"key": key, "at": at})
196
+ out.sort(key=lambda r: r["at"], reverse=True)
197
+ return out[:_MAX_RECENTS]
198
+
199
+
200
  @router.get("/nav")
201
  def nav(session: Session = Depends(require_session)):
202
  """`{pages: [{key,label,source?,chrome}], landing}`.
 
286
  landing = perms.landing_page(session.user)
287
  if landing and not any(p.get("key") == landing for p in pages):
288
  landing = pages[0].get("key")
289
+ # WAVE 23 (C10 / R7) β€” the Home landing's recents, on the payload the client already asks
290
+ # for. A second round trip for a list this short, computed from a bucket this route is
291
+ # already holding the store open for, would be a request per page load for no gain.
292
+ #
293
+ # β›” `allowed` IS THE ASSEMBLED PAGE LIST, not `_visible_top_keys`. The latter reads
294
+ # `perms.nav_pages` alone, which does NOT include this tenant's `ut_*` databases β€” those are
295
+ # merged into `pages` above, by this route, after the permission wall. Pruning against the
296
+ # narrower set would have silently dropped every user database from Home's recents: the
297
+ # exact surface R7 is about, invisible, with every gate green.
298
+ recents = _read_recents(session.runtime, session.uname,
299
+ {str(p.get("key", "")) for p in pages})
300
+ return {"pages": pages, "landing": landing, "recents": recents}
301
+
302
+
303
+ @router.post("/nav/opened")
304
+ def nav_opened(body: dict = Body(default=None),
305
+ session: Session = Depends(require_session)):
306
+ """WAVE 23 (C10) β€” stamp a page as JUST OPENED. Fire-and-forget from the client.
307
+
308
+ The client calls this on every route commit, so this is the only write in this file on a
309
+ hot path, and three things follow from that:
310
+
311
+ Β· `flush='async'` β€” the coalescing mode ([[store-async-flush]]). A blocking upload per
312
+ page open against an HF-Dataset-backed store would put a network round trip inside every
313
+ navigation. `nav_prefs`/`nav_meta` stay `sync` because a folder rename is not a hot path;
314
+ this is.
315
+ Β· NO VALIDATION OF THE KEY against the nav. Building the page list to check one string
316
+ would make the stamp cost more than the navigation that triggered it β€” and it would buy
317
+ nothing, because the READ prunes to what the session may currently see. An unknown or
318
+ revoked key is stored and never served back.
319
+ Β· THE MAP IS CAPPED HERE TOO. Read-side capping alone would let a hostile or buggy client
320
+ grow one user's document without bound; `_MAX_RECENTS` entries survive, oldest first to
321
+ go, which is the same rule the read applies.
322
+ """
323
+ body = body if isinstance(body, dict) else {}
324
+ key = str(body.get("key") or "").strip()[:60]
325
+ if not key:
326
+ raise err(400, "bad_request", "no page was named")
327
+ if not session.runtime.available():
328
+ raise err(503, "store_unavailable",
329
+ "the tenant store is unavailable β€” nothing was recorded")
330
+ stamp, uname = _now(), session.uname
331
+
332
+ def _up(data):
333
+ data = data if isinstance(data, dict) else {}
334
+ mine = dict(data.get(uname) or {}) if isinstance(data.get(uname), dict) else {}
335
+ mine[key] = stamp
336
+ if len(mine) > _MAX_RECENTS:
337
+ # Oldest first. `int(v)` guarded: a stamp an older build wrote in another shape
338
+ # sorts as 0 and is the first thing evicted, which is the right answer for a value
339
+ # this route can no longer read.
340
+ def _at(item):
341
+ try:
342
+ return int(item[1])
343
+ except (TypeError, ValueError):
344
+ return 0
345
+ mine = dict(sorted(mine.items(), key=_at, reverse=True)[:_MAX_RECENTS])
346
+ data[uname] = mine
347
+ return data
348
+
349
+ try:
350
+ session.runtime.update(_NAV_RECENTS_KEY, _up, flush='async')
351
+ except Exception:
352
+ raise err(503, "store_unavailable",
353
+ "the tenant store refused the write β€” nothing was recorded")
354
+ return {"key": key, "at": stamp}
355
 
356
 
357
  @router.post("/nav/meta")
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
 
api/routes_tables.py CHANGED
@@ -375,13 +375,37 @@ def add_field(table_key: str, body: dict = Body(default=None),
375
  ut = _ut()
376
  field = ut.add_field(table_key, body or {}, st=session.runtime)
377
  if not field:
378
- raise err(400, "refused",
379
- f"the column was refused β€” check the name and type, or the table may be at "
380
- f"its {ut.MAX_FIELDS}-column cap (types: "
381
- f"{', '.join(sorted(ut.UT_FIELD_TYPES))})")
 
 
 
 
382
  return {"field": field}
383
 
384
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
385
  @router.patch("/tables/{table_key}/fields/{fkey}")
386
  def patch_field(table_key: str, fkey: str, body: dict = Body(default=None),
387
  session: Session = Depends(require_session)):
 
375
  ut = _ut()
376
  field = ut.add_field(table_key, body or {}, st=session.runtime)
377
  if not field:
378
+ # ⭐ D-46 CLOSED (wave 23) β€” the C8 flow law gets its OWN sentence. `add_field` answers
379
+ # None for every refusal, so this route said "check the name and type" to somebody whose
380
+ # name and type were fine and whose automation column named a flow that does not exist.
381
+ # A refusal that misdirects is worse than a bare 400: it sends the reader to look at the
382
+ # one thing that was never wrong. Checked HERE, in the route's own words, because the
383
+ # law itself stays enforced in `user_tables.flow_bound` β€” this narrates it, never
384
+ # re-implements it (a second copy of the rule is how two doors start disagreeing).
385
+ raise err(400, "refused", _refusal_sentence(ut, session, body or {}))
386
  return {"field": field}
387
 
388
 
389
+ def _refusal_sentence(ut, session, body):
390
+ """Why was this column refused? The specific reason when we can name one, the general list
391
+ otherwise β€” never a specific-sounding guess."""
392
+ bag = (body or {}).get("automation")
393
+ if isinstance(bag, dict):
394
+ flow = str(bag.get("flowId") or "").strip()
395
+ if not flow:
396
+ return ("an automation column has to name the automation that fills it β€” pick a "
397
+ "flow, or make this an ordinary column")
398
+ if not ut.flow_bound(bag, st=session.runtime):
399
+ return (f"this column names automation {flow!r}, which does not exist in this "
400
+ f"workspace β€” it may have been deleted; pick a flow that is still there")
401
+ kind = str((body or {}).get("type") or "").strip()
402
+ if kind and kind not in ut.UT_FIELD_TYPES:
403
+ return (f"{kind!r} is not a column type here (types: "
404
+ f"{', '.join(sorted(ut.UT_FIELD_TYPES))})")
405
+ return (f"the column was refused β€” check the name and type, or the table may be at its "
406
+ f"{ut.MAX_FIELDS}-column cap (types: {', '.join(sorted(ut.UT_FIELD_TYPES))})")
407
+
408
+
409
  @router.patch("/tables/{table_key}/fields/{fkey}")
410
  def patch_field(table_key: str, fkey: str, body: dict = Body(default=None),
411
  session: Session = Depends(require_session)):
api/routes_templates.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """routes_templates.py β€” WAVE 23 item 7 (ruling R10, contract C12): the template doors.
2
+
3
+ GET /api/v1/templates?table=<page key> what can be applied HERE
4
+ POST /api/v1/templates/{key}/apply {table} apply it, to the CALLING USER's own views
5
+
6
+ Both session-gated. Neither is public and neither is admin-only: applying a template writes the
7
+ caller's PERSONAL saved views, which is something every user does to their own workspace all day
8
+ (`table_store.save_view(..., shared=False)`). The registry itself is platform-curated code
9
+ (`platform/core/view_templates.py`) β€” R10 explicitly rules out an end-user authoring UI this
10
+ wave, so there is no write door for the registry at all.
11
+
12
+ β›” THE WALL IS THE SAME PREDICATE THE NAV USES, per topic, and it is applied before anything is
13
+ read or written:
14
+ Β· `ut_*` β€” `user_tables.may_open` (creator, admin, or a share grant), exactly as
15
+ `routes_tables._defn_or_refuse` does. `session.require` would 403 every ut key, because a
16
+ user table is deliberately not a module (the split `/nav/schema/{key}` already makes).
17
+ Β· a built-in topic β€” `session.require(key)`, the module grant.
18
+ A key that is neither is a 404 with the same sentence for both: this route is not a directory of
19
+ what exists.
20
+
21
+ ⚠ REFUSE, NEVER PARTIALLY APPLY. `view_templates.missing_columns` runs against the TARGET's live
22
+ contract, and a template naming a column the target does not have comes back 400 with the
23
+ columns listed. The alternative β€” writing the views anyway β€” is the `_seed_wave17` failure
24
+ verbatim: `clean_filter_tree` DROPS a leaf on an unknown column, and a view whose only condition
25
+ was dropped shows EVERY row under a name that promises a shortlist.
26
+ """
27
+ import uuid
28
+
29
+ from fastapi import APIRouter, Body, Depends
30
+
31
+ from deps import Session, err, perms, require_session
32
+
33
+ router = APIRouter(prefix="/api/v1")
34
+
35
+
36
+ def _templates():
37
+ import core.view_templates as view_templates
38
+ return view_templates
39
+
40
+
41
+ def _target_or_refuse(session, table_key):
42
+ """`(field_keys, source_label)` for a table this session may open β€” or a refusal.
43
+
44
+ The field keys are the LIVE contract, read the same way each topic's own reader reads it, so
45
+ a template can never be offered against a column list this end assembled by hand.
46
+ """
47
+ key = str(table_key or '').strip()
48
+ if not key:
49
+ raise err(400, "bad_request", "no database was named")
50
+ if key.startswith('ut_'):
51
+ import core.user_tables as user_tables
52
+ defn = user_tables.get(key, st=session.runtime)
53
+ if not defn:
54
+ raise err(404, "unknown_table", "that database does not exist")
55
+ if not user_tables.may_open(key, session.uname, session.admin, st=session.runtime):
56
+ raise err(403, "forbidden", "that database belongs to another user")
57
+ fields = [str(f.get('key')) for f in (defn.get('fields') or []) if f.get('key')]
58
+ # A user table has no fixed topic. Its SOURCE label is left blank so `offer` gates on
59
+ # columns alone β€” which is the honest answer for a table whose shape its owner decides,
60
+ # and is exactly why the column test is the real contract (view_templates' own note).
61
+ return fields, ''
62
+ if key not in ('customer_data', 'product_data'):
63
+ raise err(404, "unknown_table", "that database does not exist")
64
+ session.require(key)
65
+ import aios_grid
66
+ if key == 'product_data':
67
+ return [f['key'] for f in aios_grid.product_fields()], 'odoo_product'
68
+ return [f['key'] for f in aios_grid.FIELDS], 'odoo_customer'
69
+
70
+
71
+ @router.get("/templates")
72
+ def list_templates(table: str = "", session: Session = Depends(require_session)):
73
+ """What can be applied to THIS database. `{table, templates: [...]}`.
74
+
75
+ Filtered by the target's real columns, so the picker cannot offer something the apply door
76
+ would refuse β€” one predicate, two callers (`view_templates.offer` wraps
77
+ `missing_columns`, which is the same function the POST below re-runs).
78
+ """
79
+ fields, source = _target_or_refuse(session, table)
80
+ vt = _templates()
81
+ return {"table": table, "templates": vt.offer(fields, source or None)}
82
+
83
+
84
+ @router.post("/templates/{key}/apply")
85
+ def apply_template(key: str, body: dict = Body(default=None),
86
+ session: Session = Depends(require_session)):
87
+ """Apply a template to a database, as the CALLING USER's own saved views.
88
+
89
+ IDEMPOTENT BY PINNED VIEW ID (`tpl_<template>_<suffix>`): a second click updates the same
90
+ views rather than minting "Past due 2". ⚠ That matters more than it sounds β€” `save_view`
91
+ de-duplicates NAMES by appending a number, so an unpinned id would make every re-apply a
92
+ fresh copy and the store would fill with numbered near-duplicates nobody asked for.
93
+ """
94
+ body = body if isinstance(body, dict) else {}
95
+ fields, _source = _target_or_refuse(session, body.get("table"))
96
+ vt = _templates()
97
+ tpl = vt.get(key)
98
+ if not tpl:
99
+ raise err(404, "unknown_template", "that template does not exist")
100
+ missing = vt.missing_columns(tpl, fields)
101
+ if missing:
102
+ # NAMED, not counted. "3 columns are missing" is a sentence the reader cannot act on;
103
+ # the column keys are what tells them this is the wrong database for this template.
104
+ raise err(400, "missing_columns",
105
+ "this database does not have the columns that template needs: "
106
+ + ", ".join(missing))
107
+ ws_key = vt.workspace_key(body.get("table"))
108
+ if not ws_key:
109
+ raise err(404, "unknown_table", "that database does not exist")
110
+ if not session.runtime.available():
111
+ raise err(503, "store_unavailable",
112
+ "the tenant store is unavailable β€” nothing was applied")
113
+ import core.table_store as table_store
114
+ ops = table_store.make(ws_key, st=session.runtime)
115
+ applied = []
116
+ for view in tpl.get('views') or ():
117
+ # β›” A COPY PER APPLY, and `createdBy` STAMPED HERE. The registry's dicts are module-level
118
+ # β€” mutating one would write this caller's username into the template every other tenant
119
+ # then reads, which is a cross-tenant leak with no symptom until two people apply the
120
+ # same template. Same invariant `routes_nav`'s in-place merge documents from the other
121
+ # side.
122
+ payload = dict(view)
123
+ payload['config'] = dict(view.get('config') or {})
124
+ payload['createdBy'] = session.uname
125
+ saved = ops.save_view(session.uname, payload, shared=False)
126
+ applied.append({"id": payload['id'], "name": saved.get('name') or payload['name']})
127
+
128
+ alert_id = None
129
+ if tpl.get('alert') and applied:
130
+ # The template's own view, watched. `core.alerts.create` stores the view BY ID rather
131
+ # than a copy of its filter tree, so an alert made here keeps meaning "tell me about
132
+ # this view" even after its owner edits it.
133
+ topic = ('product' if body.get("table") == 'product_data'
134
+ else 'customer' if body.get("table") == 'customer_data'
135
+ else str(body.get("table")))
136
+ try:
137
+ import core.alerts as alerts
138
+ alert_id = f"al_{uuid.uuid4().hex[:12]}"
139
+ alerts.create(alert_id, view_id=applied[0]["id"], topic=topic,
140
+ owner=session.uname, label=applied[0]["name"],
141
+ st=session.runtime)
142
+ except Exception:
143
+ # ⚠ THE VIEWS ARE ALREADY WRITTEN AND THAT IS THE POINT: a failed alert must not
144
+ # un-apply a template that worked. The response says which half landed rather than
145
+ # reporting a total failure over a partial success.
146
+ alert_id = None
147
+ return {"key": key, "table": body.get("table"), "views": applied,
148
+ "alert": alert_id, "alerted": bool(alert_id)}
platform/aios_grid.py CHANGED
@@ -109,9 +109,15 @@ def _round(v):
109
  #: megabyte-per-row tax on the whole store. Editable by NATURE (deliberately NOT in
110
  #: `READONLY_CUSTOM_TYPES`): the ref is what the upload endpoint hands back, and the client PATCHes
111
  #: it through the ordinary overlay wall rather than the asset route writing cells behind it.
 
 
 
 
 
 
112
  CUSTOM_FIELD_TYPES = {"text", "select", "multiselect", "user", "int", "currency", "pct", "date",
113
  "checkbox", "phone", "email", "url", "rating", "created_time", "formula",
114
- "automation", "image"}
115
  #: User-created types whose CELLS are read-only: their values are computed (formula β€” client
116
  #: side, any error degrades to BLANK) or system-owned (created_time = the row's `_created`).
117
  #: Emitted with the cohort column's read-only mechanism β€” `source: 'odoo'` + `derived` β€” so
 
109
  #: megabyte-per-row tax on the whole store. Editable by NATURE (deliberately NOT in
110
  #: `READONLY_CUSTOM_TYPES`): the ref is what the upload endpoint hands back, and the client PATCHes
111
  #: it through the ordinary overlay wall rather than the asset route writing cells behind it.
112
+ #: ⭐ WAVE 23 (C7) β€” `json` joined: a cell holding a whole DOCUMENT (an Instagram comment thread,
113
+ #: a webhook payload, a scraped blob) that opens in its own viewer instead of being flattened
114
+ #: into one unreadable line. It is EDITABLE by nature, like `image`: the value is still a plain
115
+ #: string on the wire, so it rides the ordinary overlay wall β€” what makes it a json field is that
116
+ #: `grid_events` REFUSES a write that does not parse (a column promising structure must not
117
+ #: silently hold something that isn't).
118
  CUSTOM_FIELD_TYPES = {"text", "select", "multiselect", "user", "int", "currency", "pct", "date",
119
  "checkbox", "phone", "email", "url", "rating", "created_time", "formula",
120
+ "automation", "image", "json"}
121
  #: User-created types whose CELLS are read-only: their values are computed (formula β€” client
122
  #: side, any error degrades to BLANK) or system-owned (created_time = the row's `_created`).
123
  #: Emitted with the cohort column's read-only mechanism β€” `source: 'odoo'` + `derived` β€” so
platform/core/alerts.py CHANGED
@@ -209,6 +209,44 @@ def _queue(rec, pids, labels, st=None):
209
  _st(st).update(NOTIFICATIONS_KEY, _apply, flush='async')
210
 
211
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  def inbox(user, st=None, limit=100):
213
  """`{'unread': int, 'items': [...]}` β€” newest first, for the badge and the pane."""
214
  try:
 
209
  _st(st).update(NOTIFICATIONS_KEY, _apply, flush='async')
210
 
211
 
212
+ def notify(owner, label, *, topic='automation', key='', row_id='', detail='', st=None):
213
+ """⭐ WAVE 23 (C6) β€” put ONE notification in a named user's inbox, for a producer that is not
214
+ a view-alert evaluation.
215
+
216
+ The automation engine needs the bell to ring when records arrive at a review gate, and that
217
+ is not an alert over a view: there is no filter tree, no `matched` set, no entrant diff. It
218
+ reached for `_queue` directly during the wave, which would have made a private function a
219
+ cross-module contract β€” so this is the public door instead, and `_queue` stays the internal
220
+ half of `evaluate()`.
221
+
222
+ The inbox shape is UNCHANGED, deliberately: `AlertsPane` reads one list, and a second row
223
+ shape would mean a client that must branch on where a notification came from. `alertId`
224
+ carries the producer's key so a click-through can route (W23-W5).
225
+ """
226
+ owner = str(owner or '').strip()
227
+ if not owner or not label:
228
+ return None
229
+ at = _now_iso()
230
+ item = {'id': f"{key or topic}:{row_id or 'n'}:{at}",
231
+ 'alertId': str(key or ''), 'viewId': '', 'topic': str(topic),
232
+ 'rowId': str(row_id or ''), 'label': str(detail or label),
233
+ 'alertLabel': str(label), 'at': at, 'read': False}
234
+
235
+ def _apply(data):
236
+ box = list(data.get(owner) or [])
237
+ box.append(item)
238
+ if len(box) > MAX_NOTIFICATIONS:
239
+ unread = [n for n in box if not n.get('read')]
240
+ read = [n for n in box if n.get('read')]
241
+ keep_read = read[max(0, len(unread) + len(read) - MAX_NOTIFICATIONS):]
242
+ box = sorted(unread + keep_read, key=lambda n: str(n.get('at') or ''))
243
+ data[owner] = box
244
+ return data
245
+
246
+ _st(st).update(NOTIFICATIONS_KEY, _apply, flush='async')
247
+ return item
248
+
249
+
250
  def inbox(user, st=None, limit=100):
251
  """`{'unread': int, 'items': [...]}` β€” newest first, for the badge and the pane."""
252
  try:
platform/core/grid_events.py CHANGED
@@ -38,11 +38,13 @@ so the import stays and the violation is RECORDED rather than hidden. It is the
38
  down, and this note is the marker for that work.
39
  """
40
  import datetime as dt
 
41
  from dataclasses import dataclass, field
42
  from typing import MutableMapping, Optional
43
 
44
  import core.store as store
45
  import core.table_store as _tstore # wave-9 I17: the shared-view authorisation predicates
 
46
  import core.users as users
47
  import harness.telemetry as _tel # _tel.error() = THE error sink (all caught errors log)
48
  import modules.cohort as cohort_mod
@@ -1703,6 +1705,26 @@ def handle_one(event, ctx):
1703
  else:
1704
  refused = True
1705
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1706
  clean = str(value)[:10000]
1707
  if isinstance(value, str) and clean != value:
1708
  # Truncated: the stored truth is shorter than the client's copy. (An
 
38
  down, and this note is the marker for that work.
39
  """
40
  import datetime as dt
41
+ import json as _json_ev # wave 23 (C7): the json field's parse wall
42
  from dataclasses import dataclass, field
43
  from typing import MutableMapping, Optional
44
 
45
  import core.store as store
46
  import core.table_store as _tstore # wave-9 I17: the shared-view authorisation predicates
47
+ import core.user_tables as _ut_limits # wave 23 (C7): MAX_JSON_CELL β€” one ceiling, one definer
48
  import core.users as users
49
  import harness.telemetry as _tel # _tel.error() = THE error sink (all caught errors log)
50
  import modules.cohort as cohort_mod
 
1705
  else:
1706
  refused = True
1707
  continue
1708
+ # ⭐ WAVE 23 (C7) β€” the json wall, BEFORE the generic 10 000-char truncation, which
1709
+ # would otherwise cut a document in half and store the halves as valid text. A json
1710
+ # column promises its readers a parseable document; a write that is not one is
1711
+ # REFUSED with the cell unchanged rather than silently kept as a string nothing can
1712
+ # open. Blank stays legal β€” an empty cell is "no document", not a malformed one.
1713
+ if (field_by_key.get(key) or {}).get('type') == 'json':
1714
+ raw_j = value if isinstance(value, str) else _json_ev.dumps(value)
1715
+ if not str(raw_j).strip():
1716
+ updates[key] = ''
1717
+ continue
1718
+ if len(str(raw_j)) > _ut_limits.MAX_JSON_CELL:
1719
+ refused = True
1720
+ continue
1721
+ try:
1722
+ _json_ev.loads(raw_j)
1723
+ except (ValueError, TypeError):
1724
+ refused = True
1725
+ continue
1726
+ updates[key] = str(raw_j)
1727
+ continue
1728
  clean = str(value)[:10000]
1729
  if isinstance(value, str) and clean != value:
1730
  # Truncated: the stored truth is shorter than the client's copy. (An
platform/core/keychain.py CHANGED
@@ -27,7 +27,13 @@ import os
27
  import secrets as _secrets
28
 
29
  KEY = 'keychain'
30
- ENTRY_TYPES = {'odoo', 'generic'}
 
 
 
 
 
 
31
  #: which stored field feeds the masked preview, per type (first present wins)
32
  _PREVIEW_FIELDS = ('api_key', 'value', 'password', 'token')
33
  MAX_ENTRIES = 40
 
27
  import secrets as _secrets
28
 
29
  KEY = 'keychain'
30
+ #: ⭐ WAVE 23 (C11/R8) β€” `stripe` and `shopify` joined. They are TOKEN connectors, not OAuth
31
+ #: ones, and that is the whole reason they could ship in this wave: both issue a long-lived
32
+ #: restricted key / custom-app token an admin pastes in, so they need no OAuth client, no
33
+ #: consent screen and no app review β€” the three things that make every other provider on the
34
+ #: standing queue a multi-week errand. A type here is what lets the connectors directory show
35
+ #: them as CONNECTABLE rather than as another faded to-do.
36
+ ENTRY_TYPES = {'odoo', 'generic', 'stripe', 'shopify'}
37
  #: which stored field feeds the masked preview, per type (first present wins)
38
  _PREVIEW_FIELDS = ('api_key', 'value', 'password', 'token')
39
  MAX_ENTRIES = 40
platform/core/user_tables.py CHANGED
@@ -58,8 +58,15 @@ KEY_PREFIX = 'ut_'
58
  #: landed in the per-user workspace stratum and the picker could not see them β€” the owner's
59
  #: "Choose a column..." stays empty. Local literal rather than an aios_grid import so this
60
  #: module stays dependency-light for the API's boot path.
 
 
 
61
  UT_FIELD_TYPES = {'text', 'select', 'multiselect', 'user', 'int', 'currency', 'pct', 'date',
62
- 'checkbox', 'phone', 'email', 'url', 'rating', 'automation'}
 
 
 
 
63
 
64
 
65
  def _st(st):
@@ -186,8 +193,8 @@ def delete(table_key, st=None):
186
  is no longer optional. Cleaned here, in one place: definition (`user_tables`) Β· the
187
  workspace bucket (`<key>_table_workspace`, every stratum incl. `__shared__` β€” views,
188
  custom fields, overlays, folders) Β· cohorts (`<key>_cohorts`) Β· record comments
189
- (`<key>_record_comments`) Β· docs metadata (`<key>_docs`; dataset BYTES under
190
- `docs/<key>/…` become unreachable and are left to storage β€” disclosed, not hidden) Β·
191
  `nav_meta[<key>]` Β· share grants (the database grant plus a view grant per view that
192
  lived in this bucket, via `shares.drop_objects`) Β· alert definitions on this topic.
193
  Bound AUTOMATIONS are the API layer's to disable (platform must not import the engine).
@@ -210,11 +217,34 @@ def delete(table_key, st=None):
210
  view_ids |= set((ws.get('views') or {}).keys())
211
  except Exception:
212
  pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  for b in (ws_key, f'{key}_cohorts', f'{key}_record_comments', f'{key}_docs'):
214
  try:
215
  s.update(b, lambda cur: {}, flush='async')
216
  except Exception:
217
  pass
 
 
 
 
 
 
218
 
219
  def _drop_meta(cur):
220
  if isinstance(cur, dict):
 
58
  #: landed in the per-user workspace stratum and the picker could not see them β€” the owner's
59
  #: "Choose a column..." stays empty. Local literal rather than an aios_grid import so this
60
  #: module stays dependency-light for the API's boot path.
61
+ #: ⭐ `json` JOINED IN WAVE 23 (C7) β€” and it belongs here rather than staying grid-only the way
62
+ #: `image` did, because the databases that need it are exactly these: a scrape lands a comment
63
+ #: thread or a webhook payload against a row, and the automation engine writes those cells.
64
  UT_FIELD_TYPES = {'text', 'select', 'multiselect', 'user', 'int', 'currency', 'pct', 'date',
65
+ 'checkbox', 'phone', 'email', 'url', 'rating', 'automation', 'json'}
66
+ #: C7's ceiling. A cell is still a scalar on the wire (`Row` values are strings/numbers) β€” what
67
+ #: this bounds is the DOCUMENT inside it. 32 KB holds a long comment thread and refuses a payload
68
+ #: somebody meant to store as a file.
69
+ MAX_JSON_CELL = 32 * 1024
70
 
71
 
72
  def _st(st):
 
193
  is no longer optional. Cleaned here, in one place: definition (`user_tables`) Β· the
194
  workspace bucket (`<key>_table_workspace`, every stratum incl. `__shared__` β€” views,
195
  custom fields, overlays, folders) Β· cohorts (`<key>_cohorts`) Β· record comments
196
+ (`<key>_record_comments`) Β· docs metadata (`<key>_docs`) AND the dataset BYTES each
197
+ metadata row names (D-36, closed wave 23 β€” wave 21 left those unreachable-but-present) Β·
198
  `nav_meta[<key>]` Β· share grants (the database grant plus a view grant per view that
199
  lived in this bucket, via `shares.drop_objects`) Β· alert definitions on this topic.
200
  Bound AUTOMATIONS are the API layer's to disable (platform must not import the engine).
 
217
  view_ids |= set((ws.get('views') or {}).keys())
218
  except Exception:
219
  pass
220
+ # ⭐ D-36 CLOSED (wave 23) β€” the document BYTES, not just their metadata. Wave 21 cleaned
221
+ # `<key>_docs` and disclosed that the blobs under `docs/<key>/…` were left on the dataset;
222
+ # "unreachable" is not "deleted", and for a tenant asking us to delete a database the
223
+ # difference is the whole promise. Read the metadata FIRST (it carries each blob's exact
224
+ # stored `path`, so nothing is guessed from a naming convention that could drift), then
225
+ # clear the bucket, then delete the blobs. Best-effort per file: a storage blip must not
226
+ # resurrect the table or abort the rest of the sweep β€” an undeleted blob is residue we can
227
+ # sweep again, an aborted delete is a table the user asked to be gone.
228
+ doc_paths = []
229
+ try:
230
+ for _pid, _rows in (s.get(f'{key}_docs') or {}).items():
231
+ for _doc in (_rows or []):
232
+ p = str((_doc or {}).get('path') or '')
233
+ if p:
234
+ doc_paths.append(p)
235
+ except Exception:
236
+ pass
237
  for b in (ws_key, f'{key}_cohorts', f'{key}_record_comments', f'{key}_docs'):
238
  try:
239
  s.update(b, lambda cur: {}, flush='async')
240
  except Exception:
241
  pass
242
+ for p in doc_paths:
243
+ try:
244
+ import core.store as _store_bytes
245
+ _store_bytes.delete_path(p)
246
+ except Exception:
247
+ pass
248
 
249
  def _drop_meta(cur):
250
  if isinstance(cur, dict):
platform/core/view_templates.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """view_templates.py β€” WAVE 23 item 7 (ruling R10, contract C12): the PLATFORM-CURATED
2
+ template registry.
3
+
4
+ WHAT A TEMPLATE IS, precisely, because the word is overloaded: a named bundle of SAVED VIEWS
5
+ that a user applies to a database they already have. It does NOT create a table, it does not add
6
+ columns, and it does not connect anything. It is the answer to "this database has 30 columns and
7
+ I do not know which twelve matter for chasing money" β€” a starting layout, authored once by the
8
+ platform, applied by whoever wants it.
9
+
10
+ β›” THE ONE RULE THAT DECIDES EVERY DESIGN CHOICE HERE β€” `_seed_wave17.py`'s :9-20 law:
11
+ **only VIEWS are shared; `fields` and `overlays` are strictly per-user.** So a SHARED view that
12
+ filtered on a user-created column would, for every other account, name a column that does not
13
+ exist β€” and an unknown column is an INACTIVE leaf in the tri-state filter engine, which is
14
+ IGNORED, which WIDENS. A "Collections focus" that quietly showed the whole customer book to
15
+ everyone but its author, with nothing going red.
16
+
17
+ Two consequences, both load-bearing:
18
+
19
+ 1. **Applying writes the CALLING USER's own views** (`save_view(..., shared=False)`), never
20
+ shared ones. A template is a convenience, not an administrative act, and the moment it
21
+ wrote into the shared bucket it would need an admin wall and a name-collision policy across
22
+ the tenant.
23
+ 2. **Every column a template names is checked against the TARGET's live contract before
24
+ anything is written**, and a template whose columns are missing is REFUSED with them named
25
+ β€” never applied partially, never applied with the offending leaf dropped. That check is
26
+ also what makes eligibility honest: `source` below is a label for grouping, the COLUMNS are
27
+ the gate, and the two cannot disagree because only one of them is consulted.
28
+
29
+ IDEMPOTENT BY PINNED ID. Every view carries `tpl_<template>_<suffix>`, so re-applying updates
30
+ the same views instead of minting "Collections focus 2". `save_view` renames on collision, which
31
+ would otherwise turn a second click into a second copy.
32
+
33
+ Pure-ish by construction: `TEMPLATES` and every builder are data, so `verify_home.py` can assert
34
+ their shape without a store.
35
+ """
36
+
37
+ #: The topic a template is FOR. A coarse grouping label used to filter the picker's list; the
38
+ #: real gate is `missing_columns` below (a table whose contract has the columns can take the
39
+ #: template, whatever we called its source).
40
+ SOURCES = ('odoo_customer', 'odoo_product', 'instagram', 'any')
41
+
42
+ #: The workspace bucket a topic's views live in. `<key>_table_workspace` for user tables
43
+ #: (`core/user_tables.py:211` builds the same string when it deletes them), and the two built-ins
44
+ #: keep the names their modules have always used.
45
+ _WS_KEYS = {
46
+ 'customer_data': 'customer_table_workspace',
47
+ 'product_data': 'product_table_workspace',
48
+ }
49
+
50
+
51
+ def workspace_key(table_key):
52
+ """The `core.table_store` key for a page key, or None if it is not a table at all."""
53
+ key = str(table_key or '')
54
+ if key in _WS_KEYS:
55
+ return _WS_KEYS[key]
56
+ if key.startswith('ut_'):
57
+ return f'{key}_table_workspace'
58
+ return None
59
+
60
+
61
+ def _view(view_id, name, note, visible, *, mode='grid', stack_field=None, sorts=(),
62
+ filters=(), group_by=None, conj='and'):
63
+ """One saved view, in the shape `table_store.save_view` stores and the grid reads.
64
+
65
+ ⚠ THE SHAPE IS COPIED FROM `_seed_wave17._view` ON PURPOSE, field for field, including the
66
+ keys that look inert (`widths`, `memberPids`, `rowHeightMode`). The grid's own cleaner fills
67
+ defaults for what is missing, but a view assembled from a DIFFERENT skeleton is a second
68
+ definition of what a view is β€” and the two drift on the day one of them gains a key.
69
+
70
+ `permissions.edit` is absent: `table_store.is_shared` reads it, and a view with no
71
+ permissions block is PERSONAL, which is the only thing this file is allowed to write.
72
+
73
+ β›” THE MODE LIVES AT `config.display.mode`, AND THE FIRST DRAFT PUT IT AT
74
+ `config.displayMode` β€” A KEY NOTHING READS. The gate caught nothing, because it asserted the
75
+ VALUE against `aios_grid.DISPLAY_MODES` and never the PATH: `"kanban" in DISPLAY_MODES` is
76
+ true wherever you happen to have written it. The Instagram "Review board" would have been
77
+ created as a plain GRID under a name promising a board β€” the view exists, the filter works,
78
+ the kanban never happens, and nothing goes red. Exactly the silent-drop class as a dropped
79
+ filter leaf, one field over. Corrected against `aios_grid._clean_display`, which is now RUN
80
+ over every template in `verify_home` rather than consulted for a vocabulary.
81
+
82
+ ⚠ AND `grid` STORES NOTHING. `_clean_display` returns None for it by design ("grid is the
83
+ absent default, so storing it would be a second way to say nothing"), so writing
84
+ `display: {'mode': 'grid'}` would be a key the cleaner strips on the next save β€” a value that
85
+ exists until something touches it.
86
+ """
87
+ display = None
88
+ if mode != 'grid':
89
+ display = {'mode': mode}
90
+ if stack_field:
91
+ # The kanban lane column. `_clean_display` accepts any ref that NAMES a real field
92
+ # and leaves what the mode means to the client, which degrades a wrong-typed ref to
93
+ # its own default rather than erroring.
94
+ display['stackField'] = stack_field
95
+ return {
96
+ 'id': view_id, 'name': name, 'kind': 'custom', 'locked': False, 'note': note,
97
+ 'config': {
98
+ 'filters': list(filters), 'filterConj': conj, 'sorts': list(sorts),
99
+ 'groupBy': group_by, 'colorBy': None, 'rowHeightMode': 'short',
100
+ 'order': list(visible), 'visible': list(visible), 'widths': {},
101
+ 'memberPids': [], **({'display': display} if display else {}),
102
+ },
103
+ }
104
+
105
+
106
+ # ── THE REGISTRY ────────────────────────────────────────────────────────────────────────────
107
+ #
108
+ # ⚠ FIRST BATCH (C12). Every column named below was checked against the live contract when this
109
+ # file was written β€” `aios_grid_fields.json` for customer, `aios_grid.product_fields()` for
110
+ # product, `automation_engine.CANDIDATE_FIELDS` for the Instagram candidate pool β€” but the check
111
+ # that MATTERS runs at apply time, against the target the user actually picked, because a
112
+ # contract can move and a ut_ table's columns are whatever its owner made.
113
+
114
+ TEMPLATES = [
115
+ {
116
+ 'key': 'collections_focus',
117
+ 'label': 'Collections focus',
118
+ 'desc': 'Everyone with money past due, largest first, with the aging buckets beside it.',
119
+ 'source': 'odoo_customer',
120
+ 'views': [
121
+ _view(
122
+ 'tpl_collections_focus_overdue', 'Past due',
123
+ 'Customers with an overdue balance, largest first. The four aging columns sum '
124
+ 'to AR overdue; a balance inside the grace period counts as open, not overdue.',
125
+ ['customer', 'agent', 'ar_overdue', 'ar_aged_1_30', 'ar_aged_31_60',
126
+ 'ar_aged_61_90', 'ar_aged_90_plus', 'ar_open', 'days_to_pay',
127
+ 'payment_terms', 'last_order'],
128
+ sorts=[{'colId': 'ar_overdue', 'dir': 'desc'}],
129
+ filters=[{'colId': 'ar_overdue', 'op': 'gt', 'value': '0'}],
130
+ ),
131
+ _view(
132
+ 'tpl_collections_focus_worst', 'Over 90 days',
133
+ 'The part of the book that is no longer a payment-terms conversation.',
134
+ ['customer', 'agent', 'ar_aged_90_plus', 'ar_overdue', 'ar_exposure',
135
+ 'days_to_pay', 'last_order'],
136
+ sorts=[{'colId': 'ar_aged_90_plus', 'dir': 'desc'}],
137
+ filters=[{'colId': 'ar_aged_90_plus', 'op': 'gt', 'value': '0'}],
138
+ ),
139
+ ],
140
+ },
141
+ {
142
+ 'key': 'dba_missing',
143
+ 'label': 'DBA is empty',
144
+ # The owner's own example (C12). One view, one job, and it is a DATA-QUALITY view: the
145
+ # brand a customer buys from decides which BU-scoped account can see them at all, so a
146
+ # blank DBA is a customer nobody's book contains.
147
+ 'desc': 'Customers with no brand recorded β€” they fall outside every scoped book.',
148
+ 'source': 'odoo_customer',
149
+ 'alert': True,
150
+ 'views': [
151
+ _view(
152
+ 'tpl_dba_missing_blank', 'DBA is empty',
153
+ 'Customers whose DBA is blank. The brand decides which scoped account sees a '
154
+ 'customer, so a blank one is invisible to every book except an unscoped view.',
155
+ # ⚠ SORTED BY OPEN RECEIVABLE, NOT BY SALES. This view first named `sales_ltm`,
156
+ # which DOES NOT EXIST β€” the customer contract carries no LTM sales column (the
157
+ # 32 keys in `aios_grid_fields.json`; `verify_home` caught it against the live
158
+ # contract on the first run). `ar_open` is the nearest real column that answers
159
+ # the same question β€” "which of these matters most" β€” and it answers it in
160
+ # money that is actually outstanding rather than in history.
161
+ ['customer', 'dba', 'agent', 'ar_open', 'last_order', 'days_since'],
162
+ sorts=[{'colId': 'ar_open', 'dir': 'desc'}],
163
+ # ⚠ `isEmpty`, and it is the one op that is safe here. A `select` column's blank
164
+ # is not the empty string in every row shape, and `eq ''` would miss the nulls β€”
165
+ # `isEmpty`/`isNotEmpty` are evaluated type-independently BEFORE any coercion
166
+ # (the same reason `_seed_wave17`'s buy list leans on them).
167
+ filters=[{'colId': 'dba', 'op': 'isEmpty'}],
168
+ ),
169
+ ],
170
+ },
171
+ {
172
+ 'key': 'buy_list_companion',
173
+ 'label': 'Buy-list companion',
174
+ 'desc': 'What is running out, and what it costs to bring in β€” beside the buy list.',
175
+ 'source': 'odoo_product',
176
+ 'views': [
177
+ _view(
178
+ 'tpl_buy_list_companion_cover', 'Cover gap',
179
+ 'SKUs whose days of supply is already shorter than their supplier lead time. '
180
+ 'Stock columns are consolidated across the one physical warehouse, so this is '
181
+ 'empty for a BU-scoped account.',
182
+ ['code', 'product', 'cover_gap_d', 'dos', 'lead_days', 'supplier', 'on_hand',
183
+ 'qty_ltm', 'first_cost', 'origin_country'],
184
+ sorts=[{'colId': 'cover_gap_d', 'dir': 'asc'}],
185
+ # The same four leaves the wave-17 seed uses, and for the same reason: a bare
186
+ # `dos < lead_days` reads a SKU with NO days-of-supply as `0 < 30` (the client
187
+ # engine's `toNum(null)` is 0) and puts every never-selling product on the list.
188
+ filters=[{'colId': 'dos', 'op': 'isNotEmpty'},
189
+ {'colId': 'lead_days', 'op': 'isNotEmpty'},
190
+ {'colId': 'lead_days', 'op': 'gt', 'value': '0'},
191
+ {'colId': 'dos', 'op': 'lt',
192
+ 'rhs': {'kind': 'field', 'colId': 'lead_days'}}],
193
+ ),
194
+ _view(
195
+ 'tpl_buy_list_companion_nosupplier', 'No supplier on file',
196
+ 'SKUs we cannot reorder because nobody is recorded as selling them to us.',
197
+ ['code', 'product', 'supplier', 'on_hand', 'qty_ltm', 'first_cost'],
198
+ sorts=[{'colId': 'qty_ltm', 'dir': 'desc'}],
199
+ filters=[{'colId': 'supplier', 'op': 'isEmpty'}],
200
+ ),
201
+ ],
202
+ },
203
+ {
204
+ 'key': 'ig_candidates',
205
+ 'label': 'Candidates review',
206
+ 'desc': 'Discovered profiles as a review board, plus the ones worth reading first.',
207
+ 'source': 'instagram',
208
+ 'views': [
209
+ _view(
210
+ 'tpl_ig_candidates_board', 'Review board',
211
+ 'Discovered profiles grouped by category. Tick "Tracked" on the ones worth '
212
+ 'keeping β€” that column is written by a person, never by the automation.',
213
+ ['handle', 'full_name', 'followers', 'avg_engagement', 'verified', 'category',
214
+ 'tracked', 'profile_url'],
215
+ # `stackField`, NOT `groupBy` β€” the kanban lane column is a `display` ref, while
216
+ # `groupBy` is the GRID's row grouping. They are two different features that both
217
+ # sound like "group by", and only one of them makes lanes.
218
+ mode='kanban', stack_field='category',
219
+ sorts=[{'colId': 'followers', 'dir': 'desc'}],
220
+ ),
221
+ _view(
222
+ 'tpl_ig_candidates_engaged', 'High engagement',
223
+ 'Profiles whose audience actually responds, biggest first. Engagement, not '
224
+ 'follower count, is what a small account can be good at.',
225
+ ['handle', 'full_name', 'avg_engagement', 'followers', 'category', 'bio',
226
+ 'external_url', 'tracked'],
227
+ sorts=[{'colId': 'avg_engagement', 'dir': 'desc'}],
228
+ filters=[{'colId': 'avg_engagement', 'op': 'gt', 'value': '0'}],
229
+ ),
230
+ ],
231
+ },
232
+ ]
233
+
234
+
235
+ def get(key):
236
+ """One template by key, or None."""
237
+ return next((t for t in TEMPLATES if t['key'] == str(key)), None)
238
+
239
+
240
+ def columns_named(template):
241
+ """Every column key a template's views reference β€” visible, filtered, sorted, grouped, and
242
+ the right-hand side of a field-vs-field comparison.
243
+
244
+ β›” THE `rhs` IS THE ONE PEOPLE FORGET, and `_seed_wave17` learned it the expensive way:
245
+ `clean_filter_tree` KEEPS a leaf whose rhs names an unknown column β€” it drops the rhs and
246
+ leaves the rule β€” so `dos < lead_days` silently becomes `dos < ""`. The leaf count is
247
+ unchanged, so a check that counted leaves would pass while the view answered a different
248
+ question. Naming the rhs here is what makes the eligibility test see it.
249
+ """
250
+ out = set()
251
+ for view in template.get('views') or ():
252
+ cfg = view.get('config') or {}
253
+ out.update(cfg.get('visible') or ())
254
+ for s in cfg.get('sorts') or ():
255
+ if isinstance(s, dict) and s.get('colId'):
256
+ out.add(s['colId'])
257
+ if cfg.get('groupBy'):
258
+ out.add(cfg['groupBy'])
259
+ for f in cfg.get('filters') or ():
260
+ if not isinstance(f, dict):
261
+ continue
262
+ if f.get('colId'):
263
+ out.add(f['colId'])
264
+ rhs = f.get('rhs')
265
+ if isinstance(rhs, dict) and rhs.get('colId'):
266
+ out.add(rhs['colId'])
267
+ return out
268
+
269
+
270
+ def missing_columns(template, field_keys):
271
+ """The columns this template needs that the target does not have. Empty β‡’ it can be applied.
272
+
273
+ THE ELIGIBILITY TEST AND THE REFUSAL TEST ARE THE SAME FUNCTION, deliberately: a picker that
274
+ offered a template the apply door would then refuse is a control that lies, and two separate
275
+ predicates is how those two answers drift apart.
276
+ """
277
+ return sorted(columns_named(template) - set(field_keys or ()))
278
+
279
+
280
+ def offer(field_keys, source=None):
281
+ """Every template that CAN be applied to a target with these columns.
282
+
283
+ `source` narrows further when the caller knows it (the picker passes the target's own), but
284
+ a template whose columns are all present is offered regardless of label β€” the columns are
285
+ the contract and the label is a grouping.
286
+ """
287
+ out = []
288
+ for t in TEMPLATES:
289
+ if missing_columns(t, field_keys):
290
+ continue
291
+ if source and t['source'] not in ('any', source):
292
+ continue
293
+ out.append({'key': t['key'], 'label': t['label'], 'desc': t['desc'],
294
+ 'source': t['source'], 'views': len(t.get('views') or ()),
295
+ 'alert': bool(t.get('alert'))})
296
+ return out
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/alerts/AlertsPane.tsx CHANGED
@@ -19,7 +19,14 @@ import {
19
  markRead,
20
  runAlert,
21
  } from "./alertsApi";
22
- import { EMPTY_INBOX, applyRead, inboxOrder, routeForTopic, stampText } from "./alertsModel";
 
 
 
 
 
 
 
23
  import type { Alert, Inbox, Notification } from "./alertsModel";
24
 
25
  /** The clock face this pane uses for its one glyph β€” drawn, never an emoji. */
@@ -35,12 +42,23 @@ function BellIcon() {
35
  export default function AlertsPane({
36
  onClose,
37
  onOpenView,
 
38
  onInbox,
39
  onToast,
40
  }: {
41
  onClose: () => void;
42
  /** Navigate to the alert's view. The FRAME owns routing; this pane owns the row. */
43
  onOpenView: (topic: string, viewId: string) => void;
 
 
 
 
 
 
 
 
 
 
44
  /** Hand the freshly-read inbox back so the nav badge and the pane agree. */
45
  onInbox: (inbox: Inbox) => void;
46
  onToast: (message: string) => void;
@@ -114,6 +132,16 @@ export default function AlertsPane({
114
  publish(applyRead(inbox, [n.id], true));
115
  void markRead([n.id], true);
116
  }
 
 
 
 
 
 
 
 
 
 
117
  // A route this client cannot resolve opens NOTHING and says so β€” alerts
118
  // outlive the surfaces they were made from.
119
  if (!routeForTopic(n.topic)) {
@@ -123,7 +151,7 @@ export default function AlertsPane({
123
  onOpenView(n.topic, n.viewId);
124
  onClose();
125
  },
126
- [inbox, publish, onOpenView, onClose, onToast]
127
  );
128
 
129
  const rows = inboxOrder(inbox.items);
@@ -166,7 +194,14 @@ export default function AlertsPane({
166
  type="button"
167
  className="alerts-row-main"
168
  onClick={() => open(n)}
169
- title={`Open ${n.alertLabel || "the alert's view"}`}
 
 
 
 
 
 
 
170
  >
171
  <span className="alerts-row-label">{n.label}</span>
172
  <span className="alerts-row-meta">
 
19
  markRead,
20
  runAlert,
21
  } from "./alertsApi";
22
+ import {
23
+ EMPTY_INBOX,
24
+ applyRead,
25
+ inboxOrder,
26
+ isAutomationReview,
27
+ routeForTopic,
28
+ stampText,
29
+ } from "./alertsModel";
30
  import type { Alert, Inbox, Notification } from "./alertsModel";
31
 
32
  /** The clock face this pane uses for its one glyph β€” drawn, never an emoji. */
 
42
  export default function AlertsPane({
43
  onClose,
44
  onOpenView,
45
+ onOpenAutomation,
46
  onInbox,
47
  onToast,
48
  }: {
49
  onClose: () => void;
50
  /** Navigate to the alert's view. The FRAME owns routing; this pane owns the row. */
51
  onOpenView: (topic: string, viewId: string) => void;
52
+ /**
53
+ * WAVE 23 (C6, wiring W23-W5) β€” the same division for a REVIEW notification: the frame routes
54
+ * to `#/automation` and asks the surface to select this automation.
55
+ *
56
+ * β›” REQUIRED, NOT OPTIONAL, and that is the wave-20 lesson written into a type. An optional
57
+ * callback the frame forgot to pass degrades to "clicking a review notification does nothing",
58
+ * which is indistinguishable from "the feature was never built" and goes red in no gate. A
59
+ * required prop fails `tsc` the moment it is unmounted.
60
+ */
61
+ onOpenAutomation: (autoId: string, stageId?: string) => void;
62
  /** Hand the freshly-read inbox back so the nav badge and the pane agree. */
63
  onInbox: (inbox: Inbox) => void;
64
  onToast: (message: string) => void;
 
132
  publish(applyRead(inbox, [n.id], true));
133
  void markRead([n.id], true);
134
  }
135
+ // β›” WAVE 23 C6 β€” THE KIND BRANCH COMES FIRST, AND ITS ORDER IS THE WHOLE FIX. A review
136
+ // notification has no `topic` a grid could render, so the view guard below would have
137
+ // caught every one of them and told the reader their table was "no longer available" β€”
138
+ // a confidently wrong sentence about a feature that is working. The destination decides
139
+ // which guard applies, so the destination is decided first.
140
+ if (isAutomationReview(n)) {
141
+ onOpenAutomation(n.autoId!, n.stageId);
142
+ onClose();
143
+ return;
144
+ }
145
  // A route this client cannot resolve opens NOTHING and says so β€” alerts
146
  // outlive the surfaces they were made from.
147
  if (!routeForTopic(n.topic)) {
 
151
  onOpenView(n.topic, n.viewId);
152
  onClose();
153
  },
154
+ [inbox, publish, onOpenView, onOpenAutomation, onClose, onToast]
155
  );
156
 
157
  const rows = inboxOrder(inbox.items);
 
194
  type="button"
195
  className="alerts-row-main"
196
  onClick={() => open(n)}
197
+ // The hover names the DESTINATION, which is now two different places.
198
+ // "Open the alert's view" over a review notification described a journey
199
+ // the click does not take.
200
+ title={
201
+ isAutomationReview(n)
202
+ ? "Open the automation"
203
+ : `Open ${n.alertLabel || "the alert's view"}`
204
+ }
205
  >
206
  <span className="alerts-row-label">{n.label}</span>
207
  <span className="alerts-row-meta">
web/src/alerts/alertsModel.ts CHANGED
@@ -31,6 +31,29 @@ export interface Notification {
31
  * would re-introduce the browser-clock drift the offset exists to remove. */
32
  at: string;
33
  read: boolean;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  }
35
 
36
  /** One alert, as `GET /api/v1/alerts` sends it. */
@@ -87,6 +110,14 @@ export function parseInbox(body: unknown): Inbox {
87
  alertLabel: str(n.alertLabel),
88
  at: str(n.at),
89
  read: n.read === true,
 
 
 
 
 
 
 
 
90
  });
91
  }
92
  return { unread: Math.max(0, num(b.unread)), items };
@@ -134,6 +165,24 @@ export function routeForTopic(topic: string): string | null {
134
  return null;
135
  }
136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  /** Newest first, and unread before read at the same instant β€” the inbox order.
138
  * Stable: two notifications from one write keep the server's order. */
139
  export function inboxOrder(items: Notification[]): Notification[] {
 
31
  * would re-introduce the browser-clock drift the offset exists to remove. */
32
  at: string;
33
  read: boolean;
34
+ /**
35
+ * WAVE 23 (contract C6) β€” WHAT KIND of notification this is.
36
+ *
37
+ * Absent (and every notification written before this wave) means the original one: a record
38
+ * ENTERED a watched view, routed by `topic` + `viewId`. `"automation_review"` means a card
39
+ * arrived at a review stage and routes by `autoId` instead β€” a different destination reached
40
+ * from the same list.
41
+ *
42
+ * β›” A STRING, NEVER A UNION, and that is the wave-9 law rather than laziness: the vocabulary
43
+ * is the SERVER's, and a client union over it turns "the server grew a kind" into "the client
44
+ * silently drops the row". Unknown kinds fall through to the view route, which is exactly what
45
+ * they did before this field existed.
46
+ */
47
+ kind?: string;
48
+ /** `automation_review` only: the automation whose review stage a card reached. Absent on
49
+ * every other kind β€” and an `automation_review` row that arrives WITHOUT one opens nothing
50
+ * rather than guessing, the same posture `viewId` gets. */
51
+ autoId?: string;
52
+ /** Advisory. A surface that does not scroll to a stage simply selects the automation. */
53
+ stageId?: string;
54
+ /** How many cards arrived in the batch. C6 queues ONE notification per run naming the count,
55
+ * never one per record β€” so this is the number the row's own text is built from. */
56
+ count?: number;
57
  }
58
 
59
  /** One alert, as `GET /api/v1/alerts` sends it. */
 
110
  alertLabel: str(n.alertLabel),
111
  at: str(n.at),
112
  read: n.read === true,
113
+ // WAVE 23 C6 β€” ADDITIVE and spread-conditional, exactly like `NavPage`'s flags: a payload
114
+ // that predates this wave keeps today's shape rather than gaining four `undefined` keys,
115
+ // and an `automation_review` row missing its `autoId` is left WITHOUT one rather than
116
+ // with an empty string that would render as a real destination.
117
+ ...(str(n.kind) ? { kind: str(n.kind) } : {}),
118
+ ...(str(n.autoId) ? { autoId: str(n.autoId) } : {}),
119
+ ...(str(n.stageId) ? { stageId: str(n.stageId) } : {}),
120
+ ...(num(n.count) > 0 ? { count: num(n.count) } : {}),
121
  });
122
  }
123
  return { unread: Math.max(0, num(b.unread)), items };
 
165
  return null;
166
  }
167
 
168
+ /** WAVE 23 C6 β€” the kind literal the server queues for a card reaching a review stage.
169
+ * ONE place, so the pane's branch and the gate's fixture cannot disagree about the word. */
170
+ export const AUTOMATION_REVIEW_KIND = "automation_review";
171
+
172
+ /**
173
+ * Does this notification route to an AUTOMATION rather than to a view?
174
+ *
175
+ * β›” BOTH HALVES ARE REQUIRED, and the second is the one that matters. A row whose kind says
176
+ * `automation_review` but whose `autoId` never arrived (a server mid-deploy, a truncated
177
+ * payload) would otherwise take the automation branch and dispatch an open request naming
178
+ * nothing β€” a click that appears to work and silently does not. Failing this test sends it down
179
+ * the view branch, where `routeForTopic` refuses out loud. Fail-closed in the direction that
180
+ * still says something.
181
+ */
182
+ export function isAutomationReview(n: Notification): boolean {
183
+ return n.kind === AUTOMATION_REVIEW_KIND && !!str(n.autoId).trim();
184
+ }
185
+
186
  /** Newest first, and unread before read at the same instant β€” the inbox order.
187
  * Stable: two notifications from one write keep the server's order. */
188
  export function inboxOrder(items: Notification[]): Notification[] {
web/src/apiContract.ts CHANGED
@@ -101,3 +101,49 @@ export interface ViewOpenDetail {
101
  topic: string;
102
  viewId: string;
103
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  topic: string;
102
  viewId: string;
103
  }
104
+
105
+ /**
106
+ * WAVE 23 (contract C6, wiring W23-W5) — the shell→automation channel for a review
107
+ * notification's click-through.
108
+ *
109
+ * β›” THE SAME SHAPE AS `VIEW_OPEN_EVENT` ABOVE, FOR THE SAME REASON, and wave 20 is why both
110
+ * exist as constants in this leaf rather than as a string typed twice. A card arriving at a
111
+ * review stage queues an `automation_review` notification naming `{autoId, stageId, count}`;
112
+ * clicking it has to do TWO things that live on opposite sides of an ownership fence β€” route to
113
+ * `#/automation` (the SHELL's hash) and select that automation in the rail (`AutomationSurface`'s
114
+ * own `activeId`, which the shell cannot see and must not learn). So the frame navigates and
115
+ * then ASKS, and the surface answers if it can.
116
+ *
117
+ * ⚠ THE LISTENER IS THE HALF THAT CAN BE ABSENT. Wave 20 shipped item 25's click-through with
118
+ * this exact shape and NO listener β€” the event was dispatched into nothing, every gate green,
119
+ * the notification landing the reader on the right table and doing nothing else. Declared here
120
+ * on the wave's first day precisely so the surface can wire the listener while it is being
121
+ * built rather than at close-out; the wiring row (W23-W5) asserts both ends.
122
+ *
123
+ * An automation the reader can no longer open must do NOTHING rather than throw β€” the listener
124
+ * checks its own list first, exactly as the grid does for a view it cannot see.
125
+ */
126
+ export const AUTOMATION_OPEN_EVENT = "aios:automation-open";
127
+
128
+ /** `detail` of {@link AUTOMATION_OPEN_EVENT}. `stageId` is advisory β€” a surface that does not
129
+ * scroll to a stage simply selects the automation. */
130
+ export interface AutomationOpenDetail {
131
+ autoId: string;
132
+ stageId?: string;
133
+ }
134
+
135
+ /**
136
+ * WAVE 23 (contracts C2 + C10) β€” "create an AUTOMATED database", asked from outside the
137
+ * automation surface.
138
+ *
139
+ * R7 puts an "Automated database" door on Home and in the Database flyout, and C2 makes the
140
+ * automation create wizard the thing behind it β€” because an automated database is created BY
141
+ * the automation that fills it, not by a name box that then needs one. The shell cannot open
142
+ * that wizard directly (it is the surface's own state), so it routes to `#/automation` and
143
+ * raises this; the surface opens its create flow.
144
+ *
145
+ * ⚠ NO DETAIL, deliberately. "Open the create wizard" is the whole message. Anything more β€”
146
+ * a preselected kind, a name β€” would be the shell deciding what the wizard's first step says,
147
+ * which is the surface's contract (C2's three cards), not the frame's.
148
+ */
149
+ export const AUTOMATION_CREATE_EVENT = "aios:automation-create";
web/src/automation/AutomationBoard.tsx CHANGED
@@ -115,7 +115,23 @@ export default function AutomationBoard({
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
 
@@ -176,7 +192,25 @@ export default function AutomationBoard({
176
  }, 0);
177
  }}
178
  >
179
- <span className="autob-card-title">{card.title}</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  {card.sub ? <span className="autob-card-sub">{card.sub}</span> : null}
181
  {card.movedAt ? (
182
  <span className="autob-card-when">{whenText(card.movedAt)}</span>
@@ -332,57 +366,17 @@ export default function AutomationBoard({
332
  Records appear here once this flow is bound to a database.
333
  </p>
334
  ) : null}
335
- {stripStages.length ? (
336
- <div className="autob-strip">
337
- {stripStages.map((st) => (
338
- /*
339
- ⚠ A WRAPPER, NOT ONE BUTTON, and the switch is the reason. `write` carries a
340
- toggle β€” it is the DRY-RUN control, the difference between a run that writes
341
- and a run that only reports what it would have written β€” and the strip is now
342
- the only place that stage appears. A chip that dropped it would have deleted a
343
- shipped control from the product while every gate stayed green. (Nesting the
344
- switch inside the chip's own button is not the fix: a button inside a button
345
- is invalid, and browsers un-nest it in ways that lose the inner click.)
346
- */
347
- <div
348
- key={st.id}
349
- className={
350
- "autob-strip-step" +
351
- (st.id === selected ? " is-selected" : "") +
352
- (st.enabled ? "" : " is-off")
353
- }
354
- >
355
- <button
356
- type="button"
357
- className="autob-strip-hit"
358
- aria-pressed={st.id === selected}
359
- title={st.detail || st.label}
360
- onClick={() => onSelect(st.id)}
361
- >
362
- <span className="autob-strip-label">{st.label}</span>
363
- <span
364
- className={`auto-dot is-${st.status}`}
365
- title={`Last run: ${st.status}`}
366
- aria-label={`Last run: ${st.status}`}
367
- />
368
- </button>
369
- {st.toggle ? (
370
- <button
371
- type="button"
372
- className={"auto-step-switch autob-strip-switch" + (st.enabled ? " is-on" : "")}
373
- disabled={busyStage === st.id}
374
- aria-pressed={st.enabled}
375
- aria-label={`${st.enabled ? "Turn off" : "Turn on"} ${st.label}`}
376
- title={`${st.enabled ? "Turn off" : "Turn on"} ${st.label}`}
377
- onClick={() => onToggle(st.id)}
378
- >
379
- <span className="auto-step-switch-knob" />
380
- </button>
381
- ) : null}
382
- </div>
383
- ))}
384
- </div>
385
- ) : null}
386
  <div className="autob-cols">
387
  {cols.map((col) => (
388
  <div className="autob-col" key={col}>
 
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
 
 
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>
 
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}>
web/src/automation/AutomationBuilder.tsx ADDED
@@ -0,0 +1,2097 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // automation/AutomationBuilder.tsx β€” the BUILDER (owner item 3b, contracts
3
+ // C1/C2/C4, ruling R1: "exact layout, Loopable skin").
4
+ //
5
+ // THE ANATOMY IS AIRTABLE'S, 1:1, and it is the owner's reference (images 1-9):
6
+ // a centre column of TRIGGER β†’ ACTIONS with a spine down the left carrying each
7
+ // step's status chip, dashed add-boxes at the end of each section, and a
8
+ // Properties panel on the right whose sections are Trigger details /
9
+ // Configuration / Test step. Every colour, size and weight is OURS (R1,
10
+ // DESIGN.md) β€” no Airtable blue, no caps micro-labels (R6: "TRIGGER" is
11
+ // "Trigger" here, and de-capping takes the letter-spacing with it).
12
+ //
13
+ // β›” IT RENDERS SYNCHRONOUSLY FROM WHAT IT WAS HANDED (C14 leg 1). No fetch, no
14
+ // effect, no second frame: the trigger comes from `automation.trigger`, the
15
+ // actions from `automation.flow`, the machine steps from `automation.graph` β€”
16
+ // all three already on the list payload the rail used to draw the row you
17
+ // clicked. THIS IS THE GHOST FIX. The old detail rendered Steps, then swapped to
18
+ // the Board when `/board` answered, so switching automations painted the
19
+ // PREVIOUS one's shape inside the new one's frame for as long as a fetch takes.
20
+ // A view that cannot be in two shapes cannot show you the wrong one.
21
+ //
22
+ // β›” NO CLIENT UNION OVER A SERVER VOCABULARY, anywhere. Trigger keys, action
23
+ // kinds, comparison operators, ending modes, review deciders and every ceiling
24
+ // ride `GET /automations`. What this file owns is pixels and wording.
25
+ //
26
+ // WHAT PERSISTS WHEN. A discrete choice writes immediately β€” picking a trigger,
27
+ // adding an action, flipping a switch β€” because a control you have to remember
28
+ // to Save is not a control (R9). FREE TEXT does not: a value, a prompt or a name
29
+ // commits on BLUR, or every keystroke would PATCH a half-typed condition and the
30
+ // server would refuse most of them out loud (the cron-string precedent in
31
+ // AutomationTrigger).
32
+ // ---------------------------------------------------------------------------
33
+ import type { ReactNode } from "react";
34
+ import { useRef, useState } from "react";
35
+
36
+ import type {
37
+ Action,
38
+ ActionCatalogRow,
39
+ Automation,
40
+ Cond,
41
+ FlowVocab,
42
+ GraphNode,
43
+ OAuthStatus,
44
+ TriggerOption,
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[];
81
+ vocab?: FlowVocab;
82
+ tables: UserTable[];
83
+ oauth: OAuthStatus | null;
84
+ /** True while a write is in flight β€” drives the "All changes saved" stamp and disables edits. */
85
+ busy: boolean;
86
+ /** Write a partial definition. The caller owns the request and prints the refusal verbatim. */
87
+ onPatch: (body: Record<string, unknown>) => void;
88
+ onToggleNode: (nodeId: string) => void;
89
+ /**
90
+ * β›” CHOOSING A TRIGGER IS NOT A `{trigger:{key}}` PATCH, and getting that wrong is invisible.
91
+ * `schedule` is what today's engine actually READS, so a pick has to write BOTH halves or
92
+ * "At a scheduled time" would store a key and leave the cron switched off β€” a trigger that
93
+ * says it is scheduled and never fires. The detail already owns that two-write shape
94
+ * (`pickTrigger`); the builder calls it rather than composing a second copy of it.
95
+ */
96
+ onPickTrigger: (key: string) => void;
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
113
+ * and the tick-honesty note exist exactly once, and both this view and the board render the
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;
148
+
149
+ /**
150
+ * A trigger's icon, PER KIND. Drawn, never an emoji (owner constant).
151
+ *
152
+ * ⚠ THE FIRST VERSION DREW ONE GLYPH FOR ALL ELEVEN, and reading the suggested list settled it:
153
+ * six identical arrows down the left edge is decoration, not information β€” the eye learns
154
+ * nothing and the column just gets wider. Airtable differentiates them (images 1/2) for the
155
+ * same reason. Unknown keys keep the neutral arrow, so a trigger the engine adds tomorrow
156
+ * renders plainly rather than not at all (the silent-drop rule, applied to icons).
157
+ */
158
+ function TriggerMark({ kind = "" }: { kind?: string }) {
159
+ const common = {
160
+ width: 15, height: 15, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor",
161
+ strokeWidth: 1.4, strokeLinecap: "round" as const, strokeLinejoin: "round" as const,
162
+ "aria-hidden": true,
163
+ };
164
+ if (kind === "schedule")
165
+ return (
166
+ <svg {...common}>
167
+ <circle cx="8" cy="8" r="5.6" />
168
+ <path d="M8 5.2V8l2 1.4" />
169
+ </svg>
170
+ );
171
+ if (kind === "event_field")
172
+ return (
173
+ <svg {...common}>
174
+ <path d="M2.8 3.4h10.4l-4 4.6v4.2l-2.4 1.2V8z" />
175
+ </svg>
176
+ );
177
+ if (kind === "record_created")
178
+ return (
179
+ <svg {...common}>
180
+ <rect x="3" y="2.6" width="10" height="10.8" rx="1.8" />
181
+ <path d="M8 5.8v4.4M5.8 8h4.4" />
182
+ </svg>
183
+ );
184
+ if (kind === "record_updated")
185
+ return (
186
+ <svg {...common}>
187
+ <rect x="3" y="2.6" width="10" height="10.8" rx="1.8" />
188
+ <path d="M5.8 6.4h4.4M5.8 9.2h2.6" />
189
+ </svg>
190
+ );
191
+ if (kind === "enters_view")
192
+ return (
193
+ <svg {...common}>
194
+ <path d="M1.8 8s2.4-4 6.2-4 6.2 4 6.2 4-2.4 4-6.2 4-6.2-4-6.2-4z" />
195
+ <circle cx="8" cy="8" r="1.7" />
196
+ </svg>
197
+ );
198
+ if (kind === "webhook")
199
+ return (
200
+ <svg {...common}>
201
+ <path d="M6.6 9.4 4.9 11a2.6 2.6 0 1 1-1.5-4.4" />
202
+ <path d="M9.4 6.6 11.1 5a2.6 2.6 0 1 1 1.5 4.4" />
203
+ <path d="M6.2 8h3.6" />
204
+ </svg>
205
+ );
206
+ if (kind === "email")
207
+ return (
208
+ <svg {...common}>
209
+ <rect x="2.2" y="3.6" width="11.6" height="8.8" rx="1.6" />
210
+ <path d="m2.6 4.6 5.4 3.8 5.4-3.8" />
211
+ </svg>
212
+ );
213
+ if (kind === "form_submitted")
214
+ return (
215
+ <svg {...common}>
216
+ <rect x="3" y="2.6" width="10" height="10.8" rx="1.8" />
217
+ <path d="M5.8 6h4.4M5.8 8.6h2.2M9 11l1.2 1.2L12.6 9.8" />
218
+ </svg>
219
+ );
220
+ if (kind === "button_clicked")
221
+ return (
222
+ <svg {...common}>
223
+ <path d="M6 3.2v6.2l1.6-1.4 1.4 3 1.6-.8-1.4-2.8 2.2-.2z" />
224
+ </svg>
225
+ );
226
+ if (kind === "comment_added")
227
+ return (
228
+ <svg {...common}>
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" />
251
+ <path d="M10.2 9.2 12.8 11.2 10.2 13.2" />
252
+ </svg>
253
+ );
254
+ }
255
+
256
+ function ActionMark({ kind }: { kind: string }) {
257
+ const common = {
258
+ width: 15, height: 15, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor",
259
+ strokeWidth: 1.4, strokeLinecap: "round" as const, strokeLinejoin: "round" as const,
260
+ "aria-hidden": true,
261
+ };
262
+ if (kind === "group")
263
+ return (
264
+ <svg {...common}>
265
+ <path d="M2.6 8h3l2.6-3.6h5M8.2 11.6H5.6m2.6 0h5" />
266
+ <path d="M11.6 2.6 13.4 4.4 11.6 6.2M11.6 9.8l1.8 1.8-1.8 1.8" />
267
+ </svg>
268
+ );
269
+ if (kind === "review")
270
+ return (
271
+ <svg {...common}>
272
+ <circle cx="8" cy="5.6" r="2.6" />
273
+ <path d="M3 13.4c.7-2.3 2.6-3.6 5-3.6s4.3 1.3 5 3.6" />
274
+ </svg>
275
+ );
276
+ if (kind === "create_record")
277
+ return (
278
+ <svg {...common}>
279
+ <rect x="2.6" y="2.6" width="10.8" height="10.8" rx="2" />
280
+ <path d="M8 5.6v4.8M5.6 8h4.8" />
281
+ </svg>
282
+ );
283
+ if (kind === "find_records")
284
+ return (
285
+ <svg {...common}>
286
+ <circle cx="7.2" cy="7.2" r="4" />
287
+ <path d="m10.2 10.2 3.2 3.2" />
288
+ </svg>
289
+ );
290
+ /*
291
+ ⚠ THE MACHINE KINDS ARE HERE TOO, and leaving them out was a real defect for one render:
292
+ the engine's nodes are `source | capture | branch | write`, none of which matched above, so
293
+ "Write to the database" and "Fetch the page" both drew the PENCIL β€” an edit glyph on a step
294
+ that reads a web page and a step that writes a database. Caught by reading the screenshot,
295
+ not by a gate ([[ui-invisible-to-assertions]]): the icon was present, legible and wrong.
296
+ These are the shapes the retired `AutomationSteps.KindMark` used, kept with their meanings.
297
+ */
298
+ if (kind === "source")
299
+ return (
300
+ <svg {...common}>
301
+ <circle cx="8" cy="8" r="5.6" />
302
+ <path d="M2.6 8h10.8M8 2.4c1.5 1.7 2.2 3.6 2.2 5.6S9.5 12.3 8 13.6C6.5 12.3 5.8 10 5.8 8s.7-3.9 2.2-5.6z" />
303
+ </svg>
304
+ );
305
+ if (kind === "write")
306
+ return (
307
+ <svg {...common}>
308
+ <ellipse cx="8" cy="4.2" rx="4.8" ry="1.9" />
309
+ <path d="M3.2 4.2v7.6c0 1 2.1 1.9 4.8 1.9s4.8-.9 4.8-1.9V4.2M3.2 8c0 1 2.1 1.9 4.8 1.9s4.8-.9 4.8-1.9" />
310
+ </svg>
311
+ );
312
+ if (kind === "capture")
313
+ return (
314
+ <svg {...common}>
315
+ <path d="M8 2.6v7.2M5.2 7l2.8 2.8L10.8 7M3 12.4h10" />
316
+ </svg>
317
+ );
318
+ if (kind === "branch")
319
+ return (
320
+ <svg {...common}>
321
+ <path d="M2.6 8h3.2l2.6-3.6h5M8.4 11.6H5.8m2.6 0h5" />
322
+ <path d="M11.6 2.6 13.4 4.4 11.6 6.2M11.6 9.8l1.8 1.8-1.8 1.8" />
323
+ </svg>
324
+ );
325
+ if (kind === "update_record")
326
+ return (
327
+ <svg {...common}>
328
+ <path d="M11.4 2.8 13.2 4.6 6 11.8l-2.6.8.8-2.6z" />
329
+ <path d="M3 13.6h10" />
330
+ </svg>
331
+ );
332
+ if (kind === "send_email")
333
+ return (
334
+ <svg {...common}>
335
+ <rect x="2.2" y="3.6" width="11.6" height="8.8" rx="1.6" />
336
+ <path d="m2.6 4.6 5.4 3.8 5.4-3.8" />
337
+ </svg>
338
+ );
339
+ if (kind === "slack")
340
+ return (
341
+ <svg {...common}>
342
+ <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" />
343
+ </svg>
344
+ );
345
+ if (kind === "run_script")
346
+ return (
347
+ <svg {...common}>
348
+ <path d="M5.6 5.4 3 8l2.6 2.6M10.4 5.4 13 8l-2.6 2.6M9 3.4 7 12.6" />
349
+ </svg>
350
+ );
351
+ if (kind === "generate_ai")
352
+ return (
353
+ <svg {...common}>
354
+ <path d="M8 2.4l1.5 3.4 3.4 1.5-3.4 1.5L8 12.2 6.5 8.8 3.1 7.3l3.4-1.5z" />
355
+ </svg>
356
+ );
357
+ if (kind === "repeating_group")
358
+ return (
359
+ <svg {...common}>
360
+ <path d="M3 8a5 5 0 0 1 5-5c2 0 3.4 1 4.3 2.4M13 8a5 5 0 0 1-5 5c-2 0-3.4-1-4.3-2.4" />
361
+ <path d="M12.4 2.6v2.9h-2.9M3.6 13.4v-2.9h2.9" />
362
+ </svg>
363
+ );
364
+ /*
365
+ β›” THE FALLBACK IS NEUTRAL, and it was not the first time round. The default used to BE the
366
+ pencil β€” a real member of the set (`update_record`) β€” so every kind with no arm silently
367
+ borrowed "edit": `send_email`, `run_script` and `repeating_group` all drew it in the action
368
+ menu, which reads as three actions that modify a record. A fallback that is a real member
369
+ cannot be told apart from a match; this one can.
370
+ */
371
+ return (
372
+ <svg {...common}>
373
+ <rect x="3.2" y="3.2" width="9.6" height="9.6" rx="2.2" />
374
+ <circle cx="8" cy="8" r="1.4" />
375
+ </svg>
376
+ );
377
+ }
378
+
379
+ /** The label a table key reads as. A raw `ut_9f3a…` on a card is a key, not a subtitle. */
380
+ function tableLabel(tables: UserTable[], key: string): string {
381
+ if (!key) return "";
382
+ return tables.find((t) => t.key === key)?.label || key;
383
+ }
384
+
385
+ export default function AutomationBuilder({
386
+ automation,
387
+ name,
388
+ onNameText,
389
+ onNameCommit,
390
+ triggers,
391
+ catalog,
392
+ vocab,
393
+ tables,
394
+ oauth,
395
+ busy,
396
+ onPatch,
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");
424
+ const options = triggers || [];
425
+ const picked = options.find((t) => t.key === triggerKey) || null;
426
+ const actions = automation.flow?.actions || [];
427
+ const nodes = (automation.graph?.nodes || []).filter((n) => n.kind !== "trigger");
428
+ const ops = vocab?.condOps || [];
429
+ const nullaryOps = vocab?.nullaryCondOps || [];
430
+ const table = tables.find((t) => t.key === (trigger?.table || "")) || null;
431
+
432
+ /**
433
+ * β›” HAS ANYTHING BEEN CHOSEN? β€” and the first version of this line was wrong in a way only
434
+ * a screenshot showed.
435
+ *
436
+ * It read `!!trigger || key === "schedule" || key === "manual"`, and `triggerKey` DERIVES
437
+ * "manual" whenever nothing is stored β€” so it was true for every automation ever, and the
438
+ * Airtable empty state (image 1) was unreachable code that every gate was happy with.
439
+ *
440
+ * The honest test is what the DEFINITION holds, not what the picker displays: the engine
441
+ * deliberately stores no trigger for manual/schedule ("`schedule` already owns the cron"), so
442
+ * `trigger === null && !schedule.enabled` IS "nobody has decided yet". Manual is what that
443
+ * state DOES, not a thing you pick out of it β€” which is why the suggested list below omits
444
+ * it: an option whose selection stores nothing would bounce straight back to this state on
445
+ * the next reload, and a control that undoes itself is worse than no control.
446
+ */
447
+ const chosen = !!trigger || !!automation.schedule?.enabled;
448
+ const configured = !trigger || trigger.configured !== false;
449
+
450
+ /** Write one key of the trigger, keeping the rest β€” the engine merges against `previous`. */
451
+ const patchTrigger = (patch: Record<string, unknown>) =>
452
+ onPatch({ trigger: { key: triggerKey, ...patch } });
453
+
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
521
+ * gate was green and the harness could not see it (SSR renders no click).
522
+ *
523
+ * MEASURED against `clean_actions` itself (`python -c` over the engine module, no server):
524
+ * `{values:{"":""}}` -> "a value is written to a field with no name"
525
+ * `{table:"",values:…}` -> the same, twice
526
+ * `{table:""}` (find) -> "the find records action names no database"
527
+ * `{cond:…,actions:[]}` -> "a conditional group with no actions inside it does nothing"
528
+ * So clicking "Add β†’ Update record" would have produced a red banner and NO CARD. This is the
529
+ * wave-22 discovery-predicate scar reproduced exactly ([[cg-condition-builder-items]] β€” every
530
+ * default must be one the server takes), in a file whose own comment cites it.
531
+ *
532
+ * The seeds below are built from data this component already holds, and `seedFor` returns
533
+ * NULL when it cannot build a legal one. A kind with no legal seed is offered DISABLED with
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 || "";
551
+
552
+ const seedFor = (kind: string): Record<string, unknown> | null => {
553
+ if (kind === "review")
554
+ return { decidedBy: "user", label: "Review", next: ["Approved", "Declined"], prompt: "" };
555
+ if (kind === "update_record")
556
+ return firstField ? { values: { [firstField]: "" } } : null;
557
+ if (kind === "create_record")
558
+ return firstTable && firstTableField
559
+ ? { table: firstTable.key, values: { [firstTableField]: "" } }
560
+ : null;
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
+ };
599
+
600
+ /** Why a kind cannot be added yet β€” the server's own precondition, said before the click. */
601
+ const seedBlock = (kind: string): string => {
602
+ if (kind === "update_record" || kind === "group")
603
+ return "Name the trigger's database first β€” this needs a column to write.";
604
+ if (kind === "create_record" || kind === "find_records")
605
+ return "There is no blank database to point at yet.";
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;
722
+ if (!configured)
723
+ return (
724
+ <span className="autox-chip is-warn" title="This trigger cannot fire until it is finished">
725
+ Finish configuration
726
+ </span>
727
+ );
728
+ if (trigger?.paused)
729
+ return <span className="autox-chip is-warn">Paused</span>;
730
+ if (picked && picked.ready === false)
731
+ return <span className="autox-chip is-warn">Not set up</span>;
732
+ const last = automation.runs?.[0];
733
+ if (last)
734
+ return (
735
+ <span className="autox-chip is-ok" title={last.summary}>
736
+ {last.ok ? "Last run succeeded" : "Last run failed"}
737
+ </span>
738
+ );
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
+ /**
747
+ * ⭐ THE PERMANENT FIRST STEP (owner ruling 2026-08-06). An Instagram search produces rows
748
+ * and has nowhere to put them until something writes them, so Create record is step 1 and
749
+ * stays. DERIVED from the same rule the server enforces (`ig_action_pinned`) rather than
750
+ * from a stored flag β€” and the control is HIDDEN rather than disabled, because the server
751
+ * re-inserts the action on the next save, so a delete button here would appear to work and
752
+ * then silently undo itself.
753
+ */
754
+ const pinned =
755
+ automation.kind === "discover_instagram" && depth === 0 && a.id === actions[0]?.id;
756
+ /** Only TOP-LEVEL cards reorder (see `moveAction`) β€” depth 0, and never while a write is up. */
757
+ const canDrag = depth === 0 && !busy && !pinned;
758
+ return (
759
+ <div className="autox-actionwrap" key={a.id}>
760
+ <div
761
+ className={
762
+ "autox-card" +
763
+ (sel.kind === "action" && sel.id === a.id ? " is-selected" : "") +
764
+ (a.enabled ? "" : " is-off") +
765
+ (isGroup ? " is-group" : "") +
766
+ /* ⚠ THE GUARD IS NOT DECORATION. `dragOver` idles at `""` and a fresh action carries
767
+ `id: ""` until the server names it, so a bare `dragOver === a.id` would be
768
+ `"" === ""` β€” TRUE AT REST β€” and every new card would paint as a drop target from
769
+ its first frame. That is wave 20's `is-folddrag` defect exactly, which shipped and
770
+ was seen by the owner before any gate noticed. */
771
+ (dragOver && dragOver === a.id ? " is-dropinto" : "")
772
+ }
773
+ draggable={canDrag}
774
+ onDragStart={
775
+ canDrag
776
+ ? (e) => {
777
+ draggedRef.current = true;
778
+ e.dataTransfer.effectAllowed = "move";
779
+ e.dataTransfer.setData(ACTION_DRAG_TYPE, a.id);
780
+ }
781
+ : undefined
782
+ }
783
+ onDragOver={
784
+ canDrag
785
+ ? (e) => {
786
+ // Somebody else's drag β€” a file, a nav row, selected text β€” is not ours to
787
+ // accept. Without this test the card would light up for anything dragged over
788
+ // it and then swallow the drop.
789
+ if (!e.dataTransfer.types.includes(ACTION_DRAG_TYPE)) return;
790
+ e.preventDefault();
791
+ e.dataTransfer.dropEffect = "move";
792
+ setDragOver(a.id);
793
+ }
794
+ : undefined
795
+ }
796
+ onDragLeave={
797
+ canDrag
798
+ ? (e) => {
799
+ // Moving onto a CHILD of this card is not leaving it; without this the
800
+ // highlight flickers off every time the pointer crosses the title.
801
+ if (e.currentTarget.contains(e.relatedTarget as Node)) return;
802
+ setDragOver((cur) => (cur === a.id ? "" : cur));
803
+ }
804
+ : undefined
805
+ }
806
+ onDrop={
807
+ canDrag
808
+ ? (e) => {
809
+ const dragId = e.dataTransfer.getData(ACTION_DRAG_TYPE);
810
+ setDragOver("");
811
+ if (!dragId) return;
812
+ e.preventDefault();
813
+ moveAction(dragId, a.id);
814
+ }
815
+ : undefined
816
+ }
817
+ onDragEnd={() => {
818
+ setDragOver("");
819
+ // Cleared a tick later: the post-drag click arrives BEFORE this would run.
820
+ window.setTimeout(() => {
821
+ draggedRef.current = false;
822
+ }, 0);
823
+ }}
824
+ >
825
+ <button
826
+ type="button"
827
+ className="autox-card-hit"
828
+ aria-pressed={sel.kind === "action" && sel.id === a.id}
829
+ onClick={() => {
830
+ // The one click a finished drag is allowed to cost is this one.
831
+ if (draggedRef.current) return;
832
+ setSel({ kind: "action", id: a.id });
833
+ }}
834
+ >
835
+ {/* ⭐ R8's STEP NUMBER, computed once for the whole flow (`numberActions`). The
836
+ TRIGGER carries no number at all β€” that is the ruling, and it reverses wave 21's
837
+ "Step 1 is always the Trigger" β€” so the numbers here start at 1 on the first
838
+ ACTION. A fork occupies one number and its branches consume none. */}
839
+ <span className="autox-card-n">{stepNos.get(a.id) || ""}</span>
840
+ <span className="autox-card-mark">
841
+ <ActionMark kind={a.kind} />
842
+ </span>
843
+ <span className="autox-card-text">
844
+ <span className="autox-card-title">
845
+ {/* β›” NOT "If conditions are met" ANY MORE, and the literal was the problem
846
+ rather than the wording. C-ACT relabels the `group` kind to "If / then" on
847
+ the SERVER, so a hard-coded title here was a client paraphrase of a server
848
+ vocabulary β€” it would have gone on saying the old words after the catalog
849
+ changed, which is the one failure this file's header names twice. */}
850
+ {row?.label || a.kind}
851
+ </span>
852
+ {isGroup ? (
853
+ <span className="autox-card-sub">
854
+ {branches.length === 1
855
+ ? "1 branch"
856
+ : `${branches.length} branches`}
857
+ </span>
858
+ ) : (
859
+ <span className="autox-card-sub">{actionSub(a, tables)}</span>
860
+ )}
861
+ </span>
862
+ </button>
863
+ {pinned ? (
864
+ <span className="autox-card-pin" title="Every search saves what it finds">
865
+ Always first
866
+ </span>
867
+ ) : (
868
+ <button
869
+ type="button"
870
+ className="autox-card-drop"
871
+ disabled={busy}
872
+ aria-label={`Remove ${row?.label || a.kind}`}
873
+ title={`Remove ${row?.label || a.kind}`}
874
+ onClick={() => dropAction(a.id)}
875
+ >
876
+ <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
877
+ <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
878
+ strokeLinecap="round" />
879
+ </svg>
880
+ </button>
881
+ )}
882
+ </div>
883
+
884
+ {/*
885
+ ⭐ THE FORK (owner item 12a, ruling R8, contract C-FORK). A group used to hold ONE
886
+ nested column; it now holds a LETTERED LANE PER BRANCH, because R8 rules that a fork
887
+ occupies one step number and its legs are alternatives rather than later steps.
888
+
889
+ THE LETTER AND THE "Otherwise" ARE THE SERVER'S WORDS β€” `br.label`, printed, never
890
+ composed. `clean_actions` letters by index and names a null-cond last leg "Otherwise",
891
+ so the lanes re-letter themselves correctly when one is deleted.
892
+ The nesting ceiling is still the SERVER's `maxGroupDepth`, so the add-here affordance
893
+ disappears at exactly the depth `clean_actions` refuses.
894
+ */}
895
+ {isGroup ? (
896
+ <div className="autox-branches">
897
+ {branches.map((br) => (
898
+ <div className="autox-branch" key={br.id || br.label}>
899
+ <div className="autox-branch-head">
900
+ <span className="autox-branch-letter">{br.label}</span>
901
+ <span className="autox-branch-cond">
902
+ {/* ⚠ NOT A RENDERED CONDITION β€” the tree is edited in Properties, and a
903
+ second editable copy here would be two controls for one fact. This says
904
+ only WHICH leg you are looking at. A null cond is the catch-all, and the
905
+ server has already labelled it, so this says nothing twice. */}
906
+ {br.cond ? "when its conditions match" : "everything else"}
907
+ </span>
908
+ {branches.length > 1 ? (
909
+ <button
910
+ type="button"
911
+ className="autox-branch-x"
912
+ disabled={busy}
913
+ aria-label={`Remove branch ${br.label}`}
914
+ title={`Remove branch ${br.label}`}
915
+ onClick={() => dropBranch(a.id, br.id)}
916
+ >
917
+ <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
918
+ <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
919
+ strokeLinecap="round" />
920
+ </svg>
921
+ </button>
922
+ ) : null}
923
+ </div>
924
+ <div className="autox-nest">
925
+ {(br.actions || []).map((k) => actionCard(k, depth + 1))}
926
+ {depth + 1 < (vocab?.maxGroupDepth ?? 2) || !(br.actions || []).length ? (
927
+ <button
928
+ type="button"
929
+ className="autox-add is-nested"
930
+ disabled={busy || !seedFor("update_record")}
931
+ title={seedFor("update_record") ? undefined : seedBlock("update_record")}
932
+ onClick={() => addAction("update_record", { actionId: a.id, branchId: br.id })}
933
+ >
934
+ + Add an action in {br.label}
935
+ </button>
936
+ ) : null}
937
+ </div>
938
+ </div>
939
+ ))}
940
+ <button
941
+ type="button"
942
+ className="autox-add is-nested"
943
+ disabled={busy || !seedFor("update_record")}
944
+ title={seedFor("update_record") ? undefined : seedBlock("update_record")}
945
+ onClick={() => addBranch(a.id)}
946
+ >
947
+ + Add a branch
948
+ </button>
949
+ </div>
950
+ ) : null}
951
+
952
+ {/*
953
+ THE ARROW BACK INTO THE FLOW (item 12a). The lanes are alternatives and exactly one of
954
+ them runs β€” the engine takes the first matching branch and breaks β€” so they REJOIN, and
955
+ without a mark saying so a fork at the end of a column reads as several parallel endings.
956
+ Drawn only when there IS a next step to rejoin: an arrow into nothing is a promise the
957
+ flow does not keep.
958
+ */}
959
+ {isGroup && hasNext ? (
960
+ <div className="autox-merge" aria-hidden="true">
961
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor"
962
+ strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
963
+ <path d="M8 2.6v10.8M5.2 10.6 8 13.4l2.8-2.8" />
964
+ </svg>
965
+ </div>
966
+ ) : null}
967
+ </div>
968
+ );
969
+ };
970
+
971
+ return (
972
+ <>
973
+ <div className="autox-flow">
974
+ {/* ── TRIGGER ─────────────────────────────────────────────────────────────────── */}
975
+ <div className="autox-step">
976
+ <div className="autox-side">
977
+ <span className="autox-tag">Trigger</span>
978
+ {chip()}
979
+ </div>
980
+ <div className="autox-main">
981
+ {chosen && options.length ? (
982
+ <div
983
+ className={
984
+ "autox-card is-trigger" + (sel.kind === "trigger" ? " is-selected" : "")
985
+ }
986
+ >
987
+ <button
988
+ type="button"
989
+ className="autox-card-hit"
990
+ aria-pressed={sel.kind === "trigger"}
991
+ onClick={() => setSel({ kind: "trigger", id: "" })}
992
+ >
993
+ <span className="autox-card-mark">
994
+ <TriggerMark kind={triggerKey} />
995
+ </span>
996
+ <span className="autox-card-text">
997
+ <span className="autox-card-title">
998
+ {picked?.label || triggerKey}
999
+ </span>
1000
+ {trigger?.table ? (
1001
+ <span className="autox-card-sub">
1002
+ In {tableLabel(tables, trigger.table)}
1003
+ </span>
1004
+ ) : null}
1005
+ </span>
1006
+ </button>
1007
+ </div>
1008
+ ) : (
1009
+ /*
1010
+ THE EMPTY STATE (image 1): a dashed add-box and the server's own suggested
1011
+ triggers. One line of chrome, no tour (R13) β€” the list IS the explanation, and
1012
+ it is the server's list so it cannot describe a trigger we removed.
1013
+ */
1014
+ <>
1015
+ <button
1016
+ type="button"
1017
+ className="autox-add is-empty"
1018
+ disabled={busy || !options.length}
1019
+ onClick={() => setPicking(true)}
1020
+ >
1021
+ + Add trigger
1022
+ </button>
1023
+ {options.length ? (
1024
+ <div className="autox-suggest">
1025
+ <p className="autox-suggest-head">Suggested triggers</p>
1026
+ {options
1027
+ .filter((t) => t.ready !== false && !t.planned && t.key !== "manual")
1028
+ .slice(0, SUGGESTED)
1029
+ .map((t) => (
1030
+ <button
1031
+ key={t.key}
1032
+ type="button"
1033
+ className="autox-suggest-row"
1034
+ disabled={busy}
1035
+ onClick={() => onPickTrigger(t.key)}
1036
+ >
1037
+ <span className="autox-card-mark">
1038
+ <TriggerMark kind={t.key} />
1039
+ </span>
1040
+ {t.label}
1041
+ </button>
1042
+ ))}
1043
+ </div>
1044
+ ) : (
1045
+ <p className="auto-note">This server did not offer a trigger list.</p>
1046
+ )}
1047
+ {/* ONE LINE (R13), and it is what is TRUE of this state rather than a caption
1048
+ for the box above it: with nothing chosen, Run now is the only thing that
1049
+ starts this automation. Airtable's empty state means "it cannot run"; ours
1050
+ does not, and saying so is the difference between a screen that is honest
1051
+ and one that merely looks the same. */}
1052
+ <p className="auto-hint">Until then, only Run now starts it.</p>
1053
+ </>
1054
+ )}
1055
+ </div>
1056
+ </div>
1057
+
1058
+ {/* ── ACTIONS ─────────────────────────────────────────────────────────────────── */}
1059
+ <div className="autox-step">
1060
+ <div className="autox-side">
1061
+ <span className="autox-tag">Actions</span>
1062
+ </div>
1063
+ <div className="autox-main">
1064
+ {actions.map((a, i) => actionCard(a, 0, i < actions.length - 1))}
1065
+
1066
+ {/*
1067
+ β›” THE MACHINE STEPS ARE NOT CARDS ANY MORE (owner item 5, contract C-CFG). They
1068
+ were engine-derived read-only cards sitting under the owner's own actions β€” "fetch
1069
+ the page", "Bright Data", "Anonymous", "Write" β€” so the centre column mixed two
1070
+ different things: what the AUTOMATION is, which nobody chose and nobody can reorder,
1071
+ and what the OWNER added, which is the whole subject of this builder. Their
1072
+ configuration and their switches moved to Properties β†’ Configuration β†’
1073
+ "How this fetches", one section per panel.
1074
+
1075
+ ⚠ THE ENGINE STILL RUNS THEM. `graph()` emits the same nodes; this surface simply
1076
+ stops DRAWING them, which is why the switches had to move rather than go β€” R7 names
1077
+ Bright Data (money) and Write's dry run (reads and reports without writing a row) as
1078
+ controls that must survive the cards that carried them.
1079
+ */}
1080
+
1081
+ <button
1082
+ type="button"
1083
+ className="autox-add"
1084
+ disabled={busy || !catalog.length}
1085
+ onClick={() => setAdding((v) => !v)}
1086
+ >
1087
+ + Add advanced logic or action
1088
+ </button>
1089
+
1090
+ {/* THE ACTION MENU (images 7/8): the server's catalog, grouped by its own `group`
1091
+ key, with `ready:false` rows faded and carrying the server's reason. A shorter
1092
+ menu would imply those actions do not exist β€” the owner asked to see all of
1093
+ them, and `clean_actions` refuses the unready ones at the door, so faded is a
1094
+ wall rather than a decoration. */}
1095
+ {adding ? (
1096
+ <div className="autox-menu" role="menu">
1097
+ {menuGroups.map((group) => (
1098
+ <div className="autox-menu-group" key={group}>
1099
+ <p className="autox-menu-head">{group}</p>
1100
+ {catalog
1101
+ .filter((c) => c.group === group)
1102
+ .map((c) => (
1103
+ <button
1104
+ key={c.kind}
1105
+ type="button"
1106
+ className={
1107
+ "autox-menu-row" +
1108
+ (c.ready && seedFor(c.kind) ? "" : " is-planned")
1109
+ }
1110
+ disabled={!c.ready || busy || !seedFor(c.kind)}
1111
+ title={
1112
+ c.ready && !seedFor(c.kind) ? seedBlock(c.kind) : c.detail
1113
+ }
1114
+ onClick={() => addAction(c.kind)}
1115
+ >
1116
+ <span className="autox-card-mark">
1117
+ <ActionMark kind={c.kind} />
1118
+ </span>
1119
+ <span className="autox-menu-text">
1120
+ <span className="autox-menu-label">
1121
+ {c.label}
1122
+ {!c.ready ? (
1123
+ <span className="autox-soon">Coming soon</span>
1124
+ ) : !seedFor(c.kind) ? (
1125
+ /* NOT the same state as "coming soon", so not the same word:
1126
+ this one is built and waiting on THIS automation, and the
1127
+ title says exactly what is missing. */
1128
+ <span className="autox-soon">Needs a database</span>
1129
+ ) : null}
1130
+ </span>
1131
+ <span className="autox-menu-detail">{c.detail}</span>
1132
+ </span>
1133
+ </button>
1134
+ ))}
1135
+ </div>
1136
+ ))}
1137
+ </div>
1138
+ ) : null}
1139
+ </div>
1140
+ </div>
1141
+ </div>
1142
+
1143
+ {/* ── PROPERTIES ──────────────────────────────────────────────────────────────────── */}
1144
+ <aside className="auto-panel autox-props" aria-label="Properties">
1145
+ <div className="auto-panel-head">
1146
+ <h2>Properties</h2>
1147
+ {/*
1148
+ THREE STATES, because this panel now holds two save disciplines. The discrete choices
1149
+ (a trigger, an action, a switch, a branch) persist as they are made; the machine
1150
+ steps' fields, which moved in here with item 5, commit with the header's Save. A
1151
+ two-state stamp had to be wrong about one of them, and "All changes saved" printed
1152
+ over an unsaved column map is the direction that loses work.
1153
+ */}
1154
+ <span
1155
+ className={"autox-saved" + (busy ? " is-busy" : dirty ? " is-dirty" : "")}
1156
+ >
1157
+ {busy ? "Saving…" : dirty ? "Unsaved changes β€” press Save" : "All changes saved"}
1158
+ </span>
1159
+ </div>
1160
+
1161
+ {/*
1162
+ ⭐ THE NAME (item 15b). It is ABOVE the selection-dependent body rather than inside the
1163
+ trigger's face, because it is a property of the AUTOMATION and not of whichever step
1164
+ happens to be selected β€” clicking an action card must not make the name disappear.
1165
+ It commits on blur; the caller writes it and prints any refusal.
1166
+ */}
1167
+ <div className="auto-field">
1168
+ <label htmlFor="autox-name">Name</label>
1169
+ <input
1170
+ id="autox-name"
1171
+ className="auto-input"
1172
+ value={name}
1173
+ disabled={busy}
1174
+ placeholder="Name this automation"
1175
+ onChange={(e) => onNameText(e.target.value)}
1176
+ onBlur={() => onNameCommit()}
1177
+ />
1178
+ </div>
1179
+
1180
+ {sel.kind === "trigger" ? (
1181
+ <TriggerProps
1182
+ automation={automation}
1183
+ triggerKey={triggerKey}
1184
+ options={options}
1185
+ picked={picked}
1186
+ table={table}
1187
+ tables={tables}
1188
+ ops={ops}
1189
+ nullaryOps={nullaryOps}
1190
+ vocab={vocab}
1191
+ oauth={oauth}
1192
+ busy={busy}
1193
+ nodes={nodes}
1194
+ onToggleNode={onToggleNode}
1195
+ renderNodeBody={renderNodeBody}
1196
+ onAskChange={setConfirmKey}
1197
+ onPatchTrigger={patchTrigger}
1198
+ onPickTrigger={onPickTrigger}
1199
+ onRunNow={onRunNow}
1200
+ scheduleFace={scheduleFace}
1201
+ schedules={schedules}
1202
+ />
1203
+ ) : (
1204
+ <ActionProps
1205
+ action={findAction(actions, sel.id)}
1206
+ catalog={catalog}
1207
+ tables={tables}
1208
+ walkFields={walkFields}
1209
+ ops={ops}
1210
+ nullaryOps={nullaryOps}
1211
+ vocab={vocab}
1212
+ busy={busy}
1213
+ onEdit={(change) => editAction(sel.id, change)}
1214
+ />
1215
+ )}
1216
+ </aside>
1217
+
1218
+ {/* THE CONFIRM (image 6). A trigger change can invalidate the configuration under it, so
1219
+ it ASKS β€” and it says what it will cost rather than "are you sure". */}
1220
+ {confirmKey ? (
1221
+ <div className="autox-confirm" role="dialog" aria-label="Change the trigger">
1222
+ <p className="autox-confirm-title">Change the trigger?</p>
1223
+ <p className="autox-confirm-body">
1224
+ Anything configured for {picked?.label || triggerKey} is dropped.
1225
+ </p>
1226
+ <div className="autox-confirm-acts">
1227
+ <button type="button" className="auto-btn" onClick={() => setConfirmKey("")}>
1228
+ Cancel
1229
+ </button>
1230
+ <button
1231
+ type="button"
1232
+ className="auto-btn is-danger"
1233
+ onClick={() => {
1234
+ onPickTrigger(confirmKey);
1235
+ setConfirmKey("");
1236
+ }}
1237
+ >
1238
+ Change trigger
1239
+ </button>
1240
+ </div>
1241
+ </div>
1242
+ ) : null}
1243
+
1244
+ {/* The picker, opened from the empty state's dashed box (image 2). */}
1245
+ {picking ? (
1246
+ <div className="autox-menu is-trigger" role="menu">
1247
+ {options.map((t) => (
1248
+ <button
1249
+ key={t.key}
1250
+ type="button"
1251
+ className={"autox-menu-row" + (t.planned ? " is-planned" : "")}
1252
+ disabled={!!t.planned || busy}
1253
+ onClick={() => {
1254
+ onPickTrigger(t.key);
1255
+ setPicking(false);
1256
+ }}
1257
+ >
1258
+ <span className="autox-card-mark">
1259
+ <TriggerMark kind={t.key} />
1260
+ </span>
1261
+ <span className="autox-menu-text">
1262
+ <span className="autox-menu-label">
1263
+ {t.label}
1264
+ {t.planned ? <span className="autox-soon">Coming soon</span> : null}
1265
+ {!t.planned && t.ready === false ? (
1266
+ <span className="autox-soon">Needs setting up</span>
1267
+ ) : null}
1268
+ </span>
1269
+ </span>
1270
+ </button>
1271
+ ))}
1272
+ </div>
1273
+ ) : null}
1274
+ </>
1275
+ );
1276
+ }
1277
+
1278
+ /** One action's subtitle β€” what it will DO, composed from its own config. */
1279
+ function actionSub(a: Action, tables: UserTable[]): string {
1280
+ const cfg = a.config || {};
1281
+ if (a.kind === "update_record") {
1282
+ const keys = Object.keys((cfg as { values?: Record<string, unknown> }).values || {})
1283
+ .filter(Boolean);
1284
+ return keys.length ? `Sets ${keys.join(", ")}` : "No values yet";
1285
+ }
1286
+ if (a.kind === "create_record") {
1287
+ const t = String((cfg as { table?: string }).table || "");
1288
+ return t ? `Into ${tableLabel(tables, t)}` : "No database yet";
1289
+ }
1290
+ if (a.kind === "find_records") {
1291
+ const t = String((cfg as { table?: string }).table || "");
1292
+ return t ? `In ${tableLabel(tables, t)}` : "No database yet";
1293
+ }
1294
+ if (a.kind === "review") {
1295
+ const by = String((cfg as { decidedBy?: string }).decidedBy || "user");
1296
+ return by === "ai" ? "Decided by AI" : "Decided by a person";
1297
+ }
1298
+ return "";
1299
+ }
1300
+
1301
+ function findAction(list: Action[], id: string): Action | null {
1302
+ for (const a of list) {
1303
+ if (a.id === id) return a;
1304
+ // ⚠ THROUGH THE BRANCHES (C-FORK). This read `config.actions`, which a fork no longer has β€”
1305
+ // so selecting any action inside one would have found nothing and the Properties panel would
1306
+ // have said "that action is no longer part of this flow" about a card visibly on screen.
1307
+ if (a.kind === "group")
1308
+ for (const br of groupBranches(a)) {
1309
+ const hit = findAction(br.actions || [], id);
1310
+ if (hit) return hit;
1311
+ }
1312
+ }
1313
+ return null;
1314
+ }
1315
+
1316
+ /*
1317
+ * β›” `nodePanel()` IS GONE (item 5). It rendered ONE machine node's panel, chosen by the card the
1318
+ * reader had clicked, and included a "that step is no longer part of this automation" branch for
1319
+ * a selection the graph had since dropped. Both facts died with the cards: the panels are now
1320
+ * rendered together under "How this fetches", keyed by PANEL rather than by node id, so there is
1321
+ * no selection left to go stale.
1322
+ */
1323
+
1324
+ // ── the Properties panel's two faces ─────────────────────────────────────────────────────────
1325
+
1326
+ function TriggerProps({
1327
+ automation,
1328
+ triggerKey,
1329
+ options,
1330
+ picked,
1331
+ table,
1332
+ tables,
1333
+ ops,
1334
+ nullaryOps,
1335
+ vocab,
1336
+ oauth,
1337
+ busy,
1338
+ nodes,
1339
+ onToggleNode,
1340
+ renderNodeBody,
1341
+ onAskChange,
1342
+ onPatchTrigger,
1343
+ onPickTrigger,
1344
+ onRunNow,
1345
+ scheduleFace,
1346
+ schedules,
1347
+ }: {
1348
+ automation: Automation;
1349
+ triggerKey: string;
1350
+ options: TriggerOption[];
1351
+ picked: TriggerOption | null;
1352
+ table: UserTable | null;
1353
+ tables: UserTable[];
1354
+ ops: string[];
1355
+ nullaryOps: string[];
1356
+ vocab?: FlowVocab;
1357
+ oauth: OAuthStatus | null;
1358
+ busy: boolean;
1359
+ /** The engine's machine steps (item 5) β€” their switches and bodies live under Configuration. */
1360
+ nodes: GraphNode[];
1361
+ onToggleNode: (nodeId: string) => void;
1362
+ renderNodeBody: (panel: string) => ReactNode;
1363
+ /** Ask before a trigger change that can invalidate the config under it (image 6). */
1364
+ onAskChange: (key: string) => void;
1365
+ onPatchTrigger: (patch: Record<string, unknown>) => void;
1366
+ onPickTrigger: (key: string) => void;
1367
+ onRunNow: () => void;
1368
+ scheduleFace: ReactNode;
1369
+ schedules: boolean;
1370
+ }) {
1371
+ const trigger = automation.trigger || null;
1372
+ const provider = picked?.connect?.provider || "";
1373
+ const connected = !!(provider && oauth?.[provider]?.connected);
1374
+ const startUrl = picked?.connect?.startUrl || "";
1375
+ const needsTable = !!trigger && "table" in trigger;
1376
+ const last = automation.runs?.[0];
1377
+
1378
+ return (
1379
+ <>
1380
+ <h3>Trigger details</h3>
1381
+ <div className="auto-field">
1382
+ <label htmlFor="autox-tkind">Trigger type</label>
1383
+ <select
1384
+ id="autox-tkind"
1385
+ className="auto-input"
1386
+ value={triggerKey}
1387
+ disabled={busy}
1388
+ onChange={(e) => {
1389
+ const next = e.target.value;
1390
+ if (next === triggerKey) return;
1391
+ // A change that can invalidate the configuration under it ASKS FIRST (image 6);
1392
+ // one that cannot β€” there is nothing configured yet β€” just happens.
1393
+ if (trigger && trigger.configured !== false) onAskChange(next);
1394
+ else onPickTrigger(next);
1395
+ }}
1396
+ >
1397
+ {triggerKey && !options.some((t) => t.key === triggerKey) ? (
1398
+ <option value={triggerKey}>{triggerKey} (not offered here)</option>
1399
+ ) : null}
1400
+ {/*
1401
+ ⭐ GROUPED BY THE SERVER'S OWN `group` (C-TYPES). `ig_profile_match` is a "Sources"
1402
+ trigger β€” it MAKES rows rather than watching them β€” and burying it among the record
1403
+ triggers is what made the wizard look like the only way to reach discovery.
1404
+ β›” THE GROUP ORDER IS FIRST-APPEARANCE IN THE SERVER'S ARRAY, never a literal list of
1405
+ group names here. `TriggerOption` carries no `groupOrder` (only `ActionCatalogRow`
1406
+ does), so the array's own order is the only ordering the server has expressed β€” and a
1407
+ client `["Standard", "Sources"]` would drop a third group off the end, silently, on
1408
+ the day the engine adds one.
1409
+ ⚠ `group` absent reads as "Standard" per the contract, which keeps a server older
1410
+ than this client rendering one ungrouped-looking list rather than a blank optgroup.
1411
+ */}
1412
+ {[...new Set(options.map((t) => t.group || "Standard"))].map((group) => (
1413
+ <optgroup key={group} label={group}>
1414
+ {options
1415
+ .filter((t) => (t.group || "Standard") === group)
1416
+ .map((t) => (
1417
+ <option key={t.key} value={t.key} disabled={!!t.planned}>
1418
+ {t.planned
1419
+ ? `${t.label} β€” coming soon`
1420
+ : t.ready === false
1421
+ ? `${t.label} β€” needs setting up`
1422
+ : t.label}
1423
+ </option>
1424
+ ))}
1425
+ </optgroup>
1426
+ ))}
1427
+ </select>
1428
+ </div>
1429
+ {/*
1430
+ ⭐ THE DESCRIPTION IS THE SERVER'S, AND IT RIDES NOW (wave 24, C-TYPES). This block used
1431
+ to be a comment explaining why there was NO paragraph here: Airtable prints two sentences
1432
+ under this select (image 3), ours would have been a client paraphrase of a server
1433
+ vocabulary, and the note said "when `detail` rides, it renders here and cannot disagree
1434
+ with the engine". `TriggerOption.detail` landed this wave, so the paragraph is the
1435
+ engine's own sentence, printed verbatim and never composed with anything.
1436
+ */}
1437
+ {picked?.detail ? <p className="auto-hint">{picked.detail}</p> : null}
1438
+ {picked && picked.ready === false && !picked.planned ? (
1439
+ <div className="autob-needs">
1440
+ <span className="autob-needs-text">
1441
+ {connected
1442
+ ? "Connected β€” this trigger is still being switched on for this deployment."
1443
+ : "This trigger is not set up yet."}
1444
+ </span>
1445
+ {!connected && startUrl ? (
1446
+ <a className="auto-btn is-primary autob-connect" href={startUrl}>
1447
+ Connect
1448
+ </a>
1449
+ ) : null}
1450
+ </div>
1451
+ ) : null}
1452
+
1453
+ <h3>Configuration</h3>
1454
+ {needsTable ? (
1455
+ <div className="auto-field">
1456
+ <label htmlFor="autox-ttable">
1457
+ <span className="autox-req">*</span> Database
1458
+ </label>
1459
+ <select
1460
+ id="autox-ttable"
1461
+ className="auto-input"
1462
+ value={trigger?.table || ""}
1463
+ disabled={busy}
1464
+ onChange={(e) => onPatchTrigger({ table: e.target.value })}
1465
+ >
1466
+ <option value="">Select a database…</option>
1467
+ {trigger?.table && !tables.some((t) => t.key === trigger.table) ? (
1468
+ <option value={trigger.table}>{trigger.table} (not visible to you)</option>
1469
+ ) : null}
1470
+ {tables.map((t) => (
1471
+ <option key={t.key} value={t.key}>
1472
+ {t.label}
1473
+ </option>
1474
+ ))}
1475
+ </select>
1476
+ </div>
1477
+ ) : null}
1478
+
1479
+ {triggerKey === "event_field" ? (
1480
+ <>
1481
+ {/*
1482
+ β›” "WATCHED COLUMN" IS GONE (owner item 7, C-TRIG law 4). "When a record matches
1483
+ conditions" is a FILTER, and a watched column was a second, different question
1484
+ answered in the same box β€” the trigger fired on a column changing AND on the
1485
+ conditions holding, which is two triggers wearing one name.
1486
+ ⚠ THE SERVER WENT FIRST, and that ordering was the point: `clean_trigger` stopped
1487
+ reading `field` (C posted law 4 done) BEFORE this control came out. Deleting the
1488
+ control while the validator still read the key would have left a stored watched
1489
+ column that nothing displays and nothing can clear β€” and deleting the key while the
1490
+ control still showed it would have made every Save silently drop what the user
1491
+ picked. The CONDITION is what completes this trigger now: with none, it rides
1492
+ `configured:false` and says so.
1493
+ */}
1494
+ <p className="auto-field-label">
1495
+ <span className="autox-req">*</span> Conditions
1496
+ </p>
1497
+ <CondBuilder
1498
+ cond={trigger?.when || null}
1499
+ onChange={(next) => onPatchTrigger({ when: next })}
1500
+ fields={table?.fields || []}
1501
+ ops={ops}
1502
+ nullaryOps={nullaryOps}
1503
+ maxDepth={vocab?.maxCondDepth ?? 3}
1504
+ maxChildren={vocab?.maxCondChildren ?? 12}
1505
+ disabled={busy}
1506
+ />
1507
+ </>
1508
+ ) : null}
1509
+
1510
+ {triggerKey === "record_updated" ? (
1511
+ <div className="auto-field">
1512
+ <label htmlFor="autox-twatch">Watched columns</label>
1513
+ <select
1514
+ id="autox-twatch"
1515
+ className="auto-input"
1516
+ multiple
1517
+ size={5}
1518
+ value={trigger?.fields || []}
1519
+ disabled={busy}
1520
+ onChange={(e) =>
1521
+ onPatchTrigger({
1522
+ fields: Array.from(e.target.selectedOptions).map((o) => o.value),
1523
+ })
1524
+ }
1525
+ >
1526
+ {(table?.fields || []).map((f) => (
1527
+ <option key={f.key} value={f.key}>
1528
+ {f.label}
1529
+ </option>
1530
+ ))}
1531
+ </select>
1532
+ <p className="auto-hint">Select none to fire on any column.</p>
1533
+ </div>
1534
+ ) : null}
1535
+
1536
+ {triggerKey === "enters_view" ? (
1537
+ <div className="auto-field">
1538
+ <label htmlFor="autox-tview">
1539
+ <span className="autox-req">*</span> View
1540
+ </label>
1541
+ {/*
1542
+ ⭐ FOUR STATES, AND THREE OF THEM ARE SENTENCES (owner item 8, C-TYPES).
1543
+ `views` now rides `GET /automations/tables`, so this control is live β€” but "drop the
1544
+ note" would have collapsed it to two states and rebuilt the exact defect the contract
1545
+ forbids. Absent and empty are DIFFERENT FACTS:
1546
+ Β· no database chosen -> choose one first
1547
+ Β· `views` ABSENT -> the server offered nothing (a server older than this
1548
+ client). Saying "no views" here would be a claim
1549
+ nobody measured.
1550
+ Β· `views` present and [] -> this database genuinely has none. That IS measured,
1551
+ and it is the one that tells the reader to go and
1552
+ make a view rather than to go and find an admin.
1553
+ Β· non-empty -> the picker.
1554
+ */}
1555
+ {!table ? (
1556
+ <p className="auto-note">Choose a database first.</p>
1557
+ ) : !table.views ? (
1558
+ <p className="auto-note">This server did not offer a view list for that database.</p>
1559
+ ) : !table.views.length ? (
1560
+ <p className="auto-note">
1561
+ That database has no saved views yet β€” make one on its grid and it appears here.
1562
+ </p>
1563
+ ) : (
1564
+ <select
1565
+ id="autox-tview"
1566
+ className="auto-input"
1567
+ value={trigger?.viewId || ""}
1568
+ disabled={busy}
1569
+ onChange={(e) => onPatchTrigger({ viewId: e.target.value })}
1570
+ >
1571
+ <option value="">Select a view…</option>
1572
+ {/*
1573
+ ⚠ THE STORED VALUE IS ALWAYS AN OPTION, and this control did not have that guard.
1574
+ A <select> whose `value` matches no <option> renders the FIRST one β€” here
1575
+ "Select a view…", whose value is `""` β€” so an `enters_view` trigger pointed at a
1576
+ view that has since been deleted, or at one the server deliberately withholds
1577
+ (another user's personal view, a share that does not name this viewer), would have
1578
+ LOOKED unconfigured and the next patch would have written the blank over it. This
1579
+ repo has paid for that twice; the two "(not in this database)" options elsewhere
1580
+ in this file exist for the same reason.
1581
+ */}
1582
+ {trigger?.viewId && !table.views.some((v) => v.id === trigger.viewId) ? (
1583
+ <option value={trigger.viewId}>{trigger.viewId} (not offered here)</option>
1584
+ ) : null}
1585
+ {table.views.map((v) => (
1586
+ <option key={v.id} value={v.id}>
1587
+ {v.label}
1588
+ </option>
1589
+ ))}
1590
+ </select>
1591
+ )}
1592
+ </div>
1593
+ ) : null}
1594
+
1595
+ {triggerKey === "email" ? (
1596
+ <div className="auto-field">
1597
+ <label htmlFor="autox-tquery">Gmail search</label>
1598
+ <input
1599
+ id="autox-tquery"
1600
+ className="auto-input"
1601
+ defaultValue={trigger?.query || ""}
1602
+ disabled={busy}
1603
+ placeholder="from:orders@example.com"
1604
+ // FREE TEXT COMMITS ON BLUR β€” per-keystroke would PATCH a half-typed query.
1605
+ onBlur={(e) => onPatchTrigger({ query: e.target.value })}
1606
+ />
1607
+ </div>
1608
+ ) : null}
1609
+
1610
+ {triggerKey === "webhook" && trigger?.token ? (
1611
+ <div className="auto-field">
1612
+ <label htmlFor="autox-thook">Hook URL</label>
1613
+ <input
1614
+ id="autox-thook"
1615
+ className="auto-input is-mono"
1616
+ readOnly
1617
+ value={`/api/v1/automations/hook/${trigger.token}`}
1618
+ />
1619
+ <p className="auto-hint">Minted once. It survives every other change to this trigger.</p>
1620
+ </div>
1621
+ ) : null}
1622
+
1623
+ {/* THE SCHEDULE, rendered by the one component that owns the cron round-trip.
1624
+ ⚠ NOT `triggerKey === "schedule"` ANY MORE (item 7, C-TRIG). `ig_profile_match` watches
1625
+ nothing β€” it MAKES rows, on the cron β€” so its Configuration carries these controls
1626
+ "always", and the caller says which keys those are. */}
1627
+ {schedules ? scheduleFace : null}
1628
+ {triggerKey === "manual" ? (
1629
+ <p className="auto-hint">
1630
+ It runs when you press Run once now, and nothing else starts it.
1631
+ </p>
1632
+ ) : null}
1633
+
1634
+ {/*
1635
+ ⭐ HOW THIS FETCHES (owner item 5, contract C-CFG) β€” the machine steps' switches and
1636
+ config bodies, below the trigger's own fields, under ONE sub-heading.
1637
+
1638
+ β›” ONE SECTION PER PANEL, NOT PER NODE (`groupByPanel`, and its note is the reason). Four
1639
+ of `field_instagram`'s nodes share `panel: "capture"` and both of `discover_instagram`'s
1640
+ share `panel: "find"`, so a section per node would print one body four times and mount the
1641
+ discovery filter twice against a single `preds` array.
1642
+
1643
+ β›” AND THE SWITCHES ARE THE POINT, not a leftover. R7: Bright Data buys exact counts with
1644
+ MONEY and Write's switch is the difference between a run that writes rows and one that
1645
+ reads and reports. They were on the cards this wave deleted, so deleting the cards without
1646
+ moving them would have retired two shipped controls silently. Each still posts to the
1647
+ node-toggle door β€” the server decides what a switch means, this only says which node.
1648
+
1649
+ `plain` automations have no machine nodes at all, so the whole section is absent for them
1650
+ rather than an empty heading (R6 makes that the common case from now on).
1651
+ */}
1652
+ {nodes.length ? (
1653
+ <>
1654
+ <h3>How this fetches</h3>
1655
+ {groupByPanel(nodes).map((g) => (
1656
+ <div className="autox-machine" key={g.panel}>
1657
+ {g.nodes.map((n) => (
1658
+ <div className="autox-machine-row" key={n.id}>
1659
+ <span className="autox-card-mark">
1660
+ <ActionMark kind={n.kind} />
1661
+ </span>
1662
+ <span className="autox-machine-text">
1663
+ <span className="autox-machine-title">{n.title}</span>
1664
+ <span className="autox-machine-sub">{n.subtitle}</span>
1665
+ </span>
1666
+ <span
1667
+ className={`auto-dot is-${n.status}`}
1668
+ aria-label={`Last run: ${n.status}`}
1669
+ />
1670
+ {n.toggle ? (
1671
+ <button
1672
+ type="button"
1673
+ className={"auto-step-switch" + (n.enabled ? " is-on" : "")}
1674
+ disabled={busy}
1675
+ aria-pressed={n.enabled}
1676
+ aria-label={`${n.enabled ? "Turn off" : "Turn on"} ${n.title}`}
1677
+ title={`${n.enabled ? "Turn off" : "Turn on"} ${n.title}`}
1678
+ onClick={() => onToggleNode(n.id)}
1679
+ >
1680
+ <span className="auto-step-switch-knob" />
1681
+ </button>
1682
+ ) : null}
1683
+ </div>
1684
+ ))}
1685
+ {/* The engine's own sentence about the step, where it wrote one β€” never a client
1686
+ paraphrase of what a node does. */}
1687
+ {g.nodes[0]?.detail ? (
1688
+ <p className="auto-hint">{g.nodes[0].detail}</p>
1689
+ ) : null}
1690
+ {renderNodeBody(g.panel)}
1691
+ </div>
1692
+ ))}
1693
+ </>
1694
+ ) : null}
1695
+
1696
+ <h3>Test step</h3>
1697
+ {/*
1698
+ β›” HONEST TO OUR SEMANTICS, not to Airtable's. Airtable's "Test step" replays one step
1699
+ against a chosen record. Ours has no step-replay: the engine runs a whole automation. So
1700
+ the control says what it actually does β€” RUN IT β€” and the results below are the last
1701
+ real run's, from the run log, rather than a rehearsal nobody performed.
1702
+ */}
1703
+ <button type="button" className="auto-btn" disabled={busy || !!automation.running}
1704
+ onClick={onRunNow}>
1705
+ {automation.running ? "Running…" : "Run once now"}
1706
+ </button>
1707
+ {last ? (
1708
+ <>
1709
+ <p className={"autox-result is-" + (last.ok ? "ok" : "bad")}>
1710
+ {last.ok ? "Last run succeeded" : "Last run failed"}
1711
+ </p>
1712
+ <p className="auto-hint">
1713
+ {last.ts.replace("T", " ").slice(0, 16)} β€” {last.summary}
1714
+ </p>
1715
+ </>
1716
+ ) : (
1717
+ <p className="auto-hint">It has not run yet.</p>
1718
+ )}
1719
+ </>
1720
+ );
1721
+ }
1722
+
1723
+ function ActionProps({
1724
+ action,
1725
+ catalog,
1726
+ tables,
1727
+ walkFields,
1728
+ ops,
1729
+ nullaryOps,
1730
+ vocab,
1731
+ busy,
1732
+ onEdit,
1733
+ }: {
1734
+ action: Action | null;
1735
+ catalog: ActionCatalogRow[];
1736
+ tables: UserTable[];
1737
+ /**
1738
+ * β›” THE WALKING RECORD'S COLUMNS β€” the trigger's database, resolved by the builder.
1739
+ *
1740
+ * These three surfaces were built with `fields={[]}` and it made R3's headline feature
1741
+ * unauthorable: a conditional group's condition, an action's `when`, and `update_record`'s
1742
+ * column picker all offered "Choose a field…" and nothing else. An empty list is not a
1743
+ * neutral default here β€” it is a picker with no options, which reads as "this database has
1744
+ * no columns".
1745
+ */
1746
+ walkFields: { key: string; label: string; type: string }[];
1747
+ ops: string[];
1748
+ nullaryOps: string[];
1749
+ vocab?: FlowVocab;
1750
+ busy: boolean;
1751
+ onEdit: (change: (a: Action) => Action) => void;
1752
+ }) {
1753
+ if (!action) return <p className="auto-note">That action is no longer part of this flow.</p>;
1754
+ const row = catalog.find((c) => c.kind === action.kind);
1755
+ const cfg = action.config || {};
1756
+ const setCfg = (patch: Record<string, unknown>) =>
1757
+ onEdit((a) => ({ ...a, config: { ...a.config, ...patch } }));
1758
+ const values = (cfg as { values?: Record<string, string | number> }).values || {};
1759
+ const target = tables.find((t) => t.key === String((cfg as { table?: string }).table || ""));
1760
+ const valueFields = action.kind === "create_record" ? target?.fields || [] : walkFields;
1761
+
1762
+ return (
1763
+ <>
1764
+ <h3>{row?.label || action.kind}</h3>
1765
+ {row?.detail ? <p className="auto-hint">{row.detail}</p> : null}
1766
+
1767
+ <h3>Configuration</h3>
1768
+
1769
+ {action.kind === "group" ? (
1770
+ <>
1771
+ {/*
1772
+ ⭐ ONE CONDITION EDITOR PER BRANCH (C-FORK). The group's own `config.cond` is GONE β€”
1773
+ a fork has a condition per leg, not one for the whole thing β€” so an editor bound to
1774
+ `cfg.cond` would now write a key `clean_actions` drops on the floor: the tree would
1775
+ look saved, survive a reload from local state, and be absent the next time anyone
1776
+ opened the automation.
1777
+ THE HEADING IS THE SERVER'S LABEL. The last leg may carry no condition, and the
1778
+ server has already named it "Otherwise" β€” giving it one here turns it into a lettered
1779
+ branch, which is a real thing to want and needs no separate control.
1780
+ */}
1781
+ {groupBranches(action).map((br, i) => (
1782
+ <div key={br.id || i}>
1783
+ <p className="auto-field-label">
1784
+ {br.label}
1785
+ {br.cond ? " β€” run these actions if…" : " β€” everything that reaches here"}
1786
+ </p>
1787
+ <CondBuilder
1788
+ cond={br.cond}
1789
+ onChange={(next) =>
1790
+ onEdit((a) => ({
1791
+ ...a,
1792
+ config: {
1793
+ ...a.config,
1794
+ branches: groupBranches(a).map((x) =>
1795
+ x.id === br.id ? { ...x, cond: next } : x
1796
+ ),
1797
+ },
1798
+ }))
1799
+ }
1800
+ fields={walkFields}
1801
+ ops={ops}
1802
+ nullaryOps={nullaryOps}
1803
+ maxDepth={vocab?.maxCondDepth ?? 3}
1804
+ maxChildren={vocab?.maxCondChildren ?? 12}
1805
+ lead=""
1806
+ disabled={busy}
1807
+ />
1808
+ </div>
1809
+ ))}
1810
+ <p className="auto-hint">
1811
+ The first branch whose conditions match is the one that runs β€” the record does not go
1812
+ down two of them.
1813
+ </p>
1814
+ </>
1815
+ ) : null}
1816
+
1817
+ {action.kind === "create_record" ? (
1818
+ <div className="auto-field">
1819
+ <label htmlFor="autox-atable">
1820
+ <span className="autox-req">*</span> Database
1821
+ </label>
1822
+ <select
1823
+ id="autox-atable"
1824
+ className="auto-input"
1825
+ value={String((cfg as { table?: string }).table || "")}
1826
+ disabled={busy}
1827
+ onChange={(e) => setCfg({ table: e.target.value })}
1828
+ >
1829
+ <option value="">Select a database…</option>
1830
+ {tables.map((t) => (
1831
+ <option key={t.key} value={t.key}>
1832
+ {t.label}
1833
+ </option>
1834
+ ))}
1835
+ </select>
1836
+ </div>
1837
+ ) : null}
1838
+
1839
+ {action.kind === "update_record" || action.kind === "create_record" ? (
1840
+ <>
1841
+ <p className="auto-field-label">
1842
+ <span className="autox-req">*</span> Values
1843
+ </p>
1844
+ {Object.entries(values).map(([key, val], i) => (
1845
+ <div className="autoc-row" key={i}>
1846
+ <button
1847
+ type="button"
1848
+ className="autoc-drop"
1849
+ disabled={busy}
1850
+ aria-label="Remove this value"
1851
+ onClick={() => {
1852
+ const next = { ...values };
1853
+ delete next[key];
1854
+ setCfg({ values: next });
1855
+ }}
1856
+ >
1857
+ <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
1858
+ <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
1859
+ strokeLinecap="round" />
1860
+ </svg>
1861
+ </button>
1862
+ <select
1863
+ className="auto-input is-tiny"
1864
+ value={key}
1865
+ disabled={busy}
1866
+ aria-label="Column"
1867
+ onChange={(e) => {
1868
+ const next: Record<string, string | number> = {};
1869
+ for (const [k, v] of Object.entries(values))
1870
+ next[k === key ? e.target.value : k] = v;
1871
+ setCfg({ values: next });
1872
+ }}
1873
+ >
1874
+ <option value="">Choose a column…</option>
1875
+ {/* ⚠ WHICH RECORD'S COLUMNS depends on the action: `create_record` writes into
1876
+ the database it NAMES, `update_record` writes onto the record walking the
1877
+ flow β€” the trigger's. Offering the target's columns for both would list the
1878
+ wrong database's columns for every update action. */}
1879
+ {key && !valueFields.some((f) => f.key === key) ? (
1880
+ <option value={key}>{key}</option>
1881
+ ) : null}
1882
+ {valueFields.map((f) => (
1883
+ <option key={f.key} value={f.key}>
1884
+ {f.label}
1885
+ </option>
1886
+ ))}
1887
+ </select>
1888
+ <input
1889
+ className="auto-input is-tiny autoc-value"
1890
+ defaultValue={String(val ?? "")}
1891
+ disabled={busy}
1892
+ aria-label="Value"
1893
+ placeholder="Value or {{column}}"
1894
+ onBlur={(e) => setCfg({ values: { ...values, [key]: e.target.value } })}
1895
+ />
1896
+ </div>
1897
+ ))}
1898
+ <button
1899
+ type="button"
1900
+ className="autoc-add"
1901
+ disabled={busy}
1902
+ onClick={() => setCfg({ values: { ...values, "": "" } })}
1903
+ >
1904
+ + Add a value
1905
+ </button>
1906
+ <p className="auto-hint">
1907
+ <code>{"{{column_key}}"}</code> reads that column off the record walking the flow.
1908
+ </p>
1909
+ </>
1910
+ ) : null}
1911
+
1912
+ {action.kind === "find_records" ? (
1913
+ <>
1914
+ <div className="auto-field">
1915
+ <label htmlFor="autox-ftable">
1916
+ <span className="autox-req">*</span> Database
1917
+ </label>
1918
+ <select
1919
+ id="autox-ftable"
1920
+ className="auto-input"
1921
+ value={String((cfg as { table?: string }).table || "")}
1922
+ disabled={busy}
1923
+ onChange={(e) => setCfg({ table: e.target.value })}
1924
+ >
1925
+ <option value="">Select a database…</option>
1926
+ {tables.map((t) => (
1927
+ <option key={t.key} value={t.key}>
1928
+ {t.label}
1929
+ </option>
1930
+ ))}
1931
+ </select>
1932
+ </div>
1933
+ <p className="auto-field-label">Conditions</p>
1934
+ <CondBuilder
1935
+ cond={(cfg as { cond?: Cond | null }).cond || null}
1936
+ onChange={(next) => setCfg({ cond: next })}
1937
+ fields={target?.fields || []}
1938
+ ops={ops}
1939
+ nullaryOps={nullaryOps}
1940
+ maxDepth={vocab?.maxCondDepth ?? 3}
1941
+ maxChildren={vocab?.maxCondChildren ?? 12}
1942
+ disabled={busy}
1943
+ />
1944
+ <div className="auto-field">
1945
+ <label htmlFor="autox-flimit">How many at most</label>
1946
+ <input
1947
+ id="autox-flimit"
1948
+ className="auto-input"
1949
+ type="number"
1950
+ min={1}
1951
+ defaultValue={Number((cfg as { limit?: number }).limit || 25)}
1952
+ disabled={busy}
1953
+ onBlur={(e) => setCfg({ limit: Number(e.target.value) || 25 })}
1954
+ />
1955
+ </div>
1956
+ <p className="auto-hint">
1957
+ What it found opens from the run log. Piping the rows into a later step is not built
1958
+ yet.
1959
+ </p>
1960
+ </>
1961
+ ) : null}
1962
+
1963
+ {action.kind === "review" ? (
1964
+ <ReviewProps
1965
+ cfg={cfg as Record<string, unknown>}
1966
+ vocab={vocab}
1967
+ busy={busy}
1968
+ setCfg={setCfg}
1969
+ />
1970
+ ) : null}
1971
+
1972
+ {/* EVERY action can be conditional, not just a group β€” `Action.when` is the engine's own
1973
+ field and a card with no way to set it would be a stored value the UI cannot reach. */}
1974
+ <h3>Run this only when</h3>
1975
+ <CondBuilder
1976
+ cond={action.when || null}
1977
+ onChange={(next) => onEdit((a) => ({ ...a, when: next }))}
1978
+ fields={walkFields}
1979
+ ops={ops}
1980
+ nullaryOps={nullaryOps}
1981
+ maxDepth={vocab?.maxCondDepth ?? 3}
1982
+ maxChildren={vocab?.maxCondChildren ?? 12}
1983
+ disabled={busy}
1984
+ />
1985
+ {!condComplete(action.when || null, nullaryOps) ? null : (
1986
+ <p className="auto-hint">Leave empty to run it every time.</p>
1987
+ )}
1988
+ </>
1989
+ );
1990
+ }
1991
+
1992
+ function ReviewProps({
1993
+ cfg,
1994
+ vocab,
1995
+ busy,
1996
+ setCfg,
1997
+ }: {
1998
+ cfg: Record<string, unknown>;
1999
+ vocab?: FlowVocab;
2000
+ busy: boolean;
2001
+ setCfg: (patch: Record<string, unknown>) => void;
2002
+ }) {
2003
+ const by = String(cfg.decidedBy || "user");
2004
+ const next = Array.isArray(cfg.next) ? (cfg.next as string[]) : [];
2005
+ const aiReady = vocab?.aiReady !== false;
2006
+ return (
2007
+ <>
2008
+ <div className="auto-field">
2009
+ <label htmlFor="autox-rby">Decided by</label>
2010
+ <select
2011
+ id="autox-rby"
2012
+ className="auto-input"
2013
+ value={by}
2014
+ disabled={busy}
2015
+ onChange={(e) => setCfg({ decidedBy: e.target.value })}
2016
+ >
2017
+ {(vocab?.reviewDeciders || ["user"]).map((d) => (
2018
+ <option key={d} value={d}>
2019
+ {d === "ai" ? "AI" : "A person"}
2020
+ </option>
2021
+ ))}
2022
+ </select>
2023
+ </div>
2024
+ {/*
2025
+ ⚠ `aiReady` IS A MEASUREMENT OF THIS DEPLOYMENT, and it is stated rather than styled
2026
+ around. With no LLM key the engine holds every card for a human β€” so an AI review that
2027
+ looked configured would promise a decision nothing will make (C6's fail-closed path).
2028
+ */}
2029
+ {by === "ai" && !aiReady ? (
2030
+ <p className="auto-note">
2031
+ No AI provider is configured here, so these cards wait for a person.
2032
+ </p>
2033
+ ) : null}
2034
+ {by === "ai" ? (
2035
+ <div className="auto-field">
2036
+ <label htmlFor="autox-rprompt">What should it decide?</label>
2037
+ <textarea
2038
+ id="autox-rprompt"
2039
+ className="auto-input"
2040
+ rows={3}
2041
+ defaultValue={String(cfg.prompt || "")}
2042
+ disabled={busy}
2043
+ placeholder="Approve suppliers with a UK address and more than 20 reviews."
2044
+ onBlur={(e) => setCfg({ prompt: e.target.value })}
2045
+ />
2046
+ </div>
2047
+ ) : null}
2048
+ <div className="auto-field">
2049
+ <label htmlFor="autox-rlabel">Stage name</label>
2050
+ <input
2051
+ id="autox-rlabel"
2052
+ className="auto-input"
2053
+ defaultValue={String(cfg.label || "Review")}
2054
+ disabled={busy}
2055
+ onBlur={(e) => setCfg({ label: e.target.value })}
2056
+ />
2057
+ </div>
2058
+ <p className="auto-field-label">Where it can go next</p>
2059
+ {next.map((n, i) => (
2060
+ <div className="autoc-row" key={i}>
2061
+ <button
2062
+ type="button"
2063
+ className="autoc-drop"
2064
+ disabled={busy}
2065
+ aria-label={`Remove ${n}`}
2066
+ onClick={() => setCfg({ next: next.filter((_x, j) => j !== i) })}
2067
+ >
2068
+ <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
2069
+ <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
2070
+ strokeLinecap="round" />
2071
+ </svg>
2072
+ </button>
2073
+ <input
2074
+ className="auto-input is-tiny"
2075
+ defaultValue={n}
2076
+ disabled={busy}
2077
+ aria-label="Stage this review can send a record to"
2078
+ onBlur={(e) =>
2079
+ setCfg({ next: next.map((x, j) => (j === i ? e.target.value : x)) })
2080
+ }
2081
+ />
2082
+ </div>
2083
+ ))}
2084
+ <button
2085
+ type="button"
2086
+ className="autoc-add"
2087
+ disabled={busy}
2088
+ onClick={() => setCfg({ next: [...next, ""] })}
2089
+ >
2090
+ + Add an exit
2091
+ </button>
2092
+ <p className="auto-hint">
2093
+ Each exit is a lane on the board. A card waits here until it is moved to one of them.
2094
+ </p>
2095
+ </>
2096
+ );
2097
+ }
web/src/automation/AutomationDetail.tsx CHANGED
@@ -23,14 +23,16 @@
23
  import { useCallback, useEffect, useState } from "react";
24
 
25
  import AutomationBoard from "./AutomationBoard";
 
26
  import AutomationFind from "./AutomationFind";
27
- import AutomationSteps from "./AutomationSteps";
28
  import AutomationTrigger from "./AutomationTrigger";
29
  import type {
 
30
  Automation,
31
  AutomationKind,
32
  Board,
33
  BoardStage,
 
34
  GraphNode,
35
  OAuthStatus,
36
  Predicate,
@@ -62,6 +64,13 @@ import {
62
 
63
  interface Props {
64
  automation: Automation;
 
 
 
 
 
 
 
65
  kinds: { key: AutomationKind; label: string }[];
66
  /** The server's schedule vocabulary, forwarded to Step 1's Custom face. */
67
  cronPresets: { cron: string; label: string }[];
@@ -70,30 +79,76 @@ interface Props {
70
  discover?: DiscoverVocab;
71
  /** The server's trigger vocabulary (C3). Absent until the engine ships it. */
72
  triggers?: TriggerOption[];
 
 
 
73
  /**
74
  * Can a schedule fire here? `null` = the server did not say (C6 amendment #1 is not live
75
  * yet) β€” a REQUIRED key so an unmounted prop fails `tsc` rather than silently reading as
76
  * "off", which would make Step 1 state a measurement nobody made.
77
  */
78
  tick: TickState | null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  onSaved: (id?: string) => void | Promise<void>;
80
  onDeleted: () => void | Promise<void>;
81
  }
82
 
 
 
 
 
 
 
 
 
 
 
83
  /**
84
- * The run-state chip's WORDS. The chip printed the stored enum straight β€” a header
85
- * reading "ok" beside the automation's name, which is a value from a state machine
86
- * rather than a sentence anybody would write. Sentence case, and "Succeeded"/"Failed"
87
- * rather than "ok"/"error" so the chip agrees with the rail's own tooltip, which has
88
- * always said "Last run succeeded".
 
 
 
 
 
 
 
 
 
 
 
 
89
  */
90
- const STATE_LABELS: Record<string, string> = {
91
- idle: "Not run yet",
92
- running: "Running",
93
- ok: "Succeeded",
94
- partial: "Partial",
95
- error: "Failed",
96
- };
97
 
98
  interface ColumnPlan {
99
  column: string;
@@ -103,12 +158,15 @@ interface ColumnPlan {
103
 
104
  export default function AutomationDetail({
105
  automation,
106
- kinds,
107
  cronPresets,
108
  paidReady,
109
  discover,
110
  triggers,
 
 
111
  tick,
 
 
112
  onSaved,
113
  onDeleted,
114
  }: Props) {
@@ -123,7 +181,28 @@ export default function AutomationDetail({
123
  const [touched, setTouched] = useState(false);
124
  const [busyNode, setBusyNode] = useState("");
125
  const [triggerBusy, setTriggerBusy] = useState(false);
126
- const [selected, setSelected] = useState("");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
  // --- the board (C1)
129
  const [board, setBoard] = useState<Board | null>(null);
@@ -161,11 +240,24 @@ export default function AutomationDetail({
161
  // --- discover_instagram half (R7)
162
  const [recordsLimit, setRecordsLimit] = useState(Number(cfg.recordsLimit || 25));
163
  const [joinOp, setJoinOp] = useState(String(cfg.operator || "and"));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  const [preds, setPreds] = useState<Predicate[]>(() => {
165
  const stored = (automation.config as { predicates?: Predicate[] })?.predicates;
166
- return stored && stored.length
167
- ? stored.map((p) => ({ ...p }))
168
- : [{ name: "followers", operator: ">=", value: 10000 }];
169
  });
170
  const [estimate, setEstimate] = useState<DiscoverEstimate | null>(null);
171
 
@@ -243,6 +335,30 @@ export default function AutomationDetail({
243
 
244
  const table = tables.find((t) => t.key === targetTable) || null;
245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  /**
247
  * WHICH CONFIG PANEL IS OPEN β€” and the join is on `panel`, never on id equality.
248
  *
@@ -330,6 +446,51 @@ export default function AutomationDetail({
330
  * value for any flag a config omits β€” so a Save from here can never quietly
331
  * turn the paid rung off. (`clean_config`'s `flag()`, asserted in section N.)
332
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333
  const buildConfig = (): Record<string, unknown> => {
334
  if (kind === "scrape_db") {
335
  const fieldMap: Record<string, string> = {};
@@ -348,11 +509,34 @@ export default function AutomationDetail({
348
  return {
349
  recordsLimit,
350
  operator: joinOp,
351
- predicates: preds.filter((p) => p.name && p.operator),
352
  targetTable: String(cfg.targetTable || ""),
353
  };
354
  }
355
- return { targetTable, fieldKey, urlField, maxPosts };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
  };
357
 
358
  const persist = async (announce = true, sched?: { cron: string; enabled: boolean }) => {
@@ -363,7 +547,7 @@ export default function AutomationDetail({
363
  schedule: sched || { cron, enabled: !!automation.schedule?.enabled },
364
  });
365
  setTouched(false);
366
- if (announce) setMessage("Saved.");
367
  return res.automation.id;
368
  };
369
 
@@ -391,6 +575,7 @@ export default function AutomationDetail({
391
  schedule: { cron: next.cron, enabled: next.enabled },
392
  });
393
  setTouched(false);
 
394
  await onSaved(automation.id);
395
  await loadBoard();
396
  } catch (e) {
@@ -428,6 +613,7 @@ export default function AutomationDetail({
428
  schedule: { cron, enabled: key === "schedule" },
429
  });
430
  setTouched(false);
 
431
  await onSaved(automation.id);
432
  await loadBoard();
433
  } catch (e) {
@@ -541,14 +727,18 @@ export default function AutomationDetail({
541
  }
542
  };
543
 
544
- const state = automation.running ? "running" : automation.status?.state || "idle";
545
-
546
  /**
547
- * The trigger controls, built ONCE and rendered by whichever frame is mounted.
548
- * `AutomationTrigger` owns the vocabulary (C3), the cron round-trip and the tick
549
  * honesty note; this file owns only what a change should WRITE.
 
 
 
 
 
 
550
  */
551
- const triggerFace = (
552
  <AutomationTrigger
553
  triggers={triggers}
554
  current={triggerKey}
@@ -564,28 +754,455 @@ export default function AutomationDetail({
564
  oauth={oauth}
565
  showCron={showCron}
566
  onShowCron={setShowCron}
 
 
567
  />
568
  );
569
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
570
  return (
571
  <div className="auto-detail">
572
  <header className="auto-head">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
573
  <div className="auto-head-title">
574
- <input
575
- className="auto-name"
576
- value={name}
577
- placeholder="Name this automation"
578
- aria-label="Automation name"
579
- onChange={(e) => edit(setName)(e.target.value)}
580
- />
581
- <span className={`auto-chip is-${state}`}>
582
- {STATE_LABELS[state] || state}
583
- </span>
584
- <span className="auto-kindtag">
585
- {kinds.find((k) => k.key === kind)?.label || kind}
586
- </span>
 
 
 
587
  </div>
588
  <div className="auto-head-actions">
 
 
 
 
 
 
 
 
 
 
 
 
 
589
  <button
590
  type="button"
591
  className="auto-btn"
@@ -621,44 +1238,126 @@ export default function AutomationDetail({
621
 
622
  <div className="auto-work">
623
  {/*
624
- TWO FRAMES, ONE TRIGGER FACE. The board is what the owner asked for (R1) and
625
- the numbered steps are what a server that does not answer `/board` can still
626
- describe honestly β€” neither is a degraded version of the other, and the
627
- trigger controls are the SAME ELEMENT in both, so the cron round-trip and the
628
- tick honesty note exist exactly once.
 
 
 
 
 
629
  */}
630
- {board ? (
631
- <div className="autob-flow">
632
- <div className="autob-triggerbar">
633
- <span className="autob-triggerbar-tag">Trigger</span>
634
- {triggerFace}
635
- </div>
636
- <AutomationBoard
637
- board={board}
638
- selected={selected}
639
- onSelect={setSelected}
640
- onToggle={(id) => void flip(id)}
641
- busyStage={busyNode}
642
- onMove={(rowId, to) => void moveOne(rowId, to)}
643
- movingRow={movingRow}
644
- />
645
- </div>
646
- ) : (
647
- <AutomationSteps
648
- graph={automation.graph}
649
- selected={selected}
650
- onSelect={setSelected}
651
- onToggle={(id) => void flip(id)}
652
- busyNode={busyNode}
653
- triggerFace={triggerFace}
654
- triggerOff={triggerKey === "manual"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
655
  />
656
- )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
657
 
658
- <aside
659
- className="auto-panel"
660
- aria-label={panelOpen ? `${panelTitle} settings` : "Run history"}
661
- >
662
  {panelOpen ? (
663
  <>
664
  <div className="auto-panel-head">
@@ -712,10 +1411,24 @@ export default function AutomationDetail({
712
  {(automation.reviews || []).slice(0, 12).map((r) => (
713
  <li key={`${r.ts}-${r.rowId}`} className="autob-review">
714
  <span className="autob-review-ts">{r.ts.replace("T", " ").slice(0, 16)}</span>
715
- <span className="autob-review-who">{r.user}</span>
 
 
 
 
 
 
 
 
 
716
  <span className="autob-review-move">
717
  {r.from} to {r.to}
718
  </span>
 
 
 
 
 
719
  </li>
720
  ))}
721
  </ol>
@@ -731,340 +1444,7 @@ export default function AutomationDetail({
731
  here that the card does not already say.
732
  */}
733
 
734
- {panelKey === "source" && kind === "scrape_db" ? (
735
- <>
736
- <div className="auto-field">
737
- <label htmlFor="auto-url">Page URL</label>
738
- <input
739
- id="auto-url"
740
- className="auto-input"
741
- value={url}
742
- placeholder="https://en.wikipedia.org/wiki/List_of_S%26P_500_companies"
743
- onChange={(e) => edit(setUrl)(e.target.value)}
744
- />
745
- </div>
746
- <button
747
- type="button"
748
- className="auto-btn"
749
- disabled={!url.trim() || reading}
750
- onClick={() => void readPage()}
751
- >
752
- {reading ? "Reading…" : "Read the page"}
753
- </button>
754
- <div className="auto-field">
755
- <label htmlFor="auto-extract">Read</label>
756
- <select
757
- id="auto-extract"
758
- className="auto-input"
759
- value={extract}
760
- onChange={(e) => edit(setExtract)(e.target.value)}
761
- >
762
- <option value="table">An HTML table</option>
763
- <option value="jsonld">Structured data (JSON-LD)</option>
764
- </select>
765
- </div>
766
- {extract === "table" ? (
767
- <div className="auto-field">
768
- <label htmlFor="auto-tidx">Which table</label>
769
- <input
770
- id="auto-tidx"
771
- className="auto-input"
772
- type="number"
773
- min={0}
774
- value={tableIndex}
775
- onChange={(e) => edit(setTableIndex)(Number(e.target.value) || 0)}
776
- />
777
- </div>
778
- ) : null}
779
- <p className="auto-hint">
780
- Public web pages only. Private, loopback and link-local addresses are refused
781
- β€” including a public URL that redirects to one.
782
- </p>
783
- </>
784
- ) : null}
785
-
786
- {panelKey === "columns" ? (
787
- plan.length ? (
788
- <>
789
- <p className="auto-hint">
790
- Pick the key β€” the column that identifies a row. On every re-run, a row
791
- whose key already exists is updated; a new key is inserted; a key that has
792
- stopped appearing is counted and kept.
793
- </p>
794
- <div className="auto-panel-scroll">
795
- <table className="auto-table">
796
- <thead>
797
- <tr>
798
- <th>Use</th>
799
- <th>Source column</th>
800
- <th>Field key</th>
801
- <th>Key</th>
802
- </tr>
803
- </thead>
804
- <tbody>
805
- {plan.map((c, i) => (
806
- <tr key={c.column}>
807
- <td>
808
- <input
809
- type="checkbox"
810
- checked={c.include}
811
- aria-label={`Include ${c.column}`}
812
- onChange={(e) =>
813
- edit(setPlan)(
814
- plan.map((x, j) =>
815
- j === i ? { ...x, include: e.target.checked } : x
816
- )
817
- )
818
- }
819
- />
820
- </td>
821
- <td className="auto-cell-name">{c.column}</td>
822
- <td>
823
- <input
824
- className="auto-input is-small"
825
- value={c.key}
826
- aria-label={`Field key for ${c.column}`}
827
- onChange={(e) =>
828
- edit(setPlan)(
829
- plan.map((x, j) =>
830
- j === i
831
- ? { ...x, key: fieldKeyFor(e.target.value) }
832
- : x
833
- )
834
- )
835
- }
836
- />
837
- </td>
838
- <td>
839
- <input
840
- type="radio"
841
- name="auto-keyfield"
842
- checked={keyField === c.key && c.include}
843
- disabled={!c.include}
844
- aria-label={`Use ${c.column} as the key`}
845
- onChange={() => edit(setKeyField)(c.key)}
846
- />
847
- </td>
848
- </tr>
849
- ))}
850
- </tbody>
851
- </table>
852
- </div>
853
- {preview?.sample?.length ? (
854
- <p className="auto-hint">
855
- First row read: {Object.values(preview.sample[0]).slice(0, 4).join(" Β· ")}
856
- </p>
857
- ) : null}
858
- </>
859
- ) : (
860
- <p className="auto-note">
861
- Open the Fetch step and read the page to see what columns it offers.
862
- </p>
863
- )
864
- ) : null}
865
-
866
- {panelKey === "source" && kind === "field_instagram" ? (
867
- <>
868
- <div className="auto-field">
869
- <label htmlFor="auto-table">Database</label>
870
- <select
871
- id="auto-table"
872
- className="auto-input"
873
- value={targetTable}
874
- onChange={(e) => {
875
- edit(setTargetTable)(e.target.value);
876
- setFieldKey("");
877
- setUrlField("");
878
- }}
879
- >
880
- <option value="">Choose a database…</option>
881
- {targetTable && !tables.some((t) => t.key === targetTable) ? (
882
- <option value={targetTable}>{targetTable} (not visible to you)</option>
883
- ) : null}
884
- {tables.map((t) => (
885
- <option key={t.key} value={t.key}>
886
- {t.label} ({t.rowCount} {t.rowCount === 1 ? "row" : "rows"})
887
- </option>
888
- ))}
889
- </select>
890
- </div>
891
- <div className="auto-field">
892
- <label htmlFor="auto-urlfield">Profile URL column</label>
893
- <select
894
- id="auto-urlfield"
895
- className="auto-input"
896
- value={urlField}
897
- onChange={(e) => edit(setUrlField)(e.target.value)}
898
- >
899
- <option value="">The column the field is bound to</option>
900
- {(table?.fields || []).map((f) => (
901
- <option key={f.key} value={f.key}>
902
- {f.label}
903
- </option>
904
- ))}
905
- </select>
906
- </div>
907
- <div className="auto-field">
908
- <label htmlFor="auto-fieldkey">Automation column</label>
909
- <select
910
- id="auto-fieldkey"
911
- className="auto-input"
912
- value={fieldKey}
913
- onChange={(e) => edit(setFieldKey)(e.target.value)}
914
- >
915
- <option value="">Choose a column…</option>
916
- {/*
917
- ⚠ THE STORED VALUE IS ALWAYS AN OPTION, even when the list
918
- below does not contain it. A <select> whose `value` matches
919
- no <option> renders the FIRST one β€” so a column the server
920
- knows about but this list has not caught up with would look
921
- like a DIFFERENT column, and the next Save would write that
922
- different column without anybody choosing it. Showing it as
923
- "(not in this database)" is the honest version.
924
- */}
925
- {fieldKey && !(table?.fields || []).some((f) => f.key === fieldKey) ? (
926
- <option value={fieldKey}>{fieldKey} (not in this database)</option>
927
- ) : null}
928
- {(table?.fields || [])
929
- .filter((f) => f.type === "automation")
930
- .map((f) => (
931
- <option key={f.key} value={f.key}>
932
- {f.label}
933
- </option>
934
- ))}
935
- </select>
936
- </div>
937
- {table && !(table.fields || []).some((f) => f.type === "automation") ? (
938
- <p className="auto-note">
939
- That database has no automation column yet. Add one from the grid&rsquo;s
940
- column menu, then choose it here.
941
- </p>
942
- ) : null}
943
- </>
944
- ) : null}
945
-
946
- {panelKey === "capture" ? (
947
- <>
948
- <div className="auto-field">
949
- <label htmlFor="auto-maxposts">Posts per pull</label>
950
- <input
951
- id="auto-maxposts"
952
- className="auto-input"
953
- type="number"
954
- min={1}
955
- max={200}
956
- value={maxPosts}
957
- onChange={(e) => edit(setMaxPosts)(Number(e.target.value) || 24)}
958
- />
959
- </div>
960
- <h3>Bright Data β€” the paid rung</h3>
961
- <p className="auto-hint">
962
- Exact follower counts and the profile&rsquo;s top posts, and it works from a
963
- datacenter. Its node&rsquo;s switch turns it on.
964
- {paidReady
965
- ? " A key is configured on this deployment."
966
- : " No key is configured on this deployment yet, so it will report itself blocked and the anonymous rung will answer instead."}
967
- </p>
968
- <h3>Post engagement β€” the per-post rung</h3>
969
- <p className="auto-hint">
970
- Likes and comments for each post. It is a separate step because it is a
971
- separate bill: the profile read costs one record, and engagement costs{" "}
972
- <strong>one record per post</strong>. With it off, the posts database still
973
- grows but the engagement series does not β€” and no empty rows are appended to
974
- stand in for the numbers nobody bought.
975
- </p>
976
- <h3>Anonymous β€” the free rung</h3>
977
- <p className="auto-hint">
978
- No login and no credentials. Instagram blocks datacenter addresses and has
979
- closed most of its anonymous surface, so this rung is honest rather than
980
- reliable: counts come from the page&rsquo;s own abbreviations (204K, not
981
- 204,312) and are marked approximate. Turning it off means{" "}
982
- <strong>exact numbers or nothing</strong> β€” a run reports blocked rather than
983
- quietly writing a rounded number.
984
- </p>
985
- <p className="auto-hint">
986
- A pull reports what it actually got: <strong>ok</strong> (profile and posts),{" "}
987
- <strong>partial</strong> (profile only), or <strong>blocked</strong>. It never
988
- reports success on nothing.
989
- </p>
990
- </>
991
- ) : null}
992
-
993
- {panelKey === "find" ? (
994
- <AutomationFind
995
- discover={discover}
996
- recordsLimit={recordsLimit}
997
- onRecordsLimit={(n) => {
998
- edit(setRecordsLimit)(n);
999
- setEstimate(null);
1000
- }}
1001
- joinOp={joinOp}
1002
- onJoinOp={edit(setJoinOp)}
1003
- preds={preds}
1004
- onPreds={edit(setPreds)}
1005
- estimate={estimate}
1006
- onEstimate={() => {
1007
- void discoverEstimate(recordsLimit)
1008
- .then(setEstimate)
1009
- .catch(() => setEstimate(null));
1010
- }}
1011
- />
1012
- ) : null}
1013
-
1014
- {panelKey === "write" ? (
1015
- <>
1016
- {kind === "scrape_db" ? (
1017
- <div className="auto-field">
1018
- <label htmlFor="auto-tlabel">Database name</label>
1019
- <input
1020
- id="auto-tlabel"
1021
- className="auto-input"
1022
- value={targetLabel}
1023
- placeholder="S&P 500 companies"
1024
- onChange={(e) => edit(setTargetLabel)(e.target.value)}
1025
- />
1026
- </div>
1027
- ) : kind === "discover_instagram" ? (
1028
- <p className="auto-hint">
1029
- Matches are collected into{" "}
1030
- <code>{discover?.table || "ut_ig_candidates"}</code>, upserted by handle β€” so
1031
- re-finding an account costs nothing and its <em>Times found</em> count grows.{" "}
1032
- <strong>Nothing found is ever tracked automatically.</strong> Tick the ones
1033
- you want; a later search can never un-tick them.
1034
- </p>
1035
- ) : (
1036
- <p className="auto-hint">
1037
- Each pull appends a timestamped row to <code>ut_ig_snapshots</code> and, when
1038
- the post-engagement step is on, one per post to{" "}
1039
- <code>ut_ig_post_snapshots</code> β€” so the history is a time series you can
1040
- filter by date rather than a single current value.{" "}
1041
- <code>ut_ig_posts</code> holds one row per post, ever.
1042
- </p>
1043
- )}
1044
- <p className="auto-hint">
1045
- Turning this step off makes the automation a <strong>dry run</strong>: it
1046
- reads everything and reports exactly what it would have written, without
1047
- creating or changing a single row.
1048
- </p>
1049
- {kind === "field_instagram" ? (
1050
- <p className="auto-hint">
1051
- {/*
1052
- ⚠ "Writes nothing" and "costs nothing" are DIFFERENT CLAIMS, and only the
1053
- first one is true. A dry run still READS β€” so with the paid steps on it
1054
- bills exactly what a real run bills. Saying so here is the only place a
1055
- user finds out before the invoice.
1056
- */}
1057
- A dry run still <strong>reads</strong>. With the Bright Data step on it
1058
- costs what a real run costs, and with post engagement on that is one
1059
- charged record per post. Turn those steps off too if you want a free
1060
- rehearsal.
1061
- </p>
1062
- ) : null}
1063
- <p className="auto-hint">
1064
- A row that stops appearing at the source is counted and kept, never deleted.
1065
- </p>
1066
- </>
1067
- ) : null}
1068
  </>
1069
  ) : (
1070
  <>
@@ -1137,11 +1517,13 @@ export default function AutomationDetail({
1137
  <p className="auto-hint">
1138
  {board
1139
  ? "Click a stage to see and change what it does."
1140
- : "Click any step to see and change what it does."}
1141
  </p>
1142
  </>
1143
  )}
1144
- </aside>
 
 
1145
  </div>
1146
  </div>
1147
  );
 
23
  import { useCallback, useEffect, useState } from "react";
24
 
25
  import AutomationBoard from "./AutomationBoard";
26
+ import AutomationBuilder from "./AutomationBuilder";
27
  import AutomationFind from "./AutomationFind";
 
28
  import AutomationTrigger from "./AutomationTrigger";
29
  import type {
30
+ ActionCatalogRow,
31
  Automation,
32
  AutomationKind,
33
  Board,
34
  BoardStage,
35
+ FlowVocab,
36
  GraphNode,
37
  OAuthStatus,
38
  Predicate,
 
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 }[];
 
79
  discover?: DiscoverVocab;
80
  /** The server's trigger vocabulary (C3). Absent until the engine ships it. */
81
  triggers?: TriggerOption[];
82
+ /** The ACTION MENU and the builder's ceilings (C4). Same rule: absent is a state, not a gap. */
83
+ catalog?: ActionCatalogRow[];
84
+ vocab?: FlowVocab;
85
  /**
86
  * Can a schedule fire here? `null` = the server did not say (C6 amendment #1 is not live
87
  * yet) β€” a REQUIRED key so an unmounted prop fails `tsc` rather than silently reading as
88
  * "off", which would make Step 1 state a measurement nobody made.
89
  */
90
  tick: TickState | null;
91
+ /**
92
+ * W23-W5 β€” the stage a review notification asked for, seeding the config panel's selection.
93
+ * Advisory by contract: a stage this automation does not have simply opens nothing, which is
94
+ * the same thing that happens when no stage is named. The surface remounts this component on
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,
164
  triggers,
165
+ catalog,
166
+ vocab,
167
  tick,
168
+ initialStage,
169
+ liveStep,
170
  onSaved,
171
  onDeleted,
172
  }: Props) {
 
181
  const [touched, setTouched] = useState(false);
182
  const [busyNode, setBusyNode] = useState("");
183
  const [triggerBusy, setTriggerBusy] = useState(false);
184
+ const [selected, setSelected] = useState(initialStage || "");
185
+
186
+ /**
187
+ * β›” WHICH VIEW (C1 + C14 leg 1) β€” and it is STATE, not a consequence of a fetch.
188
+ *
189
+ * The ghost this wave was called to kill lived exactly here. The detail used to render
190
+ * `{board ? <AutomationBoard/> : <AutomationSteps/>}`: the shape of the page was decided by
191
+ * whether a request had come back, so opening any automation drew the STEPS, then replaced
192
+ * them with the BOARD a fetch later. Click A then B and the frame showed A's shape while B
193
+ * loaded β€” a ghost of the previous automation, which is exactly what the owner reported.
194
+ *
195
+ * A view the reader CHOOSES cannot do that. The Builder renders synchronously from data the
196
+ * rail already had; the Board keeps a fixed-shape skeleton until its own fetch lands. Neither
197
+ * view ever changes shape twice, so there is no second shape to catch a glimpse of.
198
+ */
199
+ /**
200
+ * ⚠ A REVIEW NOTIFICATION OPENS THE BOARD (W23-W5). `initialStage` seeds the stage panel, and
201
+ * only the BOARD reads that β€” so defaulting to the Builder would have landed the reader on a
202
+ * view where the stage they were told about does not appear, with a selection nobody could
203
+ * see. The notification says "cards are waiting at Review"; the cards are on the board.
204
+ */
205
+ const [view, setView] = useState<"builder" | "board">(initialStage ? "board" : "builder");
206
 
207
  // --- the board (C1)
208
  const [board, setBoard] = useState<Board | null>(null);
 
240
  // --- discover_instagram half (R7)
241
  const [recordsLimit, setRecordsLimit] = useState(Number(cfg.recordsLimit || 25));
242
  const [joinOp, setJoinOp] = useState(String(cfg.operator || "and"));
243
+ /**
244
+ * β›” NO SEEDED CONDITION, AND THAT IS THE FIX.
245
+ *
246
+ * This used to seed `{followers >= 10000}` when nothing was stored β€” a field the narrowing
247
+ * guard does not count and a comparison it does not count either. Every Save of a discovery
248
+ * automation therefore sent it and 400'd with "add at least one CONTENT condition…": renaming
249
+ * the automation, changing the cron, editing a step, all of it, on an automation whose filter
250
+ * the user had never touched. Wave 24 made it unmissable by deleting the wizard, so this seed
251
+ * became what every new Instagram automation carries from birth.
252
+ *
253
+ * ⚠ EMPTY IS LEGAL AND MEANS SOMETHING. `clean_predicates` stores `[]` inert (wave 24 A2) and
254
+ * `configured: false` rides the wire, so the surface says "finish setting this up" instead of
255
+ * refusing the save β€” while `run_discover_instagram` still refuses to SPEND on a filter that
256
+ * narrows nothing. Incomplete is a state; only the money door is a wall.
257
+ */
258
  const [preds, setPreds] = useState<Predicate[]>(() => {
259
  const stored = (automation.config as { predicates?: Predicate[] })?.predicates;
260
+ return stored && stored.length ? stored.map((p) => ({ ...p })) : [];
 
 
261
  });
262
  const [estimate, setEstimate] = useState<DiscoverEstimate | null>(null);
263
 
 
335
 
336
  const table = tables.find((t) => t.key === targetTable) || null;
337
 
338
+ /**
339
+ * ⭐ THE WALKING RECORD'S DATABASE β€” the root cause of "the condition on the group names no
340
+ * field" (owner item 12a), and it was never a condition bug.
341
+ *
342
+ * `AutomationBuilder` resolved the field list from `trigger.table` ALONE. Every trigger without
343
+ * a table β€” manual, schedule, and the new `ig_profile_match`, which watches nothing because it
344
+ * MAKES rows β€” therefore handed `CondBuilder` an empty list, so the field picker offered
345
+ * "Choose a field…" and nothing else, and any condition saved against it named no field. The
346
+ * picker looked broken; the automation simply had no table for it to read.
347
+ *
348
+ * β›” MIRRORS `automation_engine._flow_table` (`:4319`) RATHER THAN INVENTING A SECOND RULE, and
349
+ * the ORDER is the part worth copying: the automation's own `targetTable` WINS over the
350
+ * trigger's table, not the other way round. A flow whose actions walk one database while its
351
+ * trigger watches another is a real shape, and getting the precedence backwards would offer the
352
+ * columns of the database the actions do not touch β€” a wrong list that looks authoritative,
353
+ * which this file already says is worse than no list.
354
+ * ⚠ The trigger's OWN pickers keep using the trigger's own table; these are two different
355
+ * questions and answering both from one variable is what produced the bug.
356
+ */
357
+ const walkTable =
358
+ kind === "discover_instagram"
359
+ ? String(cfg.targetTable || "") || String(discover?.table || "")
360
+ : String(cfg.targetTable || "") || String(automation.trigger?.table || "");
361
+
362
  /**
363
  * WHICH CONFIG PANEL IS OPEN β€” and the join is on `panel`, never on id equality.
364
  *
 
446
  * value for any flag a config omits β€” so a Save from here can never quietly
447
  * turn the paid rung off. (`clean_config`'s `flag()`, asserted in section N.)
448
  */
449
+ /**
450
+ * The discovery conditions that are FINISHED enough to send.
451
+ *
452
+ * A condition is written in two gestures β€” pick the comparison, then type the value β€” and the
453
+ * server refuses a non-nullary comparison with no value ("give a value to compare 'biography'
454
+ * against"). Sending a half-written row therefore turned every Save between those two gestures
455
+ * into an error about a condition the user was still in the middle of writing. Held back
456
+ * instead: the row stays on screen and in state, it just is not claimed to the server yet.
457
+ *
458
+ * ⚠ HELD BACK IS SAID OUT LOUD (see `persist`) β€” a row that vanishes from the stored filter
459
+ * without a word is the silent-drop class this module refuses everywhere else.
460
+ *
461
+ * The nullary list comes off the wire; the literal is only for a server that did not send one,
462
+ * and it errs toward SENDING (the server then refuses, loudly) rather than toward dropping.
463
+ */
464
+ const completePreds = (): Predicate[] => {
465
+ const nullary = discover?.nullaryOperators || ["is_null", "is_not_null"];
466
+ return preds.filter((p) => {
467
+ if (!p.name || !p.operator) return false;
468
+ if (nullary.includes(p.operator)) return true;
469
+ return !(
470
+ p.value === undefined ||
471
+ p.value === null ||
472
+ (typeof p.value === "string" && !p.value.trim())
473
+ );
474
+ });
475
+ };
476
+
477
+ /**
478
+ * The sentence for whatever `completePreds` held back, or "" when it held nothing.
479
+ *
480
+ * ⚠ EVERY SAVE PATH SAYS IT, not just the Save button. The trigger picker and the cron control
481
+ * persist IMMEDIATELY (R9) and announce nothing on success β€” so without this, CLEARING a
482
+ * condition's value and then changing the trigger would drop that condition from the stored
483
+ * filter with the row still on screen and not a word anywhere. Holding a half-written row back
484
+ * is a courtesy; holding it back in silence is the drop class this module refuses everywhere.
485
+ */
486
+ const heldNote = (): string => {
487
+ if (kind !== "discover_instagram") return "";
488
+ const held = preds.length - completePreds().length;
489
+ if (held < 1) return "";
490
+ return `Saved β€” ${held} condition${held === 1 ? " was" : "s were"} not saved yet, `
491
+ + `${held === 1 ? "it needs" : "they need"} a value.`;
492
+ };
493
+
494
  const buildConfig = (): Record<string, unknown> => {
495
  if (kind === "scrape_db") {
496
  const fieldMap: Record<string, string> = {};
 
509
  return {
510
  recordsLimit,
511
  operator: joinOp,
512
+ predicates: completePreds(),
513
  targetTable: String(cfg.targetTable || ""),
514
  };
515
  }
516
+ if (kind === "field_instagram") {
517
+ return { targetTable, fieldKey, urlField, maxPosts };
518
+ }
519
+ /*
520
+ β›” EVERY ARM IS EXPLICIT AND THE FALL-THROUGH IS THE MINIMUM (wave 24, R6).
521
+ This used to END at `field_instagram`'s shape, as a bare `return` β€” so it was not a default,
522
+ it was a SILENT DEFAULT KIND, and R6 made `plain` the kind of every new automation. Picking
523
+ a trigger (the first thing anyone does now) called this and sent
524
+ `{targetTable, fieldKey, urlField, maxPosts}` for an automation that has no Instagram column
525
+ and no posts. It happens to be harmless today β€” `clean_config`'s `plain` arm reads only
526
+ `targetTable` and `lanes`, and falls back to the stored `lanes` β€” so nothing is lost and
527
+ nothing 400s. It is fixed anyway, because "harmless" here is luck rather than design: the
528
+ keys are dropped by a validator that was written independently, and the day `plain` grows a
529
+ key this shape happens to contain, a Save from any panel would write a value nobody chose.
530
+
531
+ This is the same defect C found twice in the engine on the same day β€” `graph()`'s final
532
+ `else` is `scrape_db`'s branch and `compose_sentence`'s is `discover_instagram`'s β€” so a new
533
+ kind silently inherited another kind's whole description. A last bare `else` is not a
534
+ default; it is whichever arm happened to be written last.
535
+
536
+ `targetTable` is the one key EVERY kind shares (it is what `_flow_table` resolves), so the
537
+ remaining fall-through carries that and nothing else.
538
+ */
539
+ return { targetTable };
540
  };
541
 
542
  const persist = async (announce = true, sched?: { cron: string; enabled: boolean }) => {
 
547
  schedule: sched || { cron, enabled: !!automation.schedule?.enabled },
548
  });
549
  setTouched(false);
550
+ if (announce) setMessage(heldNote() || "Saved.");
551
  return res.automation.id;
552
  };
553
 
 
575
  schedule: { cron: next.cron, enabled: next.enabled },
576
  });
577
  setTouched(false);
578
+ setMessage(heldNote());
579
  await onSaved(automation.id);
580
  await loadBoard();
581
  } catch (e) {
 
613
  schedule: { cron, enabled: key === "schedule" },
614
  });
615
  setTouched(false);
616
+ setMessage(heldNote());
617
  await onSaved(automation.id);
618
  await loadBoard();
619
  } catch (e) {
 
727
  }
728
  };
729
 
 
 
730
  /**
731
+ * The SCHEDULE half of the trigger face, built once and rendered by the Builder's Properties
732
+ * panel. `AutomationTrigger` owns the vocabulary (C3), the cron round-trip and the tick
733
  * honesty note; this file owns only what a change should WRITE.
734
+ *
735
+ * β›” ONE FACE NOW, NOT TWO (item 10). There used to be a second copy with its picker SHOWN,
736
+ * rendered by the board's `.autob-triggerbar`. The board is for reading where records ARE β€”
737
+ * the trigger belongs to the Builder β€” so the bar is gone and with it the only caller that
738
+ * ever wanted the picker from this file. `hidePicker` survives because it is what makes ONE
739
+ * cron round-trip serve the Properties panel without a second trigger dropdown above it.
740
  */
741
+ const scheduleFace = (
742
  <AutomationTrigger
743
  triggers={triggers}
744
  current={triggerKey}
 
754
  oauth={oauth}
755
  showCron={showCron}
756
  onShowCron={setShowCron}
757
+ hidePicker
758
+ schedules={CRON_DRIVEN_TRIGGERS.includes(triggerKey)}
759
  />
760
  );
761
 
762
+ /**
763
+ * The Builder's writer (C4). It PATCHES a PARTIAL definition β€” `{trigger}` or `{flow}` β€” and
764
+ * nothing else, which is what makes an immediate write safe here: `clean_trigger` and
765
+ * `clean_flow` merge against what is stored, so sending the one key that changed cannot
766
+ * blank the rest. (`persist()` above is the whole-form save the machine-step panels use; the
767
+ * two must not be confused, because that one DOES rewrite `config` from local state.)
768
+ */
769
+ const writeDefinition = async (body: Record<string, unknown>) => {
770
+ setTriggerBusy(true);
771
+ setProblem("");
772
+ setMessage("");
773
+ try {
774
+ await patchAutomation(automation.id, body);
775
+ await onSaved(automation.id);
776
+ await loadBoard();
777
+ } catch (e) {
778
+ // β›” THE SERVER'S SENTENCE, VERBATIM. `clean_flow` refuses an empty group, an unready
779
+ // action kind, a valueless compare β€” each with a reason worth reading. A client that
780
+ // predicted those refusals would be a second validator free to disagree with the one
781
+ // that decides.
782
+ setProblem(e instanceof AutomationError ? e.message : "That change was not saved.");
783
+ } finally {
784
+ setTriggerBusy(false);
785
+ }
786
+ };
787
+
788
+ /**
789
+ * THE NAME, now that it lives at the top of Properties instead of in the page header
790
+ * (item 15b, C-DETAIL).
791
+ *
792
+ * β›” IT COMMITS ON BLUR AND WRITES IMMEDIATELY, like every other free-text field in that
793
+ * panel (the Gmail query, the review prompt, a value). That is not a style choice: the panel
794
+ * stamps "All changes saved", which is its receipt for the immediate-write discipline β€” a
795
+ * name sitting unsaved underneath it would make the stamp a lie. It is the cron field's exact
796
+ * shape (controlled while typing, one write on blur), because per-keystroke would PATCH a
797
+ * half-typed name.
798
+ *
799
+ * ⚠ A BLANK NAME IS NOT A NAME, and the header's Save has always refused one
800
+ * (`disabled={… || !name.trim()}`). Blurring an emptied box therefore RESTORES the stored
801
+ * name rather than writing an empty string or leaving the box contradicting the store β€” the
802
+ * two states a bare early-return would have left behind.
803
+ */
804
+ const commitName = async () => {
805
+ const next = name.trim();
806
+ const stored = automation.name || "";
807
+ if (!next) {
808
+ setName(stored);
809
+ return;
810
+ }
811
+ // Whitespace-only edits still normalise the box; they just have nothing to write.
812
+ if (next === stored) {
813
+ if (next !== name) setName(next);
814
+ return;
815
+ }
816
+ setName(next);
817
+ // ⚠ `{name}` ALONE IS A LEGAL PATCH β€” `engine.patch` merges by key over the stored
818
+ // definition (`automation_engine.py:1176` lists `name` among the patchable six), so this
819
+ // cannot blank the config, the schedule, the trigger or the flow.
820
+ await writeDefinition({ name: next });
821
+ };
822
+
823
+ /**
824
+ * THE MACHINE STEPS' CONFIG BODIES, joined on `panel` (C1 amendment 1) and rendered by
825
+ * BOTH views.
826
+ *
827
+ * ⚠ EXTRACTED, NOT COPIED, and the difference is the whole point. The Builder shows the
828
+ * same engine-derived steps the Board's process strip does, so a second copy of these
829
+ * five panels would be two surfaces that must agree with `clean_config` forever β€” and the
830
+ * way they would stop agreeing is silent: one of them keeps writing a key the engine
831
+ * renamed. One body, two callers.
832
+ */
833
+ const panelBody = (panelKey: string) => (
834
+ <>
835
+ {panelKey === "source" && kind === "scrape_db" ? (
836
+ <>
837
+ <div className="auto-field">
838
+ <label htmlFor="auto-url">Page URL</label>
839
+ <input
840
+ id="auto-url"
841
+ className="auto-input"
842
+ value={url}
843
+ placeholder="https://en.wikipedia.org/wiki/List_of_S%26P_500_companies"
844
+ onChange={(e) => edit(setUrl)(e.target.value)}
845
+ />
846
+ </div>
847
+ <button
848
+ type="button"
849
+ className="auto-btn"
850
+ disabled={!url.trim() || reading}
851
+ onClick={() => void readPage()}
852
+ >
853
+ {reading ? "Reading…" : "Read the page"}
854
+ </button>
855
+ <div className="auto-field">
856
+ <label htmlFor="auto-extract">Read</label>
857
+ <select
858
+ id="auto-extract"
859
+ className="auto-input"
860
+ value={extract}
861
+ onChange={(e) => edit(setExtract)(e.target.value)}
862
+ >
863
+ <option value="table">An HTML table</option>
864
+ <option value="jsonld">Structured data (JSON-LD)</option>
865
+ </select>
866
+ </div>
867
+ {extract === "table" ? (
868
+ <div className="auto-field">
869
+ <label htmlFor="auto-tidx">Which table</label>
870
+ <input
871
+ id="auto-tidx"
872
+ className="auto-input"
873
+ type="number"
874
+ min={0}
875
+ value={tableIndex}
876
+ onChange={(e) => edit(setTableIndex)(Number(e.target.value) || 0)}
877
+ />
878
+ </div>
879
+ ) : null}
880
+ {/* "loopback and link-local addresses" is the SSRF rail describing itself.
881
+ The rail still refuses them, loudly, at the moment it happens. */}
882
+ <p className="auto-hint">Public web pages only.</p>
883
+ </>
884
+ ) : null}
885
+
886
+ {panelKey === "columns" ? (
887
+ plan.length ? (
888
+ <>
889
+ {/* The upsert rules, in full, to somebody choosing a column. What they
890
+ need is which column, and that rows are updated rather than duplicated. */}
891
+ <p className="auto-hint">
892
+ Pick the column that identifies a row, so re-runs update it instead of
893
+ adding it again.
894
+ </p>
895
+ <div className="auto-panel-scroll">
896
+ <table className="auto-table">
897
+ <thead>
898
+ <tr>
899
+ <th>Use</th>
900
+ <th>Source column</th>
901
+ <th>Field key</th>
902
+ <th>Key</th>
903
+ </tr>
904
+ </thead>
905
+ <tbody>
906
+ {plan.map((c, i) => (
907
+ <tr key={c.column}>
908
+ <td>
909
+ <input
910
+ type="checkbox"
911
+ checked={c.include}
912
+ aria-label={`Include ${c.column}`}
913
+ onChange={(e) =>
914
+ edit(setPlan)(
915
+ plan.map((x, j) =>
916
+ j === i ? { ...x, include: e.target.checked } : x
917
+ )
918
+ )
919
+ }
920
+ />
921
+ </td>
922
+ <td className="auto-cell-name">{c.column}</td>
923
+ <td>
924
+ <input
925
+ className="auto-input is-small"
926
+ value={c.key}
927
+ aria-label={`Field key for ${c.column}`}
928
+ onChange={(e) =>
929
+ edit(setPlan)(
930
+ plan.map((x, j) =>
931
+ j === i
932
+ ? { ...x, key: fieldKeyFor(e.target.value) }
933
+ : x
934
+ )
935
+ )
936
+ }
937
+ />
938
+ </td>
939
+ <td>
940
+ <input
941
+ type="radio"
942
+ name="auto-keyfield"
943
+ checked={keyField === c.key && c.include}
944
+ disabled={!c.include}
945
+ aria-label={`Use ${c.column} as the key`}
946
+ onChange={() => edit(setKeyField)(c.key)}
947
+ />
948
+ </td>
949
+ </tr>
950
+ ))}
951
+ </tbody>
952
+ </table>
953
+ </div>
954
+ {preview?.sample?.length ? (
955
+ <p className="auto-hint">
956
+ First row read: {Object.values(preview.sample[0]).slice(0, 4).join(" Β· ")}
957
+ </p>
958
+ ) : null}
959
+ </>
960
+ ) : (
961
+ <p className="auto-note">
962
+ Open the Fetch step and read the page to see what columns it offers.
963
+ </p>
964
+ )
965
+ ) : null}
966
+
967
+ {panelKey === "source" && kind === "field_instagram" ? (
968
+ <>
969
+ <div className="auto-field">
970
+ <label htmlFor="auto-table">Database</label>
971
+ <select
972
+ id="auto-table"
973
+ className="auto-input"
974
+ value={targetTable}
975
+ onChange={(e) => {
976
+ edit(setTargetTable)(e.target.value);
977
+ setFieldKey("");
978
+ setUrlField("");
979
+ }}
980
+ >
981
+ <option value="">Choose a database…</option>
982
+ {targetTable && !tables.some((t) => t.key === targetTable) ? (
983
+ <option value={targetTable}>{targetTable} (not visible to you)</option>
984
+ ) : null}
985
+ {tables.map((t) => (
986
+ <option key={t.key} value={t.key}>
987
+ {t.label} ({t.rowCount} {t.rowCount === 1 ? "row" : "rows"})
988
+ </option>
989
+ ))}
990
+ </select>
991
+ </div>
992
+ <div className="auto-field">
993
+ <label htmlFor="auto-urlfield">Profile URL column</label>
994
+ <select
995
+ id="auto-urlfield"
996
+ className="auto-input"
997
+ value={urlField}
998
+ onChange={(e) => edit(setUrlField)(e.target.value)}
999
+ >
1000
+ <option value="">The column the field is bound to</option>
1001
+ {(table?.fields || []).map((f) => (
1002
+ <option key={f.key} value={f.key}>
1003
+ {f.label}
1004
+ </option>
1005
+ ))}
1006
+ </select>
1007
+ </div>
1008
+ <div className="auto-field">
1009
+ <label htmlFor="auto-fieldkey">Automation column</label>
1010
+ <select
1011
+ id="auto-fieldkey"
1012
+ className="auto-input"
1013
+ value={fieldKey}
1014
+ onChange={(e) => edit(setFieldKey)(e.target.value)}
1015
+ >
1016
+ <option value="">Choose a column…</option>
1017
+ {/*
1018
+ ⚠ THE STORED VALUE IS ALWAYS AN OPTION, even when the list
1019
+ below does not contain it. A <select> whose `value` matches
1020
+ no <option> renders the FIRST one β€” so a column the server
1021
+ knows about but this list has not caught up with would look
1022
+ like a DIFFERENT column, and the next Save would write that
1023
+ different column without anybody choosing it. Showing it as
1024
+ "(not in this database)" is the honest version.
1025
+ */}
1026
+ {fieldKey && !(table?.fields || []).some((f) => f.key === fieldKey) ? (
1027
+ <option value={fieldKey}>{fieldKey} (not in this database)</option>
1028
+ ) : null}
1029
+ {(table?.fields || [])
1030
+ .filter((f) => f.type === "automation")
1031
+ .map((f) => (
1032
+ <option key={f.key} value={f.key}>
1033
+ {f.label}
1034
+ </option>
1035
+ ))}
1036
+ </select>
1037
+ </div>
1038
+ {table && !(table.fields || []).some((f) => f.type === "automation") ? (
1039
+ <p className="auto-note">
1040
+ That database has no automation column yet. Add one from the grid&rsquo;s
1041
+ column menu, then choose it here.
1042
+ </p>
1043
+ ) : null}
1044
+ </>
1045
+ ) : null}
1046
+
1047
+ {panelKey === "capture" ? (
1048
+ <>
1049
+ <div className="auto-field">
1050
+ <label htmlFor="auto-maxposts">Posts per pull</label>
1051
+ <input
1052
+ id="auto-maxposts"
1053
+ className="auto-input"
1054
+ type="number"
1055
+ min={1}
1056
+ max={200}
1057
+ value={maxPosts}
1058
+ onChange={(e) => edit(setMaxPosts)(Number(e.target.value) || 24)}
1059
+ />
1060
+ </div>
1061
+ {/* β›” THREE <h3> ESSAYS ON THE CAPTURE RUNGS lived here β€” the vendor by name,
1062
+ datacenter egress, "204K not 204,312", which rung answers when. The
1063
+ CHOICE a person makes is exact-or-estimated and what it costs; the rest
1064
+ was the architecture explaining itself. DESIGN.md Β§4. */}
1065
+ <h3>Exact counts</h3>
1066
+ <p className="auto-hint">
1067
+ Real follower numbers and the account&rsquo;s top posts, charged per profile.
1068
+ {paidReady ? "" : " Not set up on this workspace yet."}
1069
+ </p>
1070
+ <h3>Post engagement</h3>
1071
+ <p className="auto-hint">
1072
+ Likes and comments per post. Charged per post, so it is its own switch.
1073
+ </p>
1074
+ <h3>Estimated counts</h3>
1075
+ <p className="auto-hint">
1076
+ Free, but rounded (204K rather than 204,312) and marked as estimates. Switch
1077
+ it off to get exact numbers or nothing.
1078
+ </p>
1079
+ </>
1080
+ ) : null}
1081
+
1082
+ {panelKey === "find" ? (
1083
+ <AutomationFind
1084
+ discover={discover}
1085
+ recordsLimit={recordsLimit}
1086
+ onRecordsLimit={(n) => {
1087
+ edit(setRecordsLimit)(n);
1088
+ setEstimate(null);
1089
+ }}
1090
+ joinOp={joinOp}
1091
+ onJoinOp={edit(setJoinOp)}
1092
+ preds={preds}
1093
+ onPreds={edit(setPreds)}
1094
+ estimate={estimate}
1095
+ onEstimate={() => {
1096
+ void discoverEstimate(recordsLimit)
1097
+ .then(setEstimate)
1098
+ .catch(() => setEstimate(null));
1099
+ }}
1100
+ />
1101
+ ) : null}
1102
+
1103
+ {panelKey === "write" ? (
1104
+ <>
1105
+ {kind === "scrape_db" ? (
1106
+ <div className="auto-field">
1107
+ <label htmlFor="auto-tlabel">Database name</label>
1108
+ <input
1109
+ id="auto-tlabel"
1110
+ className="auto-input"
1111
+ value={targetLabel}
1112
+ placeholder="S&P 500 companies"
1113
+ onChange={(e) => edit(setTargetLabel)(e.target.value)}
1114
+ />
1115
+ </div>
1116
+ ) : kind === "discover_instagram" ? (
1117
+ /*
1118
+ β›” FOUR PARAGRAPHS LIVED HERE and the owner quoted every one of them back:
1119
+ the upsert key, the Times-found counter, the never-un-ticked guarantee,
1120
+ the dry-run definition, and "a row that stops appearing at the source is
1121
+ counted and kept, never deleted". All TRUE, all engine internals, none of
1122
+ them a thing a customer came here to learn. DESIGN.md Β§4.
1123
+ What survives is the only sentence with a decision in it: results wait for
1124
+ you. (Duplicates elsewhere are gone rather than reworded β€” the Find panel
1125
+ already says nothing is picked automatically.)
1126
+ */
1127
+ <p className="auto-hint">
1128
+ Profiles you find are saved here for you to review. Nothing is picked
1129
+ automatically.
1130
+ </p>
1131
+ ) : (
1132
+ <p className="auto-hint">
1133
+ Each run adds a dated row, so you keep the history rather than just
1134
+ today&rsquo;s number.
1135
+ </p>
1136
+ )}
1137
+ <p className="auto-hint">
1138
+ Switch this off to test the automation without saving anything.
1139
+ {kind === "field_instagram" ? (
1140
+ <>
1141
+ {" "}
1142
+ {/* "Writes nothing" and "costs nothing" are different claims and only
1143
+ the first is true β€” the one place anybody finds out before the bill. */}
1144
+ It still reads, so it still costs the same.
1145
+ </>
1146
+ ) : null}
1147
+ </p>
1148
+ </>
1149
+ ) : null}
1150
+ </>
1151
+ );
1152
+
1153
  return (
1154
  <div className="auto-detail">
1155
  <header className="auto-head">
1156
+ {/*
1157
+ ⭐ ITEM 15b β€” THE TITLE ROW IS THE VIEW SWITCH NOW. It held an editable name, a run-state
1158
+ chip and a kind tag; all three left and Builder/Board took the space, left-aligned, with
1159
+ Run now / Save / Delete still on the right.
1160
+
1161
+ WHERE EACH ONE WENT, because "removed" and "lost" are different claims:
1162
+ Β· the NAME is the first field of the Builder's Properties panel, writing on blur;
1163
+ Β· the STATE is the builder's own step chip, the Run-now button's "Running…", and the
1164
+ rail's per-automation dot β€” three surfaces that were already saying it;
1165
+ Β· the KIND stops being a user-facing fact at all this wave (R6: every new automation
1166
+ is `plain`), and the two legacy machine kinds describe themselves in Properties β†’
1167
+ Configuration β†’ "How this fetches".
1168
+
1169
+ ⚠ AND THE PAGE TITLE IS NOT DRAWN HERE EITHER WAY. The shell's `DbHead` (W23-W1) draws
1170
+ the SURFACE's name β€” the literal "Automation" off the nav payload β€” never this
1171
+ automation's. See the dated amendment under C-DETAIL: the contract's premise was wrong
1172
+ on that point and the consequence (no name in the Board view) is booked, not patched.
1173
+ */}
1174
  <div className="auto-head-title">
1175
+ {/* TWO VIEWS OF ONE AUTOMATION (C1): what it DOES, and where its records ARE. The
1176
+ switch is a segmented control rather than a tab strip because the page below it
1177
+ does not change identity β€” it is the same automation, read two ways. */}
1178
+ <div className="autox-views" role="group" aria-label="View">
1179
+ {(["builder", "board"] as const).map((v) => (
1180
+ <button
1181
+ key={v}
1182
+ type="button"
1183
+ className={"autox-view" + (view === v ? " is-on" : "")}
1184
+ aria-pressed={view === v}
1185
+ onClick={() => setView(v)}
1186
+ >
1187
+ {v === "builder" ? "Builder" : "Board"}
1188
+ </button>
1189
+ ))}
1190
+ </div>
1191
  </div>
1192
  <div className="auto-head-actions">
1193
+ {/*
1194
+ ⭐ W24-W1 β€” WHAT IT IS DOING, beside the button that started it. This is the whole of
1195
+ item 6's honest fix: "Running…" for two minutes is indistinguishable from a hung
1196
+ thread, and the engine has been publishing the step text the entire time.
1197
+ ⚠ IT IS A STATEMENT, NOT A CONTROL, and it renders only while there is something to
1198
+ say β€” `liveStepOf` returns `""` unless the automation is running, so this never shows
1199
+ a step left over from a run that finished.
1200
+ */}
1201
+ {liveStep ? (
1202
+ <span className="auto-livestep" role="status">
1203
+ {liveStep}
1204
+ </span>
1205
+ ) : null}
1206
  <button
1207
  type="button"
1208
  className="auto-btn"
 
1238
 
1239
  <div className="auto-work">
1240
  {/*
1241
+ β›” THE VIEW IS CHOSEN, NEVER INFERRED (C14 leg 1). This block used to be
1242
+ `{board ? <Board/> : <Steps/>}` β€” the page's SHAPE decided by whether a fetch had
1243
+ answered β€” so every automation you opened drew one layout and then replaced it with
1244
+ another. That second paint, showing the previous automation's shape inside the new
1245
+ one's frame, is the ghost the owner reported.
1246
+
1247
+ `AutomationSteps` is DELETED with that branch. It was the honest fallback for a server
1248
+ with no `/board`; the Builder is a better answer to the same question (it renders the
1249
+ engine's own steps AND what the owner added, from data the rail already had) and there
1250
+ is no longer a state in which the reader gets it by accident.
1251
  */}
1252
+ {view === "builder" ? (
1253
+ <AutomationBuilder
1254
+ automation={automation}
1255
+ // ITEM 15b β€” the name left the header, and this is where it went. Three REQUIRED
1256
+ // props rather than one: the cron field's shape (controlled while typing, one write
1257
+ // on blur) needs the text and the commit to be separable, and an OPTIONAL name would
1258
+ // degrade to "the field does not exist", which is indistinguishable from never
1259
+ // having built it.
1260
+ name={name}
1261
+ // ⚠ NOT `edit(setName)` β€” the name has its own immediate write (`commitName`), so
1262
+ // marking the whole FORM dirty for it would leave `touched` true forever after a
1263
+ // name edit and make the panel's stamp say "unsaved changes" about something it had
1264
+ // just saved. `touched` now means exactly "a field the header's Save owns has been
1265
+ // edited", which is what the stamp below reports.
1266
+ onNameText={setName}
1267
+ onNameCommit={() => void commitName()}
1268
+ // ⭐ THE PANEL'S STAMP MUST NOT LIE, and item 5 is what made this urgent. "All changes
1269
+ // saved" was honest while Properties held only immediate-write controls; the machine
1270
+ // steps' panels moved in this wave and THOSE commit with the header's Save (url,
1271
+ // extract, the column map, the discovery filters). A stamp promising they are saved,
1272
+ // above the fields that are not, is the same defect as an unsaved name under it.
1273
+ dirty={touched}
1274
+ {...(triggers ? { triggers } : {})}
1275
+ catalog={catalog || []}
1276
+ {...(vocab ? { vocab } : {})}
1277
+ tables={tables}
1278
+ oauth={oauth}
1279
+ busy={triggerBusy || saving}
1280
+ onPatch={(body) => void writeDefinition(body)}
1281
+ onToggleNode={(id) => void flip(id)}
1282
+ // β›” THE EXISTING TWO-WRITE SHAPE, not a second copy of it. `pickTrigger` writes
1283
+ // `trigger:{key}` AND `schedule.enabled` together, because the schedule half is
1284
+ // what today's engine reads β€” a builder that wrote only the key would leave "At a
1285
+ // scheduled time" selected on an automation with the cron switched off.
1286
+ onPickTrigger={(key) => void pickTrigger(key)}
1287
+ onRunNow={() => void start()}
1288
+ // Item 7's third clause: the IG trigger's Configuration carries the Scheduled-run
1289
+ // controls too, so the builder needs to know when to render the face it was handed.
1290
+ schedules={CRON_DRIVEN_TRIGGERS.includes(triggerKey)}
1291
+ // Item 12a's root-cause fix β€” resolved HERE because it needs `discover.table`, which
1292
+ // is this component's prop and has no business being threaded into the builder just
1293
+ // to be read once.
1294
+ walkTable={walkTable}
1295
+ // ITEM 5 / C-CFG β€” handed over DIRECTLY now, not wrapped in `(node) => panelBody(
1296
+ // node.panel)`. The builder renders these grouped by panel key under "How this
1297
+ // fetches", so a wrapper taking a node would have to pick one node of a group and
1298
+ // imply the body belonged to it.
1299
+ renderNodeBody={panelBody}
1300
+ // ONE cron round-trip, rendered inside the Properties panel with its own picker
1301
+ // suppressed β€” the builder supplies the "Trigger type" select above it.
1302
+ scheduleFace={scheduleFace}
1303
  />
1304
+ ) : (
1305
+ <>
1306
+ <div className="autob-flow">
1307
+ {/*
1308
+ β›” THE TRIGGER BAR IS GONE (item 10). `.autob-triggerbar` sat above the lanes with
1309
+ a full copy of the trigger face β€” picker included β€” so the same fact had two
1310
+ controls on two views, which is the defect this file's header forbids. The board
1311
+ answers "where are the records"; what starts the run is the Builder's question,
1312
+ and its Properties panel is the one place that answers it now.
1313
+ ⚠ Their CSS is SWEPT too β€” `.autob-triggerbar`, `.autob-triggerbar .auto-field`
1314
+ and `.autob-triggerbar-tag` are deleted from the WAVE22 region by the session that
1315
+ owns it, with a tombstone in their place. (This note said they were "left in the
1316
+ stylesheet"; that was true for about an hour. A comment describing residue that
1317
+ has since been cleaned sends the next reader looking for it.)
1318
+ */}
1319
+ {board ? (
1320
+ <AutomationBoard
1321
+ board={board}
1322
+ selected={selected}
1323
+ onSelect={setSelected}
1324
+ onToggle={(id) => void flip(id)}
1325
+ busyStage={busyNode}
1326
+ onMove={(rowId, to) => void moveOne(rowId, to)}
1327
+ movingRow={movingRow}
1328
+ />
1329
+ ) : (
1330
+ /*
1331
+ A FIXED-SHAPE SKELETON, and the fixed part is what matters (C14 leg 1). Three
1332
+ lanes of the same size appear whatever the board turns out to hold, so the
1333
+ frame never resizes twice: skeleton β†’ board is ONE shape change, and it
1334
+ happens inside a view the reader chose. A spinner would do the same job for
1335
+ the eye; DESIGN.md 4 asks for skeletons because they also hold the space.
1336
+ */
1337
+ <div className="autob-board" aria-busy="true">
1338
+ <div className="autob-cols">
1339
+ {[0, 1, 2].map((i) => (
1340
+ <div className="autob-col" key={i}>
1341
+ <div className="autob-lane is-skeleton">
1342
+ <div className="autob-lane-head">
1343
+ <span className="autox-skel is-pill" />
1344
+ </div>
1345
+ <div className="autob-lane-cards">
1346
+ <span className="autox-skel is-card" />
1347
+ <span className="autox-skel is-card" />
1348
+ </div>
1349
+ </div>
1350
+ </div>
1351
+ ))}
1352
+ </div>
1353
+ </div>
1354
+ )}
1355
+ </div>
1356
 
1357
+ <aside
1358
+ className="auto-panel"
1359
+ aria-label={panelOpen ? `${panelTitle} settings` : "Run history"}
1360
+ >
1361
  {panelOpen ? (
1362
  <>
1363
  <div className="auto-panel-head">
 
1411
  {(automation.reviews || []).slice(0, 12).map((r) => (
1412
  <li key={`${r.ts}-${r.rowId}`} className="autob-review">
1413
  <span className="autob-review-ts">{r.ts.replace("T", " ").slice(0, 16)}</span>
1414
+ {/*
1415
+ ⭐ C6 β€” WHO DECIDED, and a model is not a person. `by: "ai"` prints the
1416
+ MODEL rather than the account the run happened to belong to; printing
1417
+ a username beside a decision nobody made would be the one thing an
1418
+ audit log must never do. Absent `by` = written before this wave = a
1419
+ person, which is what it was.
1420
+ */}
1421
+ <span className="autob-review-who">
1422
+ {r.by === "ai" ? r.model || "AI" : r.user}
1423
+ </span>
1424
  <span className="autob-review-move">
1425
  {r.from} to {r.to}
1426
  </span>
1427
+ {/* The reason, VERBATIM. It is the model's own sentence (or a person's
1428
+ note) β€” this file neither writes nor summarises one. */}
1429
+ {r.note ? (
1430
+ <span className="autob-review-note">{r.note}</span>
1431
+ ) : null}
1432
  </li>
1433
  ))}
1434
  </ol>
 
1444
  here that the card does not already say.
1445
  */}
1446
 
1447
+ {panelBody(panelKey)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1448
  </>
1449
  ) : (
1450
  <>
 
1517
  <p className="auto-hint">
1518
  {board
1519
  ? "Click a stage to see and change what it does."
1520
+ : "The lanes appear once the board answers."}
1521
  </p>
1522
  </>
1523
  )}
1524
+ </aside>
1525
+ </>
1526
+ )}
1527
  </div>
1528
  </div>
1529
  );
web/src/automation/AutomationFind.tsx CHANGED
@@ -34,6 +34,7 @@
34
  import type {
35
  DiscoverEstimate,
36
  DiscoverFieldMeta,
 
37
  DiscoverVocab,
38
  Predicate,
39
  } from "./automationApi";
@@ -51,9 +52,160 @@ 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;
 
 
 
 
 
 
57
  /** Every stored condition naming this field, with its index in the saved array. */
58
  at: number[];
59
  /** MEASURED to carry values. `null` = the server has not said (C4 not shipped yet). */
@@ -62,24 +214,48 @@ interface FieldRow {
62
  narrowing: boolean | null;
63
  }
64
 
 
 
 
 
 
 
65
  /**
66
- * A default operator that is VALID THE MOMENT THE SWITCH GOES ON.
 
67
  *
68
- * ⚠ This is the wave-21 item-8 scar in a new shape. A new condition used to
69
- * arrive as `{biography includes ""}` β€” a comparison with no value, which
70
- * `clean_predicates` refuses outright β€” so adding one and pressing Save returned
71
- * "give a value to compare 'biography' against" for a condition the user had not
72
- * finished writing. A NULLARY operator needs no value, so a freshly toggled
73
- * field is a complete, saveable, narrowing-in-the-right-direction condition
74
- * ("this field has any value") from its first frame.
 
 
 
 
 
 
 
 
75
  *
76
- * Derived from the server's own lists rather than typed here, so it cannot name
77
- * an operator the API rejects.
 
 
 
 
 
 
 
 
 
 
78
  */
79
- function firstOperator(v?: DiscoverVocab): string {
80
- const nullary = v?.nullaryOperators || [];
81
- const preferred = nullary.find((o) => o === "is_not_null");
82
- return preferred || nullary[0] || (v?.operators || [])[0] || "";
83
  }
84
 
85
  /**
@@ -107,6 +283,14 @@ function buildRows(preds: Predicate[], v?: DiscoverVocab): FieldRow[] {
107
  const m = meta.get(name);
108
  return {
109
  name,
 
 
 
 
 
 
 
 
110
  at: byName.get(name) || [],
111
  populated: m ? !!m.populated : lead.has(name) ? true : null,
112
  narrowing: m ? !!m.narrowing : null,
@@ -131,8 +315,10 @@ export default function AutomationFind({
131
  }: Props) {
132
  const rows = buildRows(preds, discover);
133
  const known = new Set(discover?.fields || []);
 
 
 
134
  const nullary = new Set(discover?.nullaryOperators || []);
135
- const operators = discover?.operators || [];
136
  const withValues = rows.filter((r) => r.populated === true);
137
  const rest = rows.filter((r) => r.populated !== true);
138
  const knownMeta = !!(discover?.filterMeta || []).length;
@@ -157,13 +343,20 @@ export default function AutomationFind({
157
  onPreds(preds.filter((p) => p.name !== row.name));
158
  return;
159
  }
160
- onPreds([...preds, { name: row.name, operator: firstOperator(discover) }]);
161
  };
162
 
163
  /** One condition line β€” the comparison, its value, and a way out. */
164
- const condition = (i: number, label: string) => {
165
  const p = preds[i];
166
  if (!p) return null;
 
 
 
 
 
 
 
167
  return (
168
  <div className="autob-cond" key={`${p.name}-${i}`}>
169
  <select
@@ -175,27 +368,49 @@ export default function AutomationFind({
175
  {/* The stored value is ALWAYS an option. A select whose value matches no
176
  option renders the FIRST one, and the next Save writes a comparison
177
  nobody chose β€” this codebase has paid for that twice. */}
178
- {p.operator && !operators.includes(p.operator) ? (
179
  <option value={p.operator}>{p.operator}</option>
180
  ) : null}
181
- {operators.map((o) => (
182
- <option key={o} value={o}>
183
- {o}
184
  </option>
185
  ))}
186
  </select>
187
- {nullary.has(p.operator) ? (
188
- <span className="autob-cond-novalue" title="This comparison takes no value">
189
- any value
190
- </span>
 
 
 
 
 
 
 
 
 
 
 
 
191
  ) : (
192
  <input
193
  className="auto-input is-small"
 
194
  aria-label={`Value for ${label}`}
195
- value={p.value === undefined ? "" : String(p.value)}
196
- onChange={(e) => setAt(i, { value: e.target.value })}
 
 
 
 
197
  />
198
  )}
 
 
 
 
 
199
  <button
200
  type="button"
201
  className="autob-cond-x"
@@ -220,17 +435,24 @@ export default function AutomationFind({
220
  type="button"
221
  className={"auto-step-switch autob-tgl-switch" + (on ? " is-on" : "")}
222
  aria-pressed={on}
223
- aria-label={`${on ? "Stop searching" : "Search"} on ${row.name}`}
224
- title={`${on ? "Stop searching" : "Search"} on ${row.name}`}
225
  onClick={() => toggleField(row)}
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
232
- differently from the error makes the error unmatchable. */}
233
- <span className="autob-tgl-name">{row.name}</span>
 
 
 
 
 
 
 
234
  {/*
235
  ⚠ ONE CHIP, AND IT MARKS THE MINORITY. The first version chipped every
236
  non-narrowing field "broad" AND every unpopulated one "no values seen" β€”
@@ -247,7 +469,7 @@ export default function AutomationFind({
247
  {row.narrowing === true ? (
248
  <span
249
  className="autob-tgl-flag is-narrow"
250
- title="Cuts the corpus down. A search needs at least one condition that does."
251
  >
252
  narrows
253
  </span>
@@ -255,15 +477,16 @@ export default function AutomationFind({
255
  </div>
256
  {on ? (
257
  <div className="autob-tgl-body">
258
- {row.at.map((i) => condition(i, row.name))}
 
259
  <button
260
  type="button"
261
  className="autob-cond-add"
262
  onClick={() =>
263
- onPreds([...preds, { name: row.name, operator: firstOperator(discover) }])
264
  }
265
  >
266
- Another condition on {row.name}
267
  </button>
268
  </div>
269
  ) : null}
@@ -285,11 +508,10 @@ export default function AutomationFind({
285
  onChange={(e) => onRecordsLimit(Number(e.target.value) || 1)}
286
  />
287
  </div>
288
- <p className="auto-hint">
289
- A search must be bounded β€” at most {maxRecords.toLocaleString()} profiles a run. An
290
- unbounded one matches a share of a corpus of hundreds of millions, and the vendor
291
- refuses it outright rather than delivering it.
292
- </p>
293
 
294
  <h3>Conditions</h3>
295
  <div className="auto-field autob-match">
@@ -315,9 +537,9 @@ export default function AutomationFind({
315
  <div className="autob-tglgroup">
316
  <p
317
  className="autob-tglgroup-label"
318
- title="Seen carrying values on real corpus rows."
319
  >
320
- Has values
321
  </p>
322
  {withValues.map(fieldRow)}
323
  </div>
@@ -329,11 +551,11 @@ export default function AutomationFind({
329
  className="autob-tglgroup-label"
330
  title={
331
  knownMeta
332
- ? "Filterable, but empty on every profile we have measured β€” a condition on one of these can return nothing at all."
333
- : "Whether these carry values has not been measured yet."
334
  }
335
  >
336
- {knownMeta ? "No values seen" : "Not measured"}
337
  </p>
338
  {rest.map(fieldRow)}
339
  </div>
@@ -345,6 +567,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
@@ -356,14 +586,11 @@ export default function AutomationFind({
356
  </div>
357
  ) : null}
358
 
 
 
 
359
  <p className="auto-hint">
360
- {/* ONE consequence sentence, because it is the one that costs money. Which
361
- fields carry values is not trivia: a condition on an empty field returns
362
- nothing and looks exactly like an honest "no such accounts exist". */}
363
- A condition on a field with no values returns nothing while looking exactly like
364
- &ldquo;no such accounts exist&rdquo;. Narrow conditions matter more than a small limit
365
- β€” the search reads the whole corpus either way, so a broad one is slow and expensive
366
- however few rows you keep.
367
  </p>
368
 
369
  <h3>What it costs</h3>
 
34
  import type {
35
  DiscoverEstimate,
36
  DiscoverFieldMeta,
37
+ DiscoverOperator,
38
  DiscoverVocab,
39
  Predicate,
40
  } from "./automationApi";
 
52
  onEstimate: () => void;
53
  }
54
 
55
+ /**
56
+ * A FILTER FIELD'S ICON (owner item 5). Drawn, `currentColor`, never an emoji β€” and in the
57
+ * existing `TriggerMark`/`ActionMark` language rather than a new one: same 16 viewBox, same 15px
58
+ * box, same 1.4 stroke, so a row here and a card in the builder read as one product.
59
+ *
60
+ * ⚠ SHARED SHAPES WHERE THE FIELDS SHARE A MEANING, distinct everywhere else. `TriggerMark`'s
61
+ * note settled the principle β€” a column of identical glyphs is decoration, the eye learns nothing
62
+ * β€” but its converse matters just as much here: `bio_hashtags` and `post_hashtags` ARE both
63
+ * hashtags, and drawing two different marks for them would invent a distinction the vendor does
64
+ * not make. Twenty-one contrived glyphs would be twenty-one things to misread.
65
+ *
66
+ * β›” THE FALLBACK IS NOT A MEMBER OF THE SET, which is the `ActionMark` scar exactly: its default
67
+ * used to BE the pencil, a real member, so every unmatched kind silently borrowed "edit" and a
68
+ * fallback could not be told from a match. The vocabulary is the SERVER's β€” it can grow a field
69
+ * tomorrow β€” so an unmatched name draws a neutral mark that is deliberately meaningless.
70
+ */
71
+ function FilterMark({ name }: { name: string }) {
72
+ const common = {
73
+ width: 15, height: 15, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor",
74
+ strokeWidth: 1.4, strokeLinecap: "round" as const, strokeLinejoin: "round" as const,
75
+ "aria-hidden": true,
76
+ };
77
+ // Audience size β€” two figures, one behind the other.
78
+ if (name === "followers")
79
+ return (
80
+ <svg {...common}>
81
+ <circle cx="6.2" cy="5.6" r="2.4" />
82
+ <path d="M2.2 13c.5-2 2.1-3.2 4-3.2s3.5 1.2 4 3.2" />
83
+ <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" />
84
+ </svg>
85
+ );
86
+ // Who this account follows β€” a figure with an outbound arrow.
87
+ if (name === "following")
88
+ return (
89
+ <svg {...common}>
90
+ <circle cx="6" cy="5.6" r="2.4" />
91
+ <path d="M1.8 13c.5-2 2.1-3.2 4.2-3.2 .6 0 1.2.1 1.7.3" />
92
+ <path d="M9.8 10.6h4.2M12.2 8.8l1.8 1.8-1.8 1.8" />
93
+ </svg>
94
+ );
95
+ if (name === "posts_count")
96
+ return (
97
+ <svg {...common}>
98
+ <rect x="2.6" y="2.6" width="4.6" height="4.6" rx="1" />
99
+ <rect x="8.8" y="2.6" width="4.6" height="4.6" rx="1" />
100
+ <rect x="2.6" y="8.8" width="4.6" height="4.6" rx="1" />
101
+ <rect x="8.8" y="8.8" width="4.6" height="4.6" rx="1" />
102
+ </svg>
103
+ );
104
+ // A story highlight β€” the ring Instagram draws around one.
105
+ if (name === "highlights_count")
106
+ return (
107
+ <svg {...common}>
108
+ <circle cx="8" cy="8" r="5.6" strokeDasharray="2.6 1.8" />
109
+ <circle cx="8" cy="8" r="2.2" />
110
+ </svg>
111
+ );
112
+ if (name === "avg_engagement")
113
+ return (
114
+ <svg {...common}>
115
+ <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" />
116
+ </svg>
117
+ );
118
+ if (name === "biography")
119
+ return (
120
+ <svg {...common}>
121
+ <rect x="2.4" y="2.8" width="11.2" height="10.4" rx="1.6" />
122
+ <path d="M4.8 6h6.4M4.8 8.4h6.4M4.8 10.8h3.6" />
123
+ </svg>
124
+ );
125
+ if (name === "category_name" || name === "business_category_name")
126
+ return (
127
+ <svg {...common}>
128
+ <path d="M8.4 2.6H13v4.6l-6.2 6.2-4.6-4.6z" />
129
+ <circle cx="10.8" cy="5.2" r="0.9" />
130
+ </svg>
131
+ );
132
+ if (name === "is_business_account" || name === "is_professional_account")
133
+ return (
134
+ <svg {...common}>
135
+ <rect x="2.2" y="5" width="11.6" height="8.2" rx="1.6" />
136
+ <path d="M6 5V3.6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1V5" />
137
+ </svg>
138
+ );
139
+ if (name === "is_verified")
140
+ return (
141
+ <svg {...common}>
142
+ <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" />
143
+ <path d="m5.8 8.1 1.5 1.5 3-3.1" />
144
+ </svg>
145
+ );
146
+ // The handle, and the display name it is written under.
147
+ if (name === "account" || name === "profile_name")
148
+ return (
149
+ <svg {...common}>
150
+ <circle cx="8" cy="8" r="2.4" />
151
+ <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" />
152
+ </svg>
153
+ );
154
+ if (name === "full_name")
155
+ return (
156
+ <svg {...common}>
157
+ <circle cx="8" cy="5.6" r="2.6" />
158
+ <path d="M3 13.4c.7-2.3 2.6-3.6 5-3.6s4.3 1.3 5 3.6" />
159
+ </svg>
160
+ );
161
+ if (name === "external_url" || name === "profile_url")
162
+ return (
163
+ <svg {...common}>
164
+ <path d="M6.6 9.4 4.9 11a2.6 2.6 0 1 1-1.5-4.4" />
165
+ <path d="M9.4 6.6 11.1 5a2.6 2.6 0 1 1 1.5 4.4" />
166
+ <path d="M6.2 8h3.6" />
167
+ </svg>
168
+ );
169
+ if (name === "bio_hashtags" || name === "post_hashtags")
170
+ return (
171
+ <svg {...common}>
172
+ <path d="M6.2 2.8 4.8 13.2M11.2 2.8 9.8 13.2M2.8 6h10.4M2.2 10h10.4" />
173
+ </svg>
174
+ );
175
+ if (name === "related_accounts")
176
+ return (
177
+ <svg {...common}>
178
+ <circle cx="8" cy="3.6" r="1.8" />
179
+ <circle cx="3.6" cy="12" r="1.8" />
180
+ <circle cx="12.4" cy="12" r="1.8" />
181
+ <path d="M6.8 5.2 4.6 10.4M9.2 5.2l2.2 5.2M5.4 12h5.2" />
182
+ </svg>
183
+ );
184
+ // The vendor's own record keys β€” the thing you hold to open exactly one row.
185
+ if (name === "id" || name === "fbid")
186
+ return (
187
+ <svg {...common}>
188
+ <circle cx="5.4" cy="10.6" r="2.6" />
189
+ <path d="M7.2 8.8 13 3M10.6 5.4l1.6 1.6M9.2 6.8l1.6 1.6" />
190
+ </svg>
191
+ );
192
+ return (
193
+ <svg {...common}>
194
+ <rect x="3.2" y="3.2" width="9.6" height="9.6" rx="2.2" />
195
+ <circle cx="8" cy="8" r="1.4" />
196
+ </svg>
197
+ );
198
+ }
199
+
200
  /** One field's line in the list, with everything known about it. */
201
  interface FieldRow {
202
  name: string;
203
+ /** What the row is CALLED. Falls back to the raw name only if the server sent none. */
204
+ label: string;
205
+ hint: string;
206
+ kind: string;
207
+ operators: DiscoverOperator[];
208
+ options: { value: string; label: string }[];
209
  /** Every stored condition naming this field, with its index in the saved array. */
210
  at: number[];
211
  /** MEASURED to carry values. `null` = the server has not said (C4 not shipped yet). */
 
214
  narrowing: boolean | null;
215
  }
216
 
217
+ /** A stored value β†’ what the text box shows. A list is the "any of" shape. */
218
+ function valueText(v: Predicate["value"]): string {
219
+ if (Array.isArray(v)) return v.join(", ");
220
+ return v === undefined || v === null ? "" : String(v);
221
+ }
222
+
223
  /**
224
+ * What the user typed β†’ what is stored. Comma-separated becomes a LIST for the operators that
225
+ * accept one, and stays a plain string for the ones that do not.
226
  *
227
+ * ⚠ A single value stays a SCALAR rather than a one-element list β€” the server sends scalars
228
+ * flat and lists as a nested OR group, and a one-element group is a shape nothing has been
229
+ * billed against.
230
+ */
231
+ function parseValue(text: string, multi: boolean): Predicate["value"] {
232
+ if (!multi) return text;
233
+ const parts = text.split(",").map((s) => s.trim()).filter(Boolean);
234
+ if (parts.length > 1) return parts;
235
+ // Keep the RAW text while it is still being typed β€” trimming here would fight the cursor on
236
+ // every keystroke, and the server trims anyway.
237
+ return text;
238
+ }
239
+
240
+ /**
241
+ * The comparison a freshly toggled field starts with β€” ASKED FOR, never chosen here.
242
  *
243
+ * β›” THE THIRD COSTUME OF ONE SCAR, and the reason this function no longer has an opinion.
244
+ * Wave 21 made a new condition NULLARY (`is_not_null`) so it would be saveable without a
245
+ * value, and called that "narrowing-in-the-right-direction". Wave 22 then wrote the narrowing
246
+ * law server-side and `is_not_null` is not in it. From that moment, toggling ANY field on and
247
+ * pressing Save returned "add at least one CONTENT condition…" β€” the error told the user to do
248
+ * the exact thing they had just done. Wave 24 deleted the wizard and made this panel the only
249
+ * door, so it stopped being a corner case and became the first thing a new user hits.
250
+ *
251
+ * The fix is not a better guess. It is that the module owning the guard also names the default
252
+ * (`automation_engine.default_operator`, asserted against `predicate_narrows` in
253
+ * `verify_automation.py`), and this file looks it up per FIELD. An absent one falls back to the
254
+ * server's first operator β€” never to a nullary, which is the thing that could not narrow.
255
  */
256
+ function firstOperator(v: DiscoverVocab | undefined, name: string): string {
257
+ const meta = (v?.filterMeta || []).find((m) => m.name === name);
258
+ return meta?.defaultOperator || (v?.operators || [])[0] || "";
 
259
  }
260
 
261
  /**
 
283
  const m = meta.get(name);
284
  return {
285
  name,
286
+ label: m?.label || name,
287
+ hint: m?.hint || "",
288
+ kind: m?.kind || "text",
289
+ // β›” NO FALLBACK TO THE GLOBAL OPERATOR LIST. An older server that sends no per-field list
290
+ // gets a row with no comparisons rather than all fourteen on every field β€” visibly
291
+ // unfinished beats quietly offering `at least` on a yes/no column.
292
+ operators: m?.operators || [],
293
+ options: m?.options || [],
294
  at: byName.get(name) || [],
295
  populated: m ? !!m.populated : lead.has(name) ? true : null,
296
  narrowing: m ? !!m.narrowing : null,
 
315
  }: Props) {
316
  const rows = buildRows(preds, discover);
317
  const known = new Set(discover?.fields || []);
318
+ // The GLOBAL operator list is gone from this component: comparisons are per field now
319
+ // (`row.operators`). `nullary` survives for STRAYS only β€” a stored condition on a field the
320
+ // vendor dropped has no per-field row to read from, and it still has to render to be removable.
321
  const nullary = new Set(discover?.nullaryOperators || []);
 
322
  const withValues = rows.filter((r) => r.populated === true);
323
  const rest = rows.filter((r) => r.populated !== true);
324
  const knownMeta = !!(discover?.filterMeta || []).length;
 
343
  onPreds(preds.filter((p) => p.name !== row.name));
344
  return;
345
  }
346
+ onPreds([...preds, { name: row.name, operator: firstOperator(discover, row.name) }]);
347
  };
348
 
349
  /** One condition line β€” the comparison, its value, and a way out. */
350
+ const condition = (i: number, label: string, row?: FieldRow) => {
351
  const p = preds[i];
352
  if (!p) return null;
353
+ // The field's OWN comparisons. `row` is absent only for a stray (a stored condition on a
354
+ // field the vendor no longer offers), which keeps the raw token so it stays removable.
355
+ const ops = row?.operators || [];
356
+ const cur = ops.find((o) => o.value === p.operator);
357
+ const isNullary = cur ? cur.nullary : nullary.has(p.operator);
358
+ const isMulti = !!cur?.multi;
359
+ const options = row?.options || [];
360
  return (
361
  <div className="autob-cond" key={`${p.name}-${i}`}>
362
  <select
 
368
  {/* The stored value is ALWAYS an option. A select whose value matches no
369
  option renders the FIRST one, and the next Save writes a comparison
370
  nobody chose β€” this codebase has paid for that twice. */}
371
+ {p.operator && !ops.some((o) => o.value === p.operator) ? (
372
  <option value={p.operator}>{p.operator}</option>
373
  ) : null}
374
+ {ops.map((o) => (
375
+ <option key={o.value} value={o.value}>
376
+ {o.label}
377
  </option>
378
  ))}
379
  </select>
380
+ {isNullary ? null : options.length ? (
381
+ // A fixed vocabulary gets a dropdown. Owner item 2: a yes/no column was a box you
382
+ // typed `true` into, beside a comparison list that offered "at least".
383
+ <select
384
+ className="auto-input is-small"
385
+ aria-label={`Value for ${label}`}
386
+ value={valueText(p.value)}
387
+ onChange={(e) => setAt(i, { value: e.target.value })}
388
+ >
389
+ <option value="">Choose…</option>
390
+ {options.map((o) => (
391
+ <option key={o.value} value={o.value}>
392
+ {o.label}
393
+ </option>
394
+ ))}
395
+ </select>
396
  ) : (
397
  <input
398
  className="auto-input is-small"
399
+ type={row?.kind === "number" ? "number" : "text"}
400
  aria-label={`Value for ${label}`}
401
+ // ⭐ OWNER ITEM 3. Several comma-separated values become an "any of" condition, which
402
+ // the server sends as its own OR group β€” so it does NOT drag Followers into a union
403
+ // the way the Match dropdown would.
404
+ placeholder={isMulti ? "floral, flower, beauty" : ""}
405
+ value={valueText(p.value)}
406
+ onChange={(e) => setAt(i, { value: parseValue(e.target.value, isMulti) })}
407
  />
408
  )}
409
+ {isMulti && Array.isArray(p.value) && p.value.length > 1 ? (
410
+ <span className="autob-cond-any" title="Any one of these is a match">
411
+ any of {p.value.length}
412
+ </span>
413
+ ) : null}
414
  <button
415
  type="button"
416
  className="autob-cond-x"
 
435
  type="button"
436
  className={"auto-step-switch autob-tgl-switch" + (on ? " is-on" : "")}
437
  aria-pressed={on}
438
+ aria-label={`${on ? "Stop searching" : "Search"} on ${row.label}`}
439
+ title={`${on ? "Stop searching" : "Search"} on ${row.label}`}
440
  onClick={() => toggleField(row)}
441
  >
442
  <span className="auto-step-switch-knob" />
443
  </button>
444
+ <span className="autob-tgl-mark">
445
+ <FilterMark name={row.name} />
446
+ </span>
447
+ {/* ⭐ THE HUMAN LABEL (owner item 1: "wtf is id/fbid").
448
+ This used to render the vendor's own column name verbatim, and the comment
449
+ defending it was RIGHT about the reason β€” a refusal names the field, and a label
450
+ that reads differently makes the error unmatchable. So the label did not move
451
+ alone: `field_label()` is what the SERVER's refusals use too, which is the only
452
+ version of this change that does not trade one confusion for another. */}
453
+ <span className="autob-tgl-name" title={row.hint || undefined}>
454
+ {row.label}
455
+ </span>
456
  {/*
457
  ⚠ ONE CHIP, AND IT MARKS THE MINORITY. The first version chipped every
458
  non-narrowing field "broad" AND every unpopulated one "no values seen" β€”
 
469
  {row.narrowing === true ? (
470
  <span
471
  className="autob-tgl-flag is-narrow"
472
+ title="A search needs at least one condition like this."
473
  >
474
  narrows
475
  </span>
 
477
  </div>
478
  {on ? (
479
  <div className="autob-tgl-body">
480
+ {row.at.map((i) => condition(i, row.label, row))}
481
+ {row.hint ? <p className="autob-tgl-hint">{row.hint}</p> : null}
482
  <button
483
  type="button"
484
  className="autob-cond-add"
485
  onClick={() =>
486
+ onPreds([...preds, { name: row.name, operator: firstOperator(discover, row.name) }])
487
  }
488
  >
489
+ Another condition on {row.label}
490
  </button>
491
  </div>
492
  ) : null}
 
508
  onChange={(e) => onRecordsLimit(Number(e.target.value) || 1)}
509
  />
510
  </div>
511
+ {/* Owner item 5: "Stop at the 'A search must be at most 500 profiles a run'". The two
512
+ sentences that followed explained the vendor's billing model to somebody who wants a
513
+ list of florists. */}
514
+ <p className="auto-hint">At most {maxRecords.toLocaleString()} profiles a run.</p>
 
515
 
516
  <h3>Conditions</h3>
517
  <div className="auto-field autob-match">
 
537
  <div className="autob-tglgroup">
538
  <p
539
  className="autob-tglgroup-label"
540
+ title="Most accounts have this filled in."
541
  >
542
+ Usually filled in
543
  </p>
544
  {withValues.map(fieldRow)}
545
  </div>
 
551
  className="autob-tglgroup-label"
552
  title={
553
  knownMeta
554
+ ? "Most accounts leave these blank, so a condition here can return nothing."
555
+ : "We have not measured how often these are filled in."
556
  }
557
  >
558
+ {knownMeta ? "Often blank" : "Not measured"}
559
  </p>
560
  {rest.map(fieldRow)}
561
  </div>
 
567
  {strays.map(({ p, i }) => (
568
  <div className="autob-tgl is-on is-stray" key={`stray-${i}`}>
569
  <div className="autob-tgl-head">
570
+ {/* A stray gets a mark too β€” "every filter row" includes the ones the vendor no
571
+ longer offers, and a row missing the icon its neighbours have would read as a
572
+ different KIND of thing rather than as a field that fell out of the list. It
573
+ draws the neutral fallback by construction: a stray is, by definition, not in
574
+ the vocabulary this component has arms for. */}
575
+ <span className="autob-tgl-mark">
576
+ <FilterMark name={p.name} />
577
+ </span>
578
  <span className="autob-tgl-name">{p.name}</span>
579
  <span className="autob-tgl-flag is-stray" title="The server will refuse this condition by name.">
580
  not searchable
 
586
  </div>
587
  ) : null}
588
 
589
+ {/* The consequence kept, the mechanism dropped: a condition on an often-blank field
590
+ returning nothing is a thing that will happen to somebody and confuse them. Why the
591
+ search is slow when broad is our problem, not theirs. */}
592
  <p className="auto-hint">
593
+ Conditions on often-blank fields can come back with nothing.
 
 
 
 
 
 
594
  </p>
595
 
596
  <h3>What it costs</h3>
web/src/automation/AutomationSurface.tsx CHANGED
@@ -16,20 +16,37 @@
16
  import type { KeyboardEvent as ReactKeyboardEvent } from "react";
17
  import { useCallback, useEffect, useRef, useState } from "react";
18
 
19
- import AutomationCreate from "./AutomationCreate";
 
20
  import AutomationDetail from "./AutomationDetail";
21
  import type { Automation, AutomationList } from "./automationApi";
22
  import {
23
  AutomationError,
 
24
  listAutomations,
 
25
  patchAutomation,
26
  stateOf,
27
  } from "./automationApi";
28
 
 
 
 
 
 
 
 
 
29
  /** The status dot's title β€” the rail says WHY it is that colour, not just that it is. */
30
  function stateTitle(a: Automation): string {
31
  const s = stateOf(a);
32
- if (s === "running") return "Running now";
 
 
 
 
 
 
33
  if (s === "ok") return `Last run succeeded β€” ${a.status?.lastSummary || ""}`;
34
  if (s === "partial") return `Last run was partial β€” ${a.status?.lastSummary || ""}`;
35
  if (s === "error") return `Last run failed β€” ${a.status?.lastSummary || ""}`;
@@ -50,33 +67,188 @@ function stateTitle(a: Automation): string {
50
  * its job. [[ui-invisible-to-assertions]] β€” judge the pixels even when everything is green.
51
  */
52
  function railSubtitle(a: Automation): string {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  if (a.schedule?.enabled) return a.nextRunAt ? `Next ${a.nextRunAt}` : "Scheduled";
54
  const last = a.status?.lastRunAt ? a.status.lastRunAt.replace("T", " ").slice(0, 16) : "";
55
  return last ? `Last run ${last}` : "Manual only";
56
  }
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  export default function AutomationSurface() {
59
  const [data, setData] = useState<AutomationList | null>(null);
60
  const [error, setError] = useState("");
61
  const [activeId, setActiveId] = useState<string>("");
62
- const [creating, setCreating] = useState(false);
63
  const [railShut, setRailShut] = useState(false);
64
  const [busy, setBusy] = useState("");
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  const listRef = useRef<HTMLDivElement | null>(null);
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  const load = useCallback(async (abort?: AbortSignal) => {
 
68
  try {
69
  const next = await listAutomations(abort);
70
- setData(next);
71
- setError("");
 
 
72
  return next;
73
  } catch (e) {
74
  if ((e as Error)?.name === "AbortError") return null;
75
- setError(
76
- e instanceof AutomationError
77
- ? e.message
78
- : "The automation service did not answer."
79
- );
 
80
  return null;
81
  }
82
  }, []);
@@ -87,16 +259,169 @@ export default function AutomationSurface() {
87
  return () => ac.abort();
88
  }, [load]);
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  // A run is a background thread on the server, so the surface has to ASK whether it
91
  // finished. Polling only while something is actually running keeps an idle surface
92
  // silent β€” a fixed interval would be a request every few seconds forever, for a page
93
  // whose contents change a handful of times a day.
94
- const anyRunning = (data?.automations || []).some((a) => a.running);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  useEffect(() => {
96
- if (!anyRunning) return undefined;
97
- const t = window.setInterval(() => void load(), 2500);
98
- return () => window.clearInterval(t);
99
- }, [anyRunning, load]);
 
 
 
100
 
101
  const items = data?.automations || [];
102
  const active = items.find((a) => a.id === activeId) || null;
@@ -160,10 +485,8 @@ export default function AutomationSurface() {
160
  <button
161
  type="button"
162
  className="auto-create-btn"
163
- onClick={() => {
164
- setCreating(true);
165
- setActiveId("");
166
- }}
167
  >
168
  <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
169
  <path
@@ -188,10 +511,7 @@ export default function AutomationSurface() {
188
  <button
189
  type="button"
190
  className="auto-row-main"
191
- onClick={() => {
192
- setActiveId(a.id);
193
- setCreating(false);
194
- }}
195
  >
196
  <span
197
  className={`auto-dot is-${s}`}
@@ -243,17 +563,18 @@ export default function AutomationSurface() {
243
  </div>
244
  ) : null}
245
 
246
- {creating ? (
247
- <AutomationCreate
248
- kinds={data?.kinds || []}
249
- onCreated={async (id) => {
250
- setCreating(false);
251
- const next = await load();
252
- if (id && next) setActiveId(id);
253
- }}
254
- onCancel={() => setCreating(false)}
255
- />
256
- ) : active ? (
 
257
  <AutomationDetail
258
  key={active.id}
259
  automation={active}
@@ -265,16 +586,52 @@ export default function AutomationSurface() {
265
  // trigger face can tell "the server offered nothing" from "the server offered
266
  // an empty list" rather than collapsing both into a picker with no options.
267
  triggers={data?.triggers}
 
 
 
 
 
268
  // `?? null` and never `|| {enabled:false}`: an absent tick bit is "the server did
269
  // not say", which Step 1 prints as its own sentence. Defaulting it here would
270
  // turn a missing field into a claim about production (C6 amendment #1).
271
  tick={data?.tick ?? null}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
  onSaved={async (id) => {
273
  const next = await load();
274
- if (id && next) setActiveId(id);
275
  }}
276
  onDeleted={async () => {
277
- setActiveId("");
278
  await load();
279
  }}
280
  />
@@ -296,17 +653,24 @@ export default function AutomationSurface() {
296
  * paragraph, spent differently.
297
  */
298
  <div className="autob-empty">
299
- <h1 className="autob-empty-title">Automations</h1>
 
 
 
 
 
 
 
 
 
300
  <p className="autob-empty-line">
301
  A job this workspace runs for you, on demand or on a schedule.
302
  </p>
303
  <button
304
  type="button"
305
  className="auto-btn is-primary"
306
- onClick={() => {
307
- setCreating(true);
308
- setActiveId("");
309
- }}
310
  >
311
  New automation
312
  </button>
 
16
  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_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";
90
  }
91
 
92
+ /*
93
+ * β›” W23-W5's LISTENER IS AT MODULE SCOPE, AND THAT IS THE POINT β€” not a stylistic choice.
94
+ *
95
+ * The frame's click-through sets `window.location.hash = "#/automation"` and signals on the
96
+ * VERY NEXT LINE (Shell.tsx:1647-1650, and its comment is right that the order matters). But a
97
+ * hash write does not mount anything synchronously: `hashchange` is delivered as a task, the
98
+ * router state then updates, React renders, and only THEN does a component effect subscribe.
99
+ * A listener registered in `useEffect` therefore misses every click that arrives from another
100
+ * page β€” which is every click, since a reader looking at Alerts is by definition not already
101
+ * on this surface. The event would dispatch into nothing and every gate would stay green:
102
+ * exactly the wave-20 item-25 failure the contract's own note describes, reproduced one layer
103
+ * down.
104
+ *
105
+ * This module is imported statically by the shell, so this listener exists from app start. It
106
+ * LATCHES the request; the component consumes the latch when it mounts and hears live events
107
+ * while it is mounted. A request nobody claims is dropped on the next one β€” the latch is a
108
+ * one-slot mailbox, never a queue.
109
+ */
110
+ let pendingOpen: AutomationOpenDetail | null = null;
111
+ const openSubscribers = new Set<(detail: AutomationOpenDetail) => void>();
112
+
113
+ if (typeof window !== "undefined") {
114
+ window.addEventListener(AUTOMATION_OPEN_EVENT, (event) => {
115
+ const detail = (event as CustomEvent<AutomationOpenDetail>).detail;
116
+ if (!detail?.autoId) return;
117
+ if (openSubscribers.size) {
118
+ for (const notify of openSubscribers) notify(detail);
119
+ return;
120
+ }
121
+ pendingOpen = detail;
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
+ /**
199
+ * β›” C14 LEG 2 β€” THE ID THE USER LAST ASKED FOR, and it is a ref because it has to be
200
+ * written SYNCHRONOUSLY, inside the click, before any promise that was already in flight
201
+ * can resolve. State would not do: a resolution racing React's commit would read the
202
+ * previous value, which is the exact window this guard exists to close.
203
+ */
204
+ const wantedId = useRef("");
205
+
206
+ /**
207
+ * ⭐ THE ONLY PLACE THE RAIL'S SELECTION MOVES ON PURPOSE. Every deliberate change of
208
+ * automation β€” a rail click, a create, a delete β€” goes through here, so "what the user
209
+ * asked for" and "what is on screen" are written in one statement and cannot drift apart.
210
+ * A resolution that wants to steer the rail compares itself against `wantedId` instead.
211
+ */
212
+ const select = useCallback((id: string, stage = "") => {
213
+ wantedId.current = id;
214
+ setActiveId(id);
215
+ // The stage hint belongs to THIS selection and no other. Every ordinary caller passes
216
+ // nothing, which clears it β€” so a review notification cannot leave a stage open on the
217
+ // next automation the reader clicks by hand.
218
+ setOpenStage(stage);
219
+ }, []);
220
+
221
+ /**
222
+ * β›” C14 LEG 3 (the paint half) β€” A STALE READ MAY NOT REPAINT.
223
+ *
224
+ * Every call takes the next generation; only the newest one is allowed to `setData`. The
225
+ * defect this closes is not cosmetic: a poll issued BEFORE a delete resolves AFTER it, and
226
+ * a list that still contains the deleted automation puts a row back in the rail that the
227
+ * user has just watched disappear. Same for a toggle, and same for a create.
228
+ *
229
+ * ⚠ THE RETURN VALUE IS NOT GUARDED, deliberately. The caller asked a question and gets
230
+ * its own answer β€” coupling the two would mean a create whose `load()` was overtaken by a
231
+ * poll silently failed to select the automation it had just made.
232
+ */
233
+ const gen = useRef(0);
234
+
235
  const load = useCallback(async (abort?: AbortSignal) => {
236
+ const mine = ++gen.current;
237
  try {
238
  const next = await listAutomations(abort);
239
+ if (mine === gen.current) {
240
+ setData(next);
241
+ setError("");
242
+ }
243
  return next;
244
  } catch (e) {
245
  if ((e as Error)?.name === "AbortError") return null;
246
+ if (mine === gen.current)
247
+ setError(
248
+ e instanceof AutomationError
249
+ ? e.message
250
+ : "The automation service did not answer."
251
+ );
252
  return null;
253
  }
254
  }, []);
 
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
304
  // whose contents change a handful of times a day.
305
+ //
306
+ // β›” C14 LEG 3 (the abort half). It used to call `load()` bare β€” no signal, nothing to
307
+ // cancel β€” so a request the interval had already issued kept going after the effect that
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(() => {
367
+ const notify = (detail: AutomationOpenDetail) => setOpenRequest(detail);
368
+ openSubscribers.add(notify);
369
+ if (pendingOpen) {
370
+ const latched = pendingOpen;
371
+ pendingOpen = null;
372
+ setOpenRequest(latched);
373
+ }
374
+ return () => {
375
+ openSubscribers.delete(notify);
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
410
+ * list" would drop every real click and keep only the one case where the reader was already
411
+ * here. So the request is held until `data` exists, and only then answered.
412
+ *
413
+ * An automation the reader can no longer open does NOTHING (the contract's own words): the
414
+ * request is cleared either way, so a stale id cannot sit here re-firing against every
415
+ * subsequent list.
416
+ */
417
  useEffect(() => {
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);
424
+ }, [openRequest, data, select]);
425
 
426
  const items = data?.automations || [];
427
  const active = items.find((a) => a.id === activeId) || 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}
 
586
  // trigger face can tell "the server offered nothing" from "the server offered
587
  // an empty list" rather than collapsing both into a picker with no options.
588
  triggers={data?.triggers}
589
+ // C4's action menu + the builder's ceilings. Forwarded as-is for the same reason
590
+ // `triggers` is: absent must stay absent, so the builder can tell "the server
591
+ // offered nothing" from "the server offered an empty list".
592
+ catalog={data?.actionsCatalog}
593
+ vocab={data?.flow}
594
  // `?? null` and never `|| {enabled:false}`: an absent tick bit is "the server did
595
  // not say", which Step 1 prints as its own sentence. Defaulting it here would
596
  // turn a missing field into a claim about production (C6 amendment #1).
597
  tick={data?.tick ?? null}
598
+ // W23-W5's advisory half. A review notification names the stage its cards are
599
+ // waiting at, and landing on the automation with that stage's panel already open
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
+ *
616
+ * The detail calls `onSaved(automation.id)` from six places (save, the trigger
617
+ * picker, a schedule change, a node switch, a card move, a run). Each closure
618
+ * captures the automation it was mounted for, so a save that resolves AFTER the
619
+ * user has clicked a different row used to call `setActiveId(the OLD id)` β€” the
620
+ * rail jumped back, the detail remounted, and what the user saw was the previous
621
+ * automation reappearing over the one they had just opened. It looked like a
622
+ * rendering bug; it was a resolution steering the selection.
623
+ *
624
+ * A resolution may no longer steer anything. It reloads the list β€” that part was
625
+ * always right β€” and it re-asserts the selection ONLY when its id is still the one
626
+ * the user asked for, which makes the write a no-op in the good case and nothing
627
+ * at all in the bad one.
628
+ */
629
  onSaved={async (id) => {
630
  const next = await load();
631
+ if (id && next && id === wantedId.current) select(id);
632
  }}
633
  onDeleted={async () => {
634
+ select("");
635
  await load();
636
  }}
637
  />
 
653
  * paragraph, spent differently.
654
  */
655
  <div className="autob-empty">
656
+ {/*
657
+ β›” NO TITLE HERE ANY MORE (C13, owner item 2). This pane carried an `h1`
658
+ reading "Automations" at 20px/600 β€” a THIRD title treatment on a page that
659
+ also had the header's editable 16px/700 input, against every database page's
660
+ single 16px/650 `shell-db-name`. The shell now wraps this branch in the same
661
+ `shell-db-frame` + `DbHead` a database gets (wiring W23-W1), so the page's name
662
+ is drawn once, by the one component that draws every other page's name. A
663
+ stand-in restyled to match would have been a second copy of the same fact,
664
+ free to drift the day the header moves.
665
+ */}
666
  <p className="autob-empty-line">
667
  A job this workspace runs for you, on demand or on a schedule.
668
  </p>
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
@@ -24,7 +24,6 @@
24
  // nothing and gets asked again.
25
  // ---------------------------------------------------------------------------
26
  import type { OAuthStatus, TickState, TriggerOption } from "./automationApi";
27
- import { oauthProviderFor, oauthStartUrlFor } from "./automationApi";
28
  import { WEEKDAYS, readCron, writeCron } from "./steps";
29
 
30
  interface Props {
@@ -54,20 +53,36 @@ interface Props {
54
  /** True when the raw cron face is open β€” a VIEW choice, not a schedule change. */
55
  showCron: boolean;
56
  onShowCron: (v: boolean) => void;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  }
58
 
59
- /**
60
- * ⚠ THE FALLBACK, AND IT IS TEMPORARY BY CONSTRUCTION. Until `triggers` rides,
61
- * these are the only two shapes the stored definition can express β€” the engine
62
- * has exactly one trigger node and `schedule.enabled` decides it β€” so this is a
63
- * description of what the server can do today, not a second vocabulary. It is
64
- * NEVER consulted once the list arrives; when C3 lands, deleting this constant
65
- * changes nothing on screen.
 
 
 
66
  */
67
- const FALLBACK_TRIGGERS: TriggerOption[] = [
68
- { key: "manual", label: "Manual only", ready: true },
69
- { key: "schedule", label: "On a schedule", ready: true },
70
- ];
71
 
72
  /** The one-line next step a not-ready trigger carries. Server words where there are any. */
73
  function needsLabel(needs: string): string {
@@ -77,6 +92,16 @@ function needsLabel(needs: string): string {
77
  return needs.replace(/_/g, " ");
78
  }
79
 
 
 
 
 
 
 
 
 
 
 
80
  /**
81
  * What the deployment will actually do with a schedule.
82
  *
@@ -128,20 +153,41 @@ export default function AutomationTrigger({
128
  oauth,
129
  showCron,
130
  onShowCron,
 
 
131
  }: Props) {
132
- const options = triggers && triggers.length ? triggers : FALLBACK_TRIGGERS;
 
 
133
  const picked = options.find((t) => t.key === current) || null;
134
- const isSchedule = current === "schedule";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  const shape = readCron(cron);
136
  const note = tickNote(tick);
137
  const every = showCron ? "custom" : shape.every;
138
- // The connector this trigger is waiting on, resolved from the SERVER's `needs`
139
- // token. Empty provider = we cannot name a route for it, which is a state the
140
- // block below states in words instead of drawing a button that goes nowhere.
141
- const waiting = !!picked && picked.ready === false && !!picked.needs;
142
- const provider = waiting ? oauthProviderFor(picked.needs as string) : "";
143
  const connected = !!(provider && oauth?.[provider]?.connected);
144
- const startUrl = waiting ? oauthStartUrlFor(picked.needs as string) : "";
145
 
146
  const pickEvery = (next: string) => {
147
  onShowCron(next === "custom");
@@ -152,6 +198,10 @@ export default function AutomationTrigger({
152
  return (
153
  <>
154
  <div className="auto-field-row">
 
 
 
 
155
  <div className="auto-field">
156
  <label htmlFor="auto-trigger-kind">When it runs</label>
157
  <select
@@ -171,14 +221,40 @@ export default function AutomationTrigger({
171
  <option value={current}>{current} (not offered here)</option>
172
  ) : null}
173
  {options.map((t) => (
174
- <option key={t.key} value={t.key}>
175
- {/* Not-ready is stated ON the option rather than by disabling it: the
176
- option is pickable, and picking it shows what it is waiting for. */}
177
- {t.ready === false ? `${t.label} β€” needs setting up` : t.label}
 
 
 
 
 
 
 
178
  </option>
179
  ))}
180
  </select>
181
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
 
183
  {isSchedule ? (
184
  <>
@@ -269,6 +345,16 @@ export default function AutomationTrigger({
269
  ) : null}
270
  </div>
271
 
 
 
 
 
 
 
 
 
 
 
272
  {/* NOT CONFIGURED IS A STATE WITH A NEXT STEP, never a dead control (C3). */}
273
  {waiting ? (
274
  <div className="autob-needs">
 
24
  // nothing and gets asked again.
25
  // ---------------------------------------------------------------------------
26
  import type { OAuthStatus, TickState, TriggerOption } from "./automationApi";
 
27
  import { WEEKDAYS, readCron, writeCron } from "./steps";
28
 
29
  interface Props {
 
53
  /** True when the raw cron face is open β€” a VIEW choice, not a schedule change. */
54
  showCron: boolean;
55
  onShowCron: (v: boolean) => void;
56
+ /**
57
+ * WAVE 23 β€” the BUILDER supplies its own "Trigger type" select (Properties β†’ Trigger details),
58
+ * so this face drops its picker and contributes only the schedule half. It is a prop rather
59
+ * than a second component because the thing worth having exactly once is what sits BELOW the
60
+ * picker: the cron round-trip, the preset list and the tick-honesty note, three things that go
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
+ /*
76
+ * β›” `FALLBACK_TRIGGERS` IS GONE (D-43, wave 23). It described the only two shapes a stored
77
+ * definition could express before C3 shipped (manual / on a schedule), and its own note set
78
+ * the deletion condition: "NEVER consulted once the list arrives; when C3 lands, deleting this
79
+ * constant changes nothing on screen." C3 has been live for two releases and the vocabulary is
80
+ * now nine keys plus two planned, so the fallback could only ever have been WRONG β€” a server
81
+ * hiccup would have painted a two-option picker that looks authoritative.
82
+ *
83
+ * The absent case is a STATE now, not a substitute list: no `triggers` means the surface says
84
+ * so in one line (below) rather than quietly offering a vocabulary of its own.
85
  */
 
 
 
 
86
 
87
  /** The one-line next step a not-ready trigger carries. Server words where there are any. */
88
  function needsLabel(needs: string): string {
 
92
  return needs.replace(/_/g, " ");
93
  }
94
 
95
+ /**
96
+ * What an option says about itself. THREE states, and they are not the same fact:
97
+ * ready (nothing), waiting on a connection the USER can make ("needs setting up"), and
98
+ * declared-but-not-built ("coming soon", R2) which is waiting on us.
99
+ */
100
+ function optionLabel(t: TriggerOption): string {
101
+ if (t.planned) return `${t.label} β€” coming soon`;
102
+ return t.ready === false ? `${t.label} β€” needs setting up` : t.label;
103
+ }
104
+
105
  /**
106
  * What the deployment will actually do with a schedule.
107
  *
 
153
  oauth,
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;
184
+ // The connector this trigger is waiting on, and the route to it, BOTH COMPOSED BY THE
185
+ // SERVER (`TriggerOption.connect`). No `connect` = we cannot name a route, which is a state
186
+ // the block below states in words instead of drawing a button that goes nowhere.
187
+ const waiting = !!picked && picked.ready === false && !picked.planned && !!picked.needs;
188
+ const provider = picked?.connect?.provider || "";
189
  const connected = !!(provider && oauth?.[provider]?.connected);
190
+ const startUrl = picked?.connect?.startUrl || "";
191
 
192
  const pickEvery = (next: string) => {
193
  onShowCron(next === "custom");
 
198
  return (
199
  <>
200
  <div className="auto-field-row">
201
+ {/* ⚠ CONDITIONALLY RENDERED, never `hidden` β€” `.auto-field` sets `display: flex`, which
202
+ beats the `hidden` attribute's UA `display: none`, so the attribute would have left
203
+ a second trigger picker on screen looking exactly as if it had been asked for. */}
204
+ {hidePicker ? null : (
205
  <div className="auto-field">
206
  <label htmlFor="auto-trigger-kind">When it runs</label>
207
  <select
 
221
  <option value={current}>{current} (not offered here)</option>
222
  ) : null}
223
  {options.map((t) => (
224
+ /*
225
+ Not-ready is stated ON the option rather than by disabling it: the option is
226
+ pickable, and picking it shows what it is waiting for.
227
+ ⚠ PLANNED IS THE ONE EXCEPTION, and it is not the same fact (R2). The server
228
+ REFUSES a planned key at the door, so leaving it pickable would offer a
229
+ control whose only possible outcome is a refusal. It still renders β€” the
230
+ question "can it run when a button is clicked" has an answer β€” it just is not
231
+ an offer.
232
+ */
233
+ <option key={t.key} value={t.key} disabled={!!t.planned}>
234
+ {optionLabel(t)}
235
  </option>
236
  ))}
237
  </select>
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
  <>
 
345
  ) : null}
346
  </div>
347
 
348
+ {/*
349
+ THE ABSENT LIST, SAID OUT LOUD (D-43). With the fallback deleted there is no
350
+ client-side vocabulary left to fall back TO, and that is the point: a picker that
351
+ quietly offers two options because a payload was short is a surface stating something
352
+ nobody measured. One line, no paragraph (R13).
353
+ */}
354
+ {!options.length && !hidePicker ? (
355
+ <p className="auto-note">This server did not offer a trigger list.</p>
356
+ ) : null}
357
+
358
  {/* NOT CONFIGURED IS A STATE WITH A NEXT STEP, never a dead control (C3). */}
359
  {waiting ? (
360
  <div className="autob-needs">
web/src/automation/CondBuilder.tsx ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // automation/CondBuilder.tsx β€” the condition TREE editor (contract C4).
3
+ //
4
+ // ONE editor, three callers: the trigger's "when a record matches conditions"
5
+ // (image 4), a conditional group's "Run actions in this group if…" (image 9),
6
+ // and a Find records step. They are the same shape (`Cond`) evaluated by the
7
+ // same engine function, so a second implementation would be a second set of
8
+ // bugs β€” and the one that matters is silent: a tree the editor can BUILD but
9
+ // the server refuses reads to the user as "it just doesn't save".
10
+ //
11
+ // β›” THE VOCABULARY IS THE SERVER'S. The operators are `flow.condOps`, the
12
+ // value-free ones are `flow.nullaryCondOps`, and the depth/breadth ceilings are
13
+ // `flow.maxCondDepth`/`maxCondChildren` β€” all off `GET /automations`. This file
14
+ // holds NO list of operators. It holds a WORDING for the ones it recognises and
15
+ // falls through to the raw key for anything it does not, which is visible and
16
+ // therefore reportable; a `switch` with no arm for a new op would render the row
17
+ // as nothing at all (the wave-9 silent-drop class).
18
+ //
19
+ // β›” IT NEVER PREDICTS A REFUSAL. `clean_cond` refuses an empty group, an
20
+ // unknown op, a valueless compare and an over-deep tree, each with a sentence.
21
+ // This editor SAYS a condition is incomplete β€” the red line Airtable shows β€” and
22
+ // still lets the save happen, so the authority on legality stays in one place.
23
+ // A client that blocked Save on its own arithmetic can block a tree the server
24
+ // would have taken, and the user cannot tell which of the two is wrong
25
+ // (`DiscoverGuard`'s note in automationApi states the same rule for the corpus
26
+ // filter, and it is the same rule).
27
+ // ---------------------------------------------------------------------------
28
+ import type { Cond } from "./automationApi";
29
+ import { groupParts, isCondGroup } from "./automationApi";
30
+
31
+ interface Field {
32
+ key: string;
33
+ label: string;
34
+ type?: string;
35
+ }
36
+
37
+ interface Props {
38
+ /** The stored tree. `null` = no conditions yet, which is a legal state, not an empty one. */
39
+ cond: Cond | null;
40
+ onChange: (next: Cond | null) => void;
41
+ fields: Field[];
42
+ /** `flow.condOps` β€” the comparisons the engine can answer. */
43
+ ops: string[];
44
+ /** `flow.nullaryCondOps` β€” the ones that take no value. */
45
+ nullaryOps: string[];
46
+ maxDepth: number;
47
+ maxChildren: number;
48
+ /** Prefix on the first row. Airtable says "When" at a trigger and nothing inside a group. */
49
+ lead?: string;
50
+ disabled?: boolean;
51
+ }
52
+
53
+ /**
54
+ * The WORDING of an operator, never the LIST of them.
55
+ *
56
+ * ⚠ The keys are the engine's `LANE_OPS` and the fallback is the key itself: an operator this
57
+ * table has not heard of renders as `>=` rather than as a blank cell. Ugly beats invisible β€”
58
+ * a blank is indistinguishable from a bug and nobody reports the row they cannot see.
59
+ * (Booked in the B mailbox as a small ask: `condOpLabels` on the wire would delete this map.)
60
+ */
61
+ const OP_WORDS: Record<string, string> = {
62
+ "=": "is",
63
+ "!=": "is not",
64
+ ">": "is greater than",
65
+ ">=": "is at least",
66
+ "<": "is less than",
67
+ "<=": "is at most",
68
+ includes: "contains",
69
+ not_includes: "does not contain",
70
+ is_empty: "is empty",
71
+ is_not_empty: "is not empty",
72
+ };
73
+
74
+ export function opWord(op: string): string {
75
+ return OP_WORDS[op] || op;
76
+ }
77
+
78
+ /** A fresh leaf, using the FIRST operator the server offered rather than a hard-coded "=". */
79
+ function newLeaf(ops: string[]): Cond {
80
+ return { field: "", op: ops[0] || "", value: "" };
81
+ }
82
+
83
+ /**
84
+ * ⭐ ONE CHILD IS STORED AS A BARE LEAF, not as a group of one.
85
+ *
86
+ * Both are legal (`cond_match` dispatches on shape), and the engine's own note says a stored
87
+ * leaf is never rewritten at rest. Emitting the leaf keeps a one-condition trigger byte-identical
88
+ * to what wave 22 wrote, so opening an old automation in this editor and saving it unchanged
89
+ * does not produce a diff β€” a save that silently reshapes stored data is how "I only looked at
90
+ * it" turns into a migration nobody reviewed.
91
+ */
92
+ function pack(join: "all" | "any", children: Cond[]): Cond | null {
93
+ if (!children.length) return null;
94
+ if (children.length === 1 && !isCondGroup(children[0])) return children[0];
95
+ return join === "all" ? { all: children } : { any: children };
96
+ }
97
+
98
+ /** Is every leaf in this tree answerable? Drives the red line, never the Save button. */
99
+ export function condComplete(cond: Cond | null | undefined, nullaryOps: string[]): boolean {
100
+ if (!cond) return true;
101
+ if (isCondGroup(cond)) {
102
+ const { children } = groupParts(cond);
103
+ return children.length > 0 && children.every((c) => condComplete(c, nullaryOps));
104
+ }
105
+ const leaf = cond as { field: string; op: string; value?: string | number };
106
+ if (!leaf.field || !leaf.op) return false;
107
+ if (nullaryOps.includes(leaf.op)) return true;
108
+ return leaf.value !== undefined && String(leaf.value).trim() !== "";
109
+ }
110
+
111
+ export default function CondBuilder({
112
+ cond,
113
+ onChange,
114
+ fields,
115
+ ops,
116
+ nullaryOps,
117
+ maxDepth,
118
+ maxChildren,
119
+ lead = "When",
120
+ disabled,
121
+ }: Props) {
122
+ // The editor always works on a GROUP even when one leaf is stored β€” a list of one is still a
123
+ // list, and `pack` puts it back the way it was found.
124
+ const { join, children } = isCondGroup(cond)
125
+ ? groupParts(cond)
126
+ : { join: "all" as const, children: cond ? [cond] : [] };
127
+
128
+ const emit = (nextJoin: "all" | "any", next: Cond[]) => onChange(pack(nextJoin, next));
129
+ const replace = (i: number, next: Cond) =>
130
+ emit(join, children.map((c, j) => (j === i ? next : c)));
131
+
132
+ return (
133
+ <div className="autoc-tree">
134
+ {children.map((child, i) => (
135
+ /*
136
+ ⚠ THE KEY CARRIES THE ROW COUNT, and that is what makes the uncontrolled value input
137
+ above safe. Keyed by index alone, removing row 0 would REUSE row 0's DOM node for what
138
+ used to be row 1 β€” and an uncontrolled input keeps its own DOM value, so the reader
139
+ would be looking at the deleted row's text under the surviving row's field. Changing
140
+ the count remounts the whole list, which discards every stale DOM value at exactly the
141
+ moment the structure changes.
142
+ */
143
+ <div className="autoc-row" key={`${children.length}:${i}`}>
144
+ <button
145
+ type="button"
146
+ className="autoc-drop"
147
+ disabled={disabled}
148
+ aria-label="Remove this condition"
149
+ title="Remove this condition"
150
+ onClick={() => emit(join, children.filter((_c, j) => j !== i))}
151
+ >
152
+ <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
153
+ <path
154
+ d="M4 4l8 8M12 4l-8 8"
155
+ stroke="currentColor"
156
+ strokeWidth="1.5"
157
+ strokeLinecap="round"
158
+ />
159
+ </svg>
160
+ </button>
161
+
162
+ {/*
163
+ THE JOIN IS THE GROUP'S, AND IT IS EDITED IN EXACTLY ONE PLACE. Row 2 carries the
164
+ dropdown; every later row prints the word it chose. Giving each row its own
165
+ and/or select would offer a mixed tree the shape cannot express β€” `{all: […]}` has
166
+ one join β€” and the user would discover that only when their third row silently
167
+ behaved like the second's.
168
+ */}
169
+ <span className="autoc-join">
170
+ {i === 0 ? (
171
+ lead
172
+ ) : i === 1 ? (
173
+ <select
174
+ className="auto-input is-tiny"
175
+ value={join}
176
+ disabled={disabled}
177
+ aria-label="Match all or any of these conditions"
178
+ onChange={(e) => emit(e.target.value === "any" ? "any" : "all", children)}
179
+ >
180
+ <option value="all">and</option>
181
+ <option value="any">or</option>
182
+ </select>
183
+ ) : (
184
+ <span className="autoc-join-word">{join === "all" ? "and" : "or"}</span>
185
+ )}
186
+ </span>
187
+
188
+ {isCondGroup(child) ? (
189
+ <div className="autoc-nest">
190
+ <CondBuilder
191
+ cond={child}
192
+ onChange={(next) =>
193
+ next
194
+ ? replace(i, next)
195
+ : emit(join, children.filter((_c, j) => j !== i))
196
+ }
197
+ fields={fields}
198
+ ops={ops}
199
+ nullaryOps={nullaryOps}
200
+ maxDepth={maxDepth - 1}
201
+ maxChildren={maxChildren}
202
+ lead=""
203
+ {...(disabled ? { disabled: true } : {})}
204
+ />
205
+ </div>
206
+ ) : (
207
+ <Leaf
208
+ leaf={child as { field: string; op: string; value?: string | number }}
209
+ fields={fields}
210
+ ops={ops}
211
+ nullaryOps={nullaryOps}
212
+ {...(disabled ? { disabled: true } : {})}
213
+ onChange={(next) => replace(i, next)}
214
+ />
215
+ )}
216
+ </div>
217
+ ))}
218
+
219
+ <div className="autoc-adds">
220
+ <button
221
+ type="button"
222
+ className="autoc-add"
223
+ disabled={disabled || children.length >= maxChildren}
224
+ title={
225
+ children.length >= maxChildren
226
+ ? `This group holds at most ${maxChildren} conditions.`
227
+ : undefined
228
+ }
229
+ onClick={() => emit(join, [...children, newLeaf(ops)])}
230
+ >
231
+ + Add condition
232
+ </button>
233
+ {/* Nesting is offered only while the SERVER's depth allows it β€” the ceiling rides the
234
+ payload, so this control disappears at the same depth `clean_cond` refuses. */}
235
+ {maxDepth > 1 ? (
236
+ <button
237
+ type="button"
238
+ className="autoc-add"
239
+ disabled={disabled || children.length >= maxChildren}
240
+ onClick={() => emit(join, [...children, { all: [newLeaf(ops)] }])}
241
+ >
242
+ + Add condition group
243
+ </button>
244
+ ) : null}
245
+ </div>
246
+
247
+ {/* THE RED LINE (image 4). A statement about the tree, not a wall in front of Save. */}
248
+ {!condComplete(pack(join, children), nullaryOps) ? (
249
+ <p className="autoc-bad">A condition is incomplete or invalid.</p>
250
+ ) : null}
251
+ </div>
252
+ );
253
+ }
254
+
255
+ function Leaf({
256
+ leaf,
257
+ fields,
258
+ ops,
259
+ nullaryOps,
260
+ disabled,
261
+ onChange,
262
+ }: {
263
+ leaf: { field: string; op: string; value?: string | number };
264
+ fields: Field[];
265
+ ops: string[];
266
+ nullaryOps: string[];
267
+ disabled?: boolean;
268
+ onChange: (next: Cond) => void;
269
+ }) {
270
+ const nullary = nullaryOps.includes(leaf.op);
271
+ return (
272
+ <>
273
+ <select
274
+ className="auto-input is-tiny"
275
+ value={leaf.field}
276
+ disabled={disabled}
277
+ aria-label="Field"
278
+ onChange={(e) => onChange({ ...leaf, field: e.target.value })}
279
+ >
280
+ <option value="">Choose a field…</option>
281
+ {/*
282
+ ⚠ THE STORED VALUE IS ALWAYS AN OPTION. A <select> whose `value` matches no <option>
283
+ renders the FIRST one, so a condition on a column this list has not caught up with
284
+ would LOOK like a condition on a different column β€” and the next Save would write that
285
+ different column without anybody choosing it. This repo has paid for that twice
286
+ ([[cg-condition-builder-items]]).
287
+ */}
288
+ {leaf.field && !fields.some((f) => f.key === leaf.field) ? (
289
+ <option value={leaf.field}>{leaf.field} (not in this database)</option>
290
+ ) : null}
291
+ {fields.map((f) => (
292
+ <option key={f.key} value={f.key}>
293
+ {f.label}
294
+ </option>
295
+ ))}
296
+ </select>
297
+
298
+ <select
299
+ className="auto-input is-tiny"
300
+ value={leaf.op}
301
+ disabled={disabled}
302
+ aria-label="Comparison"
303
+ onChange={(e) => {
304
+ const op = e.target.value;
305
+ // Moving to a value-free comparison DROPS the value rather than keeping it out of
306
+ // sight: a stored `value` under `is_empty` is a fact the sentence does not show and
307
+ // the next operator change would silently resurrect.
308
+ onChange(nullaryOps.includes(op) ? { field: leaf.field, op } : { ...leaf, op });
309
+ }}
310
+ >
311
+ {leaf.op && !ops.includes(leaf.op) ? (
312
+ <option value={leaf.op}>{opWord(leaf.op)} (not offered here)</option>
313
+ ) : null}
314
+ {ops.map((op) => (
315
+ <option key={op} value={op}>
316
+ {opWord(op)}
317
+ </option>
318
+ ))}
319
+ </select>
320
+
321
+ {nullary ? null : (
322
+ /*
323
+ β›” FREE TEXT COMMITS ON BLUR, like every other free-text field in this builder β€” and
324
+ the controlled version this replaced was worse than merely chatty. `onChange` reached
325
+ `patchTrigger` β†’ PATCH, so typing "New" fired THREE requests; the displayed value
326
+ could not advance until each round-trip landed; and `disabled={busy}` disabled the
327
+ input under the typist's fingers. The two selects beside it stay controlled because
328
+ each is ONE discrete decision, which is exactly the distinction the cron field made
329
+ (AutomationTrigger's note) and the reason this input is not one.
330
+ */
331
+ <input
332
+ className="auto-input is-tiny autoc-value"
333
+ defaultValue={leaf.value === undefined ? "" : String(leaf.value)}
334
+ disabled={disabled}
335
+ aria-label="Value"
336
+ placeholder="Value"
337
+ onBlur={(e) => {
338
+ if (e.target.value !== String(leaf.value ?? "")) onChange({ ...leaf, value: e.target.value });
339
+ }}
340
+ />
341
+ )}
342
+ </>
343
+ );
344
+ }
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.
@@ -100,7 +113,31 @@ export interface Automation {
100
  * definition can express are `schedule.enabled` true/false, and the picker
101
  * derives those rather than inventing a third answer.
102
  */
103
- trigger?: { key: string; ready?: boolean; needs?: string };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  /**
105
  * The review gate's decisions, newest first (<=100). A promotion is a person's
106
  * judgement written into a record, so it says WHO β€” the same reason every count in
@@ -158,6 +195,13 @@ export interface AutomationList {
158
  * controls that already exist rather than rendering an empty dropdown.
159
  */
160
  triggers?: TriggerOption[];
 
 
 
 
 
 
 
161
  storeAvailable: boolean;
162
  }
163
 
@@ -173,6 +217,166 @@ export interface TriggerOption {
173
  ready: boolean;
174
  /** What it is waiting for, e.g. `"connect_gmail"`. Rendered as a next step, never as an error. */
175
  needs?: string;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  }
177
 
178
  export interface OAuthConnection {
@@ -190,28 +394,19 @@ export interface OAuthConnection {
190
  */
191
  export type OAuthStatus = Record<string, OAuthConnection | undefined>;
192
 
193
- /**
194
- * A trigger's `needs` token β†’ the connector it is waiting on.
195
  *
196
- * ⚠ THE ONE PLACE A SERVER TOKEN BECOMES A ROUTE, and it is deliberately tiny and
197
- * deliberately FAIL-QUIET-BUT-VISIBLE: an unknown token resolves to "", the connect
198
- * BUTTON is not drawn, and the not-configured state is still stated in words. A
199
- * button that navigates nowhere is worse than no button β€” it reads as a broken
200
- * product rather than an unfinished one.
 
201
  *
202
- * DEBT: this table disappears the day a `TriggerOption` carries its own provider or
203
- * start URL. Booked in the wave-22 mailbox as a question for the engine session.
204
  */
205
- const CONNECT_PROVIDERS: Record<string, string> = { connect_gmail: "google" };
206
-
207
- export function oauthProviderFor(needs: string): string {
208
- return CONNECT_PROVIDERS[String(needs || "")] || "";
209
- }
210
-
211
- export function oauthStartUrlFor(needs: string): string {
212
- const provider = oauthProviderFor(needs);
213
- return provider ? `${API_V1}/oauth/${provider}/start` : "";
214
- }
215
 
216
  export interface TickState {
217
  enabled: boolean;
@@ -222,7 +417,9 @@ export interface TickState {
222
  export interface SourceStatus {
223
  key: string;
224
  label: string;
225
- vendor: string;
 
 
226
  ready: boolean;
227
  canDiscover: boolean;
228
  }
@@ -257,12 +454,49 @@ export interface DiscoverVocab {
257
  guard?: DiscoverGuard;
258
  }
259
 
 
 
 
 
 
 
 
 
 
 
 
260
  export interface DiscoverFieldMeta {
261
  name: string;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
  /** Seen carrying values on real corpus rows. */
263
  populated: boolean;
264
  /** A condition on this field actually cuts the corpus down. */
265
  narrowing: boolean;
 
 
 
 
 
 
 
 
 
 
266
  }
267
 
268
  /**
@@ -290,7 +524,11 @@ export interface DiscoverGuard {
290
  export interface Predicate {
291
  name: string;
292
  operator: string;
293
- value?: string | number;
 
 
 
 
294
  }
295
 
296
  /**
@@ -311,7 +549,20 @@ export interface UserTable {
311
  label: string;
312
  source: string;
313
  rowCount: number;
314
- fields: { key: string; label: string; type: string; automation?: unknown }[];
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  }
316
 
317
  export interface SourcePreview {
@@ -422,6 +673,16 @@ export interface BoardCard {
422
  /** The SERVER's answer to "may this move", not a permission the client derives. */
423
  canAdvance: boolean;
424
  next: string[];
 
 
 
 
 
 
 
 
 
 
425
  }
426
 
427
  export interface Board {
@@ -444,13 +705,25 @@ export interface Board {
444
  truncated?: string[];
445
  }
446
 
447
- /** One human decision at a review gate β€” R7's approval posture, audited (A2(5)). */
 
 
 
 
 
 
448
  export interface ReviewEntry {
449
  ts: string;
450
  user: string;
451
  rowId: string;
452
  from: string;
453
  to: string;
 
 
 
 
 
 
454
  }
455
 
456
  export class AutomationError extends Error {
@@ -620,6 +893,30 @@ export function stateOf(a: Automation): RunState {
620
  return a.running ? "running" : (a.status?.state as RunState) || "idle";
621
  }
622
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623
  /**
624
  * A run's counts as ordered label/value pairs. The ORDER is the sentence the
625
  * numbers make β€” new, updated, unchanged, then the ones that need explaining β€”
@@ -648,7 +945,7 @@ export const COUNT_LABELS: [string, string][] = [
648
  ["partial", "Profile only"],
649
  ["blocked", "Blocked"],
650
  ["error", "Errors"],
651
- ["paid", "Exact via Bright Data"],
652
  ["posts", "Posts"],
653
  ["new_posts", "New posts"],
654
  // The engagement series only grows while the per-post rung is on, so its
 
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.
 
113
  * definition can express are `schedule.enabled` true/false, and the picker
114
  * derives those rather than inventing a third answer.
115
  */
116
+ trigger?: {
117
+ key: string;
118
+ ready?: boolean;
119
+ needs?: string;
120
+ /** ⚠ STORED INERT, NOT REFUSED (A3): the picker writes `{key}` first and the table/field
121
+ * after, so an unfinished trigger is a STATE the builder finishes β€” never a snap-back to
122
+ * Manual. It cannot fire while incomplete, which is the fail-closed direction. */
123
+ configured?: boolean;
124
+ paused?: boolean;
125
+ enabled?: boolean;
126
+ table?: string;
127
+ field?: string;
128
+ fields?: string[];
129
+ viewId?: string;
130
+ query?: string;
131
+ token?: string;
132
+ formToken?: string;
133
+ when?: Cond | null;
134
+ };
135
+ /**
136
+ * WAVE 23 / C4 β€” the ACTIONS this automation runs, and how it ends (C5). Defaulted
137
+ * server-side to `{actions: [], ending: {mode: "terminal"}}`, so an automation written before
138
+ * this wave reads as "no actions, stops at the end" rather than as a missing key.
139
+ */
140
+ flow?: Flow;
141
  /**
142
  * The review gate's decisions, newest first (<=100). A promotion is a person's
143
  * judgement written into a record, so it says WHO β€” the same reason every count in
 
195
  * controls that already exist rather than rendering an empty dropdown.
196
  */
197
  triggers?: TriggerOption[];
198
+ /**
199
+ * WAVE 23 / C4 β€” the action menu and the builder's ceilings. OPTIONAL for the reason every
200
+ * other server vocabulary here is: absent is a third state (a server older than this client),
201
+ * and the builder prints what it has rather than inventing a menu.
202
+ */
203
+ actionsCatalog?: ActionCatalogRow[];
204
+ flow?: FlowVocab;
205
  storeAvailable: boolean;
206
  }
207
 
 
217
  ready: boolean;
218
  /** What it is waiting for, e.g. `"connect_gmail"`. Rendered as a next step, never as an error. */
219
  needs?: string;
220
+ /**
221
+ * WAVE 23 / R2 β€” DECLARED BUT NOT BUILT (`button_clicked`, `comment_added`). Distinct from
222
+ * `ready:false`, and the difference is what the user can DO about it: a not-ready trigger is
223
+ * waiting on a connection THEY can make, a planned one is waiting on us. Both render; only
224
+ * the first offers an action. The server refuses a planned key at the door
225
+ * (`clean_trigger`), so the faded state is enforced rather than merely displayed.
226
+ */
227
+ planned?: boolean;
228
+ /**
229
+ * ⭐ THE CONNECT AFFORDANCE, SERVER-COMPOSED (A3(3), wave 23). This replaced a client table
230
+ * that mapped a `needs` token to a provider and hand-built the start URL β€” two facts the
231
+ * OAuth registry already owns, kept in a second place that could disagree with it. `null`
232
+ * (or absent) means there is no route to offer, which the trigger face states in words
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 ───────────────────────────
257
+ //
258
+ // β›” EVERY VOCABULARY BELOW IS `string`, for the reason C1 and C3 already give: a client union
259
+ // over a server enumeration is a list that can go stale, and it goes stale SILENTLY. The engine
260
+ // ships `flow.condOps`, `flow.endingModes`, `flow.reviewDeciders` and `actionsCatalog` on
261
+ // `GET /automations`; the builder renders whatever rides and never a list of its own.
262
+
263
+ /**
264
+ * ONE condition, as a TREE (C4). A leaf is wave 22's lane condition unchanged β€” which is why
265
+ * nothing migrated: a stored leaf IS a valid tree, and the engine dispatches on shape.
266
+ * Depth and breadth are the SERVER's numbers (`flow.maxCondDepth` / `maxCondChildren`), read
267
+ * from the payload rather than repeated here.
268
+ */
269
+ export type Cond =
270
+ | { field: string; op: string; value?: string | number }
271
+ | { all: Cond[] }
272
+ | { any: Cond[] };
273
+
274
+ export function isCondGroup(c: Cond | null | undefined): c is { all: Cond[] } | { any: Cond[] } {
275
+ return !!c && (Array.isArray((c as { all?: Cond[] }).all)
276
+ || Array.isArray((c as { any?: Cond[] }).any));
277
+ }
278
+
279
+ /** A group's join word and its children, without the caller re-testing both keys every time. */
280
+ export function groupParts(c: Cond): { join: "all" | "any"; children: Cond[] } {
281
+ const all = (c as { all?: Cond[] }).all;
282
+ return Array.isArray(all) ? { join: "all", children: all }
283
+ : { join: "any", children: (c as { any: Cond[] }).any || [] };
284
+ }
285
+
286
+ /**
287
+ * One step of a flow (C4). `config` is per-kind and deliberately loose here β€” the engine
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
+
328
+ /** `flow.ending` (C5) β€” what happens to a record that reaches the end. */
329
+ export interface FlowEnding {
330
+ mode: string;
331
+ hours?: number;
332
+ }
333
+
334
+ export interface Flow {
335
+ actions: Action[];
336
+ ending: FlowEnding;
337
+ }
338
+
339
+ /**
340
+ * A row of the ACTION MENU (image 7/8's grouped list). `group` is the section heading and
341
+ * `ready:false` paints the card faded WITH the server's own reason β€” the owner asked for the
342
+ * full menu, and a shorter one would imply the missing actions do not exist. `clean_actions`
343
+ * refuses an unready kind, so faded is a wall rather than a styling choice.
344
+ */
345
+ export interface ActionCatalogRow {
346
+ kind: string;
347
+ label: string;
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. */
363
+ export interface FlowVocab {
364
+ condOps: string[];
365
+ nullaryCondOps: string[];
366
+ maxCondDepth: number;
367
+ maxCondChildren: number;
368
+ maxGroupDepth: number;
369
+ maxActions: number;
370
+ endingModes: string[];
371
+ maxResetHours: number;
372
+ reviewDeciders: string[];
373
+ /**
374
+ * ⚠ PER-DEPLOYMENT, AND HONEST RATHER THAN DECORATIVE. With no LLM key configured the engine
375
+ * holds every card for a human β€” so an enabled-looking "decided by AI" control would promise
376
+ * a decision nothing will make. False renders it as not-configured (C6's fail-closed path,
377
+ * made visible).
378
+ */
379
+ aiReady: boolean;
380
  }
381
 
382
  export interface OAuthConnection {
 
394
  */
395
  export type OAuthStatus = Record<string, OAuthConnection | undefined>;
396
 
397
+ /*
398
+ * β›” `CONNECT_PROVIDERS` / `oauthProviderFor` / `oauthStartUrlFor` ARE GONE (D-43, wave 23).
399
  *
400
+ * They were a client table mapping a server `needs` token ("connect_gmail") to a provider
401
+ * ("google") and composing `/oauth/google/start` by hand β€” a second copy of the OAuth
402
+ * registry, booked as debt on the day it shipped with the resolution written into it: "this
403
+ * table disappears the day a `TriggerOption` carries its own provider or start URL." It does
404
+ * now (`TriggerOption.connect`, composed by `routes_automation._triggers_vocab`), so the copy
405
+ * is deleted rather than left to drift the first time a second provider lands.
406
  *
407
+ * The FAIL-QUIET-BUT-VISIBLE behaviour it was built for is unchanged and now belongs to the
408
+ * server: no `connect` means no button, and the not-configured state is still said in words.
409
  */
 
 
 
 
 
 
 
 
 
 
410
 
411
  export interface TickState {
412
  enabled: boolean;
 
417
  export interface SourceStatus {
418
  key: string;
419
  label: string;
420
+ /** β›” NOT SENT any more β€” the supplier is an implementation detail. Optional so an
421
+ * older server's payload still types, never so a surface can print it. */
422
+ vendor?: string;
423
  ready: boolean;
424
  canDiscover: boolean;
425
  }
 
454
  guard?: DiscoverGuard;
455
  }
456
 
457
+ export interface DiscoverOperator {
458
+ /** The token the vendor accepts. Never rendered. */
459
+ value: string;
460
+ /** Plain English β€” "contains", "at least", "has any of". */
461
+ label: string;
462
+ /** Takes no value at all ("is empty"). */
463
+ nullary: boolean;
464
+ /** May carry several values, which the server expands into an OR. */
465
+ multi: boolean;
466
+ }
467
+
468
  export interface DiscoverFieldMeta {
469
  name: string;
470
+ /** What a person reads β€” "Bio", not `biography`. Server-owned; refusals use the same word. */
471
+ label?: string;
472
+ /** One line for the rows nobody can guess (`fbid`). Absent on the self-evident ones. */
473
+ hint?: string;
474
+ /** text | choice | number | boolean | tags β€” decides the value control. */
475
+ kind?: string;
476
+ /**
477
+ * The comparisons THIS field may be asked, in offer order.
478
+ *
479
+ * β›” Optional only because an older server does not send it β€” and when it is missing the row
480
+ * offers nothing rather than falling back to the global list. Every operator on every field is
481
+ * what produced `is_business_account >= 3`.
482
+ */
483
+ operators?: DiscoverOperator[];
484
+ /** Fixed choices for the value (Yes/No on a boolean). Empty = free text. */
485
+ options?: { value: string; label: string }[];
486
  /** Seen carrying values on real corpus rows. */
487
  populated: boolean;
488
  /** A condition on this field actually cuts the corpus down. */
489
  narrowing: boolean;
490
+ /**
491
+ * The comparison a NEW condition on this field starts with β€” SERVER-OWNED, and optional only
492
+ * because an older server does not send it.
493
+ *
494
+ * β›” Do not replace an absent one with a client default. That is the whole defect this field
495
+ * exists to fix: the client used to pick `is_not_null` for every field, which the server's
496
+ * narrowing guard refuses on every field, so a filter stayed unsaveable no matter what the
497
+ * user toggled on.
498
+ */
499
+ defaultOperator?: string;
500
  }
501
 
502
  /**
 
524
  export interface Predicate {
525
  name: string;
526
  operator: string;
527
+ /**
528
+ * One value, or SEVERAL β€” several is "Bio contains any of floral, flower, beauty", which the
529
+ * server expands into a nested OR so it still composes with the other conditions.
530
+ */
531
+ value?: string | number | (string | number)[];
532
  }
533
 
534
  /**
 
549
  label: string;
550
  source: string;
551
  rowCount: number;
552
+ /**
553
+ * `automation` is the machine-owner TAG (W23/R9's grey columns) β€” the id of the automation
554
+ * that owns the column, or `null`. Narrowed from `unknown` in wave 24 against the route that
555
+ * composes it: `routes_automation.py:291` sends `f.get("automation") or None`, so `string`
556
+ * and `null` are the only two values that ride.
557
+ */
558
+ fields: { key: string; label: string; type: string; automation?: string | null }[];
559
+ /**
560
+ * The table's saved views β€” what `enters_view` names (C3). ABSENT until the server sends it,
561
+ * and absent is a third state, not an empty list: the trigger's view control says the list was
562
+ * not offered rather than rendering an empty picker that looks like "this table has no views".
563
+ * (Asked of session A in the wave mailbox; the control reads this key the day it rides.)
564
+ */
565
+ views?: { id: string; label: string }[];
566
  }
567
 
568
  export interface SourcePreview {
 
673
  /** The SERVER's answer to "may this move", not a permission the client derives. */
674
  canAdvance: boolean;
675
  next: string[];
676
+ /**
677
+ * WAVE 23 / C5 β€” how many times this record has been round the flow. The count lives in the
678
+ * machine cell `stage_<autoId>_cycles` and the engine increments it on every reset.
679
+ *
680
+ * ⚠ NOT ON THE CARD WIRE YET (asked of session A in the wave mailbox). Absent means "not
681
+ * reported", NOT "once": the badge only draws from 2 upwards, so a missing key renders
682
+ * nothing at all rather than a claim that every record is on its first pass β€” which is
683
+ * exactly the measurement nobody made. It lights up the day the key rides.
684
+ */
685
+ cycles?: number;
686
  }
687
 
688
  export interface Board {
 
705
  truncated?: string[];
706
  }
707
 
708
+ /**
709
+ * One decision at a review gate β€” R7's approval posture, audited (A2(5)).
710
+ *
711
+ * ⭐ WAVE 23 / C6 (R4/R14): a decision may now be made by a MODEL, and the audit says so. One
712
+ * log, not two β€” a reader asking "who decided this" gets one answer whether it was a person or
713
+ * a provider, which is the only version that can be trusted at all.
714
+ */
715
  export interface ReviewEntry {
716
  ts: string;
717
  user: string;
718
  rowId: string;
719
  from: string;
720
  to: string;
721
+ /** `"user"` | `"ai"`. Absent on entries written before this wave β€” render as a person. */
722
+ by?: string;
723
+ /** The one-line reason. On an AI decision it is the model's own; never invented here. */
724
+ note?: string;
725
+ /** Which model decided. Present only on AI entries, and shown so the reason has provenance. */
726
+ model?: string;
727
  }
728
 
729
  export class AutomationError extends Error {
 
893
  return a.running ? "running" : (a.status?.state as RunState) || "idle";
894
  }
895
 
896
+ /**
897
+ * ⭐ WAVE 24 / C-TYPES + C-PERF (item 6) β€” WHAT THIS RUN IS DOING RIGHT NOW, or `""`.
898
+ *
899
+ * This is the honest half of "Run once now looks stuck": the engine has been publishing a live
900
+ * step text the whole time and **nothing has ever rendered it**, so a 120-second Bright Data
901
+ * wait and a hung thread look identical from the outside. They are not the same thing, and the
902
+ * server already knows which one it is.
903
+ *
904
+ * β›” WHY A FUNCTION AND NOT A FIELD β€” C-TYPES AMENDMENT A2 (2026-08-06, session D).
905
+ * The contract block writes `liveStep?: string` on `interface Automation`. Measured against the
906
+ * route that composes the payload: `_wire()` (`routes_automation.py:52-81`) emits `status` with
907
+ * `step` inside it (`:50-51`) and emits **no top-level `liveStep` at all**. Declaring the field
908
+ * would put a key on the `Automation` interface that no server sends β€” so `automation.liveStep`
909
+ * would compile, type-check, and be `undefined` forever. That is this codebase's own
910
+ * silent-drop class pointing the other way: the whole file is built on "absent must stay
911
+ * absent", and inventing a present-looking field is the same defect with the sign flipped.
912
+ * `step` is ALREADY typed on `status` (see `Automation.status`), so nothing is lost β€” this
913
+ * function is the greppable name the contract wanted, reading the key that actually rides.
914
+ * The W24-W1 hand-off is unaffected: it is a PROP called `liveStep`, and this is what fills it.
915
+ */
916
+ export function liveStepOf(a: Automation): string {
917
+ return stateOf(a) === "running" ? String(a.status?.step || "") : "";
918
+ }
919
+
920
  /**
921
  * A run's counts as ordered label/value pairs. The ORDER is the sentence the
922
  * numbers make β€” new, updated, unchanged, then the ones that need explaining β€”
 
945
  ["partial", "Profile only"],
946
  ["blocked", "Blocked"],
947
  ["error", "Errors"],
948
+ ["paid", "Exact counts"],
949
  ["posts", "Posts"],
950
  ["new_posts", "New posts"],
951
  // The engagement series only grows while the per-post rung is on, so its
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/connectors/ConnectorsPage.tsx ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // connectors/ConnectorsPage.tsx β€” WAVE 23 item 10 (ruling R8, contract C11).
3
+ //
4
+ // The Claude-style directory: a search box and a card grid, laid out from
5
+ // `reference/Claude Connectors.png` and painted in OUR tokens. Every card is a
6
+ // row of `GET /api/v1/connectors/directory` (SESSION A's route) β€” this page
7
+ // invents nothing, which is what lets `#/connectors` be a CHROME route without
8
+ // touching the shell's "an undeclared surface is denied" law (nav.ts'
9
+ // `CHROME_ROUTES` note carries the full argument).
10
+ //
11
+ // β›” NO THIRD-PARTY LOGOS AND NO EMOJIS (R8 + DESIGN.md Β§4). A connector's mark is
12
+ // a two-letter tile in the chip family every database already wears, so the
13
+ // directory reads as part of this product rather than as a wall of other
14
+ // companies' branding β€” and nobody has to ship, license or update an icon set.
15
+ //
16
+ // ⚠ NO CLIENT UNION OVER `state` OR `kind`. They are the server's vocabulary and
17
+ // arrive as strings (the wave-9 law): a client `type State = "connected" | …`
18
+ // turns "the server added a state" into "the client drops the card".
19
+ // ---------------------------------------------------------------------------
20
+
21
+ import { useEffect, useState } from "react";
22
+ import { API_V1, CREDENTIALS } from "../apiContract";
23
+
24
+ /** One row of the directory. Everything optional but `key` + `label` is genuinely optional on
25
+ * the wire β€” a builtin has no provider, a planned connector has no `connectedAs`. */
26
+ export interface ConnectorRow {
27
+ key: string;
28
+ label: string;
29
+ desc: string;
30
+ /** `connected` | `available` | `planned` β€” read as a STRING, never a union. */
31
+ state: string;
32
+ /** `builtin` | `oauth` | `token`. */
33
+ kind: string;
34
+ provider?: string;
35
+ /** What is missing before it can connect β€” shown on the card, never invented here. */
36
+ needs?: string;
37
+ /** The account the connection is made as, when the server chooses to say. */
38
+ connectedAs?: string;
39
+ /**
40
+ * β›” A DESTINATION WORD, NOT A URL β€” `"keychain" | "oauth" | "automation" | ""`.
41
+ *
42
+ * This page was first written against C11's prose, which reads as though `manage` were a link,
43
+ * and it rendered `<a href={row.manage}>` β€” i.e. `href="keychain"`, a relative link to a page
44
+ * that does not exist, on every Odoo and token card. It compiled, it looked right, and it went
45
+ * nowhere. Corrected against the real payload (`routes_connectors.directory`): the server
46
+ * names WHERE the action lives and this page decides how to open it, which is the right split β€”
47
+ * the door for a keychain entry is a modal the shell owns and no URL could express it.
48
+ *
49
+ * Empty for a NON-ADMIN, deliberately (the route's own note): the card renders without an
50
+ * action rather than offering a door that would 403.
51
+ */
52
+ manage?: string;
53
+ /** OAuth only: the URL that starts the flow. This IS a link, and it is a different field. */
54
+ startUrl?: string;
55
+ /** A token connector's honest one-liner: the key is stored, the data arrives later (R13). */
56
+ note?: string;
57
+ /** What the admin will be asked for β€” shown where the decision is made, not in a tour. */
58
+ hint?: string;
59
+ }
60
+
61
+ type Load =
62
+ | { phase: "loading" }
63
+ | { phase: "ready"; rows: ConnectorRow[] }
64
+ | { phase: "error"; message: string };
65
+
66
+ const str = (v: unknown): string => (typeof v === "string" ? v : "");
67
+
68
+ export function parseDirectory(body: unknown): ConnectorRow[] {
69
+ const raw = (body as { connectors?: unknown } | null)?.connectors;
70
+ if (!Array.isArray(raw)) return [];
71
+ const out: ConnectorRow[] = [];
72
+ for (const item of raw) {
73
+ if (!item || typeof item !== "object") continue;
74
+ const c = item as Record<string, unknown>;
75
+ const key = str(c.key).trim();
76
+ const label = str(c.label).trim();
77
+ // A card with no name is a tile with no sign on it β€” dropped rather than rendered from its
78
+ // key, which would put an internal identifier on screen (`parsePages`' own rule).
79
+ if (!key || !label) continue;
80
+ out.push({
81
+ key,
82
+ label,
83
+ desc: str(c.desc),
84
+ state: str(c.state) || "available",
85
+ kind: str(c.kind),
86
+ ...(str(c.provider) ? { provider: str(c.provider) } : {}),
87
+ ...(str(c.needs) ? { needs: str(c.needs) } : {}),
88
+ ...(str(c.connectedAs) ? { connectedAs: str(c.connectedAs) } : {}),
89
+ ...(str(c.manage) ? { manage: str(c.manage) } : {}),
90
+ ...(str(c.startUrl) ? { startUrl: str(c.startUrl) } : {}),
91
+ ...(str(c.note) ? { note: str(c.note) } : {}),
92
+ ...(str(c.hint) ? { hint: str(c.hint) } : {}),
93
+ });
94
+ }
95
+ return out;
96
+ }
97
+
98
+ /** The card's mark: two letters from the connector's own name, in the database chip family.
99
+ * Unicode-aware for the same reason the account monogram is (`Shell.tsx:299`). */
100
+ export function tileText(label: string): string {
101
+ const chars = String(label ?? "").match(/[\p{L}\p{N}]/gu) ?? [];
102
+ return chars.slice(0, 2).join("").toUpperCase();
103
+ }
104
+
105
+ /** Search over the two things a person actually reads. Case-folded substring: this list is a
106
+ * couple of dozen rows, and a ranking function over a set you can see all of is noise. */
107
+ export function matches(row: ConnectorRow, query: string): boolean {
108
+ const q = query.trim().toLowerCase();
109
+ if (!q) return true;
110
+ return (
111
+ row.label.toLowerCase().includes(q) ||
112
+ row.desc.toLowerCase().includes(q) ||
113
+ row.key.toLowerCase().includes(q)
114
+ );
115
+ }
116
+
117
+ /**
118
+ * The chip's tone for a state.
119
+ *
120
+ * ⚠ FIVE STATES ARRIVE, NOT THREE. C11's prose names `connected | available | planned`; the real
121
+ * payload also sends `reconnect` (the token expired) and `unconfigured` (nobody registered the
122
+ * client on this deployment) β€” a distinction the route's own comment calls the point of the
123
+ * change. Read as strings and mapped here, so a SIXTH state renders in the neutral tone rather
124
+ * than dropping the card (the wave-9 law: no client union over a server vocabulary).
125
+ */
126
+ export function stateTone(state: string): string {
127
+ if (state === "connected") return " is-on";
128
+ if (state === "available" || state === "reconnect") return " is-open";
129
+ return ""; // planned, unconfigured, and anything new
130
+ }
131
+
132
+ export default function ConnectorsPage({
133
+ onKeychain,
134
+ }: {
135
+ /**
136
+ * `manage: "keychain"` β€” open Settings on the Keychains tab.
137
+ *
138
+ * β›” A CALLBACK, NOT A LINK, because the destination is a MODAL the shell owns and no URL can
139
+ * express it. REQUIRED rather than optional: an optional handler the frame forgot to pass
140
+ * degrades to "the Connect button does nothing", which is indistinguishable from a feature
141
+ * that was never built and goes red in no gate (this repo's most expensive lesson).
142
+ */
143
+ onKeychain: () => void;
144
+ }) {
145
+ const [load, setLoad] = useState<Load>({ phase: "loading" });
146
+ const [query, setQuery] = useState("");
147
+
148
+ useEffect(() => {
149
+ let dead = false;
150
+ void (async () => {
151
+ try {
152
+ const res = await fetch(`${API_V1}/connectors/directory`, {
153
+ credentials: CREDENTIALS,
154
+ });
155
+ const body = (await res.json().catch(() => null)) as
156
+ | { error?: { message?: string } }
157
+ | null;
158
+ if (dead) return;
159
+ if (!res.ok) {
160
+ setLoad({
161
+ phase: "error",
162
+ message: body?.error?.message || `The server answered ${res.status}.`,
163
+ });
164
+ return;
165
+ }
166
+ setLoad({ phase: "ready", rows: parseDirectory(body) });
167
+ } catch {
168
+ if (!dead) setLoad({ phase: "error", message: "Cannot reach the server." });
169
+ }
170
+ })();
171
+ return () => {
172
+ dead = true;
173
+ };
174
+ }, []);
175
+
176
+ const rows = load.phase === "ready" ? load.rows.filter((r) => matches(r, query)) : [];
177
+
178
+ return (
179
+ <div className="shell-conn">
180
+ <h1 className="conn-title">Connectors</h1>
181
+
182
+ <input
183
+ className="conn-search"
184
+ placeholder="Search connectors"
185
+ value={query}
186
+ maxLength={60}
187
+ onChange={(e) => setQuery(e.target.value)}
188
+ />
189
+
190
+ {load.phase === "loading" ? (
191
+ <div className="shell-loading">
192
+ <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading" />
193
+ </div>
194
+ ) : null}
195
+ {load.phase === "error" ? (
196
+ // Honest, and it names the retry. Never a hard-coded list of connectors as a fallback:
197
+ // that would put sources on screen this workspace may not have (the nav's own rule,
198
+ // applied to a second server-composed payload).
199
+ <p className="conn-note">{load.message}</p>
200
+ ) : null}
201
+ {load.phase === "ready" && rows.length === 0 ? (
202
+ <p className="conn-note">
203
+ {query ? "No connector matches that." : "No connectors are available yet."}
204
+ </p>
205
+ ) : null}
206
+
207
+ <div className="conn-grid">
208
+ {rows.map((row) => {
209
+ const planned = row.state === "planned";
210
+ const connected = row.state === "connected";
211
+ return (
212
+ <div
213
+ key={row.key}
214
+ className={"conn-card" + (planned ? " is-planned" : "")}
215
+ // β›” `aria-disabled`, NOT `inert`/`pointer-events` alone. A planned card is
216
+ // non-interactive by R8, and a card that merely LOOKS faded while still taking a
217
+ // click is the painted-but-unclickable failure in reverse
218
+ // ([[ui-invisible-to-assertions]]). It carries no controls at all, so there is
219
+ // nothing to disable β€” the attribute is what says so to a screen reader.
220
+ {...(planned ? { "aria-disabled": true } : {})}
221
+ >
222
+ <div className="conn-card-head">
223
+ <span className="shell-db-chip conn-tile" aria-hidden="true">
224
+ {tileText(row.label)}
225
+ </span>
226
+ <span className="conn-card-name">{row.label}</span>
227
+ <span className={"conn-state" + stateTone(row.state)}>
228
+ {/* The server's own word, sentence-cased by CSS never by `toUpperCase` β€” R6
229
+ bans caps in app chrome, and a chip is chrome. */}
230
+ {row.state}
231
+ </span>
232
+ </div>
233
+ <p className="conn-card-desc">{row.desc}</p>
234
+ {connected && row.connectedAs ? (
235
+ <p className="conn-card-meta">Connected as {row.connectedAs}</p>
236
+ ) : null}
237
+ {/* ⚠ `needs` IS SHOWN WHATEVER THE STATE, and that is a correction: gating it on
238
+ "not connected" hid the one line that explains an `unconfigured` row, which is
239
+ the state it exists for ("the owner registers the client"). Only `planned`
240
+ suppresses it, because "not built yet" beside a card already marked planned is
241
+ the same sentence twice. */}
242
+ {!planned && row.needs ? (
243
+ <p className="conn-card-meta">{row.needs}</p>
244
+ ) : null}
245
+ {/* R13's honesty line for a token connector: the key is stored, the data arrives
246
+ later. Shown ON the card where the decision is, never in a paragraph. */}
247
+ {!planned && row.note ? <p className="conn-card-meta">{row.note}</p> : null}
248
+ {/* ── the ACTION. `manage` names WHERE it lives; this decides how to open it.
249
+ Every door here already existed β€” an OAuth start URL, the keychain dialog,
250
+ the automation surface β€” which is exactly why this page can be chrome: it
251
+ mints no new credential path (C11). An empty `manage` (a non-admin) renders
252
+ NO control rather than one that would 403. */}
253
+ {!planned && row.manage === "oauth" && row.startUrl ? (
254
+ <a className="conn-card-go" href={row.startUrl}>
255
+ {row.state === "reconnect" ? "Reconnect" : "Connect"}
256
+ </a>
257
+ ) : null}
258
+ {!planned && row.manage === "keychain" ? (
259
+ <button type="button" className="conn-card-go" onClick={onKeychain}>
260
+ {connected ? "Manage keys" : "Add keys"}
261
+ </button>
262
+ ) : null}
263
+ {!planned && row.manage === "automation" ? (
264
+ <a className="conn-card-go" href="#/automation">
265
+ Open automations
266
+ </a>
267
+ ) : null}
268
+ </div>
269
+ );
270
+ })}
271
+ </div>
272
+ </div>
273
+ );
274
+ }
web/src/customer-grid/ColumnMenu.tsx CHANGED
@@ -3,8 +3,8 @@ import { AnchoredOverlay } from "./OverlaySurface";
3
  import type { AnchorRect } from "./OverlaySurface";
4
  import { FieldTypeIcon, MenuLabel } from "./icons";
5
  import { FieldSelectButton } from "./FieldSelect";
6
- import { CREATABLE_TYPES, choiceOptions, choiceRenames, directionLabel, parseOptions, ratingMax }
7
- from "./types";
8
  import type { Field, FieldFormat, FieldScope, FieldType, Measure, Viewer } from "./types";
9
  import type { WindowSpec } from "./windows";
10
  import { normalizeWindow, windowLabel } from "./windows";
@@ -1235,7 +1235,16 @@ export default function ColumnMenu({
1235
  // Item 8c β€” the period draft is valid when it normalizes and differs from what the field
1236
  // already has. Compared through normalizeWindow so `{kind:'ltm'}` and `{kind:'ltm', n:undefined}`
1237
  // read as the same window.
1238
- const typeLineBase = field.measure
 
 
 
 
 
 
 
 
 
1239
  ? "Metric, read-only"
1240
  : field.type === "formula"
1241
  ? "Formula field, computed"
 
3
  import type { AnchorRect } from "./OverlaySurface";
4
  import { FieldTypeIcon, MenuLabel } from "./icons";
5
  import { FieldSelectButton } from "./FieldSelect";
6
+ import { CREATABLE_TYPES, choiceOptions, choiceRenames, directionLabel, isMachineOwned,
7
+ parseOptions, ratingMax } from "./types";
8
  import type { Field, FieldFormat, FieldScope, FieldType, Measure, Viewer } from "./types";
9
  import type { WindowSpec } from "./windows";
10
  import { normalizeWindow, windowLabel } from "./windows";
 
1235
  // Item 8c β€” the period draft is valid when it normalizes and differs from what the field
1236
  // already has. Compared through normalizeWindow so `{kind:'ltm'}` and `{kind:'ltm', n:undefined}`
1237
  // read as the same window.
1238
+ // ⭐ Wave-23 C8 (owner item 4 / R9) β€” FIRST in the chain, because it is the most specific true
1239
+ // thing about the column and the branches below it were saying something false. An
1240
+ // `automation` or `metric` column, and every column an automation SPAWNED (the `automation`
1241
+ // tag), is overlay-sourced and non-derived, so it fell through to "Editable overlay field" β€”
1242
+ // which is what the wash now visibly contradicts. ONE line, no second sentence about what an
1243
+ // automation is (R13 / DESIGN.md Β§4): the person reading a column menu is deciding whether to
1244
+ // type in it, and "filled by automation" is the whole answer.
1245
+ const typeLineBase = isMachineOwned(field)
1246
+ ? "Filled by automation"
1247
+ : field.measure
1248
  ? "Metric, read-only"
1249
  : field.type === "formula"
1250
  ? "Formula field, computed"
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -33,6 +33,7 @@ import type { MeasureSets } from "./useVisibleRows";
33
  import { useGetCellContent } from "./useGetCellContent";
34
  import { useGridSelection } from "./useGridSelection";
35
  import Toolbar from "./Toolbar";
 
36
  import RecordDetail from "./RecordDetail";
37
  import ViewSidebar from "./ViewSidebar";
38
  import ColumnMenu from "./ColumnMenu";
@@ -537,6 +538,14 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
537
  setPicker(null);
538
  requestAnimationFrame(() => gridRef.current?.focus());
539
  }, []);
 
 
 
 
 
 
 
 
540
  /** WAVE 21 item 11 (R10) β€” is "Select records from a list" open? Opened from the view
541
  * rail's "…" and closed by the dialog; the SELECTION it produces outlives it. */
542
  const [selectFromFile, setSelectFromFile] = useState(false);
@@ -1910,6 +1919,18 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
1910
  });
1911
  return;
1912
  }
 
 
 
 
 
 
 
 
 
 
 
 
1913
  // Wave-5 item 11 β€” a URL cell opens its link on click (scheme-guarded: http/https only,
1914
  // a bare domain gets https://). Editing stays with glide's overlay (Enter/double-click).
1915
  if (row.kind === "data" && field?.type === "url") {
@@ -3640,6 +3661,17 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
3640
  onCalendarMetrics={setCalendarMetrics}
3641
  />
3642
  );
 
 
 
 
 
 
 
 
 
 
 
3643
  const pickerField = picker ? fieldByKey.get(picker.fieldKey) : undefined;
3644
  // A `user` field's choices come from the HOST's real user list, a `select`'s from its own
3645
  // definition β€” so an assignee is always someone who can log in, and a status is always one of
@@ -4691,6 +4723,21 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
4691
  </AnchoredOverlay>
4692
  )}
4693
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4694
  {pickerField && picker && (
4695
  <AnchoredOverlay
4696
  anchor={picker.anchor}
 
33
  import { useGetCellContent } from "./useGetCellContent";
34
  import { useGridSelection } from "./useGridSelection";
35
  import Toolbar from "./Toolbar";
36
+ import JsonViewer from "./JsonViewer";
37
  import RecordDetail from "./RecordDetail";
38
  import ViewSidebar from "./ViewSidebar";
39
  import ColumnMenu from "./ColumnMenu";
 
538
  setPicker(null);
539
  requestAnimationFrame(() => gridRef.current?.focus());
540
  }, []);
541
+ /** ⭐ Wave-23 C7 β€” which `json` cell the big viewer is open on. NOT anchored like the picker
542
+ * above: a document is not a choice list, so it opens as a centred modal (the record drawer's
543
+ * surface) rather than a popover the size of the cell it came from. */
544
+ const [jsonAt, setJsonAt] = useState<{ pid: number; fieldKey: string } | null>(null);
545
+ const closeJson = useCallback(() => {
546
+ setJsonAt(null);
547
+ requestAnimationFrame(() => gridRef.current?.focus());
548
+ }, []);
549
  /** WAVE 21 item 11 (R10) β€” is "Select records from a list" open? Opened from the view
550
  * rail's "…" and closed by the dialog; the SELECTION it produces outlives it. */
551
  const [selectFromFile, setSelectFromFile] = useState(false);
 
1919
  });
1920
  return;
1921
  }
1922
+ // ⭐ Wave-23 C7 β€” a JSON cell opens the big viewer. It is the ONLY door: the cell carries
1923
+ // `allowOverlay:false`, because glide's overlay is a one-line box and one keystroke in the
1924
+ // wrong place inside a 32 KB document turns a well-formed payload into an unparseable one,
1925
+ // saved. Opened for EVERY reader (a document you may not edit is still one you must be
1926
+ // able to read) β€” the viewer takes `onSave` only when the permission verdict allows it,
1927
+ // and the host's write wall is the real one either way.
1928
+ if (row.kind === "data" && field?.type === "json") {
1929
+ event.preventDefault();
1930
+ setActiveCell(cell[0], cell[1]);
1931
+ setJsonAt({ pid: row.record.pid, fieldKey: field.key });
1932
+ return;
1933
+ }
1934
  // Wave-5 item 11 β€” a URL cell opens its link on click (scheme-guarded: http/https only,
1935
  // a bare domain gets https://). Editing stays with glide's overlay (Enter/double-click).
1936
  if (row.kind === "data" && field?.type === "url") {
 
3661
  onCalendarMetrics={setCalendarMetrics}
3662
  />
3663
  );
3664
+ // ⭐ Wave-23 C7 β€” the open document, resolved exactly like the picker's value below it:
3665
+ // the OPTIMISTIC edit wins over the raw record, so a save the server has not echoed yet is
3666
+ // what re-opening the cell shows (the echo-suppression law β€” reading the raw row here would
3667
+ // make a just-saved document appear to revert).
3668
+ const jsonField = jsonAt ? fieldByKey.get(jsonAt.fieldKey) : undefined;
3669
+ const jsonRow = jsonAt ? rawRows.find((r) => r.pid === jsonAt.pid) : undefined;
3670
+ const jsonValue = String(
3671
+ (jsonAt && overlayEdits[jsonAt.pid]?.[jsonAt.fieldKey])
3672
+ ?? (jsonField && jsonRow ? jsonRow[jsonField.key] : "")
3673
+ ?? ""
3674
+ );
3675
  const pickerField = picker ? fieldByKey.get(picker.fieldKey) : undefined;
3676
  // A `user` field's choices come from the HOST's real user list, a `select`'s from its own
3677
  // definition β€” so an assignee is always someone who can log in, and a status is always one of
 
4723
  </AnchoredOverlay>
4724
  )}
4725
 
4726
+ {/* ⭐ Wave-23 C7 β€” the document viewer. `onSave` is OMITTED, not disabled, when the reader
4727
+ may not edit: an absent handler is what makes the raw tab a `<pre>` instead of a
4728
+ textarea, so there is no editor to be refused by. */}
4729
+ {jsonField && jsonAt && (
4730
+ <JsonViewer
4731
+ label={jsonField.label}
4732
+ value={jsonValue}
4733
+ onSave={
4734
+ canEditField(jsonField)
4735
+ ? (next) => patchAndRecord(jsonAt.pid, { [jsonField.key]: next }, "a document")
4736
+ : undefined
4737
+ }
4738
+ onClose={closeJson}
4739
+ />
4740
+ )}
4741
  {pickerField && picker && (
4742
  <AnchoredOverlay
4743
  anchor={picker.anchor}
web/src/customer-grid/JsonViewer.tsx ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / JsonViewer.tsx β€” ⭐ wave-23 C7 (owner item 5 / ruling R5).
3
+ //
4
+ // THE BIG VIEWER a json cell opens on click. One component, reached from two
5
+ // places (the grid cell's click path and the record drawer's value slot), for
6
+ // the reason `assetUrl` is one resolver: two readers of the same document that
7
+ // disagree about how it folds is a bug nobody can see in either one alone.
8
+ //
9
+ // The document is a STRING at rest (the scalar Row contract β€” see the `json`
10
+ // note in types.ts), so everything here is text in and text out. Nothing in
11
+ // this file ever writes a parsed OBJECT back.
12
+ //
13
+ // THREE decisions worth stating, because each has a plausible alternative:
14
+ //
15
+ // 1. THE RAW TAB IS THE EDITOR, and there is no field-by-field one. A form
16
+ // over a document whose shape nobody declared would have to invent that
17
+ // shape from the current value β€” so adding a key would mean editing the
18
+ // form's idea of the schema, and the first machine write with a different
19
+ // shape would silently drop what it did not recognise.
20
+ // 2. PARSE ON SAVE, REFUSE WITH A SENTENCE. Never repair, never re-indent on
21
+ // the way in: `{a:1}` is not JSON and quietly "fixing" it to `{"a":1}`
22
+ // teaches a person their typo was fine, until the day a value cannot be
23
+ // guessed. The host applies the same rule at the write wall (C7), so a
24
+ // refusal here says the same thing the server would.
25
+ // 3. THE TREE IS READ-ONLY and collapses by DEPTH, not by hand-kept state per
26
+ // node beyond what the reader opens. A 200-key payload that arrives fully
27
+ // expanded is a scroll bar, not a document.
28
+ // ---------------------------------------------------------------------------
29
+
30
+ import { useEffect, useId, useMemo, useRef, useState } from "react";
31
+ import type { ReactNode } from "react";
32
+ import { BodyPortal, useOverlayLayer } from "./OverlaySurface";
33
+ import { jsonParse, jsonPretty, MAX_JSON_BYTES } from "./display";
34
+
35
+ /** Bytes, not characters β€” the host's cap is on the stored UTF-8, and a
36
+ * document of 20,000 emoji is 80 KB. Counting `length` would let a value
37
+ * through here that the server then refuses, which is the one refusal a user
38
+ * cannot act on (nothing on screen said it was too big). */
39
+ export function jsonByteLength(text: string): number {
40
+ return typeof TextEncoder === "undefined"
41
+ ? text.length
42
+ : new TextEncoder().encode(text).length;
43
+ }
44
+
45
+ /** The one-line summary in the modal's header: what this document IS. */
46
+ export function jsonSummary(text: string): string {
47
+ const parsed = jsonParse(text);
48
+ const bytes = jsonByteLength(text);
49
+ const size = bytes < 1024 ? `${bytes} bytes` : `${(bytes / 1024).toFixed(1)} KB`;
50
+ if (String(text ?? "").trim() === "") return "Empty";
51
+ if (!parsed.ok) return `Not valid JSON Β· ${size}`;
52
+ const v = parsed.value;
53
+ if (Array.isArray(v)) return `${v.length} item${v.length === 1 ? "" : "s"} Β· ${size}`;
54
+ if (v !== null && typeof v === "object") {
55
+ const n = Object.keys(v as object).length;
56
+ return `${n} key${n === 1 ? "" : "s"} Β· ${size}`;
57
+ }
58
+ return `${v === null ? "null" : typeof v} Β· ${size}`;
59
+ }
60
+
61
+ // --- the tree ---------------------------------------------------------------
62
+
63
+ /** How deep a node is open when the viewer mounts. Two levels shows the shape
64
+ * of every payload this product actually receives (an object of objects) and
65
+ * stops before the leaf spam of a scraped array. */
66
+ const OPEN_TO_DEPTH = 2;
67
+
68
+ function isBranch(v: unknown): v is Record<string, unknown> | unknown[] {
69
+ return v !== null && typeof v === "object";
70
+ }
71
+
72
+ /** The value's own text, in its own ink class. Strings keep their quotes: a
73
+ * bare `12` and a `"12"` are different documents and the tree is where that
74
+ * difference has to be visible. */
75
+ function Leaf({ v }: { v: unknown }): ReactNode {
76
+ if (v === null) return <span className="cg-json-null">null</span>;
77
+ if (typeof v === "string") return <span className="cg-json-str">&quot;{v}&quot;</span>;
78
+ if (typeof v === "number") return <span className="cg-json-num">{String(v)}</span>;
79
+ if (typeof v === "boolean") return <span className="cg-json-bool">{String(v)}</span>;
80
+ return <span className="cg-json-str">{String(v)}</span>;
81
+ }
82
+
83
+ function Node({
84
+ name,
85
+ value,
86
+ depth,
87
+ last,
88
+ }: {
89
+ name: string | null;
90
+ value: unknown;
91
+ depth: number;
92
+ last: boolean;
93
+ }) {
94
+ const [open, setOpen] = useState(depth < OPEN_TO_DEPTH);
95
+ if (!isBranch(value))
96
+ return (
97
+ <div className="cg-json-row" style={{ paddingLeft: depth * 14 }}>
98
+ {name !== null && <span className="cg-json-key">{name}</span>}
99
+ {name !== null && <span className="cg-json-punct">: </span>}
100
+ <Leaf v={value} />
101
+ {!last && <span className="cg-json-punct">,</span>}
102
+ </div>
103
+ );
104
+
105
+ const array = Array.isArray(value);
106
+ const entries: [string, unknown][] = array
107
+ ? (value as unknown[]).map((v, i) => [String(i), v])
108
+ : Object.entries(value as Record<string, unknown>);
109
+ const openMark = array ? "[" : "{";
110
+ const closeMark = array ? "]" : "}";
111
+
112
+ return (
113
+ <>
114
+ <div className="cg-json-row" style={{ paddingLeft: depth * 14 }}>
115
+ <button
116
+ type="button"
117
+ className={"cg-json-twist" + (open ? " is-open" : "")}
118
+ onClick={() => setOpen((o) => !o)}
119
+ aria-expanded={open}
120
+ aria-label={`${open ? "Collapse" : "Expand"} ${name ?? "the document"}`}
121
+ >
122
+ <svg viewBox="0 0 16 16" width="10" height="10" aria-hidden>
123
+ <path
124
+ d="M6 4l4 4-4 4"
125
+ fill="none"
126
+ stroke="currentColor"
127
+ strokeWidth="1.6"
128
+ strokeLinecap="round"
129
+ strokeLinejoin="round"
130
+ />
131
+ </svg>
132
+ </button>
133
+ {name !== null && <span className="cg-json-key">{name}</span>}
134
+ {name !== null && <span className="cg-json-punct">: </span>}
135
+ <span className="cg-json-punct">{openMark}</span>
136
+ {/* Collapsed, the count IS the content β€” a bare `{…}` tells a reader
137
+ nothing about whether opening it is worth the click. */}
138
+ {!open && (
139
+ <span className="cg-json-count">
140
+ {entries.length} {array ? (entries.length === 1 ? "item" : "items")
141
+ : entries.length === 1 ? "key" : "keys"}
142
+ </span>
143
+ )}
144
+ {!open && <span className="cg-json-punct">{closeMark}{last ? "" : ","}</span>}
145
+ </div>
146
+ {open &&
147
+ entries.map(([k, v], i) => (
148
+ <Node
149
+ key={k}
150
+ name={array ? null : k}
151
+ value={v}
152
+ depth={depth + 1}
153
+ last={i === entries.length - 1}
154
+ />
155
+ ))}
156
+ {open && (
157
+ <div className="cg-json-row" style={{ paddingLeft: depth * 14 }}>
158
+ <span className="cg-json-punct">
159
+ {closeMark}
160
+ {last ? "" : ","}
161
+ </span>
162
+ </div>
163
+ )}
164
+ </>
165
+ );
166
+ }
167
+
168
+ // --- the modal --------------------------------------------------------------
169
+
170
+ export interface JsonViewerProps {
171
+ /** The column's own label β€” the modal's title. */
172
+ label: string;
173
+ /** The stored document, as a string. */
174
+ value: string;
175
+ /** Absent = read-only (the field is machine-owned, Odoo-sourced, or this
176
+ * viewer permits the reader nothing). Present = the raw tab is an editor. */
177
+ onSave?: (next: string) => void;
178
+ onClose: () => void;
179
+ }
180
+
181
+ export default function JsonViewer({ label, value, onSave, onClose }: JsonViewerProps) {
182
+ const panelRef = useRef<HTMLDivElement>(null);
183
+ const titleId = useId();
184
+ const tabsId = useId();
185
+ const [tab, setTab] = useState<"tree" | "raw">("tree");
186
+ const [draft, setDraft] = useState(value);
187
+ const [error, setError] = useState("");
188
+ const [copied, setCopied] = useState(false);
189
+
190
+ // ⚠ The draft re-seeds when the CELL changes underneath (a machine write
191
+ // landing while the viewer is open), and only then β€” keying on `value` alone
192
+ // would also stamp on every keystroke's re-render if a parent echoed it back.
193
+ useEffect(() => {
194
+ setDraft(value);
195
+ setError("");
196
+ }, [value]);
197
+
198
+ useOverlayLayer({
199
+ panelRef,
200
+ onDismiss: onClose,
201
+ dismissOnOutside: true,
202
+ initialFocus: "[data-overlay-autofocus]",
203
+ trapFocus: true,
204
+ });
205
+
206
+ const parsed = useMemo(() => jsonParse(draft), [draft]);
207
+ const dirty = draft !== value;
208
+
209
+ const save = () => {
210
+ const text = draft.trim();
211
+ // Blank is a legal edit: it clears the cell, which is how a document is
212
+ // removed. Everything else must parse before it is allowed to leave here.
213
+ if (text !== "") {
214
+ if (!jsonParse(text).ok) {
215
+ setError("That is not valid JSON β€” nothing was saved. Check for a trailing comma, a "
216
+ + "single quote, or an unquoted key.");
217
+ return;
218
+ }
219
+ const bytes = jsonByteLength(text);
220
+ if (bytes > MAX_JSON_BYTES) {
221
+ setError(`That document is ${(bytes / 1024).toFixed(1)} KB and the limit is 32 KB β€” `
222
+ + "nothing was saved.");
223
+ return;
224
+ }
225
+ }
226
+ setError("");
227
+ onSave?.(text);
228
+ onClose();
229
+ };
230
+
231
+ const copy = () => {
232
+ void navigator.clipboard?.writeText(draft).then(
233
+ () => {
234
+ setCopied(true);
235
+ window.setTimeout(() => setCopied(false), 1400);
236
+ },
237
+ () => setError("The browser refused clipboard access β€” select the raw text and copy it.")
238
+ );
239
+ };
240
+
241
+ return (
242
+ <BodyPortal>
243
+ <div className="cg-record-backdrop">
244
+ <div
245
+ className="cg-json-modal"
246
+ ref={panelRef}
247
+ role="dialog"
248
+ aria-modal="true"
249
+ aria-labelledby={titleId}
250
+ data-overlay-kind="json-viewer"
251
+ tabIndex={-1}
252
+ >
253
+ <div className="cg-json-head">
254
+ <div>
255
+ <div className="cg-json-title" id={titleId}>{label}</div>
256
+ {/* The summary is the ONE explanatory line (DESIGN.md Β§4): what
257
+ this document is, not what a JSON field is for. */}
258
+ <div className="cg-json-sub">{jsonSummary(draft)}</div>
259
+ </div>
260
+ <div className="cg-json-headacts">
261
+ <button type="button" className="cg-json-btn" onClick={copy}>
262
+ {copied ? "Copied" : "Copy"}
263
+ </button>
264
+ <button
265
+ type="button"
266
+ className="cg-icon-btn"
267
+ onClick={onClose}
268
+ aria-label="Close viewer"
269
+ >
270
+ Γ—
271
+ </button>
272
+ </div>
273
+ </div>
274
+
275
+ <div className="cg-record-tabs" role="tablist" aria-label="Document view">
276
+ {(["tree", "raw"] as const).map((k) => (
277
+ <button
278
+ key={k}
279
+ type="button"
280
+ role="tab"
281
+ id={`${tabsId}-${k}`}
282
+ aria-selected={tab === k}
283
+ aria-controls={`${tabsId}-panel`}
284
+ className={"cg-record-tab" + (tab === k ? " is-on" : "")}
285
+ onClick={() => setTab(k)}
286
+ data-overlay-autofocus={k === "tree" ? true : undefined}
287
+ >
288
+ {k === "tree" ? "Tree" : "Raw"}
289
+ </button>
290
+ ))}
291
+ </div>
292
+
293
+ <div
294
+ className="cg-json-body"
295
+ id={`${tabsId}-panel`}
296
+ role="tabpanel"
297
+ aria-labelledby={`${tabsId}-${tab}`}
298
+ >
299
+ {tab === "tree" ? (
300
+ parsed.ok ? (
301
+ <div className="cg-json-tree">
302
+ <Node name={null} value={parsed.value} depth={0} last />
303
+ </div>
304
+ ) : (
305
+ // β›” NOT an empty tree and NOT a repaired one. A document the app
306
+ // cannot open is a fact about the value, and the raw tab is where
307
+ // it gets read β€” so the empty state POINTS THERE rather than
308
+ // describing what JSON is.
309
+ <p className="cg-json-empty">
310
+ {draft.trim() === ""
311
+ ? "Nothing here yet."
312
+ : "This value is not valid JSON β€” read it on the Raw tab."}
313
+ </p>
314
+ )
315
+ ) : onSave ? (
316
+ <textarea
317
+ className="cg-json-raw"
318
+ value={draft}
319
+ spellCheck={false}
320
+ onChange={(e) => {
321
+ setDraft(e.target.value);
322
+ if (error) setError("");
323
+ }}
324
+ aria-label={`${label} raw JSON`}
325
+ />
326
+ ) : (
327
+ <pre className="cg-json-raw cg-json-raw--ro">{jsonPretty(draft)}</pre>
328
+ )}
329
+ </div>
330
+
331
+ {(error || (onSave && dirty)) && (
332
+ <div className="cg-json-foot">
333
+ {error ? (
334
+ <span className="cg-json-err">{error}</span>
335
+ ) : (
336
+ <span className="cg-json-hint">Unsaved changes</span>
337
+ )}
338
+ {onSave && (
339
+ <span className="cg-json-footacts">
340
+ <button
341
+ type="button"
342
+ className="cg-json-btn"
343
+ onClick={() => {
344
+ setDraft(value);
345
+ setError("");
346
+ }}
347
+ >
348
+ Revert
349
+ </button>
350
+ <button type="button" className="cg-json-btn cg-json-btn--primary" onClick={save}>
351
+ Save
352
+ </button>
353
+ </span>
354
+ )}
355
+ </div>
356
+ )}
357
+ </div>
358
+ </div>
359
+ </BodyPortal>
360
+ );
361
+ }
web/src/customer-grid/RecordDetail.css CHANGED
@@ -146,6 +146,25 @@
146
  line-height: 1.45;
147
  }
148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  /* A rating's marks are 18px inline SVG; on the text baseline they hang their
150
  descender space below the line box and grow the slot past every neighbour. */
151
  .cg-record-main .cg-detail-value .cg-stars {
@@ -451,6 +470,33 @@
451
  font-size: var(--lp-fs-2xs);
452
  }
453
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
454
  /* Rating: the stars ARE the picker. Clicking the lit star clears the value β€”
455
  without it a rating could be changed here but never removed. */
456
  .cg-record-main .cg-detail-stars {
 
146
  line-height: 1.45;
147
  }
148
 
149
+ /* ⭐ Wave-23 C8 (owner item 4 / ruling R9) β€” a MACHINE-OWNED field's value slot.
150
+
151
+ `--lp-machine-tint` is EXACTLY what the canvas wash (`theme.MACHINE_CELL`,
152
+ `washOf(LP_MACHINE_DEEP, 0.12)`) composites to over white, so the drawer slot
153
+ and the grid cell are one grey rather than two that were each picked to look
154
+ right on their own β€” the sibling-panel rule (DESIGN.md Β§2) applied across two
155
+ rendering technologies instead of two panes.
156
+
157
+ THE VALUE KEEPS ITS INK, deliberately, on both surfaces. The wash is the whole
158
+ signal; dimming the number as well would say the figure matters less, and an
159
+ automation-written follower count is the entire reason its column exists.
160
+
161
+ Background only β€” no border change, no second marker. The column menu already
162
+ says "Filled by automation" once, and DESIGN.md Β§4 is that the app does not
163
+ narrate itself twice. */
164
+ .cg-record-main .cg-detail-field.is-machine .cg-detail-value {
165
+ background: var(--lp-machine-tint);
166
+ }
167
+
168
  /* A rating's marks are 18px inline SVG; on the text baseline they hang their
169
  descender space below the line box and grow the slot past every neighbour. */
170
  .cg-record-main .cg-detail-value .cg-stars {
 
470
  font-size: var(--lp-fs-2xs);
471
  }
472
 
473
+ /* ⭐ Wave-23 C7 (owner item 5) β€” a `json` field's row: the same compact preview the grid cell
474
+ paints, plus the door to the viewer. Reuses `.cg-detail-imagebtn` rather than minting a
475
+ second quiet-button shape (DESIGN.md Β§4) β€” the two rows are doing the same job, showing a
476
+ value too big for a slot and offering the surface that owns it. */
477
+ .cg-record-main .cg-detail-jsonslot {
478
+ display: flex;
479
+ align-items: center;
480
+ justify-content: space-between;
481
+ gap: 10px;
482
+ }
483
+
484
+ /* ⚠ `min-width: 0` is what lets the ellipsis happen at all: a flex item's default
485
+ `min-width: auto` refuses to shrink below its content, so the preview would push the Open
486
+ button out of the panel instead of truncating. Monospace because the preview is a fragment
487
+ of a document β€” `{handle: "royalimports"}` reads as code, and setting it in Inter beside the
488
+ viewer's monospace tree would make one value look like two different things. */
489
+ .cg-record-main .cg-detail-jsonpreview {
490
+ flex: 1 1 auto;
491
+ min-width: 0;
492
+ overflow: hidden;
493
+ text-overflow: ellipsis;
494
+ white-space: nowrap;
495
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
496
+ font-size: var(--lp-fs-2xs);
497
+ color: var(--lp-ink);
498
+ }
499
+
500
  /* Rating: the stars ARE the picker. Clicking the lit star clears the value β€”
501
  without it a rating could be changed here but never removed. */
502
  .cg-record-main .cg-detail-stars {
web/src/customer-grid/RecordDetail.tsx CHANGED
@@ -7,9 +7,11 @@ import {
7
  automationStateLabel,
8
  checkboxOn,
9
  formatDisplay,
 
10
  } from "./cells";
 
11
  import { StarRow, StarIcon } from "./Stars";
12
- import { isPickType, mayEditField, ratingMax } from "./types";
13
  import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
14
  // Item 9 (wave 14) β€” the pure value round-trip. Everything that could silently
15
  // LOSE a stored value moving it into an editor and back lives there, gated by
@@ -269,6 +271,10 @@ export default function RecordDetail({
269
  // reachable second case.
270
  const [imageBusy, setImageBusy] = useState("");
271
  const [imageError, setImageError] = useState("");
 
 
 
 
272
  const overlayFields = fields.filter((field) => field.source === "overlay");
273
  // ⚠ These five buckets are the DEFAULT ORDER of the interleaved list (C-LAYOUT) and NOTHING
274
  // ELSE. They used to double as the editability split β€” picked/rating fields rendered
@@ -475,12 +481,24 @@ export default function RecordDetail({
475
  // somebody to type `rec:` by hand at a picture that does not exist. Its slot is a
476
  // thumbnail plus an upload control, so it joins the constrained-control family.
477
  field.type !== "image" &&
 
 
 
 
 
 
478
  field.type !== "pct";
479
  const isControl = editable && !isEdit;
480
  const cls =
481
  "cg-detail-field" +
482
  (isEdit ? " cg-detail-field--edit" : "") +
483
  (isControl ? " cg-detail-field--control" : "") +
 
 
 
 
 
 
484
  (dropKey === field.key ? " is-dropzone" : "") +
485
  (dragKey === field.key ? " is-dragging" : "");
486
 
@@ -802,6 +820,28 @@ export default function RecordDetail({
802
  <StarRow value={ratingValue(field, record[field.key])} max={ratingMax(field)} />
803
  </span>
804
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
805
  } else if (field.type === "automation") {
806
  // C5-AUTOFIELD (wave 18). It has to be its OWN branch and not the read-only fallback
807
  // below, because that branch explains read-only-ness as a PERMISSION ("You do not have
@@ -1042,6 +1082,25 @@ export default function RecordDetail({
1042
  </div>
1043
  </div>
1044
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1045
  </BodyPortal>
1046
  );
1047
  }
 
7
  automationStateLabel,
8
  checkboxOn,
9
  formatDisplay,
10
+ jsonPreview,
11
  } from "./cells";
12
+ import JsonViewer from "./JsonViewer";
13
  import { StarRow, StarIcon } from "./Stars";
14
+ import { isMachineOwned, isPickType, mayEditField, ratingMax } from "./types";
15
  import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
16
  // Item 9 (wave 14) β€” the pure value round-trip. Everything that could silently
17
  // LOSE a stored value moving it into an editor and back lives there, gated by
 
271
  // reachable second case.
272
  const [imageBusy, setImageBusy] = useState("");
273
  const [imageError, setImageError] = useState("");
274
+ /** ⭐ Wave-23 C7 β€” which json field's viewer is open, by KEY. One at a time for the same
275
+ * reason `imageBusy` is one pair: a record has a handful of document columns and only one
276
+ * modal can be on screen. */
277
+ const [jsonKey, setJsonKey] = useState<string | null>(null);
278
  const overlayFields = fields.filter((field) => field.source === "overlay");
279
  // ⚠ These five buckets are the DEFAULT ORDER of the interleaved list (C-LAYOUT) and NOTHING
280
  // ELSE. They used to double as the editability split β€” picked/rating fields rendered
 
481
  // somebody to type `rec:` by hand at a picture that does not exist. Its slot is a
482
  // thumbnail plus an upload control, so it joins the constrained-control family.
483
  field.type !== "image" &&
484
+ // ⭐ Wave-23 C7 β€” a `json` value is NEVER edited through a free textarea, here or in the
485
+ // grid. `AutoTextarea` commits on blur straight through `onNotesCommit`, so this branch
486
+ // would be a door that saves an unparseable document with no check at all β€” the exact
487
+ // thing the viewer's parse-on-save exists to prevent, sitting one panel away from it.
488
+ // It joins the constrained-control family: preview + "Open", and the viewer owns the edit.
489
+ field.type !== "json" &&
490
  field.type !== "pct";
491
  const isControl = editable && !isEdit;
492
  const cls =
493
  "cg-detail-field" +
494
  (isEdit ? " cg-detail-field--edit" : "") +
495
  (isControl ? " cg-detail-field--control" : "") +
496
+ // ⭐ Wave-23 C8 (R9) β€” the SAME claim the grid cell makes, on the DOM side. A machine-owned
497
+ // column is grey in the table; opening the record must not present the identical value in
498
+ // an ordinary editable-looking slot, because the drawer is where somebody would try to type
499
+ // in it. `RecordDetail.css` paints the pair (`--lp-machine-tint` background, the measured
500
+ // `--lp-machine-deep` ink) at the value slot, not the row, so the label keeps its rhythm.
501
+ (isMachineOwned(field) ? " is-machine" : "") +
502
  (dropKey === field.key ? " is-dropzone" : "") +
503
  (dragKey === field.key ? " is-dragging" : "");
504
 
 
820
  <StarRow value={ratingValue(field, record[field.key])} max={ratingMax(field)} />
821
  </span>
822
  );
823
+ } else if (field.type === "json") {
824
+ // ⭐ Wave-23 C7 β€” the drawer shows the same compact preview the grid cell does and hands
825
+ // the document to the SAME viewer, because two readers of one document that fold it
826
+ // differently is a disagreement nobody can see in either one alone. The button is the
827
+ // whole affordance: a `<pre>` of 32 KB inside a field row would push every column below
828
+ // it off the panel.
829
+ const raw = rawText(record[field.key]);
830
+ slot = (
831
+ <span className="cg-detail-value cg-detail-jsonslot">
832
+ <span className="cg-detail-jsonpreview">{jsonPreview(raw) || "β€”"}</span>
833
+ <button
834
+ type="button"
835
+ className="cg-detail-imagebtn"
836
+ onClick={() => setJsonKey(field.key)}
837
+ >
838
+ {/* "Open" for a reader, "Open" for an editor β€” the viewer decides what it offers
839
+ once it is open, and a button that says "Edit" to somebody who then cannot would
840
+ be the painted-but-inert control the standing rule is about. */}
841
+ Open
842
+ </button>
843
+ </span>
844
+ );
845
  } else if (field.type === "automation") {
846
  // C5-AUTOFIELD (wave 18). It has to be its OWN branch and not the read-only fallback
847
  // below, because that branch explains read-only-ness as a PERMISSION ("You do not have
 
1082
  </div>
1083
  </div>
1084
  </div>
1085
+ {/* ⭐ Wave-23 C7 β€” the document viewer, INSIDE this portal and therefore stacked above
1086
+ this modal. `useOverlayLayer`'s stack is what makes that work: it registers on top, so
1087
+ Escape closes the viewer and leaves the record open rather than dismissing both. */}
1088
+ {jsonKey && (() => {
1089
+ const field = fields.find((f) => f.key === jsonKey);
1090
+ if (!field) return null;
1091
+ return (
1092
+ <JsonViewer
1093
+ label={field.label}
1094
+ value={rawText(record[field.key])}
1095
+ onSave={
1096
+ mayEditField(field, viewer)
1097
+ ? (next) => onNotesCommit(field.key, next)
1098
+ : undefined
1099
+ }
1100
+ onClose={() => setJsonKey(null)}
1101
+ />
1102
+ );
1103
+ })()}
1104
  </BodyPortal>
1105
  );
1106
  }
web/src/customer-grid/cells.ts CHANGED
@@ -34,7 +34,7 @@ import type {
34
  } from "@glideapps/glide-data-grid";
35
  import { assetUrl } from "./catalogData";
36
  import type { Field } from "./types";
37
- import { ratingMax } from "./types";
38
  import {
39
  LP_BLUE_TEXT,
40
  LP_BLUE_TINT,
@@ -44,6 +44,7 @@ import {
44
  LP_RED_TINT,
45
  LP_YELLOW_DEEP,
46
  LP_YELLOW_TINT,
 
47
  STATUS_BUBBLE,
48
  } from "./theme";
49
  // ⚠ ALIASED: this module has its own `pickTint` (the bubble table above) and choiceColors has
@@ -51,7 +52,7 @@ import {
51
  // distinguishable at the call site rather than one silently shadowing the other.
52
  import { optionTint, pickTint as choicePickTint } from "./choiceColors";
53
  import { automationState, avatarInitials, avatarSize, checkboxOn, dateTimeText, formulaIsBlank,
54
- formulaIsText, num, numberText, userCellPayload } from "./display";
55
  import type { AutomationState, CellValue, UserCellData } from "./display";
56
 
57
  // Wave-7 (item W2): the pure display-string half moved to display.ts so the
@@ -66,6 +67,9 @@ export type { UserCellData } from "./display";
66
  // gate can hold it); only the canvas tint table below needs this module.
67
  export { automationDetail, automationState, automationStateLabel } from "./display";
68
  export type { AutomationState } from "./display";
 
 
 
69
 
70
  /**
71
  * Wave-18 C5-AUTOFIELD β€” the cell tint per automation state.
@@ -393,6 +397,37 @@ export function makeCell(
393
  /** C-AVATAR β€” username β†’ data URL, straight off `GridWorkspace.userAvatars`. Absent, or a
394
  * username absent from it, paints the initials fallback. */
395
  userAvatars?: Record<string, string>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
396
  ): GridCell {
397
  const ro = { allowOverlay: editable, readonly: !editable };
398
  const blank = v == null || v === "";
@@ -508,6 +543,33 @@ export function makeCell(
508
  allowOverlay: false,
509
  };
510
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511
  case "rating": {
512
  const max = ratingMax(field);
513
  const n = Math.max(0, Math.min(max, Math.round(num(v))));
 
34
  } from "@glideapps/glide-data-grid";
35
  import { assetUrl } from "./catalogData";
36
  import type { Field } from "./types";
37
+ import { isMachineOwned, ratingMax } from "./types";
38
  import {
39
  LP_BLUE_TEXT,
40
  LP_BLUE_TINT,
 
44
  LP_RED_TINT,
45
  LP_YELLOW_DEEP,
46
  LP_YELLOW_TINT,
47
+ machineCellTheme,
48
  STATUS_BUBBLE,
49
  } from "./theme";
50
  // ⚠ ALIASED: this module has its own `pickTint` (the bubble table above) and choiceColors has
 
52
  // distinguishable at the call site rather than one silently shadowing the other.
53
  import { optionTint, pickTint as choicePickTint } from "./choiceColors";
54
  import { automationState, avatarInitials, avatarSize, checkboxOn, dateTimeText, formulaIsBlank,
55
+ formulaIsText, jsonPreview, num, numberText, userCellPayload } from "./display";
56
  import type { AutomationState, CellValue, UserCellData } from "./display";
57
 
58
  // Wave-7 (item W2): the pure display-string half moved to display.ts so the
 
67
  // gate can hold it); only the canvas tint table below needs this module.
68
  export { automationDetail, automationState, automationStateLabel } from "./display";
69
  export type { AutomationState } from "./display";
70
+ // Wave-23 C7 β€” same arrangement again: the parse, the preview and the pretty-printer are pure
71
+ // (`verify_grid_ux` drives them under node); only the canvas cell below needs this module.
72
+ export { jsonParse, jsonPretty, jsonPreview, MAX_JSON_BYTES } from "./display";
73
 
74
  /**
75
  * Wave-18 C5-AUTOFIELD β€” the cell tint per automation state.
 
397
  /** C-AVATAR β€” username β†’ data URL, straight off `GridWorkspace.userAvatars`. Absent, or a
398
  * username absent from it, paints the initials fallback. */
399
  userAvatars?: Record<string, string>
400
+ ): GridCell {
401
+ const cell = baseCell(field, v, editable, userAvatars);
402
+ return isMachineOwned(field) ? withMachineWash(cell) : cell;
403
+ }
404
+
405
+ /**
406
+ * ⭐ Wave-23 C8 (owner item 4 / R9) β€” the grey wash on a MACHINE-OWNED cell.
407
+ *
408
+ * A per-CELL override rather than a per-column one (`useGridColumns.columnTheme`), following the
409
+ * `AUTOMATION_TINT` precedent directly below: the column path returns one of three SHARED
410
+ * `COLUMN_TONE_THEME` references, so forking it per column would both break that sharing and put
411
+ * the wash on the HEADER, which R9 does not ask for β€” an involved column's filter/sort/group tone
412
+ * keeps winning its header.
413
+ *
414
+ * The PRECEDENCE (state tint over wash, bubble tint alongside it) is `theme.machineCellTheme` β€”
415
+ * it lives there because this module imports glide and therefore cannot be driven by a gate,
416
+ * and precedence is the half of this that can be silently wrong. Same split as `display.ts`.
417
+ *
418
+ * ⚠ Re-built rather than mutated: glide declares every cell key `readonly`, and `baseCell`
419
+ * returns a fresh literal on every branch anyway. The `as GridCell` is the union-spread widening,
420
+ * not a claim about the shape β€” the object is byte-identical to the branch's own plus one key.
421
+ */
422
+ function withMachineWash(cell: GridCell): GridCell {
423
+ return { ...cell, themeOverride: machineCellTheme(cell.themeOverride) } as GridCell;
424
+ }
425
+
426
+ function baseCell(
427
+ field: Field,
428
+ v: CellValue,
429
+ editable: boolean,
430
+ userAvatars?: Record<string, string>
431
  ): GridCell {
432
  const ro = { allowOverlay: editable, readonly: !editable };
433
  const blank = v == null || v === "";
 
543
  allowOverlay: false,
544
  };
545
  }
546
+ case "json": {
547
+ // ⭐ Wave-23 C7 (owner item 5) β€” the compact preview; the DOCUMENT lives in the viewer.
548
+ //
549
+ // `allowOverlay: false` for the same reason `select` and `image` carry it: glide's text
550
+ // overlay is a one-line box, and a one-line box over a 32 KB document is an editor that
551
+ // can only damage the value β€” one keystroke in the wrong place and a well-formed payload
552
+ // becomes unparseable, saved. CustomerGrid opens the viewer on click instead (the same
553
+ // `onCellClicked` path the pickers use), and THAT is where the raw text is editable, with
554
+ // parse-on-save.
555
+ //
556
+ // ⚠ `readonly` is NOT set, and the difference matters: `allowOverlay:false` means "no
557
+ // inline editor", while `readonly` would tell glide the CELL cannot change β€” which would
558
+ // also block the paste path that legitimately writes a whole document into it.
559
+ //
560
+ // ⚠ `copyData` carries the RAW document, never the preview (the lesson the image cell
561
+ // booked in wave 19). Copy a json column and you get the payload; copy the preview and
562
+ // you get the sentence "{…} 5 keys", which is not data and cannot be pasted back.
563
+ const raw = String(v ?? "");
564
+ const text = jsonPreview(raw);
565
+ return {
566
+ kind: GridCellKind.Text,
567
+ data: text,
568
+ displayData: text,
569
+ copyData: raw,
570
+ allowOverlay: false,
571
+ };
572
+ }
573
  case "rating": {
574
  const max = ratingMax(field);
575
  const n = Math.max(0, Math.min(max, Math.round(num(v))));
web/src/customer-grid/display.ts CHANGED
@@ -228,6 +228,92 @@ export function automationStateLabel(v: CellValue): string {
228
  return s === "none" ? "Not run yet" : s[0].toUpperCase() + s.slice(1);
229
  }
230
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  export function formatDisplay(field: Field, v: CellValue): string {
232
  switch (field.type) {
233
  case "currency":
@@ -261,6 +347,12 @@ export function formatDisplay(field: Field, v: CellValue): string {
261
  const n = num(v);
262
  return n >= 1 ? `${Math.round(n)} of ${ratingMax(field)}` : "";
263
  }
 
 
 
 
 
 
264
  case "automation":
265
  // The machine-written line, verbatim. Explicit rather than left to the `default` branch
266
  // below: `formula` fell through a default once and printed every text result as `0` for
 
228
  return s === "none" ? "Not run yet" : s[0].toUpperCase() + s.slice(1);
229
  }
230
 
231
+ /**
232
+ * ⭐ Wave-23 C7 (owner item 5) β€” THE JSON PREVIEW: what a 200px cell says about a document.
233
+ *
234
+ * `MAX_JSON_BYTES` is the contract's ceiling, mirrored from the host's write validation so the
235
+ * viewer can refuse a paste with the same number the server would (a client that lets you type
236
+ * 40 KB and then shows you a server refusal has wasted the edit).
237
+ *
238
+ * The four cases, and each one is a decision rather than a formatting preference:
239
+ * Β· **a single-pair object shows THE PAIR.** `{handle: "royalimports"}` is more useful than
240
+ * "1 key" and it is the shape most machine writes actually have. Past one pair the pairs
241
+ * stop fitting and the honest answer is the count.
242
+ * Β· **many keys / many items β†’ `{…} N keys` / `[…] N items`.** Showing the FIRST pair of a
243
+ * twelve-key object would let a reader take one arbitrary value β€” whichever key the writer's
244
+ * serializer happened to emit first β€” for the cell's content.
245
+ * Β· **a bare scalar renders as itself.** `12`, `"ok"`, `true` and `null` are all valid JSON
246
+ * documents, and wrapping them in braces would describe a shape they do not have.
247
+ * Β· β›” **text that does not parse renders AS ITSELF, never as a shape.** The host validates on
248
+ * write, so this only happens to a value that predates the validation or arrived another
249
+ * way β€” and the one thing the preview must never do is claim a document is well-formed. The
250
+ * viewer's raw tab is where such a value gets read and repaired.
251
+ *
252
+ * Blank stays blank: an empty json cell is a document nobody has written, and `{}` is a document
253
+ * somebody wrote that is empty. Two different facts, two different cells.
254
+ */
255
+ export const MAX_JSON_BYTES = 32 * 1024;
256
+
257
+ /** Does this text parse as JSON? The ONE test, shared by the preview, the cell and the viewer's
258
+ * save β€” three copies of a try/catch is how they end up disagreeing about `""` or `NaN`. */
259
+ export function jsonParse(v: CellValue): { ok: boolean; value?: unknown } {
260
+ const s = String(v ?? "").trim();
261
+ if (s === "") return { ok: false };
262
+ try {
263
+ return { ok: true, value: JSON.parse(s) as unknown };
264
+ } catch {
265
+ return { ok: false };
266
+ }
267
+ }
268
+
269
+ /** One compact line for a json cell. See the note above for why each case reads as it does. */
270
+ export function jsonPreview(v: CellValue): string {
271
+ const raw = String(v ?? "").trim();
272
+ if (raw === "") return "";
273
+ const parsed = jsonParse(raw);
274
+ // ⚠ First line only, and clipped: an unparseable value is often a whole pasted response, and
275
+ // a cell is not where a 4 KB blob gets read. It is shown rather than hidden because the
276
+ // reader has to be able to see that the column holds something the app could not open.
277
+ if (!parsed.ok) return clip(raw.split("\n")[0], 60);
278
+ const value = parsed.value;
279
+ if (Array.isArray(value))
280
+ return value.length === 0 ? "[]" : `[…] ${value.length} item${value.length === 1 ? "" : "s"}`;
281
+ if (value !== null && typeof value === "object") {
282
+ const keys = Object.keys(value as Record<string, unknown>);
283
+ if (keys.length === 0) return "{}";
284
+ if (keys.length === 1)
285
+ return clip(`{${keys[0]}: ${scalarText((value as Record<string, unknown>)[keys[0]])}}`, 60);
286
+ return `{…} ${keys.length} keys`;
287
+ }
288
+ return clip(scalarText(value), 60);
289
+ }
290
+
291
+ /** A nested value, small enough to sit inside a one-pair preview. Objects and arrays collapse
292
+ * to their own marks rather than recursing β€” a preview that unfolds is not a preview. */
293
+ function scalarText(v: unknown): string {
294
+ if (v === null) return "null";
295
+ if (Array.isArray(v)) return `[…] ${v.length}`;
296
+ if (typeof v === "object") return `{…} ${Object.keys(v as object).length}`;
297
+ return typeof v === "string" ? v : String(v);
298
+ }
299
+
300
+ /** ⚠ An ellipsis CHARACTER, not three dots: the grid's canvas measures text and three periods
301
+ * are three glyphs wide. Same mark the group-bar fitter uses. */
302
+ function clip(s: string, n: number): string {
303
+ return s.length <= n ? s : s.slice(0, n - 1) + "…";
304
+ }
305
+
306
+ /**
307
+ * The document, indented for the viewer's pretty tab. Returns the RAW TEXT UNCHANGED when it
308
+ * does not parse β€” re-indenting is not repair, and handing a reader a "prettified" version of
309
+ * something the app could not read would hide the only thing they need to see.
310
+ */
311
+ export function jsonPretty(v: CellValue): string {
312
+ const raw = String(v ?? "");
313
+ const parsed = jsonParse(raw);
314
+ return parsed.ok ? JSON.stringify(parsed.value, null, 2) : raw;
315
+ }
316
+
317
  export function formatDisplay(field: Field, v: CellValue): string {
318
  switch (field.type) {
319
  case "currency":
 
347
  const n = num(v);
348
  return n >= 1 ? `${Math.round(n)} of ${ratingMax(field)}` : "";
349
  }
350
+ case "json":
351
+ // Wave-23 C7 β€” the SAME compact line the canvas cell paints. Explicit here rather than
352
+ // left to `default` for the reason the `formula` note above records: this function feeds
353
+ // ListView, KanbanView, the calendar, the record panel and all four EXPORT formats, and
354
+ // falling through would dump a whole 32 KB document into a CSV cell.
355
+ return jsonPreview(v);
356
  case "automation":
357
  // The machine-written line, verbatim. Explicit rather than left to the `default` branch
358
  // below: `formula` fell through a default once and printed every text result as `0` for
web/src/customer-grid/iconShapes.ts CHANGED
@@ -112,6 +112,17 @@ export const TYPE_SHAPES: Record<FieldType, IconShape[]> = {
112
  { d: "M3.2 3.2v9.6h9.6" },
113
  { d: "M5 10.4l2.4-2.6 1.9 1.5 3.1-3.9" },
114
  ],
 
 
 
 
 
 
 
 
 
 
 
115
  // Wave-19 R7 β€” a framed picture: the mount, a sun, and the hill line every photo glyph
116
  // resolves to at 16px. Drawn on the same 16-unit grid as its neighbours.
117
  image: [
@@ -168,6 +179,17 @@ export const MODE_SHAPES: Record<DisplayMode, IconShape[]> = {
168
  { d: "M13.6 4.2H9a1.6 1.6 0 0 0-1 .4l0 8a1.6 1.6 0 0 1 1-.4h4.6z" },
169
  { d: "M3.9 6.4h2.3v2.8H3.9z" },
170
  ],
 
 
 
 
 
 
 
 
 
 
 
171
  };
172
 
173
  /**
@@ -330,6 +352,10 @@ export const MODE_LABELS: Record<DisplayMode, string> = {
330
  map: "Map",
331
  timeseries: "Time series",
332
  catalog: "Catalog",
 
 
 
 
333
  };
334
 
335
  /**
@@ -388,6 +414,11 @@ export const MODE_TONE: Record<DisplayMode, FolderTone> = {
388
  // analytical, yellow = board/date, red = spatial); a catalog arranges nothing β€” it is a
389
  // published artifact. Giving it a colour would file it under a family it is not in.
390
  catalog: "neutral",
 
 
 
 
 
391
  };
392
 
393
  /**
@@ -418,6 +449,10 @@ export const TYPE_LABELS: Record<FieldType, string> = {
418
  metric: "Metric",
419
  // Wave-19 R7 β€” the picture column.
420
  image: "Image",
 
 
 
 
421
  status: "Lifecycle status (Odoo)", // never creatable; present so the map stays total
422
  };
423
 
 
112
  { d: "M3.2 3.2v9.6h9.6" },
113
  { d: "M5 10.4l2.4-2.6 1.9 1.5 3.1-3.9" },
114
  ],
115
+ // Wave-23 C7 β€” TWO BRACES facing each other with a dot between them: the universal mark for
116
+ // "a structured document", and the one glyph in this table that draws its own SYNTAX rather
117
+ // than a picture of what the value means. Deliberately not a document page (nothing here owns
118
+ // that yet, but a page reads as a file/attachment, which a json cell is not) and not a tree
119
+ // of nodes (too fine to survive 16px). The centre dot is what keeps the two braces from
120
+ // reading as parentheses at small sizes.
121
+ json: [
122
+ { d: "M6.4 3.2c-1.5 0-1.5 3.4-1.5 3.4S4.8 8 3.4 8s1.5 1.4 1.5 1.4 0 3.4 1.5 3.4" },
123
+ { d: "M9.6 3.2c1.5 0 1.5 3.4 1.5 3.4s.1 1.4 1.5 1.4-1.5 1.4-1.5 1.4 0 3.4-1.5 3.4" },
124
+ { d: circle(8, 8, 0.85), fill: true },
125
+ ],
126
  // Wave-19 R7 β€” a framed picture: the mount, a sun, and the hill line every photo glyph
127
  // resolves to at 16px. Drawn on the same 16-unit grid as its neighbours.
128
  image: [
 
179
  { d: "M13.6 4.2H9a1.6 1.6 0 0 0-1 .4l0 8a1.6 1.6 0 0 1 1-.4h4.6z" },
180
  { d: "M3.9 6.4h2.3v2.8H3.9z" },
181
  ],
182
+ // Wave-23 C9 β€” a SHEET WITH A WRITING LINE: two filled answer bars and an empty rule beneath
183
+ // them. Every other mode here draws a way of ARRANGING records that already exist; this one
184
+ // has to read as a record being MADE, so it is the only mark whose bottom line is open.
185
+ // Deliberately not a clipboard (nothing else here has a frame with a tab) and not a pencil
186
+ // (an edit affordance means something else app-wide).
187
+ form: [
188
+ { d: "M3.4 2.8h9.2v10.4H3.4z" },
189
+ { d: "M5.6 5.6h4.8" },
190
+ { d: "M5.6 8h4.8" },
191
+ { d: "M5.6 10.6h2.6" },
192
+ ],
193
  };
194
 
195
  /**
 
352
  map: "Map",
353
  timeseries: "Time series",
354
  catalog: "Catalog",
355
+ // Wave-23 C9 β€” the mode that COLLECTS records. "Form", the word the whole product uses for
356
+ // it (the public page, the share panel, the `form_submitted` trigger); a synonym here would
357
+ // be the one surface calling it something else.
358
+ form: "Form",
359
  };
360
 
361
  /**
 
414
  // analytical, yellow = board/date, red = spatial); a catalog arranges nothing β€” it is a
415
  // published artifact. Giving it a colour would file it under a family it is not in.
416
  catalog: "neutral",
417
+ // Wave-23 C9 β€” NEUTRAL, and for `catalog`'s reason rather than by elimination: the four tones
418
+ // name families of ways to ARRANGE records (blue tabular, green analytical, yellow
419
+ // board/date, red spatial). A form arranges nothing β€” it is a door records come in through β€”
420
+ // so giving it a colour would file it under a family it is not in.
421
+ form: "neutral",
422
  };
423
 
424
  /**
 
449
  metric: "Metric",
450
  // Wave-19 R7 β€” the picture column.
451
  image: "Image",
452
+ // Wave-23 C7 β€” the structured-document column. "JSON" rather than "Structured data": it is
453
+ // the word on the wire, in the viewer's raw tab and in every error the server can return, and
454
+ // a friendlier synonym would be the only place in the product using a different one.
455
+ json: "JSON",
456
  status: "Lifecycle status (Odoo)", // never creatable; present so the map stays total
457
  };
458
 
web/src/customer-grid/theme.ts CHANGED
@@ -73,6 +73,30 @@ export const LP_PURPLE_DEEP = "#6B57A8"; // 5.17:1 on its own tint
73
  */
74
  export const LP_VOID = "#F6F8FC";
75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  export const LP_BLUE_DEEP = "#768FB6"; // 3.29:1 on white β€” rings, control borders
77
  /* THE PRODUCT PRIMARY β€” the same #5B8FD9 the host's `.streamlit/config.toml`
78
  paints on every primary button, so embed and standalone stop disagreeing
@@ -294,6 +318,57 @@ export const COLUMN_TONE_THEME: Record<ControlTone, Partial<Theme>> = {
294
  },
295
  };
296
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297
  /* wave17 GRID β€” item 2 / owner R5: **THE ALTERNATING ROW BANDS ARE DEAD.**
298
  *
299
  * `CONTROL_BAND_THEME` stood here: a faint wash on every other data row while any control was
 
73
  */
74
  export const LP_VOID = "#F6F8FC";
75
 
76
+ /**
77
+ * ⭐ Wave-23 C8 (owner item 4 / ruling R9) β€” **the MACHINE-OWNED column pair.**
78
+ *
79
+ * A sixth family, and neutral rather than a hue on purpose: the four C1 pastels each mean a
80
+ * STATE (green positive, red negative, yellow attention, blue interactive) and purple means
81
+ * GROUP. "A robot fills this column" is none of those β€” it is a property of the column's
82
+ * OWNERSHIP, so it takes the grey the palette had no name for. Deliberately NOT `LP_MUTED`
83
+ * (#6B7280): that is chrome ink, it is warmer, and re-using it would make "muted text" and
84
+ * "machine-owned" one token that two unrelated rules could then drag apart.
85
+ *
86
+ * `LP_MACHINE_TINT` the flat wash the DOM surfaces paint (`RecordDetail.css`'s
87
+ * `.cg-detail-field.is-machine .cg-detail-value`). It is exactly what the
88
+ * canvas wash below COMPOSITES TO over white, so the drawer's value slot
89
+ * and the grid cell are the same grey rather than two greys that were each
90
+ * picked to look right alone.
91
+ * `LP_MACHINE_DEEP` its ink β€” 5.35:1 on the tint, 6.32:1 on white (measured, not picked) β€”
92
+ * and the hue `MACHINE_CELL` derives the canvas wash from.
93
+ *
94
+ * Mirrors `--lp-machine-tint` / `--lp-machine-deep` in index.css; `verify_icons`' I7c parity
95
+ * diffs the two files, which is why both are plain hex strings here and neither is computed.
96
+ */
97
+ export const LP_MACHINE_TINT = "#EBECEE";
98
+ export const LP_MACHINE_DEEP = "#59606E";
99
+
100
  export const LP_BLUE_DEEP = "#768FB6"; // 3.29:1 on white β€” rings, control borders
101
  /* THE PRODUCT PRIMARY β€” the same #5B8FD9 the host's `.streamlit/config.toml`
102
  paints on every primary button, so embed and standalone stop disagreeing
 
318
  },
319
  };
320
 
321
+ /**
322
+ * ⭐ Wave-23 C8 β€” the wash a MACHINE-OWNED cell paints (`isMachineOwned`, types.ts).
323
+ *
324
+ * **ONE SHARED REFERENCE, and that is not a micro-optimisation.** glide has no theme-merge
325
+ * cache, so a fresh `{bgCell}` per cell costs a ~35-key spread on every cell of every frame β€”
326
+ * the same reasoning `STATUS_ROW_THEME` and `COLUMN_TONE_THEME` state, and it bites harder here
327
+ * because this override is returned for a whole COLUMN of cells rather than for the few rows
328
+ * that carry a status.
329
+ *
330
+ * **`rgba`, NOT a hex, and it is load-bearing** (the wave-15 R5 lesson, one surface down):
331
+ * `mergeAndRealizeTheme` alpha-BLENDS `bgCell` and hard-replaces every other key, so an opaque
332
+ * grey here would ERASE whatever it landed on β€” a colour-by row's status wash and the
333
+ * hover/active row wash both, leaving a machine column as a permanent gap through every tinted
334
+ * row. Blending means a hovered machine cell is darker than either alone, which is exactly the
335
+ * reading a person expects.
336
+ *
337
+ * ⚠ **0.12, chosen against a COLLISION rather than by eye.** `ROW_HIGHLIGHT_NEUTRAL` (the
338
+ * hover/active row) composites to β‰ˆ#F2F2F3 β€” a neutral grey wash already means something on
339
+ * this canvas. At 0.12 this composites to `LP_MACHINE_TINT` (#EBECEE), which is visibly the
340
+ * stronger of the two, so "a whole column is grey" and "the row under my pointer is grey" stay
341
+ * two different readings. Raising it is the one knob if a machine column reads as nothing; do
342
+ * not switch it to a hue (R9 is explicit that this is not a state).
343
+ */
344
+ export const MACHINE_CELL: Partial<Theme> = { bgCell: washOf(LP_MACHINE_DEEP, 0.12) };
345
+
346
+ /**
347
+ * ⭐ Wave-23 C8 β€” a machine-owned cell's FINAL theme override, given whatever the cell already
348
+ * carried. **THE PRECEDENCE IS THE WHOLE FUNCTION**, so it lives here (node-reachable, under
349
+ * `verify_grid_ux`'s mutation harness) rather than inline in `cells.ts`, which imports glide and
350
+ * therefore cannot be driven by a gate at all.
351
+ *
352
+ * MERGED, with the CELL's own keys landing last β€” not "keep whichever exists", which was the
353
+ * first shape and is wrong in both directions:
354
+ * Β· an `automation` cell that HAS run carries `AUTOMATION_TINT[state]` β€” a green/red/yellow
355
+ * `bgCell` plus its ink. That is a STATE and it says something the wash does not, so it must
356
+ * win. (A cell that has never run carries no override at all β€” `AUTOMATION_TINT.none` is
357
+ * deliberately `undefined` β€” and takes the wash, which is the honest reading: machine-owned,
358
+ * nothing written yet.)
359
+ * Β· a machine-TAGGED `status`/`select`/`multiselect` cell β€” an automation-spawned column is an
360
+ * ordinary field TYPE wearing the tag β€” carries a BUBBLE tint (`bgBubble`/`textBubble`),
361
+ * which does not touch `bgCell` at all. "Keep whichever exists" would have silently cost
362
+ * every one of those columns its wash, and a column of pills is exactly where a reader is
363
+ * least able to tell who typed the value.
364
+ *
365
+ * The no-override case returns the SHARED `MACHINE_CELL` reference (see its note above); only
366
+ * the two merge cases allocate, and both already allocated a fresh override upstream.
367
+ */
368
+ export function machineCellTheme(own: Partial<Theme> | undefined): Partial<Theme> {
369
+ return own ? { ...MACHINE_CELL, ...own } : MACHINE_CELL;
370
+ }
371
+
372
  /* wave17 GRID β€” item 2 / owner R5: **THE ALTERNATING ROW BANDS ARE DEAD.**
373
  *
374
  * `CONTROL_BAND_THEME` stood here: a faint wash on every other data row while any control was
web/src/customer-grid/types.ts CHANGED
@@ -44,6 +44,14 @@ export type FieldType =
44
  // menu (deliberately absent from CREATABLE_TYPES: the menu has no measure/window face yet β€”
45
  // offering the type without its config would mint permanently blank columns).
46
  | "metric"
 
 
 
 
 
 
 
 
47
  // ⭐ Wave-19 R7 / C5 β€” `image` is a PICTURE on a record. The cell holds a STRING REFERENCE,
48
  // never bytes (see `imageRef`): a SKU code, an `ed:` editorial slug, or a `rec:` upload. That
49
  // is what lets Royal's 1,142 existing SKU masters appear with nothing uploaded, and it keeps
@@ -56,10 +64,26 @@ export type FieldSource = "odoo" | "overlay";
56
  /** The types a user may create from the column menu. Odoo-sourced fields are not in this list β€”
57
  * their type comes from the model, and `status` in particular is Odoo's lifecycle, not a
58
  * user-defined set. */
 
 
 
 
 
 
 
 
59
  export const CREATABLE_TYPES: readonly FieldType[] = [
60
  "text", "select", "multiselect", "user", "int", "currency", "pct", "date",
61
  "checkbox", "phone", "email", "url", "rating", "created_time", "formula", "automation",
62
  "image",
 
 
 
 
 
 
 
 
63
  ];
64
 
65
  /**
@@ -237,8 +261,16 @@ export type FieldScope = "cohort" | "global";
237
  // held OUT of CREATABLE_MODES until `aios_grid.DISPLAY_MODES` accepts the name, because
238
  // `_clean_display` drops an unknown mode and offering it first would let a user build a whole
239
  // catalogue that silently reverts to a grid on the next read with nothing going red.
 
 
 
 
 
 
 
240
  export const DISPLAY_MODES = [
241
  "grid", "chart", "dashboard", "list", "calendar", "kanban", "map", "timeseries", "catalog",
 
242
  ] as const;
243
  export type DisplayMode = (typeof DISPLAY_MODES)[number];
244
 
@@ -946,6 +978,35 @@ export function mayEditField(field: Field, viewer: Viewer | undefined): boolean
946
  return edit === "creator" && field.createdBy === viewer.name;
947
  }
948
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
949
  /**
950
  * The NUMERIC and DATE families, for UI dispatch (operator lists, input kinds, sort-direction
951
  * wording). ONE definition here; the ENGINE (useVisibleRows) keeps its own deliberately β€”
@@ -1081,16 +1142,32 @@ export interface Field {
1081
  * Wave-18 C5-AUTOFIELD β€” what this column's automation DOES. Absent = unconfigured (the cells
1082
  * render "Not configured" and no run ever targets the column). Written through the field's
1083
  * gear; validated host-side (`aios_grid._clean_automation`) exactly as `options`/`formula` are.
 
 
 
 
 
 
 
 
 
 
1084
  */
1085
  automation?: {
1086
- /** v1 vocabulary: 'instagram_profile'. Host-whitelisted; an unknown kind is dropped. */
1087
- kind: string;
1088
- /** where the run gets its subject. 'record_url_field' reads `urlField` off the row. */
1089
- source: "record_url_field" | "self";
 
 
1090
  /** the row field holding the profile URL when source = 'record_url_field'. */
1091
  urlField?: string;
1092
  /** kind-specific knobs. Scalars only β€” the host clamps keys and value lengths. */
1093
  settings?: Record<string, string | number | boolean>;
 
 
 
 
1094
  };
1095
  /**
1096
  * Wave-22 C7 β€” a METRIC field's config bag, mirrored from `user_tables._clean_metric` (the
 
44
  // menu (deliberately absent from CREATABLE_TYPES: the menu has no measure/window face yet β€”
45
  // offering the type without its config would mint permanently blank columns).
46
  | "metric"
47
+ // ⭐ Wave-23 C7 (owner item 5 / ruling R5) β€” `json` is a STRUCTURED DOCUMENT on a record: an
48
+ // API response, a webhook body, a scraped payload. The cell holds a STRING that must parse as
49
+ // JSON, ≀ 32 KB, validated host-side on write (refuse with a sentence, never truncate) β€” so
50
+ // the scalar `Row` contract (types.ts's Row, and `grid_events.py:1619`'s non-scalar refusal)
51
+ // is untouched. The grid shows a compact preview and the big viewer modal owns the document.
52
+ // It is NOT in `READONLY_CELL_TYPES`: the value is editable, just never through a 200px cell
53
+ // β€” the same "picked, not typed" reasoning `select` and `image` carry.
54
+ | "json"
55
  // ⭐ Wave-19 R7 / C5 β€” `image` is a PICTURE on a record. The cell holds a STRING REFERENCE,
56
  // never bytes (see `imageRef`): a SKU code, an `ed:` editorial slug, or a `rec:` upload. That
57
  // is what lets Royal's 1,142 existing SKU masters appear with nothing uploaded, and it keeps
 
64
  /** The types a user may create from the column menu. Odoo-sourced fields are not in this list β€”
65
  * their type comes from the model, and `status` in particular is Odoo's lifecycle, not a
66
  * user-defined set. */
67
+ // ⚠ Wave-23 C7 β€” `json` is deliberately ABSENT from this list until SESSION A posts that
68
+ // `aios_grid.CUSTOM_FIELD_TYPES` and `core.user_tables.UT_FIELD_TYPES` accept the name. It is
69
+ // the field-kind twin of the CREATABLE_MODES hold (iconShapes.ts:344-364) and the failure is
70
+ // worse here, because it is not a downgrade: `user_tables._clean_field` (:389) RETURNS NONE for
71
+ // an unknown type, so a column created before the server knows the word simply does not exist
72
+ // on the next read β€” created, named, configured, gone, with nothing anywhere going red. Every
73
+ // OTHER json table below lands now, because reading a json field the server already sends is a
74
+ // different question from offering to create one.
75
  export const CREATABLE_TYPES: readonly FieldType[] = [
76
  "text", "select", "multiselect", "user", "int", "currency", "pct", "date",
77
  "checkbox", "phone", "email", "url", "rating", "created_time", "formula", "automation",
78
  "image",
79
+ // ⭐ Wave-23 C7 (owner item 5) β€” ADDED AT THE CLOSE-OUT AUDIT, and its absence is the exact
80
+ // half-landing the fields contract exists to catch. `json` reached the `FieldType` union, the
81
+ // shape/label tables and the server's `CUSTOM_FIELD_TYPES`, but not this list β€” so the server
82
+ // would have accepted a json field that the client offered no way to create. The type would
83
+ // have shipped real, documented and unreachable.
84
+ // `verify_fields_contract` caught it by diffing the two lists; nothing else could have, because
85
+ // every individual file was internally consistent.
86
+ "json",
87
  ];
88
 
89
  /**
 
261
  // held OUT of CREATABLE_MODES until `aios_grid.DISPLAY_MODES` accepts the name, because
262
  // `_clean_display` drops an unknown mode and offering it first would let a user build a whole
263
  // catalogue that silently reverts to a grid on the next read with nothing going red.
264
+ // ⭐ Wave-23 C9 (owner item 8): `form` joins the union β€” a view that COLLECTS records instead of
265
+ // arranging them, published at a public `#/form/<token>` link. Landed here (so the type, the
266
+ // icon table, the label table and the tone table are total over it, and a stored `form` view
267
+ // renders rather than blanking) and held OUT of `CREATABLE_MODES` until `aios_grid.DISPLAY_MODES`
268
+ // accepts the name β€” the identical hold `timeseries` and `catalog` served, for the identical
269
+ // reason: `_clean_display` DROPS an unknown mode, so offering it early would let somebody build
270
+ // a whole form, share its link, and have the view silently revert to a grid on the next read.
271
  export const DISPLAY_MODES = [
272
  "grid", "chart", "dashboard", "list", "calendar", "kanban", "map", "timeseries", "catalog",
273
+ "form",
274
  ] as const;
275
  export type DisplayMode = (typeof DISPLAY_MODES)[number];
276
 
 
978
  return edit === "creator" && field.createdBy === viewer.name;
979
  }
980
 
981
+ /**
982
+ * ⭐ Wave-23 C8 (owner item 4 / ruling R9) β€” **is this column filled by a MACHINE?**
983
+ *
984
+ * Two clauses, and R9 is what makes it exactly two:
985
+ * Β· `field.automation` present β€” the TAG the engine stamps on everything it spawns or writes:
986
+ * the IG preset columns (`{flowId}`, automation_engine.py:757), the `stage_<autoId>` board
987
+ * column and its cycles counter (`{flowId, stageField}`, :3600), and a user-configured
988
+ * `automation` column's own gear bag. Ordinary field TYPES, machine ownership, one marker.
989
+ * Β· `type ∈ {automation, metric}` β€” the two kinds that are machine-written BY DEFINITION even
990
+ * when no tag reached the client (an `automation` column created before the flow that fills
991
+ * it; a `metric`, which is computed server-side from the master series and never typed).
992
+ *
993
+ * β›” R9 DRAWS THE LINE HERE ON PURPOSE, and the two exclusions are the whole ruling: an
994
+ * ODOO-sourced column and a `formula`/`created_time` column **keep their current look**. All
995
+ * four are read-only, so "read-only" is NOT the predicate β€” a formula is written by the reader's
996
+ * own arithmetic and an Odoo column by the business, and greying either would say a robot owns
997
+ * a number the reader owns. This is why it is a separate function from `mayEditField` and not a
998
+ * branch of it.
999
+ *
1000
+ * ⚠ **PAINT, NEVER PERMISSION.** `mayEditField` above stays the one edit wall (client courtesy;
1001
+ * `grid_events.py:1608-1650` is the real one). A column can be machine-owned and editable
1002
+ * (nothing is, today) or editable and machine-owned tomorrow, and this predicate must not be
1003
+ * the reason a cell locks β€” two functions that agree today are exactly how one silently becomes
1004
+ * the other's enforcement.
1005
+ */
1006
+ export function isMachineOwned(field: Field): boolean {
1007
+ return !!field.automation || field.type === "automation" || field.type === "metric";
1008
+ }
1009
+
1010
  /**
1011
  * The NUMERIC and DATE families, for UI dispatch (operator lists, input kinds, sort-direction
1012
  * wording). ONE definition here; the ENGINE (useVisibleRows) keeps its own deliberately β€”
 
1142
  * Wave-18 C5-AUTOFIELD β€” what this column's automation DOES. Absent = unconfigured (the cells
1143
  * render "Not configured" and no run ever targets the column). Written through the field's
1144
  * gear; validated host-side (`aios_grid._clean_automation`) exactly as `options`/`formula` are.
1145
+ *
1146
+ * ⭐ WIDENED wave-23 C8, because this interface described only ONE of the three writers and
1147
+ * the other two have been shipping for a wave. `kind`/`source` are what the field GEAR writes
1148
+ * (`_clean_automation`); the engine stamps two more bags that never carry either of them:
1149
+ * Β· a SPAWNED preset column β€” `{flowId}` alone (`automation_engine.py:757`);
1150
+ * Β· a STAGE column β€” `{flowId, stageField: true, …}` (`automation_engine.py:3600`).
1151
+ * Nothing went red, because the wire arrives untyped: `field.automation.kind` on a stage
1152
+ * column is a runtime `undefined` under a green `tsc`. C8 makes the TAG ITSELF load-bearing
1153
+ * ("present β‡’ machine-owned", `isMachineOwned` above), so the shape it actually has is
1154
+ * declared here rather than left to the one writer that happened to be typed first.
1155
  */
1156
  automation?: {
1157
+ /** v1 vocabulary: 'instagram_profile'. Host-whitelisted; an unknown kind is dropped.
1158
+ * Absent on engine-stamped bags (spawned presets, stage columns). */
1159
+ kind?: string;
1160
+ /** where the run gets its subject. 'record_url_field' reads `urlField` off the row.
1161
+ * Absent on engine-stamped bags. */
1162
+ source?: "record_url_field" | "self";
1163
  /** the row field holding the profile URL when source = 'record_url_field'. */
1164
  urlField?: string;
1165
  /** kind-specific knobs. Scalars only β€” the host clamps keys and value lengths. */
1166
  settings?: Record<string, string | number | boolean>;
1167
+ /** the automation definition that owns this column (engine-stamped; the machine marker). */
1168
+ flowId?: string;
1169
+ /** true on the `stage_<autoId>` column an automation board walks its records through. */
1170
+ stageField?: boolean;
1171
  };
1172
  /**
1173
  * Wave-22 C7 β€” a METRIC field's config bag, mirrored from `user_tables._clean_metric` (the
web/src/filter-kit/ops.ts CHANGED
@@ -83,6 +83,20 @@ export function opsForType(t: FieldType): FilterOp[] {
83
  // by the user's own choice list. `eq` reads "is exactly": the whole set is that one choice.
84
  if (t === "multiselect")
85
  return ["contains", "doesNotContain", "eq", "neq", "isEmpty", "isNotEmpty"];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  // Wave-18 C5-AUTOFIELD β€” `automation` lands HERE, on the text ops, and that is the whole
87
  // v1 answer. Its cell is one machine-written line (`ok Β· 2026-08-03 14:10 Β· 12 posts`), so
88
  // `contains ok` and `contains error` are the two questions anyone actually asks of the
 
83
  // by the user's own choice list. `eq` reads "is exactly": the whole set is that one choice.
84
  if (t === "multiselect")
85
  return ["contains", "doesNotContain", "eq", "neq", "isEmpty", "isNotEmpty"];
86
+ // ⭐ Wave-23 C7 β€” `json` gets EXACTLY the two value-free ops, and the omissions are the
87
+ // decision. `contains` over a serialized document is a substring test against punctuation and
88
+ // key names: `contains "12"` would match a key `id_12`, a value 12, a timestamp and a
89
+ // fragment of 5120, and every one of those reads as a working filter. `eq` is worse β€” two
90
+ // documents that mean the same thing differ by key order and whitespace, so "is" would answer
91
+ // false for a record that plainly matches. "Has anything been captured here yet" is the
92
+ // question a json column can answer soundly, and it is the one people actually ask.
93
+ //
94
+ // ⚠ NO NEW OPERATOR ENTERS EITHER ENGINE. `isEmpty`/`isNotEmpty` already exist in
95
+ // `filter_sql.py` (:76, and :112's VALUE_FREE_OPS) and `filter_eval.py` (:260-262), and both
96
+ // are TYPE-INDEPENDENT β€” they test blankness before any type dispatch β€” so the lock-step is
97
+ // untouched and nothing on the server had to move for this line. (The contract's prose spells
98
+ // them `is_empty`/`is_not_empty`; the runtimes do not. The names come from the code.)
99
+ if (t === "json") return ["isNotEmpty", "isEmpty"];
100
  // Wave-18 C5-AUTOFIELD β€” `automation` lands HERE, on the text ops, and that is the whole
101
  // v1 answer. Its cell is one machine-written line (`ok Β· 2026-08-03 14:10 Β· 12 posts`), so
102
  // `contains ok` and `contains error` are the two questions anyone actually asks of the
web/src/forms/FormPublic.tsx ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // forms / FormPublic.tsx β€” ⭐ wave-23 item 8 (contract W23-C9).
3
+ //
4
+ // The page an ANONYMOUS person lands on at `#/form/<token>`. E mounts it in the
5
+ // Shell BEFORE the auth wall (wiring W23-W2); everything below assumes there is
6
+ // no session, no workspace, no nav and no viewer.
7
+ //
8
+ // β›” IT IMPORTS NOTHING FROM `customer-grid/**`, AND THAT IS A REQUIREMENT, NOT
9
+ // A PREFERENCE. The grid bundle drags glide-data-grid β€” hundreds of kilobytes
10
+ // of canvas table β€” into whatever chunk touches it, and this page is the one
11
+ // surface in the product that a stranger loads cold, once, probably on a phone,
12
+ // probably on mobile data, to type four answers. One convenience import from
13
+ // `types.ts` would put the whole spreadsheet engine on that wire. So the field
14
+ // vocabulary below is DECLARED HERE as plain strings rather than imported: the
15
+ // server sends `type` as a string and this page renders a control per string,
16
+ // which is the same "no client union over a server vocabulary" rule the rest of
17
+ // the wave follows, arriving here for a second reason.
18
+ //
19
+ // ⚠ Styling reuses `.lpf-*` rules in the D REGION of index.css β€” the shell's
20
+ // stylesheet is one file and already loaded; a second stylesheet for one page
21
+ // would be a second copy of the tokens.
22
+ // ---------------------------------------------------------------------------
23
+
24
+ import { useEffect, useState } from "react";
25
+
26
+ /** One field, exactly as `routes_forms._public_form` builds it. Nothing here is
27
+ * optional-because-maybe: every key below is one the server always sends, and
28
+ * the three that are conditional say so. */
29
+ interface FormField {
30
+ key: string;
31
+ label: string;
32
+ /** The server's own word. Deliberately `string`, not a union β€” an unknown
33
+ * type lands on the text input, which is the safe direction: a person can
34
+ * always type an answer, and a control this page has never heard of would
35
+ * otherwise render as nothing at all. */
36
+ type: string;
37
+ required: boolean;
38
+ options?: string[];
39
+ max?: number;
40
+ }
41
+
42
+ interface FormSpec {
43
+ title: string;
44
+ desc: string;
45
+ submitLabel: string;
46
+ fields: FormField[];
47
+ /** The honeypot's field name β€” planted, never shown. Server-named so the two
48
+ * halves cannot drift into a trap nobody checks. */
49
+ honeypot: string;
50
+ }
51
+
52
+ type Phase = "loading" | "ready" | "sent" | "gone";
53
+
54
+ const LONG_TEXT_MIN = 0; // every text field gets a textarea when it is the only one
55
+
56
+ export default function FormPublic({ token }: { token: string }) {
57
+ const [spec, setSpec] = useState<FormSpec | null>(null);
58
+ const [phase, setPhase] = useState<Phase>("loading");
59
+ const [values, setValues] = useState<Record<string, string>>({});
60
+ const [error, setError] = useState("");
61
+ const [busy, setBusy] = useState(false);
62
+
63
+ useEffect(() => {
64
+ let live = true;
65
+ setPhase("loading");
66
+ fetch(`/api/v1/forms/${encodeURIComponent(token)}`)
67
+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))
68
+ .then((data: FormSpec) => {
69
+ if (!live) return;
70
+ setSpec(data);
71
+ setPhase("ready");
72
+ })
73
+ // ⚠ ONE dead-end state for every failure, mirroring the server's uniform 403. Telling a
74
+ // visitor "this form is disabled" versus "no such form" would hand an enumerator the
75
+ // distinction the whole server-side refusal exists to withhold.
76
+ .catch(() => live && setPhase("gone"));
77
+ return () => {
78
+ live = false;
79
+ };
80
+ }, [token]);
81
+
82
+ const set = (key: string, v: string) =>
83
+ setValues((prev) => ({ ...prev, [key]: v }));
84
+
85
+ const submit = (event: React.FormEvent) => {
86
+ event.preventDefault();
87
+ if (busy) return;
88
+ setBusy(true);
89
+ setError("");
90
+ fetch(`/api/v1/forms/${encodeURIComponent(token)}`, {
91
+ method: "POST",
92
+ headers: { "Content-Type": "application/json" },
93
+ body: JSON.stringify({ values }),
94
+ })
95
+ .then(async (r) => {
96
+ if (r.ok) {
97
+ setPhase("sent");
98
+ return;
99
+ }
100
+ // The server's sentence, verbatim β€” it names the field by the label THIS PAGE showed,
101
+ // which is the only name the person has. A generic "something went wrong" here would
102
+ // discard the one useful thing the refusal carried.
103
+ const body = await r.json().catch(() => null);
104
+ setError(
105
+ String(body?.error?.message || "That could not be sent β€” check your answers and try again.")
106
+ );
107
+ })
108
+ .catch(() =>
109
+ setError("That could not be sent β€” check your connection and try again.")
110
+ )
111
+ .finally(() => setBusy(false));
112
+ };
113
+
114
+ if (phase === "loading")
115
+ return (
116
+ <div className="lpf-page">
117
+ <div className="lpf-card lpf-card--quiet" />
118
+ </div>
119
+ );
120
+
121
+ if (phase === "gone")
122
+ return (
123
+ <div className="lpf-page">
124
+ <div className="lpf-card">
125
+ <h1 className="lpf-title">This form is not available</h1>
126
+ {/* ONE line (DESIGN.md Β§4). There is nothing this person can do about it and no
127
+ detail we may safely give, so the page does not pretend otherwise. */}
128
+ <p className="lpf-desc">The link may have expired or been turned off.</p>
129
+ </div>
130
+ </div>
131
+ );
132
+
133
+ if (phase === "sent")
134
+ return (
135
+ <div className="lpf-page">
136
+ <div className="lpf-card">
137
+ <h1 className="lpf-title">Thank you</h1>
138
+ <p className="lpf-desc">Your response has been recorded.</p>
139
+ <button
140
+ type="button"
141
+ className="lpf-btn"
142
+ onClick={() => {
143
+ setValues({});
144
+ setPhase("ready");
145
+ }}
146
+ >
147
+ Submit another
148
+ </button>
149
+ </div>
150
+ </div>
151
+ );
152
+
153
+ if (!spec) return null;
154
+
155
+ return (
156
+ <div className="lpf-page">
157
+ <form className="lpf-card" onSubmit={submit}>
158
+ <h1 className="lpf-title">{spec.title || "Form"}</h1>
159
+ {spec.desc && <p className="lpf-desc">{spec.desc}</p>}
160
+
161
+ {spec.fields.map((f) => (
162
+ <label key={f.key} className="lpf-field">
163
+ <span className="lpf-label">
164
+ {f.label}
165
+ {f.required && <span className="lpf-req" aria-hidden> *</span>}
166
+ </span>
167
+ <FieldControl field={f} value={values[f.key] ?? ""} onChange={set} />
168
+ </label>
169
+ ))}
170
+
171
+ {/* β›” THE HONEYPOT. Off-screen rather than `display:none` β€” several bot frameworks skip
172
+ hidden inputs on purpose, and a trap they know to skip is not a trap. `tabIndex={-1}`
173
+ and `aria-hidden` keep it away from a keyboard user and a screen reader alike, and
174
+ `autoComplete="off"` stops a browser filling it for a real person, which would
175
+ silently drop their submission. */}
176
+ <input
177
+ className="lpf-hp"
178
+ type="text"
179
+ name={spec.honeypot}
180
+ value={values[spec.honeypot] ?? ""}
181
+ onChange={(e) => set(spec.honeypot, e.target.value)}
182
+ tabIndex={-1}
183
+ autoComplete="off"
184
+ aria-hidden
185
+ />
186
+
187
+ {error && <p className="lpf-err">{error}</p>}
188
+ <button type="submit" className="lpf-btn lpf-btn--primary" disabled={busy}>
189
+ {busy ? "Sending…" : spec.submitLabel || "Submit"}
190
+ </button>
191
+ <p className="lpf-brand">Loopable</p>
192
+ </form>
193
+ </div>
194
+ );
195
+ }
196
+
197
+ /** One control per server type string. An unrecognised type falls through to text β€” see the
198
+ * `FormField.type` note: a stranger can always type an answer, and a blank where a control
199
+ * should be is the one failure they cannot work around. */
200
+ function FieldControl({
201
+ field,
202
+ value,
203
+ onChange,
204
+ }: {
205
+ field: FormField;
206
+ value: string;
207
+ onChange: (key: string, v: string) => void;
208
+ }) {
209
+ const common = {
210
+ className: "lpf-input",
211
+ value,
212
+ required: field.required,
213
+ onChange: (e: { target: { value: string } }) => onChange(field.key, e.target.value),
214
+ };
215
+ switch (field.type) {
216
+ case "checkbox":
217
+ return (
218
+ <input
219
+ type="checkbox"
220
+ className="lpf-check"
221
+ checked={value === "1"}
222
+ onChange={(e) => onChange(field.key, e.target.checked ? "1" : "")}
223
+ />
224
+ );
225
+ case "select":
226
+ case "status":
227
+ return (
228
+ <select {...common} className="lpf-input lpf-select">
229
+ {/* An explicit empty option, always. A `<select>` with no blank member has its first
230
+ choice pre-selected, so an untouched optional field silently submits a value the
231
+ person never picked. */}
232
+ <option value="">{field.required ? "Choose…" : "β€”"}</option>
233
+ {(field.options ?? []).map((o) => (
234
+ <option key={o} value={o}>{o}</option>
235
+ ))}
236
+ </select>
237
+ );
238
+ case "int":
239
+ case "currency":
240
+ case "pct":
241
+ case "rating":
242
+ return <input {...common} type="number" inputMode="decimal" />;
243
+ case "date":
244
+ // ⚠ `type="date"` submits ISO (`YYYY-MM-DD`) whatever the browser DISPLAYS, which is
245
+ // exactly what the server's refuse-never-coerce date check demands. A text input here
246
+ // would send whatever the locale suggested and be refused on half the planet.
247
+ return <input {...common} type="date" />;
248
+ case "email":
249
+ return <input {...common} type="email" inputMode="email" />;
250
+ case "phone":
251
+ return <input {...common} type="tel" inputMode="tel" />;
252
+ case "url":
253
+ return <input {...common} type="url" inputMode="url" />;
254
+ case "text":
255
+ return (
256
+ <textarea
257
+ {...common}
258
+ className="lpf-input lpf-textarea"
259
+ rows={value.length > 60 ? 4 : 2}
260
+ minLength={LONG_TEXT_MIN}
261
+ />
262
+ );
263
+ default:
264
+ return <input {...common} type="text" />;
265
+ }
266
+ }
web/src/home/HomePage.tsx ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // home/HomePage.tsx β€” WAVE 23 item 9 (ruling R7, contract C10): the landing.
3
+ //
4
+ // The layout is `reference/Airtable Home.png`, in OUR tokens: an `h1`, a row of
5
+ // quick-start cards, then the recently-opened databases under Today / Past 7
6
+ // days / Older, with a list/grid toggle. Nothing is copied but the ANATOMY β€”
7
+ // every colour, size and weight is the Loopable palette (R1's rule for the
8
+ // builder, applied here for the same reason).
9
+ //
10
+ // β›” THIS PAGE IS CHROME, NOT A GRANTED SURFACE, and the distinction is the one
11
+ // the shell's oldest law turns on (`Shell.tsx` :1039 β€” "the nav is
12
+ // server-filtered and an undeclared surface is denied"). Home does not violate
13
+ // that law because it cannot: every database it names is resolved from the
14
+ // `entries` the server returned (`homeModel.groupRecents` drops a recent whose
15
+ // key is not in them), and the four cards open doors the rail already offered.
16
+ // There is no payload here that `GET /nav` did not send.
17
+ //
18
+ // It holds NO state of its own beyond the layout toggle. The recents come down
19
+ // with the nav; the four actions are the frame's, because the frame owns the
20
+ // dialogs and the hash.
21
+ // ---------------------------------------------------------------------------
22
+
23
+ import { useEffect, useState } from "react";
24
+ import { FolderMark } from "../customer-grid/icons";
25
+ import { dbChipClass } from "../shell/nav";
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
+ //
36
+ // Drawn here, in the same 16x16 stroke vocabulary as the rail's `DbIcon`/`AutoIcon`/`BellIcon`
37
+ // β€” the established pattern in this tree (the shell and the alerts pane each draw their own
38
+ // bell rather than sharing an icon module). DESIGN.md's rule is "extend the set, don't import a
39
+ // new icon language", and these are the same language: 16x16, `currentColor` strokes, no fills,
40
+ // no emoji.
41
+
42
+ /** Templates β€” stacked sheets, the thing a template gives you. */
43
+ function TemplateIcon() {
44
+ return (
45
+ <svg className="home-card-icon" viewBox="0 0 16 16" aria-hidden="true">
46
+ <rect x="2.2" y="4.4" width="11.6" height="9.2" rx="1.4" />
47
+ <path d="M4.4 4.4V2.6h9.4v9.2h-1.8M2.2 7.6h11.6" />
48
+ </svg>
49
+ );
50
+ }
51
+
52
+ /** A blank database β€” the rail's cylinder with the plus that makes one. */
53
+ function NewDbIcon() {
54
+ return (
55
+ <svg className="home-card-icon" viewBox="0 0 16 16" aria-hidden="true">
56
+ <ellipse cx="6.6" cy="3.7" rx="4.4" ry="1.8" />
57
+ <path d="M2.2 3.7v6.6c0 1 2 1.8 4.4 1.8" />
58
+ <path d="M11 3.7v3.1" />
59
+ <path d="M11.6 10.4v4M9.6 12.4h4" />
60
+ </svg>
61
+ );
62
+ }
63
+
64
+ /** An automated database β€” two nodes and the edge between them, the rail's `AutoIcon` family. */
65
+ function AutomatedIcon() {
66
+ return (
67
+ <svg className="home-card-icon" viewBox="0 0 16 16" aria-hidden="true">
68
+ <rect x="1.9" y="5.4" width="4.6" height="5.2" rx="1.1" />
69
+ <rect x="9.5" y="5.4" width="4.6" height="5.2" rx="1.1" />
70
+ <path d="M6.5 8h3" />
71
+ </svg>
72
+ );
73
+ }
74
+
75
+ /** Connect a source β€” two links of a chain, which is what a connector is. */
76
+ function ConnectIcon() {
77
+ return (
78
+ <svg className="home-card-icon" viewBox="0 0 16 16" aria-hidden="true">
79
+ <path d="M6.7 9.3 9.3 6.7" />
80
+ <path d="M7.6 4.6 9.1 3.1a2.7 2.7 0 0 1 3.8 3.8l-1.5 1.5" />
81
+ <path d="M8.4 11.4l-1.5 1.5a2.7 2.7 0 0 1-3.8-3.8l1.5-1.5" />
82
+ </svg>
83
+ );
84
+ }
85
+
86
+ /** The two layout marks: rows, and a 2x2 of tiles. The reference pair, in our stroke weight. */
87
+ function ListIcon() {
88
+ return (
89
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="home-layout-icon">
90
+ <path d="M2.6 4.4h10.8M2.6 8h10.8M2.6 11.6h10.8" />
91
+ </svg>
92
+ );
93
+ }
94
+
95
+ function GridIcon() {
96
+ return (
97
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="home-layout-icon">
98
+ <rect x="2.5" y="2.5" width="4.6" height="4.6" rx="1" />
99
+ <rect x="8.9" y="2.5" width="4.6" height="4.6" rx="1" />
100
+ <rect x="2.5" y="8.9" width="4.6" height="4.6" rx="1" />
101
+ <rect x="8.9" y="8.9" width="4.6" height="4.6" rx="1" />
102
+ </svg>
103
+ );
104
+ }
105
+
106
+ /**
107
+ * One quick-start card. A `<button>` β€” every one of these opens a dialog or a wizard rather
108
+ * than navigating, and a link that does not link is a lie the browser's status bar tells.
109
+ *
110
+ * ⚠ `type="button"` and the UA reset ride the CLASS (DESIGN.md 4's button rule: a styled
111
+ * `<button>` sets `border/background/font/color` in its base rule, or it leaks the user agent's
112
+ * chrome β€” the wave-19 item-3 "mystery outer lines and tinted fill").
113
+ */
114
+ function QuickCard({
115
+ icon,
116
+ title,
117
+ detail,
118
+ onClick,
119
+ }: {
120
+ icon: React.ReactNode;
121
+ title: string;
122
+ /** ONE line. R13: the app does not narrate itself, and this is a passing-through surface. */
123
+ detail: string;
124
+ onClick: () => void;
125
+ }) {
126
+ return (
127
+ <button type="button" className="home-card" onClick={onClick}>
128
+ <span className="home-card-head">
129
+ {icon}
130
+ <span className="home-card-title">{title}</span>
131
+ </span>
132
+ <span className="home-card-detail">{detail}</span>
133
+ </button>
134
+ );
135
+ }
136
+
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 {
172
+ return parseLayout(localStorage.getItem(HOME_LAYOUT_KEY));
173
+ } catch {
174
+ return "grid";
175
+ }
176
+ });
177
+ useEffect(() => {
178
+ try {
179
+ localStorage.setItem(HOME_LAYOUT_KEY, layout);
180
+ } catch {
181
+ // storage can be blocked; the toggle still works for this session
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">
196
+ <h1 className="home-title">Home</h1>
197
+
198
+ <div className="home-cards">
199
+ {/* ⚠ THE DETAIL LINES ARE BYTE-IDENTICAL TO THE DIALOG'S ROWS, and that is deliberate
200
+ rather than lazy. Each of these cards opens the same door as a row in the
201
+ New-database dialog, and the first draft described the same two things in four
202
+ slightly different sentences ("fills and keeps up to date" vs "creates and keeps up
203
+ to date"; "ready-made views" vs "a curated set of views"). Two words for one thing is
204
+ how a reader concludes they are two things β€” DESIGN.md 1's "variety is a defect".
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"
221
+ detail="Add a curated set of views to a database you already have."
222
+ onClick={onTemplates}
223
+ />
224
+ <QuickCard
225
+ icon={<NewDbIcon />}
226
+ title="New database"
227
+ detail="A blank database in this workspace."
228
+ onClick={onNewDatabase}
229
+ />
230
+ <QuickCard
231
+ icon={<AutomatedIcon />}
232
+ title="Automated database"
233
+ detail="A database an automation creates and keeps up to date."
234
+ onClick={onAutomated}
235
+ />
236
+ <QuickCard
237
+ icon={<ConnectIcon />}
238
+ title="Connect a source"
239
+ detail="Browse the connectors this workspace can use."
240
+ onClick={onConnectors}
241
+ />
242
+ </div>
243
+
244
+ <div className="home-recents-bar">
245
+ {/* The reference puts an "Opened anytime" filter here. We do not have one and do not
246
+ pretend to: a control that filters nothing is worse than no control. The toggle is
247
+ the real affordance, so it sits alone. */}
248
+ <div className="home-layout-toggle" role="group" aria-label="Layout">
249
+ <button
250
+ type="button"
251
+ className={"home-layout-btn" + (layout === "list" ? " is-on" : "")}
252
+ aria-pressed={layout === "list"}
253
+ aria-label="List"
254
+ title="List"
255
+ onClick={() => setLayout("list")}
256
+ >
257
+ <ListIcon />
258
+ </button>
259
+ <button
260
+ type="button"
261
+ className={"home-layout-btn" + (layout === "grid" ? " is-on" : "")}
262
+ aria-pressed={layout === "grid"}
263
+ aria-label="Grid"
264
+ title="Grid"
265
+ onClick={() => setLayout("grid")}
266
+ >
267
+ <GridIcon />
268
+ </button>
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}>
288
+ {section.tiles.map((tile) => (
289
+ <a
290
+ key={tile.key}
291
+ className="home-tile"
292
+ href={tile.href}
293
+ {...(tile.external ? { target: "_blank", rel: "noreferrer" } : {})}
294
+ >
295
+ {/* The SAME chip family as the database header and the rail row
296
+ (`dbChipClass` β†’ `.shell-db-chip` + its tone), so a database looks like
297
+ itself everywhere. DESIGN.md 4: new elements join the existing rhythm,
298
+ never a new control shape. The chosen mark wins when there is one; two
299
+ letters otherwise, which is what the reference tiles show.
300
+
301
+ β›” AND THOSE TWO BRANCHES CARRY A CONTRAST RULE β€” DO NOT "SIMPLIFY" THEM
302
+ APART. `dbChipClass` returns a TONE class only when there IS an icon, and
303
+ an icon is exactly when we draw a GLYPH. That matters because the tones are
304
+ measured for a graphical object, not for text: white on `--lp-blue-deep` is
305
+ 3.29:1 (the stylesheet publishes every pairing beside its declaration) β€”
306
+ over the 3:1 bar a 16px glyph must clear, UNDER the 4.5:1 bar 12px letters
307
+ must. The fallback branch has no icon, so it takes the BASE chip
308
+ (`--lp-primary`, 7.71:1) and that is where the letters go. Forcing a tone
309
+ onto the initials, or letters onto a toned chip, would put 12px text at
310
+ 3.29:1 on screen. The two branches agree by construction; keep them
311
+ agreeing. */}
312
+ <span className={dbChipClass(tile.icon) + " home-tile-chip"} aria-hidden="true">
313
+ {tile.icon ? <FolderMark icon={tile.icon} size={16} /> : tile.initials}
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
+ ))}
326
+ </div>
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/TemplatePicker.tsx ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // home/TemplatePicker.tsx β€” WAVE 23 item 7 (R10, contract C12, wiring W23-W6).
3
+ //
4
+ // A template is a bundle of SAVED VIEWS applied to a database you already have β€”
5
+ // it does not create a table. So the picker asks two questions in the order a
6
+ // person actually answers them: WHICH DATABASE, then WHICH TEMPLATE. The second
7
+ // list is a function of the first, because the server filters templates by the
8
+ // target's real columns (`view_templates.missing_columns`), and offering one the
9
+ // apply door would refuse is a control that lies.
10
+ //
11
+ // It renders inside the New-database dialog's "From a template" mode rather than
12
+ // as a third modal: one dialog, several doors (DESIGN.md Β§4 β€” new elements join
13
+ // the existing rhythm).
14
+ // ---------------------------------------------------------------------------
15
+
16
+ import { useEffect, useState } from "react";
17
+ import { API_V1, CREDENTIALS } from "../apiContract";
18
+ import type { NavEntry } from "../shell/nav";
19
+
20
+ /** One row of `GET /templates?table=` β€” the server's vocabulary, read as strings (the wave-9
21
+ * law: no client union over a server list). */
22
+ interface TemplateRow {
23
+ key: string;
24
+ label: string;
25
+ desc: string;
26
+ source: string;
27
+ views: number;
28
+ alert: boolean;
29
+ }
30
+
31
+ type Load =
32
+ | { phase: "idle" }
33
+ | { phase: "loading" }
34
+ | { phase: "ready"; rows: TemplateRow[] }
35
+ | { phase: "error"; message: string };
36
+
37
+ function parseRows(body: unknown): TemplateRow[] {
38
+ const raw = (body as { templates?: unknown } | null)?.templates;
39
+ if (!Array.isArray(raw)) return [];
40
+ const out: TemplateRow[] = [];
41
+ for (const item of raw) {
42
+ if (!item || typeof item !== "object") continue;
43
+ const t = item as Record<string, unknown>;
44
+ const key = typeof t.key === "string" ? t.key : "";
45
+ const label = typeof t.label === "string" ? t.label : "";
46
+ if (!key || !label) continue;
47
+ out.push({
48
+ key,
49
+ label,
50
+ desc: typeof t.desc === "string" ? t.desc : "",
51
+ source: typeof t.source === "string" ? t.source : "",
52
+ views: typeof t.views === "number" ? t.views : 0,
53
+ alert: t.alert === true,
54
+ });
55
+ }
56
+ return out;
57
+ }
58
+
59
+ export default function TemplatePicker({
60
+ entries,
61
+ onToast,
62
+ onDone,
63
+ }: {
64
+ /** The databases this session may open β€” the shaped, server-filtered nav, minus Automation. */
65
+ entries: NavEntry[];
66
+ onToast: (message: string) => void;
67
+ /** Applied: close the dialog and open the database, where the new views now are. */
68
+ onDone: (tableKey: string) => void;
69
+ }) {
70
+ // Only real destinations: a group head is a folder label with no table behind it.
71
+ const tables = entries.filter((e) => e.kind === "native");
72
+ const [table, setTable] = useState(tables[0]?.key ?? "");
73
+ const [load, setLoad] = useState<Load>({ phase: "idle" });
74
+ const [busy, setBusy] = useState("");
75
+
76
+ useEffect(() => {
77
+ if (!table) {
78
+ setLoad({ phase: "ready", rows: [] });
79
+ return;
80
+ }
81
+ let dead = false;
82
+ setLoad({ phase: "loading" });
83
+ void (async () => {
84
+ try {
85
+ const res = await fetch(
86
+ `${API_V1}/templates?table=${encodeURIComponent(table)}`,
87
+ { credentials: CREDENTIALS }
88
+ );
89
+ const body = (await res.json().catch(() => null)) as
90
+ | { error?: { message?: string } }
91
+ | null;
92
+ if (dead) return;
93
+ if (!res.ok) {
94
+ setLoad({
95
+ phase: "error",
96
+ message: body?.error?.message || `The server answered ${res.status}.`,
97
+ });
98
+ return;
99
+ }
100
+ setLoad({ phase: "ready", rows: parseRows(body) });
101
+ } catch {
102
+ if (!dead) setLoad({ phase: "error", message: "Cannot reach the server." });
103
+ }
104
+ })();
105
+ return () => {
106
+ dead = true;
107
+ };
108
+ }, [table]);
109
+
110
+ const apply = (key: string) => {
111
+ setBusy(key);
112
+ void (async () => {
113
+ try {
114
+ const res = await fetch(
115
+ `${API_V1}/templates/${encodeURIComponent(key)}/apply`,
116
+ {
117
+ method: "POST",
118
+ credentials: CREDENTIALS,
119
+ headers: { "Content-Type": "application/json" },
120
+ body: JSON.stringify({ table }),
121
+ }
122
+ );
123
+ const body = (await res.json().catch(() => null)) as
124
+ | { views?: { name?: string }[]; alerted?: boolean; error?: { message?: string } }
125
+ | null;
126
+ setBusy("");
127
+ if (!res.ok) {
128
+ // ⚠ THE SERVER'S SENTENCE, VERBATIM. A refusal here names the COLUMNS the target is
129
+ // missing, which is the only thing that tells the reader they picked the wrong
130
+ // database β€” replacing it with "could not apply" would throw that away.
131
+ onToast(body?.error?.message || `The server answered ${res.status}.`);
132
+ return;
133
+ }
134
+ const n = (body?.views ?? []).length;
135
+ onToast(
136
+ `${n} view${n === 1 ? "" : "s"} added.` +
137
+ (body?.alerted ? " An alert is now watching the first one." : "")
138
+ );
139
+ onDone(table);
140
+ } catch {
141
+ setBusy("");
142
+ onToast("Cannot reach the server.");
143
+ }
144
+ })();
145
+ };
146
+
147
+ // β›” A WORKSPACE WITH NO DATABASES IS NOT "NO TEMPLATE FITS". Without this branch the select
148
+ // renders empty, `table` is "", the fetch is skipped, and the reader is told
149
+ // "No template fits this database's columns." about a database they do not have β€” a false
150
+ // sentence, on the FIRST thing a brand-new workspace can click (Home's "Start with templates"
151
+ // card sits on exactly the empty state the tenant hero used to own). The distinction is the
152
+ // same one the Database flyout already makes between a search that matched nothing and a
153
+ // workspace that holds nothing; this branch is the third place it has to be made.
154
+ if (tables.length === 0) {
155
+ return (
156
+ <p className="home-tpl-note">
157
+ A template adds views to a database. Create one first β€” "Blank" above.
158
+ </p>
159
+ );
160
+ }
161
+
162
+ return (
163
+ <div className="home-tpl">
164
+ <label className="home-tpl-target">
165
+ <span className="home-tpl-label">Apply to</span>
166
+ {/* ⚠ A `<select>` MUST CARRY ITS VALUE. A select rendered without one shows its FIRST
167
+ option while the state says something else β€” the wave-22 scar ([[cg-condition-builder-items]]);
168
+ the control then reads as "customer_data" and applies to whatever `table` happens to
169
+ hold. Bound, not defaulted. */}
170
+ <select
171
+ className="home-tpl-select"
172
+ value={table}
173
+ onChange={(e) => setTable(e.target.value)}
174
+ >
175
+ {tables.map((t) => (
176
+ <option key={t.key} value={t.key}>
177
+ {t.label}
178
+ </option>
179
+ ))}
180
+ </select>
181
+ </label>
182
+
183
+ {load.phase === "loading" ? (
184
+ <div className="home-tpl-note">
185
+ <span className="lp-spin" role="status" aria-label="Loading" />
186
+ </div>
187
+ ) : null}
188
+ {load.phase === "error" ? <p className="shell-newdb-err">{load.message}</p> : null}
189
+ {load.phase === "ready" && load.rows.length === 0 ? (
190
+ // ONE line (R13). And it says the RIGHT thing: nothing fits THIS database, which is not
191
+ // the same as "there are no templates".
192
+ <p className="home-tpl-note">No template fits this database's columns.</p>
193
+ ) : null}
194
+
195
+ {load.phase === "ready" && load.rows.length > 0 ? (
196
+ <ul className="home-tpl-list">
197
+ {load.rows.map((row) => (
198
+ <li key={row.key} className="home-tpl-row">
199
+ <span className="home-tpl-text">
200
+ <span className="home-tpl-name">{row.label}</span>
201
+ <span className="home-tpl-desc">{row.desc}</span>
202
+ </span>
203
+ <button
204
+ type="button"
205
+ className="login-submit home-tpl-apply"
206
+ disabled={!!busy}
207
+ onClick={() => apply(row.key)}
208
+ >
209
+ {busy === row.key ? "Adding…" : `Add ${row.views}`}
210
+ </button>
211
+ </li>
212
+ ))}
213
+ </ul>
214
+ ) : null}
215
+ </div>
216
+ );
217
+ }
web/src/home/homeModel.ts ADDED
@@ -0,0 +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
+ /* β›” `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