fsanyoto commited on
Commit
aac1dbd
Β·
verified Β·
1 Parent(s): cb09fd0

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "446ffb3",
3
  "releases": [
4
  {
5
  "version": "v13",
 
1
  {
2
+ "current": "b7dd2ff",
3
  "releases": [
4
  {
5
  "version": "v13",
VERSION CHANGED
@@ -1 +1 @@
1
- 446ffb3
 
1
+ b7dd2ff
api/automation_engine.py CHANGED
@@ -4047,8 +4047,26 @@ def run_discover_instagram(rt, defn, username="automation", log=print, step=_no_
4047
  # minutes; holding a worker thread that long on a free-tier container to poll would be
4048
  # the wrong shape. Say plainly that it is still running and who collects it.
4049
  steps["collect"] = "partial"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4050
  return ("partial",
4051
- "Still searching β€” this takes about 20 minutes. The next run picks up the results; nothing is lost and you are not charged twice", counts, [], steps)
 
 
 
 
4052
  if status == "empty":
4053
  # A search that matched nothing RAN CORRECTLY. It is the ordinary result of a keyword
4054
  # that is too specific, so it says what to do about it instead of reporting a fault.
@@ -5156,6 +5174,61 @@ def review_actions(defn):
5156
  and a.get("enabled", True)]
5157
 
5158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5159
  def interpolate(text, row):
5160
  """`{{field_key}}` β†’ the record's value. Unknown keys resolve to EMPTY, deliberately: an
5161
  action that wrote the literal `{{status}}` into a cell because somebody typo'd the key would
@@ -5257,26 +5330,65 @@ def stages_for(defn):
5257
  # gate records at a place the kanban cannot show, which is the whole complaint the board was
5258
  # built to answer. Its declared exits become assignable stages too β€” a gate with nowhere to
5259
  # go is a hole records fall into.
 
 
 
 
 
 
 
 
 
 
 
5260
  tail = max((s["col"] for s in stages), default=0)
5261
- for i, act in enumerate(review_actions(defn)):
 
5262
  acfg = act.get("config") or {}
5263
  rid = act["id"]
5264
- stages.append({"id": rid, "label": acfg.get("label") or "Review", "kind": "review",
5265
- "col": tail + 1 + (i * 2), "row": 0, "enabled": True, "toggle": "",
5266
- "status": "idle", "panel": "review_action", "posture": "strict",
 
 
 
 
 
 
 
 
 
 
5267
  "record": True, "assignable": True, "actionId": rid,
5268
- "decidedBy": acfg.get("decidedBy") or "user",
5269
- "detail": ("An AI decides where each card goes β€” a person can override it"
5270
- if acfg.get("decidedBy") == "ai"
5271
- else "Cards wait here for a person to move them on")})
5272
- for j, label in enumerate(acfg.get("next") or []):
 
 
 
 
 
 
5273
  oid = f"{rid}_out_{j}"
5274
- stages.append({"id": oid, "label": label, "kind": "action",
5275
- "col": tail + 2 + (i * 2), "row": j, "enabled": True, "toggle": "",
 
 
5276
  "status": "idle", "panel": "review_action", "posture": "auto",
5277
  "record": True, "assignable": True, "actionId": rid,
5278
- "detail": f"Where {acfg.get('label') or 'Review'} sends a card"})
5279
- routes.append({"from": rid, "to": oid, "label": label, "condition": None})
 
 
 
 
 
 
 
 
 
5280
  return stages, routes
5281
 
5282
 
@@ -5391,10 +5503,31 @@ def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print
5391
  if not rows:
5392
  return counts
5393
  stages, routes = stages_for(defn)
 
 
 
 
 
 
 
 
5394
  skey = stage_field_key(defn.get("id"))
5395
  stamp = _iso()
5396
  patches, creates, ai_budget = {}, {}, [AI_DECISIONS_PER_RUN]
5397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5398
  def _walk(acts, row, rid, depth=0):
5399
  """Returns True when the record was SUSPENDED (a review holds it)."""
5400
  for act in acts:
@@ -5405,6 +5538,8 @@ def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print
5405
  kind = act.get("kind")
5406
  cfg = act.get("config") or {}
5407
  counts["actionsRun"] += 1
 
 
5408
  if kind == "group":
5409
  # ⭐ WAVE 24 Β· C-FORK β€” FIRST MATCHING BRANCH WINS, and only that one runs.
5410
  # Declaration order is priority order, the same rule `route_record` applies to
@@ -5489,6 +5624,14 @@ def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print
5489
  # a card could never leave a flow that runs on a schedule. Found by this
5490
  # wave's own terminal-ending negative control, which is the argument for
5491
  # writing the NC in the same change as the feature.
 
 
 
 
 
 
 
 
5492
  continue
5493
  decided = ""
5494
  if cfg.get("decidedBy") == "ai" and ai_budget[0] > 0:
@@ -5499,6 +5642,11 @@ def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print
5499
  _act_row_patch(patches, table, rid,
5500
  {skey: decided, skey + "_at": stamp})
5501
  row[skey] = decided
 
 
 
 
 
5502
  continue # the AI moved it on β€” keep walking
5503
  _act_row_patch(patches, table, rid, {skey: label, skey + "_at": stamp})
5504
  row[skey] = label
@@ -5514,6 +5662,18 @@ def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print
5514
  continue
5515
  if _walk(actions, row, str(rid)):
5516
  held.append(str(rid))
 
 
 
 
 
 
 
 
 
 
 
 
5517
  counts.update(_enrich_flush(rt, defn, username, enrich, log))
5518
  counts["cycles"] = _apply_ending(rt, defn, table, rows, patches, stages, routes, stamp)
5519
  # ⭐ C5: the REALIZED numbers overwrite the walk's attempt count. `counts["created"]` was
@@ -5789,11 +5949,19 @@ def _commit_action_writes(rt, table, patches, creates, username, log):
5789
  "createCapped": 0, "createSkipped": 0}
5790
  if not patches and not creates:
5791
  return out
 
 
 
 
 
 
 
 
5792
  for tkey, rowpatch in (patches or {}).items():
5793
  cur = dict((ut_get(rt, tkey) or {}).get("rows") or {})
5794
  for rid, vals in rowpatch.items():
5795
  cur[str(rid)] = {**(cur.get(str(rid)) or {}), **vals}
5796
- ut_write_rows(rt, tkey, cur)
5797
  # β›” ONE WRITE PER TABLE, even when several actions target it under different keys. The
5798
  # accumulator is keyed by (table, uniqueOn), so a naive loop would call `ut_write_rows` once
5799
  # per GROUP β€” two store commits for one table, against the 20 s flush floor and the 256/hr
@@ -5808,7 +5976,10 @@ def _commit_action_writes(rt, table, patches, creates, username, log):
5808
  log(f"[aios-auto] create_record: {tkey} no longer exists β€” {n} skipped")
5809
  out["createSkipped"] += n
5810
  continue
5811
- cur = dict(t.get("rows") or {})
 
 
 
5812
  cap = row_cap(tkey)
5813
  for unique, new_rows in groups:
5814
  if unique:
@@ -5839,6 +6010,11 @@ def _commit_action_writes(rt, table, patches, creates, username, log):
5839
  nxt += 1
5840
  out["created"] += 1
5841
  ut_write_rows(rt, tkey, cur)
 
 
 
 
 
5842
  return out
5843
 
5844
 
@@ -7312,6 +7488,33 @@ def run_async(rt, tenant, auto_id, username="automation", log=print, rows=None):
7312
  # THE TICK + the in-process scheduler
7313
  # ---------------------------------------------------------------------------------------------
7314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7315
  def due_ids(rt, now=None):
7316
  """Which of this tenant's automations a tick at `now` should start. Pure over the store."""
7317
  return sorted(aid for aid, d in all_definitions(rt).items() if is_due(d, now))
@@ -7322,7 +7525,10 @@ def tick(rt, tenant, now=None, log=print):
7322
  ids started. The email polls are bounded and fail-quiet per automation β€” one broken
7323
  mailbox connection must not stop the tenant's schedules."""
7324
  started = []
7325
- for aid in due_ids(rt, now):
 
 
 
7326
  if run_async(rt, tenant, aid, username="scheduler", log=log):
7327
  started.append(aid)
7328
  for aid, d in all_definitions(rt).items():
 
4047
  # minutes; holding a worker thread that long on a free-tier container to poll would be
4048
  # the wrong shape. Say plainly that it is still running and who collects it.
4049
  steps["collect"] = "partial"
4050
+ # ⚠ THE SENTENCE NAMES WHO COLLECTS IT, because the old one did not and that is what made
4051
+ # this read as "stuck": *"The next run picks up the results"* is a promise about a run
4052
+ # that, on a MANUAL automation, nobody had scheduled. `pending_collect_ids` makes the tick
4053
+ # finish it, so the promise is now kept by something rather than by the reader.
4054
+ mins = 0
4055
+ try:
4056
+ since = (defn.get("state") or {}).get("pendingSince")
4057
+ if since:
4058
+ mins = max(0, int((_dt.datetime.now(_dt.timezone.utc)
4059
+ - _dt.datetime.fromisoformat(str(since))).total_seconds()
4060
+ // 60))
4061
+ except Exception: # noqa: BLE001
4062
+ mins = 0
4063
+ been = f" β€” {mins} min so far" if mins else ""
4064
  return ("partial",
4065
+ f"Still searching at the provider{been}. A corpus search takes about 20 minutes "
4066
+ f"however few records you asked for: the wait is the SEARCH over 620 million "
4067
+ f"profiles, not the 10 rows. Nothing is lost, you are not charged twice, and the "
4068
+ f"results are collected automatically as soon as they are ready",
4069
+ counts, [], steps)
4070
  if status == "empty":
4071
  # A search that matched nothing RAN CORRECTLY. It is the ordinary result of a keyword
4072
  # that is too specific, so it says what to do about it instead of reporting a fault.
 
5174
  and a.get("enabled", True)]
5175
 
5176
 
5177
+ #: Every action kind's board label, from the ONE catalog the menu is built from β€” so a stage can
5178
+ #: never be named something the builder does not call the step it came from.
5179
+ _ACTION_LABELS = {r["kind"]: r["label"] for r in ACTION_CATALOG}
5180
+
5181
+
5182
+ def board_actions(defn):
5183
+ """⭐ OWNER ITEM 1 (2026-08-06) β€” the actions a card WALKS, in flow order.
5184
+
5185
+ Owner, verbatim: *"the stages should always be based on the Automation Actions path, so we
5186
+ track every card as they go along the automation."* Before this, only `review` actions became
5187
+ stages (wave 23 C4/C6) and everything else was invisible on the board β€” so a discovery flow's
5188
+ kanban showed three columns (`Review`/`Tracked`/`Declined`) that corresponded to no step
5189
+ anybody had added, which is exactly what prompted *"What exactly are those stages?"*.
5190
+
5191
+ β›” THE PINNED DISCOVERY STEP IS EXCLUDED, and it must be: `apply_actions` DROPS `actions[0]`
5192
+ for `discover_instagram` because the runner writes the candidates itself. A column for a step
5193
+ the engine skips could never hold a card β€” a lane that is permanently empty for a structural
5194
+ reason, which is the "green dot over nothing" defect wearing a different hat.
5195
+
5196
+ ⚠ DISABLED ACTIONS ARE EXCLUDED for the same reason and no other: `_walk` skips them, so a
5197
+ card cannot rest there. Switching one back on brings its column back.
5198
+ """
5199
+ flow = (defn or {}).get("flow") or {}
5200
+ acts = list(flow.get("actions") or [])
5201
+ if ig_action_pinned(defn, 0) and acts:
5202
+ acts = acts[1:]
5203
+ out = []
5204
+ for a in walk_actions(acts):
5205
+ if not isinstance(a, dict) or not a.get("enabled", True):
5206
+ continue
5207
+ # A GROUP is a fork, not a place β€” the card is inside one of its branches, never "at" it.
5208
+ if a.get("kind") == "group":
5209
+ continue
5210
+ out.append(a)
5211
+ return out
5212
+
5213
+
5214
+ def action_stage_label(act, taken):
5215
+ """One action's stage label: what the BUILDER calls that step, made unique.
5216
+
5217
+ ⚠ UNIQUE MATTERS MORE THAN PRETTY. `_card_stage` resolves a stored cell back to a stage by
5218
+ LABEL, and `_stage_choices` feeds those labels to a `select` column β€” so two steps sharing a
5219
+ name would produce a duplicated option and a card that could be at either of them. Two
5220
+ `Create record` steps become `Create record` and `Create record (step 2)`.
5221
+ """
5222
+ cfg = act.get("config") or {}
5223
+ base = _s(cfg.get("label") or _ACTION_LABELS.get(act.get("kind")) or act.get("kind"), 40)
5224
+ if base not in taken:
5225
+ return base
5226
+ n = 2
5227
+ while f"{base} (step {n})" in taken:
5228
+ n += 1
5229
+ return f"{base} (step {n})"
5230
+
5231
+
5232
  def interpolate(text, row):
5233
  """`{{field_key}}` β†’ the record's value. Unknown keys resolve to EMPTY, deliberately: an
5234
  action that wrote the literal `{{status}}` into a cell because somebody typo'd the key would
 
5330
  # gate records at a place the kanban cannot show, which is the whole complaint the board was
5331
  # built to answer. Its declared exits become assignable stages too β€” a gate with nowhere to
5332
  # go is a hole records fall into.
5333
+ # ⭐ OWNER ITEM 1 (2026-08-06) β€” EVERY ACTION IS A STAGE, not only the review ones.
5334
+ #
5335
+ # This block used to iterate `review_actions(defn)`. That was wave 23's C4/C6 answer to "a
5336
+ # review has to exist on the board", and it was right as far as it went β€” but it left every
5337
+ # other step invisible, so the board could not answer *where did this card get to*. The
5338
+ # owner's ask is the general form of the same argument: the columns ARE the actions path.
5339
+ #
5340
+ # ⚠ WHAT MAKES THIS HONEST RATHER THAN DECORATIVE is the other half, in `apply_actions`:
5341
+ # a record is STAMPED with the furthest action it reached. Columns nothing ever writes into
5342
+ # would be a picture of a flow rather than a report on it, and the two are told apart only by
5343
+ # whether cards ever appear in them.
5344
  tail = max((s["col"] for s in stages), default=0)
5345
+ col, taken = tail + 1, set()
5346
+ for act in board_actions(defn):
5347
  acfg = act.get("config") or {}
5348
  rid = act["id"]
5349
+ label = action_stage_label(act, taken)
5350
+ taken.add(label)
5351
+ is_review = act.get("kind") == "review"
5352
+ stages.append({"id": rid, "label": label,
5353
+ "kind": "review" if is_review else "action",
5354
+ "col": col, "row": 0, "enabled": True, "toggle": "",
5355
+ "status": "idle",
5356
+ "panel": "review_action" if is_review else "flow_action",
5357
+ # POSTURE IS THE AUDIT RULE, so only a review claims `strict` β€” an
5358
+ # ordinary step is somewhere a card passes through, not a gate somebody
5359
+ # signs off, and marking every column strict would ask for an audited
5360
+ # click on movements nobody decided.
5361
+ "posture": "strict" if is_review else "auto",
5362
  "record": True, "assignable": True, "actionId": rid,
5363
+ **({"decidedBy": acfg.get("decidedBy") or "user"} if is_review else {}),
5364
+ "detail": (
5365
+ ("An AI decides where each card goes β€” a person can override it"
5366
+ if acfg.get("decidedBy") == "ai"
5367
+ else "Cards wait here for a person to move them on")
5368
+ if is_review else
5369
+ f"Cards that reached this step and went no further this run")})
5370
+ col += 1
5371
+ if not is_review:
5372
+ continue
5373
+ for j, nxt in enumerate(acfg.get("next") or []):
5374
  oid = f"{rid}_out_{j}"
5375
+ olabel = nxt if nxt not in taken else f"{nxt} (step {j + 2})"
5376
+ taken.add(olabel)
5377
+ stages.append({"id": oid, "label": olabel, "kind": "action",
5378
+ "col": col, "row": j, "enabled": True, "toggle": "",
5379
  "status": "idle", "panel": "review_action", "posture": "auto",
5380
  "record": True, "assignable": True, "actionId": rid,
5381
+ "detail": f"Where {label} sends a card"})
5382
+ routes.append({"from": rid, "to": oid, "label": nxt, "condition": None})
5383
+ if acfg.get("next"):
5384
+ col += 1
5385
+ # THE PATH IS A PATH: consecutive action stages are joined, so the board reads left-to-right
5386
+ # as the flow does rather than as a row of disconnected columns.
5387
+ walkable = [s for s in stages if s.get("actionId")]
5388
+ for a, b in zip(walkable, walkable[1:]):
5389
+ if a["col"] < b["col"] and not any(
5390
+ r["from"] == a["id"] and r["to"] == b["id"] for r in routes):
5391
+ routes.append({"from": a["id"], "to": b["id"], "label": "", "condition": None})
5392
  return stages, routes
5393
 
5394
 
 
5503
  if not rows:
5504
  return counts
5505
  stages, routes = stages_for(defn)
5506
+ # action id -> its board label, so the walk can stamp without re-deriving names.
5507
+ # ⚠ `s["id"] == s["actionId"]` IS LOAD-BEARING. A review's EXIT stages carry the review's
5508
+ # own `actionId` (that is how the board groups them), so a plain "has an actionId" filter
5509
+ # let the LAST exit win the dict entry β€” and the walk then stamped every reviewed card
5510
+ # with the last option in the list. Measured: an AI that decided `Approved` produced a
5511
+ # card sitting in `Declined`. Only the stage that IS the action may claim its id.
5512
+ stage_label_by_action = {s["actionId"]: s["label"] for s in stages
5513
+ if s.get("actionId") and s["id"] == s.get("actionId")}
5514
  skey = stage_field_key(defn.get("id"))
5515
  stamp = _iso()
5516
  patches, creates, ai_budget = {}, {}, [AI_DECISIONS_PER_RUN]
5517
 
5518
+ # ⭐ OWNER ITEM 1 (2026-08-06) β€” WHERE EACH CARD GOT TO. `stages_for` now makes every action a
5519
+ # board column; this is what puts cards in them. Keyed by row id, holding the LABEL of the
5520
+ # furthest action that record reached this run, flushed once per record after the walk.
5521
+ #
5522
+ # β›” ONE STAMP PER RECORD, NOT ONE PER ACTION. Writing at each step would put N patches on the
5523
+ # same cell in a single run and land the same final value, at N times the cost β€” and on a
5524
+ # flood-limited walk over thousands of rows that is the difference between a run and a
5525
+ # timeout. The last value is the only one that was ever going to survive.
5526
+ #
5527
+ # ⚠ A REVIEW STAMPS ITSELF AND RETURNS (see its branch), so it must WIN over this: it is a
5528
+ # HOLD, and overwriting it with the step before would release a card nobody decided on.
5529
+ reached = {}
5530
+
5531
  def _walk(acts, row, rid, depth=0):
5532
  """Returns True when the record was SUSPENDED (a review holds it)."""
5533
  for act in acts:
 
5538
  kind = act.get("kind")
5539
  cfg = act.get("config") or {}
5540
  counts["actionsRun"] += 1
5541
+ if kind != "group" and act.get("id") in stage_label_by_action:
5542
+ reached[rid] = stage_label_by_action[act["id"]]
5543
  if kind == "group":
5544
  # ⭐ WAVE 24 Β· C-FORK β€” FIRST MATCHING BRANCH WINS, and only that one runs.
5545
  # Declaration order is priority order, the same rule `route_record` applies to
 
5624
  # a card could never leave a flow that runs on a schedule. Found by this
5625
  # wave's own terminal-ending negative control, which is the argument for
5626
  # writing the NC in the same change as the feature.
5627
+ #
5628
+ # β›” AND THE CARD IS AT ITS OWN EXIT, NOT AT THIS GATE (owner item 1,
5629
+ # 2026-08-06). The end-of-walk stamp records the furthest ACTION a record
5630
+ # reached, and the action here is the REVIEW β€” so without this line a card
5631
+ # resting in `Done` is stamped back to `Gate` on the next scheduled run, and
5632
+ # walks backwards through the flow forever. The very same negative control
5633
+ # caught it, which is the second time this branch has been paid for by it.
5634
+ reached[rid] = at
5635
  continue
5636
  decided = ""
5637
  if cfg.get("decidedBy") == "ai" and ai_budget[0] > 0:
 
5642
  _act_row_patch(patches, table, rid,
5643
  {skey: decided, skey + "_at": stamp})
5644
  row[skey] = decided
5645
+ # β›” THE DECISION IS THE LANDING. Without this the end-of-walk stamp would
5646
+ # overwrite the stage the AI just chose with the REVIEW's own label β€”
5647
+ # silently un-deciding it, on the one path where a machine had already
5648
+ # committed to an answer.
5649
+ reached[rid] = decided
5650
  continue # the AI moved it on β€” keep walking
5651
  _act_row_patch(patches, table, rid, {skey: label, skey + "_at": stamp})
5652
  row[skey] = label
 
5662
  continue
5663
  if _walk(actions, row, str(rid)):
5664
  held.append(str(rid))
5665
+ continue
5666
+ # ⭐ OWNER ITEM 1 β€” the card lands on the furthest step it reached. Skipped for a HELD
5667
+ # record (the `continue` above): its review already stamped its own label and holding
5668
+ # it is the point, so writing the step before would quietly release it.
5669
+ #
5670
+ # ⚠ ONLY WHEN IT MOVED. Re-stamping the label a row already carries would mark the
5671
+ # cell dirty on every scheduled run β€” the store commits it, the grid repaints it, and
5672
+ # `stage_moved` tells every open browser to re-read β€” for a value that did not change.
5673
+ landed = reached.get(str(rid))
5674
+ if landed and str(row.get(skey) or "").strip() != landed:
5675
+ _act_row_patch(patches, table, str(rid),
5676
+ {skey: landed, skey + "_at": stamp})
5677
  counts.update(_enrich_flush(rt, defn, username, enrich, log))
5678
  counts["cycles"] = _apply_ending(rt, defn, table, rows, patches, stages, routes, stamp)
5679
  # ⭐ C5: the REALIZED numbers overwrite the walk's attempt count. `counts["created"]` was
 
5949
  "createCapped": 0, "createSkipped": 0}
5950
  if not patches and not creates:
5951
  return out
5952
+ # ⭐ PATCHES ARE STAGED, NOT WRITTEN YET (2026-08-06). They used to commit here, one
5953
+ # `ut_write_rows` per patched table, and that was free while the only patcher was a review
5954
+ # gate on a table no create action touched. Owner item 1 stamps EVERY walked record with the
5955
+ # step it reached, so the flow's own table is now patched on essentially every run β€” and a
5956
+ # flow that also creates into that same table would have committed it TWICE per run, against
5957
+ # the 20 s flush floor and the 256-commits/hr repo budget this module is shaped around.
5958
+ # Staged into `staged` and handed to the creates pass, which writes each table exactly once.
5959
+ staged = {}
5960
  for tkey, rowpatch in (patches or {}).items():
5961
  cur = dict((ut_get(rt, tkey) or {}).get("rows") or {})
5962
  for rid, vals in rowpatch.items():
5963
  cur[str(rid)] = {**(cur.get(str(rid)) or {}), **vals}
5964
+ staged[str(tkey)] = cur
5965
  # β›” ONE WRITE PER TABLE, even when several actions target it under different keys. The
5966
  # accumulator is keyed by (table, uniqueOn), so a naive loop would call `ut_write_rows` once
5967
  # per GROUP β€” two store commits for one table, against the 20 s flush floor and the 256/hr
 
5976
  log(f"[aios-auto] create_record: {tkey} no longer exists β€” {n} skipped")
5977
  out["createSkipped"] += n
5978
  continue
5979
+ # The PATCHED rows when this table was also stamped this run, so the creates land on top
5980
+ # of the stamp rather than on a copy of the store that predates it.
5981
+ cur = staged.pop(tkey, None)
5982
+ cur = dict(t.get("rows") or {}) if cur is None else cur
5983
  cap = row_cap(tkey)
5984
  for unique, new_rows in groups:
5985
  if unique:
 
6010
  nxt += 1
6011
  out["created"] += 1
6012
  ut_write_rows(rt, tkey, cur)
6013
+ # Whatever the creates pass did NOT claim: tables this run only STAMPED. Written last and
6014
+ # once each, so "one store write per table" holds whether a table was patched, created into,
6015
+ # or both.
6016
+ for tkey, cur in staged.items():
6017
+ ut_write_rows(rt, tkey, cur)
6018
  return out
6019
 
6020
 
 
7488
  # THE TICK + the in-process scheduler
7489
  # ---------------------------------------------------------------------------------------------
7490
 
7491
+ def pending_collect_ids(rt):
7492
+ """⭐ 2026-08-06 β€” automations holding a snapshot the vendor is still building.
7493
+
7494
+ β›” THE DEFECT THIS CLOSES, reported live: *"why is the SMALL 10 records test search taking
7495
+ forever, its not populating"*. A corpus search takes ~20 minutes, so the run hands off and
7496
+ stores `pendingSnapshot` with the summary *"The next run picks up the results"* β€” which is
7497
+ true only if there IS a next run. The owner's automation is MANUAL (`schedule.enabled` false),
7498
+ so `due_ids` never returns it, nothing ever collected it, and the results the account had
7499
+ already been charged for sat ready at the vendor forever. The sentence was not wrong; it was
7500
+ describing a run nobody had scheduled.
7501
+
7502
+ A pending snapshot is unfinished work the tenant has already paid for, so the tick finishes it
7503
+ regardless of schedule. Independent of `due_ids` on purpose β€” a schedule says *start something
7504
+ new*, this says *collect what is already running*, and folding the second into the first would
7505
+ make an unscheduled automation's paid result depend on someone remembering to press a button.
7506
+ """
7507
+ out = []
7508
+ for aid, d in all_definitions(rt).items():
7509
+ if not isinstance(d, dict) or d.get("kind") != "discover_instagram":
7510
+ continue
7511
+ if (d.get("trigger") or {}).get("paused"):
7512
+ continue
7513
+ if str((d.get("state") or {}).get("pendingSnapshot") or "").strip():
7514
+ out.append(aid)
7515
+ return sorted(out)
7516
+
7517
+
7518
  def due_ids(rt, now=None):
7519
  """Which of this tenant's automations a tick at `now` should start. Pure over the store."""
7520
  return sorted(aid for aid, d in all_definitions(rt).items() if is_due(d, now))
 
7525
  ids started. The email polls are bounded and fail-quiet per automation β€” one broken
7526
  mailbox connection must not stop the tenant's schedules."""
7527
  started = []
7528
+ # ⭐ COLLECT-FIRST (2026-08-06). A snapshot the vendor has finished building is a result the
7529
+ # tenant has already been charged for; it is collected whether or not this automation is on a
7530
+ # schedule. `_claim` makes the union safe β€” an id in both lists starts once.
7531
+ for aid in dict.fromkeys(list(pending_collect_ids(rt)) + list(due_ids(rt, now))):
7532
  if run_async(rt, tenant, aid, username="scheduler", log=log):
7533
  started.append(aid)
7534
  for aid, d in all_definitions(rt).items():
platform/core/grid_events.py CHANGED
@@ -1817,6 +1817,29 @@ def handle_one(event, ctx):
1817
  stage_moved = True # cells the client never typed changed: re-read
1818
  row_events.append((key, _pw['handle']))
1819
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1820
  # ⭐ WAVE 23 (C7) β€” the json wall, BEFORE the generic 10 000-char truncation, which
1821
  # would otherwise cut a document in half and store the halves as valid text. A json
1822
  # column promises its readers a parseable document; a write that is not one is
 
1817
  stage_moved = True # cells the client never typed changed: re-read
1818
  row_events.append((key, _pw['handle']))
1819
  continue
1820
+ # ⭐ OWNER ITEM 4 (2026-08-06) β€” A COLUMN AN AUTOMATION FILLS IS NOT A COLUMN A
1821
+ # PERSON TYPES IN. Owner, verbatim: *"I should not be able to edit any of the
1822
+ # Pre-set fields on instagram automation, we talked about this extensively."*
1823
+ #
1824
+ # β›” IT HAD NEVER BEEN ENFORCED ANYWHERE. `editRole: 'admins'` rides on every
1825
+ # preset column and reads exactly like this wall, which is why it was believed to
1826
+ # be one β€” but it governs the SCHEMA (`user_tables.py:535`): who may rename or
1827
+ # retype the column. The VALUES stayed open to anyone with grid access, and the
1828
+ # owner typed into one to prove it. The metric branch above is the same rule for
1829
+ # the same reason, written for a different column kind; this is its sibling.
1830
+ #
1831
+ # ⚠ REACHED ONLY AFTER stage AND profile have `continue`d, and the order is the
1832
+ # rule rather than an accident: both of those columns carry the identical tag and
1833
+ # both are cells a human is SUPPOSED to drive β€” the stage because moving a card
1834
+ # IS the decision, the profile because it is where enrichment gets its subject.
1835
+ # Refusing on the tag alone would freeze every kanban.
1836
+ #
1837
+ # `flowId` and not merely `automation`: a user-configured `automation` COLUMN
1838
+ # carries its own gear bag (kind/source/urlField/settings) and no flowId, and it
1839
+ # is not this ruling's subject.
1840
+ if isinstance(_auto, dict) and _auto.get('flowId'):
1841
+ refused = True
1842
+ continue
1843
  # ⭐ WAVE 23 (C7) β€” the json wall, BEFORE the generic 10 000-char truncation, which
1844
  # would otherwise cut a document in half and store the halves as valid text. A json
1845
  # column promises its readers a parseable document; a write that is not one is
web/src/customer-grid/CustomerGrid.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/RecordDetail.tsx CHANGED
@@ -11,7 +11,7 @@ import {
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
@@ -493,12 +493,16 @@ export default function RecordDetail({
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
 
 
11
  } from "./cells";
12
  import JsonViewer from "./JsonViewer";
13
  import { StarRow, StarIcon } from "./Stars";
14
+ import { 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
 
493
  "cg-detail-field" +
494
  (isEdit ? " cg-detail-field--edit" : "") +
495
  (isControl ? " cg-detail-field--control" : "") +
496
+ // β›” NO `is-machine` TINT (owner item 2, 2026-08-06). It followed the grid cell's wash by
497
+ // design β€” "the SAME claim the grid cell makes, on the DOM side" β€” so it follows it out.
498
+ // Keeping the drawer grey while the table stopped being grey would leave the product
499
+ // saying one thing in two places about the same column, which is the sibling-panel rule
500
+ // (DESIGN.md Β§2) broken in the direction nobody notices until they open a record.
501
+ //
502
+ // ⚠ THE CLAIM ITSELF SURVIVES, and more honestly than a tint did: `mayEditField` now
503
+ // refuses a machine-written column (`isMachineWritten`), so the drawer renders it as a
504
+ // READ-ONLY slot rather than "an ordinary editable-looking slot" with a grey wash on it.
505
+ // That was the paragraph's actual worry, and it is now answered by behaviour.
506
  (dropKey === field.key ? " is-dropzone" : "") +
507
  (dragKey === field.key ? " is-dragging" : "");
508
 
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 { isMachineOwned, ratingMax } from "./types";
38
  import {
39
  LP_BLUE_TEXT,
40
  LP_BLUE_TINT,
@@ -44,7 +44,6 @@ import {
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
@@ -398,30 +397,30 @@ export function makeCell(
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,
 
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
  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
 
397
  * username absent from it, paints the initials fallback. */
398
  userAvatars?: Record<string, string>
399
  ): GridCell {
400
+ // β›” NO MACHINE WASH (owner item 2, 2026-08-06): *"Remove the light grey highlight for the
401
+ // column that is supposedly pre-set."* Wave-23 R9 introduced a grey background on every
402
+ // machine-owned cell; on a `ut_*` database that is EVERY column but one, so the grid read as a
403
+ // sea of grey with a white stripe rather than as a table. The fact it was trying to state β€”
404
+ // *something else fills this column* β€” is now stated in WORDS where a reader will meet it
405
+ // (the `Pre-set` chip in Hide fields, `isPresetField`) and enforced where it matters (the
406
+ // cells refuse the edit, `isMachineWritten`). A label beats a tint the reader has to be taught.
407
+ return baseCell(field, v, editable, userAvatars);
408
  }
409
 
410
+ /* β›” THE MACHINE WASH IS RETIRED (owner item 2, 2026-08-06).
411
+
412
+ Wave-23 C8/R9 washed every machine-owned cell grey. On the Customer grid that was a handful
413
+ of columns; on a `ut_*` database it is EVERY column but the identity one, so the owner's
414
+ Instagram table rendered as a grey sheet with one white stripe. `withMachineWash` and
415
+ `theme.machineCellTheme` are deleted with it β€” a composer nothing composes is a subject a gate
416
+ can still go green on ([[gate-answers-the-wrong-question]]), so the precedence assertions that
417
+ guarded it were RETARGETED onto the new law rather than dropped: `makeCell` adds no wash, and
418
+ a machine cell keeps exactly the override it already carried.
419
+
420
+ What replaced the signal, because removing it without replacing it would be a loss:
421
+ Β· the `Pre-set` chip in Hide fields (`isPresetField`) β€” the same word Odoo columns use;
422
+ Β· the custom-field DOT no longer painted on them (they are not yours to edit);
423
+ Β· and the cells genuinely refuse the edit now (`isMachineWritten`), which the wash never did. */
 
 
 
 
 
 
424
 
425
  function baseCell(
426
  field: Field,
web/src/customer-grid/theme.ts CHANGED
@@ -341,33 +341,12 @@ export const COLUMN_TONE_THEME: Record<ControlTone, Partial<Theme>> = {
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
  *
 
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
+ /* β›” `MACHINE_CELL` + `machineCellTheme` DELETED (owner item 2, 2026-08-06): *"Remove the light
345
+ grey highlight for the column that is supposedly pre-set."* The wash said "a machine fills
346
+ this" in a tint the reader had to be taught; the product says it in a word now (the `Pre-set`
347
+ chip) and enforces it at the cell (`isMachineWritten`). `LP_MACHINE_DEEP`/`LP_MACHINE_TINT`
348
+ above stay β€” they are palette entries mirrored by `verify_icons`' I7c parity, and deleting one
349
+ side of a mirrored pair is how that gate goes red for a reason unrelated to any defect. */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
350
 
351
  /* wave17 GRID β€” item 2 / owner R5: **THE ALTERNATING ROW BANDS ARE DEAD.**
352
  *
web/src/customer-grid/types.ts CHANGED
@@ -971,6 +971,12 @@ export interface Viewer {
971
  */
972
  export function mayEditField(field: Field, viewer: Viewer | undefined): boolean {
973
  if (field.source !== "overlay" || READONLY_CELL_TYPES.has(field.type)) return false;
 
 
 
 
 
 
974
  const edit = field.permissions?.edit ?? "everyone";
975
  if (edit === "everyone") return true;
976
  if (!viewer) return false;
@@ -1007,6 +1013,53 @@ 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 β€”
 
971
  */
972
  export function mayEditField(field: Field, viewer: Viewer | undefined): boolean {
973
  if (field.source !== "overlay" || READONLY_CELL_TYPES.has(field.type)) return false;
974
+ // ⭐ OWNER ITEM 4 (2026-08-06) β€” a column an automation FILLS is not a column a person types
975
+ // in. `editRole: 'admins'` already rode on every preset column and did nothing about this: it
976
+ // governs the SCHEMA (`user_tables.py:535`), i.e. who may rename or retype the column, while
977
+ // the VALUES stayed open to anyone with grid access. The stage and profile columns are
978
+ // excluded inside `isMachineWritten` β€” both are cells a human is *supposed* to drive.
979
+ if (isMachineWritten(field)) return false;
980
  const edit = field.permissions?.edit ?? "everyone";
981
  if (edit === "everyone") return true;
982
  if (!viewer) return false;
 
1013
  return !!field.automation || field.type === "automation" || field.type === "metric";
1014
  }
1015
 
1016
+ /**
1017
+ * ⭐ 2026-08-06, owner items 2/3/4 β€” **is this column PRE-SET, i.e. filled FOR you?**
1018
+ *
1019
+ * The owner's three complaints about the IG preset columns were one complaint: the product
1020
+ * identified them by a light grey WASH and a "this is your custom field" DOT, and said the word
1021
+ * `Pre-set` only about Odoo columns β€” so the columns an automation fills read as *yours, and
1022
+ * oddly shaded*, which is the opposite of true.
1023
+ *
1024
+ * β›” ONE CONCEPT, ONE WORD. An Odoo-precomputed column and an automation-filled column are the
1025
+ * same thing to a reader β€” *something else puts the values here* β€” so they get the same `Pre-set`
1026
+ * chip in the fields panel and neither gets the custom-field dot. The wash is gone entirely
1027
+ * (item 2): a label the reader can read beats a tint they have to be taught.
1028
+ *
1029
+ * ⚠ `custom` still excludes a user-created `custom_`/`measure_` column from the Odoo half, as it
1030
+ * always did β€” a column YOU added beside the Odoo ones is yours even though its neighbours are not.
1031
+ */
1032
+ export function isPresetField(field: Field): boolean {
1033
+ return (field.source === "odoo" && !field.custom) || isMachineOwned(field);
1034
+ }
1035
+
1036
+ /**
1037
+ * ⭐ 2026-08-06, owner item 4 β€” **the cells a person must not type into.**
1038
+ *
1039
+ * Owner, verbatim: *"I should not be able to edit any of the Pre-set fields on instagram
1040
+ * automation, we talked about this extensively."* They were right that it had been settled and
1041
+ * wrong to still be able to: `editRole: 'admins'` rides on every preset column and governs the
1042
+ * **SCHEMA** (`user_tables.py:535`) β€” who may rename or retype it β€” while the VALUES stayed open
1043
+ * to anyone with grid access. Two different walls, one of which nobody had built.
1044
+ *
1045
+ * β›” NARROWER THAN `isMachineOwned`, and the two exclusions are the whole point:
1046
+ * Β· the **stage** column β€” moving a card IS the human decision the board exists for
1047
+ * (`automation.humanMoves`); locking it would freeze every kanban.
1048
+ * Β· a **profile**-flagged column β€” wave-25 C3 is explicit that its values stay fully editable;
1049
+ * typing a handle there is how enrichment gets its subject.
1050
+ *
1051
+ * ⚠ This is a CLIENT courtesy. `core/grid_events.py` carries the same rule at the write door,
1052
+ * which is the one that counts β€” a client wall is a UI affordance, not a permission.
1053
+ */
1054
+ export function isMachineWritten(field: Field): boolean {
1055
+ if (!isMachineOwned(field)) return false;
1056
+ if (field.automation?.stageField) return false;
1057
+ // `isProfileField`, not a second reading of `field.profile` β€” that predicate already exists
1058
+ // below and already carries the argument for why a profile column is the opposite of a
1059
+ // machine-written one. Hoisted, so declaration order is not a problem.
1060
+ return !isProfileField(field);
1061
+ }
1062
+
1063
  /**
1064
  * The NUMERIC and DATE families, for UI dispatch (operator lists, input kinds, sort-direction
1065
  * wording). ONE definition here; the ENGINE (useVisibleRows) keeps its own deliberately β€”
web/src/filter-kit/FieldsHidePanel.tsx CHANGED
@@ -1,318 +1,323 @@
1
- // ---------------------------------------------------------------------------
2
- // filter-kit / FieldsHidePanel.tsx
3
- // The "Hide fields" list β€” search, per-field toggle, drag-to-reorder, delete.
4
- //
5
- // Extracted from customer-grid/Toolbar.tsx (wave 15, contract C-KIT).
6
- //
7
- // ⚠ ONE MODEL CHANGE IN THE MOVE, and it is deliberate: the panel speaks HIDDEN,
8
- // where the toolbar's version spoke VISIBLE. Its title has always been "Hide
9
- // fields" and the thing it now also edits β€” a user's `perms[module].hiddenFields`
10
- // β€” is a list of hidden keys, so a panel that took the complement would have made
11
- // the admin editor invert on the way in and again on the way out. The grid adapts
12
- // instead (one memo at the call site), because the grid is the surface that
13
- // happens to store the other polarity.
14
- // ---------------------------------------------------------------------------
15
-
16
- import { useState } from "react";
17
- import type { Field } from "../customer-grid/types";
18
- import { FieldTypeIcon } from "../customer-grid/icons";
19
- import { TYPE_LABELS } from "../customer-grid/iconShapes";
20
-
21
- export interface FieldsHidePanelProps {
22
- /** Owner item 23 β€” in the view's COLUMN ORDER, not definition order. Dragging a row here
23
- * rewrites `config.order`, so a list showing a different sequence from the one it edits
24
- * would move a field to a position the user never pointed at. */
25
- fields: Field[];
26
- /** The keys that are HIDDEN. Every field not named here renders as shown. */
27
- hidden: ReadonlySet<string>;
28
- onToggle: (key: string) => void;
29
- onHideAll?: () => void;
30
- onShowAll?: () => void;
31
- /** The one field that can never be hidden (the identity column). Absent = nothing is
32
- * locked, which is the right default for a module whose identity column is not this
33
- * panel's business. */
34
- lockedKey?: string;
35
- /** Owner item 23 β€” the whole new order, keys only. The panel owns the arithmetic because it
36
- * owns the list the user is pointing at; the caller just persists it. */
37
- onFieldOrder?: (keys: string[]) => void;
38
- /** Wave-7 item W9 β€” the keys the caller allows a PERMANENT delete on (the same
39
- * created-strata wall as the column menu's Delete: `custom` and never the locked
40
- * identity column). Base/preset fields are simply not in the set, so no delete
41
- * affordance renders for them at all. */
42
- deletableKeys?: ReadonlySet<string>;
43
- onDeleteField?: (key: string) => void;
44
- }
45
-
46
- /**
47
- * The Fields show/hide panel (owner item 7 remainder, wave 2 2026-07-27): a SEARCH box over the
48
- * field list, and a small muted `Pre-set` chip on every Odoo-precomputed field. The chip's
49
- * predicate is the shared contract's, exactly: `source === "odoo" && !custom` β€” user-created
50
- * columns (`custom_`/`measure_`) and the overlay stratum are yours; everything else came with
51
- * the table. Show all / Hide all keep acting on ALL fields, not the searched subset β€” their
52
- * labels say "all", and a narrowed meaning under an active search would be a quiet lie.
53
- */
54
- export function FieldsHidePanel({
55
- fields,
56
- hidden,
57
- onToggle,
58
- onHideAll,
59
- onShowAll,
60
- lockedKey,
61
- onFieldOrder,
62
- deletableKeys,
63
- onDeleteField,
64
- }: FieldsHidePanelProps) {
65
- const [query, setQuery] = useState("");
66
- /** W9 β€” destructive, so the trash arms first (the grid's confirm pattern): first
67
- * click reads "Delete permanently?", the second fires. Per-key, so arming one row
68
- * and clicking another re-arms rather than firing. */
69
- const [confirmKey, setConfirmKey] = useState<string | null>(null);
70
- /** Item 23 β€” the row being dragged, and the row it is currently over. Both are KEYS, never
71
- * indices: the list re-renders on every move and an index would point at whatever slid into
72
- * that slot. */
73
- const [dragKey, setDragKey] = useState<string | null>(null);
74
- const [overKey, setOverKey] = useState<string | null>(null);
75
- const q = query.trim().toLowerCase();
76
- const shown = q ? fields.filter((f) => f.label.toLowerCase().includes(q)) : fields;
77
- /**
78
- * Item 23 β€” reorder is OFF while a search is narrowing the list. Dropping "City" above
79
- * "State" in a list that is hiding the eight fields between them means nothing the user can
80
- * predict: the visible neighbour is not the real neighbour. Airtable does the same. The grip
81
- * still renders (so the row does not change shape mid-search) but says why it is inert.
82
- */
83
- const canReorder = !!onFieldOrder && q === "";
84
- /** Move `key` to where `target` currently sits, in the FULL order. Returns null when the
85
- * move is a no-op or forbidden, so the caller never persists a config identical to the one
86
- * it has (which would still cost an autosave round trip). */
87
- const reorderTo = (key: string, target: string): string[] | null => {
88
- if (key === target) return null;
89
- // The identity column is pinned first by `reconcileOrder` regardless, so a drag involving
90
- // it would appear to work and then silently snap back. Refuse it at the door instead.
91
- if (key === lockedKey || target === lockedKey) return null;
92
- const keys = fields.map((f) => f.key);
93
- const from = keys.indexOf(key);
94
- const to = keys.indexOf(target);
95
- if (from < 0 || to < 0) return null;
96
- const next = keys.slice();
97
- next.splice(from, 1);
98
- next.splice(to, 0, key);
99
- return next;
100
- };
101
- /** Keyboard equivalent of the drag: a pointer-only reorder is unusable without a mouse, and
102
- * the grip is a real button precisely so it can carry this. */
103
- const nudge = (key: string, delta: -1 | 1): void => {
104
- if (!canReorder) return;
105
- const keys = fields.map((f) => f.key);
106
- const at = keys.indexOf(key);
107
- const target = keys[at + delta];
108
- if (target === undefined) return;
109
- const next = reorderTo(key, target);
110
- if (next) onFieldOrder!(next);
111
- };
112
- return (
113
- <div className="cg-pop-body">
114
- {/* Owner item 23 β€” "Hide fields", Airtable's wording and the honest one: this panel's job
115
- is choosing what NOT to show. "Fields" named the noun and left the verb to be guessed. */}
116
- <div className="cg-pop-title">Hide fields</div>
117
- <input
118
- type="text"
119
- className="cg-input cg-fields-search"
120
- placeholder="Find a field…"
121
- aria-label="Find a field"
122
- value={query}
123
- onChange={(e) => setQuery(e.target.value)}
124
- />
125
- <div className="cg-pop-list">
126
- {shown.map((f) => {
127
- const locked = lockedKey !== undefined && f.key === lockedKey;
128
- const on = !hidden.has(f.key);
129
- const deletable = !!onDeleteField && !!deletableKeys?.has(f.key);
130
- const armed = confirmKey === f.key;
131
- return (
132
- <label
133
- key={f.key}
134
- className={
135
- "cg-check-row" +
136
- // Item 12 β€” the ROW is the control (clicking anywhere on it toggles the
137
- // checkbox, which the <label> wrapper has always done: measured, not assumed
138
- // β€” `useOverlayLayer`'s pointerdown listener returns early inside its own
139
- // panel, so nothing cancels label activation). What the row could NOT do was
140
- // SAY which state it was in without reading a 15px checkbox, so a hidden
141
- // field's row now reads as hidden. The checkbox stays: it is the a11y control
142
- // and the keyboard one.
143
- (on ? "" : " is-off") +
144
- (locked ? " is-locked" : "") +
145
- (dragKey === f.key ? " is-dragging" : "") +
146
- (overKey === f.key && dragKey !== null && dragKey !== f.key
147
- ? " is-drop-target"
148
- : "")
149
- }
150
- title={locked ? "Always visible" : undefined}
151
- // Item 23 β€” the whole ROW is the drop zone; only the GRIP starts a drag. Dropping
152
- // is a big target on purpose (a 22px handle is a hard thing to hit precisely);
153
- // starting is a small one, so the row still behaves as a label everywhere else.
154
- onDragOver={
155
- canReorder && dragKey && dragKey !== f.key
156
- ? (e) => {
157
- e.preventDefault(); // without this the drop NEVER fires
158
- e.dataTransfer.dropEffect = "move";
159
- if (overKey !== f.key) setOverKey(f.key);
160
- }
161
- : undefined
162
- }
163
- onDrop={
164
- canReorder && dragKey
165
- ? (e) => {
166
- e.preventDefault();
167
- // ...and this: a drop inside a <label> would otherwise ALSO activate the
168
- // label and toggle the column's visibility as a side effect of moving it.
169
- e.stopPropagation();
170
- const next = reorderTo(dragKey, f.key);
171
- setDragKey(null);
172
- setOverKey(null);
173
- if (next) onFieldOrder!(next);
174
- }
175
- : undefined
176
- }
177
- >
178
- {/* Owner item 23 β€” the six-dot grip. Rendered for EVERY row including the locked
179
- one (an absent handle would misalign that row against all the others), but
180
- inert there: the identity column is pinned first by `reconcileOrder`, so a
181
- drag would appear to work and snap back.
182
- A real <button>, not a decorative <span>: it carries the keyboard reorder,
183
- which is the only route for anyone not using a pointer. */}
184
- <button
185
- type="button"
186
- className="cg-field-grip"
187
- draggable={canReorder && !locked}
188
- aria-label={
189
- locked
190
- ? `${f.label} is always first`
191
- : canReorder
192
- ? `Reorder ${f.label} β€” drag, or use the arrow keys`
193
- : `Reorder ${f.label} (clear the search first)`
194
- }
195
- title={
196
- canReorder && !locked
197
- ? "Drag to reorder, or use the arrow keys"
198
- : locked
199
- ? "This column is always first"
200
- : "Clear the search to reorder"
201
- }
202
- onDragStart={(e) => {
203
- // Firefox refuses to start a drag with no payload set.
204
- e.dataTransfer.setData("text/plain", f.key);
205
- e.dataTransfer.effectAllowed = "move";
206
- setDragKey(f.key);
207
- }}
208
- onDragEnd={() => {
209
- setDragKey(null);
210
- setOverKey(null);
211
- }}
212
- // Inside a <label>, exactly as the delete button below: an unguarded click
213
- // activates the label and hides the column you were trying to move.
214
- onClick={(e) => {
215
- e.preventDefault();
216
- e.stopPropagation();
217
- }}
218
- onKeyDown={(e) => {
219
- if (e.key !== "ArrowUp" && e.key !== "ArrowDown") return;
220
- e.preventDefault();
221
- e.stopPropagation();
222
- nudge(f.key, e.key === "ArrowUp" ? -1 : 1);
223
- }}
224
- >
225
- <svg width="10" height="16" viewBox="0 0 10 16" aria-hidden focusable="false">
226
- {[4, 8, 12].map((cy) =>
227
- [2.5, 7.5].map((cx) => (
228
- <circle key={`${cx}-${cy}`} cx={cx} cy={cy} r="1.15" fill="currentColor" />
229
- ))
230
- )}
231
- </svg>
232
- </button>
233
- <input
234
- type="checkbox"
235
- checked={on}
236
- disabled={locked}
237
- onChange={() => onToggle(f.key)}
238
- />
239
- {/* Wave-8 I20 β€” the field-TYPE mark, same geometry the column header
240
- draws (icons.tsx). Titled, because this list is where the icon
241
- vocabulary is learned. */}
242
- <FieldTypeIcon type={f.type} title={TYPE_LABELS[f.type]} />
243
- <span className="cg-check-label">{f.label}</span>
244
- {f.source === "odoo" && !f.custom && (
245
- <span className="cg-preset-tag">Pre-set</span>
246
- )}
247
- {/* Wave-6 item 9c β€” a cohort-scoped field says so (contract: "label it"). */}
248
- {f.scope === "cohort" && (
249
- <span className="cg-preset-tag cg-scope-tag">Cohort-only</span>
250
- )}
251
- {locked && <span className="cg-lock-tag">Locked</span>}
252
- {deletable && (
253
- // Inside a <label>: preventDefault stops the click from ALSO toggling
254
- // the row's checkbox (label activation), which would hide the column
255
- // as a side effect of trying to delete it.
256
- <button
257
- type="button"
258
- className={"cg-check-del" + (armed ? " is-armed" : "")}
259
- aria-label={
260
- armed ? `Permanently delete ${f.label}?` : `Delete ${f.label}`
261
- }
262
- title={armed ? undefined : "Removes this field and its values on every row."}
263
- onClick={(e) => {
264
- e.preventDefault();
265
- e.stopPropagation();
266
- if (!armed) {
267
- setConfirmKey(f.key);
268
- return;
269
- }
270
- setConfirmKey(null);
271
- onDeleteField(f.key);
272
- }}
273
- >
274
- {armed ? (
275
- "Delete permanently?"
276
- ) : (
277
- <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden>
278
- <path
279
- d="M3.5 4.5h9M6.5 4.5V3h3v1.5M5 4.5l.6 8.5h4.8l.6-8.5"
280
- stroke="currentColor"
281
- strokeWidth={1.3}
282
- strokeLinecap="round"
283
- strokeLinejoin="round"
284
- />
285
- </svg>
286
- )}
287
- </button>
288
- )}
289
- </label>
290
- );
291
- })}
292
- {shown.length === 0 && (
293
- <div className="cg-builder-empty">No field matches your search.</div>
294
- )}
295
- </div>
296
- {/* Item 12 (owner, 2026-08-02) β€” the two bulk actions sit in a quiet grey box rather
297
- than floating under a hairline. They act on ALL fields at once, which is a different
298
- kind of act from the per-row checkboxes above them; the box says so without a second
299
- heading, and it is what Airtable does with the same pair.
300
- Each renders only when the caller supplies its handler β€” the house posture: a missing
301
- prop makes the action ABSENT, never present-and-inert. */}
302
- {(onShowAll || onHideAll) && (
303
- <div className="cg-pop-footer cg-fields-footer">
304
- {onShowAll && (
305
- <button type="button" className="cg-link-btn" onClick={onShowAll}>
306
- Show all
307
- </button>
308
- )}
309
- {onHideAll && (
310
- <button type="button" className="cg-link-btn" onClick={onHideAll}>
311
- Hide all
312
- </button>
313
- )}
314
- </div>
315
- )}
316
- </div>
317
- );
318
- }
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // filter-kit / FieldsHidePanel.tsx
3
+ // The "Hide fields" list β€” search, per-field toggle, drag-to-reorder, delete.
4
+ //
5
+ // Extracted from customer-grid/Toolbar.tsx (wave 15, contract C-KIT).
6
+ //
7
+ // ⚠ ONE MODEL CHANGE IN THE MOVE, and it is deliberate: the panel speaks HIDDEN,
8
+ // where the toolbar's version spoke VISIBLE. Its title has always been "Hide
9
+ // fields" and the thing it now also edits β€” a user's `perms[module].hiddenFields`
10
+ // β€” is a list of hidden keys, so a panel that took the complement would have made
11
+ // the admin editor invert on the way in and again on the way out. The grid adapts
12
+ // instead (one memo at the call site), because the grid is the surface that
13
+ // happens to store the other polarity.
14
+ // ---------------------------------------------------------------------------
15
+
16
+ import { useState } from "react";
17
+ import type { Field } from "../customer-grid/types";
18
+ import { isPresetField } from "../customer-grid/types";
19
+ import { FieldTypeIcon } from "../customer-grid/icons";
20
+ import { TYPE_LABELS } from "../customer-grid/iconShapes";
21
+
22
+ export interface FieldsHidePanelProps {
23
+ /** Owner item 23 β€” in the view's COLUMN ORDER, not definition order. Dragging a row here
24
+ * rewrites `config.order`, so a list showing a different sequence from the one it edits
25
+ * would move a field to a position the user never pointed at. */
26
+ fields: Field[];
27
+ /** The keys that are HIDDEN. Every field not named here renders as shown. */
28
+ hidden: ReadonlySet<string>;
29
+ onToggle: (key: string) => void;
30
+ onHideAll?: () => void;
31
+ onShowAll?: () => void;
32
+ /** The one field that can never be hidden (the identity column). Absent = nothing is
33
+ * locked, which is the right default for a module whose identity column is not this
34
+ * panel's business. */
35
+ lockedKey?: string;
36
+ /** Owner item 23 β€” the whole new order, keys only. The panel owns the arithmetic because it
37
+ * owns the list the user is pointing at; the caller just persists it. */
38
+ onFieldOrder?: (keys: string[]) => void;
39
+ /** Wave-7 item W9 β€” the keys the caller allows a PERMANENT delete on (the same
40
+ * created-strata wall as the column menu's Delete: `custom` and never the locked
41
+ * identity column). Base/preset fields are simply not in the set, so no delete
42
+ * affordance renders for them at all. */
43
+ deletableKeys?: ReadonlySet<string>;
44
+ onDeleteField?: (key: string) => void;
45
+ }
46
+
47
+ /**
48
+ * The Fields show/hide panel (owner item 7 remainder, wave 2 2026-07-27): a SEARCH box over the
49
+ * field list, and a small muted `Pre-set` chip on every Odoo-precomputed field. The chip's
50
+ * predicate is the shared contract's, exactly: `source === "odoo" && !custom` β€” user-created
51
+ * columns (`custom_`/`measure_`) and the overlay stratum are yours; everything else came with
52
+ * the table. Show all / Hide all keep acting on ALL fields, not the searched subset β€” their
53
+ * labels say "all", and a narrowed meaning under an active search would be a quiet lie.
54
+ */
55
+ export function FieldsHidePanel({
56
+ fields,
57
+ hidden,
58
+ onToggle,
59
+ onHideAll,
60
+ onShowAll,
61
+ lockedKey,
62
+ onFieldOrder,
63
+ deletableKeys,
64
+ onDeleteField,
65
+ }: FieldsHidePanelProps) {
66
+ const [query, setQuery] = useState("");
67
+ /** W9 β€” destructive, so the trash arms first (the grid's confirm pattern): first
68
+ * click reads "Delete permanently?", the second fires. Per-key, so arming one row
69
+ * and clicking another re-arms rather than firing. */
70
+ const [confirmKey, setConfirmKey] = useState<string | null>(null);
71
+ /** Item 23 β€” the row being dragged, and the row it is currently over. Both are KEYS, never
72
+ * indices: the list re-renders on every move and an index would point at whatever slid into
73
+ * that slot. */
74
+ const [dragKey, setDragKey] = useState<string | null>(null);
75
+ const [overKey, setOverKey] = useState<string | null>(null);
76
+ const q = query.trim().toLowerCase();
77
+ const shown = q ? fields.filter((f) => f.label.toLowerCase().includes(q)) : fields;
78
+ /**
79
+ * Item 23 β€” reorder is OFF while a search is narrowing the list. Dropping "City" above
80
+ * "State" in a list that is hiding the eight fields between them means nothing the user can
81
+ * predict: the visible neighbour is not the real neighbour. Airtable does the same. The grip
82
+ * still renders (so the row does not change shape mid-search) but says why it is inert.
83
+ */
84
+ const canReorder = !!onFieldOrder && q === "";
85
+ /** Move `key` to where `target` currently sits, in the FULL order. Returns null when the
86
+ * move is a no-op or forbidden, so the caller never persists a config identical to the one
87
+ * it has (which would still cost an autosave round trip). */
88
+ const reorderTo = (key: string, target: string): string[] | null => {
89
+ if (key === target) return null;
90
+ // The identity column is pinned first by `reconcileOrder` regardless, so a drag involving
91
+ // it would appear to work and then silently snap back. Refuse it at the door instead.
92
+ if (key === lockedKey || target === lockedKey) return null;
93
+ const keys = fields.map((f) => f.key);
94
+ const from = keys.indexOf(key);
95
+ const to = keys.indexOf(target);
96
+ if (from < 0 || to < 0) return null;
97
+ const next = keys.slice();
98
+ next.splice(from, 1);
99
+ next.splice(to, 0, key);
100
+ return next;
101
+ };
102
+ /** Keyboard equivalent of the drag: a pointer-only reorder is unusable without a mouse, and
103
+ * the grip is a real button precisely so it can carry this. */
104
+ const nudge = (key: string, delta: -1 | 1): void => {
105
+ if (!canReorder) return;
106
+ const keys = fields.map((f) => f.key);
107
+ const at = keys.indexOf(key);
108
+ const target = keys[at + delta];
109
+ if (target === undefined) return;
110
+ const next = reorderTo(key, target);
111
+ if (next) onFieldOrder!(next);
112
+ };
113
+ return (
114
+ <div className="cg-pop-body">
115
+ {/* Owner item 23 β€” "Hide fields", Airtable's wording and the honest one: this panel's job
116
+ is choosing what NOT to show. "Fields" named the noun and left the verb to be guessed. */}
117
+ <div className="cg-pop-title">Hide fields</div>
118
+ <input
119
+ type="text"
120
+ className="cg-input cg-fields-search"
121
+ placeholder="Find a field…"
122
+ aria-label="Find a field"
123
+ value={query}
124
+ onChange={(e) => setQuery(e.target.value)}
125
+ />
126
+ <div className="cg-pop-list">
127
+ {shown.map((f) => {
128
+ const locked = lockedKey !== undefined && f.key === lockedKey;
129
+ const on = !hidden.has(f.key);
130
+ const deletable = !!onDeleteField && !!deletableKeys?.has(f.key);
131
+ const armed = confirmKey === f.key;
132
+ return (
133
+ <label
134
+ key={f.key}
135
+ className={
136
+ "cg-check-row" +
137
+ // Item 12 β€” the ROW is the control (clicking anywhere on it toggles the
138
+ // checkbox, which the <label> wrapper has always done: measured, not assumed
139
+ // β€” `useOverlayLayer`'s pointerdown listener returns early inside its own
140
+ // panel, so nothing cancels label activation). What the row could NOT do was
141
+ // SAY which state it was in without reading a 15px checkbox, so a hidden
142
+ // field's row now reads as hidden. The checkbox stays: it is the a11y control
143
+ // and the keyboard one.
144
+ (on ? "" : " is-off") +
145
+ (locked ? " is-locked" : "") +
146
+ (dragKey === f.key ? " is-dragging" : "") +
147
+ (overKey === f.key && dragKey !== null && dragKey !== f.key
148
+ ? " is-drop-target"
149
+ : "")
150
+ }
151
+ title={locked ? "Always visible" : undefined}
152
+ // Item 23 β€” the whole ROW is the drop zone; only the GRIP starts a drag. Dropping
153
+ // is a big target on purpose (a 22px handle is a hard thing to hit precisely);
154
+ // starting is a small one, so the row still behaves as a label everywhere else.
155
+ onDragOver={
156
+ canReorder && dragKey && dragKey !== f.key
157
+ ? (e) => {
158
+ e.preventDefault(); // without this the drop NEVER fires
159
+ e.dataTransfer.dropEffect = "move";
160
+ if (overKey !== f.key) setOverKey(f.key);
161
+ }
162
+ : undefined
163
+ }
164
+ onDrop={
165
+ canReorder && dragKey
166
+ ? (e) => {
167
+ e.preventDefault();
168
+ // ...and this: a drop inside a <label> would otherwise ALSO activate the
169
+ // label and toggle the column's visibility as a side effect of moving it.
170
+ e.stopPropagation();
171
+ const next = reorderTo(dragKey, f.key);
172
+ setDragKey(null);
173
+ setOverKey(null);
174
+ if (next) onFieldOrder!(next);
175
+ }
176
+ : undefined
177
+ }
178
+ >
179
+ {/* Owner item 23 β€” the six-dot grip. Rendered for EVERY row including the locked
180
+ one (an absent handle would misalign that row against all the others), but
181
+ inert there: the identity column is pinned first by `reconcileOrder`, so a
182
+ drag would appear to work and snap back.
183
+ A real <button>, not a decorative <span>: it carries the keyboard reorder,
184
+ which is the only route for anyone not using a pointer. */}
185
+ <button
186
+ type="button"
187
+ className="cg-field-grip"
188
+ draggable={canReorder && !locked}
189
+ aria-label={
190
+ locked
191
+ ? `${f.label} is always first`
192
+ : canReorder
193
+ ? `Reorder ${f.label} β€” drag, or use the arrow keys`
194
+ : `Reorder ${f.label} (clear the search first)`
195
+ }
196
+ title={
197
+ canReorder && !locked
198
+ ? "Drag to reorder, or use the arrow keys"
199
+ : locked
200
+ ? "This column is always first"
201
+ : "Clear the search to reorder"
202
+ }
203
+ onDragStart={(e) => {
204
+ // Firefox refuses to start a drag with no payload set.
205
+ e.dataTransfer.setData("text/plain", f.key);
206
+ e.dataTransfer.effectAllowed = "move";
207
+ setDragKey(f.key);
208
+ }}
209
+ onDragEnd={() => {
210
+ setDragKey(null);
211
+ setOverKey(null);
212
+ }}
213
+ // Inside a <label>, exactly as the delete button below: an unguarded click
214
+ // activates the label and hides the column you were trying to move.
215
+ onClick={(e) => {
216
+ e.preventDefault();
217
+ e.stopPropagation();
218
+ }}
219
+ onKeyDown={(e) => {
220
+ if (e.key !== "ArrowUp" && e.key !== "ArrowDown") return;
221
+ e.preventDefault();
222
+ e.stopPropagation();
223
+ nudge(f.key, e.key === "ArrowUp" ? -1 : 1);
224
+ }}
225
+ >
226
+ <svg width="10" height="16" viewBox="0 0 10 16" aria-hidden focusable="false">
227
+ {[4, 8, 12].map((cy) =>
228
+ [2.5, 7.5].map((cx) => (
229
+ <circle key={`${cx}-${cy}`} cx={cx} cy={cy} r="1.15" fill="currentColor" />
230
+ ))
231
+ )}
232
+ </svg>
233
+ </button>
234
+ <input
235
+ type="checkbox"
236
+ checked={on}
237
+ disabled={locked}
238
+ onChange={() => onToggle(f.key)}
239
+ />
240
+ {/* Wave-8 I20 β€” the field-TYPE mark, same geometry the column header
241
+ draws (icons.tsx). Titled, because this list is where the icon
242
+ vocabulary is learned. */}
243
+ <FieldTypeIcon type={f.type} title={TYPE_LABELS[f.type]} />
244
+ <span className="cg-check-label">{f.label}</span>
245
+ {/* ⭐ OWNER ITEM 3 (2026-08-06): *"it doesn't show pre-set when I hide fields just
246
+ like how Odoo fields are. This is always the standard label."* Right β€” the chip
247
+ asked `source === "odoo"`, so a column an AUTOMATION fills (source `overlay`)
248
+ never earned the word, even though it is pre-set in exactly the sense the chip
249
+ means: something other than you puts the values there. `isPresetField` is that
250
+ one concept; the two sources answer to it together. */}
251
+ {isPresetField(f) && <span className="cg-preset-tag">Pre-set</span>}
252
+ {/* Wave-6 item 9c β€” a cohort-scoped field says so (contract: "label it"). */}
253
+ {f.scope === "cohort" && (
254
+ <span className="cg-preset-tag cg-scope-tag">Cohort-only</span>
255
+ )}
256
+ {locked && <span className="cg-lock-tag">Locked</span>}
257
+ {deletable && (
258
+ // Inside a <label>: preventDefault stops the click from ALSO toggling
259
+ // the row's checkbox (label activation), which would hide the column
260
+ // as a side effect of trying to delete it.
261
+ <button
262
+ type="button"
263
+ className={"cg-check-del" + (armed ? " is-armed" : "")}
264
+ aria-label={
265
+ armed ? `Permanently delete ${f.label}?` : `Delete ${f.label}`
266
+ }
267
+ title={armed ? undefined : "Removes this field and its values on every row."}
268
+ onClick={(e) => {
269
+ e.preventDefault();
270
+ e.stopPropagation();
271
+ if (!armed) {
272
+ setConfirmKey(f.key);
273
+ return;
274
+ }
275
+ setConfirmKey(null);
276
+ onDeleteField(f.key);
277
+ }}
278
+ >
279
+ {armed ? (
280
+ "Delete permanently?"
281
+ ) : (
282
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden>
283
+ <path
284
+ d="M3.5 4.5h9M6.5 4.5V3h3v1.5M5 4.5l.6 8.5h4.8l.6-8.5"
285
+ stroke="currentColor"
286
+ strokeWidth={1.3}
287
+ strokeLinecap="round"
288
+ strokeLinejoin="round"
289
+ />
290
+ </svg>
291
+ )}
292
+ </button>
293
+ )}
294
+ </label>
295
+ );
296
+ })}
297
+ {shown.length === 0 && (
298
+ <div className="cg-builder-empty">No field matches your search.</div>
299
+ )}
300
+ </div>
301
+ {/* Item 12 (owner, 2026-08-02) β€” the two bulk actions sit in a quiet grey box rather
302
+ than floating under a hairline. They act on ALL fields at once, which is a different
303
+ kind of act from the per-row checkboxes above them; the box says so without a second
304
+ heading, and it is what Airtable does with the same pair.
305
+ Each renders only when the caller supplies its handler β€” the house posture: a missing
306
+ prop makes the action ABSENT, never present-and-inert. */}
307
+ {(onShowAll || onHideAll) && (
308
+ <div className="cg-pop-footer cg-fields-footer">
309
+ {onShowAll && (
310
+ <button type="button" className="cg-link-btn" onClick={onShowAll}>
311
+ Show all
312
+ </button>
313
+ )}
314
+ {onHideAll && (
315
+ <button type="button" className="cg-link-btn" onClick={onHideAll}>
316
+ Hide all
317
+ </button>
318
+ )}
319
+ </div>
320
+ )}
321
+ </div>
322
+ );
323
+ }