fsanyoto commited on
Commit
a83fcff
Β·
verified Β·
1 Parent(s): cfd4ac1

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 +1 -1
  2. VERSION +1 -1
  3. api/application_registry.py +194 -9
  4. api/connectors_amazon.py +94 -0
  5. api/deps.py +31 -1
  6. api/odoo_relational.py +311 -9
  7. api/routes_connectors.py +303 -22
  8. api/routes_nav.py +38 -0
  9. api/routes_odoo_tables.py +155 -3
  10. api/routes_sheet.py +69 -0
  11. platform/core/connector_spec.py +29 -0
  12. web/src/connectors/ConnectorModal.tsx +145 -1
  13. web/src/connectors/DatabasesTab.tsx +14 -3
  14. web/src/connectors/KeychainTab.tsx +122 -4
  15. web/src/connectors/OdooConfig.tsx +46 -22
  16. web/src/connectors/RelationshipDiagram.tsx +34 -5
  17. web/src/customer-grid/CatalogView.tsx +96 -0
  18. web/src/customer-grid/MapView.tsx +152 -4
  19. web/src/customer-grid/RecordDetail.css +96 -0
  20. web/src/customer-grid/RecordDetail.tsx +639 -135
  21. web/src/customer-grid/RouteNav.tsx +7 -1
  22. web/src/customer-grid/SwipeView.tsx +586 -586
  23. web/src/customer-grid/viewModes.tsx +128 -1
  24. web/src/home/HomePage.tsx +259 -22
  25. web/src/home/homeModel.ts +18 -0
  26. web/src/sheet/BindingEditor.tsx +93 -51
  27. web/src/sheet/ChartDialog.tsx +89 -41
  28. web/src/sheet/DrillModal.tsx +575 -49
  29. web/src/sheet/KeyTips.tsx +24 -7
  30. web/src/sheet/Ribbon.tsx +67 -4
  31. web/src/sheet/SheetChart.tsx +229 -73
  32. web/src/sheet/SheetGrid.tsx +283 -67
  33. web/src/sheet/SheetPage.tsx +235 -14
  34. web/src/sheet/bindingRefs.ts +123 -2
  35. web/src/sheet/cellBorders.ts +42 -70
  36. web/src/sheet/cellStyleOps.ts +18 -0
  37. web/src/sheet/clipboardOps.ts +8 -0
  38. web/src/sheet/ribbonData.tsx +87 -0
  39. web/src/sheet/ribbonFormulas.tsx +61 -0
  40. web/src/sheet/ribbonHome.tsx +18 -10
  41. web/src/sheet/ribbonView.tsx +99 -0
  42. web/src/sheet/sheetState.ts +158 -65
  43. web/src/sheet/shortcuts.ts +17 -1
  44. web/src/sheet/types.ts +148 -6
  45. web/src/shell/ShareDialog.tsx +58 -34
  46. web/src/shell/Shell.tsx +490 -217
  47. web/src/shell/nav.ts +56 -15
  48. web/src/shell/shareModel.ts +43 -0
  49. web/src/shell/useApplicationWizardOverlay.ts +18 -0
  50. web/src/starred/StarredPage.tsx +7 -46
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "463db38",
3
  "releases": [
4
  {
5
  "version": "v71",
 
1
  {
2
+ "current": "fb85b60",
3
  "releases": [
4
  {
5
  "version": "v71",
VERSION CHANGED
@@ -1 +1 @@
1
- 463db38
 
1
+ fb85b60
api/application_registry.py CHANGED
@@ -7,14 +7,57 @@ import uuid
7
 
8
 
9
  APPLICATION_TYPES = ("chart", "route", "map", "timeseries")
 
10
  _KEY = "applications_v1"
11
  _MAX = 500
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  class ApplicationError(ValueError):
15
  pass
16
 
17
 
 
 
 
 
 
18
  def blank_doc():
19
  return {"schema": 1, "applications": {}, "defaults": {}}
20
 
@@ -125,6 +168,125 @@ def _allowed(compatible, allowed_databases):
125
  else set(compatible or ()) & set(allowed_databases))
126
 
127
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  def _public(app, user, is_admin=False, *, allowed_databases=None, target_database=None,
129
  is_default=False):
130
  row=copy.deepcopy(app)
@@ -160,23 +322,34 @@ def list_apps(runtime, user, is_admin=False, *, database=None, kind=None, starre
160
  return sorted(rows,key=lambda x:(str(x.get("updatedAt") or ""),str(x.get("id"))),reverse=True)
161
 
162
 
163
- def create(runtime, tenant, user, payload, *, semantic_records=None, allowed_databases=None):
 
164
  payload=payload if isinstance(payload,dict) else {}
165
- kind=str(payload.get("type") or "").lower()
166
- if kind not in APPLICATION_TYPES: raise ApplicationError("application type is not recognized")
 
 
 
 
167
  name=" ".join(str(payload.get("name") or "").split())[:120]
168
  if not name: raise ApplicationError("application name is required")
169
  app_id=f"app_{uuid.uuid4().hex[:16]}"; now=dt.datetime.now(dt.timezone.utc).isoformat()
170
- compatible = _compat(payload.get("compatibleDatabases"))
 
171
  if _allowed(compatible, allowed_databases) != set(compatible):
172
  raise PermissionError("an Application cannot bind a database you cannot open")
 
 
 
 
173
  app={"id":app_id,"tenant":str(tenant),"type":kind,"name":name,
174
  "compatibleDatabases":compatible,
175
  "semanticRoleBindings":_governed_bindings(
176
  payload.get("semanticRoleBindings"), compatible, semantic_records or {}),
177
- "config":_typed_config(kind, payload.get("config")),
178
  "share":{"mode":"private","users":[]},"starredBy":[],"createdBy":user,
179
  "createdAt":now,"updatedAt":now,"revision":1}
 
180
  def apply(raw):
181
  doc=_clean_doc(raw)
182
  if len(doc["applications"])>=_MAX: raise ApplicationError("application limit reached")
@@ -188,11 +361,19 @@ def create(runtime, tenant, user, payload, *, semantic_records=None, allowed_dat
188
  def mutate(runtime, app_id, user, is_admin, patch, *, semantic_records=None,
189
  allowed_databases=None, target_database=None):
190
  patch=patch if isinstance(patch,dict) else {}; landed={}
 
 
 
 
 
 
191
  def apply(raw):
192
  doc=_clean_doc(raw); app=doc["applications"].get(app_id)
193
  if not app: raise ApplicationError("application does not exist")
194
  if not _allowed(app.get("compatibleDatabases"), allowed_databases):
195
  raise ApplicationError("application does not exist")
 
 
196
  star_only = set(patch) <= {"starred"}
197
  if star_only:
198
  if not may_read(app,user,is_admin): raise PermissionError("application is not available")
@@ -230,15 +411,19 @@ def mutate(runtime, app_id, user, is_admin, patch, *, semantic_records=None,
230
 
231
 
232
  def duplicate(runtime, app_id, tenant, user, is_admin=False, *, semantic_records=None,
233
- allowed_databases=None):
234
  app=load(runtime)["applications"].get(app_id)
235
  if not may_read(app,user,is_admin): raise ApplicationError("application does not exist")
236
  if not _allowed(app.get("compatibleDatabases"), allowed_databases):
237
  raise ApplicationError("application does not exist")
238
- return create(runtime,tenant,user,{"type":app["type"],"name":f"{app['name']} copy",
239
  "compatibleDatabases":app.get("compatibleDatabases"),
240
- "semanticRoleBindings":app.get("semanticRoleBindings"),"config":app.get("config")},
241
- semantic_records=semantic_records, allowed_databases=allowed_databases)
 
 
 
 
242
 
243
 
244
  def delete(runtime, app_id, user, is_admin=False, *, allowed_databases=None):
 
7
 
8
 
9
  APPLICATION_TYPES = ("chart", "route", "map", "timeseries")
10
+ APPLICATION_TEMPLATE_KINDS = ("route", "catalog")
11
  _KEY = "applications_v1"
12
  _MAX = 500
13
 
14
+ # Routing and Catalog are the first authored App templates. These are wire contracts, not
15
+ # executable module declarations: the client renders a trusted platform surface from the stored
16
+ # definition. ``required`` is consumed by the creation flow and enforced again below, so a
17
+ # future client cannot weaken a template by skipping a wizard step.
18
+ _TEMPLATE_CONTRACTS = {
19
+ "route": {
20
+ "kind": "route",
21
+ "label": "Routing",
22
+ "applicationType": "route",
23
+ "displayMode": "map",
24
+ "fieldRoles": [
25
+ {"key": "title", "label": "Record title", "required": True, "types": []},
26
+ {"key": "latitude", "label": "Latitude", "required": False,
27
+ "types": ["text", "int", "currency", "pct", "rating", "number", "float", "decimal"]},
28
+ {"key": "longitude", "label": "Longitude", "required": False,
29
+ "types": ["text", "int", "currency", "pct", "rating", "number", "float", "decimal"]},
30
+ ],
31
+ "defaultPlacement": {"section": "app", "order": 0},
32
+ },
33
+ "catalog": {
34
+ "kind": "catalog",
35
+ "label": "Catalog",
36
+ # Catalog is a template discriminator over an existing trusted renderer contract. The
37
+ # governed Application type vocabulary stays four-way; the client launches the Catalog
38
+ # surface from ``templateKind`` rather than teaching every shared type mirror a fifth word.
39
+ "applicationType": "map",
40
+ "displayMode": "map",
41
+ "fieldRoles": [
42
+ {"key": "key", "label": "Record key", "required": True, "types": []},
43
+ {"key": "title", "label": "Record title", "required": True, "types": []},
44
+ {"key": "image", "label": "Image", "required": False,
45
+ "types": ["image", "attachment", "url", "text"]},
46
+ ],
47
+ "defaultPlacement": {"section": "app", "order": 0},
48
+ },
49
+ }
50
+
51
 
52
  class ApplicationError(ValueError):
53
  pass
54
 
55
 
56
+ def template_contracts():
57
+ """The trusted renderer contracts offered by the Application creation flow."""
58
+ return [copy.deepcopy(_TEMPLATE_CONTRACTS[kind]) for kind in APPLICATION_TEMPLATE_KINDS]
59
+
60
+
61
  def blank_doc():
62
  return {"schema": 1, "applications": {}, "defaults": {}}
63
 
 
168
  else set(compatible or ()) & set(allowed_databases))
169
 
170
 
171
+ def _contract_fields(database, semantic_records=None, field_contracts=None):
172
+ """Return ``{field key: type}`` from a caller's already permission-scoped contract.
173
+
174
+ The nav creation door supplies its served schema fields. The older Application door supplies
175
+ governed semantic records. Supporting both here keeps one validator while never making this
176
+ registry reach around either caller's database/field wall.
177
+ """
178
+ fields = {}
179
+ raw = ((field_contracts or {}).get(database)
180
+ if isinstance(field_contracts, dict) else None)
181
+ if isinstance(raw, dict):
182
+ raw = list(raw.values())
183
+ for row in raw if isinstance(raw, (list, tuple)) else ():
184
+ if not isinstance(row, dict):
185
+ continue
186
+ key = str(row.get("key") or row.get("field") or "").strip()
187
+ if key:
188
+ fields[key] = str(row.get("type") or row.get("dataType") or "").strip().lower()
189
+ records = ((semantic_records or {}).get(database)
190
+ if isinstance(semantic_records, dict) else None)
191
+ for row in (records or {}).values() if isinstance(records, dict) else ():
192
+ if not isinstance(row, dict):
193
+ continue
194
+ key = str(row.get("field") or row.get("key") or "").strip()
195
+ if key and key not in fields:
196
+ fields[key] = str(row.get("dataType") or row.get("type") or "").strip().lower()
197
+ return fields
198
+
199
+
200
+ def _template_definition(kind, payload, *, semantic_records=None, field_contracts=None,
201
+ allowed_databases=None):
202
+ contract = _TEMPLATE_CONTRACTS[kind]
203
+ template_kind = str(payload.get("templateKind") or "").strip().lower()
204
+ if template_kind != kind:
205
+ raise ApplicationError(f"{kind} applications require templateKind {kind!r}")
206
+ source = str(payload.get("sourceDatabase") or "").strip()[:120]
207
+ if not source:
208
+ raise ApplicationError("sourceDatabase is required")
209
+ if source not in set(allowed_databases or ()):
210
+ raise PermissionError("an Application cannot bind a database you cannot open")
211
+ if "compatibleDatabases" in payload:
212
+ compatible = _compat(payload.get("compatibleDatabases"))
213
+ if compatible != [source]:
214
+ raise ApplicationError("a template Application has exactly one sourceDatabase")
215
+
216
+ raw_map = payload.get("fieldMap")
217
+ if not isinstance(raw_map, dict):
218
+ raise ApplicationError("fieldMap must be an object")
219
+ roles = {row["key"]: row for row in contract["fieldRoles"]}
220
+ extras = sorted(set(raw_map) - set(roles))
221
+ if extras:
222
+ raise ApplicationError("fieldMap contains roles outside the template contract: "
223
+ + ", ".join(extras))
224
+ missing = sorted(key for key, role in roles.items()
225
+ if role["required"] and not str(raw_map.get(key) or "").strip())
226
+ if missing:
227
+ raise ApplicationError("fieldMap is missing required roles: " + ", ".join(missing))
228
+ available = _contract_fields(source, semantic_records, field_contracts)
229
+ if not available:
230
+ raise ApplicationError("the source database has no readable field contract")
231
+ field_map = {}
232
+ for role, raw_field in raw_map.items():
233
+ field = str(raw_field or "").strip()
234
+ if not field:
235
+ continue
236
+ if len(field) > 160 or field not in available:
237
+ raise ApplicationError(f"fieldMap role {role!r} does not name a source field")
238
+ allowed_types = set(roles[role].get("types") or ())
239
+ if allowed_types and available[field] not in allowed_types:
240
+ raise ApplicationError(
241
+ f"fieldMap role {role!r} cannot use field type {available[field]!r}")
242
+ field_map[role] = field
243
+ latitude, longitude = field_map.get("latitude"), field_map.get("longitude")
244
+ if bool(latitude) != bool(longitude):
245
+ raise ApplicationError("Routing needs both coordinate fields or neither")
246
+ if latitude and latitude == longitude:
247
+ raise ApplicationError("Routing latitude and longitude must use different fields")
248
+
249
+ raw_placement = payload.get("navPlacement")
250
+ if not isinstance(raw_placement, dict) or set(raw_placement) != {"section", "order"}:
251
+ raise ApplicationError("navPlacement must contain section and order")
252
+ section = str(raw_placement.get("section") or "").strip().lower()
253
+ order = raw_placement.get("order")
254
+ if section != "app":
255
+ raise ApplicationError("template Applications must be placed in App")
256
+ if isinstance(order, bool) or not isinstance(order, int) or not 0 <= order <= 999:
257
+ raise ApplicationError("navPlacement order must be an integer from 0 to 999")
258
+ return {"templateKind": kind, "sourceDatabase": source, "fieldMap": field_map,
259
+ "navPlacement": {"section": "app", "order": order}}
260
+
261
+
262
+ def validate_application(payload, tenant, *, semantic_records=None, field_contracts=None,
263
+ allowed_databases=None):
264
+ """Validate the server-authored identity/tenant envelope and any template definition."""
265
+ payload = payload if isinstance(payload, dict) else {}
266
+ if payload.get("id") not in (None, ""):
267
+ raise ApplicationError("application id is server assigned")
268
+ if "tenant" in payload and str(payload.get("tenant") or "") != str(tenant):
269
+ raise PermissionError("an Application cannot be created for another tenant")
270
+ template_kind = str(payload.get("templateKind") or "").strip().lower()
271
+ if template_kind and template_kind not in APPLICATION_TEMPLATE_KINDS:
272
+ raise ApplicationError("application template kind is not recognized")
273
+ expected_type = (_TEMPLATE_CONTRACTS[template_kind]["applicationType"]
274
+ if template_kind else "")
275
+ kind = str(payload.get("type") or expected_type).strip().lower()
276
+ if kind not in APPLICATION_TYPES:
277
+ raise ApplicationError("application type is not recognized")
278
+ if template_kind:
279
+ if kind != expected_type:
280
+ raise ApplicationError(
281
+ f"{template_kind} template Applications require type {expected_type!r}")
282
+ return _template_definition(
283
+ template_kind, payload, semantic_records=semantic_records,
284
+ field_contracts=field_contracts, allowed_databases=allowed_databases)
285
+ if any(key in payload for key in ("sourceDatabase", "fieldMap", "navPlacement")):
286
+ raise ApplicationError("only a template Application may carry template fields")
287
+ return {}
288
+
289
+
290
  def _public(app, user, is_admin=False, *, allowed_databases=None, target_database=None,
291
  is_default=False):
292
  row=copy.deepcopy(app)
 
322
  return sorted(rows,key=lambda x:(str(x.get("updatedAt") or ""),str(x.get("id"))),reverse=True)
323
 
324
 
325
+ def create(runtime, tenant, user, payload, *, semantic_records=None, field_contracts=None,
326
+ allowed_databases=None):
327
  payload=payload if isinstance(payload,dict) else {}
328
+ template_kind=str(payload.get("templateKind") or "").strip().lower()
329
+ expected_type = (_TEMPLATE_CONTRACTS.get(template_kind) or {}).get("applicationType")
330
+ kind=str(payload.get("type") or expected_type or "").strip().lower()
331
+ definition = validate_application(
332
+ payload, tenant, semantic_records=semantic_records, field_contracts=field_contracts,
333
+ allowed_databases=allowed_databases)
334
  name=" ".join(str(payload.get("name") or "").split())[:120]
335
  if not name: raise ApplicationError("application name is required")
336
  app_id=f"app_{uuid.uuid4().hex[:16]}"; now=dt.datetime.now(dt.timezone.utc).isoformat()
337
+ compatible = ([definition["sourceDatabase"]] if definition
338
+ else _compat(payload.get("compatibleDatabases")))
339
  if _allowed(compatible, allowed_databases) != set(compatible):
340
  raise PermissionError("an Application cannot bind a database you cannot open")
341
+ raw_config = payload.get("config")
342
+ if definition and raw_config is None:
343
+ raw_config = {"schemaVersion": 1,
344
+ "display": {"mode": _TEMPLATE_CONTRACTS[template_kind]["displayMode"]}}
345
  app={"id":app_id,"tenant":str(tenant),"type":kind,"name":name,
346
  "compatibleDatabases":compatible,
347
  "semanticRoleBindings":_governed_bindings(
348
  payload.get("semanticRoleBindings"), compatible, semantic_records or {}),
349
+ "config":_typed_config(kind, raw_config),
350
  "share":{"mode":"private","users":[]},"starredBy":[],"createdBy":user,
351
  "createdAt":now,"updatedAt":now,"revision":1}
352
+ app.update(definition)
353
  def apply(raw):
354
  doc=_clean_doc(raw)
355
  if len(doc["applications"])>=_MAX: raise ApplicationError("application limit reached")
 
361
  def mutate(runtime, app_id, user, is_admin, patch, *, semantic_records=None,
362
  allowed_databases=None, target_database=None):
363
  patch=patch if isinstance(patch,dict) else {}; landed={}
364
+ immutable = sorted(set(patch) & {
365
+ "id", "tenant", "type", "templateKind", "sourceDatabase", "fieldMap", "navPlacement"
366
+ })
367
+ if immutable:
368
+ raise ApplicationError("Application identity and template definition are immutable: "
369
+ + ", ".join(immutable))
370
  def apply(raw):
371
  doc=_clean_doc(raw); app=doc["applications"].get(app_id)
372
  if not app: raise ApplicationError("application does not exist")
373
  if not _allowed(app.get("compatibleDatabases"), allowed_databases):
374
  raise ApplicationError("application does not exist")
375
+ if app.get("templateKind") in APPLICATION_TEMPLATE_KINDS and "compatibleDatabases" in patch:
376
+ raise ApplicationError("a template Application's sourceDatabase is immutable")
377
  star_only = set(patch) <= {"starred"}
378
  if star_only:
379
  if not may_read(app,user,is_admin): raise PermissionError("application is not available")
 
411
 
412
 
413
  def duplicate(runtime, app_id, tenant, user, is_admin=False, *, semantic_records=None,
414
+ field_contracts=None, allowed_databases=None):
415
  app=load(runtime)["applications"].get(app_id)
416
  if not may_read(app,user,is_admin): raise ApplicationError("application does not exist")
417
  if not _allowed(app.get("compatibleDatabases"), allowed_databases):
418
  raise ApplicationError("application does not exist")
419
+ payload={"type":app["type"],"name":f"{app['name']} copy",
420
  "compatibleDatabases":app.get("compatibleDatabases"),
421
+ "semanticRoleBindings":app.get("semanticRoleBindings"),"config":app.get("config")}
422
+ for key in ("templateKind", "sourceDatabase", "fieldMap", "navPlacement"):
423
+ if key in app: payload[key]=copy.deepcopy(app[key])
424
+ return create(runtime,tenant,user,payload,
425
+ semantic_records=semantic_records, field_contracts=field_contracts,
426
+ allowed_databases=allowed_databases)
427
 
428
 
429
  def delete(runtime, app_id, user, is_admin=False, *, allowed_databases=None):
api/connectors_amazon.py CHANGED
@@ -41,6 +41,100 @@ from harness.amazon_client import ( # noqa: F
41
  #: comments in `keychain.py` warn about it in as many words.
42
  ENTRY_TYPE = "amazon_sp"
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  def probe_credential(fields, timeout=8):
46
  """`{ok, message}` for a stored `amazon_sp` credential: the keychain's liveness probe.
 
41
  #: comments in `keychain.py` warn about it in as many words.
42
  ENTRY_TYPE = "amazon_sp"
43
 
44
+ #: W55-T19 / R7 / C10 β€” AMAZON'S OWN ENABLEMENT DOCUMENT. This is deliberately not Odoo's
45
+ #: model catalogue or connector config: Amazon publishes report schemas, not ``fields_get``, and
46
+ #: its seven databases are enabled at the provider boundary rather than masquerading as Odoo
47
+ #: models. The document lives on the request's tenant runtime, so two tenants can make opposite
48
+ #: choices without a process-global map ever seeing either answer.
49
+ ENABLEMENT_KEY = "amazon_connector_enablement"
50
+ ENABLEMENT_ROUTE = "/connectors/amazon_sp/databases/{databaseKey}/enablement"
51
+
52
+
53
+ class EnablementConfigError(ValueError):
54
+ """The tenant's stored Amazon enablement document is malformed."""
55
+
56
+
57
+ def database_keys():
58
+ """The authored Amazon database keys, derived from the connector's one report roster."""
59
+ return tuple("ut_amzn_" + str(name) for name in REPORT_TYPES)
60
+
61
+
62
+ def read_database_enablement(rt):
63
+ """Return this tenant's fail-closed Amazon database enablement state.
64
+
65
+ An absent document preserves the connector's shipped behaviour: all seven databases are on.
66
+ Once a document exists, every value must be a real boolean and every key must belong to the
67
+ authored Amazon roster. A malformed or unreadable document disables every row in the detail
68
+ response and marks the capability unavailable; it never guesses through corrupt tenant state.
69
+ """
70
+ keys = database_keys()
71
+ try:
72
+ current = rt.get(ENABLEMENT_KEY) if rt is not None else None
73
+ except Exception: # noqa: BLE001
74
+ return {"available": False, "databases": {key: False for key in keys}}
75
+ # Runtime/store readers use ``{}`` for a genuinely absent document, so both empty forms are
76
+ # the migration default rather than malformed state.
77
+ if current is None or current == {}:
78
+ return {"available": True, "databases": {key: True for key in keys}}
79
+ if not isinstance(current, dict):
80
+ return {"available": False, "databases": {key: False for key in keys}}
81
+ stored = current.get("databases")
82
+ if not isinstance(stored, dict):
83
+ return {"available": False, "databases": {key: False for key in keys}}
84
+ if (set(stored) - set(keys)
85
+ or any(type(value) is not bool for value in stored.values())):
86
+ return {"available": False, "databases": {key: False for key in keys}}
87
+ return {"available": True,
88
+ # Absent keys stay on so a later report addition does not silently disappear for
89
+ # every tenant that saved an older version of this document.
90
+ "databases": {key: stored.get(key, True) for key in keys}}
91
+
92
+
93
+ def set_database_enabled(rt, database_key, enabled):
94
+ """Persist one tenant's Amazon database choice without touching its materialised rows."""
95
+ key = str(database_key or "").strip()
96
+ known = set(database_keys())
97
+ if key not in known:
98
+ raise KeyError(key)
99
+ if type(enabled) is not bool:
100
+ raise ValueError("enabled must be true or false")
101
+
102
+ def _set(current):
103
+ if current is None:
104
+ current = {}
105
+ if not isinstance(current, dict):
106
+ raise EnablementConfigError("the stored Amazon enablement document is malformed")
107
+ stored = current.get("databases", {})
108
+ if not isinstance(stored, dict):
109
+ raise EnablementConfigError("the stored Amazon database choices are malformed")
110
+ if (set(stored) - known
111
+ or any(type(value) is not bool for value in stored.values())):
112
+ raise EnablementConfigError("the stored Amazon database choices are malformed")
113
+ # A fresh document contains the whole current roster. That makes the stored answer
114
+ # inspectable while retaining the migration rule above for future database additions.
115
+ choices = {name: stored.get(name, True) for name in database_keys()}
116
+ choices[key] = enabled
117
+ return {**current, "databases": choices}
118
+
119
+ rt.update(ENABLEMENT_KEY, _set, flush="sync")
120
+ return read_database_enablement(rt)
121
+
122
+
123
+ def enablement_capability(rt, is_admin):
124
+ """The provider-aware capability served by Amazon's connector detail response."""
125
+ state = read_database_enablement(rt)
126
+ can_manage = bool(is_admin) and state["available"]
127
+ return {"provider": ENTRY_TYPE,
128
+ "mode": "database",
129
+ "canManage": can_manage,
130
+ # A member receives no write URL. The route still enforces administrator status; this
131
+ # is the matching affordance wall, not the permission boundary.
132
+ "updatePath": ENABLEMENT_ROUTE if can_manage else "",
133
+ # Disabling changes only this config document. No mirror or ``ut_amzn_*`` row is
134
+ # removed, so re-enabling resumes against the same materialised database.
135
+ "preservesData": True,
136
+ "available": state["available"]}
137
+
138
 
139
  def probe_credential(fields, timeout=8):
140
  """`{ok, message}` for a stored `amazon_sp` credential: the keychain's liveness probe.
api/deps.py CHANGED
@@ -103,10 +103,40 @@ class Session:
103
  # the Customer/Product pool builders, connector routes, provider routes, Odoo, or an environment
104
  # lookup from this boundary. A cache miss is a named refusal, never permission to refresh from the
105
  # source of truth. That is what "data the app already stores or serves" means in executable form.
106
- _ASSISTANT_BUILT_INS = {
 
 
 
 
107
  "customer_data": {"label": "Odoo customers", "cache_prefix": "pool"},
108
  "product_data": {"label": "Odoo products", "cache_prefix": "product_pool"},
109
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
 
112
  def _assistant_refuse(status, code, message):
 
103
  # the Customer/Product pool builders, connector routes, provider routes, Odoo, or an environment
104
  # lookup from this boundary. A cache miss is a named refusal, never permission to refresh from the
105
  # source of truth. That is what "data the app already stores or serves" means in executable form.
106
+ # These two keys name registry modules backed by runtime pools. They are DATABASES the product
107
+ # may open, but they are not materialised `ut_*` documents and they are not DuckDB read-through
108
+ # mirrors. Keeping that distinction in the request boundary prevents a route resolver from
109
+ # treating `product_data` as though `_sources()` could bind it to a mirror table.
110
+ MODULE_CACHE_DATABASES = {
111
  "customer_data": {"label": "Odoo customers", "cache_prefix": "pool"},
112
  "product_data": {"label": "Odoo products", "cache_prefix": "product_pool"},
113
  }
114
+ # The Assistant predates the public taxonomy above. Its private name remains an alias so its
115
+ # snapshot-only contract and every existing caller stay byte-for-byte unchanged.
116
+ _ASSISTANT_BUILT_INS = MODULE_CACHE_DATABASES
117
+
118
+
119
+ def module_cache_source(database: str):
120
+ """Metadata for a runtime-cache database, or None for every materialised/mirror key."""
121
+ meta = MODULE_CACHE_DATABASES.get(str(database or ""))
122
+ return dict(meta) if meta else None
123
+
124
+
125
+ def module_cache_rows(session: Session, database: str):
126
+ """The current viewer's scoped rows for one known runtime-cache database.
127
+
128
+ This is deliberately the interactive grid boundary, not the Assistant snapshot reader:
129
+ `scoped_table` applies the same team/agent and row grants as the module page, while
130
+ `Session.require` keeps the account and tenant-catalogue checks in their one chokepoint.
131
+ Unknown keys fail before either check, so an absent relation target cannot be mislabeled as
132
+ a permission denial.
133
+ """
134
+ key = str(database or "")
135
+ if module_cache_source(key) is None:
136
+ raise KeyError(key)
137
+ session.require(key)
138
+ import core.perm_scope as perm_scope
139
+ return list(perm_scope.scoped_table(session.user, key, st=session.runtime) or [])
140
 
141
 
142
  def _assistant_refuse(status, code, message):
api/odoo_relational.py CHANGED
@@ -48,6 +48,7 @@ wider link would count 31,418 documents and call them open invoices, so those tw
48
  the oracle's predicate as an explicit `payment_state` condition pair.
49
  """
50
  import datetime as _dt
 
51
 
52
  #: β›” ROUTE ENTITLEMENT, NOT THE SPAWN GATE β€” `refresh()` stopped reading this at W53-T39 / R3,
53
  #: which admits on CONFIGURED CREDENTIALS (`available()`) so a second Odoo tenant needs no edit.
@@ -1869,6 +1870,137 @@ def authoritative_schema_snapshot():
1869
  return models, errors
1870
 
1871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1872
  #: ⭐⭐ W53-T38 / C2 β€” THE CONNECTOR SCHEMA SPEC ODOO HAS NEVER HAD.
1873
  #:
1874
  #: Amazon and Meta each got a `ConnectorTableSpec` row per table in `platform/core/connector_spec.py`
@@ -2463,11 +2595,16 @@ def split_table_key(table_key):
2463
  keeps its legacy key.
2464
  """
2465
  raw = str(table_key or "").strip()
2466
- if raw in BASE_TABLE_KEYS:
2467
- return raw, None
 
 
 
2468
  base, sep, cid = raw.rpartition(CONNECTION_SEP)
2469
- if sep and cid and base in BASE_TABLE_KEYS:
2470
  return base, cid
 
 
2471
  return None, None
2472
 
2473
 
@@ -2550,7 +2687,10 @@ def table_subject_for(table_key):
2550
  DIFFERENT population from client A's, so the claim carries the connection with it.
2551
  """
2552
  base, cid = split_table_key(table_key)
2553
- subject = TABLE_SUBJECTS.get(base if base is not None else str(table_key or ""))
 
 
 
2554
  if not subject or not cid:
2555
  return subject
2556
  return f"{subject}@{cid}"
@@ -2737,17 +2877,49 @@ def read_config(rt):
2737
  "frozenAt": str(cur.get("frozenAt") or "")}
2738
 
2739
 
2740
- def grid_choices(rt):
2741
- """`[{key, label, enabled}]` for every grid this connector can materialise β€” DERIVED from
2742
- `TABLES`, never a second hand-typed list (contract C2's parity leg asserts exactly that).
2743
 
2744
  ⚠ ABSENT MEANS ENABLED. A tenant that has never opened the panel has every grid, which is
2745
  what they have today; only an explicit untick turns one off. The alternative β€” an empty
2746
  config meaning "nothing enabled" β€” would silently unspawn ten live databases on deploy.
 
 
 
 
 
 
2747
  """
2748
  chosen = read_config(rt)["grids"]
2749
- return [{"key": key, "label": label, "enabled": bool(chosen.get(key, True))}
2750
- for _bucket, key, label, _fields in TABLES]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2751
 
2752
 
2753
  def enabled_buckets(rt):
@@ -2756,6 +2928,14 @@ def enabled_buckets(rt):
2756
  return {bucket for bucket, key, _l, _f in TABLES if chosen.get(key, True)}
2757
 
2758
 
 
 
 
 
 
 
 
 
2759
  def sync_seconds(rt):
2760
  """How often this tenant's Odoo mirror should resync, or None for `manual` (R11).
2761
 
@@ -3157,6 +3337,119 @@ def _ensure_table_inplace(cur, key, label, fields, rows, username, stamp):
3157
  return counts
3158
 
3159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3160
  def is_royal(tenant):
3161
  """ENTITLEMENT by slug, kept verbatim for the five callers outside this module.
3162
 
@@ -3341,6 +3634,12 @@ def refresh(rt, tenant, username="automation", cur=None, today=None, connection_
3341
  plan_report = {}
3342
  written = apply_plan(rt, built, username=username, today=today, report=plan_report,
3343
  connection_id=ns)
 
 
 
 
 
 
3344
  # ⭐⭐ W49-T25 / C6 β€” THE SCHEMA CATALOGUE FOLLOWS THE CODE WITH NO MANUAL STEP. Runs AFTER the
3345
  # tables are applied, so the snapshot describes a pass that actually landed. The two early
3346
  # returns above are respected by construction: a tenant with no Odoo entitlement raised, and a
@@ -3349,6 +3648,9 @@ def refresh(rt, tenant, username="automation", cur=None, today=None, connection_
3349
  declared_report = _refresh_declared_schema(rt)
3350
  out = {"tables": written,
3351
  **({"schemaDeclared": declared_report} if declared_report else {}),
 
 
 
3352
  **({"retired": plan_report["retired"]} if plan_report.get("retired") else {}),
3353
  # R6's second sentence: a set that was deliberately not built SAYS SO, with the keys.
3354
  **({"skipped": skipped} if skipped else {}),
 
48
  the oracle's predicate as an explicit `payment_state` condition pair.
49
  """
50
  import datetime as _dt
51
+ import json as _json
52
 
53
  #: β›” ROUTE ENTITLEMENT, NOT THE SPAWN GATE β€” `refresh()` stopped reading this at W53-T39 / R3,
54
  #: which admits on CONFIGURED CREDENTIALS (`available()`) so a second Odoo tenant needs no edit.
 
1870
  return models, errors
1871
 
1872
 
1873
+ # The compiled TABLES tuple remains the curated mirror contract. This is the separate, per-tenant
1874
+ # discovery cache for every other Odoo model the active API account may read (W55-T17 / C9).
1875
+ MODEL_CATALOG_KEY = "odoo_readable_model_catalog"
1876
+ MODEL_CATALOG_VERSION = 1
1877
+ MODEL_READ_PAGE = 2000
1878
+ MODEL_CATALOG_TTL = _dt.timedelta(hours=6)
1879
+ _MODEL_FIELD_TYPES = {
1880
+ "boolean": "checkbox", "integer": "int", "float": "number", "monetary": "currency",
1881
+ "date": "date", "datetime": "datetime",
1882
+ }
1883
+
1884
+
1885
+ def discover_readable_models(client):
1886
+ """Read-only introspection over an injected Odoo client.
1887
+
1888
+ ``ir.model`` supplies candidates, ``check_access_rights('read')`` narrows them to this API
1889
+ account, and ``fields_get`` supplies only fields that account may inspect. No method in this
1890
+ path can mutate Odoo; the production client independently blocks write-shaped method names.
1891
+ """
1892
+ errors = []
1893
+ try:
1894
+ candidates = client.search_read(
1895
+ "ir.model", [], ["model", "name", "transient"], order="name,model")
1896
+ except Exception as exc: # noqa: BLE001
1897
+ return [], [f"ir.model: {type(exc).__name__}: {exc}"]
1898
+ rows = []
1899
+ for item in candidates or ():
1900
+ model = str((item or {}).get("model") or "").strip().lower()
1901
+ if not model:
1902
+ continue
1903
+ try:
1904
+ readable = client.execute_kw(
1905
+ model, "check_access_rights", ["read"], {"raise_exception": False})
1906
+ except Exception as exc: # noqa: BLE001
1907
+ errors.append(f"{model}: access: {type(exc).__name__}: {exc}")
1908
+ continue
1909
+ if not bool(readable):
1910
+ continue
1911
+ try:
1912
+ fields = client.fields_get(
1913
+ model, attributes=("string", "type", "required", "readonly", "relation"))
1914
+ except Exception as exc: # noqa: BLE001
1915
+ fields = {}
1916
+ errors.append(f"{model}: fields: {type(exc).__name__}: {exc}")
1917
+ clean_fields = {}
1918
+ for name, meta in (fields or {}).items():
1919
+ if not str(name).strip() or not isinstance(meta, dict):
1920
+ continue
1921
+ clean_fields[str(name)] = {k: meta.get(k) for k in
1922
+ ("string", "type", "required", "readonly", "relation")
1923
+ if k in meta}
1924
+ rows.append({"model": model,
1925
+ "name": " ".join(str((item or {}).get("name") or model).split()),
1926
+ "fields": clean_fields})
1927
+ rows.sort(key=lambda row: (str(row.get("name") or "").casefold(), row["model"]))
1928
+ return rows, errors
1929
+
1930
+
1931
+ def _catalog_slot(connection_id):
1932
+ return str(connection_id or DEFAULT_CONNECTION)
1933
+
1934
+
1935
+ def readable_model_catalog(rt, connection_id=None):
1936
+ """The last complete tenant-local catalogue; reading it never contacts Odoo."""
1937
+ try:
1938
+ cached = rt.get(MODEL_CATALOG_KEY) if rt is not None else None
1939
+ except Exception: # noqa: BLE001
1940
+ cached = None
1941
+ if not isinstance(cached, dict) or cached.get("version") != MODEL_CATALOG_VERSION:
1942
+ return {"version": MODEL_CATALOG_VERSION, "complete": False, "capturedAt": "",
1943
+ "models": [], "errors": []}
1944
+ cached = (cached.get("connections") or {}).get(_catalog_slot(connection_id)) or {}
1945
+ return {"version": MODEL_CATALOG_VERSION,
1946
+ "complete": cached.get("complete") is True,
1947
+ "capturedAt": str(cached.get("capturedAt") or ""),
1948
+ "models": [dict(row) for row in (cached.get("models") or ())
1949
+ if isinstance(row, dict) and row.get("model")],
1950
+ "errors": [str(value) for value in (cached.get("errors") or ())][:50]}
1951
+
1952
+
1953
+ def refresh_readable_model_catalog(rt, connection_id=None, client=None, force=False):
1954
+ """Populate one tenant's catalogue once, or explicitly refresh it; never widen on failure."""
1955
+ current = readable_model_catalog(rt, connection_id)
1956
+ if current["capturedAt"] and not force:
1957
+ try:
1958
+ captured = _dt.datetime.fromisoformat(current["capturedAt"])
1959
+ if _dt.datetime.now(_dt.timezone.utc) - captured < MODEL_CATALOG_TTL:
1960
+ return current
1961
+ except (TypeError, ValueError):
1962
+ pass
1963
+ source = None
1964
+ if client is None:
1965
+ try:
1966
+ source = (rt.odoo_source() if connection_id is None
1967
+ else rt.odoo_source(connection_id))
1968
+ except Exception: # noqa: BLE001
1969
+ source = None
1970
+ if source is None:
1971
+ return current
1972
+ try:
1973
+ if client is None:
1974
+ from core.odoo import get_odoo
1975
+ with source._bound(): # tenant credential + scope
1976
+ rows, errors = discover_readable_models(get_odoo())
1977
+ else:
1978
+ rows, errors = discover_readable_models(client)
1979
+ except Exception as exc: # noqa: BLE001
1980
+ rows, errors = [], [f"catalogue: {type(exc).__name__}: {exc}"]
1981
+ # A partial retry is not evidence that a previously readable model disappeared. Preserve a
1982
+ # complete, stamped catalogue in full whenever the new pass reports any error; otherwise one
1983
+ # refused model could silently shrink the enablement roster. A first-ever partial pass may be
1984
+ # retained for diagnostics, but an entirely failed pass still has no catalogue to publish.
1985
+ if errors and current["complete"] and current["capturedAt"]:
1986
+ return current
1987
+ if not rows and errors:
1988
+ return current
1989
+ captured = _dt.datetime.now(_dt.timezone.utc).isoformat()
1990
+ result = {"version": MODEL_CATALOG_VERSION, "complete": not errors,
1991
+ "capturedAt": captured, "models": rows, "errors": errors[:50]}
1992
+ slot = _catalog_slot(connection_id)
1993
+
1994
+ def _cache(current_cache):
1995
+ current_cache = dict(current_cache) if isinstance(current_cache, dict) else {}
1996
+ connections = dict(current_cache.get("connections") or {})
1997
+ connections[slot] = result
1998
+ return {"version": MODEL_CATALOG_VERSION, "connections": connections}
1999
+
2000
+ rt.update(MODEL_CATALOG_KEY, _cache, flush="sync")
2001
+ return result
2002
+
2003
+
2004
  #: ⭐⭐ W53-T38 / C2 β€” THE CONNECTOR SCHEMA SPEC ODOO HAS NEVER HAD.
2005
  #:
2006
  #: Amazon and Meta each got a `ConnectorTableSpec` row per table in `platform/core/connector_spec.py`
 
2595
  keeps its legacy key.
2596
  """
2597
  raw = str(table_key or "").strip()
2598
+ try:
2599
+ from core import connector_spec
2600
+ dynamic_prefix = connector_spec.ODOO_MODEL_TABLE_PREFIX
2601
+ except Exception: # noqa: BLE001
2602
+ dynamic_prefix = "ut_odoo_model_"
2603
  base, sep, cid = raw.rpartition(CONNECTION_SEP)
2604
+ if sep and cid and (base in BASE_TABLE_KEYS or base.startswith(dynamic_prefix)):
2605
  return base, cid
2606
+ if raw in BASE_TABLE_KEYS or raw.startswith(dynamic_prefix):
2607
+ return raw, None
2608
  return None, None
2609
 
2610
 
 
2687
  DIFFERENT population from client A's, so the claim carries the connection with it.
2688
  """
2689
  base, cid = split_table_key(table_key)
2690
+ raw_base = base if base is not None else str(table_key or "")
2691
+ subject = TABLE_SUBJECTS.get(raw_base)
2692
+ if subject is None and raw_base.startswith("ut_odoo_model_"):
2693
+ subject = f"odoo.model.{raw_base}"
2694
  if not subject or not cid:
2695
  return subject
2696
  return f"{subject}@{cid}"
 
2877
  "frozenAt": str(cur.get("frozenAt") or "")}
2878
 
2879
 
2880
+ def grid_choices(rt, connection_id=None):
2881
+ """Every API-readable model, with the curated TABLES roster retained as its stable front.
 
2882
 
2883
  ⚠ ABSENT MEANS ENABLED. A tenant that has never opened the panel has every grid, which is
2884
  what they have today; only an explicit untick turns one off. The alternative β€” an empty
2885
  config meaning "nothing enabled" β€” would silently unspawn ten live databases on deploy.
2886
+
2887
+ W55-T17 keeps two facts separate: ``TABLES`` is what the mirror materialiser knows, while the
2888
+ tenant-local catalogue is what this API account may read. A readable model already represented
2889
+ by a curated table is covered there; every remaining readable model receives a stable raw-model
2890
+ key and defaults off. Stored choices survive catalogue refreshes because config is keyed by the
2891
+ stable database key, never by its position.
2892
  """
2893
  chosen = read_config(rt)["grids"]
2894
+ catalogue = readable_model_catalog(rt, connection_id)
2895
+ fixed = [{"key": key, "label": label, "model": ODOO_TABLE_MODELS.get(key, ""),
2896
+ "relevant": True, "defaultEnabled": True,
2897
+ "enabled": bool(chosen.get(key, True))}
2898
+ for _bucket, key, label, _fields in TABLES]
2899
+ # Before discovery, keep the established curated defaults. A complete stamped catalogue is
2900
+ # authoritative for this API account, so a curated database whose model is absent must not be
2901
+ # offered: relevance never widens access.
2902
+ if catalogue["complete"] and catalogue["capturedAt"]:
2903
+ readable = {str(row.get("model") or "") for row in catalogue["models"]}
2904
+ fixed = [row for row in fixed if not row["model"] or row["model"] in readable]
2905
+ covered = {row["model"] for row in fixed if row["model"]}
2906
+ dynamic = []
2907
+ try:
2908
+ from core import connector_spec
2909
+ for item in catalogue["models"]:
2910
+ model = str(item.get("model") or "")
2911
+ if not model or model in covered:
2912
+ continue
2913
+ key = connector_spec.odoo_model_table_key(model)
2914
+ dynamic.append({"key": key,
2915
+ "label": connector_spec.odoo_model_label(model, item.get("name")),
2916
+ "model": model, "relevant": False, "defaultEnabled": False,
2917
+ "enabled": chosen.get(key) is True})
2918
+ except Exception: # noqa: BLE001
2919
+ dynamic = []
2920
+ return sorted(fixed + dynamic,
2921
+ key=lambda row: (not row["enabled"], not row["relevant"],
2922
+ str(row["label"]).casefold(), row["key"]))
2923
 
2924
 
2925
  def enabled_buckets(rt):
 
2928
  return {bucket for bucket, key, _l, _f in TABLES if chosen.get(key, True)}
2929
 
2930
 
2931
+ def enabled_discovered_models(rt, connection_id=None):
2932
+ """The explicitly enabled long-tail model rows; curated TABLES never enter this set."""
2933
+ fixed = {str(model) for model in ODOO_TABLE_MODELS.values() if model}
2934
+ return [row for row in grid_choices(rt, connection_id)
2935
+ if row.get("enabled") is True and row.get("model") not in fixed
2936
+ and str(row.get("key") or "").startswith("ut_odoo_model_")]
2937
+
2938
+
2939
  def sync_seconds(rt):
2940
  """How often this tenant's Odoo mirror should resync, or None for `manual` (R11).
2941
 
 
3337
  return counts
3338
 
3339
 
3340
+ def _model_field_specs(catalogue_row):
3341
+ """Safe grid fields for one discovered model; binary payloads are never copied into cells."""
3342
+ fields = catalogue_row.get("fields") if isinstance(catalogue_row, dict) else {}
3343
+ fields = fields if isinstance(fields, dict) else {}
3344
+ ordered = sorted(fields.items(), key=lambda item: (item[0] != "id", item[0]))
3345
+ out = []
3346
+ for raw_name, meta in ordered:
3347
+ meta = meta if isinstance(meta, dict) else {}
3348
+ raw_type = str(meta.get("type") or "char")
3349
+ if raw_type == "binary":
3350
+ continue
3351
+ out.append({"key": str(raw_name),
3352
+ "label": str(meta.get("string") or raw_name),
3353
+ "type": _MODEL_FIELD_TYPES.get(raw_type, "text"),
3354
+ "source": "odoo",
3355
+ "automation": {"preset": True}})
3356
+ if not any(field["key"] == "id" for field in out):
3357
+ out.insert(0, {"key": "id", "label": "ID", "type": "int", "source": "odoo",
3358
+ "automation": {"preset": True}})
3359
+ for preferred in ("display_name", "name", "id"):
3360
+ match = next((field for field in out if field["key"] == preferred), None)
3361
+ if match is not None:
3362
+ match["pinned"] = True
3363
+ break
3364
+ return out
3365
+
3366
+
3367
+ def _model_cell(value):
3368
+ """Make XML-RPC relation/list values durable without inventing a relation to another table."""
3369
+ if isinstance(value, (list, tuple, dict)):
3370
+ return _json.dumps(value, ensure_ascii=False, sort_keys=isinstance(value, dict))
3371
+ return value
3372
+
3373
+
3374
+ def _read_model_rows(client, catalogue_row):
3375
+ """Read one explicitly enabled model in stable pages; every call is a read method."""
3376
+ model = str(catalogue_row.get("model") or "")
3377
+ fields = [field["key"] for field in _model_field_specs(catalogue_row)]
3378
+ rows, offset = [], 0
3379
+ while True:
3380
+ page = client.search_read(model, [], fields, limit=MODEL_READ_PAGE,
3381
+ offset=offset, order="id")
3382
+ for item in page or ():
3383
+ rid = (item or {}).get("id")
3384
+ if rid in (None, ""):
3385
+ continue
3386
+ rows.append({"_id": str(rid),
3387
+ **{name: _model_cell((item or {}).get(name)) for name in fields}})
3388
+ if len(page or ()) < MODEL_READ_PAGE:
3389
+ break
3390
+ offset += len(page)
3391
+ return rows
3392
+
3393
+
3394
+ def sync_discovered_models(rt, source_connection_id=None, namespace=None,
3395
+ username="automation", today=None):
3396
+ """Materialise only explicitly enabled long-tail models, atomically and tenant-bound.
3397
+
3398
+ Disabled models are absent from this pass rather than represented by an empty row set. That
3399
+ distinction is the preservation guarantee: no updater touches their definition, rows, fields,
3400
+ grants, ownership, or tenant rename, and re-enabling resumes against the same stable key.
3401
+ """
3402
+ catalogue = refresh_readable_model_catalog(rt, connection_id=source_connection_id)
3403
+ by_model = {str(row.get("model") or ""): row for row in catalogue.get("models") or ()}
3404
+ selected = [choice for choice in enabled_discovered_models(rt, source_connection_id)
3405
+ if str(choice.get("model") or "") in by_model]
3406
+ if not selected:
3407
+ return {}
3408
+ ut = _ut()
3409
+ existing = dict(rt.get(ut.STORE_KEY) or {})
3410
+ keys = [table_key_for(str(choice["key"]), namespace) for choice in selected]
3411
+ missing = [key for key in keys if key not in existing]
3412
+ if missing and len(existing) + len(missing) > ut.MAX_TABLES:
3413
+ raise Refused(f"tenant holds {len(existing)} of MAX_TABLES={ut.MAX_TABLES} databases and "
3414
+ f"needs {len(missing)} more enabled Odoo models; nothing was created")
3415
+ source = (rt.odoo_source() if source_connection_id is None
3416
+ else rt.odoo_source(source_connection_id))
3417
+ if source is None:
3418
+ raise Refused("the selected Odoo connection is unavailable, so no discovered model was read")
3419
+ prepared, errors = [], []
3420
+ from core.odoo import get_odoo
3421
+ with source._bound(): # tenant credential + scope
3422
+ client = get_odoo()
3423
+ for choice, key in zip(selected, keys):
3424
+ model = str(choice["model"])
3425
+ row = by_model[model]
3426
+ try:
3427
+ values = _read_model_rows(client, row)
3428
+ except Exception as exc: # noqa: BLE001
3429
+ errors.append(f"{model}: {type(exc).__name__}: {exc}")
3430
+ continue
3431
+ stored_n = len(((existing.get(key) or {}).get("rows")) or {})
3432
+ if stored_n and len(values) < stored_n * MAX_SHRINK:
3433
+ errors.append(f"{model}: read returned {len(values)} rows against {stored_n} "
3434
+ "stored; preserved the prior database instead")
3435
+ continue
3436
+ prepared.append((key, str(choice["label"]), _model_field_specs(row), values, model))
3437
+ written = {}
3438
+ stamp = today or _iso_today()
3439
+ ut.register_connected(*(key for key, _label, _fields, _rows, _model in prepared))
3440
+
3441
+ def _apply(cur):
3442
+ cur = cur if isinstance(cur, dict) else {}
3443
+ for key, label, fields, rows, model in prepared:
3444
+ written[key] = _ensure_table_inplace(cur, key, label, fields, rows, username, stamp)
3445
+ cur[key]["connector"] = {"key": "odoo", "model": model, "readOnly": True}
3446
+ return cur
3447
+
3448
+ if prepared:
3449
+ rt.update(ut.STORE_KEY, _apply, flush="sync")
3450
+ return {"tables": written, "errors": errors}
3451
+
3452
+
3453
  def is_royal(tenant):
3454
  """ENTITLEMENT by slug, kept verbatim for the five callers outside this module.
3455
 
 
3634
  plan_report = {}
3635
  written = apply_plan(rt, built, username=username, today=today, report=plan_report,
3636
  connection_id=ns)
3637
+ # The fixed mirror roster above and the discovered long tail deliberately use separate
3638
+ # materialisers. Only an explicit long-tail enablement reaches this read-only path; disabled
3639
+ # databases are not passed an empty set and therefore cannot be erased by reconciliation.
3640
+ discovered_report = (sync_discovered_models(
3641
+ rt, source_connection_id=connection_id, namespace=ns, username=username, today=today)
3642
+ if rt is not None else {})
3643
  # ⭐⭐ W49-T25 / C6 β€” THE SCHEMA CATALOGUE FOLLOWS THE CODE WITH NO MANUAL STEP. Runs AFTER the
3644
  # tables are applied, so the snapshot describes a pass that actually landed. The two early
3645
  # returns above are respected by construction: a tenant with no Odoo entitlement raised, and a
 
3648
  declared_report = _refresh_declared_schema(rt)
3649
  out = {"tables": written,
3650
  **({"schemaDeclared": declared_report} if declared_report else {}),
3651
+ **({"discovered": discovered_report}
3652
+ if discovered_report and (discovered_report.get("tables")
3653
+ or discovered_report.get("errors")) else {}),
3654
  **({"retired": plan_report["retired"]} if plan_report.get("retired") else {}),
3655
  # R6's second sentence: a set that was deliberately not built SAYS SO, with the keys.
3656
  **({"skipped": skipped} if skipped else {}),
api/routes_connectors.py CHANGED
@@ -1107,6 +1107,26 @@ def _schema_catalog(session):
1107
  return _schema_catalog_rt(session.runtime)
1108
 
1109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1110
  def _schema_catalog_rt(rt):
1111
  """The same catalogue, over a RUNTIME rather than a session.
1112
 
@@ -1119,7 +1139,7 @@ def _schema_catalog_rt(rt):
1119
  import core.user_tables as user_tables
1120
  enabled = rt.get(_ODOO_SCHEMA_ENABLEMENTS) or {}
1121
  snapshot = user_tables.odoo_schema_snapshot(rt)
1122
- raw_models = snapshot.get("models") or {}
1123
  if raw_models:
1124
  rows = []
1125
  for model, raw_fields in raw_models.items():
@@ -1156,10 +1176,21 @@ def odoo_schema(session: Session = Depends(require_session)):
1156
  fields = _schema_catalog(session)
1157
  import core.user_tables as user_tables
1158
  snapshot = user_tables.odoo_schema_snapshot(session.runtime)
 
 
 
 
 
 
 
 
1159
  return {"fields": fields, "default": "off", "adminOnly": True,
1160
- "complete": snapshot.get("complete") is True,
1161
- "capturedAt": snapshot.get("capturedAt"),
1162
- "errors": list(snapshot.get("errors") or ()), "source": "Odoo"}
 
 
 
1163
 
1164
 
1165
  @router.patch("/connectors/odoo/schema/{field_key}")
@@ -1168,7 +1199,13 @@ def odoo_schema_enable(field_key: str, body: dict = Body(default=None),
1168
  _odoo_admin(session)
1169
  import core.user_tables as user_tables
1170
  _snapshot = user_tables.odoo_schema_snapshot(session.runtime)
1171
- if _snapshot.get("complete") is not True:
 
 
 
 
 
 
1172
  raise err(409, "odoo_schema_unavailable",
1173
  "run a successful schema sync before changing raw-field enablement")
1174
  known = {field["key"] for field in _schema_catalog(session)}
@@ -1294,6 +1331,18 @@ def _detail_connect(entry_type, is_admin):
1294
  "tenantWide": tenant_wide}
1295
 
1296
 
 
 
 
 
 
 
 
 
 
 
 
 
1297
  def _oauth_slot_entries(rt, uname, row):
1298
  """A per-user OAuth connection, rendered as C4's `keychain` entry shape.
1299
 
@@ -1332,7 +1381,8 @@ def _oauth_slot_entries(rt, uname, row):
1332
  # A per-user slot is personal by construction, in the vocabulary `routes_keychain`
1333
  # already declares. Never a third word for the same idea.
1334
  "scope": "personal",
1335
- "testable": False}]
 
1336
 
1337
 
1338
  def _detail_keychain(rt, uname, is_admin, row):
@@ -1353,6 +1403,7 @@ def _detail_keychain(rt, uname, is_admin, row):
1353
  # already decided admin vs member vs nothing, and deciding again here is how two answers to
1354
  # one question get born ([[one-question-two-normalizers]]).
1355
  can_connect = manage in ("keychain", "keychain_personal")
 
1356
  entries = []
1357
  if entry_type:
1358
  try:
@@ -1370,6 +1421,11 @@ def _detail_keychain(rt, uname, is_admin, row):
1370
  # xmlrpc check otherwise. The flag says whether a Test control would have
1371
  # something to call, and it always does.
1372
  "testable": True,
 
 
 
 
 
1373
  })
1374
  except Exception: # noqa: BLE001
1375
  entries = []
@@ -1398,9 +1454,7 @@ def _odoo_catalog_by_model(rt):
1398
  not offer. Today that diff is empty, which is the honest answer, and it fills itself the moment
1399
  the catalogue starts filtering instead of needing somebody to remember.
1400
  """
1401
- import core.user_tables as user_tables
1402
- snapshot = user_tables.odoo_schema_snapshot(rt)
1403
- raw_models = snapshot.get("models") or {}
1404
  offered = {}
1405
  for row in _schema_catalog_rt(rt):
1406
  offered.setdefault(str(row.get("model") or ""), []).append(row)
@@ -1675,13 +1729,13 @@ def _detail_databases(rt, is_admin, connector_key, uname=""):
1675
  shared = {}
1676
  for choice in choices:
1677
  key = str(choice.get("key") or "")
1678
- model = str(models.get(key) or "")
1679
  if model:
1680
  shared.setdefault(model, []).append(key)
1681
  out = []
1682
  for choice in choices:
1683
  key = str(choice.get("key") or "")
1684
- model = str(models.get(key) or "")
1685
  fields, excluded = catalog.get(model, ([], []))
1686
  # ⚠ THE SPEC WINS WHERE IT SPEAKS, AND THE MIRROR STILL GROUPS. `native` is a DISPLAY fact
1687
  # (what Odoo calls this table); `shared` above is keyed by the model the ENABLEMENT flag
@@ -1721,13 +1775,16 @@ def _amazon_databases(rt, is_admin, spec=None):
1721
 
1722
  ⚠ NO FIELD TOGGLES. `canToggleFields` is False for Amazon in `_detail_introspection`; there is
1723
  no `PATCH /connectors/amazon_sp/schema/{field}` route and this wave does not build one. Fields
1724
- are disclosed, not switched, and a control that could only ever 409 is R7's banned shape.
 
1725
  """
1726
  try:
1727
  from harness import amazon_schema
1728
  import connectors_amazon as cx
1729
  except Exception: # noqa: BLE001
1730
  return []
 
 
1731
  cat = amazon_schema.catalogue()
1732
  tables = cat.get("tables") or {}
1733
 
@@ -1771,7 +1828,10 @@ def _amazon_databases(rt, is_admin, spec=None):
1771
  "defaultLabel": str(declared.get("label")
1772
  or LABELS_AMAZON.get(key) or key),
1773
  "native": str(declared.get("native") or rep),
1774
- "enabled": True,
 
 
 
1775
  "fields": fields,
1776
  "excluded": excluded,
1777
  "sharesFieldsWith": [k for k in by_report.get(rep, ()) if k != key]})
@@ -1849,10 +1909,10 @@ def _detail_introspection(rt, is_admin, row):
1849
  "catalogueComplete": False, "capturedAt": "", "excludedBasis": ""}
1850
  if key == "amazon_sp":
1851
  # ⭐⭐ W52 Β· R6. Introspectable under the AMENDED test (a real schema artifact, not a
1852
- # `fields_get`), and deliberately with NO toggles: there is no Amazon field-toggle route
1853
- # and no Amazon table-config route, so both flags are False. A control that could only
1854
- # ever 409 is R7's banned shape, and naming the connector introspectable buys the
1855
- # DISCLOSURE only.
1856
  #
1857
  # β›” `catalogueComplete` IS FALSE AND SAYING SO IS THE HONEST ANSWER. Only two of the seven
1858
  # tables have a published artifact; the other five measure their columns from the report's
@@ -1882,8 +1942,13 @@ def _detail_introspection(rt, is_admin, row):
1882
  try:
1883
  import core.user_tables as user_tables
1884
  snapshot = user_tables.odoo_schema_snapshot(rt)
1885
- complete = snapshot.get("complete") is True
1886
- captured = str(snapshot.get("capturedAt") or "")
 
 
 
 
 
1887
  except Exception: # noqa: BLE001
1888
  complete, captured = False, ""
1889
  return {"introspectable": True,
@@ -1903,13 +1968,13 @@ def _detail_introspection(rt, is_admin, row):
1903
  def _detail_overview(row, databases, graph):
1904
  """C4's `overview` half: what the modal's first tab reads, top to bottom.
1905
 
1906
- `creates` is the table LABELS this connector stands behind: the declared grids when the
1907
  connector declares any, and otherwise the tables its own permitted graph actually found. Both
1908
  are real readings of THIS workspace; neither is a provider template.
1909
  """
1910
  creates = [str(entry.get("label") or "") for entry in (databases or [])
1911
- if str(entry.get("label") or "")]
1912
- if not creates and isinstance(graph, dict) and graph.get("status") == "ready":
1913
  creates = [str(table.get("label") or "") for table in (graph.get("tables") or ())
1914
  if str(table.get("label") or "")]
1915
  return {"key": str(row.get("key") or ""),
@@ -1925,6 +1990,24 @@ def _detail_overview(row, databases, graph):
1925
  "creates": creates}
1926
 
1927
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1928
  def connector_detail(rt, user, uname, is_admin, connector_key):
1929
  """The whole C4 detail DTO for one connector, or `None` when this reader has no such card.
1930
 
@@ -1946,6 +2029,9 @@ def connector_detail(rt, user, uname, is_admin, connector_key):
1946
  return {"overview": _detail_overview(row, databases, graph),
1947
  "keychain": _detail_keychain(rt, uname, bool(is_admin), row),
1948
  "databases": databases,
 
 
 
1949
  # ⭐ W49-T14 / R24 β€” WHETHER THE DATABASES TAB MAY DISCLOSE ANYTHING AT ALL, and what
1950
  # THIS reader may do there. An addition to C4, declared on `_detail_introspection`:
1951
  # without it an empty `databases` list is "this connector has no schema" and "this
@@ -1957,6 +2043,52 @@ def connector_detail(rt, user, uname, is_admin, connector_key):
1957
  "relationships": graph}
1958
 
1959
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1960
  # ⚠ DECLARED AFTER THE LITERAL `/connectors/odoo/*` ROUTES. FastAPI matches in declaration order,
1961
  # and while none of those ends in `/detail` β€” so no shadowing is possible today β€” the ordering is
1962
  # the habit that keeps it impossible tomorrow. `/connectors/directory` is two segments and cannot
@@ -1977,6 +2109,155 @@ def connectors_detail(connector_key: str, session: Session = Depends(require_ses
1977
  return detail
1978
 
1979
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1980
  # ⚠ FIVE SEGMENTS, so it can collide with nothing already declared here: the literal Odoo routes
1981
  # are four (`/connectors/odoo/schema/{field_key}`) and `/detail` is three.
1982
  @router.patch("/connectors/{connector_key}/databases/{database_key}/name")
 
1107
  return _schema_catalog_rt(session.runtime)
1108
 
1109
 
1110
+ def _odoo_raw_models(rt, snapshot=None):
1111
+ """Raw fields from stamped discovery, or the legacy snapshot before discovery exists."""
1112
+ if snapshot is None:
1113
+ import core.user_tables as user_tables
1114
+ snapshot = user_tables.odoo_schema_snapshot(rt)
1115
+ legacy = dict((snapshot or {}).get("models") or {})
1116
+ try:
1117
+ import odoo_relational
1118
+ discovered = odoo_relational.readable_model_catalog(rt)
1119
+ except Exception: # noqa: BLE001
1120
+ discovered = {}
1121
+ if not discovered.get("capturedAt"):
1122
+ return legacy
1123
+ # A stamp means this tenant-bound account has spoken. Even a partial stamped set is safer
1124
+ # than adding snapshot-only models that the current account never proved it may read.
1125
+ return {str(item.get("model") or ""): dict(item.get("fields") or {})
1126
+ for item in (discovered.get("models") or ())
1127
+ if str(item.get("model") or "")}
1128
+
1129
+
1130
  def _schema_catalog_rt(rt):
1131
  """The same catalogue, over a RUNTIME rather than a session.
1132
 
 
1139
  import core.user_tables as user_tables
1140
  enabled = rt.get(_ODOO_SCHEMA_ENABLEMENTS) or {}
1141
  snapshot = user_tables.odoo_schema_snapshot(rt)
1142
+ raw_models = _odoo_raw_models(rt, snapshot)
1143
  if raw_models:
1144
  rows = []
1145
  for model, raw_fields in raw_models.items():
 
1176
  fields = _schema_catalog(session)
1177
  import core.user_tables as user_tables
1178
  snapshot = user_tables.odoo_schema_snapshot(session.runtime)
1179
+ try:
1180
+ import odoo_relational
1181
+ discovered = odoo_relational.readable_model_catalog(session.runtime)
1182
+ except Exception: # noqa: BLE001
1183
+ discovered = {}
1184
+ has_discovery = bool(discovered.get("capturedAt"))
1185
+ complete = (discovered.get("complete") is True if has_discovery
1186
+ else snapshot.get("complete") is True)
1187
  return {"fields": fields, "default": "off", "adminOnly": True,
1188
+ "complete": complete,
1189
+ "capturedAt": (discovered.get("capturedAt") if has_discovery
1190
+ else snapshot.get("capturedAt")),
1191
+ "errors": list((discovered.get("errors") if has_discovery
1192
+ else snapshot.get("errors")) or ()),
1193
+ "source": "Odoo"}
1194
 
1195
 
1196
  @router.patch("/connectors/odoo/schema/{field_key}")
 
1199
  _odoo_admin(session)
1200
  import core.user_tables as user_tables
1201
  _snapshot = user_tables.odoo_schema_snapshot(session.runtime)
1202
+ try:
1203
+ import odoo_relational
1204
+ _discovered_complete = odoo_relational.readable_model_catalog(
1205
+ session.runtime).get("complete") is True
1206
+ except Exception: # noqa: BLE001
1207
+ _discovered_complete = False
1208
+ if _snapshot.get("complete") is not True and not _discovered_complete:
1209
  raise err(409, "odoo_schema_unavailable",
1210
  "run a successful schema sync before changing raw-field enablement")
1211
  known = {field["key"] for field in _schema_catalog(session)}
 
1331
  "tenantWide": tenant_wide}
1332
 
1333
 
1334
+ def _replacement_field_specs(entry_type):
1335
+ """The write-only fields that may change on an existing credential.
1336
+
1337
+ This is deliberately a projection of the Connect descriptor rather than another provider
1338
+ vocabulary. URL, database, account and every future non-secret field stay server-held during
1339
+ replacement; only fields the existing descriptor marks secret cross this door.
1340
+ """
1341
+ spec = _detail_connect(entry_type, True) or {}
1342
+ return [dict(field) for field in (spec.get("fields") or [])
1343
+ if field.get("secret") is True and str(field.get("key") or "").strip()]
1344
+
1345
+
1346
  def _oauth_slot_entries(rt, uname, row):
1347
  """A per-user OAuth connection, rendered as C4's `keychain` entry shape.
1348
 
 
1381
  # A per-user slot is personal by construction, in the vocabulary `routes_keychain`
1382
  # already declares. Never a third word for the same idea.
1383
  "scope": "personal",
1384
+ "testable": False,
1385
+ "replaceable": False}]
1386
 
1387
 
1388
  def _detail_keychain(rt, uname, is_admin, row):
 
1403
  # already decided admin vs member vs nothing, and deciding again here is how two answers to
1404
  # one question get born ([[one-question-two-normalizers]]).
1405
  can_connect = manage in ("keychain", "keychain_personal")
1406
+ can_replace = bool(is_admin and can_connect and _replacement_field_specs(entry_type))
1407
  entries = []
1408
  if entry_type:
1409
  try:
 
1421
  # xmlrpc check otherwise. The flag says whether a Test control would have
1422
  # something to call, and it always does.
1423
  "testable": True,
1424
+ # W55-T18 / C10: credential replacement is an administrator action. The
1425
+ # client reads this wall instead of inferring it from scope or from whether
1426
+ # a masked preview happened to be visible. The replacement endpoint changes
1427
+ # this row's encrypted payload in place; no secret is added to this DTO.
1428
+ "replaceable": can_replace,
1429
  })
1430
  except Exception: # noqa: BLE001
1431
  entries = []
 
1454
  not offer. Today that diff is empty, which is the honest answer, and it fills itself the moment
1455
  the catalogue starts filtering instead of needing somebody to remember.
1456
  """
1457
+ raw_models = _odoo_raw_models(rt)
 
 
1458
  offered = {}
1459
  for row in _schema_catalog_rt(rt):
1460
  offered.setdefault(str(row.get("model") or ""), []).append(row)
 
1729
  shared = {}
1730
  for choice in choices:
1731
  key = str(choice.get("key") or "")
1732
+ model = str(choice.get("model") or models.get(key) or "")
1733
  if model:
1734
  shared.setdefault(model, []).append(key)
1735
  out = []
1736
  for choice in choices:
1737
  key = str(choice.get("key") or "")
1738
+ model = str(choice.get("model") or models.get(key) or "")
1739
  fields, excluded = catalog.get(model, ([], []))
1740
  # ⚠ THE SPEC WINS WHERE IT SPEAKS, AND THE MIRROR STILL GROUPS. `native` is a DISPLAY fact
1741
  # (what Odoo calls this table); `shared` above is keyed by the model the ENABLEMENT flag
 
1775
 
1776
  ⚠ NO FIELD TOGGLES. `canToggleFields` is False for Amazon in `_detail_introspection`; there is
1777
  no `PATCH /connectors/amazon_sp/schema/{field}` route and this wave does not build one. Fields
1778
+ are disclosed, not switched. Database enablement is a separate provider capability and route,
1779
+ never the generic Odoo-table flag consumed by `DatabasesTab`.
1780
  """
1781
  try:
1782
  from harness import amazon_schema
1783
  import connectors_amazon as cx
1784
  except Exception: # noqa: BLE001
1785
  return []
1786
+ enablement = cx.read_database_enablement(rt)
1787
+ enabled = enablement.get("databases") or {}
1788
  cat = amazon_schema.catalogue()
1789
  tables = cat.get("tables") or {}
1790
 
 
1828
  "defaultLabel": str(declared.get("label")
1829
  or LABELS_AMAZON.get(key) or key),
1830
  "native": str(declared.get("native") or rep),
1831
+ # W55-T19 / R7 β€” AMAZON'S OWN tenant-local answer. This is deliberately not
1832
+ # read from Odoo's grid config, and disabling it leaves every stored row and
1833
+ # definition untouched: only this provider config document changes.
1834
+ "enabled": enabled.get(key) is True,
1835
  "fields": fields,
1836
  "excluded": excluded,
1837
  "sharesFieldsWith": [k for k in by_report.get(rep, ()) if k != key]})
 
1909
  "catalogueComplete": False, "capturedAt": "", "excludedBasis": ""}
1910
  if key == "amazon_sp":
1911
  # ⭐⭐ W52 Β· R6. Introspectable under the AMENDED test (a real schema artifact, not a
1912
+ # `fields_get`), and deliberately with NO generic toggles: there is no Amazon field-toggle
1913
+ # route, and `canToggleTables` belongs to Odoo's config surface. W55-T19 serves Amazon's
1914
+ # database switches through the separate `enablement` capability instead, so this flag
1915
+ # stays False and can never send Amazon through an Odoo endpoint.
1916
  #
1917
  # β›” `catalogueComplete` IS FALSE AND SAYING SO IS THE HONEST ANSWER. Only two of the seven
1918
  # tables have a published artifact; the other five measure their columns from the report's
 
1942
  try:
1943
  import core.user_tables as user_tables
1944
  snapshot = user_tables.odoo_schema_snapshot(rt)
1945
+ import odoo_relational
1946
+ discovered = odoo_relational.readable_model_catalog(rt)
1947
+ has_discovery = bool(discovered.get("capturedAt"))
1948
+ complete = (discovered.get("complete") is True if has_discovery
1949
+ else snapshot.get("complete") is True)
1950
+ captured = str((discovered.get("capturedAt") if has_discovery
1951
+ else snapshot.get("capturedAt")) or "")
1952
  except Exception: # noqa: BLE001
1953
  complete, captured = False, ""
1954
  return {"introspectable": True,
 
1968
  def _detail_overview(row, databases, graph):
1969
  """C4's `overview` half: what the modal's first tab reads, top to bottom.
1970
 
1971
+ `creates` is the ENABLED table LABELS this connector stands behind: the declared grids when the
1972
  connector declares any, and otherwise the tables its own permitted graph actually found. Both
1973
  are real readings of THIS workspace; neither is a provider template.
1974
  """
1975
  creates = [str(entry.get("label") or "") for entry in (databases or [])
1976
+ if entry.get("enabled") is True and str(entry.get("label") or "")]
1977
+ if not databases and isinstance(graph, dict) and graph.get("status") == "ready":
1978
  creates = [str(table.get("label") or "") for table in (graph.get("tables") or ())
1979
  if str(table.get("label") or "")]
1980
  return {"key": str(row.get("key") or ""),
 
1990
  "creates": creates}
1991
 
1992
 
1993
+ def _detail_enablement(rt, is_admin, row):
1994
+ """A provider-owned enablement capability, or ``None`` when this connector has no door.
1995
+
1996
+ Amazon is intentionally the first entry and is named here rather than inferred from whether a
1997
+ database list happened to be non-empty. Odoo keeps its model-catalogue and config routes;
1998
+ every other connector keeps no enablement affordance until its provider declares one.
1999
+ """
2000
+ if str(row.get("key") or "") != "amazon_sp":
2001
+ return None
2002
+ try:
2003
+ import connectors_amazon as cx
2004
+ return cx.enablement_capability(rt, bool(is_admin))
2005
+ except Exception: # noqa: BLE001
2006
+ # Fail closed. An unreadable provider capability is no write door.
2007
+ return {"provider": "amazon_sp", "mode": "database", "canManage": False,
2008
+ "updatePath": "", "preservesData": True, "available": False}
2009
+
2010
+
2011
  def connector_detail(rt, user, uname, is_admin, connector_key):
2012
  """The whole C4 detail DTO for one connector, or `None` when this reader has no such card.
2013
 
 
2029
  return {"overview": _detail_overview(row, databases, graph),
2030
  "keychain": _detail_keychain(rt, uname, bool(is_admin), row),
2031
  "databases": databases,
2032
+ # W55-T19 / R7 / C10 β€” a provider-specific capability. The client neither infers it
2033
+ # from ``introspectable`` nor sends Amazon through Odoo's schema/config endpoints.
2034
+ "enablement": _detail_enablement(rt, bool(is_admin), row),
2035
  # ⭐ W49-T14 / R24 β€” WHETHER THE DATABASES TAB MAY DISCLOSE ANYTHING AT ALL, and what
2036
  # THIS reader may do there. An addition to C4, declared on `_detail_introspection`:
2037
  # without it an empty `databases` list is "this connector has no schema" and "this
 
2043
  "relationships": graph}
2044
 
2045
 
2046
+ def _set_amazon_database_enablement(database_key, body, session):
2047
+ """The testable core of Amazon's tenant-scoped administrator enablement door."""
2048
+ if not session.admin:
2049
+ raise err(403, "not_admin",
2050
+ "only an administrator can change Amazon database enablement")
2051
+ if not session.runtime.available():
2052
+ raise err(503, "store_unavailable", "the tenant store is unavailable")
2053
+ request = body if isinstance(body, dict) else {}
2054
+ if set(request) != {"enabled"} or type(request.get("enabled")) is not bool:
2055
+ raise err(400, "bad_enabled", "enabled must be true or false")
2056
+
2057
+ import connectors_amazon as cx # noqa: PLC0415 - provider owns state
2058
+ key = str(database_key or "").strip()
2059
+ try:
2060
+ state = cx.set_database_enabled(session.runtime, key, request["enabled"])
2061
+ except KeyError:
2062
+ # One refusal for blank, malformed and cross-provider keys. The response does not expose
2063
+ # the rest of the tenant's Amazon roster.
2064
+ raise err(404, "unknown_amazon_database",
2065
+ "Amazon does not declare a database with that key")
2066
+ except cx.EnablementConfigError:
2067
+ raise err(409, "amazon_enablement_unavailable",
2068
+ "the stored Amazon enablement settings are invalid. Nothing was changed.")
2069
+ except ValueError:
2070
+ raise err(400, "bad_enabled", "enabled must be true or false")
2071
+ except Exception: # noqa: BLE001
2072
+ raise err(503, "enablement_unconfirmed",
2073
+ "the server could not confirm the Amazon database setting. Reload before "
2074
+ "trying again.")
2075
+ return {"provider": cx.ENTRY_TYPE,
2076
+ "key": key,
2077
+ "enabled": state["databases"].get(key) is True,
2078
+ # This route changes only the provider config document. It never deletes a mirror or
2079
+ # a materialised table, and the wire states that invariant explicitly.
2080
+ "preservesData": True}
2081
+
2082
+
2083
+ # Literal and provider-owned. It appears before the generic connector detail route so future
2084
+ # dynamic route additions cannot turn Amazon enablement into an Odoo-model dispatch by accident.
2085
+ @router.patch("/connectors/amazon_sp/databases/{database_key}/enablement")
2086
+ def amazon_database_enablement(database_key: str, body: dict = Body(default=None),
2087
+ session: Session = Depends(require_session)):
2088
+ """Enable or disable one declared Amazon database for this tenant, without deleting data."""
2089
+ return _set_amazon_database_enablement(database_key, body, session)
2090
+
2091
+
2092
  # ⚠ DECLARED AFTER THE LITERAL `/connectors/odoo/*` ROUTES. FastAPI matches in declaration order,
2093
  # and while none of those ends in `/detail` β€” so no shadowing is possible today β€” the ordering is
2094
  # the habit that keeps it impossible tomorrow. `/connectors/directory` is two segments and cannot
 
2109
  return detail
2110
 
2111
 
2112
+ class _ReplacementConflict(Exception):
2113
+ """The addressed keychain row changed between replacement preparation and its store update."""
2114
+
2115
+
2116
+ def _encrypted_replacement_payload(kc, label, entry_type, fields, username):
2117
+ """Validate and encrypt through ``core.keychain.add_entry`` without writing a tenant row.
2118
+
2119
+ ``add_entry`` is the keychain's one validation, preview and Fernet implementation. A tiny
2120
+ memory-only runtime lets this route reuse it while discarding the temporary identity it mints;
2121
+ the tenant store sees only the later, single-row payload swap.
2122
+ """
2123
+ class _Stage:
2124
+ def __init__(self):
2125
+ self.bucket = {}
2126
+
2127
+ def get(self, name):
2128
+ return self.bucket if name == kc.KEY else {}
2129
+
2130
+ def update(self, name, fn, flush="sync"):
2131
+ if name != kc.KEY:
2132
+ raise RuntimeError("the keychain encryptor wrote an unexpected bucket")
2133
+ updated = fn(self.bucket)
2134
+ self.bucket = updated if updated is not None else self.bucket
2135
+ return self.bucket
2136
+
2137
+ stage = _Stage()
2138
+ temporary = kc.add_entry(stage, label, entry_type, fields, username)
2139
+ row = ((stage.bucket.get("entries") or {}).get(str(temporary.get("id") or "")) or {})
2140
+ if not row.get("enc"):
2141
+ raise RuntimeError("the keychain encryptor returned no encrypted payload")
2142
+ return {"enc": str(row["enc"]), "preview": str(row.get("preview") or "")}
2143
+
2144
+
2145
+ def _replace_connector_key(connector_key, entry_id, body, session):
2146
+ """Replace only one connector entry's declared secrets while preserving its identity.
2147
+
2148
+ The existing row remains untouched through validation, decryption, merge and encryption. The
2149
+ final store update compares the complete old row before swapping only ``enc`` and ``preview``;
2150
+ a concurrent rename or credential change therefore conflicts instead of being overwritten.
2151
+ Scope and owner live in a separate bucket and are never written by this operation.
2152
+ """
2153
+ if not session.admin:
2154
+ raise err(403, "not_admin",
2155
+ "only an administrator can replace a workspace connection key")
2156
+ if not session.runtime.available():
2157
+ raise err(503, "store_unavailable", "the tenant store is unavailable")
2158
+
2159
+ key = str(connector_key or "").strip()
2160
+ connector = next((row for row in directory(session.runtime, session.uname, True)
2161
+ if str(row.get("key") or "") == key), None)
2162
+ entry_type = _entry_type_for(key)
2163
+ if connector is None or not entry_type:
2164
+ raise err(404, "unknown_connector", "this workspace has no connector with that key")
2165
+ if str(connector.get("manage") or "") not in ("keychain", "keychain_personal"):
2166
+ raise err(403, "replacement_unavailable",
2167
+ "this connector has no replaceable keychain credential")
2168
+
2169
+ import routes_keychain as rk # noqa: PLC0415 - circular at import
2170
+ from core import keychain as kc # noqa: PLC0415 - keep boot lean
2171
+ visible = rk.visible_entries(session.runtime, session.uname, True)
2172
+ entry = next((row for row in visible
2173
+ if str(row.get("id") or "") == str(entry_id)
2174
+ and str(row.get("type") or "") == entry_type), None)
2175
+ if entry is None:
2176
+ # One 404 covers missing, cross-tenant, another user's personal entry and a real id bound
2177
+ # to another connector. The mismatch itself is information this route does not disclose.
2178
+ raise err(404, "no_entry", "no such key for this connector")
2179
+
2180
+ secret_specs = _replacement_field_specs(entry_type)
2181
+ secret_keys = [str(field["key"]) for field in secret_specs]
2182
+ request = body if isinstance(body, dict) else {}
2183
+ supplied = request.get("fields")
2184
+ if set(request) != {"fields"} or not isinstance(supplied, dict):
2185
+ raise err(400, "bad_replacement",
2186
+ "send only the connector's new secret fields")
2187
+ if set(supplied) != set(secret_keys):
2188
+ raise err(400, "bad_replacement",
2189
+ "send every new secret field and no account or server settings")
2190
+ replacements = {}
2191
+ for field in secret_keys:
2192
+ value = supplied.get(field)
2193
+ if not isinstance(value, str) or not value.strip():
2194
+ raise err(400, "bad_replacement", "a replacement secret cannot be blank")
2195
+ replacements[field] = value.strip()
2196
+
2197
+ try:
2198
+ current_fields = kc.read_fields(session.runtime, entry_id)
2199
+ except kc.KeychainLocked as exc:
2200
+ raise err(503, "keychain_locked",
2201
+ f"the keychain is locked: {exc}. Nothing was changed.")
2202
+ except Exception: # noqa: BLE001
2203
+ raise err(503, "store_unavailable",
2204
+ "the current key could not be read. Nothing was changed.")
2205
+ if not isinstance(current_fields, dict) or not current_fields:
2206
+ raise err(409, "credential_unreadable",
2207
+ "the stored credential is incomplete. Nothing was changed.")
2208
+
2209
+ merged_fields = {**current_fields, **replacements}
2210
+ raw_bucket = session.runtime.get(kc.KEY) or {}
2211
+ original = ((raw_bucket.get("entries") or {}).get(str(entry_id)))
2212
+ if not isinstance(original, dict):
2213
+ raise err(409, "credential_changed",
2214
+ "the stored credential changed while replacement was prepared. Reload it.")
2215
+ original = dict(original)
2216
+ try:
2217
+ encrypted = _encrypted_replacement_payload(
2218
+ kc, entry.get("label"), entry_type, merged_fields, session.uname)
2219
+ except kc.KeychainLocked as exc:
2220
+ raise err(503, "keychain_locked",
2221
+ f"the keychain is locked: {exc}. Nothing was changed.")
2222
+ except ValueError as exc:
2223
+ raise err(400, "bad_replacement", str(exc))
2224
+ except Exception: # noqa: BLE001
2225
+ raise err(503, "replacement_not_stored",
2226
+ "the replacement could not be encrypted. The current key is unchanged.")
2227
+
2228
+ def _swap(cur):
2229
+ entries = cur.get("entries") if isinstance(cur, dict) else None
2230
+ stored = entries.get(str(entry_id)) if isinstance(entries, dict) else None
2231
+ if not isinstance(stored, dict) or stored != original:
2232
+ raise _ReplacementConflict()
2233
+ replacement = dict(stored)
2234
+ replacement["enc"] = encrypted["enc"]
2235
+ replacement["preview"] = encrypted["preview"]
2236
+ entries[str(entry_id)] = replacement
2237
+ return cur
2238
+
2239
+ try:
2240
+ session.runtime.update(kc.KEY, _swap, flush="sync")
2241
+ except _ReplacementConflict:
2242
+ raise err(409, "credential_changed",
2243
+ "the stored credential changed while replacement was prepared. Reload it.")
2244
+ except Exception: # noqa: BLE001
2245
+ # A remote store can fail after accepting a write. Claiming either outcome would be a lie;
2246
+ # the safe next act is a fresh detail read, never an automatic retry or delete.
2247
+ raise err(503, "replacement_unconfirmed",
2248
+ "the server could not confirm whether the replacement landed. Reload this "
2249
+ "connector before trying again.")
2250
+ return {"ok": True}
2251
+
2252
+
2253
+ @router.post("/connectors/{connector_key}/keychain/{entry_id}/replace")
2254
+ def replace_connector_key(connector_key: str, entry_id: str,
2255
+ body: dict = Body(default=None),
2256
+ session: Session = Depends(require_session)):
2257
+ """Admin-only, write-only replacement for one visible connector credential."""
2258
+ return _replace_connector_key(connector_key, entry_id, body, session)
2259
+
2260
+
2261
  # ⚠ FIVE SEGMENTS, so it can collide with nothing already declared here: the literal Odoo routes
2262
  # are four (`/connectors/odoo/schema/{field_key}`) and `/detail` is three.
2263
  @router.patch("/connectors/{connector_key}/databases/{database_key}/name")
api/routes_nav.py CHANGED
@@ -15,6 +15,7 @@ import time
15
  from fastapi import APIRouter, Body, Depends
16
 
17
  from deps import Session, err, perms, require_session
 
18
 
19
  router = APIRouter(prefix="/api/v1")
20
 
@@ -1281,3 +1282,40 @@ def update_schema_map_setup(key: str, body: dict = Body(default=None),
1281
  return {"map": {"canConfigure": True,
1282
  "fields": map_payload.get("fields") or [],
1283
  **active}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  from fastapi import APIRouter, Body, Depends
16
 
17
  from deps import Session, err, perms, require_session
18
+ import application_registry
19
 
20
  router = APIRouter(prefix="/api/v1")
21
 
 
1282
  return {"map": {"canConfigure": True,
1283
  "fields": map_payload.get("fields") or [],
1284
  **active}}
1285
+
1286
+
1287
+ @router.get("/nav/application-templates")
1288
+ def application_templates(session: Session = Depends(require_session)):
1289
+ """The trusted template contracts the App creation flow may offer."""
1290
+ return {"templates": application_registry.template_contracts()}
1291
+
1292
+
1293
+ @router.post("/nav/applications", status_code=201)
1294
+ def create_nav_application(body: dict = Body(default=None),
1295
+ session: Session = Depends(require_session)):
1296
+ """Create one tenant Application from the caller's permission-filtered database schema.
1297
+
1298
+ This is a thin nav/schema adapter over the existing Application registry writer. It does not
1299
+ create a View or code module, and it deliberately calls ``nav_schema`` before persistence so
1300
+ a field hidden from this caller cannot be smuggled into an Application definition.
1301
+ """
1302
+ payload = body if isinstance(body, dict) else {}
1303
+ source = str(payload.get("sourceDatabase") or "").strip()
1304
+ if not source:
1305
+ raise err(400, "bad_application", "sourceDatabase is required")
1306
+ schema = nav_schema(source, session)
1307
+ fields = schema.get("fields") if isinstance(schema, dict) else None
1308
+ if not session.runtime.available():
1309
+ raise err(503, "store_unavailable", "the tenant store is unavailable. Nothing was saved.")
1310
+ try:
1311
+ application = application_registry.create(
1312
+ session.runtime, session.tenant, session.uname, payload,
1313
+ field_contracts={source: fields if isinstance(fields, list) else []},
1314
+ allowed_databases={source})
1315
+ except PermissionError as exc:
1316
+ raise err(403, "forbidden", str(exc))
1317
+ except application_registry.ApplicationError as exc:
1318
+ raise err(400, "bad_application", str(exc))
1319
+ except Exception:
1320
+ raise err(503, "store_unavailable", "the Application was not saved.")
1321
+ return {"application": application}
api/routes_odoo_tables.py CHANGED
@@ -24,10 +24,10 @@ import hmac
24
  import json
25
  import time
26
 
27
- from fastapi import Body, Depends
28
  from fastapi import APIRouter, Query
29
 
30
- from deps import Session, err, require_session
31
 
32
  router = APIRouter(prefix="/api/v1")
33
 
@@ -1128,7 +1128,14 @@ def _source_for(cur, table_key):
1128
  DIFFERENT QUESTION and keeps its existing answer: `tables`/`table` must all resolve, and a
1129
  spec whose base table the mirror lacks is no binding at all (None, and the caller refuses).
1130
  """
1131
- spec = _sources().get(str(table_key or ""))
 
 
 
 
 
 
 
1132
  if not spec:
1133
  return None
1134
  from harness import datastore
@@ -1509,6 +1516,151 @@ def _related_source_value(session, entry, record):
1509
  return None
1510
 
1511
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1512
  def _via_path(via):
1513
  """The list of EDGE KEYS a `via` names, or None when it is one edge's bag instead.
1514
 
 
24
  import json
25
  import time
26
 
27
+ from fastapi import Body, Depends, HTTPException
28
  from fastapi import APIRouter, Query
29
 
30
+ from deps import (Session, err, module_cache_rows, module_cache_source, require_session)
31
 
32
  router = APIRouter(prefix="/api/v1")
33
 
 
1128
  DIFFERENT QUESTION and keeps its existing answer: `tables`/`table` must all resolve, and a
1129
  spec whose base table the mirror lacks is no binding at all (None, and the caller refuses).
1130
  """
1131
+ key = str(table_key or "")
1132
+ # Registry-module pools are databases, but never mirror bindings. In particular,
1133
+ # `product_data` must be reached through its scoped product pool after a relation has resolved
1134
+ # target ids; letting it fall into `_sources()` makes a cache alias look like an absent Odoo
1135
+ # table and turns Products ordered into the wrong 404.
1136
+ if module_cache_source(key) is not None:
1137
+ return None
1138
+ spec = _sources().get(key)
1139
  if not spec:
1140
  return None
1141
  from harness import datastore
 
1516
  return None
1517
 
1518
 
1519
+ def _cache_relation_plan(session, source, via, target):
1520
+ """The offered module link and its explicit bridge, or a cause-specific refusal.
1521
+
1522
+ A module/cache target is resolved from its module field declaration because the public
1523
+ relation entry intentionally carries only the edge needed by ordinary one-hop pins. The
1524
+ `through` metadata is not a second inferred graph: it is the exact link bag that declared
1525
+ Products ordered. Resolving against `related_entries` first keeps hidden link fields outside
1526
+ this door just as they are outside the drawer's tab list.
1527
+ """
1528
+ import core.relations as relations
1529
+ from routes_grid import _may_open, related_entries
1530
+
1531
+ source = str(source or "")
1532
+ target = str(target or "")
1533
+ via = str(via or "")
1534
+ if relations.is_retired_table(target):
1535
+ raise err(404, "relation_target_retired",
1536
+ f"'{target}' is retired and is no longer a relation target in this workspace")
1537
+ if module_cache_source(target) is None:
1538
+ raise err(404, "relation_target_missing",
1539
+ f"'{target}' is not a current module/cache relation target in this workspace")
1540
+ if not _may_open(session, source):
1541
+ raise err(403, "not_permitted",
1542
+ f"'{source}' could not be opened for your account, so this relation cannot "
1543
+ "be followed")
1544
+
1545
+ offered = next((entry for entry in related_entries(session, source)
1546
+ if str(entry.get("key") or "") == via
1547
+ and str(entry.get("target") or "") == target
1548
+ and str((entry.get("via") or {}).get("direction") or "") == "forward"),
1549
+ None)
1550
+ if offered is None:
1551
+ raise err(400, "unknown_relation",
1552
+ f"'{via}' is not an available relation from '{source}' to '{target}'")
1553
+
1554
+ field = next((item for item in _rel().module_link_fields(source)
1555
+ if str(item.get("key") or "") == via), None)
1556
+ link = (field or {}).get("link") if isinstance(field, dict) else None
1557
+ if not isinstance(link, dict) or str(link.get("table") or "") != target:
1558
+ raise err(404, "relation_target_missing",
1559
+ f"the relation '{via}' no longer has a current target in this workspace")
1560
+ through = str(link.get("through") or "")
1561
+ through_on = str(link.get("throughOn") or "")
1562
+ through_to = str(link.get("throughTo") or "")
1563
+ on = str(link.get("on") or relations.IDENTITY_COL)
1564
+ if not through or not through_on or not through_to:
1565
+ raise err(409, "relation_target_unavailable",
1566
+ f"the relation '{via}' has no complete stored path to '{target}' right now")
1567
+ if relations.is_retired_table(through):
1568
+ raise err(404, "relation_target_retired",
1569
+ f"'{through}' is retired, so the relation to '{target}' is no longer available")
1570
+ if not _may_open(session, through):
1571
+ raise err(403, "forbidden_table",
1572
+ f"the relation to '{target}' crosses '{through}', which your account cannot "
1573
+ "open")
1574
+ if not _may_open(session, target):
1575
+ raise err(403, "forbidden_table",
1576
+ f"the relation ends at '{target}', which your account cannot open")
1577
+ return dict(offered, __source__=source), link, through, through_on, through_to, on
1578
+
1579
+
1580
+ def _cache_relation_source_value(session, entry, record):
1581
+ """Read a cache-backed source value only from a row visible to this session."""
1582
+ import core.relations as relations
1583
+
1584
+ source = str(entry.get("__source__") or "")
1585
+ if module_cache_source(source) is None:
1586
+ return _related_source_value(session, entry, record)
1587
+ try:
1588
+ rows = module_cache_rows(session, source)
1589
+ except HTTPException:
1590
+ raise
1591
+ except Exception as exc: # noqa: BLE001
1592
+ raise err(503, "relation_source_unavailable",
1593
+ f"'{source}' could not be read right now; try this relation again") from exc
1594
+ row = next((item for item in rows if str(item.get("pid")) == str(record)), None)
1595
+ if row is None:
1596
+ raise err(404, "relation_source_missing",
1597
+ f"record {record} is no longer available in '{source}'")
1598
+ frm = str((entry.get("via") or {}).get("from") or relations.IDENTITY_COL)
1599
+ value = row.get("pid") if frm == relations.IDENTITY_COL else row.get(frm)
1600
+ return value if value not in (None, "") else None
1601
+
1602
+
1603
+ def _cache_relation_target_ids(session, source, record, via, target):
1604
+ """Resolve one explicit source -> mirror bridge -> module-cache path to target row pids."""
1605
+ entry, _link, through, through_on, through_to, on = _cache_relation_plan(
1606
+ session, source, via, target)
1607
+ source_value = _cache_relation_source_value(session, entry, record)
1608
+ if source_value in (None, ""):
1609
+ raise err(400, "unknown_relation",
1610
+ f"record {record} has no readable source value for relation '{via}'")
1611
+
1612
+ compiled = _compiled_read(through, session)
1613
+ spec = compiled["spec"]
1614
+ left = (spec.get("cols") or {}).get(through_on)
1615
+ right = (spec.get("cols") or {}).get(through_to)
1616
+ if not left or not right:
1617
+ raise err(409, "relation_target_unavailable",
1618
+ f"the stored path through '{through}' is missing a required join column")
1619
+ try:
1620
+ source_value = left[1](source_value)
1621
+ except Exception: # noqa: BLE001
1622
+ source_value = str(source_value)
1623
+
1624
+ frm = spec.get("from_sql") or spec.get("table")
1625
+ where = str(compiled.get("where") or "").strip()
1626
+ params = list(compiled.get("params") or ())
1627
+ predicate = f"({where}) AND " if where else ""
1628
+ sql = (f"SELECT DISTINCT {right[0]} AS related_value FROM {frm} WHERE "
1629
+ f"{predicate}{left[0]} = ? AND {right[0]} IS NOT NULL")
1630
+ values = {str(row[0]) for row in compiled["cur"].execute(
1631
+ sql, params + [source_value]).fetchall() if row and row[0] not in (None, "")}
1632
+
1633
+ try:
1634
+ target_rows = module_cache_rows(session, target)
1635
+ except HTTPException:
1636
+ raise
1637
+ except Exception as exc: # noqa: BLE001
1638
+ raise err(503, "relation_target_unavailable",
1639
+ f"'{target}' could not be read right now; try this relation again") from exc
1640
+ ids = []
1641
+ seen = set()
1642
+ for row in target_rows:
1643
+ if str(row.get(on)) not in values:
1644
+ continue
1645
+ try:
1646
+ pid = int(row.get("pid"))
1647
+ except (TypeError, ValueError):
1648
+ continue
1649
+ if pid > 0 and pid not in seen:
1650
+ seen.add(pid)
1651
+ ids.append(pid)
1652
+ return {"ok": True, "sourceKind": "module_cache", "target": str(target),
1653
+ "ids": ids, "path": [str(source), through, str(target)]}
1654
+
1655
+
1656
+ @router.get("/odoo-tables/relation-targets")
1657
+ def odoo_relation_targets(source: str = Query(...), record: int = Query(..., ge=1),
1658
+ via: str = Query(...), target: str = Query(...),
1659
+ session: Session = Depends(require_session)):
1660
+ """Target pids for a declared relation whose destination is a runtime-cache database."""
1661
+ return _cache_relation_target_ids(session, source, record, via, target)
1662
+
1663
+
1664
  def _via_path(via):
1665
  """The list of EDGE KEYS a `via` names, or None when it is one edge's bag instead.
1666
 
api/routes_sheet.py CHANGED
@@ -591,6 +591,22 @@ def _view_filter_once(session: Session, database: str, view_id: str, view_name:
591
  return rot._fe().tree_parts(sheets_mod.adopted_scope_filter(view))
592
 
593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594
  #: β›” THE TWO CAP CODES ANSWER 413, NOT 400 (contract C3). A 400 says the request was malformed and
595
  #: sends a client looking for a typo; these two say the request was perfectly well formed and the
596
  #: DOCUMENT it would produce cannot be stored, which is what 413 means and is the only status a
@@ -1913,6 +1929,59 @@ def preview_cell(workbook_id: str, addr: str, body: dict = Body(default=None),
1913
  "limits": out["limits"]}
1914
 
1915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1916
  @router.post("/sheets/{workbook_id}/cells/{addr}/compute")
1917
  def compute_cell(workbook_id: str, addr: str, body: dict = Body(default=None),
1918
  session: Session = Depends(require_session)):
 
591
  return rot._fe().tree_parts(sheets_mod.adopted_scope_filter(view))
592
 
593
 
594
+ def _materialize_copy_binding(raw_binding, filter_tree):
595
+ """A copied saved-View binding with its own filter, without mutating either input.
596
+
597
+ R5 is deliberately a COPY-TIME action. The source cell keeps following its saved View, while
598
+ the copy receives a deep local shadow and can step a chosen leaf without editing shared View
599
+ state. A binding already scoped to a local filter passes through the normal cleaner unchanged.
600
+ """
601
+ from modules import sheet as sheet_mod
602
+ import copy as _copy
603
+
604
+ binding = sheet_mod.clean_binding(raw_binding)
605
+ if not binding["scope"].get("view_id"):
606
+ return binding
607
+ return {**binding, "scope": {"filter": _copy.deepcopy(filter_tree)}}
608
+
609
+
610
  #: β›” THE TWO CAP CODES ANSWER 413, NOT 400 (contract C3). A 400 says the request was malformed and
611
  #: sends a client looking for a typo; these two say the request was perfectly well formed and the
612
  #: DOCUMENT it would produce cannot be stored, which is what 413 means and is the only status a
 
1929
  "limits": out["limits"]}
1930
 
1931
 
1932
+ @router.post("/sheets/{workbook_id}/binding-shadows")
1933
+ def binding_shadows(workbook_id: str, body: dict = Body(default=None),
1934
+ session: Session = Depends(require_session)):
1935
+ """Canonical saved-View filters needed before copied bindings step (C5, R5).
1936
+
1937
+ request: `{"bindings": [<binding>, ...]}`
1938
+ response: `{"shadows": [{database, viewId, filter}, ...]}`
1939
+
1940
+ The source bindings and saved Views are read only. The browser materialises each returned tree
1941
+ into the copied binding, commits the stale cells immediately, then schedules Save's evaluator.
1942
+ The editor wall is intentional: this door exists only to prepare a workbook write, and a
1943
+ viewer must never turn a reader-specific filter into the owner's stored document.
1944
+ """
1945
+ from core import sheets
1946
+ from modules import sheet as sheet_mod
1947
+
1948
+ try:
1949
+ book = sheets.get_workbook(_store(session), workbook_id)
1950
+ _require_editor(session, book)
1951
+ except sheets.SheetRefusal as exc:
1952
+ raise _refuse(exc)
1953
+
1954
+ raw_bindings = (body or {}).get("bindings")
1955
+ if not isinstance(raw_bindings, list):
1956
+ raise err(400, "sheet_bindings_required",
1957
+ "Choose the database cells whose saved Views should be copied.")
1958
+
1959
+ shadows = []
1960
+ seen = set()
1961
+ view_memo = {}
1962
+ for raw in raw_bindings:
1963
+ try:
1964
+ binding = sheet_mod.clean_binding(raw)
1965
+ except sheet_mod.SheetRefusal as exc:
1966
+ raise err(400, exc.code, exc.message)
1967
+ scope = binding["scope"]
1968
+ view_id = str(scope.get("view_id") or "")
1969
+ if not view_id:
1970
+ continue
1971
+ database = _require_database(session, binding["database"])
1972
+ slot = (database, view_id)
1973
+ if slot in seen:
1974
+ continue
1975
+ seen.add(slot)
1976
+ nodes, conj = _view_filter(session, database, view_id, scope.get("view_name", ""),
1977
+ memo=view_memo)
1978
+ local = _materialize_copy_binding(
1979
+ binding, {"conj": conj, "nodes": nodes})
1980
+ shadows.append({"database": database, "viewId": view_id,
1981
+ "filter": local["scope"]["filter"]})
1982
+ return {"shadows": shadows}
1983
+
1984
+
1985
  @router.post("/sheets/{workbook_id}/cells/{addr}/compute")
1986
  def compute_cell(workbook_id: str, addr: str, body: dict = Body(default=None),
1987
  session: Session = Depends(require_session)):
platform/core/connector_spec.py CHANGED
@@ -49,12 +49,40 @@ because a tautology is exactly what catches a hand edit that re-introduces a lit
49
  no `"odoo"` entry and no stub for one; `edges_for("odoo")` returns `[]` until that ticket lands.
50
  """
51
  from dataclasses import dataclass, replace
 
 
52
 
53
  #: ⭐ THE CARDINALITY VOCABULARY, AS A CONSTANT SO EVERY CONSUMER CHECKS MEMBERSHIP RATHER THAN
54
  #: SPELLING. The relation wire (W53-T17) and the parity gate both read this set; a fifth value
55
  #: added by hand in a link tuple goes red instead of travelling silently to a screen.
56
  CARDINALITIES = ("many_to_one", "one_to_many", "one_to_one", "many_to_many")
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
  @dataclass(frozen=True)
60
  class ConnectorTableSpec:
@@ -391,5 +419,6 @@ register("amazon", AMAZON_TABLES)
391
  register("meta", META_TABLES)
392
 
393
  __all__ = ["CARDINALITIES", "ConnectorTableSpec", "SPECS", "AMAZON_TABLES", "META_TABLES",
 
394
  "register", "connectors", "tables_for", "all_specs", "spec_for", "connector_of",
395
  "edges_for"]
 
49
  no `"odoo"` entry and no stub for one; `edges_for("odoo")` returns `[]` until that ticket lands.
50
  """
51
  from dataclasses import dataclass, replace
52
+ import hashlib
53
+ import re
54
 
55
  #: ⭐ THE CARDINALITY VOCABULARY, AS A CONSTANT SO EVERY CONSUMER CHECKS MEMBERSHIP RATHER THAN
56
  #: SPELLING. The relation wire (W53-T17) and the parity gate both read this set; a fifth value
57
  #: added by hand in a link tuple goes red instead of travelling silently to a screen.
58
  CARDINALITIES = ("many_to_one", "one_to_many", "one_to_one", "many_to_many")
59
 
60
+ # The discoverable Odoo catalogue is runtime data, because two API accounts can read different
61
+ # installed modules. Only its stable naming rule belongs in this tenant-independent spec layer.
62
+ # A digest closes the otherwise-real collision between model names such as ``x.a_b`` and
63
+ # ``x_a.b`` after punctuation is normalised for a ``ut_*`` key.
64
+ ODOO_MODEL_TABLE_PREFIX = "ut_odoo_model_"
65
+
66
+
67
+ def odoo_model_table_key(model):
68
+ """Stable ``ut_*`` key for one vendor model name; blank/invalid input is refused."""
69
+ native = str(model or "").strip().lower()
70
+ if not native or not re.fullmatch(r"[a-z0-9_.]+", native):
71
+ raise ValueError("an Odoo model name may contain only lowercase letters, digits, dots and underscores")
72
+ # 18 + the 14-character prefix + separator + digest leaves room for the connector's
73
+ # ``__k_<12 hex>`` namespace under user_tables' 60-character key ceiling.
74
+ stem = re.sub(r"[^a-z0-9]+", "_", native).strip("_")[:18] or "model"
75
+ digest = hashlib.sha256(native.encode("utf-8")).hexdigest()[:10]
76
+ return f"{ODOO_MODEL_TABLE_PREFIX}{stem}_{digest}"
77
+
78
+
79
+ def odoo_model_label(model, vendor_label=""):
80
+ """Our default database label, while preserving Odoo's own label when it supplied one."""
81
+ label = " ".join(str(vendor_label or "").split())
82
+ if label:
83
+ return label[:80]
84
+ return str(model or "").replace(".", " ").replace("_", " ").strip().capitalize()[:80]
85
+
86
 
87
  @dataclass(frozen=True)
88
  class ConnectorTableSpec:
 
419
  register("meta", META_TABLES)
420
 
421
  __all__ = ["CARDINALITIES", "ConnectorTableSpec", "SPECS", "AMAZON_TABLES", "META_TABLES",
422
+ "ODOO_MODEL_TABLE_PREFIX", "odoo_model_table_key", "odoo_model_label",
423
  "register", "connectors", "tables_for", "all_specs", "spec_for", "connector_of",
424
  "edges_for"]
web/src/connectors/ConnectorModal.tsx CHANGED
@@ -63,6 +63,7 @@ import type { ConnectorRelationshipGraph, ConnectorRow } from "./ConnectorsPage"
63
  import { parseRelationshipGraph } from "./ConnectorsPage";
64
  import "../styles/wave49/connectors.css";
65
  import "../styles/wave52/connectors.css";
 
66
 
67
  /** R26's original four, plus "cadence" (W52-T04, the done-when's "sync cadence" section). */
68
  export type ConnectorTab = "overview" | "keychain" | "databases" | "relationships" | "cadence";
@@ -126,6 +127,8 @@ export interface ConnectorKeychainEntry {
126
  masked: string;
127
  scope: string;
128
  testable: boolean;
 
 
129
  }
130
 
131
  /**
@@ -233,10 +236,24 @@ export interface ConnectorIntrospection {
233
  excludedBasis: string;
234
  }
235
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  export interface ConnectorDetail {
237
  overview: ConnectorOverview;
238
  keychain: ConnectorKeychainHalf;
239
  databases: ConnectorDatabase[];
 
240
  introspection: ConnectorIntrospection;
241
  relationships: ConnectorRelationshipGraph;
242
  }
@@ -265,6 +282,7 @@ function parseKeychainHalf(raw: unknown): ConnectorKeychainHalf {
265
  masked: str(entry.masked),
266
  scope: str(entry.scope).trim(),
267
  testable: entry.testable === true,
 
268
  });
269
  }
270
  return {
@@ -381,6 +399,36 @@ function parseIntrospection(raw: unknown): ConnectorIntrospection {
381
  };
382
  }
383
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
384
  /**
385
  * Read the detail payload for the card that was actually clicked.
386
  *
@@ -405,6 +453,7 @@ export function parseConnectorDetail(body: unknown, selectedKey: string): Connec
405
  },
406
  keychain: parseKeychainHalf(source.keychain),
407
  databases: parseDatabases(source.databases),
 
408
  introspection: parseIntrospection(source.introspection),
409
  relationships: parseRelationshipGraph(source.relationships, selectedKey),
410
  };
@@ -529,6 +578,96 @@ export function ConnectorOverviewPanel({
529
  );
530
  }
531
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532
  // ── The three tabs that are not built yet. β›” EACH IS ITS OWN COMPONENT SLOT so W49-T13, T14 and
533
  // T15 replace a named component rather than editing a sentence out of a branch, and the switch
534
  // below never has to change shape. Plain sentences, no dashes, no emojis.
@@ -708,7 +847,12 @@ export default function ConnectorModal({
708
  return <KeychainTab row={row} keychain={load.detail.keychain} onChanged={reread} />;
709
  }
710
  if (tab === "databases") {
711
- return <DatabasesTab row={row} detail={load.detail} onChanged={reread} />;
 
 
 
 
 
712
  }
713
  if (tab === "relationships") {
714
  return <RelationshipDiagram connector={row.label} graph={load.detail.relationships} />;
 
63
  import { parseRelationshipGraph } from "./ConnectorsPage";
64
  import "../styles/wave49/connectors.css";
65
  import "../styles/wave52/connectors.css";
66
+ import "../styles/wave55/connectors.css";
67
 
68
  /** R26's original four, plus "cadence" (W52-T04, the done-when's "sync cadence" section). */
69
  export type ConnectorTab = "overview" | "keychain" | "databases" | "relationships" | "cadence";
 
127
  masked: string;
128
  scope: string;
129
  testable: boolean;
130
+ /** Server-owned admin permission for the write-only replacement flow. */
131
+ replaceable: boolean;
132
  }
133
 
134
  /**
 
236
  excludedBasis: string;
237
  }
238
 
239
+ /** W55-T19 / R7 β€” one provider's own database-enablement door. */
240
+ export interface ConnectorEnablement {
241
+ /** Must match the connector detail envelope that carried it. */
242
+ provider: string;
243
+ /** Read as a string so a future provider mode fails closed instead of widening this UI. */
244
+ mode: string;
245
+ canManage: boolean;
246
+ updatePath: string;
247
+ /** The Amazon route changes only config; stored database rows remain in place. */
248
+ preservesData: boolean;
249
+ available: boolean;
250
+ }
251
+
252
  export interface ConnectorDetail {
253
  overview: ConnectorOverview;
254
  keychain: ConnectorKeychainHalf;
255
  databases: ConnectorDatabase[];
256
+ enablement: ConnectorEnablement | null;
257
  introspection: ConnectorIntrospection;
258
  relationships: ConnectorRelationshipGraph;
259
  }
 
282
  masked: str(entry.masked),
283
  scope: str(entry.scope).trim(),
284
  testable: entry.testable === true,
285
+ replaceable: entry.replaceable === true,
286
  });
287
  }
288
  return {
 
399
  };
400
  }
401
 
402
+ /**
403
+ * Parse a provider capability bound to the selected connector, or refuse it.
404
+ *
405
+ * A path is actionable only when it stays under this provider and carries the one database-key
406
+ * slot the server declared. Missing, cross-provider and unknown modes render no control; the API
407
+ * remains the permission boundary, but the modal never paints a button it knows cannot work.
408
+ */
409
+ export function parseConnectorEnablement(
410
+ raw: unknown,
411
+ selectedKey: string
412
+ ): ConnectorEnablement | null {
413
+ const source = obj(raw);
414
+ const provider = str(source.provider).trim();
415
+ const mode = str(source.mode).trim();
416
+ if (provider !== selectedKey || mode !== "database" || source.preservesData !== true) return null;
417
+ const updatePath = str(source.updatePath).trim();
418
+ const expectedPrefix = `/connectors/${encodeURIComponent(provider)}/databases/`;
419
+ const validPath = updatePath.startsWith(expectedPrefix) && updatePath.endsWith("/enablement")
420
+ && updatePath.includes("{databaseKey}");
421
+ const canManage = source.canManage === true && source.available === true && validPath;
422
+ return {
423
+ provider,
424
+ mode,
425
+ canManage,
426
+ updatePath: canManage ? updatePath : "",
427
+ preservesData: true,
428
+ available: source.available === true,
429
+ };
430
+ }
431
+
432
  /**
433
  * Read the detail payload for the card that was actually clicked.
434
  *
 
453
  },
454
  keychain: parseKeychainHalf(source.keychain),
455
  databases: parseDatabases(source.databases),
456
+ enablement: parseConnectorEnablement(source.enablement, selectedKey),
457
  introspection: parseIntrospection(source.introspection),
458
  relationships: parseRelationshipGraph(source.relationships, selectedKey),
459
  };
 
578
  );
579
  }
580
 
581
+ /** Amazon's provider-specific administrator controls, separate from Odoo's model catalogue. */
582
+ export function ProviderEnablementPanel({
583
+ detail,
584
+ onChanged,
585
+ }: {
586
+ detail: ConnectorDetail;
587
+ onChanged: () => void;
588
+ }) {
589
+ const capability = detail.enablement;
590
+ const [busyKey, setBusyKey] = useState("");
591
+ const [message, setMessage] = useState("");
592
+ if (!capability?.canManage || !capability.updatePath) return null;
593
+
594
+ const setEnabled = async (database: ConnectorDatabase, enabled: boolean) => {
595
+ const path = capability.updatePath.replace(
596
+ "{databaseKey}",
597
+ encodeURIComponent(database.key)
598
+ );
599
+ if (path === capability.updatePath) {
600
+ setMessage("This provider did not return a usable enablement path.");
601
+ return;
602
+ }
603
+ setBusyKey(database.key);
604
+ setMessage("");
605
+ let saved = false;
606
+ try {
607
+ const res = await fetch(`${API_V1}${path}`, {
608
+ method: "PATCH",
609
+ credentials: CREDENTIALS,
610
+ headers: { "Content-Type": "application/json" },
611
+ body: JSON.stringify({ enabled }),
612
+ });
613
+ const body = (await res.json().catch(() => null)) as
614
+ | { error?: { message?: string } }
615
+ | null;
616
+ if (!res.ok) {
617
+ setMessage(body?.error?.message || `The server answered ${res.status}.`);
618
+ return;
619
+ }
620
+ saved = true;
621
+ onChanged();
622
+ } catch {
623
+ setMessage("Cannot reach the server.");
624
+ } finally {
625
+ // A successful write immediately asks the modal to re-read and leaves the old switches
626
+ // disabled until that load guard replaces them. An error keeps the current detail and must
627
+ // release the control for a retry.
628
+ if (!saved) setBusyKey("");
629
+ }
630
+ };
631
+
632
+ return (
633
+ <section className="conn-provider-enable" aria-labelledby="conn-provider-enable-title">
634
+ <div className="conn-provider-enable-head">
635
+ <h3 id="conn-provider-enable-title">Enablement</h3>
636
+ <p>Choose which Amazon databases are enabled. Switching one off keeps its stored rows.</p>
637
+ </div>
638
+ <ul className="conn-provider-enable-list">
639
+ {detail.databases.map((database) => (
640
+ <li key={database.key}>
641
+ <span>{database.label}</span>
642
+ <span className="conn-provider-enable-control">
643
+ <span className="conn-db-state">{database.enabled ? "On" : "Off"}</span>
644
+ <button
645
+ type="button"
646
+ role="switch"
647
+ aria-checked={database.enabled}
648
+ aria-label={
649
+ database.enabled
650
+ ? `Switch the database ${database.label} off`
651
+ : `Switch the database ${database.label} on`
652
+ }
653
+ className={"conn-db-switch" + (database.enabled ? " is-on" : "")}
654
+ disabled={Boolean(busyKey)}
655
+ aria-busy={busyKey === database.key}
656
+ onClick={() => void setEnabled(database, !database.enabled)}
657
+ >
658
+ <span className="conn-db-knob" aria-hidden="true" />
659
+ </button>
660
+ </span>
661
+ </li>
662
+ ))}
663
+ </ul>
664
+ <div className="conn-provider-enable-status" role="status" aria-live="polite">
665
+ {message}
666
+ </div>
667
+ </section>
668
+ );
669
+ }
670
+
671
  // ── The three tabs that are not built yet. β›” EACH IS ITS OWN COMPONENT SLOT so W49-T13, T14 and
672
  // T15 replace a named component rather than editing a sentence out of a branch, and the switch
673
  // below never has to change shape. Plain sentences, no dashes, no emojis.
 
847
  return <KeychainTab row={row} keychain={load.detail.keychain} onChanged={reread} />;
848
  }
849
  if (tab === "databases") {
850
+ return (
851
+ <>
852
+ <ProviderEnablementPanel detail={load.detail} onChanged={reread} />
853
+ <DatabasesTab row={row} detail={load.detail} onChanged={reread} />
854
+ </>
855
+ );
856
  }
857
  if (tab === "relationships") {
858
  return <RelationshipDiagram connector={row.label} graph={load.detail.relationships} />;
web/src/connectors/DatabasesTab.tsx CHANGED
@@ -402,6 +402,17 @@ export default function DatabasesTab({
402
  for (const database of databases) out[database.key] = database.label;
403
  return out;
404
  }, [databases]);
 
 
 
 
 
 
 
 
 
 
 
405
 
406
  /**
407
  * β›”β›” R23's ENFORCEMENT, AND TODAY IT LIVES HERE. The write door is
@@ -514,8 +525,8 @@ export default function DatabasesTab({
514
  </p>
515
  ) : null}
516
  <p className="conn-db-lede">
517
- <span className="conn-db-n">{databases.length}</span> databases are created from this
518
- connection.
519
  </p>
520
  {/* β›” THE IDENTITY BLOCK IS EXPLAINED, NOT INFERRED FROM A GREYED CONTROL. Which of the
521
  three names is ours, which is theirs and which one a rename touches is the question this
@@ -535,7 +546,7 @@ export default function DatabasesTab({
535
  <th scope="col">Enabled</th>
536
  </tr>
537
  </thead>
538
- {databases.map((database) => {
539
  const isOpen = open[database.key] === true;
540
  const refusal = refusals[database.key] || "";
541
  return (
 
402
  for (const database of databases) out[database.key] = database.label;
403
  return out;
404
  }, [databases]);
405
+ const orderedDatabases = useMemo(
406
+ () =>
407
+ databases
408
+ .map((database, index) => ({ database, index }))
409
+ .sort(
410
+ (a, b) =>
411
+ Number(b.database.enabled) - Number(a.database.enabled) || a.index - b.index
412
+ )
413
+ .map(({ database }) => database),
414
+ [databases]
415
+ );
416
 
417
  /**
418
  * β›”β›” R23's ENFORCEMENT, AND TODAY IT LIVES HERE. The write door is
 
525
  </p>
526
  ) : null}
527
  <p className="conn-db-lede">
528
+ <span className="conn-db-n">{databases.length}</span> databases are available from this
529
+ connection. Enabled databases are first.
530
  </p>
531
  {/* β›” THE IDENTITY BLOCK IS EXPLAINED, NOT INFERRED FROM A GREYED CONTROL. Which of the
532
  three names is ours, which is theirs and which one a rename touches is the question this
 
546
  <th scope="col">Enabled</th>
547
  </tr>
548
  </thead>
549
+ {orderedDatabases.map((database) => {
550
  const isOpen = open[database.key] === true;
551
  const refusal = refusals[database.key] || "";
552
  return (
web/src/connectors/KeychainTab.tsx CHANGED
@@ -75,9 +75,7 @@ async function post(path: string, body?: unknown): Promise<string> {
75
  headers: { "Content-Type": "application/json" },
76
  body: JSON.stringify(body ?? {}),
77
  });
78
- const payload = (await res.json().catch(() => null)) as
79
- | { error?: { message?: string } }
80
- | null;
81
  if (!res.ok) return payload?.error?.message || `The server answered ${res.status}.`;
82
  return "";
83
  } catch {
@@ -220,6 +218,100 @@ function ConnectForm({
220
  );
221
  }
222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  /**
224
  * ⭐ THE PANEL, PURE AND EXPORTED, for the reason `ConnectorOverviewPanel` is: the modal fetches
225
  * on mount and `renderToStaticMarkup` runs no effects, so a static proof of this tab has to be
@@ -240,6 +332,7 @@ export default function KeychainTab({
240
  const [tested, setTested] = useState<Record<string, string>>({});
241
  const [error, setError] = useState("");
242
  const [adding, setAdding] = useState(false);
 
243
 
244
  const runTest = useCallback(async (entry: ConnectorKeychainEntry) => {
245
  setTested((current) => ({ ...current, [entry.id]: "Testing" }));
@@ -322,6 +415,21 @@ export default function KeychainTab({
322
  );
323
  }
324
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
325
  return (
326
  <div className="conn-kc">
327
  {error ? (
@@ -339,7 +447,7 @@ export default function KeychainTab({
339
  {/* An empty preview is a RULE, not a gap: R4 withholds the last four characters
340
  of a business key from a member who did not store it, and saying so is
341
  better than an empty cell that reads as a bug. */}
342
- {entry.masked || "The preview is hidden for connections you did not add"}
343
  {" Β· "}
344
  {scopeLabel(entry.scope)}
345
  </span>
@@ -350,6 +458,16 @@ export default function KeychainTab({
350
  ) : null}
351
  </div>
352
  <div className="conn-kc-controls">
 
 
 
 
 
 
 
 
 
 
353
  {entry.testable ? (
354
  <button
355
  type="button"
 
75
  headers: { "Content-Type": "application/json" },
76
  body: JSON.stringify(body ?? {}),
77
  });
78
+ const payload = (await res.json().catch(() => null)) as { error?: { message?: string } } | null;
 
 
79
  if (!res.ok) return payload?.error?.message || `The server answered ${res.status}.`;
80
  return "";
81
  } catch {
 
218
  );
219
  }
220
 
221
+ /**
222
+ * A stored credential is never opened into this form. Every field starts empty and the current
223
+ * key remains active while the server validates, merges and encrypts the replacement. Only the
224
+ * server-declared secret fields render; account, server and database settings never cross back
225
+ * through the browser.
226
+ */
227
+ function ReplaceForm({
228
+ connectorKey,
229
+ spec,
230
+ entry,
231
+ onDone,
232
+ onCancel,
233
+ }: {
234
+ connectorKey: string;
235
+ spec: ConnectorConnectSpec;
236
+ entry: ConnectorKeychainEntry;
237
+ onDone: () => void;
238
+ onCancel: () => void;
239
+ }) {
240
+ const [values, setValues] = useState<Record<string, string>>({});
241
+ const [busy, setBusy] = useState(false);
242
+ const [error, setError] = useState("");
243
+ const fields = spec.fields.filter((field) => field.secret);
244
+ const complete =
245
+ fields.length > 0 && fields.every((field) => Boolean((values[field.key] || "").trim()));
246
+
247
+ const save = async () => {
248
+ if (busy || !complete) return;
249
+ setBusy(true);
250
+ setError("");
251
+ const replacement = Object.fromEntries(
252
+ fields.map((field) => [field.key, (values[field.key] || "").trim()])
253
+ );
254
+ const message = await post(
255
+ `/connectors/${encodeURIComponent(connectorKey)}/keychain/${encodeURIComponent(entry.id)}/replace`,
256
+ { fields: replacement }
257
+ );
258
+ if (message) {
259
+ setError(message);
260
+ setBusy(false);
261
+ return;
262
+ }
263
+ // Dropping this component clears every write-only value from React state before the detail
264
+ // payload is fetched again. No submitted credential is copied into a response-facing model.
265
+ onDone();
266
+ };
267
+
268
+ return (
269
+ <div className="conn-kc-form conn-kc-replace">
270
+ <h3>Replace key</h3>
271
+ <p className="conn-kc-note">
272
+ The current key stays unchanged until the complete replacement is stored.
273
+ </p>
274
+ {fields.map((field) => (
275
+ <div className="conn-kc-field" key={field.key}>
276
+ <label htmlFor={`conn-kc-replace-${entry.id}-${field.key}`}>
277
+ {`New ${field.label.toLocaleLowerCase()}`}
278
+ </label>
279
+ <input
280
+ id={`conn-kc-replace-${entry.id}-${field.key}`}
281
+ type="password"
282
+ autoComplete="new-password"
283
+ disabled={busy}
284
+ value={values[field.key] ?? ""}
285
+ onChange={(event) =>
286
+ setValues((current) => ({ ...current, [field.key]: event.target.value }))
287
+ }
288
+ />
289
+ </div>
290
+ ))}
291
+ <div className="conn-kc-message-slot">
292
+ {error ? (
293
+ <p className="conn-kc-error" role="alert">
294
+ {error}
295
+ </p>
296
+ ) : null}
297
+ </div>
298
+ <div className="conn-kc-actions">
299
+ <button type="button" className="conn-kc-btn" disabled={busy} onClick={onCancel}>
300
+ Cancel
301
+ </button>
302
+ <button
303
+ type="button"
304
+ className="conn-kc-btn is-primary"
305
+ disabled={busy || !complete}
306
+ onClick={() => void save()}
307
+ >
308
+ {busy ? "Replacing" : "Store replacement"}
309
+ </button>
310
+ </div>
311
+ </div>
312
+ );
313
+ }
314
+
315
  /**
316
  * ⭐ THE PANEL, PURE AND EXPORTED, for the reason `ConnectorOverviewPanel` is: the modal fetches
317
  * on mount and `renderToStaticMarkup` runs no effects, so a static proof of this tab has to be
 
332
  const [tested, setTested] = useState<Record<string, string>>({});
333
  const [error, setError] = useState("");
334
  const [adding, setAdding] = useState(false);
335
+ const [replacing, setReplacing] = useState<ConnectorKeychainEntry | null>(null);
336
 
337
  const runTest = useCallback(async (entry: ConnectorKeychainEntry) => {
338
  setTested((current) => ({ ...current, [entry.id]: "Testing" }));
 
415
  );
416
  }
417
 
418
+ if (replacing && keychain.connect) {
419
+ return (
420
+ <ReplaceForm
421
+ connectorKey={row.key}
422
+ spec={keychain.connect}
423
+ entry={replacing}
424
+ onCancel={() => setReplacing(null)}
425
+ onDone={() => {
426
+ setReplacing(null);
427
+ onChanged();
428
+ }}
429
+ />
430
+ );
431
+ }
432
+
433
  return (
434
  <div className="conn-kc">
435
  {error ? (
 
447
  {/* An empty preview is a RULE, not a gap: R4 withholds the last four characters
448
  of a business key from a member who did not store it, and saying so is
449
  better than an empty cell that reads as a bug. */}
450
+ {entry.masked ? `Stored key ${entry.masked}` : "Stored key. Preview hidden"}
451
  {" Β· "}
452
  {scopeLabel(entry.scope)}
453
  </span>
 
458
  ) : null}
459
  </div>
460
  <div className="conn-kc-controls">
461
+ {entry.replaceable && keychain.connect ? (
462
+ <button
463
+ type="button"
464
+ className="conn-kc-btn"
465
+ disabled={Boolean(busyId)}
466
+ onClick={() => setReplacing(entry)}
467
+ >
468
+ Replace
469
+ </button>
470
+ ) : null}
471
  {entry.testable ? (
472
  <button
473
  type="button"
web/src/connectors/OdooConfig.tsx CHANGED
@@ -29,7 +29,7 @@
29
  // writes. See `SyncCadenceTab`'s own header for the Amazon/Meta Ads answer.
30
  // ---------------------------------------------------------------------------
31
 
32
- import { useCallback, useEffect, useState } from "react";
33
  import { API_V1, CREDENTIALS } from "../apiContract";
34
  import type { ConnectorRow } from "./ConnectorsPage";
35
 
@@ -38,6 +38,9 @@ export interface OdooGrid {
38
  key: string;
39
  label: string;
40
  enabled: boolean;
 
 
 
41
  }
42
 
43
  /** The config payload. Everything optional but `grids` is genuinely optional on the wire β€”
@@ -104,7 +107,16 @@ export default function OdooConfigPanel({
104
  onDisconnect: () => void;
105
  onReconnect: () => void;
106
  }) {
107
- const grids = cfg.grids ?? [];
 
 
 
 
 
 
 
 
 
108
  const options = cfg.syncOptions ?? [];
109
  const on = grids.filter((g) => g.enabled).length;
110
  return (
@@ -113,12 +125,17 @@ export default function OdooConfigPanel({
113
 
114
  {/* ── the credential, as much of it as may be shown ────────────────────────────────── */}
115
  <div className="conn-odoo-row">
116
- <span className="conn-odoo-k">Key</span>
117
  <span className="conn-odoo-v">
118
  {cfg.preview ? cfg.preview : "held on this deployment"}
119
- {cfg.apiUser ? " Β· " + cfg.apiUser : ""}
120
  </span>
121
  </div>
 
 
 
 
 
 
122
  {cfg.serverUrl ? (
123
  <div className="conn-odoo-row">
124
  <span className="conn-odoo-k">Server</span>
@@ -143,7 +160,7 @@ export default function OdooConfigPanel({
143
  />
144
  ) : (
145
  <span className="conn-odoo-v">
146
- {cfg.serverDb || "β€”"}
147
  {/* R6's second sentence: a thing you cannot change says WHY, not nothing. */}
148
  <em> (set on this deployment, not in this workspace)</em>
149
  </span>
@@ -152,7 +169,7 @@ export default function OdooConfigPanel({
152
 
153
  {/* ── R9's second reading: WHICH grids this workspace materialises ─────────────────── */}
154
  <p className="conn-odoo-h">
155
- Databases to build <span className="conn-odoo-count">{on} of {grids.length}</span>
156
  </p>
157
  <div className="conn-odoo-grids">
158
  {grids.map((g) => (
@@ -171,25 +188,32 @@ export default function OdooConfigPanel({
171
  database; it does not delete the one you already have. A checkbox that silently threw
172
  away rows would be the worst control on this page. */}
173
  <p className="conn-card-meta">
174
- Unticking one stops it being rebuilt on the next sync. Nothing you already have is
175
- deleted.
176
  </p>
177
 
178
  {/* ── R11: the cadence, from the server's own preset list, floor included ──────────── */}
179
- <p className="conn-odoo-h">How often to sync</p>
180
- <select
181
- className="conn-odoo-every"
182
- value={cfg.syncEvery ?? ""}
183
- disabled={busy || cfg.frozen}
184
- aria-label="How often to sync"
185
- onChange={(e) => onSyncEvery(e.target.value)}
186
- >
187
- {options.map((o) => (
188
- <option value={o} key={o}>
189
- {everyLabel(o)}
190
- </option>
191
- ))}
192
- </select>
 
 
 
 
 
 
 
193
 
194
  {/* ── R10: off, and back on ────────────────────────────────────────────────────────── */}
195
  {cfg.frozen ? (
 
29
  // writes. See `SyncCadenceTab`'s own header for the Amazon/Meta Ads answer.
30
  // ---------------------------------------------------------------------------
31
 
32
+ import { useCallback, useEffect, useMemo, useState } from "react";
33
  import { API_V1, CREDENTIALS } from "../apiContract";
34
  import type { ConnectorRow } from "./ConnectorsPage";
35
 
 
38
  key: string;
39
  label: string;
40
  enabled: boolean;
41
+ model?: string;
42
+ relevant?: boolean;
43
+ defaultEnabled?: boolean;
44
  }
45
 
46
  /** The config payload. Everything optional but `grids` is genuinely optional on the wire β€”
 
107
  onDisconnect: () => void;
108
  onReconnect: () => void;
109
  }) {
110
+ const grids = useMemo(
111
+ () =>
112
+ (cfg.grids ?? [])
113
+ .map((grid, index) => ({ grid, index }))
114
+ .sort(
115
+ (a, b) => Number(b.grid.enabled) - Number(a.grid.enabled) || a.index - b.index
116
+ )
117
+ .map(({ grid }) => grid),
118
+ [cfg.grids]
119
+ );
120
  const options = cfg.syncOptions ?? [];
121
  const on = grids.filter((g) => g.enabled).length;
122
  return (
 
125
 
126
  {/* ── the credential, as much of it as may be shown ────────────────────────────────── */}
127
  <div className="conn-odoo-row">
128
+ <span className="conn-odoo-k">Credential</span>
129
  <span className="conn-odoo-v">
130
  {cfg.preview ? cfg.preview : "held on this deployment"}
 
131
  </span>
132
  </div>
133
+ {cfg.apiUser ? (
134
+ <div className="conn-odoo-row">
135
+ <span className="conn-odoo-k">Account</span>
136
+ <span className="conn-odoo-v">{cfg.apiUser}</span>
137
+ </div>
138
+ ) : null}
139
  {cfg.serverUrl ? (
140
  <div className="conn-odoo-row">
141
  <span className="conn-odoo-k">Server</span>
 
160
  />
161
  ) : (
162
  <span className="conn-odoo-v">
163
+ {cfg.serverDb || "Not set"}
164
  {/* R6's second sentence: a thing you cannot change says WHY, not nothing. */}
165
  <em> (set on this deployment, not in this workspace)</em>
166
  </span>
 
169
 
170
  {/* ── R9's second reading: WHICH grids this workspace materialises ─────────────────── */}
171
  <p className="conn-odoo-h">
172
+ Databases available <span className="conn-odoo-count">{on} of {grids.length} enabled</span>
173
  </p>
174
  <div className="conn-odoo-grids">
175
  {grids.map((g) => (
 
188
  database; it does not delete the one you already have. A checkbox that silently threw
189
  away rows would be the worst control on this page. */}
190
  <p className="conn-card-meta">
191
+ Switching one off stops its next refresh. Its rows, fields, and access stay in this
192
+ workspace.
193
  </p>
194
 
195
  {/* ── R11: the cadence, from the server's own preset list, floor included ──────────── */}
196
+ <div className="conn-cadence-row">
197
+ <label htmlFor="conn-odoo-cadence">Sync</label>
198
+ <select
199
+ id="conn-odoo-cadence"
200
+ className="conn-odoo-every"
201
+ value={cfg.syncEvery ?? ""}
202
+ disabled={busy || cfg.frozen}
203
+ onChange={(e) => onSyncEvery(e.target.value)}
204
+ >
205
+ {options.map((o) => (
206
+ <option value={o} key={o}>
207
+ {everyLabel(o)}
208
+ </option>
209
+ ))}
210
+ </select>
211
+ {cfg.syncFloorSeconds ? (
212
+ <span className="conn-cadence-floor">
213
+ Minimum {Math.ceil(cfg.syncFloorSeconds / 60)} minutes
214
+ </span>
215
+ ) : null}
216
+ </div>
217
 
218
  {/* ── R10: off, and back on ────────────────────────────────────────────────────────── */}
219
  {cfg.frozen ? (
web/src/connectors/RelationshipDiagram.tsx CHANGED
@@ -51,7 +51,7 @@
51
  // constant here to the `--lp-fs-*` token used by the matching rule.
52
  // ---------------------------------------------------------------------------
53
 
54
- import { useCallback, useMemo, useState } from "react";
55
  import type { ConnectorRelationshipGraph } from "./ConnectorsPage";
56
  import "../styles/wave49/connectors.css";
57
 
@@ -246,7 +246,11 @@ function moreLabel(hidden: number, expanded: boolean): string {
246
  * function under node and proves the geometry over its return value, so every
247
  * number a reader sees on the screen is a number the gate has checked.
248
  */
249
- export function relationshipLayout(graph: DiagramInput, expandedKeys: string[] = []): DiagramLayout {
 
 
 
 
250
  const expanded = new Set(expandedKeys);
251
  const tables = graph.tables.slice();
252
  const relationships = graph.relationships.slice();
@@ -398,7 +402,13 @@ export function relationshipLayout(graph: DiagramInput, expandedKeys: string[] =
398
  // ---- the tables no relationship touches, in a wrapped grid under the bands.
399
  const singles = tables.filter((table) => !linkedTables.has(table.key));
400
  const linkedWidth = bandMembers.length ? CARD_W * 2 + GUTTER : CARD_W * 3 + SINGLE_GAP * 2;
401
- const perRow = Math.max(1, Math.floor((linkedWidth + SINGLE_GAP) / (CARD_W + SINGLE_GAP)));
 
 
 
 
 
 
402
  let singleRowTop = cursorY;
403
  let rowHeight = 0;
404
  singles.forEach((table, index) => {
@@ -612,6 +622,7 @@ export function relationshipLayout(graph: DiagramInput, expandedKeys: string[] =
612
  for (const card of cards) width = Math.max(width, card.x + card.width);
613
  for (const edge of edges) width = Math.max(width, edge.corridorX);
614
  for (const text of texts) width = Math.max(width, text.x + text.width);
 
615
  let height = PAD;
616
  for (const card of cards) height = Math.max(height, card.y + card.height);
617
  for (const text of texts) height = Math.max(height, text.y + text.height);
@@ -679,9 +690,27 @@ export default function RelationshipDiagram({
679
  graph: ConnectorRelationshipGraph;
680
  }) {
681
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
 
 
682
  // ⚠ HOOKS BEFORE ANY EARLY RETURN. A refused graph must not change the hook
683
  // order between renders ([[react-hooks-order-gate]]).
684
- const layout = useMemo(() => relationshipLayout(graph, expandedKeys), [graph, expandedKeys]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
685
  const toggle = useCallback((key: string) => {
686
  setExpandedKeys((keys) => (keys.includes(key) ? keys.filter((k) => k !== key) : keys.concat(key)));
687
  }, []);
@@ -699,7 +728,7 @@ export default function RelationshipDiagram({
699
 
700
  return (
701
  <div className="conn-rd">
702
- <div className="conn-rd-scroll">
703
  <div className="conn-rd-stage" style={{ width: layout.width, height: layout.height }}>
704
  <svg
705
  className="conn-rd-edges"
 
51
  // constant here to the `--lp-fs-*` token used by the matching rule.
52
  // ---------------------------------------------------------------------------
53
 
54
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
55
  import type { ConnectorRelationshipGraph } from "./ConnectorsPage";
56
  import "../styles/wave49/connectors.css";
57
 
 
246
  * function under node and proves the geometry over its return value, so every
247
  * number a reader sees on the screen is a number the gate has checked.
248
  */
249
+ export function relationshipLayout(
250
+ graph: DiagramInput,
251
+ expandedKeys: string[] = [],
252
+ availableWidth = 0
253
+ ): DiagramLayout {
254
  const expanded = new Set(expandedKeys);
255
  const tables = graph.tables.slice();
256
  const relationships = graph.relationships.slice();
 
402
  // ---- the tables no relationship touches, in a wrapped grid under the bands.
403
  const singles = tables.filter((table) => !linkedTables.has(table.key));
404
  const linkedWidth = bandMembers.length ? CARD_W * 2 + GUTTER : CARD_W * 3 + SINGLE_GAP * 2;
405
+ // T17 can add any number of readable models. Use the measured viewport when it exists so
406
+ // those server-owned nodes consume the room the modal actually has instead of remaining in a
407
+ // fixed three-card canvas. The default preserves deterministic bare-node gate geometry.
408
+ const singlesWidth = availableWidth > 0
409
+ ? Math.max(CARD_W, availableWidth - PAD * 2)
410
+ : linkedWidth;
411
+ const perRow = Math.max(1, Math.floor((singlesWidth + SINGLE_GAP) / (CARD_W + SINGLE_GAP)));
412
  let singleRowTop = cursorY;
413
  let rowHeight = 0;
414
  singles.forEach((table, index) => {
 
622
  for (const card of cards) width = Math.max(width, card.x + card.width);
623
  for (const edge of edges) width = Math.max(width, edge.corridorX);
624
  for (const text of texts) width = Math.max(width, text.x + text.width);
625
+ if (availableWidth > 0) width = Math.max(width, availableWidth - PAD);
626
  let height = PAD;
627
  for (const card of cards) height = Math.max(height, card.y + card.height);
628
  for (const text of texts) height = Math.max(height, text.y + text.height);
 
690
  graph: ConnectorRelationshipGraph;
691
  }) {
692
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
693
+ const scrollRef = useRef<HTMLDivElement>(null);
694
+ const [availableWidth, setAvailableWidth] = useState(0);
695
  // ⚠ HOOKS BEFORE ANY EARLY RETURN. A refused graph must not change the hook
696
  // order between renders ([[react-hooks-order-gate]]).
697
+ useEffect(() => {
698
+ const surface = scrollRef.current;
699
+ if (!surface) return;
700
+ const measure = () => setAvailableWidth(Math.max(0, Math.floor(surface.clientWidth)));
701
+ measure();
702
+ if (typeof ResizeObserver === "undefined") {
703
+ window.addEventListener("resize", measure);
704
+ return () => window.removeEventListener("resize", measure);
705
+ }
706
+ const observer = new ResizeObserver(measure);
707
+ observer.observe(surface);
708
+ return () => observer.disconnect();
709
+ }, []);
710
+ const layout = useMemo(
711
+ () => relationshipLayout(graph, expandedKeys, availableWidth),
712
+ [availableWidth, graph, expandedKeys]
713
+ );
714
  const toggle = useCallback((key: string) => {
715
  setExpandedKeys((keys) => (keys.includes(key) ? keys.filter((k) => k !== key) : keys.concat(key)));
716
  }, []);
 
728
 
729
  return (
730
  <div className="conn-rd">
731
+ <div className="conn-rd-scroll" ref={scrollRef}>
732
  <div className="conn-rd-stage" style={{ width: layout.width, height: layout.height }}>
733
  <svg
734
  className="conn-rd-edges"
web/src/customer-grid/CatalogView.tsx CHANGED
@@ -146,6 +146,102 @@ export function isPlaced(it: CatalogViewItem | undefined): boolean {
146
  return !!it && it.x != null && it.y != null;
147
  }
148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  // ------------------------------------------------------------------- marks
150
 
151
  const STROKE = {
 
146
  return !!it && it.x != null && it.y != null;
147
  }
148
 
149
+ /** A saved Catalog Application is deliberately much smaller than an authored Catalog View.
150
+ * It binds three semantic roles to ordinary database fields and renders the current row set.
151
+ * The definition comes from the Application registry, never from a client-side template draft. */
152
+ export interface CatalogApplicationDefinition {
153
+ id: string;
154
+ name: string;
155
+ templateKind: "catalog";
156
+ sourceDatabase: string;
157
+ fieldMap: { key: string; title: string; image?: string };
158
+ }
159
+
160
+ export interface CatalogApplicationItem {
161
+ pid: number;
162
+ key: string;
163
+ title: string;
164
+ image: string;
165
+ }
166
+
167
+ function applicationImageUrl(value: string): string {
168
+ if (/^https?:\/\//i.test(value)) return value;
169
+ return assetUrl(value, "web");
170
+ }
171
+
172
+ /** Pure role projection shared by the renderer and its negative-control gate. */
173
+ export function catalogApplicationItems(
174
+ rows: Row[],
175
+ fieldMap: CatalogApplicationDefinition["fieldMap"],
176
+ ): CatalogApplicationItem[] {
177
+ const items: CatalogApplicationItem[] = [];
178
+ for (const row of rows) {
179
+ const key = String(row[fieldMap.key] ?? "").trim();
180
+ if (!key) continue;
181
+ const title = String(row[fieldMap.title] ?? "").trim() || key;
182
+ const image = fieldMap.image ? String(row[fieldMap.image] ?? "").trim() : "";
183
+ items.push({ pid: row.pid, key, title, image });
184
+ }
185
+ return items;
186
+ }
187
+
188
+ /** The trusted read-only surface launched by a Catalog Application definition. Existing
189
+ * Catalog Views continue to use the full page editor below and are not converted or deleted. */
190
+ export const CatalogApplicationView = memo(function CatalogApplicationView({
191
+ definition,
192
+ rows,
193
+ onOpen,
194
+ }: {
195
+ definition: CatalogApplicationDefinition;
196
+ rows: Row[];
197
+ onOpen: (pid: number) => void;
198
+ }) {
199
+ const items = useMemo(
200
+ () => catalogApplicationItems(rows, definition.fieldMap),
201
+ [rows, definition.fieldMap],
202
+ );
203
+ return (
204
+ <section className="cg-app-catalog" aria-label={`${definition.name} catalog`}>
205
+ <header className="cg-app-catalog-head">
206
+ <div>
207
+ <p className="cg-app-catalog-kicker">Catalog app</p>
208
+ <h2>{definition.name}</h2>
209
+ </div>
210
+ <span className="cg-app-catalog-count">
211
+ {items.length.toLocaleString()} {items.length === 1 ? "record" : "records"}
212
+ </span>
213
+ </header>
214
+ {items.length ? (
215
+ <div className="cg-app-catalog-grid">
216
+ {items.map((item) => (
217
+ <button
218
+ key={item.pid}
219
+ type="button"
220
+ className="cg-app-catalog-card"
221
+ onClick={() => onOpen(item.pid)}
222
+ aria-label={`Open ${item.title}`}
223
+ >
224
+ <span className="cg-app-catalog-image">
225
+ {item.image ? (
226
+ <img src={applicationImageUrl(item.image)} alt="" loading="lazy" />
227
+ ) : (
228
+ <span>No image</span>
229
+ )}
230
+ </span>
231
+ <span className="cg-app-catalog-copy">
232
+ <strong>{item.title}</strong>
233
+ <span>{item.key}</span>
234
+ </span>
235
+ </button>
236
+ ))}
237
+ </div>
238
+ ) : (
239
+ <p className="cg-app-catalog-empty">No records have a value in the mapped key field.</p>
240
+ )}
241
+ </section>
242
+ );
243
+ });
244
+
245
  // ------------------------------------------------------------------- marks
246
 
247
  const STROKE = {
web/src/customer-grid/MapView.tsx CHANGED
@@ -55,8 +55,12 @@
55
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
56
  import type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from "react";
57
  import type { Field, Row, ViewConfig } from "./types";
58
- import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
59
  import { formatDisplay } from "./cells";
 
 
 
 
60
  import { LAND_PATH, LAKE_PATHS } from "./mapGeometry";
61
  import {
62
  BASEMAP_DETAIL_K,
@@ -641,7 +645,7 @@ function DrawZoneIcon() {
641
  );
642
  }
643
 
644
- export function MapView({
645
  rows,
646
  field,
647
  coordinateFields,
@@ -659,6 +663,7 @@ export function MapView({
659
  tableKey,
660
  onManagedRouteViewState,
661
  onZoneChanged,
 
662
  }: {
663
  /** DISTINCT data rows from the full pipeline, overlay edits layered β€” the
664
  * calendar/kanban contract, verbatim. */
@@ -708,6 +713,9 @@ export function MapView({
708
  /** Customer Zones also project into the read-only grid field, so a successful normalized
709
  * mutation invalidates the host row payload instead of leaving that projection stale. */
710
  onZoneChanged?: () => void;
 
 
 
711
  /**
712
  * ⭐⭐ OWNER ITEM 9 β€” THE WHOLE BOOK, so a stop can be added that the VIEW filtered out.
713
  *
@@ -3580,7 +3588,7 @@ export function MapView({
3580
 
3581
  if (!view || !fit) {
3582
  return (
3583
- <div className="cg-mode-empty">
3584
  No records with a location to map yet. Set latitude and longitude fields in View schema to plot records.
3585
  {noCoords > 0 &&
3586
  ` ${noCoords.toLocaleString()} matching record${noCoords === 1 ? "" : "s"} have no location.`}
@@ -3667,7 +3675,7 @@ export function MapView({
3667
 
3668
  return (
3669
  <div
3670
- className="cg-mapview"
3671
  /* Both custom properties, from ONE number. The unsaved shape stays exactly half, which is
3672
  the invariant `map-panels.css` says has already survived three retunes. */
3673
  style={{
@@ -3676,6 +3684,9 @@ export function MapView({
3676
  } as React.CSSProperties}
3677
  >
3678
  <div className="cg-map-bar">
 
 
 
3679
  {/* The count is "N of M", never a bare N: a pin can only be drawn for a
3680
  row the host geocoded, and a lone "1,402" silently redefines the
3681
  toolbar's 1,550 ([[no-unverifiable-aggregates]]). */}
@@ -4598,6 +4609,7 @@ export function MapView({
4598
  is already loaded here to draw the map, so RouteNav gets a pass-through and
4599
  never a second fetch of its own. */}
4600
  <RouteNav
 
4601
  routes={namedRoutes}
4602
  folders={routeFolders}
4603
  selectedIds={selectedRouteIds}
@@ -4950,3 +4962,139 @@ export function MapView({
4950
  </div>
4951
  );
4952
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
56
  import type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from "react";
57
  import type { Field, Row, ViewConfig } from "./types";
58
+ import { API_V1, CREDENTIALS, NAV_MINIMIZE_EVENT, signal } from "../apiContract";
59
  import { formatDisplay } from "./cells";
60
+ import { readDataPath } from "./dataPath";
61
+ import { CatalogApplicationView } from "./CatalogView";
62
+ import type { CatalogApplicationDefinition } from "./CatalogView";
63
+ import { applicationTemplateSurface } from "./viewModes";
64
  import { LAND_PATH, LAKE_PATHS } from "./mapGeometry";
65
  import {
66
  BASEMAP_DETAIL_K,
 
645
  );
646
  }
647
 
648
+ function MapViewSurface({
649
  rows,
650
  field,
651
  coordinateFields,
 
663
  tableKey,
664
  onManagedRouteViewState,
665
  onZoneChanged,
666
+ applicationName,
667
  }: {
668
  /** DISTINCT data rows from the full pipeline, overlay edits layered β€” the
669
  * calendar/kanban contract, verbatim. */
 
713
  /** Customer Zones also project into the read-only grid field, so a successful normalized
714
  * mutation invalidates the host row payload instead of leaving that projection stale. */
715
  onZoneChanged?: () => void;
716
+ /** Saved Routing Application identity, shown in the route navigator without changing the
717
+ * existing View or its route assets. */
718
+ applicationName?: string;
719
  /**
720
  * ⭐⭐ OWNER ITEM 9 β€” THE WHOLE BOOK, so a stop can be added that the VIEW filtered out.
721
  *
 
3588
 
3589
  if (!view || !fit) {
3590
  return (
3591
+ <div className={"cg-mode-empty" + (applicationName ? " cg-app-route-surface" : "")}>
3592
  No records with a location to map yet. Set latitude and longitude fields in View schema to plot records.
3593
  {noCoords > 0 &&
3594
  ` ${noCoords.toLocaleString()} matching record${noCoords === 1 ? "" : "s"} have no location.`}
 
3675
 
3676
  return (
3677
  <div
3678
+ className={"cg-mapview" + (applicationName ? " cg-app-route-surface" : "")}
3679
  /* Both custom properties, from ONE number. The unsaved shape stays exactly half, which is
3680
  the invariant `map-panels.css` says has already survived three retunes. */
3681
  style={{
 
3684
  } as React.CSSProperties}
3685
  >
3686
  <div className="cg-map-bar">
3687
+ {applicationName ? (
3688
+ <span className="cg-app-map-name"><small>Routing app</small><strong>{applicationName}</strong></span>
3689
+ ) : null}
3690
  {/* The count is "N of M", never a bare N: a pin can only be drawn for a
3691
  row the host geocoded, and a lone "1,402" silently redefines the
3692
  toolbar's 1,550 ([[no-unverifiable-aggregates]]). */}
 
4609
  is already loaded here to draw the map, so RouteNav gets a pass-through and
4610
  never a second fetch of its own. */}
4611
  <RouteNav
4612
+ applicationName={applicationName}
4613
  routes={namedRoutes}
4614
  folders={routeFolders}
4615
  selectedIds={selectedRouteIds}
 
4962
  </div>
4963
  );
4964
  }
4965
+
4966
+ type MapViewProps = Parameters<typeof MapViewSurface>[0];
4967
+
4968
+ interface RegistryTemplateApplication {
4969
+ id: string;
4970
+ name: string;
4971
+ type: string;
4972
+ templateKind?: unknown;
4973
+ sourceDatabase?: unknown;
4974
+ fieldMap?: unknown;
4975
+ openTarget?: { database?: unknown };
4976
+ compatibleDatabases?: unknown[];
4977
+ }
4978
+
4979
+ type TemplateApplicationState =
4980
+ | { phase: "idle" }
4981
+ | { phase: "loading"; key: string }
4982
+ | { phase: "ready"; key: string; application: RegistryTemplateApplication | null }
4983
+ | { phase: "error"; key: string; message: string };
4984
+
4985
+ /** Resolve an Application deep link from the registry before selecting a specialized renderer.
4986
+ * CustomerGrid still applies the definition's ordinary display config; this wrapper only handles
4987
+ * the route and catalog discriminators which deliberately share the trusted Map mode. */
4988
+ export function MapView(props: MapViewProps) {
4989
+ const target = readDataPath();
4990
+ const applicationId = target?.application ?? "";
4991
+ const database = target?.database ?? "";
4992
+ const requestKey = applicationId && database ? `${database}::${applicationId}` : "";
4993
+ const [state, setState] = useState<TemplateApplicationState>(() => requestKey
4994
+ ? { phase: "loading", key: requestKey }
4995
+ : { phase: "idle" });
4996
+ const requestGeneration = useRef(0);
4997
+
4998
+ useEffect(() => {
4999
+ const mine = ++requestGeneration.current;
5000
+ if (!applicationId || !database) {
5001
+ setState({ phase: "idle" });
5002
+ return;
5003
+ }
5004
+ const controller = new AbortController();
5005
+ setState({ phase: "loading", key: requestKey });
5006
+ void fetch(`${API_V1}/applications?database=${encodeURIComponent(database)}`, {
5007
+ credentials: CREDENTIALS,
5008
+ signal: controller.signal,
5009
+ }).then(async (response) => {
5010
+ const body = await response.json().catch(() => ({}));
5011
+ if (!response.ok) {
5012
+ throw new Error(String(
5013
+ body?.detail?.message ?? body?.detail ?? "The Application could not be loaded.",
5014
+ ));
5015
+ }
5016
+ const applications = Array.isArray(body?.applications)
5017
+ ? body.applications as RegistryTemplateApplication[]
5018
+ : [];
5019
+ const application = applications.find((candidate) => candidate.id === applicationId) ?? null;
5020
+ if (!application) throw new Error("This Application is no longer available.");
5021
+ const compatible = application.openTarget?.database === database ||
5022
+ application.compatibleDatabases?.includes(database) === true;
5023
+ if (!compatible) throw new Error("This Application cannot open this database.");
5024
+ if (controller.signal.aborted || mine !== requestGeneration.current) return;
5025
+ const live = readDataPath();
5026
+ if (live?.application !== applicationId || live.database !== database) return;
5027
+ setState({ phase: "ready", key: requestKey, application });
5028
+ }).catch((error: unknown) => {
5029
+ if (controller.signal.aborted || mine !== requestGeneration.current) return;
5030
+ setState({
5031
+ phase: "error",
5032
+ key: requestKey,
5033
+ message: error instanceof Error ? error.message : "The Application could not be loaded.",
5034
+ });
5035
+ });
5036
+ return () => controller.abort();
5037
+ }, [applicationId, database, requestKey]);
5038
+
5039
+ if (applicationId && (state.phase === "idle" || state.key !== requestKey || state.phase === "loading")) {
5040
+ return (
5041
+ <div className="cg-app-launch-state" role="status" aria-label="Loading Application">
5042
+ <span className="cg-app-launch-line is-wide" />
5043
+ <span className="cg-app-launch-line" />
5044
+ <span className="cg-app-launch-grid" />
5045
+ </div>
5046
+ );
5047
+ }
5048
+ if (applicationId && state.phase === "error" && state.key === requestKey) {
5049
+ return <div className="cg-app-launch-state is-error" role="alert">{state.message}</div>;
5050
+ }
5051
+
5052
+ const application = state.phase === "ready" && state.key === requestKey ? state.application : null;
5053
+ const surface = applicationTemplateSurface(application);
5054
+ const fieldMap = application?.fieldMap && typeof application.fieldMap === "object" &&
5055
+ !Array.isArray(application.fieldMap)
5056
+ ? application.fieldMap as Record<string, unknown>
5057
+ : {};
5058
+
5059
+ if (surface === "catalog") {
5060
+ const key = String(fieldMap.key ?? "");
5061
+ const title = String(fieldMap.title ?? "");
5062
+ if (!application || !key || !title) {
5063
+ return <div className="cg-app-launch-state is-error" role="alert">The Catalog field mapping is incomplete.</div>;
5064
+ }
5065
+ const definition: CatalogApplicationDefinition = {
5066
+ id: application.id,
5067
+ name: application.name,
5068
+ templateKind: "catalog",
5069
+ sourceDatabase: String(application.sourceDatabase ?? database),
5070
+ fieldMap: {
5071
+ key,
5072
+ title,
5073
+ ...(fieldMap.image ? { image: String(fieldMap.image) } : {}),
5074
+ },
5075
+ };
5076
+ return <CatalogApplicationView definition={definition} rows={props.rows} onOpen={props.onOpen} />;
5077
+ }
5078
+
5079
+ if (surface === "route" && application) {
5080
+ const titleKey = String(fieldMap.title ?? "");
5081
+ const latitudeKey = String(fieldMap.latitude ?? "");
5082
+ const longitudeKey = String(fieldMap.longitude ?? "");
5083
+ const coordinateFields = latitudeKey && longitudeKey
5084
+ ? {
5085
+ latitude: { ...props.field, key: latitudeKey, label: "Latitude" },
5086
+ longitude: { ...props.field, key: longitudeKey, label: "Longitude" },
5087
+ }
5088
+ : props.coordinateFields;
5089
+ return (
5090
+ <MapViewSurface
5091
+ {...props}
5092
+ field={titleKey ? { ...props.field, key: titleKey, label: "Record title" } : props.field}
5093
+ coordinateFields={coordinateFields}
5094
+ applicationName={application.name}
5095
+ />
5096
+ );
5097
+ }
5098
+
5099
+ return <MapViewSurface {...props} />;
5100
+ }
web/src/customer-grid/RecordDetail.css CHANGED
@@ -892,6 +892,83 @@
892
  opacity: 0.6;
893
  }
894
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
895
  /* Folded, the real rows show no labels at all, so the placeholders drop their bars for the same
896
  reason `.shell-side.is-collapsed .shell-rail-skeleton-bar` does: otherwise the fold runs
897
  against a width the settled rail never has. */
@@ -1183,6 +1260,19 @@
1183
  white-space: nowrap;
1184
  }
1185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1186
  .cg-record-comment-compose-foot span {
1187
  min-width: 0;
1188
  overflow: hidden;
@@ -1460,6 +1550,12 @@
1460
  }
1461
 
1462
  @media (prefers-reduced-motion: reduce) {
 
 
 
 
 
 
1463
  .cg-refusal-sum::before {
1464
  transition: none;
1465
  }
 
892
  opacity: 0.6;
893
  }
894
 
895
+ /* W55-T15: one compact control row above every related projection. It reserves the same height
896
+ before and after a mode change, and the hairline is the drawer's only internal separator. */
897
+ .cg-record-related-modebar {
898
+ flex: 0 0 40px;
899
+ min-width: 0;
900
+ min-height: 40px;
901
+ display: flex;
902
+ align-items: center;
903
+ padding: 0 12px;
904
+ border-bottom: 1px solid var(--lp-line);
905
+ background: var(--lp-surface);
906
+ }
907
+
908
+ .cg-record-related-modebar .cg-modes,
909
+ .cg-record-related-modebar .cg-tb-btn,
910
+ .cg-record-related-modebar .cg-mode-field {
911
+ min-height: 28px;
912
+ align-items: center;
913
+ line-height: 1;
914
+ }
915
+
916
+ /* The canonical projection owns its scrolling while this host owns the bounded drawer slot. */
917
+ .cg-record-related-modebody,
918
+ .cg-record-mode-skeleton {
919
+ flex: 1 1 auto;
920
+ min-width: 0;
921
+ min-height: 0;
922
+ }
923
+
924
+ .cg-record-related-modebody {
925
+ overflow: auto;
926
+ background: var(--lp-surface);
927
+ animation: cg-record-mode-arrive 160ms ease-out both;
928
+ }
929
+
930
+ /* Stable geometry replaces the requested projection immediately. No previous row content remains
931
+ underneath it, and the five row bars keep the body height unchanged while the read settles. */
932
+ .cg-record-mode-skeleton {
933
+ display: grid;
934
+ grid-template-rows: 24px repeat(5, 36px) minmax(0, 1fr);
935
+ gap: 8px;
936
+ overflow: hidden;
937
+ padding: 16px;
938
+ background: var(--lp-surface);
939
+ animation: cg-record-mode-arrive 160ms ease-out both;
940
+ }
941
+
942
+ .cg-record-mode-skeleton-head,
943
+ .cg-record-mode-skeleton-row {
944
+ display: block;
945
+ border-radius: 4px;
946
+ background: var(--lp-surface-2);
947
+ }
948
+
949
+ .cg-record-mode-skeleton-head {
950
+ width: min(220px, 36%);
951
+ }
952
+
953
+ .cg-record-mode-skeleton-row {
954
+ width: 100%;
955
+ }
956
+
957
+ .cg-record-mode-skeleton-row.is-short {
958
+ width: 72%;
959
+ }
960
+
961
+ @keyframes cg-record-mode-arrive {
962
+ from {
963
+ opacity: 0.58;
964
+ transform: translateY(4px);
965
+ }
966
+ to {
967
+ opacity: 1;
968
+ transform: translateY(0);
969
+ }
970
+ }
971
+
972
  /* Folded, the real rows show no labels at all, so the placeholders drop their bars for the same
973
  reason `.shell-side.is-collapsed .shell-rail-skeleton-bar` does: otherwise the fold runs
974
  against a width the settled rail never has. */
 
1260
  white-space: nowrap;
1261
  }
1262
 
1263
+ /* W55-T16: the position keeps its footprint while a latest-intent navigation settles. */
1264
+ .cg-record-modal .cg-detail-pos-skeleton {
1265
+ flex: 0 0 112px;
1266
+ width: 112px;
1267
+ height: 8px;
1268
+ border-radius: 4px;
1269
+ background: var(--lp-surface-2);
1270
+ animation-name: cg-record-mode-arrive;
1271
+ animation-duration: 160ms;
1272
+ animation-timing-function: ease-out;
1273
+ animation-fill-mode: both;
1274
+ }
1275
+
1276
  .cg-record-comment-compose-foot span {
1277
  min-width: 0;
1278
  overflow: hidden;
 
1550
  }
1551
 
1552
  @media (prefers-reduced-motion: reduce) {
1553
+ .cg-record-related-modebody,
1554
+ .cg-record-mode-skeleton,
1555
+ .cg-detail-pos-skeleton {
1556
+ animation: none;
1557
+ }
1558
+
1559
  .cg-refusal-sum::before {
1560
  transition: none;
1561
  }
web/src/customer-grid/RecordDetail.tsx CHANGED
@@ -49,18 +49,19 @@ import { AI_STATE_PREFIX, choiceOptions, codeLanguageOf, isPickType, mayEditFiel
49
  [[two-lanes-one-contract-dead-feature]]. */
50
  import { CUSTOMER_TOPIC, PRODUCT_TOPIC, RELATED_REFUSAL, relatedTabs, skeletonTabs,
51
  topicForScope } from "./types";
52
- import type { CustomerDoc, Field, RelatedEntry, RelatedPin, RelatedRefusal, RelatedVia, Row,
53
- Viewer } from "./types";
54
- /* ⭐ THE THREE DOORS THIS PANEL ASKS, ALL OF THEM ALREADY OWNED BY `apiBridge`: what is related
55
- to this table, what the databases are called, and whether an edge's pinned read can be served
56
- today. No `fetch` is written here β€” `apiBridge` owns the credential mode, the session handling
57
- and the refusal reading, and a fourth copy of that in a drawer is how one surface stops
58
- noticing an expired cookie. */
59
  /* ⭐ W53-T22 adds a FOURTH and a FIFTH, and for the same reason: `fetchTableWindow` +
60
  `WINDOW_ROWS` are the one windowed read this product owns, and the sibling set a pushed
61
  frame's chevrons page is that read with the frame's own pin on it. */
62
- import { fetchLinkTargets, fetchRelated, fetchTableWindow, probeRelatedRead, readThroughTables,
63
- WINDOW_ROWS } from "./apiBridge";
 
64
 
65
  /**
66
  * ⭐⭐ WAVE-34 (owner ruling R13) β€” whose value sits in this enrichment cell, in words.
@@ -130,6 +131,7 @@ import RecordComments from "./RecordComments";
130
  // (`tab`/`activeTab`/`setTab`, unchanged below), a different DOM shape: a `cg-views` nav down the
131
  // side instead of a tablist strip under the title. See RecordRail.tsx's own header for why.
132
  import RecordRail from "./RecordRail";
 
133
  import { isStreamlitComponent } from "./hostBridge";
134
  // ⚠ ALIASED for the same reason `CustomerGrid` aliases it: `./Stars`'s `StarIcon` is the RATING
135
  // atom and this one is the record MARK. Two meanings, one noun, both reachable in this tree.
@@ -466,9 +468,69 @@ function ChoiceCreateInput({
466
  type RelatedTabState =
467
  | { status: "probing" }
468
  | { status: "ready" }
469
- | { status: "projected" }
470
  | { status: "refused"; reason: string; code: string; table?: string; hop?: string };
471
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
472
  /**
473
  * ⭐⭐ W53-T24 Β· R13 β€” **WHO THE REFUSAL IS ABOUT**, and it is the SERVER'S OWN DATUM every time.
474
  *
@@ -779,6 +841,102 @@ function linkedPids(value: unknown): number[] {
779
  return [...seen];
780
  }
781
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
782
  function relatedScope(target: string): SurfaceScope {
783
  if (target === CUSTOMER_TOPIC.key) return CUSTOMER_TOPIC.scope as SurfaceScope;
784
  if (target === PRODUCT_TOPIC.key) return PRODUCT_TOPIC.scope as SurfaceScope;
@@ -831,6 +989,13 @@ export default function RecordDetail({
831
  */
832
  const [stack, setStack] = useState<RecordFrame[]>([]);
833
  const frame = stack.length > 0 ? stack[stack.length - 1] : null;
 
 
 
 
 
 
 
834
  /**
835
  * β›”β›” THE SHADOW IS THE WHOLE MECHANISM, AND IT IS DELIBERATE RATHER THAN CLEVER. Every one of
836
  * the ~40 references below (`renderRow`, the ordering, the editors, the viewers) reads `fields`
@@ -1131,17 +1296,18 @@ export default function RecordDetail({
1131
  * β›” AND AN EMPTY ANSWER IS NOT A LOADING ONE. A database with no relations settles to zero
1132
  * tabs and the placeholders go, because `relatedPending` is false the moment the stamp matches.
1133
  */
 
1134
  const tabs = useMemo(
1135
  () => (relatedPending && !entries.length
1136
  ? skeletonTabs()
1137
- : relatedTabs(entries, (target) => tableLabels[target] ?? "")),
1138
- [entries, tableLabels, relatedPending]
1139
  );
1140
 
1141
  /**
1142
- * Which tab is open, by EDGE KEY. `"fields"` is the default and the fallback: a tab whose edge
1143
- * has disappeared (a link column deleted while the drawer was open) drops back to Fields
1144
- * rather than rendering a panel for an edge that is no longer offered.
1145
  */
1146
  /* ⭐⭐ W53-T22 β€” STAMPED WITH ITS TABLE, THE SAME WAY `related` IS, AND FOR THE SAME RENDER.
1147
  An edge key belongs to ONE database's relation list; carried across a hop it names an edge
@@ -1150,13 +1316,21 @@ export default function RecordDetail({
1150
  parent's selection at all.
1151
  ⚠ `setTab` STAYS A `(tab: string) => void`, so `RecordRail`'s props do not change and the
1152
  mount below stays byte-identical to what `verify_wiring.py` asserts. */
1153
- const [tabSel, setTabSel] = useState<{ table: string; key: string }>(
1154
- { table: "", key: "fields" }
1155
  );
1156
- const tab = tabSel.table === recordTable ? tabSel.key : "fields";
 
 
 
 
1157
  const setTab = useCallback(
1158
- (next: string) => setTabSel({ table: recordTable, key: next }),
1159
- [recordTable]
 
 
 
 
1160
  );
1161
  const activeTab = tabs.some((entry) => entry.entry.key === tab) ? tab : "fields";
1162
  const activeRelated = tabs.find((entry) => entry.entry.key === activeTab) ?? null;
@@ -1164,18 +1338,47 @@ export default function RecordDetail({
1164
  /**
1165
  * ⭐⭐ CLAUSE 10 β€” THE LAST-OPENED VIEW **PER TAB**, PER PERSON, IN `localStorage`.
1166
  *
1167
- * β›” PER TAB, NOT PER DATABASE. R2 gives two links between the same pair two tabs, so two tabs
1168
- * can point at one database; a memory keyed by the target alone would make each of them reopen
1169
- * on the other's view. The key is `<this table>:<edge key>`, and the EDGE KEY is what makes it
1170
- * unique: `relations._entry`'s own note says the entry key is the only member of `via` that
1171
- * identifies an edge on its own, precisely because `{direction, on}` does not.
1172
  * ⚠ `writeTabViews` runs inside the updater rather than beside it, so the write and the
1173
  * decision that there IS something to write are one expression. Under StrictMode the updater
1174
  * is invoked twice in development, which writes the same value twice; the write is idempotent
1175
  * and that is cheaper than a second effect whose only job is to mirror this state.
1176
  */
1177
  const [tabViews, setTabViews] = useState<Record<string, string>>(readTabViews);
1178
- const tabViewKey = activeRelated ? `${recordTable}:${activeRelated.entry.key}` : "";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1179
  const rememberTabView = useCallback(
1180
  (viewId: string) => {
1181
  if (!tabViewKey) return;
@@ -1319,6 +1522,11 @@ export default function RecordDetail({
1319
  const [siblings, setSiblings] = useState<{ key: string; rows: Row[]; fields: Field[] }>(
1320
  { key: "", rows: EMPTY_ROWS, fields: EMPTY_FIELDS }
1321
  );
 
 
 
 
 
1322
  useEffect(() => {
1323
  if (!framePinKey) return;
1324
  const asked = JSON.parse(framePinKey) as { table: string; pin: RelatedPin };
@@ -1343,8 +1551,13 @@ export default function RecordDetail({
1343
  const siblingIndex = frame
1344
  ? siblingRows.findIndex((row) => Number(row.pid) === frame.pid)
1345
  : -1;
1346
- const frameCanPrev = siblingIndex > 0;
1347
- const frameCanNext = siblingIndex >= 0 && siblingIndex < siblingRows.length - 1;
 
 
 
 
 
1348
  /**
1349
  * One step along the frame's own row set. It REPLACES the top frame rather than pushing one,
1350
  * so paging orders inside a customer leaves the breadcrumb reading `Customer / Order` at the
@@ -1355,11 +1568,23 @@ export default function RecordDetail({
1355
  const stepFrame = useCallback(
1356
  (delta: number) => {
1357
  if (!frame || siblingIndex < 0) return;
1358
- const next = siblingRows[siblingIndex + delta];
 
 
 
 
 
 
1359
  if (!next) return;
1360
  const first = siblings.fields[0];
1361
  const named = first ? String(next[first.key] ?? "") : "";
1362
  const pid = Number(next.pid);
 
 
 
 
 
 
1363
  setStack((prev) => (prev.length === 0 ? prev : [...prev.slice(0, -1), {
1364
  table: frame.table,
1365
  pid,
@@ -1369,7 +1594,15 @@ export default function RecordDetail({
1369
  pin: frame.pin,
1370
  }]));
1371
  },
1372
- [frame, siblingIndex, siblingRows, siblings.fields]
 
 
 
 
 
 
 
 
1373
  );
1374
  /**
1375
  * The frame's own caption, in the host's shape (`Record 3 of 3,673`) with the DATABASE's name
@@ -1428,72 +1661,285 @@ export default function RecordDetail({
1428
  * fetch the server's sentence for the state, and `unpinnableNote` covers the one state that
1429
  * has no server sentence (the roster says no while the door answers 200).
1430
  */
1431
- const [tabState, setTabState] = useState<RelatedTabState>({ status: "probing" });
 
 
 
 
 
 
 
 
1432
  useEffect(() => {
 
 
 
 
 
 
 
 
 
 
 
1433
  if (!activeRelated || !relatedPin) {
1434
- setTabState({ status: "probing" });
 
 
1435
  return;
1436
  }
1437
- let live = true;
1438
- setTabState({ status: "probing" });
1439
- const target = activeRelated.entry.target;
1440
- const pin = { table: relatedPin.table, record: relatedPin.record, via: relatedPin.via };
1441
- void (async () => {
1442
- const through = await readThroughTables();
1443
- if (!live) return;
1444
- // β›” THE ONE MOUNT CONDITION, and it is the read path's own. See the note above.
1445
- const pinnable = activeRelated.entry.served && through.has(target);
1446
- if (pinnable) {
1447
- setTabState({ status: "ready" });
1448
- return;
1449
- }
1450
- /* ⭐⭐ W53-T25 Β· D-657 β€” THE THIRD OUTCOME, AND THE ROSTER IS STILL WHAT SEPARATES IT FROM
1451
- THE FIRST. `through.has(target)` is asked again rather than inferred from `!pinnable`,
1452
- because those two come apart on exactly the edge that matters: a target the roster DOES
1453
- name whose entry is `served: false` is a read-through table, and pulling one whole is the
1454
- standing-rule-1 violation this branch must never commit. Not on the roster β‡’ the whole
1455
- table is what its own Data page reads anyway, through the same door, under the same
1456
- reported cap. See `RelatedTabState` and `projectedIds`. */
1457
- if (!through.has(target) && projectedIds) {
1458
- setTabState({ status: "projected" });
1459
- return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1460
  }
1461
- /* ⭐⭐ W54-T40 Β· INSTRUCTION 22 β€” **THE PROBE IS ONLY ASKED OF A DOOR THAT KNOWS THIS
1462
- TARGET**, and skipping it is the whole of the owner's third error.
1463
- `probeRelatedRead` addresses `odoo-tables/<key>/rows`, whose vocabulary is the
1464
- read-through roster and nothing else. MEASURED 2026-09-06: opening **Products ordered**
1465
- asked that door for `product_data`, a compiled registry module it has never heard of, and
1466
- got `404 unknown_table` back. Its message is the honest answer to the question that door
1467
- was asked and the WRONG answer to the one the reader asked, so the tab rendered a bare
1468
- lower-case *"that database does not exist"* about a database that plainly does exist.
1469
- β›” THE ROSTER IS ALREADY THE MOUNT CONDITION (see `pinnable` above), so a target it does
1470
- not name has no pinned read to probe: there is nothing this call can learn and one wrong
1471
- sentence it can bring back. The state that is left is exactly the one `unpinnableNote`
1472
- was written for, and it says what was asked, why it cannot be answered here and what to
1473
- do instead.
1474
- ⚠ THE PROBE SURVIVES FOR THE STATE IT EXISTS FOR: a target the roster DOES name whose
1475
- edge is `served: false`. That door has a real sentence and it is still the server's. */
1476
- const refused = through.has(target) ? await probeRelatedRead(target, pin) : null;
1477
- if (!live) return;
1478
- /* ⚠ A `null` here means the pinned door answered 200 while the ROSTER said no, which is
1479
- the one state with no server sentence (see `unpinnableNote`) and therefore no code
1480
- either. `""` sends it down the plain branch, which is exactly where it belongs. */
1481
- setTabState({
1482
- status: "refused",
1483
- reason: refused?.reason ?? unpinnableNote(target),
1484
- code: refused?.code ?? "",
1485
- /* ⭐ W54-T40 β€” THE SERVER'S SUBJECT WHERE THERE IS ONE, AND THIS TAB'S TARGET WHERE THERE
1486
- IS NOT. A refusal the client authored is still ABOUT a database, and the only one it
1487
- can be about is the target of the tab that is open. See `refusalSubject`'s last
1488
- branch, which turns this into a display name or into nothing. */
1489
- table: refused?.table ?? target,
1490
- hop: refused?.hop,
1491
  });
1492
- })();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1493
  return () => {
1494
- live = false;
 
 
1495
  };
1496
- }, [activeRelated, relatedPin, projectedIds]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1497
 
1498
  /** ⭐ W54-T38 β€” the listing's refusals, one row per distinct sentence. See `groupRefusals`. */
1499
  const groupedRefusals = useMemo(() => groupRefusals(refusals), [refusals]);
@@ -2183,6 +2629,37 @@ export default function RecordDetail({
2183
  );
2184
  };
2185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2186
  // One modal surface is shared by Grid, List, Calendar, Kanban, and Map.
2187
  // Focus stays inside it, then returns to the exact opener on close.
2188
  /* ⭐⭐ W53-T22 (R4) β€” **ESCAPE GOES UP ONE LEVEL** while a frame is on screen, and closes the
@@ -2226,7 +2703,7 @@ export default function RecordDetail({
2226
  <RecordRail tabs={tabs} activeTab={activeTab} onSelect={setTab} />
2227
  <div className="cg-record-shell">
2228
  <div className="cg-detail-header">
2229
- <div className="cg-detail-nav">
2230
  {/* ⭐⭐ W53-T22 (OWNER RULING R4) β€” TWO CHEVRONS, ALWAYS, AND THEY ALWAYS PAGE
2231
  SIBLINGS OF WHAT IS ON SCREEN.
2232
  β›” WHAT WAS HERE AND WHY IT WENT. W51-T06 replaced this pair with a single
@@ -2242,7 +2719,7 @@ export default function RecordDetail({
2242
  <button
2243
  type="button"
2244
  className="cg-detail-navbtn"
2245
- onClick={frame ? () => stepFrame(-1) : onPrev}
2246
  disabled={frame ? !frameCanPrev : !canPrev}
2247
  aria-label="Previous record"
2248
  title="Previous record"
@@ -2252,7 +2729,7 @@ export default function RecordDetail({
2252
  <button
2253
  type="button"
2254
  className="cg-detail-navbtn"
2255
- onClick={frame ? () => stepFrame(1) : onNext}
2256
  disabled={frame ? !frameCanNext : !canNext}
2257
  aria-label="Next record"
2258
  title="Next record"
@@ -2295,7 +2772,15 @@ export default function RecordDetail({
2295
  reads one: `Orders 3 of 12`, the host's own shape with the database's name where
2296
  the host says "Record". It falls back to silence, not to a guess, whenever the
2297
  sibling set could not be read (see `framePositionLabel`). */}
2298
- <span className="cg-detail-pos">{frame ? framePositionLabel : positionLabel}</span>
 
 
 
 
 
 
 
 
2299
  </div>
2300
  <button
2301
  type="button"
@@ -2413,9 +2898,25 @@ export default function RecordDetail({
2413
  state (`tab`/`activeTab`/`setTab`) and clause 1 + clause 2's edge list (`tabs`)
2414
  are UNCHANGED; only the strip is gone, replaced by `RecordRail` on the left of
2415
  the modal (see the render tree below `.cg-record-modal`). */}
2416
- <div className="cg-detail-body" id={`${tabsId}-panel`}>
2417
- {activeRelated && relatedPin && scope ? (
 
 
 
 
 
 
2418
  <div className="cg-record-related">
 
 
 
 
 
 
 
 
 
 
2419
  {/* ⭐⭐ CLAUSES 4 + 6 + 7 β€” THE TARGET DATABASE'S OWN GRID, over rows the SERVER
2420
  narrowed to this record.
2421
  β›” NO `embedded` AND NO `embeddedRecordIds` **ON THIS MOUNT**. That pair is the
@@ -2461,12 +2962,7 @@ export default function RecordDetail({
2461
  details={EMPTY_DIAGNOSES}
2462
  />
2463
  ) : tabState.status === "probing" ? (
2464
- /* Owner R6 β€” one small bare rotating mark, NO WORDS on screen. The `aria-label`
2465
- is not a word on screen and stays, or the wait is announced as nothing at all
2466
- (C-SPIN). */
2467
- <p className="cg-record-related-note">
2468
- <span className="lp-spin" role="status" aria-label="Loading" />
2469
- </p>
2470
  ) : tabState.status === "projected" ? (
2471
  /* ⭐⭐ W53-T25 Β· D-657 β€” **THE ROWS AGAIN**, on a related tab whose target is an
2472
  ordinary user table. This is wave 27's `LinkedGrid` mount, which W51-T06
@@ -2485,23 +2981,27 @@ export default function RecordDetail({
2485
  that carries every other "why is this number what it is" sentence. A second
2486
  cap sentence written here would be this file inventing a limit the wire did
2487
  not declare, which is the opposite of standing rule 1's second sentence. */
2488
- projectedIds && projectedIds.length > 0 ? (
2489
- <Suspense
2490
- fallback={
2491
- <p className="cg-record-related-note">
2492
- <span className="lp-spin" role="status" aria-label="Loading" />
2493
- </p>
2494
- }
2495
- >
2496
- <RelatedGrid
2497
- scope={relatedScope(activeRelated.entry.target)}
2498
- embedded
2499
- embeddedRecordIds={projectedIds}
2500
- /* ⭐ CLAUSE 9 β€” a row click NAVIGATES THIS PANEL rather than stacking a
2501
- second drawer on top of the one it is already inside. */
2502
- onOpenRecord={pushFrame}
2503
- />
2504
- </Suspense>
 
 
 
 
2505
  ) : (
2506
  /* An empty link cell is an ANSWER. See `emptyLinkNote`. `role="status"` for
2507
  the same reason the refusal above uses it: a reported state, not a failure.
@@ -2518,24 +3018,28 @@ export default function RecordDetail({
2518
  </p>
2519
  )
2520
  ) : (
2521
- <Suspense
2522
- fallback={
2523
- <p className="cg-record-related-note">
2524
- <span className="lp-spin" role="status" aria-label="Loading" />
2525
- </p>
2526
- }
2527
- >
2528
- <RelatedGrid
2529
- scope={relatedScope(activeRelated.entry.target)}
2530
- related={relatedPin}
2531
- /* ⭐ CLAUSE 9 β€” a row click NAVIGATES THIS PANEL rather than stacking a
2532
- second drawer on top of the one it is already inside. */
2533
- onOpenRecord={pushFrame}
2534
- /* ⭐ CLAUSE 10 β€” the view THIS TAB was last left on, and the way back. */
2535
- relatedViewId={tabViews[tabViewKey]}
2536
- onRelatedViewChange={rememberTabView}
2537
- />
2538
- </Suspense>
 
 
 
 
2539
  )}
2540
 
2541
  {/* ⭐⭐ W53-T24 Β· R13 β€” **WHAT THE LISTING WOULD NOT SHOW YOU**, said out loud. A
 
49
  [[two-lanes-one-contract-dead-feature]]. */
50
  import { CUSTOMER_TOPIC, PRODUCT_TOPIC, RELATED_REFUSAL, relatedTabs, skeletonTabs,
51
  topicForScope } from "./types";
52
+ import type { CustomerDoc, DisplayMode, Field, RelatedEntry, RelatedPin, RelatedRefusal,
53
+ RelatedVia, Row, Viewer } from "./types";
54
+ /* ⭐ THE THREE GENERAL GRID DOORS THIS PANEL ASKS ARE OWNED BY `apiBridge`: what is related to
55
+ this table, what the databases are called, and whether an edge's pinned read can be served.
56
+ The narrow cache-target resolver below is local because its endpoint belongs only to this
57
+ drawer; it still imports the shared credential, tenant and session signals from `apiContract`,
58
+ so it cannot drift on the boundaries that matter. */
59
  /* ⭐ W53-T22 adds a FOURTH and a FIFTH, and for the same reason: `fetchTableWindow` +
60
  `WINDOW_ROWS` are the one windowed read this product owns, and the sibling set a pushed
61
  frame's chevrons page is that read with the frame's own pin on it. */
62
+ import { fetchLinkTargets, fetchRelated, fetchTableWindow, fetchTopicRows, probeRelatedRead,
63
+ readThroughTables, WINDOW_ROWS } from "./apiBridge";
64
+ import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../apiContract";
65
 
66
  /**
67
  * ⭐⭐ WAVE-34 (owner ruling R13) β€” whose value sits in this enrichment cell, in words.
 
131
  // (`tab`/`activeTab`/`setTab`, unchanged below), a different DOM shape: a `cg-views` nav down the
132
  // side instead of a tablist strip under the title. See RecordRail.tsx's own header for why.
133
  import RecordRail from "./RecordRail";
134
+ import { ModeSwitch, RECORD_DETAIL_MODES, RecordRelatedModeView } from "./viewModes";
135
  import { isStreamlitComponent } from "./hostBridge";
136
  // ⚠ ALIASED for the same reason `CustomerGrid` aliases it: `./Stars`'s `StarIcon` is the RATING
137
  // atom and this one is the record MARK. Two meanings, one noun, both reachable in this tree.
 
468
  type RelatedTabState =
469
  | { status: "probing" }
470
  | { status: "ready" }
471
+ | { status: "projected"; ids: number[] }
472
  | { status: "refused"; reason: string; code: string; table?: string; hop?: string };
473
 
474
+ const PROBING_TAB_STATE: RelatedTabState = { status: "probing" };
475
+
476
+ interface RelatedTabRequest {
477
+ key: string;
478
+ sequence: number;
479
+ entry: RelatedEntry;
480
+ pin: RelatedPin;
481
+ projectedIds: number[] | null;
482
+ }
483
+
484
+ type RecordModeProjection =
485
+ | { key: string; status: "idle" | "loading" }
486
+ | { key: string; status: "error"; message: string }
487
+ | { key: string; status: "ready"; rows: Row[]; fields: Field[]; today?: string;
488
+ notice?: string };
489
+
490
+ interface RecordModeRequest {
491
+ key: string;
492
+ sequence: number;
493
+ target: string;
494
+ source: "pinned" | "projected";
495
+ pin?: RelatedPin;
496
+ ids?: number[];
497
+ }
498
+
499
+ /** The latest Previous/Next target whose record-owned reads still have to settle. */
500
+ interface RecordNavigationIntent {
501
+ sequence: number;
502
+ fromPid: number;
503
+ targetPid?: number;
504
+ }
505
+
506
+ const RECORD_MODE_WINDOW = 5000;
507
+
508
+ /** A fixed-height stand-in for every related projection, so a new intent never paints old rows. */
509
+ function RecordModeSkeleton({
510
+ mode,
511
+ label = "Loading related records",
512
+ }: {
513
+ mode: DisplayMode;
514
+ label?: string;
515
+ }) {
516
+ return (
517
+ <div
518
+ className="cg-record-mode-skeleton"
519
+ role="status"
520
+ aria-label={label}
521
+ aria-busy="true"
522
+ data-mode={mode}
523
+ >
524
+ <span className="cg-record-mode-skeleton-head" aria-hidden="true" />
525
+ <span className="cg-record-mode-skeleton-row" aria-hidden="true" />
526
+ <span className="cg-record-mode-skeleton-row is-short" aria-hidden="true" />
527
+ <span className="cg-record-mode-skeleton-row" aria-hidden="true" />
528
+ <span className="cg-record-mode-skeleton-row is-short" aria-hidden="true" />
529
+ <span className="cg-record-mode-skeleton-row" aria-hidden="true" />
530
+ </div>
531
+ );
532
+ }
533
+
534
  /**
535
  * ⭐⭐ W53-T24 Β· R13 β€” **WHO THE REFUSAL IS ABOUT**, and it is the SERVER'S OWN DATUM every time.
536
  *
 
841
  return [...seen];
842
  }
843
 
844
+ interface RelationTargetAnswer {
845
+ ok: boolean;
846
+ ids: number[];
847
+ code: string;
848
+ reason: string;
849
+ }
850
+
851
+ /** Resolve a declared bridge onto a registry-module pool without pretending the pool is a mirror. */
852
+ async function fetchModuleRelationTargets(
853
+ source: string,
854
+ record: number,
855
+ entry: RelatedEntry,
856
+ ): Promise<RelationTargetAnswer> {
857
+ const query = new URLSearchParams({
858
+ source,
859
+ record: String(record),
860
+ via: entry.key,
861
+ target: entry.target,
862
+ });
863
+ try {
864
+ const res = await fetch(`${API_V1}/odoo-tables/relation-targets?${query.toString()}`, {
865
+ credentials: CREDENTIALS,
866
+ });
867
+ if (checkTenant(res)) return { ok: false, ids: [], code: "", reason: "" };
868
+ if (res.status === 401) {
869
+ signal(UNAUTHORIZED_EVENT);
870
+ return { ok: false, ids: [], code: "", reason: "Your session ended. Sign in again." };
871
+ }
872
+ let body: unknown = null;
873
+ try { body = await res.json(); } catch { body = null; }
874
+ if (res.ok) {
875
+ const ids = (body as { ids?: unknown } | null)?.ids;
876
+ return Array.isArray(ids)
877
+ ? { ok: true, ids: linkedPids(ids.join(",")), code: "", reason: "" }
878
+ : { ok: false, ids: [], code: "relation_target_unavailable",
879
+ reason: "The related database returned an unreadable answer. Try again." };
880
+ }
881
+ const envelope = body as {
882
+ error?: { code?: unknown; message?: unknown };
883
+ detail?: { error?: { code?: unknown; message?: unknown } };
884
+ } | null;
885
+ const refusal = envelope?.error ?? envelope?.detail?.error;
886
+ return {
887
+ ok: false,
888
+ ids: [],
889
+ code: String(refusal?.code ?? "relation_target_unavailable"),
890
+ reason: String(refusal?.message ?? "This relation could not be read right now. Try again."),
891
+ };
892
+ } catch {
893
+ return { ok: false, ids: [], code: "relation_target_unavailable",
894
+ reason: "This relation could not be reached right now. Try again." };
895
+ }
896
+ }
897
+
898
+ interface NormalizedRelationRoutes {
899
+ entries: RelatedEntry[];
900
+ aliases: Map<string, string>;
901
+ values: Map<string, string>;
902
+ byValue: Map<string, string>;
903
+ }
904
+
905
+ /** A route's user-visible meaning, independent of an incidental intermediate jump. */
906
+ function relationSemanticValue(entry: RelatedEntry): string {
907
+ const label = String(entry.label || entry.target)
908
+ .replace(/\s+via\s+.+$/i, "")
909
+ .trim()
910
+ .toLowerCase();
911
+ return `${entry.target}\u001f${label}`;
912
+ }
913
+
914
+ /** Keep one closest route per meaning and retain aliases for a selection made before refresh. */
915
+ function normalizeRelationRoutes(entries: RelatedEntry[]): NormalizedRelationRoutes {
916
+ const best = new Map<string, RelatedEntry>();
917
+ for (const candidate of entries) {
918
+ const value = relationSemanticValue(candidate);
919
+ const current = best.get(value);
920
+ if (!current || candidate.hops < current.hops) best.set(value, candidate);
921
+ }
922
+ const aliases = new Map<string, string>();
923
+ const values = new Map<string, string>();
924
+ const byValue = new Map<string, string>();
925
+ for (const candidate of entries) {
926
+ const value = relationSemanticValue(candidate);
927
+ const canonical = best.get(value) as RelatedEntry;
928
+ aliases.set(candidate.key, canonical.key);
929
+ values.set(canonical.key, value);
930
+ byValue.set(value, canonical.key);
931
+ }
932
+ return {
933
+ entries: entries.filter((candidate) => best.get(relationSemanticValue(candidate)) === candidate),
934
+ aliases,
935
+ values,
936
+ byValue,
937
+ };
938
+ }
939
+
940
  function relatedScope(target: string): SurfaceScope {
941
  if (target === CUSTOMER_TOPIC.key) return CUSTOMER_TOPIC.scope as SurfaceScope;
942
  if (target === PRODUCT_TOPIC.key) return PRODUCT_TOPIC.scope as SurfaceScope;
 
989
  */
990
  const [stack, setStack] = useState<RecordFrame[]>([]);
991
  const frame = stack.length > 0 ? stack[stack.length - 1] : null;
992
+ const navigationSequence = useRef(0);
993
+ const [recordNavigation, setRecordNavigation] = useState<RecordNavigationIntent | null>(null);
994
+ const beginRecordNavigation = useCallback((fromPid: number, targetPid?: number) => {
995
+ const sequence = navigationSequence.current + 1;
996
+ navigationSequence.current = sequence;
997
+ setRecordNavigation({ sequence, fromPid, targetPid });
998
+ }, []);
999
  /**
1000
  * β›”β›” THE SHADOW IS THE WHOLE MECHANISM, AND IT IS DELIBERATE RATHER THAN CLEVER. Every one of
1001
  * the ~40 references below (`renderRow`, the ordering, the editors, the viewers) reads `fields`
 
1296
  * β›” AND AN EMPTY ANSWER IS NOT A LOADING ONE. A database with no relations settles to zero
1297
  * tabs and the placeholders go, because `relatedPending` is false the moment the stamp matches.
1298
  */
1299
+ const relationRoutes = useMemo(() => normalizeRelationRoutes(entries), [entries]);
1300
  const tabs = useMemo(
1301
  () => (relatedPending && !entries.length
1302
  ? skeletonTabs()
1303
+ : relatedTabs(relationRoutes.entries, (target) => tableLabels[target] ?? "")),
1304
+ [entries.length, relationRoutes.entries, tableLabels, relatedPending]
1305
  );
1306
 
1307
  /**
1308
+ * Which tab is open, by EDGE KEY plus its semantic value. `"fields"` is the default and the
1309
+ * fallback: a route key may be replaced while the drawer is open and then follows the same
1310
+ * value, while a meaning that genuinely disappeared drops back to Fields.
1311
  */
1312
  /* ⭐⭐ W53-T22 β€” STAMPED WITH ITS TABLE, THE SAME WAY `related` IS, AND FOR THE SAME RENDER.
1313
  An edge key belongs to ONE database's relation list; carried across a hop it names an edge
 
1316
  parent's selection at all.
1317
  ⚠ `setTab` STAYS A `(tab: string) => void`, so `RecordRail`'s props do not change and the
1318
  mount below stays byte-identical to what `verify_wiring.py` asserts. */
1319
+ const [tabSel, setTabSel] = useState<{ table: string; key: string; value: string }>(
1320
+ { table: "", key: "fields", value: "" }
1321
  );
1322
+ const tab = tabSel.table === recordTable
1323
+ ? (relationRoutes.aliases.get(tabSel.key)
1324
+ ?? relationRoutes.byValue.get(tabSel.value)
1325
+ ?? tabSel.key)
1326
+ : "fields";
1327
  const setTab = useCallback(
1328
+ (next: string) => setTabSel({
1329
+ table: recordTable,
1330
+ key: next,
1331
+ value: relationRoutes.values.get(next) ?? "",
1332
+ }),
1333
+ [recordTable, relationRoutes.values]
1334
  );
1335
  const activeTab = tabs.some((entry) => entry.entry.key === tab) ? tab : "fields";
1336
  const activeRelated = tabs.find((entry) => entry.entry.key === activeTab) ?? null;
 
1338
  /**
1339
  * ⭐⭐ CLAUSE 10 β€” THE LAST-OPENED VIEW **PER TAB**, PER PERSON, IN `localStorage`.
1340
  *
1341
+ * β›” PER SEMANTIC TAB, NOT PER DATABASE. R2 gives two genuinely different links between the
1342
+ * same pair two tabs, so a memory keyed by target alone still merges too much. An incidental
1343
+ * intermediate route is different: when it collapses onto a closer path, the meaning remains
1344
+ * the same and its remembered view must follow it. The key therefore carries this table plus
1345
+ * the normalized target-and-label value, never an unstable route key.
1346
  * ⚠ `writeTabViews` runs inside the updater rather than beside it, so the write and the
1347
  * decision that there IS something to write are one expression. Under StrictMode the updater
1348
  * is invoked twice in development, which writes the same value twice; the write is idempotent
1349
  * and that is cheaper than a second effect whose only job is to mirror this state.
1350
  */
1351
  const [tabViews, setTabViews] = useState<Record<string, string>>(readTabViews);
1352
+ /* Keep the pre-normalization edge key as a read fallback. Wave 55 made route selection
1353
+ semantic so a shorter equivalent path can replace a longer one without losing the open tab,
1354
+ but existing browsers may still hold the earlier edge-keyed preference. */
1355
+ const legacyTabViewKey = activeRelated
1356
+ ? `${recordTable}:${activeRelated.entry.key}`
1357
+ : "";
1358
+ const tabViewKey = activeRelated
1359
+ ? `${recordTable}:${relationSemanticValue(activeRelated.entry)}`
1360
+ : "";
1361
+ const [recordModes, setRecordModes] = useState<Record<string, DisplayMode>>({});
1362
+ const relatedMode = tabViewKey ? recordModes[tabViewKey] ?? "grid" : "grid";
1363
+ const chooseRecordMode = useCallback((next: DisplayMode) => {
1364
+ if (!tabViewKey || !RECORD_DETAIL_MODES.includes(next)) return;
1365
+ setRecordModes((prev) => (prev[tabViewKey] === next
1366
+ ? prev
1367
+ : { ...prev, [tabViewKey]: next }));
1368
+ }, [tabViewKey]);
1369
+ const [recordModeFields, setRecordModeFields] = useState<
1370
+ Record<string, { dateField?: string; stackField?: string }>
1371
+ >({});
1372
+ const chooseRecordModeField = useCallback(
1373
+ (kind: "dateField" | "stackField", key: string) => {
1374
+ if (!tabViewKey) return;
1375
+ setRecordModeFields((prev) => ({
1376
+ ...prev,
1377
+ [tabViewKey]: { ...prev[tabViewKey], [kind]: key },
1378
+ }));
1379
+ },
1380
+ [tabViewKey]
1381
+ );
1382
  const rememberTabView = useCallback(
1383
  (viewId: string) => {
1384
  if (!tabViewKey) return;
 
1522
  const [siblings, setSiblings] = useState<{ key: string; rows: Row[]; fields: Field[] }>(
1523
  { key: "", rows: EMPTY_ROWS, fields: EMPTY_FIELDS }
1524
  );
1525
+ /* W55-T16 / R12: clicks use the last requested sibling index, not the last PAINTED one. React
1526
+ may batch several pointer events before `frame` changes; anchoring every click to
1527
+ `siblingIndex` would turn Next, Next, Previous into one Next. The ref advances synchronously,
1528
+ while the state update below gives React only the final target to paint. */
1529
+ const frameIntent = useRef<{ key: string; index: number; pid: number } | null>(null);
1530
  useEffect(() => {
1531
  if (!framePinKey) return;
1532
  const asked = JSON.parse(framePinKey) as { table: string; pin: RelatedPin };
 
1551
  const siblingIndex = frame
1552
  ? siblingRows.findIndex((row) => Number(row.pid) === frame.pid)
1553
  : -1;
1554
+ const pendingFrame = frameIntent.current;
1555
+ const queuedFrameIndex = pendingFrame?.key === framePinKey
1556
+ && Number(siblingRows[pendingFrame.index]?.pid) === pendingFrame.pid
1557
+ ? pendingFrame.index
1558
+ : siblingIndex;
1559
+ const frameCanPrev = queuedFrameIndex > 0;
1560
+ const frameCanNext = queuedFrameIndex >= 0 && queuedFrameIndex < siblingRows.length - 1;
1561
  /**
1562
  * One step along the frame's own row set. It REPLACES the top frame rather than pushing one,
1563
  * so paging orders inside a customer leaves the breadcrumb reading `Customer / Order` at the
 
1568
  const stepFrame = useCallback(
1569
  (delta: number) => {
1570
  if (!frame || siblingIndex < 0) return;
1571
+ const pending = frameIntent.current;
1572
+ const queued = pending?.key === framePinKey
1573
+ && Number(siblingRows[pending.index]?.pid) === pending.pid
1574
+ ? pending.index
1575
+ : siblingIndex;
1576
+ const nextIndex = Math.max(0, Math.min(siblingRows.length - 1, queued + delta));
1577
+ const next = siblingRows[nextIndex];
1578
  if (!next) return;
1579
  const first = siblings.fields[0];
1580
  const named = first ? String(next[first.key] ?? "") : "";
1581
  const pid = Number(next.pid);
1582
+ const currentPid = queued === pending?.index && pending?.key === framePinKey
1583
+ ? pending.pid
1584
+ : Number(frame.pid);
1585
+ if (!Number.isFinite(pid) || pid === currentPid) return;
1586
+ frameIntent.current = { key: framePinKey, index: nextIndex, pid };
1587
+ beginRecordNavigation(currentPid, pid);
1588
  setStack((prev) => (prev.length === 0 ? prev : [...prev.slice(0, -1), {
1589
  table: frame.table,
1590
  pid,
 
1594
  pin: frame.pin,
1595
  }]));
1596
  },
1597
+ [beginRecordNavigation, frame, framePinKey, siblingIndex, siblingRows, siblings.fields]
1598
+ );
1599
+ const stepBase = useCallback(
1600
+ (delta: -1 | 1) => {
1601
+ beginRecordNavigation(Number(baseRecord.pid));
1602
+ if (delta < 0) onPrev();
1603
+ else onNext();
1604
+ },
1605
+ [baseRecord.pid, beginRecordNavigation, onNext, onPrev]
1606
  );
1607
  /**
1608
  * The frame's own caption, in the host's shape (`Record 3 of 3,673`) with the DATABASE's name
 
1661
  * fetch the server's sentence for the state, and `unpinnableNote` covers the one state that
1662
  * has no server sentence (the roster says no while the door answers 200).
1663
  */
1664
+ const [tabStateResult, setTabState] = useState<RelatedTabState>(PROBING_TAB_STATE);
1665
+ const [tabStateStamp, setTabStateStamp] = useState("");
1666
+ const tabState = tabStateStamp === relatedPinKey ? tabStateResult : PROBING_TAB_STATE;
1667
+ const tabRequest = useRef<{
1668
+ mounted: boolean;
1669
+ running: boolean;
1670
+ sequence: number;
1671
+ wanted: RelatedTabRequest | null;
1672
+ }>({ mounted: true, running: false, sequence: 0, wanted: null });
1673
  useEffect(() => {
1674
+ tabRequest.current.mounted = true;
1675
+ return () => {
1676
+ tabRequest.current.mounted = false;
1677
+ tabRequest.current.wanted = null;
1678
+ tabRequest.current.sequence += 1;
1679
+ };
1680
+ }, []);
1681
+ useEffect(() => {
1682
+ const coordinator = tabRequest.current;
1683
+ const sequence = coordinator.sequence + 1;
1684
+ coordinator.sequence = sequence;
1685
  if (!activeRelated || !relatedPin) {
1686
+ coordinator.wanted = null;
1687
+ setTabStateStamp("");
1688
+ setTabState(PROBING_TAB_STATE);
1689
  return;
1690
  }
1691
+ setTabStateStamp(relatedPinKey);
1692
+ setTabState(PROBING_TAB_STATE);
1693
+ const request: RelatedTabRequest = {
1694
+ key: relatedPinKey,
1695
+ sequence,
1696
+ entry: activeRelated.entry,
1697
+ pin: { table: relatedPin.table, record: relatedPin.record, via: relatedPin.via },
1698
+ projectedIds,
1699
+ };
1700
+ /* W55-T16 / R12: one slot, replaced rather than appended. If a bridge query is already in
1701
+ flight it may finish, but every intermediate record disappears from this slot before the
1702
+ next compiled query is chosen. */
1703
+ coordinator.wanted = { ...request };
1704
+
1705
+ const current = (asked: RelatedTabRequest) => coordinator.mounted
1706
+ && coordinator.sequence === asked.sequence;
1707
+ const commit = (asked: RelatedTabRequest, answer: RelatedTabState) => {
1708
+ if (!current(asked)) return;
1709
+ setTabStateStamp(asked.key);
1710
+ setTabState(answer);
1711
+ };
1712
+ const drain = async () => {
1713
+ if (coordinator.running === true) return;
1714
+ coordinator.running = true;
1715
+ try {
1716
+ while (coordinator.mounted && coordinator.wanted) {
1717
+ const asked = coordinator.wanted;
1718
+ coordinator.wanted = null;
1719
+ /* Freeze the active relation to this queued request. Reading the render's current
1720
+ `activeRelated` here would let a later click rewrite an earlier in-flight request. */
1721
+ const activeRelated = asked;
1722
+ const target = activeRelated.entry.target;
1723
+ const through = await readThroughTables();
1724
+ /* The roster read is cheap and shared. This check is deliberately BEFORE either route
1725
+ that can compile a relation query, so a burst pays for the running intent and the
1726
+ final intent, never for the records superseded between them. */
1727
+ if (!current(asked)) continue;
1728
+ const pinnable = activeRelated.entry.served && through.has(target);
1729
+ if (pinnable) {
1730
+ commit(asked, { status: "ready" });
1731
+ continue;
1732
+ }
1733
+ if (!through.has(target) && asked.projectedIds) {
1734
+ commit(asked, { status: "projected", ids: asked.projectedIds });
1735
+ continue;
1736
+ }
1737
+ const isModuleCache = target === CUSTOMER_TOPIC.key || target === PRODUCT_TOPIC.key;
1738
+ if (!through.has(target) && isModuleCache
1739
+ && asked.entry.via.direction === "forward") {
1740
+ const answer = await fetchModuleRelationTargets(
1741
+ asked.pin.table, asked.pin.record, asked.entry);
1742
+ if (!current(asked)) continue;
1743
+ if (answer.ok) {
1744
+ setTabStateStamp(asked.key);
1745
+ setTabState({ status: "projected", ids: answer.ids });
1746
+ } else {
1747
+ commit(asked, {
1748
+ status: "refused",
1749
+ reason: answer.reason,
1750
+ code: answer.code,
1751
+ table: target,
1752
+ });
1753
+ }
1754
+ continue;
1755
+ }
1756
+ const refused = through.has(target) ? await probeRelatedRead(target, asked.pin) : null;
1757
+ if (!current(asked)) continue;
1758
+ commit(asked, {
1759
+ status: "refused",
1760
+ reason: refused?.reason ?? unpinnableNote(target),
1761
+ code: refused?.code ?? "",
1762
+ table: refused?.table ?? target,
1763
+ hop: refused?.hop,
1764
+ });
1765
+ }
1766
+ } finally {
1767
+ coordinator.running = false;
1768
  }
1769
+ };
1770
+ void drain();
1771
+ }, [activeRelated, relatedPin, projectedIds]);
1772
+
1773
+ /* W55-T15 / C8: non-Grid projections use a stamped, single-flight reader. A new tab or mode
1774
+ replaces `wanted` immediately; the running request is allowed to finish but cannot paint,
1775
+ then only the final queued intent is read. This keeps one request in flight without showing
1776
+ the prior relation as the newly requested one. */
1777
+ const recordProjectionKey = useMemo(() => {
1778
+ if (!activeRelated || !relatedPin) return "";
1779
+ if (tabState.status === "ready") {
1780
+ return JSON.stringify({
1781
+ tab: tabViewKey,
1782
+ target: activeRelated.entry.target,
1783
+ source: "pinned",
1784
+ pin: relatedPin,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1785
  });
1786
+ }
1787
+ if (tabState.status === "projected" && tabState.ids.length > 0) {
1788
+ return JSON.stringify({
1789
+ tab: tabViewKey,
1790
+ target: activeRelated.entry.target,
1791
+ source: "projected",
1792
+ ids: tabState.ids,
1793
+ });
1794
+ }
1795
+ return "";
1796
+ }, [activeRelated, relatedPin, tabState, tabViewKey]);
1797
+ const [recordProjection, setRecordProjection] = useState<RecordModeProjection>(
1798
+ { key: "", status: "idle" }
1799
+ );
1800
+ const recordProjectionCache = useRef(new Map<string, Extract<
1801
+ RecordModeProjection, { status: "ready" }
1802
+ >>());
1803
+ const recordRequest = useRef<{
1804
+ mounted: boolean;
1805
+ running: boolean;
1806
+ sequence: number;
1807
+ wanted: RecordModeRequest | null;
1808
+ }>({ mounted: true, running: false, sequence: 0, wanted: null });
1809
+ useEffect(() => {
1810
+ recordRequest.current.mounted = true;
1811
  return () => {
1812
+ recordRequest.current.mounted = false;
1813
+ recordRequest.current.wanted = null;
1814
+ recordRequest.current.sequence += 1;
1815
  };
1816
+ }, []);
1817
+ useEffect(() => {
1818
+ const coordinator = recordRequest.current;
1819
+ const sequence = coordinator.sequence + 1;
1820
+ coordinator.sequence = sequence;
1821
+ if (relatedMode === "grid" || !recordProjectionKey || !activeRelated || !relatedPin) {
1822
+ coordinator.wanted = null;
1823
+ setRecordProjection({ key: "", status: "idle" });
1824
+ return;
1825
+ }
1826
+
1827
+ const cached = recordProjectionCache.current.get(recordProjectionKey);
1828
+ if (cached) {
1829
+ coordinator.wanted = null;
1830
+ setRecordProjection(cached);
1831
+ return;
1832
+ }
1833
+ const request: RecordModeRequest = {
1834
+ key: recordProjectionKey,
1835
+ sequence,
1836
+ target: activeRelated.entry.target,
1837
+ source: tabState.status === "ready" ? "pinned" : "projected",
1838
+ pin: tabState.status === "ready" ? relatedPin : undefined,
1839
+ ids: tabState.status === "projected" ? tabState.ids : undefined,
1840
+ };
1841
+ coordinator.wanted = request;
1842
+ setRecordProjection({ key: recordProjectionKey, status: "loading" });
1843
+
1844
+ const drain = async () => {
1845
+ if (coordinator.running) return;
1846
+ coordinator.running = true;
1847
+ try {
1848
+ while (coordinator.mounted && coordinator.wanted) {
1849
+ const asked = coordinator.wanted;
1850
+ coordinator.wanted = null;
1851
+ const payload = asked.source === "pinned" && asked.pin
1852
+ ? await fetchTableWindow(asked.target, {
1853
+ offset: 0,
1854
+ limit: RECORD_MODE_WINDOW,
1855
+ related: asked.pin,
1856
+ })
1857
+ : await fetchTopicRows(topicForScope(relatedScope(asked.target)));
1858
+ if (!coordinator.mounted || coordinator.sequence !== asked.sequence) continue;
1859
+ if (!payload) {
1860
+ setRecordProjection({
1861
+ key: asked.key,
1862
+ status: "error",
1863
+ message: "This view could not load. Return to Grid or try again.",
1864
+ });
1865
+ continue;
1866
+ }
1867
+
1868
+ let rows = payload.rows;
1869
+ let notice: string | undefined;
1870
+ if (asked.source === "pinned") {
1871
+ if ((payload.counts?.matched ?? rows.length) > rows.length) {
1872
+ setRecordProjection({
1873
+ key: asked.key,
1874
+ status: "error",
1875
+ message: "This related set is too large for this view. Use Grid to reach every record.",
1876
+ });
1877
+ continue;
1878
+ }
1879
+ } else {
1880
+ const ids = new Set<number>(asked.ids ?? []);
1881
+ rows = payload.rows.filter((row) => ids.has(Number(row.pid)));
1882
+ const found = new Set(rows.map((row) => Number(row.pid)));
1883
+ const missing = [...ids].filter((pid) => !found.has(pid)).length;
1884
+ const wholeSource = !payload.counts
1885
+ || (payload.counts.shown ?? payload.rows.length) >= payload.counts.matched;
1886
+ if (missing > 0 && !wholeSource) {
1887
+ setRecordProjection({
1888
+ key: asked.key,
1889
+ status: "error",
1890
+ message: "This linked set is outside the loaded window. Use Grid to reach every record.",
1891
+ });
1892
+ continue;
1893
+ }
1894
+ if (missing > 0) notice = "Some linked records are no longer available.";
1895
+ }
1896
+ const ready: Extract<RecordModeProjection, { status: "ready" }> = {
1897
+ key: asked.key,
1898
+ status: "ready",
1899
+ rows,
1900
+ fields: payload.fields,
1901
+ today: payload.today,
1902
+ notice,
1903
+ };
1904
+ recordProjectionCache.current.set(asked.key, ready);
1905
+ setRecordProjection(ready);
1906
+ }
1907
+ } finally {
1908
+ coordinator.running = false;
1909
+ }
1910
+ };
1911
+ void drain();
1912
+ }, [activeRelated, recordProjectionKey, relatedMode, relatedPin, tabState]);
1913
+
1914
+ const visibleRecordProjection = recordProjection.key === recordProjectionKey
1915
+ && recordProjection.status === "ready" ? recordProjection : null;
1916
+ const navigationRecordArrived = !recordNavigation
1917
+ || (recordNavigation.targetPid == null
1918
+ ? Number(baseRecord.pid) !== recordNavigation.fromPid
1919
+ : Number(record.pid) === recordNavigation.targetPid);
1920
+ const navigationReadSettled = !activeRelated
1921
+ || tabState.status === "refused"
1922
+ || (tabState.status === "projected" && tabState.ids.length === 0)
1923
+ || (tabState.status !== "probing" && relatedMode === "grid")
1924
+ || (Object.is(recordProjection.key, recordProjectionKey)
1925
+ && (recordProjection.status === "ready" || recordProjection.status === "error"));
1926
+ const recordNavigationBusy = Boolean(
1927
+ recordNavigation && (!navigationRecordArrived || !navigationReadSettled)
1928
+ );
1929
+ useEffect(() => {
1930
+ if (!recordNavigation || recordNavigationBusy) return;
1931
+ const settledSequence = recordNavigation.sequence;
1932
+ setRecordNavigation((current) => current?.sequence === settledSequence ? null : current);
1933
+ }, [recordNavigation, recordNavigationBusy]);
1934
+ const recordModeChoices = visibleRecordProjection?.fields ?? EMPTY_FIELDS;
1935
+ const recordModePrefs = recordModeFields[tabViewKey] ?? {};
1936
+ const recordStackChoices = useMemo(
1937
+ () => recordModeChoices.filter((field) => field.type === "select" || field.type === "status"),
1938
+ [recordModeChoices]
1939
+ );
1940
+ const recordStackField = recordStackChoices.find(
1941
+ (field) => field.key === recordModePrefs.stackField
1942
+ ) ?? recordStackChoices[0];
1943
 
1944
  /** ⭐ W54-T38 β€” the listing's refusals, one row per distinct sentence. See `groupRefusals`. */
1945
  const groupedRefusals = useMemo(() => groupRefusals(refusals), [refusals]);
 
2629
  );
2630
  };
2631
 
2632
+ const recordProjectionFailure = recordProjection.key === recordProjectionKey
2633
+ && recordProjection.status === "error" ? recordProjection.message : "";
2634
+ const recordProjectionPanel = activeRelated && visibleRecordProjection ? (
2635
+ <div
2636
+ className="cg-record-related-modebody"
2637
+ data-mode={relatedMode}
2638
+ aria-busy="false"
2639
+ >
2640
+ <RecordRelatedModeView
2641
+ mode={relatedMode}
2642
+ rows={visibleRecordProjection.rows}
2643
+ fields={visibleRecordProjection.fields}
2644
+ dateFieldKey={recordModePrefs.dateField}
2645
+ stackFieldKey={recordStackField?.key}
2646
+ today={visibleRecordProjection.today}
2647
+ scope={relatedScope(activeRelated.entry.target)}
2648
+ onOpen={(pid, selected, selectedFields) => pushFrame(
2649
+ pid,
2650
+ activeRelated.entry.target,
2651
+ selected,
2652
+ selectedFields
2653
+ )}
2654
+ />
2655
+ {visibleRecordProjection.notice ? (
2656
+ <p className="cg-record-related-note" role="status">
2657
+ {visibleRecordProjection.notice}
2658
+ </p>
2659
+ ) : null}
2660
+ </div>
2661
+ ) : null;
2662
+
2663
  // One modal surface is shared by Grid, List, Calendar, Kanban, and Map.
2664
  // Focus stays inside it, then returns to the exact opener on close.
2665
  /* ⭐⭐ W53-T22 (R4) β€” **ESCAPE GOES UP ONE LEVEL** while a frame is on screen, and closes the
 
2703
  <RecordRail tabs={tabs} activeTab={activeTab} onSelect={setTab} />
2704
  <div className="cg-record-shell">
2705
  <div className="cg-detail-header">
2706
+ <div className="cg-detail-nav" aria-busy={recordNavigationBusy}>
2707
  {/* ⭐⭐ W53-T22 (OWNER RULING R4) β€” TWO CHEVRONS, ALWAYS, AND THEY ALWAYS PAGE
2708
  SIBLINGS OF WHAT IS ON SCREEN.
2709
  β›” WHAT WAS HERE AND WHY IT WENT. W51-T06 replaced this pair with a single
 
2719
  <button
2720
  type="button"
2721
  className="cg-detail-navbtn"
2722
+ onClick={frame ? () => stepFrame(-1) : () => stepBase(-1)}
2723
  disabled={frame ? !frameCanPrev : !canPrev}
2724
  aria-label="Previous record"
2725
  title="Previous record"
 
2729
  <button
2730
  type="button"
2731
  className="cg-detail-navbtn"
2732
+ onClick={frame ? () => stepFrame(1) : () => stepBase(1)}
2733
  disabled={frame ? !frameCanNext : !canNext}
2734
  aria-label="Next record"
2735
  title="Next record"
 
2772
  reads one: `Orders 3 of 12`, the host's own shape with the database's name where
2773
  the host says "Record". It falls back to silence, not to a guess, whenever the
2774
  sibling set could not be read (see `framePositionLabel`). */}
2775
+ {recordNavigationBusy ? (
2776
+ <span
2777
+ className="cg-detail-pos cg-detail-pos-skeleton"
2778
+ role="status"
2779
+ aria-label="Loading record"
2780
+ />
2781
+ ) : (
2782
+ <span className="cg-detail-pos">{frame ? framePositionLabel : positionLabel}</span>
2783
+ )}
2784
  </div>
2785
  <button
2786
  type="button"
 
2898
  state (`tab`/`activeTab`/`setTab`) and clause 1 + clause 2's edge list (`tabs`)
2899
  are UNCHANGED; only the strip is gone, replaced by `RecordRail` on the left of
2900
  the modal (see the render tree below `.cg-record-modal`). */}
2901
+ <div
2902
+ className="cg-detail-body"
2903
+ id={`${tabsId}-panel`}
2904
+ aria-busy={recordNavigationBusy}
2905
+ >
2906
+ {recordNavigationBusy ? (
2907
+ <RecordModeSkeleton mode={activeRelated ? relatedMode : "grid"} label="Loading record" />
2908
+ ) : activeRelated && relatedPin && scope ? (
2909
  <div className="cg-record-related">
2910
+ <div className="cg-record-related-modebar" aria-label="Related record view">
2911
+ <ModeSwitch
2912
+ mode={relatedMode}
2913
+ onMode={chooseRecordMode}
2914
+ allowedModes={RECORD_DETAIL_MODES}
2915
+ stackField={recordStackField}
2916
+ stackChoices={recordStackChoices}
2917
+ onPickField={chooseRecordModeField}
2918
+ />
2919
+ </div>
2920
  {/* ⭐⭐ CLAUSES 4 + 6 + 7 β€” THE TARGET DATABASE'S OWN GRID, over rows the SERVER
2921
  narrowed to this record.
2922
  β›” NO `embedded` AND NO `embeddedRecordIds` **ON THIS MOUNT**. That pair is the
 
2962
  details={EMPTY_DIAGNOSES}
2963
  />
2964
  ) : tabState.status === "probing" ? (
2965
+ <RecordModeSkeleton mode={relatedMode} />
 
 
 
 
 
2966
  ) : tabState.status === "projected" ? (
2967
  /* ⭐⭐ W53-T25 Β· D-657 β€” **THE ROWS AGAIN**, on a related tab whose target is an
2968
  ordinary user table. This is wave 27's `LinkedGrid` mount, which W51-T06
 
2981
  that carries every other "why is this number what it is" sentence. A second
2982
  cap sentence written here would be this file inventing a limit the wire did
2983
  not declare, which is the opposite of standing rule 1's second sentence. */
2984
+ tabState.ids.length > 0 ? (
2985
+ relatedMode === "grid" ? (
2986
+ <Suspense fallback={<RecordModeSkeleton mode="grid" />}>
2987
+ <RelatedGrid
2988
+ scope={relatedScope(activeRelated.entry.target)}
2989
+ embedded
2990
+ embeddedRecordIds={tabState.ids}
2991
+ /* ⭐ CLAUSE 9 β€” a row click NAVIGATES THIS PANEL rather than stacking a
2992
+ second drawer on top of the one it is already inside. */
2993
+ onOpenRecord={pushFrame}
2994
+ />
2995
+ </Suspense>
2996
+ ) : recordProjectionPanel ? (
2997
+ recordProjectionPanel
2998
+ ) : recordProjectionFailure ? (
2999
+ <p className="cg-record-related-note" role="status">
3000
+ {recordProjectionFailure}
3001
+ </p>
3002
+ ) : (
3003
+ <RecordModeSkeleton mode={relatedMode} />
3004
+ )
3005
  ) : (
3006
  /* An empty link cell is an ANSWER. See `emptyLinkNote`. `role="status"` for
3007
  the same reason the refusal above uses it: a reported state, not a failure.
 
3018
  </p>
3019
  )
3020
  ) : (
3021
+ relatedMode === "grid" ? (
3022
+ <Suspense fallback={<RecordModeSkeleton mode="grid" />}>
3023
+ <RelatedGrid
3024
+ scope={relatedScope(activeRelated.entry.target)}
3025
+ related={relatedPin}
3026
+ /* ⭐ CLAUSE 9 β€” a row click NAVIGATES THIS PANEL rather than stacking a
3027
+ second drawer on top of the one it is already inside. */
3028
+ onOpenRecord={pushFrame}
3029
+ /* ⭐ CLAUSE 10 β€” the view THIS TAB was last left on, and the way back. */
3030
+ relatedViewId={tabViews[tabViewKey] ?? tabViews[legacyTabViewKey]}
3031
+ onRelatedViewChange={rememberTabView}
3032
+ />
3033
+ </Suspense>
3034
+ ) : recordProjectionPanel ? (
3035
+ recordProjectionPanel
3036
+ ) : recordProjectionFailure ? (
3037
+ <p className="cg-record-related-note" role="status">
3038
+ {recordProjectionFailure}
3039
+ </p>
3040
+ ) : (
3041
+ <RecordModeSkeleton mode={relatedMode} />
3042
+ )
3043
  )}
3044
 
3045
  {/* ⭐⭐ W53-T24 Β· R13 β€” **WHAT THE LISTING WOULD NOT SHOW YOU**, said out loud. A
web/src/customer-grid/RouteNav.tsx CHANGED
@@ -154,7 +154,8 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
154
  stopCoords = {},
155
  onFolderCreate, onFolderUpdate, onFolderDelete, onFolderReorder, onCreateStart, mapLinks, mapLinkRefusal, deliveries, onSchedule,
156
  onDeleteDelivery, assignees, routeToday, assigneeError, zones = [],
157
- roundTrip = false, onRoundTripChange, routeStartPid = null, routeEndPid = null, onRouteStartChange, onRouteEndChange, onStopAdded }: {
 
158
  routes: MapRouteDto[];
159
  folders: MapRouteFolderDto[];
160
  selectedIds: ReadonlySet<string>;
@@ -218,6 +219,8 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
218
  /** The Route the membership door answered with, so the host's read model gains the new stop
219
  * without a second fetch. Mirrors what `moveNamedRouteStop` already does on a reorder. */
220
  onStopAdded?: (route: MapRouteDto) => void;
 
 
221
  }) {
222
  /* ⭐⭐ OWNER 2026-08-31 item 3 - THE ROUTES RAIL IS THE VIEWS RAIL, NOT A COUSIN OF IT.
223
  Owner: *"I need the routes LIST navigation and the routes itself to have the exact same
@@ -1924,6 +1927,9 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
1924
  const rows = renderLevel(ROOT_LEVEL, 0);
1925
  return (
1926
  <section className="cg-w44-route-nav" aria-label="Named routes">
 
 
 
1927
  {/* Owner item 3 - the SAME create door the Views rail mounts (`.cg-create-new` /
1928
  `.cg-create-btn` are a shared contract, see `ViewSidebar.tsx`'s note on them), with the
1929
  two things a Routes rail can make behind it. */}
 
154
  stopCoords = {},
155
  onFolderCreate, onFolderUpdate, onFolderDelete, onFolderReorder, onCreateStart, mapLinks, mapLinkRefusal, deliveries, onSchedule,
156
  onDeleteDelivery, assignees, routeToday, assigneeError, zones = [],
157
+ roundTrip = false, onRoundTripChange, routeStartPid = null, routeEndPid = null, onRouteStartChange, onRouteEndChange, onStopAdded,
158
+ applicationName = "" }: {
159
  routes: MapRouteDto[];
160
  folders: MapRouteFolderDto[];
161
  selectedIds: ReadonlySet<string>;
 
219
  /** The Route the membership door answered with, so the host's read model gains the new stop
220
  * without a second fetch. Mirrors what `moveNamedRouteStop` already does on a reorder. */
221
  onStopAdded?: (route: MapRouteDto) => void;
222
+ /** Present only when this trusted route surface was launched by a saved Application. */
223
+ applicationName?: string;
224
  }) {
225
  /* ⭐⭐ OWNER 2026-08-31 item 3 - THE ROUTES RAIL IS THE VIEWS RAIL, NOT A COUSIN OF IT.
226
  Owner: *"I need the routes LIST navigation and the routes itself to have the exact same
 
1927
  const rows = renderLevel(ROOT_LEVEL, 0);
1928
  return (
1929
  <section className="cg-w44-route-nav" aria-label="Named routes">
1930
+ {applicationName ? (
1931
+ <p className="cg-app-route-context"><span>Routing app</span><strong>{applicationName}</strong></p>
1932
+ ) : null}
1933
  {/* Owner item 3 - the SAME create door the Views rail mounts (`.cg-create-new` /
1934
  `.cg-create-btn` are a shared contract, see `ViewSidebar.tsx`'s note on them), with the
1935
  two things a Routes rail can make behind it. */}
web/src/customer-grid/SwipeView.tsx CHANGED
@@ -1,586 +1,586 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / SwipeView.tsx
3
- // ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) β€” the SWIPE deck.
4
- //
5
- // One record at a time, decided left or right into two options of ONE
6
- // single-select. R2 fixes the shape and it is narrow on purpose:
7
- // Β· SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.
8
- // Β· the deck holds only the records whose bound field is EMPTY β€” a record
9
- // that already has a value has been decided, and re-asking is not triage.
10
- // Β· a swipe writes through the NORMAL cell door (`onSwipe`, which the host
11
- // maps to the same `patchAndRecord` a kanban card move uses), so undo,
12
- // echo-suppression and the permission wall all hold without being
13
- // re-implemented here.
14
- //
15
- // Honesty rules carried from the other modes:
16
- // Β· nothing is silently hidden β€” the deck states what is left, and the
17
- // empty state names the bound field rather than saying "all done".
18
- // Β· a lost binding is SHOWN, never repaired by guessing. `_clean_display`
19
- // validates that `fieldKey` names a field the table HAS and stops there;
20
- // it cannot know the field is still a select, or that the two options are
21
- // still in its vocabulary (its docstring draws that line explicitly). So
22
- // those three losses land here, and each one says what happened and
23
- // re-opens the picker β€” the `viewModes.tsx:190-194` rule, which exists
24
- // because the wave-7 trap was a picker silently falling back to its first
25
- // option.
26
- // ---------------------------------------------------------------------------
27
-
28
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
- // ⭐⭐ W41-T48 (owner instruction 22) β€” opening a record from the swipe deck folds the shell's
30
- // navigation rail exactly as a grid cell click does. Guard rationale: `MapView.tsx:2755`.
31
- import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
32
- import { choiceOptions } from "./types";
33
- import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
34
- // ⚠ `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is
35
- // loaded here) β€” the same import `RecordComments` takes for the same prop.
36
- import type { SurfaceScope } from "./apiBridge";
37
- import RecordComments from "./RecordComments";
38
- import { Documents } from "./Documents";
39
- import { formatDisplay } from "./cells";
40
- import { actionHref } from "./display";
41
- import { optionTint } from "./choiceColors";
42
- import { ModeIcon } from "./icons";
43
- // ⭐ W29-T73 β€” the line its three siblings all have, and the one this file shipped without.
44
- // `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered
45
- // unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right β€”
46
- // a partially-styled surface reads as a design choice, which is why nobody reported it and no
47
- // gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).
48
- import "./SwipeView.css";
49
-
50
- export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;
51
-
52
- /** The three ways a stored binding can rot that the host cannot see (see the header note). */
53
- type BindingFault =
54
- | { kind: "unbound" }
55
- | { kind: "field-gone"; fieldKey: string }
56
- | { kind: "not-select"; field: Field }
57
- | { kind: "option-gone"; field: Field; missing: string[] };
58
-
59
- function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map<string, Field>):
60
- { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {
61
- if (!spec) return { ok: false, fault: { kind: "unbound" } };
62
- const field = fieldByKey.get(spec.fieldKey);
63
- if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };
64
- // R2 β€” SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,
65
- // so "write this option" would mean append-or-replace, and a triage gesture that sometimes
66
- // adds and sometimes overwrites is two gestures wearing one button.
67
- if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };
68
- const options = choiceOptions(field);
69
- const has = new Set(options.map((o) => o.toLowerCase()));
70
- const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));
71
- if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };
72
- return { ok: true, field, spec };
73
- }
74
-
75
- /** The bound cell is EMPTY β€” the one predicate that decides deck membership (R2). */
76
- const isUndecided = (row: Row, key: string): boolean =>
77
- String(row[key] ?? "").trim() === "";
78
-
79
- export function SwipeView({
80
- rows,
81
- fields,
82
- fieldByKey,
83
- spec,
84
- cardKeys,
85
- detailKeys,
86
- scope,
87
- viewer,
88
- docs,
89
- docPayload,
90
- onDocAdd,
91
- onDocFetch,
92
- onDocDelete,
93
- titleKey,
94
- canWrite,
95
- readOnlyReason,
96
- canBind,
97
- onSpec,
98
- onSwipe,
99
- onOpen,
100
- }: {
101
- /** DISTINCT data rows from the full pipeline, overlay edits layered β€” the kanban's contract.
102
- * The deck re-derives from these, so a written record leaves it as soon as the optimistic
103
- * patch lands; there is no local cursor to drift out of step with the data. */
104
- rows: Row[];
105
- /** Every field, for the picker's field list. */
106
- fields: Field[];
107
- fieldByKey: Map<string, Field>;
108
- /** The stored binding, or undefined for a deck nobody has configured yet. */
109
- spec: SwipeSpec | undefined;
110
- /** The handful of visible fields the card lists under its title. */
111
- cardKeys: string[];
112
- titleKey: string;
113
- /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */
114
- canWrite: boolean;
115
- /** Stated when the deck cannot be decided β€” permissions, or a computed column. */
116
- readOnlyReason: string | null;
117
- /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the
118
- * view-editing permission and NOT `canWrite` β€” conflating the two is
119
- * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does
120
- * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */
121
- canBind: boolean;
122
- /** `undefined` DELETES the binding β€” absent is the honest unconfigured state, and storing a
123
- * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */
124
- onSpec: (next: SwipeSpec | undefined) => void;
125
- onSwipe: (pid: number, value: string) => void;
126
- onOpen: (pid: number) => void;
127
- /**
128
- * ⭐⭐ WAVE-29 T26 (owner R9) β€” WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.
129
- *
130
- * R9: *"the swipe CARD itself renders the record detail inline β€” fields, comments and
131
- * attachments β€” so a reviewer decides without leaving the deck."* Everything below is that,
132
- * and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply
133
- * different amounts. A card must render with none of them rather than throw β€” the standalone
134
- * embed has no `scope`, and a deployment with no document storage serves no handlers.
135
- */
136
- /** Every field the VIEW shows, in its order β€” not the three-key card summary. */
137
- detailKeys?: string[];
138
- /** The surface these records live on. Comments are keyed by it; absent β‡’ no comments section,
139
- * which is the pre-existing precondition `RecordDetail` already carries. */
140
- scope?: SurfaceScope;
141
- viewer?: Viewer;
142
- /** This record's attachments, and the plumbing. Handlers absent β‡’ the section is not rendered
143
- * at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app
144
- * cannot keep). */
145
- /** Keyed by pid, because a deck shows many records β€” `RecordDetail` takes ONE record's list
146
- * and that shape cannot serve a deck. */
147
- docs?: Record<string, CustomerDoc[]>;
148
- docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };
149
- /** ⚠ EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE
150
- * open record. A deck paints many records at once, so a handler bound to a single pid would
151
- * attach every reviewer's upload to whichever card happened to be open. */
152
- onDocAdd?: (
153
- pid: number,
154
- file: { name: string; mime: string; size: number; data_b64: string }
155
- ) => void;
156
- onDocFetch?: (pid: number, docId: string) => void;
157
- onDocDelete?: (pid: number, docId: string) => void;
158
- }) {
159
- // "Later" β€” session-only, never stored. A deck with no way past a record you cannot decide
160
- // blocks on that record forever, so this is navigation WITHIN the deck rather than a third
161
- // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty
162
- // state rather than quietly shrinking the deck (rule 8b).
163
- const [later, setLater] = useState<Set<number>>(new Set());
164
- const deckRef = useRef<HTMLDivElement>(null);
165
-
166
- const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);
167
- const boundKey = binding.ok ? binding.field.key : null;
168
-
169
- const undecided = useMemo(
170
- () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),
171
- [rows, boundKey]
172
- );
173
- const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);
174
- const card = deck[0];
175
-
176
- // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever β€”
177
- // otherwise the disclosed skip count drifts away from what is actually on the deck.
178
- useEffect(() => {
179
- setLater((prev) => {
180
- if (prev.size === 0) return prev;
181
- const live = new Set(undecided.map((r) => r.pid));
182
- const next = new Set([...prev].filter((pid) => live.has(pid)));
183
- return next.size === prev.size ? prev : next;
184
- });
185
- }, [undecided]);
186
-
187
- const decide = useCallback(
188
- (value: string) => {
189
- if (!card || !canWrite) return;
190
- onSwipe(card.pid, value);
191
- },
192
- [card, canWrite, onSwipe]
193
- );
194
-
195
- // ← / β†’ decide, and they are the SAME two actions the buttons are rather than a second code
196
- // path: the whole point of the mode is that one hand can clear a queue.
197
- useEffect(() => {
198
- if (!binding.ok || !canWrite || !card) return;
199
- const onKey = (e: KeyboardEvent) => {
200
- if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
201
- const el = document.activeElement as HTMLElement | null;
202
- // Never steal an arrow key from a text field or a native control the user is inside.
203
- if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))
204
- return;
205
- if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;
206
- e.preventDefault();
207
- decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);
208
- };
209
- window.addEventListener("keydown", onKey);
210
- return () => window.removeEventListener("keydown", onKey);
211
- }, [binding, canWrite, card, decide]);
212
-
213
- if (!binding.ok) {
214
- return (
215
- <div className="cg-swipe" ref={deckRef}>
216
- <SwipeBinder
217
- fault={binding.fault}
218
- fields={fields}
219
- fieldByKey={fieldByKey}
220
- spec={spec}
221
- canBind={canBind}
222
- onSpec={onSpec}
223
- />
224
- </div>
225
- );
226
- }
227
-
228
- const { field } = binding;
229
- const leftTint = optionTint(field, binding.spec.leftOption);
230
- const rightTint = optionTint(field, binding.spec.rightOption);
231
-
232
- return (
233
- <div className="cg-swipe" ref={deckRef} tabIndex={-1}>
234
- <div className="cg-swipe-bar">
235
- <span className="cg-swipe-bound">
236
- <ModeIcon mode="swipe" />
237
- Sorting into <strong>{field.label}</strong>
238
- </span>
239
- <span className="cg-swipe-left">
240
- {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort
241
- </span>
242
- {canBind && (
243
- <button
244
- type="button"
245
- className="cg-link-btn"
246
- onClick={() => onSpec(undefined)}
247
- title="Choose a different field or different options for this deck"
248
- >
249
- Change
250
- </button>
251
- )}
252
- </div>
253
- {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
254
- {card ? (
255
- <div className="cg-swipe-deck">
256
- <button
257
- type="button"
258
- className="cg-swipe-side cg-swipe-side--left"
259
- disabled={!canWrite}
260
- style={leftTint ? { background: leftTint.bg, color: leftTint.fg } : undefined}
261
- onClick={() => decide(binding.spec.leftOption)}
262
- title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}
263
- >
264
- <span aria-hidden className="cg-swipe-arrow">
265
- <svg width="16" height="16" viewBox="0 0 16 16">
266
- <path
267
- d="M11 3.2 6.2 8l4.8 4.8"
268
- fill="none"
269
- stroke="currentColor"
270
- strokeWidth="1.6"
271
- strokeLinecap="round"
272
- strokeLinejoin="round"
273
- />
274
- </svg>
275
- </span>
276
- {binding.spec.leftOption}
277
- </button>
278
- <article
279
- className="cg-swipe-card"
280
- role="button"
281
- tabIndex={0}
282
- onClick={(e) => {
283
- // ⭐ W41-T48 β€” the card IS the deck's record open, so it folds the rail.
284
- // ⚠ Nothing that is NOT an open can reach this line: every control inside the
285
- // card (a url cell, the comments box, the document tray) already stops its own
286
- // click, and the left/right decision buttons are siblings of the card, not
287
- // children of it. The deck also has no pointer drag to disambiguate β€” its swipe
288
- // is the two buttons and the arrow keys, neither of which opens anything.
289
- // ⚠ `<article role="button">`, not a native button, so a keyboard activation
290
- // never arrives here as a synthetic click; the keydown path below is the whole
291
- // keyboard story and the two cannot both fire for one gesture.
292
- if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT);
293
- onOpen(card.pid);
294
- }}
295
- onKeyDown={(e) => {
296
- if (e.key !== "Enter" && e.key !== " ") return;
297
- e.preventDefault();
298
- // W41-T48 β€” `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space
299
- // auto-repeats keydown, and every one of those repeats is the SAME gesture.
300
- if (!e.repeat) signal(NAV_MINIMIZE_EVENT);
301
- onOpen(card.pid);
302
- }}
303
- >
304
- <h3 className="cg-swipe-title">{String(card[titleKey] ?? "")}</h3>
305
- <div className="cg-swipe-cells">
306
- {/* ⭐ WAVE-29 T26 (R9) β€” the RECORD's visible fields, not the three-key summary the
307
- kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not
308
- been widened yet renders exactly what it rendered before. */}
309
- {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {
310
- const f = fieldByKey.get(k);
311
- if (!f) return null;
312
- const text = formatDisplay(f, card[k]);
313
- if (!text) return null;
314
- // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one
315
- // scheme guard β€” and every gesture that reaches it must be stopped from also
316
- // reaching the card, which is a button (the kanban card's note, same trap).
317
- const href = actionHref(f, card[k]);
318
- return (
319
- <div key={k} className="cg-swipe-cell">
320
- <span className="cg-lv-k">{f.label}</span>
321
- {href ? (
322
- <a
323
- className="cg-lv-v"
324
- href={href}
325
- target="_blank"
326
- rel="noopener noreferrer"
327
- title={text}
328
- onClick={(e) => e.stopPropagation()}
329
- onKeyDown={(e) => e.stopPropagation()}
330
- >
331
- {text}
332
- </a>
333
- ) : (
334
- <span className="cg-lv-v">{text}</span>
335
- )}
336
- </div>
337
- );
338
- })}
339
- </div>
340
- {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"`
341
- that opens the record, and a click on a comment box or an upload control must not
342
- also open the modal it exists to make unnecessary (the kanban card's link trap,
343
- one surface over). */}
344
- {onDocAdd && onDocFetch && onDocDelete && (
345
- <div
346
- className="cg-swipe-docs"
347
- onClick={(e) => e.stopPropagation()}
348
- onKeyDown={(e) => e.stopPropagation()}
349
- role="presentation"
350
- >
351
- <Documents
352
- pid={Number(card.pid)}
353
- docs={docs?.[String(card.pid)] ?? []}
354
- docPayload={docPayload}
355
- onAdd={(file) => onDocAdd(card.pid, file)}
356
- onFetch={(docId) => onDocFetch(card.pid, docId)}
357
- onDelete={(docId) => onDocDelete(card.pid, docId)}
358
- />
359
- </div>
360
- )}
361
- {scope != null && (
362
- <div
363
- className="cg-swipe-comments"
364
- onClick={(e) => e.stopPropagation()}
365
- onKeyDown={(e) => e.stopPropagation()}
366
- role="presentation"
367
- >
368
- {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React
369
- reuses the mounted instance across a card change and paints one record's
370
- comments under another's name until the fetch returns. */}
371
- <RecordComments
372
- key={`${scope}:${Number(card.pid)}`}
373
- scope={scope}
374
- pid={Number(card.pid)}
375
- viewer={viewer}
376
- />
377
- </div>
378
- )}
379
- {canWrite && (
380
- <button
381
- type="button"
382
- className="cg-link-btn cg-swipe-later"
383
- onClick={(e) => {
384
- e.stopPropagation();
385
- setLater((prev) => new Set(prev).add(card.pid));
386
- }}
387
- >
388
- Decide later
389
- </button>
390
- )}
391
- </article>
392
- <button
393
- type="button"
394
- className="cg-swipe-side cg-swipe-side--right"
395
- disabled={!canWrite}
396
- style={rightTint ? { background: rightTint.bg, color: rightTint.fg } : undefined}
397
- onClick={() => decide(binding.spec.rightOption)}
398
- title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}
399
- >
400
- {binding.spec.rightOption}
401
- <span aria-hidden className="cg-swipe-arrow">
402
- <svg width="16" height="16" viewBox="0 0 16 16">
403
- <path
404
- d="M5 3.2 9.8 8 5 12.8"
405
- fill="none"
406
- stroke="currentColor"
407
- strokeWidth="1.6"
408
- strokeLinecap="round"
409
- strokeLinejoin="round"
410
- />
411
- </svg>
412
- </span>
413
- </button>
414
- </div>
415
- ) : (
416
- // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous
417
- // between "the deck is finished" and "the filter hid everything", and the two want
418
- // different next actions. `later` is disclosed rather than quietly subtracted.
419
- <div className="cg-mode-empty cg-swipe-empty">
420
- {later.size > 0 ? (
421
- <>
422
- <p>
423
- {later.size.toLocaleString()}{" "}
424
- {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else
425
- in this view is missing a <strong>{field.label}</strong>.
426
- </p>
427
- <button type="button" className="cg-btn" onClick={() => setLater(new Set())}>
428
- Bring them back
429
- </button>
430
- </>
431
- ) : (
432
- <p>
433
- Every record in this view already has a <strong>{field.label}</strong>. Widen the
434
- view's filters to sort more.
435
- </p>
436
- )}
437
- </div>
438
- )}
439
- </div>
440
- );
441
- }
442
-
443
- /**
444
- * The binding picker: field + two options. It is also the surface every LOST binding lands on,
445
- * with the loss stated above it β€” one place that answers "what is this deck for", rather than an
446
- * error screen beside a separate setup screen.
447
- */
448
- function SwipeBinder({
449
- fault,
450
- fields,
451
- fieldByKey,
452
- spec,
453
- canBind,
454
- onSpec,
455
- }: {
456
- fault: BindingFault;
457
- fields: Field[];
458
- fieldByKey: Map<string, Field>;
459
- spec: SwipeSpec | undefined;
460
- canBind: boolean;
461
- onSpec: (next: SwipeSpec | undefined) => void;
462
- }) {
463
- const selects = useMemo(
464
- () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),
465
- [fields]
466
- );
467
- const [fieldKey, setFieldKey] = useState<string>(() => {
468
- if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;
469
- return selects[0]?.key ?? "";
470
- });
471
- const chosen = fieldByKey.get(fieldKey);
472
- const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);
473
- const [left, setLeft] = useState<string>("");
474
- const [right, setRight] = useState<string>("");
475
-
476
- // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's
477
- // pick survives re-renders, and reset whenever the field changes β€” carrying an option from the
478
- // previous field would offer a value the new field cannot hold.
479
- useEffect(() => {
480
- setLeft(options[0] ?? "");
481
- setRight(options.find((o) => o !== options[0]) ?? "");
482
- }, [options]);
483
-
484
- const message = ((): string => {
485
- switch (fault.kind) {
486
- case "field-gone":
487
- return "The field this deck sorted into has been deleted. Pick another one.";
488
- case "not-select":
489
- return `β€œ${fault.field.label}” is no longer a single-select, so it has no options to`
490
- + " sort into. Pick another field.";
491
- case "option-gone":
492
- return `${fault.missing.map((m) => `β€œ${m}”`).join(" and ")} ${
493
- fault.missing.length === 1 ? "is" : "are"
494
- } no longer ${fault.missing.length === 1 ? "an option" : "options"} on β€œ${
495
- fault.field.label
496
- }”. Pick the sides again.`;
497
- default:
498
- return "Sort records one at a time into two options of a single-select field.";
499
- }
500
- })();
501
-
502
- if (!canBind) {
503
- return (
504
- <div className="cg-mode-empty">
505
- <p>{message}</p>
506
- <p>Its creator or an admin can set this view up.</p>
507
- </div>
508
- );
509
- }
510
- if (selects.length === 0) {
511
- // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the
512
- // requirement is what turns a dead end into a next action.
513
- return (
514
- <div className="cg-mode-empty">
515
- <p>
516
- A swipe deck sorts into a single-select field with at least two options. This database
517
- does not have one yet β€” add a single-select column, then come back.
518
- </p>
519
- </div>
520
- );
521
- }
522
- const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();
523
- return (
524
- <div className="cg-swipe-setup">
525
- <p className="cg-swipe-setup-note">{message}</p>
526
- <label className="cg-swipe-setup-row">
527
- <span>Sort into</span>
528
- <select
529
- className="cg-select"
530
- value={fieldKey}
531
- onChange={(e) => setFieldKey(e.target.value)}
532
- >
533
- {/* Every option carries an explicit `value`: a <select> whose value names nothing
534
- renders its FIRST option and reports a choice the user never made
535
- ([[cg-condition-builder-items]]). */}
536
- {selects.map((f) => (
537
- <option key={f.key} value={f.key}>
538
- {f.label}
539
- </option>
540
- ))}
541
- </select>
542
- </label>
543
- <div className="cg-swipe-setup-sides">
544
- <label className="cg-swipe-setup-row">
545
- <span>Swipe left</span>
546
- <select className="cg-select" value={left} onChange={(e) => setLeft(e.target.value)}>
547
- {options.map((o) => (
548
- <option key={o} value={o}>
549
- {o}
550
- </option>
551
- ))}
552
- </select>
553
- </label>
554
- <label className="cg-swipe-setup-row">
555
- <span>Swipe right</span>
556
- <select className="cg-select" value={right} onChange={(e) => setRight(e.target.value)}>
557
- {options.map((o) => (
558
- <option key={o} value={o}>
559
- {o}
560
- </option>
561
- ))}
562
- </select>
563
- </label>
564
- </div>
565
- {!ready && left && right && (
566
- // Stated, not silently refused: both engines DROP a binding whose sides are the same
567
- // option, so a Save that looked like it worked would simply not persist.
568
- <p className="cg-swipe-setup-warn">
569
- The two sides must be different options β€” otherwise both gestures do the same thing.
570
- </p>
571
- )}
572
- <button
573
- type="button"
574
- className="cg-btn cg-btn--primary"
575
- disabled={!ready}
576
- onClick={() =>
577
- chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })
578
- }
579
- >
580
- Start sorting
581
- </button>
582
- </div>
583
- );
584
- }
585
-
586
- export default SwipeView;
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / SwipeView.tsx
3
+ // ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) β€” the SWIPE deck.
4
+ //
5
+ // One record at a time, decided left or right into two options of ONE
6
+ // single-select. R2 fixes the shape and it is narrow on purpose:
7
+ // Β· SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.
8
+ // Β· the deck holds only the records whose bound field is EMPTY β€” a record
9
+ // that already has a value has been decided, and re-asking is not triage.
10
+ // Β· a swipe writes through the NORMAL cell door (`onSwipe`, which the host
11
+ // maps to the same `patchAndRecord` a kanban card move uses), so undo,
12
+ // echo-suppression and the permission wall all hold without being
13
+ // re-implemented here.
14
+ //
15
+ // Honesty rules carried from the other modes:
16
+ // Β· nothing is silently hidden β€” the deck states what is left, and the
17
+ // empty state names the bound field rather than saying "all done".
18
+ // Β· a lost binding is SHOWN, never repaired by guessing. `_clean_display`
19
+ // validates that `fieldKey` names a field the table HAS and stops there;
20
+ // it cannot know the field is still a select, or that the two options are
21
+ // still in its vocabulary (its docstring draws that line explicitly). So
22
+ // those three losses land here, and each one says what happened and
23
+ // re-opens the picker β€” the `viewModes.tsx:190-194` rule, which exists
24
+ // because the wave-7 trap was a picker silently falling back to its first
25
+ // option.
26
+ // ---------------------------------------------------------------------------
27
+
28
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
+ // ⭐⭐ W41-T48 (owner instruction 22) β€” opening a record from the swipe deck folds the shell's
30
+ // navigation rail exactly as a grid cell click does. Guard rationale: `MapView.tsx:2755`.
31
+ import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
32
+ import { choiceOptions } from "./types";
33
+ import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
34
+ // ⚠ `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is
35
+ // loaded here) β€” the same import `RecordComments` takes for the same prop.
36
+ import type { SurfaceScope } from "./apiBridge";
37
+ import RecordComments from "./RecordComments";
38
+ import { Documents } from "./Documents";
39
+ import { formatDisplay } from "./cells";
40
+ import { actionHref } from "./display";
41
+ import { optionTint } from "./choiceColors";
42
+ import { ModeIcon } from "./icons";
43
+ // ⭐ W29-T73 β€” the line its three siblings all have, and the one this file shipped without.
44
+ // `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered
45
+ // unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right β€”
46
+ // a partially-styled surface reads as a design choice, which is why nobody reported it and no
47
+ // gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).
48
+ import "./SwipeView.css";
49
+
50
+ export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;
51
+
52
+ /** The three ways a stored binding can rot that the host cannot see (see the header note). */
53
+ type BindingFault =
54
+ | { kind: "unbound" }
55
+ | { kind: "field-gone"; fieldKey: string }
56
+ | { kind: "not-select"; field: Field }
57
+ | { kind: "option-gone"; field: Field; missing: string[] };
58
+
59
+ function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map<string, Field>):
60
+ { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {
61
+ if (!spec) return { ok: false, fault: { kind: "unbound" } };
62
+ const field = fieldByKey.get(spec.fieldKey);
63
+ if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };
64
+ // R2 β€” SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,
65
+ // so "write this option" would mean append-or-replace, and a triage gesture that sometimes
66
+ // adds and sometimes overwrites is two gestures wearing one button.
67
+ if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };
68
+ const options = choiceOptions(field);
69
+ const has = new Set(options.map((o) => o.toLowerCase()));
70
+ const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));
71
+ if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };
72
+ return { ok: true, field, spec };
73
+ }
74
+
75
+ /** The bound cell is EMPTY β€” the one predicate that decides deck membership (R2). */
76
+ const isUndecided = (row: Row, key: string): boolean =>
77
+ String(row[key] ?? "").trim() === "";
78
+
79
+ export function SwipeView({
80
+ rows,
81
+ fields,
82
+ fieldByKey,
83
+ spec,
84
+ cardKeys,
85
+ detailKeys,
86
+ scope,
87
+ viewer,
88
+ docs,
89
+ docPayload,
90
+ onDocAdd,
91
+ onDocFetch,
92
+ onDocDelete,
93
+ titleKey,
94
+ canWrite,
95
+ readOnlyReason,
96
+ canBind,
97
+ onSpec,
98
+ onSwipe,
99
+ onOpen,
100
+ }: {
101
+ /** DISTINCT data rows from the full pipeline, overlay edits layered β€” the kanban's contract.
102
+ * The deck re-derives from these, so a written record leaves it as soon as the optimistic
103
+ * patch lands; there is no local cursor to drift out of step with the data. */
104
+ rows: Row[];
105
+ /** Every field, for the picker's field list. */
106
+ fields: Field[];
107
+ fieldByKey: Map<string, Field>;
108
+ /** The stored binding, or undefined for a deck nobody has configured yet. */
109
+ spec: SwipeSpec | undefined;
110
+ /** The handful of visible fields the card lists under its title. */
111
+ cardKeys: string[];
112
+ titleKey: string;
113
+ /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */
114
+ canWrite: boolean;
115
+ /** Stated when the deck cannot be decided β€” permissions, or a computed column. */
116
+ readOnlyReason: string | null;
117
+ /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the
118
+ * view-editing permission and NOT `canWrite` β€” conflating the two is
119
+ * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does
120
+ * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */
121
+ canBind: boolean;
122
+ /** `undefined` DELETES the binding β€” absent is the honest unconfigured state, and storing a
123
+ * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */
124
+ onSpec: (next: SwipeSpec | undefined) => void;
125
+ onSwipe: (pid: number, value: string) => void;
126
+ onOpen: (pid: number) => void;
127
+ /**
128
+ * ⭐⭐ WAVE-29 T26 (owner R9) β€” WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.
129
+ *
130
+ * R9: *"the swipe CARD itself renders the record detail inline β€” fields, comments and
131
+ * attachments β€” so a reviewer decides without leaving the deck."* Everything below is that,
132
+ * and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply
133
+ * different amounts. A card must render with none of them rather than throw β€” the standalone
134
+ * embed has no `scope`, and a deployment with no document storage serves no handlers.
135
+ */
136
+ /** Every field the VIEW shows, in its order β€” not the three-key card summary. */
137
+ detailKeys?: string[];
138
+ /** The surface these records live on. Comments are keyed by it; absent β‡’ no comments section,
139
+ * which is the pre-existing precondition `RecordDetail` already carries. */
140
+ scope?: SurfaceScope;
141
+ viewer?: Viewer;
142
+ /** This record's attachments, and the plumbing. Handlers absent β‡’ the section is not rendered
143
+ * at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app
144
+ * cannot keep). */
145
+ /** Keyed by pid, because a deck shows many records β€” `RecordDetail` takes ONE record's list
146
+ * and that shape cannot serve a deck. */
147
+ docs?: Record<string, CustomerDoc[]>;
148
+ docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };
149
+ /** ⚠ EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE
150
+ * open record. A deck paints many records at once, so a handler bound to a single pid would
151
+ * attach every reviewer's upload to whichever card happened to be open. */
152
+ onDocAdd?: (
153
+ pid: number,
154
+ file: { name: string; mime: string; size: number; data_b64: string }
155
+ ) => void;
156
+ onDocFetch?: (pid: number, docId: string) => void;
157
+ onDocDelete?: (pid: number, docId: string) => void;
158
+ }) {
159
+ // "Later" β€” session-only, never stored. A deck with no way past a record you cannot decide
160
+ // blocks on that record forever, so this is navigation WITHIN the deck rather than a third
161
+ // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty
162
+ // state rather than quietly shrinking the deck (rule 8b).
163
+ const [later, setLater] = useState<Set<number>>(new Set());
164
+ const deckRef = useRef<HTMLDivElement>(null);
165
+
166
+ const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);
167
+ const boundKey = binding.ok ? binding.field.key : null;
168
+
169
+ const undecided = useMemo(
170
+ () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),
171
+ [rows, boundKey]
172
+ );
173
+ const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);
174
+ const card = deck[0];
175
+
176
+ // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever β€”
177
+ // otherwise the disclosed skip count drifts away from what is actually on the deck.
178
+ useEffect(() => {
179
+ setLater((prev) => {
180
+ if (prev.size === 0) return prev;
181
+ const live = new Set(undecided.map((r) => r.pid));
182
+ const next = new Set([...prev].filter((pid) => live.has(pid)));
183
+ return next.size === prev.size ? prev : next;
184
+ });
185
+ }, [undecided]);
186
+
187
+ const decide = useCallback(
188
+ (value: string) => {
189
+ if (!card || !canWrite) return;
190
+ onSwipe(card.pid, value);
191
+ },
192
+ [card, canWrite, onSwipe]
193
+ );
194
+
195
+ // ← / β†’ decide, and they are the SAME two actions the buttons are rather than a second code
196
+ // path: the whole point of the mode is that one hand can clear a queue.
197
+ useEffect(() => {
198
+ if (!binding.ok || !canWrite || !card) return;
199
+ const onKey = (e: KeyboardEvent) => {
200
+ if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
201
+ const el = document.activeElement as HTMLElement | null;
202
+ // Never steal an arrow key from a text field or a native control the user is inside.
203
+ if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))
204
+ return;
205
+ if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;
206
+ e.preventDefault();
207
+ decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);
208
+ };
209
+ window.addEventListener("keydown", onKey);
210
+ return () => window.removeEventListener("keydown", onKey);
211
+ }, [binding, canWrite, card, decide]);
212
+
213
+ if (!binding.ok) {
214
+ return (
215
+ <div className="cg-swipe" ref={deckRef}>
216
+ <SwipeBinder
217
+ fault={binding.fault}
218
+ fields={fields}
219
+ fieldByKey={fieldByKey}
220
+ spec={spec}
221
+ canBind={canBind}
222
+ onSpec={onSpec}
223
+ />
224
+ </div>
225
+ );
226
+ }
227
+
228
+ const { field } = binding;
229
+ const leftTint = optionTint(field, binding.spec.leftOption);
230
+ const rightTint = optionTint(field, binding.spec.rightOption);
231
+
232
+ return (
233
+ <div className="cg-swipe" ref={deckRef} tabIndex={-1}>
234
+ <div className="cg-swipe-bar">
235
+ <span className="cg-swipe-bound">
236
+ <ModeIcon mode="swipe" />
237
+ Sorting into <strong>{field.label}</strong>
238
+ </span>
239
+ <span className="cg-swipe-left">
240
+ {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort
241
+ </span>
242
+ {canBind && (
243
+ <button
244
+ type="button"
245
+ className="cg-link-btn"
246
+ onClick={() => onSpec(undefined)}
247
+ title="Choose a different field or different options for this deck"
248
+ >
249
+ Change
250
+ </button>
251
+ )}
252
+ </div>
253
+ {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
254
+ {card ? (
255
+ <div className="cg-swipe-deck">
256
+ <button
257
+ type="button"
258
+ className="cg-swipe-side cg-swipe-side--left"
259
+ disabled={!canWrite}
260
+ style={leftTint ? { background: leftTint.bg, color: leftTint.fg } : undefined}
261
+ onClick={() => decide(binding.spec.leftOption)}
262
+ title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}
263
+ >
264
+ <span aria-hidden className="cg-swipe-arrow">
265
+ <svg width="16" height="16" viewBox="0 0 16 16">
266
+ <path
267
+ d="M11 3.2 6.2 8l4.8 4.8"
268
+ fill="none"
269
+ stroke="currentColor"
270
+ strokeWidth="1.6"
271
+ strokeLinecap="round"
272
+ strokeLinejoin="round"
273
+ />
274
+ </svg>
275
+ </span>
276
+ {binding.spec.leftOption}
277
+ </button>
278
+ <article
279
+ className="cg-swipe-card"
280
+ role="button"
281
+ tabIndex={0}
282
+ onClick={(e) => {
283
+ // ⭐ W41-T48 β€” the card IS the deck's record open, so it folds the rail.
284
+ // ⚠ Nothing that is NOT an open can reach this line: every control inside the
285
+ // card (a url cell, the comments box, the document tray) already stops its own
286
+ // click, and the left/right decision buttons are siblings of the card, not
287
+ // children of it. The deck also has no pointer drag to disambiguate β€” its swipe
288
+ // is the two buttons and the arrow keys, neither of which opens anything.
289
+ // ⚠ `<article role="button">`, not a native button, so a keyboard activation
290
+ // never arrives here as a synthetic click; the keydown path below is the whole
291
+ // keyboard story and the two cannot both fire for one gesture.
292
+ if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT);
293
+ onOpen(card.pid);
294
+ }}
295
+ onKeyDown={(e) => {
296
+ if (e.key !== "Enter" && e.key !== " ") return;
297
+ e.preventDefault();
298
+ // W41-T48 β€” `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space
299
+ // auto-repeats keydown, and every one of those repeats is the SAME gesture.
300
+ if (!e.repeat) signal(NAV_MINIMIZE_EVENT);
301
+ onOpen(card.pid);
302
+ }}
303
+ >
304
+ <h3 className="cg-swipe-title">{String(card[titleKey] ?? "")}</h3>
305
+ <div className="cg-swipe-cells">
306
+ {/* ⭐ WAVE-29 T26 (R9) β€” the RECORD's visible fields, not the three-key summary the
307
+ kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not
308
+ been widened yet renders exactly what it rendered before. */}
309
+ {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {
310
+ const f = fieldByKey.get(k);
311
+ if (!f) return null;
312
+ const text = formatDisplay(f, card[k]);
313
+ if (!text) return null;
314
+ // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one
315
+ // scheme guard β€” and every gesture that reaches it must be stopped from also
316
+ // reaching the card, which is a button (the kanban card's note, same trap).
317
+ const href = actionHref(f, card[k]);
318
+ return (
319
+ <div key={k} className="cg-swipe-cell">
320
+ <span className="cg-lv-k">{f.label}</span>
321
+ {href ? (
322
+ <a
323
+ className="cg-lv-v"
324
+ href={href}
325
+ target="_blank"
326
+ rel="noopener noreferrer"
327
+ title={text}
328
+ onClick={(e) => e.stopPropagation()}
329
+ onKeyDown={(e) => e.stopPropagation()}
330
+ >
331
+ {text}
332
+ </a>
333
+ ) : (
334
+ <span className="cg-lv-v">{text}</span>
335
+ )}
336
+ </div>
337
+ );
338
+ })}
339
+ </div>
340
+ {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"`
341
+ that opens the record, and a click on a comment box or an upload control must not
342
+ also open the modal it exists to make unnecessary (the kanban card's link trap,
343
+ one surface over). */}
344
+ {onDocAdd && onDocFetch && onDocDelete && (
345
+ <div
346
+ className="cg-swipe-docs"
347
+ onClick={(e) => e.stopPropagation()}
348
+ onKeyDown={(e) => e.stopPropagation()}
349
+ role="presentation"
350
+ >
351
+ <Documents
352
+ pid={Number(card.pid)}
353
+ docs={docs?.[String(card.pid)] ?? []}
354
+ docPayload={docPayload}
355
+ onAdd={(file) => onDocAdd(card.pid, file)}
356
+ onFetch={(docId) => onDocFetch(card.pid, docId)}
357
+ onDelete={(docId) => onDocDelete(card.pid, docId)}
358
+ />
359
+ </div>
360
+ )}
361
+ {scope != null && (
362
+ <div
363
+ className="cg-swipe-comments"
364
+ onClick={(e) => e.stopPropagation()}
365
+ onKeyDown={(e) => e.stopPropagation()}
366
+ role="presentation"
367
+ >
368
+ {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React
369
+ reuses the mounted instance across a card change and paints one record's
370
+ comments under another's name until the fetch returns. */}
371
+ <RecordComments
372
+ key={`${scope}:${Number(card.pid)}`}
373
+ scope={scope}
374
+ pid={Number(card.pid)}
375
+ viewer={viewer}
376
+ />
377
+ </div>
378
+ )}
379
+ {canWrite && (
380
+ <button
381
+ type="button"
382
+ className="cg-link-btn cg-swipe-later"
383
+ onClick={(e) => {
384
+ e.stopPropagation();
385
+ setLater((prev) => new Set(prev).add(card.pid));
386
+ }}
387
+ >
388
+ Decide later
389
+ </button>
390
+ )}
391
+ </article>
392
+ <button
393
+ type="button"
394
+ className="cg-swipe-side cg-swipe-side--right"
395
+ disabled={!canWrite}
396
+ style={rightTint ? { background: rightTint.bg, color: rightTint.fg } : undefined}
397
+ onClick={() => decide(binding.spec.rightOption)}
398
+ title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}
399
+ >
400
+ {binding.spec.rightOption}
401
+ <span aria-hidden className="cg-swipe-arrow">
402
+ <svg width="16" height="16" viewBox="0 0 16 16">
403
+ <path
404
+ d="M5 3.2 9.8 8 5 12.8"
405
+ fill="none"
406
+ stroke="currentColor"
407
+ strokeWidth="1.6"
408
+ strokeLinecap="round"
409
+ strokeLinejoin="round"
410
+ />
411
+ </svg>
412
+ </span>
413
+ </button>
414
+ </div>
415
+ ) : (
416
+ // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous
417
+ // between "the deck is finished" and "the filter hid everything", and the two want
418
+ // different next actions. `later` is disclosed rather than quietly subtracted.
419
+ <div className="cg-mode-empty cg-swipe-empty">
420
+ {later.size > 0 ? (
421
+ <>
422
+ <p>
423
+ {later.size.toLocaleString()}{" "}
424
+ {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else
425
+ in this view is missing a <strong>{field.label}</strong>.
426
+ </p>
427
+ <button type="button" className="cg-btn" onClick={() => setLater(new Set())}>
428
+ Bring them back
429
+ </button>
430
+ </>
431
+ ) : (
432
+ <p>
433
+ Every record in this view already has a <strong>{field.label}</strong>. Widen the
434
+ view's filters to sort more.
435
+ </p>
436
+ )}
437
+ </div>
438
+ )}
439
+ </div>
440
+ );
441
+ }
442
+
443
+ /**
444
+ * The binding picker: field + two options. It is also the surface every LOST binding lands on,
445
+ * with the loss stated above it β€” one place that answers "what is this deck for", rather than an
446
+ * error screen beside a separate setup screen.
447
+ */
448
+ function SwipeBinder({
449
+ fault,
450
+ fields,
451
+ fieldByKey,
452
+ spec,
453
+ canBind,
454
+ onSpec,
455
+ }: {
456
+ fault: BindingFault;
457
+ fields: Field[];
458
+ fieldByKey: Map<string, Field>;
459
+ spec: SwipeSpec | undefined;
460
+ canBind: boolean;
461
+ onSpec: (next: SwipeSpec | undefined) => void;
462
+ }) {
463
+ const selects = useMemo(
464
+ () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),
465
+ [fields]
466
+ );
467
+ const [fieldKey, setFieldKey] = useState<string>(() => {
468
+ if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;
469
+ return selects[0]?.key ?? "";
470
+ });
471
+ const chosen = fieldByKey.get(fieldKey);
472
+ const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);
473
+ const [left, setLeft] = useState<string>("");
474
+ const [right, setRight] = useState<string>("");
475
+
476
+ // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's
477
+ // pick survives re-renders, and reset whenever the field changes β€” carrying an option from the
478
+ // previous field would offer a value the new field cannot hold.
479
+ useEffect(() => {
480
+ setLeft(options[0] ?? "");
481
+ setRight(options.find((o) => o !== options[0]) ?? "");
482
+ }, [options]);
483
+
484
+ const message = ((): string => {
485
+ switch (fault.kind) {
486
+ case "field-gone":
487
+ return "The field this deck sorted into has been deleted. Pick another one.";
488
+ case "not-select":
489
+ return `β€œ${fault.field.label}” is no longer a single-select, so it has no options to`
490
+ + " sort into. Pick another field.";
491
+ case "option-gone":
492
+ return `${fault.missing.map((m) => `β€œ${m}”`).join(" and ")} ${
493
+ fault.missing.length === 1 ? "is" : "are"
494
+ } no longer ${fault.missing.length === 1 ? "an option" : "options"} on β€œ${
495
+ fault.field.label
496
+ }”. Pick the sides again.`;
497
+ default:
498
+ return "Sort records one at a time into two options of a single-select field.";
499
+ }
500
+ })();
501
+
502
+ if (!canBind) {
503
+ return (
504
+ <div className="cg-mode-empty">
505
+ <p>{message}</p>
506
+ <p>Its creator or an admin can set this view up.</p>
507
+ </div>
508
+ );
509
+ }
510
+ if (selects.length === 0) {
511
+ // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the
512
+ // requirement is what turns a dead end into a next action.
513
+ return (
514
+ <div className="cg-mode-empty">
515
+ <p>
516
+ A swipe deck sorts into a single-select field with at least two options. This database
517
+ does not have one yet β€” add a single-select column, then come back.
518
+ </p>
519
+ </div>
520
+ );
521
+ }
522
+ const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();
523
+ return (
524
+ <div className="cg-swipe-setup">
525
+ <p className="cg-swipe-setup-note">{message}</p>
526
+ <label className="cg-swipe-setup-row">
527
+ <span>Sort into</span>
528
+ <select
529
+ className="cg-select"
530
+ value={fieldKey}
531
+ onChange={(e) => setFieldKey(e.target.value)}
532
+ >
533
+ {/* Every option carries an explicit `value`: a <select> whose value names nothing
534
+ renders its FIRST option and reports a choice the user never made
535
+ ([[cg-condition-builder-items]]). */}
536
+ {selects.map((f) => (
537
+ <option key={f.key} value={f.key}>
538
+ {f.label}
539
+ </option>
540
+ ))}
541
+ </select>
542
+ </label>
543
+ <div className="cg-swipe-setup-sides">
544
+ <label className="cg-swipe-setup-row">
545
+ <span>Swipe left</span>
546
+ <select className="cg-select" value={left} onChange={(e) => setLeft(e.target.value)}>
547
+ {options.map((o) => (
548
+ <option key={o} value={o}>
549
+ {o}
550
+ </option>
551
+ ))}
552
+ </select>
553
+ </label>
554
+ <label className="cg-swipe-setup-row">
555
+ <span>Swipe right</span>
556
+ <select className="cg-select" value={right} onChange={(e) => setRight(e.target.value)}>
557
+ {options.map((o) => (
558
+ <option key={o} value={o}>
559
+ {o}
560
+ </option>
561
+ ))}
562
+ </select>
563
+ </label>
564
+ </div>
565
+ {!ready && left && right && (
566
+ // Stated, not silently refused: both engines DROP a binding whose sides are the same
567
+ // option, so a Save that looked like it worked would simply not persist.
568
+ <p className="cg-swipe-setup-warn">
569
+ The two sides must be different options β€” otherwise both gestures do the same thing.
570
+ </p>
571
+ )}
572
+ <button
573
+ type="button"
574
+ className="cg-btn cg-btn--primary"
575
+ disabled={!ready}
576
+ onClick={() =>
577
+ chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })
578
+ }
579
+ >
580
+ Start sorting
581
+ </button>
582
+ </div>
583
+ );
584
+ }
585
+
586
+ export default SwipeView;
web/src/customer-grid/viewModes.tsx CHANGED
@@ -60,6 +60,20 @@ import { useScrollBox, windowRange } from "./GalleryTimelineViews";
60
  // wave52-owned sheet instead of being added there.
61
  import "../styles/wave52/timeline.css";
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  /** Item 4 β€” plain words for the aggregates. "avg" is jargon in a picker aimed at a day cell. */
64
  const AGG_LABELS: Record<ChartAgg, string> = {
65
  sum: "Total",
@@ -229,6 +243,7 @@ export function ModeSwitch({
229
  mode,
230
  onMode,
231
  locked = false,
 
232
  stackField,
233
  stackChoices,
234
  onPickField,
@@ -244,6 +259,8 @@ export function ModeSwitch({
244
  * stay editable"), so removing those too would be a broader lock than the contract grants.
245
  */
246
  locked?: boolean;
 
 
247
  /** The kanban's effective stack field (resolved by the caller). */
248
  stackField?: Field;
249
  stackChoices: Field[];
@@ -265,6 +282,13 @@ export function ModeSwitch({
265
  metricChoices?: Field[];
266
  onCalendarMetrics?: (next: { id: string; field: string; agg: string }[]) => void;
267
  }) {
 
 
 
 
 
 
 
268
  // Wave-7 item W12: the switcher is a DROPDOWN in the toolbar-button family β€” the
269
  // same Popover component Fields/Filter/Sort use, radio rows inside (the Rows/Color
270
  // panel pattern), with the current mode named on the trigger chip.
@@ -326,7 +350,7 @@ export function ModeSwitch({
326
  alignItems: "flex-start",
327
  }}
328
  >
329
- {CREATABLE_GROUPS.map((group) => (
330
  <div key={group.label} style={{ minWidth: 130 }}>
331
  <div className="cg-pop-title">{group.label}</div>
332
  {group.modes.map((m) => (
@@ -1669,3 +1693,106 @@ function KanbanLane({
1669
  );
1670
  }
1671
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  // wave52-owned sheet instead of being added there.
61
  import "../styles/wave52/timeline.css";
62
 
63
+ /** The two template-backed surfaces which may be launched through the ordinary Map mode.
64
+ * The registry object is the discriminator: a name, hash fragment, or client-side template
65
+ * draft is never allowed to choose the renderer after the Application has been saved. */
66
+ export type ApplicationTemplateSurface = "route" | "catalog" | null;
67
+
68
+ export function applicationTemplateSurface(application: unknown): ApplicationTemplateSurface {
69
+ if (!application || typeof application !== "object" || Array.isArray(application)) return null;
70
+ const row = application as { templateKind?: unknown; fieldMap?: unknown };
71
+ if (!row.fieldMap || typeof row.fieldMap !== "object" || Array.isArray(row.fieldMap)) return null;
72
+ return row.templateKind === "route" || row.templateKind === "catalog"
73
+ ? row.templateKind
74
+ : null;
75
+ }
76
+
77
  /** Item 4 β€” plain words for the aggregates. "avg" is jargon in a picker aimed at a day cell. */
78
  const AGG_LABELS: Record<ChartAgg, string> = {
79
  sum: "Total",
 
243
  mode,
244
  onMode,
245
  locked = false,
246
+ allowedModes,
247
  stackField,
248
  stackChoices,
249
  onPickField,
 
259
  * stay editable"), so removing those too would be a broader lock than the contract grants.
260
  */
261
  locked?: boolean;
262
+ /** A host may expose only the projections it can render without weakening their data contract. */
263
+ allowedModes?: readonly DisplayMode[];
264
  /** The kanban's effective stack field (resolved by the caller). */
265
  stackField?: Field;
266
  stackChoices: Field[];
 
282
  metricChoices?: Field[];
283
  onCalendarMetrics?: (next: { id: string; field: string; agg: string }[]) => void;
284
  }) {
285
+ const offeredGroups = CREATABLE_GROUPS.map((group) => ({
286
+ ...group,
287
+ modes: allowedModes
288
+ ? group.modes.filter((candidate) => allowedModes.includes(candidate))
289
+ : group.modes,
290
+ }))
291
+ .filter((group) => group.modes.length > 0);
292
  // Wave-7 item W12: the switcher is a DROPDOWN in the toolbar-button family β€” the
293
  // same Popover component Fields/Filter/Sort use, radio rows inside (the Rows/Color
294
  // panel pattern), with the current mode named on the trigger chip.
 
350
  alignItems: "flex-start",
351
  }}
352
  >
353
+ {offeredGroups.map((group) => (
354
  <div key={group.label} style={{ minWidth: 130 }}>
355
  <div className="cg-pop-title">{group.label}</div>
356
  {group.modes.map((m) => (
 
1693
  );
1694
  }
1695
 
1696
+ /**
1697
+ * The projections a linked database can safely host inside Record detail. This is a subset of the
1698
+ * canonical display-mode registry: labels, icons, grouping, and renderers remain owned by this
1699
+ * module rather than being copied into the drawer.
1700
+ */
1701
+ export const RECORD_DETAIL_MODES: readonly DisplayMode[] = [
1702
+ "grid",
1703
+ "list",
1704
+ "calendar",
1705
+ "kanban",
1706
+ ];
1707
+
1708
+ const ignoreRecordGroup = (_groupKey: string) => undefined;
1709
+ const ignoreRecordMove = (_pid: number, _value: string) => undefined;
1710
+
1711
+ /** Render a complete, already-authorized linked row set through the ordinary mode components. */
1712
+ export function RecordRelatedModeView({
1713
+ mode,
1714
+ rows,
1715
+ fields,
1716
+ dateFieldKey,
1717
+ stackFieldKey,
1718
+ today,
1719
+ scope,
1720
+ onOpen,
1721
+ }: {
1722
+ mode: DisplayMode;
1723
+ rows: Row[];
1724
+ fields: Field[];
1725
+ dateFieldKey?: string;
1726
+ stackFieldKey?: string;
1727
+ today?: string;
1728
+ scope: SurfaceScope;
1729
+ onOpen: (pid: number, record: Row, fields: Field[]) => void;
1730
+ }) {
1731
+ const fieldByKey = useMemo(
1732
+ () => new Map(fields.map((field) => [field.key, field])),
1733
+ [fields]
1734
+ );
1735
+ const titleKey = fields[0]?.key ?? "pid";
1736
+ const visibleKeys = useMemo(() => fields.slice(0, 5).map((field) => field.key), [fields]);
1737
+ const visibleRows = useMemo<VisibleRow[]>(
1738
+ () => rows.map((record) => ({ kind: "data", record })),
1739
+ [rows]
1740
+ );
1741
+ const dateField = fields.find((field) => field.key === dateFieldKey)
1742
+ ?? fields.find((field) => field.type === "date");
1743
+ const stackField = fields.find((field) => field.key === stackFieldKey)
1744
+ ?? fields.find((field) => field.type === "select" || field.type === "status");
1745
+ const openRecord = (pid: number) => {
1746
+ const selected = rows.find((record) => Number(record.pid) === pid);
1747
+ if (selected) onOpen(pid, selected, fields);
1748
+ };
1749
+
1750
+ if (mode === "list") {
1751
+ return (
1752
+ <ListView
1753
+ rows={visibleRows}
1754
+ fieldByKey={fieldByKey}
1755
+ visibleKeys={visibleKeys}
1756
+ titleKey={titleKey}
1757
+ onOpen={openRecord}
1758
+ onToggleGroup={ignoreRecordGroup}
1759
+ />
1760
+ );
1761
+ }
1762
+ if (mode === "calendar") {
1763
+ return dateField ? (
1764
+ <CalendarView
1765
+ rows={rows}
1766
+ field={dateField}
1767
+ today={today}
1768
+ titleKey={titleKey}
1769
+ fieldByKey={fieldByKey}
1770
+ scope={scope}
1771
+ onOpen={openRecord}
1772
+ />
1773
+ ) : (
1774
+ <div className="cg-mode-empty">This database has no date field to place records by.</div>
1775
+ );
1776
+ }
1777
+ if (mode === "kanban") {
1778
+ return stackField ? (
1779
+ <KanbanView
1780
+ rows={rows}
1781
+ field={stackField}
1782
+ fieldByKey={fieldByKey}
1783
+ cardKeys={visibleKeys.filter((key) => key !== titleKey && key !== stackField.key).slice(0, 3)}
1784
+ titleKey={titleKey}
1785
+ canMove={false}
1786
+ readOnlyReason={null}
1787
+ onMove={ignoreRecordMove}
1788
+ onOpen={openRecord}
1789
+ onAddOption={null}
1790
+ />
1791
+ ) : (
1792
+ <div className="cg-mode-empty">
1793
+ This database has no status or single-select field to stack by.
1794
+ </div>
1795
+ );
1796
+ }
1797
+ return <div className="cg-mode-empty">Choose List, Calendar, or Kanban.</div>;
1798
+ }
web/src/home/HomePage.tsx CHANGED
@@ -15,9 +15,9 @@
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";
@@ -47,15 +47,18 @@ import { API_V1, CREDENTIALS } from "../apiContract";
47
  // worn by both surfaces. R4 makes star and "mark important" one idea and one flag; a second star
48
  // component here would be the "one mark, one meaning" failure DESIGN.md 4 names, and `useStarred`
49
  // is what keeps Home and Starred from ending up with different ideas of what is starred.
50
- import { StarButton, Tile } from "../starred/StarredPage";
51
  import { shapeStarred, useStarred, viewCount, viewCountKey } from "../starred/starredApi";
52
  import type { StarKind, Starred, StarredCounts, StarredLoad } from "../starred/starredApi";
 
53
  import {
54
  HOME_LAYOUT_KEY,
 
55
  allDatabases,
 
56
  parseLayout,
57
  } from "./homeModel";
58
- import type { AutomationTile, HomeLayout } from "./homeModel";
59
 
60
  // ── the four quick-start marks ───────────────────────────────────────────────────────────────
61
  //
@@ -145,6 +148,27 @@ function GridIcon() {
145
  );
146
  }
147
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  /**
149
  * One quick-start card. A `<button>` β€” every one of these opens a dialog or a wizard rather
150
  * than navigating, and a link that does not link is a lie the browser's status bar tells.
@@ -179,6 +203,10 @@ function QuickCard({
179
  /** What the FRAME hands Home. Unchanged by the wave-35 split, and named so both halves take
180
  * exactly the same shape rather than drifting. */
181
  export interface HomeProps {
 
 
 
 
182
  /**
183
  * The SHAPED, server-filtered nav. The only thing a tile may be drawn from.
184
  *
@@ -224,6 +252,8 @@ export interface HomeProps {
224
  * a view opened from one cannot behave differently from the same view opened from the other.
225
  */
226
  onOpenView: (database: string, viewId: string) => void;
 
 
227
  }
228
 
229
  /**
@@ -236,9 +266,12 @@ export interface HomeProps {
236
  * a person can SEE without a server. `inbox/_inbox_shot.tsx` paid for this lesson first; the same
237
  * split is now on `StarredSurface`.
238
  *
239
- * ⚠ THE DEFAULT EXPORT'S PROPS ARE UNCHANGED, so the frame's mount is untouched by this.
 
240
  */
241
  export function HomeSurface({
 
 
242
  entries,
243
  recents,
244
  automations,
@@ -247,16 +280,25 @@ export function HomeSurface({
247
  onConnectors,
248
  onOpenAutomation,
249
  onOpenView,
 
250
  folders = [],
251
  folderPlacement = {},
252
  applications = [],
 
 
 
 
253
  starLoad,
254
  starred,
255
  busy,
256
  counts,
257
  toggle,
258
  }: HomeProps & {
259
- applications?: Array<{ id: string; name: string; type: string; compatibleDatabases?: string[]; openTarget?: { database?: string } }>;
 
 
 
 
260
  starLoad: StarredLoad;
261
  starred: Starred;
262
  busy: boolean;
@@ -278,6 +320,11 @@ export function HomeSurface({
278
  // storage can be blocked; the toggle still works for this session
279
  }
280
  }, [layout]);
 
 
 
 
 
281
 
282
  // ⚠ THE CLOCK IS READ ONCE, HERE, AND HANDED IN AS A NUMBER. `homeModel` stays pure so a gate
283
  // can assert the ordering rather than whatever today happens to be.
@@ -295,6 +342,21 @@ export function HomeSurface({
295
  const known = starLoad.phase === "ready";
296
  const dbStarred = new Set(starred.databases);
297
  const agentStarred = new Set(starred.agents);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
 
299
  // ⭐ WAVE 35 Β· W35-T16 (owner item 9) β€” the starred VIEWS, resolved by the SAME function
300
  // Starred uses. Item 9 asks for these views on Home and under Starred; running them through one
@@ -303,13 +365,23 @@ export function HomeSurface({
303
  // β›” AND THE DROP RULE COMES WITH IT: `shapeStarred` refuses a view whose database is not in
304
  // `entries`, so a star that outlived its database (deleted, or a grant revoked) draws NOTHING
305
  // rather than a tile that lands the reader in a 403.
306
- const starredViews = shapeStarred(starred, entries, automations).views;
 
 
 
307
 
308
  return (
309
  <div className="shell-home">
310
- <h1 className="home-title">Home</h1>
 
 
 
 
 
 
 
311
 
312
- <div className="home-cards">
313
  {/* ⚠ THE DETAIL LINES ARE BYTE-IDENTICAL TO THE DIALOG'S ROWS, and that is deliberate
314
  rather than lazy. Each of these cards opens the same door as a row in the
315
  New-database dialog, and the first draft described the same two things in four
@@ -356,7 +428,7 @@ export function HomeSurface({
356
  detail="Browse the connectors this workspace can use."
357
  onClick={onConnectors}
358
  />
359
- </div>
360
 
361
  <div className="home-recents-bar">
362
  {/* The reference puts an "Opened anytime" filter here. We do not have one and do not
@@ -383,10 +455,24 @@ export function HomeSurface({
383
  >
384
  <GridIcon />
385
  </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
386
  </div>
387
  </div>
388
 
389
- {databases.length === 0 ? (
390
  // β›” ONE LINE, AND IT NAMES THE DOOR THAT FILLS IT (DESIGN.md 4 / R13). This is also
391
  // where wave 18's tenant hero went: a workspace with no databases lands here, and the
392
  // cards above ARE the "create your first database" affordance the hero carried. Two
@@ -395,10 +481,10 @@ export function HomeSurface({
395
  // described a state that can no longer exist β€” every granted database is drawn whether it
396
  // has been opened or not, so an empty list now means exactly one thing.
397
  <p className="home-empty">
398
- This workspace has no databases yet β€” create one above, or connect a source.
399
  </p>
400
- ) : (
401
- [{ id: "databases", title: "Databases", tiles: databases }].map((section) => (
402
  <section key={section.id} className="home-section">
403
  <h2 className="home-section-title">{section.title}</h2>
404
  <div className={"home-tiles is-" + layout}>
@@ -469,9 +555,61 @@ export function HomeSurface({
469
  </div>
470
  </section>
471
  ))
472
- )}
473
- {folders.length > 0 && <section className="home-section"><h2 className="home-section-title">Folders</h2><div className={"home-tiles is-" + layout}>{folders.map((folder) => { const count = Object.values(folderPlacement).filter((id) => id === folder.id).length; return <a className="home-tile" href={`#/data?folder=${encodeURIComponent(folder.id)}`} key={folder.id}><span className="home-tile-chip home-folder-glyph" aria-hidden><FolderMark size={16} /></span><span className="home-tile-text"><span className="home-tile-name">{folder.name}</span><span className="home-tile-ago">{count} database{count === 1 ? "" : "s"}</span></span></a>; })}</div></section>}
474
- {applications.length > 0 && <section className="home-section"><h2 className="home-section-title">Applications</h2><div className={"home-tiles is-" + layout}>{applications.map((application) => { const database = application.openTarget?.database ?? application.compatibleDatabases?.[0] ?? ""; return <a className="home-tile" href={database ? `#/data?database=${encodeURIComponent(database)}&application=${encodeURIComponent(application.id)}` : "#/home"} key={application.id}><span className="home-tile-chip home-app-glyph" aria-hidden>{application.type.slice(0, 1).toUpperCase()}</span><span className="home-tile-text"><span className="home-tile-name">{application.name}</span><span className="home-tile-ago">{application.type}</span></span></a>; })}</div></section>}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
475
 
476
  {/* ⭐ WAVE 24 item 13 (R10) β€” THE AUTOMATIONS SECTION.
477
  Same tiles, same rhythm.
@@ -495,6 +633,7 @@ export function HomeSurface({
495
  turns a 403 into `[]`) β€” and a heading over nothing says "there should be something
496
  here", which is a different and false statement. */}
497
  {automations.length ? (
 
498
  <section className="home-section">
499
  {/* β›” W34-T40's `done-when` names FOUR surfaces that must read Agents, and this was the
500
  one that did not: a hardcoded `"Automations"` that never consulted the module label.
@@ -506,7 +645,7 @@ export function HomeSurface({
506
  here would have left the next rename in exactly the same trap. */}
507
  <h2 className="home-section-title">{AGENTS_MODULE_LABEL}</h2>
508
  <div className={"home-tiles is-" + layout}>
509
- {automations.map((a) => (
510
  <div key={a.id} className="st-tilewrap">
511
  <button
512
  type="button"
@@ -537,6 +676,7 @@ export function HomeSurface({
537
  ))}
538
  </div>
539
  </section>
 
540
  ) : null}
541
 
542
  {/* ⭐ WAVE 35 Β· W35-T16 (owner item 9) β€” THE STARRED VIEWS.
@@ -551,7 +691,7 @@ export function HomeSurface({
551
  ⚠ EMPTY RENDERS NOTHING, like every other section here: no starred views is a real
552
  answer, and a heading over nothing says "there should be something here", which is a
553
  different and false statement. */}
554
- {starredViews.length ? (
555
  <section className="home-section">
556
  <h2 className="home-section-title">Starred views</h2>
557
  <div className={"home-tiles is-" + layout}>
@@ -576,6 +716,42 @@ export function HomeSurface({
576
  </div>
577
  </section>
578
  ) : null}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
579
  </div>
580
  );
581
  }
@@ -593,8 +769,65 @@ export function HomeSurface({
593
  */
594
  export default function HomePage(props: HomeProps) {
595
  const { load: starLoad, starred, busy, counts, toggle } = useStarred();
596
- const [applications, setApplications] = useState<Array<{ id: string; name: string; type: string; compatibleDatabases?: string[]; openTarget?: { database?: string } }>>([]);
597
- useEffect(() => { const controller = new AbortController(); void fetch(`${API_V1}/applications`, { credentials: CREDENTIALS, signal: controller.signal }).then(async (response) => response.ok ? response.json() : { applications: [] }).then((body) => { if (!controller.signal.aborted) setApplications(Array.isArray(body?.applications) ? body.applications : []); }).catch(() => undefined); return () => controller.abort(); }, []);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
598
  return (
599
  <HomeSurface
600
  {...props}
@@ -604,6 +837,10 @@ export default function HomePage(props: HomeProps) {
604
  counts={counts}
605
  toggle={toggle}
606
  applications={applications}
 
 
 
 
607
  />
608
  );
609
  }
 
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 keeps display state for layout and the starred-only filter. Recents and
19
+ // grants still come down with the nav; Application definitions are read from
20
+ // their governed tenant registry and reuse the existing tile star control.
21
  // ---------------------------------------------------------------------------
22
 
23
  import { useEffect, useState } from "react";
 
47
  // worn by both surfaces. R4 makes star and "mark important" one idea and one flag; a second star
48
  // component here would be the "one mark, one meaning" failure DESIGN.md 4 names, and `useStarred`
49
  // is what keeps Home and Starred from ending up with different ideas of what is starred.
50
+ import { QueryIcon, StarButton, Tile } from "../starred/StarredPage";
51
  import { shapeStarred, useStarred, viewCount, viewCountKey } from "../starred/starredApi";
52
  import type { StarKind, Starred, StarredCounts, StarredLoad } from "../starred/starredApi";
53
+ import { StarIcon } from "../ui/icons";
54
  import {
55
  HOME_LAYOUT_KEY,
56
+ applyHomeFilter,
57
  allDatabases,
58
+ parseHomeFilter,
59
  parseLayout,
60
  } from "./homeModel";
61
+ import type { AutomationTile, HomeFilter, HomeLayout } from "./homeModel";
62
 
63
  // ── the four quick-start marks ───────────────────────────────────────────────────────────────
64
  //
 
148
  );
149
  }
150
 
151
+ /** Applications use one quiet four-pane mark, in the shell's existing stroke vocabulary. */
152
+ function ApplicationIcon() {
153
+ return (
154
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="home-app-icon">
155
+ <rect x="2.3" y="2.3" width="11.4" height="11.4" rx="2" />
156
+ <path d="M8 2.3v11.4M2.3 8h11.4" />
157
+ </svg>
158
+ );
159
+ }
160
+
161
+ interface ApplicationTile {
162
+ id: string;
163
+ name: string;
164
+ type: string;
165
+ templateKind?: string;
166
+ compatibleDatabases?: string[];
167
+ openTarget?: { database?: string };
168
+ starred?: boolean;
169
+ capabilities?: { star?: boolean };
170
+ }
171
+
172
  /**
173
  * One quick-start card. A `<button>` β€” every one of these opens a dialog or a wizard rather
174
  * than navigating, and a link that does not link is a lie the browser's status bar tells.
 
203
  /** What the FRAME hands Home. Unchanged by the wave-35 split, and named so both halves take
204
  * exactly the same shape rather than drifting. */
205
  export interface HomeProps {
206
+ /** App reuses Home's tile vocabulary without becoming a second shell. */
207
+ mode?: "home" | "app";
208
+ /** Compatibility entry for a retired `#/starred` bookmark. */
209
+ initialStarredOnly?: boolean;
210
  /**
211
  * The SHAPED, server-filtered nav. The only thing a tile may be drawn from.
212
  *
 
252
  * a view opened from one cannot behave differently from the same view opened from the other.
253
  */
254
  onOpenView: (database: string, viewId: string) => void;
255
+ /** Queries remain reachable after Starred leaves the rail. */
256
+ onOpenQuery?: (queryId: string) => void;
257
  }
258
 
259
  /**
 
266
  * a person can SEE without a server. `inbox/_inbox_shot.tsx` paid for this lesson first; the same
267
  * split is now on `StarredSurface`.
268
  *
269
+ * Wave 55 adds optional Home/App mode and compatibility-filter props; the original callers keep
270
+ * their existing Home behavior by default.
271
  */
272
  export function HomeSurface({
273
+ mode = "home",
274
+ initialStarredOnly = false,
275
  entries,
276
  recents,
277
  automations,
 
280
  onConnectors,
281
  onOpenAutomation,
282
  onOpenView,
283
+ onOpenQuery = () => undefined,
284
  folders = [],
285
  folderPlacement = {},
286
  applications = [],
287
+ applicationsKnown = true,
288
+ applicationsError = "",
289
+ applicationBusy = new Set<string>(),
290
+ onToggleApplication = () => undefined,
291
  starLoad,
292
  starred,
293
  busy,
294
  counts,
295
  toggle,
296
  }: HomeProps & {
297
+ applications?: ApplicationTile[];
298
+ applicationsKnown?: boolean;
299
+ applicationsError?: string;
300
+ applicationBusy?: ReadonlySet<string>;
301
+ onToggleApplication?: (application: ApplicationTile, on: boolean) => void;
302
  starLoad: StarredLoad;
303
  starred: Starred;
304
  busy: boolean;
 
320
  // storage can be blocked; the toggle still works for this session
321
  }
322
  }, [layout]);
323
+ const [filter, setFilter] = useState<HomeFilter>(() =>
324
+ parseHomeFilter(initialStarredOnly ? "starred" : "all"));
325
+ useEffect(() => {
326
+ setFilter(parseHomeFilter(initialStarredOnly ? "starred" : "all"));
327
+ }, [initialStarredOnly]);
328
 
329
  // ⚠ THE CLOCK IS READ ONCE, HERE, AND HANDED IN AS A NUMBER. `homeModel` stays pure so a gate
330
  // can assert the ordering rather than whatever today happens to be.
 
342
  const known = starLoad.phase === "ready";
343
  const dbStarred = new Set(starred.databases);
344
  const agentStarred = new Set(starred.agents);
345
+ const visibleDatabases = applyHomeFilter(
346
+ databases,
347
+ filter,
348
+ (database) => dbStarred.has(database.key),
349
+ );
350
+ const visibleAutomations = applyHomeFilter(
351
+ automations,
352
+ filter,
353
+ (automation) => agentStarred.has(automation.id),
354
+ );
355
+ const visibleApplications = applyHomeFilter(
356
+ applications,
357
+ mode === "app" ? "all" : filter,
358
+ (application) => application.starred === true,
359
+ );
360
 
361
  // ⭐ WAVE 35 Β· W35-T16 (owner item 9) β€” the starred VIEWS, resolved by the SAME function
362
  // Starred uses. Item 9 asks for these views on Home and under Starred; running them through one
 
365
  // β›” AND THE DROP RULE COMES WITH IT: `shapeStarred` refuses a view whose database is not in
366
  // `entries`, so a star that outlived its database (deleted, or a grant revoked) draws NOTHING
367
  // rather than a tile that lands the reader in a 403.
368
+ const starredRows = shapeStarred(starred, entries, automations);
369
+ const starredViews = starredRows.views;
370
+ const starredQueries = starredRows.queries;
371
+ const starredOnly = mode === "home" && filter === "starred";
372
 
373
  return (
374
  <div className="shell-home">
375
+ <div className="home-page-head">
376
+ <h1 className="home-title">{mode === "app" ? "App" : "Home"}</h1>
377
+ {mode === "app" ? (
378
+ <button type="button" className="home-app-create" onClick={onTemplates}>
379
+ Create new
380
+ </button>
381
+ ) : null}
382
+ </div>
383
 
384
+ {mode === "home" ? <div className="home-cards">
385
  {/* ⚠ THE DETAIL LINES ARE BYTE-IDENTICAL TO THE DIALOG'S ROWS, and that is deliberate
386
  rather than lazy. Each of these cards opens the same door as a row in the
387
  New-database dialog, and the first draft described the same two things in four
 
428
  detail="Browse the connectors this workspace can use."
429
  onClick={onConnectors}
430
  />
431
+ </div> : null}
432
 
433
  <div className="home-recents-bar">
434
  {/* The reference puts an "Opened anytime" filter here. We do not have one and do not
 
455
  >
456
  <GridIcon />
457
  </button>
458
+ {mode === "home" ? (
459
+ <button
460
+ type="button"
461
+ className={"home-layout-btn home-starred-filter" + (starredOnly ? " is-on" : "")}
462
+ aria-pressed={starredOnly}
463
+ aria-label="Starred only"
464
+ title="Starred only"
465
+ disabled={!known}
466
+ onClick={() => setFilter(starredOnly ? "all" : "starred")}
467
+ >
468
+ <StarIcon size={14} filled={starredOnly} />
469
+ <span>Starred only</span>
470
+ </button>
471
+ ) : null}
472
  </div>
473
  </div>
474
 
475
+ {mode === "home" && !starredOnly && databases.length === 0 ? (
476
  // β›” ONE LINE, AND IT NAMES THE DOOR THAT FILLS IT (DESIGN.md 4 / R13). This is also
477
  // where wave 18's tenant hero went: a workspace with no databases lands here, and the
478
  // cards above ARE the "create your first database" affordance the hero carried. Two
 
481
  // described a state that can no longer exist β€” every granted database is drawn whether it
482
  // has been opened or not, so an empty list now means exactly one thing.
483
  <p className="home-empty">
484
+ This workspace has no databases yet. Create one above, or connect a source.
485
  </p>
486
+ ) : mode === "home" && visibleDatabases.length ? (
487
+ [{ id: "databases", title: "Databases", tiles: visibleDatabases }].map((section) => (
488
  <section key={section.id} className="home-section">
489
  <h2 className="home-section-title">{section.title}</h2>
490
  <div className={"home-tiles is-" + layout}>
 
555
  </div>
556
  </section>
557
  ))
558
+ ) : null}
559
+ {mode === "home" && !starredOnly && folders.length > 0 && <section className="home-section"><h2 className="home-section-title">Folders</h2><div className={"home-tiles is-" + layout}>{folders.map((folder) => { const count = Object.values(folderPlacement).filter((id) => id === folder.id).length; return <a className="home-tile" href={`#/data?folder=${encodeURIComponent(folder.id)}`} key={folder.id}><span className="home-tile-chip home-folder-glyph" aria-hidden><FolderMark size={16} /></span><span className="home-tile-text"><span className="home-tile-name">{folder.name}</span><span className="home-tile-ago">{count} database{count === 1 ? "" : "s"}</span></span></a>; })}</div></section>}
560
+ {applicationsError ? (
561
+ <p className="home-app-note" role="alert">{applicationsError}</p>
562
+ ) : null}
563
+ {visibleApplications.length > 0 ? (
564
+ <section className="home-section">
565
+ <h2 className="home-section-title">Applications</h2>
566
+ <div className={"home-tiles is-" + layout}>
567
+ {visibleApplications.map((application) => {
568
+ const database = application.openTarget?.database
569
+ ?? application.compatibleDatabases?.[0]
570
+ ?? "";
571
+ const kind = application.templateKind === "catalog"
572
+ ? "Catalog"
573
+ : application.templateKind === "route"
574
+ ? "Routing"
575
+ : application.type.slice(0, 1).toUpperCase() + application.type.slice(1);
576
+ return (
577
+ <div className="st-tilewrap" key={application.id}>
578
+ <a
579
+ className="home-tile"
580
+ href={database
581
+ ? "#/data?database=" + encodeURIComponent(database)
582
+ + "&application=" + encodeURIComponent(application.id)
583
+ : "#/app"}
584
+ >
585
+ <span className="home-tile-chip home-app-glyph" aria-hidden="true">
586
+ <ApplicationIcon />
587
+ </span>
588
+ <span className="home-tile-text">
589
+ <span className="home-tile-name">{application.name}</span>
590
+ <span className="home-tile-ago">{kind}</span>
591
+ </span>
592
+ </a>
593
+ {application.capabilities?.star !== false ? (
594
+ <StarButton
595
+ on={application.starred === true}
596
+ label={application.name}
597
+ busy={applicationBusy.has(application.id)}
598
+ onToggle={() => onToggleApplication(application, application.starred !== true)}
599
+ />
600
+ ) : null}
601
+ </div>
602
+ );
603
+ })}
604
+ </div>
605
+ </section>
606
+ ) : mode === "app" && applicationsKnown && !applicationsError ? (
607
+ <p className="home-empty">No applications yet. Create one to add it here.</p>
608
+ ) : mode === "app" && !applicationsKnown ? (
609
+ <div className="st-loading">
610
+ <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading applications" />
611
+ </div>
612
+ ) : null}
613
 
614
  {/* ⭐ WAVE 24 item 13 (R10) β€” THE AUTOMATIONS SECTION.
615
  Same tiles, same rhythm.
 
633
  turns a 403 into `[]`) β€” and a heading over nothing says "there should be something
634
  here", which is a different and false statement. */}
635
  {automations.length ? (
636
+ mode === "home" && visibleAutomations.length ? (
637
  <section className="home-section">
638
  {/* β›” W34-T40's `done-when` names FOUR surfaces that must read Agents, and this was the
639
  one that did not: a hardcoded `"Automations"` that never consulted the module label.
 
645
  here would have left the next rename in exactly the same trap. */}
646
  <h2 className="home-section-title">{AGENTS_MODULE_LABEL}</h2>
647
  <div className={"home-tiles is-" + layout}>
648
+ {visibleAutomations.map((a) => (
649
  <div key={a.id} className="st-tilewrap">
650
  <button
651
  type="button"
 
676
  ))}
677
  </div>
678
  </section>
679
+ ) : null
680
  ) : null}
681
 
682
  {/* ⭐ WAVE 35 Β· W35-T16 (owner item 9) β€” THE STARRED VIEWS.
 
691
  ⚠ EMPTY RENDERS NOTHING, like every other section here: no starred views is a real
692
  answer, and a heading over nothing says "there should be something here", which is a
693
  different and false statement. */}
694
+ {mode === "home" && starredViews.length ? (
695
  <section className="home-section">
696
  <h2 className="home-section-title">Starred views</h2>
697
  <div className={"home-tiles is-" + layout}>
 
716
  </div>
717
  </section>
718
  ) : null}
719
+ {starredOnly && starredQueries.length ? (
720
+ <section className="home-section">
721
+ <h2 className="home-section-title">Starred queries</h2>
722
+ <div className={"home-tiles is-" + layout}>
723
+ {starredQueries.map((row) => (
724
+ <Tile
725
+ key={row.id}
726
+ row={row}
727
+ glyph={<QueryIcon />}
728
+ star={
729
+ known ? (
730
+ <StarButton
731
+ on
732
+ label={row.label}
733
+ busy={busy}
734
+ onToggle={() => toggle("query", row.id, false)}
735
+ />
736
+ ) : undefined
737
+ }
738
+ onOpen={() => onOpenQuery(row.id)}
739
+ />
740
+ ))}
741
+ </div>
742
+ </section>
743
+ ) : null}
744
+ {known
745
+ && applicationsKnown
746
+ && !applicationsError
747
+ && starredOnly
748
+ && visibleDatabases.length === 0
749
+ && visibleAutomations.length === 0
750
+ && visibleApplications.length === 0
751
+ && starredViews.length === 0
752
+ && starredQueries.length === 0 ? (
753
+ <p className="home-empty">Nothing starred yet.</p>
754
+ ) : null}
755
  </div>
756
  );
757
  }
 
769
  */
770
  export default function HomePage(props: HomeProps) {
771
  const { load: starLoad, starred, busy, counts, toggle } = useStarred();
772
+ const [applications, setApplications] = useState<ApplicationTile[]>([]);
773
+ const [applicationsKnown, setApplicationsKnown] = useState(false);
774
+ const [applicationsError, setApplicationsError] = useState("");
775
+ const [applicationBusy, setApplicationBusy] = useState<Set<string>>(() => new Set());
776
+ useEffect(() => {
777
+ const controller = new AbortController();
778
+ void fetch(`${API_V1}/applications`, {
779
+ credentials: CREDENTIALS,
780
+ signal: controller.signal,
781
+ })
782
+ .then(async (response) => {
783
+ if (!response.ok) throw new Error("application_list_failed");
784
+ return response.json();
785
+ })
786
+ .then((body) => {
787
+ if (!controller.signal.aborted) {
788
+ setApplications(Array.isArray(body?.applications) ? body.applications : []);
789
+ setApplicationsKnown(true);
790
+ }
791
+ })
792
+ .catch(() => {
793
+ if (!controller.signal.aborted) {
794
+ setApplicationsKnown(true);
795
+ setApplicationsError("Applications could not be loaded. Reload to retry.");
796
+ }
797
+ });
798
+ return () => controller.abort();
799
+ }, []);
800
+
801
+ const toggleApplication = (application: ApplicationTile, on: boolean) => {
802
+ if (applicationBusy.has(application.id)) return;
803
+ setApplicationsError("");
804
+ setApplicationBusy((current) => new Set(current).add(application.id));
805
+ void fetch(`${API_V1}/applications/${encodeURIComponent(application.id)}`, {
806
+ method: "PATCH",
807
+ credentials: CREDENTIALS,
808
+ headers: { "Content-Type": "application/json" },
809
+ body: JSON.stringify({ starred: on }),
810
+ })
811
+ .then(async (response) => {
812
+ if (!response.ok) throw new Error("application_star_failed");
813
+ const body = await response.json();
814
+ return body?.application as ApplicationTile | undefined;
815
+ })
816
+ .then((landed) => {
817
+ if (!landed) return;
818
+ setApplications((current) => current.map((row) => row.id === landed.id ? landed : row));
819
+ })
820
+ .catch(() => {
821
+ setApplicationsError("The Application could not be updated. Try again.");
822
+ })
823
+ .finally(() => {
824
+ setApplicationBusy((current) => {
825
+ const next = new Set(current);
826
+ next.delete(application.id);
827
+ return next;
828
+ });
829
+ });
830
+ };
831
  return (
832
  <HomeSurface
833
  {...props}
 
837
  counts={counts}
838
  toggle={toggle}
839
  applications={applications}
840
+ applicationsKnown={applicationsKnown}
841
+ applicationsError={applicationsError}
842
+ applicationBusy={applicationBusy}
843
+ onToggleApplication={toggleApplication}
844
  />
845
  );
846
  }
web/src/home/homeModel.ts CHANGED
@@ -210,3 +210,21 @@ export const HOME_LAYOUT_KEY = "aios-home-layout";
210
  export function parseLayout(raw: unknown): HomeLayout {
211
  return raw === "list" ? "list" : "grid";
212
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  export function parseLayout(raw: unknown): HomeLayout {
211
  return raw === "list" ? "list" : "grid";
212
  }
213
+
214
+ // ── WAVE 55: Home's starred-only filter ───────────────────────────────────────────────────
215
+
216
+ export type HomeFilter = "all" | "starred";
217
+
218
+ /** An old `#/starred` bookmark is rewritten to Home with this query value. */
219
+ export function parseHomeFilter(raw: unknown): HomeFilter {
220
+ return raw === "starred" ? "starred" : "all";
221
+ }
222
+
223
+ /** One pure filter for every Home tile species, so the toggle cannot mean different things. */
224
+ export function applyHomeFilter<T>(
225
+ rows: T[],
226
+ filter: HomeFilter,
227
+ isStarred: (row: T) => boolean,
228
+ ): T[] {
229
+ return filter === "starred" ? rows.filter(isStarred) : rows;
230
+ }
web/src/sheet/BindingEditor.tsx CHANGED
@@ -51,6 +51,7 @@ import { countConditions, isNumericType } from "../filter-kit/ops";
51
  import { SheetFilterPopup } from "../filter-kit/SheetFilterPopup";
52
  import { useEscapeClose } from "../ui/useEscapeClose";
53
  import { previewCell } from "./sheetApi";
 
54
 
55
  const AGGREGATES = [
56
  { fn: "sum", label: "Sum" },
@@ -928,6 +929,8 @@ export default function BindingEditor({
928
  * column this database cannot total still shows its own name beside the notice that says so.
929
  * That is the same three-state rule `customer-grid/FieldSelect.tsx` documents at its head. */
930
  const chosenField = useMemo(() => fields.find((f) => f.key === field), [fields, field]);
 
 
931
 
932
  /** The database's own label, which the column list's heading names. Two databases can both
933
  * carry a column called "Total", and the heading is where that ambiguity is answered. */
@@ -943,6 +946,10 @@ export default function BindingEditor({
943
  const adopted = (initial?.scope as Record<string, unknown> | undefined)?.adoptedFrom;
944
  if (scopeKind === "filter" && adopted) scope.adoptedFrom = adopted;
945
  const out: Record<string, unknown> = { database, aggregate: agg, scope };
 
 
 
 
946
  // C2's period, spelled the contract's way. R14: a period SOURCE is a `$`-anchored cell
947
  // reference; the A1 resolver reads it BEFORE the query is built, so it is an INPUT to the
948
  // filter and never a post-filter. It rides ALONGSIDE the unit and the start rather than
@@ -952,14 +959,18 @@ export default function BindingEditor({
952
  // stamped to this month's default, and turning the switch off drops the key rather than writing
953
  // an empty period the server would have to guess about.
954
  if (periodOn) {
955
- const period: Record<string, unknown> = { unit, start, locked };
 
 
956
  if (refOpen && periodRef.trim()) period.ref = periodRef.trim();
957
  out.period = period;
958
  }
959
- out.onDrag = { across, down: downField ? { field: downField } : "none" };
 
 
960
  return out;
961
  }, [database, fn, field, scopeKind, viewId, views, tree, initial,
962
- unit, start, locked, refOpen, periodRef, periodOn, across, downField]);
963
 
964
  // ⭐ THE NUMBER APPEARS BEFORE SAVING. `preview` evaluates the binding without persisting it,
965
  // which is what lets someone see whether they picked the right thing while they can still change
@@ -1294,24 +1305,34 @@ export default function BindingEditor({
1294
 
1295
  {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the
1296
  sentence under it says what each one costs when the cell is copied. */}
1297
- <div className="sheet-period-lock">
1298
- <button
1299
- type="button"
1300
- role="switch"
1301
- aria-checked={locked}
1302
- className={"sheet-lock-toggle" + (locked ? " is-on" : "")}
1303
- onClick={() => setLocked((v) => !v)}
1304
- >
1305
- <span className="sheet-lock-dot" aria-hidden />
1306
- <span>Lock this period</span>
1307
- </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
1308
  <p className="sheet-period-note">
1309
- {locked
1310
- ? "Locked, so any copy of this cell keeps this period."
1311
- : `Not locked, so copying right or left moves the period by one ${UNIT_NOUN[unit]} `
1312
- + "per column, and copying up or down keeps it."}
1313
  </p>
1314
- </div>
1315
 
1316
  {/* ⭐ "Use a cell" STAYS A LINK (R9). It reveals the A1 input rather than replacing the
1317
  picker, so the ordinary reader never meets a cell reference and the person who wants
@@ -1342,39 +1363,60 @@ export default function BindingEditor({
1342
 
1343
  {/* ══ R10: THE DRAG RULES ═════════════════════════════════════════════════════════════ */}
1344
  <fieldset className="sheet-scope sheet-drag">
1345
- <legend>When dragged</legend>
1346
 
1347
- <label className="sheet-field">
1348
- <span>Across</span>
1349
- <select
1350
- value={across}
1351
- aria-label="When dragged across columns"
1352
- onChange={(e) => setAcross(e.target.value === "none" ? "none" : "period")}
1353
- >
1354
- <option value="period">Period</option>
1355
- <option value="none">Nothing</option>
1356
- </select>
1357
- </label>
1358
-
1359
- <label className="sheet-field">
1360
- <span>Down</span>
1361
- <select
1362
- value={downField}
1363
- aria-label="When dragged down rows"
1364
- onChange={(e) => setDownField(e.target.value)}
1365
- >
1366
- <option value="">Nothing</option>
1367
- {dragDownFields.map((f) => (
1368
- <option key={f.key} value={f.key}>{`Next value of ${f.label}`}</option>
1369
- ))}
1370
- </select>
1371
- </label>
1372
-
1373
- {dragDownFields.length === 0 && (
1374
- <p className="sheet-period-note">
1375
- This database has no single select or link column to walk, so dragging down repeats
1376
- the same rows.
1377
- </p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1378
  )}
1379
  </fieldset>
1380
 
 
51
  import { SheetFilterPopup } from "../filter-kit/SheetFilterPopup";
52
  import { useEscapeClose } from "../ui/useEscapeClose";
53
  import { previewCell } from "./sheetApi";
54
+ import { bindingDisplay } from "./types";
55
 
56
  const AGGREGATES = [
57
  { fn: "sum", label: "Sum" },
 
929
  * column this database cannot total still shows its own name beside the notice that says so.
930
  * That is the same three-state rule `customer-grid/FieldSelect.tsx` documents at its head. */
931
  const chosenField = useMemo(() => fields.find((f) => f.key === field), [fields, field]);
932
+ /** Metric columns step their period; every other aggregate steps one chosen filter driver. */
933
+ const chosenIsMetric = Boolean(chosenField && isMetricField(chosenField));
934
 
935
  /** The database's own label, which the column list's heading names. Two databases can both
936
  * carry a column called "Total", and the heading is where that ambiguity is answered. */
 
946
  const adopted = (initial?.scope as Record<string, unknown> | undefined)?.adoptedFrom;
947
  if (scopeKind === "filter" && adopted) scope.adoptedFrom = adopted;
948
  const out: Record<string, unknown> = { database, aggregate: agg, scope };
949
+ // W55-T07 / R6: re-saving what this cell points at must not reset how its View drawer opens.
950
+ // The display bag belongs to this binding, not to the saved View and not to localStorage.
951
+ const display = bindingDisplay(initial);
952
+ if (display) out.display = display;
953
  // C2's period, spelled the contract's way. R14: a period SOURCE is a `$`-anchored cell
954
  // reference; the A1 resolver reads it BEFORE the query is built, so it is an INPUT to the
955
  // filter and never a post-filter. It rides ALONGSIDE the unit and the start rather than
 
959
  // stamped to this month's default, and turning the switch off drops the key rather than writing
960
  // an empty period the server would have to guess about.
961
  if (periodOn) {
962
+ const period: Record<string, unknown> = {
963
+ unit, start, locked: chosenIsMetric ? locked : true,
964
+ };
965
  if (refOpen && periodRef.trim()) period.ref = periodRef.trim();
966
  out.period = period;
967
  }
968
+ out.onDrag = chosenIsMetric
969
+ ? { across: periodOn && !locked ? across : "none", down: "none" }
970
+ : { across: "none", down: downField ? { field: downField } : "none" };
971
  return out;
972
  }, [database, fn, field, scopeKind, viewId, views, tree, initial,
973
+ unit, start, locked, refOpen, periodRef, periodOn, across, downField, chosenIsMetric]);
974
 
975
  // ⭐ THE NUMBER APPEARS BEFORE SAVING. `preview` evaluates the binding without persisting it,
976
  // which is what lets someone see whether they picked the right thing while they can still change
 
1305
 
1306
  {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the
1307
  sentence under it says what each one costs when the cell is copied. */}
1308
+ {chosenIsMetric ? (
1309
+ <div className="sheet-period-lock">
1310
+ <button
1311
+ type="button"
1312
+ role="switch"
1313
+ aria-checked={locked}
1314
+ className={"sheet-lock-toggle" + (locked ? " is-on" : "")}
1315
+ onClick={() => {
1316
+ const next = !locked;
1317
+ setLocked(next);
1318
+ setAcross(next ? "none" : "period");
1319
+ }}
1320
+ >
1321
+ <span className="sheet-lock-dot" aria-hidden />
1322
+ <span>Lock this period</span>
1323
+ </button>
1324
+ <p className="sheet-period-note">
1325
+ {locked
1326
+ ? "Locked, so any copy of this cell keeps this period."
1327
+ : `Not locked, so a stepped copy moves by one ${UNIT_NOUN[unit]} per cell. `
1328
+ + "Right and down move forward. Left and up move backward."}
1329
+ </p>
1330
+ </div>
1331
+ ) : (
1332
  <p className="sheet-period-note">
1333
+ This period stays fixed when copied. The filter driver below is what changes.
 
 
 
1334
  </p>
1335
+ )}
1336
 
1337
  {/* ⭐ "Use a cell" STAYS A LINK (R9). It reveals the A1 input rather than replacing the
1338
  picker, so the ordinary reader never meets a cell reference and the person who wants
 
1363
 
1364
  {/* ══ R10: THE DRAG RULES ═════════════════════════════════════════════════════════════ */}
1365
  <fieldset className="sheet-scope sheet-drag">
1366
+ <legend>When copied</legend>
1367
 
1368
+ {chosenIsMetric ? (
1369
+ periodOn ? (
1370
+ <>
1371
+ <label className="sheet-field">
1372
+ <span>Period</span>
1373
+ <select
1374
+ value={!locked && across === "period" ? "period" : "none"}
1375
+ aria-label="Period step when copied"
1376
+ onChange={(e) => {
1377
+ const step = e.target.value === "period";
1378
+ setAcross(step ? "period" : "none");
1379
+ setLocked(!step);
1380
+ }}
1381
+ >
1382
+ <option value="period">{`Step by ${UNIT_NOUN[unit]}`}</option>
1383
+ <option value="none">Keep this period</option>
1384
+ </select>
1385
+ </label>
1386
+ <p className="sheet-period-note">
1387
+ Right and down move forward. Left and up move backward.
1388
+ </p>
1389
+ </>
1390
+ ) : (
1391
+ <p className="sheet-period-note">
1392
+ This metric is all time, so copied cells keep the same all-time period.
1393
+ </p>
1394
+ )
1395
+ ) : (
1396
+ <>
1397
+ <label className="sheet-field">
1398
+ <span>Filter driver</span>
1399
+ <select
1400
+ value={downField}
1401
+ aria-label="Filter driver when copied"
1402
+ onChange={(e) => setDownField(e.target.value)}
1403
+ >
1404
+ <option value="">Keep this filter</option>
1405
+ {dragDownFields.map((f) => (
1406
+ <option key={f.key} value={f.key}>{`Step by ${f.label}`}</option>
1407
+ ))}
1408
+ </select>
1409
+ </label>
1410
+ {dragDownFields.length === 0 ? (
1411
+ <p className="sheet-period-note">
1412
+ This database has no single select or link field with ordered options.
1413
+ </p>
1414
+ ) : (
1415
+ <p className="sheet-period-note">
1416
+ Right and down choose later options. Left and up choose earlier options.
1417
+ </p>
1418
+ )}
1419
+ </>
1420
  )}
1421
  </fieldset>
1422
 
web/src/sheet/ChartDialog.tsx CHANGED
@@ -48,14 +48,10 @@ import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
48
  // The document's own addresser, in SHEET coordinates. A second spelling of A1 in this file would
49
  // be a second answer to a question the document already answers.
50
  import { addressOf } from "./sheetState";
51
- import type { Cell, SheetChartSpec } from "./types";
 
52
 
53
- export interface ChartRange {
54
- col0: number;
55
- row0: number;
56
- col1: number;
57
- row1: number;
58
- }
59
 
60
  /**
61
  * ⭐ THE EIGHT KINDS THE DOCUMENT CARRIES. `types.ts::SheetChartSpec` declares all eight and
@@ -173,6 +169,13 @@ export function chartRangeOf(sel: ChartRange | null): ChartRange {
173
  return { col0, row0, col1: col0 + CHART_COLS - 1, row1: row0 + CHART_ROWS - 1 };
174
  }
175
 
 
 
 
 
 
 
 
176
  /** Where a database block lands: the selection's top left, or A1 when there is no selection. */
177
  export function landingOf(sel: ChartRange | null): { col: number; row: number } {
178
  if (!sel) return { col: 0, row: 0 };
@@ -309,27 +312,43 @@ const SOURCE_TABS: { id: SourceTab; label: string }[] = [
309
  export interface ChartDialogProps {
310
  /** The current selection, in SHEET coordinates, or null when there is none. */
311
  selection: ChartRange | null;
312
- /** Escape, an outside pointerdown, the close mark, or Cancel. All the same event. */
 
 
313
  onClose: () => void;
314
  /**
315
  * The one door out. `cells` is present only on the database tab, and the caller commits it in a
316
  * single call so the block, the chart and the refresh are one step.
317
  */
318
- onCreate: (
319
  kind: SheetChartSpec["kind"],
320
  range: ChartRange,
321
  cells?: Record<string, Cell>,
322
  ) => void;
 
 
 
 
323
  }
324
 
325
- export default function ChartDialog({ selection, onClose, onCreate }: ChartDialogProps) {
 
 
 
 
 
 
 
326
  const panelRef = useRef<HTMLDivElement>(null);
327
  const titleId = useId();
 
 
328
 
329
  const [tab, setTab] = useState<SourceTab>("range");
330
- const [kind, setKind] = useState<SheetChartSpec["kind"]>("bar");
 
331
  const [databases, setDatabases] = useState<{ key: string; label: string }[]>([]);
332
- const [loading, setLoading] = useState(true);
333
  const [database, setDatabase] = useState("");
334
  const [fn, setFn] = useState("count");
335
  const [field, setField] = useState("");
@@ -343,9 +362,10 @@ export default function ChartDialog({ selection, onClose, onCreate }: ChartDialo
343
  useOverlayLayer({
344
  panelRef,
345
  onDismiss: onClose,
346
- dismissOnOutside: true,
 
347
  initialFocus: "first",
348
- restoreFocus: false,
349
  trapFocus: true,
350
  });
351
 
@@ -356,6 +376,7 @@ export default function ChartDialog({ selection, onClose, onCreate }: ChartDialo
356
  * dialog is not.
357
  */
358
  useEffect(() => {
 
359
  let live = true;
360
  (async () => {
361
  try {
@@ -375,20 +396,23 @@ export default function ChartDialog({ selection, onClose, onCreate }: ChartDialo
375
  }
376
  })();
377
  return () => { live = false; };
378
- }, []);
379
 
380
- const range = useMemo(() => chartRangeOf(selection), [selection]);
381
- const rangeSentence = `The chart will cover ${addressOf(range.col0, range.row0)} to `
382
- + `${addressOf(range.col1, range.row1)}.`;
383
 
384
  const wantsField = fn !== "count";
385
  const ready = tab === "range"
386
- ? true
387
  : Boolean(database) && (!wantsField || field.trim().length > 0);
388
 
389
  const create = () => {
 
 
 
 
 
390
  if (tab === "range") {
391
- onCreate(kind, range);
392
  return;
393
  }
394
  if (!ready) return;
@@ -400,9 +424,29 @@ export default function ChartDialog({ selection, onClose, onCreate }: ChartDialo
400
  unit,
401
  periods: Number(periods),
402
  });
403
- onCreate(kind, plan.range, plan.cells);
404
  };
405
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
  const kindPicker = (
407
  <div className="sheet-chart-gallery" role="group" aria-label="Chart type">
408
  {CHART_KINDS.map((entry) => (
@@ -435,7 +479,9 @@ export default function ChartDialog({ selection, onClose, onCreate }: ChartDialo
435
  data-overlay-kind="sheet-chart"
436
  >
437
  <div className="lp-dialog-head">
438
- <h2 className="lp-dialog-title" id={titleId}>Insert a chart</h2>
 
 
439
  <button
440
  type="button"
441
  className="lp-dialog-x"
@@ -453,32 +499,34 @@ export default function ChartDialog({ selection, onClose, onCreate }: ChartDialo
453
  </button>
454
  </div>
455
 
456
- <div className="sheet-chart-tabs" role="tablist" aria-label="What the chart reads">
457
- {SOURCE_TABS.map((entry) => (
458
- <button
459
- key={entry.id}
460
- type="button"
461
- role="tab"
462
- id={`${titleId}-tab-${entry.id}`}
463
- className="sheet-chart-tab"
464
- aria-selected={tab === entry.id}
465
- aria-controls={`${titleId}-panel`}
466
- onClick={() => setTab(entry.id)}
467
- >
468
- {entry.label}
469
- </button>
470
- ))}
471
- </div>
 
 
472
 
473
  <div
474
  className="sheet-chart-panel"
475
  id={`${titleId}-panel`}
476
  role="tabpanel"
477
- aria-labelledby={`${titleId}-tab-${tab}`}
478
  >
479
  {tab === "range" ? (
480
  <>
481
- <p className="sheet-chart-caption">{rangeSentence}</p>
482
  {kindPicker}
483
  </>
484
  ) : (
@@ -583,7 +631,7 @@ export default function ChartDialog({ selection, onClose, onCreate }: ChartDialo
583
  disabled={!ready}
584
  onClick={create}
585
  >
586
- Insert chart
587
  </button>
588
  </div>
589
  </div>
 
48
  // The document's own addresser, in SHEET coordinates. A second spelling of A1 in this file would
49
  // be a second answer to a question the document already answers.
50
  import { addressOf } from "./sheetState";
51
+ import { parseRange } from "./rules";
52
+ import type { Cell, SheetChartRange, SheetChartSpec } from "./types";
53
 
54
+ export type ChartRange = SheetChartRange;
 
 
 
 
 
55
 
56
  /**
57
  * ⭐ THE EIGHT KINDS THE DOCUMENT CARRIES. `types.ts::SheetChartSpec` declares all eight and
 
169
  return { col0, row0, col1: col0 + CHART_COLS - 1, row1: row0 + CHART_ROWS - 1 };
170
  }
171
 
172
+ /** A chart range as one editable A1 expression. */
173
+ export function chartRangeText(range: ChartRange): string {
174
+ const first = addressOf(Math.min(range.col0, range.col1), Math.min(range.row0, range.row1));
175
+ const last = addressOf(Math.max(range.col0, range.col1), Math.max(range.row0, range.row1));
176
+ return first === last ? first : `${first}:${last}`;
177
+ }
178
+
179
  /** Where a database block lands: the selection's top left, or A1 when there is no selection. */
180
  export function landingOf(sel: ChartRange | null): { col: number; row: number } {
181
  if (!sel) return { col: 0, row: 0 };
 
312
  export interface ChartDialogProps {
313
  /** The current selection, in SHEET coordinates, or null when there is none. */
314
  selection: ChartRange | null;
315
+ /** Present when this is the same dialog reopened for an existing chart. */
316
+ chart?: SheetChartSpec;
317
+ /** Escape, the close mark, or Cancel. All converge on the same event. */
318
  onClose: () => void;
319
  /**
320
  * The one door out. `cells` is present only on the database tab, and the caller commits it in a
321
  * single call so the block, the chart and the refresh are one step.
322
  */
323
+ onCreate?: (
324
  kind: SheetChartSpec["kind"],
325
  range: ChartRange,
326
  cells?: Record<string, Cell>,
327
  ) => void;
328
+ /** The existing chart's one persisted settings write. */
329
+ onUpdate?: (chart: SheetChartSpec) => void;
330
+ /** Ribbon openers restore themselves; a chart settings button delegates restoration here. */
331
+ restoreFocus?: boolean;
332
  }
333
 
334
+ export default function ChartDialog({
335
+ selection,
336
+ chart,
337
+ onClose,
338
+ onCreate,
339
+ onUpdate,
340
+ restoreFocus = false,
341
+ }: ChartDialogProps) {
342
  const panelRef = useRef<HTMLDivElement>(null);
343
  const titleId = useId();
344
+ const editing = chart !== undefined;
345
+ const seedRange = chart?.range ?? chartRangeOf(selection);
346
 
347
  const [tab, setTab] = useState<SourceTab>("range");
348
+ const [kind, setKind] = useState<SheetChartSpec["kind"]>(chart?.kind ?? "bar");
349
+ const [rangeDraft, setRangeDraft] = useState(() => chartRangeText(seedRange));
350
  const [databases, setDatabases] = useState<{ key: string; label: string }[]>([]);
351
+ const [loading, setLoading] = useState(!editing);
352
  const [database, setDatabase] = useState("");
353
  const [fn, setFn] = useState("count");
354
  const [field, setField] = useState("");
 
362
  useOverlayLayer({
363
  panelRef,
364
  onDismiss: onClose,
365
+ // This is a modal settings surface. A stray click must not discard a half-edited range.
366
+ dismissOnOutside: false,
367
  initialFocus: "first",
368
+ restoreFocus,
369
  trapFocus: true,
370
  });
371
 
 
376
  * dialog is not.
377
  */
378
  useEffect(() => {
379
+ if (editing) return undefined;
380
  let live = true;
381
  (async () => {
382
  try {
 
396
  }
397
  })();
398
  return () => { live = false; };
399
+ }, [editing]);
400
 
401
+ const range = useMemo(() => parseRange(rangeDraft), [rangeDraft]);
 
 
402
 
403
  const wantsField = fn !== "count";
404
  const ready = tab === "range"
405
+ ? range !== null
406
  : Boolean(database) && (!wantsField || field.trim().length > 0);
407
 
408
  const create = () => {
409
+ if (editing) {
410
+ if (!range || !chart || !onUpdate) return;
411
+ onUpdate({ ...chart, kind, range });
412
+ return;
413
+ }
414
  if (tab === "range") {
415
+ if (range) onCreate?.(kind, range);
416
  return;
417
  }
418
  if (!ready) return;
 
424
  unit,
425
  periods: Number(periods),
426
  });
427
+ onCreate?.(kind, plan.range, plan.cells);
428
  };
429
 
430
+ const rangeField = (
431
+ <div className="sheet-chart-fields">
432
+ <label className="sheet-chart-label" htmlFor={`${titleId}-range`}>Cell range</label>
433
+ <input
434
+ id={`${titleId}-range`}
435
+ className="sheet-chart-text"
436
+ type="text"
437
+ value={rangeDraft}
438
+ aria-invalid={range === null}
439
+ aria-describedby={range === null ? `${titleId}-range-error` : undefined}
440
+ onChange={(event) => setRangeDraft(event.target.value)}
441
+ />
442
+ {range === null ? (
443
+ <p className="sheet-chart-caption" id={`${titleId}-range-error`} role="alert">
444
+ Enter a cell range such as B2:E8.
445
+ </p>
446
+ ) : null}
447
+ </div>
448
+ );
449
+
450
  const kindPicker = (
451
  <div className="sheet-chart-gallery" role="group" aria-label="Chart type">
452
  {CHART_KINDS.map((entry) => (
 
479
  data-overlay-kind="sheet-chart"
480
  >
481
  <div className="lp-dialog-head">
482
+ <h2 className="lp-dialog-title" id={titleId}>
483
+ {editing ? "Chart settings" : "Insert a chart"}
484
+ </h2>
485
  <button
486
  type="button"
487
  className="lp-dialog-x"
 
499
  </button>
500
  </div>
501
 
502
+ {!editing ? (
503
+ <div className="sheet-chart-tabs" role="tablist" aria-label="What the chart reads">
504
+ {SOURCE_TABS.map((entry) => (
505
+ <button
506
+ key={entry.id}
507
+ type="button"
508
+ role="tab"
509
+ id={`${titleId}-tab-${entry.id}`}
510
+ className="sheet-chart-tab"
511
+ aria-selected={tab === entry.id}
512
+ aria-controls={`${titleId}-panel`}
513
+ onClick={() => setTab(entry.id)}
514
+ >
515
+ {entry.label}
516
+ </button>
517
+ ))}
518
+ </div>
519
+ ) : null}
520
 
521
  <div
522
  className="sheet-chart-panel"
523
  id={`${titleId}-panel`}
524
  role="tabpanel"
525
+ aria-labelledby={editing ? titleId : `${titleId}-tab-${tab}`}
526
  >
527
  {tab === "range" ? (
528
  <>
529
+ {rangeField}
530
  {kindPicker}
531
  </>
532
  ) : (
 
631
  disabled={!ready}
632
  onClick={create}
633
  >
634
+ {editing ? "Save chart" : "Insert chart"}
635
  </button>
636
  </div>
637
  </div>
web/src/sheet/DrillModal.tsx CHANGED
@@ -38,8 +38,9 @@
38
  // when we click 'View row' so its easy for user also to know what this filter is. In fact, they
39
  // should be able to change the filter there too. And if they make a mistake etc, they can just
40
  // CTRL + Z to return the Cell to its original filter."* Three clauses, and each one is a decision
41
- // recorded beside the code that answers it: the BAND (`DrillFilterBand`) states it, the shared
42
- // `SheetFilterDialog` edits it, and one cell-scoped step of undo takes it back.
 
43
  //
44
  // β›”β›” THE BAND IS PORTALLED INTO `LinkGridModal`'s OWN CARD, WHICH LOOKS LIKE A LIBERTY AND IS
45
  // THE CONSERVATIVE CHOICE. `LinkGridModal` has no slot for extra chrome and it is not this lane's
@@ -59,19 +60,25 @@
59
  // same chunk is in hand, so the stylesheet is guaranteed present. Same file, opposite verdict,
60
  // for one reason: WHEN it paints.
61
 
62
- import { Suspense, lazy, useCallback, useEffect, useRef, useState } from "react";
63
  import { createPortal } from "react-dom";
64
  import { fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge";
65
  import type { SurfaceScope } from "../customer-grid/apiBridge";
66
- import { OverlayProvider } from "../customer-grid/OverlaySurface";
67
- import type { Field, FilterTree, Row } from "../customer-grid/types";
68
- import { choiceVocabulary, topicForScope } from "../customer-grid/types";
 
 
 
69
  import {
70
  SheetFilterDialog, conditionCountLabel, filterSentence,
71
  } from "../filter-kit/SheetFilterPopup";
72
  import { useEscapeClose } from "../ui/useEscapeClose";
 
73
  import { drillCell } from "./sheetApi";
74
  import type { CellDrill } from "./sheetApi";
 
 
75
 
76
  /**
77
  * β›”β›” LAZY, AND THE BUILD IS WHAT SAID SO. A plain `import { LinkGridModal } from
@@ -107,6 +114,191 @@ const LinkGridModal = lazy(() =>
107
  */
108
  const warmLinkChunk = () => import("../customer-grid/CustomerGrid");
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  /**
111
  * A Sheet binding names a DATABASE KEY; `LinkGridModal` wants a `SurfaceScope`. The two are not
112
  * the same vocabulary and the difference is only visible for the two compiled modules.
@@ -178,9 +370,14 @@ function DrillSkeleton(
178
  * silently fork the cell off its view or edit the view for everybody who uses it. So a view-bound
179
  * cell gets the sentence and no Edit door.
180
  */
181
- export type DrillCellScope =
182
- | { kind: "filter"; tree: FilterTree }
183
- | { kind: "view"; name: string };
 
 
 
 
 
184
 
185
  /** What the drill's own answer says about the scope, for a caller that passed none. */
186
  function scopeFromDrill(drill: CellDrill | null): DrillCellScope | null {
@@ -203,14 +400,13 @@ const sameTree = (a: FilterTree | null, b: FilterTree | null): boolean =>
203
  /**
204
  * ⭐⭐ W54-T35 β€” THE BAND THAT STATES THE FILTER, at the foot of the rows it produced.
205
  *
206
- * β›” IT IS A STATEMENT FIRST AND A CONTROL SECOND. The sentence is the whole of the owner's first
207
- * clause, so it takes the width and truncates with an ellipsis rather than being shortened into a
208
- * count; the full text stays reachable as the element's `title`. `Edit the filter` is one quiet
209
- * button in the card's own `cg-btn` chrome, which is what the editable footer of this same modal
210
- * already uses, so nothing new is introduced into the surface's control vocabulary.
211
  */
212
  function DrillFilterBand(
213
- { text, onEdit, editing }: { text: string; onEdit: (() => void) | null; editing: boolean },
214
  ) {
215
  return (
216
  <div
@@ -219,11 +415,6 @@ function DrillFilterBand(
219
  // `sheet-filter-popup`: it is the name a gate, a screenshot or a person in the inspector
220
  // can point at.
221
  className="cg-link-grid-foot sheet-drill-filter"
222
- // ⚠ THE ONE GEOMETRY OVERRIDE, and it is a single word: the shipped footer is
223
- // `justify-content: flex-end` because it holds two buttons at the right. This band holds a
224
- // sentence and a button, so they take opposite ends. Declaring it here rather than in a
225
- // stylesheet keeps the rule beside the only element that wants it.
226
- style={{ justifyContent: "space-between" }}
227
  >
228
  <span
229
  className="sheet-drill-filter-text"
@@ -238,17 +429,6 @@ function DrillFilterBand(
238
  >
239
  {text}
240
  </span>
241
- {onEdit && (
242
- <button
243
- type="button"
244
- className="cg-btn"
245
- aria-haspopup="dialog"
246
- aria-expanded={editing}
247
- onClick={onEdit}
248
- >
249
- Edit the filter
250
- </button>
251
- )}
252
  </div>
253
  );
254
  }
@@ -284,10 +464,18 @@ export interface DrillModalProps {
284
  * over the new filter.
285
  */
286
  onFilterChange?: (addr: string, tree: FilterTree) => void | Promise<void>;
 
 
 
 
 
 
287
  }
288
 
289
  export default function DrillModal(
290
- { workbookId, addr, label, onClose, onSettled, cellScope, onFilterChange }: DrillModalProps,
 
 
291
  ) {
292
  const [drill, setDrill] = useState<CellDrill | null>(null);
293
  const [error, setError] = useState("");
@@ -302,6 +490,28 @@ export default function DrillModal(
302
  /** Same reason, one ticket later: the page hands this an inline arrow too. */
303
  const filterChangeRef = useRef(onFilterChange);
304
  filterChangeRef.current = onFilterChange;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
 
306
  // ── W54-T35 state ─────────────────────────────────────────────────────────────────────────
307
  /** Is the centred filter dialog on screen? */
@@ -336,6 +546,14 @@ export default function DrillModal(
336
  /** The filter kit's two vocabularies for this database. Fetched once the drill has answered. */
337
  const [fields, setFields] = useState<Field[]>([]);
338
  const [statusValues, setStatusValues] = useState<Record<string, string[]>>({});
 
 
 
 
 
 
 
 
339
 
340
  useEffect(() => {
341
  let live = true;
@@ -438,17 +656,28 @@ export default function DrillModal(
438
  * against the list, so a minutes-old field list cannot paint a configuration nobody saved.
439
  */
440
  useEffect(() => {
441
- if (!scope || shownKind !== "filter") return;
442
  let live = true;
 
 
 
 
 
 
443
  (async () => {
444
  const [ws, rowsPayload] = await Promise.all([
445
  fetchWorkspace(scope, { allowCached: true }),
446
  fetchTopicRows(topicForScope(scope)),
447
  ]);
448
- if (!live || !ws) return;
449
- const list = (ws.fields ?? []) as Field[];
 
 
 
 
 
450
  const rows: Row[] = rowsPayload?.rows ?? [];
451
- const options: string[] = rowsPayload?.userOptions ?? ws.userOptions ?? [];
452
  const map: Record<string, string[]> = {};
453
  // The same rule `Toolbar.tsx` and `BindingEditor.tsx` compute, through the same pure
454
  // function, so a server-computed select has a value list here as well.
@@ -460,14 +689,35 @@ export default function DrillModal(
460
  if (f.type === "select" || f.type === "multiselect" || f.type === "status")
461
  map[f.key] = choiceVocabulary(f, rows);
462
  }
 
463
  setFields(list);
 
464
  setStatusValues(map);
 
 
465
  })();
466
  return () => { live = false; };
467
- // ⚠ `shownKind` RATHER THAN `shown`. The page rebuilds that object on every one of its own
468
- // renders, so depending on it would re-run these two fetches for reasons that have nothing to
469
- // do with this cell; only the KIND decides whether they run at all.
470
- }, [scope, shownKind]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471
 
472
  /** Persist a tree through the page's one binding writer, then read the rows again. */
473
  const applyTree = useCallback(async (tree: FilterTree) => {
@@ -577,6 +827,103 @@ export default function DrillModal(
577
  return () => window.cancelAnimationFrame(frame);
578
  }, [showRows]);
579
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580
  /**
581
  * The sentence. ⚠ NOT MEMOISED, and that is measured rather than lazy: `filterSentence` walks
582
  * at most three live leaves and stops, so a memo keyed on a `shown` the page rebuilds every
@@ -649,8 +996,8 @@ export default function DrillModal(
649
  * β›” ESCAPE IS UNAFFECTED AND STILL RESOLVES TO EXACTLY ONE SURFACE. That is the module-level
650
  * stack in `ui/useEscapeClose`, not this one: the card claims when it mounts, the dialog
651
  * claims when it opens and is therefore topmost, so one press closes the filter and the next
652
- * closes the drill. The band claims nothing - it is a statement and a button inside the
653
- * card, not an overlay - so the "exactly one claimant" property W51-T12 bought is unspent.
654
  */
655
  <OverlayProvider>
656
  <Suspense fallback={<DrillSkeleton label={label} nodeRef={skeletonRef} />}>
@@ -662,14 +1009,193 @@ export default function DrillModal(
662
  onClose={onClose}
663
  />
664
  </Suspense>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
665
  {host && bandText && createPortal(
666
- <DrillFilterBand
667
- text={bandText}
668
- // R8: no editor under a saved view, and none at all for a caller that gave us no
669
- // writer. A button that cannot write is a control that lies.
670
- onEdit={shownKind === "filter" && onFilterChange ? openFilter : null}
671
- editing={filterOpen}
672
- />,
673
  host,
674
  )}
675
  {filterOpen && draft && (
 
38
  // when we click 'View row' so its easy for user also to know what this filter is. In fact, they
39
  // should be able to change the filter there too. And if they make a mistake etc, they can just
40
  // CTRL + Z to return the Cell to its original filter."* Three clauses, and each one is a decision
41
+ // recorded beside the code that answers it: the BAND (`DrillFilterBand`) states it, the top-right
42
+ // Edit filter action opens the shared `SheetFilterDialog`, and one cell-scoped step of undo takes
43
+ // it back.
44
  //
45
  // β›”β›” THE BAND IS PORTALLED INTO `LinkGridModal`'s OWN CARD, WHICH LOOKS LIKE A LIBERTY AND IS
46
  // THE CONSERVATIVE CHOICE. `LinkGridModal` has no slot for extra chrome and it is not this lane's
 
60
  // same chunk is in hand, so the stylesheet is guaranteed present. Same file, opposite verdict,
61
  // for one reason: WHEN it paints.
62
 
63
+ import { Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from "react";
64
  import { createPortal } from "react-dom";
65
  import { fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge";
66
  import type { SurfaceScope } from "../customer-grid/apiBridge";
67
+ import { dataPathHash } from "../customer-grid/dataPath";
68
+ import { formatDisplay } from "../customer-grid/display";
69
+ import { ModeIcon } from "../customer-grid/icons";
70
+ import { AnchoredOverlay, OverlayProvider } from "../customer-grid/OverlaySurface";
71
+ import type { Field, FilterTree, GridWorkspace, Row } from "../customer-grid/types";
72
+ import { choiceVocabulary, mayEditField, topicForScope } from "../customer-grid/types";
73
  import {
74
  SheetFilterDialog, conditionCountLabel, filterSentence,
75
  } from "../filter-kit/SheetFilterPopup";
76
  import { useEscapeClose } from "../ui/useEscapeClose";
77
+ import { cellViewVisibleKeys, filterFieldKeys } from "./bindingRefs";
78
  import { drillCell } from "./sheetApi";
79
  import type { CellDrill } from "./sheetApi";
80
+ import { CELL_VIEW_MODES } from "./types";
81
+ import type { BindingDisplay, CellViewMode } from "./types";
82
 
83
  /**
84
  * β›”β›” LAZY, AND THE BUILD IS WHAT SAID SO. A plain `import { LinkGridModal } from
 
114
  */
115
  const warmLinkChunk = () => import("../customer-grid/CustomerGrid");
116
 
117
+ const CELL_VIEW_LABELS: Record<CellViewMode, string> = {
118
+ grid: "Grid",
119
+ list: "List",
120
+ map: "Map",
121
+ };
122
+
123
+ /** Compact Grid projection for a cell; values use the Data grid's one formatter. */
124
+ function CellGridView(
125
+ { rows, fields, identityKey }: { rows: Row[]; fields: Field[]; identityKey: string },
126
+ ) {
127
+ return (
128
+ <div className="sheet-cell-grid" role="table" aria-label="Matching records">
129
+ <div className="sheet-cell-grid-head" role="row">
130
+ {fields.map((field) => <span role="columnheader" key={field.key}>{field.label}</span>)}
131
+ </div>
132
+ {rows.map((row) => (
133
+ <div className="sheet-cell-grid-row" role="row" key={row.pid}>
134
+ {fields.map((field) => (
135
+ <span
136
+ role="cell"
137
+ className={field.key === identityKey ? "is-identity" : undefined}
138
+ key={field.key}
139
+ title={formatDisplay(field, row[field.key])}
140
+ >
141
+ {formatDisplay(field, row[field.key]) || " "}
142
+ </span>
143
+ ))}
144
+ </div>
145
+ ))}
146
+ {rows.length === 0 && <div className="sheet-cell-view-empty">No records match this cell.</div>}
147
+ </div>
148
+ );
149
+ }
150
+
151
+ /** List projection keeps one record together and labels every secondary value. */
152
+ function CellListView(
153
+ { rows, fields, identityKey }: { rows: Row[]; fields: Field[]; identityKey: string },
154
+ ) {
155
+ const identity = fields.find((field) => field.key === identityKey) ?? fields[0] ?? null;
156
+ const details = fields.filter((field) => field.key !== identity?.key);
157
+ return (
158
+ <div className="sheet-cell-list" role="list" aria-label="Matching records">
159
+ {rows.map((row) => (
160
+ <article className="sheet-cell-list-row" role="listitem" key={row.pid}>
161
+ <h3>{identity ? formatDisplay(identity, row[identity.key]) : `Record ${row.pid}`}</h3>
162
+ <div className="sheet-cell-list-fields">
163
+ {details.map((field) => (
164
+ <span key={field.key}>
165
+ <small>{field.label}</small>
166
+ <strong title={formatDisplay(field, row[field.key])}>
167
+ {formatDisplay(field, row[field.key]) || " "}
168
+ </strong>
169
+ </span>
170
+ ))}
171
+ </div>
172
+ </article>
173
+ ))}
174
+ {rows.length === 0 && <div className="sheet-cell-view-empty">No records match this cell.</div>}
175
+ </div>
176
+ );
177
+ }
178
+
179
+ interface CellMapAssets {
180
+ land: string;
181
+ lakes: string[];
182
+ project: (lon: number, lat: number) => { x: number; y: number };
183
+ parse: (value: unknown) => { lat: number; lon: number } | null;
184
+ }
185
+
186
+ interface CellMapSetup {
187
+ latField?: string;
188
+ lonField?: string;
189
+ coordField?: string;
190
+ }
191
+
192
+ const numberAt = (value: unknown): number | null => {
193
+ if (value == null || value === "") return null;
194
+ const number = typeof value === "number" ? value : Number(value);
195
+ return Number.isFinite(number) ? number : null;
196
+ };
197
+
198
+ /** The ordinary map projection, narrowed to the cell's exact row ids and without route writers. */
199
+ function CellMapView({
200
+ rows, identityKey, setup, assets,
201
+ }: {
202
+ rows: Row[];
203
+ identityKey: string;
204
+ setup: CellMapSetup | null;
205
+ assets: CellMapAssets | null;
206
+ }) {
207
+ if (!assets) {
208
+ return (
209
+ <div className="sheet-cell-view-loading" role="status" aria-label="Loading map">
210
+ <span /><span /><span /><span />
211
+ </div>
212
+ );
213
+ }
214
+ const points: { pid: number; title: string; x: number; y: number }[] = [];
215
+ for (const row of rows) {
216
+ let at: { lat: number; lon: number } | null = null;
217
+ if (setup?.latField && setup.lonField) {
218
+ const lat = numberAt(row[setup.latField]);
219
+ const lon = numberAt(row[setup.lonField]);
220
+ if (lat != null && lon != null) at = { lat, lon };
221
+ } else if (setup?.coordField) {
222
+ at = assets.parse(row[setup.coordField]);
223
+ } else {
224
+ const lat = numberAt(row.lat);
225
+ const lon = numberAt(row.lon);
226
+ if (lat != null && lon != null) at = { lat, lon };
227
+ }
228
+ if (!at || Math.abs(at.lat) > 85.05112878 || Math.abs(at.lon) > 180) continue;
229
+ const projected = assets.project(at.lon, at.lat);
230
+ points.push({
231
+ pid: row.pid,
232
+ title: String(row[identityKey] ?? `Record ${row.pid}`),
233
+ x: projected.x,
234
+ y: projected.y,
235
+ });
236
+ }
237
+
238
+ let minX = 0;
239
+ let minY = 850;
240
+ let width = 4096;
241
+ let height = 1450;
242
+ if (points.length) {
243
+ const xs = points.map((point) => point.x);
244
+ const ys = points.map((point) => point.y);
245
+ minX = Math.min(...xs);
246
+ minY = Math.min(...ys);
247
+ width = Math.max(420, Math.max(...xs) - minX);
248
+ height = Math.max(260, Math.max(...ys) - minY);
249
+ const pad = Math.max(width, height) * 0.18;
250
+ minX -= pad;
251
+ minY -= pad;
252
+ width += pad * 2;
253
+ height += pad * 2;
254
+ const ratio = 1.72;
255
+ if (width / height < ratio) {
256
+ const next = height * ratio;
257
+ minX -= (next - width) / 2;
258
+ width = next;
259
+ } else {
260
+ const next = width / ratio;
261
+ minY -= (next - height) / 2;
262
+ height = next;
263
+ }
264
+ }
265
+ const radius = Math.max(width, height) / 125;
266
+ const missing = rows.length - points.length;
267
+ return (
268
+ <div className="sheet-cell-map">
269
+ <svg
270
+ className="sheet-cell-map-canvas"
271
+ viewBox={`${minX} ${minY} ${width} ${height}`}
272
+ role="img"
273
+ aria-label={`${points.length.toLocaleString()} matching records on a map`}
274
+ >
275
+ <rect className="sheet-cell-map-water" x={minX} y={minY} width={width} height={height} />
276
+ <path className="sheet-cell-map-land" d={assets.land} />
277
+ {assets.lakes.map((path, index) => (
278
+ <path className="sheet-cell-map-lake" d={path} key={index} />
279
+ ))}
280
+ {points.map((point) => (
281
+ <circle
282
+ className="sheet-cell-map-pin"
283
+ cx={point.x}
284
+ cy={point.y}
285
+ r={radius}
286
+ key={point.pid}
287
+ >
288
+ <title>{point.title}</title>
289
+ </circle>
290
+ ))}
291
+ </svg>
292
+ {missing > 0 && (
293
+ <span className="sheet-cell-map-note">
294
+ {`${missing.toLocaleString()} matching ${missing === 1 ? "record has" : "records have"} no location`}
295
+ </span>
296
+ )}
297
+ {rows.length === 0 && <div className="sheet-cell-view-empty">No records match this cell.</div>}
298
+ </div>
299
+ );
300
+ }
301
+
302
  /**
303
  * A Sheet binding names a DATABASE KEY; `LinkGridModal` wants a `SurfaceScope`. The two are not
304
  * the same vocabulary and the difference is only visible for the two compiled modules.
 
370
  * silently fork the cell off its view or edit the view for everybody who uses it. So a view-bound
371
  * cell gets the sentence and no Edit door.
372
  */
373
+ export type DrillCellScope = (
374
+ | { kind: "filter"; tree: FilterTree }
375
+ | { kind: "view"; name: string }
376
+ )
377
+ & {
378
+ /** W55-T07: the cell binding's own display bag, never the saved View's config. */
379
+ display?: BindingDisplay;
380
+ };
381
 
382
  /** What the drill's own answer says about the scope, for a caller that passed none. */
383
  function scopeFromDrill(drill: CellDrill | null): DrillCellScope | null {
 
400
  /**
401
  * ⭐⭐ W54-T35 β€” THE BAND THAT STATES THE FILTER, at the foot of the rows it produced.
402
  *
403
+ * The sentence is the whole of the owner's first clause, so it takes the width and truncates with
404
+ * an ellipsis rather than being shortened into a count; the full text stays reachable as the
405
+ * element's `title`. W55-T07 moves Edit filter to the top-right toolbar and leaves this band one
406
+ * statement with one job.
 
407
  */
408
  function DrillFilterBand(
409
+ { text }: { text: string },
410
  ) {
411
  return (
412
  <div
 
415
  // `sheet-filter-popup`: it is the name a gate, a screenshot or a person in the inspector
416
  // can point at.
417
  className="cg-link-grid-foot sheet-drill-filter"
 
 
 
 
 
418
  >
419
  <span
420
  className="sheet-drill-filter-text"
 
429
  >
430
  {text}
431
  </span>
 
 
 
 
 
 
 
 
 
 
 
432
  </div>
433
  );
434
  }
 
464
  * over the new filter.
465
  */
466
  onFilterChange?: (addr: string, tree: FilterTree) => void | Promise<void>;
467
+ /**
468
+ * W55-T07 / R6: persist presentation on this cell's binding. The current Sheet host does not
469
+ * expose this writer yet, so absence leaves a working session-local switch and no false save
470
+ * claim; the typed seam is what the host must connect to its existing one-cell binding writer.
471
+ */
472
+ onDisplayChange?: (addr: string, display: BindingDisplay) => void | Promise<void>;
473
  }
474
 
475
  export default function DrillModal(
476
+ {
477
+ workbookId, addr, label, onClose, onSettled, cellScope, onFilterChange, onDisplayChange,
478
+ }: DrillModalProps,
479
  ) {
480
  const [drill, setDrill] = useState<CellDrill | null>(null);
481
  const [error, setError] = useState("");
 
490
  /** Same reason, one ticket later: the page hands this an inline arrow too. */
491
  const filterChangeRef = useRef(onFilterChange);
492
  filterChangeRef.current = onFilterChange;
493
+ const displayChangeRef = useRef(onDisplayChange);
494
+ displayChangeRef.current = onDisplayChange;
495
+
496
+ // R6: hydrate from the binding seam, not from a database View and not from localStorage.
497
+ const displayKey = JSON.stringify(cellScope?.display ?? null);
498
+ const hydratedDisplayRef = useRef("");
499
+ const [cellDisplay, setCellDisplay] = useState<BindingDisplay>(
500
+ () => cellScope?.display ?? { mode: "grid", visible: [] },
501
+ );
502
+ useEffect(() => {
503
+ const key = `${workbookId}:${addr}:${displayKey}`;
504
+ if (hydratedDisplayRef.current === key) return;
505
+ hydratedDisplayRef.current = key;
506
+ setCellDisplay(cellScope?.display ?? { mode: "grid", visible: [] });
507
+ }, [addr, cellScope?.display, displayKey, workbookId]);
508
+
509
+ const changeDisplay = useCallback((next: BindingDisplay) => {
510
+ setCellDisplay(next);
511
+ // No callback means no durable writer. The switch still answers the current gesture, but it
512
+ // never falls back to a second browser store that would violate R6's cell-local contract.
513
+ void Promise.resolve(displayChangeRef.current?.(addr, next));
514
+ }, [addr]);
515
 
516
  // ── W54-T35 state ─────────────────────────────────────────────────────────────────────────
517
  /** Is the centred filter dialog on screen? */
 
546
  /** The filter kit's two vocabularies for this database. Fetched once the drill has answered. */
547
  const [fields, setFields] = useState<Field[]>([]);
548
  const [statusValues, setStatusValues] = useState<Record<string, string[]>>({});
549
+ /** Raw, permission-scoped rows back the List, Map and export projections. */
550
+ const [rawRows, setRawRows] = useState<Row[]>([]);
551
+ const [workspace, setWorkspace] = useState<GridWorkspace | null>(null);
552
+ const [rowsResolved, setRowsResolved] = useState(false);
553
+ const [rowsError, setRowsError] = useState("");
554
+ const [today, setToday] = useState<string | undefined>(undefined);
555
+ const [mapAssets, setMapAssets] = useState<CellMapAssets | null>(null);
556
+ const [mapError, setMapError] = useState(false);
557
 
558
  useEffect(() => {
559
  let live = true;
 
656
  * against the list, so a minutes-old field list cannot paint a configuration nobody saved.
657
  */
658
  useEffect(() => {
659
+ if (!scope) return;
660
  let live = true;
661
+ setRowsResolved(false);
662
+ setRowsError("");
663
+ setFields([]);
664
+ setRawRows([]);
665
+ setWorkspace(null);
666
+ setToday(undefined);
667
  (async () => {
668
  const [ws, rowsPayload] = await Promise.all([
669
  fetchWorkspace(scope, { allowCached: true }),
670
  fetchTopicRows(topicForScope(scope)),
671
  ]);
672
+ if (!live) return;
673
+ if (!ws && !rowsPayload) {
674
+ setRowsError("These records could not be loaded for List, Map or Export.");
675
+ setRowsResolved(true);
676
+ return;
677
+ }
678
+ const list = ((rowsPayload?.fields?.length ? rowsPayload.fields : ws?.fields) ?? []) as Field[];
679
  const rows: Row[] = rowsPayload?.rows ?? [];
680
+ const options: string[] = rowsPayload?.userOptions ?? ws?.userOptions ?? [];
681
  const map: Record<string, string[]> = {};
682
  // The same rule `Toolbar.tsx` and `BindingEditor.tsx` compute, through the same pure
683
  // function, so a server-computed select has a value list here as well.
 
689
  if (f.type === "select" || f.type === "multiselect" || f.type === "status")
690
  map[f.key] = choiceVocabulary(f, rows);
691
  }
692
+ setWorkspace(ws);
693
  setFields(list);
694
+ setRawRows(rows);
695
  setStatusValues(map);
696
+ setToday(rowsPayload?.today);
697
+ setRowsResolved(true);
698
  })();
699
  return () => { live = false; };
700
+ }, [scope]);
701
+
702
+ /** Load only the two leaf geometry modules when Map is actually selected. */
703
+ useEffect(() => {
704
+ if (cellDisplay.mode !== "map" || mapAssets) return;
705
+ let live = true;
706
+ setMapError(false);
707
+ void Promise.all([
708
+ import("../customer-grid/mapGeometry"),
709
+ import("../customer-grid/mapProjection"),
710
+ ]).then(([geometry, projection]) => {
711
+ if (!live) return;
712
+ setMapAssets({
713
+ land: geometry.LAND_PATH,
714
+ lakes: geometry.LAKE_PATHS,
715
+ project: projection.project,
716
+ parse: (value) => projection.parseLatLon(value as Row[keyof Row]),
717
+ });
718
+ }, () => { if (live) setMapError(true); });
719
+ return () => { live = false; };
720
+ }, [cellDisplay.mode, mapAssets]);
721
 
722
  /** Persist a tree through the page's one binding writer, then read the rows again. */
723
  const applyTree = useCallback(async (tree: FilterTree) => {
 
827
  return () => window.cancelAnimationFrame(frame);
828
  }, [showRows]);
829
 
830
+ const headerHost = host?.querySelector<HTMLElement>(".cg-link-grid-head") ?? null;
831
+ const bodyHost = host?.querySelector<HTMLElement>(".cg-link-grid-body") ?? null;
832
+ useEffect(() => {
833
+ if (!bodyHost) return;
834
+ bodyHost.classList.add("sheet-cell-view-custom");
835
+ return () => bodyHost.classList.remove("sheet-cell-view-custom");
836
+ }, [bodyHost]);
837
+
838
+ /** Exact record order from the drill answer; a topic payload is only the row book. */
839
+ const recordRows = useMemo(() => {
840
+ if (!drill) return [];
841
+ const byPid = new Map(rawRows.map((row) => [row.pid, row]));
842
+ return drill.record_ids.map((pid) => byPid.get(pid)).filter((row): row is Row => Boolean(row));
843
+ }, [drill, rawRows]);
844
+
845
+ const identityField = fields.find((field) => field.pinned) ?? fields[0] ?? null;
846
+ const savedView = drill?.view_id
847
+ ? workspace?.views?.find((view) => view.id === drill.view_id) ?? null
848
+ : null;
849
+ const fieldFilter: FilterTree | null = shown?.kind === "filter"
850
+ ? shown.tree
851
+ : savedView
852
+ ? { conj: savedView.config.filterConj, nodes: savedView.config.filters }
853
+ : null;
854
+ const forcedFieldKeys = filterFieldKeys(fieldFilter);
855
+ const defaultFieldKeys = fields
856
+ .filter((field) => field.default !== false && field.custom !== true && field.shared !== true)
857
+ .map((field) => field.key);
858
+ const visibleKeys = cellViewVisibleKeys(
859
+ defaultFieldKeys,
860
+ cellDisplay.visible,
861
+ forcedFieldKeys,
862
+ fields.map((field) => field.key),
863
+ identityField?.key ?? "",
864
+ );
865
+ const visibleFields = visibleKeys
866
+ .map((key) => fields.find((field) => field.key === key))
867
+ .filter((field): field is Field => Boolean(field));
868
+ const mapSetup = (workspace?.mapSetup ?? null) as CellMapSetup | null;
869
+ const fieldKeys = new Set(fields.map((field) => field.key));
870
+ const mapSupported = Boolean(
871
+ (mapSetup?.latField && mapSetup.lonField
872
+ && fieldKeys.has(mapSetup.latField) && fieldKeys.has(mapSetup.lonField))
873
+ || (mapSetup?.coordField && fieldKeys.has(mapSetup.coordField))
874
+ || (fieldKeys.has("lat") && fieldKeys.has("lon")),
875
+ );
876
+
877
+ // CustomerGrid's own value-edit predicate. It distinguishes source-locked values, machine-
878
+ // written pre-set fields and viewer grants field by field instead of inventing one read-only flag.
879
+ const canEditRows = Boolean(
880
+ rowsResolved && !rowsError && fields.some((field) => mayEditField(field, workspace?.viewer)),
881
+ );
882
+ const allRowsLoaded = rowsResolved
883
+ && (drill?.record_ids.length ?? 0) === recordRows.length;
884
+ const editInData = useCallback(() => {
885
+ if (!drill || !canEditRows) return;
886
+ onClose();
887
+ window.location.hash = dataPathHash({
888
+ database: drill.database,
889
+ ...(drill.view_id ? { view: drill.view_id } : {}),
890
+ });
891
+ }, [canEditRows, drill, onClose]);
892
+
893
+ const fieldsButtonRef = useRef<HTMLButtonElement>(null);
894
+ const exportButtonRef = useRef<HTMLButtonElement>(null);
895
+ const [fieldsOpen, setFieldsOpen] = useState(false);
896
+ const [exportOpen, setExportOpen] = useState(false);
897
+ const [exporting, setExporting] = useState(false);
898
+
899
+ const setMode = useCallback((mode: CellViewMode) => {
900
+ if (mode === "map" && rowsResolved && !mapSupported) return;
901
+ changeDisplay({ ...cellDisplay, mode });
902
+ }, [cellDisplay, changeDisplay, mapSupported, rowsResolved]);
903
+
904
+ const setFieldVisible = useCallback((key: string, checked: boolean) => {
905
+ if (!identityField || forcedFieldKeys.includes(key) || key === identityField.key) return;
906
+ const chosen = new Set(visibleKeys);
907
+ if (checked) chosen.add(key);
908
+ else chosen.delete(key);
909
+ changeDisplay({
910
+ ...cellDisplay,
911
+ visible: fields.map((field) => field.key).filter((fieldKey) => chosen.has(fieldKey)),
912
+ });
913
+ }, [cellDisplay, changeDisplay, fields, forcedFieldKeys, identityField, visibleKeys]);
914
+
915
+ const exportCell = useCallback(async (format: "csv" | "xlsx" | "pdf" | "json") => {
916
+ if (!allRowsLoaded || exporting) return;
917
+ setExportOpen(false);
918
+ setExporting(true);
919
+ try {
920
+ const exporter = await import("../customer-grid/export");
921
+ exporter.runExport(format, `${label} records`, today, visibleFields, recordRows);
922
+ } finally {
923
+ setExporting(false);
924
+ }
925
+ }, [allRowsLoaded, exporting, label, recordRows, today, visibleFields]);
926
+
927
  /**
928
  * The sentence. ⚠ NOT MEMOISED, and that is measured rather than lazy: `filterSentence` walks
929
  * at most three live leaves and stops, so a memo keyed on a `shown` the page rebuilds every
 
996
  * β›” ESCAPE IS UNAFFECTED AND STILL RESOLVES TO EXACTLY ONE SURFACE. That is the module-level
997
  * stack in `ui/useEscapeClose`, not this one: the card claims when it mounts, the dialog
998
  * claims when it opens and is therefore topmost, so one press closes the filter and the next
999
+ * closes the drill. The band claims nothing: it is a statement inside the card, not an
1000
+ * overlay, so the "exactly one claimant" property W51-T12 bought is unspent.
1001
  */
1002
  <OverlayProvider>
1003
  <Suspense fallback={<DrillSkeleton label={label} nodeRef={skeletonRef} />}>
 
1009
  onClose={onClose}
1010
  />
1011
  </Suspense>
1012
+ {headerHost && createPortal(
1013
+ <div className="sheet-cell-view-toolbar" role="toolbar" aria-label="Cell View controls">
1014
+ <div className="sheet-cell-view-modes" role="group" aria-label="View mode">
1015
+ {CELL_VIEW_MODES.map((mode) => {
1016
+ const unavailable = mode === "map" && (!rowsResolved || !mapSupported);
1017
+ return (
1018
+ <button
1019
+ type="button"
1020
+ className="sheet-cell-view-mode"
1021
+ data-active={cellDisplay.mode === mode ? "true" : undefined}
1022
+ aria-pressed={cellDisplay.mode === mode}
1023
+ disabled={unavailable}
1024
+ title={unavailable
1025
+ ? rowsResolved
1026
+ ? "Map needs location fields in this database."
1027
+ : "Map is loading this database's location fields."
1028
+ : CELL_VIEW_LABELS[mode]}
1029
+ onClick={() => setMode(mode)}
1030
+ key={mode}
1031
+ >
1032
+ <ModeIcon mode={mode} size={13} />
1033
+ <span>{CELL_VIEW_LABELS[mode]}</span>
1034
+ </button>
1035
+ );
1036
+ })}
1037
+ </div>
1038
+ <button
1039
+ ref={fieldsButtonRef}
1040
+ type="button"
1041
+ className="sheet-cell-view-action"
1042
+ aria-haspopup="dialog"
1043
+ aria-expanded={fieldsOpen}
1044
+ disabled={!rowsResolved || fields.length === 0}
1045
+ onClick={() => { setExportOpen(false); setFieldsOpen((open) => !open); }}
1046
+ >
1047
+ <svg viewBox="0 0 16 16" aria-hidden="true">
1048
+ <path d="M2.5 3.5h11M2.5 8h11M2.5 12.5h11M5.5 2v12" />
1049
+ </svg>
1050
+ <span>Fields</span>
1051
+ </button>
1052
+ <button
1053
+ type="button"
1054
+ className="sheet-cell-view-action"
1055
+ aria-haspopup="dialog"
1056
+ aria-expanded={filterOpen}
1057
+ disabled={shownKind !== "filter" || !onFilterChange}
1058
+ title={shownKind === "view"
1059
+ ? "This cell follows a saved view, so its filter is changed in Data."
1060
+ : undefined}
1061
+ onClick={openFilter}
1062
+ >
1063
+ <svg viewBox="0 0 16 16" aria-hidden="true">
1064
+ <path d="M2.5 3h11L9.2 8v4.2l-2.4 1V8z" />
1065
+ </svg>
1066
+ <span>Edit filter</span>
1067
+ </button>
1068
+ {canEditRows && (
1069
+ <button type="button" className="sheet-cell-view-action" onClick={editInData}>
1070
+ <svg viewBox="0 0 16 16" aria-hidden="true">
1071
+ <path d="m3 11.8-.3 2.1 2.1-.3 7.9-7.9-1.8-1.8zM9.9 4.9l1.8 1.8" />
1072
+ </svg>
1073
+ <span>Edit rows</span>
1074
+ </button>
1075
+ )}
1076
+ <button
1077
+ ref={exportButtonRef}
1078
+ type="button"
1079
+ className="sheet-cell-view-action"
1080
+ aria-haspopup="menu"
1081
+ aria-expanded={exportOpen}
1082
+ disabled={!allRowsLoaded || exporting}
1083
+ title={!allRowsLoaded && rowsResolved
1084
+ ? "Export waits until every matching record is loaded."
1085
+ : undefined}
1086
+ onClick={() => { setFieldsOpen(false); setExportOpen((open) => !open); }}
1087
+ >
1088
+ <svg viewBox="0 0 16 16" aria-hidden="true">
1089
+ <path d="M8 2v8M5 7l3 3 3-3M3 12.5h10" />
1090
+ </svg>
1091
+ <span>{exporting ? "Preparing" : "Export"}</span>
1092
+ </button>
1093
+ </div>,
1094
+ headerHost,
1095
+ )}
1096
+ {bodyHost && createPortal(
1097
+ <div className="sheet-cell-view-surface" data-mode={cellDisplay.mode}>
1098
+ {!rowsResolved ? (
1099
+ <div className="sheet-cell-view-loading" role="status" aria-label="Loading records">
1100
+ <span /><span /><span /><span />
1101
+ </div>
1102
+ ) : rowsError ? (
1103
+ <div className="sheet-cell-view-empty" role="alert">{rowsError}</div>
1104
+ ) : cellDisplay.mode === "grid" ? (
1105
+ <CellGridView
1106
+ rows={recordRows}
1107
+ fields={visibleFields}
1108
+ identityKey={identityField?.key ?? ""}
1109
+ />
1110
+ ) : cellDisplay.mode === "list" ? (
1111
+ <CellListView
1112
+ rows={recordRows}
1113
+ fields={visibleFields}
1114
+ identityKey={identityField?.key ?? ""}
1115
+ />
1116
+ ) : mapSupported && mapError ? (
1117
+ <div className="sheet-cell-view-empty" role="alert">
1118
+ Map could not be loaded.
1119
+ </div>
1120
+ ) : mapSupported ? (
1121
+ <CellMapView
1122
+ rows={recordRows}
1123
+ identityKey={identityField?.key ?? ""}
1124
+ setup={mapSetup}
1125
+ assets={mapAssets}
1126
+ />
1127
+ ) : (
1128
+ <div className="sheet-cell-view-empty">
1129
+ Map needs latitude and longitude fields in this database.
1130
+ </div>
1131
+ )}
1132
+ {rowsResolved && !rowsError && !allRowsLoaded && (
1133
+ <div className="sheet-cell-view-limit" role="status">
1134
+ {`${recordRows.length.toLocaleString()} of ${(drill?.record_ids.length ?? 0).toLocaleString()} matching records are loaded.`}
1135
+ </div>
1136
+ )}
1137
+ </div>,
1138
+ bodyHost,
1139
+ )}
1140
+ {fieldsOpen && fieldsButtonRef.current && (
1141
+ <AnchoredOverlay
1142
+ anchor={fieldsButtonRef.current}
1143
+ className="sheet-cell-fields-pop"
1144
+ placement="bottom-end"
1145
+ onDismiss={() => setFieldsOpen(false)}
1146
+ role="dialog"
1147
+ ariaLabel="Fields shown in this cell"
1148
+ dataKind="sheet-cell-fields"
1149
+ >
1150
+ <div className="sheet-cell-fields-title">Fields shown in this cell</div>
1151
+ <div className="sheet-cell-fields-list">
1152
+ {fields.map((field) => {
1153
+ const forced = field.key === identityField?.key || forcedFieldKeys.includes(field.key);
1154
+ return (
1155
+ <label className="sheet-cell-field-choice" key={field.key}>
1156
+ <input
1157
+ type="checkbox"
1158
+ checked={visibleKeys.includes(field.key)}
1159
+ disabled={forced}
1160
+ onChange={(event) => setFieldVisible(field.key, event.target.checked)}
1161
+ />
1162
+ <span>{field.label}</span>
1163
+ {forcedFieldKeys.includes(field.key)
1164
+ ? <small>Used by filter</small>
1165
+ : field.key === identityField?.key
1166
+ ? <small>Identity</small>
1167
+ : null}
1168
+ </label>
1169
+ );
1170
+ })}
1171
+ </div>
1172
+ </AnchoredOverlay>
1173
+ )}
1174
+ {exportOpen && exportButtonRef.current && (
1175
+ <AnchoredOverlay
1176
+ anchor={exportButtonRef.current}
1177
+ className="sheet-cell-export-pop"
1178
+ placement="bottom-end"
1179
+ onDismiss={() => setExportOpen(false)}
1180
+ role="menu"
1181
+ ariaLabel="Export matching records"
1182
+ dataKind="sheet-cell-export"
1183
+ >
1184
+ {(["csv", "xlsx", "pdf", "json"] as const).map((format) => (
1185
+ <button
1186
+ type="button"
1187
+ role="menuitem"
1188
+ className="sheet-cell-export-choice"
1189
+ onClick={() => { void exportCell(format); }}
1190
+ key={format}
1191
+ >
1192
+ {format === "xlsx" ? "Excel" : format === "pdf" ? "PDF" : format.toUpperCase()}
1193
+ </button>
1194
+ ))}
1195
+ </AnchoredOverlay>
1196
+ )}
1197
  {host && bandText && createPortal(
1198
+ <DrillFilterBand text={bandText} />,
 
 
 
 
 
 
1199
  host,
1200
  )}
1201
  {filterOpen && draft && (
web/src/sheet/KeyTips.tsx CHANGED
@@ -30,8 +30,9 @@
30
  // fresh badge set from whatever `.sheet-ribbon-pop` is now open (KT-11).
31
  //
32
  // ⚠ SCOPE, STATED HONESTLY (the ticket's own "best effort" clause for the third level). The first
33
- // two levels β€” Alt -> Home tab badge, H -> every Home control badge, prefix match, arrow/Enter
34
- // nav, Escape/Alt exit β€” are built to the full spec. The THIRD level (inside an opened gallery) is
 
35
  // exercised to full fidelity for Borders only (`Ribbon.tsx`'s `BORDERS` array now carries its own
36
  // one-letter `data-kt` per entry, plus "No border"). Every OTHER gallery (Insert, Delete, Format,
37
  // Clear, Fill/Text colour, Font size, Number format) still gets Escape-to-close and generic
@@ -40,6 +41,7 @@
40
  // no letter badges yet. That gap is booked in the ticket's HANDOFF, not hidden here.
41
  import { useCallback, useEffect, useReducer, useRef } from "react";
42
  import type { RefObject } from "react";
 
43
 
44
  type Depth = "tabs" | "home" | "gallery";
45
 
@@ -190,11 +192,11 @@ export default function KeyTips({ containerRef }: KeyTipsProps) {
190
  el.classList.add("sheet-kt-flash");
191
  }, []);
192
 
193
- const deactivateAll = useCallback(() => {
194
  const el = previousFocusRef.current;
195
  previousFocusRef.current = null;
196
  setKt(INITIAL);
197
- requestAnimationFrame(() => el?.focus?.());
198
  }, [setKt]);
199
 
200
  const activateFirstLevel = useCallback(() => {
@@ -314,7 +316,21 @@ export default function KeyTips({ containerRef }: KeyTipsProps) {
314
  stepBack();
315
  return;
316
  }
317
- if (e.key === "ArrowRight" || e.key === "ArrowDown") {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  e.preventDefault(); e.stopPropagation();
319
  if (targets.length) {
320
  const next = (st.focusedIdx + 1) % targets.length;
@@ -323,7 +339,7 @@ export default function KeyTips({ containerRef }: KeyTipsProps) {
323
  }
324
  return;
325
  }
326
- if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
327
  e.preventDefault(); e.stopPropagation();
328
  if (targets.length) {
329
  const next = (st.focusedIdx - 1 + targets.length) % targets.length;
@@ -354,7 +370,8 @@ export default function KeyTips({ containerRef }: KeyTipsProps) {
354
  // no flash, since KT-17's soft signal is for an unmatched CHARACTER, not for every
355
  // non-actionable key a person might happen to touch.
356
  e.preventDefault(); e.stopPropagation();
357
- }, [activate, activateFirstLevel, containerRef, flash, handleCharacter, stepBack, setKt]);
 
358
 
359
  const onDocKeyUp = useCallback((e: KeyboardEvent) => {
360
  if (e.key !== "Alt") return;
 
30
  // fresh badge set from whatever `.sheet-ribbon-pop` is now open (KT-11).
31
  //
32
  // ⚠ SCOPE, STATED HONESTLY (the ticket's own "best effort" clause for the third level). The first
33
+ // two levels β€” Alt -> Home tab badge, H -> every Home control badge, prefix match, Left/Right and
34
+ // Enter nav, Escape/Alt exit β€” are built to the full spec. Wave 55 gives Up/Down back to the grid
35
+ // immediately. The THIRD level (inside an opened gallery) is
36
  // exercised to full fidelity for Borders only (`Ribbon.tsx`'s `BORDERS` array now carries its own
37
  // one-letter `data-kt` per entry, plus "No border"). Every OTHER gallery (Insert, Delete, Format,
38
  // Clear, Fill/Text colour, Font size, Number format) still gets Escape-to-close and generic
 
41
  // no letter badges yet. That gap is booked in the ticket's HANDOFF, not hidden here.
42
  import { useCallback, useEffect, useReducer, useRef } from "react";
43
  import type { RefObject } from "react";
44
+ import { KEY_TIP_GRID_ARROW_EVENT, keyTipGridArrow } from "./shortcuts";
45
 
46
  type Depth = "tabs" | "home" | "gallery";
47
 
 
192
  el.classList.add("sheet-kt-flash");
193
  }, []);
194
 
195
+ const deactivateAll = useCallback((restoreFocus = true) => {
196
  const el = previousFocusRef.current;
197
  previousFocusRef.current = null;
198
  setKt(INITIAL);
199
+ if (restoreFocus) requestAnimationFrame(() => el?.focus?.());
200
  }, [setKt]);
201
 
202
  const activateFirstLevel = useCallback(() => {
 
316
  stepBack();
317
  return;
318
  }
319
+ // W55-T05 / R4: Up and Down leave the Alt path instead of walking its badges. The original
320
+ // document-capture key cannot reach Glide because focus currently belongs to the ribbon, so
321
+ // consume it once, close synchronously, and hand one semantic arrow to this ribbon's own
322
+ // SheetGrid wrapper. That wrapper owns selection and focus; no global key listener competes
323
+ // with the shared overlay/Escape stack.
324
+ const gridArrow = keyTipGridArrow(e.key);
325
+ if (gridArrow) {
326
+ e.preventDefault(); e.stopPropagation();
327
+ deactivateAll(false);
328
+ containerRef.current?.closest<HTMLElement>(".sheet-grid-wrap")?.dispatchEvent(
329
+ new CustomEvent(KEY_TIP_GRID_ARROW_EVENT, { detail: { key: gridArrow } }),
330
+ );
331
+ return;
332
+ }
333
+ if (e.key === "ArrowRight") {
334
  e.preventDefault(); e.stopPropagation();
335
  if (targets.length) {
336
  const next = (st.focusedIdx + 1) % targets.length;
 
339
  }
340
  return;
341
  }
342
+ if (e.key === "ArrowLeft") {
343
  e.preventDefault(); e.stopPropagation();
344
  if (targets.length) {
345
  const next = (st.focusedIdx - 1 + targets.length) % targets.length;
 
370
  // no flash, since KT-17's soft signal is for an unmatched CHARACTER, not for every
371
  // non-actionable key a person might happen to touch.
372
  e.preventDefault(); e.stopPropagation();
373
+ }, [activate, activateFirstLevel, containerRef, deactivateAll, flash, handleCharacter,
374
+ stepBack, setKt]);
375
 
376
  const onDocKeyUp = useCallback((e: KeyboardEvent) => {
377
  if (e.key !== "Alt") return;
web/src/sheet/Ribbon.tsx CHANGED
@@ -59,6 +59,12 @@ import { HOME_TAB } from "./ribbonHome";
59
  // ⭐⭐ W54-T10 (lane B) β€” the second registered tab. Same three exports, same registry, and the
60
  // shell learns nothing about it beyond its descriptor.
61
  import { INSERT_TAB } from "./ribbonInsert";
 
 
 
 
 
 
62
  // ⭐⭐ W52-T17 (instruction 20, ruling R7) β€” the KeyTips overlay is a SEPARATE keyboard-capture
63
  // layer, mounted once, that reads this file's DOM (`[data-kt]`, `[data-kt-opens]`) rather than
64
  // threading new props through 30+ `control()` call sites. See that file's own header for the
@@ -190,7 +196,7 @@ export interface RibbonProps {
190
  * `STRIP`, `reachable`, the tab-strip JSX and `Popover` are every one of them derived from this
191
  * array, so a THIRD tab is the same one line.
192
  */
193
- const TABS = [HOME_TAB, INSERT_TAB] as const;
194
 
195
  /**
196
  * ⭐⭐ W52-T15 (instruction 14, contract C4) β€” IMPORT, REFRESH AND FULL SCREEN LIVE IN THE TAB
@@ -250,6 +256,11 @@ export interface RibbonTabContext {
250
  onApply: (patch: CellStylePatch) => void;
251
  apply: (patch: CellStylePatch) => void;
252
  act: (kind: RibbonActionKind, arg?: string | number) => void;
 
 
 
 
 
253
  openPop: (which: Popover) => (event: ReactMouseEvent<HTMLButtonElement>) => void;
254
  closePop: () => void;
255
  control: (
@@ -264,6 +275,8 @@ export interface RibbonTabContext {
264
  ) => ReactNode;
265
  group: (name: string, body: ReactNode, extra?: string) => ReactNode;
266
  word: (text: string) => ReactNode;
 
 
267
  item: (label: string, onClick: () => void, on?: boolean, role?: string, kt?: string) => ReactNode;
268
  /**
269
  * ⭐ W54-T10 β€” the Insert tab's document doors, handed through unchanged. Undefined on a page
@@ -279,6 +292,7 @@ export interface RibbonTabContext {
279
  * the state that shows every control rather than the state that hides them.
280
  */
281
  const COLLAPSE_KEY = "aios.sheet.ribbon.collapsed";
 
282
 
283
  const readCollapsed = (): boolean => {
284
  try {
@@ -296,6 +310,22 @@ const writeCollapsed = (next: boolean) => {
296
  }
297
  };
298
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
  function IconRefresh() {
300
  return (
301
  <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
@@ -346,9 +376,24 @@ export default function Ribbon({
346
  */
347
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
348
  const [collapsed, setCollapsed] = useState<boolean>(readCollapsed);
 
349
  const rootRef = useRef<HTMLDivElement | null>(null);
350
 
351
- /** Which tab is showing. One registered tab today, so this never changes hands yet. */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
352
  const [active, setActive] = useState<TabId>(TABS[0].id);
353
  const activeTab = TABS.find((tab) => tab.id === active) ?? TABS[0];
354
 
@@ -554,6 +599,23 @@ export default function Ribbon({
554
  /** A plain word inside a control. A ribbon is not an icon quiz. */
555
  const word = (text: string) => <span className="sheet-ribbon-label">{text}</span>;
556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557
  // ⭐ W52-T17 β€” the optional 5th argument `kt` is the THIRD-LEVEL key-tip badge (KT-11): a
558
  // gallery item painted with its own letter once the gallery that owns it is open. Additive and
559
  // undefined everywhere this ticket did not touch, so every existing `item(...)` call site keeps
@@ -577,8 +639,9 @@ export default function Ribbon({
577
  const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen";
578
 
579
  const tabContext: RibbonTabContext = {
580
- style, frozen, open, anchorEl, onApply, apply, act, openPop, closePop,
581
- control, group, word, item, insert,
 
582
  };
583
 
584
  return (
 
59
  // ⭐⭐ W54-T10 (lane B) β€” the second registered tab. Same three exports, same registry, and the
60
  // shell learns nothing about it beyond its descriptor.
61
  import { INSERT_TAB } from "./ribbonInsert";
62
+ // W55-T06 adopts the public Excel audit's tab grouping through Loopable's existing ribbon
63
+ // registry and command vocabulary. The tab modules cite the audit and keep unsupported commands
64
+ // visibly unavailable rather than widening SheetGrid's closed action union.
65
+ import { FORMULAS_TAB } from "./ribbonFormulas";
66
+ import { DATA_TAB } from "./ribbonData";
67
+ import { VIEW_TAB } from "./ribbonView";
68
  // ⭐⭐ W52-T17 (instruction 20, ruling R7) β€” the KeyTips overlay is a SEPARATE keyboard-capture
69
  // layer, mounted once, that reads this file's DOM (`[data-kt]`, `[data-kt-opens]`) rather than
70
  // threading new props through 30+ `control()` call sites. See that file's own header for the
 
196
  * `STRIP`, `reachable`, the tab-strip JSX and `Popover` are every one of them derived from this
197
  * array, so a THIRD tab is the same one line.
198
  */
199
+ const TABS = [HOME_TAB, INSERT_TAB, FORMULAS_TAB, DATA_TAB, VIEW_TAB] as const;
200
 
201
  /**
202
  * ⭐⭐ W52-T15 (instruction 14, contract C4) β€” IMPORT, REFRESH AND FULL SCREEN LIVE IN THE TAB
 
256
  onApply: (patch: CellStylePatch) => void;
257
  apply: (patch: CellStylePatch) => void;
258
  act: (kind: RibbonActionKind, arg?: string | number) => void;
259
+ /** View-only state owned by the ribbon shell, with no new document or SheetGrid action. */
260
+ fullscreen: boolean;
261
+ toggleFullscreen: () => void;
262
+ formulaBarVisible: boolean;
263
+ toggleFormulaBar: () => void;
264
  openPop: (which: Popover) => (event: ReactMouseEvent<HTMLButtonElement>) => void;
265
  closePop: () => void;
266
  control: (
 
275
  ) => ReactNode;
276
  group: (name: string, body: ReactNode, extra?: string) => ReactNode;
277
  word: (text: string) => ReactNode;
278
+ /** A command the current Sheet door cannot execute, stated visibly instead of acting dead. */
279
+ unavailable: (label: string, body: ReactNode) => ReactNode;
280
  item: (label: string, onClick: () => void, on?: boolean, role?: string, kt?: string) => ReactNode;
281
  /**
282
  * ⭐ W54-T10 β€” the Insert tab's document doors, handed through unchanged. Undefined on a page
 
292
  * the state that shows every control rather than the state that hides them.
293
  */
294
  const COLLAPSE_KEY = "aios.sheet.ribbon.collapsed";
295
+ const FORMULA_BAR_KEY = "aios.sheet.ribbon.formula-bar";
296
 
297
  const readCollapsed = (): boolean => {
298
  try {
 
310
  }
311
  };
312
 
313
+ const readFormulaBar = (): boolean => {
314
+ try {
315
+ return window.localStorage.getItem(FORMULA_BAR_KEY) !== "0";
316
+ } catch {
317
+ return true;
318
+ }
319
+ };
320
+
321
+ const writeFormulaBar = (visible: boolean) => {
322
+ try {
323
+ window.localStorage.setItem(FORMULA_BAR_KEY, visible ? "1" : "0");
324
+ } catch {
325
+ // A refused storage write affects persistence only; the current view still changes.
326
+ }
327
+ };
328
+
329
  function IconRefresh() {
330
  return (
331
  <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
 
376
  */
377
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
378
  const [collapsed, setCollapsed] = useState<boolean>(readCollapsed);
379
+ const [formulaBarVisible, setFormulaBarVisible] = useState<boolean>(readFormulaBar);
380
  const rootRef = useRef<HTMLDivElement | null>(null);
381
 
382
+ useEffect(() => {
383
+ const wrap = rootRef.current?.closest<HTMLElement>(".sheet-grid-wrap");
384
+ wrap?.classList.toggle("is-formula-bar-hidden", !formulaBarVisible);
385
+ return () => wrap?.classList.remove("is-formula-bar-hidden");
386
+ }, [formulaBarVisible]);
387
+
388
+ const toggleFormulaBar = useCallback(() => {
389
+ setFormulaBarVisible((was) => {
390
+ const next = !was;
391
+ writeFormulaBar(next);
392
+ return next;
393
+ });
394
+ }, []);
395
+
396
+ /** Which registered tab is showing. */
397
  const [active, setActive] = useState<TabId>(TABS[0].id);
398
  const activeTab = TABS.find((tab) => tab.id === active) ?? TABS[0];
399
 
 
599
  /** A plain word inside a control. A ribbon is not an icon quiz. */
600
  const word = (text: string) => <span className="sheet-ribbon-label">{text}</span>;
601
 
602
+ /**
603
+ * A disabled command is intentionally outside the roving registry. Native `disabled` keeps it
604
+ * inert; the visible status and accessible name explain why it does not receive focus or fire.
605
+ */
606
+ const unavailable = (label: string, body: ReactNode) => (
607
+ <button
608
+ type="button"
609
+ className="sheet-ribbon-btn sheet-ribbon-unavailable"
610
+ aria-label={`${label}, unavailable`}
611
+ title={`${label} is unavailable`}
612
+ disabled
613
+ >
614
+ {body}
615
+ <span className="sheet-ribbon-state">Unavailable</span>
616
+ </button>
617
+ );
618
+
619
  // ⭐ W52-T17 β€” the optional 5th argument `kt` is the THIRD-LEVEL key-tip badge (KT-11): a
620
  // gallery item painted with its own letter once the gallery that owns it is open. Additive and
621
  // undefined everywhere this ticket did not touch, so every existing `item(...)` call site keeps
 
639
  const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen";
640
 
641
  const tabContext: RibbonTabContext = {
642
+ style, frozen, open, anchorEl, onApply, apply, act,
643
+ fullscreen, toggleFullscreen, formulaBarVisible, toggleFormulaBar,
644
+ openPop, closePop, control, group, word, unavailable, item, insert,
645
  };
646
 
647
  return (
web/src/sheet/SheetChart.tsx CHANGED
@@ -65,13 +65,15 @@ import { SeriesChart } from "../viz/SeriesChart";
65
  import type { ChartSpec } from "../viz/chartData";
66
  import type { WireField } from "../viz/seriesData";
67
  import type { Row } from "../viz/types";
68
- import type { CellMap, SheetChartDrawnKind, SheetChartSpec } from "./types";
 
 
69
  import { isDrawnChartKind } from "./types";
70
  import { addressOf } from "./sheetState";
71
 
72
  export interface SheetChartProps {
73
  /** Zero-based inclusive rectangle: the cells this chart occupies AND reads (R9, R15). */
74
- range: { col0: number; row0: number; col1: number; row1: number };
75
  cells: CellMap;
76
  kind?: SheetChartSpec["kind"];
77
  /** Rendered size in px. The SVG scales to it; the renderer is not resized. */
@@ -85,8 +87,16 @@ export interface SheetChartProps {
85
  * ⚠ BOTH ARE OPTIONAL, so the component still renders wherever nothing has wired them, and the
86
  * handles simply do not appear rather than moving something nobody will save.
87
  */
88
- onMove?: (dx: number, dy: number) => void;
89
- onResize?: (dx: number, dy: number) => void;
 
 
 
 
 
 
 
 
90
  }
91
 
92
  /** A cell's text, however it is stored. A chart reads what the sheet SHOWS. */
@@ -94,20 +104,158 @@ const textAt = (cells: CellMap, col: number, row: number): string => {
94
  const cell = cells[addressOf(col, row)];
95
  if (!cell) return "";
96
  if (cell.state === "refused") return "";
97
- return cell.display ?? (cell.value == null ? "" : String(cell.value));
98
  };
99
 
100
  /**
101
- * A column is numeric when EVERY non-blank value in it parses as a number.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  *
103
- * ⚠ "every", not "any". One numeric-looking value in a column of labels would otherwise retype the
104
- * whole column and the axis would render nonsense. A wholly blank column stays text, because there
105
- * is no evidence for anything else.
 
 
106
  */
107
- const columnType = (values: string[]): string => {
108
- const filled = values.filter((v) => v.trim() !== "");
109
- if (!filled.length) return "text";
110
- return filled.every((v) => Number.isFinite(Number(v))) ? "int" : "text";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  };
112
 
113
  /**
@@ -650,51 +798,12 @@ export default function SheetChart({
650
  height,
651
  onMove,
652
  onResize,
 
653
  }: SheetChartProps) {
654
- const { fields, rows, series } = useMemo(() => {
655
- const { col0, row0, col1, row1 } = range;
656
- const loCol = Math.min(col0, col1);
657
- const hiCol = Math.max(col0, col1);
658
- const loRow = Math.min(row0, row1);
659
- const hiRow = Math.max(row0, row1);
660
-
661
- // R15: the header ROW names the columns. A blank header still gets a key, because a column
662
- // with no name is still a column and dropping it would silently narrow the chart.
663
- const headers: string[] = [];
664
- for (let c = loCol; c <= hiCol; c += 1) {
665
- headers.push(textAt(cells, c, loRow) || addressOf(c, loRow).replace(/[0-9]+$/, ""));
666
- }
667
-
668
- const body: string[][] = [];
669
- for (let r = loRow + 1; r <= hiRow; r += 1) {
670
- const line: string[] = [];
671
- for (let c = loCol; c <= hiCol; c += 1) line.push(textAt(cells, c, r));
672
- body.push(line);
673
- }
674
-
675
- const keys = headers.map((_h, i) => `c${i}`);
676
- const wire: WireField[] = headers.map((label, i) => ({
677
- key: keys[i],
678
- label,
679
- type: columnType(body.map((line) => line[i] ?? "")),
680
- }));
681
-
682
- const asRows: Row[] = body.map((line, i) => {
683
- const row: Record<string, unknown> = { pid: i + 1 };
684
- line.forEach((value, c) => {
685
- row[keys[c]] = wire[c].type === "int" && value.trim() !== "" ? Number(value) : value;
686
- });
687
- return row as unknown as Row;
688
- });
689
-
690
- // The first column is the x bucket; every numeric column after it is a series.
691
- const valueFields = wire.slice(1).filter((f) => f.type === "int");
692
- return {
693
- fields: wire,
694
- rows: asRows,
695
- series: valueFields.map((f) => ({ y: f.key, label: f.label })),
696
- };
697
- }, [range, cells]);
698
 
699
  const delegated = useMemo<SheetChartDrawnKind | null>(() => {
700
  const viz = VIZ_KIND[kind];
@@ -714,7 +823,14 @@ export default function SheetChart({
714
 
715
  const [nudge, setNudge] = useState<Nudge>(ZERO);
716
  const [flash, setFlash] = useState(false);
717
- const grab = useRef<{ x: number; y: number; mode: "move" | "resize" } | null>(null);
 
 
 
 
 
 
 
718
  const frame = useRef<number | null>(null);
719
 
720
  const stopSettle = useCallback(() => {
@@ -772,18 +888,26 @@ export default function SheetChart({
772
  event.preventDefault();
773
  event.stopPropagation();
774
  stopSettle();
775
- grab.current = { x: event.clientX, y: event.clientY, mode };
 
 
 
 
 
 
 
 
776
  event.currentTarget.setPointerCapture(event.pointerId);
777
  setNudge(ZERO);
778
  }, [stopSettle]);
779
 
780
  const duringDrag = useCallback((event: React.PointerEvent<HTMLButtonElement>) => {
781
  const held = grab.current;
782
- if (!held) return;
783
  // 1:1 with the pointer, from the offset it was grabbed at, so pushing back the way it came
784
  // undoes the drag exactly rather than starting a new one.
785
- const dx = event.clientX - held.x;
786
- const dy = event.clientY - held.y;
787
  setNudge(held.mode === "move"
788
  ? { dx, dy, dw: 0, dh: 0 }
789
  : { dx: 0, dy: 0, dw: dx, dh: dy });
@@ -791,20 +915,34 @@ export default function SheetChart({
791
 
792
  const endDrag = useCallback((event: React.PointerEvent<HTMLButtonElement>) => {
793
  const held = grab.current;
794
- if (!held) return;
795
  grab.current = null;
796
  if (event.currentTarget.hasPointerCapture(event.pointerId)) {
797
  event.currentTarget.releasePointerCapture(event.pointerId);
798
  }
799
- const dx = event.clientX - held.x;
800
- const dy = event.clientY - held.y;
801
- if (held.mode === "move") onMove?.(dx, dy);
802
- else onResize?.(dx, dy);
 
 
 
 
803
  settle(held.mode === "move"
804
- ? { dx, dy, dw: 0, dh: 0 }
805
- : { dx: 0, dy: 0, dw: dx, dh: dy });
806
  }, [onMove, onResize, settle]);
807
 
 
 
 
 
 
 
 
 
 
 
808
  // ⭐ THE DRAG IS NOT THE ONLY WAY, which DESIGN.md requires: the arrow keys walk the anchor one
809
  // cell at a time from the same two controls, and the Insert tab's own dialog sets a range
810
  // outright. A step is this chart's own width over the columns it spans, which IS one column on
@@ -824,17 +962,18 @@ export default function SheetChart({
824
  event.preventDefault();
825
  }, [onMove, onResize, stepX, stepY]);
826
 
827
- const tools = (onMove || onResize) ? (
828
  <div className="sheet-chart-tools">
829
  {onMove ? (
830
  <button
831
  type="button"
832
  className="sheet-chart-tool sheet-chart-grip"
833
- aria-label="Move this chart. Drag it, or use the arrow keys."
 
834
  onPointerDown={beginDrag("move")}
835
  onPointerMove={duringDrag}
836
  onPointerUp={endDrag}
837
- onPointerCancel={endDrag}
838
  onKeyDown={arrowKeys("move")}
839
  >
840
  {/* Four arrows from one centre: the existing set's stroke weight and round caps. */}
@@ -844,6 +983,23 @@ export default function SheetChart({
844
  </svg>
845
  </button>
846
  ) : null}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
847
  {onResize ? (
848
  <button
849
  type="button"
@@ -852,7 +1008,7 @@ export default function SheetChart({
852
  onPointerDown={beginDrag("resize")}
853
  onPointerMove={duringDrag}
854
  onPointerUp={endDrag}
855
- onPointerCancel={endDrag}
856
  onKeyDown={arrowKeys("resize")}
857
  >
858
  {/* The corner angle, the same two-stroke glyph the grid's own edge affordances use. */}
 
65
  import type { ChartSpec } from "../viz/chartData";
66
  import type { WireField } from "../viz/seriesData";
67
  import type { Row } from "../viz/types";
68
+ import type {
69
+ CellMap, SheetChartDrawnKind, SheetChartRange, SheetChartSpec,
70
+ } from "./types";
71
  import { isDrawnChartKind } from "./types";
72
  import { addressOf } from "./sheetState";
73
 
74
  export interface SheetChartProps {
75
  /** Zero-based inclusive rectangle: the cells this chart occupies AND reads (R9, R15). */
76
+ range: SheetChartRange;
77
  cells: CellMap;
78
  kind?: SheetChartSpec["kind"];
79
  /** Rendered size in px. The SVG scales to it; the renderer is not resized. */
 
87
  * ⚠ BOTH ARE OPTIONAL, so the component still renders wherever nothing has wired them, and the
88
  * handles simply do not appear rather than moving something nobody will save.
89
  */
90
+ onMove?: (dx: number, dy: number) => ChartAnchorDelta;
91
+ onResize?: (dx: number, dy: number) => ChartAnchorDelta;
92
+ /** Reopens this chart's persisted kind and range in the shared chart dialog. */
93
+ onEdit?: () => void;
94
+ }
95
+
96
+ /** How far the persisted cell anchor actually moved after a pointer gesture snapped to the grid. */
97
+ export interface ChartAnchorDelta {
98
+ dx: number;
99
+ dy: number;
100
  }
101
 
102
  /** A cell's text, however it is stored. A chart reads what the sheet SHOWS. */
 
104
  const cell = cells[addressOf(col, row)];
105
  if (!cell) return "";
106
  if (cell.state === "refused") return "";
107
+ return cell.display ?? (cell.value == null ? (cell.text ?? "") : String(cell.value));
108
  };
109
 
110
  /**
111
+ * The numeric value of a cell. The stored value wins over presentation, so applying Currency or
112
+ * Percent never turns a number into a text column. A typed string remains eligible, including
113
+ * grouped, currency and percent text, because literal cells intentionally keep what was typed.
114
+ */
115
+ const numberAt = (cells: CellMap, col: number, row: number): number | null => {
116
+ const cell = cells[addressOf(col, row)];
117
+ if (!cell || cell.state === "refused") return null;
118
+ const raw = cell.value ?? cell.text ?? cell.display;
119
+ if (typeof raw === "number") return Number.isFinite(raw) ? raw : null;
120
+ if (typeof raw !== "string") return null;
121
+ let text = raw.trim();
122
+ if (!text) return null;
123
+ const negative = text.startsWith("(") && text.endsWith(")");
124
+ if (negative) text = text.slice(1, -1).trim();
125
+ const percent = text.endsWith("%");
126
+ if (percent) text = text.slice(0, -1).trim();
127
+ text = text.replace(/[,\s]/g, "").replace(/^([$€£])/, "");
128
+ if (!/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(text)) return null;
129
+ const value = Number(text);
130
+ if (!Number.isFinite(value)) return null;
131
+ return (negative ? -value : value) / (percent ? 100 : 1);
132
+ };
133
+
134
+ interface ChartCellValue {
135
+ text: string;
136
+ number: number | null;
137
+ col: number;
138
+ row: number;
139
+ }
140
+
141
+ export interface SheetChartData {
142
+ fields: WireField[];
143
+ rows: Row[];
144
+ series: { y: string; label: string }[];
145
+ }
146
+
147
+ const valueColumn = (values: ChartCellValue[]): boolean => {
148
+ const filled = values.filter((value) => value.text.trim() !== "" || value.number !== null);
149
+ return filled.length > 0 && filled.every((value) => value.number !== null);
150
+ };
151
+
152
+ /**
153
+ * Turn any selected numeric rectangle into the chart engine's category plus series shape.
154
  *
155
+ * A labelled table keeps Excel's first-row/first-column convention. A numeric-only row, column,
156
+ * or block has no labels to infer, so cell addresses become its categories and column letters its
157
+ * series names. This is the missing path that used to make a perfectly valid numeric selection
158
+ * render the empty-chart refusal. The ninth numeric series and everything after it fold into one
159
+ * `Other` series, as DESIGN.md section 3 requires.
160
  */
161
+ export const chartDataForRange = (cells: CellMap, range: SheetChartRange): SheetChartData => {
162
+ const loCol = Math.min(range.col0, range.col1);
163
+ const hiCol = Math.max(range.col0, range.col1);
164
+ const loRow = Math.min(range.row0, range.row1);
165
+ const hiRow = Math.max(range.row0, range.row1);
166
+ const matrix: ChartCellValue[][] = [];
167
+ for (let row = loRow; row <= hiRow; row += 1) {
168
+ const line: ChartCellValue[] = [];
169
+ for (let col = loCol; col <= hiCol; col += 1) {
170
+ line.push({ text: textAt(cells, col, row), number: numberAt(cells, col, row), col, row });
171
+ }
172
+ matrix.push(line);
173
+ }
174
+
175
+ const empty: SheetChartData = { fields: [], rows: [], series: [] };
176
+ if (!matrix.length || !matrix[0]?.length) return empty;
177
+
178
+ // A horizontal numeric run is one measure observed across the selected cells.
179
+ if (matrix.length === 1) {
180
+ const numeric = matrix[0].filter((value) => value.number !== null);
181
+ if (!numeric.length) return empty;
182
+ const named = matrix[0].find((value) => value.number === null && value.text.trim() !== "");
183
+ const fields: WireField[] = [
184
+ { key: "category", label: "Cell", type: "text" },
185
+ { key: "value", label: named?.text ?? "Values", type: "int" },
186
+ ];
187
+ const rows = numeric.map((value, index) => ({
188
+ pid: index + 1,
189
+ category: addressOf(value.col, value.row),
190
+ value: value.number,
191
+ } as unknown as Row));
192
+ return { fields, rows, series: [{ y: "value", label: fields[1].label }] };
193
+ }
194
+
195
+ // A vertical numeric run is the same shape, with row addresses as its category axis.
196
+ if (matrix[0].length === 1) {
197
+ const first = matrix[0][0];
198
+ const header = first.number === null && first.text.trim() !== "" ? first.text : "Values";
199
+ const numeric = matrix.slice(first.number === null ? 1 : 0)
200
+ .map((line) => line[0])
201
+ .filter((value) => value.number !== null);
202
+ if (!numeric.length) return empty;
203
+ const fields: WireField[] = [
204
+ { key: "category", label: "Cell", type: "text" },
205
+ { key: "value", label: header, type: "int" },
206
+ ];
207
+ const rows = numeric.map((value, index) => ({
208
+ pid: index + 1,
209
+ category: addressOf(value.col, value.row),
210
+ value: value.number,
211
+ } as unknown as Row));
212
+ return { fields, rows, series: [{ y: "value", label: fields[1].label }] };
213
+ }
214
+
215
+ const laterHasNumber = matrix.slice(1).some((line) => line.some((value) => value.number !== null));
216
+ const headerRow = laterHasNumber
217
+ && matrix[0].some((value) => value.text.trim() !== "" && value.number === null);
218
+ const body = matrix.slice(headerRow ? 1 : 0);
219
+ if (!body.length) return empty;
220
+
221
+ const numericCols: number[] = [];
222
+ for (let col = 0; col < matrix[0].length; col += 1) {
223
+ if (valueColumn(body.map((line) => line[col]))) numericCols.push(col);
224
+ }
225
+ if (!numericCols.length) return empty;
226
+ const categoryCol = numericCols.includes(0) ? null : 0;
227
+ const sourceCols = numericCols.filter((col) => col !== categoryCol);
228
+ if (!sourceCols.length) return empty;
229
+
230
+ const kept = sourceCols.slice(0, 8);
231
+ const folded = sourceCols.slice(8);
232
+ const seriesFields: WireField[] = kept.map((source, index) => ({
233
+ key: `value${index}`,
234
+ label: headerRow
235
+ ? (matrix[0][source].text || addressOf(loCol + source, loRow).replace(/[0-9]+$/, ""))
236
+ : addressOf(loCol + source, loRow).replace(/[0-9]+$/, ""),
237
+ type: "int",
238
+ }));
239
+ if (folded.length) seriesFields.push({ key: "other", label: "Other", type: "int" });
240
+ const fields: WireField[] = [{ key: "category", label: "Cell", type: "text" }, ...seriesFields];
241
+ const rows = body.map((line, index) => {
242
+ const out: Record<string, unknown> = {
243
+ pid: index + 1,
244
+ category: categoryCol === null
245
+ ? addressOf(loCol, line[0].row)
246
+ : (line[categoryCol].text || addressOf(line[categoryCol].col, line[categoryCol].row)),
247
+ };
248
+ kept.forEach((source, slot) => { out[`value${slot}`] = line[source].number ?? 0; });
249
+ if (folded.length) {
250
+ out.other = folded.reduce((total, source) => total + (line[source].number ?? 0), 0);
251
+ }
252
+ return out as unknown as Row;
253
+ });
254
+ return {
255
+ fields,
256
+ rows,
257
+ series: seriesFields.map((field) => ({ y: field.key, label: field.label })),
258
+ };
259
  };
260
 
261
  /**
 
798
  height,
799
  onMove,
800
  onResize,
801
+ onEdit,
802
  }: SheetChartProps) {
803
+ const { fields, rows, series } = useMemo(
804
+ () => chartDataForRange(cells, range),
805
+ [cells, range],
806
+ );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
807
 
808
  const delegated = useMemo<SheetChartDrawnKind | null>(() => {
809
  const viz = VIZ_KIND[kind];
 
823
 
824
  const [nudge, setNudge] = useState<Nudge>(ZERO);
825
  const [flash, setFlash] = useState(false);
826
+ const grab = useRef<{
827
+ pointerId: number;
828
+ originLeft: number;
829
+ originTop: number;
830
+ offsetX: number;
831
+ offsetY: number;
832
+ mode: "move" | "resize";
833
+ } | null>(null);
834
  const frame = useRef<number | null>(null);
835
 
836
  const stopSettle = useCallback(() => {
 
888
  event.preventDefault();
889
  event.stopPropagation();
890
  stopSettle();
891
+ const rect = event.currentTarget.getBoundingClientRect();
892
+ grab.current = {
893
+ pointerId: event.pointerId,
894
+ originLeft: rect.left,
895
+ originTop: rect.top,
896
+ offsetX: event.clientX - rect.left,
897
+ offsetY: event.clientY - rect.top,
898
+ mode,
899
+ };
900
  event.currentTarget.setPointerCapture(event.pointerId);
901
  setNudge(ZERO);
902
  }, [stopSettle]);
903
 
904
  const duringDrag = useCallback((event: React.PointerEvent<HTMLButtonElement>) => {
905
  const held = grab.current;
906
+ if (!held || held.pointerId !== event.pointerId) return;
907
  // 1:1 with the pointer, from the offset it was grabbed at, so pushing back the way it came
908
  // undoes the drag exactly rather than starting a new one.
909
+ const dx = event.clientX - held.offsetX - held.originLeft;
910
+ const dy = event.clientY - held.offsetY - held.originTop;
911
  setNudge(held.mode === "move"
912
  ? { dx, dy, dw: 0, dh: 0 }
913
  : { dx: 0, dy: 0, dw: dx, dh: dy });
 
915
 
916
  const endDrag = useCallback((event: React.PointerEvent<HTMLButtonElement>) => {
917
  const held = grab.current;
918
+ if (!held || held.pointerId !== event.pointerId) return;
919
  grab.current = null;
920
  if (event.currentTarget.hasPointerCapture(event.pointerId)) {
921
  event.currentTarget.releasePointerCapture(event.pointerId);
922
  }
923
+ const dx = event.clientX - held.offsetX - held.originLeft;
924
+ const dy = event.clientY - held.offsetY - held.originTop;
925
+ const snapped = held.mode === "move" ? onMove?.(dx, dy) : onResize?.(dx, dy);
926
+ // The persisted anchor changes in the same release. Keep only the UNSNAPPED residual in the
927
+ // presentation value, so old anchor + pointer travel equals new anchor + residual and there is
928
+ // no release-frame jump or double movement.
929
+ const residualX = dx - (snapped?.dx ?? 0);
930
+ const residualY = dy - (snapped?.dy ?? 0);
931
  settle(held.mode === "move"
932
+ ? { dx: residualX, dy: residualY, dw: 0, dh: 0 }
933
+ : { dx: 0, dy: 0, dw: residualX, dh: residualY });
934
  }, [onMove, onResize, settle]);
935
 
936
+ const cancelDrag = useCallback((event: React.PointerEvent<HTMLButtonElement>) => {
937
+ const held = grab.current;
938
+ if (!held || held.pointerId !== event.pointerId) return;
939
+ grab.current = null;
940
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {
941
+ event.currentTarget.releasePointerCapture(event.pointerId);
942
+ }
943
+ settle(nudge);
944
+ }, [nudge, settle]);
945
+
946
  // ⭐ THE DRAG IS NOT THE ONLY WAY, which DESIGN.md requires: the arrow keys walk the anchor one
947
  // cell at a time from the same two controls, and the Insert tab's own dialog sets a range
948
  // outright. A step is this chart's own width over the columns it spans, which IS one column on
 
962
  event.preventDefault();
963
  }, [onMove, onResize, stepX, stepY]);
964
 
965
+ const tools = (onMove || onResize || onEdit) ? (
966
  <div className="sheet-chart-tools">
967
  {onMove ? (
968
  <button
969
  type="button"
970
  className="sheet-chart-tool sheet-chart-grip"
971
+ style={{ left: 3, right: onEdit ? 27 : 3, width: "auto" }}
972
+ aria-label="Move chart. Drag this top area, or use the arrow keys."
973
  onPointerDown={beginDrag("move")}
974
  onPointerMove={duringDrag}
975
  onPointerUp={endDrag}
976
+ onPointerCancel={cancelDrag}
977
  onKeyDown={arrowKeys("move")}
978
  >
979
  {/* Four arrows from one centre: the existing set's stroke weight and round caps. */}
 
983
  </svg>
984
  </button>
985
  ) : null}
986
+ {onEdit ? (
987
+ <button
988
+ type="button"
989
+ className="sheet-chart-tool"
990
+ style={{ top: 3, right: 3 }}
991
+ aria-label="Open chart settings"
992
+ onPointerDown={(event) => event.stopPropagation()}
993
+ onClick={(event) => {
994
+ event.stopPropagation();
995
+ onEdit();
996
+ }}
997
+ >
998
+ <svg className="sheet-chart-tool-icon" viewBox="0 0 16 16" aria-hidden="true">
999
+ <path d="M3 4.5h10M3 8h10M3 11.5h10M6 3v3M10 6.5v3M7 10v3" />
1000
+ </svg>
1001
+ </button>
1002
+ ) : null}
1003
  {onResize ? (
1004
  <button
1005
  type="button"
 
1008
  onPointerDown={beginDrag("resize")}
1009
  onPointerMove={duringDrag}
1010
  onPointerUp={endDrag}
1011
+ onPointerCancel={cancelDrag}
1012
  onKeyDown={arrowKeys("resize")}
1013
  >
1014
  {/* The corner angle, the same two-stroke glyph the grid's own edge affordances use. */}
web/src/sheet/SheetGrid.tsx CHANGED
@@ -137,7 +137,9 @@ import Ribbon from "./Ribbon";
137
  // act union it deliberately is not part of. See its own doc comment in `Ribbon.tsx`.
138
  import type { RibbonAction, RibbonInsertDoor } from "./Ribbon";
139
  import { RulesDialog, ValidationDialog } from "./RulesDialog";
 
140
  import SheetChart from "./SheetChart";
 
141
  import ShortcutsPanel from "./ShortcutsPanel";
142
  import { colToIndex, indexToCol } from "./a1";
143
  // β›”β›” W51-T18 β€” THE RULE ENGINE AND THE VALIDATION CHECKER ARE PURE AND SHEET LOCAL, and that is
@@ -155,7 +157,8 @@ import {
155
  // setup needs; `clipboardOps.ts` owns what a copy is made of; `sparkline.ts` is an empty seam that
156
  // answers `false` today. All three were moved or wired without changing a pixel.
157
  import { paintCellBorders, tokenColour } from "./cellBorders";
158
- import { buildCopyPayload, runCopySelection } from "./clipboardOps";
 
159
  import { drawSparkline } from "./sparkline";
160
  // ⭐ W54-T14 / LANE B β€” A CELL'S ATTACHMENTS: the canvas marks, the hover bubble and the door that
161
  // follows a link. `LinkDialog.tsx` owns all three beside the surface that authors them; this file
@@ -167,6 +170,7 @@ import {
167
  } from "./validation";
168
  import {
169
  fontPx, fontStack, formatCellText, stylePaints, sheetExtent,
 
170
  DEFAULT_COL_WIDTH, DEFAULT_SHEET_COLS, DEFAULT_SHEET_ROWS,
171
  MAX_CELL_INDENT, MAX_COL_WIDTH, MIN_COL_WIDTH,
172
  } from "./types";
@@ -174,25 +178,26 @@ import type {
174
  Cell, CellStyle, CellStylePatch, CellValign, SheetChartSpec, SheetRule, SheetTab, Workbook,
175
  } from "./types";
176
  import {
177
- addressOf, appendLineBreak, autoSumFormula, boundDragLabel, cellAt,
178
  cellShiftLabel, cellToValue, clearAll, recalcDependents,
179
  clearCells, clearFormats, commitTyped, cycleAnchors, dateStamp, displayText, drillAffordance,
180
  editableText, fillCells, fillDown, fillRight, findMatches,
181
  isFilled, markOf, noMatchLabel, nothingHiddenLabel, paintPatch, pasteCells,
182
  frozenBandSize, lockstepScrollX,
183
  rememberCut, setFormula, shiftCells, splitAddress, styleCells, styleOf, usedExtent,
184
- viewIndexOf,
185
  visibleIndices, withHidden,
186
  } from "./sheetState";
187
  import type {
188
  CellRange, DragContext, FillEdit, OptionCatalogue, StructureOp,
189
  } from "./sheetState";
 
190
  // β›”β›” W51-T17 β€” ONE TABLE, TWO CONSUMERS. `shortcuts.ts` is the key map AND the panel's rows, and
191
  // it imports NOTHING: see its head note on tsc's emitted root. This file matches against it and
192
  // `ShortcutsPanel.tsx` renders it, so the two cannot advertise different keys.
193
  import { arrowStep, columnBand, commitDirection, commitTarget, edgeIndex, edgeStart,
194
- extendEdgeRect, isArrowKey, matchShortcut, rowBand, shortcutOwner, structureAxis,
195
- tabRunOrigin } from "./shortcuts";
196
  import type { SelectionAxis, SelectionRect, ShortcutId } from "./shortcuts";
197
 
198
  /**
@@ -364,6 +369,12 @@ export interface SheetGridProps {
364
  onUndo: () => void;
365
  onRedo: () => void;
366
  onNotice: (message: string) => void;
 
 
 
 
 
 
367
 
368
  // ── W50-T20 ────────────────────────────────────────────────────────────────────────────────
369
  /**
@@ -436,19 +447,24 @@ export interface SheetGridProps {
436
 
437
  // ── W51-T19, contract C2, rulings R9 and R10 ───────────────────────────────────────────────
438
  /**
439
- * ⭐⭐ THE OPTION ORDER A `down` DRAG WALKS, AND IT IS A SEAM RATHER THAN A FETCH. R10 says a
440
- * bound cell dragged DOWN steps its chosen filter to the next option "in the field's option
441
- * order, or the linked table's view order", which is schema, and THIS COMPONENT IS
442
  * DELIBERATELY SCHEMA FREE: its own head note says so, and reaching for `fetchWorkspace` here
443
  * would make the grid know about databases so that one drag could work.
444
  *
445
- * ⚠ SO IT IS UNDEFINED TODAY, AND THAT IS SPECIFIED BEHAVIOUR RATHER THAN A SHORTFALL. With no
446
- * catalogue a `down` drag copies the filter unchanged and STATES that the options have not
447
- * loaded ({@link boundDragLabel}). It never wraps to the first option and it never sits silent,
448
- * which is the honest degradation the ruling asks for. The engine itself is complete: pass a
449
- * catalogue and the walk happens, which is what `_test/sheetDrag.test.ts` proves.
450
  */
451
  options?: OptionCatalogue;
 
 
 
 
 
 
 
 
452
  }
453
 
454
  /** The corner mark each of R19's three states wears, plus the refusal. Colour rides a token; the
@@ -597,10 +613,10 @@ interface FormulaEditState {
597
  export default function SheetGrid({
598
  workbook, tab, busy = false, onEdit, onViewRows,
599
  formulaBar, onRefresh, onSaveNow, onOpenImport,
600
- onCommit, onUndo, onRedo, onNotice,
601
  onSelect, onStructure, onGrow, onFreeze, onColumnWidth, onHideBands, onRules, onCharts,
602
  onSelectTab,
603
- options,
604
  }: SheetGridProps) {
605
  const [selection, setSelection] = useState<GridSelection | undefined>(undefined);
606
  /**
@@ -720,6 +736,8 @@ export default function SheetGrid({
720
  */
721
  const [chartsLocal, setChartsLocal] =
722
  useState<{ tabId: string; charts: SheetChartSpec[] } | null>(null);
 
 
723
  /** The validation list editor: which addresses it will write, and what the anchor holds now. */
724
  const [listAsk, setListAsk] =
725
  useState<{ addrs: string[]; list: string[] } | null>(null);
@@ -833,6 +851,23 @@ export default function SheetGrid({
833
  // writer produced it.
834
  const localCharts = chartsLocal?.tabId === tab.id ? chartsLocal.charts : tab.charts;
835
  const charts = (onCharts ? tab.charts : localCharts) ?? [];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
836
 
837
  // ⚠ MEMOISED ON A STRING KEY, not on the array. A hidden band is rebuilt on every render (it is
838
  // read through two `??`s), so an array in the dependency list would be a new object every time
@@ -954,6 +989,59 @@ export default function SheetGrid({
954
 
955
  const cells = tab.cells ?? {};
956
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
957
  // ═══════════════════════════════════════════════════════════════════════════════════════════
958
  // ⭐⭐ W53-T01 / RULING R2 / INSTRUCTION 19 β€” THE IN-CELL SHIMMER, AND WHY IT IS DRIVEN RATHER
959
  // THAN DECLARED.
@@ -1864,12 +1952,21 @@ export default function SheetGrid({
1864
  const copiedBlock = useCallback(
1865
  (values: readonly (readonly string[])[]): DragContext | undefined => {
1866
  const held = copiedRef.current;
1867
- if (!held) return options ? { catalogue: options } : undefined;
 
 
1868
  const text = values.map((row) => row.join("\t")).join("\n");
1869
- if (text !== held.text) return options ? { catalogue: options } : undefined;
1870
- return { catalogue: options, cells: held.cells, from: { col: held.col, row: held.row } };
 
 
 
 
 
 
 
1871
  },
1872
- [options],
1873
  );
1874
 
1875
  /**
@@ -1922,13 +2019,24 @@ export default function SheetGrid({
1922
  const edits = { ...dragged, ...screened.edits };
1923
  // ⭐ W53-T01: a fill or a paste can change a cell some OTHER formula reads, so the landing
1924
  // door recalculates its dependents in the same commit every typed edit does.
1925
- if (Object.keys(edits).length > 0) commitWithRecalc(edits);
 
 
 
 
 
 
 
 
 
 
 
1926
  const said = [
1927
  screened.refusals.length > 0 ? refusalLabel(screened.refusals) : "",
1928
  boundDragLabel(out),
1929
  ].filter(Boolean).join(" ");
1930
  if (said) onNotice(said);
1931
- }, [commitWithRecalc, onNotice, tab]);
1932
 
1933
  /**
1934
  * ⭐ THE PASTE IS OURS, NOT GLIDE'S, AND IT RETURNS `false` DELIBERATELY. glide has already
@@ -2006,9 +2114,8 @@ export default function SheetGrid({
2006
  // FORMULA WORK BELOW THEM, and they are diverted INSIDE the one fill primitive rather
2007
  // than by a second pass here. `fillCells` decides on a bound pattern ahead of its
2008
  // formula branch and hands it to `dragBoundCell`; the fill handle, Ctrl+D, Ctrl+R and
2009
- // the paste door all reach that same arithmetic, which is what makes "a locked period
2010
- // copies verbatim through every door" one fact instead of four that agree today.
2011
- { catalogue: options },
2012
  // ⭐ W53-T01 / R2: a dragged formula shows its NUMBER when it lands, not its text.
2013
  cellValueGetter,
2014
  );
@@ -2016,7 +2123,7 @@ export default function SheetGrid({
2016
  // it on every cell it passes, list or no list, so it is screened exactly as the paste is.
2017
  landFill(out, true);
2018
  },
2019
- [cellValueGetter, landFill, options, realCol, realRow, tab],
2020
  );
2021
 
2022
  /** Every address the selection covers, translated. `[]` when nothing is selected. */
@@ -2120,6 +2227,33 @@ export default function SheetGrid({
2120
  if (scroll && at[1] >= 0) gridRef.current?.scrollTo(at[0], at[1]);
2121
  }, [onSelectionChange]);
2122
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2123
  /**
2124
  * Ctrl+PgUp and Ctrl+PgDn. See `onSelectTab` in the props above for why there are two paths.
2125
  *
@@ -2321,7 +2455,7 @@ export default function SheetGrid({
2321
  const at = axis === "row"
2322
  ? realRow(Math.min(range.row0, range.row1)) + 1
2323
  : realCol(Math.min(range.col0, range.col1)) + 1;
2324
- onStructure({ axis, at, delta: insert ? span : -span });
2325
  return;
2326
  }
2327
  const real: CellRange = {
@@ -2335,7 +2469,7 @@ export default function SheetGrid({
2335
  // dependents recompute in the same commit rather than at the next Refresh.
2336
  if (Object.keys(out.edits).length > 0) commitWithRecalc(out.edits);
2337
  onNotice(cellShiftLabel(insert, out.dropped));
2338
- }, [commitWithRecalc, extent.rows, onNotice, onStructure, realCol, realRow, tab, viewRange,
2339
  visCols.length, visRows.length]);
2340
 
2341
  /**
@@ -2469,8 +2603,8 @@ export default function SheetGrid({
2469
  return;
2470
  }
2471
  setMenu(null);
2472
- onStructure({ axis, at: index, delta });
2473
- }, [at, onNotice, onStructure]);
2474
 
2475
  // ═══════════════════════════════════════════════════════════════════════════════════════════
2476
  // ⭐⭐ W51-T16 β€” THE ACTS THEMSELVES. Every one of them ends at `onCommit`, `onStructure`,
@@ -2505,7 +2639,7 @@ export default function SheetGrid({
2505
  * PASTE. glide already handles Ctrl+V through `onPaste`; this is the ribbon's own door, which
2506
  * has to read the clipboard itself because no paste event fired.
2507
  */
2508
- const pasteFromClipboard = useCallback(() => {
2509
  const range = viewRange();
2510
  if (!range) {
2511
  onNotice("Select the top left cell first, then paste.");
@@ -2527,12 +2661,17 @@ export default function SheetGrid({
2527
  { cols: extent.cols, rows: extent.rows }, copiedBlock(values),
2528
  cellValueGetter,
2529
  { col0: realCol(range.col0), row0: realRow(range.row0),
2530
- col1: realCol(range.col1), row1: realRow(range.row1) });
 
 
 
 
 
2531
  if (out.sizeRefusal) {
2532
  onNotice(out.sizeRefusal);
2533
  return;
2534
  }
2535
- landFill(out, false);
2536
  // ⭐ W52-T07: same highlight the glide door sets, from the ribbon's own paste path.
2537
  setPasteHighlight({ col: realCol(range.col0), row: realRow(range.row0),
2538
  cols: values[0]?.length ?? 0, rows: values.length });
@@ -2607,10 +2746,9 @@ export default function SheetGrid({
2607
  col0: realCol(range.col0), row0: realRow(range.row0),
2608
  col1: realCol(range.col1), row1: realRow(range.row1),
2609
  };
2610
- // β›” W51-T19: Ctrl+D and Ctrl+R carry the SAME drag rules the fill handle does, because they
2611
- // are the same operation through a different door. A bound cell filled down keeps its period
2612
- // (R10's `down` defaults to Nothing) and one filled right walks it, whichever door was used.
2613
- const rules: DragContext = { catalogue: options };
2614
  const out = axis === "down" ? fillDown(tab, real, rules) : fillRight(tab, real, rules);
2615
  if (Object.keys(out.edits).length === 0) {
2616
  onNotice(axis === "down"
@@ -2619,7 +2757,7 @@ export default function SheetGrid({
2619
  return;
2620
  }
2621
  landFill(out, false);
2622
- }, [landFill, onNotice, options, realCol, realRow, tab, viewRange]);
2623
 
2624
  /** Clear formats, and clear all. Clear contents is `clearSelection`, which the Delete key uses. */
2625
  const clearSelectionWith = useCallback((which: "formats" | "all") => {
@@ -2940,7 +3078,7 @@ export default function SheetGrid({
2940
  case "import": onOpenImport?.(); return;
2941
 
2942
  // -- Clipboard --------------------------------------------------------------------------
2943
- case "paste": pasteFromClipboard(); return;
2944
  case "cut": copySelection(true); return;
2945
  case "copy": copySelection(false); return;
2946
  case "format-painter": toggleFormatPainter(); return;
@@ -3429,7 +3567,7 @@ export default function SheetGrid({
3429
  // Ctrl+D and Ctrl+R do. A door that reached `fillCells` without them would drag a
3430
  // bound cell by a different rule from the one beside it, which is exactly the split
3431
  // "one primitive, every door" exists to prevent.
3432
- { catalogue: options },
3433
  cellValueGetter,
3434
  );
3435
  if (Object.keys(out.edits).length === 0) {
@@ -3509,9 +3647,9 @@ export default function SheetGrid({
3509
  },
3510
  [addrAt, anchorStyle, applySelection, applyStyle, bandRows, cellValueGetter, commitWithRecalc,
3511
  extent.cols, extent.rows,
3512
- onCommit, onNotice, onRedo, onRibbonAction, onSaveNow, onUndo, openFormulaEditor,
3513
  openNumberFormat, realCol, realRow, selection, structureForSelection, switchTab, tab,
3514
- viewRange, viewRowOf, visCols, visRows],
3515
  );
3516
 
3517
  // ══════════════════════════════════════════════════════════════════════════════════════════
@@ -3575,7 +3713,20 @@ export default function SheetGrid({
3575
  // makes it a controlled horizontal position. Verified in `data-editor.js`.
3576
  // ══════════════════════════════════════════════════════════════════════════════════════════
3577
  const [bandScrollX, setBandScrollX] = useState(0);
3578
- const onVisibleRegionChanged = useCallback((range: Rectangle, tx: number) => {
 
 
 
 
 
 
 
 
 
 
 
 
 
3579
  if (bandRows <= 0) return;
3580
  setBandScrollX(lockstepScrollX(columns.map((c) => c.width), frozenCols, range.x, tx));
3581
  }, [bandRows, columns, frozenCols]);
@@ -4085,21 +4236,27 @@ export default function SheetGrid({
4085
  [realRow, rowHeight, wrapHeights],
4086
  );
4087
  /**
4088
- * ⭐ W54-T12 / LANE B β€” THE ONE CHART WRITER, LIFTED OUT OF `insertDoor` SO THE DRAG CAN SHARE
4089
- * IT. Two writers of one list is the defect this file already carries a rule about: the local
4090
- * fallback and its notice have to read the same whichever gesture produced the new list, or a
4091
- * chart dragged on an unwired page would save while a chart inserted on it would not.
4092
  */
4093
- const writeCharts = useCallback((next: SheetChartSpec[]) => {
4094
- if (!onCharts) {
4095
- setChartsLocal({ tabId: tab.id, charts: next });
4096
- onNotice("This chart sits on the sheet for as long as it stays open. Saving it with the "
4097
- + "workbook arrives with the page's own door.");
4098
- return;
4099
  }
4100
- onCharts(next);
4101
- }, [onCharts, onNotice, tab.id]);
4102
-
 
 
 
 
 
 
 
 
 
 
4103
  /**
4104
  * ⭐⭐ W54-T12 / LANE B β€” A PIXEL DELTA BECOMES A CELL RANGE, AND ONLY THIS FILE CAN DO IT.
4105
  *
@@ -4117,7 +4274,12 @@ export default function SheetGrid({
4117
  * at or past the near one, so a range cannot turn inside out and cannot leave the sheet.
4118
  */
4119
  const nudgeChart = useCallback(
4120
- (chart: SheetChartSpec, dx: number, dy: number, mode: "move" | "resize") => {
 
 
 
 
 
4121
  const lo = Math.min(chart.range.col0, chart.range.col1);
4122
  const hi = Math.max(chart.range.col0, chart.range.col1);
4123
  const top = Math.min(chart.range.row0, chart.range.row1);
@@ -4126,7 +4288,9 @@ export default function SheetGrid({
4126
  const viewHi = visCols.indexOf(hi);
4127
  const viewTop = visRows.indexOf(top);
4128
  const viewBottom = visRows.indexOf(bottom);
4129
- if (viewLo < 0 || viewHi < 0 || viewTop < 0 || viewBottom < 0) return;
 
 
4130
 
4131
  const nearestView = (x: number) => {
4132
  let best = 0;
@@ -4137,6 +4301,24 @@ export default function SheetGrid({
4137
  }
4138
  return best;
4139
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4140
  const clamp = (v: number, low: number, high: number) => Math.min(high, Math.max(low, v));
4141
  const lastCol = visCols.length - 1;
4142
  const lastRow = visRows.length - 1;
@@ -4150,25 +4332,41 @@ export default function SheetGrid({
4150
  nearestView(columnX(viewLo) + dx) - viewLo, -viewLo, lastCol - viewHi,
4151
  );
4152
  const stepRows = clamp(
4153
- Math.round(dy / rowHeight), -viewTop, lastRow - viewBottom,
4154
  );
4155
  nextLo = viewLo + stepCols;
4156
  nextHi = viewHi + stepCols;
4157
  nextTop = viewTop + stepRows;
4158
  nextBottom = viewBottom + stepRows;
4159
  } else {
4160
- nextHi = clamp(nearestView(columnX(viewHi + 1) + dx) - 1, viewLo, lastCol);
4161
- nextBottom = clamp(viewBottom + Math.round(dy / rowHeight), viewTop, lastRow);
 
 
 
 
4162
  }
4163
  const range = {
4164
  col0: visCols[nextLo], col1: visCols[nextHi],
4165
  row0: visRows[nextTop], row1: visRows[nextBottom],
4166
  };
4167
  if (range.col0 === chart.range.col0 && range.col1 === chart.range.col1
4168
- && range.row0 === chart.range.row0 && range.row1 === chart.range.row1) return;
 
 
 
 
 
 
 
 
 
 
 
4169
  writeCharts(charts.map((c) => (c.id === chart.id ? { ...c, range } : c)));
 
4170
  },
4171
- [charts, columnX, rowHeight, visCols, visRows, writeCharts],
4172
  );
4173
 
4174
  /**
@@ -4566,8 +4764,12 @@ export default function SheetGrid({
4566
  if (viewLo < 0 || viewHi < 0 || viewTop < 0 || viewBottom < 0) return null;
4567
  // ⚠ SUMMED, NOT MULTIPLIED (W50-T20). A column width is per column now, so
4568
  // `lo * COL_WIDTH` would drift as soon as anybody dragged one.
4569
- const left = columnX(viewLo);
4570
- const width = columnX(viewHi + 1) - left;
 
 
 
 
4571
  return (
4572
  <div
4573
  key={chart.id}
@@ -4582,9 +4784,9 @@ export default function SheetGrid({
4582
  // over. Origin measured 102 against a true row top of 138.
4583
  style={{
4584
  left,
4585
- top: HEADER_HEIGHT + (bandRows + viewTop) * rowHeight,
4586
  width,
4587
- height: (viewBottom - viewTop + 1) * rowHeight,
4588
  }}
4589
  >
4590
  {/* ⭐ W54-T12 / lane B β€” THE KIND GOES THROUGH RAW. It used to be narrowed to the
@@ -4597,13 +4799,27 @@ export default function SheetGrid({
4597
  cells={cells}
4598
  kind={chart.kind}
4599
  width={width}
4600
- height={(viewBottom - viewTop + 1) * rowHeight}
4601
  onMove={(dx, dy) => nudgeChart(chart, dx, dy, "move")}
4602
  onResize={(dx, dy) => nudgeChart(chart, dx, dy, "resize")}
 
4603
  />
4604
  </div>
4605
  );
4606
  })}
 
 
 
 
 
 
 
 
 
 
 
 
 
4607
  </div>
4608
 
4609
  {/* ⭐⭐ THE RIGHT-CLICK MENU, IN THE HOUSE OVERLAY VOCABULARY. `AnchoredOverlay` is what
 
137
  // act union it deliberately is not part of. See its own doc comment in `Ribbon.tsx`.
138
  import type { RibbonAction, RibbonInsertDoor } from "./Ribbon";
139
  import { RulesDialog, ValidationDialog } from "./RulesDialog";
140
+ import ChartDialog from "./ChartDialog";
141
  import SheetChart from "./SheetChart";
142
+ import type { ChartAnchorDelta } from "./SheetChart";
143
  import ShortcutsPanel from "./ShortcutsPanel";
144
  import { colToIndex, indexToCol } from "./a1";
145
  // β›”β›” W51-T18 β€” THE RULE ENGINE AND THE VALIDATION CHECKER ARE PURE AND SHEET LOCAL, and that is
 
157
  // setup needs; `clipboardOps.ts` owns what a copy is made of; `sparkline.ts` is an empty seam that
158
  // answers `false` today. All three were moved or wired without changing a pixel.
159
  import { paintCellBorders, tokenColour } from "./cellBorders";
160
+ import { buildCopyPayload, pasteModeFrom, runCopySelection } from "./clipboardOps";
161
+ import type { PasteMode } from "./clipboardOps";
162
  import { drawSparkline } from "./sparkline";
163
  // ⭐ W54-T14 / LANE B β€” A CELL'S ATTACHMENTS: the canvas marks, the hover bubble and the door that
164
  // follows a link. `LinkDialog.tsx` owns all three beside the surface that authors them; this file
 
170
  } from "./validation";
171
  import {
172
  fontPx, fontStack, formatCellText, stylePaints, sheetExtent,
173
+ chartRangeAfterStructure,
174
  DEFAULT_COL_WIDTH, DEFAULT_SHEET_COLS, DEFAULT_SHEET_ROWS,
175
  MAX_CELL_INDENT, MAX_COL_WIDTH, MIN_COL_WIDTH,
176
  } from "./types";
 
178
  Cell, CellStyle, CellStylePatch, CellValign, SheetChartSpec, SheetRule, SheetTab, Workbook,
179
  } from "./types";
180
  import {
181
+ addressOf, appendLineBreak, applyStructure, autoSumFormula, boundDragLabel, cellAt,
182
  cellShiftLabel, cellToValue, clearAll, recalcDependents,
183
  clearCells, clearFormats, commitTyped, cycleAnchors, dateStamp, displayText, drillAffordance,
184
  editableText, fillCells, fillDown, fillRight, findMatches,
185
  isFilled, markOf, noMatchLabel, nothingHiddenLabel, paintPatch, pasteCells,
186
  frozenBandSize, lockstepScrollX,
187
  rememberCut, setFormula, shiftCells, splitAddress, styleCells, styleOf, usedExtent,
188
+ structureRefusal, viewIndexOf,
189
  visibleIndices, withHidden,
190
  } from "./sheetState";
191
  import type {
192
  CellRange, DragContext, FillEdit, OptionCatalogue, StructureOp,
193
  } from "./sheetState";
194
+ import type { SavedViewShadow } from "./bindingRefs";
195
  // β›”β›” W51-T17 β€” ONE TABLE, TWO CONSUMERS. `shortcuts.ts` is the key map AND the panel's rows, and
196
  // it imports NOTHING: see its head note on tsc's emitted root. This file matches against it and
197
  // `ShortcutsPanel.tsx` renders it, so the two cannot advertise different keys.
198
  import { arrowStep, columnBand, commitDirection, commitTarget, edgeIndex, edgeStart,
199
+ extendEdgeRect, isArrowKey, KEY_TIP_GRID_ARROW_EVENT, keyTipGridArrow, matchShortcut,
200
+ rowBand, shortcutOwner, structureAxis, tabRunOrigin } from "./shortcuts";
201
  import type { SelectionAxis, SelectionRect, ShortcutId } from "./shortcuts";
202
 
203
  /**
 
369
  onUndo: () => void;
370
  onRedo: () => void;
371
  onNotice: (message: string) => void;
372
+ /**
373
+ * C5's post-commit evaluator. Each entry is the exact bound cell object just landed, so the
374
+ * page can flush the save, compute through Save's one-cell door, and ignore an answer whose
375
+ * binding identity no longer matches.
376
+ */
377
+ onEvaluateBindings?: (request: BoundEvaluationRequest) => void;
378
 
379
  // ── W50-T20 ────────────────────────────────────────────────────────────────────────────────
380
  /**
 
447
 
448
  // ── W51-T19, contract C2, rulings R9 and R10 ───────────────────────────────────────────────
449
  /**
450
+ * ⭐⭐ THE OPTION ORDER A NON-METRIC COPY WALKS, AND IT IS A SEAM RATHER THAN A FETCH.
451
+ * R13 applies the chosen driver's option order in every signed direction, which is schema, and
452
+ * THIS COMPONENT IS
453
  * DELIBERATELY SCHEMA FREE: its own head note says so, and reaching for `fetchWorkspace` here
454
  * would make the grid know about databases so that one drag could work.
455
  *
456
+ * The page loads this alongside `viewShadows`; absence is an explicit incomplete copy reported
457
+ * by {@link boundDragLabel}, never a reason to guess an option or wrap to the beginning.
 
 
 
458
  */
459
  options?: OptionCatalogue;
460
+ /** Canonical saved-View filters loaded before a copy, for R5's local shadow materialisation. */
461
+ viewShadows?: readonly SavedViewShadow[];
462
+ }
463
+
464
+ /** The copied cells that must take the same save-then-compute path as Binding editor Save. */
465
+ export interface BoundEvaluationRequest {
466
+ tabId: string;
467
+ cells: Readonly<Record<string, Cell>>;
468
  }
469
 
470
  /** The corner mark each of R19's three states wears, plus the refusal. Colour rides a token; the
 
613
  export default function SheetGrid({
614
  workbook, tab, busy = false, onEdit, onViewRows,
615
  formulaBar, onRefresh, onSaveNow, onOpenImport,
616
+ onCommit, onUndo, onRedo, onNotice, onEvaluateBindings,
617
  onSelect, onStructure, onGrow, onFreeze, onColumnWidth, onHideBands, onRules, onCharts,
618
  onSelectTab,
619
+ options, viewShadows,
620
  }: SheetGridProps) {
621
  const [selection, setSelection] = useState<GridSelection | undefined>(undefined);
622
  /**
 
736
  */
737
  const [chartsLocal, setChartsLocal] =
738
  useState<{ tabId: string; charts: SheetChartSpec[] } | null>(null);
739
+ /** The one existing chart whose persisted range and kind are open in the shared dialog. */
740
+ const [chartEditId, setChartEditId] = useState<string | null>(null);
741
  /** The validation list editor: which addresses it will write, and what the anchor holds now. */
742
  const [listAsk, setListAsk] =
743
  useState<{ addrs: string[]; list: string[] } | null>(null);
 
851
  // writer produced it.
852
  const localCharts = chartsLocal?.tabId === tab.id ? chartsLocal.charts : tab.charts;
853
  const charts = (onCharts ? tab.charts : localCharts) ?? [];
854
+ const editingChart = charts.find((chart) => chart.id === chartEditId) ?? null;
855
+
856
+ /**
857
+ * The one chart writer. Insert, settings, drag and structure all replace the same tab-level list,
858
+ * so a local fallback cannot disagree with the document depending on which gesture produced it.
859
+ */
860
+ const writeCharts = useCallback((next: SheetChartSpec[]) => {
861
+ if (!onCharts) {
862
+ setChartsLocal({ tabId: tab.id, charts: next });
863
+ onNotice("This chart sits on the sheet for as long as it stays open. Saving it with the "
864
+ + "workbook arrives with the page's own door.");
865
+ return;
866
+ }
867
+ onCharts(next);
868
+ }, [onCharts, onNotice, tab.id]);
869
+
870
+ useEffect(() => setChartEditId(null), [tab.id]);
871
 
872
  // ⚠ MEMOISED ON A STRING KEY, not on the array. A hidden band is rebuilt on every render (it is
873
  // read through two `??`s), so an array in the dependency list would be a new object every time
 
989
 
990
  const cells = tab.cells ?? {};
991
 
992
+ /**
993
+ * A structural write can be accepted immediately, refused, or pause in the page's bound-cell
994
+ * confirmation. Remember the exact expected cell map and update chart anchors only after the
995
+ * accepted structure paints back. Comparing the contents as well as the addresses means a
996
+ * cancelled confirmation followed by an ordinary edit cannot masquerade as acceptance. This
997
+ * retains the page as the one refusal/confirmation authority.
998
+ */
999
+ const pendingChartStructure = useRef<{
1000
+ tabId: string;
1001
+ beforeCells: typeof cells;
1002
+ expectedCells: string;
1003
+ charts: SheetChartSpec[];
1004
+ op: StructureOp;
1005
+ } | null>(null);
1006
+
1007
+ useEffect(() => {
1008
+ pendingChartStructure.current = null;
1009
+ }, [tab.id]);
1010
+
1011
+ const requestStructure = useCallback((op: StructureOp) => {
1012
+ pendingChartStructure.current = null;
1013
+ if (charts.length > 0 && !structureRefusal(workbook, tab.id, op)) {
1014
+ const expected = applyStructure(workbook, tab.id, op)
1015
+ .find((candidate) => candidate.id === tab.id)?.cells ?? {};
1016
+ pendingChartStructure.current = {
1017
+ tabId: tab.id,
1018
+ beforeCells: cells,
1019
+ expectedCells: JSON.stringify(expected),
1020
+ charts: [...charts],
1021
+ op,
1022
+ };
1023
+ }
1024
+ onStructure(op);
1025
+ }, [cells, charts, onStructure, tab.id, workbook]);
1026
+
1027
+ useEffect(() => {
1028
+ const pending = pendingChartStructure.current;
1029
+ if (!pending || pending.tabId !== tab.id || pending.beforeCells === cells) return;
1030
+ pendingChartStructure.current = null;
1031
+ if (JSON.stringify(cells) !== pending.expectedCells) return;
1032
+ const next = pending.charts.map((chart) => ({
1033
+ ...chart,
1034
+ range: chartRangeAfterStructure(chart.range, pending.op, extent),
1035
+ }));
1036
+ const changed = next.some((chart, index) => {
1037
+ const before = pending.charts[index].range;
1038
+ const after = chart.range;
1039
+ return before.col0 !== after.col0 || before.col1 !== after.col1
1040
+ || before.row0 !== after.row0 || before.row1 !== after.row1;
1041
+ });
1042
+ if (changed) writeCharts(next);
1043
+ }, [cells, extent, tab.id, writeCharts]);
1044
+
1045
  // ═══════════════════════════════════════════════════════════════════════════════════════════
1046
  // ⭐⭐ W53-T01 / RULING R2 / INSTRUCTION 19 β€” THE IN-CELL SHIMMER, AND WHY IT IS DRIVEN RATHER
1047
  // THAN DECLARED.
 
1952
  const copiedBlock = useCallback(
1953
  (values: readonly (readonly string[])[]): DragContext | undefined => {
1954
  const held = copiedRef.current;
1955
+ if (!held) {
1956
+ return options || viewShadows ? { catalogue: options, shadows: viewShadows } : undefined;
1957
+ }
1958
  const text = values.map((row) => row.join("\t")).join("\n");
1959
+ if (text !== held.text) {
1960
+ return options || viewShadows
1961
+ ? { catalogue: options, shadows: viewShadows }
1962
+ : undefined;
1963
+ }
1964
+ return {
1965
+ catalogue: options, shadows: viewShadows,
1966
+ cells: held.cells, from: { col: held.col, row: held.row },
1967
+ };
1968
  },
1969
+ [options, viewShadows],
1970
  );
1971
 
1972
  /**
 
2019
  const edits = { ...dragged, ...screened.edits };
2020
  // ⭐ W53-T01: a fill or a paste can change a cell some OTHER formula reads, so the landing
2021
  // door recalculates its dependents in the same commit every typed edit does.
2022
+ if (Object.keys(edits).length > 0) {
2023
+ commitWithRecalc(edits);
2024
+ // C5: schedule only the bound cells that ACTUALLY landed. The page owns save ordering and
2025
+ // revisions, so this seam carries identities instead of calling Refresh or a second writer.
2026
+ const pending: Record<string, Cell> = {};
2027
+ for (const [addr, cell] of Object.entries(edits)) {
2028
+ if (cell?.kind === "bound") pending[addr] = cell;
2029
+ }
2030
+ if (Object.keys(pending).length > 0) {
2031
+ onEvaluateBindings?.({ tabId: tab.id, cells: pending });
2032
+ }
2033
+ }
2034
  const said = [
2035
  screened.refusals.length > 0 ? refusalLabel(screened.refusals) : "",
2036
  boundDragLabel(out),
2037
  ].filter(Boolean).join(" ");
2038
  if (said) onNotice(said);
2039
+ }, [commitWithRecalc, onEvaluateBindings, onNotice, tab]);
2040
 
2041
  /**
2042
  * ⭐ THE PASTE IS OURS, NOT GLIDE'S, AND IT RETURNS `false` DELIBERATELY. glide has already
 
2114
  // FORMULA WORK BELOW THEM, and they are diverted INSIDE the one fill primitive rather
2115
  // than by a second pass here. `fillCells` decides on a bound pattern ahead of its
2116
  // formula branch and hands it to `dragBoundCell`; the fill handle, Ctrl+D, Ctrl+R and
2117
+ // paste therefore share R5's localisation and R13's signed stepping.
2118
+ { catalogue: options, shadows: viewShadows },
 
2119
  // ⭐ W53-T01 / R2: a dragged formula shows its NUMBER when it lands, not its text.
2120
  cellValueGetter,
2121
  );
 
2123
  // it on every cell it passes, list or no list, so it is screened exactly as the paste is.
2124
  landFill(out, true);
2125
  },
2126
+ [cellValueGetter, landFill, options, realCol, realRow, tab, viewShadows],
2127
  );
2128
 
2129
  /** Every address the selection covers, translated. `[]` when nothing is selected. */
 
2227
  if (scroll && at[1] >= 0) gridRef.current?.scrollTo(at[0], at[1]);
2228
  }, [onSelectionChange]);
2229
 
2230
+ /**
2231
+ * W55-T05 / R4: KeyTips consumes its capture-phase key while focus is on the ribbon, then
2232
+ * dispatches one scoped semantic arrow on this wrapper. Move through `applySelection`, the same
2233
+ * selection door used by every sheet-owned key, and return focus to the grid that owns the
2234
+ * landing row. A component-scoped custom event avoids both a synthetic keyboard replay and the
2235
+ * raw global key listener prohibited by the overlay contract.
2236
+ */
2237
+ useEffect(() => {
2238
+ const host = wrapRef.current;
2239
+ if (!host) return;
2240
+ const moveFromKeyTips = (event: Event) => {
2241
+ const key = keyTipGridArrow((event as CustomEvent<{ key?: string }>).detail?.key ?? "");
2242
+ const current = selection?.current?.cell;
2243
+ if (!key || !current) return;
2244
+ const step = arrowStep(key);
2245
+ if (!step) return;
2246
+ const row = Math.max(
2247
+ -bandRows,
2248
+ Math.min(Math.max(0, visRows.length - 1), current[1] + step.dRow),
2249
+ );
2250
+ applySelection({ col0: current[0], row0: row, col1: current[0], row1: row });
2251
+ (row < 0 ? bandGridRef : gridRef).current?.focus();
2252
+ };
2253
+ host.addEventListener(KEY_TIP_GRID_ARROW_EVENT, moveFromKeyTips);
2254
+ return () => host.removeEventListener(KEY_TIP_GRID_ARROW_EVENT, moveFromKeyTips);
2255
+ }, [applySelection, bandRows, selection, visRows.length]);
2256
+
2257
  /**
2258
  * Ctrl+PgUp and Ctrl+PgDn. See `onSelectTab` in the props above for why there are two paths.
2259
  *
 
2455
  const at = axis === "row"
2456
  ? realRow(Math.min(range.row0, range.row1)) + 1
2457
  : realCol(Math.min(range.col0, range.col1)) + 1;
2458
+ requestStructure({ axis, at, delta: insert ? span : -span });
2459
  return;
2460
  }
2461
  const real: CellRange = {
 
2469
  // dependents recompute in the same commit rather than at the next Refresh.
2470
  if (Object.keys(out.edits).length > 0) commitWithRecalc(out.edits);
2471
  onNotice(cellShiftLabel(insert, out.dropped));
2472
+ }, [commitWithRecalc, extent.rows, onNotice, realCol, realRow, requestStructure, tab, viewRange,
2473
  visCols.length, visRows.length]);
2474
 
2475
  /**
 
2603
  return;
2604
  }
2605
  setMenu(null);
2606
+ requestStructure({ axis, at: index, delta });
2607
+ }, [at, onNotice, requestStructure]);
2608
 
2609
  // ═══════════════════════════════════════════════════════════════════════════════════════════
2610
  // ⭐⭐ W51-T16 β€” THE ACTS THEMSELVES. Every one of them ends at `onCommit`, `onStructure`,
 
2639
  * PASTE. glide already handles Ctrl+V through `onPaste`; this is the ribbon's own door, which
2640
  * has to read the clipboard itself because no paste event fired.
2641
  */
2642
+ const pasteFromClipboard = useCallback((mode: PasteMode = "normal") => {
2643
  const range = viewRange();
2644
  if (!range) {
2645
  onNotice("Select the top left cell first, then paste.");
 
2661
  { cols: extent.cols, rows: extent.rows }, copiedBlock(values),
2662
  cellValueGetter,
2663
  { col0: realCol(range.col0), row0: realRow(range.row0),
2664
+ col1: realCol(range.col1), row1: realRow(range.row1) },
2665
+ mode);
2666
+ if (out.layerRefusal) {
2667
+ onNotice(out.layerRefusal);
2668
+ return;
2669
+ }
2670
  if (out.sizeRefusal) {
2671
  onNotice(out.sizeRefusal);
2672
  return;
2673
  }
2674
+ landFill(out, mode === "values");
2675
  // ⭐ W52-T07: same highlight the glide door sets, from the ribbon's own paste path.
2676
  setPasteHighlight({ col: realCol(range.col0), row: realRow(range.row0),
2677
  cols: values[0]?.length ?? 0, rows: values.length });
 
2746
  col0: realCol(range.col0), row0: realRow(range.row0),
2747
  col1: realCol(range.col1), row1: realRow(range.row1),
2748
  };
2749
+ // Ctrl+D and Ctrl+R carry the same copy rules as the fill handle. R13 now advances periods
2750
+ // and chosen filter options in either direction, whichever door was used.
2751
+ const rules: DragContext = { catalogue: options, shadows: viewShadows };
 
2752
  const out = axis === "down" ? fillDown(tab, real, rules) : fillRight(tab, real, rules);
2753
  if (Object.keys(out.edits).length === 0) {
2754
  onNotice(axis === "down"
 
2757
  return;
2758
  }
2759
  landFill(out, false);
2760
+ }, [landFill, onNotice, options, realCol, realRow, tab, viewRange, viewShadows]);
2761
 
2762
  /** Clear formats, and clear all. Clear contents is `clearSelection`, which the Delete key uses. */
2763
  const clearSelectionWith = useCallback((which: "formats" | "all") => {
 
3078
  case "import": onOpenImport?.(); return;
3079
 
3080
  // -- Clipboard --------------------------------------------------------------------------
3081
+ case "paste": pasteFromClipboard(pasteModeFrom(action.arg)); return;
3082
  case "cut": copySelection(true); return;
3083
  case "copy": copySelection(false); return;
3084
  case "format-painter": toggleFormatPainter(); return;
 
3567
  // Ctrl+D and Ctrl+R do. A door that reached `fillCells` without them would drag a
3568
  // bound cell by a different rule from the one beside it, which is exactly the split
3569
  // "one primitive, every door" exists to prevent.
3570
+ { catalogue: options, shadows: viewShadows },
3571
  cellValueGetter,
3572
  );
3573
  if (Object.keys(out.edits).length === 0) {
 
3647
  },
3648
  [addrAt, anchorStyle, applySelection, applyStyle, bandRows, cellValueGetter, commitWithRecalc,
3649
  extent.cols, extent.rows,
3650
+ onCommit, onNotice, onRedo, onRibbonAction, onSaveNow, onUndo, openFormulaEditor, options,
3651
  openNumberFormat, realCol, realRow, selection, structureForSelection, switchTab, tab,
3652
+ viewRange, viewRowOf, viewShadows, visCols, visRows],
3653
  );
3654
 
3655
  // ══════════════════════════════════════════════════════════════════════════════════════════
 
3713
  // makes it a controlled horizontal position. Verified in `data-editor.js`.
3714
  // ══════════════════════════════════════════════════════════════════════════════════════════
3715
  const [bandScrollX, setBandScrollX] = useState(0);
3716
+ /** Glide's own scroll coordinates. Chart anchors consume the same x/y and sub-cell transforms. */
3717
+ const [chartViewport, setChartViewport] = useState({ x: 0, y: 0, tx: 0, ty: 0 });
3718
+ const onVisibleRegionChanged = useCallback((range: Rectangle, tx: number, ty: number) => {
3719
+ const next = {
3720
+ x: Math.max(0, range.x),
3721
+ y: Math.max(0, range.y),
3722
+ tx: Number.isFinite(tx) ? tx : 0,
3723
+ ty: Number.isFinite(ty) ? ty : 0,
3724
+ };
3725
+ setChartViewport((before) => (
3726
+ before.x === next.x && before.y === next.y && before.tx === next.tx && before.ty === next.ty
3727
+ ? before
3728
+ : next
3729
+ ));
3730
  if (bandRows <= 0) return;
3731
  setBandScrollX(lockstepScrollX(columns.map((c) => c.width), frozenCols, range.x, tx));
3732
  }, [bandRows, columns, frozenCols]);
 
4236
  [realRow, rowHeight, wrapHeights],
4237
  );
4238
  /**
4239
+ * Every main-grid row boundary, cached because wrapped rows are not uniformly tall. Building
4240
+ * this once makes each chart's scroll geometry and each pointer-release snap an O(1) lookup.
 
 
4241
  */
4242
+ const chartRowOffsets = useMemo(() => {
4243
+ const offsets = [0];
4244
+ for (let row = 0; row < visRows.length; row += 1) {
4245
+ offsets.push(offsets[row] + rowHeightAt(row));
 
 
4246
  }
4247
+ return offsets;
4248
+ }, [rowHeightAt, visRows.length]);
4249
+ const chartRowY = useCallback(
4250
+ (index: number) => chartRowOffsets[Math.max(0, Math.min(index, visRows.length))] ?? 0,
4251
+ [chartRowOffsets, visRows.length],
4252
+ );
4253
+ const chartScrollX = useMemo(
4254
+ () => lockstepScrollX(
4255
+ columns.map((column) => column.width), frozenCols, chartViewport.x, chartViewport.tx,
4256
+ ),
4257
+ [chartViewport.tx, chartViewport.x, columns, frozenCols],
4258
+ );
4259
+ const chartScrollY = chartRowY(chartViewport.y) - chartViewport.ty;
4260
  /**
4261
  * ⭐⭐ W54-T12 / LANE B β€” A PIXEL DELTA BECOMES A CELL RANGE, AND ONLY THIS FILE CAN DO IT.
4262
  *
 
4274
  * at or past the near one, so a range cannot turn inside out and cannot leave the sheet.
4275
  */
4276
  const nudgeChart = useCallback(
4277
+ (
4278
+ chart: SheetChartSpec,
4279
+ dx: number,
4280
+ dy: number,
4281
+ mode: "move" | "resize",
4282
+ ): ChartAnchorDelta => {
4283
  const lo = Math.min(chart.range.col0, chart.range.col1);
4284
  const hi = Math.max(chart.range.col0, chart.range.col1);
4285
  const top = Math.min(chart.range.row0, chart.range.row1);
 
4288
  const viewHi = visCols.indexOf(hi);
4289
  const viewTop = visRows.indexOf(top);
4290
  const viewBottom = visRows.indexOf(bottom);
4291
+ if (viewLo < 0 || viewHi < 0 || viewTop < 0 || viewBottom < 0) {
4292
+ return { dx: 0, dy: 0 };
4293
+ }
4294
 
4295
  const nearestView = (x: number) => {
4296
  let best = 0;
 
4301
  }
4302
  return best;
4303
  };
4304
+ const nearestColumnBoundary = (x: number) => {
4305
+ let best = 0;
4306
+ let bestGap = Infinity;
4307
+ for (let col = 0; col <= visCols.length; col += 1) {
4308
+ const gap = Math.abs(columnX(col) - x);
4309
+ if (gap < bestGap) { bestGap = gap; best = col; }
4310
+ }
4311
+ return best;
4312
+ };
4313
+ const nearestRow = (y: number) => {
4314
+ let best = 0;
4315
+ let bestGap = Infinity;
4316
+ for (let row = 0; row <= visRows.length; row += 1) {
4317
+ const gap = Math.abs(chartRowY(row) - y);
4318
+ if (gap < bestGap) { bestGap = gap; best = row; }
4319
+ }
4320
+ return best;
4321
+ };
4322
  const clamp = (v: number, low: number, high: number) => Math.min(high, Math.max(low, v));
4323
  const lastCol = visCols.length - 1;
4324
  const lastRow = visRows.length - 1;
 
4332
  nearestView(columnX(viewLo) + dx) - viewLo, -viewLo, lastCol - viewHi,
4333
  );
4334
  const stepRows = clamp(
4335
+ nearestRow(chartRowY(viewTop) + dy) - viewTop, -viewTop, lastRow - viewBottom,
4336
  );
4337
  nextLo = viewLo + stepCols;
4338
  nextHi = viewHi + stepCols;
4339
  nextTop = viewTop + stepRows;
4340
  nextBottom = viewBottom + stepRows;
4341
  } else {
4342
+ nextHi = clamp(
4343
+ nearestColumnBoundary(columnX(viewHi + 1) + dx) - 1, viewLo, lastCol,
4344
+ );
4345
+ nextBottom = clamp(
4346
+ nearestRow(chartRowY(viewBottom + 1) + dy) - 1, viewTop, lastRow,
4347
+ );
4348
  }
4349
  const range = {
4350
  col0: visCols[nextLo], col1: visCols[nextHi],
4351
  row0: visRows[nextTop], row1: visRows[nextBottom],
4352
  };
4353
  if (range.col0 === chart.range.col0 && range.col1 === chart.range.col1
4354
+ && range.row0 === chart.range.row0 && range.row1 === chart.range.row1) {
4355
+ return { dx: 0, dy: 0 };
4356
+ }
4357
+ const snapped = mode === "move"
4358
+ ? {
4359
+ dx: columnX(nextLo) - columnX(viewLo),
4360
+ dy: chartRowY(nextTop) - chartRowY(viewTop),
4361
+ }
4362
+ : {
4363
+ dx: columnX(nextHi + 1) - columnX(viewHi + 1),
4364
+ dy: chartRowY(nextBottom + 1) - chartRowY(viewBottom + 1),
4365
+ };
4366
  writeCharts(charts.map((c) => (c.id === chart.id ? { ...c, range } : c)));
4367
+ return snapped;
4368
  },
4369
+ [chartRowY, charts, columnX, visCols, visRows, writeCharts],
4370
  );
4371
 
4372
  /**
 
4764
  if (viewLo < 0 || viewHi < 0 || viewTop < 0 || viewBottom < 0) return null;
4765
  // ⚠ SUMMED, NOT MULTIPLIED (W50-T20). A column width is per column now, so
4766
  // `lo * COL_WIDTH` would drift as soon as anybody dragged one.
4767
+ const left = columnX(viewLo) - (viewLo >= frozenCols ? chartScrollX : 0);
4768
+ const right = columnX(viewHi + 1) - (viewHi >= frozenCols ? chartScrollX : 0);
4769
+ const width = Math.max(24, right - left);
4770
+ const topPx = HEADER_HEIGHT + bandRows * rowHeight
4771
+ + chartRowY(viewTop) - chartScrollY;
4772
+ const height = Math.max(24, chartRowY(viewBottom + 1) - chartRowY(viewTop));
4773
  return (
4774
  <div
4775
  key={chart.id}
 
4784
  // over. Origin measured 102 against a true row top of 138.
4785
  style={{
4786
  left,
4787
+ top: topPx,
4788
  width,
4789
+ height,
4790
  }}
4791
  >
4792
  {/* ⭐ W54-T12 / lane B β€” THE KIND GOES THROUGH RAW. It used to be narrowed to the
 
4799
  cells={cells}
4800
  kind={chart.kind}
4801
  width={width}
4802
+ height={height}
4803
  onMove={(dx, dy) => nudgeChart(chart, dx, dy, "move")}
4804
  onResize={(dx, dy) => nudgeChart(chart, dx, dy, "resize")}
4805
+ onEdit={() => setChartEditId(chart.id)}
4806
  />
4807
  </div>
4808
  );
4809
  })}
4810
+ {editingChart ? (
4811
+ <ChartDialog
4812
+ key={editingChart.id}
4813
+ selection={editingChart.range}
4814
+ chart={editingChart}
4815
+ restoreFocus
4816
+ onClose={() => setChartEditId(null)}
4817
+ onUpdate={(next) => {
4818
+ writeCharts(charts.map((chart) => (chart.id === next.id ? next : chart)));
4819
+ setChartEditId(null);
4820
+ }}
4821
+ />
4822
+ ) : null}
4823
  </div>
4824
 
4825
  {/* ⭐⭐ THE RIGHT-CLICK MENU, IN THE HOUSE OVERLAY VOCABULARY. `AnchoredOverlay` is what
web/src/sheet/SheetPage.tsx CHANGED
@@ -36,9 +36,10 @@
36
  // ---------------------------------------------------------------------------
37
 
38
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
39
- import type { ReactNode } from "react";
40
  import "../styles/wave49/sheet.css";
41
  import "../styles/wave50/sheet.css";
 
42
  // β›”β›” W51-T09 β€” THE LAUNCHER'S OWN STYLESHEET, AND IT IS NOT OPTIONAL. `.cg-chat-toggle` and
43
  // `.cg-chat-dock` live in `customer-grid/chatDock.css`, which until this ticket ONLY
44
  // `CustomerGrid.tsx` imported. On a direct load of `#/sheet` that chunk is never fetched, so the
@@ -228,6 +229,29 @@ function repairSentence(repairs: readonly IndexRepair[] | undefined): string {
228
  */
229
  const SAVE_DEBOUNCE_MS = 600;
230
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  /** The cache key for one tab's cells. Workbook scoped, so switching books cannot reuse them. */
232
  const tabKeyOf = (workbookId: string, tabId: string): string => `${workbookId}:${tabId}`;
233
 
@@ -357,6 +381,20 @@ export default function SheetPage() {
357
  const saveChainRef = useRef<Promise<void>>(Promise.resolve());
358
  /** Bumped by every local edit, so a save knows whether the tree moved under it. */
359
  const editSeqRef = useRef(0);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
 
361
  // ── W51-T11's five refs ────────────────────────────────────────────────────────────────────
362
 
@@ -723,10 +761,16 @@ export default function SheetPage() {
723
  const sent = await patchTabCells(current.id, tabKey, {
724
  cells, rev: tabRevOf(sheet, current),
725
  });
 
 
 
 
726
  if (sent.ok) {
727
  patchModeRef.current = "patch";
728
  const live = bookRef.current;
729
- if (live && sent.value.rev) applyLocal({ ...live, rev: sent.value.rev });
 
 
730
  const refused = sent.value.refused ?? [];
731
  if (refused.length > 0) {
732
  savedCleanRef.current = false;
@@ -787,7 +831,9 @@ export default function SheetPage() {
787
  // is not written at all.
788
  const whole = await ensureTabs(opening.id, opening.sheets.map((t) => t.id));
789
  const current = bookRef.current;
790
- if (!current) return;
 
 
791
  if (!whole) {
792
  // β›”β›” THE FLAG GOES BACK ON, AND THIS IS THE SAME RE-ARM DISCIPLINE THE DIRTY SET GETS.
793
  // `drainSave` clears `structureDirtyRef` before the await, so a return from here without
@@ -807,18 +853,20 @@ export default function SheetPage() {
807
  const saved = await writeWorkbook(current.id, {
808
  name: current.name, sheets: current.sheets, rev: current.rev,
809
  });
 
810
  if (!saved.ok) {
811
  // β›” A STALE REV IS NOT A DEAD SESSION. Leaving the local `rev` behind would make every
812
  // later save stale too, so editing would be over until someone reloaded the page. The
813
  // workbook is re-read instead, and the reader is told the edit did not land.
814
  if (saved.code === "workbook_revision_stale") {
815
  const fresh = await readWorkbook(current.id);
816
- if (fresh.ok) {
817
  historyRef.current = emptyHistory();
818
  editSeqRef.current += 1;
819
  markAllLoaded(fresh.value);
820
  applyLocal(fresh.value);
821
  }
 
822
  // ⚠ AND HERE THE FLAG STAYS OFF, deliberately. The re-read REPLACED the tree the
823
  // structure change was made in, so there is nothing left to re-send; the sentence above
824
  // is what tells the reader their change did not land.
@@ -834,10 +882,11 @@ export default function SheetPage() {
834
  setNotice(saved.message);
835
  return;
836
  }
 
837
  if (editSeqRef.current === seq) {
838
  markAllLoaded(saved.value);
839
  applyLocal(saved.value);
840
- } else if (bookRef.current) {
841
  applyLocal({ ...bookRef.current, rev: saved.value.rev, updated_at: saved.value.updated_at });
842
  }
843
  }, [applyLocal, ensureTabs, markAllLoaded]);
@@ -852,11 +901,16 @@ export default function SheetPage() {
852
  const drainSave = useCallback(() => {
853
  saveChainRef.current = saveChainRef.current.then(async () => {
854
  if (!bookRef.current) return;
855
- savedCleanRef.current = true;
856
  const structural = structureDirtyRef.current;
857
  structureDirtyRef.current = false;
 
 
 
 
 
 
 
858
  if (!structural && patchModeRef.current !== "put") {
859
- if (dirtyRef.current.size === 0) return;
860
  const outcome = await sendDirtyCells();
861
  if (outcome === "stopped") savedCleanRef.current = false;
862
  // β›” ONLY AN ABSENT ROUTE FALLS THROUGH TO THE PUT, and it falls through in THIS drain so
@@ -881,6 +935,10 @@ export default function SheetPage() {
881
  saveTimerRef.current = null;
882
  drainRef.current();
883
  }
 
 
 
 
884
  }, []);
885
 
886
  /** Drain now, cancelling any pending debounce, and answer when the write has finished. */
@@ -893,6 +951,38 @@ export default function SheetPage() {
893
  return saveChainRef.current;
894
  }, [drainSave]);
895
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
896
  /**
897
  * ⭐⭐ THE DEBOUNCE THE TICKET ASSUMED ALREADY EXISTED. Every commit, undo, redo, binding save
898
  * and structure op calls this; the drain runs once the typing stops.
@@ -1118,6 +1208,93 @@ export default function SheetPage() {
1118
  if (base) commitSheets(moveTab(base, id, step));
1119
  }, [commitSheets]);
1120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1121
  const onRenameTab = useCallback(() => {
1122
  const pending = tabRename;
1123
  const base = bookRef.current;
@@ -1372,37 +1549,52 @@ export default function SheetPage() {
1372
  }, [applyLocal, markAllLoaded]);
1373
 
1374
  const openWorkbook = useCallback(async (id: string) => {
1375
- if (id === bookRef.current?.id) return;
 
1376
  setOpening(true);
1377
  setNotice("");
 
 
 
 
1378
  // ⭐ R4: one tab at a time here too. The meta read carries the tab list and the revision; the
1379
  // tab being opened is the only one whose cells are fetched.
1380
  const got = await readTabMeta(id);
1381
  if (!got.ok) {
1382
  setNotice(got.message);
 
1383
  setOpening(false);
1384
  return;
1385
  }
1386
  adoptWorkbook(got.value, "meta");
1387
  const firstTab = got.value.sheets[0]?.id ?? "";
1388
  if (firstTab) await ensureTabs(got.value.id, [firstTab]);
 
1389
  setOpening(false);
1390
- }, [adoptWorkbook, ensureTabs]);
1391
 
1392
  /** R2's create door: made and OPENED in one act, with no name step in between. */
1393
  const createAndOpen = useCallback(async () => {
 
 
1394
  setOpening(true);
1395
  setNotice("");
 
 
 
 
1396
  const made = await createWorkbook("Untitled workbook");
1397
  if (!made.ok) {
1398
  setNotice(made.message);
 
1399
  setOpening(false);
1400
  return;
1401
  }
1402
  adoptWorkbook(made.value, "all");
1403
  await refreshIndex();
 
1404
  setOpening(false);
1405
- }, [adoptWorkbook, refreshIndex]);
1406
 
1407
  /**
1408
  * ⭐ DUPLICATE IS COMPOSED, NOT ROUTED. Read the source, create an empty workbook, then write
@@ -1410,17 +1602,25 @@ export default function SheetPage() {
1410
  * would be refused as stale against a document that has only ever been at rev 1.
1411
  */
1412
  const duplicateWorkbook = useCallback(async (id: string) => {
 
 
1413
  setOpening(true);
1414
  setNotice("");
 
 
 
 
1415
  const source = await readWorkbook(id);
1416
  if (!source.ok) {
1417
  setNotice(source.message);
 
1418
  setOpening(false);
1419
  return;
1420
  }
1421
  const made = await createWorkbook(`${source.value.name} copy`);
1422
  if (!made.ok) {
1423
  setNotice(made.message);
 
1424
  setOpening(false);
1425
  return;
1426
  }
@@ -1429,13 +1629,15 @@ export default function SheetPage() {
1429
  });
1430
  if (!filled.ok) {
1431
  setNotice(filled.message);
 
1432
  setOpening(false);
1433
  return;
1434
  }
1435
  adoptWorkbook(filled.value, "all");
1436
  await refreshIndex();
 
1437
  setOpening(false);
1438
- }, [adoptWorkbook, refreshIndex]);
1439
 
1440
  /**
1441
  * β›” RENAMING THE OPEN WORKBOOK GOES THROUGH THE SAVE CHAIN, NOT AROUND IT. Reading the
@@ -1443,6 +1645,7 @@ export default function SheetPage() {
1443
  * and sending a second `rev` beside the queued one is exactly the race `put_workbook` refuses.
1444
  */
1445
  const renameWorkbook = useCallback(async (id: string, name: string) => {
 
1446
  setNotice("");
1447
  if (bookRef.current && bookRef.current.id === id) {
1448
  applyLocal({ ...bookRef.current, name });
@@ -1474,6 +1677,7 @@ export default function SheetPage() {
1474
  }, [applyLocal, flushSave, queueSave, refreshIndex]);
1475
 
1476
  const removeWorkbook = useCallback(async (id: string) => {
 
1477
  setNotice("");
1478
  const gone = await deleteWorkbook(id);
1479
  if (!gone.ok) {
@@ -1917,15 +2121,32 @@ export default function SheetPage() {
1917
  A tab bar that shrank the grid would read as "the Sheet broke again", so it takes its
1918
  content height and nothing more, exactly as `.sheet-fx` above it does. */}
1919
  {book && (
1920
- <div className="sheet-ribbon" role="toolbar" aria-label="Sheets">
 
 
 
 
 
1921
  {book.sheets.map((t) => (
1922
  <button
1923
  key={t.id}
1924
  type="button"
 
1925
  className={"sheet-ribbon-btn" + (t.id === (tab?.id ?? "") ? " is-on" : "")}
1926
  aria-pressed={t.id === (tab?.id ?? "")}
1927
- onClick={() => openTab(t.id)}
 
 
 
 
 
 
1928
  onDoubleClick={() => setTabRename({ id: t.id, name: t.name })}
 
 
 
 
 
1929
  // ⚠ THE ELEMENT IS CAPTURED BEFORE THE UPDATER RUNS. Reading `e.currentTarget`
1930
  // inside a state updater is how this app lost an anchor before
1931
  // ([[react-event-currenttarget-updater]]); by then React has moved on.
@@ -1935,7 +2156,7 @@ export default function SheetPage() {
1935
  openTab(t.id);
1936
  setTabMenu({ id: t.id, el });
1937
  }}
1938
- title="Click to open. Double click to rename. Right click for more."
1939
  >
1940
  <span className="sheet-ribbon-label">{t.name}</span>
1941
  </button>
 
36
  // ---------------------------------------------------------------------------
37
 
38
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
39
+ import type { PointerEvent as ReactPointerEvent, ReactNode } from "react";
40
  import "../styles/wave49/sheet.css";
41
  import "../styles/wave50/sheet.css";
42
+ import "../styles/wave55/sheet.css";
43
  // β›”β›” W51-T09 β€” THE LAUNCHER'S OWN STYLESHEET, AND IT IS NOT OPTIONAL. `.cg-chat-toggle` and
44
  // `.cg-chat-dock` live in `customer-grid/chatDock.css`, which until this ticket ONLY
45
  // `CustomerGrid.tsx` imported. On a direct load of `#/sheet` that chunk is never fetched, so the
 
229
  */
230
  const SAVE_DEBOUNCE_MS = 600;
231
 
232
+ /**
233
+ * A workbook identity change may wait for persistence, but it may not strand the rail forever
234
+ * behind an unreachable store. On expiry the identity stays put and the in-flight save keeps its
235
+ * ordinary recovery path; the person can retry the switch after that path settles.
236
+ */
237
+ const SAVE_FLUSH_TIMEOUT_MS = 5_000;
238
+
239
+ /** A pointer drag starts only after ordinary click slop, so click and double click keep working. */
240
+ const TAB_DRAG_SLOP_PX = 4;
241
+
242
+ interface TabDrag {
243
+ workbookId: string;
244
+ tabId: string;
245
+ pointerId: number;
246
+ element: HTMLButtonElement;
247
+ originX: number;
248
+ grabOffsetX: number;
249
+ width: number;
250
+ startIndex: number;
251
+ targetIndex: number;
252
+ moved: boolean;
253
+ }
254
+
255
  /** The cache key for one tab's cells. Workbook scoped, so switching books cannot reuse them. */
256
  const tabKeyOf = (workbookId: string, tabId: string): string => `${workbookId}:${tabId}`;
257
 
 
381
  const saveChainRef = useRef<Promise<void>>(Promise.resolve());
382
  /** Bumped by every local edit, so a save knows whether the tree moved under it. */
383
  const editSeqRef = useRef(0);
384
+ /**
385
+ * A workbook identity transition is single-flight even though the rail stays interactive while
386
+ * the main pane shows its opening spinner. State alone cannot guard the second click: React may
387
+ * not have committed `opening` before another rail event runs, so this ref closes the boundary
388
+ * synchronously and prevents an older, slower read from winning after a newer choice.
389
+ */
390
+ const workbookTransitionRef = useRef(false);
391
+ /** The bottom tab strip and its one pointer-captured drag. High-frequency motion stays in DOM. */
392
+ const tabStripRef = useRef<HTMLDivElement | null>(null);
393
+ const tabDragRef = useRef<TabDrag | null>(null);
394
+ /** A completed drag emits a click after pointerup; consume that click instead of opening twice. */
395
+ const suppressTabClickRef = useRef("");
396
+ /** Clears suppression when a browser emits no post-drag click (for example after release outside). */
397
+ const suppressTabClickTimerRef = useRef<number | null>(null);
398
 
399
  // ── W51-T11's five refs ────────────────────────────────────────────────────────────────────
400
 
 
761
  const sent = await patchTabCells(current.id, tabKey, {
762
  cells, rev: tabRevOf(sheet, current),
763
  });
764
+ // A workbook transition normally waits for this request. This identity fence is the
765
+ // second line of defence for a timed-out or overlapping transition: an old response may
766
+ // finish, but it can never lend its revision, notice or recovery tree to the new book.
767
+ if (bookRef.current?.id !== current.id) return "stopped";
768
  if (sent.ok) {
769
  patchModeRef.current = "patch";
770
  const live = bookRef.current;
771
+ if (live?.id === current.id && sent.value.rev) {
772
+ applyLocal({ ...live, rev: sent.value.rev });
773
+ }
774
  const refused = sent.value.refused ?? [];
775
  if (refused.length > 0) {
776
  savedCleanRef.current = false;
 
831
  // is not written at all.
832
  const whole = await ensureTabs(opening.id, opening.sheets.map((t) => t.id));
833
  const current = bookRef.current;
834
+ // `ensureTabs` awaits network reads. If another transition won while those reads were away,
835
+ // never turn that newer workbook into the subject of this older drain.
836
+ if (!current || current.id !== opening.id) return;
837
  if (!whole) {
838
  // β›”β›” THE FLAG GOES BACK ON, AND THIS IS THE SAME RE-ARM DISCIPLINE THE DIRTY SET GETS.
839
  // `drainSave` clears `structureDirtyRef` before the await, so a return from here without
 
853
  const saved = await writeWorkbook(current.id, {
854
  name: current.name, sheets: current.sheets, rev: current.rev,
855
  });
856
+ if (bookRef.current?.id !== current.id) return;
857
  if (!saved.ok) {
858
  // β›” A STALE REV IS NOT A DEAD SESSION. Leaving the local `rev` behind would make every
859
  // later save stale too, so editing would be over until someone reloaded the page. The
860
  // workbook is re-read instead, and the reader is told the edit did not land.
861
  if (saved.code === "workbook_revision_stale") {
862
  const fresh = await readWorkbook(current.id);
863
+ if (fresh.ok && bookRef.current?.id === current.id) {
864
  historyRef.current = emptyHistory();
865
  editSeqRef.current += 1;
866
  markAllLoaded(fresh.value);
867
  applyLocal(fresh.value);
868
  }
869
+ if (bookRef.current?.id !== current.id) return;
870
  // ⚠ AND HERE THE FLAG STAYS OFF, deliberately. The re-read REPLACED the tree the
871
  // structure change was made in, so there is nothing left to re-send; the sentence above
872
  // is what tells the reader their change did not land.
 
882
  setNotice(saved.message);
883
  return;
884
  }
885
+ if (bookRef.current?.id !== current.id) return;
886
  if (editSeqRef.current === seq) {
887
  markAllLoaded(saved.value);
888
  applyLocal(saved.value);
889
+ } else if (bookRef.current?.id === current.id) {
890
  applyLocal({ ...bookRef.current, rev: saved.value.rev, updated_at: saved.value.updated_at });
891
  }
892
  }, [applyLocal, ensureTabs, markAllLoaded]);
 
901
  const drainSave = useCallback(() => {
902
  saveChainRef.current = saveChainRef.current.then(async () => {
903
  if (!bookRef.current) return;
 
904
  const structural = structureDirtyRef.current;
905
  structureDirtyRef.current = false;
906
+ const hasPendingCells = dirtyRef.current.size > 0;
907
+ // A flush appends a drain behind any request already in flight. If that request refuses,
908
+ // the appended drain may find nothing to send; it must not turn the refusal back into a
909
+ // clean result merely by existing. Only a drain that owns real pending authored work may
910
+ // clear the prior failure, and each refusal path below sets it false again.
911
+ if (!structural && !hasPendingCells) return;
912
+ savedCleanRef.current = true;
913
  if (!structural && patchModeRef.current !== "put") {
 
914
  const outcome = await sendDirtyCells();
915
  if (outcome === "stopped") savedCleanRef.current = false;
916
  // β›” ONLY AN ABSENT ROUTE FALLS THROUGH TO THE PUT, and it falls through in THIS drain so
 
935
  saveTimerRef.current = null;
936
  drainRef.current();
937
  }
938
+ if (suppressTabClickTimerRef.current !== null) {
939
+ window.clearTimeout(suppressTabClickTimerRef.current);
940
+ suppressTabClickTimerRef.current = null;
941
+ }
942
  }, []);
943
 
944
  /** Drain now, cancelling any pending debounce, and answer when the write has finished. */
 
951
  return saveChainRef.current;
952
  }, [drainSave]);
953
 
954
+ /**
955
+ * C2's bounded barrier before a workbook identity changes.
956
+ *
957
+ * `flushSave` is intentionally called before the target workbook is even requested or created:
958
+ * the old workbook must keep owning `bookRef`, its dirty addresses and its revision until the
959
+ * final queued write has settled. A timeout does not cancel that write. It leaves the current
960
+ * workbook in place, which lets the ordinary stale-revision/refusal recovery finish without a
961
+ * late response ever being adopted into a different workbook.
962
+ */
963
+ const flushBeforeWorkbookChange = useCallback(async (): Promise<boolean> => {
964
+ const leavingId = bookRef.current?.id;
965
+ if (!leavingId) return true;
966
+ let timer: number | null = null;
967
+ const outcome = await Promise.race([
968
+ flushSave().then(() => "flushed" as const),
969
+ new Promise<"timeout">((resolve) => {
970
+ timer = window.setTimeout(() => resolve("timeout"), SAVE_FLUSH_TIMEOUT_MS);
971
+ }),
972
+ ]);
973
+ if (timer !== null) window.clearTimeout(timer);
974
+ if (outcome === "timeout") {
975
+ setNotice("This workbook is still saving. Wait for it to finish before opening another one.");
976
+ workbookTransitionRef.current = false;
977
+ return false;
978
+ }
979
+ // A refusal already left its exact sentence in `notice`. Do not hide it behind a generic
980
+ // transition error, and do not clear the dirty tree by adopting another workbook.
981
+ const mayChange = savedCleanRef.current && bookRef.current?.id === leavingId;
982
+ if (!mayChange) workbookTransitionRef.current = false;
983
+ return mayChange;
984
+ }, [flushSave]);
985
+
986
  /**
987
  * ⭐⭐ THE DEBOUNCE THE TICKET ASSUMED ALREADY EXISTED. Every commit, undo, redo, binding save
988
  * and structure op calls this; the drain runs once the typing stops.
 
1208
  if (base) commitSheets(moveTab(base, id, step));
1209
  }, [commitSheets]);
1210
 
1211
+ /** Capture the whole tab, preserving the exact point inside it that the pointer grabbed. */
1212
+ const startTabDrag = useCallback((id: string, event: ReactPointerEvent<HTMLButtonElement>) => {
1213
+ if (event.button !== 0 || !bookRef.current || tabDragRef.current) return;
1214
+ const element = event.currentTarget;
1215
+ const rect = element.getBoundingClientRect();
1216
+ const startIndex = bookRef.current.sheets.findIndex((sheet) => sheet.id === id);
1217
+ if (startIndex < 0) return;
1218
+ element.setPointerCapture(event.pointerId);
1219
+ element.dataset.dragging = "true";
1220
+ element.setAttribute("aria-grabbed", "true");
1221
+ tabDragRef.current = {
1222
+ workbookId: bookRef.current.id,
1223
+ tabId: id,
1224
+ pointerId: event.pointerId,
1225
+ element,
1226
+ originX: event.clientX,
1227
+ grabOffsetX: event.clientX - rect.left,
1228
+ width: rect.width,
1229
+ startIndex,
1230
+ targetIndex: startIndex,
1231
+ moved: false,
1232
+ };
1233
+ }, []);
1234
+
1235
+ /**
1236
+ * Gesture frames write only a transform and a target index. React state would re-layout the
1237
+ * flex row on every pointermove; keeping siblings still gives the grabbed tab 1:1 tracking.
1238
+ */
1239
+ const moveTabDrag = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {
1240
+ const held = tabDragRef.current;
1241
+ if (!held || held.pointerId !== event.pointerId) return;
1242
+ const delta = event.clientX - held.originX;
1243
+ if (!held.moved && Math.abs(delta) < TAB_DRAG_SLOP_PX) return;
1244
+ held.moved = true;
1245
+ event.preventDefault();
1246
+ held.element.style.setProperty("--sheet-tab-drag-x", `${delta}px`);
1247
+
1248
+ const strip = tabStripRef.current;
1249
+ if (!strip) return;
1250
+ const draggedCenter = event.clientX - held.grabOffsetX + (held.width / 2);
1251
+ const peers = Array.from(
1252
+ strip.querySelectorAll<HTMLButtonElement>("button[data-sheet-tab-id]"),
1253
+ );
1254
+ held.targetIndex = peers.reduce((index, peer) => {
1255
+ if (peer === held.element) return index;
1256
+ const box = peer.getBoundingClientRect();
1257
+ return draggedCenter > box.left + (box.width / 2) ? index + 1 : index;
1258
+ }, 0);
1259
+ }, []);
1260
+
1261
+ const finishTabDrag = useCallback((
1262
+ event: ReactPointerEvent<HTMLButtonElement>, commit: boolean,
1263
+ ) => {
1264
+ const held = tabDragRef.current;
1265
+ if (!held || held.pointerId !== event.pointerId) return;
1266
+ tabDragRef.current = null;
1267
+ delete held.element.dataset.dragging;
1268
+ held.element.removeAttribute("aria-grabbed");
1269
+ held.element.style.removeProperty("--sheet-tab-drag-x");
1270
+ if (held.element.hasPointerCapture(held.pointerId)) {
1271
+ held.element.releasePointerCapture(held.pointerId);
1272
+ }
1273
+ if (!commit || !held.moved) return;
1274
+ suppressTabClickRef.current = held.tabId;
1275
+ if (suppressTabClickTimerRef.current !== null) {
1276
+ window.clearTimeout(suppressTabClickTimerRef.current);
1277
+ }
1278
+ // `click` normally follows this pointerup before the next task. If release happened outside
1279
+ // and no click arrives, do not let a stale suppression consume the person's next real click.
1280
+ suppressTabClickTimerRef.current = window.setTimeout(() => {
1281
+ if (suppressTabClickRef.current === held.tabId) suppressTabClickRef.current = "";
1282
+ suppressTabClickTimerRef.current = null;
1283
+ }, 0);
1284
+
1285
+ const base = bookRef.current;
1286
+ if (!base || base.id !== held.workbookId) return;
1287
+ let at = base.sheets.findIndex((sheet) => sheet.id === held.tabId);
1288
+ const target = Math.max(0, Math.min(held.targetIndex, base.sheets.length - 1));
1289
+ let ordered = base.sheets;
1290
+ while (at >= 0 && at !== target) {
1291
+ const step = target > at ? 1 : -1;
1292
+ ordered = moveTab({ ...base, sheets: ordered }, held.tabId, step);
1293
+ at += step;
1294
+ }
1295
+ if (ordered !== base.sheets) commitSheets(ordered);
1296
+ }, [commitSheets]);
1297
+
1298
  const onRenameTab = useCallback(() => {
1299
  const pending = tabRename;
1300
  const base = bookRef.current;
 
1549
  }, [applyLocal, markAllLoaded]);
1550
 
1551
  const openWorkbook = useCallback(async (id: string) => {
1552
+ if (id === bookRef.current?.id || workbookTransitionRef.current) return;
1553
+ workbookTransitionRef.current = true;
1554
  setOpening(true);
1555
  setNotice("");
1556
+ if (!await flushBeforeWorkbookChange()) {
1557
+ setOpening(false);
1558
+ return;
1559
+ }
1560
  // ⭐ R4: one tab at a time here too. The meta read carries the tab list and the revision; the
1561
  // tab being opened is the only one whose cells are fetched.
1562
  const got = await readTabMeta(id);
1563
  if (!got.ok) {
1564
  setNotice(got.message);
1565
+ workbookTransitionRef.current = false;
1566
  setOpening(false);
1567
  return;
1568
  }
1569
  adoptWorkbook(got.value, "meta");
1570
  const firstTab = got.value.sheets[0]?.id ?? "";
1571
  if (firstTab) await ensureTabs(got.value.id, [firstTab]);
1572
+ workbookTransitionRef.current = false;
1573
  setOpening(false);
1574
+ }, [adoptWorkbook, ensureTabs, flushBeforeWorkbookChange]);
1575
 
1576
  /** R2's create door: made and OPENED in one act, with no name step in between. */
1577
  const createAndOpen = useCallback(async () => {
1578
+ if (workbookTransitionRef.current) return;
1579
+ workbookTransitionRef.current = true;
1580
  setOpening(true);
1581
  setNotice("");
1582
+ if (!await flushBeforeWorkbookChange()) {
1583
+ setOpening(false);
1584
+ return;
1585
+ }
1586
  const made = await createWorkbook("Untitled workbook");
1587
  if (!made.ok) {
1588
  setNotice(made.message);
1589
+ workbookTransitionRef.current = false;
1590
  setOpening(false);
1591
  return;
1592
  }
1593
  adoptWorkbook(made.value, "all");
1594
  await refreshIndex();
1595
+ workbookTransitionRef.current = false;
1596
  setOpening(false);
1597
+ }, [adoptWorkbook, flushBeforeWorkbookChange, refreshIndex]);
1598
 
1599
  /**
1600
  * ⭐ DUPLICATE IS COMPOSED, NOT ROUTED. Read the source, create an empty workbook, then write
 
1602
  * would be refused as stale against a document that has only ever been at rev 1.
1603
  */
1604
  const duplicateWorkbook = useCallback(async (id: string) => {
1605
+ if (workbookTransitionRef.current) return;
1606
+ workbookTransitionRef.current = true;
1607
  setOpening(true);
1608
  setNotice("");
1609
+ if (!await flushBeforeWorkbookChange()) {
1610
+ setOpening(false);
1611
+ return;
1612
+ }
1613
  const source = await readWorkbook(id);
1614
  if (!source.ok) {
1615
  setNotice(source.message);
1616
+ workbookTransitionRef.current = false;
1617
  setOpening(false);
1618
  return;
1619
  }
1620
  const made = await createWorkbook(`${source.value.name} copy`);
1621
  if (!made.ok) {
1622
  setNotice(made.message);
1623
+ workbookTransitionRef.current = false;
1624
  setOpening(false);
1625
  return;
1626
  }
 
1629
  });
1630
  if (!filled.ok) {
1631
  setNotice(filled.message);
1632
+ workbookTransitionRef.current = false;
1633
  setOpening(false);
1634
  return;
1635
  }
1636
  adoptWorkbook(filled.value, "all");
1637
  await refreshIndex();
1638
+ workbookTransitionRef.current = false;
1639
  setOpening(false);
1640
+ }, [adoptWorkbook, flushBeforeWorkbookChange, refreshIndex]);
1641
 
1642
  /**
1643
  * β›” RENAMING THE OPEN WORKBOOK GOES THROUGH THE SAVE CHAIN, NOT AROUND IT. Reading the
 
1645
  * and sending a second `rev` beside the queued one is exactly the race `put_workbook` refuses.
1646
  */
1647
  const renameWorkbook = useCallback(async (id: string, name: string) => {
1648
+ if (workbookTransitionRef.current) return;
1649
  setNotice("");
1650
  if (bookRef.current && bookRef.current.id === id) {
1651
  applyLocal({ ...bookRef.current, name });
 
1677
  }, [applyLocal, flushSave, queueSave, refreshIndex]);
1678
 
1679
  const removeWorkbook = useCallback(async (id: string) => {
1680
+ if (workbookTransitionRef.current) return;
1681
  setNotice("");
1682
  const gone = await deleteWorkbook(id);
1683
  if (!gone.ok) {
 
2121
  A tab bar that shrank the grid would read as "the Sheet broke again", so it takes its
2122
  content height and nothing more, exactly as `.sheet-fx` above it does. */}
2123
  {book && (
2124
+ <div
2125
+ ref={tabStripRef}
2126
+ className="sheet-ribbon sheet-tab-strip"
2127
+ role="toolbar"
2128
+ aria-label="Sheets"
2129
+ >
2130
  {book.sheets.map((t) => (
2131
  <button
2132
  key={t.id}
2133
  type="button"
2134
+ data-sheet-tab-id={t.id}
2135
  className={"sheet-ribbon-btn" + (t.id === (tab?.id ?? "") ? " is-on" : "")}
2136
  aria-pressed={t.id === (tab?.id ?? "")}
2137
+ onClick={() => {
2138
+ if (suppressTabClickRef.current === t.id) {
2139
+ suppressTabClickRef.current = "";
2140
+ return;
2141
+ }
2142
+ openTab(t.id);
2143
+ }}
2144
  onDoubleClick={() => setTabRename({ id: t.id, name: t.name })}
2145
+ onPointerDown={(event) => startTabDrag(t.id, event)}
2146
+ onPointerMove={moveTabDrag}
2147
+ onPointerUp={(event) => finishTabDrag(event, true)}
2148
+ onPointerCancel={(event) => finishTabDrag(event, false)}
2149
+ onLostPointerCapture={(event) => finishTabDrag(event, false)}
2150
  // ⚠ THE ELEMENT IS CAPTURED BEFORE THE UPDATER RUNS. Reading `e.currentTarget`
2151
  // inside a state updater is how this app lost an anchor before
2152
  // ([[react-event-currenttarget-updater]]); by then React has moved on.
 
2156
  openTab(t.id);
2157
  setTabMenu({ id: t.id, el });
2158
  }}
2159
+ title="Click to open. Drag to reorder. Double click to rename. Right click for more."
2160
  >
2161
  <span className="sheet-ribbon-label">{t.name}</span>
2162
  </button>
web/src/sheet/bindingRefs.ts CHANGED
@@ -61,6 +61,8 @@ interface RefSlotSpec {
61
  readonly path: readonly string[];
62
  /** A path to a truthy value that freezes this slot. Absent means nothing freezes it. */
63
  readonly pinnedAt?: readonly string[];
 
 
64
  }
65
 
66
  /**
@@ -71,7 +73,17 @@ interface RefSlotSpec {
71
  * and paste door starts shifting it correctly on the same commit.
72
  */
73
  const REF_SLOTS: readonly RefSlotSpec[] = [
74
- { key: "period.ref", path: ["period", "ref"], pinnedAt: ["period", "locked"] },
 
 
 
 
 
 
 
 
 
 
75
  ];
76
 
77
  /** What one occupied slot IS, right now, with its anchoring already parsed out per axis. */
@@ -154,7 +166,7 @@ export const bindingRefSlots = (binding: unknown): BindingRefSlot[] => {
154
  path: spec.path,
155
  text,
156
  parsed: parseRef(text),
157
- pinned: flagAt(record, spec.pinnedAt),
158
  });
159
  }
160
  return out;
@@ -195,3 +207,112 @@ export const shiftBindingRefs = (
195
  }
196
  return { binding: out, changed: moved.length > 0, moved };
197
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  readonly path: readonly string[];
62
  /** A path to a truthy value that freezes this slot. Absent means nothing freezes it. */
63
  readonly pinnedAt?: readonly string[];
64
+ /** A binding-wide rule that freezes this slot even without a flag at its own path. */
65
+ readonly pinnedWhen?: (binding: Record<string, unknown>) => boolean;
66
  }
67
 
68
  /**
 
73
  * and paste door starts shifting it correctly on the same commit.
74
  */
75
  const REF_SLOTS: readonly RefSlotSpec[] = [
76
+ {
77
+ key: "period.ref",
78
+ path: ["period", "ref"],
79
+ pinnedAt: ["period", "locked"],
80
+ // R13: turning period stepping off clones the WHOLE period, including a relative source ref.
81
+ pinnedWhen: (binding) => {
82
+ const rule = binding.onDrag;
83
+ return Boolean(rule && typeof rule === "object" && !Array.isArray(rule)
84
+ && (rule as Record<string, unknown>).across === "none");
85
+ },
86
+ },
87
  ];
88
 
89
  /** What one occupied slot IS, right now, with its anchoring already parsed out per axis. */
 
166
  path: spec.path,
167
  text,
168
  parsed: parseRef(text),
169
+ pinned: flagAt(record, spec.pinnedAt) || Boolean(spec.pinnedWhen?.(record)),
170
  });
171
  }
172
  return out;
 
207
  }
208
  return { binding: out, changed: moved.length > 0, moved };
209
  };
210
+
211
+ // ── W55-T07, contract C6: fields a cell filter depends on ───────────────────────────────────
212
+ //
213
+ // This stays structural and import-free on purpose. `bindingRefs.ts` is a leaf used by the Sheet
214
+ // node proofs, and importing the customer-grid filter types here would move tsc's emitted root.
215
+ // The stored dialect is still the exact FilterTree dialect.
216
+
217
+ // W55-T08 / C5: copied saved Views become local filters before their drivers step.
218
+ /** One canonical saved-View filter returned by the Sheet server for copying. */
219
+ export interface SavedViewShadow {
220
+ readonly database: string;
221
+ readonly viewId: string;
222
+ readonly filter: unknown;
223
+ }
224
+
225
+ /** What localising one binding did. Missing means the caller must not pretend R5 completed. */
226
+ export interface LocalViewBinding {
227
+ readonly binding: Record<string, unknown>;
228
+ readonly localized: boolean;
229
+ readonly missing: boolean;
230
+ }
231
+
232
+ /**
233
+ * Copy JSON-shaped filter state without sharing any record or array with the saved View snapshot.
234
+ * The filter language stays structural here so this leaf module does not import UI types.
235
+ */
236
+ const copyJson = (value: unknown): unknown => {
237
+ if (Array.isArray(value)) return value.map(copyJson);
238
+ const record = asRecord(value);
239
+ if (!record) return value;
240
+ return Object.fromEntries(Object.entries(record).map(([key, child]) => [key, copyJson(child)]));
241
+ };
242
+
243
+ /**
244
+ * R5's materialisation boundary. A saved-View binding becomes a filter-scoped binding before any
245
+ * driver walks it. The original binding and the server-owned shadow are never mutated.
246
+ *
247
+ * A binding that is already local is returned untouched. A missing saved-View shadow is explicit
248
+ * so the copy door can say that it has not completed instead of silently retaining shared state.
249
+ */
250
+ export const materializeLocalViewBinding = (
251
+ binding: Record<string, unknown>, shadows: readonly SavedViewShadow[] | undefined,
252
+ ): LocalViewBinding => {
253
+ const scope = asRecord(binding.scope);
254
+ const viewId = typeof scope?.view_id === "string" ? scope.view_id.trim() : "";
255
+ if (!viewId) return { binding, localized: false, missing: false };
256
+ const database = typeof binding.database === "string" ? binding.database.trim() : "";
257
+ const found = (shadows ?? []).find(
258
+ (shadow) => shadow.database === database && shadow.viewId === viewId,
259
+ );
260
+ if (!found || !asRecord(found.filter)) {
261
+ return { binding, localized: false, missing: true };
262
+ }
263
+ return {
264
+ binding: { ...binding, scope: { filter: copyJson(found.filter) } },
265
+ localized: true,
266
+ missing: false,
267
+ };
268
+ };
269
+
270
+ // W55-T07 / C6 continues with the filter fields a cell View must show.
271
+ /** Every real field key a filter names, including nested groups and right-hand field operands. */
272
+ export const filterFieldKeys = (tree: unknown): string[] => {
273
+ const root = asRecord(tree);
274
+ const seen = new Set<string>();
275
+ const add = (value: unknown) => {
276
+ const key = typeof value === "string" ? value.trim() : "";
277
+ // Cohort and View membership leaves are filter vocabulary, not database fields.
278
+ if (key && !key.startsWith("__")) seen.add(key);
279
+ };
280
+ const walk = (nodes: unknown) => {
281
+ if (!Array.isArray(nodes)) return;
282
+ for (const raw of nodes) {
283
+ const node = asRecord(raw);
284
+ if (!node) continue;
285
+ if (Array.isArray(node.children)) {
286
+ walk(node.children);
287
+ continue;
288
+ }
289
+ add(node.colId);
290
+ const rhs = asRecord(node.rhs);
291
+ if (rhs) add(rhs.colId);
292
+ }
293
+ };
294
+ walk(root?.nodes);
295
+ return [...seen];
296
+ };
297
+
298
+ /**
299
+ * C6's visible-field law: a person's ordered choice (or the database defaults) UNION every
300
+ * field the filter needs. Invalid/stale field keys are removed, and the identity key stays first.
301
+ */
302
+ export const cellViewVisibleKeys = (
303
+ defaults: readonly string[],
304
+ preferred: readonly string[],
305
+ filterKeys: readonly string[],
306
+ available: readonly string[],
307
+ identity = "",
308
+ ): string[] => {
309
+ const valid = new Set(available);
310
+ const out: string[] = [];
311
+ const add = (key: string) => {
312
+ if (key && valid.has(key) && !out.includes(key)) out.push(key);
313
+ };
314
+ if (identity) add(identity);
315
+ for (const key of preferred.length ? preferred : defaults) add(key);
316
+ for (const key of filterKeys) add(key);
317
+ return out;
318
+ };
web/src/sheet/cellBorders.ts CHANGED
@@ -1,15 +1,13 @@
1
  // ---------------------------------------------------------------------------------------------
2
  // sheet/cellBorders.ts β€” THE PER-CELL BORDER PAINT, LIFTED OUT OF `SheetGrid.tsx`.
3
  //
4
- // ⭐ WAVE 54 BASE KIT β€” this is a SEAM, not a redesign. Every line below was moved verbatim out of
5
- // `SheetGrid.tsx::paintCell` step 4 so that the border work and the rest of the hub file can be
6
- // edited by two different lanes at once. The move itself changed nothing; W54-T01 then changed the
7
- // LEFT and TOP geometry here, for the reason written on `paintCellBorders` below. Order of sides,
8
- // stroke colour, line width, the single stroke and the save/restore pair are all still the ones
9
- // that came over.
10
  //
11
- // β›” `tokenColour` CAME ALONG, AND THAT IS A FENCE DECISION RATHER THAN A DESIGN ONE. The stroke
12
- // setup reads `--lp-line-strong` through `SheetGrid.tsx`'s own memoised token resolver, which was
13
  // a module-local `const` there and is not exported. The three ways out were: import it back from
14
  // `SheetGrid.tsx` (a cycle, and a NEW export on the file this split exists to shrink), copy it
15
  // (two caches for one palette), or move the definition here and let `SheetGrid.tsx` import it.
@@ -21,15 +19,15 @@
21
  import type { CellBorder } from "./types";
22
 
23
  /**
24
- * A `--lp-*` token name resolved to the hue the document currently gives it.
25
  *
26
  * ⭐ MEMOISED, BECAUSE `drawCell` RUNS PER CELL PER FRAME. `getComputedStyle` forces a style
27
  * recalculation on every call, and a 26 by 40 viewport of styled cells would ask for it a
28
  * thousand times a frame. The tokens are declared once on `:root` and nothing in this app swaps
29
  * a palette at runtime, so one read each is the whole of it.
30
  *
31
- * ⚠ THE FALLBACK IS THE INK, NOT BLACK. A token that has been renamed out of the palette must
32
- * still leave a readable cell rather than an invisible one.
33
  */
34
  const TOKEN_CACHE = new Map<string, string>();
35
  export const tokenColour = (token: string, fallback: string): string => {
@@ -42,73 +40,47 @@ export const tokenColour = (token: string, fallback: string): string => {
42
  return value || fallback;
43
  };
44
 
 
 
 
 
 
 
45
  /**
46
- * THE CELL'S OWN BORDERS, painted onto `rect`.
47
- *
48
- * β›”β›” THE INSET IS ASYMMETRIC ON PURPOSE: LEFT AND TOP SIT A PIXEL FURTHER IN THAN RIGHT AND
49
- * BOTTOM, AND TIDYING ALL FOUR BACK TO A SYMMETRIC HALF PIXEL RE-BREAKS THE FEATURE. Before
50
- * W54-T01 all four sides were laid on the cell's own edge at a half pixel, and "All sides" then
51
- * painted a visible right and bottom with NO left and NO top. Two independent mechanisms of the
52
- * grid library eat those two strokes, and both of them are escaped by the same one pixel move
53
- * inward:
54
- * 1. THE DAMAGE CLIP. `data-grid-render.cells` clips each cell to a box that starts at
55
- * `cellX + 1` and `drawY + 1` while running flush to the right and bottom edges, so
56
- * anything we draw left of `cellX + 1` or above `drawY + 1` is discarded outright. A nested
57
- * clip can only ever intersect that one, so it cannot be widened from in here.
58
- * 2. THE LIBRARY'S OWN GRID LINES. `data-grid-render` draws its light grid AFTER the cells, on
59
- * the same context, at exactly `cellX + 0.5` and `drawY + 0.5` in the theme's border
60
- * colour. Those are the very device pixels our left and top strokes used to occupy, so even
61
- * an unclipped stroke there would be painted over on every frame. The right stroke at
62
- * `width - 0.5` and the bottom at `height - 0.5` land a pixel inside and are never touched,
63
- * which is exactly why the bug looked like "only two sides work".
64
- *
65
- * ⚠ THE OFFSET IS 1.5 AND NOT 1.0. At 1.5 the stroke covers one whole device pixel column or row
66
- * inside the clip and clear of the library's line, at full intensity. At 1.0 a one pixel wide
67
- * stroke straddles the clip boundary: half of it is clipped away and the other half is overpainted
68
- * by the library's grid line, giving a faint smear rather than a border.
69
  *
70
- * ⚠ A STROKE POSITION IS NOT A RUN EXTENT, and conflating the two is what hid this for two waves.
71
- * `strokeX*` / `strokeY*` say WHERE a line lies along its own thin axis. `runFrom*` / `runTo*` say
72
- * how far it travels along the other axis. The runs start at the cell's own half pixel edge and
73
- * let the damage clip trim them, which is what makes all four corners meet on a fully covered
74
- * pixel with no antialiased gap.
75
- *
76
- * ⚠ THE CALLER PAINTS THIS OUTSIDE ITS TEXT CLIP, so a side lands on the cell edge rather than
77
- * deep inside it. That is the caller's business and the reason the call sits where it does in
78
- * `paintCell`; this function only assumes it is free to save and restore the context. The frozen
79
- * band needs no separate handling: `paintFrozenCell` delegates to `paintCell`, so it is the same
80
- * paint.
81
- *
82
- * ⚠ AN ABSENT `border` IS NOT AN ERROR, it is the ordinary case: {@link CellBorder} carries only
83
- * the sides that are ON, and a cell with no border at all has no `border` key. The early return
84
- * is the `if (border)` guard the call site used to hold, said one scope down.
85
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  export function paintCellBorders(
87
  ctx: CanvasRenderingContext2D,
88
- rect: { x: number; y: number; width: number; height: number },
89
  border: CellBorder | undefined,
90
  ): void {
91
  if (!border) return;
 
 
92
  ctx.save();
93
- ctx.strokeStyle = tokenColour("--lp-line-strong", "#c9ced8");
94
- ctx.lineWidth = 1;
95
- ctx.beginPath();
96
- // Where each side's thin line lies. Left and top are inset a further pixel to clear the damage
97
- // clip and the library's own grid line; right and bottom already sit inside both.
98
- const strokeXLeft = rect.x + 1.5;
99
- const strokeYTop = rect.y + 1.5;
100
- const strokeXRight = rect.x + rect.width - 0.5;
101
- const strokeYBottom = rect.y + rect.height - 0.5;
102
- // How far each side travels. Starts on the cell's own edge so the clip trims it to a whole
103
- // pixel and the corners meet the perpendicular stroke exactly.
104
- const runFromX = rect.x + 0.5;
105
- const runToX = strokeXRight;
106
- const runFromY = rect.y + 0.5;
107
- const runToY = strokeYBottom;
108
- if (border.top) { ctx.moveTo(runFromX, strokeYTop); ctx.lineTo(runToX, strokeYTop); }
109
- if (border.bottom) { ctx.moveTo(runFromX, strokeYBottom); ctx.lineTo(runToX, strokeYBottom); }
110
- if (border.left) { ctx.moveTo(strokeXLeft, runFromY); ctx.lineTo(strokeXLeft, runToY); }
111
- if (border.right) { ctx.moveTo(strokeXRight, runFromY); ctx.lineTo(strokeXRight, runToY); }
112
- ctx.stroke();
113
  ctx.restore();
114
  }
 
1
  // ---------------------------------------------------------------------------------------------
2
  // sheet/cellBorders.ts β€” THE PER-CELL BORDER PAINT, LIFTED OUT OF `SheetGrid.tsx`.
3
  //
4
+ // ⭐ WAVE 54 BASE KIT β€” this is the border seam lifted from `SheetGrid.tsx::paintCell`, so border
5
+ // geometry can change without disturbing the grid's selection, chart, marquee or formula paint.
6
+ // W55-T05 makes the live cell rectangle the source for four filled edge strips and gives inserted
7
+ // borders their explicit black default. Both main and frozen grids still call this one paint door.
 
 
8
  //
9
+ // β›” `tokenColour` CAME ALONG, AND THAT IS A FENCE DECISION RATHER THAN A DESIGN ONE. Border paint
10
+ // and the grid's other canvas paint read CSS properties through one memoised resolver, which was
11
  // a module-local `const` there and is not exported. The three ways out were: import it back from
12
  // `SheetGrid.tsx` (a cycle, and a NEW export on the file this split exists to shrink), copy it
13
  // (two caches for one palette), or move the definition here and let `SheetGrid.tsx` import it.
 
19
  import type { CellBorder } from "./types";
20
 
21
  /**
22
+ * A CSS custom-property name resolved to the hue the document currently gives it.
23
  *
24
  * ⭐ MEMOISED, BECAUSE `drawCell` RUNS PER CELL PER FRAME. `getComputedStyle` forces a style
25
  * recalculation on every call, and a 26 by 40 viewport of styled cells would ask for it a
26
  * thousand times a frame. The tokens are declared once on `:root` and nothing in this app swaps
27
  * a palette at runtime, so one read each is the whole of it.
28
  *
29
+ * Each caller supplies its own safe fallback. Inserted cell borders deliberately supply black;
30
+ * other canvas paint keeps the existing palette fallbacks owned by `SheetGrid`.
31
  */
32
  const TOKEN_CACHE = new Map<string, string>();
33
  export const tokenColour = (token: string, fallback: string): string => {
 
40
  return value || fallback;
41
  };
42
 
43
+ /** The executable default for an inserted border. The stylesheet publishes the same value. */
44
+ export const DEFAULT_CELL_BORDER_COLOR = "#000000";
45
+
46
+ export interface CellBorderRect { x: number; y: number; width: number; height: number }
47
+ type BorderStrip = CellBorderRect;
48
+
49
  /**
50
+ * Turn the current Glide cell rectangle into its four one-pixel inner edge strips.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  *
52
+ * The cell rectangle is the source on every paint, so fractional scroll positions and browser
53
+ * zoom cannot leave a cached border behind. `+ 1` is Glide's first paintable coordinate during a
54
+ * damage repaint; the strip starts there and touches the grid line without the half-pixel stroke
55
+ * inset that made left/top visibly different from right/bottom. Filled strips avoid antialiasing
56
+ * and survive the light grid lines Glide paints after cell content.
 
 
 
 
 
 
 
 
 
 
57
  */
58
+ export function cellBorderStrips(rect: CellBorderRect, border: CellBorder): BorderStrip[] {
59
+ const left = rect.x + 1;
60
+ const top = rect.y + 1;
61
+ const right = rect.x + rect.width;
62
+ const bottom = rect.y + rect.height;
63
+ const width = Math.max(0, right - left);
64
+ const height = Math.max(0, bottom - top);
65
+ const strips: BorderStrip[] = [];
66
+ if (border.top && width > 0) strips.push({ x: left, y: top, width, height: 1 });
67
+ if (border.right && height > 0) strips.push({ x: right - 1, y: top, width: 1, height });
68
+ if (border.bottom && width > 0) strips.push({ x: left, y: bottom - 1, width, height: 1 });
69
+ if (border.left && height > 0) strips.push({ x: left, y: top, width: 1, height });
70
+ return strips;
71
+ }
72
+
73
+ /** Paint the cell's own enabled edges outside the caller's text clip. */
74
  export function paintCellBorders(
75
  ctx: CanvasRenderingContext2D,
76
+ rect: CellBorderRect,
77
  border: CellBorder | undefined,
78
  ): void {
79
  if (!border) return;
80
+ const strips = cellBorderStrips(rect, border);
81
+ if (strips.length === 0) return;
82
  ctx.save();
83
+ ctx.fillStyle = tokenColour("--sheet-cell-border", DEFAULT_CELL_BORDER_COLOR);
84
+ strips.forEach((strip) => ctx.fillRect(strip.x, strip.y, strip.width, strip.height));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  ctx.restore();
86
  }
web/src/sheet/cellStyleOps.ts CHANGED
@@ -139,6 +139,24 @@ export const clearAll = (
139
  export const styleOf = (cell: Cell | null | undefined): CellStyle | null =>
140
  cell?.style ? { ...cell.style } : null;
141
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  /**
143
  * β›”β›” EVERY KEY `CellStyle` CARRIES, AND A MISSING ONE IS A SILENT HALF-PAINT. The Format painter
144
  * REPLACES a style rather than merging into it, so it has to say `null` for the keys the picked
 
139
  export const styleOf = (cell: Cell | null | undefined): CellStyle | null =>
140
  cell?.style ? { ...cell.style } : null;
141
 
142
+ /** Replace only a cell's formatting layer, preserving content and every other target layer. */
143
+ export const replaceCellStyle = (
144
+ cell: Cell | null | undefined,
145
+ style: CellStyle | null | undefined,
146
+ ): Cell | null => {
147
+ if (style) {
148
+ const base: Cell = cell ?? { kind: "empty", state: "fresh" };
149
+ return { ...base, style: { ...style } };
150
+ }
151
+ if (!cell?.style) return cell ?? null;
152
+ const next: Cell = { ...cell };
153
+ delete next.style;
154
+ if (next.kind === "empty" && !next.validation && !next.link && !next.note && !next.sparkline) {
155
+ return null;
156
+ }
157
+ return next;
158
+ };
159
+
160
  /**
161
  * β›”β›” EVERY KEY `CellStyle` CARRIES, AND A MISSING ONE IS A SILENT HALF-PAINT. The Format painter
162
  * REPLACES a style rather than merging into it, so it has to say `null` for the keys the picked
web/src/sheet/clipboardOps.ts CHANGED
@@ -28,6 +28,14 @@ import { editableText, rawDisplayText, rememberCopy, rememberCut } from "./sheet
28
  import type { Cell, CellMap } from "./types";
29
  import { formatCellText } from "./types";
30
 
 
 
 
 
 
 
 
 
31
  /**
32
  * WHAT A COPY OF `range` PUTS ON THE CLIPBOARD, AND WHAT THE COMPONENT REMEMBERS ABOUT IT.
33
  *
 
28
  import type { Cell, CellMap } from "./types";
29
  import { formatCellText } from "./types";
30
 
31
+ /** The three clipboard layers a paste command may apply. Normal is the full cell payload. */
32
+ export const PASTE_MODES = ["normal", "values", "formatting"] as const;
33
+ export type PasteMode = (typeof PASTE_MODES)[number];
34
+
35
+ /** Narrow a ribbon argument at the clipboard boundary; unknown arguments remain normal paste. */
36
+ export const pasteModeFrom = (value: unknown): PasteMode =>
37
+ value === "values" || value === "formatting" ? value : "normal";
38
+
39
  /**
40
  * WHAT A COPY OF `range` PUTS ON THE CLIPBOARD, AND WHAT THE COMPONENT REMEMBERS ABOUT IT.
41
  *
web/src/sheet/ribbonData.tsx ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Sheet Data ribbon, behaviorally adapted from the Wave 55 public Excel audit. The commands below
2
+ // stay within Sheet's existing executable actions; unavailable audit commands remain visible and
3
+ // honest rather than becoming no-op affordances.
4
+
5
+ import type { RibbonTabContext } from "./Ribbon";
6
+
7
+ const DATA = ["data-refresh"] as const;
8
+ const OUTLINE = ["data-hide-rows", "data-hide-columns", "data-unhide"] as const;
9
+
10
+ export const DATA_KEYS = [...DATA, ...OUTLINE] as const;
11
+
12
+ function IconRefresh() {
13
+ return (
14
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
15
+ <path d="M13 8a5 5 0 1 1-1.6-3.7" />
16
+ <path d="M13.2 2.6v3.2h-3.2" />
17
+ </svg>
18
+ );
19
+ }
20
+
21
+ function IconBand({ column = false }: { column?: boolean }) {
22
+ return (
23
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
24
+ <rect x="2.5" y="2.5" width="11" height="11" rx="1" />
25
+ {column ? <path d="M6.2 2.5v11M9.8 2.5v11" /> : <path d="M2.5 6.2h11M2.5 9.8h11" />}
26
+ </svg>
27
+ );
28
+ }
29
+
30
+ export const dataGroups = (ctx: RibbonTabContext) => {
31
+ const { act, control, group, unavailable, word } = ctx;
32
+ return (
33
+ <>
34
+ {group("Data", (
35
+ <>
36
+ {control(
37
+ "data-refresh", "Refresh all", <><IconRefresh />{word("Refresh all")}</>,
38
+ () => act("refresh"), false, undefined, "R",
39
+ )}
40
+ {unavailable("Queries and connections", word("Queries and connections"))}
41
+ </>
42
+ ))}
43
+ {group("Sort", (
44
+ <>
45
+ {unavailable("Sort ascending", word("Sort ascending"))}
46
+ {unavailable("Sort descending", word("Sort descending"))}
47
+ </>
48
+ ))}
49
+ {group("Auto filter", unavailable("Filter", word("Filter")))}
50
+ {group("Data validation", unavailable("Data validation", word("Data validation")))}
51
+ {group("Data tools", (
52
+ <>
53
+ {unavailable("Split text to columns", word("Text to columns"))}
54
+ {unavailable("Flash fill", word("Flash fill"))}
55
+ {unavailable("Remove duplicates", word("Remove duplicates"))}
56
+ </>
57
+ ))}
58
+ {group("Outline", (
59
+ <>
60
+ {control(
61
+ "data-hide-rows", "Hide rows", <><IconBand />{word("Hide rows")}</>,
62
+ () => act("hide-rows"), false, undefined, "HR",
63
+ )}
64
+ {control(
65
+ "data-hide-columns", "Hide columns", <><IconBand column />{word("Hide columns")}</>,
66
+ () => act("hide-columns"), false, undefined, "HC",
67
+ )}
68
+ {control(
69
+ "data-unhide", "Unhide rows and columns", word("Unhide"),
70
+ () => act("unhide"), false, undefined, "U",
71
+ )}
72
+ </>
73
+ ))}
74
+ </>
75
+ );
76
+ };
77
+
78
+ export const DATA_TAB = {
79
+ id: "data",
80
+ key: "tab-data",
81
+ kt: "A",
82
+ label: "Data",
83
+ bodyClass: "sheet-ribbon-data",
84
+ toolbarLabel: "Data",
85
+ keys: DATA_KEYS,
86
+ groups: dataGroups,
87
+ } as const;
web/src/sheet/ribbonFormulas.tsx ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Sheet Formulas ribbon, adapted from the behavior and grouping recorded in
2
+ // `.claude/wiki/waves/wave55/planning/excel-online-audit.md`. This is an original Loopable
3
+ // expression: it reuses the ribbon primitives and closed action vocabulary, never external
4
+ // source, assets, or private class names. Commands without an executable Sheet door say so.
5
+
6
+ import type { RibbonTabContext } from "./Ribbon";
7
+ import { IconAutoSum } from "./ribbonIcons";
8
+
9
+ const FUNCTION_LIBRARY = ["formula-autosum"] as const;
10
+ const DATA = ["formula-refresh"] as const;
11
+
12
+ export const FORMULAS_KEYS = [...FUNCTION_LIBRARY, ...DATA] as const;
13
+
14
+ function IconCalculate() {
15
+ return (
16
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
17
+ <path d="M12.8 7.8a4.8 4.8 0 1 1-1.5-3.5" />
18
+ <path d="M12.9 2.6v3.2H9.7" />
19
+ </svg>
20
+ );
21
+ }
22
+
23
+ export const formulasGroups = (ctx: RibbonTabContext) => {
24
+ const { act, control, group, unavailable, word } = ctx;
25
+ return (
26
+ <>
27
+ {group("Function library", (
28
+ <>
29
+ {unavailable("Insert function", word("Insert function"))}
30
+ {control(
31
+ "formula-autosum", "AutoSum", <><IconAutoSum />{word("AutoSum")}</>,
32
+ () => act("autosum"), false, undefined, "U",
33
+ )}
34
+ {unavailable("More functions", word("More functions"))}
35
+ </>
36
+ ))}
37
+ {group("Name manager", unavailable("Name manager", word("Name manager")))}
38
+ {group("Show formulas", unavailable("Show formulas", word("Show formulas")))}
39
+ {group("Data", (
40
+ <>
41
+ {control(
42
+ "formula-refresh", "Calculate now", <><IconCalculate />{word("Calculate now")}</>,
43
+ () => act("refresh"), false, undefined, "C",
44
+ )}
45
+ {unavailable("Calculation options", word("Calculation options"))}
46
+ </>
47
+ ))}
48
+ </>
49
+ );
50
+ };
51
+
52
+ export const FORMULAS_TAB = {
53
+ id: "formulas",
54
+ key: "tab-formulas",
55
+ kt: "M",
56
+ label: "Formulas",
57
+ bodyClass: "sheet-ribbon-formulas",
58
+ toolbarLabel: "Formulas",
59
+ keys: FORMULAS_KEYS,
60
+ groups: formulasGroups,
61
+ } as const;
web/src/sheet/ribbonHome.tsx CHANGED
@@ -509,20 +509,28 @@ export const homeGroups = (ctx: RibbonTabContext) => {
509
  EXPLICITLY: a large split Paste on the left (icon above, caption below) with Cut,
510
  Copy and Format painter stacked as three small icon+label rows to its right,
511
  exactly like Excel's own Clipboard group.
512
- ⚠ DOCUMENTED DEVIATION (contract C4) β€” real Excel's Paste is a SPLIT button: a
513
- direct click pastes, and a separate caret opens Paste Special and friends. This
514
- app's `RibbonActionKind` union (`SheetGrid.tsx`'s exhaustive switch, OUTSIDE this
515
- ticket's file fence) has no act for those sub-options, and adding one is lane B's
516
- surface, not this ticket's. So Paste stays a SINGLE button here β€” same tall
517
- left-slot layout Excel uses, still firing `act("paste")` directly on click, with
518
- `data-kt="V"` and no `data-kt-opens` (it does not actually open a menu in this
519
- codebase). The LAYOUT is what instruction 18 and R4 ask for; the backend act stays
520
- exactly what W51-T16 already built. */}
521
  {group("Clipboard", (
522
  <div className="sheet-ribbon-clip">
523
  <span className="sheet-ribbon-paste-large">
524
  {control("paste", "Paste", <>{<IconPaste />}{word("Paste")}</>,
525
- () => act("paste"), false, undefined, "V")}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
526
  </span>
527
  {/* ⭐⭐ W53-T06 (owner instruction 17) β€” CUT, COPY AND FORMAT PAINTER ARE ICONS,
528
  WITH NO WORD BESIDE THEM. Excel's Clipboard group is one large captioned Paste
 
509
  EXPLICITLY: a large split Paste on the left (icon above, caption below) with Cut,
510
  Copy and Format painter stacked as three small icon+label rows to its right,
511
  exactly like Excel's own Clipboard group.
512
+ The tall Paste control opens the existing anchored menu vocabulary. Normal paste and
513
+ both named paste-special layers still travel through the one `paste` act; its argument
514
+ selects the layer without widening the ribbon action union or adding a save path. */}
 
 
 
 
 
 
515
  {group("Clipboard", (
516
  <div className="sheet-ribbon-clip">
517
  <span className="sheet-ribbon-paste-large">
518
  {control("paste", "Paste", <>{<IconPaste />}{word("Paste")}</>,
519
+ openPop("paste"), false, open === "paste", "V", "gallery")}
520
+ {open === "paste" && (
521
+ <AnchoredOverlay
522
+ anchor={anchorEl}
523
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
524
+ onDismiss={closePop}
525
+ role="menu"
526
+ ariaLabel="Paste options"
527
+ initialFocus="first"
528
+ >
529
+ {item("Paste", () => act("paste", "normal"))}
530
+ {item("Paste values", () => act("paste", "values"))}
531
+ {item("Paste formatting", () => act("paste", "formatting"))}
532
+ </AnchoredOverlay>
533
+ )}
534
  </span>
535
  {/* ⭐⭐ W53-T06 (owner instruction 17) β€” CUT, COPY AND FORMAT PAINTER ARE ICONS,
536
  WITH NO WORD BESIDE THEM. Excel's Clipboard group is one large captioned Paste
web/src/sheet/ribbonView.tsx ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Sheet View ribbon, adapted from the behavior and grouping in the Wave 55 public Excel audit.
2
+ // Freeze, Formula bar, Full screen, and Go to use existing executable doors. Canvas gridline
3
+ // visibility and the other unsupported commands are deliberately labelled unavailable.
4
+
5
+ import type { RibbonTabContext } from "./Ribbon";
6
+
7
+ const SHOW = ["view-formula-bar"] as const;
8
+ const WINDOW = ["view-freeze", "view-fullscreen"] as const;
9
+ const NAVIGATION = ["view-go-to"] as const;
10
+
11
+ export const VIEW_KEYS = [...SHOW, ...WINDOW, ...NAVIGATION] as const;
12
+
13
+ function IconFormulaBar() {
14
+ return (
15
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
16
+ <rect x="2.3" y="3.2" width="11.4" height="9.6" rx="1" />
17
+ <path d="M4.5 6.2h7M4.5 9.5h4" />
18
+ </svg>
19
+ );
20
+ }
21
+
22
+ function IconFreeze() {
23
+ return (
24
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
25
+ <rect x="2.4" y="2.4" width="11.2" height="11.2" rx="1" />
26
+ <path d="M6.2 2.4v11.2M2.4 6.2h11.2" />
27
+ </svg>
28
+ );
29
+ }
30
+
31
+ function IconFullScreen() {
32
+ return (
33
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
34
+ <path d="M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10" />
35
+ </svg>
36
+ );
37
+ }
38
+
39
+ function IconGoTo() {
40
+ return (
41
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
42
+ <circle cx="8" cy="8" r="5.2" />
43
+ <circle cx="8" cy="8" r="1.8" />
44
+ </svg>
45
+ );
46
+ }
47
+
48
+ export const viewGroups = (ctx: RibbonTabContext) => {
49
+ const {
50
+ act, control, formulaBarVisible, frozen, fullscreen, group,
51
+ toggleFormulaBar, toggleFullscreen, unavailable, word,
52
+ } = ctx;
53
+ const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen";
54
+ return (
55
+ <>
56
+ {group("Workbook views", unavailable("New window", word("New window")))}
57
+ {group("Show", (
58
+ <>
59
+ {control(
60
+ "view-formula-bar", "Formula bar", <><IconFormulaBar />{word("Formula bar")}</>,
61
+ toggleFormulaBar, formulaBarVisible, undefined, "B",
62
+ )}
63
+ {unavailable("Gridlines", word("Gridlines"))}
64
+ {unavailable("Headings", word("Headings"))}
65
+ </>
66
+ ))}
67
+ {group("Window", (
68
+ <>
69
+ {control(
70
+ "view-freeze", "Freeze panes", <><IconFreeze />{word("Freeze panes")}</>,
71
+ () => act("freeze"), frozen, undefined, "F",
72
+ )}
73
+ {control(
74
+ "view-fullscreen", fullscreenLabel,
75
+ <><IconFullScreen />{word(fullscreenLabel)}</>,
76
+ toggleFullscreen, fullscreen, undefined, "U",
77
+ )}
78
+ </>
79
+ ))}
80
+ {group("Zoom", unavailable("100%", word("100%")))}
81
+ {group("Navigation", control(
82
+ "view-go-to", "Go to", <><IconGoTo />{word("Go to")}</>,
83
+ () => act("go-to"), false, undefined, "N",
84
+ ))}
85
+ {group("Sheet view", unavailable("Sheet view", word("Sheet view")))}
86
+ </>
87
+ );
88
+ };
89
+
90
+ export const VIEW_TAB = {
91
+ id: "view",
92
+ key: "tab-view",
93
+ kt: "W",
94
+ label: "View",
95
+ bodyClass: "sheet-ribbon-view",
96
+ toolbarLabel: "View",
97
+ keys: VIEW_KEYS,
98
+ groups: viewGroups,
99
+ } as const;
web/src/sheet/sheetState.ts CHANGED
@@ -30,7 +30,8 @@ import type { StructuralShift } from "./a1";
30
  // (its registry) and HOW one moves (delegated straight to `a1.ts`, never re-derived). This file
31
  // used to answer the first half inline, in two branches of `dragBoundCell`, which meant C3's
32
  // second reference slot would have had to be added here as well as wherever it was declared.
33
- import { shiftBindingRefs, shiftRefText } from "./bindingRefs";
 
34
  // ⭐⭐ W53-T01 / CONTRACT C1 β€” THE ONE IMPORT THAT MAKES A COMMITTED FORMULA COMPUTE LOCALLY.
35
  // `formulaEval.ts` imports nothing back from this file (see its own header): it takes a plain
36
  // `get(addr) => CellValue` callback and knows nothing about a `Cell`. `cellToValue`, below, is the
@@ -39,6 +40,8 @@ import {
39
  CYCLE_REFUSAL, cyclicAddresses, evaluateFormula, recalcOrder,
40
  } from "./formulaEval";
41
  import type { CellValue } from "./formulaEval";
 
 
42
 
43
  /** R19's three MARKS. `refused` is a fourth state and not one of the three: it replaces the value
44
  * rather than qualifying it, so it gets its own treatment in the renderer. */
@@ -152,6 +155,7 @@ export const blankOf = (cell: Cell | null | undefined): Cell | null => {
152
  */
153
  export const setLiteral = (cell: Cell | null | undefined, text: string): Cell => {
154
  const rest = { ...(cell ?? { kind: "literal", state: "typed" as CellState }) } as Partial<Cell>;
 
155
  delete rest.binding;
156
  delete rest.source;
157
  delete rest.refusal;
@@ -667,21 +671,13 @@ export interface BulkEdit {
667
  // β›”β›” THIS SECTION REVERSES A WAVE-49 DECISION ON PURPOSE, AND IT IS WRITTEN DOWN SO A LATER
668
  // WAVE KNOWS IT IS CHANGING A DECISION RATHER THAN FIXING A BUG. `fillCells` used to refuse to
669
  // copy a binding at all, and its reason was good at the time: "copying a binding would give
670
- // forty cells the same database read with no way to tell them apart". R9 and R10 give them a way
671
- // to tell each other apart. Dragging ACROSS columns walks the period one unit per column;
672
- // dragging DOWN rows walks a chosen filter to its next option; and a person who wants forty
673
- // identical reads now has to ask for them by setting both rules to Nothing.
674
  // [[two-gates-can-assert-opposite-things]]
675
  //
676
- // β›”β›” THE TWO AXES NEVER FALL BACK ON EACH OTHER. `across` reads the COLUMN delta and only the
677
- // column delta; `down` reads the ROW delta and only the row delta. The defect this feature will
678
- // have if it has one is `steps = dCol || dRow`, or "if the column delta is zero, use the row
679
- // one": both make a cell dragged straight DOWN walk its period, which R10 says it must not, and
680
- // both look perfectly correct in any screenshot of a single row.
681
- //
682
- // β›” AND THE BOUND WALL STILL STANDS ON THE TARGET. A bulk door may now COPY a binding; it still
683
- // may not OVERWRITE one. Landing on a bound cell is still a skip that gets reported, because
684
- // nobody confirmed unbinding the cell that was already there (A2, R20).
685
  //
686
  // ⚠ NOTHING HERE IMPORTS THE FILTER LANGUAGE. `customer-grid/types.ts` owns `FilterTree`, and
687
  // importing it would move tsc's emitted root and break every `require` path the battery's Sheet
@@ -690,7 +686,7 @@ export interface BulkEdit {
690
  // ═════════════════════════════════════════════════════════════════════════════════════════════
691
 
692
  /**
693
- * The option order a DOWN drag walks, keyed by field.
694
  *
695
  * ⭐ ONE SHAPE SERVES BOTH OF R10's CASES. "The next value of a single select" is its option
696
  * order; "the next linked record" is the linked table's view order. Both are an ordered list of
@@ -698,15 +694,22 @@ export interface BulkEdit {
698
  */
699
  export type OptionCatalogue = Record<string, readonly string[]>;
700
 
 
 
 
 
701
  /** What a bulk door needs to know to drag a BOUND cell. Every member is optional by design. */
702
  export interface DragContext {
703
  /**
704
- * The field option order. ABSENT IS THE ORDINARY CASE TODAY: `SheetGrid.tsx` is deliberately
705
- * schema free, so nothing has loaded a catalogue for it. A `down` rule then copies the filter
706
- * unchanged and SAYS SO through {@link boundDragLabel}, which is the honest degradation R10
707
- * asks for. It never wraps to the first option and it never sits silent.
708
  */
709
  catalogue?: OptionCatalogue;
 
 
 
 
 
710
  /**
711
  * PASTE ONLY: the cells the block was copied FROM, in the same shape as the pasted values, and
712
  * the corner they came from. A clipboard round trip carries TEXT, so a pasted bound cell can
@@ -720,9 +723,11 @@ export interface DragContext {
720
  export interface BoundDragTally {
721
  /** Bound cells the rule wrote. Not a notice: a drag that worked says nothing. */
722
  dragged: number;
723
- /** A `down` rule was asked for and no option order was available to walk. */
724
  noCatalogue: number;
725
- /** A `down` rule named a field the cell's own filter does not use. */
 
 
726
  noField: number;
727
  /** The walk ran off the end of the option order, so the value stayed where it was. */
728
  atEnd: number;
@@ -742,9 +747,13 @@ export interface FillEdit extends BulkEdit, BoundDragTally {}
742
  export interface PasteEdit extends FillEdit {
743
  /** Set when the target rectangle cannot hold whole copies of the block. `edits` is then empty. */
744
  sizeRefusal?: string;
 
 
745
  }
746
 
747
- const emptyTally = (): BoundDragTally => ({ dragged: 0, noCatalogue: 0, noField: 0, atEnd: 0 });
 
 
748
 
749
  /** How many MONTHS one step of each unit is worth. `start` is `YYYY-MM` for all three (C2). */
750
  const UNIT_MONTHS: Record<PeriodUnit, number> = { month: 1, quarter: 3, year: 12 };
@@ -785,6 +794,12 @@ export const shiftPeriodStart = (
785
  return `${String(outYear).padStart(4, "0")}-${String(outMonth).padStart(2, "0")}`;
786
  };
787
 
 
 
 
 
 
 
788
  /**
789
  * Shift a period's `ref` the way a dragged formula reference shifts, `$` anchors honoured.
790
  *
@@ -792,11 +807,8 @@ export const shiftPeriodStart = (
792
  * ITSELF: `bindingRefs.ts::shiftRefText` is the one-reference rule now, so this name survives as
793
  * the door its callers already know while there stays exactly ONE implementation underneath.
794
  *
795
- * ⚠ THE REF SHIFTS ON BOTH AXES, WHILE THE PERIOD'S `start` SHIFTS ONLY ACROSS COLUMNS. They are
796
- * different things: a `start` is a period, and R9 says a period moves across and holds down; a
797
- * `ref` is a POINTER at a cell, and a pointer that did not follow the drag would point at the
798
- * same cell from forty different places. A reader who wants it fixed writes `$B$1`, which is the
799
- * control Excel already taught them, or locks the period.
800
  */
801
  export const shiftPeriodRef = (ref: string, dRow: number, dCol: number): string =>
802
  shiftRefText(ref, dRow, dCol);
@@ -853,6 +865,7 @@ export interface BoundDrag {
853
  /** The binding is not the one it was copied from. */
854
  changed: boolean;
855
  noCatalogue: boolean;
 
856
  noField: boolean;
857
  atEnd: boolean;
858
  }
@@ -874,6 +887,7 @@ export interface BoundDrag {
874
  */
875
  export const dragBoundCell = (
876
  source: Cell, dCol: number, dRow: number, catalogue?: OptionCatalogue,
 
877
  ): BoundDrag => {
878
  const binding = (source.binding ?? null) as Record<string, unknown> | null;
879
  // ⭐ DESTRUCTURED RATHER THAN DELETED, which is this file's own idiom (`setLiteral`,
@@ -884,20 +898,33 @@ export const dragBoundCell = (
884
  if (!binding) {
885
  return {
886
  cell: { ...kept, kind: "bound", state: "stale" },
887
- changed: false, noCatalogue: false, noField: false, atEnd: false,
 
 
 
 
 
 
 
 
888
  };
889
  }
890
 
891
  const rules: BindingOnDrag = bindingOnDrag(binding);
892
  const period: BindingPeriod | null = bindingPeriod(binding);
893
- let next: Record<string, unknown> = { ...binding };
894
- let changed = false;
895
-
896
- // ── ACROSS COLUMNS (R9, R10): the period, and only ever the COLUMN delta ──────────────────
897
- if (period && !period.locked && rules.across === "period" && dCol !== 0 && period.start) {
898
- const start = shiftPeriodStart(period.start, period.unit, dCol);
 
 
899
  if (start !== period.start) {
900
- next.period = { ...(binding.period as Record<string, unknown>), start };
 
 
 
901
  changed = true;
902
  }
903
  }
@@ -914,17 +941,21 @@ export const dragBoundCell = (
914
  changed = true;
915
  }
916
 
917
- // ── DOWN ROWS (R10): the chosen filter's value, and only ever the ROW delta ───────────────
918
  let noCatalogue = false;
 
919
  let noField = false;
920
  let atEnd = false;
921
- if (rules.down !== "none" && dRow !== 0) {
922
  const field = rules.down.field;
923
- const options = catalogue ? catalogue[field] : undefined;
 
 
 
924
  if (!options || options.length === 0) {
925
  noCatalogue = true;
926
  } else {
927
- const scope = (binding.scope ?? null) as Record<string, unknown> | null;
928
  const tree = scope && typeof scope.filter === "object" && scope.filter
929
  ? (scope.filter as Record<string, unknown>)
930
  : null;
@@ -933,9 +964,9 @@ export const dragBoundCell = (
933
  noField = true;
934
  } else {
935
  const walked = walkFilterNodes(nodes, field, (value) => {
936
- const step = walkOption(options, value, dRow);
937
- atEnd = atEnd || step.atEnd;
938
- return step.value;
939
  });
940
  if (!walked.found) noField = true;
941
  else {
@@ -952,7 +983,7 @@ export const dragBoundCell = (
952
  const cell: Cell = changed
953
  ? { ...bare, kind: "bound", state: "stale", binding: next }
954
  : { ...kept, kind: "bound", state: "stale", binding: next };
955
- return { cell, changed, noCatalogue, noField, atEnd };
956
  };
957
 
958
  /**
@@ -966,6 +997,12 @@ export const dragBoundCell = (
966
  */
967
  export const boundDragLabel = (tally: BoundDragTally): string => {
968
  const parts: string[] = [];
 
 
 
 
 
 
969
  if (tally.noCatalogue > 0) {
970
  parts.push(tally.noCatalogue === 1
971
  ? "The list of options has not loaded, so one cell kept the filter it was copied from."
@@ -1143,7 +1180,7 @@ export const forgetCut = (): void => { pendingCut = null; };
1143
  const cutFingerprint = (cell: Cell | null | undefined): string =>
1144
  cell
1145
  ? [cell.kind, cell.text ?? "", String(cell.value ?? ""), cell.display ?? "",
1146
- cell.binding ? "bound" : ""].join("")
1147
  : "";
1148
 
1149
  /**
@@ -1223,16 +1260,43 @@ const clearCutSource = (
1223
  * ⚠ A STYLED BLANK STILL LANDS. Copying an empty cell that carries only a fill and pasting it
1224
  * paints that fill, which is why this may build a cell where {@link commitTyped} returned none.
1225
  */
1226
- const withSourceStyle = (landed: Cell | null, copied: Cell | null): Cell | null => {
1227
- if (!copied) return landed;
1228
- if (copied.style) {
1229
- const base: Cell = landed ?? { kind: "empty", state: "fresh" };
1230
- return { ...base, style: { ...copied.style } };
1231
- }
1232
- if (!landed?.style) return landed;
1233
- const bare: Cell = { ...landed };
1234
- delete bare.style;
1235
- return bare;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1236
  };
1237
 
1238
  /**
@@ -1262,6 +1326,7 @@ export const pasteCells = (
1262
  * what every existing caller and every existing proof already expects.
1263
  */
1264
  region?: CellRange,
 
1265
  ): PasteEdit => {
1266
  const edits: Record<string, Cell | null> = {};
1267
  const tally = emptyTally();
@@ -1287,12 +1352,19 @@ export const pasteCells = (
1287
  const pastedText = source.map((row) => row.join("\t")).join("\n");
1288
  // β›”β›” W54-T16 β€” A CUT IS A MOVE, AND A MOVE SHIFTS NOTHING. Answered ONCE, before any cell is
1289
  // built, because every landing cell in the block has to agree about it.
1290
- const moving = completesCut(pastedText);
1291
  const recalled = drag?.cells
1292
  ? null
1293
  : recallCopy(pastedText);
1294
  const held = drag?.cells ?? recalled?.cells ?? null;
1295
  const heldFrom = drag?.from ?? (recalled ? { col: recalled.col, row: recalled.row } : null);
 
 
 
 
 
 
 
1296
  /**
1297
  * Land the copied block ONCE, with its top left corner at `originCol` / `originRow`.
1298
  *
@@ -1331,6 +1403,15 @@ export const pasteCells = (
1331
  // destination kept its own fill, borders and number format while the source's were
1332
  // dropped. {@link withSourceStyle} carries the style object across as a whole.
1333
  const copied = held?.[r]?.[c] ?? null;
 
 
 
 
 
 
 
 
 
1334
  if (copied && copied.kind === "bound" && heldFrom) {
1335
  // β›”β›” W54-T16 β€” A CUT IS A MOVE, AND A MOVE SHIFTS NOTHING. Excel's rule, and the two
1336
  // halves of it are different acts: a COPY walks a binding's period and its cell
@@ -1347,8 +1428,12 @@ export const pasteCells = (
1347
  // cut whose source has since changed is still a MOVE for reference purposes.
1348
  const dCol = moving ? 0 : originCol - heldFrom.col;
1349
  const dRow = moving ? 0 : originRow - heldFrom.row;
1350
- const out = dragBoundCell(copied, dCol, dRow, drag?.catalogue);
1351
- edits[addr] = withSourceStyle(out.cell, copied);
 
 
 
 
1352
  tally.dragged += 1;
1353
  if (out.noCatalogue) tally.noCatalogue += 1;
1354
  if (out.noField) tally.noField += 1;
@@ -1370,7 +1455,7 @@ export const pasteCells = (
1370
  // β›” AND THE NO SOURCE PATH IS UNTOUCHED. An external paste, or a registry miss, has no
1371
  // cell to ask, so it commits the clipboard string exactly as it always has.
1372
  const landing = copied ? editableText(copied) : String(row[c] ?? "");
1373
- edits[addr] = withSourceStyle(commitTyped(cell, landing, read), copied);
1374
  }
1375
  }
1376
  };
@@ -1386,7 +1471,7 @@ export const pasteCells = (
1386
  // No drag, or one target cell: the block lands anchored where it was dropped, as it always has.
1387
  writeBlock(targetCol, targetRow);
1388
  // β›” W54-T16: AFTER the paste's own writes, so an overlapping cut keeps what just landed.
1389
- clearCutSource(tab, edits, pastedText);
1390
  return { edits, ...tally };
1391
  }
1392
  if (wide % srcCols !== 0 || tall % srcRows !== 0) {
@@ -1403,7 +1488,7 @@ export const pasteCells = (
1403
  // β›” W54-T16: same rule on the tiled path, and after every tile - a cut tiled back over its own
1404
  // rectangle keeps the copies that landed there. A SIZE REFUSAL above wrote nothing and returned
1405
  // before this line, so a refused paste also leaves the cut armed for the paste that works.
1406
- clearCutSource(tab, edits, pastedText);
1407
  return { edits, ...tally };
1408
  };
1409
 
@@ -1471,7 +1556,13 @@ export const fillCells = (
1471
  // both spread the TARGET, so without {@link withSourceStyle} dragging a formatted cell
1472
  // across a range copied its value and left every destination wearing its own old format.
1473
  if (pattern.kind === "bound") {
1474
- const dragged = dragBoundCell(pattern, col - srcCol, row - srcRow, drag?.catalogue);
 
 
 
 
 
 
1475
  edits[addr] = withSourceStyle(dragged.cell, pattern);
1476
  tally.dragged += 1;
1477
  if (dragged.noCatalogue) tally.noCatalogue += 1;
@@ -1870,7 +1961,7 @@ export const moveTab = (book: Workbook, tabId: string, step: number): SheetTab[]
1870
  // style act, and it belongs beside the other bulk value doors above.
1871
  // ════════════════════════════════════════════════════════════════════════════════════════
1872
  export {
1873
- clearAll, clearFormats, paintPatch, styleCells, styleOf, STYLE_KEYS,
1874
  } from "./cellStyleOps";
1875
 
1876
  /** One selected rectangle, in the sheet's own zero based coordinates, inclusive of both corners. */
@@ -2125,9 +2216,11 @@ export const usedExtent = (
2125
  return col < 0 || row < 0 ? null : { col, row };
2126
  };
2127
 
2128
- /** Does this address hold anything at all? Ctrl+Arrow's occupancy test, said once. */
2129
- export const isFilled = (tab: SheetTab | null | undefined, col: number, row: number): boolean =>
2130
- cellAt(tab, addressOf(col, row)) !== null;
 
 
2131
 
2132
  /**
2133
  * ⭐ Ctrl+; β€” TODAY, AS AN UNAMBIGUOUS STRING.
 
30
  // (its registry) and HOW one moves (delegated straight to `a1.ts`, never re-derived). This file
31
  // used to answer the first half inline, in two branches of `dragBoundCell`, which meant C3's
32
  // second reference slot would have had to be added here as well as wherever it was declared.
33
+ import { materializeLocalViewBinding, shiftBindingRefs, shiftRefText } from "./bindingRefs";
34
+ import type { SavedViewShadow } from "./bindingRefs";
35
  // ⭐⭐ W53-T01 / CONTRACT C1 β€” THE ONE IMPORT THAT MAKES A COMMITTED FORMULA COMPUTE LOCALLY.
36
  // `formulaEval.ts` imports nothing back from this file (see its own header): it takes a plain
37
  // `get(addr) => CellValue` callback and knows nothing about a `Cell`. `cellToValue`, below, is the
 
40
  CYCLE_REFUSAL, cyclicAddresses, evaluateFormula, recalcOrder,
41
  } from "./formulaEval";
42
  import type { CellValue } from "./formulaEval";
43
+ import { replaceCellStyle } from "./cellStyleOps";
44
+ import type { PasteMode } from "./clipboardOps";
45
 
46
  /** R19's three MARKS. `refused` is a fourth state and not one of the three: it replaces the value
47
  * rather than qualifying it, so it gets its own treatment in the renderer. */
 
155
  */
156
  export const setLiteral = (cell: Cell | null | undefined, text: string): Cell => {
157
  const rest = { ...(cell ?? { kind: "literal", state: "typed" as CellState }) } as Partial<Cell>;
158
+ delete rest.formula;
159
  delete rest.binding;
160
  delete rest.source;
161
  delete rest.refusal;
 
671
  // β›”β›” THIS SECTION REVERSES A WAVE-49 DECISION ON PURPOSE, AND IT IS WRITTEN DOWN SO A LATER
672
  // WAVE KNOWS IT IS CHANGING A DECISION RATHER THAN FIXING A BUG. `fillCells` used to refuse to
673
  // copy a binding at all, and its reason was good at the time: "copying a binding would give
674
+ // forty cells the same database read with no way to tell them apart". W55 R5 and R13 finish the
675
+ // answer: a saved View becomes local before it moves, a metric period uses the signed copy
676
+ // direction, and a non-metric chosen field walks its ordered options in that same direction.
 
677
  // [[two-gates-can-assert-opposite-things]]
678
  //
679
+ // β›” THE SIGN IS THE CONTRACT. Right and down advance; left and up retreat. A diagonal keeps
680
+ // the horizontal distance, so one copied cell is never stepped once per axis.
 
 
 
 
 
 
 
681
  //
682
  // ⚠ NOTHING HERE IMPORTS THE FILTER LANGUAGE. `customer-grid/types.ts` owns `FilterTree`, and
683
  // importing it would move tsc's emitted root and break every `require` path the battery's Sheet
 
686
  // ═════════════════════════════════════════════════════════════════════════════════════════════
687
 
688
  /**
689
+ * The option order a copied non-metric binding walks, normally keyed by database and field.
690
  *
691
  * ⭐ ONE SHAPE SERVES BOTH OF R10's CASES. "The next value of a single select" is its option
692
  * order; "the next linked record" is the linked table's view order. Both are an ordered list of
 
694
  */
695
  export type OptionCatalogue = Record<string, readonly string[]>;
696
 
697
+ /** A database-qualified driver slot. The bare field key remains a legacy/test fallback. */
698
+ export const bindingOptionKey = (database: string, field: string): string =>
699
+ JSON.stringify([String(database || ""), String(field || "")]);
700
+
701
  /** What a bulk door needs to know to drag a BOUND cell. Every member is optional by design. */
702
  export interface DragContext {
703
  /**
704
+ * The field option order. `SheetGrid.tsx` stays schema free, so its page supplies this catalogue.
705
+ * When it is absent the filter stays unchanged and {@link boundDragLabel} says why.
 
 
706
  */
707
  catalogue?: OptionCatalogue;
708
+ /**
709
+ * Canonical saved-View filters, loaded before the copy starts. R5 needs this snapshot to replace
710
+ * a shared View pointer with cell-local filter state before a chosen driver can walk it.
711
+ */
712
+ shadows?: readonly SavedViewShadow[];
713
  /**
714
  * PASTE ONLY: the cells the block was copied FROM, in the same shape as the pasted values, and
715
  * the corner they came from. A clipboard round trip carries TEXT, so a pasted bound cell can
 
723
  export interface BoundDragTally {
724
  /** Bound cells the rule wrote. Not a notice: a drag that worked says nothing. */
725
  dragged: number;
726
+ /** A chosen driver had no option order available to walk. */
727
  noCatalogue: number;
728
+ /** A copied saved View had no canonical local snapshot available. */
729
+ noViewShadow?: number;
730
+ /** A chosen driver named a field the cell's own filter does not use. */
731
  noField: number;
732
  /** The walk ran off the end of the option order, so the value stayed where it was. */
733
  atEnd: number;
 
747
  export interface PasteEdit extends FillEdit {
748
  /** Set when the target rectangle cannot hold whole copies of the block. `edits` is then empty. */
749
  sizeRefusal?: string;
750
+ /** Set when a named paste layer is unavailable from the clipboard payload. */
751
+ layerRefusal?: string;
752
  }
753
 
754
+ const emptyTally = (): BoundDragTally => ({
755
+ dragged: 0, noCatalogue: 0, noViewShadow: 0, noField: 0, atEnd: 0,
756
+ });
757
 
758
  /** How many MONTHS one step of each unit is worth. `start` is `YYYY-MM` for all three (C2). */
759
  const UNIT_MONTHS: Record<PeriodUnit, number> = { month: 1, quarter: 3, year: 12 };
 
794
  return `${String(outYear).padStart(4, "0")}-${String(outMonth).padStart(2, "0")}`;
795
  };
796
 
797
+ /**
798
+ * One signed copy distance for R13. Right and down are forward; left and up are backward.
799
+ * A diagonal keeps the horizontal distance, the established spreadsheet period-axis rule.
800
+ */
801
+ export const signedCopyStep = (dCol: number, dRow: number): number => dCol || dRow;
802
+
803
  /**
804
  * Shift a period's `ref` the way a dragged formula reference shifts, `$` anchors honoured.
805
  *
 
807
  * ITSELF: `bindingRefs.ts::shiftRefText` is the one-reference rule now, so this name survives as
808
  * the door its callers already know while there stays exactly ONE implementation underneath.
809
  *
810
+ * ⚠ The reference and period start both understand two axes, but anchoring is independent:
811
+ * `$B$1` stays fixed while `B1` follows the copied cell. Locking the period pins the slot too.
 
 
 
812
  */
813
  export const shiftPeriodRef = (ref: string, dRow: number, dCol: number): string =>
814
  shiftRefText(ref, dRow, dCol);
 
865
  /** The binding is not the one it was copied from. */
866
  changed: boolean;
867
  noCatalogue: boolean;
868
+ noViewShadow: boolean;
869
  noField: boolean;
870
  atEnd: boolean;
871
  }
 
887
  */
888
  export const dragBoundCell = (
889
  source: Cell, dCol: number, dRow: number, catalogue?: OptionCatalogue,
890
+ shadows?: readonly SavedViewShadow[],
891
  ): BoundDrag => {
892
  const binding = (source.binding ?? null) as Record<string, unknown> | null;
893
  // ⭐ DESTRUCTURED RATHER THAN DELETED, which is this file's own idiom (`setLiteral`,
 
898
  if (!binding) {
899
  return {
900
  cell: { ...kept, kind: "bound", state: "stale" },
901
+ changed: false, noCatalogue: false, noViewShadow: false, noField: false, atEnd: false,
902
+ };
903
+ }
904
+ // A zero delta is the paste door's CUT marker. A move retains the exact binding, including a
905
+ // saved-View pointer; only a copy materialises local state and applies copy stepping.
906
+ if (!dCol && !dRow) {
907
+ return {
908
+ cell: { ...kept, kind: "bound", state: "stale", binding },
909
+ changed: false, noCatalogue: false, noViewShadow: false, noField: false, atEnd: false,
910
  };
911
  }
912
 
913
  const rules: BindingOnDrag = bindingOnDrag(binding);
914
  const period: BindingPeriod | null = bindingPeriod(binding);
915
+ const local = materializeLocalViewBinding(binding, shadows);
916
+ let next: Record<string, unknown> = local.binding;
917
+ let changed = local.localized;
918
+ const step = signedCopyStep(dCol, dRow);
919
+
920
+ // R13: metric periods use the selected grain and signed copy direction on either axis.
921
+ if (period && !period.locked && rules.across === "period" && step !== 0 && period.start) {
922
+ const start = shiftPeriodStart(period.start, period.unit, step);
923
  if (start !== period.start) {
924
+ next = {
925
+ ...next,
926
+ period: { ...(next.period as Record<string, unknown>), start },
927
+ };
928
  changed = true;
929
  }
930
  }
 
941
  changed = true;
942
  }
943
 
944
+ // R5: a non-metric chosen driver walks the local filter in that signed direction.
945
  let noCatalogue = false;
946
+ const noViewShadow = local.missing;
947
  let noField = false;
948
  let atEnd = false;
949
+ if (rules.down !== "none" && step !== 0 && !noViewShadow) {
950
  const field = rules.down.field;
951
+ const database = typeof next.database === "string" ? next.database : "";
952
+ const options = catalogue
953
+ ? catalogue[bindingOptionKey(database, field)] ?? catalogue[field]
954
+ : undefined;
955
  if (!options || options.length === 0) {
956
  noCatalogue = true;
957
  } else {
958
+ const scope = (next.scope ?? null) as Record<string, unknown> | null;
959
  const tree = scope && typeof scope.filter === "object" && scope.filter
960
  ? (scope.filter as Record<string, unknown>)
961
  : null;
 
964
  noField = true;
965
  } else {
966
  const walked = walkFilterNodes(nodes, field, (value) => {
967
+ const walkedOption = walkOption(options, value, step);
968
+ atEnd = atEnd || walkedOption.atEnd;
969
+ return walkedOption.value;
970
  });
971
  if (!walked.found) noField = true;
972
  else {
 
983
  const cell: Cell = changed
984
  ? { ...bare, kind: "bound", state: "stale", binding: next }
985
  : { ...kept, kind: "bound", state: "stale", binding: next };
986
+ return { cell, changed, noCatalogue, noViewShadow, noField, atEnd };
987
  };
988
 
989
  /**
 
997
  */
998
  export const boundDragLabel = (tally: BoundDragTally): string => {
999
  const parts: string[] = [];
1000
+ const missingShadows = tally.noViewShadow ?? 0;
1001
+ if (missingShadows > 0) {
1002
+ parts.push(missingShadows === 1
1003
+ ? "One saved View has not loaded, so its cell could not be copied yet."
1004
+ : `${missingShadows} saved Views have not loaded, so their cells could not be copied yet.`);
1005
+ }
1006
  if (tally.noCatalogue > 0) {
1007
  parts.push(tally.noCatalogue === 1
1008
  ? "The list of options has not loaded, so one cell kept the filter it was copied from."
 
1180
  const cutFingerprint = (cell: Cell | null | undefined): string =>
1181
  cell
1182
  ? [cell.kind, cell.text ?? "", String(cell.value ?? ""), cell.display ?? "",
1183
+ cell.binding ? "bound" : ""].join("\u0000")
1184
  : "";
1185
 
1186
  /**
 
1260
  * ⚠ A STYLED BLANK STILL LANDS. Copying an empty cell that carries only a fill and pasting it
1261
  * paints that fill, which is why this may build a cell where {@link commitTyped} returned none.
1262
  */
1263
+ const withSourceStyle = (
1264
+ landed: Cell | null,
1265
+ copied: Cell | null,
1266
+ sourceKnown = true,
1267
+ ): Cell | null => sourceKnown ? replaceCellStyle(landed, copied?.style) : landed;
1268
+
1269
+ /** Remove only value/formula/binding content, retaining the target's other cell layers. */
1270
+ const withoutValueLayer = (cell: Cell | null | undefined): Cell | null => {
1271
+ if (!cell) return null;
1272
+ const next: Cell = { ...cell, kind: "empty", state: "fresh" };
1273
+ delete next.text;
1274
+ delete next.formula;
1275
+ delete next.value;
1276
+ delete next.display;
1277
+ delete next.binding;
1278
+ delete next.source;
1279
+ delete next.refusal;
1280
+ delete next.refreshed_at;
1281
+ return next.style || next.validation || next.link || next.note || next.sparkline ? next : null;
1282
+ };
1283
+
1284
+ /** A copied cell's result as literal content. Formulas and bindings never survive Paste values. */
1285
+ const valueLayerText = (cell: Cell | null): string => {
1286
+ if (!cell || cell.kind === "empty") return "";
1287
+ if (cell.value != null) return String(cell.value);
1288
+ if (cell.kind === "literal" && cell.text != null) return cell.text;
1289
+ return rawDisplayText(cell);
1290
+ };
1291
+
1292
+ const withValueLayer = (
1293
+ target: Cell | null,
1294
+ copied: Cell | null,
1295
+ fallback: string,
1296
+ sourceKnown: boolean,
1297
+ ): Cell | null => {
1298
+ const text = sourceKnown ? valueLayerText(copied) : fallback;
1299
+ return text === "" ? withoutValueLayer(target) : setLiteral(target, text);
1300
  };
1301
 
1302
  /**
 
1326
  * what every existing caller and every existing proof already expects.
1327
  */
1328
  region?: CellRange,
1329
+ mode: PasteMode = "normal",
1330
  ): PasteEdit => {
1331
  const edits: Record<string, Cell | null> = {};
1332
  const tally = emptyTally();
 
1352
  const pastedText = source.map((row) => row.join("\t")).join("\n");
1353
  // β›”β›” W54-T16 β€” A CUT IS A MOVE, AND A MOVE SHIFTS NOTHING. Answered ONCE, before any cell is
1354
  // built, because every landing cell in the block has to agree about it.
1355
+ const moving = mode === "normal" && completesCut(pastedText);
1356
  const recalled = drag?.cells
1357
  ? null
1358
  : recallCopy(pastedText);
1359
  const held = drag?.cells ?? recalled?.cells ?? null;
1360
  const heldFrom = drag?.from ?? (recalled ? { col: recalled.col, row: recalled.row } : null);
1361
+ const sourceKnown = held !== null;
1362
+ if (mode === "formatting" && !sourceKnown) {
1363
+ return {
1364
+ edits: {}, ...emptyTally(),
1365
+ layerRefusal: "Copy cells from this sheet before pasting formatting.",
1366
+ };
1367
+ }
1368
  /**
1369
  * Land the copied block ONCE, with its top left corner at `originCol` / `originRow`.
1370
  *
 
1403
  // destination kept its own fill, borders and number format while the source's were
1404
  // dropped. {@link withSourceStyle} carries the style object across as a whole.
1405
  const copied = held?.[r]?.[c] ?? null;
1406
+ if (mode === "formatting") {
1407
+ const styled = withSourceStyle(cell, copied, true);
1408
+ if (styled !== cell) edits[addr] = styled;
1409
+ continue;
1410
+ }
1411
+ if (mode === "values") {
1412
+ edits[addr] = withValueLayer(cell, copied, String(row[c] ?? ""), sourceKnown);
1413
+ continue;
1414
+ }
1415
  if (copied && copied.kind === "bound" && heldFrom) {
1416
  // β›”β›” W54-T16 β€” A CUT IS A MOVE, AND A MOVE SHIFTS NOTHING. Excel's rule, and the two
1417
  // halves of it are different acts: a COPY walks a binding's period and its cell
 
1428
  // cut whose source has since changed is still a MOVE for reference purposes.
1429
  const dCol = moving ? 0 : originCol - heldFrom.col;
1430
  const dRow = moving ? 0 : originRow - heldFrom.row;
1431
+ const out = dragBoundCell(copied, dCol, dRow, drag?.catalogue, drag?.shadows);
1432
+ if (out.noViewShadow) {
1433
+ tally.noViewShadow = (tally.noViewShadow ?? 0) + 1;
1434
+ continue;
1435
+ }
1436
+ edits[addr] = withSourceStyle(out.cell, copied, sourceKnown);
1437
  tally.dragged += 1;
1438
  if (out.noCatalogue) tally.noCatalogue += 1;
1439
  if (out.noField) tally.noField += 1;
 
1455
  // β›” AND THE NO SOURCE PATH IS UNTOUCHED. An external paste, or a registry miss, has no
1456
  // cell to ask, so it commits the clipboard string exactly as it always has.
1457
  const landing = copied ? editableText(copied) : String(row[c] ?? "");
1458
+ edits[addr] = withSourceStyle(commitTyped(cell, landing, read), copied, sourceKnown);
1459
  }
1460
  }
1461
  };
 
1471
  // No drag, or one target cell: the block lands anchored where it was dropped, as it always has.
1472
  writeBlock(targetCol, targetRow);
1473
  // β›” W54-T16: AFTER the paste's own writes, so an overlapping cut keeps what just landed.
1474
+ if (mode === "normal") clearCutSource(tab, edits, pastedText);
1475
  return { edits, ...tally };
1476
  }
1477
  if (wide % srcCols !== 0 || tall % srcRows !== 0) {
 
1488
  // β›” W54-T16: same rule on the tiled path, and after every tile - a cut tiled back over its own
1489
  // rectangle keeps the copies that landed there. A SIZE REFUSAL above wrote nothing and returned
1490
  // before this line, so a refused paste also leaves the cut armed for the paste that works.
1491
+ if (mode === "normal") clearCutSource(tab, edits, pastedText);
1492
  return { edits, ...tally };
1493
  };
1494
 
 
1556
  // both spread the TARGET, so without {@link withSourceStyle} dragging a formatted cell
1557
  // across a range copied its value and left every destination wearing its own old format.
1558
  if (pattern.kind === "bound") {
1559
+ const dragged = dragBoundCell(
1560
+ pattern, col - srcCol, row - srcRow, drag?.catalogue, drag?.shadows,
1561
+ );
1562
+ if (dragged.noViewShadow) {
1563
+ tally.noViewShadow = (tally.noViewShadow ?? 0) + 1;
1564
+ continue;
1565
+ }
1566
  edits[addr] = withSourceStyle(dragged.cell, pattern);
1567
  tally.dragged += 1;
1568
  if (dragged.noCatalogue) tally.noCatalogue += 1;
 
1961
  // style act, and it belongs beside the other bulk value doors above.
1962
  // ════════════════════════════════════════════════════════════════════════════════════════
1963
  export {
1964
+ clearAll, clearFormats, paintPatch, replaceCellStyle, styleCells, styleOf, STYLE_KEYS,
1965
  } from "./cellStyleOps";
1966
 
1967
  /** One selected rectangle, in the sheet's own zero based coordinates, inclusive of both corners. */
 
2216
  return col < 0 || row < 0 ? null : { col, row };
2217
  };
2218
 
2219
+ /** Semantic occupancy for navigation: formatting alone does not make a cell filled. */
2220
+ export const isFilled = (tab: SheetTab | null | undefined, col: number, row: number): boolean => {
2221
+ const kind = cellAt(tab, addressOf(col, row))?.kind;
2222
+ return kind === "literal" || kind === "formula" || kind === "bound";
2223
+ };
2224
 
2225
  /**
2226
  * ⭐ Ctrl+; β€” TODAY, AS AN UNAMBIGUOUS STRING.
web/src/sheet/shortcuts.ts CHANGED
@@ -358,11 +358,27 @@ export interface KeyChord {
358
  altKey?: boolean;
359
  }
360
 
 
 
 
361
  /** The four arrow keys, as a lookup rather than four comparisons in five places. */
362
  const ARROWS: Record<string, boolean> = {
363
- ArrowUp: true, ArrowDown: true, ArrowLeft: true, ArrowRight: true,
364
  };
365
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
  /**
367
  * ⭐⭐ W54-T19 (instruction 13) β€” IS THIS PRESS ONE OF THE FOUR ARROWS, ASKED ONCE.
368
  *
 
358
  altKey?: boolean;
359
  }
360
 
361
+ /** The vertical pair has one extra job: leaving an active KeyTips path for the grid. */
362
+ const VERTICAL_ARROWS: Record<string, boolean> = { ArrowUp: true, ArrowDown: true };
363
+
364
  /** The four arrow keys, as a lookup rather than four comparisons in five places. */
365
  const ARROWS: Record<string, boolean> = {
366
+ ...VERTICAL_ARROWS, ArrowLeft: true, ArrowRight: true,
367
  };
368
 
369
+ /**
370
+ * The scoped DOM event by which KeyTips hands one Up/Down press back to its containing grid.
371
+ * It is not a keyboard listener: the active overlay consumes the real key once, then emits this
372
+ * one semantic act on the nearest `.sheet-grid-wrap`, where the selection state already lives.
373
+ */
374
+ export const KEY_TIP_GRID_ARROW_EVENT = "aios:sheet-key-tip-grid-arrow";
375
+
376
+ export type KeyTipGridArrow = "ArrowUp" | "ArrowDown";
377
+
378
+ /** Only Up/Down leave KeyTips for the selected cell under Wave 55 ruling R4. */
379
+ export const keyTipGridArrow = (key: string): KeyTipGridArrow | null =>
380
+ (VERTICAL_ARROWS[key] === true ? key as KeyTipGridArrow : null);
381
+
382
  /**
383
  * ⭐⭐ W54-T19 (instruction 13) β€” IS THIS PRESS ONE OF THE FOUR ARROWS, ASKED ONCE.
384
  *
web/src/sheet/types.ts CHANGED
@@ -74,6 +74,66 @@ export interface CellSource {
74
  */
75
  export type CellBinding = Record<string, unknown>;
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  // ── W51-T19, contract C2: the DRAG vocabulary (rulings R9 and R10) ──────────────────────────
78
  //
79
  // ⭐⭐ WHAT THESE NAMES ARE FOR. R9 and R10 make a bound cell DRAGGABLE: pulling it across
@@ -129,11 +189,6 @@ export interface BindingAdoptedFrom {
129
  at: string;
130
  }
131
 
132
- const asRecord = (value: unknown): Record<string, unknown> | null =>
133
- value && typeof value === "object" && !Array.isArray(value)
134
- ? (value as Record<string, unknown>)
135
- : null;
136
-
137
  /**
138
  * Read a binding's C2 period, or `null` when it carries none.
139
  *
@@ -683,10 +738,21 @@ export type CellMap = Record<string, Cell>;
683
  * charts beside the cells also says something true: a chart has no value, no state and no binding,
684
  * so every field a `Cell` carries would have been dead weight on it.
685
  */
 
 
 
 
 
 
 
 
 
 
 
686
  export interface SheetChartSpec {
687
  id: string;
688
  /** Zero-based inclusive rectangle. The header ROW is the axis (R15). */
689
- range: { col0: number; row0: number; col1: number; row1: number };
690
  /**
691
  * ⭐ WAVE 54 BASE KIT WIDENED THIS UNION, AND ALL EIGHT NAMES ARE REAL NOW.
692
  *
@@ -703,6 +769,82 @@ export interface SheetChartSpec {
703
  kind: "bar" | "line" | "area" | "donut" | "column" | "pie" | "scatter" | "combo";
704
  }
705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
706
  /**
707
  * β›” THE FOUR THE SHARED VIZ RENDERER DRAWS, WHICH IS NO LONGER THE SAME QUESTION AS WHAT THE
708
  * SERVER STORES. Every one of {@link SheetChartSpec.kind}'s eight names round trips (W54-T09);
 
74
  */
75
  export type CellBinding = Record<string, unknown>;
76
 
77
+ const asRecord = (value: unknown): Record<string, unknown> | null =>
78
+ value && typeof value === "object" && !Array.isArray(value)
79
+ ? (value as Record<string, unknown>)
80
+ : null;
81
+
82
+ // ── W55-T07, contract C6: the CELL-LOCAL View presentation ────────────────────────────────
83
+ //
84
+ // A database View already has a `config.display`, but a bound Sheet cell is not that View. R6
85
+ // makes the distinction durable: changing this drawer must not rewrite a shared View or seed a
86
+ // browser-local preference bucket. The small display bag therefore rides on the binding itself.
87
+ // `scope` continues to own which rows belong to the cell; this owns only how those rows are
88
+ // presented when the cell is opened.
89
+
90
+ /** The projections the compact Cell View can render without inventing mode-specific setup. */
91
+ export const CELL_VIEW_MODES = ["grid", "list", "map"] as const;
92
+ export type CellViewMode = (typeof CELL_VIEW_MODES)[number];
93
+
94
+ /** R6's per-cell display state, stored as `binding.display`. */
95
+ export interface BindingDisplay {
96
+ mode: CellViewMode;
97
+ /** Chosen field keys in display order. Filter fields are unioned at read time by C6. */
98
+ visible: string[];
99
+ }
100
+
101
+ /**
102
+ * Read a binding's display state without accepting an unknown renderer or duplicate field key.
103
+ *
104
+ * `null` means the binding predates W55-T07. Callers then use Grid plus the database's normally
105
+ * visible fields; absence stays absence until the person actually changes a display choice.
106
+ */
107
+ export const bindingDisplay = (binding: unknown): BindingDisplay | null => {
108
+ const record = asRecord(binding);
109
+ const display = record && asRecord(record.display);
110
+ if (!display) return null;
111
+ const named = String(display.mode ?? "");
112
+ const mode = (CELL_VIEW_MODES as readonly string[]).includes(named)
113
+ ? (named as CellViewMode)
114
+ : "grid";
115
+ const visible: string[] = [];
116
+ if (Array.isArray(display.visible)) {
117
+ for (const value of display.visible) {
118
+ const key = typeof value === "string" ? value.trim() : "";
119
+ if (key && !visible.includes(key)) visible.push(key);
120
+ }
121
+ }
122
+ return { mode, visible };
123
+ };
124
+
125
+ /** Copy a binding with one validated cell-local display bag. */
126
+ export const withBindingDisplay = (
127
+ binding: CellBinding,
128
+ display: BindingDisplay,
129
+ ): CellBinding => ({
130
+ ...binding,
131
+ display: {
132
+ mode: (CELL_VIEW_MODES as readonly string[]).includes(display.mode) ? display.mode : "grid",
133
+ visible: [...new Set(display.visible.map((key) => String(key).trim()).filter(Boolean))],
134
+ },
135
+ });
136
+
137
  // ── W51-T19, contract C2: the DRAG vocabulary (rulings R9 and R10) ──────────────────────────
138
  //
139
  // ⭐⭐ WHAT THESE NAMES ARE FOR. R9 and R10 make a bound cell DRAGGABLE: pulling it across
 
189
  at: string;
190
  }
191
 
 
 
 
 
 
192
  /**
193
  * Read a binding's C2 period, or `null` when it carries none.
194
  *
 
738
  * charts beside the cells also says something true: a chart has no value, no state and no binding,
739
  * so every field a `Cell` carries would have been dead weight on it.
740
  */
741
+ /**
742
+ * The one rectangle a chart stores. Pixels are deliberately absent: the grid derives them from
743
+ * these cell anchors every time it renders, scrolls, or changes structure.
744
+ */
745
+ export interface SheetChartRange {
746
+ col0: number;
747
+ row0: number;
748
+ col1: number;
749
+ row1: number;
750
+ }
751
+
752
  export interface SheetChartSpec {
753
  id: string;
754
  /** Zero-based inclusive rectangle. The header ROW is the axis (R15). */
755
+ range: SheetChartRange;
756
  /**
757
  * ⭐ WAVE 54 BASE KIT WIDENED THIS UNION, AND ALL EIGHT NAMES ARE REAL NOW.
758
  *
 
769
  kind: "bar" | "line" | "area" | "donut" | "column" | "pie" | "scatter" | "combo";
770
  }
771
 
772
+ /** The structural vocabulary a chart anchor needs. `at` is 1 based, as the Sheet controls are. */
773
+ export interface SheetChartStructure {
774
+ axis: "row" | "col";
775
+ at: number;
776
+ delta: number;
777
+ }
778
+
779
+ /** Keep a normalized inclusive interval inside the sheet without changing its span if it fits. */
780
+ const clampChartAxis = (start: number, end: number, limit: number): [number, number] => {
781
+ const ceiling = Math.max(0, Math.round(limit) - 1);
782
+ let lo = Math.max(0, Math.min(start, end));
783
+ let hi = Math.max(lo, Math.max(start, end));
784
+ if (hi > ceiling) {
785
+ const overflow = hi - ceiling;
786
+ lo = Math.max(0, lo - overflow);
787
+ hi = ceiling;
788
+ }
789
+ return [Math.min(lo, ceiling), Math.min(Math.max(lo, hi), ceiling)];
790
+ };
791
+
792
+ /**
793
+ * Move one pair of cell anchors through an insert or delete.
794
+ *
795
+ * An insert before the range moves both anchors; an insert inside expands the far anchor. A delete
796
+ * keeps whichever anchored cells survive and collapses a fully deleted range onto the first cell
797
+ * of the removed band. That last case is still a real cell anchor, never an orphaned pixel box.
798
+ */
799
+ const chartAxisAfterStructure = (
800
+ start: number,
801
+ end: number,
802
+ at: number,
803
+ delta: number,
804
+ limit: number,
805
+ ): [number, number] => {
806
+ const lo = Math.max(0, Math.min(Math.round(start), Math.round(end)));
807
+ const hi = Math.max(lo, Math.max(Math.round(start), Math.round(end)));
808
+ const point = Math.max(0, Math.round(at) - 1);
809
+ const step = Math.round(delta);
810
+ if (step === 0) return clampChartAxis(lo, hi, limit);
811
+
812
+ if (step > 0) {
813
+ if (point <= lo) return clampChartAxis(lo + step, hi + step, limit);
814
+ if (point <= hi) return clampChartAxis(lo, hi + step, limit);
815
+ return clampChartAxis(lo, hi, limit);
816
+ }
817
+
818
+ const count = -step;
819
+ const afterBand = point + count;
820
+ const hasBefore = lo < point;
821
+ const hasAfter = hi >= afterBand;
822
+ const nextLo = hasBefore ? lo : hasAfter ? Math.max(lo, afterBand) - count : point;
823
+ const nextHi = hasAfter ? hi - count : hasBefore ? Math.min(hi, point - 1) : point;
824
+ return clampChartAxis(nextLo, nextHi, limit);
825
+ };
826
+
827
+ /**
828
+ * Re-anchor a chart after Sheet structure changes. This is pure document arithmetic: callers save
829
+ * the returned range, while render and scroll continue to derive the current pixel box from it.
830
+ */
831
+ export const chartRangeAfterStructure = (
832
+ range: SheetChartRange,
833
+ op: SheetChartStructure,
834
+ extent: { cols: number; rows: number },
835
+ ): SheetChartRange => {
836
+ if (op.axis === "col") {
837
+ const [col0, col1] = chartAxisAfterStructure(
838
+ range.col0, range.col1, op.at, op.delta, extent.cols,
839
+ );
840
+ return { ...range, col0, col1 };
841
+ }
842
+ const [row0, row1] = chartAxisAfterStructure(
843
+ range.row0, range.row1, op.at, op.delta, extent.rows,
844
+ );
845
+ return { ...range, row0, row1 };
846
+ };
847
+
848
  /**
849
  * β›” THE FOUR THE SHARED VIZ RENDERER DRAWS, WHICH IS NO LONGER THE SAME QUESTION AS WHAT THE
850
  * SERVER STORES. Every one of {@link SheetChartSpec.kind}'s eight names round trips (W54-T09);
web/src/shell/ShareDialog.tsx CHANGED
@@ -12,15 +12,19 @@
12
  // `shareModel.ts`, where the access gate can run it.
13
  // ---------------------------------------------------------------------------
14
 
15
- import { useCallback, useEffect, useState } from "react";
16
  import { API_V1, CREDENTIALS } from "../apiContract";
17
  import PublishPanel from "../publish/PublishPanel";
 
18
  import {
 
 
19
  SHARE_ROLES,
20
  addablePeople,
21
  parseShare,
 
 
22
  sharePutBody,
23
- shareSummary,
24
  withEntry,
25
  withoutEntry,
26
  } from "./shareModel";
@@ -230,8 +234,10 @@ export default function ShareDialog({
230
  const [entries, setEntries] = useState<ShareEntry[]>([]);
231
  const [error, setError] = useState("");
232
  const [busy, setBusy] = useState(false);
233
- const [pick, setPick] = useState("");
234
  const [pickRole, setPickRole] = useState<ShareRole>("view");
 
 
235
  // W42-T26 β€” the RESULT half: what the last successful save actually granted, and what it
236
  // refused. Empty until a save answers, and empty again whenever one answers without the keys.
237
  const [sharedFields, setSharedFields] = useState<FieldNote[]>([]);
@@ -244,6 +250,17 @@ export default function ShareDialog({
244
 
245
  const path = `${API_V1}/share/${encodeURIComponent(kind)}/${encodeURIComponent(id)}`;
246
 
 
 
 
 
 
 
 
 
 
 
 
247
  useEffect(() => {
248
  let dead = false;
249
  setError("");
@@ -298,15 +315,11 @@ export default function ShareDialog({
298
  };
299
  }, [path]);
300
 
301
- // β›” ESCAPE CLOSES A MODAL, or its scrim becomes a trap β€” the wave-18 lesson this
302
- // shell already carries at its other two dialogs.
303
- useEffect(() => {
304
- const onKey = (e: KeyboardEvent) => {
305
- if (e.key === "Escape" && !busy) onClose();
306
- };
307
- window.addEventListener("keydown", onKey);
308
- return () => window.removeEventListener("keydown", onKey);
309
- }, [busy, onClose]);
310
 
311
  const save = useCallback(
312
  async (next: ShareEntry[]) => {
@@ -378,6 +391,10 @@ export default function ShareDialog({
378
  finally { setBusy(false); }
379
  }, [path, onToast]);
380
  const options = state ? addablePeople(state.people, entries) : [];
 
 
 
 
381
  const nameOf = (user: string) =>
382
  user === "*"
383
  ? "Everyone"
@@ -386,11 +403,14 @@ export default function ShareDialog({
386
  : state?.people.find((p) => p.user === user)?.name ?? user;
387
 
388
  return (
389
- <div className="shell-newdb-scrim" onClick={() => (busy ? null : onClose())}>
390
  <div
 
391
  className="shell-newdb shell-share"
392
  role="dialog"
 
393
  aria-label={`Share ${label}`}
 
394
  onClick={(e) => e.stopPropagation()}
395
  >
396
  <h2>Share {KIND_WORD[kind]}</h2>
@@ -452,7 +472,10 @@ export default function ShareDialog({
452
  question people open this for is "who has this already" β€” with the
453
  one-line answer above it, since the fact that changes everything
454
  ("Everyone can edit") is the one a list of rows buries. */}
455
- <p className="shell-share-summary">{shareSummary(entries)}</p>
 
 
 
456
  {/* ⭐⭐ W42-T26 / C7 β€” THE RESULT: which fields actually travelled, and which could not,
457
  each with the reason the SERVER gave. Absent both keys this renders nothing at all
458
  so an older server remains compatible.
@@ -556,26 +579,23 @@ export default function ShareDialog({
556
 
557
  {mayAdminister ? (
558
  <div className="shell-share-add">
559
- <select
560
  className="shell-share-select"
561
- value={pick}
 
 
562
  disabled={busy}
563
- aria-label="Who to share with"
564
- onChange={(e) => setPick(e.target.value)}
565
- >
566
- {/* ⚠ An explicit placeholder OPTION, not a blank first row: a
567
- <select> whose value matches nothing renders its first option
568
- while holding "", so the box would read as a chosen person and
569
- the button beside it would grant somebody nobody picked
570
- ([[cg-condition-builder-items]]). */}
571
- <option value="">Choose a person…</option>
572
- <option value="*">Everyone in this workspace</option>
573
  {options.map((p) => (
574
- <option key={p.user} value={p.user}>
575
- {p.name}
576
- </option>
577
  ))}
578
- </select>
579
  <select
580
  className="shell-share-select"
581
  value={pickRole}
@@ -597,6 +617,7 @@ export default function ShareDialog({
597
  className="login-submit shell-share-grant"
598
  disabled={busy || !pick}
599
  onClick={() => {
 
600
  const next = withEntry(entries, pick, pickRole);
601
  setEntries(next);
602
  void save(next).then((ok) => {
@@ -606,12 +627,12 @@ export default function ShareDialog({
606
  ? `${nameOf(pick)} can now ${pickRole === "edit" ? "edit" : "view"} this field.`
607
  : `${nameOf(pick)} can now ${pickRole} this ${KIND_WORD[kind]}.`
608
  );
609
- setPick("");
610
  }
611
  });
612
  }}
613
  >
614
- Share
615
  </button>
616
  <p className="shell-share-blurb">{ROLE_BLURB[kind][pickRole]}</p>
617
  {/* β›” W33-T30 / audit S-5 β€” `*` + `edit` IS A TENANT-WIDE WRITE GRANT AND LOOKED
@@ -631,7 +652,7 @@ export default function ShareDialog({
631
  JSX pass skips any run containing a newline [[web-prose-blind-to-wrapped-jsx]].
632
  REWRITTEN, not merely stripped β€” the comma keeps the contrast the sentence
633
  exists to draw. */}
634
- {pick === "*" && pickRole === "edit" ? (
635
  <p className="shell-share-note">
636
  Everyone in this workspace will be able to change this {KIND_WORD[kind]},
637
  not just open it.
@@ -669,7 +690,10 @@ export default function ShareDialog({
669
  nothing if not β€” so "absent on non-interface views" is one evaluator, not two. */}
670
  {kind === "view" && topic ? <PublishPanel topic={topic} view={id} /> : null}
671
 
672
- {error ? <p className="shell-newdb-err">{error}</p> : null}
 
 
 
673
  </div>
674
  </div>
675
  );
 
12
  // `shareModel.ts`, where the access gate can run it.
13
  // ---------------------------------------------------------------------------
14
 
15
+ import { useCallback, useEffect, useRef, useState } from "react";
16
  import { API_V1, CREDENTIALS } from "../apiContract";
17
  import PublishPanel from "../publish/PublishPanel";
18
+ import { useEscapeClose } from "../ui/useEscapeClose";
19
  import {
20
+ EVERYONE,
21
+ EVERYONE_LABEL,
22
  SHARE_ROLES,
23
  addablePeople,
24
  parseShare,
25
+ resolveShareRecipient,
26
+ shareAccessStatus,
27
  sharePutBody,
 
28
  withEntry,
29
  withoutEntry,
30
  } from "./shareModel";
 
234
  const [entries, setEntries] = useState<ShareEntry[]>([]);
235
  const [error, setError] = useState("");
236
  const [busy, setBusy] = useState(false);
237
+ const [recipientQuery, setRecipientQuery] = useState("");
238
  const [pickRole, setPickRole] = useState<ShareRole>("view");
239
+ const dialogRef = useRef<HTMLDivElement>(null);
240
+ const focusReturnRef = useRef<HTMLElement | null>(null);
241
  // W42-T26 β€” the RESULT half: what the last successful save actually granted, and what it
242
  // refused. Empty until a save answers, and empty again whenever one answers without the keys.
243
  const [sharedFields, setSharedFields] = useState<FieldNote[]>([]);
 
250
 
251
  const path = `${API_V1}/share/${encodeURIComponent(kind)}/${encodeURIComponent(id)}`;
252
 
253
+ useEffect(() => {
254
+ focusReturnRef.current = document.activeElement instanceof HTMLElement
255
+ ? document.activeElement
256
+ : null;
257
+ dialogRef.current?.focus();
258
+ return () => {
259
+ const opener = focusReturnRef.current;
260
+ if (opener?.isConnected) opener.focus();
261
+ };
262
+ }, []);
263
+
264
  useEffect(() => {
265
  let dead = false;
266
  setError("");
 
315
  };
316
  }, [path]);
317
 
318
+ // The Share modal joins the one overlay stack. A local key listener races any picker or
319
+ // nested publish control mounted inside it and can close two surfaces from one Escape.
320
+ useEscapeClose(true, () => {
321
+ if (!busy) onClose();
322
+ }, { container: () => dialogRef.current });
 
 
 
 
323
 
324
  const save = useCallback(
325
  async (next: ShareEntry[]) => {
 
391
  finally { setBusy(false); }
392
  }, [path, onToast]);
393
  const options = state ? addablePeople(state.people, entries) : [];
394
+ const pick = state
395
+ ? resolveShareRecipient(state.people, entries, recipientQuery)
396
+ : null;
397
+ const canAddEveryone = !entries.some((entry) => entry.user === EVERYONE);
398
  const nameOf = (user: string) =>
399
  user === "*"
400
  ? "Everyone"
 
403
  : state?.people.find((p) => p.user === user)?.name ?? user;
404
 
405
  return (
406
+ <div className="shell-newdb-scrim">
407
  <div
408
+ ref={dialogRef}
409
  className="shell-newdb shell-share"
410
  role="dialog"
411
+ aria-modal="true"
412
  aria-label={`Share ${label}`}
413
+ tabIndex={-1}
414
  onClick={(e) => e.stopPropagation()}
415
  >
416
  <h2>Share {KIND_WORD[kind]}</h2>
 
472
  question people open this for is "who has this already" β€” with the
473
  one-line answer above it, since the fact that changes everything
474
  ("Everyone can edit") is the one a list of rows buries. */}
475
+ <h3 className="shell-share-summary">Manage access</h3>
476
+ <p className="shell-share-note">
477
+ Workspace access: {shareAccessStatus(entries)}.
478
+ </p>
479
  {/* ⭐⭐ W42-T26 / C7 β€” THE RESULT: which fields actually travelled, and which could not,
480
  each with the reason the SERVER gave. Absent both keys this renders nothing at all
481
  so an older server remains compatible.
 
579
 
580
  {mayAdminister ? (
581
  <div className="shell-share-add">
582
+ <input
583
  className="shell-share-select"
584
+ type="search"
585
+ list="shell-share-recipient-options"
586
+ value={recipientQuery}
587
  disabled={busy}
588
+ aria-label="Search people to share with"
589
+ placeholder="Search people"
590
+ autoFocus
591
+ onChange={(e) => setRecipientQuery(e.target.value)}
592
+ />
593
+ <datalist id="shell-share-recipient-options">
594
+ {canAddEveryone ? <option value={EVERYONE_LABEL} /> : null}
 
 
 
595
  {options.map((p) => (
596
+ <option key={p.user} value={`${p.name} (${p.user})`} />
 
 
597
  ))}
598
+ </datalist>
599
  <select
600
  className="shell-share-select"
601
  value={pickRole}
 
617
  className="login-submit shell-share-grant"
618
  disabled={busy || !pick}
619
  onClick={() => {
620
+ if (!pick) return;
621
  const next = withEntry(entries, pick, pickRole);
622
  setEntries(next);
623
  void save(next).then((ok) => {
 
627
  ? `${nameOf(pick)} can now ${pickRole === "edit" ? "edit" : "view"} this field.`
628
  : `${nameOf(pick)} can now ${pickRole} this ${KIND_WORD[kind]}.`
629
  );
630
+ setRecipientQuery("");
631
  }
632
  });
633
  }}
634
  >
635
+ Send
636
  </button>
637
  <p className="shell-share-blurb">{ROLE_BLURB[kind][pickRole]}</p>
638
  {/* β›” W33-T30 / audit S-5 β€” `*` + `edit` IS A TENANT-WIDE WRITE GRANT AND LOOKED
 
652
  JSX pass skips any run containing a newline [[web-prose-blind-to-wrapped-jsx]].
653
  REWRITTEN, not merely stripped β€” the comma keeps the contrast the sentence
654
  exists to draw. */}
655
+ {pick === EVERYONE && pickRole === "edit" ? (
656
  <p className="shell-share-note">
657
  Everyone in this workspace will be able to change this {KIND_WORD[kind]},
658
  not just open it.
 
690
  nothing if not β€” so "absent on non-interface views" is one evaluator, not two. */}
691
  {kind === "view" && topic ? <PublishPanel topic={topic} view={id} /> : null}
692
 
693
+ {error ? <p className="shell-newdb-err" role="alert">{error}</p> : null}
694
+ <div className="shell-newdb-actions">
695
+ <button type="button" disabled={busy} onClick={onClose}>Close</button>
696
+ </div>
697
  </div>
698
  </div>
699
  );
web/src/shell/Shell.tsx CHANGED
@@ -48,7 +48,7 @@ import "./shell.css";
48
  ⚠ AND `npx tsc --noEmit` DID NOT CATCH IT β€” only `npm run build`'s `tsc -b` did. The two are not
49
  the same check here; a lane that runs the first and skips the second gets a false green on every
50
  symbol it orphans. */
51
- import type { MouseEvent as ReactMouseEvent, ReactNode } from "react";
52
  /**
53
  * ⭐ WAVE-27 item 34 (I5) β€” ROUTE-LEVEL CODE SPLITTING.
54
  *
@@ -78,6 +78,7 @@ import { clearCustomersCache, currentSurfaceScope } from "../customer-grid/apiBr
78
  import { OverlayProvider } from "../customer-grid/OverlaySurface";
79
  import { dataPathHash, readDataPath } from "../customer-grid/dataPath";
80
  import type { DataDatabase } from "../customer-grid/dataPath";
 
81
  // ROWS_STALE_EVENT left with `addRecord` (wave 20 item 4): the shell no longer writes rows,
82
  // so it no longer has to tell the grid that it did.
83
  import { AGENTS_CHANGED, API_V1, AUTOMATION_OPEN_EVENT, CREDENTIALS, DATA_ERROR_EVENT, NAV_MINIMIZE_EVENT, TOAST_EVENT, UNAUTHORIZED_EVENT, VIEW_OPEN_EVENT, signal } from "../apiContract";
@@ -88,21 +89,20 @@ import type { SettingsSection } from "../settings/SettingsModal";
88
  import { Brand } from "./Brand";
89
  import { ErrorBoundary } from "./ErrorBoundary";
90
  import LoginPage from "./LoginPage";
91
- import { ASSISTANT_ROUTE, CONNECTORS_ROUTE, EMPTY_NAV_PREFS, ENVELOPE_KEYS, FEEDBACK_ROUTE, HOME_ROUTE, INBOX_ROUTE, NO_SUBSCRIPTION_TENANT, STARRED_ROUTE, SUBSCRIPTION_ROUTE, USAGE_ROUTE, MAX_NAV_FOLDERS, NAV_STAYS_EXPANDED_ROUTES, NAV_TIMEOUT_STATUS, appLink, canonicalRoute, databaseEntries, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchTableFootprint, hasVisibleRailSlot, postOpened, QUERY_ROUTE, resolveRoute, rewrittenHash, routeKeyOf, saveNavMeta, saveNavPrefs, shapeNav, splitChrome } from "./nav";
92
- import type { NavEntry, NavMetaPatch, NavPage, NavPrefs, RailSlot, Recent } from "./nav";
93
  // ⭐ 2026-08-14 β€” the database frame, extracted so the Query module can wear the SAME one.
94
  // β›” W53-T35 β€” `DbIcon` IS NO LONGER IMPORTED HERE. The Data row wears `icons.tsx::DatabaseIcon`
95
  // (owner instruction 26: the Home page's cylinder is the correct one), and `dbFrame.tsx` keeps
96
  // exporting `DbIcon` for `query/queryParts.tsx`, which still draws the coin stack. Only
97
  // `gridScopeFor` is read from this module now.
98
  import { gridScopeFor } from "./dbFrame";
99
- /* ⭐ W35-T09 β€” the app's own star (B-3): one mark, one meaning (DESIGN.md Β§4). */
100
- import { StarIcon } from "../ui/icons";
101
  // W51-T31 β€” the shell's overlays join the ONE Escape stack (C8 / DESIGN.md Β§4). Every
102
  // registration below is gated on that overlay's OWN open flag, never on `true`: the arbiter
103
  // preventDefaults and stops propagation on a claimed Escape, and Escape is also the browser's
104
  // cancel-this-drag key for the rail's folder drag-and-drop.
105
  import { useEscapeClose } from "../ui/useEscapeClose";
 
106
  /* ⭐ W35-T09 β€” the assistant's EXISTING door for opening an AI-built view: hash + a retry
107
  ladder, returning a canceller. A second emit here would be a second answer. */
108
  import { openBuiltView } from "../assistant/AssistantPage";
@@ -131,8 +131,6 @@ const ConnectorsPage = lazy(() => import("../connectors/ConnectorsPage"));
131
  */
132
  import { SHEET_ROUTE } from "../sheet";
133
  const SheetPage = lazy(() => import("../sheet/SheetPage"));
134
- /* ⭐ WAVE 35 Β· T09 (wiring W1) β€” the Starred surface, session B's tree. */
135
- const StarredPage = lazy(() => import("../starred/StarredPage"));
136
  /* ⭐ WAVE 35 Β· T06 (contract C6, wiring W2) β€” the three account surfaces, session B's tree. Lazy
137
  like every other page here: none of them is on the path to first paint, and all three are behind
138
  a menu the user has to open. Default exports, as B published them β€” `lazy()` over a NAMED export
@@ -244,6 +242,349 @@ function Lazily({ children, surface }: { children: ReactNode; surface: string })
244
  );
245
  }
246
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  import { createAlert, fetchInbox } from "../alerts/alertsApi";
248
  import {
249
  ALERT_CREATE_EVENT,
@@ -364,7 +705,7 @@ type Nav =
364
  /** β›” W31-T11 β€” parts of the payload the SERVER could not read. Not deliberate. */
365
  degraded?: string[];
366
  }
367
- | { phase: "error"; timedOut?: boolean };
368
 
369
  const NO_UTILITY: NavPage[] = [];
370
  /** Stable identity, like `NO_ENTRIES` β€” a fresh `[]` per render would re-run Home's memo. */
@@ -440,15 +781,15 @@ const findAutomation = (entries: NavEntry[]) =>
440
  * `degraded` are UNCHANGED: they draw the real rows with their unavailable arms, because there
441
  * the answer has arrived and is bad news, which is a fact worth showing rather than a wait.
442
  *
443
- * ⚠ The count is the rail's own maximum, not a guess. WAVE 34 R15/R23 took it from 7 to **6**:
444
- * Home Β· Inbox Β· Assistant Β· Agents Β· Database Β· Connectors. Query lost its row to the Chat/Query
445
- * toggle (R14), and there was never a seventh "Alerts" row β€” Inbox IS that surface.
446
  * β›” KEEP THIS NUMBER >= THE SETTLED ROW COUNT AND NEVER BELOW IT. A skeleton one bar TALLER than
447
  * the settled rail is a shrink, which is fine; one bar SHORTER is the appear-from-nowhere shove
448
  * W33-T22 was written about, arriving by a different door. The two `.shell-nav-sep` hairlines are
449
  * deliberately NOT counted: they are hidden by the same `is-rail-loading` rule as the rows.
450
  */
451
- const RAIL_SKELETON_ROWS = 6;
452
 
453
  function RailSkeleton() {
454
  return (
@@ -797,6 +1138,16 @@ function SheetIcon() {
797
  );
798
  }
799
 
 
 
 
 
 
 
 
 
 
 
800
  /** ⭐ WAVE 35 Β· T05 (owner item 6) β€” Templates. Owner, of Airtable's rail: *"a 'Templates and apps'
801
  * section? I want our app to have it too but just call it Templates ... located just above our
802
  * User button."* A sheet of cards, which is what a template gallery is: one outlined page with a
@@ -1552,7 +1903,8 @@ function ShellFrame() {
1552
  // conflating them would leave a signed-out user staring at a frame.
1553
  else if (r.status === 401) setSession({ phase: "anon" });
1554
  else setNav({ phase: "error",
1555
- ...(r.status === NAV_TIMEOUT_STATUS ? { timedOut: true } : {}) });
 
1556
  });
1557
  return () => {
1558
  dead = true;
@@ -1950,26 +2302,27 @@ function ShellFrame() {
1950
  // doc): the anon render mounted N hooks, the authed render mounted N+5, and React refuses
1951
  // a component whose hook count changes between renders. Every hook in this component stays
1952
  // above `if (session.phase …) return`, whatever lands here next wave.
1953
- // (owner item 3): the assistant's under-construction note.
1954
- // ⭐ WAVE 24 item 14 β€” it carries WHICH boarded door was knocked on, not just "open". Two
1955
- // surfaces are now under construction (the assistant, and Home's templates card) and they are
1956
- // the same dialog with a different sentence β€” a second near-identical modal would be the
1957
- // "variety is a defect" failure, and a shared one that could not say which door you came
1958
- // through would tell a reader about the wrong feature.
1959
- /** ⭐ 2026-08-14 β€” `"assistant"` LEFT THIS UNION. The assistant is a route now, so the only
1960
- * boarded door left behind this state is Templates. Narrowing the type rather than leaving the
1961
- * dead member is what makes `setAssistOpen("assistant")` a compile error instead of a screen
1962
- * nobody meant to be reachable. */
1963
  const [assistOpen, setAssistOpen] = useState<false | "templates">(false);
1964
- // β›” ESCAPE CLOSES A MODAL, or its scrim becomes a trap. The assistant note shipped with only
1965
- // a scrim-click and a Close button, and the first close-out probe to press Escape found every
1966
- // subsequent click swallowed by an invisible full-screen div β€” the
1967
- // painted-but-unclickable failure [[ui-invisible-to-assertions]] names, in reverse. The
1968
- // new-database dialog had Escape only while its INPUT held focus, which is not the same thing.
1969
- //
1970
- // W51-T31 β€” the registrations moved BELOW `newDb`'s declaration and onto `useEscapeClose`.
1971
- // The window listener that used to sit here closed BOTH dialogs on one press, because it was
1972
- // one handler reading two flags; the shared stack resolves to the topmost overlay instead.
 
 
 
 
 
 
 
 
 
1973
  // (C3-UT): "+ New database" + the user-table Add-record bar.
1974
  //
1975
  // WAVE 23 C10 β€” the dialog grew a `mode`: blank, or from a template.
@@ -1987,8 +2340,8 @@ function ShellFrame() {
1987
  }>(null);
1988
  const newDbOpenRef = useRef(false);
1989
  newDbOpenRef.current = newDb !== null;
1990
- // W51-T31 β€” the two shell dialogs, each its own entry on the ONE Escape stack.
1991
- useEscapeClose(assistOpen !== false, () => setAssistOpen(false));
1992
  // β›” The busy guard is the same one the scrim keeps: a create already in flight is not
1993
  // cancellable, so Escape must leave the dialog standing rather than orphan the request.
1994
  useEscapeClose(newDb !== null, () => setNewDb((cur) => (cur && cur.busy ? cur : null)));
@@ -2294,6 +2647,13 @@ function ShellFrame() {
2294
  * about when the nav is settled [[one-question-two-normalizers]].
2295
  */
2296
  const railLoading = nav.phase === "loading" || nav.phase === "idle";
 
 
 
 
 
 
 
2297
  const railSlot = (present: boolean): RailSlot =>
2298
  present
2299
  ? "row"
@@ -2304,10 +2664,6 @@ function ShellFrame() {
2304
  : "absent";
2305
  const automationSlot: RailSlot = railSlot(!!automation);
2306
  const analystSlot: RailSlot = railSlot(!!analyst);
2307
- // C9: decide whether the AI section exists before rendering either separator.
2308
- // A granted/unavailable module gets its normal group framing; known absence gets
2309
- // neither a row nor vertical geometry, so Data follows Inbox without a dead band.
2310
- const aiRailVisible = hasVisibleRailSlot([analystSlot, automationSlot]);
2311
  // WAVE 23 C10 β€” the flyout's search. A plain label substring, case-folded: this list is at
2312
  // most a few dozen rows, so anything cleverer (fuzzy, ranked) would be a scoring function
2313
  // nobody can predict over a set small enough to read.
@@ -2466,29 +2822,6 @@ function ShellFrame() {
2466
  <span className="shell-nav-label">Home</span>
2467
  </a>
2468
 
2469
- {/* ⭐⭐ WAVE 35 Β· T09 (owner item 8, R4) β€” STARRED, directly under Home. Owner: *"Let's add
2470
- a button under 'Home' called 'Starred' … only for Database/Agents/Queries/Marked
2471
- important that the user has marked."*
2472
- ⚠ IT TAKES THE SLOT INBOX HELD. Wave-34 R23 put Inbox *"right below Home"*; owner item
2473
- 8 is later and explicit about this position, so Inbox moves down one. Both rulings are
2474
- obeyed in their own order rather than one being quietly dropped.
2475
- ⭐ THE SHARED `StarIcon`, not a fourth hand-drawn star (B-3). It is already the app's
2476
- star β€” the view menu's and the grid's β€” and "one mark, one meaning" is DESIGN.md Β§4.
2477
- ⚠ `nav.ts::CHROME_ROUTES` is what lets this render with no grant: the page lists only
2478
- objects the caller was already given, so it shows nothing the server did not send. */}
2479
- <a
2480
- className={
2481
- "shell-nav-item shell-nav-starred" + (route === STARRED_ROUTE ? " is-active" : "")
2482
- }
2483
- href={`#/${STARRED_ROUTE}`}
2484
- onClick={expandOnNavClick}
2485
- onMouseEnter={navCollapsed ? tipEnter("Starred") : undefined}
2486
- onMouseLeave={navCollapsed ? tipLeave : undefined}
2487
- >
2488
- <StarIcon size={16} className="shell-nav-icon" />
2489
- <span className="shell-nav-label">Starred</span>
2490
- </a>
2491
-
2492
  {/* ⭐⭐ WAVE 34 R15 + R23 β€” INBOX MOVED UP, directly under Home, and took a MAIL icon.
2493
  Owner, 2026-08-16: *"Home/Inbox (change the inbox logo to a mail icon) then a subtle
2494
  line separation. Then Assistant / Agents"* and, correcting the planner minutes later,
@@ -2521,16 +2854,7 @@ function ShellFrame() {
2521
  ) : null}
2522
  </a>
2523
 
2524
- {/* The AI-group hairlines exist only when a settled Assistant or Agents slot is visible.
2525
- A known-absent module is not a row and cannot leave a divider band behind it; an
2526
- unavailable slot remains visible and therefore retains the honest group boundary.
2527
- This stays a DIRECT CHILD of `.shell-nav`, so the whole-rail loading skeleton still
2528
- hides it with every real row. */}
2529
- {aiRailVisible ? (
2530
- <div className="shell-nav-sep" role="none" />
2531
- ) : null}
2532
-
2533
- {/* The Analyst slot, above the database list β€” the host's own IA
2534
  (app.py:8166 pins "AI assistant" over the nav tree, same label,
2535
  same sparkle). Wave 18 (owner item 3): the hand-off into Streamlit
2536
  is PAUSED β€” the click opens an in-app "under construction" note
@@ -2572,8 +2896,8 @@ function ShellFrame() {
2572
  <div
2573
  className="shell-nav-item shell-nav-assist is-unavailable"
2574
  title={
2575
- nav.phase === "error" && nav.timedOut
2576
- ? "The navigation request timed out. Reload to retry."
2577
  : "This list could not be loaded in full. Reload to retry."
2578
  }
2579
  >
@@ -2593,6 +2917,11 @@ function ShellFrame() {
2593
  />
2594
  )}
2595
 
 
 
 
 
 
2596
  {/* β›” THE "AI agent" ROW WAS HERE AND IS DELETED (owner, 2026-08-14): *"AI assistant
2597
  module IS AI agent module. So no need to separate it like that."* Wave 33's own note
2598
  on this row had already argued the collapse and deferred it as ASK C-9 because
@@ -2616,78 +2945,9 @@ function ShellFrame() {
2616
  Found again at the close-out dead-code sweep, which greps every deleted symbol and
2617
  reads each survivor: this one was a stale CLAIM rather than a live caller. */}
2618
 
2619
- {/* WAVE 19 R10 / C3 β€” Automation, now AGENTS. An `<a>` to the route it already had: the
2620
- surface, its rail and its editor are another session's tree this wave and
2621
- are not touched by any of this. The LABEL comes off the payload, never a
2622
- literal here β€” the registry owns what this surface is called, and a client
2623
- that hard-codes the word is the drift that outlives the row. */}
2624
- {automation ? (
2625
- <a
2626
- className={
2627
- "shell-nav-item shell-nav-auto" +
2628
- (active && active.key === automation.key ? " is-active" : "")
2629
- }
2630
- href={automation.href}
2631
- onClick={expandOnNavClick}
2632
- onMouseEnter={navCollapsed ? tipEnter(automation.label) : undefined}
2633
- onMouseLeave={navCollapsed ? tipLeave : undefined}
2634
- >
2635
- {/* ⭐⭐ WAVE 51 Β· T30 (R15) β€” THE FLOW GLYPH, UNCONDITIONALLY.
2636
- ⚠ THE MARK CHANGED, THE RULE DID NOT. W35-T04 shipped `RobotIcon` here on owner
2637
- item 5 (*"let's just have it look like a robot"*); R15 replaces it with a
2638
- two-node flow mark. What survives verbatim from that ticket, and what the gate
2639
- actually guards, is the UNCONDITIONAL part below.
2640
- β›” THIS WAS `automation.icon ? FolderMark : RobotIcon`, AND THAT TERNARY IS THE
2641
- WHOLE DEFECT β€” not a missing glyph. `RobotIcon` had existed since wave 34 R15 and
2642
- simply LOST: on any tenant that had ever chosen a mark for `automation`, the
2643
- chosen coloured chip won and the robot never painted. So the bug reads as "the
2644
- icon is wrong" while the code looks like it already does the right thing, which
2645
- is why owner items 2 and 5 turned out to share one cause.
2646
- ⚠ The wave-23 R8 note this replaces argued Automation is among the databases that
2647
- may carry a chosen icon. R8 is not revoked for DATABASES; what changed is that
2648
- Agents is a MODULE β€” a fixed rail row like Home or Connectors β€” and a module's
2649
- glyph is the product's, not the tenant's. `FolderMark` is still how every real
2650
- database draws its chosen mark. */}
2651
- <AgentIcon />
2652
- <span className="shell-nav-label">{automation.label}</span>
2653
- </a>
2654
- ) : automationSlot === "unavailable" ? (
2655
- /* β›” W31-T11 β€” NOT LOADING, AND NOT ABSENT-ON-PURPOSE: the server said this payload
2656
- is incomplete (`degraded`), or it never answered. The row states that rather than
2657
- leaving a gap the reader has to interpret β€” which is the whole of owner item 6b. */
2658
- <div
2659
- className="shell-nav-item shell-nav-auto is-unavailable"
2660
- title={
2661
- nav.phase === "error" && nav.timedOut
2662
- ? "The navigation request timed out. Reload to retry."
2663
- : "This list could not be loaded in full. Reload to retry."
2664
- }
2665
- >
2666
- <AgentIcon />
2667
- <span className="shell-nav-label shell-nav-label--muted">Agents</span>
2668
- <span className="shell-nav-note-dot" aria-hidden="true" />
2669
- </div>
2670
- ) : (
2671
- /* Mirror Assistant's zero-geometry absent arm: actual permission absence is silent;
2672
- only an incomplete navigation response renders the unavailable row above. */
2673
- <div
2674
- className="shell-nav-item shell-nav-auto is-rail-skeleton"
2675
- aria-hidden="true"
2676
- hidden
2677
- style={{ display: "none" }}
2678
- />
2679
- )}
2680
-
2681
- {/* Close the AI group only when it rendered at least one real/unavailable row. */}
2682
- {aiRailVisible ? (
2683
- <div className="shell-nav-sep" role="none" />
2684
- ) : null}
2685
-
2686
- {/* ⭐⭐ WAVE 49 Β· T01 (rulings R1, R2, R30) β€” SHEET, AT THE HEAD OF THE DATA BAND.
2687
- R30 fixes the whole rail: Home Β· Starred Β· Inbox | Assistant Β· Agents | Sheet Β· Data Β·
2688
- Connectors. So this row stands AFTER the AI group's closing separator and IMMEDIATELY
2689
- BEFORE the Data button, and `verify_shell_rail.py::data_band_faults` asserts both the
2690
- order and the adjacency rather than trusting this comment.
2691
 
2692
  β›” AN `<a>` LIKE CONNECTORS, UNCONDITIONAL, AND BOTH HALVES MATTER. A `<button>` would
2693
  be the Data affordance's shape (it opens a panel over a server-sent list); Sheet is a
@@ -2759,6 +3019,58 @@ function ShellFrame() {
2759
  <span className="shell-nav-label">Data</span>
2760
  </button>
2761
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2762
  {/* ⭐ WAVE 23 item 10 (R8, contract C11, wiring W23-W3) β€” CONNECTORS.
2763
  ⭐ WAVE 24 item 1 β€” it moved BELOW Database. R8 put it above; the owner's wave-24
2764
  order puts the two destinations that open panels-over-server-data (Database, then
@@ -2791,12 +3103,7 @@ function ShellFrame() {
2791
  surfaces the server never granted. */}
2792
  {nav.phase === "error" ? (
2793
  <div className="shell-nav-note">
2794
- {nav.timedOut
2795
- ? /* ⭐ W31-T11 β€” A DEADLINE IS A DIFFERENT FACT FROM A DEAD SERVER, and it earns
2796
- its own sentence: before this ticket `fetchNav` had no timeout at all, so
2797
- this state was UNREACHABLE and the rail waited for ever. */
2798
- "Navigation took too long to load. Reload to retry."
2799
- : "Navigation unavailable. Reload to retry."}
2800
  </div>
2801
  ) : null}
2802
  {/* β›” W31-T11 β€” A 200 THAT COULD NOT READ THE DATABASES SAYS SO. This is the case that
@@ -2820,11 +3127,9 @@ function ShellFrame() {
2820
  ) : null}
2821
  </nav>
2822
 
2823
- {/* ⭐⭐ WAVE 35 Β· T05 (owner item 6) β€” TEMPLATES, DIRECTLY ABOVE THE USER BUTTON.
2824
- β›” IT OPENS THE SAME DOOR HOME'S CARD OPENS β€” `setAssistOpen("templates")`, the exact
2825
- handler passed to Home as `onTemplates`. A second under-construction note would be a
2826
- second answer to one question, and the two would drift the day either is replaced by a
2827
- real picker.
2828
  β›” A SIBLING OF `.shell-side-bottom`, NOT A CHILD, and that is behavioural rather than
2829
  cosmetic: that band carries an `onClickCapture` which, while collapsed, swallows the
2830
  click and expands the rail instead (the account POPOVER cannot fit in a 56px strip).
@@ -2849,7 +3154,7 @@ function ShellFrame() {
2849
  // W53-T33 β€” instruction 6 says "any of the icon". Templates opens an OVERLAY rather
2850
  // than a route, and the rail expanding behind it is what every other row now does.
2851
  expandOnNavClick();
2852
- setAssistOpen("templates");
2853
  }}
2854
  onMouseEnter={navCollapsed ? tipEnter("Templates") : undefined}
2855
  onMouseLeave={navCollapsed ? tipLeave : undefined}
@@ -3028,33 +3333,6 @@ function ShellFrame() {
3028
  </div>
3029
  ) : active ? (
3030
  <StranglerPage entry={active} />
3031
- ) : route === STARRED_ROUTE ? (
3032
- // ⭐⭐ WAVE 35 Β· T09 (owner item 8, wiring W1) β€” the Starred surface, session B's tree.
3033
- // β›” `dbEntries`, NOT `entries`, and B's own note says so for the same reason Home's does:
3034
- // the Agents SURFACE is a granted nav entry with an href, so `entries` would draw it a
3035
- // tile under the heading "Databases", beside the section listing what it contains. That
3036
- // was a real wave-24 defect, found by LOOKING rather than by any gate.
3037
- // β›” EVERY CALLBACK IS REQUIRED, never optional: an optional one the frame forgot to pass
3038
- // degrades to "clicking a starred thing does nothing", which is indistinguishable from
3039
- // "the feature was never built" and is red in no gate.
3040
- // ⚠ `onOpenQuery` calls the assistant's EXISTING `openBuiltView`, which already does hash
3041
- // + a retry ladder and returns a canceller β€” a second emit here would be a second answer
3042
- // to one question. Cancel any ladder still running, as the view path does.
3043
- <Lazily surface="Starred">
3044
- <StarredPage
3045
- entries={dbEntries}
3046
- automations={autoTiles}
3047
- onOpenAutomation={(autoId) => {
3048
- window.location.hash = "#/automation";
3049
- signal(AUTOMATION_OPEN_EVENT, { autoId });
3050
- }}
3051
- onOpenQuery={(qid) => {
3052
- viewEmitCancel.current?.();
3053
- viewEmitCancel.current = openBuiltView(qid);
3054
- }}
3055
- onOpenView={openViewInDatabase}
3056
- />
3057
- </Lazily>
3058
  ) : route === FEEDBACK_ROUTE ? (
3059
  // ⭐⭐ WAVE 35 Β· T06 (owner item 13, R8, contract C6, wiring W2) β€” the three account
3060
  // surfaces. All three take NO props, on purpose and per B's published contract: Usage
@@ -3215,6 +3493,9 @@ function ShellFrame() {
3215
  // true by construction, and the build door re-checks with the same wall regardless.
3216
  <Lazily surface="Assistant"><AssistantPage granted={entries} /></Lazily>
3217
  ) : nav.phase === "ready" ? (
 
 
 
3218
  // ⭐ WAVE 23 item 9 (R7, C10) β€” HOME, AND IT IS THE FALLBACK RATHER THAN A ROUTE MATCH.
3219
  //
3220
  // β›” WHY `!active` AND NOT `route === HOME_ROUTE`. Three states have to land here and
@@ -3233,8 +3514,10 @@ function ShellFrame() {
3233
  // hero's create door, and its empty line carries the hero's sentence (HomePage's
3234
  // `home-empty`, which branches on `entries.length === 0` for exactly this reason).
3235
  // Booked as a dated amendment in the wave doc, since it moves an R4 surface.
3236
- <Lazily surface="Home">
3237
  <HomePage
 
 
3238
  // ⭐ `dbEntries`, NOT `entries` β€” found by LOOKING at it (wave 24 close-out visual
3239
  // pass), which is the only way it could have been found. The Automation SURFACE is a
3240
  // granted nav entry with an href, so `allDatabases` drew it a tile under the heading
@@ -3248,11 +3531,8 @@ function ShellFrame() {
3248
  folders={navPrefs.folders}
3249
  folderPlacement={navPrefs.placement}
3250
  automations={autoTiles}
3251
- // ⭐ WAVE 24 item 14 β€” the templates CARD is boarded. It opens the same
3252
- // under-construction note the AI assistant uses, rather than the picker.
3253
- // ⚠ The flyout's "From a template" row is UNAFFECTED (R9 keeps it working) β€” see
3254
- // HomePage's own note on why that asymmetry is deliberate rather than a miss.
3255
- onTemplates={() => setAssistOpen("templates")}
3256
  onNewDatabase={() => openNewDb("blank")}
3257
  /* β›” `onAutomated` LEFT WITH THE CARD IT OPENED (wave 25 item 5a, R8). */
3258
  onConnectors={() => {
@@ -3268,6 +3548,10 @@ function ShellFrame() {
3268
  view opened from Home and the same view opened from Starred must not behave
3269
  differently, and two copies of "route then ask" is how they would. */
3270
  onOpenView={openViewInDatabase}
 
 
 
 
3271
  />
3272
  </Lazily>
3273
  ) : nav.phase === "error" ? (
@@ -3279,8 +3563,15 @@ function ShellFrame() {
3279
  // Home above (which welcomes an empty workspace properly), so this is only ever the
3280
  // nav that FAILED, and the nested ternary that used to sort the two is gone.
3281
  <div className="shell-placeholder">
3282
- <h1>Nothing to show</h1>
3283
- <p>The navigation service did not answer. Reload to retry.</p>
 
 
 
 
 
 
 
3284
  </div>
3285
  ) : (
3286
  // Still asking (`loading`, or the `idle` beat before the effect runs).
@@ -3295,32 +3586,14 @@ function ShellFrame() {
3295
  {/* The server's own confirmation of a write (X2's `toast`). In standalone
3296
  it is the ONLY feedback for the events whose effect the payload does
3297
  not yet echo back β€” cohort membership, list adds, folder moves. */}
3298
- {/* Wave 18 (owner item 3): the boarded door.
3299
- ⭐ 2026-08-14 β€” IT IS THE TEMPLATES DOOR ONLY NOW. The assistant arm is gone with the
3300
- boarding: that surface exists (`#/assistant`), so an "under construction" note for it
3301
- would be a lie about a working feature. Templates is a SEPARATE boarded door (wave 24
3302
- item 14) and is deliberately left exactly as it was β€” the owner unblocked the assistant,
3303
- not the template picker. */}
3304
  {assistOpen ? (
3305
- <div className="shell-newdb-scrim" onClick={() => setAssistOpen(false)}>
3306
- <div
3307
- className="shell-newdb shell-assist-note"
3308
- role="dialog"
3309
- aria-label="Templates"
3310
- onClick={(e) => e.stopPropagation()}
3311
- >
3312
- <h2>Templates</h2>
3313
- <p className="shell-newdb-sub">
3314
- Under construction. Curated template sets are being built and will open here in
3315
- a later release.
3316
- </p>
3317
- <div className="shell-newdb-actions">
3318
- <button type="button" className="login-submit" onClick={() => setAssistOpen(false)}>
3319
- Close
3320
- </button>
3321
- </div>
3322
- </div>
3323
- </div>
3324
  ) : null}
3325
 
3326
  {/* Wave 18 (C3-UT): the New-database dialog. Scrim click cancels unless mid-create. */}
 
48
  ⚠ AND `npx tsc --noEmit` DID NOT CATCH IT β€” only `npm run build`'s `tsc -b` did. The two are not
49
  the same check here; a lane that runs the first and skips the second gets a false green on every
50
  symbol it orphans. */
51
+ import type { MouseEvent as ReactMouseEvent, ReactNode, RefObject } from "react";
52
  /**
53
  * ⭐ WAVE-27 item 34 (I5) β€” ROUTE-LEVEL CODE SPLITTING.
54
  *
 
78
  import { OverlayProvider } from "../customer-grid/OverlaySurface";
79
  import { dataPathHash, readDataPath } from "../customer-grid/dataPath";
80
  import type { DataDatabase } from "../customer-grid/dataPath";
81
+ import "../styles/wave55/apps.css";
82
  // ROWS_STALE_EVENT left with `addRecord` (wave 20 item 4): the shell no longer writes rows,
83
  // so it no longer has to tell the grid that it did.
84
  import { AGENTS_CHANGED, API_V1, AUTOMATION_OPEN_EVENT, CREDENTIALS, DATA_ERROR_EVENT, NAV_MINIMIZE_EVENT, TOAST_EVENT, UNAUTHORIZED_EVENT, VIEW_OPEN_EVENT, signal } from "../apiContract";
 
89
  import { Brand } from "./Brand";
90
  import { ErrorBoundary } from "./ErrorBoundary";
91
  import LoginPage from "./LoginPage";
92
+ import { APP_ROUTE, ASSISTANT_ROUTE, CONNECTORS_ROUTE, EMPTY_NAV_PREFS, ENVELOPE_KEYS, FEEDBACK_ROUTE, HOME_ROUTE, INBOX_ROUTE, NO_SUBSCRIPTION_TENANT, SUBSCRIPTION_ROUTE, USAGE_ROUTE, MAX_NAV_FOLDERS, NAV_MALFORMED_STATUS, NAV_STAYS_EXPANDED_ROUTES, NAV_TIMEOUT_STATUS, appLink, canonicalRoute, databaseEntries, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchSchema, fetchTableFootprint, postOpened, QUERY_ROUTE, resolveRoute, rewrittenHash, routeKeyOf, saveNavMeta, saveNavPrefs, shapeNav, splitChrome } from "./nav";
93
+ import type { NavEntry, NavMetaPatch, NavPage, NavPrefs, RailSlot, Recent, SchemaField, SchemaPayload } from "./nav";
94
  // ⭐ 2026-08-14 β€” the database frame, extracted so the Query module can wear the SAME one.
95
  // β›” W53-T35 β€” `DbIcon` IS NO LONGER IMPORTED HERE. The Data row wears `icons.tsx::DatabaseIcon`
96
  // (owner instruction 26: the Home page's cylinder is the correct one), and `dbFrame.tsx` keeps
97
  // exporting `DbIcon` for `query/queryParts.tsx`, which still draws the coin stack. Only
98
  // `gridScopeFor` is read from this module now.
99
  import { gridScopeFor } from "./dbFrame";
 
 
100
  // W51-T31 β€” the shell's overlays join the ONE Escape stack (C8 / DESIGN.md Β§4). Every
101
  // registration below is gated on that overlay's OWN open flag, never on `true`: the arbiter
102
  // preventDefaults and stops propagation on a claimed Escape, and Escape is also the browser's
103
  // cancel-this-drag key for the rail's folder drag-and-drop.
104
  import { useEscapeClose } from "../ui/useEscapeClose";
105
+ import { useApplicationWizardOverlay } from "./useApplicationWizardOverlay";
106
  /* ⭐ W35-T09 β€” the assistant's EXISTING door for opening an AI-built view: hash + a retry
107
  ladder, returning a canceller. A second emit here would be a second answer. */
108
  import { openBuiltView } from "../assistant/AssistantPage";
 
131
  */
132
  import { SHEET_ROUTE } from "../sheet";
133
  const SheetPage = lazy(() => import("../sheet/SheetPage"));
 
 
134
  /* ⭐ WAVE 35 Β· T06 (contract C6, wiring W2) β€” the three account surfaces, session B's tree. Lazy
135
  like every other page here: none of them is on the path to first paint, and all three are behind
136
  a menu the user has to open. Default exports, as B published them β€” `lazy()` over a NAMED export
 
242
  );
243
  }
244
 
245
+ type ApplicationTemplateKind = "route" | "catalog";
246
+
247
+ interface ApplicationTemplateRole {
248
+ key: string;
249
+ label: string;
250
+ required: boolean;
251
+ types: string[];
252
+ }
253
+
254
+ interface ApplicationTemplate {
255
+ kind: ApplicationTemplateKind;
256
+ label: string;
257
+ applicationType: "route" | "map";
258
+ displayMode: "map";
259
+ fieldRoles: ApplicationTemplateRole[];
260
+ defaultPlacement: { section: "app"; order: number };
261
+ }
262
+
263
+ interface CreatedTemplateApplication {
264
+ id: string;
265
+ name: string;
266
+ type: string;
267
+ templateKind: ApplicationTemplateKind;
268
+ sourceDatabase: string;
269
+ fieldMap: Record<string, string>;
270
+ openTarget?: { database?: string };
271
+ }
272
+
273
+ type WizardLoad<T> =
274
+ | { phase: "idle" }
275
+ | { phase: "loading" }
276
+ | { phase: "ready"; value: T }
277
+ | { phase: "error"; message: string };
278
+
279
+ function TemplateRouteIcon() {
280
+ return (
281
+ <svg viewBox="0 0 24 24" aria-hidden="true">
282
+ <circle cx="5" cy="6" r="2.2" />
283
+ <circle cx="19" cy="18" r="2.2" />
284
+ <path d="M7.2 6h3.3c2.2 0 2.2 3.3 4.4 3.3h1c2 0 2 3.6 0 3.6h-4.8c-2.1 0-2.1 3.1-4.1 3.1H5" />
285
+ </svg>
286
+ );
287
+ }
288
+
289
+ function TemplateCatalogIcon() {
290
+ return (
291
+ <svg viewBox="0 0 24 24" aria-hidden="true">
292
+ <rect x="3" y="4" width="18" height="16" rx="2" />
293
+ <path d="M3 9h18M9 9v11M15 9v11" />
294
+ </svg>
295
+ );
296
+ }
297
+
298
+ function ApplicationWizard({
299
+ databases,
300
+ panelRef,
301
+ onClose,
302
+ onBusyChange,
303
+ onCreated,
304
+ }: {
305
+ databases: DataDatabase[];
306
+ panelRef: RefObject<HTMLDivElement>;
307
+ onClose: () => void;
308
+ onBusyChange: (busy: boolean) => void;
309
+ onCreated: (application: CreatedTemplateApplication) => void;
310
+ }) {
311
+ const [step, setStep] = useState(0);
312
+ const [templates, setTemplates] = useState<WizardLoad<ApplicationTemplate[]>>({ phase: "loading" });
313
+ const [templateKind, setTemplateKind] = useState<ApplicationTemplateKind | "">("");
314
+ const [sourceDatabase, setSourceDatabase] = useState("");
315
+ const [schema, setSchema] = useState<WizardLoad<SchemaPayload>>({ phase: "idle" });
316
+ const [fieldMap, setFieldMap] = useState<Record<string, string>>({});
317
+ const [name, setName] = useState("");
318
+ const [busy, setBusy] = useState(false);
319
+ const [error, setError] = useState("");
320
+ const schemaGeneration = useRef(0);
321
+
322
+ useEffect(() => {
323
+ const controller = new AbortController();
324
+ setTemplates({ phase: "loading" });
325
+ void fetch(`${API_V1}/nav/application-templates`, {
326
+ credentials: CREDENTIALS,
327
+ signal: controller.signal,
328
+ }).then(async (response) => {
329
+ const body = await response.json().catch(() => ({}));
330
+ if (!response.ok) throw new Error(String(
331
+ body?.detail?.message ?? body?.detail ?? "Application templates could not be loaded.",
332
+ ));
333
+ const offered = Array.isArray(body?.templates)
334
+ ? body.templates.filter((row: unknown): row is ApplicationTemplate => {
335
+ if (!row || typeof row !== "object" || Array.isArray(row)) return false;
336
+ const candidate = row as Partial<ApplicationTemplate>;
337
+ return (candidate.kind === "route" || candidate.kind === "catalog") &&
338
+ Array.isArray(candidate.fieldRoles) && !!candidate.defaultPlacement;
339
+ })
340
+ : [];
341
+ if (!offered.length) throw new Error("No Application templates are available.");
342
+ if (!controller.signal.aborted) setTemplates({ phase: "ready", value: offered });
343
+ }).catch((reason: unknown) => {
344
+ if (!controller.signal.aborted) setTemplates({
345
+ phase: "error",
346
+ message: reason instanceof Error ? reason.message : "Application templates could not be loaded.",
347
+ });
348
+ });
349
+ return () => controller.abort();
350
+ }, []);
351
+
352
+ useEffect(() => {
353
+ onBusyChange(busy);
354
+ return () => onBusyChange(false);
355
+ }, [busy, onBusyChange]);
356
+
357
+ useEffect(() => {
358
+ const mine = ++schemaGeneration.current;
359
+ if (!sourceDatabase) {
360
+ setSchema({ phase: "idle" });
361
+ return;
362
+ }
363
+ setSchema({ phase: "loading" });
364
+ void fetchSchema(sourceDatabase).then((answer) => {
365
+ if (mine !== schemaGeneration.current) return;
366
+ setSchema(answer
367
+ ? { phase: "ready", value: answer }
368
+ : { phase: "error", message: "The database fields could not be loaded." });
369
+ });
370
+ return () => { schemaGeneration.current += 1; };
371
+ }, [sourceDatabase]);
372
+
373
+ useApplicationWizardOverlay(panelRef, onClose);
374
+
375
+ const template = templates.phase === "ready"
376
+ ? templates.value.find((candidate) => candidate.kind === templateKind) ?? null
377
+ : null;
378
+ const mappedLatitude = fieldMap.latitude ?? "";
379
+ const mappedLongitude = fieldMap.longitude ?? "";
380
+ const missingRequired = template?.fieldRoles.some(
381
+ (role) => role.required && !String(fieldMap[role.key] ?? "").trim(),
382
+ ) ?? true;
383
+ const coordinatePairError = templateKind === "route" && (
384
+ Boolean(mappedLatitude) !== Boolean(mappedLongitude) ||
385
+ Boolean(mappedLatitude && mappedLongitude && mappedLatitude === mappedLongitude)
386
+ );
387
+ const canContinue = step === 0
388
+ ? !!template
389
+ : step === 1
390
+ ? !!sourceDatabase && schema.phase === "ready"
391
+ : step === 2
392
+ ? !missingRequired && !coordinatePairError
393
+ : !!name.trim();
394
+
395
+ const chooseTemplate = (candidate: ApplicationTemplate) => {
396
+ setTemplateKind(candidate.kind);
397
+ setName(candidate.label);
398
+ setFieldMap({});
399
+ setError("");
400
+ };
401
+
402
+ const createApplication = async () => {
403
+ if (!template || schema.phase !== "ready" || !canContinue || busy) return;
404
+ setBusy(true);
405
+ setError("");
406
+ const mapped = Object.fromEntries(
407
+ Object.entries(fieldMap).filter(([, value]) => String(value).trim()),
408
+ );
409
+ try {
410
+ const response = await fetch(`${API_V1}/nav/applications`, {
411
+ method: "POST",
412
+ credentials: CREDENTIALS,
413
+ headers: { "Content-Type": "application/json" },
414
+ body: JSON.stringify({
415
+ name: name.trim(),
416
+ templateKind: template.kind,
417
+ type: template.applicationType,
418
+ sourceDatabase,
419
+ fieldMap: mapped,
420
+ navPlacement: template.defaultPlacement,
421
+ }),
422
+ });
423
+ const body = await response.json().catch(() => ({}));
424
+ if (!response.ok || !body?.application?.id) {
425
+ throw new Error(String(
426
+ body?.detail?.message ?? body?.detail ?? "The Application was not saved.",
427
+ ));
428
+ }
429
+ onCreated(body.application as CreatedTemplateApplication);
430
+ } catch (reason: unknown) {
431
+ setError(reason instanceof Error ? reason.message : "The Application was not saved.");
432
+ } finally {
433
+ setBusy(false);
434
+ }
435
+ };
436
+
437
+ const headings = ["Choose a template", "Choose a database", "Map the fields", "Review and create"];
438
+ return (
439
+ <div className="shell-newdb-scrim">
440
+ <div
441
+ ref={panelRef}
442
+ className="shell-newdb app-wizard"
443
+ role="dialog"
444
+ aria-modal="true"
445
+ aria-label="Create application"
446
+ >
447
+ <header className="app-wizard-head">
448
+ <div>
449
+ <p>New Application</p>
450
+ <h2>{headings[step]}</h2>
451
+ </div>
452
+ <button type="button" className="app-wizard-close" aria-label="Close" onClick={onClose} disabled={busy}>
453
+ <svg viewBox="0 0 16 16" aria-hidden="true"><path d="m3.5 3.5 9 9m0-9-9 9" /></svg>
454
+ </button>
455
+ </header>
456
+ <ol className="app-wizard-steps" aria-label="Application setup progress">
457
+ {["Template", "Database", "Fields", "Review"].map((label, index) => (
458
+ <li key={label} className={index === step ? "is-current" : index < step ? "is-done" : ""}
459
+ aria-current={index === step ? "step" : undefined}>
460
+ <span>{index + 1}</span>{label}
461
+ </li>
462
+ ))}
463
+ </ol>
464
+
465
+ <div className="app-wizard-body">
466
+ {step === 0 ? (
467
+ templates.phase === "loading" ? (
468
+ <div className="app-wizard-loading" role="status" aria-label="Loading templates">
469
+ <span /><span />
470
+ </div>
471
+ ) : templates.phase === "error" ? (
472
+ <p className="app-wizard-message is-error" role="alert">{templates.message}</p>
473
+ ) : templates.phase === "ready" ? (
474
+ <div className="app-wizard-template-grid">
475
+ {templates.value.map((candidate) => (
476
+ <button
477
+ key={candidate.kind}
478
+ type="button"
479
+ className={templateKind === candidate.kind ? "app-wizard-template is-selected" : "app-wizard-template"}
480
+ aria-pressed={templateKind === candidate.kind}
481
+ onClick={() => chooseTemplate(candidate)}
482
+ >
483
+ <span className="app-wizard-template-icon">
484
+ {candidate.kind === "route" ? <TemplateRouteIcon /> : <TemplateCatalogIcon />}
485
+ </span>
486
+ <span><strong>{candidate.label}</strong><small>
487
+ {candidate.kind === "route"
488
+ ? "Plan customer routes from mapped records."
489
+ : "Browse mapped records as a visual catalog."}
490
+ </small></span>
491
+ </button>
492
+ ))}
493
+ </div>
494
+ ) : null
495
+ ) : null}
496
+
497
+ {step === 1 ? (
498
+ <label className="app-wizard-field">
499
+ <span>Source database</span>
500
+ <select value={sourceDatabase} onChange={(event) => {
501
+ setSourceDatabase(event.target.value);
502
+ setFieldMap({});
503
+ setError("");
504
+ }}>
505
+ <option value="">Choose a database</option>
506
+ {databases.map((database) => <option key={database.key} value={database.key}>{database.label}</option>)}
507
+ </select>
508
+ {schema.phase === "loading" ? <small role="status">Loading database fields...</small> : null}
509
+ {schema.phase === "error" ? <small className="is-error" role="alert">{schema.message}</small> : null}
510
+ </label>
511
+ ) : null}
512
+
513
+ {step === 2 && template && schema.phase === "ready" ? (
514
+ <div className="app-wizard-field-list">
515
+ <p>Map each Application role to a field in {schema.value.label}.</p>
516
+ {template.fieldRoles.map((role) => {
517
+ const options = schema.value.fields.filter((field) =>
518
+ !role.types.length || role.types.includes(field.type.toLowerCase()),
519
+ );
520
+ return (
521
+ <label className="app-wizard-field" key={role.key}>
522
+ <span>{role.label}{role.required ? <small>Required</small> : <small>Optional</small>}</span>
523
+ <select value={fieldMap[role.key] ?? ""} onChange={(event) => {
524
+ setFieldMap((current) => ({ ...current, [role.key]: event.target.value }));
525
+ setError("");
526
+ }}>
527
+ <option value="">{role.required ? "Choose a field" : "Not mapped"}</option>
528
+ {options.map((field: SchemaField) => (
529
+ <option key={field.key} value={field.key}>{field.label}</option>
530
+ ))}
531
+ </select>
532
+ </label>
533
+ );
534
+ })}
535
+ {coordinatePairError ? (
536
+ <p className="app-wizard-message is-error" role="alert">
537
+ Routing needs both coordinate fields or neither, and they must be different.
538
+ </p>
539
+ ) : null}
540
+ </div>
541
+ ) : null}
542
+
543
+ {step === 3 && template ? (
544
+ <div className="app-wizard-review">
545
+ <label className="app-wizard-field">
546
+ <span>Application name</span>
547
+ <input value={name} maxLength={120} onChange={(event) => { setName(event.target.value); setError(""); }} />
548
+ </label>
549
+ <dl>
550
+ <div><dt>Template</dt><dd>{template.label}</dd></div>
551
+ <div><dt>Database</dt><dd>{schema.phase === "ready" ? schema.value.label : sourceDatabase}</dd></div>
552
+ {template.fieldRoles.filter((role) => fieldMap[role.key]).map((role) => (
553
+ <div key={role.key}><dt>{role.label}</dt><dd>{
554
+ schema.phase === "ready"
555
+ ? schema.value.fields.find((field) => field.key === fieldMap[role.key])?.label ?? fieldMap[role.key]
556
+ : fieldMap[role.key]
557
+ }</dd></div>
558
+ ))}
559
+ </dl>
560
+ <p className="app-wizard-review-note">This saves an Application definition in App and opens it with the selected database.</p>
561
+ </div>
562
+ ) : null}
563
+
564
+ <p className={error ? "app-wizard-message is-error" : "app-wizard-message"} role="alert">
565
+ {error}
566
+ </p>
567
+ </div>
568
+
569
+ <footer className="app-wizard-actions">
570
+ <button type="button" className="app-wizard-secondary" onClick={onClose} disabled={busy}>Cancel</button>
571
+ <span />
572
+ {step > 0 ? (
573
+ <button type="button" className="app-wizard-secondary" onClick={() => { setStep((current) => current - 1); setError(""); }} disabled={busy}>Back</button>
574
+ ) : null}
575
+ {step < 3 ? (
576
+ <button type="button" className="login-submit" disabled={!canContinue || busy}
577
+ onClick={() => { setStep((current) => current + 1); setError(""); }}>Continue</button>
578
+ ) : (
579
+ <button type="button" className="login-submit" disabled={!canContinue || busy}
580
+ onClick={() => void createApplication()}>{busy ? "Creating..." : "Create and open"}</button>
581
+ )}
582
+ </footer>
583
+ </div>
584
+ </div>
585
+ );
586
+ }
587
+
588
  import { createAlert, fetchInbox } from "../alerts/alertsApi";
589
  import {
590
  ALERT_CREATE_EVENT,
 
705
  /** β›” W31-T11 β€” parts of the payload the SERVER could not read. Not deliberate. */
706
  degraded?: string[];
707
  }
708
+ | { phase: "error"; timedOut?: boolean; malformed?: boolean };
709
 
710
  const NO_UTILITY: NavPage[] = [];
711
  /** Stable identity, like `NO_ENTRIES` β€” a fresh `[]` per render would re-run Home's memo. */
 
781
  * `degraded` are UNCHANGED: they draw the real rows with their unavailable arms, because there
782
  * the answer has arrived and is bad news, which is a fact worth showing rather than a wait.
783
  *
784
+ * ⚠ The count is the rail's own maximum, not a guess. WAVE 55 instruction 2 fixes it at **8**:
785
+ * Home Β· Inbox Β· Assistant Β· Sheet Β· Data Β· Agents Β· App Β· Connectors. Starred moved into Home's
786
+ * filter, while App became the tenant Application directory.
787
  * β›” KEEP THIS NUMBER >= THE SETTLED ROW COUNT AND NEVER BELOW IT. A skeleton one bar TALLER than
788
  * the settled rail is a shrink, which is fine; one bar SHORTER is the appear-from-nowhere shove
789
  * W33-T22 was written about, arriving by a different door. The two `.shell-nav-sep` hairlines are
790
  * deliberately NOT counted: they are hidden by the same `is-rail-loading` rule as the rows.
791
  */
792
+ const RAIL_SKELETON_ROWS = 8;
793
 
794
  function RailSkeleton() {
795
  return (
 
1138
  );
1139
  }
1140
 
1141
+ /** Tenant Apps: one window with four arranged parts, in the shell's existing stroke register. */
1142
+ function AppIcon() {
1143
+ return (
1144
+ <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
1145
+ <rect x="2.3" y="2.3" width="11.4" height="11.4" rx="1.7" />
1146
+ <path d="M2.3 6.2h11.4M6.2 6.2v7.5M10 6.2v7.5" />
1147
+ </svg>
1148
+ );
1149
+ }
1150
+
1151
  /** ⭐ WAVE 35 Β· T05 (owner item 6) β€” Templates. Owner, of Airtable's rail: *"a 'Templates and apps'
1152
  * section? I want our app to have it too but just call it Templates ... located just above our
1153
  * User button."* A sheet of cards, which is what a template gallery is: one outlined page with a
 
1903
  // conflating them would leave a signed-out user staring at a frame.
1904
  else if (r.status === 401) setSession({ phase: "anon" });
1905
  else setNav({ phase: "error",
1906
+ ...(r.status === NAV_TIMEOUT_STATUS ? { timedOut: true } : {}),
1907
+ ...(r.status === NAV_MALFORMED_STATUS ? { malformed: true } : {}) });
1908
  });
1909
  return () => {
1910
  dead = true;
 
2302
  // doc): the anon render mounted N hooks, the authed render mounted N+5, and React refuses
2303
  // a component whose hook count changes between renders. Every hook in this component stays
2304
  // above `if (session.phase …) return`, whatever lands here next wave.
2305
+ /** Templates, Home and App all open this one creation flow. The narrow state keeps unrelated
2306
+ * overlays from drifting into the Application wizard. */
 
 
 
 
 
 
 
 
2307
  const [assistOpen, setAssistOpen] = useState<false | "templates">(false);
2308
+ const appWizardRef = useRef<HTMLDivElement>(null);
2309
+ const appWizardBusy = useRef(false);
2310
+ const openApplicationWizard = useCallback(() => {
2311
+ setAssistOpen("templates");
2312
+ }, []);
2313
+ const closeApplicationWizard = useCallback(() => {
2314
+ if (appWizardBusy.current) return;
2315
+ setAssistOpen(false);
2316
+ }, []);
2317
+ const setApplicationWizardBusy = useCallback((busy: boolean) => {
2318
+ appWizardBusy.current = busy;
2319
+ }, []);
2320
+ const launchCreatedApplication = useCallback((application: CreatedTemplateApplication) => {
2321
+ appWizardBusy.current = false;
2322
+ setAssistOpen(false);
2323
+ const database = application.openTarget?.database || application.sourceDatabase;
2324
+ window.location.hash = dataPathHash({ database, application: application.id });
2325
+ }, []);
2326
  // (C3-UT): "+ New database" + the user-table Add-record bar.
2327
  //
2328
  // WAVE 23 C10 β€” the dialog grew a `mode`: blank, or from a template.
 
2340
  }>(null);
2341
  const newDbOpenRef = useRef(false);
2342
  newDbOpenRef.current = newDb !== null;
2343
+ // ApplicationWizard joins the shared overlay layer itself so focus trap, restoration and
2344
+ // Escape ordering are one contract. The older database dialog still needs this direct claim.
2345
  // β›” The busy guard is the same one the scrim keeps: a create already in flight is not
2346
  // cancellable, so Escape must leave the dialog standing rather than orphan the request.
2347
  useEscapeClose(newDb !== null, () => setNewDb((cur) => (cur && cur.busy ? cur : null)));
 
2647
  * about when the nav is settled [[one-question-two-normalizers]].
2648
  */
2649
  const railLoading = nav.phase === "loading" || nav.phase === "idle";
2650
+ const navFailureMessage = nav.phase !== "error"
2651
+ ? ""
2652
+ : nav.timedOut
2653
+ ? "Navigation took too long to load. Try again."
2654
+ : nav.malformed
2655
+ ? "Navigation data could not be read. Try again."
2656
+ : "Navigation unavailable. Try again.";
2657
  const railSlot = (present: boolean): RailSlot =>
2658
  present
2659
  ? "row"
 
2664
  : "absent";
2665
  const automationSlot: RailSlot = railSlot(!!automation);
2666
  const analystSlot: RailSlot = railSlot(!!analyst);
 
 
 
 
2667
  // WAVE 23 C10 β€” the flyout's search. A plain label substring, case-folded: this list is at
2668
  // most a few dozen rows, so anything cleverer (fuzzy, ranked) would be a scoring function
2669
  // nobody can predict over a set small enough to read.
 
2822
  <span className="shell-nav-label">Home</span>
2823
  </a>
2824
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2825
  {/* ⭐⭐ WAVE 34 R15 + R23 β€” INBOX MOVED UP, directly under Home, and took a MAIL icon.
2826
  Owner, 2026-08-16: *"Home/Inbox (change the inbox logo to a mail icon) then a subtle
2827
  line separation. Then Assistant / Agents"* and, correcting the planner minutes later,
 
2854
  ) : null}
2855
  </a>
2856
 
2857
+ {/* The Analyst slot closes the first rail group: Home / Inbox / Assistant.
 
 
 
 
 
 
 
 
 
2858
  (app.py:8166 pins "AI assistant" over the nav tree, same label,
2859
  same sparkle). Wave 18 (owner item 3): the hand-off into Streamlit
2860
  is PAUSED β€” the click opens an in-app "under construction" note
 
2896
  <div
2897
  className="shell-nav-item shell-nav-assist is-unavailable"
2898
  title={
2899
+ nav.phase === "error"
2900
+ ? navFailureMessage
2901
  : "This list could not be loaded in full. Reload to retry."
2902
  }
2903
  >
 
2917
  />
2918
  )}
2919
 
2920
+ {/* WAVE 55 instruction 2: the first group is complete even when Assistant is absent.
2921
+ Home and Inbox remain real rows, so this boundary is stable rather than permission
2922
+ dependent. */}
2923
+ <div className="shell-nav-sep" role="none" />
2924
+
2925
  {/* β›” THE "AI agent" ROW WAS HERE AND IS DELETED (owner, 2026-08-14): *"AI assistant
2926
  module IS AI agent module. So no need to separate it like that."* Wave 33's own note
2927
  on this row had already argued the collapse and deferred it as ASK C-9 because
 
2945
  Found again at the close-out dead-code sweep, which greps every deleted symbol and
2946
  reads each survivor: this one was a stale CLAIM rather than a live caller. */}
2947
 
2948
+ {/* WAVE 55 instruction 2: Sheet starts the application-building group and remains an
2949
+ unconditional chrome destination. It is followed by Data, Agents and App. The gate
2950
+ reads rendered JSX with comments removed, so this note cannot satisfy the order.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2951
 
2952
  β›” AN `<a>` LIKE CONNECTORS, UNCONDITIONAL, AND BOTH HALVES MATTER. A `<button>` would
2953
  be the Data affordance's shape (it opens a panel over a server-sent list); Sheet is a
 
3019
  <span className="shell-nav-label">Data</span>
3020
  </button>
3021
 
3022
+ {/* Agents stays permission-aware, but its literal position is now after Data. The label
3023
+ still comes from the server registry when present; the unavailable arm names the
3024
+ intended destination without inventing access. */}
3025
+ {automation ? (
3026
+ <a
3027
+ className={
3028
+ "shell-nav-item shell-nav-auto" +
3029
+ (active && active.key === automation.key ? " is-active" : "")
3030
+ }
3031
+ href={automation.href}
3032
+ onClick={expandOnNavClick}
3033
+ onMouseEnter={navCollapsed ? tipEnter(automation.label) : undefined}
3034
+ onMouseLeave={navCollapsed ? tipLeave : undefined}
3035
+ >
3036
+ <AgentIcon />
3037
+ <span className="shell-nav-label">{automation.label}</span>
3038
+ </a>
3039
+ ) : automationSlot === "unavailable" ? (
3040
+ <div
3041
+ className="shell-nav-item shell-nav-auto is-unavailable"
3042
+ title={
3043
+ nav.phase === "error"
3044
+ ? navFailureMessage
3045
+ : "This list could not be loaded in full. Reload to retry."
3046
+ }
3047
+ >
3048
+ <AgentIcon />
3049
+ <span className="shell-nav-label shell-nav-label--muted">Agents</span>
3050
+ <span className="shell-nav-note-dot" aria-hidden="true" />
3051
+ </div>
3052
+ ) : (
3053
+ <div
3054
+ className="shell-nav-item shell-nav-auto is-rail-skeleton"
3055
+ aria-hidden="true"
3056
+ hidden
3057
+ style={{ display: "none" }}
3058
+ />
3059
+ )}
3060
+
3061
+ <a
3062
+ className={"shell-nav-item shell-nav-app" + (route === APP_ROUTE ? " is-active" : "")}
3063
+ href={`#/${APP_ROUTE}`}
3064
+ onClick={expandOnNavClick}
3065
+ onMouseEnter={navCollapsed ? tipEnter("App") : undefined}
3066
+ onMouseLeave={navCollapsed ? tipLeave : undefined}
3067
+ >
3068
+ <AppIcon />
3069
+ <span className="shell-nav-label">App</span>
3070
+ </a>
3071
+
3072
+ <div className="shell-nav-sep" role="none" />
3073
+
3074
  {/* ⭐ WAVE 23 item 10 (R8, contract C11, wiring W23-W3) β€” CONNECTORS.
3075
  ⭐ WAVE 24 item 1 β€” it moved BELOW Database. R8 put it above; the owner's wave-24
3076
  order puts the two destinations that open panels-over-server-data (Database, then
 
3103
  surfaces the server never granted. */}
3104
  {nav.phase === "error" ? (
3105
  <div className="shell-nav-note">
3106
+ {navFailureMessage}
 
 
 
 
 
3107
  </div>
3108
  ) : null}
3109
  {/* β›” W31-T11 β€” A 200 THAT COULD NOT READ THE DATABASES SAYS SO. This is the case that
 
3127
  ) : null}
3128
  </nav>
3129
 
3130
+ {/* ⭐⭐ WAVE 35 Β· T05 (owner item 6) β€” TEMPLATES, DIRECTLY ABOVE THE USER BUTTON.
3131
+ It opens the same Application wizard as Home and App, so the three entry points share
3132
+ one template, database and field-mapping contract.
 
 
3133
  β›” A SIBLING OF `.shell-side-bottom`, NOT A CHILD, and that is behavioural rather than
3134
  cosmetic: that band carries an `onClickCapture` which, while collapsed, swallows the
3135
  click and expands the rail instead (the account POPOVER cannot fit in a 56px strip).
 
3154
  // W53-T33 β€” instruction 6 says "any of the icon". Templates opens an OVERLAY rather
3155
  // than a route, and the rail expanding behind it is what every other row now does.
3156
  expandOnNavClick();
3157
+ openApplicationWizard();
3158
  }}
3159
  onMouseEnter={navCollapsed ? tipEnter("Templates") : undefined}
3160
  onMouseLeave={navCollapsed ? tipLeave : undefined}
 
3333
  </div>
3334
  ) : active ? (
3335
  <StranglerPage entry={active} />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3336
  ) : route === FEEDBACK_ROUTE ? (
3337
  // ⭐⭐ WAVE 35 Β· T06 (owner item 13, R8, contract C6, wiring W2) β€” the three account
3338
  // surfaces. All three take NO props, on purpose and per B's published contract: Usage
 
3493
  // true by construction, and the build door re-checks with the same wall regardless.
3494
  <Lazily surface="Assistant"><AssistantPage granted={entries} /></Lazily>
3495
  ) : nav.phase === "ready" ? (
3496
+ // WAVE 55: Home and App share one tile vocabulary. App is chrome and therefore reaches
3497
+ // this fallback without inventing a granted nav entry; `mode` decides which directory
3498
+ // the surface renders. Home remains the fallback for empty, stale and unknown hashes.
3499
  // ⭐ WAVE 23 item 9 (R7, C10) β€” HOME, AND IT IS THE FALLBACK RATHER THAN A ROUTE MATCH.
3500
  //
3501
  // β›” WHY `!active` AND NOT `route === HOME_ROUTE`. Three states have to land here and
 
3514
  // hero's create door, and its empty line carries the hero's sentence (HomePage's
3515
  // `home-empty`, which branches on `entries.length === 0` for exactly this reason).
3516
  // Booked as a dated amendment in the wave doc, since it moves an R4 surface.
3517
+ <Lazily surface={route === APP_ROUTE ? "App" : "Home"}>
3518
  <HomePage
3519
+ mode={route === APP_ROUTE ? "app" : "home"}
3520
+ initialStarredOnly={window.location.hash.includes("filter=starred")}
3521
  // ⭐ `dbEntries`, NOT `entries` β€” found by LOOKING at it (wave 24 close-out visual
3522
  // pass), which is the only way it could have been found. The Automation SURFACE is a
3523
  // granted nav entry with an href, so `allDatabases` drew it a tile under the heading
 
3531
  folders={navPrefs.folders}
3532
  folderPlacement={navPrefs.placement}
3533
  automations={autoTiles}
3534
+ // Home's Templates card and App's Create new button share this wizard door.
3535
+ onTemplates={openApplicationWizard}
 
 
 
3536
  onNewDatabase={() => openNewDb("blank")}
3537
  /* β›” `onAutomated` LEFT WITH THE CARD IT OPENED (wave 25 item 5a, R8). */
3538
  onConnectors={() => {
 
3548
  view opened from Home and the same view opened from Starred must not behave
3549
  differently, and two copies of "route then ask" is how they would. */
3550
  onOpenView={openViewInDatabase}
3551
+ onOpenQuery={(qid) => {
3552
+ viewEmitCancel.current?.();
3553
+ viewEmitCancel.current = openBuiltView(qid);
3554
+ }}
3555
  />
3556
  </Lazily>
3557
  ) : nav.phase === "error" ? (
 
3563
  // Home above (which welcomes an empty workspace properly), so this is only ever the
3564
  // nav that FAILED, and the nested ternary that used to sort the two is gone.
3565
  <div className="shell-placeholder">
3566
+ <h1>Navigation unavailable</h1>
3567
+ <p>{navFailureMessage}</p>
3568
+ <button
3569
+ className="login-submit shell-retry"
3570
+ type="button"
3571
+ onClick={() => setNavEpoch((epoch) => epoch + 1)}
3572
+ >
3573
+ Try again
3574
+ </button>
3575
  </div>
3576
  ) : (
3577
  // Still asking (`loading`, or the `idle` beat before the effect runs).
 
3586
  {/* The server's own confirmation of a write (X2's `toast`). In standalone
3587
  it is the ONLY feedback for the events whose effect the payload does
3588
  not yet echo back β€” cohort membership, list adds, folder moves. */}
 
 
 
 
 
 
3589
  {assistOpen ? (
3590
+ <ApplicationWizard
3591
+ databases={dataDatabases}
3592
+ panelRef={appWizardRef}
3593
+ onClose={closeApplicationWizard}
3594
+ onBusyChange={setApplicationWizardBusy}
3595
+ onCreated={launchCreatedApplication}
3596
+ />
 
 
 
 
 
 
 
 
 
 
 
 
3597
  ) : null}
3598
 
3599
  {/* Wave 18 (C3-UT): the New-database dialog. Scrim click cancels unless mid-create. */}
web/src/shell/nav.ts CHANGED
@@ -10,10 +10,11 @@
10
  // one end, permission-filtered at the other.
11
  //
12
  // ⚠ THERE IS NO CLIENT-SIDE FALLBACK LIST, deliberately. If `/api/v1/nav`
13
- // fails, the shell renders an honest empty nav β€” never a hard-coded one. A
14
- // fallback would put surfaces on screen that the server never authorised, which
15
- // is precisely the fail-closed rule the wave is built on ("an undeclared
16
- // surface is denied"), and it would mask a broken API as a working one.
 
17
  //
18
  // No `import.meta` here either: `appBase` is a PARAMETER so this module
19
  // compiles and runs under node in `verify_login.py` (see session.ts).
@@ -375,6 +376,27 @@ export const NAV_TIMEOUT_MS = 20_000;
375
  /** Our encoding for "the deadline passed", distinct from 0 (transport) and any HTTP status. */
376
  export const NAV_TIMEOUT_STATUS = -1;
377
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
378
  /**
379
  * `{recents:[…]}` β†’ the list, fail-closed. An entry with no key or an unreadable stamp is
380
  * DROPPED rather than rendered at the epoch, which would file it under "Older" for ever and
@@ -463,10 +485,19 @@ export async function fetchNav(timeoutMs: number = NAV_TIMEOUT_MS): Promise<NavR
463
  const res = deadline ? await Promise.race([call, deadline]) : await call;
464
  if (res === null) return { ok: false, status: NAV_TIMEOUT_STATUS };
465
  if (!res.ok) return { ok: false, status: res.status };
466
- const body = await res.json();
467
- const empty = typeof body?.empty === "string" ? body.empty : undefined;
468
- const omitted = parseKeyList((body as { omitted?: unknown } | null)?.omitted);
469
- const degraded = parseKeyList((body as { degraded?: unknown } | null)?.degraded);
 
 
 
 
 
 
 
 
 
470
  return {
471
  ok: true,
472
  pages: parsePages(body),
@@ -1193,6 +1224,14 @@ export function shapeNav(pages: NavPage[], appBase: string): NavEntry[] {
1193
  // that could would be the hard-coded surface the frame refuses to have.
1194
  export const HOME_ROUTE = "home";
1195
  export const CONNECTORS_ROUTE = "connectors";
 
 
 
 
 
 
 
 
1196
  /**
1197
  * ⭐⭐ WAVE 32 (ruling R7, contract C3) β€” INBOX IS THE THIRD CHROME ROUTE, AND IT PASSES THE LAW
1198
  * ABOVE RATHER THAN BEING EXCEPTED FROM IT.
@@ -1270,9 +1309,9 @@ export const ASSISTANT_ROUTE = "assistant";
1270
  * bug wearing the same screen.
1271
  */
1272
  /**
1273
- * ⭐⭐ WAVE 35 Β· T09 (owner item 8, R4) β€” Starred. Chrome, for the same reason Home is: the page
1274
- * lists only objects the caller's own nav already granted, so it renders nothing the server did not
1275
- * already send. A grant wall here would be a second opinion about a set the server already decided.
1276
  */
1277
  export const STARRED_ROUTE = "starred";
1278
 
@@ -1292,11 +1331,11 @@ export const NO_SUBSCRIPTION_TENANT = "royal-imports";
1292
 
1293
  export const CHROME_ROUTES: ReadonlySet<string> = new Set([
1294
  HOME_ROUTE,
 
1295
  CONNECTORS_ROUTE,
1296
  INBOX_ROUTE,
1297
  QUERY_ROUTE,
1298
  ASSISTANT_ROUTE,
1299
- STARRED_ROUTE,
1300
  FEEDBACK_ROUTE,
1301
  USAGE_ROUTE,
1302
  SUBSCRIPTION_ROUTE,
@@ -1306,9 +1345,10 @@ export const CHROME_ROUTES: ReadonlySet<string> = new Set([
1306
  * ⭐⭐ WAVE 53 Β· T32 (ruling R1) β€” THE SURFACES WHERE THE NAV NEVER FOLDS ITSELF. Owner,
1307
  * instruction 3, verbatim: *"When user first open the app and they're at home. Make sure the
1308
  * navigation is unminimized."* and *"Never collapse on home or starred UNLESS the user click the
1309
- * minmize navigation button of course. Also apply this for inbox module."*
 
1310
  *
1311
- * These three are READING surfaces: Home, Starred and Inbox are lists of places to go, and a rail
1312
  * that folds itself while you are choosing where to go has taken away the very thing the page is
1313
  * for. Every other route is a WORK surface, where the fold buys screen for the work β€” W38-T04's
1314
  * unconditional cell-click fold is untouched there and stays exactly as ruling R9 left it.
@@ -1322,7 +1362,6 @@ export const CHROME_ROUTES: ReadonlySet<string> = new Set([
1322
  */
1323
  export const NAV_STAYS_EXPANDED_ROUTES: ReadonlySet<string> = new Set([
1324
  HOME_ROUTE,
1325
- STARRED_ROUTE,
1326
  INBOX_ROUTE,
1327
  ]);
1328
 
@@ -1345,6 +1384,7 @@ export const NAV_STAYS_EXPANDED_ROUTES: ReadonlySet<string> = new Set([
1345
  */
1346
  export const LEGACY_ROUTES: Readonly<Record<string, string>> = {
1347
  alerts: INBOX_ROUTE,
 
1348
  /**
1349
  * ⭐ 2026-08-14 β€” `#/ai-agent` was a REAL route for one wave (wave 33 shipped it, and the
1350
  * owner's *"remove that AI agent module completely"* retires it). Unlike `alerts` above, this
@@ -1384,6 +1424,7 @@ export const LEGACY_ROUTES: Readonly<Record<string, string>> = {
1384
  */
1385
  export const REWRITTEN_ROUTES: Readonly<Record<string, string>> = {
1386
  [QUERY_ROUTE]: `${ASSISTANT_ROUTE}?mode=query`,
 
1387
  };
1388
 
1389
  /**
 
10
  // one end, permission-filtered at the other.
11
  //
12
  // ⚠ THERE IS NO CLIENT-SIDE FALLBACK LIST, deliberately. If `/api/v1/nav`
13
+ // fails or answers with a malformed envelope, the shell renders a bounded retry
14
+ // state, never a hard-coded list. A fallback would put surfaces on screen that
15
+ // the server never authorised, which is precisely the fail-closed rule the wave
16
+ // is built on ("an undeclared surface is denied"), and it would mask a broken API
17
+ // as a working one.
18
  //
19
  // No `import.meta` here either: `appBase` is a PARAMETER so this module
20
  // compiles and runs under node in `verify_login.py` (see session.ts).
 
376
  /** Our encoding for "the deadline passed", distinct from 0 (transport) and any HTTP status. */
377
  export const NAV_TIMEOUT_STATUS = -1;
378
 
379
+ /** Our encoding for "the server answered, but not with a readable navigation envelope". */
380
+ export const NAV_MALFORMED_STATUS = -2;
381
+
382
+ /**
383
+ * A readable nav envelope has a pages list whose every destination carries a nonblank key and
384
+ * label. Optional decoration on a valid destination may still be pruned by `parsePages`, but a
385
+ * malformed destination cannot disappear into a confident partial rail. An empty list remains
386
+ * valid because a newly provisioned tenant can legitimately have no destinations yet.
387
+ */
388
+ export function isReadableNavEnvelope(body: unknown): boolean {
389
+ if (!body || typeof body !== "object" || Array.isArray(body)) return false;
390
+ const raw = (body as { pages?: unknown }).pages;
391
+ if (!Array.isArray(raw)) return false;
392
+ return raw.every((item) => {
393
+ if (!item || typeof item !== "object" || Array.isArray(item)) return false;
394
+ const page = item as { key?: unknown; label?: unknown };
395
+ return typeof page.key === "string" && !!page.key.trim()
396
+ && typeof page.label === "string" && !!page.label.trim();
397
+ });
398
+ }
399
+
400
  /**
401
  * `{recents:[…]}` β†’ the list, fail-closed. An entry with no key or an unreadable stamp is
402
  * DROPPED rather than rendered at the epoch, which would file it under "Older" for ever and
 
485
  const res = deadline ? await Promise.race([call, deadline]) : await call;
486
  if (res === null) return { ok: false, status: NAV_TIMEOUT_STATUS };
487
  if (!res.ok) return { ok: false, status: res.status };
488
+ let body: unknown;
489
+ try {
490
+ body = await res.json();
491
+ } catch {
492
+ return { ok: false, status: NAV_MALFORMED_STATUS };
493
+ }
494
+ if (!isReadableNavEnvelope(body)) {
495
+ return { ok: false, status: NAV_MALFORMED_STATUS };
496
+ }
497
+ const envelope = body as { empty?: unknown; omitted?: unknown; degraded?: unknown };
498
+ const empty = typeof envelope.empty === "string" ? envelope.empty : undefined;
499
+ const omitted = parseKeyList(envelope.omitted);
500
+ const degraded = parseKeyList(envelope.degraded);
501
  return {
502
  ok: true,
503
  pages: parsePages(body),
 
1224
  // that could would be the hard-coded surface the frame refuses to have.
1225
  export const HOME_ROUTE = "home";
1226
  export const CONNECTORS_ROUTE = "connectors";
1227
+ /**
1228
+ * WAVE 55 / R1-R3: the tenant Application registry has one chrome destination.
1229
+ *
1230
+ * App is a directory over Application definitions already permission-filtered by the server. It
1231
+ * is not a registry module and it does not replace the database Views that pre-date it. Keeping
1232
+ * the route in chrome prevents a tenant's restricted module list from hiding its own Apps.
1233
+ */
1234
+ export const APP_ROUTE = "app";
1235
  /**
1236
  * ⭐⭐ WAVE 32 (ruling R7, contract C3) β€” INBOX IS THE THIRD CHROME ROUTE, AND IT PASSES THE LAW
1237
  * ABOVE RATHER THAN BEING EXCEPTED FROM IT.
 
1309
  * bug wearing the same screen.
1310
  */
1311
  /**
1312
+ * WAVE 55 instruction 2 removes Starred as a module. The old key remains only as a compatibility
1313
+ * address and is rewritten to Home's starred-only filter below. Keeping the key costs no rail row,
1314
+ * preserves bookmarks, and leaves the tenant's durable star flags untouched.
1315
  */
1316
  export const STARRED_ROUTE = "starred";
1317
 
 
1331
 
1332
  export const CHROME_ROUTES: ReadonlySet<string> = new Set([
1333
  HOME_ROUTE,
1334
+ APP_ROUTE,
1335
  CONNECTORS_ROUTE,
1336
  INBOX_ROUTE,
1337
  QUERY_ROUTE,
1338
  ASSISTANT_ROUTE,
 
1339
  FEEDBACK_ROUTE,
1340
  USAGE_ROUTE,
1341
  SUBSCRIPTION_ROUTE,
 
1345
  * ⭐⭐ WAVE 53 Β· T32 (ruling R1) β€” THE SURFACES WHERE THE NAV NEVER FOLDS ITSELF. Owner,
1346
  * instruction 3, verbatim: *"When user first open the app and they're at home. Make sure the
1347
  * navigation is unminimized."* and *"Never collapse on home or starred UNLESS the user click the
1348
+ * minmize navigation button of course. Also apply this for inbox module."* Starred is now a Home
1349
+ * filter, so HOME_ROUTE carries that earlier reading-surface behavior for both Home states.
1350
  *
1351
+ * These two are READING surfaces: Home and Inbox are lists of places to go, and a rail
1352
  * that folds itself while you are choosing where to go has taken away the very thing the page is
1353
  * for. Every other route is a WORK surface, where the fold buys screen for the work β€” W38-T04's
1354
  * unconditional cell-click fold is untouched there and stays exactly as ruling R9 left it.
 
1362
  */
1363
  export const NAV_STAYS_EXPANDED_ROUTES: ReadonlySet<string> = new Set([
1364
  HOME_ROUTE,
 
1365
  INBOX_ROUTE,
1366
  ]);
1367
 
 
1384
  */
1385
  export const LEGACY_ROUTES: Readonly<Record<string, string>> = {
1386
  alerts: INBOX_ROUTE,
1387
+ [STARRED_ROUTE]: HOME_ROUTE,
1388
  /**
1389
  * ⭐ 2026-08-14 β€” `#/ai-agent` was a REAL route for one wave (wave 33 shipped it, and the
1390
  * owner's *"remove that AI agent module completely"* retires it). Unlike `alerts` above, this
 
1424
  */
1425
  export const REWRITTEN_ROUTES: Readonly<Record<string, string>> = {
1426
  [QUERY_ROUTE]: `${ASSISTANT_ROUTE}?mode=query`,
1427
+ [STARRED_ROUTE]: `${HOME_ROUTE}?filter=starred`,
1428
  };
1429
 
1430
  /**
web/src/shell/shareModel.ts CHANGED
@@ -52,6 +52,8 @@ export type ShareRole = (typeof SHARE_ROLES)[number];
52
 
53
  /** The wildcard entry: "everyone who can already open this surface". */
54
  export const EVERYONE = "*";
 
 
55
 
56
  export interface ShareEntry {
57
  user: string;
@@ -176,6 +178,47 @@ export function addablePeople(people: SharePerson[], entries: ShareEntry[]): Sha
176
  return people.filter((p) => !taken.has(p.user));
177
  }
178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  /**
180
  * One sentence naming who can reach this object, for the row that opens the
181
  * editor. Never a count on its own: "3 people" reads as reassurance, and the
 
52
 
53
  /** The wildcard entry: "everyone who can already open this surface". */
54
  export const EVERYONE = "*";
55
+ /** The human-facing choice for the wildcard. Kept beside its stored value so search and status agree. */
56
+ export const EVERYONE_LABEL = "Everyone in this workspace";
57
 
58
  export interface ShareEntry {
59
  user: string;
 
178
  return people.filter((p) => !taken.has(p.user));
179
  }
180
 
181
+ /**
182
+ * Resolve the recipient search only after it names one unshared account exactly.
183
+ *
184
+ * The picker is a search input rather than a select, so a half-typed display name must never be
185
+ * treated as authority to grant access. Usernames, display names and the datalist's combined
186
+ * `name (username)` value are accepted; a duplicated display name remains unresolved until the
187
+ * username disambiguates it. The wildcard follows the same rule and disappears once granted.
188
+ */
189
+ export function resolveShareRecipient(
190
+ people: SharePerson[],
191
+ entries: ShareEntry[],
192
+ query: string,
193
+ ): string | null {
194
+ const wanted = str(query).toLowerCase();
195
+ if (!wanted) return null;
196
+ const taken = new Set(entries.map((entry) => entry.user));
197
+ if (wanted === EVERYONE_LABEL.toLowerCase() && !taken.has(EVERYONE)) return EVERYONE;
198
+ const matches = people.filter((person) => {
199
+ if (taken.has(person.user)) return false;
200
+ const combined = `${person.name} (${person.user})`.toLowerCase();
201
+ return wanted === person.user || wanted === person.name.toLowerCase() || wanted === combined;
202
+ });
203
+ const users = [...new Set(matches.map((person) => person.user))];
204
+ return users.length === 1 ? users[0] : null;
205
+ }
206
+
207
+ /** The current AIOS workspace-access state, in the same vocabulary as the role controls. */
208
+ export function shareAccessStatus(entries: ShareEntry[]): string {
209
+ const everyone = entries.find((entry) => entry.user === EVERYONE);
210
+ if (everyone) {
211
+ return everyone.role === "edit"
212
+ ? "Everyone in this workspace can edit"
213
+ : "Everyone in this workspace can view";
214
+ }
215
+ if (!entries.length) return "Restricted";
216
+ const editors = entries.filter((entry) => entry.role === "edit").length;
217
+ const shared = entries.length === 1 ? "Shared with 1 person" : `Shared with ${entries.length} people`;
218
+ if (!editors) return shared;
219
+ return `${shared}, ${editors} can edit`;
220
+ }
221
+
222
  /**
223
  * One sentence naming who can reach this object, for the row that opens the
224
  * editor. Never a count on its own: "3 people" reads as reassurance, and the
web/src/shell/useApplicationWizardOverlay.ts ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { RefObject } from "react";
2
+
3
+ import { useOverlayLayer } from "../customer-grid/OverlaySurface";
4
+
5
+ /** The Application wizard's modal interaction contract, kept out of the shell frame itself. */
6
+ export function useApplicationWizardOverlay(
7
+ panelRef: RefObject<HTMLDivElement>,
8
+ onDismiss: () => void,
9
+ ): void {
10
+ useOverlayLayer({
11
+ panelRef,
12
+ onDismiss,
13
+ dismissOnOutside: false,
14
+ initialFocus: ".app-wizard-close",
15
+ restoreFocus: true,
16
+ trapFocus: true,
17
+ });
18
+ }
web/src/starred/StarredPage.tsx CHANGED
@@ -1,5 +1,5 @@
1
  // ---------------------------------------------------------------------------
2
- // starred/StarredPage.tsx β€” WAVE 35 Β· W35-T14 (owner item 8, ruling R4, C2).
3
  //
4
  // Owner item 8, verbatim: *"Let's add a button under 'Home' called 'Starred' …
5
  // only for Database/Agents/Queries/Marked important that the user has marked."*
@@ -21,18 +21,13 @@
21
  // β›” THE STAR LIST IS NOT A PERMISSION β€” `starredApi.shapeStarred` drops every
22
  // starred object that is not in `entries`, the server-filtered nav. A star
23
  // outlives its subject, and the shell's oldest law ("an undeclared surface is
24
- // denied") is what makes `#/starred` a legal chrome route at all: this page can
25
- // name nothing `GET /nav` did not send.
26
  //
27
- // β›” THE READ HAPPENS AFTER PAINT, AND THAT IS A MEASUREMENT, NOT A STYLE CHOICE.
28
- // `GET /starred` scans a view bucket per database because C2 forbids a second
29
- // store for the flag: 6.2 ms warm, **7,331 ms cold** on tenant #0 (mailbox E-2).
30
- // `useEffect` (never `useLayoutEffect`) is what keeps it off the paint path.
31
  // ---------------------------------------------------------------------------
32
 
33
- import { useEffect, useState } from "react";
34
- import { API_V1, CREDENTIALS } from "../apiContract";
35
-
36
  import { FolderMark } from "../customer-grid/icons";
37
  import { AGENTS_MODULE_LABEL } from "../inbox/inboxModel";
38
  import { Mark } from "../shell/Brand";
@@ -45,7 +40,6 @@ import {
45
  EMPTY_STARRED,
46
  shapeStarred,
47
  starredCount,
48
- useStarred,
49
  viewCount,
50
  viewCountKey,
51
  } from "./starredApi";
@@ -60,10 +54,8 @@ import type {
60
  } from "./starredApi";
61
  import "./starred.css";
62
 
63
- /** A magnifier: Query's own mark since the AI surfaces split, drawn in the rail's 16px stroke
64
- * vocabulary. Local to this file, which is this tree's established pattern for a glyph with one
65
- * caller (Home draws its own four; the alerts pane draws its own bell). */
66
- function QueryIcon() {
67
  return (
68
  <svg className="st-chip-glyph" viewBox="0 0 16 16" aria-hidden="true">
69
  <circle cx="7.1" cy="7.1" r="4.2" />
@@ -485,34 +477,3 @@ export function StarredSurface({
485
  </div>
486
  );
487
  }
488
-
489
- /**
490
- * The page the frame mounts at `#/starred`: the read, and the two pieces of state that go with it.
491
- *
492
- * Everything it holds is its own (which list arrived, which tab is selected). Nothing here is a
493
- * fact about the workspace that the frame already knows, which is why `entries` and `automations`
494
- * arrive as props rather than being fetched a second time.
495
- */
496
- export default function StarredPage(props: StarredProps) {
497
- // ⭐ THE SAME HOOK HOME USES, so the two surfaces cannot end up with different ideas about what
498
- // is starred or about what happens when a write is refused. Everything about the read (the
499
- // after-paint timing, the generation counter, the revert-and-say-so on a refusal) lives there.
500
- const { load, busy, counts, toggle, reload } = useStarred();
501
- const [filter, setFilter] = useState<Filter>("all");
502
- const [applications, setApplications] = useState<Array<{ id: string; name: string; type: string; openTarget?: { database?: string } }>>([]);
503
- useEffect(() => { const controller = new AbortController(); void fetch(`${API_V1}/applications?starred=true`, { credentials: CREDENTIALS, signal: controller.signal }).then(async (response) => response.ok ? response.json() : { applications: [] }).then((body) => { if (!controller.signal.aborted) setApplications(Array.isArray(body?.applications) ? body.applications : []); }).catch(() => undefined); return () => controller.abort(); }, []);
504
-
505
- return (
506
- <StarredSurface
507
- {...props}
508
- load={load}
509
- filter={filter}
510
- onFilter={setFilter}
511
- onRetry={reload}
512
- busy={busy}
513
- counts={counts}
514
- onUnstar={(kind, id, database) => toggle(kind, id, false, database)}
515
- applications={applications}
516
- />
517
- );
518
- }
 
1
  // ---------------------------------------------------------------------------
2
+ // starred/StarredPage.tsx β€” shared starred tile controls and the retained visual fixture.
3
  //
4
  // Owner item 8, verbatim: *"Let's add a button under 'Home' called 'Starred' …
5
  // only for Database/Agents/Queries/Marked important that the user has marked."*
 
21
  // β›” THE STAR LIST IS NOT A PERMISSION β€” `starredApi.shapeStarred` drops every
22
  // starred object that is not in `entries`, the server-filtered nav. A star
23
  // outlives its subject, and the shell's oldest law ("an undeclared surface is
24
+ // denied") means every consumer can name only what `GET /nav` sent. Wave 55
25
+ // retires the standalone route and mounts the starred-only filter on Home.
26
  //
27
+ // The live read now belongs to Home's `useStarred` hook. This file keeps the
28
+ // shared Tile and StarButton vocabulary plus the static fixture surface.
 
 
29
  // ---------------------------------------------------------------------------
30
 
 
 
 
31
  import { FolderMark } from "../customer-grid/icons";
32
  import { AGENTS_MODULE_LABEL } from "../inbox/inboxModel";
33
  import { Mark } from "../shell/Brand";
 
40
  EMPTY_STARRED,
41
  shapeStarred,
42
  starredCount,
 
43
  viewCount,
44
  viewCountKey,
45
  } from "./starredApi";
 
54
  } from "./starredApi";
55
  import "./starred.css";
56
 
57
+ /** A magnifier shared by the retained fixture and Home's starred-query results. */
58
+ export function QueryIcon() {
 
 
59
  return (
60
  <svg className="st-chip-glyph" viewBox="0 0 16 16" aria-hidden="true">
61
  <circle cx="7.1" cy="7.1" r="4.2" />
 
477
  </div>
478
  );
479
  }