fsanyoto commited on
Commit
b80130d
·
verified ·
1 Parent(s): 0d60127

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 +2 -441
  2. VERSION +1 -1
  3. api/routes_automation.py +101 -10
  4. api/routes_external.py +115 -5
  5. api/routes_module_index.py +9 -4
  6. api/routes_odoo_tables.py +52 -15
  7. api/routes_query.py +1 -0
  8. api/routes_sheet.py +195 -61
  9. api/routes_starred.py +27 -3
  10. platform/core/external_access.py +69 -7
  11. platform/core/relations.py +14 -0
  12. platform/core/sheet_structure.py +51 -17
  13. platform/core/sheets.py +164 -39
  14. platform/core/user_tables.py +14 -1
  15. web/package-lock.json +18 -0
  16. web/package-lock.linux.sha256 +2 -2
  17. web/package.json +2 -0
  18. web/src/assistant/AssistantPage.tsx +82 -41
  19. web/src/customer-grid/MapView.tsx +27 -8
  20. web/src/customer-grid/RecordDetail.tsx +16 -5
  21. web/src/customer-grid/Toolbar.tsx +29 -18
  22. web/src/customer-grid/ViewSidebar.tsx +62 -65
  23. web/src/customer-grid/apiBridge.ts +181 -1
  24. web/src/customer-grid/mapProjection.ts +17 -3
  25. web/src/customer-grid/pipelineWorker.ts +155 -0
  26. web/src/home/FolderNameDialog.tsx +65 -0
  27. web/src/home/HomePage.tsx +147 -69
  28. web/src/index.css +195 -9
  29. web/src/settings/ExternalAccessPane.tsx +121 -12
  30. web/src/settings/SettingsModal.tsx +2 -2
  31. web/src/sheet/BindingEditor.tsx +157 -33
  32. web/src/sheet/DrillModal.tsx +88 -4
  33. web/src/sheet/Ribbon.tsx +8 -42
  34. web/src/sheet/SheetGrid.tsx +817 -145
  35. web/src/sheet/SheetPage.tsx +82 -14
  36. web/src/sheet/SheetRail.tsx +45 -38
  37. web/src/sheet/SheetViewLayer.tsx +266 -0
  38. web/src/sheet/a1.ts +47 -17
  39. web/src/sheet/ribbonData.tsx +22 -22
  40. web/src/sheet/ribbonFormulas.tsx +10 -10
  41. web/src/sheet/ribbonHome.tsx +76 -76
  42. web/src/sheet/ribbonInsert.tsx +13 -13
  43. web/src/sheet/ribbonView.tsx +13 -28
  44. web/src/sheet/sheetState.ts +102 -12
  45. web/src/sheet/types.ts +59 -2
  46. web/src/sheet/viewPlacement.ts +319 -0
  47. web/src/shell/Shell.tsx +14 -9
  48. web/src/shell/nav.ts +33 -2
  49. web/src/shell/navExtras.css +1 -1
  50. web/src/styles/wave55/sheet.css +0 -5
RELEASES.json CHANGED
@@ -1,443 +1,4 @@
1
  {
2
- "current": "0576185",
3
- "releases": [
4
- {
5
- "version": "v74",
6
- "sha": "40dceba",
7
- "date": "2026-09-14",
8
- "subject": "release v74: waves 58+59 incl. the Amazon credential door (W59-T21/22/23) and sync producer (W59-T42); hotfix promote so"
9
- },
10
- {
11
- "version": "v73",
12
- "sha": "bb94de5",
13
- "date": "2026-09-13",
14
- "subject": "release v73"
15
- },
16
- {
17
- "version": "v71",
18
- "sha": "96143dc",
19
- "date": "2026-09-04",
20
- "subject": "release v71 - wave 51, QA'd 24 PASS / 6 FAIL / 5 UNPROVEN"
21
- },
22
- {
23
- "version": "v70",
24
- "sha": "eedfb6a",
25
- "date": "2026-09-03",
26
- "subject": "release v70 - wave 50 (grid analytics, the Sheet as a spreadsheet, view trash and audit)"
27
- },
28
- {
29
- "version": "v69",
30
- "sha": "8598f56",
31
- "date": "2026-09-02",
32
- "subject": "release v69: wave48-continuation validated + hotfixes v67/v68/d4e3e31 + go-live QA repairs (Supplier option limit, optio"
33
- },
34
- {
35
- "version": "v68",
36
- "sha": "62b065a",
37
- "date": "2026-09-01",
38
- "subject": "release v68: unified holiday date offsets"
39
- },
40
- {
41
- "version": "v67",
42
- "sha": "3b22419",
43
- "date": "2026-09-01",
44
- "subject": "release v67"
45
- },
46
- {
47
- "version": "v66",
48
- "sha": "73c94f0",
49
- "date": "2026-08-31",
50
- "subject": "release v66"
51
- },
52
- {
53
- "version": "v65",
54
- "sha": "9f6cfed",
55
- "date": "2026-08-31",
56
- "subject": "release v65"
57
- },
58
- {
59
- "version": "v64",
60
- "sha": "bb8985c",
61
- "date": "2026-08-31",
62
- "subject": "release v64"
63
- },
64
- {
65
- "version": "v63",
66
- "sha": "ec75cb8",
67
- "date": "2026-08-31",
68
- "subject": "release v63"
69
- },
70
- {
71
- "version": "v62",
72
- "sha": "2c8f702",
73
- "date": "2026-08-31",
74
- "subject": "release v62"
75
- },
76
- {
77
- "version": "v61",
78
- "sha": "bbc4c07",
79
- "date": "2026-08-30",
80
- "subject": "v61 - wave 46 hotfix: D-590 schema overlay reaches the grid read (all three assemblies), D-599 route to zone association"
81
- },
82
- {
83
- "version": "v60",
84
- "sha": "dd1b062",
85
- "date": "2026-08-30",
86
- "subject": "v60 - wave 46"
87
- },
88
- {
89
- "version": "v59",
90
- "sha": "3cb73ce",
91
- "date": "2026-08-29",
92
- "subject": "release v59"
93
- },
94
- {
95
- "version": "v58",
96
- "sha": "c526ced",
97
- "date": "2026-08-29",
98
- "subject": "release v58"
99
- },
100
- {
101
- "version": "v57",
102
- "sha": "4859c03",
103
- "date": "2026-08-29",
104
- "subject": "release v57"
105
- },
106
- {
107
- "version": "v56",
108
- "sha": "2970b72",
109
- "date": "2026-08-28",
110
- "subject": "release v56"
111
- },
112
- {
113
- "version": "v55",
114
- "sha": "b766b90",
115
- "date": "2026-08-28",
116
- "subject": "release v55"
117
- },
118
- {
119
- "version": "v54",
120
- "sha": "6a8e99a",
121
- "date": "2026-08-27",
122
- "subject": "release v54"
123
- },
124
- {
125
- "version": "v53",
126
- "sha": "89ed2cb",
127
- "date": "2026-08-24",
128
- "subject": "release v53"
129
- },
130
- {
131
- "version": "v52",
132
- "sha": "8263493",
133
- "date": "2026-08-23",
134
- "subject": "release v52"
135
- },
136
- {
137
- "version": "v51",
138
- "sha": "5740d20",
139
- "date": "2026-08-23",
140
- "subject": "release v51"
141
- },
142
- {
143
- "version": "v50",
144
- "sha": "8027c83",
145
- "date": "2026-08-23",
146
- "subject": "release v50"
147
- },
148
- {
149
- "version": "v49",
150
- "sha": "9a14c01",
151
- "date": "2026-08-23",
152
- "subject": "release v49"
153
- },
154
- {
155
- "version": "v48",
156
- "sha": "3c69fd9",
157
- "date": "2026-08-23",
158
- "subject": "release v48"
159
- },
160
- {
161
- "version": "v47",
162
- "sha": "917f9a0",
163
- "date": "2026-08-23",
164
- "subject": "release v47"
165
- },
166
- {
167
- "version": "v46",
168
- "sha": "a8dc531",
169
- "date": "2026-08-23",
170
- "subject": "release v46"
171
- },
172
- {
173
- "version": "v45",
174
- "sha": "0b2b501",
175
- "date": "2026-08-23",
176
- "subject": "release v45"
177
- },
178
- {
179
- "version": "v44",
180
- "sha": "a7877aa",
181
- "date": "2026-08-23",
182
- "subject": "Hotfix: allow renaming the active Map view"
183
- },
184
- {
185
- "version": "v43",
186
- "sha": "e2ba461",
187
- "date": "2026-08-23",
188
- "subject": "release v43"
189
- },
190
- {
191
- "version": "v42",
192
- "sha": "25b885e",
193
- "date": "2026-08-23",
194
- "subject": "release v42"
195
- },
196
- {
197
- "version": "v41",
198
- "sha": "1d6adcc",
199
- "date": "2026-08-22",
200
- "subject": "v41 vertical route navigation"
201
- },
202
- {
203
- "version": "v40",
204
- "sha": "1451837",
205
- "date": "2026-08-22",
206
- "subject": "release v40 route UI correction"
207
- },
208
- {
209
- "version": "v39",
210
- "sha": "a78bdf0",
211
- "date": "2026-08-21",
212
- "subject": "W39 clean stale migration targets"
213
- },
214
- {
215
- "version": "v38",
216
- "sha": "a556631",
217
- "date": "2026-08-21",
218
- "subject": "W39 reversible Live store cutover"
219
- },
220
- {
221
- "version": "v37",
222
- "sha": "1ddd8cf",
223
- "date": "2026-08-21",
224
- "subject": "W39: coalesce derived workspace reads"
225
- },
226
- {
227
- "version": "v36",
228
- "sha": "51db3b7",
229
- "date": "2026-08-21",
230
- "subject": "W39 share-field oid repair"
231
- },
232
- {
233
- "version": "v35",
234
- "sha": "0f64212",
235
- "date": "2026-08-21",
236
- "subject": "W39 visual QA fixture"
237
- },
238
- {
239
- "version": "v34",
240
- "sha": "cb4caa1",
241
- "date": "2026-08-21",
242
- "subject": "W39 Staging PostgreSQL egress controls"
243
- },
244
- {
245
- "version": "v33",
246
- "sha": "2b115e5",
247
- "date": "2026-08-21",
248
- "subject": "W39: stop nonproduction Postgres background egress"
249
- },
250
- {
251
- "version": "v32",
252
- "sha": "b47b27c",
253
- "date": "2026-08-21",
254
- "subject": "W39: repair Staging Postgres projection"
255
- },
256
- {
257
- "version": "v31",
258
- "sha": "8880a49",
259
- "date": "2026-08-21",
260
- "subject": "v31: Wave 39 staging candidate"
261
- },
262
- {
263
- "version": "v30",
264
- "sha": "71776ca",
265
- "date": "2026-08-20",
266
- "subject": "v30: W39-T29 Member-owned View first-share hotfix"
267
- },
268
- {
269
- "version": "v29",
270
- "sha": "55ced50",
271
- "date": "2026-08-18",
272
- "subject": "v29: the build staging has been running since 2026-08-18 (55ced50)."
273
- },
274
- {
275
- "version": "v28",
276
- "sha": "2793e4b",
277
- "date": "2026-08-18",
278
- "subject": "release v28"
279
- },
280
- {
281
- "version": "v27",
282
- "sha": "c05a794",
283
- "date": "2026-08-18",
284
- "subject": "release v27"
285
- },
286
- {
287
- "version": "v25",
288
- "sha": "bc24829",
289
- "date": "2026-08-14",
290
- "subject": "v25 - wave 32's LIVE build (deployed 2026-08-13, bc24829)"
291
- },
292
- {
293
- "version": "v26",
294
- "sha": "6a642e1",
295
- "date": "2026-08-14",
296
- "subject": "v26 - wave 33's build (deployed 2026-08-14, 6a642e1)"
297
- },
298
- {
299
- "version": "v24",
300
- "sha": "514d829",
301
- "date": "2026-08-09",
302
- "subject": "release v24"
303
- },
304
- {
305
- "version": "v23",
306
- "sha": "44cc283",
307
- "date": "2026-08-09",
308
- "subject": "release v23"
309
- },
310
- {
311
- "version": "v22",
312
- "sha": "f14e199",
313
- "date": "2026-08-09",
314
- "subject": "release v22"
315
- },
316
- {
317
- "version": "v21",
318
- "sha": "5fdffce",
319
- "date": "2026-08-09",
320
- "subject": "release v21"
321
- },
322
- {
323
- "version": "v20",
324
- "sha": "442e4a1",
325
- "date": "2026-08-09",
326
- "subject": "release v20"
327
- },
328
- {
329
- "version": "v19",
330
- "sha": "94cb4a4",
331
- "date": "2026-08-09",
332
- "subject": "release v19"
333
- },
334
- {
335
- "version": "v18",
336
- "sha": "0106ef9",
337
- "date": "2026-08-09",
338
- "subject": "release v18"
339
- },
340
- {
341
- "version": "v17",
342
- "sha": "308240c",
343
- "date": "2026-08-09",
344
- "subject": "release v17"
345
- },
346
- {
347
- "version": "v16",
348
- "sha": "a804df5",
349
- "date": "2026-08-09",
350
- "subject": "release v16"
351
- },
352
- {
353
- "version": "v15",
354
- "sha": "6b84d72",
355
- "date": "2026-08-09",
356
- "subject": "release v15"
357
- },
358
- {
359
- "version": "v14",
360
- "sha": "bee5eaf",
361
- "date": "2026-08-07",
362
- "subject": "release v14"
363
- },
364
- {
365
- "version": "v13",
366
- "sha": "314c0e3",
367
- "date": "2026-08-06",
368
- "subject": "release v13"
369
- },
370
- {
371
- "version": "v12",
372
- "sha": "4908f39",
373
- "date": "2026-08-06",
374
- "subject": "release v12"
375
- },
376
- {
377
- "version": "v11",
378
- "sha": "3126617",
379
- "date": "2026-08-05",
380
- "subject": "release v11"
381
- },
382
- {
383
- "version": "v10",
384
- "sha": "43f8042",
385
- "date": "2026-08-05",
386
- "subject": "release v10"
387
- },
388
- {
389
- "version": "v9",
390
- "sha": "2e26f57",
391
- "date": "2026-08-05",
392
- "subject": "release v9"
393
- },
394
- {
395
- "version": "v8",
396
- "sha": "8073b3e",
397
- "date": "2026-08-05",
398
- "subject": "release v8"
399
- },
400
- {
401
- "version": "v7",
402
- "sha": "b1c5a7e",
403
- "date": "2026-08-05",
404
- "subject": "release v7"
405
- },
406
- {
407
- "version": "v6",
408
- "sha": "a344020",
409
- "date": "2026-08-05",
410
- "subject": "release v6"
411
- },
412
- {
413
- "version": "v5",
414
- "sha": "c0b0fbb",
415
- "date": "2026-08-05",
416
- "subject": "release v5"
417
- },
418
- {
419
- "version": "v4",
420
- "sha": "de5037f",
421
- "date": "2026-08-05",
422
- "subject": "release v4"
423
- },
424
- {
425
- "version": "v3",
426
- "sha": "6b9fa62",
427
- "date": "2026-08-05",
428
- "subject": "release v3"
429
- },
430
- {
431
- "version": "v2",
432
- "sha": "fd05861",
433
- "date": "2026-08-04",
434
- "subject": "release v2"
435
- },
436
- {
437
- "version": "v1",
438
- "sha": "5b4e2c4",
439
- "date": "2026-08-04",
440
- "subject": "release v1"
441
- }
442
- ]
443
  }
 
1
  {
2
+ "current": "83594e0",
3
+ "releases": []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- 0576185
 
1
+ 83594e0
api/routes_automation.py CHANGED
@@ -126,10 +126,27 @@ def _voice_options(session):
126
  tables.append(option)
127
  except Exception: # noqa: BLE001 - permission/absence.
128
  pass
129
- # User tables are permissioned by their own object wall inside automation_tables().
130
- for table in automation_tables(session).get("tables") or []:
131
- option = _voice_option(table.get("key"), table.get("label") or table.get("key"),
132
- table.get("fields"), table.get("views"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  if option:
134
  tables.append(option)
135
  return {"tables": tables}
@@ -210,8 +227,23 @@ def _voice_view_input(session, audience):
210
 
211
  @router.get("/voice-agents")
212
  def list_voice_agents(session: Session = Depends(_GATE)):
213
- options = _voice_options(session)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  rows = voice.list_browser_dtos(session.runtime)
 
215
  for row in rows:
216
  row["audienceOptions"] = options
217
  return {"voiceAgents": rows}
@@ -1081,6 +1113,49 @@ def _discover_default(session, tables):
1081
  lambda: engine.discover_default_table(session.runtime))
1082
 
1083
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1084
  def warm_default(rt):
1085
  """⭐⭐ WAVE 30 · T12, THE COLD HALF. Elect the discovery picker's default at BOOT.
1086
 
@@ -1396,7 +1471,22 @@ def _table_views(session, key):
1396
 
1397
  @router.get("/automations/tables")
1398
  def automation_tables(session: Session = Depends(_GATE)):
1399
- """The blank databases an automation can target, with their fields.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1400
 
1401
  ⚠ A READ-ONLY MIRROR of C3-UT's `GET /api/v1/tables`, under this router's own prefix so the
1402
  two can never collide. It exists because the automation editor needs the table+field list to
@@ -1442,11 +1532,12 @@ def automation_tables(session: Session = Depends(_GATE)):
1442
  "type": f.get("type") or "text",
1443
  "automation": f.get("automation") or None}
1444
  for f in (t.get("fields") or [])]}
1445
- views = _table_views(session, key)
1446
- if views is not None:
1447
- row["views"] = views # absent when the bucket did not answer — never []
 
1448
  out.append(row)
1449
- return {"tables": out}
1450
 
1451
 
1452
  @router.get("/automations/presets")
 
126
  tables.append(option)
127
  except Exception: # noqa: BLE001 - permission/absence.
128
  pass
129
+ # User tables are permissioned by their own object wall inside _automation_table_rows().
130
+ #
131
+ # ⭐⭐ W62-T17 — THE VIEW LIST IS BOUGHT PER DATABASE AND `_voice_option` THROWS MOST OF IT
132
+ # AWAY. That helper returns None unless a database has BOTH a phone-type field AND a saved
133
+ # View, so a database with no phone field is dropped whatever its Views say — and resolving
134
+ # them cost a `shares.grants` read plus a whole workspace-document read EACH. MEASURED on
135
+ # staging: `_table_views` x24 = 6,810 ms of this pass
136
+ # (`AutoWiki/waves/wave62/proto/T17-profile.md`). The phone test is free (the field list is
137
+ # already in hand), so it is asked FIRST and the view read is spent only where it can matter.
138
+ #
139
+ # ⚠ THE ANSWER IS IDENTICAL, not merely similar: the skipped databases are exactly the ones
140
+ # `_voice_option` returned None for, and `_table_views` is still the single source of the
141
+ # view list for every database that survives — ABSENT (None) still reads as "nobody looked"
142
+ # and still drops the option, exactly as it did when the list rode on the row.
143
+ for table in _automation_table_rows(session, with_views=False):
144
+ if not any(isinstance(field, dict) and field.get("key") and field.get("type") == "phone"
145
+ for field in (table.get("fields") or [])):
146
+ continue
147
+ key = table.get("key")
148
+ option = _voice_option(key, table.get("label") or key,
149
+ table.get("fields"), _table_views(session, key))
150
  if option:
151
  tables.append(option)
152
  return {"tables": tables}
 
227
 
228
  @router.get("/voice-agents")
229
  def list_voice_agents(session: Session = Depends(_GATE)):
230
+ """Every voice agent, each carrying the audience choices its editor offers.
231
+
232
+ ⭐⭐ W62-T17 (R12, D-739) — **THE OPTIONS ARE RESOLVED ONLY IF A ROW WILL CARRY THEM**, and on
233
+ the store that produced this ticket that is the whole fix. `_voice_options` is the most
234
+ expensive read pass in this file (MEASURED at 14,705 ms of this route's 14,748 ms on staging's
235
+ Royal Imports, `AutoWiki/waves/wave62/proto/T17-profile.md`), and Royal Imports has NO voice
236
+ agents, so every one of those seconds was assembled and then thrown away with the empty list.
237
+ The payload is unchanged by construction: with no rows the loop below never ran, so the
238
+ options never reached a caller.
239
+
240
+ ⛔ THE ORDER IS THE FIX, not a tidy-up — read the rows first, then decide. Reinstating the
241
+ eager call "because it is simpler" restores a 14 second answer to an 18 byte payload. This is
242
+ the same shape this file already carries twice (W29-T01 and W30-T12, both on `list_automations`
243
+ below): work whose result is discarded is still paid for.
244
+ """
245
  rows = voice.list_browser_dtos(session.runtime)
246
+ options = _voice_options(session) if rows else None
247
  for row in rows:
248
  row["audienceOptions"] = options
249
  return {"voiceAgents": rows}
 
1113
  lambda: engine.discover_default_table(session.runtime))
1114
 
1115
 
1116
+ def automation_ids(session):
1117
+ """Every automation id `GET /automations` would list, WITHOUT wiring a single DTO.
1118
+
1119
+ ⭐⭐ W62-T17 — THE ID-ONLY ACCESSOR `routes_module_index._readable_ids` ASKED FOR IN WRITING:
1120
+ *"all_definitions omits synthetic field/Odoo agents. Keep the complete automation list until it
1121
+ has an id-only accessor."* That route needs the id SET and nothing else — it uses it to drop a
1122
+ folder placement whose item the caller cannot read — and it was building the whole Agents rail
1123
+ payload to get it. MEASURED on staging: `GET /api/v1/module-index/agents` spent 1,101 ms of its
1124
+ 1,180 ms inside `list_automations`, whose `_wire` reads `agent_contracts` and
1125
+ `automation_agent_actions` once PER AUTOMATION (`AutoWiki/waves/wave62/proto/T17-profile.md`).
1126
+
1127
+ ⛔⛔ THE SET MUST BE `list_automations`' SET EXACTLY, BECAUSE IT IS A WALL. An id this omits is
1128
+ a tile that silently stops rendering — the worst failure shape on a folder home, because the
1129
+ placement is still stored and the page simply looks emptier. So all three strata stay: the
1130
+ stored definitions, the synthetic field agents (C3), and the derived Odoo sync row (C4). Add a
1131
+ stratum to `list_automations` and it belongs here in the same commit.
1132
+
1133
+ ⛔ AND THE STATEMENTS SEED STAYS, for a reason that is not obvious: `seed_statements_agent`
1134
+ MINTS a row that `all_definitions` then lists (W35-T37 / R10), once per tenant per process. If
1135
+ only `list_automations` seeded it, this set would depend on WHICH ROUTE the process happened to
1136
+ serve first — the Agents home would hide the statements agent's placement until somebody
1137
+ opened the rail. Same guard, same idempotency key, same never-take-the-rail-down posture.
1138
+
1139
+ ⚠ WHAT IT DELIBERATELY DOES NOT DO is the board-retirement scan. That is hygiene over stored
1140
+ state (`all_definitions` strips retired board state on every read anyway), it changes no id,
1141
+ and `list_automations` still runs it on its own first call per tenant.
1142
+ """
1143
+ if session.tenant not in _STATEMENTS_SEEDED:
1144
+ try:
1145
+ engine.seed_statements_agent(session.runtime, username=session.uname or "system")
1146
+ except Exception: # noqa: BLE001
1147
+ pass
1148
+ _STATEMENTS_SEEDED.add(session.tenant)
1149
+ ids = {str(defn.get("id")) for defn in engine.all_definitions(session.runtime).values()
1150
+ if isinstance(defn, dict) and defn.get("id")}
1151
+ ids |= {str(row.get("id")) for row in _field_agent_rows(session)
1152
+ if isinstance(row, dict) and row.get("id")}
1153
+ odoo = _odoo_sync_row(session)
1154
+ if isinstance(odoo, dict) and odoo.get("id"):
1155
+ ids.add(str(odoo["id"]))
1156
+ return ids
1157
+
1158
+
1159
  def warm_default(rt):
1160
  """⭐⭐ WAVE 30 · T12, THE COLD HALF. Elect the discovery picker's default at BOOT.
1161
 
 
1471
 
1472
  @router.get("/automations/tables")
1473
  def automation_tables(session: Session = Depends(_GATE)):
1474
+ """The blank databases an automation can target, with their fields. See the helper below."""
1475
+ return {"tables": _automation_table_rows(session)}
1476
+
1477
+
1478
+ def _automation_table_rows(session, with_views=True):
1479
+ """The blank databases an automation can target, with their fields — the rows behind
1480
+ `GET /automations/tables`, as a plain list.
1481
+
1482
+ ⭐⭐ W62-T17 — SPLIT OUT OF THE ROUTE SO ONE IN-PROCESS CALLER CAN DECLINE THE EXPENSIVE HALF.
1483
+ The route's payload is unchanged (`with_views=True` is the default and the route passes
1484
+ nothing else); `_voice_options` above is the caller that asks for `with_views=False`, because
1485
+ it filters on phone fields first and most databases never reach the view list at all. See that
1486
+ call site for the measurement.
1487
+
1488
+ ⛔ A PLAIN FUNCTION, NOT A SECOND ROUTE. The wall, the C8 migration and the lent document all
1489
+ stay exactly where they were; only the `views` read became optional.
1490
 
1491
  ⚠ A READ-ONLY MIRROR of C3-UT's `GET /api/v1/tables`, under this router's own prefix so the
1492
  two can never collide. It exists because the automation editor needs the table+field list to
 
1532
  "type": f.get("type") or "text",
1533
  "automation": f.get("automation") or None}
1534
  for f in (t.get("fields") or [])]}
1535
+ if with_views:
1536
+ views = _table_views(session, key)
1537
+ if views is not None:
1538
+ row["views"] = views # absent when the bucket did not answer — never []
1539
  out.append(row)
1540
+ return out
1541
 
1542
 
1543
  @router.get("/automations/presets")
api/routes_external.py CHANGED
@@ -1,5 +1,6 @@
1
  """Per-user credentials, governed reads and explicitly allowed bearer build tools."""
2
 
 
3
  import json
4
  import uuid
5
  from urllib.parse import quote
@@ -17,6 +18,53 @@ router = APIRouter(prefix="/api/v1/external", tags=["external"])
17
  _CREDENTIAL_PREFIX = "lpb1."
18
 
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  def _auth_refusal():
21
  raise err(401, external_access.AUTH_ERROR, "The credential is invalid or revoked.")
22
 
@@ -42,6 +90,10 @@ def require_external_session(
42
  "u": verified.user["username"],
43
  "external": True,
44
  "external_key_id": verified.key_id,
 
 
 
 
45
  },
46
  runtime=verified.runtime,
47
  )
@@ -66,13 +118,17 @@ def _can_use_analyst(session: Session) -> bool:
66
 
67
 
68
  def _management_refusal(exc: external_access.ExternalAccessError):
 
 
 
 
69
  if exc.code == "external_label_invalid":
70
  raise err(400, exc.code, "Enter a label between 1 and 80 characters.")
71
  if exc.code == "external_key_not_found":
72
  raise err(404, exc.code, "That credential was not found.")
73
  if exc.code in {"external_identity_invalid", "external_account_unavailable"}:
74
  raise err(409, exc.code, "This account cannot create an external credential.")
75
- raise err(503, "external_access_unavailable", "External access is unavailable right now.")
76
 
77
 
78
  def _resolve_external_scope(
@@ -130,6 +186,8 @@ def _resolve_external_scope(
130
  else:
131
  row["label"] = fallback_label(database)
132
  row["fields"] = []
 
 
133
  resolved.append(row)
134
  return resolved
135
 
@@ -326,7 +384,9 @@ def _portable_skill_document(session: Session, base_url: str) -> str:
326
  "## Limits",
327
  "",
328
  ("This surface writes only through the named tools, as the key's maker with the maker's "
329
- "own grants. Workbook roles and database restrictions still apply. It returns no data "
 
 
330
  "the maker cannot already see in Loopable. Sheet cell history records the maker and "
331
  "key label. Saved Views and Apps keep the UI's username attribution; their writers "
332
  "have no author display-name field. No tool writes to Odoo."),
@@ -343,8 +403,11 @@ def create_key(body=Body(default=None), session: Session = Depends(require_sessi
343
  """Mint a credential for the signed-in human. Bearer auth is not accepted here."""
344
  session.require("analyst")
345
  label = body.get("label") if isinstance(body, dict) else None
 
 
346
  try:
347
- key, token = external_access.mint(session.runtime, session.uname, session.tenant, label)
 
348
  except external_access.ExternalAccessError as exc:
349
  _management_refusal(exc)
350
  return {"key": key, "secret": token}
@@ -385,20 +448,38 @@ def portable_skill(request: Request, session: Session = Depends(require_session)
385
  @router.get("/whoami")
386
  def whoami(session: Session = Depends(require_external_analyst)):
387
  """Name the authenticated maker and the explicit limits on bearer writes."""
 
388
  return {
389
  "username": session.uname,
390
  "name": session.user.get("name") or session.uname,
391
  "tenant": session.tenant,
392
  "key_id": session.claims["external_key_id"],
 
 
 
393
  "write_scope": "Named tools only, as the key's maker with the maker's own grants.",
394
  }
395
 
396
 
 
 
 
 
 
 
 
 
 
 
 
397
  @router.get("/databases")
398
  def list_databases(session: Session = Depends(require_external_analyst)):
399
  """List only sources this user may read or already sees elsewhere in the product."""
400
  databases = []
 
401
  for row in _resolve_external_scope(session):
 
 
402
  if not (row.get("permitted") or row.get("visible")):
403
  continue
404
  public = {
@@ -416,6 +497,7 @@ def list_databases(session: Session = Depends(require_external_analyst)):
416
  @router.get("/databases/{database}/schema")
417
  def database_schema(database: str, session: Session = Depends(require_external_analyst)):
418
  """Return the field contract after resolving the ordinary strict Assistant read wall."""
 
419
  resolved = _resolve_external_scope(
420
  session, databases=[database], include_schema=True, strict_schema=True,
421
  )
@@ -429,6 +511,7 @@ def query_database(
429
  session: Session = Depends(require_external_analyst),
430
  ):
431
  """Read one detached Assistant snapshot; FastAPI rejects non-object request bodies."""
 
432
  payload = body or {}
433
  return deps.assistant_read_scope(
434
  session,
@@ -504,6 +587,7 @@ def _view_event(session, kind, args):
504
  from core import grid_events
505
 
506
  database = args["database"]
 
507
  event = {"id": uuid.uuid4().hex, "type": kind}
508
  if kind == "view_upsert":
509
  raw = args["view"]
@@ -556,6 +640,10 @@ def _application_upsert(session, args):
556
  import application_registry as applications
557
  import routes_assets
558
 
 
 
 
 
559
  payload = {key: value for key, value in args.items() if key != "app_id"}
560
  app_id = args.get("app_id")
561
  if "app_id" in args and not str(app_id or "").strip():
@@ -595,9 +683,27 @@ def _tool_context(session: Session) -> external_tools.ToolContext:
595
 
596
  def project(book):
597
  served = routes_sheet._read_for(session, book)
 
 
 
 
 
 
 
 
 
 
 
 
 
598
  routes_sheet._recompute_formulas(served, formula_runtime, sheet_mod)
599
  return served
600
 
 
 
 
 
 
601
  def cache_binding(workbook_id, tab, addr, binding, resolved):
602
  # Same best-effort cache fill as the UI's compute_cell. A fresh value must replace
603
  # this scope's old slot before an editor's read projection can use that slot.
@@ -618,7 +724,7 @@ def _tool_context(session: Session) -> external_tools.ToolContext:
618
  require_reader=lambda book: routes_sheet._require_reader(session, book),
619
  require_editor=lambda book: routes_sheet._require_editor(session, book),
620
  project_book=project,
621
- resolve_binding=lambda binding, book, tab: routes_sheet._resolve_cell_binding(session, binding, book, tab),
622
  cache_binding=cache_binding,
623
  list_databases=lambda: list_databases(session),
624
  describe_database=lambda database: database_schema(database, session),
@@ -687,6 +793,10 @@ def _handle_mcp(req, session: Session):
687
  for key, tool in external_tools.TOOLS.items()]}}
688
  if method != "tools/call":
689
  return protocol_error(rid, -32601, "The requested MCP method was not found.")
 
 
 
 
690
  data = external_tools.dispatch(_tool_context(session), name, params.get("arguments", {}))
691
  if isinstance(data, dict) and data.get("refused"):
692
  first = data["refused"][0]
@@ -697,7 +807,7 @@ def _handle_mcp(req, session: Session):
697
  except external_access.ExternalAuthError:
698
  _auth_refusal()
699
  except external_access.ExternalAccessError:
700
- out = _tool_refusal(name, "external_access_unavailable", "External access is unavailable right now.", 503)
701
  except sheets.SheetRefusal as exc:
702
  import routes_sheet
703
  translated = routes_sheet._refuse(exc)
 
1
  """Per-user credentials, governed reads and explicitly allowed bearer build tools."""
2
 
3
+ import copy
4
  import json
5
  import uuid
6
  from urllib.parse import quote
 
18
  _CREDENTIAL_PREFIX = "lpb1."
19
 
20
 
21
+ def _key_scope(session):
22
+ """(access, databases) for THIS request. A session without the claims is an in-app human."""
23
+ claims = session.claims or {}
24
+ return external_access.scope_of({
25
+ "access": claims.get("external_access"),
26
+ "databases": claims.get("external_databases"),
27
+ })
28
+
29
+
30
+ def _assert_database_scope(session, database):
31
+ if external_access.database_allowed(_key_scope(session)[1], database):
32
+ return
33
+ # A binding can carry no database at all. Name what was asked for when there is a name, and
34
+ # never interpolate a bare None into a sentence a caller reads.
35
+ named = str(database or "").strip()
36
+ raise err(403, "key_database_out_of_scope",
37
+ f"Database {named} is outside this credential's scope." if named
38
+ else "This credential is limited to named databases, and none was named.")
39
+
40
+
41
+ def _assert_write_scope(session, tool_name):
42
+ if not external_access.may_write(_key_scope(session)[0]):
43
+ raise err(403, "key_read_only", f"{tool_name} writes, and this credential is read only.")
44
+
45
+
46
+ def _databases_in_arguments(value):
47
+ """Find database references, including bound cell documents, without unbounded recursion."""
48
+ found = []
49
+
50
+ def scan(node, depth):
51
+ if depth > 12:
52
+ return
53
+ if isinstance(node, dict):
54
+ for key, item in node.items():
55
+ if key in ("database", "sourceDatabase") and isinstance(item, str):
56
+ found.append(item)
57
+ elif key == "compatibleDatabases" and isinstance(item, list):
58
+ found.extend(database for database in item if isinstance(database, str))
59
+ scan(item, depth + 1)
60
+ elif isinstance(node, (list, tuple)):
61
+ for item in node:
62
+ scan(item, depth + 1)
63
+
64
+ scan(value, 0)
65
+ return found
66
+
67
+
68
  def _auth_refusal():
69
  raise err(401, external_access.AUTH_ERROR, "The credential is invalid or revoked.")
70
 
 
90
  "u": verified.user["username"],
91
  "external": True,
92
  "external_key_id": verified.key_id,
93
+ "external_access": verified.access,
94
+ "external_databases": (external_access.ALL_DATABASES
95
+ if verified.databases == external_access.ALL_DATABASES
96
+ else list(verified.databases)),
97
  },
98
  runtime=verified.runtime,
99
  )
 
118
 
119
 
120
  def _management_refusal(exc: external_access.ExternalAccessError):
121
+ if exc.code == "external_access_scope_invalid":
122
+ raise err(400, exc.code, "Choose Read only or Read and write.")
123
+ if exc.code == "external_databases_invalid":
124
+ raise err(400, exc.code, "Choose all databases, or name at least one database.")
125
  if exc.code == "external_label_invalid":
126
  raise err(400, exc.code, "Enter a label between 1 and 80 characters.")
127
  if exc.code == "external_key_not_found":
128
  raise err(404, exc.code, "That credential was not found.")
129
  if exc.code in {"external_identity_invalid", "external_account_unavailable"}:
130
  raise err(409, exc.code, "This account cannot create an external credential.")
131
+ raise err(503, "external_access_unavailable", "The AI API is unavailable right now.")
132
 
133
 
134
  def _resolve_external_scope(
 
186
  else:
187
  row["label"] = fallback_label(database)
188
  row["fields"] = []
189
+ else:
190
+ row["label"] = fallback_label(database)
191
  resolved.append(row)
192
  return resolved
193
 
 
384
  "## Limits",
385
  "",
386
  ("This surface writes only through the named tools, as the key's maker with the maker's "
387
+ "own grants. Workbook roles and database restrictions still apply. Each credential also "
388
+ "carries its own access level and database scope, set when it is created and shown in "
389
+ "Loopable Settings. It returns no data "
390
  "the maker cannot already see in Loopable. Sheet cell history records the maker and "
391
  "key label. Saved Views and Apps keep the UI's username attribution; their writers "
392
  "have no author display-name field. No tool writes to Odoo."),
 
403
  """Mint a credential for the signed-in human. Bearer auth is not accepted here."""
404
  session.require("analyst")
405
  label = body.get("label") if isinstance(body, dict) else None
406
+ access = body.get("access") if isinstance(body, dict) else None
407
+ databases = body.get("databases") if isinstance(body, dict) else None
408
  try:
409
+ key, token = external_access.mint(session.runtime, session.uname, session.tenant, label,
410
+ access=access, databases=databases)
411
  except external_access.ExternalAccessError as exc:
412
  _management_refusal(exc)
413
  return {"key": key, "secret": token}
 
448
  @router.get("/whoami")
449
  def whoami(session: Session = Depends(require_external_analyst)):
450
  """Name the authenticated maker and the explicit limits on bearer writes."""
451
+ access, databases = _key_scope(session)
452
  return {
453
  "username": session.uname,
454
  "name": session.user.get("name") or session.uname,
455
  "tenant": session.tenant,
456
  "key_id": session.claims["external_key_id"],
457
+ "access": access,
458
+ "databases": (external_access.ALL_DATABASES
459
+ if databases == external_access.ALL_DATABASES else list(databases)),
460
  "write_scope": "Named tools only, as the key's maker with the maker's own grants.",
461
  }
462
 
463
 
464
+ @router.get("/scope/databases")
465
+ def scope_databases(session: Session = Depends(require_session)):
466
+ """List the databases this signed-in maker could put inside a new credential's scope."""
467
+ session.require("analyst")
468
+ return {"databases": [
469
+ {key: row[key] for key in ("database", "label", "permitted", "answerable")}
470
+ for row in _resolve_external_scope(session)
471
+ if row.get("permitted") or row.get("visible")
472
+ ]}
473
+
474
+
475
  @router.get("/databases")
476
  def list_databases(session: Session = Depends(require_external_analyst)):
477
  """List only sources this user may read or already sees elsewhere in the product."""
478
  databases = []
479
+ key_databases = _key_scope(session)[1]
480
  for row in _resolve_external_scope(session):
481
+ if not external_access.database_allowed(key_databases, row["database"]):
482
+ continue
483
  if not (row.get("permitted") or row.get("visible")):
484
  continue
485
  public = {
 
497
  @router.get("/databases/{database}/schema")
498
  def database_schema(database: str, session: Session = Depends(require_external_analyst)):
499
  """Return the field contract after resolving the ordinary strict Assistant read wall."""
500
+ _assert_database_scope(session, database)
501
  resolved = _resolve_external_scope(
502
  session, databases=[database], include_schema=True, strict_schema=True,
503
  )
 
511
  session: Session = Depends(require_external_analyst),
512
  ):
513
  """Read one detached Assistant snapshot; FastAPI rejects non-object request bodies."""
514
+ _assert_database_scope(session, database)
515
  payload = body or {}
516
  return deps.assistant_read_scope(
517
  session,
 
587
  from core import grid_events
588
 
589
  database = args["database"]
590
+ _assert_database_scope(session, database)
591
  event = {"id": uuid.uuid4().hex, "type": kind}
592
  if kind == "view_upsert":
593
  raw = args["view"]
 
640
  import application_registry as applications
641
  import routes_assets
642
 
643
+ for database in args.get("compatibleDatabases") or []:
644
+ _assert_database_scope(session, database)
645
+ if args.get("sourceDatabase") is not None:
646
+ _assert_database_scope(session, args["sourceDatabase"])
647
  payload = {key: value for key, value in args.items() if key != "app_id"}
648
  app_id = args.get("app_id")
649
  if "app_id" in args and not str(app_id or "").strip():
 
683
 
684
  def project(book):
685
  served = routes_sheet._read_for(session, book)
686
+ databases = _key_scope(session)[1]
687
+ if databases != external_access.ALL_DATABASES:
688
+ # The owner projection can share cells with its input; key scope is response-only.
689
+ served = copy.deepcopy(served)
690
+ for tab in served.get("sheets", []):
691
+ for cell in tab.get("cells", {}).values():
692
+ if not isinstance(cell, dict) or cell.get("kind") != "bound":
693
+ continue
694
+ binding = cell.get("binding")
695
+ database = binding.get("database") if isinstance(binding, dict) else None
696
+ if not external_access.database_allowed(databases, database):
697
+ cell["value"] = None
698
+ cell["display"] = ""
699
  routes_sheet._recompute_formulas(served, formula_runtime, sheet_mod)
700
  return served
701
 
702
+ def resolve_binding(binding, book, tab):
703
+ if isinstance(binding, dict):
704
+ _assert_database_scope(session, binding.get("database"))
705
+ return routes_sheet._resolve_cell_binding(session, binding, book, tab)
706
+
707
  def cache_binding(workbook_id, tab, addr, binding, resolved):
708
  # Same best-effort cache fill as the UI's compute_cell. A fresh value must replace
709
  # this scope's old slot before an editor's read projection can use that slot.
 
724
  require_reader=lambda book: routes_sheet._require_reader(session, book),
725
  require_editor=lambda book: routes_sheet._require_editor(session, book),
726
  project_book=project,
727
+ resolve_binding=resolve_binding,
728
  cache_binding=cache_binding,
729
  list_databases=lambda: list_databases(session),
730
  describe_database=lambda database: database_schema(database, session),
 
793
  for key, tool in external_tools.TOOLS.items()]}}
794
  if method != "tools/call":
795
  return protocol_error(rid, -32601, "The requested MCP method was not found.")
796
+ if isinstance(name, str) and name in _WRITE_TOOLS:
797
+ _assert_write_scope(session, name)
798
+ for database in _databases_in_arguments(params.get("arguments", {})):
799
+ _assert_database_scope(session, database)
800
  data = external_tools.dispatch(_tool_context(session), name, params.get("arguments", {}))
801
  if isinstance(data, dict) and data.get("refused"):
802
  first = data["refused"][0]
 
807
  except external_access.ExternalAuthError:
808
  _auth_refusal()
809
  except external_access.ExternalAccessError:
810
+ out = _tool_refusal(name, "external_access_unavailable", "The AI API is unavailable right now.", 503)
811
  except sheets.SheetRefusal as exc:
812
  import routes_sheet
813
  translated = routes_sheet._refuse(exc)
api/routes_module_index.py CHANGED
@@ -52,10 +52,15 @@ def _readable_ids(module, session):
52
  # records, never audience-option assembly, just to verify placement ids.
53
  if module == "app":
54
  return {row["id"] for row in routes_assets.application_index(session=session)["applications"]}
55
- # all_definitions omits synthetic field/Odoo agents. Keep the complete automation
56
- # list until it has an id-only accessor; callers skip this work for empty placements.
57
- return ({"agent:" + row["id"] for row in
58
- routes_automation.list_automations(session=session)["automations"]}
 
 
 
 
 
59
  | {"voice:" + row["id"] for row in
60
  voice._store(session.runtime)["voice_agent"].values() if isinstance(row, dict)})
61
 
 
52
  # records, never audience-option assembly, just to verify placement ids.
53
  if module == "app":
54
  return {row["id"] for row in routes_assets.application_index(session=session)["applications"]}
55
+ # ⭐⭐ W62-T17 — THE ID-ONLY ACCESSOR THIS COMMENT USED TO ASK FOR NOW EXISTS. It read
56
+ # *"all_definitions omits synthetic field/Odoo agents. Keep the complete automation list until
57
+ # it has an id-only accessor"*, and the whole Agents rail payload was being built to answer a
58
+ # membership question. `routes_automation.automation_ids` keeps all three strata (stored
59
+ # definitions, field agents, the derived Odoo sync row) and the statements seed, so the SET is
60
+ # unchanged; what it drops is `_wire` per automation, which read `agent_contracts` and
61
+ # `automation_agent_actions` once EACH TIME (MEASURED: 1,101 ms of this route's 1,180 ms on
62
+ # staging, `AutoWiki/waves/wave62/proto/T17-profile.md`).
63
+ return ({"agent:" + aid for aid in routes_automation.automation_ids(session)}
64
  | {"voice:" + row["id"] for row in
65
  voice._store(session.runtime)["voice_agent"].values() if isinstance(row, dict)})
66
 
api/routes_odoo_tables.py CHANGED
@@ -1522,18 +1522,37 @@ def _materialised_table(table_key):
1522
  return module_cache_source(table_key) is not None or table_key not in _sources()
1523
 
1524
 
1525
- def _relation_rows(session, table, columns, *, ids=None, match=None, where=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1526
  """Internal join values, after the ordinary row wall, with no row-count ceiling.
1527
 
1528
  Join columns may be hidden on the wire. Only identities leave the resolver; the native
1529
  payload builders still apply their complete hidden-field closure before returning cells.
 
 
1530
  """
1531
  import core.perm_scope as perm_scope
1532
  import core.relations as relations
1533
 
1534
  columns = set(columns) | {relations.IDENTITY_COL}
1535
  if not _materialised_table(table):
1536
- read = _compiled_read(table, session)
 
1537
  spec = read["spec"]
1538
  bindings = dict(spec["cols"], pid=(spec["id"], int))
1539
  if columns - set(bindings):
@@ -1556,7 +1575,7 @@ def _relation_rows(session, table, columns, *, ids=None, match=None, where=None)
1556
 
1557
  # This is an internal join, never a cell response. Apply the same permanent wall on the
1558
  # complete contract before taking any join value, including a join on a hidden column.
1559
- if not perm_scope.may_read(session.user, table, st=session.runtime):
1560
  raise err(403, "forbidden_table", "This account cannot open the linked database.")
1561
  if module_cache_source(table) is not None:
1562
  session.require(table)
@@ -1582,6 +1601,8 @@ def _relation_cell_ids(value):
1582
 
1583
  def _relation_leg_ids(session, source, source_ids, entry):
1584
  """Follow one declared leg, including manual, inverse and through links."""
 
 
1585
  target = str(entry["target"])
1586
  via = entry.get("via") or {}
1587
  link = entry.get("link") or {}
@@ -1601,11 +1622,12 @@ def _relation_leg_ids(session, source, source_ids, entry):
1601
  if (manual and not reverse) or (inverse and reverse):
1602
  values = set().union(*(_relation_cell_ids(row.get(source_col)) for row in source_rows))
1603
  target_col = "pid"
1604
- through = link.get("through") if not manual else None
1605
  if through:
1606
  left = str(link["throughTo"] if reverse else link["throughOn"])
1607
  right = str(link["throughOn"] if reverse else link["throughTo"])
1608
- middle = _relation_rows(session, str(through), [left, right], match=(left, values))
 
1609
  values = {str(row[right]) for row in middle if row.get(right) not in (None, "")}
1610
  if (manual and reverse) or (inverse and not reverse):
1611
  rows = _relation_rows(session, target, [target_col])
@@ -1616,6 +1638,15 @@ def _relation_leg_ids(session, source, source_ids, entry):
1616
  return {int(row["pid"]) for row in rows}
1617
 
1618
 
 
 
 
 
 
 
 
 
 
1619
  def _relation_target_ids(session, target, related):
1620
  """One pin resolver for SQL, pool and tenant rows, selected from the scoped path list."""
1621
  import core.relations as relations
@@ -1631,7 +1662,8 @@ def _relation_target_ids(session, target, related):
1631
  if path and len(path) > relations.MAX_DEPTH:
1632
  raise err(400, "over_depth", relations.over_depth_refusal(source, path))
1633
  if not _may_open(session, source):
1634
- raise err(403, "forbidden_table", "This account cannot open the source database.")
 
1635
  entries = related_path_entries(session, source, len(path) if path else 1)
1636
  entry = relations.pick_path(entries, path) if path else relations.pick(entries, via)
1637
  if entry is None or str(entry.get("target")) != str(target):
@@ -1646,7 +1678,8 @@ def _relation_target_ids(session, target, related):
1646
  legs = [(source, first), (middle, last)]
1647
  for table, leg in legs:
1648
  if not _may_open(session, leg["target"]):
1649
- raise err(403, "forbidden_table", "This account cannot open the linked database.")
 
1650
  ids = _relation_leg_ids(session, table, ids, leg)
1651
  return ids
1652
 
@@ -1700,7 +1733,7 @@ def _cache_relation_plan(session, source, via, target):
1700
  if not isinstance(link, dict) or str(link.get("table") or "") != target:
1701
  raise err(404, "relation_target_missing",
1702
  f"the relation '{via}' no longer has a current target in this workspace")
1703
- through = str(link.get("through") or "")
1704
  through_on = str(link.get("throughOn") or "")
1705
  through_to = str(link.get("throughTo") or "")
1706
  on = str(link.get("on") or relations.IDENTITY_COL)
@@ -1710,10 +1743,8 @@ def _cache_relation_plan(session, source, via, target):
1710
  if relations.is_retired_table(through):
1711
  raise err(404, "relation_target_retired",
1712
  f"'{through}' is retired, so the relation to '{target}' is no longer available")
1713
- if not _may_open(session, through):
1714
- raise err(403, "forbidden_table",
1715
- f"the relation to '{target}' crosses '{through}', which your account cannot "
1716
- "open")
1717
  if not _may_open(session, target):
1718
  raise err(403, "forbidden_table",
1719
  f"the relation ends at '{target}', which your account cannot open")
@@ -1755,7 +1786,10 @@ def _cache_relation_target_ids(session, source, record, via, target):
1755
  raise err(400, "unknown_relation",
1756
  f"record {record} has no readable source value for relation '{via}'")
1757
 
1758
- compiled = _compiled_read(through, session)
 
 
 
1759
  spec = compiled["spec"]
1760
  left = (spec.get("cols") or {}).get(through_on)
1761
  right = (spec.get("cols") or {}).get(through_to)
@@ -2163,7 +2197,7 @@ def _may_see_view(session, vid, store):
2163
 
2164
 
2165
  def _compiled_read(table_key, session, *, filters=None, filterConj="and", sorts=None,
2166
- search=None, tree=_TREE_UNSET, related=None):
2167
  """EVERYTHING THAT DECIDES **WHICH ROWS** A CONNECTED GRID MAY ANSWER OVER, compiled once.
2168
 
2169
  Returns `{defn, fields, cur, spec, cols, base_where, wall_params, where, params, limits,
@@ -2223,7 +2257,10 @@ def _compiled_read(table_key, session, *, filters=None, filterConj="and", sorts=
2223
  # tenant #0's eight databases is read-through. Left un-applied, an administrator could set a
2224
  # filter in Manage user, see it saved, and the scoped user would meet a 409 where their rows
2225
  # used to be. So the wall is APPLIED here, in SQL, three paragraphs down.
2226
- defn = _defn_or_refuse(session, table_key, defs_only=True, scope_applied=True)
 
 
 
2227
  fields = None
2228
  for _bucket, key, _label, mk_fields in rel.TABLES:
2229
  if key == table_key:
 
1522
  return module_cache_source(table_key) is not None or table_key not in _sources()
1523
 
1524
 
1525
+ def _traversal_defn_or_refuse(session, table_key):
1526
+ """R50 / C4: admit an intermediate after the caller has established both end grants.
1527
+
1528
+ The session may already open both ends of a declared two-hop link. Its intermediate
1529
+ is read only to find target ids, and only join values leave this traversal. The compiled
1530
+ read still applies the row wall, hidden-field closure, BU scope and mirror guard.
1531
+ """
1532
+ ut = _ut()
1533
+ st = ut.lend_defs(session.runtime)
1534
+ defn = ut.get(table_key, st=st)
1535
+ if not defn:
1536
+ raise err(404, "unknown_table", "that database does not exist")
1537
+ return defn
1538
+
1539
+
1540
+ def _relation_rows(session, table, columns, *, ids=None, match=None, where=None,
1541
+ traversal_of=None):
1542
  """Internal join values, after the ordinary row wall, with no row-count ceiling.
1543
 
1544
  Join columns may be hidden on the wire. Only identities leave the resolver; the native
1545
  payload builders still apply their complete hidden-field closure before returning cells.
1546
+ With traversal_of, the caller must already have established both ends of the declared
1547
+ edge named by that key. Only join values leave this intermediate read, never a cell.
1548
  """
1549
  import core.perm_scope as perm_scope
1550
  import core.relations as relations
1551
 
1552
  columns = set(columns) | {relations.IDENTITY_COL}
1553
  if not _materialised_table(table):
1554
+ read = (_compiled_read(table, session, traversal_intermediate=True)
1555
+ if traversal_of is not None else _compiled_read(table, session))
1556
  spec = read["spec"]
1557
  bindings = dict(spec["cols"], pid=(spec["id"], int))
1558
  if columns - set(bindings):
 
1575
 
1576
  # This is an internal join, never a cell response. Apply the same permanent wall on the
1577
  # complete contract before taking any join value, including a join on a hidden column.
1578
+ if traversal_of is None and not perm_scope.may_read(session.user, table, st=session.runtime):
1579
  raise err(403, "forbidden_table", "This account cannot open the linked database.")
1580
  if module_cache_source(table) is not None:
1581
  session.require(table)
 
1601
 
1602
  def _relation_leg_ids(session, source, source_ids, entry):
1603
  """Follow one declared leg, including manual, inverse and through links."""
1604
+ import core.relations as relations
1605
+
1606
  target = str(entry["target"])
1607
  via = entry.get("via") or {}
1608
  link = entry.get("link") or {}
 
1622
  if (manual and not reverse) or (inverse and reverse):
1623
  values = set().union(*(_relation_cell_ids(row.get(source_col)) for row in source_rows))
1624
  target_col = "pid"
1625
+ through = relations.declared_through(link) if not manual else None
1626
  if through:
1627
  left = str(link["throughTo"] if reverse else link["throughOn"])
1628
  right = str(link["throughOn"] if reverse else link["throughTo"])
1629
+ middle = _relation_rows(session, str(through), [left, right], match=(left, values),
1630
+ traversal_of=str(entry.get("key") or via.get("key") or ""))
1631
  values = {str(row[right]) for row in middle if row.get(right) not in (None, "")}
1632
  if (manual and reverse) or (inverse and not reverse):
1633
  rows = _relation_rows(session, target, [target_col])
 
1638
  return {int(row["pid"]) for row in rows}
1639
 
1640
 
1641
+ def _relation_label(key):
1642
+ """Prefer the database's display label in relation refusals."""
1643
+ source = module_cache_source(key)
1644
+ if source and source.get("label"):
1645
+ return source["label"]
1646
+ return next((label for _bucket, table, label, _fields in _rel().TABLES
1647
+ if table == key and label), str(key))
1648
+
1649
+
1650
  def _relation_target_ids(session, target, related):
1651
  """One pin resolver for SQL, pool and tenant rows, selected from the scoped path list."""
1652
  import core.relations as relations
 
1662
  if path and len(path) > relations.MAX_DEPTH:
1663
  raise err(400, "over_depth", relations.over_depth_refusal(source, path))
1664
  if not _may_open(session, source):
1665
+ raise err(403, "forbidden_table",
1666
+ f"the relation starts at '{_relation_label(source)}', which your account cannot open")
1667
  entries = related_path_entries(session, source, len(path) if path else 1)
1668
  entry = relations.pick_path(entries, path) if path else relations.pick(entries, via)
1669
  if entry is None or str(entry.get("target")) != str(target):
 
1678
  legs = [(source, first), (middle, last)]
1679
  for table, leg in legs:
1680
  if not _may_open(session, leg["target"]):
1681
+ raise err(403, "forbidden_table",
1682
+ f"the relation ends at '{_relation_label(leg['target'])}', which your account cannot open")
1683
  ids = _relation_leg_ids(session, table, ids, leg)
1684
  return ids
1685
 
 
1733
  if not isinstance(link, dict) or str(link.get("table") or "") != target:
1734
  raise err(404, "relation_target_missing",
1735
  f"the relation '{via}' no longer has a current target in this workspace")
1736
+ through = relations.declared_through(link)
1737
  through_on = str(link.get("throughOn") or "")
1738
  through_to = str(link.get("throughTo") or "")
1739
  on = str(link.get("on") or relations.IDENTITY_COL)
 
1743
  if relations.is_retired_table(through):
1744
  raise err(404, "relation_target_retired",
1745
  f"'{through}' is retired, so the relation to '{target}' is no longer available")
1746
+ # R50: both end grants suffice. Traversal admission in _compiled_read replaces the
1747
+ # intermediate grant check and still applies the intermediate's row wall.
 
 
1748
  if not _may_open(session, target):
1749
  raise err(403, "forbidden_table",
1750
  f"the relation ends at '{target}', which your account cannot open")
 
1786
  raise err(400, "unknown_relation",
1787
  f"record {record} has no readable source value for relation '{via}'")
1788
 
1789
+ # R50 / C4: the intermediate of a DECLARED two-hop link is read to find target ids
1790
+ # only, so it is admitted on both ends' grants. The compiler still applies its row
1791
+ # wall, hidden-field closure and mirror guard to it.
1792
+ compiled = _compiled_read(through, session, traversal_intermediate=True)
1793
  spec = compiled["spec"]
1794
  left = (spec.get("cols") or {}).get(through_on)
1795
  right = (spec.get("cols") or {}).get(through_to)
 
2197
 
2198
 
2199
  def _compiled_read(table_key, session, *, filters=None, filterConj="and", sorts=None,
2200
+ search=None, tree=_TREE_UNSET, related=None, traversal_intermediate=False):
2201
  """EVERYTHING THAT DECIDES **WHICH ROWS** A CONNECTED GRID MAY ANSWER OVER, compiled once.
2202
 
2203
  Returns `{defn, fields, cur, spec, cols, base_where, wall_params, where, params, limits,
 
2257
  # tenant #0's eight databases is read-through. Left un-applied, an administrator could set a
2258
  # filter in Manage user, see it saved, and the scoped user would meet a 409 where their rows
2259
  # used to be. So the wall is APPLIED here, in SQL, three paragraphs down.
2260
+ if traversal_intermediate:
2261
+ defn = _traversal_defn_or_refuse(session, table_key)
2262
+ else:
2263
+ defn = _defn_or_refuse(session, table_key, defs_only=True, scope_applied=True)
2264
  fields = None
2265
  for _bucket, key, _label, mk_fields in rel.TABLES:
2266
  if key == table_key:
api/routes_query.py CHANGED
@@ -1447,6 +1447,7 @@ def _submit(body, session, chat=None):
1447
  assistant_message = {
1448
  "id": assistant_message_id, "threadId": thread_id, "role": "assistant", "createdAt": now,
1449
  "content": (said or _said_fallback(artifact)) if artifact else (refusal or "the assistant could not answer"),
 
1450
  "targetDatabase": target, "requestedModel": selected_model, "model": provider,
1451
  "routedTo": routed,
1452
  **_model_identity(provider),
 
1447
  assistant_message = {
1448
  "id": assistant_message_id, "threadId": thread_id, "role": "assistant", "createdAt": now,
1449
  "content": (said or _said_fallback(artifact)) if artifact else (refusal or "the assistant could not answer"),
1450
+ # D-745: the Assistant restores routing from targetDatabase; keep it equal to routed["database"].
1451
  "targetDatabase": target, "requestedModel": selected_model, "model": provider,
1452
  "routedTo": routed,
1453
  **_model_identity(provider),
api/routes_sheet.py CHANGED
@@ -221,6 +221,11 @@ def _registry_assembly(session: Session, table_key: str):
221
  if table_key in memo:
222
  return memo[table_key]
223
  try:
 
 
 
 
 
224
  if table_key == "product_data":
225
  from routes_products import product_assembly
226
  memo[table_key] = product_assembly(session, scope="product",
@@ -1042,11 +1047,7 @@ def _reresolved_for_reader(session: Session, book, *, endings_only=False):
1042
  seen_db[db] = exc
1043
  failure = seen_db.get(db)
1044
  if failure is not None:
1045
- cell["state"] = "refused"
1046
- cell["value"] = None
1047
- cell["display"] = ""
1048
- cell["refusal"] = {"code": "database_unreadable",
1049
- "message": f"You cannot read {db}."}
1050
  cell.pop("limits", None)
1051
  continue
1052
 
@@ -1075,13 +1076,10 @@ def _reresolved_for_reader(session: Session, book, *, endings_only=False):
1075
  except HTTPException as exc:
1076
  detail = getattr(exc, "detail", None) or {}
1077
  info = detail.get("error") if isinstance(detail, dict) else None
1078
- cell["state"] = "refused"
1079
- cell["value"] = None
1080
- cell["display"] = ""
1081
- cell["refusal"] = {
1082
- "code": (info or {}).get("code", "sheet_unresolved"),
1083
- "message": (info or {}).get("message", "This cell could not be refreshed."),
1084
- }
1085
  cell.pop("limits", None)
1086
  continue
1087
  cell["state"] = "fresh"
@@ -1219,7 +1217,7 @@ def read_sheet_index(session: Session = Depends(require_session)):
1219
  @router.put("/sheets/index")
1220
  def write_sheet_index(body: dict = Body(default=None),
1221
  session: Session = Depends(require_session)):
1222
- """Replace the folder, placement and star strata wholesale, or refuse by name.
1223
 
1224
  ⭐ `repairs` RIDES BACK OUT. `core.sheets.save_folders` records every change it made to the
1225
  payload, and the rail says so in a sentence rather than letting a workbook reappear at the
@@ -1235,9 +1233,16 @@ def write_sheet_index(body: dict = Body(default=None),
1235
  from core import sheets
1236
  raw = dict(body or {})
1237
  try:
1238
- out = sheets.save_folders(_store(session), raw.get("folders"),
1239
- raw.get("itemFolders"), starred=raw.get("starred"),
1240
- expect_rev=raw.get("rev"))
 
 
 
 
 
 
 
1241
  except sheets.SheetRefusal as exc:
1242
  raise _refuse(exc)
1243
  return {"index": _wire_index({**_index_for(session), "repairs": out.get("repairs", [])})}
@@ -1339,7 +1344,8 @@ def _run_import(job_id, path, filename, runtime, uname):
1339
  made = sheets.create_workbook(runtime, name=book.get("name") or "", created_by=uname,
1340
  on_duplicate="suffix")
1341
  saved = sheets.put_workbook(runtime, made["id"],
1342
- dict(book, refreshed_at=stamp, rev=made["rev"]), actor=uname)
 
1343
  _job_set(job_id, state="done", progress=1.0, workbook_id=saved["id"],
1344
  sentence=_import_sentence(report))
1345
  except sheet_import.ImportRefusal as exc:
@@ -1617,9 +1623,10 @@ def _recomputed_tab_cells(session: Session, workbook_id: str, tab_ref: str, *, c
1617
  cell.pop("refusal", None)
1618
  except HTTPException as exc:
1619
  info = ((exc.detail or {}).get("error") or {})
1620
- cell.update(value=None, display="", state="refused", refusal={
1621
- "code": info.get("code", "ending_cell_unreadable"),
1622
- "message": info.get("message", "The Ending date could not be read. Choose a valid date.")})
 
1623
  ending_cells.add((source.get("id"), addr))
1624
  if ending_cells:
1625
  _recompute_formulas(book, fr, sheet_mod)
@@ -1839,6 +1846,8 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
1839
  for addr, cell in (tab.get("cells") or {}).items():
1840
  if not isinstance(cell, dict) or cell.get("kind") != "bound":
1841
  continue
 
 
1842
  binding = cell.get("binding") or {}
1843
  db = str(binding.get("database") or "")
1844
  if db not in seen_db:
@@ -1849,11 +1858,7 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
1849
  seen_db[db] = exc
1850
  failure = seen_db.get(db)
1851
  if failure is not None:
1852
- cell["state"] = "refused"
1853
- cell["value"] = None
1854
- cell["display"] = ""
1855
- cell["refusal"] = {"code": "database_unreadable",
1856
- "message": f"You cannot read {db}."}
1857
  cell.pop("limits", None)
1858
  continue
1859
  try:
@@ -1861,13 +1866,10 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
1861
  except HTTPException as exc:
1862
  detail = getattr(exc, "detail", None) or {}
1863
  info = detail.get("error") if isinstance(detail, dict) else None
1864
- cell["state"] = "refused"
1865
- cell["value"] = None
1866
- cell["display"] = ""
1867
- cell["refusal"] = {
1868
- "code": (info or {}).get("code", "sheet_unresolved"),
1869
- "message": (info or {}).get("message", "This cell could not be refreshed."),
1870
- }
1871
  cell.pop("limits", None)
1872
  continue
1873
  cell["state"] = "fresh"
@@ -1894,11 +1896,13 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
1894
  _recompute_formulas(book, fr, sheet_mod)
1895
  recalc_ms = round((perf_counter() - started) * 1000.0, 1)
1896
  try:
 
1897
  saved = sheets.put_workbook(_store(session), workbook_id,
1898
  {"name": book.get("name"), "sheets": book.get("sheets"),
1899
  "refreshed_at": stamp, "rev": book.get("rev")},
1900
  actor=session.uname,
1901
- actor_name=session.user.get("name") or session.uname)
 
1902
  except sheets.SheetRefusal as exc:
1903
  raise _refuse(exc)
1904
  # ⭐⭐ R3 / W52-T12: REFRESH IS THE ONE EVENT ALLOWED TO INVALIDATE A READER'S CACHED SCOPE
@@ -2265,6 +2269,36 @@ def _filter_cell_values(session, nodes, *, book=None, tab=None, today=None, seen
2265
  raise err(400, exc.code, exc.message)
2266
 
2267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2268
  def _resolve_cell_binding(session, binding, book, tab, **kwargs):
2269
  """Keep the legacy resolver calling convention for bindings without workbook inputs."""
2270
  if _has_cell_inputs(binding):
@@ -2568,6 +2602,11 @@ def compute_cell(workbook_id: str, addr: str, body: dict = Body(default=None),
2568
  raise err(404, "cell_missing", f"Cell {key} is not filled in.")
2569
  if cell.get("kind") != "bound":
2570
  raise err(409, "cell_not_bound", f"Cell {key} is not bound to a database.")
 
 
 
 
 
2571
 
2572
  tab_ref = str((tab or {}).get("id") or (tab or {}).get("name") or "")
2573
  binding = cell.get("binding") or {}
@@ -2582,13 +2621,10 @@ def compute_cell(workbook_id: str, addr: str, body: dict = Body(default=None),
2582
  #: a cell left `stale` would shimmer forever, and the reason belongs on the cell.
2583
  detail = getattr(exc, "detail", None) or {}
2584
  info = detail.get("error") if isinstance(detail, dict) else None
2585
- saved["state"] = "refused"
2586
- saved["value"] = None
2587
- saved["display"] = ""
2588
- saved["refusal"] = {
2589
- "code": (info or {}).get("code", "sheet_unresolved"),
2590
- "message": (info or {}).get("message", "This cell could not be refreshed."),
2591
- }
2592
  else:
2593
  limits = resolved["limits"]
2594
  saved["state"] = "fresh"
@@ -2624,6 +2660,104 @@ def compute_cell(workbook_id: str, addr: str, body: dict = Body(default=None),
2624
  return {"cell": wire, "rev": landed.get("rev"), "tab": tab_ref, "addr": key}
2625
 
2626
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2627
  @router.get("/sheets/{workbook_id}/cells/{addr}/drill")
2628
  def drill_cell(workbook_id: str, addr: str, session: Session = Depends(require_session)):
2629
  """`{database, view_id?, filter?, record_ids, count}` for `LinkGridModal` (R6, R13, R17).
@@ -2659,6 +2793,9 @@ def drill_cell(workbook_id: str, addr: str, session: Session = Depends(require_s
2659
  if cell.get("kind") != "bound":
2660
  raise err(409, "literal_no_drill",
2661
  "A hand typed value has no rows behind it.")
 
 
 
2662
 
2663
  try:
2664
  binding = sheet_mod.clean_binding(cell.get("binding"))
@@ -2772,7 +2909,7 @@ def _asked_key(asked, home, fr):
2772
  @router.post("/sheets/{workbook_id}/resolve-bindings")
2773
  def resolve_bindings(workbook_id: str, body: dict = Body(default=None),
2774
  session: Session = Depends(require_session)):
2775
- """`{addr: value}` for the NAMED bound cells only (contract C1, ruling R2).
2776
 
2777
  ⭐⭐ THIS IS THE DOOR THE COMMIT PATH USES, AND ITS WHOLE POINT IS THAT IT IS SMALL.
2778
  Under R2 a formula evaluates in the browser the instant it is committed, so the only thing the
@@ -2788,20 +2925,13 @@ def resolve_bindings(workbook_id: str, body: dict = Body(default=None),
2788
  by THE EXACT STRING THE CALLER ASKED WITH, so a client looks its answer up under the
2789
  reference it already holds and never has to re-derive this file's key spelling.
2790
 
2791
- ⛔⛔ A KEY IS ABSENT WHEN NO BOUND CELL LIVES AT THAT ADDRESS, AND THAT IS THE ONE
2792
- DISTINCTION THE SHAPE CAN CARRY. An address that is empty, holds a typed literal or holds a
2793
- formula is not this door's business - lane A's evaluator already has those values in hand -
2794
- so asking for one costs nothing and answers nothing.
2795
-
2796
- ⛔⛔ AND HERE IS WHAT THE SHAPE CANNOT CARRY, STATED RATHER THAN HIDDEN: a bound cell whose
2797
- binding was REFUSED just now (a database wall, a row wall, a scope condition this database
2798
- cannot compile) comes back as `null`, which is also an empty AVG/MIN/MAX result. An empty
2799
- SUM returns zero. The cause is real and this door knows it; `{addr: value}` has nowhere to put it.
2800
- `POST /sheets/{id}/refresh` and `GET /sheets/{id}` both still carry the full
2801
- `{code, message}` refusal on the cell, so nothing is lost from the document - what is lost is
2802
- the client's ability to paint THIS cell's refusal at commit time. Raised as a dated PRD
2803
- amendment rather than fixed by widening the shape on one lane's authority, because lane A is
2804
- the consumer and a second shape agreed by nobody is worse than a known gap.
2805
 
2806
  ⛔ ONE BAD CELL NEVER FAILS THE BATCH, exactly as in `refresh_sheet`'s bound-cell loop: a
2807
  refusal is caught per cell and the siblings still answer.
@@ -2869,11 +2999,15 @@ def resolve_bindings(workbook_id: str, body: dict = Body(default=None),
2869
  try:
2870
  by_binding[slot] = _resolve_cell_binding(session, binding, book, own_tab,
2871
  view_memo=view_memo)["value"]
2872
- except HTTPException:
2873
- # ⛔ SWALLOWED HERE AND NOWHERE ELSE. See the docstring: the flat body has no
2874
- # room for a cause, and failing the whole batch on one walled cell would take
2875
- # every sibling's number down with it. The same refusal still travels in full on
2876
- # the refresh and read doors, which is where the cell's own sentence comes from.
2877
- by_binding[slot] = None
 
 
 
 
2878
  answer[label] = by_binding[slot]
2879
  return answer
 
221
  if table_key in memo:
222
  return memo[table_key]
223
  try:
224
+ # W62 C2: a placed ut_* view needs its own field vocabulary, without fetching its rows.
225
+ if table_key.startswith("ut_"):
226
+ from routes_tables import ut_assembly
227
+ memo[table_key] = ut_assembly(session, table_key, consume_corrections=False, with_rows=False)
228
+ return memo[table_key]
229
  if table_key == "product_data":
230
  from routes_products import product_assembly
231
  memo[table_key] = product_assembly(session, scope="product",
 
1047
  seen_db[db] = exc
1048
  failure = seen_db.get(db)
1049
  if failure is not None:
1050
+ cell.update(_binding_refusal("database_unreadable", f"You cannot read {db}."))
 
 
 
 
1051
  cell.pop("limits", None)
1052
  continue
1053
 
 
1076
  except HTTPException as exc:
1077
  detail = getattr(exc, "detail", None) or {}
1078
  info = detail.get("error") if isinstance(detail, dict) else None
1079
+ cell.update(_binding_refusal(
1080
+ (info or {}).get("code", "sheet_unresolved"),
1081
+ (info or {}).get("message", "This cell could not be refreshed."),
1082
+ ))
 
 
 
1083
  cell.pop("limits", None)
1084
  continue
1085
  cell["state"] = "fresh"
 
1217
  @router.put("/sheets/index")
1218
  def write_sheet_index(body: dict = Body(default=None),
1219
  session: Session = Depends(require_session)):
1220
+ """D-639 / W62-T25: replace the rail wholesale or merge a placements-only delta.
1221
 
1222
  ⭐ `repairs` RIDES BACK OUT. `core.sheets.save_folders` records every change it made to the
1223
  payload, and the rail says so in a sentence rather than letting a workbook reappear at the
 
1233
  from core import sheets
1234
  raw = dict(body or {})
1235
  try:
1236
+ if "placements" in raw:
1237
+ if set(raw) != {"placements"}:
1238
+ raise sheets.SheetRefusal(
1239
+ "index_request_mixed",
1240
+ "Send placements alone, or send the full Sheet rail with its revision.")
1241
+ out = sheets.merge_placements(_store(session), raw["placements"])
1242
+ else:
1243
+ out = sheets.save_folders(_store(session), raw.get("folders"),
1244
+ raw.get("itemFolders"), starred=raw.get("starred"),
1245
+ expect_rev=raw.get("rev"))
1246
  except sheets.SheetRefusal as exc:
1247
  raise _refuse(exc)
1248
  return {"index": _wire_index({**_index_for(session), "repairs": out.get("repairs", [])})}
 
1344
  made = sheets.create_workbook(runtime, name=book.get("name") or "", created_by=uname,
1345
  on_duplicate="suffix")
1346
  saved = sheets.put_workbook(runtime, made["id"],
1347
+ dict(book, refreshed_at=stamp, rev=made["rev"]), actor=uname,
1348
+ lossless=True)
1349
  _job_set(job_id, state="done", progress=1.0, workbook_id=saved["id"],
1350
  sentence=_import_sentence(report))
1351
  except sheet_import.ImportRefusal as exc:
 
1623
  cell.pop("refusal", None)
1624
  except HTTPException as exc:
1625
  info = ((exc.detail or {}).get("error") or {})
1626
+ cell.update(_binding_refusal(
1627
+ info.get("code", "ending_cell_unreadable"),
1628
+ info.get("message", "The Ending date could not be read. Choose a valid date."),
1629
+ ))
1630
  ending_cells.add((source.get("id"), addr))
1631
  if ending_cells:
1632
  _recompute_formulas(book, fr, sheet_mod)
 
1846
  for addr, cell in (tab.get("cells") or {}).items():
1847
  if not isinstance(cell, dict) or cell.get("kind") != "bound":
1848
  continue
1849
+ if _is_view_binding(cell):
1850
+ continue # C2: a placed view refreshes through its own door
1851
  binding = cell.get("binding") or {}
1852
  db = str(binding.get("database") or "")
1853
  if db not in seen_db:
 
1858
  seen_db[db] = exc
1859
  failure = seen_db.get(db)
1860
  if failure is not None:
1861
+ cell.update(_binding_refusal("database_unreadable", f"You cannot read {db}."))
 
 
 
 
1862
  cell.pop("limits", None)
1863
  continue
1864
  try:
 
1866
  except HTTPException as exc:
1867
  detail = getattr(exc, "detail", None) or {}
1868
  info = detail.get("error") if isinstance(detail, dict) else None
1869
+ cell.update(_binding_refusal(
1870
+ (info or {}).get("code", "sheet_unresolved"),
1871
+ (info or {}).get("message", "This cell could not be refreshed."),
1872
+ ))
 
 
 
1873
  cell.pop("limits", None)
1874
  continue
1875
  cell["state"] = "fresh"
 
1896
  _recompute_formulas(book, fr, sheet_mod)
1897
  recalc_ms = round((perf_counter() - started) * 1000.0, 1)
1898
  try:
1899
+ # R19: book came from get_workbook; clamping on refresh would destroy imported widths.
1900
  saved = sheets.put_workbook(_store(session), workbook_id,
1901
  {"name": book.get("name"), "sheets": book.get("sheets"),
1902
  "refreshed_at": stamp, "rev": book.get("rev")},
1903
  actor=session.uname,
1904
+ actor_name=session.user.get("name") or session.uname,
1905
+ lossless=True)
1906
  except sheets.SheetRefusal as exc:
1907
  raise _refuse(exc)
1908
  # ⭐⭐ R3 / W52-T12: REFRESH IS THE ONE EVENT ALLOWED TO INVALIDATE A READER'S CACHED SCOPE
 
2269
  raise err(400, exc.code, exc.message)
2270
 
2271
 
2272
+ # ⛔⛔ W62-T12 / C2 / R29 — A `mode: "view"` BINDING IS SKIPPED BY EVERY METRIC RESOLVER, AND
2273
+ # SKIPPING IS NOT THE SAME AS REFUSING. A placed view has no scalar value: its rows are read through
2274
+ # `POST /sheets/{id}/view-rows` and PLACED by the client, because the placement is a structure op
2275
+ # only the client can take. Before this guard the refresh door handed a view binding to
2276
+ # `modules/sheet.py::clean_binding`, which REQUIRES an `aggregate`, so `Refresh All` marked every
2277
+ # placed view `refused` and painted "That cell's source is not set up correctly." over a view that
2278
+ # was perfectly well formed. Caught by this lane's own screenshot, not by a gate.
2279
+ def _is_view_binding(cell) -> bool:
2280
+ """True for a C2 placed view, which the metric resolvers must leave exactly as they found it."""
2281
+ binding = (cell or {}).get("binding") if isinstance(cell, dict) else None
2282
+ return isinstance(binding, dict) and binding.get("mode") == "view"
2283
+
2284
+
2285
+ # R48: the persisted code is short; the original cause stays intact in the document.
2286
+ _BINDING_REFUSAL_DISPLAY = {
2287
+ "database_unreadable": "#NO ACCESS",
2288
+ "field_unknown": "#FIELD?",
2289
+ }
2290
+
2291
+
2292
+ def _binding_refusal(code, message):
2293
+ """One refusal shape for compute, refresh and caller-scoped reads of metric cells."""
2294
+ return {
2295
+ "state": "refused",
2296
+ "value": None,
2297
+ "display": _BINDING_REFUSAL_DISPLAY.get(code, "#ERROR!"),
2298
+ "refusal": {"code": code, "message": message},
2299
+ }
2300
+
2301
+
2302
  def _resolve_cell_binding(session, binding, book, tab, **kwargs):
2303
  """Keep the legacy resolver calling convention for bindings without workbook inputs."""
2304
  if _has_cell_inputs(binding):
 
2602
  raise err(404, "cell_missing", f"Cell {key} is not filled in.")
2603
  if cell.get("kind") != "bound":
2604
  raise err(409, "cell_not_bound", f"Cell {key} is not bound to a database.")
2605
+ if _is_view_binding(cell):
2606
+ # C2: a placed view has rows, not a value. Refusing BY NAME beats resolving it as a metric,
2607
+ # which is what painted "That cell's source is not set up correctly." over a good view.
2608
+ raise err(409, "cell_is_a_view",
2609
+ f"Cell {key} holds a view, so it is read through its own rows door.")
2610
 
2611
  tab_ref = str((tab or {}).get("id") or (tab or {}).get("name") or "")
2612
  binding = cell.get("binding") or {}
 
2621
  #: a cell left `stale` would shimmer forever, and the reason belongs on the cell.
2622
  detail = getattr(exc, "detail", None) or {}
2623
  info = detail.get("error") if isinstance(detail, dict) else None
2624
+ saved.update(_binding_refusal(
2625
+ (info or {}).get("code", "sheet_unresolved"),
2626
+ (info or {}).get("message", "This cell could not be refreshed."),
2627
+ ))
 
 
 
2628
  else:
2629
  limits = resolved["limits"]
2630
  saved["state"] = "fresh"
 
2660
  return {"cell": wire, "rev": landed.get("rev"), "tab": tab_ref, "addr": key}
2661
 
2662
 
2663
+ @router.post("/sheets/{workbook_id}/view-rows")
2664
+ def view_rows(workbook_id: str, body: object = Body(default=None),
2665
+ session: Session = Depends(require_session)):
2666
+ """W62 C2 / R29: read the live rows of a placed view under this caller's walls."""
2667
+ from datetime import date
2668
+ from fastapi.responses import JSONResponse
2669
+ from core import perm_scope, sheets, user_tables
2670
+ from modules import sheet as sheet_mod
2671
+
2672
+ try:
2673
+ binding = sheets.clean_view_binding(body.get("binding") if isinstance(body, dict) else None)
2674
+ except sheets.SheetRefusal as exc:
2675
+ return JSONResponse(status_code=400, content={"error": exc.code, "message": exc.message})
2676
+ try:
2677
+ book = sheets.get_workbook(_store(session), workbook_id)
2678
+ except sheets.SheetRefusal as exc:
2679
+ raise _refuse(exc)
2680
+ _require_reader(session, book)
2681
+ database = _require_database(session, binding["database"])
2682
+ fields = list(_registry_assembly(session, database).get("fields") or [])
2683
+ hidden = perm_scope.hidden_keys(session.user, database, fields, st=session.runtime)
2684
+ visible = {field["key"]: field for field in fields if field.get("key") not in hidden}
2685
+ requested = binding["fields"]
2686
+ sorted_keys = {item["field"] for item in binding["sort"]}
2687
+ for key in dict.fromkeys([*requested, *sorted(sorted_keys)]):
2688
+ if key not in visible:
2689
+ return JSONResponse(status_code=400, content={
2690
+ "error": "view_field_unknown", "message": f"Field {key} is not available in this database."})
2691
+
2692
+ # W62 C2: "Filter and sort apply to ALL rows BEFORE limit. total counts every matching row."
2693
+ wall_tree = ((perm_scope.entry(session.user, database) or {}).get("filter")
2694
+ if perm_scope.row_scope_applies(session.user, database) else None)
2695
+ wall_nodes, wall_conj = _fe_parts(wall_tree)
2696
+ scope_nodes, scope_conj = _fe_parts(binding.get("filter"))
2697
+ # W62 C2: a filter-only field obeys the same grants; linked fields have their own resolver wall.
2698
+ for key in sorted(sheet_mod.filter_columns_named(scope_nodes)):
2699
+ if not key.startswith(sheet_mod.LINKED_FILTER_PREFIX) and key not in visible:
2700
+ return JSONResponse(status_code=400, content={
2701
+ "error": "view_field_unknown", "message": f"Field {key} is not available in this database."})
2702
+ today = date.today()
2703
+ try:
2704
+ scope_nodes = _filter_cell_values(session, scope_nodes, book=book, today=today)
2705
+ window = _ending_window(session, binding, book=book, today=today)
2706
+ needed = (set(requested) | sorted_keys | sheet_mod.filter_columns_named(scope_nodes)
2707
+ | sheet_mod.filter_columns_named(wall_nodes))
2708
+ cur, spec, cols = _mirror(session)(database, metric_window=window, needed=needed)
2709
+ cols = dict(cols)
2710
+ scope_nodes = _linked_filter_scope(session, database, scope_nodes, cur, spec, cols, today=today)
2711
+ for key in dict.fromkeys([*requested, *sorted(sorted_keys | sheet_mod.filter_columns_named(scope_nodes))]):
2712
+ if key in hidden or not (cols.get(key) or {}).get("sql"):
2713
+ return JSONResponse(status_code=400, content={
2714
+ "error": "view_field_unknown", "message": f"Field {key} is not available in this database."})
2715
+ # W62 C2: an unanswerable row wall must refuse before either SQL read can widen it.
2716
+ wall_compiled = sheet_mod.compile_scope(wall_nodes, wall_conj, cols, today=today)
2717
+ if sheet_mod.widen_limits(wall_nodes, cols, wall_compiled):
2718
+ raise ValueError("unapplied row wall")
2719
+ count_sql, params, limits = sheet_mod.build_aggregate_query(
2720
+ spec, {"aggregate": {"fn": "count"}}, cols, scope_nodes=scope_nodes,
2721
+ scope_conj=scope_conj, wall_nodes=wall_nodes, wall_conj=wall_conj, today=today)
2722
+ if limits:
2723
+ raise ValueError("unapplied view filter")
2724
+ except sheet_mod.SheetRefusal as exc:
2725
+ return JSONResponse(status_code=400, content={"error": exc.code, "message": exc.message})
2726
+ except ValueError:
2727
+ raise err(409, "scope_not_applicable",
2728
+ "This view uses a restriction that cannot be applied to this database's live connection.")
2729
+
2730
+ # W62 C2 / standing rule 1: "limit caps what is PLACED"; the matching count is unlimited.
2731
+ total = (cur.execute(count_sql, params).fetchone() or [0])[0]
2732
+ # ⭐⭐ W62-T14 — EVERY ROW CARRIES ITS RECORD ID, ALWAYS, AND IT IS NOT A PROJECTED FIELD.
2733
+ # A placed Grid over one of our own tables writes a record back, and the write door is Data's
2734
+ # own `PATCH /api/v1/tables/{database}/rows/{pid}`: without the id the client can only guess
2735
+ # from a row's POSITION in the sheet, which is wrong the moment anyone sorts, filters or
2736
+ # refreshes. So the id rides beside the values under the key `pid` while `fields` still names
2737
+ # only the columns the sheet paints. ⛔ It is the SAME `spec["id"]` expression `build_ids_query`
2738
+ # uses, so the identity here and the identity the drill lists can never be two different things.
2739
+ id_expr = str(spec.get("id") or "").strip()
2740
+ projection = ", ".join([*(cols[key]["sql"] for key in requested),
2741
+ *([id_expr] if id_expr else [])])
2742
+ rows_sql = count_sql.replace("SELECT COUNT(*) FROM", f"SELECT {projection} FROM", 1)
2743
+ if binding["sort"]:
2744
+ # W62 C2 / R30: expressions come only from resolved columns; directions are validated.
2745
+ order = ", ".join(cols[item["field"]]["sql"] + (" ASC" if item["dir"] == "asc" else " DESC")
2746
+ for item in binding["sort"])
2747
+ rows_sql += " ORDER BY " + order
2748
+ rows_sql += f" LIMIT {binding['limit']}"
2749
+ keys = [*requested, *(["pid"] if id_expr else [])]
2750
+ rows = [dict(zip(keys, row)) for row in cur.execute(rows_sql, params).fetchall()]
2751
+ # W62 C2 / R34: Data's _records_or_refuse uses database access (checked above) plus
2752
+ # W62 R34: records_mutable, with no separate edit-role grant; its row/field walls still apply.
2753
+ editable = user_tables.records_mutable(database, st=session.runtime)
2754
+ return {"fields": [{"key": key, "label": visible[key].get("label") or key,
2755
+ "kind": visible[key].get("type") or visible[key].get("kind") or "text"}
2756
+ for key in requested],
2757
+ "rows": rows, "total": int(total or 0), "limit": binding["limit"],
2758
+ "viewType": binding["viewType"], "editable": bool(editable)}
2759
+
2760
+
2761
  @router.get("/sheets/{workbook_id}/cells/{addr}/drill")
2762
  def drill_cell(workbook_id: str, addr: str, session: Session = Depends(require_session)):
2763
  """`{database, view_id?, filter?, record_ids, count}` for `LinkGridModal` (R6, R13, R17).
 
2793
  if cell.get("kind") != "bound":
2794
  raise err(409, "literal_no_drill",
2795
  "A hand typed value has no rows behind it.")
2796
+ if _is_view_binding(cell):
2797
+ raise err(409, "cell_is_a_view",
2798
+ f"Cell {key} holds a view, so its rows are already on the sheet.")
2799
 
2800
  try:
2801
  binding = sheet_mod.clean_binding(cell.get("binding"))
 
2909
  @router.post("/sheets/{workbook_id}/resolve-bindings")
2910
  def resolve_bindings(workbook_id: str, body: dict = Body(default=None),
2911
  session: Session = Depends(require_session)):
2912
+ """Values or named refusals for the NAMED bound cells only (contract C1, rulings R2 and R48).
2913
 
2914
  ⭐⭐ THIS IS THE DOOR THE COMMIT PATH USES, AND ITS WHOLE POINT IS THAT IT IS SMALL.
2915
  Under R2 a formula evaluates in the browser the instant it is committed, so the only thing the
 
2925
  by THE EXACT STRING THE CALLER ASKED WITH, so a client looks its answer up under the
2926
  reference it already holds and never has to re-derive this file's key spelling.
2927
 
2928
+ A KEY IS ABSENT WHEN NO BOUND CELL LIVES AT THAT ADDRESS. An address that is empty, holds a
2929
+ typed literal or holds a formula is not this door's business - lane A's evaluator already
2930
+ has those values in hand - so asking for one costs nothing and answers nothing.
2931
+
2932
+ R48: a refused binding answers `{value: null, refusal: {code, message}}`, so it cannot be
2933
+ mistaken for a legitimate empty aggregate. The flat shape is kept for every address that
2934
+ has an answer, including a genuine null, so no existing reader of those answers changes.
 
 
 
 
 
 
 
2935
 
2936
  ⛔ ONE BAD CELL NEVER FAILS THE BATCH, exactly as in `refresh_sheet`'s bound-cell loop: a
2937
  refusal is caught per cell and the siblings still answer.
 
2999
  try:
3000
  by_binding[slot] = _resolve_cell_binding(session, binding, book, own_tab,
3001
  view_memo=view_memo)["value"]
3002
+ except HTTPException as exc:
3003
+ detail = getattr(exc, "detail", None) or {}
3004
+ info = detail.get("error") if isinstance(detail, dict) else None
3005
+ by_binding[slot] = {
3006
+ "value": None,
3007
+ "refusal": {
3008
+ "code": (info or {}).get("code", "sheet_unresolved"),
3009
+ "message": (info or {}).get("message", "This cell could not be refreshed."),
3010
+ },
3011
+ }
3012
  answer[label] = by_binding[slot]
3013
  return answer
api/routes_starred.py CHANGED
@@ -208,7 +208,29 @@ def _scan_starred_views(session, keys=None, cache=None):
208
  import core.view_templates as view_templates
209
 
210
  granted = routes_nav._granted_view_ids(session)
211
- out = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  for key in order:
213
  doc = docs.get(key)
214
  if doc is None:
@@ -217,8 +239,10 @@ def _scan_starred_views(session, keys=None, cache=None):
217
  if not ws_key:
218
  continue
219
  views = table_store.make(ws_key, st=session.runtime)
220
- for vid, view in routes_nav._visible_views(doc, session.uname, session.admin,
221
- granted, views).items():
 
 
222
  cfg = view.get("config") or {}
223
  if cfg.get("important") is True:
224
  out.append({"id": vid, "database": key,
 
208
  import core.view_templates as view_templates
209
 
210
  granted = routes_nav._granted_view_ids(session)
211
+ # ⭐⭐ W62-T17 (D-756) — EVERY GRANTED VIEW ID WAS RESOLVED ONCE PER DATABASE, and that loop is
212
+ # where `/starred`'s budget went. MEASURED on staging's Royal Imports, 26 databases
213
+ # (`AutoWiki/waves/wave62/proto/T17-profile.md`): 4,844 ms total, of which `_visible_views` was
214
+ # 3,075 ms — `object_shares` read 28 times (1,117 ms) and `TableStore.find_view` 26 times
215
+ # (2,072 ms), for ONE granted id. Neither figure is about a slow read: the grant registry is
216
+ # 8 KB and each read is a single ~40 ms round trip. They are about the same question being
217
+ # asked once per database.
218
+ #
219
+ # ⭐ A VIEW LIVES IN EXACTLY ONE DATABASE. Once a database has resolved a granted id, every
220
+ # LATER database in the scan is being asked a question whose answer cannot be yes — and each
221
+ # of those "no"s costs a `shares.may_see` read plus a full workspace-document read through
222
+ # `find_view`. Dropping resolved ids from the set handed on narrows only the LOOKUPS, never
223
+ # the answer: `_visible_views` still returns this caller's own views for every database, and a
224
+ # granted view is still admitted by `shares.may_see` before it is looked up at all.
225
+ #
226
+ # ⛔ AND THE OBVIOUS SECOND SAVING IS NOT AVAILABLE: lending `object_shares` for the pass
227
+ # (`user_tables.lend`) would collapse those 28 reads to one, but `TableStore.find_view` reaches
228
+ # `migrate_legacy_shared_views`, which WRITES grants and then READS THEM BACK to verify them. A
229
+ # lent snapshot would serve the pre-write value to that readback and the migration would raise
230
+ # `LegacySharedViewMigrationError` on any tenant that still has legacy shared views — a 500 on
231
+ # `/starred` in exchange for a few hundred milliseconds. `_Lent`'s own contract says it may
232
+ # only serve code "proven not to mutate" the lent key; this path is not that code.
233
+ resolved, out = set(), []
234
  for key in order:
235
  doc = docs.get(key)
236
  if doc is None:
 
239
  if not ws_key:
240
  continue
241
  views = table_store.make(ws_key, st=session.runtime)
242
+ pending = granted - resolved
243
+ found = routes_nav._visible_views(doc, session.uname, session.admin, pending, views)
244
+ resolved |= pending & set(found)
245
+ for vid, view in found.items():
246
  cfg = view.get("config") or {}
247
  if cfg.get("important") is True:
248
  out.append({"id": vid, "database": key,
platform/core/external_access.py CHANGED
@@ -1,8 +1,9 @@
1
- """Per-user credentials for the governed external read and build surface.
 
2
 
3
- The credential is authentication only. Verification reconstructs the same PUBLIC user record
4
- the normal API session carries, so every later database read still goes through ``perm_scope``
5
- and the existing Assistant mirror. This module never reads product rows and never caches a
6
  credential, user, bucket, or tenant runtime.
7
  """
8
  import calendar
@@ -17,6 +18,11 @@ from harness import runtime
17
 
18
 
19
  BUCKET = "external_access"
 
 
 
 
 
20
  ALGORITHM = "sha256-salt-v1"
21
  AUTH_ERROR = "invalid_external_credential"
22
  _DUMMY_SALT = bytes(32)
@@ -48,6 +54,50 @@ class ExternalAuthError(ExternalAccessError):
48
  """A uniform authentication refusal that reveals no credential or tenant detail."""
49
 
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  @dataclass(frozen=True)
52
  class VerifiedCredential:
53
  """The authenticated public principal plus the request-scoped tenant runtime."""
@@ -56,6 +106,8 @@ class VerifiedCredential:
56
  key_id: str
57
  user: dict
58
  runtime: object
 
 
59
 
60
 
61
  def _now() -> str:
@@ -130,12 +182,15 @@ def _active_public_user(username: str, tenant: str) -> dict:
130
 
131
  def _metadata(record: dict) -> dict:
132
  """Return list-safe metadata. Salt, digest, algorithm and owner never cross this seam."""
 
133
  return {
134
  "id": record.get("id"),
135
  "label": record.get("label"),
136
  "created": record.get("created"),
137
  "last_used": record.get("last_used"),
138
  "revoked_at": record.get("revoked_at"),
 
 
139
  }
140
 
141
 
@@ -150,8 +205,10 @@ def label_for(st, key_id: str) -> str:
150
  return label
151
 
152
 
153
- def mint(st, username: str, tenant: str, label: str) -> tuple[dict, str]:
154
  """Create one credential and return ``(metadata, token)``; the token is never persisted."""
 
 
155
  owner, tenant_key = _normalise_owner(username, tenant)
156
  _assert_bound_runtime(st, tenant_key)
157
  _active_public_user(owner, tenant_key)
@@ -179,6 +236,8 @@ def mint(st, username: str, tenant: str, label: str) -> tuple[dict, str]:
179
  "username": owner,
180
  "tenant": tenant_key,
181
  "label": clean_label,
 
 
182
  "salt": salt.hex(),
183
  "hash": _digest(salt, secret),
184
  "algo": ALGORITHM,
@@ -306,8 +365,10 @@ def verify(token: str) -> VerifiedCredential:
306
  except ExternalAccessError as exc:
307
  raise ExternalAuthError(AUTH_ERROR) from exc
308
 
 
309
  if not _stamp_is_due(record.get("last_used"), time.time()):
310
- return VerifiedCredential(tenant=tenant_key, key_id=key_id, user=public, runtime=st)
 
311
 
312
  used_at = _now()
313
 
@@ -332,7 +393,8 @@ def verify(token: str) -> VerifiedCredential:
332
  raise
333
  except Exception as exc:
334
  raise ExternalAuthError(AUTH_ERROR) from exc
335
- return VerifiedCredential(tenant=tenant_key, key_id=key_id, user=public, runtime=st)
 
336
  except ExternalAuthError:
337
  raise
338
  except Exception as exc:
 
1
+ """Per-user credentials carrying an access level and database subset for governed reads and
2
+ builds, with the maker's live grants still applying on top.
3
 
4
+ Verification reconstructs the same PUBLIC user record the normal API session carries, so every
5
+ later database read still goes through ``perm_scope`` and the existing Assistant mirror.
6
+ This module never reads product rows and never caches a
7
  credential, user, bucket, or tenant runtime.
8
  """
9
  import calendar
 
18
 
19
 
20
  BUCKET = "external_access"
21
+ ACCESS_READ = "read"
22
+ ACCESS_READWRITE = "readwrite"
23
+ ACCESS_LEVELS = (ACCESS_READ, ACCESS_READWRITE)
24
+ ALL_DATABASES = "all"
25
+ MAX_SCOPE_DATABASES = 200
26
  ALGORITHM = "sha256-salt-v1"
27
  AUTH_ERROR = "invalid_external_credential"
28
  _DUMMY_SALT = bytes(32)
 
54
  """A uniform authentication refusal that reveals no credential or tenant detail."""
55
 
56
 
57
+ def normalise_access(value) -> str:
58
+ if value is None or value == "":
59
+ return ACCESS_READWRITE
60
+ if value in ACCESS_LEVELS:
61
+ return value
62
+ raise ExternalAccessError("external_access_scope_invalid")
63
+
64
+
65
+ def normalise_databases(value):
66
+ if value is None or (isinstance(value, str) and value.strip().lower() == ALL_DATABASES):
67
+ return ALL_DATABASES
68
+ if not isinstance(value, (list, tuple)) or not 1 <= len(value) <= MAX_SCOPE_DATABASES:
69
+ raise ExternalAccessError("external_databases_invalid")
70
+ if any(not isinstance(item, str) or not item.strip() or len(item.strip()) > 200
71
+ for item in value):
72
+ raise ExternalAccessError("external_databases_invalid")
73
+ return tuple(dict.fromkeys(item.strip() for item in value))
74
+
75
+
76
+ def scope_of(record):
77
+ """Read legacy defaults, but preserve a stored empty subset as no database access."""
78
+ record = record if isinstance(record, dict) else {}
79
+ access = record.get("access")
80
+ if access not in ACCESS_LEVELS:
81
+ access = ACCESS_READWRITE
82
+ databases = record.get("databases")
83
+ if isinstance(databases, (list, tuple)):
84
+ databases = tuple(item.strip() for item in databases
85
+ if isinstance(item, str) and item.strip())
86
+ else:
87
+ databases = ALL_DATABASES
88
+ return access, databases
89
+
90
+
91
+ def may_write(access) -> bool:
92
+ return access == ACCESS_READWRITE
93
+
94
+
95
+ def database_allowed(databases, database) -> bool:
96
+ if databases == ALL_DATABASES:
97
+ return True
98
+ return isinstance(database, str) and bool(database.strip()) and database.strip() in databases
99
+
100
+
101
  @dataclass(frozen=True)
102
  class VerifiedCredential:
103
  """The authenticated public principal plus the request-scoped tenant runtime."""
 
106
  key_id: str
107
  user: dict
108
  runtime: object
109
+ access: str = ACCESS_READWRITE
110
+ databases: object = ALL_DATABASES
111
 
112
 
113
  def _now() -> str:
 
182
 
183
  def _metadata(record: dict) -> dict:
184
  """Return list-safe metadata. Salt, digest, algorithm and owner never cross this seam."""
185
+ access, databases = scope_of(record)
186
  return {
187
  "id": record.get("id"),
188
  "label": record.get("label"),
189
  "created": record.get("created"),
190
  "last_used": record.get("last_used"),
191
  "revoked_at": record.get("revoked_at"),
192
+ "access": access,
193
+ "databases": ALL_DATABASES if databases == ALL_DATABASES else list(databases),
194
  }
195
 
196
 
 
205
  return label
206
 
207
 
208
+ def mint(st, username: str, tenant: str, label: str, access=None, databases=None) -> tuple[dict, str]:
209
  """Create one credential and return ``(metadata, token)``; the token is never persisted."""
210
+ access = normalise_access(access)
211
+ databases = normalise_databases(databases)
212
  owner, tenant_key = _normalise_owner(username, tenant)
213
  _assert_bound_runtime(st, tenant_key)
214
  _active_public_user(owner, tenant_key)
 
236
  "username": owner,
237
  "tenant": tenant_key,
238
  "label": clean_label,
239
+ "access": access,
240
+ "databases": ALL_DATABASES if databases == ALL_DATABASES else list(databases),
241
  "salt": salt.hex(),
242
  "hash": _digest(salt, secret),
243
  "algo": ALGORITHM,
 
365
  except ExternalAccessError as exc:
366
  raise ExternalAuthError(AUTH_ERROR) from exc
367
 
368
+ access, databases = scope_of(record)
369
  if not _stamp_is_due(record.get("last_used"), time.time()):
370
+ return VerifiedCredential(tenant=tenant_key, key_id=key_id, user=public, runtime=st,
371
+ access=access, databases=databases)
372
 
373
  used_at = _now()
374
 
 
393
  raise
394
  except Exception as exc:
395
  raise ExternalAuthError(AUTH_ERROR) from exc
396
+ return VerifiedCredential(tenant=tenant_key, key_id=key_id, user=public, runtime=st,
397
+ access=access, databases=databases)
398
  except ExternalAuthError:
399
  raise
400
  except Exception as exc:
platform/core/relations.py CHANGED
@@ -265,6 +265,20 @@ def _link_bag(field):
265
  return bag if isinstance(bag, dict) else None
266
 
267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  def _entry(key, label, target, direction, field=None, on=None, frm=None, served=True,
269
  where=None, cardinality=None):
270
  """ONE `/related` entry, in C6's shape.
 
265
  return bag if isinstance(bag, dict) else None
266
 
267
 
268
+ def declared_through(link):
269
+ """R50 / C4: return the intermediate of a complete declared two-hop link, or ''.
270
+
271
+ The intermediate is a join, not a destination. R50 says grants on both ends suffice;
272
+ intermediate fields are never projected, returned or rendered. An incomplete through
273
+ bag is not a declared two-hop link and earns no traversal admission. Manual links do
274
+ not declare a traversal either.
275
+ """
276
+ if (isinstance(link, dict) and link.get('through') and link.get('throughOn')
277
+ and link.get('throughTo') and link.get('selectionMode') != 'manual'):
278
+ return str(link['through'])
279
+ return ''
280
+
281
+
282
  def _entry(key, label, target, direction, field=None, on=None, frm=None, served=True,
283
  where=None, cardinality=None):
284
  """ONE `/related` entry, in C6's shape.
platform/core/sheet_structure.py CHANGED
@@ -51,8 +51,10 @@ def parse_ref(text: str) -> dict | None:
51
  "col": col.upper(), "rowAbs": row_abs == "$", "row": int(row)}
52
 
53
 
54
- def format_ref(ref: dict) -> str:
55
  """Format a CellRef, preserving dollar marks and quoting non-bare sheet names."""
 
 
56
  body = (f"{'$' if ref['colAbs'] else ''}{ref['col']}"
57
  f"{'$' if ref['rowAbs'] else ''}{ref['row']}")
58
  sheet = ref["sheet"]
@@ -62,7 +64,8 @@ def format_ref(ref: dict) -> str:
62
  return name + "!" + body
63
 
64
 
65
- def rewrite_refs(text: str, rewrite: Callable[[dict], dict]) -> str:
 
66
  """Walk text exactly as a1.ts::rewriteRefs; strings and function names survive."""
67
  src = str(text or "")
68
  out = []
@@ -90,6 +93,15 @@ def rewrite_refs(text: str, rewrite: Callable[[dict], dict]) -> str:
90
  if match and not _FUNCTION.match(src, match.end()):
91
  ref = parse_ref(match[0])
92
  if ref:
 
 
 
 
 
 
 
 
 
93
  out.append(format_ref(rewrite(ref)))
94
  i = match.end()
95
  continue
@@ -98,14 +110,13 @@ def rewrite_refs(text: str, rewrite: Callable[[dict], dict]) -> str:
98
  return "".join(out)
99
 
100
 
101
- def shift_index(value: int, at: int, delta: int) -> int:
102
- """References in a deleted band point at its deletion point, never at #REF!."""
103
- if value < at:
104
- return value
105
- if delta > 0:
106
- return value + delta
107
- past = at - delta
108
- return max(1, at if value < past else value + delta)
109
 
110
 
111
  def _same_name(left: str, right: str) -> bool:
@@ -121,15 +132,38 @@ def shift_for_structure(text: str, shift: dict, own_sheet: str, *, bare: bool =
121
  if not shift["delta"] or (bare and parse_ref(text) is None):
122
  return str(text or "")
123
 
 
 
 
 
 
 
124
  def rewrite(ref):
125
  if not _same_name(ref["sheet"] or own_sheet, shift["sheet"]):
126
  return ref
127
- if shift["axis"] == "row":
128
- return {**ref, "row": shift_index(ref["row"], shift["at"], shift["delta"])}
129
- return {**ref, "col": index_to_col(shift_index(
130
- col_to_index(ref["col"]), shift["at"], shift["delta"]))}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
- return rewrite_refs(text, rewrite)
 
133
 
134
 
135
  def _moved_index(value: int, at: int, delta: int) -> int | None:
@@ -246,8 +280,8 @@ def _move_charts(tab: dict, tab_id: str, op: dict) -> None:
246
  for key in ("geometry", "anchor"):
247
  geometry = chart.get(key)
248
  if isinstance(geometry, dict) and op["axis"] in geometry:
249
- geometry[op["axis"]] = shift_index(
250
- geometry[op["axis"]] + 1, op["at"], op["delta"]) - 1
251
 
252
 
253
  def apply_structure(book: dict, tab_id: str, op: dict) -> dict:
 
51
  "col": col.upper(), "rowAbs": row_abs == "$", "row": int(row)}
52
 
53
 
54
+ def format_ref(ref: dict | str) -> str:
55
  """Format a CellRef, preserving dollar marks and quoting non-bare sheet names."""
56
+ if isinstance(ref, str):
57
+ return ref
58
  body = (f"{'$' if ref['colAbs'] else ''}{ref['col']}"
59
  f"{'$' if ref['rowAbs'] else ''}{ref['row']}")
60
  sheet = ref["sheet"]
 
64
  return name + "!" + body
65
 
66
 
67
+ def rewrite_refs(text: str, rewrite: Callable[[dict], dict | str],
68
+ rewrite_range: Callable[[dict, dict, str], str] | None = None) -> str:
69
  """Walk text exactly as a1.ts::rewriteRefs; strings and function names survive."""
70
  src = str(text or "")
71
  out = []
 
93
  if match and not _FUNCTION.match(src, match.end()):
94
  ref = parse_ref(match[0])
95
  if ref:
96
+ separator = re.match(r"\s*:\s*", src[match.end():]) if rewrite_range else None
97
+ if separator:
98
+ end = _REF.match(src, match.end() + separator.end())
99
+ if end and not _FUNCTION.match(src, end.end()):
100
+ last = parse_ref(end[0])
101
+ if last:
102
+ out.append(rewrite_range(ref, last, separator[0]))
103
+ i = end.end()
104
+ continue
105
  out.append(format_ref(rewrite(ref)))
106
  i = match.end()
107
  continue
 
110
  return "".join(out)
111
 
112
 
113
+ def shift_index(value: int, at: int, delta: int) -> int | None:
114
+ """R49 retires the clamp: both grammars already parse #REF! as an error token.
115
+
116
+ The feared bad_formula cannot occur. Deleted indices return None; only a range
117
+ with surviving cells may clamp its deleted endpoint and shrink.
118
+ """
119
+ return _moved_index(value, at, delta)
 
120
 
121
 
122
  def _same_name(left: str, right: str) -> bool:
 
132
  if not shift["delta"] or (bare and parse_ref(text) is None):
133
  return str(text or "")
134
 
135
+ def index(ref):
136
+ return ref["row"] if shift["axis"] == "row" else col_to_index(ref["col"])
137
+
138
+ def at_index(ref, value):
139
+ return {**ref, shift["axis"]: value if shift["axis"] == "row" else index_to_col(value)}
140
+
141
  def rewrite(ref):
142
  if not _same_name(ref["sheet"] or own_sheet, shift["sheet"]):
143
  return ref
144
+ moved = shift_index(index(ref), shift["at"], shift["delta"])
145
+ return "#REF!" if moved is None else at_index(ref, moved)
146
+
147
+ def rewrite_range(first, last, separator):
148
+ sheet = first["sheet"] or own_sheet
149
+ if last["sheet"] and not _same_name(sheet, last["sheet"]):
150
+ return format_ref(rewrite(first)) + separator + format_ref(rewrite(last))
151
+ # A bare right endpoint inherits the left endpoint's sheet, not the formula's tab.
152
+ if not _same_name(sheet, shift["sheet"]):
153
+ return format_ref(first) + separator + format_ref(last)
154
+ start, end = index(first), index(last)
155
+ low, high = min(start, end), max(start, end)
156
+ if low >= shift["at"] and high < shift["at"] - shift["delta"]:
157
+ return "#REF!"
158
+
159
+ def move(value):
160
+ moved = shift_index(value, shift["at"], shift["delta"])
161
+ return moved if moved is not None else shift["at"] if value == low else shift["at"] - 1
162
+
163
+ return format_ref(at_index(first, move(start))) + separator + format_ref(at_index(last, move(end)))
164
 
165
+ # Insertions keep the existing per-reference scan; range handling is deletion-only.
166
+ return rewrite_refs(text, rewrite, rewrite_range if shift["delta"] < 0 else None)
167
 
168
 
169
  def _moved_index(value: int, at: int, delta: int) -> int | None:
 
280
  for key in ("geometry", "anchor"):
281
  geometry = chart.get(key)
282
  if isinstance(geometry, dict) and op["axis"] in geometry:
283
+ moved = shift_index(geometry[op["axis"]] + 1, op["at"], op["delta"])
284
+ geometry[op["axis"]] = (op["at"] if moved is None else moved) - 1
285
 
286
 
287
  def apply_structure(book: dict, tab_id: str, op: dict) -> dict:
platform/core/sheets.py CHANGED
@@ -93,6 +93,11 @@ WRITE_LOG_REVS = 200
93
  CELL_KINDS = ("literal", "formula", "bound", "empty")
94
  CELL_STATES = ("fresh", "stale", "typed", "refused")
95
 
 
 
 
 
 
96
  #: A literal is ALWAYS this state (R19). Stated once, here, so no caller has to remember it.
97
  #: ⚠ AN `empty` CELL TAKES THE SAME STATE, deliberately: it holds no binding, so `stale` would say
98
  #: a refresh is owed for a value that does not exist, and a reader counting stale cells would
@@ -261,6 +266,7 @@ _MAX_DECIMALS = 10
261
  #: constants, which is why nothing could grow a sheet or remember a dragged column: there was
262
  #: nowhere to put the answer. These are the DEFAULTS a sheet is created with and the ceiling it may
263
  #: grow to, and `web/src/sheet/types.ts` mirrors the three defaults.
 
264
  #:
265
  #: ⚠ THE CEILING IS A RENDERING BUDGET, NOT A GRAMMAR LIMIT. `_ADDR` below already admits three
266
  #: column letters and seven row digits, and `a1.ts` agrees with it; 702 is the last TWO letter
@@ -273,7 +279,7 @@ MIN_SHEET_COLS = 1
273
  MIN_SHEET_ROWS = 1
274
  MAX_SHEET_COLS = 702
275
  MAX_SHEET_ROWS = 100000
276
- MIN_COL_WIDTH = 40
277
  MAX_COL_WIDTH = 1000
278
 
279
  #: A column key in `colWidths`. Letters only: a WIDTH belongs to a column, and a row number there
@@ -690,6 +696,55 @@ def _clean_sparkline(raw):
690
  return {"kind": kind, "range": rect}
691
 
692
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
693
  def clean_cell(raw, addr=""):
694
  """Normalize ONE cell, or raise `SheetRefusal` with a named code.
695
 
@@ -735,7 +790,17 @@ def clean_cell(raw, addr=""):
735
  if meta and meta.get("kind", "normal") not in ("normal", "array", "shared", "dataTable"):
736
  raise SheetRefusal("cell_formula_kind_unknown", "That formula representation is not supported.")
737
  binding = raw.get("binding")
738
- if isinstance(binding, dict):
 
 
 
 
 
 
 
 
 
 
739
  for tag in ("kind", "mode"):
740
  if tag in binding and binding[tag] not in ("number", "column"):
741
  raise SheetRefusal("cell_binding_kind_unknown", "A cell binding must choose Number or Column.")
@@ -785,7 +850,7 @@ def clean_cell(raw, addr=""):
785
  cell["value"] = _json_safe(raw.get("value"), "cell value")
786
 
787
  for key in ("binding", "source", "refusal"):
788
- blob = raw.get(key)
789
  if blob is None:
790
  continue
791
  if not isinstance(blob, dict):
@@ -888,12 +953,19 @@ def _clean_col_widths(raw, cols, *, lossless=False):
888
  "Column " + (letters or str(key)) + " is not a column letter.")
889
  if isinstance(value, bool) or not isinstance(value, (int, float)):
890
  if lossless:
891
- raise SheetRefusal("col_width_invalid", "A column width must be a finite positive size.")
892
  continue
893
  if not math.isfinite(value):
894
  raise SheetRefusal("col_width_invalid", "A column width must be a finite size.")
895
- if lossless and value <= 0:
896
- raise SheetRefusal("col_width_invalid", "A column width must be a finite positive size.")
 
 
 
 
 
 
 
897
  width = value if lossless else max(MIN_COL_WIDTH, min(MAX_COL_WIDTH, int(value)))
898
  if lossless or width != DEFAULT_COL_WIDTH:
899
  out[letters] = width
@@ -1204,15 +1276,18 @@ def _clean_base_row_height(raw):
1204
  return raw
1205
 
1206
 
1207
- def _clean_row_heights(raw):
1208
  if raw is None:
1209
  return {}
1210
  out = _document_object(raw, "sheet_row_heights")
1211
  for row, height in out.items():
1212
  if not re.fullmatch(r"[1-9][0-9]*", str(row)) or int(row) > DOCUMENT_MAX_ROWS \
1213
  or isinstance(height, bool) or not isinstance(height, (int, float)) \
1214
- or not math.isfinite(height) or height <= 0:
1215
  raise SheetRefusal("sheet_row_height_invalid", "A row height needs a row number and a positive size.")
 
 
 
1216
  return out
1217
 
1218
 
@@ -1329,7 +1404,7 @@ def _clean_sheet(raw, index=0, *, lossless=False):
1329
  "charts": _clean_charts(raw.get("charts")),
1330
  "imported": _clean_imported(raw.get("imported")),
1331
  "rowHeight": _clean_base_row_height(raw.get("rowHeight")),
1332
- "rowHeights": _clean_row_heights(raw.get("rowHeights")),
1333
  "visibility": visibility,
1334
  "view": _clean_view(raw.get("view")),
1335
  "print": _clean_print(raw.get("print")),
@@ -1371,7 +1446,7 @@ def _clean_sheets(raw, *, lossless=False):
1371
 
1372
  # ── the workbook ─────────────────────────────────────────────────────────────────────────────
1373
 
1374
- def migrate_workbook(raw):
1375
  """Pure unversioned/v0 -> v1 migration; validate current documents without recalculating.
1376
 
1377
  A read never writes or changes `rev`, timestamps or cached results. Unknown versions
@@ -1395,7 +1470,7 @@ def migrate_workbook(raw):
1395
  if book.get("print") is not None:
1396
  book["print"] = _clean_print(book["print"])
1397
  book["schemaVersion"] = SHEET_SCHEMA_VERSION
1398
- book["sheets"] = _clean_sheets(raw.get("sheets"), lossless=True)
1399
  return _json_safe(book, "workbook")
1400
 
1401
 
@@ -1564,7 +1639,7 @@ def get_workbook(st, workbook_id):
1564
  return _carry_write_logs(migrate_workbook(doc), doc)
1565
 
1566
 
1567
- def put_workbook(st, workbook_id, raw, expect_rev=None, *, actor="", actor_name=""):
1568
  """Replace a workbook's name and sheets, bumping `rev`.
1569
 
1570
  ⛔ `id`, `created_by`, `access` and `created_at` are PRIOR-WINS: a client may not reassign a workbook by
@@ -1586,7 +1661,8 @@ def put_workbook(st, workbook_id, raw, expect_rev=None, *, actor="", actor_name=
1586
  if expect_rev is False:
1587
  expect_rev = None
1588
 
1589
- incoming = migrate_workbook(raw)
 
1590
  sheets = incoming["sheets"]
1591
  name = _text(raw.get("name"), _MAX_NAME)
1592
  refreshed_at = raw.get("refreshed_at")
@@ -1977,6 +2053,7 @@ def _index_row(book):
1977
  "id": book.get("id") or "",
1978
  "name": book.get("name") or "",
1979
  "created_by": book.get("created_by") or "",
 
1980
  "created_at": book.get("created_at") or "",
1981
  "updated_at": book.get("updated_at") or "",
1982
  "rev": int(book.get("rev") or 0),
@@ -2036,9 +2113,11 @@ def narrow_workbook(st, workbook_id):
2036
  if not state.get("id"):
2037
  raise SheetRefusal("workbook_missing", "That workbook no longer exists.")
2038
  state.setdefault("access", "private")
2039
- return state, None
2040
 
2041
- _persist(st, workbook_key(wid), _apply)
 
 
2042
 
2043
 
2044
  def workbook_shares(st, workbook_id):
@@ -2094,8 +2173,8 @@ def workbook_role(st, book, viewer, *, is_admin=False, rec=None):
2094
  def may_read_workbook(book, role):
2095
  """R28: a role admits a reader; unmarked or creatorless documents remain legacy-visible.
2096
 
2097
- Creation and explicit sharing stamp access. Read the document every time:
2098
- _index_upsert rebuilds its row after every save, and PUT must preserve marker absence too.
2099
  Legacy visibility grants no ownership or editing role.
2100
  """
2101
  return bool(role) or "access" not in book or not book.get("created_by")
@@ -2104,7 +2183,7 @@ def may_read_workbook(book, role):
2104
  def project_shares(st, rows, viewer=None, *, is_admin=False, role_on_workbook=None):
2105
  """Join `shares` onto a list of index rows. Returns NEW rows; the stored ones are untouched.
2106
 
2107
- A named viewer filters rows against each live workbook document and receives their role.
2108
  The route supplies its existing role helper; core callers use workbook_role directly.
2109
  `list_workbooks` itself stays a bare pointer list on purpose:
2110
  `iter_workbooks` walks it to answer W49-T10's dependents question, and paying a grant-registry
@@ -2121,22 +2200,12 @@ def project_shares(st, rows, viewer=None, *, is_admin=False, role_on_workbook=No
2121
  the document on every save, and `workbook_role` reads nothing else; so does the route's
2122
  injected helper. The third is `may_read_workbook`'s legacy-visibility clause, `"access" not in
2123
  book`, and it is consulted ONLY when the viewer has no role at all AND the row names a
2124
- creator — the rows that are otherwise about to be REFUSED. That case still reads the document,
2125
- because admitting a row wrongly is the failure that matters here.
2126
-
2127
- ⚠ ONE BEHAVIOUR NARROWS, AND IT IS NOT A SIDE EFFECT. The old read also filtered out a
2128
- pointer row whose DOCUMENT IS GONE, as a by-product of needing the document rather than as a
2129
- designed guard — the other caller of this function passes no viewer and has never had it.
2130
- That filter now applies to every viewer EXCEPT one already holding a role without asking the
2131
- document: an admin, the row's own creator, or the holder of a grant. Measured, not reasoned:
2132
- a ghost still disappears for a stranger and for a viewer whose grants are on other rows; it
2133
- survives only for the admin, who may read everything anyway.
2134
- ⛔ AND THE DIRECTION IS THE SAFE ONE. A row can only survive that could not have been REFUSED
2135
- on its contents — `access` is consulted for every viewer whose admission actually depends on
2136
- it. Opening a ghost answers `workbook_missing` through `_require_reader`, which reads the
2137
- document for real, and `_index_drop` removes the row with the document, so a ghost needs a
2138
- torn write to exist at all. A stale row in an admin's list until the next index write is a
2139
- far smaller defect than 12.5 seconds on every Sheet open.
2140
  """
2141
  out = []
2142
  bulk = {}
@@ -2161,9 +2230,16 @@ def project_shares(st, rows, viewer=None, *, is_admin=False, role_on_workbook=No
2161
  role = (role_on_workbook(light) if role_on_workbook is not None
2162
  else workbook_role(st, light, viewer, is_admin=is_admin, rec=rec))
2163
  if not role and light["created_by"]:
2164
- book = _read(st, workbook_key(row["id"]))
2165
- if not book or not book.get("id") or not may_read_workbook(book, role):
2166
- continue
 
 
 
 
 
 
 
2167
  joined["role"] = role or "view"
2168
  joined["shares"] = shares_from_record(rec)
2169
  out.append(joined)
@@ -2659,8 +2735,8 @@ def read_index(st, viewer=None, *, is_admin=False, role_on_workbook=None):
2659
  so a `rev` here without the check there (or the check without this) is a guard nothing can
2660
  reach ([[a-rev-guard-inert-on-the-events-channel]]). The pair lands together or not at all.
2661
 
2662
- ⚠ WHICH WRITES MOVE IT IS PART OF THE CONTRACT: `save_folders` and `_index_drop`, which are
2663
- the two that rewrite the folder, placement and star strata this guard protects.
2664
  `_index_upsert` deliberately does NOT, because it is called by `create_workbook`,
2665
  `put_workbook` AND `patch_cells` — bumping there would make every cell edit 409 a folder drag
2666
  that touched nothing the guard is about.
@@ -2772,3 +2848,52 @@ def save_folders(st, folders, item_folders, starred=None, expect_rev=None):
2772
  result["workbooks"] = project_shares(st, result.get("workbooks"))
2773
  result["repairs"] = repairs
2774
  return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  CELL_KINDS = ("literal", "formula", "bound", "empty")
94
  CELL_STATES = ("fresh", "stale", "typed", "refused")
95
 
96
+ # W62 C2 / R31: "every view type can be placed" inside the binding.
97
+ VIEW_BINDING_TYPES = ("grid", "kanban", "map", "gallery", "timeline", "list", "calendar", "catalog", "swipe")
98
+ VIEW_BINDING_LIMIT_DEFAULT = 100
99
+ VIEW_BINDING_LIMIT_MAX = 10000
100
+
101
  #: A literal is ALWAYS this state (R19). Stated once, here, so no caller has to remember it.
102
  #: ⚠ AN `empty` CELL TAKES THE SAME STATE, deliberately: it holds no binding, so `stale` would say
103
  #: a refresh is owed for a value that does not exist, and a reader counting stale cells would
 
266
  #: constants, which is why nothing could grow a sheet or remember a dragged column: there was
267
  #: nowhere to put the answer. These are the DEFAULTS a sheet is created with and the ceiling it may
268
  #: grow to, and `web/src/sheet/types.ts` mirrors the three defaults.
269
+ #: W62 C1 / R14 also mirrors the width bounds there; the client half lands in W62-T05.
270
  #:
271
  #: ⚠ THE CEILING IS A RENDERING BUDGET, NOT A GRAMMAR LIMIT. `_ADDR` below already admits three
272
  #: column letters and seven row digits, and `a1.ts` agrees with it; 702 is the last TWO letter
 
279
  MIN_SHEET_ROWS = 1
280
  MAX_SHEET_COLS = 702
281
  MAX_SHEET_ROWS = 100000
282
+ MIN_COL_WIDTH = 0
283
  MAX_COL_WIDTH = 1000
284
 
285
  #: A column key in `colWidths`. Letters only: a WIDTH belongs to a column, and a row number there
 
696
  return {"kind": kind, "range": rect}
697
 
698
 
699
+ def clean_view_binding(raw):
700
+ """W62-T10 / C2: normalize a PLACED VIEW binding, or raise `SheetRefusal` with a named code.
701
+
702
+ `{database, mode: "view", viewType, fields: [key], filter?, sort: [{field, dir}], period?,`
703
+ `limit (1..10000, default 100), onDrag?, block?: {cols, rows}}`.
704
+
705
+ ⛔ IT IS A SEPARATE VALIDATOR FROM `modules/sheet.py::clean_binding` RATHER THAN A WIDENING OF
706
+ IT. That one REQUIRES an `aggregate`, because a metric binding IS an aggregate; a view has
707
+ none. Widening it would make `aggregate` optional for every caller, and the day a metric
708
+ binding arrives without one it would resolve to nothing instead of refusing by name.
709
+ """
710
+ if not isinstance(raw, dict) or not isinstance(raw.get("database"), str) or not raw["database"].strip():
711
+ raise SheetRefusal("view_binding_invalid", "A view binding must be an object naming a database.")
712
+ if raw.get("mode", raw.get("kind")) != "view":
713
+ raise SheetRefusal("view_binding_mode_unknown", "A view binding must choose view mode.")
714
+ if raw.get("viewType") not in VIEW_BINDING_TYPES:
715
+ raise SheetRefusal("view_binding_type_unknown", "That view display type is not supported.")
716
+ fields = raw.get("fields")
717
+ if not isinstance(fields, list) or not fields or any(
718
+ not isinstance(key, str) or not key.strip() for key in fields):
719
+ raise SheetRefusal("view_binding_fields_invalid", "A view needs a non-empty list of field keys.")
720
+ sort = raw.get("sort", [])
721
+ if not isinstance(sort, list) or any(
722
+ not isinstance(item, dict) or not isinstance(item.get("field"), str)
723
+ or not item["field"].strip() or item.get("dir") not in ("asc", "desc") for item in sort):
724
+ raise SheetRefusal("view_binding_sort_invalid", "A view sort needs a field key and asc or desc direction.")
725
+ limit = raw.get("limit", VIEW_BINDING_LIMIT_DEFAULT)
726
+ if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= VIEW_BINDING_LIMIT_MAX:
727
+ raise SheetRefusal("view_binding_limit_invalid", "A view limit must be a whole number from 1 to 10000.")
728
+ out = {"database": raw["database"].strip(), "mode": "view", "viewType": raw["viewType"],
729
+ "fields": list(fields), "sort": [{"field": item["field"], "dir": item["dir"]} for item in sort],
730
+ "limit": limit}
731
+ for key in ("filter", "block"):
732
+ if key in raw:
733
+ out[key] = _document_object(raw[key], "view_binding_" + key)
734
+ # W62 C2: reuse only the existing pure metadata cleaners, never the metric binding validator.
735
+ if "period" in raw or "onDrag" in raw:
736
+ from modules import sheet as sheet_mod
737
+ for key, cleaner in (("period", sheet_mod.clean_period), ("onDrag", sheet_mod.clean_on_drag)):
738
+ if key in raw:
739
+ try:
740
+ value = cleaner(_json_safe(copy.deepcopy(raw[key]), "view binding " + key))
741
+ except sheet_mod.SheetRefusal as exc:
742
+ raise SheetRefusal(exc.code, exc.message) from exc
743
+ if value is not None:
744
+ out[key] = value
745
+ return out
746
+
747
+
748
  def clean_cell(raw, addr=""):
749
  """Normalize ONE cell, or raise `SheetRefusal` with a named code.
750
 
 
790
  if meta and meta.get("kind", "normal") not in ("normal", "array", "shared", "dataTable"):
791
  raise SheetRefusal("cell_formula_kind_unknown", "That formula representation is not supported.")
792
  binding = raw.get("binding")
793
+ # ⭐⭐ W62-T10 / C2 — A PLACED VIEW LIVES INSIDE `kind: "bound"`, AND `CELL_KINDS` STAYS
794
+ # FROZEN. Wave 49's cell-kind contract is the reason: the vocabulary is pinned here and two
795
+ # gates prove the client agrees with it, so a fifth kind would be a change to a frozen
796
+ # contract for a feature that does not need one. The discriminator is `binding.mode == "view"`,
797
+ # and a view binding carries no `aggregate` at all, which is why it cannot go through the
798
+ # metric validator below.
799
+ if isinstance(binding, dict) and (binding.get("mode") == "view" or binding.get("kind") == "view"):
800
+ if kind != "bound":
801
+ raise SheetRefusal("view_binding_invalid", "A view binding needs a bound cell.")
802
+ binding = clean_view_binding(binding)
803
+ elif isinstance(binding, dict):
804
  for tag in ("kind", "mode"):
805
  if tag in binding and binding[tag] not in ("number", "column"):
806
  raise SheetRefusal("cell_binding_kind_unknown", "A cell binding must choose Number or Column.")
 
850
  cell["value"] = _json_safe(raw.get("value"), "cell value")
851
 
852
  for key in ("binding", "source", "refusal"):
853
+ blob = binding if key == "binding" else raw.get(key)
854
  if blob is None:
855
  continue
856
  if not isinstance(blob, dict):
 
953
  "Column " + (letters or str(key)) + " is not a column letter.")
954
  if isinstance(value, bool) or not isinstance(value, (int, float)):
955
  if lossless:
956
+ raise SheetRefusal("col_width_invalid", "A column width must be a finite size.")
957
  continue
958
  if not math.isfinite(value):
959
  raise SheetRefusal("col_width_invalid", "A column width must be a finite size.")
960
+ # ⭐ W62-T04 / R14 — A ZERO IS NOW A WIDTH, AND A NEGATIVE ONE STILL IS NOT. Before this
961
+ # ticket the lossless door refused every `value <= 0`, which is the same test for both; R14
962
+ # made 0 Excel's own hidden column, so an xlsx carrying one must import rather than refuse.
963
+ # A negative width is still nothing a file or a person can mean, so it keeps its refusal on
964
+ # the lossless door and is clamped to the floor on a live save.
965
+ if lossless and value < 0:
966
+ raise SheetRefusal("col_width_invalid", "A column width cannot be negative.")
967
+ #: W62 C1 / R14 / R19: reads retain hidden zero widths and exact imported values;
968
+ #: only a live save applies the bounds a person can set.
969
  width = value if lossless else max(MIN_COL_WIDTH, min(MAX_COL_WIDTH, int(value)))
970
  if lossless or width != DEFAULT_COL_WIDTH:
971
  out[letters] = width
 
1276
  return raw
1277
 
1278
 
1279
+ def _clean_row_heights(raw, *, lossless=False):
1280
  if raw is None:
1281
  return {}
1282
  out = _document_object(raw, "sheet_row_heights")
1283
  for row, height in out.items():
1284
  if not re.fullmatch(r"[1-9][0-9]*", str(row)) or int(row) > DOCUMENT_MAX_ROWS \
1285
  or isinstance(height, bool) or not isinstance(height, (int, float)) \
1286
+ or not math.isfinite(height) or (lossless and height <= 0):
1287
  raise SheetRefusal("sheet_row_height_invalid", "A row height needs a row number and a positive size.")
1288
+ #: W62 C1 / R19: a live size is clamped, while imported positive sizes stay exact.
1289
+ if not lossless:
1290
+ out[row] = max(18, min(200, height))
1291
  return out
1292
 
1293
 
 
1404
  "charts": _clean_charts(raw.get("charts")),
1405
  "imported": _clean_imported(raw.get("imported")),
1406
  "rowHeight": _clean_base_row_height(raw.get("rowHeight")),
1407
+ "rowHeights": _clean_row_heights(raw.get("rowHeights"), lossless=lossless),
1408
  "visibility": visibility,
1409
  "view": _clean_view(raw.get("view")),
1410
  "print": _clean_print(raw.get("print")),
 
1446
 
1447
  # ── the workbook ─────────────────────────────────────────────────────────────────────────────
1448
 
1449
+ def migrate_workbook(raw, *, lossless=True):
1450
  """Pure unversioned/v0 -> v1 migration; validate current documents without recalculating.
1451
 
1452
  A read never writes or changes `rev`, timestamps or cached results. Unknown versions
 
1470
  if book.get("print") is not None:
1471
  book["print"] = _clean_print(book["print"])
1472
  book["schemaVersion"] = SHEET_SCHEMA_VERSION
1473
+ book["sheets"] = _clean_sheets(raw.get("sheets"), lossless=lossless)
1474
  return _json_safe(book, "workbook")
1475
 
1476
 
 
1639
  return _carry_write_logs(migrate_workbook(doc), doc)
1640
 
1641
 
1642
+ def put_workbook(st, workbook_id, raw, expect_rev=None, *, actor="", actor_name="", lossless=False):
1643
  """Replace a workbook's name and sheets, bumping `rev`.
1644
 
1645
  ⛔ `id`, `created_by`, `access` and `created_at` are PRIOR-WINS: a client may not reassign a workbook by
 
1661
  if expect_rev is False:
1662
  expect_rev = None
1663
 
1664
+ #: W62 C1 / R19: app and AI saves share bounded defaults; import and refresh opt out.
1665
+ incoming = migrate_workbook(raw, lossless=lossless)
1666
  sheets = incoming["sheets"]
1667
  name = _text(raw.get("name"), _MAX_NAME)
1668
  refreshed_at = raw.get("refreshed_at")
 
2053
  "id": book.get("id") or "",
2054
  "name": book.get("name") or "",
2055
  "created_by": book.get("created_by") or "",
2056
+ "has_access": "access" in book,
2057
  "created_at": book.get("created_at") or "",
2058
  "updated_at": book.get("updated_at") or "",
2059
  "rev": int(book.get("rev") or 0),
 
2113
  if not state.get("id"):
2114
  raise SheetRefusal("workbook_missing", "That workbook no longer exists.")
2115
  state.setdefault("access", "private")
2116
+ return state, state
2117
 
2118
+ # R28 / W62-T25: explicit sharing changes the fact used by the index's visibility filter.
2119
+ book = _persist(st, workbook_key(wid), _apply)
2120
+ _index_upsert(st, book)
2121
 
2122
 
2123
  def workbook_shares(st, workbook_id):
 
2173
  def may_read_workbook(book, role):
2174
  """R28: a role admits a reader; unmarked or creatorless documents remain legacy-visible.
2175
 
2176
+ R28 / W62-T25: creation and explicit sharing stamp access. The index records its presence;
2177
+ workbook reads still use the document, and PUT must preserve marker absence too.
2178
  Legacy visibility grants no ownership or editing role.
2179
  """
2180
  return bool(role) or "access" not in book or not book.get("created_by")
 
2183
  def project_shares(st, rows, viewer=None, *, is_admin=False, role_on_workbook=None):
2184
  """Join `shares` onto a list of index rows. Returns NEW rows; the stored ones are untouched.
2185
 
2186
+ W62-T25: a named viewer filters rows using document facts and receives their role.
2187
  The route supplies its existing role helper; core callers use workbook_role directly.
2188
  `list_workbooks` itself stays a bare pointer list on purpose:
2189
  `iter_workbooks` walks it to answer W49-T10's dependents question, and paying a grant-registry
 
2200
  the document on every save, and `workbook_role` reads nothing else; so does the route's
2201
  injected helper. The third is `may_read_workbook`'s legacy-visibility clause, `"access" not in
2202
  book`, and it is consulted ONLY when the viewer has no role at all AND the row names a
2203
+ creator - the rows that are otherwise about to be REFUSED. W62-T25 records that third fact
2204
+ as `has_access`; only rows written before that fact existed still read their document.
2205
+
2206
+ R28 / W62-T25: admission uses the document facts rebuilt on save and explicit sharing.
2207
+ `_index_drop` removes a deleted document's row. Older rows still check document existence
2208
+ when taking the fallback; opening any workbook always reads its document for real.
 
 
 
 
 
 
 
 
 
 
2209
  """
2210
  out = []
2211
  bulk = {}
 
2230
  role = (role_on_workbook(light) if role_on_workbook is not None
2231
  else workbook_role(st, light, viewer, is_admin=is_admin, rec=rec))
2232
  if not role and light["created_by"]:
2233
+ if "has_access" in row:
2234
+ if row["has_access"]:
2235
+ continue
2236
+ else:
2237
+ # R28 / W62-T25: old rows lack this fact, so retain their document check.
2238
+ # R28: this fallback set is expected to be empty after every workbook
2239
+ # has been saved once; guessing would change R28's legacy admission.
2240
+ book = _read(st, workbook_key(row["id"]))
2241
+ if not book or not book.get("id") or not may_read_workbook(book, role):
2242
+ continue
2243
  joined["role"] = role or "view"
2244
  joined["shares"] = shares_from_record(rec)
2245
  out.append(joined)
 
2735
  so a `rev` here without the check there (or the check without this) is a guard nothing can
2736
  reach ([[a-rev-guard-inert-on-the-events-channel]]). The pair lands together or not at all.
2737
 
2738
+ D-639 / W62-T25: `save_folders`, `merge_placements` and `_index_drop` move the revision
2739
+ because they write the folder, placement and star strata this guard protects.
2740
  `_index_upsert` deliberately does NOT, because it is called by `create_workbook`,
2741
  `put_workbook` AND `patch_cells` — bumping there would make every cell edit 409 a folder drag
2742
  that touched nothing the guard is about.
 
2848
  result["workbooks"] = project_shares(st, result.get("workbooks"))
2849
  result["repairs"] = repairs
2850
  return result
2851
+
2852
+
2853
+ def merge_placements(st, placements, *, starred=None):
2854
+ """D-639 / W62-T25: apply only named moves to the current rail under the store's lock.
2855
+
2856
+ None unfiles a workbook. Disjoint moves need no expected revision; every accepted merge
2857
+ advances it so a stale wholesale save still refuses. Stars change only if explicitly supplied.
2858
+ """
2859
+ if not isinstance(placements, dict):
2860
+ raise SheetRefusal("placements_not_a_map", "Sheet placements must be a map of workbook ids.")
2861
+
2862
+ def _apply(state):
2863
+ rows = [r for r in (state.get("workbooks") or [])
2864
+ if isinstance(r, dict) and r.get("id")]
2865
+ ids = {r["id"] for r in rows}
2866
+ merged = dict(state.get("itemFolders") or {})
2867
+ for wid, fid in placements.items():
2868
+ if wid not in ids:
2869
+ raise SheetRefusal("placement_missing_workbook",
2870
+ 'The workbook "' + str(wid) + '" no longer exists in the Sheet rail.')
2871
+ if fid is None:
2872
+ merged.pop(wid, None)
2873
+ else:
2874
+ merged[wid] = fid
2875
+ # D-639: validate the merged tree inside the same update, before changing any stratum.
2876
+ # D-639: use wholesale repair names, but refuse a malformed delta instead of losing it.
2877
+ _tree, placed, repairs = validate_folder_tree(state.get("folders"), merged)
2878
+ if repairs:
2879
+ repair = repairs[0]
2880
+ raise SheetFolderRefusal(
2881
+ repair["reason"],
2882
+ 'The placement for workbook "' + str(repair.get("item_id") or "")
2883
+ + '" cannot be saved. Use an existing folder id or null to unfile it.',
2884
+ folder_id=str(repair.get("folder_id") or ""), reason=repair["reason"])
2885
+ for wid, fid in placements.items():
2886
+ if fid is not None:
2887
+ merged[wid] = placed[wid]
2888
+ state["itemFolders"] = merged
2889
+ if starred is not None:
2890
+ state["starred"] = _clean_starred(starred, ids, repairs)
2891
+ state["rev"] = _index_rev(state) + 1
2892
+ return state, {"workbooks": rows, "folders": state.get("folders") or [],
2893
+ "itemFolders": merged, "starred": state.get("starred") or [],
2894
+ "rev": _index_rev(state), "repairs": repairs}
2895
+
2896
+ result = _persist(st, INDEX_KEY, _apply, seed={"workbooks": []})
2897
+ # D-639: grant reads happen after the store releases its update lock, as in save_folders.
2898
+ result["workbooks"] = project_shares(st, result["workbooks"])
2899
+ return result
platform/core/user_tables.py CHANGED
@@ -218,7 +218,20 @@ def is_connected(table_key, st=None):
218
  key = str(table_key or '').strip()
219
  if key in _CONNECTED:
220
  return True
221
- table = get(key, st) or {}
 
 
 
 
 
 
 
 
 
 
 
 
 
222
  if not table:
223
  return False
224
  if table.get('connected') is True:
 
218
  key = str(table_key or '').strip()
219
  if key in _CONNECTED:
220
  return True
221
+ # ⭐⭐ W62-T17 (D-739) — `all_defs`, NOT `get`, AND THE THREE KEYS BELOW ARE THE WHOLE ARGUMENT.
222
+ # This function asks `connected`, `source` and `recordMode`. Every one of them is a DEFINITION
223
+ # key; not one of them is a row. `get` reaches `all_tables`, which is the whole tenant
224
+ # document — MEASURED at 97,859,052 bytes and 2,274-2,816 ms PER CALL on staging's Royal
225
+ # Imports (`AutoWiki/waves/wave62/proto/T17-profile.md`), against 106,779 bytes for the
226
+ # rows-free projection that answers identically. D-739 called this "a platform-wide hazard,
227
+ # not a templates one: anything that calls it in a loop has this defect", and the loop callers
228
+ # were never the only victims — one call was already over the whole 2,000 ms module budget.
229
+ #
230
+ # ⚠ THE PROJECTION IS SAFE HERE FOR THE SAME REASON IT IS SAFE IN `/nav`: `all_defs` drops
231
+ # exactly `rows`, raises loudly (or falls back to the whole read) rather than answering empty,
232
+ # and a lent handle already serves whichever document the pass is holding. A caller that lends
233
+ # the WHOLE document gets MORE than asked for, which is the one direction this may be wrong in.
234
+ table = all_defs(st).get(key) or {}
235
  if not table:
236
  return False
237
  if table.get('connected') is True:
web/package-lock.json CHANGED
@@ -11,6 +11,8 @@
11
  "@glideapps/glide-data-grid": "^6.0.3",
12
  "lodash": "^4.18.1",
13
  "marked": "^4.3.0",
 
 
14
  "react": "^18.3.1",
15
  "react-dom": "^18.3.1",
16
  "vega": "^6.3.1",
@@ -2358,6 +2360,22 @@
2358
  "node": ">=0.10.0"
2359
  }
2360
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2361
  "node_modules/oxlint": {
2362
  "version": "1.75.0",
2363
  "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.75.0.tgz",
 
11
  "@glideapps/glide-data-grid": "^6.0.3",
12
  "lodash": "^4.18.1",
13
  "marked": "^4.3.0",
14
+ "overlayscrollbars": "^2.16.0",
15
+ "overlayscrollbars-react": "^0.5.6",
16
  "react": "^18.3.1",
17
  "react-dom": "^18.3.1",
18
  "vega": "^6.3.1",
 
2360
  "node": ">=0.10.0"
2361
  }
2362
  },
2363
+ "node_modules/overlayscrollbars": {
2364
+ "version": "2.16.0",
2365
+ "resolved": "https://registry.npmjs.org/overlayscrollbars/-/overlayscrollbars-2.16.0.tgz",
2366
+ "integrity": "sha512-N03oje/q7j93D0aLZtoCdsDSYLmhheSsv8H7oSLE7HhdV9P/bmCURtLV/KbPye7P/bpfyt/obSfDpGUYoJ0OWg==",
2367
+ "license": "MIT"
2368
+ },
2369
+ "node_modules/overlayscrollbars-react": {
2370
+ "version": "0.5.6",
2371
+ "resolved": "https://registry.npmjs.org/overlayscrollbars-react/-/overlayscrollbars-react-0.5.6.tgz",
2372
+ "integrity": "sha512-E5To04bL5brn9GVCZ36SnfGanxa2I2MDkWoa4Cjo5wol7l+diAgi4DBc983V7l2nOk/OLJ6Feg4kySspQEGDBw==",
2373
+ "license": "MIT",
2374
+ "peerDependencies": {
2375
+ "overlayscrollbars": "^2.0.0",
2376
+ "react": ">=16.8.0"
2377
+ }
2378
+ },
2379
  "node_modules/oxlint": {
2380
  "version": "1.75.0",
2381
  "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.75.0.tgz",
web/package-lock.linux.sha256 CHANGED
@@ -1,2 +1,2 @@
1
- 3875e749397966dc170a4f83ae04cddc47a2989828cd5c46970cad69dedb255a package-lock.json
2
- # resolved on linux/x64 by HF job 6aa6bba021047bf1b0384360 on 2026-09-13, npm ci passed there before upload. Regenerate ONLY with lockfile_linux.py (W-170).
 
1
+ e3e18054f50ef4119f7d9f38fdb8c712c1277df2dfa2ba5418bb683f56afb7af package-lock.json
2
+ # resolved on linux/x64 natively in the SDLC 62 wave container (lane H, W62-T33) on 2026-09-16; `npm ci` passed there before this receipt was written. `lockfile_linux.py` submits an HF job to reach a Linux box; this container IS one, so it ran `npm install --save` and `npm ci` here instead. Regenerate ONLY on linux/x64 (W-170).
web/package.json CHANGED
@@ -18,6 +18,8 @@
18
  "@glideapps/glide-data-grid": "^6.0.3",
19
  "lodash": "^4.18.1",
20
  "marked": "^4.3.0",
 
 
21
  "react": "^18.3.1",
22
  "react-dom": "^18.3.1",
23
  "vega": "^6.3.1",
 
18
  "@glideapps/glide-data-grid": "^6.0.3",
19
  "lodash": "^4.18.1",
20
  "marked": "^4.3.0",
21
+ "overlayscrollbars": "^2.16.0",
22
+ "overlayscrollbars-react": "^0.5.6",
23
  "react": "^18.3.1",
24
  "react-dom": "^18.3.1",
25
  "vega": "^6.3.1",
web/src/assistant/AssistantPage.tsx CHANGED
@@ -31,6 +31,12 @@ export interface AssistantPageProps { granted: NavEntry[]; }
31
  * the disclosure and refusal extension local and read it through the single cast in ask(). */
32
  type RoutedTo = { database: string; label: string; reason: string; auto: boolean;
33
  alternatives: Array<{ database: string; label: string }> };
 
 
 
 
 
 
34
  // W61-T30: the drafting extension stays local while the shared API union belongs to another lane.
35
  type SemanticDraft = {
36
  database: string; label: string; canApprove: boolean; sentToAdmins: boolean;
@@ -56,16 +62,43 @@ async function draftRequest(database: string, fields?: string[], question?: stri
56
  return response.json();
57
  }
58
 
59
- function RoutingLine({ routed, onSwitch, busy }: {
60
- routed?: RoutedTo; onSwitch?: (database: string) => void; busy?: boolean;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  }) {
62
- if (!routed?.auto || !routed.database) return null;
63
  return <section className="as-routing" aria-label="Selected database">
64
- <span>{routed.reason}</span>
65
- {onSwitch ? routed.alternatives.map((alternative) => (
66
- <button type="button" className="w45-quiet" key={alternative.database} disabled={busy}
67
- onClick={() => onSwitch(alternative.database)}>{`Ask ${alternative.label} instead`}</button>
68
- )) : null}
 
 
 
 
 
 
 
 
 
 
 
69
  </section>;
70
  }
71
 
@@ -217,7 +250,7 @@ export function AssistantMessage({
217
  onRate,
218
  identity,
219
  governedArtifacts,
220
- routed,
221
  onSwitch,
222
  busy,
223
  }: {
@@ -226,7 +259,7 @@ export function AssistantMessage({
226
  onRate?: (id: string, rating: "up" | "down" | null, reason?: string) => void;
227
  identity?: QueryModelIdentity;
228
  governedArtifacts?: QueryToolArtifacts;
229
- routed?: RoutedTo;
230
  onSwitch?: (database: string) => void;
231
  busy?: boolean;
232
  }) {
@@ -260,7 +293,7 @@ export function AssistantMessage({
260
  const numeric = message.numeric;
261
  return (
262
  <article className={"as-message as-message--assistant" + (message.reason ? " is-refusal" : "")}>
263
- <RoutingLine routed={routed} onSwitch={onSwitch} busy={busy} />
264
  <p className="as-message-text">{message.content}</p>
265
  <p className="w45-model-id" aria-label="Model and provider">
266
  Provider <strong>{identity?.provider || message.model || "Not reported"}</strong>
@@ -436,9 +469,6 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
436
  const [queryRefresh, setQueryRefresh] = useState(0);
437
  const [modelCatalog, setModelCatalog] = useState<QueryModelIdentity[]>([]);
438
  const [artifactByView, setArtifactByView] = useState<Record<string, QueryToolArtifacts>>({});
439
- const [routingByMessage, setRoutingByMessage] = useState<Record<string, {
440
- routed: RoutedTo; prompt: string;
441
- }>>({});
442
  const [alignment, setAlignment] = useState<null | {
443
  prompt: string; database: string; resumeToken: string;
444
  question: string; choices: Array<{ field: string; label: string }>; maxSelections: number;
@@ -466,6 +496,12 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
466
 
467
  const databases = useMemo(() => databaseEntries(granted).filter((entry) => entry.kind !== "group"), [granted]);
468
  const labels = useMemo(() => new Map(databases.map((entry) => [entry.key, entry.label])), [databases]);
 
 
 
 
 
 
469
  /**
470
  * ⭐⭐ INSTRUCTION 12 / R11 — NO SOURCE PICKER AT ALL. Owner: *"the Assistant should always have
471
  * access to all database that the user have access to. So it doesn't need the database clicks
@@ -709,8 +745,6 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
709
  return;
710
  }
711
  setActiveThread(result.value.thread.id);
712
- if (routed) setRoutingByMessage((current) => ({ ...current,
713
- [result.value.message.id]: { routed, prompt: text } }));
714
  if (result.value.view && governed.status === "answered") {
715
  setArtifactByView((current) => ({ ...current, [result.value.view!.id]: governed.artifacts }));
716
  }
@@ -805,12 +839,32 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
805
  selectQuery(qid);
806
  }, [pickMode, selectQuery]);
807
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
808
  const empty = messages.length === 0;
809
  const composer = (
810
  <div className="as-composer">
811
  {approvalLine ? <p className="as-draft-state" role="status">{approvalLine}</p> : null}
812
  {alignment ? <section ref={alignmentRef} className={`w45-contract-card${alignment.draft ? " as-draft-card" : ""}`} aria-label="Alignment question">
813
- <RoutingLine routed={alignment.routed} busy={busy || draftBusy}
814
  onSwitch={(database) => switchDatabase(database, alignment.prompt)} />
815
  <h4>{alignment.draft ? "Database fields" : "Clarify"}</h4>
816
  <p className={alignment.sent ? "as-draft-state" : undefined} role={alignment.sent ? "status" : undefined}>
@@ -848,7 +902,7 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
848
  className="as-prompt"
849
  value={question}
850
  rows={1}
851
- placeholder={target ? `Ask about ${labels.get(target) || target}…` : "Ask about your data…"}
852
  aria-label="Ask the assistant"
853
  onChange={(event) => setQuestion(event.currentTarget.value)}
854
  onKeyDown={(event) => {
@@ -874,22 +928,8 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
874
  })}
875
  </select>
876
  </label>
877
- {/* ⚠ ONLY WHEN THE ANSWER IS AMBIGUOUS. Every generated view names ONE database (R3);
878
- with a single database reachable that database is not a question, so asking it would
879
- be chrome for its own sake. This is now the ONLY database control on the surface. */}
880
- {databases.length > 1 ? (
881
- <label className="as-pick">
882
- <span className="as-pick-label">Build on</span>
883
- <select className="as-pick-select" value={target} aria-label="Target database" disabled={busy || draftBusy}
884
- onChange={(event) => { setTarget(event.currentTarget.value); setTargetTouched(true);
885
- alignmentGeneration.current += 1;
886
- setAlignment(null); setAlignmentFields([]); setDraftProblem(""); setApprovalLine(""); }}>
887
- {databases.map((entry) => (
888
- <option key={entry.key} value={entry.key}>{labels.get(entry.key) || entry.key}</option>
889
- ))}
890
- </select>
891
- </label>
892
- ) : null}
893
  <button type="button" className="as-send" aria-label="Send"
894
  disabled={busy || draftBusy || !question.trim() || !target} onClick={() => void ask()}>
895
  <svg viewBox="0 0 16 16" aria-hidden="true" width="15" height="15">
@@ -1004,18 +1044,19 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
1004
  <>
1005
  <div className="as-stream">
1006
  <div className="as-column">
1007
- {messages.map((message) => (
1008
- <AssistantMessage key={message.id} message={message}
 
1009
  view={message.viewId ? viewById.get(message.viewId) : undefined}
1010
  citations={index.citations} onPreview={preview}
1011
  identity={modelCatalog.find((row) => row.model === message.model || row.provider === message.model)}
1012
  governedArtifacts={message.viewId ? artifactByView[message.viewId] : undefined}
1013
- routed={routingByMessage[message.id]?.routed} busy={busy}
1014
- onSwitch={routingByMessage[message.id]
1015
- ? (database) => switchDatabase(database, routingByMessage[message.id].prompt) : undefined}
1016
  onRate={message.role === "assistant" && !message.id.startsWith("pending_")
1017
- ? rate : undefined} />
1018
- ))}
1019
  {/* R16's thinking animation is the app's ONE loading mark, not a second spinner
1020
  vocabulary: `.lp-spin` is the same mark every surface uses and C is repainting
1021
  it in the brand purple this wave. The label is for screen readers only, since
 
31
  * the disclosure and refusal extension local and read it through the single cast in ask(). */
32
  type RoutedTo = { database: string; label: string; reason: string; auto: boolean;
33
  alternatives: Array<{ database: string; label: string }> };
34
+ type RoutingDisclosure = {
35
+ database: string;
36
+ label: string;
37
+ alternatives: Array<{ database: string; label: string }>;
38
+ answered: boolean;
39
+ };
40
  // W61-T30: the drafting extension stays local while the shared API union belongs to another lane.
41
  type SemanticDraft = {
42
  database: string; label: string; canApprove: boolean; sentToAdmins: boolean;
 
62
  return response.json();
63
  }
64
 
65
+ /**
66
+ * R47 / R6 — the answer names its own source, and the override lives here rather than in front of
67
+ * the question. One line: "Answered from <database> · Change".
68
+ *
69
+ * ⛔ CHANGE IS A SELECT, NOT A ROW OF BUTTONS, AND THAT WAS MEASURED ON A RUNNING TENANT. This
70
+ * first shipped as one quiet button per alternative; tenant #0 can read 28 databases, so opening
71
+ * Change pushed the answer six rows down the screen behind a wall of names, eleven of which read
72
+ * "Formula contract". A select collapses the whole override into the one word the ruling names,
73
+ * hands the browser the scrolling, the keyboard and the screen reader, and is the same control
74
+ * the model picker one line below already is. Its value is held at "" so the word Change survives
75
+ * every switch, and `onChange` ignores that empty value.
76
+ *
77
+ * ⚠ A refusal renders the control ALONE: the refusal sentence under it already names the database
78
+ * it could not answer from, so "Answered from" would be the one thing on the surface that is not
79
+ * true. The override still has to be reachable there, which is the state that needs it most.
80
+ */
81
+ function RoutingLine({ disclosure, onSwitch, busy }: {
82
+ disclosure?: RoutingDisclosure | null; onSwitch?: (database: string) => void; busy?: boolean;
83
  }) {
84
+ if (!disclosure?.database || !disclosure.alternatives.length) return null;
85
  return <section className="as-routing" aria-label="Selected database">
86
+ {disclosure.answered ? <>
87
+ <span>Answered from {disclosure.label}</span>
88
+ {onSwitch ? <span aria-hidden="true">·</span> : null}
89
+ </> : null}
90
+ {onSwitch ? (
91
+ <label className="as-pick">
92
+ <select className="as-pick-select" aria-label="Answer from another database" value=""
93
+ disabled={busy}
94
+ onChange={(event) => { const next = event.currentTarget.value; if (next) onSwitch(next); }}>
95
+ <option value="">Change</option>
96
+ {disclosure.alternatives.map((alternative) => (
97
+ <option key={alternative.database} value={alternative.database}>{alternative.label}</option>
98
+ ))}
99
+ </select>
100
+ </label>
101
+ ) : null}
102
  </section>;
103
  }
104
 
 
250
  onRate,
251
  identity,
252
  governedArtifacts,
253
+ disclosure,
254
  onSwitch,
255
  busy,
256
  }: {
 
259
  onRate?: (id: string, rating: "up" | "down" | null, reason?: string) => void;
260
  identity?: QueryModelIdentity;
261
  governedArtifacts?: QueryToolArtifacts;
262
+ disclosure?: RoutingDisclosure | null;
263
  onSwitch?: (database: string) => void;
264
  busy?: boolean;
265
  }) {
 
293
  const numeric = message.numeric;
294
  return (
295
  <article className={"as-message as-message--assistant" + (message.reason ? " is-refusal" : "")}>
296
+ <RoutingLine disclosure={disclosure} onSwitch={onSwitch} busy={busy} />
297
  <p className="as-message-text">{message.content}</p>
298
  <p className="w45-model-id" aria-label="Model and provider">
299
  Provider <strong>{identity?.provider || message.model || "Not reported"}</strong>
 
469
  const [queryRefresh, setQueryRefresh] = useState(0);
470
  const [modelCatalog, setModelCatalog] = useState<QueryModelIdentity[]>([]);
471
  const [artifactByView, setArtifactByView] = useState<Record<string, QueryToolArtifacts>>({});
 
 
 
472
  const [alignment, setAlignment] = useState<null | {
473
  prompt: string; database: string; resumeToken: string;
474
  question: string; choices: Array<{ field: string; label: string }>; maxSelections: number;
 
496
 
497
  const databases = useMemo(() => databaseEntries(granted).filter((entry) => entry.kind !== "group"), [granted]);
498
  const labels = useMemo(() => new Map(databases.map((entry) => [entry.key, entry.label])), [databases]);
499
+ const disclosureFor = useCallback((database: string, answered: boolean): RoutingDisclosure | null => {
500
+ if (!labels.has(database)) return null;
501
+ return { database, label: labels.get(database)!, answered,
502
+ alternatives: databases.filter((entry) => entry.key !== database)
503
+ .map((entry) => ({ database: entry.key, label: entry.label })) };
504
+ }, [databases, labels]);
505
  /**
506
  * ⭐⭐ INSTRUCTION 12 / R11 — NO SOURCE PICKER AT ALL. Owner: *"the Assistant should always have
507
  * access to all database that the user have access to. So it doesn't need the database clicks
 
745
  return;
746
  }
747
  setActiveThread(result.value.thread.id);
 
 
748
  if (result.value.view && governed.status === "answered") {
749
  setArtifactByView((current) => ({ ...current, [result.value.view!.id]: governed.artifacts }));
750
  }
 
839
  selectQuery(qid);
840
  }, [pickMode, selectQuery]);
841
 
842
+ /**
843
+ * The question Change re-asks for a past answer.
844
+ *
845
+ * ⛔ NOT "the nearest message above it". `_submit` stamps the question and the answer with ONE
846
+ * `createdAt`, and the index sorts on that key, so a turn's two rows arrive in whichever order
847
+ * the stored map held them: a thread whose answer sits ABOVE its question left Change with no
848
+ * question to re-ask and therefore unrendered. The shared timestamp IS the pairing, so it is
849
+ * what this matches on; the scan above is the fallback for a row that predates that shape.
850
+ */
851
+ const questionFor = useCallback((position: number) => {
852
+ const row = messages[position];
853
+ if (!row) return "";
854
+ const turn = messages.find((item) => item.role === "user" && item.createdAt === row.createdAt);
855
+ if (turn) return turn.content;
856
+ for (let index = position - 1; index >= 0; index -= 1) {
857
+ if (messages[index].role === "user") return messages[index].content;
858
+ }
859
+ return "";
860
+ }, [messages]);
861
+
862
  const empty = messages.length === 0;
863
  const composer = (
864
  <div className="as-composer">
865
  {approvalLine ? <p className="as-draft-state" role="status">{approvalLine}</p> : null}
866
  {alignment ? <section ref={alignmentRef} className={`w45-contract-card${alignment.draft ? " as-draft-card" : ""}`} aria-label="Alignment question">
867
+ <RoutingLine disclosure={disclosureFor(alignment.database, true)} busy={busy || draftBusy}
868
  onSwitch={(database) => switchDatabase(database, alignment.prompt)} />
869
  <h4>{alignment.draft ? "Database fields" : "Clarify"}</h4>
870
  <p className={alignment.sent ? "as-draft-state" : undefined} role={alignment.sent ? "status" : undefined}>
 
902
  className="as-prompt"
903
  value={question}
904
  rows={1}
905
+ placeholder={targetTouched ? `Ask about ${labels.get(target) || target}…` : "Ask about your data…"}
906
  aria-label="Ask the assistant"
907
  onChange={(event) => setQuestion(event.currentTarget.value)}
908
  onKeyDown={(event) => {
 
928
  })}
929
  </select>
930
  </label>
931
+ {/* R6 / R47: routing needs no pre-question picker; its override survives as Change
932
+ on each answer's disclosure line. */}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
933
  <button type="button" className="as-send" aria-label="Send"
934
  disabled={busy || draftBusy || !question.trim() || !target} onClick={() => void ask()}>
935
  <svg viewBox="0 0 16 16" aria-hidden="true" width="15" height="15">
 
1044
  <>
1045
  <div className="as-stream">
1046
  <div className="as-column">
1047
+ {messages.map((message, messageIndex) => {
1048
+ const prompt = questionFor(messageIndex);
1049
+ return <AssistantMessage key={message.id} message={message}
1050
  view={message.viewId ? viewById.get(message.viewId) : undefined}
1051
  citations={index.citations} onPreview={preview}
1052
  identity={modelCatalog.find((row) => row.model === message.model || row.provider === message.model)}
1053
  governedArtifacts={message.viewId ? artifactByView[message.viewId] : undefined}
1054
+ disclosure={message.role === "assistant"
1055
+ ? disclosureFor(message.targetDatabase || "", !message.reason) : null} busy={busy}
1056
+ onSwitch={prompt ? (database) => switchDatabase(database, prompt) : undefined}
1057
  onRate={message.role === "assistant" && !message.id.startsWith("pending_")
1058
+ ? rate : undefined} />;
1059
+ })}
1060
  {/* R16's thinking animation is the app's ONE loading mark, not a second spinner
1061
  vocabulary: `.lp-spin` is the same mark every surface uses and C is repainting
1062
  it in the brand purple this wave. The label is for screen readers only, since
web/src/customer-grid/MapView.tsx CHANGED
@@ -65,6 +65,7 @@ import { LAND_PATH, LAKE_PATHS } from "./mapGeometry";
65
  import {
66
  BASEMAP_DETAIL_K,
67
  bubbleRadius,
 
68
  cardBox,
69
  clientToUser,
70
  dashPattern,
@@ -96,7 +97,7 @@ import {
96
  zoomLimits,
97
  } from "./mapProjection";
98
  import type { GeoStop, Pt, RouteStamp, View } from "./mapProjection";
99
- import { LP_INK, LP_MAP_SELECTED, LP_PURPLE, LP_PURPLE_DEEP, LP_ZONE_FILL_OPACITY, LP_ZONE_STROKE_WIDTH } from "./theme";
100
  import { RouteNav } from "./RouteNav";
101
  import { endpointRoutePlan, normalizedRouteMapLinks } from "./routeLinks";
102
  import {
@@ -343,6 +344,7 @@ const SERIES: { fill: string; line: string }[] = [
343
  * ninth colour that repeats the first would make two meanings look identical. */
344
  const OVERFLOW = { fill: "#D7DBE3", line: "#8A909C" };
345
  const DEFAULT_PIN = { fill: LP_PURPLE, line: LP_PURPLE_DEEP };
 
346
  const ZONE_COLOR_CHOICES = [
347
  { value: LP_PURPLE, label: "Purple" },
348
  { value: "#A5D8B4", label: "Green" },
@@ -3027,12 +3029,14 @@ function MapViewSurface({
3027
 
3028
  const paint = useCallback(
3029
  (p: MapPoint) => {
3030
- if (!colorBuckets) return DEFAULT_PIN;
3031
  const k = p.colorKey ?? "";
3032
- if (k === "") return OVERFLOW;
3033
- return colorBuckets.swatch.get(k) ?? OVERFLOW;
 
 
 
3034
  },
3035
- [colorBuckets]
3036
  );
3037
 
3038
  const radius = useCallback(
@@ -3704,9 +3708,10 @@ function MapViewSurface({
3704
  // unlike hover — and the hover card must stay pointer-events:none, so a link
3705
  // could never live in it without becoming a click trap.
3706
  const solo = selectedPids.size === 1 ? points.find((p) => selectedPids.has(p.pid)) : undefined;
3707
- const sizeLegend = sizeRange && !sizeRange.none && sizeRange.max > sizeRange.min
3708
- ? [sizeRange.min, (sizeRange.min + sizeRange.max) / 2, sizeRange.max]
3709
  : null;
 
3710
  const navigatorTabs = (
3711
  <div className="cg-map-navigator-tabs" role="tablist" aria-label="Map assets">
3712
  <button type="button" role="tab" aria-selected={mapNavigator === "routes"}
@@ -4562,7 +4567,7 @@ function MapViewSurface({
4562
  </div>
4563
  )}
4564
  {/* --- legends (I3/I5). Floated over the map, never in the flow. --- */}
4565
- {(colorBuckets || sizeLegend) && (
4566
  <div className="cg-map-legends">
4567
  {colorField && colorBuckets && (
4568
  <div className="cg-map-legend">
@@ -4621,6 +4626,20 @@ function MapViewSurface({
4621
  bubbles cannot differ in size.
4622
  </div>
4623
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4624
  {sizeRange.missing > 0 && (
4625
  <div className="cg-map-legend-note">
4626
  {sizeRange.missing.toLocaleString()} mapped record
 
65
  import {
66
  BASEMAP_DETAIL_K,
67
  bubbleRadius,
68
+ magnitudeDomain,
69
  cardBox,
70
  clientToUser,
71
  dashPattern,
 
97
  zoomLimits,
98
  } from "./mapProjection";
99
  import type { GeoStop, Pt, RouteStamp, View } from "./mapProjection";
100
+ import { LP_INK, LP_MAP_SELECTED, LP_PURPLE, LP_PURPLE_DEEP, LP_RED, LP_RED_DEEP, LP_ZONE_FILL_OPACITY, LP_ZONE_STROKE_WIDTH } from "./theme";
101
  import { RouteNav } from "./RouteNav";
102
  import { endpointRoutePlan, normalizedRouteMapLinks } from "./routeLinks";
103
  import {
 
344
  * ninth colour that repeats the first would make two meanings look identical. */
345
  const OVERFLOW = { fill: "#D7DBE3", line: "#8A909C" };
346
  const DEFAULT_PIN = { fill: LP_PURPLE, line: LP_PURPLE_DEEP };
347
+ const NEGATIVE_PIN = { fill: LP_RED, line: LP_RED_DEEP };
348
  const ZONE_COLOR_CHOICES = [
349
  { value: LP_PURPLE, label: "Purple" },
350
  { value: "#A5D8B4", label: "Green" },
 
3029
 
3030
  const paint = useCallback(
3031
  (p: MapPoint) => {
 
3032
  const k = p.colorKey ?? "";
3033
+ const category = !colorBuckets ? DEFAULT_PIN
3034
+ : k === "" ? OVERFLOW : colorBuckets.swatch.get(k) ?? OVERFLOW;
3035
+ // R23: the bound size measure's sign overrides its category colour.
3036
+ if (sizeField && typeof p.size === "number" && Number.isFinite(p.size) && p.size < 0) return NEGATIVE_PIN;
3037
+ return category;
3038
  },
3039
+ [colorBuckets, sizeField]
3040
  );
3041
 
3042
  const radius = useCallback(
 
3708
  // unlike hover — and the hover card must stay pointer-events:none, so a link
3709
  // could never live in it without becoming a click trap.
3710
  const solo = selectedPids.size === 1 ? points.find((p) => selectedPids.has(p.pid)) : undefined;
3711
+ const sizeDomain = sizeRange && !sizeRange.none && sizeRange.max > sizeRange.min
3712
+ ? magnitudeDomain(sizeRange.min, sizeRange.max)
3713
  : null;
3714
+ const sizeLegend = sizeDomain ? [sizeDomain.lo, (sizeDomain.lo + sizeDomain.hi) / 2, sizeDomain.hi] : null;
3715
  const navigatorTabs = (
3716
  <div className="cg-map-navigator-tabs" role="tablist" aria-label="Map assets">
3717
  <button type="button" role="tab" aria-selected={mapNavigator === "routes"}
 
4567
  </div>
4568
  )}
4569
  {/* --- legends (I3/I5). Floated over the map, never in the flow. --- */}
4570
+ {(colorBuckets || sizeLegend || (sizeField && sizeRange && sizeRange.min < 0)) && (
4571
  <div className="cg-map-legends">
4572
  {colorField && colorBuckets && (
4573
  <div className="cg-map-legend">
 
4626
  bubbles cannot differ in size.
4627
  </div>
4628
  )}
4629
+ {sizeRange.min < 0 && (
4630
+ <>
4631
+ <div className="cg-map-legend-row">
4632
+ <span
4633
+ className="cg-map-swatch"
4634
+ style={{ background: LP_RED, borderColor: LP_RED_DEEP }}
4635
+ />
4636
+ <span className="cg-map-legend-k">Negative values</span>
4637
+ </div>
4638
+ <div className="cg-map-legend-note">
4639
+ Size shows the value’s magnitude; values below zero are red.
4640
+ </div>
4641
+ </>
4642
+ )}
4643
  {sizeRange.missing > 0 && (
4644
  <div className="cg-map-legend-note">
4645
  {sizeRange.missing.toLocaleString()} mapped record
web/src/customer-grid/RecordDetail.tsx CHANGED
@@ -899,10 +899,12 @@ async function fetchModuleRelationTargets(
899
  const res = await fetch(`${API_V1}/odoo-tables/relation-targets?${query.toString()}`, {
900
  credentials: CREDENTIALS,
901
  });
902
- if (checkTenant(res)) return { ok: false, ids: [], code: "", reason: "" };
 
903
  if (res.status === 401) {
904
  signal(UNAUTHORIZED_EVENT);
905
- return { ok: false, ids: [], code: "", reason: "Your session ended. Sign in again." };
 
906
  }
907
  let body: unknown = null;
908
  try { body = await res.json(); } catch { body = null; }
@@ -921,8 +923,9 @@ async function fetchModuleRelationTargets(
921
  return {
922
  ok: false,
923
  ids: [],
924
- code: String(refusal?.code ?? "relation_target_unavailable"),
925
- reason: String(refusal?.message ?? "This relation could not be read right now. Try again."),
 
926
  table: refusal?.table,
927
  hop: refusal?.hop,
928
  };
@@ -1839,9 +1842,17 @@ export default function RecordDetail({
1839
  : await probeRelatedRead(target, asked.pin);
1840
  if (!current(asked)) continue;
1841
  commit(asked, refused ? {
1842
- status: "refused", reason: refused.reason, code: refused.code,
 
 
 
1843
  table: refused.table ?? target, hop: refused.hop,
1844
  } : { status: "ready" });
 
 
 
 
 
1845
  }
1846
  }
1847
  } finally {
 
899
  const res = await fetch(`${API_V1}/odoo-tables/relation-targets?${query.toString()}`, {
900
  credentials: CREDENTIALS,
901
  });
902
+ if (checkTenant(res)) return { ok: false, ids: [], code: "relation_workspace_changed",
903
+ reason: "This workspace changed while the relation was loading. Reopen the record." };
904
  if (res.status === 401) {
905
  signal(UNAUTHORIZED_EVENT);
906
+ return { ok: false, ids: [], code: "relation_session_ended",
907
+ reason: "Your session ended. Sign in again." };
908
  }
909
  let body: unknown = null;
910
  try { body = await res.json(); } catch { body = null; }
 
923
  return {
924
  ok: false,
925
  ids: [],
926
+ code: String(refusal?.code ?? "").trim() || "relation_target_unavailable",
927
+ reason: String(refusal?.message ?? "").trim()
928
+ ? String(refusal?.message) : "This relation could not be read right now. Try again.",
929
  table: refusal?.table,
930
  hop: refusal?.hop,
931
  };
 
1842
  : await probeRelatedRead(target, asked.pin);
1843
  if (!current(asked)) continue;
1844
  commit(asked, refused ? {
1845
+ status: "refused",
1846
+ reason: refused.reason.trim() ? refused.reason
1847
+ : "This relation could not be read right now. Try again.",
1848
+ code: refused.code.trim() || "relation_target_unavailable",
1849
  table: refused.table ?? target, hop: refused.hop,
1850
  } : { status: "ready" });
1851
+ } else {
1852
+ // C4: "no refusal renders as an empty silent tab" is structural in this drain.
1853
+ commit(asked, { status: "refused", code: "relation_target_unavailable",
1854
+ reason: "This related database cannot be opened from this record right now.",
1855
+ table: target });
1856
  }
1857
  }
1858
  } finally {
web/src/customer-grid/Toolbar.tsx CHANGED
@@ -1204,6 +1204,33 @@ export default function Toolbar({
1204
  </div>
1205
  ) : (
1206
  <>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1207
  <label className="cg-radio-row">
1208
  <input
1209
  type="radio"
@@ -1227,16 +1254,10 @@ export default function Toolbar({
1227
  <span>{f.label}</span>
1228
  </label>
1229
  ))}
1230
- {/* ⭐⭐ W50-T02 (owner instruction 2, ruling R16) — "the user can click Collapse
1231
- all and the opposite (Expand all)". Inside the NON-windowed branch on
1232
- purpose: grouping is refused outright on a windowed table one branch up, so
1233
- a fold control there could only ever refuse, and a control that can only
1234
- refuse is the fake affordance this repo bans.
1235
- ⚠ And only once something IS grouped. Ungrouped there are no groups to fold,
1236
- and the same rule applies one level down. */}
1237
  {/* ⭐⭐ W50-T04 (owner ruling R3) — "a Group Summary mode in the Group menu that
1238
  collapses the grid to ONE row per group, sortable by any aggregate and
1239
- exportable". In the NON-windowed branch, for W50-T02's reason one block down:
 
1240
  grouping is refused outright on a windowed table, so a mode that reshapes a
1241
  grouped grid could only ever refuse there.
1242
  ⚠ `cg-check-row`, the checkbox twin of the radio rows above it - the two share
@@ -1254,16 +1275,6 @@ export default function Toolbar({
1254
  <span>Summary mode</span>
1255
  </label>
1256
  )}
1257
- {groupBy !== null && onCollapseAllGroups && onExpandAllGroups && (
1258
- <div className="cg-pop-footer">
1259
- <button type="button" className="cg-link-btn" onClick={onCollapseAllGroups}>
1260
- Collapse all
1261
- </button>
1262
- <button type="button" className="cg-link-btn" onClick={onExpandAllGroups}>
1263
- Expand all
1264
- </button>
1265
- </div>
1266
- )}
1267
  </>
1268
  )}
1269
  </div>
 
1204
  </div>
1205
  ) : (
1206
  <>
1207
+ {/* ⭐⭐ W50-T02 (owner instruction 2, ruling R16) — "the user can click Collapse
1208
+ all and the opposite (Expand all)". Inside the NON-windowed branch on
1209
+ purpose: grouping is refused outright on a windowed table one branch up, so
1210
+ a fold control there could only ever refuse, and a control that can only
1211
+ refuse is the fake affordance this repo bans.
1212
+ ⚠ And only once something IS grouped. Ungrouped there are no groups to fold,
1213
+ and the same rule applies one level down.
1214
+ ⭐ W62-T20 (owner instruction 1, rulings R5 and R42) — FIRST in this branch:
1215
+ the popover has no scroll of its own and grows with the groupable field count.
1216
+ At the bottom, this pair rendered 1116px below the fold on a 61-field table
1217
+ (P5 capture B1). Position, not the control, was the defect.
1218
+ ⚠ `cg-pop-footer cg-fields-footer` keeps the base flex row and 4px gap, but
1219
+ replaces its top hairline and 6px padding with the existing quiet tray:
1220
+ `--lp-surface-2` fill, `--lp-r-md` radius and 4px padding. A hairline here
1221
+ would divide the title from the buttons and leave no boundary before the
1222
+ radio list; the tray supplies that boundary once. Its buttons keep their
1223
+ resting hairline and white hover — no new rule or containment layer. */}
1224
+ {groupBy !== null && onCollapseAllGroups && onExpandAllGroups && (
1225
+ <div className="cg-pop-footer cg-fields-footer">
1226
+ <button type="button" className="cg-link-btn" onClick={onCollapseAllGroups}>
1227
+ Collapse all
1228
+ </button>
1229
+ <button type="button" className="cg-link-btn" onClick={onExpandAllGroups}>
1230
+ Expand all
1231
+ </button>
1232
+ </div>
1233
+ )}
1234
  <label className="cg-radio-row">
1235
  <input
1236
  type="radio"
 
1254
  <span>{f.label}</span>
1255
  </label>
1256
  ))}
 
 
 
 
 
 
 
1257
  {/* ⭐⭐ W50-T04 (owner ruling R3) — "a Group Summary mode in the Group menu that
1258
  collapses the grid to ONE row per group, sortable by any aggregate and
1259
+ exportable". In the NON-windowed branch, for W50-T02's R16 reason at the top
1260
+ of this same branch, above the field list:
1261
  grouping is refused outright on a windowed table, so a mode that reshapes a
1262
  grouped grid could only ever refuse there.
1263
  ⚠ `cg-check-row`, the checkbox twin of the radio rows above it - the two share
 
1275
  <span>Summary mode</span>
1276
  </label>
1277
  )}
 
 
 
 
 
 
 
 
 
 
1278
  </>
1279
  )}
1280
  </div>
web/src/customer-grid/ViewSidebar.tsx CHANGED
@@ -10,6 +10,7 @@ import { useRailSelection } from "../ui/useRailSelection";
10
  import type { ReactNode } from "react";
11
  import type { KeyboardEvent as ReactKeyboardEvent } from "react";
12
  import { AnchoredOverlay } from "./OverlaySurface";
 
13
  import { EXPORT_FORMATS, EXPORT_LABELS, exportSelectionKey } from "./export";
14
  import type { ExportFormat } from "./export";
15
  import type {
@@ -46,6 +47,8 @@ import { FolderMark, LockMark, MenuLabel, ModeIcon, ToneModeIcon } from "./icons
46
  // the user has to read, and the frame already listens here for exactly that.
47
  import { TOAST_EVENT, WORKSPACE_STALE_EVENT, signal } from "../apiContract";
48
  import { ITEM_DELETED_EVENT, openExistingItem, useItemDeletions } from "../starred/starredApi";
 
 
49
  import type { DeletedItem } from "../starred/starredApi";
50
  import { ROOT_FOLDER_ID } from "./folders";
51
  import {
@@ -753,12 +756,23 @@ function DataDatabaseNavigator({
753
  parentOfDatabase(database),
754
  { kind: "database", key: database.key },
755
  ];
 
 
 
 
 
 
 
 
 
 
 
 
756
  const [dataPathState, setDataPathState] = useState<{
757
  levels: DataNavigatorLevel[];
758
  at: number;
759
  }>(() => {
760
- const database = databases.find((candidate) => candidate.key === activeDatabaseKey);
761
- const levels = database ? levelsForDatabase(database) : [{ kind: "root" } as const];
762
  return { levels, at: levels.length - 1 };
763
  });
764
  const activeDataKey = useRef(activeDatabaseKey);
@@ -767,10 +781,33 @@ function DataDatabaseNavigator({
767
  // during render so the newly selected database can never commit under the previous source or
768
  // folder for one frame; an effect would run after that stale frame had already painted.
769
  activeDataKey.current = activeDatabaseKey;
770
- const database = databases.find((candidate) => candidate.key === activeDatabaseKey);
771
- const levels = database ? levelsForDatabase(database) : [{ kind: "root" } as const];
772
  setDataPathState({ levels, at: levels.length - 1 });
773
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
774
  const dataLevel = dataPathState.levels[dataPathState.at] ?? { kind: "root" as const };
775
  const canDataBack = dataPathState.at > 0;
776
  /** W46-T08: the levels array was ALREADY an index into history and `pushDataLevel` already
@@ -1110,7 +1147,7 @@ function DataDatabaseNavigator({
1110
  className="cg-input"
1111
  autoFocus
1112
  value={folderName}
1113
- maxLength={40}
1114
  aria-label="Database folder name"
1115
  onChange={(event) => setFolderName(event.target.value)}
1116
  />
@@ -1563,6 +1600,7 @@ export default function ViewSidebar({
1563
  const [folderMenu, setFolderMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null);
1564
  const [renamingFolder, setRenamingFolder] = useState<string | null>(null);
1565
  const [creatingFolder, setCreatingFolder] = useState(false);
 
1566
  /**
1567
  * ⭐⭐ WAVE 41 · T33 (instruction 12, R1) — WHICH FOLDER THE DRAFT FOLDER GOES INSIDE.
1568
  *
@@ -1574,8 +1612,6 @@ export default function ViewSidebar({
1574
  * leave its parent behind for the next one.
1575
  */
1576
  const [folderParent, setFolderParent] = useState<string | null>(null);
1577
- /** The controlled folder-name draft is committed only by the explicit Create action. */
1578
- const [folderName, setFolderName] = useState("");
1579
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
1580
  const [addTarget, setAddTarget] = useState<string | null>(null);
1581
  /** The element the bulk-add pane hangs off. Anchoring to document.body
@@ -2555,8 +2591,8 @@ export default function ViewSidebar({
2555
  };
2556
  const folderDest = folderDestOf(folderParent ?? atId);
2557
 
2558
- const createFolder = () => {
2559
- const value = folderName.trim();
2560
  if (!value) return;
2561
  /*
2562
  * ⭐⭐ W47-T11 — A REFUSED NESTING IS SAID OUT LOUD AND NOTHING IS WRITTEN.
@@ -2593,8 +2629,8 @@ export default function ViewSidebar({
2593
  */
2594
  if (into) setAt(into);
2595
  onFolderCreate?.(value, into);
2596
- setFolderName("");
2597
  setCreatingFolder(false);
 
2598
  setFolderParent(null);
2599
  };
2600
 
@@ -2606,8 +2642,7 @@ export default function ViewSidebar({
2606
  * places, one beside the rail and one inside it, so step 2 read as an unrelated form.
2607
  * One panel, two contents, one geometry.
2608
  *
2609
- * The FOLDER door still closes it: that path is a single step and has no second panel
2610
- * to disagree with. Moving it too would be a change the ruling does not ask for.
2611
  */
2612
  /**
2613
  * ⭐ W46-T01 — IT TAKES A PARENT, exactly as its sibling `startFolder` already does, and the
@@ -2630,6 +2665,7 @@ export default function ViewSidebar({
2630
  * nested folder is made by the control that already makes folders, not by a second form.
2631
  */
2632
  const startFolder = (parent: string | null = null) => {
 
2633
  setCreateMenu(null);
2634
  setCreating(null);
2635
  setFolderParent(parent);
@@ -2934,60 +2970,21 @@ export default function ViewSidebar({
2934
  second step, inside the same `AnchoredOverlay` (below, next to the type list it
2935
  follows). This comment stands in for the moved markup because the move IS the
2936
  item: two steps of one action that used to appear in two different places. */}
2937
- {/* The folder form has one controlled name and one explicit commit action. */}
2938
  {foldersOn && onFolderCreate && creatingFolder && (
2939
- <div className="cg-view-create cg-create-form cg-fold-form">
2940
- {/* ⭐ W41-T33 — the label carries the DESTINATION, because the pane is the same one
2941
- for both doors and a form that cannot say where it is about to put something is a
2942
- form the user has to remember which menu they came from. One line, the folder's
2943
- own name, no explanation of what nesting is (DESIGN.md §4). */}
2944
- <label htmlFor="cg-new-folder">
2945
- {/* ⭐ W47-T11 — THE SAME RESOLVED DESTINATION THE CLICK WILL USE, `folderParent`
2946
- falling back to the folder the rail is standing in. Reading `folderParent` alone
2947
- here would now say "New folder" while Create nested it, and a label that has to
2948
- be wrong for the feature to work is the defect one layer up. A destination that
2949
- is REFUSED reads as the plain "New folder", because the pane must not advertise a
2950
- nest the Create button is about to decline. */}
2951
- {folderDest.into && folders?.find((f) => f.id === folderDest.into)
2952
- ? `New folder in ${folders.find((f) => f.id === folderDest.into)!.name}`
2953
- : "New folder"}
2954
- </label>
2955
- <input
2956
- id="cg-new-folder"
2957
- className="cg-input"
2958
- autoFocus
2959
- value={folderName}
2960
- placeholder="Folder name"
2961
- onChange={(event) => setFolderName(event.target.value)}
2962
- onKeyDown={(event) => {
2963
- if (event.key === "Enter") createFolder();
2964
- if (event.key === "Escape") {
2965
- setCreatingFolder(false);
2966
- setFolderParent(null);
2967
- }
2968
- }}
2969
- />
2970
- <div className="cg-form-actions">
2971
- <button
2972
- type="button"
2973
- className="cg-btn cg-btn--primary"
2974
- onClick={createFolder}
2975
- disabled={!folderName.trim()}
2976
- >
2977
- Create
2978
- </button>
2979
- <button
2980
- type="button"
2981
- className="cg-btn"
2982
- onClick={() => {
2983
- setCreatingFolder(false);
2984
- setFolderParent(null);
2985
- }}
2986
- >
2987
- Cancel
2988
- </button>
2989
- </div>
2990
- </div>
2991
  )}
2992
 
2993
  {/* I14 — the flyout. To the RIGHT (placement right-start), every creatable view type
 
10
  import type { ReactNode } from "react";
11
  import type { KeyboardEvent as ReactKeyboardEvent } from "react";
12
  import { AnchoredOverlay } from "./OverlaySurface";
13
+ import FolderNameDialog, { FOLDER_NAME_MAX } from "../home/FolderNameDialog";
14
  import { EXPORT_FORMATS, EXPORT_LABELS, exportSelectionKey } from "./export";
15
  import type { ExportFormat } from "./export";
16
  import type {
 
47
  // the user has to read, and the frame already listens here for exactly that.
48
  import { TOAST_EVENT, WORKSPACE_STALE_EVENT, signal } from "../apiContract";
49
  import { ITEM_DELETED_EVENT, openExistingItem, useItemDeletions } from "../starred/starredApi";
50
+ // C6 / R52 shares only the address's folder stratum with chrome; dataPath.ts still owns grid paths.
51
+ import { readDataAddress } from "../shell/nav";
52
  import type { DeletedItem } from "../starred/starredApi";
53
  import { ROOT_FOLDER_ID } from "./folders";
54
  import {
 
756
  parentOfDatabase(database),
757
  { kind: "database", key: database.key },
758
  ];
759
+ const levelsForAddress = (): DataNavigatorLevel[] => {
760
+ const database = databases.find((candidate) => candidate.key === activeDatabaseKey);
761
+ const folder = readDataAddress().folder;
762
+ if (folder && folders.some((candidate) => candidate.id === folder)) {
763
+ return [
764
+ { kind: "root" },
765
+ { kind: "folder", id: folder },
766
+ ...(database ? [{ kind: "database" as const, key: database.key }] : []),
767
+ ];
768
+ }
769
+ return database ? levelsForDatabase(database) : [{ kind: "root" }];
770
+ };
771
  const [dataPathState, setDataPathState] = useState<{
772
  levels: DataNavigatorLevel[];
773
  at: number;
774
  }>(() => {
775
+ const levels = levelsForAddress();
 
776
  return { levels, at: levels.length - 1 };
777
  });
778
  const activeDataKey = useRef(activeDatabaseKey);
 
781
  // during render so the newly selected database can never commit under the previous source or
782
  // folder for one frame; an effect would run after that stale frame had already painted.
783
  activeDataKey.current = activeDatabaseKey;
784
+ const levels = levelsForAddress();
 
785
  setDataPathState({ levels, at: levels.length - 1 });
786
  }
787
+ const seenAddressFolder = useRef<string | undefined>(undefined);
788
+ useEffect(() => {
789
+ const syncAddressFolder = () => {
790
+ const levels = levelsForAddress();
791
+ const addressedFolder = levels.find((level) => level.kind === "folder")?.id;
792
+ seenAddressFolder.current = addressedFolder;
793
+ setDataPathState((current) => {
794
+ const standing = current.levels[current.at];
795
+ const standingFolder = standing?.kind === "folder" ? standing.id
796
+ : standing?.kind === "database"
797
+ ? current.levels.slice(0, current.at).reverse().find((level) => level.kind === "folder")?.id
798
+ : undefined;
799
+ // A view-only hash change must not reset history when the rail is already in this folder.
800
+ if (addressedFolder === standingFolder) return current;
801
+ return { levels, at: levels.length - 1 };
802
+ });
803
+ };
804
+ // Folder metadata may arrive after mount. Resolve it once without undoing later rail browsing.
805
+ const folder = readDataAddress().folder;
806
+ if (folder && folder !== seenAddressFolder.current
807
+ && folders.some((candidate) => candidate.id === folder)) syncAddressFolder();
808
+ window.addEventListener("hashchange", syncAddressFolder);
809
+ return () => window.removeEventListener("hashchange", syncAddressFolder);
810
+ }, [activeDatabaseKey, databases, folders]);
811
  const dataLevel = dataPathState.levels[dataPathState.at] ?? { kind: "root" as const };
812
  const canDataBack = dataPathState.at > 0;
813
  /** W46-T08: the levels array was ALREADY an index into history and `pushDataLevel` already
 
1147
  className="cg-input"
1148
  autoFocus
1149
  value={folderName}
1150
+ maxLength={FOLDER_NAME_MAX}
1151
  aria-label="Database folder name"
1152
  onChange={(event) => setFolderName(event.target.value)}
1153
  />
 
1600
  const [folderMenu, setFolderMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null);
1601
  const [renamingFolder, setRenamingFolder] = useState<string | null>(null);
1602
  const [creatingFolder, setCreatingFolder] = useState(false);
1603
+ const [folderAnchor, setFolderAnchor] = useState<HTMLElement | null>(null);
1604
  /**
1605
  * ⭐⭐ WAVE 41 · T33 (instruction 12, R1) — WHICH FOLDER THE DRAFT FOLDER GOES INSIDE.
1606
  *
 
1612
  * leave its parent behind for the next one.
1613
  */
1614
  const [folderParent, setFolderParent] = useState<string | null>(null);
 
 
1615
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
1616
  const [addTarget, setAddTarget] = useState<string | null>(null);
1617
  /** The element the bulk-add pane hangs off. Anchoring to document.body
 
2591
  };
2592
  const folderDest = folderDestOf(folderParent ?? atId);
2593
 
2594
+ const createFolder = (name: string) => {
2595
+ const value = name.trim();
2596
  if (!value) return;
2597
  /*
2598
  * ⭐⭐ W47-T11 — A REFUSED NESTING IS SAID OUT LOUD AND NOTHING IS WRITTEN.
 
2629
  */
2630
  if (into) setAt(into);
2631
  onFolderCreate?.(value, into);
 
2632
  setCreatingFolder(false);
2633
+ setFolderAnchor(null);
2634
  setFolderParent(null);
2635
  };
2636
 
 
2642
  * places, one beside the rail and one inside it, so step 2 read as an unrelated form.
2643
  * One panel, two contents, one geometry.
2644
  *
2645
+ * The folder door closes the menu and opens the shared naming popup at that same trigger.
 
2646
  */
2647
  /**
2648
  * ⭐ W46-T01 — IT TAKES A PARENT, exactly as its sibling `startFolder` already does, and the
 
2665
  * nested folder is made by the control that already makes folders, not by a second form.
2666
  */
2667
  const startFolder = (parent: string | null = null) => {
2668
+ setFolderAnchor(createMenu ?? folderMenu?.anchor ?? null);
2669
  setCreateMenu(null);
2670
  setCreating(null);
2671
  setFolderParent(parent);
 
2970
  second step, inside the same `AnchoredOverlay` (below, next to the type list it
2971
  follows). This comment stands in for the moved markup because the move IS the
2972
  item: two steps of one action that used to appear in two different places. */}
 
2973
  {foldersOn && onFolderCreate && creatingFolder && (
2974
+ <FolderNameDialog
2975
+ anchor={folderAnchor}
2976
+ title={folderDest.into && folders?.find((folder) => folder.id === folderDest.into)
2977
+ ? `New folder in ${folders.find((folder) => folder.id === folderDest.into)!.name}`
2978
+ : "New folder"}
2979
+ siblingNames={(folders ?? []).filter((folder) =>
2980
+ (nesting.parent[folder.id] ?? null) === folderDest.into).map((folder) => folder.name)}
2981
+ onSubmit={createFolder}
2982
+ onDismiss={() => {
2983
+ setCreatingFolder(false);
2984
+ setFolderAnchor(null);
2985
+ setFolderParent(null);
2986
+ }}
2987
+ />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2988
  )}
2989
 
2990
  {/* I14 — the flyout. To the RIGHT (placement right-start), every creatable view type
web/src/customer-grid/apiBridge.ts CHANGED
@@ -51,6 +51,8 @@ import {
51
  checkTenant,
52
  signal,
53
  } from "../apiContract";
 
 
54
  import { setStandaloneSink } from "./hostBridge";
55
  import { changedBuckets } from "./liveWorkspace";
56
  import type { ChangeTokens } from "./liveWorkspace";
@@ -163,7 +165,21 @@ function handledUnauthorized(status: number): boolean {
163
  * here keeps returning a cheerful 200 full of somebody else's data. `checkTenant` reads the
164
  * server's own stamp and reloads the frame; see `apiContract.ts::TENANT_HEADER`.
165
  */
166
- function handledSession(res: Response): boolean {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  if (checkTenant(res)) return true;
168
  return handledUnauthorized(res.status);
169
  }
@@ -307,11 +323,175 @@ export function refusalMessage(body: unknown, status: number, fallback?: string)
307
  return fallback ?? `The server answered ${status}.`;
308
  }
309
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
  export async function fetchTopicRows(topic: TopicConfig): Promise<CustomersPayload | null> {
311
  const cached = rowsCache.get(topic.rowsPath);
312
  if (cached && Date.now() - cached.at < CUSTOMERS_FRESH_MS) {
313
  return cached.payload;
314
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  let res: Response;
316
  try {
317
  res = await fetch(`${API_V1}/${topic.rowsPath}`, { credentials: CREDENTIALS });
 
51
  checkTenant,
52
  signal,
53
  } from "../apiContract";
54
+ import { ROWS_CHUNK } from "./pipelineWorker";
55
+ import type { RowsReply, RowsRequest } from "./pipelineWorker";
56
  import { setStandaloneSink } from "./hostBridge";
57
  import { changedBuckets } from "./liveWorkspace";
58
  import type { ChangeTokens } from "./liveWorkspace";
 
165
  * here keeps returning a cheerful 200 full of somebody else's data. `checkTenant` reads the
166
  * server's own stamp and reloads the frame; see `apiContract.ts::TENANT_HEADER`.
167
  */
168
+ /**
169
+ * ⭐ W62-T18 — WIDENED FROM `Response` TO WHAT IT ACTUALLY READS, and no further. A `Response`
170
+ * still satisfies it, so every existing call site is unchanged; what it now also accepts is the
171
+ * `{status, headers}` shim `rowsThroughWorker` builds from the worker's reply, because a worker
172
+ * that did the fetch holds no `Response` for the main thread to hand over. `checkTenant` was
173
+ * already written to this structural type (`apiContract.ts:99`) — this brings its caller into
174
+ * line rather than inventing a second session check for the worker path, which is the one way
175
+ * a tenant swap could have been missed on the read that matters most.
176
+ */
177
+ interface SessionFacts {
178
+ status: number;
179
+ headers: { get(name: string): string | null };
180
+ }
181
+
182
+ function handledSession(res: SessionFacts): boolean {
183
  if (checkTenant(res)) return true;
184
  return handledUnauthorized(res.status);
185
  }
 
323
  return fallback ?? `The server answered ${status}.`;
324
  }
325
 
326
+ /**
327
+ * ⭐⭐ W62-T18 / R51 — THE ROWS READ, OFF THE MAIN THREAD, IN BOUNDED PIECES.
328
+ *
329
+ * ⛔ THE MEASUREMENT IS THE WHOLE ARGUMENT, and it is committed beside this code in
330
+ * `AutoWiki/waves/wave62/proto/T18-measure.md`. On staging's `sale.order.line.agent` database
331
+ * (137,327 rows, 13 columns) the rows body is **69,944,226 bytes** (5.69 MB gzipped on the wire).
332
+ * `await res.json()` over it cost **731 ms** unthrottled and **2,916 ms** at 4x CPU throttling,
333
+ * and produced the only main-thread tasks over 200 ms in the whole open: 355 ms unthrottled,
334
+ * **1,523 ms and 1,384 ms** throttled. A CPU profile of the same open attributes 870.6 ms of self
335
+ * time to V8's `(program)` (the native parse) and 168.6 ms to the collector, against **22.6 ms
336
+ * for the largest application frame in the profile**. The freeze is this one line, not the grid.
337
+ *
338
+ * ⛔ AND IT IS NOT THE PIPELINE, WHICH IS WHERE THE TICKET POINTED FIRST. `runPipeline` over the
339
+ * same 137,327 rows costs 20-39 ms on open and 67-101 ms on a filter change; typing five
340
+ * characters into the search box produced five tasks, none over 102 ms. Moving THAT to a worker
341
+ * would have bought nothing and cost every feature R28 protects its synchronous access to the
342
+ * rows. R51 asked for the cost to be measured before it was fixed; this is what the measurement
343
+ * changed.
344
+ *
345
+ * ⛔ CHUNKED, BECAUSE ONE MESSAGE IS ONE TASK. The worker could hand the whole payload back in a
346
+ * single `postMessage` (measured: 472 ms of main-thread wall unthrottled, 1,314 ms at 4x), or
347
+ * columnar with a rebuild on this side (measured: a 256 ms rebuild at 4x — over budget on its
348
+ * own). Ten-thousand-row slices measured 208 ms total unthrottled with NO long task recorded at
349
+ * all, and a worst task of **70 ms** at 4x. The bound is the point: each slice is deserialised in
350
+ * its own task, so the main thread stays interruptible however far the table grows.
351
+ * ⚠ 2,000-row slices measured WORSE at both speeds (293 ms / 1,131 ms, the only long tasks the
352
+ * experiment recorded on any chunked leg) — per-message overhead and the garbage it makes. Do not
353
+ * "tune" this down without re-running the experiment in that file.
354
+ *
355
+ * ⭐ NO CAP, ANYWHERE (standing rule 1). Every row the server sends is accumulated and handed to
356
+ * the caller; the chunking is a delivery schedule, not a window. There is no paging, no "See
357
+ * more" and no second virtualiser — the grid is still glide's canvas.
358
+ *
359
+ * ⚠ ONE WORKER, REUSED, AND IT MAY REFUSE TO EXIST. Any environment without `Worker` (the gates
360
+ * execute parts of this client under node) or any construction failure falls back to the old
361
+ * main-thread read, which is exactly today's behaviour. `workerDead` latches so a browser that
362
+ * cannot build workers pays the attempt once rather than once per read.
363
+ */
364
+ let rowsWorker: Worker | null = null;
365
+ let rowsWorkerDead = false;
366
+ let rowsRequestId = 0;
367
+
368
+ function theRowsWorker(): Worker | null {
369
+ if (rowsWorkerDead) return null;
370
+ if (rowsWorker) return rowsWorker;
371
+ try {
372
+ if (typeof Worker === "undefined") { rowsWorkerDead = true; return null; }
373
+ rowsWorker = new Worker(new URL("./pipelineWorker.ts", import.meta.url), { type: "module" });
374
+ // An error that reaches here killed the worker, not one read: drop it and let the next
375
+ // caller take the main-thread path rather than wait on a worker that cannot answer.
376
+ rowsWorker.addEventListener("error", () => {
377
+ rowsWorkerDead = true;
378
+ try { rowsWorker?.terminate(); } catch { /* already gone */ }
379
+ rowsWorker = null;
380
+ });
381
+ return rowsWorker;
382
+ } catch {
383
+ rowsWorkerDead = true;
384
+ rowsWorker = null;
385
+ return null;
386
+ }
387
+ }
388
+
389
+ /** The worker's header map as something `checkTenant`/`handledSession` can read. Case-insensitive,
390
+ * like the `Headers.get` it stands in for. */
391
+ function headerReader(map: Record<string, string>): SessionFacts["headers"] {
392
+ return { get: (name: string) => map[name.toLowerCase()] ?? null };
393
+ }
394
+
395
+ /** What `rowsThroughWorker` hands back: the same three outcomes the main-thread read has, kept
396
+ * apart so the caller raises exactly what it raises today. */
397
+ type WorkerRead =
398
+ | { ok: true; payload: unknown; facts: SessionFacts }
399
+ | { ok: false; kind: "refused"; body: unknown; facts: SessionFacts }
400
+ | { ok: false; kind: "unavailable" };
401
+
402
+ /**
403
+ * ⚠ NO TIMEOUT HERE, AND THAT IS A DECISION RATHER THAN AN OVERSIGHT. A worker that dies loudly
404
+ * raises `error` (the listener above retires it) and a fetch that fails posts `failed`, so both
405
+ * realistic failures already fall back. What is left uncovered is a worker that hangs silently -
406
+ * and the main-thread read this replaces has no timeout either, so a timer here would not close a
407
+ * gap, it would only add a way to fire DURING a healthy read: this table's own rows request
408
+ * measured 10-48 s, so any bound short enough to be useful is short enough to re-request 66.7 MB
409
+ * that was already on its way.
410
+ */
411
+ function rowsThroughWorker(url: string): Promise<WorkerRead> {
412
+ const worker = theRowsWorker();
413
+ if (!worker) return Promise.resolve({ ok: false, kind: "unavailable" });
414
+ const id = ++rowsRequestId;
415
+ return new Promise<WorkerRead>((resolve) => {
416
+ let head: Record<string, unknown> | null = null;
417
+ let facts: SessionFacts | null = null;
418
+ /* ⭐ PRE-ALLOCATED FROM THE HEAD'S OWN `total`, and it is worth the extra field. Measured at 4x
419
+ CPU throttling on the 137,327-row table: growing this array with `push` cost 1,038 ms of
420
+ main-thread self time - the single largest application frame in the whole profiled open,
421
+ ahead of the pipeline (133 ms) and React's own commit - because a 137k-element array grows
422
+ by reallocating and copying about twenty times on the way up. Writing into a right-sized
423
+ array at a running offset pays none of that. The bound per slice is unchanged; what goes
424
+ away is the copying between slices. */
425
+ let rows: unknown[] = [];
426
+ let filled = 0;
427
+ const finish = (result: WorkerRead): void => {
428
+ worker.removeEventListener("message", onMessage);
429
+ resolve(result);
430
+ };
431
+ const onMessage = (event: MessageEvent<RowsReply>): void => {
432
+ const reply = event.data;
433
+ // ⚠ ONE WORKER SERVES EVERY READER, so a reply that is not this request's is another
434
+ // caller's rows. Ignoring it here is what makes the shared worker safe.
435
+ if (!reply || reply.id !== id) return;
436
+ if (reply.op === "head") {
437
+ head = reply.head;
438
+ facts = { status: reply.status, headers: headerReader(reply.headers) };
439
+ rows = new Array(reply.total);
440
+ filled = 0;
441
+ } else if (reply.op === "slice") {
442
+ // A loop, not `push(...slice)`: spreading 10,000 arguments is a stack overflow on some
443
+ // engines, and this path exists to be dependable on a big table.
444
+ // ⚠ `filled` rather than the array's length, because the array is already at its final
445
+ // length. A server that sent more rows than its own `total` still lands them all - the
446
+ // assignment grows the array the ordinary way - so this cannot drop a row.
447
+ for (let i = 0; i < reply.slice.length; i += 1) rows[filled + i] = reply.slice[i];
448
+ filled += reply.slice.length;
449
+ } else if (reply.op === "refused") {
450
+ finish({ ok: false, kind: "refused", body: reply.body,
451
+ facts: { status: reply.status, headers: headerReader(reply.headers) } });
452
+ } else if (reply.op === "failed") {
453
+ // The fetch never happened, or the body was unreadable. Fall back rather than raise: the
454
+ // main-thread read owns those two messages and must keep owning them.
455
+ finish({ ok: false, kind: "unavailable" });
456
+ } else if (reply.op === "done") {
457
+ if (!head || !facts) finish({ ok: false, kind: "unavailable" });
458
+ // A short count means a slice was lost between the two threads. Trimming keeps the array
459
+ // honest rather than handing the grid trailing holes that read as blank records.
460
+ else finish({ ok: true, payload: { ...head, rows: filled === rows.length ? rows : rows.slice(0, filled) }, facts });
461
+ }
462
+ };
463
+ worker.addEventListener("message", onMessage);
464
+ try {
465
+ worker.postMessage({ id, url, chunk: ROWS_CHUNK } satisfies RowsRequest);
466
+ } catch {
467
+ finish({ ok: false, kind: "unavailable" });
468
+ }
469
+ });
470
+ }
471
+
472
  export async function fetchTopicRows(topic: TopicConfig): Promise<CustomersPayload | null> {
473
  const cached = rowsCache.get(topic.rowsPath);
474
  if (cached && Date.now() - cached.at < CUSTOMERS_FRESH_MS) {
475
  return cached.payload;
476
  }
477
+ // ⭐ W62-T18 — the worker leg FIRST, the main-thread read below as the fallback. Both end in
478
+ // the same three outcomes and the same cache write; what differs is only which thread pays for
479
+ // `JSON.parse`. See `rowsThroughWorker` for the measurement that put it here.
480
+ const offThread = await rowsThroughWorker(`${API_V1}/${topic.rowsPath}`);
481
+ if (offThread.ok || offThread.kind === "refused") {
482
+ if (handledSession(offThread.facts)) return null;
483
+ if (!offThread.ok) {
484
+ signal(DATA_ERROR_EVENT, refusalMessage(offThread.body, offThread.facts.status));
485
+ return null;
486
+ }
487
+ const carried = offThread.payload as CustomersPayload | null;
488
+ if (!carried || !Array.isArray(carried.rows) || !Array.isArray(carried.fields)) {
489
+ signal(DATA_ERROR_EVENT, "The server sent an unreadable payload.");
490
+ return null;
491
+ }
492
+ rowsCache.set(topic.rowsPath, { at: Date.now(), payload: carried });
493
+ return carried;
494
+ }
495
  let res: Response;
496
  try {
497
  res = await fetch(`${API_V1}/${topic.rowsPath}`, { credentials: CREDENTIALS });
web/src/customer-grid/mapProjection.ts CHANGED
@@ -895,10 +895,23 @@ export function normRect(ax: number, ay: number, bx: number, by: number) {
895
  };
896
  }
897
 
 
 
 
 
 
 
 
898
  /**
899
- * Bubble radius for a value under a sqrt scale (I5). AREA is proportional to
900
- * the value, which is the only honest way to size a circle — radius-proportional
901
  * bubbles overstate large values by the square, the classic bubble-chart lie.
 
 
 
 
 
 
902
  * `null`/non-finite gets `rNull`: a value-less row is drawn small, never hidden
903
  * and never faked (rule 8b).
904
  */
@@ -912,7 +925,8 @@ export function bubbleRadius(
912
  ): number {
913
  if (v == null || !Number.isFinite(v)) return rNull;
914
  if (!(max > min)) return (rMin + rMax) / 2;
915
- const t = Math.max(0, Math.min(1, (v - min) / (max - min)));
 
916
  return Math.sqrt(rMin * rMin + t * (rMax * rMax - rMin * rMin));
917
  }
918
 
 
895
  };
896
  }
897
 
898
+ /** The shared magnitude domain for bubbles and their size key (W62-T21, R24). */
899
+ export function magnitudeDomain(min: number, max: number): { lo: number; hi: number } {
900
+ if (min >= 0) return { lo: min, hi: max };
901
+ if (max <= 0) return { lo: -max, hi: -min };
902
+ return { lo: 0, hi: Math.max(-min, max) };
903
+ }
904
+
905
  /**
906
+ * Bubble radius for a value under a sqrt scale (I5). AREA is the honest scale:
907
+ * it grows linearly with magnitude — radius-proportional
908
  * bubbles overstate large values by the square, the classic bubble-chart lie.
909
+ * R24 requires one scale over magnitude; colour alone carries the sign, so
910
+ * equal positive and negative magnitudes draw the same radius.
911
+ * For a non-negative range, magnitude IS the value and the domain is unchanged:
912
+ * the same arithmetic preserves today's picture, without a separate size scale.
913
+ * Once max > min, hi > lo: the magnitude span is max - min for either one-sign
914
+ * range, and max(-min, max) > 0 for a range straddling zero.
915
  * `null`/non-finite gets `rNull`: a value-less row is drawn small, never hidden
916
  * and never faked (rule 8b).
917
  */
 
925
  ): number {
926
  if (v == null || !Number.isFinite(v)) return rNull;
927
  if (!(max > min)) return (rMin + rMax) / 2;
928
+ const { lo, hi } = magnitudeDomain(min, max);
929
+ const t = Math.max(0, Math.min(1, (Math.abs(v) - lo) / (hi - lo)));
930
  return Math.sqrt(rMin * rMin + t * (rMax * rMax - rMin * rMin));
931
  }
932
 
web/src/customer-grid/pipelineWorker.ts ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / pipelineWorker.ts
3
+ // THE ROWS WORKER: fetch one rows payload and PARSE it off the main thread,
4
+ // then hand the rows back in bounded chunks.
5
+ //
6
+ // ⭐⭐ W62-T18 / R51 — WHY THIS FILE PARSES INSTEAD OF RUNNING THE PIPELINE.
7
+ // The ticket's candidate fix was "move the pipeline to a Web Worker". R51 said
8
+ // MEASURE FIRST, and the measurement (`AutoWiki/waves/wave62/proto/T18-measure.md`)
9
+ // refused that candidate: over the real 137,327-row `sale.order.line.agent`
10
+ // payload, `useVisibleRows.runPipeline` costs 20-39 ms on open and 67-101 ms on a
11
+ // filter change, while `Response.json()` over the 69,944,226-byte body costs
12
+ // 707-731 ms and is what produced BOTH of the >200 ms main-thread tasks in the
13
+ // before trace. The pipeline was never the freeze; the parse was. So the worker
14
+ // this file names takes the PARSE, and the pipeline stays exactly where it is,
15
+ // synchronous and on the main thread, where every feature R28 protects can keep
16
+ // reading it.
17
+ //
18
+ // ⛔ AND IT IS NOT A SECOND VIRTUALISER. Nothing here decides what is painted:
19
+ // every row this worker reads is handed to the caller, and the grid is still
20
+ // glide's canvas (F-CORR-1). There is no cap, no window and no paging in this
21
+ // file - standing rule 1 holds on the wire and holds here.
22
+ //
23
+ // ⛔ CHUNKED BECAUSE ONE MESSAGE IS ONE TASK. Handing 137,327 rows back in a
24
+ // single `postMessage` measured 472 ms of main-thread work; handing them back in
25
+ // 10,000-row slices measured 208 ms across FOURTEEN tasks, none of which the long
26
+ // task observer recorded at all. The bound is what matters, not the total: a
27
+ // chunk is deserialised in its own task, so the main thread stays interruptible
28
+ // however large the table grows.
29
+ // ---------------------------------------------------------------------------
30
+
31
+ /** Rows per `slice` message. Measured: 5,000 / 10,000 / 20,000 all produced ZERO
32
+ * long tasks unthrottled; 10,000 was the cheapest overall (208 ms against 216 and
33
+ * 226). Smaller is not safer - 2,000 measured WORSE (265 ms, and the one long task
34
+ * the whole experiment saw), because per-message overhead starts to dominate. */
35
+ export const ROWS_CHUNK = 10000;
36
+
37
+ /** What the main thread asks for. `id` pairs a reply with its request, so one
38
+ * worker can serve concurrent readers without interleaving their rows. */
39
+ export interface RowsRequest {
40
+ id: number;
41
+ url: string;
42
+ chunk?: number;
43
+ }
44
+
45
+ /** The envelope minus its rows, plus what the caller needs to reproduce today's
46
+ * session and refusal handling without holding a `Response`. */
47
+ export interface RowsHead {
48
+ id: number;
49
+ op: "head";
50
+ head: Record<string, unknown>;
51
+ total: number;
52
+ status: number;
53
+ headers: Record<string, string>;
54
+ }
55
+
56
+ export interface RowsSlice { id: number; op: "slice"; slice: unknown[] }
57
+ export interface RowsDone { id: number; op: "done" }
58
+ /** A non-2xx answer. The body rides along already parsed - a refusal body is
59
+ * small, and `refusalMessage` must see the same object it sees today. */
60
+ export interface RowsRefused {
61
+ id: number;
62
+ op: "refused";
63
+ status: number;
64
+ headers: Record<string, string>;
65
+ body: unknown;
66
+ }
67
+ /** The fetch itself never happened (offline, DNS, abort). Distinct from a
68
+ * refusal, because the two raise different things on the main thread. */
69
+ export interface RowsFailed { id: number; op: "failed"; why: string }
70
+
71
+ export type RowsReply = RowsHead | RowsSlice | RowsDone | RowsRefused | RowsFailed;
72
+
73
+ /** Headers as a plain object the structured clone can carry. Lower-cased keys,
74
+ * so the `get` shim on the other side can be case-insensitive the way
75
+ * `Headers.get` is. */
76
+ function headerMap(res: Response): Record<string, string> {
77
+ const out: Record<string, string> = {};
78
+ try {
79
+ res.headers.forEach((value, key) => { out[key.toLowerCase()] = value; });
80
+ } catch {
81
+ /* a Headers object that refuses to iterate is not worth failing the read over */
82
+ }
83
+ return out;
84
+ }
85
+
86
+ async function serve(req: RowsRequest): Promise<void> {
87
+ const chunk = req.chunk && req.chunk > 0 ? req.chunk : ROWS_CHUNK;
88
+ let res: Response;
89
+ try {
90
+ // ⚠ The literal rather than `apiContract.CREDENTIALS`, deliberately: importing that module
91
+ // here would pull the app's event bus and its `window` reads into the worker bundle, where
92
+ // there is no window. It is the same value ("same-origin") and `verify_api.py` is not the
93
+ // gate that holds it - if that constant ever changes, this line is the second site.
94
+ res = await fetch(req.url, { credentials: "same-origin" });
95
+ } catch (err) {
96
+ post({ id: req.id, op: "failed", why: String(err) });
97
+ return;
98
+ }
99
+ const headers = headerMap(res);
100
+ if (!res.ok) {
101
+ let body: unknown = null;
102
+ try { body = await res.json(); } catch { body = null; }
103
+ post({ id: req.id, op: "refused", status: res.status, headers, body });
104
+ return;
105
+ }
106
+ let payload: Record<string, unknown> | null = null;
107
+ try {
108
+ payload = (await res.json()) as Record<string, unknown> | null;
109
+ } catch (err) {
110
+ post({ id: req.id, op: "failed", why: `unreadable payload: ${String(err)}` });
111
+ return;
112
+ }
113
+ if (!payload || typeof payload !== "object") {
114
+ post({ id: req.id, op: "failed", why: "the payload was not an object" });
115
+ return;
116
+ }
117
+ const rows = Array.isArray(payload.rows) ? (payload.rows as unknown[]) : null;
118
+ if (!rows) {
119
+ // Not a rows envelope. Hand the whole thing over as the head so the caller's
120
+ // own shape check produces the message it produces today, rather than this
121
+ // worker inventing a second vocabulary for the same failure.
122
+ post({ id: req.id, op: "head", head: payload, total: 0, status: res.status, headers });
123
+ post({ id: req.id, op: "done" });
124
+ return;
125
+ }
126
+ const head: Record<string, unknown> = {};
127
+ for (const key of Object.keys(payload)) if (key !== "rows") head[key] = payload[key];
128
+ post({ id: req.id, op: "head", head, total: rows.length, status: res.status, headers });
129
+ for (let i = 0; i < rows.length; i += chunk) post({ id: req.id, op: "slice", slice: rows.slice(i, i + chunk) });
130
+ post({ id: req.id, op: "done" });
131
+ }
132
+
133
+ function post(reply: RowsReply): void {
134
+ (self as unknown as { postMessage(m: RowsReply): void }).postMessage(reply);
135
+ }
136
+
137
+ /**
138
+ * ⛔ THE HANDLER INSTALLS IN A WORKER AND NOWHERE ELSE, and the guard is load-bearing rather than
139
+ * defensive. `apiBridge.ts` imports `ROWS_CHUNK` and the message types from this same module so
140
+ * the two sides cannot drift, which means this file is ALSO evaluated on the main thread — where
141
+ * an unguarded `self.onmessage = ...` would install a handler on `window` and swallow every
142
+ * `postMessage` the app makes to itself. A worker has `self` and no `window`; the main thread has
143
+ * both; node (where the gates execute parts of this client) has neither.
144
+ */
145
+ const IN_WORKER =
146
+ typeof self !== "undefined" &&
147
+ typeof (globalThis as { window?: unknown }).window === "undefined";
148
+
149
+ if (IN_WORKER) {
150
+ self.onmessage = (event: MessageEvent<RowsRequest>) => {
151
+ const req = event.data;
152
+ if (!req || typeof req.url !== "string") return;
153
+ void serve(req);
154
+ };
155
+ }
web/src/home/FolderNameDialog.tsx ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useState } from "react";
2
+ import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
3
+
4
+ export const FOLDER_NAME_MAX = 40;
5
+
6
+ interface FolderNameDialogProps {
7
+ anchor: HTMLElement | null;
8
+ title: string;
9
+ initialName?: string;
10
+ siblingNames: readonly string[];
11
+ onSubmit(name: string): void;
12
+ onDismiss(): void;
13
+ disabled?: boolean;
14
+ disabledReason?: string;
15
+ }
16
+
17
+ export default function FolderNameDialog({
18
+ anchor, title, initialName = "", siblingNames, onSubmit, onDismiss,
19
+ disabled = false, disabledReason,
20
+ }: FolderNameDialogProps) {
21
+ const [name, setName] = useState(() => initialName.slice(0, FOLDER_NAME_MAX));
22
+ // autoFocus can precede the overlay's opener capture. Restore the supplied trigger
23
+ // after removal too, when the captured input is no longer connected.
24
+ useEffect(() => () => {
25
+ if (anchor?.isConnected) anchor.focus({ preventScroll: true });
26
+ }, [anchor]);
27
+ const clean = name.trim();
28
+ const duplicate = siblingNames.some((sibling) => sibling.trim().toLowerCase() === clean.toLowerCase());
29
+ const disabledStyle = disabled ? { opacity: 0.45, cursor: "not-allowed" } : undefined;
30
+
31
+ return (
32
+ <AnchoredOverlay
33
+ anchor={anchor}
34
+ className="cg-view-menu"
35
+ role="dialog"
36
+ ariaLabel={title}
37
+ placement="right-start"
38
+ onDismiss={onDismiss}
39
+ >
40
+ <form className="cg-data-folder-rename" onSubmit={(event) => {
41
+ event.preventDefault();
42
+ if (disabled || !clean || duplicate) return;
43
+ onSubmit(clean);
44
+ }}>
45
+ <input
46
+ className="cg-input"
47
+ autoFocus
48
+ aria-label="Folder name"
49
+ maxLength={FOLDER_NAME_MAX}
50
+ value={name}
51
+ disabled={disabled}
52
+ title={disabledReason}
53
+ style={disabledStyle}
54
+ aria-invalid={duplicate || undefined}
55
+ onChange={(event) => setName(event.currentTarget.value.slice(0, FOLDER_NAME_MAX))}
56
+ />
57
+ {duplicate ? <p role="alert">That folder name is already taken. Pick another one.</p> : null}
58
+ <button type="submit" className="cg-btn cg-btn--primary"
59
+ disabled={disabled || !clean} title={disabledReason} style={disabledStyle}>
60
+ Save
61
+ </button>
62
+ </form>
63
+ </AnchoredOverlay>
64
+ );
65
+ }
web/src/home/HomePage.tsx CHANGED
@@ -28,6 +28,7 @@ import { SHEET_SHAPE } from "../customer-grid/iconShapes";
28
  import { appPathHash } from "../customer-grid/dataPath";
29
  import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
30
  import DatabaseTile from "./DatabaseTile";
 
31
  // R16: Home and Data need the hollow glyph's box without loading the grid chunk.
32
  import "../styles/wave50/rail.css";
33
  import "../styles/wave57/home-app.css";
@@ -36,10 +37,9 @@ import "../styles/wave61/home.css";
36
  import "../styles/wave46/rail-select.css";
37
  import "../styles/wave61/rails.css";
38
  import { AGENTS_MODULE_LABEL } from "../inbox/inboxModel";
39
- import { Mark } from "../shell/Brand";
40
  // AgentIcon carries the rail's shell-nav-icon class, which supplies its stroke-only paint.
41
  import { AgentIcon } from "../shell/icons";
42
- import { agentAddressHash, MAX_NAV_FOLDERS } from "../shell/nav";
43
  import type { DatabaseEntry, NavFolder, Recent } from "../shell/nav";
44
  import { API_V1, CREDENTIALS } from "../apiContract";
45
  // ⭐ WAVE 35 · W35-T15 (R4, C2) — ONE STAR CONTROL, drawn in the module that owns the concept and
@@ -69,6 +69,21 @@ import {
69
  } from "./homeModel";
70
  import type { AutomationTile, HomeFilter, HomeLayout, ModuleFolderIndex } from "./homeModel";
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  // ── the four quick-start marks ───────────────────────────────────────────────────────────────
73
  //
74
  // Drawn here, in the same 16x16 stroke vocabulary as the rail's `DbIcon`/`AutoIcon`/`BellIcon`
@@ -284,16 +299,18 @@ function QuickCard({
284
  detail,
285
  onClick,
286
  disabled = false,
 
287
  }: {
288
  icon: React.ReactNode;
289
  title: string;
290
  /** ONE line. R13: the app does not narrate itself, and this is a passing-through surface. */
291
  detail: string;
292
- onClick: () => void;
293
  disabled?: boolean;
 
294
  }) {
295
  return (
296
- <button type="button" className="home-card" onClick={onClick} disabled={disabled}>
297
  <span className="home-card-head">
298
  {icon}
299
  <span className="home-card-title">{title}</span>
@@ -443,6 +460,7 @@ export function HomeSurface({
443
  counts: StarredCounts | null;
444
  toggle: (kind: StarKind, id: string, on: boolean, database?: string) => void;
445
  }) {
 
446
  const [layout, setLayout] = useState<HomeLayout>(() => {
447
  try {
448
  return parseLayout(localStorage.getItem(HOME_LAYOUT_KEY));
@@ -545,12 +563,13 @@ export function HomeSurface({
545
  ...visibleVoiceAgents.map((row) => ({ ...row, kind: "voice" as const })),
546
  ];
547
  const moduleHome = mode === "app" || mode === "agents" || mode === "sheet" || mode === "data";
548
- const moduleIndex = mode === "data"
549
  ? (onSaveFolders ? { folders, itemFolders: folderPlacement, rev: 0 } : null)
550
  : suppliedModuleIndex;
551
  const indexKnown = moduleHome && moduleIndex !== null;
552
- const folderWritable = indexKnown && !moduleIndexBusy;
553
  const [folderEdit, setFolderEdit] = useState<{ id: string | null; name: string } | null>(null);
 
554
  const [movePicker, setMovePicker] = useState(false);
555
  const [draggedIds, setDraggedIds] = useState<readonly string[]>([]);
556
  const emptyIndex: ModuleFolderIndex = { folders: [], itemFolders: {}, rev: 0 };
@@ -641,15 +660,22 @@ export function HomeSurface({
641
  },
642
  });
643
  const newFolderControl = folderWritable ? (
644
- <button type="button" className="shell-newfolder"
 
 
 
645
  disabled={mode === "data" && folders.length >= MAX_NAV_FOLDERS}
646
- title={mode === "data" && folders.length >= MAX_NAV_FOLDERS ? "Folder limit reached" : undefined}
647
- onClick={() => setFolderEdit({ id: null, name: "" })}>New folder</button>
 
 
 
 
648
  ) : <span className="home-card-ghost" aria-hidden="true" />;
649
  const renderModuleFolders = () => (
650
  <section className="home-section" aria-label="Module folders">
651
  {moduleIndexError ? <p className="home-app-note" role="alert">{moduleIndexError}
652
- <button type="button" className="cg-btn" disabled={moduleIndexBusy} onClick={onReloadModuleIndex}>Reload folders</button>
653
  </p> : null}
654
  {(!indexKnown && !moduleIndexError) || (mode === "app" && !applicationsKnown && !applicationsError) ? (
655
  <div className="shell-rail-skeleton" role="status"
@@ -661,37 +687,48 @@ export function HomeSurface({
661
  </div>
662
  ) : null}
663
  {indexKnown ? <>
664
- <nav className="cg-path-segments" aria-label="Folder path">
665
- <button type="button" className="cg-path-segment" aria-current={level.current === null ? "page" : undefined}
666
- onClick={() => enterFolder(null)} {...folderDropEvents(null)}>Top level</button>
667
- {level.breadcrumb.map((folder) => <span className="cg-path-segment-wrap" key={folder.id}>
668
- <span className="cg-path-separator" aria-hidden="true">/</span>
669
- <button type="button" className="cg-path-segment" aria-current={folder.id === level.current ? "page" : undefined}
670
- onClick={() => enterFolder(folder.id)} {...folderDropEvents(folder.id)}>{folder.name}</button>
671
- </span>)}
672
- </nav>
673
- {folderWritable ? <div className="home-section-head" role="group" aria-label="Folder actions">
674
- {level.current ? <>
675
- <button type="button" className="cg-btn" onClick={() => setFolderEdit({ id: level.current,
676
- name: level.breadcrumb[level.breadcrumb.length - 1].name })}>Rename folder</button>
677
- <button type="button" className="cg-btn" onClick={() => {
678
- if (moduleIndex && level.current) void saveFolders(deleteModuleFolder(moduleIndex, level.current))
679
- .then((saved) => { if (saved) enterFolder(null); });
680
- }}>Delete folder</button>
681
- </> : null}
 
682
  </div> : null}
683
- {folderWritable && folderEdit ? <form className="home-section-head" onSubmit={(event) => {
684
- event.preventDefault();
685
- if (!moduleIndex || !folderEdit.name.trim()) return;
686
- if (mode === "data" && !folderEdit.id && moduleIndex.folders.length >= MAX_NAV_FOLDERS) return;
687
- void saveFolders(saveModuleFolder(moduleIndex, { id: folderEdit.id ?? crypto.randomUUID(),
688
- name: folderEdit.name, ...(mode === "data" ? {} : { parent: level.current }) }));
689
- }}>
690
- <input className="cg-input" aria-label="Folder name" autoFocus maxLength={mode === "data" ? 40 : 80} value={folderEdit.name}
691
- onChange={(event) => setFolderEdit({ ...folderEdit, name: event.target.value })} />
692
- <button className="cg-btn" type="submit" disabled={!folderEdit.name.trim()}>Save folder</button>
693
- <button className="cg-btn" type="button" onClick={() => setFolderEdit(null)}>Cancel</button>
694
- </form> : null}
 
 
 
 
 
 
 
 
 
 
695
  {selection.selected.length > 0 ? <div className="cg-railsel" role="group" aria-label="Selected items">
696
  <span className="cg-railsel-count">{selection.selected.length} {selection.selected.length === 1 ? "item" : "items"} selected</span>
697
  {folderWritable ? <button type="button" className="cg-railsel-move" onClick={() => setMovePicker(!movePicker)}>Move to folder</button> : null}
@@ -699,7 +736,7 @@ export function HomeSurface({
699
  {folderWritable && movePicker ? <select className="cg-input" aria-label="Move selected items to folder" value=""
700
  onChange={(event) => { if (event.target.value) moveTiles(selection.selected, event.target.value === "root" ? null : event.target.value); }}>
701
  <option value="" disabled>Choose a folder</option>
702
- <option value="root">Top level</option>
703
  {moduleIndex.folders.map((folder) => <option key={folder.id} value={folder.id}>
704
  {moduleFolderPath(moduleIndex, folder.id).map((part) => part.name).join(" / ")}
705
  </option>)}
@@ -712,8 +749,7 @@ export function HomeSurface({
712
  <span className="home-tile-name">{folder.name}</span>
713
  </button>)}
714
  </div> : null}
715
- {level.empty ? <p className="home-empty">This folder is empty. <button type="button" className="cg-btn"
716
- onClick={() => enterFolder(null)}>Choose items from top level</button></p> : null}
717
  </> : null}
718
  </section>
719
  );
@@ -730,7 +766,7 @@ export function HomeSurface({
730
  href={agentHref(row.kind, row.id)} {...moduleTileEvents(moduleTileId(row))}
731
  onClick={(event) => { moduleTileEvents(moduleTileId(row)).onClick?.(event); openTileLink(event, row.kind === "voice" ? "agent" : "automation", row.id, row.kind === "voice"); }}>
732
  <span className="home-tile-chip shell-db-chip home-app-glyph" aria-hidden="true">
733
- <Mark size={16} />
734
  </span>
735
  <span className="home-tile-text">
736
  <span className="home-tile-name">{row.name}</span>
@@ -770,7 +806,7 @@ export function HomeSurface({
770
  {levelSheets.map((row) => (
771
  <div className="st-tilewrap" key={row.id}>
772
  <a className={"home-tile" + (mode === "sheet" ? " cg-view-row" + (selection.isSelected(row.id) ? " is-railsel" : "") : "")}
773
- href={"#/sheet?wb=" + encodeURIComponent(row.id)} {...moduleTileEvents(row.id)}
774
  onClick={(event) => { moduleTileEvents(row.id).onClick?.(event); openTileLink(event, "workbook", row.id); }}>
775
  <span className="home-tile-chip home-app-glyph" aria-hidden="true">
776
  <SheetGlyph />
@@ -800,7 +836,7 @@ export function HomeSurface({
800
  return (
801
  <div className="shell-home">
802
  <div className="home-page-head">
803
- <h1 className="home-title">{mode === "agents" ? AGENTS_MODULE_LABEL : mode === "sheet" ? "Sheet" : mode === "app" ? "App" : mode === "data" ? "Data" : "Home"}</h1>
804
  </div>
805
 
806
  {mode === "home" ? <div className="home-cards">
@@ -966,7 +1002,7 @@ export function HomeSurface({
966
  {...moduleTileEvents(tile.key)}
967
  onClick={(event) => { moduleTileEvents(tile.key).onClick?.(event); openTileLink(event, "database", tile.key); }}>
968
  <DatabaseTile
969
- tile={tile}
970
  known={known}
971
  starred={dbStarred.has(tile.key)}
972
  busy={busy}
@@ -1138,7 +1174,14 @@ export function HomeSurface({
1138
  />
1139
  ) : undefined
1140
  }
1141
- onOpen={() => { void openExistingItem({ kind: "view", id: row.id, database: row.database }, () => onOpenView(row.database, row.id)); }}
 
 
 
 
 
 
 
1142
  />
1143
  ))}
1144
  </div>
@@ -1207,6 +1250,8 @@ function useModuleFolders(mode: HomeProps["mode"]) {
1207
  useEffect(() => {
1208
  const controller = new AbortController();
1209
  const epoch = ++generation.current;
 
 
1210
  setState({ module, index: null, error: "" });
1211
  if (module) {
1212
  void fetch(`${API_V1}/module-index/${module}`, { credentials: CREDENTIALS, signal: controller.signal })
@@ -1229,30 +1274,48 @@ function useModuleFolders(mode: HomeProps["mode"]) {
1229
  const epoch = generation.current;
1230
  writePending.current = true;
1231
  setSaving(true);
 
1232
  try {
1233
- const response = await fetch(`${API_V1}/module-index/${module}`, {
1234
- method: "PUT", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" },
1235
- body: JSON.stringify({ folders: next.folders, itemFolders: next.itemFolders, rev: index.rev }),
1236
- });
1237
- const body = await response.json();
1238
- if (!response.ok) throw new Error(body?.detail?.error?.message || "Folders could not be saved. Reload folders to retry.");
1239
- const landed = parseModuleFolderIndex(body?.index);
1240
- if (!landed) throw new Error("The folder save could not be confirmed. Reload folders to check.");
 
 
 
 
 
 
 
 
1241
  if (epoch !== generation.current || activeModule.current !== module) return false;
1242
  setState({ module, index: landed, error: "" });
1243
  window.dispatchEvent(new CustomEvent("aios:module-index-changed", { detail: { module } }));
1244
  return true;
1245
  } catch (error) {
1246
- if (epoch === generation.current && activeModule.current === module) setState({ module, index: null,
1247
  error: error instanceof Error ? error.message : "Folders could not be saved. Reload folders to retry." });
1248
  return false;
1249
  } finally {
1250
- writePending.current = false;
1251
- setSaving(false);
 
 
 
 
1252
  }
1253
  };
1254
  return { index, saving, error: state.module === module ? state.error : "", save,
1255
- refresh: () => { if (!writePending.current) setReload((value) => value + 1); } };
 
 
 
 
 
1256
  }
1257
 
1258
  export default function HomePage(props: HomeProps) {
@@ -1272,6 +1335,8 @@ export default function HomePage(props: HomeProps) {
1272
  const sheetCreating = useRef(false);
1273
  useEffect(() => {
1274
  const generation = ++sheetIndexGeneration.current;
 
 
1275
  setSheetIndex(null);
1276
  if (props.mode === "app" || props.mode === "data" || props.mode === "agents") return;
1277
  let active = true;
@@ -1303,24 +1368,34 @@ export default function HomePage(props: HomeProps) {
1303
  const mode = props.mode;
1304
  sheetIndexWriting.current = true;
1305
  setSheetIndexBusy(true);
 
 
1306
  try {
1307
- const result = await writeIndex({ ...sheetIndex, folders: next.folders,
1308
- itemFolders: next.itemFolders, starred: sheetIndex.starred, rev: sheetIndex.rev });
 
 
 
 
 
1309
  if (generation !== sheetIndexGeneration.current || activeMode.current !== mode) return false;
1310
  if (!result.ok || result.value.rev === undefined) throw new Error("Folder save refused");
1311
  setSheetIndex(result.value);
1312
  setSheets(result.value.workbooks);
1313
  setSheetsError("");
1314
  return true;
1315
- } catch {
1316
  if (generation === sheetIndexGeneration.current && activeMode.current === mode) {
1317
- setSheetIndex(null);
1318
- setSheetsError("Folders could not be saved. Reload folders to retry.");
1319
  }
1320
  return false;
1321
  } finally {
1322
- sheetIndexWriting.current = false;
1323
- setSheetIndexBusy(false);
 
 
 
 
1324
  }
1325
  };
1326
 
@@ -1490,13 +1565,16 @@ export default function HomePage(props: HomeProps) {
1490
  <>
1491
  <HomeSurface
1492
  {...props}
1493
- moduleIndex={props.mode === "sheet" ? (sheetIndex && sheetIndex.rev !== undefined
1494
  ? { folders: sheetIndex.folders, itemFolders: sheetIndex.itemFolders, rev: sheetIndex.rev } : null) : moduleFolders.index}
1495
  moduleIndexBusy={props.mode === "sheet" ? sheetIndexBusy : moduleFolders.saving}
1496
  moduleIndexError={props.mode === "sheet" ? sheetsError : moduleFolders.error}
1497
  onSaveModuleIndex={props.mode === "sheet" ? saveSheetFolders : moduleFolders.save}
1498
  onReloadModuleIndex={props.mode === "sheet" ? () => {
1499
- if (!sheetIndexWriting.current) { setSheetIndex(null); setSheetIndexEpoch((value) => value + 1); }
 
 
 
1500
  } : moduleFolders.refresh}
1501
  starLoad={starLoad}
1502
  starred={starred}
 
28
  import { appPathHash } from "../customer-grid/dataPath";
29
  import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
30
  import DatabaseTile from "./DatabaseTile";
31
+ import FolderNameDialog from "./FolderNameDialog";
32
  // R16: Home and Data need the hollow glyph's box without loading the grid chunk.
33
  import "../styles/wave50/rail.css";
34
  import "../styles/wave57/home-app.css";
 
37
  import "../styles/wave46/rail-select.css";
38
  import "../styles/wave61/rails.css";
39
  import { AGENTS_MODULE_LABEL } from "../inbox/inboxModel";
 
40
  // AgentIcon carries the rail's shell-nav-icon class, which supplies its stroke-only paint.
41
  import { AgentIcon } from "../shell/icons";
42
+ import { agentAddressHash, dataAddressHash, readDataAddress, MAX_NAV_FOLDERS } from "../shell/nav";
43
  import type { DatabaseEntry, NavFolder, Recent } from "../shell/nav";
44
  import { API_V1, CREDENTIALS } from "../apiContract";
45
  // ⭐ WAVE 35 · W35-T15 (R4, C2) — ONE STAR CONTROL, drawn in the module that owns the concept and
 
69
  } from "./homeModel";
70
  import type { AutomationTile, HomeFilter, HomeLayout, ModuleFolderIndex } from "./homeModel";
71
 
72
+ // Twin in SheetPage.tsx; this ticket's file fence keeps the timeout local to each chunk.
73
+ const FOLDER_WRITE_TIMEOUT_MS = 20000;
74
+
75
+ function homeFolderHref(href: string, folder: string | undefined): string {
76
+ if (!folder || folder === "__root__") return href;
77
+ if (href.startsWith("#/data?") && readDataAddress(href).database) {
78
+ const address = dataAddressHash({ ...readDataAddress(href), folder });
79
+ // Keep server-supplied parameters that the shared address contract does not own.
80
+ const extras = new URLSearchParams(href.slice(href.indexOf("?") + 1));
81
+ for (const key of ["database", "view", "folder"]) extras.delete(key);
82
+ return address + (extras.size ? "&" + extras.toString() : "");
83
+ }
84
+ return href + (href.includes("?") ? "&folder=" : "?folder=") + encodeURIComponent(folder);
85
+ }
86
+
87
  // ── the four quick-start marks ───────────────────────────────────────────────────────────────
88
  //
89
  // Drawn here, in the same 16x16 stroke vocabulary as the rail's `DbIcon`/`AutoIcon`/`BellIcon`
 
299
  detail,
300
  onClick,
301
  disabled = false,
302
+ buttonTitle,
303
  }: {
304
  icon: React.ReactNode;
305
  title: string;
306
  /** ONE line. R13: the app does not narrate itself, and this is a passing-through surface. */
307
  detail: string;
308
+ onClick: (event: MouseEvent<HTMLButtonElement>) => void;
309
  disabled?: boolean;
310
+ buttonTitle?: string;
311
  }) {
312
  return (
313
+ <button type="button" className="home-card" onClick={onClick} disabled={disabled} title={buttonTitle}>
314
  <span className="home-card-head">
315
  {icon}
316
  <span className="home-card-title">{title}</span>
 
460
  counts: StarredCounts | null;
461
  toggle: (kind: StarKind, id: string, on: boolean, database?: string) => void;
462
  }) {
463
+ const moduleName = mode === "agents" ? AGENTS_MODULE_LABEL : mode === "sheet" ? "Sheet" : mode === "app" ? "App" : mode === "data" ? "Data" : "Home";
464
  const [layout, setLayout] = useState<HomeLayout>(() => {
465
  try {
466
  return parseLayout(localStorage.getItem(HOME_LAYOUT_KEY));
 
563
  ...visibleVoiceAgents.map((row) => ({ ...row, kind: "voice" as const })),
564
  ];
565
  const moduleHome = mode === "app" || mode === "agents" || mode === "sheet" || mode === "data";
566
+ const moduleIndex: ModuleFolderIndex | null = mode === "data"
567
  ? (onSaveFolders ? { folders, itemFolders: folderPlacement, rev: 0 } : null)
568
  : suppliedModuleIndex;
569
  const indexKnown = moduleHome && moduleIndex !== null;
570
+ const folderWritable = indexKnown && !moduleIndexBusy && !moduleIndexError;
571
  const [folderEdit, setFolderEdit] = useState<{ id: string | null; name: string } | null>(null);
572
+ const [folderAnchor, setFolderAnchor] = useState<HTMLElement | null>(null);
573
  const [movePicker, setMovePicker] = useState(false);
574
  const [draggedIds, setDraggedIds] = useState<readonly string[]>([]);
575
  const emptyIndex: ModuleFolderIndex = { folders: [], itemFolders: {}, rev: 0 };
 
660
  },
661
  });
662
  const newFolderControl = folderWritable ? (
663
+ <QuickCard
664
+ icon={<span className="home-card-icon" aria-hidden="true"><FolderMark size={16} /></span>}
665
+ title="New folder"
666
+ detail="Group items in this module into folders."
667
  disabled={mode === "data" && folders.length >= MAX_NAV_FOLDERS}
668
+ buttonTitle={mode === "data" && folders.length >= MAX_NAV_FOLDERS ? "Folder limit reached" : undefined}
669
+ onClick={(event) => {
670
+ setFolderAnchor(event.currentTarget);
671
+ setFolderEdit({ id: null, name: "" });
672
+ }}
673
+ />
674
  ) : <span className="home-card-ghost" aria-hidden="true" />;
675
  const renderModuleFolders = () => (
676
  <section className="home-section" aria-label="Module folders">
677
  {moduleIndexError ? <p className="home-app-note" role="alert">{moduleIndexError}
678
+ <button type="button" className="cg-btn" onClick={onReloadModuleIndex}>Reload folders</button>
679
  </p> : null}
680
  {(!indexKnown && !moduleIndexError) || (mode === "app" && !applicationsKnown && !applicationsError) ? (
681
  <div className="shell-rail-skeleton" role="status"
 
687
  </div>
688
  ) : null}
689
  {indexKnown ? <>
690
+ {level.current ? <div className="home-section-head">
691
+ <button type="button" className="cg-btn" aria-label="Back" title="Back"
692
+ onClick={() => enterFolder(level.breadcrumb[level.breadcrumb.length - 2]?.id ?? null)}
693
+ {...folderDropEvents(level.breadcrumb[level.breadcrumb.length - 2]?.id ?? null)}>
694
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="home-layout-icon" fill="none" stroke="currentColor">
695
+ <path d="M10 3 5 8l5 5" />
696
+ </svg>
697
+ </button>
698
+ <span>{level.breadcrumb[level.breadcrumb.length - 1].name}</span>
699
+ </div> : null}
700
+ {folderWritable && level.current && !level.empty ? <div className="home-section-head" role="group" aria-label="Folder actions">
701
+ <button type="button" className="cg-btn" onClick={(event) => {
702
+ setFolderAnchor(event.currentTarget);
703
+ setFolderEdit({ id: level.current, name: level.breadcrumb[level.breadcrumb.length - 1].name });
704
+ }}>Rename folder</button>
705
+ <button type="button" className="cg-btn" onClick={() => {
706
+ if (moduleIndex && level.current) void saveFolders(deleteModuleFolder(moduleIndex, level.current))
707
+ .then((saved) => { if (saved) enterFolder(null); });
708
+ }}>Delete folder</button>
709
  </div> : null}
710
+ {folderWritable && folderEdit ? <FolderNameDialog
711
+ key={folderEdit.id ?? "new"}
712
+ anchor={folderAnchor}
713
+ title={folderEdit.id ? "Rename folder" : "New folder"}
714
+ initialName={folderEdit.name}
715
+ siblingNames={moduleIndex.folders.filter((folder) => {
716
+ const parent = mode === "data" ? null : folderEdit.id
717
+ ? moduleIndex.folders.find((candidate) => candidate.id === folderEdit.id)?.parent ?? null
718
+ : level.current;
719
+ return folder.id !== folderEdit.id && (folder.parent ?? null) === parent;
720
+ }).map((folder) => folder.name)}
721
+ onSubmit={(name) => {
722
+ if (!moduleIndex || !folderWritable) return;
723
+ if (mode === "data" && !folderEdit.id && moduleIndex.folders.length >= MAX_NAV_FOLDERS) return;
724
+ const parent = folderEdit.id
725
+ ? moduleIndex.folders.find((folder) => folder.id === folderEdit.id)?.parent ?? null
726
+ : level.current;
727
+ void saveFolders(saveModuleFolder(moduleIndex, { id: folderEdit.id ?? crypto.randomUUID(),
728
+ name, ...(mode === "data" ? {} : { parent }) }));
729
+ }}
730
+ onDismiss={() => { setFolderEdit(null); setFolderAnchor(null); }}
731
+ /> : null}
732
  {selection.selected.length > 0 ? <div className="cg-railsel" role="group" aria-label="Selected items">
733
  <span className="cg-railsel-count">{selection.selected.length} {selection.selected.length === 1 ? "item" : "items"} selected</span>
734
  {folderWritable ? <button type="button" className="cg-railsel-move" onClick={() => setMovePicker(!movePicker)}>Move to folder</button> : null}
 
736
  {folderWritable && movePicker ? <select className="cg-input" aria-label="Move selected items to folder" value=""
737
  onChange={(event) => { if (event.target.value) moveTiles(selection.selected, event.target.value === "root" ? null : event.target.value); }}>
738
  <option value="" disabled>Choose a folder</option>
739
+ <option value="root">{moduleName}</option>
740
  {moduleIndex.folders.map((folder) => <option key={folder.id} value={folder.id}>
741
  {moduleFolderPath(moduleIndex, folder.id).map((part) => part.name).join(" / ")}
742
  </option>)}
 
749
  <span className="home-tile-name">{folder.name}</span>
750
  </button>)}
751
  </div> : null}
752
+ {level.empty ? <p className="home-empty">This folder is empty.</p> : null}
 
753
  </> : null}
754
  </section>
755
  );
 
766
  href={agentHref(row.kind, row.id)} {...moduleTileEvents(moduleTileId(row))}
767
  onClick={(event) => { moduleTileEvents(moduleTileId(row)).onClick?.(event); openTileLink(event, row.kind === "voice" ? "agent" : "automation", row.id, row.kind === "voice"); }}>
768
  <span className="home-tile-chip shell-db-chip home-app-glyph" aria-hidden="true">
769
+ <AgentIcon />
770
  </span>
771
  <span className="home-tile-text">
772
  <span className="home-tile-name">{row.name}</span>
 
806
  {levelSheets.map((row) => (
807
  <div className="st-tilewrap" key={row.id}>
808
  <a className={"home-tile" + (mode === "sheet" ? " cg-view-row" + (selection.isSelected(row.id) ? " is-railsel" : "") : "")}
809
+ href={homeFolderHref("#/sheet?wb=" + encodeURIComponent(row.id), moduleIndex?.itemFolders?.[row.id])} {...moduleTileEvents(row.id)}
810
  onClick={(event) => { moduleTileEvents(row.id).onClick?.(event); openTileLink(event, "workbook", row.id); }}>
811
  <span className="home-tile-chip home-app-glyph" aria-hidden="true">
812
  <SheetGlyph />
 
836
  return (
837
  <div className="shell-home">
838
  <div className="home-page-head">
839
+ <h1 className="home-title">{moduleName}</h1>
840
  </div>
841
 
842
  {mode === "home" ? <div className="home-cards">
 
1002
  {...moduleTileEvents(tile.key)}
1003
  onClick={(event) => { moduleTileEvents(tile.key).onClick?.(event); openTileLink(event, "database", tile.key); }}>
1004
  <DatabaseTile
1005
+ tile={{ ...tile, href: homeFolderHref(tile.href, mode === "data" ? moduleIndex?.itemFolders?.[tile.key] : folderPlacement[tile.key]) }}
1006
  known={known}
1007
  starred={dbStarred.has(tile.key)}
1008
  busy={busy}
 
1174
  />
1175
  ) : undefined
1176
  }
1177
+ onOpen={() => { void openExistingItem({ kind: "view", id: row.id, database: row.database }, () => {
1178
+ onOpenView(row.database, row.id);
1179
+ const href = homeFolderHref(window.location.hash, folderPlacement[row.database]);
1180
+ if (href !== window.location.hash) {
1181
+ window.history.replaceState(window.history.state, "", href);
1182
+ window.dispatchEvent(new HashChangeEvent("hashchange"));
1183
+ }
1184
+ }); }}
1185
  />
1186
  ))}
1187
  </div>
 
1250
  useEffect(() => {
1251
  const controller = new AbortController();
1252
  const epoch = ++generation.current;
1253
+ writePending.current = false;
1254
+ setSaving(false);
1255
  setState({ module, index: null, error: "" });
1256
  if (module) {
1257
  void fetch(`${API_V1}/module-index/${module}`, { credentials: CREDENTIALS, signal: controller.signal })
 
1274
  const epoch = generation.current;
1275
  writePending.current = true;
1276
  setSaving(true);
1277
+ let timeout: ReturnType<typeof setTimeout> | undefined;
1278
  try {
1279
+ const landed = await Promise.race([
1280
+ (async () => {
1281
+ const response = await fetch(`${API_V1}/module-index/${module}`, {
1282
+ method: "PUT", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" },
1283
+ body: JSON.stringify({ folders: next.folders, itemFolders: next.itemFolders, rev: index.rev }),
1284
+ });
1285
+ const body = await response.json();
1286
+ if (!response.ok) throw new Error(body?.detail?.error?.message || "Folders could not be saved. Reload folders to retry.");
1287
+ const loaded = parseModuleFolderIndex(body?.index);
1288
+ if (!loaded) throw new Error("The folder save could not be confirmed. Reload folders to check.");
1289
+ return loaded;
1290
+ })(),
1291
+ new Promise<never>((_, reject) => {
1292
+ timeout = setTimeout(() => reject(new Error("The folder move timed out. Reload folders to retry.")), FOLDER_WRITE_TIMEOUT_MS);
1293
+ }),
1294
+ ]);
1295
  if (epoch !== generation.current || activeModule.current !== module) return false;
1296
  setState({ module, index: landed, error: "" });
1297
  window.dispatchEvent(new CustomEvent("aios:module-index-changed", { detail: { module } }));
1298
  return true;
1299
  } catch (error) {
1300
+ if (epoch === generation.current && activeModule.current === module) setState({ module, index,
1301
  error: error instanceof Error ? error.message : "Folders could not be saved. Reload folders to retry." });
1302
  return false;
1303
  } finally {
1304
+ clearTimeout(timeout);
1305
+ // Reload already released an obsolete write; it must not unlock a newer one.
1306
+ if (epoch === generation.current && activeModule.current === module) {
1307
+ writePending.current = false;
1308
+ setSaving(false);
1309
+ }
1310
  }
1311
  };
1312
  return { index, saving, error: state.module === module ? state.error : "", save,
1313
+ refresh: () => {
1314
+ generation.current += 1;
1315
+ writePending.current = false;
1316
+ setSaving(false);
1317
+ setReload((value) => value + 1);
1318
+ } };
1319
  }
1320
 
1321
  export default function HomePage(props: HomeProps) {
 
1335
  const sheetCreating = useRef(false);
1336
  useEffect(() => {
1337
  const generation = ++sheetIndexGeneration.current;
1338
+ sheetIndexWriting.current = false;
1339
+ setSheetIndexBusy(false);
1340
  setSheetIndex(null);
1341
  if (props.mode === "app" || props.mode === "data" || props.mode === "agents") return;
1342
  let active = true;
 
1368
  const mode = props.mode;
1369
  sheetIndexWriting.current = true;
1370
  setSheetIndexBusy(true);
1371
+ let timeout: ReturnType<typeof setTimeout> | undefined;
1372
+ const timeoutError = new Error("The folder move timed out. Reload folders to retry.");
1373
  try {
1374
+ const result = await Promise.race([
1375
+ writeIndex({ ...sheetIndex, folders: next.folders,
1376
+ itemFolders: next.itemFolders, starred: sheetIndex.starred, rev: sheetIndex.rev }),
1377
+ new Promise<never>((_, reject) => {
1378
+ timeout = setTimeout(() => reject(timeoutError), FOLDER_WRITE_TIMEOUT_MS);
1379
+ }),
1380
+ ]);
1381
  if (generation !== sheetIndexGeneration.current || activeMode.current !== mode) return false;
1382
  if (!result.ok || result.value.rev === undefined) throw new Error("Folder save refused");
1383
  setSheetIndex(result.value);
1384
  setSheets(result.value.workbooks);
1385
  setSheetsError("");
1386
  return true;
1387
+ } catch (error) {
1388
  if (generation === sheetIndexGeneration.current && activeMode.current === mode) {
1389
+ setSheetsError(error === timeoutError ? timeoutError.message : "Folders could not be saved. Reload folders to retry.");
 
1390
  }
1391
  return false;
1392
  } finally {
1393
+ clearTimeout(timeout);
1394
+ // Reload already released an obsolete write; it must not unlock a newer one.
1395
+ if (generation === sheetIndexGeneration.current && activeMode.current === mode) {
1396
+ sheetIndexWriting.current = false;
1397
+ setSheetIndexBusy(false);
1398
+ }
1399
  }
1400
  };
1401
 
 
1565
  <>
1566
  <HomeSurface
1567
  {...props}
1568
+ moduleIndex={props.mode === "sheet" || props.mode === "home" ? (sheetIndex && sheetIndex.rev !== undefined
1569
  ? { folders: sheetIndex.folders, itemFolders: sheetIndex.itemFolders, rev: sheetIndex.rev } : null) : moduleFolders.index}
1570
  moduleIndexBusy={props.mode === "sheet" ? sheetIndexBusy : moduleFolders.saving}
1571
  moduleIndexError={props.mode === "sheet" ? sheetsError : moduleFolders.error}
1572
  onSaveModuleIndex={props.mode === "sheet" ? saveSheetFolders : moduleFolders.save}
1573
  onReloadModuleIndex={props.mode === "sheet" ? () => {
1574
+ sheetIndexGeneration.current += 1;
1575
+ sheetIndexWriting.current = false;
1576
+ setSheetIndexBusy(false);
1577
+ setSheetIndexEpoch((value) => value + 1);
1578
  } : moduleFolders.refresh}
1579
  starLoad={starLoad}
1580
  starred={starred}
web/src/index.css CHANGED
@@ -213,6 +213,11 @@
213
  --lp-ink: #202433; /* 15.42:1 on white */
214
  --lp-muted: #6b7280; /* 4.83:1 on white — body-text safe */
215
  --lp-line: #e6e9ef; /* hairlines: 1px, never a heavy border */
 
 
 
 
 
216
  /* ⛔ Was `--lp-wash: var(--lp-wash)` — a SELF-REFERENCE, which CSS resolves to
217
  the guaranteed-invalid value, so every consumer (panel washes, table-row
218
  hover, calendar blanks, the filled login field) silently painted NOTHING.
@@ -3544,6 +3549,9 @@ body > .cg-overlay {
3544
  correct through this because both are `position: fixed` and therefore out of flow — checked, not
3545
  assumed; a STATIC sibling would have become a third row in this column and eaten height. */
3546
  .shell-root {
 
 
 
3547
  display: flex;
3548
  flex-direction: column;
3549
  width: 100%;
@@ -10383,11 +10391,8 @@ a.cg-map-ctl-b { text-decoration: none; }
10383
  text-align: left;
10384
  cursor: pointer;
10385
  }
10386
- /* Hover is a WASH, not a heavier border. There is exactly one hairline token (`--lp-line`) by
10387
- design, so "a slightly stronger border" would have to be a new token for a hover state — and
10388
- the quiet-button pattern this system already uses (`.shell-newfolder`: muted ink, wash on
10389
- hover, nothing else) says the wash is the whole affordance. Checked before writing: no
10390
- `--lp-line-strong` exists, and inventing one for this would be a token nobody else can reach. */
10391
  .autox-trigbtn:hover:not(:disabled) { background: var(--lp-surface-2); }
10392
  .autox-trigbtn:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 1px; }
10393
  .autox-trigbtn-label {
@@ -12127,7 +12132,8 @@ a.cg-map-ctl-b { text-decoration: none; }
12127
  scrollbar-gutter: stable;
12128
  padding: 34px 44px 56px;
12129
  box-sizing: border-box;
12130
- background: var(--lp-surface);
 
12131
  }
12132
  .home-title {
12133
  margin: 0 0 20px;
@@ -12274,6 +12280,13 @@ a.cg-map-ctl-b { text-decoration: none; }
12274
  transition: border-color 0.14s var(--lp-fold-e);
12275
  }
12276
  .home-tile:hover { border-color: var(--lp-blue-deep); }
 
 
 
 
 
 
 
12277
  /* The SAME chip as the database header and the rail row (`.shell-db-chip` + its tone) — a
12278
  database looks like itself everywhere. Only the two letters are new, and they take the chip's
12279
  own measured white ink. */
@@ -12300,6 +12313,12 @@ a.cg-map-ctl-b { text-decoration: none; }
12300
  .home-tile-auto .home-tile-chip {
12301
  background: var(--lp-primary-tint);
12302
  }
 
 
 
 
 
 
12303
  .home-tile-text {
12304
  display: flex;
12305
  flex-direction: column;
@@ -13420,9 +13439,7 @@ textarea.cg-json-raw:focus {
13420
  .cg-view-count.is-unknown {
13421
  background: transparent;
13422
  color: var(--lp-muted);
13423
- /* ⚠ `var(--lp-line)`, not a `--lp-line-strong` fallback: `verify_icons::ghost_tokens` counts a
13424
- var() with a fallback as USAGE, and reds on a token nobody declares — correctly, because the
13425
- fallback hides the fact that the first name resolves to nothing forever. */
13426
  border: 1px dashed var(--lp-line);
13427
  font-weight: 600;
13428
  }
@@ -13682,3 +13699,172 @@ input.conn-odoo-v:disabled { background: var(--lp-surface-2); color: var(--lp-mu
13682
  .cg-grid-box { overflow: hidden; }
13683
  .cg-column-drop-shadow { position: absolute; z-index: var(--cg-z-column); top: 0; bottom: 0; width: 2px; pointer-events: none; background: var(--lp-blue-solid); box-shadow: 0 0 12px color-mix(in srgb, var(--lp-blue-solid) 45%, transparent); opacity: 0; transform: translateX(-1px); transition: opacity 140ms ease, transform 140ms ease; }
13684
  .cg-column-drop-shadow.is-visible { opacity: 1; transform: translateX(0); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  --lp-ink: #202433; /* 15.42:1 on white */
214
  --lp-muted: #6b7280; /* 4.83:1 on white — body-text safe */
215
  --lp-line: #e6e9ef; /* hairlines: 1px, never a heavy border */
216
+ --lp-line-strong: #cbd1dc; /* D-684: a darker step than --lp-line for stronger separators. */
217
+ /* W62-T33 tokens: DOM scrollbars reuse the palette, including portalled panels.
218
+ The shell scope below mirrors these aliases; no new canvas colour is needed. */
219
+ --lp-scroll-thumb: var(--lp-blue-deep);
220
+ --lp-scroll-thumb-hover: var(--lp-blue-solid);
221
  /* ⛔ Was `--lp-wash: var(--lp-wash)` — a SELF-REFERENCE, which CSS resolves to
222
  the guaranteed-invalid value, so every consumer (panel washes, table-row
223
  hover, calendar blanks, the filled login field) silently painted NOTHING.
 
3549
  correct through this because both are `position: fixed` and therefore out of flow — checked, not
3550
  assumed; a STATIC sibling would have become a third row in this column and eaten height. */
3551
  .shell-root {
3552
+ /* W62-T33 tokens: shell seam, matching the root used by body portals. */
3553
+ --lp-scroll-thumb: var(--lp-blue-deep);
3554
+ --lp-scroll-thumb-hover: var(--lp-blue-solid);
3555
  display: flex;
3556
  flex-direction: column;
3557
  width: 100%;
 
10391
  text-align: left;
10392
  cursor: pointer;
10393
  }
10394
+ /* Hover uses a wash, following the quiet-button pattern. D-684 declares --lp-line-strong
10395
+ for existing App and Sheet separators; this control keeps its --lp-line hairline. */
 
 
 
10396
  .autox-trigbtn:hover:not(:disabled) { background: var(--lp-surface-2); }
10397
  .autox-trigbtn:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 1px; }
10398
  .autox-trigbtn-label {
 
12132
  scrollbar-gutter: stable;
12133
  padding: 34px 44px 56px;
12134
  box-sizing: border-box;
12135
+ /* W62 instruction 3, R4/R21: the wash is chrome and recedes; cards stay white. */
12136
+ background: var(--lp-wash);
12137
  }
12138
  .home-title {
12139
  margin: 0 0 20px;
 
12280
  transition: border-color 0.14s var(--lp-fold-e);
12281
  }
12282
  .home-tile:hover { border-color: var(--lp-blue-deep); }
12283
+ /* R21: home-only wrappers share the tile's white surface and rounded outline. */
12284
+ .shell-home .home-data-tile,
12285
+ .shell-home .st-tilewrap,
12286
+ .shell-home .home-app-tile {
12287
+ background: var(--lp-surface);
12288
+ border-radius: var(--lp-r-md);
12289
+ }
12290
  /* The SAME chip as the database header and the rail row (`.shell-db-chip` + its tone) — a
12291
  database looks like itself everywhere. Only the two letters are new, and they take the chip's
12292
  own measured white ink. */
 
12313
  .home-tile-auto .home-tile-chip {
12314
  background: var(--lp-primary-tint);
12315
  }
12316
+ /* ⛔ R21 IS ABOUT CARDS AND TILES, NOT ABOUT THE CHIP INSIDE ONE. A `.home-tile-chip` that also
12317
+ wears `.shell-db-chip` is a SOLID `--lp-primary` square carrying `color: var(--shell-on-solid,
12318
+ #ffffff)`; repainting it white here would put white ink on white and delete the mark from every
12319
+ database and agent tile on Home. The chip sits inside `.home-tile`, which already declares
12320
+ `--lp-surface`, so a chip with no background of its own is white already and one WITH a tone
12321
+ keeps the tone the rail and the database header give it. No rule belongs here. */
12322
  .home-tile-text {
12323
  display: flex;
12324
  flex-direction: column;
 
13439
  .cg-view-count.is-unknown {
13440
  background: transparent;
13441
  color: var(--lp-muted);
13442
+ /* Unknown counts keep the quiet --lp-line hairline; --lp-line-strong is for separators. */
 
 
13443
  border: 1px dashed var(--lp-line);
13444
  font-weight: 600;
13445
  }
 
13699
  .cg-grid-box { overflow: hidden; }
13700
  .cg-column-drop-shadow { position: absolute; z-index: var(--cg-z-column); top: 0; bottom: 0; width: 2px; pointer-events: none; background: var(--lp-blue-solid); box-shadow: 0 0 12px color-mix(in srgb, var(--lp-blue-solid) 45%, transparent); opacity: 0; transform: translateX(-1px); transition: opacity 140ms ease, transform 140ms ease; }
13701
  .cg-column-drop-shadow.is-visible { opacity: 1; transform: translateX(0); }
13702
+
13703
+ /* W62-T33 / R20: lp-scroll overlays. The library owns scroll/leave detection and
13704
+ the 600 ms hide delay; only opacity animates, including the fade out. */
13705
+ .os-scrollbar.lp-scroll {
13706
+ --os-size: 8px;
13707
+ --os-padding-perpendicular: 1px;
13708
+ --os-padding-axis: 2px;
13709
+ --os-track-bg: transparent;
13710
+ --os-track-bg-hover: transparent;
13711
+ --os-track-bg-active: transparent;
13712
+ --os-handle-border-radius: var(--lp-r-md);
13713
+ --os-handle-bg: var(--lp-scroll-thumb);
13714
+ --os-handle-bg-hover: var(--lp-scroll-thumb);
13715
+ --os-handle-bg-active: var(--lp-scroll-thumb-hover);
13716
+ opacity: 0;
13717
+ visibility: visible;
13718
+ transition: opacity 150ms ease-out;
13719
+ }
13720
+ .os-scrollbar.lp-scroll.os-scrollbar-visible:not(.os-scrollbar-auto-hide-hidden) {
13721
+ opacity: 1;
13722
+ }
13723
+ .os-scrollbar.lp-scroll.os-scrollbar-auto-hide-hidden {
13724
+ opacity: 0;
13725
+ visibility: visible;
13726
+ }
13727
+ .lp-scroll.os-scrollbar-auto-hide-hidden .os-scrollbar-handle { pointer-events: none; }
13728
+
13729
+ /* Preserve the rail's column and bottom-pinned account inside the native viewport. */
13730
+ .shell-side > [data-overlayscrollbars-viewport] {
13731
+ display: flex;
13732
+ flex-direction: column;
13733
+ min-height: 100%;
13734
+ }
13735
+
13736
+ /* Panels outside this lane retain native scrollbars. CSS gives them the same
13737
+ slim, quiet thumb; timed scroll/leave fades require mounting OverlayScroll. */
13738
+ :is(.shell-home, .shell-conn, .cg-detail-body, .cg-record-related-modebody,
13739
+ .sheet-ribbon-overflow, .sheet-ribbon-scroll, .cg-overlay) {
13740
+ scrollbar-width: thin;
13741
+ scrollbar-color: transparent transparent;
13742
+ }
13743
+ :is(.shell-home, .shell-conn, .cg-detail-body, .cg-record-related-modebody,
13744
+ .sheet-ribbon-overflow, .sheet-ribbon-scroll, .cg-overlay)::-webkit-scrollbar {
13745
+ width: 8px;
13746
+ height: 8px;
13747
+ }
13748
+ :is(.shell-home, .shell-conn, .cg-detail-body, .cg-record-related-modebody,
13749
+ .sheet-ribbon-overflow, .sheet-ribbon-scroll, .cg-overlay)::-webkit-scrollbar-track {
13750
+ background: transparent;
13751
+ }
13752
+ :is(.shell-home, .shell-conn, .cg-detail-body, .cg-record-related-modebody,
13753
+ .sheet-ribbon-overflow, .sheet-ribbon-scroll, .cg-overlay)::-webkit-scrollbar-thumb {
13754
+ background: transparent;
13755
+ border: 1px solid transparent;
13756
+ background-clip: padding-box;
13757
+ border-radius: var(--lp-r-md);
13758
+ }
13759
+ @media (hover: hover) and (pointer: fine) {
13760
+ .os-scrollbar.lp-scroll { --os-handle-bg-hover: var(--lp-scroll-thumb-hover); }
13761
+ :is(.shell-home, .shell-conn, .cg-detail-body, .cg-record-related-modebody,
13762
+ .sheet-ribbon-overflow, .sheet-ribbon-scroll, .cg-overlay):hover {
13763
+ scrollbar-color: var(--lp-scroll-thumb) transparent;
13764
+ }
13765
+ :is(.shell-home, .shell-conn, .cg-detail-body, .cg-record-related-modebody,
13766
+ .sheet-ribbon-overflow, .sheet-ribbon-scroll, .cg-overlay):hover::-webkit-scrollbar-thumb {
13767
+ background-color: var(--lp-scroll-thumb);
13768
+ }
13769
+ }
13770
+ /* Keyboard focus also reveals the native fallback without relying on hover. */
13771
+ :is(.shell-home, .shell-conn, .cg-detail-body, .cg-record-related-modebody,
13772
+ .sheet-ribbon-overflow, .sheet-ribbon-scroll, .cg-overlay):focus-within {
13773
+ scrollbar-color: var(--lp-scroll-thumb) transparent;
13774
+ }
13775
+ :is(.shell-home, .shell-conn, .cg-detail-body, .cg-record-related-modebody,
13776
+ .sheet-ribbon-overflow, .sheet-ribbon-scroll, .cg-overlay):focus-within::-webkit-scrollbar-thumb {
13777
+ background-color: var(--lp-scroll-thumb);
13778
+ }
13779
+ @media (prefers-reduced-motion: reduce) {
13780
+ .os-scrollbar.lp-scroll,
13781
+ .os-scrollbar.lp-scroll.os-scrollbar-auto-hide-hidden {
13782
+ transition: none;
13783
+ }
13784
+ .os-scrollbar.lp-scroll.os-scrollbar-visible {
13785
+ opacity: 1;
13786
+ visibility: visible;
13787
+ }
13788
+ .lp-scroll.os-scrollbar-handle-interactive .os-scrollbar-handle { pointer-events: auto; }
13789
+ :is(.shell-home, .shell-conn, .cg-detail-body, .cg-record-related-modebody,
13790
+ .sheet-ribbon-overflow, .sheet-ribbon-scroll, .cg-overlay) {
13791
+ scrollbar-color: var(--lp-scroll-thumb) transparent;
13792
+ }
13793
+ :is(.shell-home, .shell-conn, .cg-detail-body, .cg-record-related-modebody,
13794
+ .sheet-ribbon-overflow, .sheet-ribbon-scroll, .cg-overlay)::-webkit-scrollbar-thumb {
13795
+ background-color: var(--lp-scroll-thumb);
13796
+ transition: none;
13797
+ }
13798
+ }
13799
+
13800
+ /* W62-T33 / R20: both grids use Glide's native DOM scroller. Always paint the
13801
+ thumb while there is overflow; no hover, auto-hide or overlay dependency. */
13802
+ .sheet-grid-canvas .dvn-scroller,
13803
+ .dvn-scroller {
13804
+ scrollbar-width: thin;
13805
+ scrollbar-color: var(--lp-scroll-thumb) transparent;
13806
+ }
13807
+ .sheet-grid-canvas .dvn-scroller::-webkit-scrollbar,
13808
+ .dvn-scroller::-webkit-scrollbar {
13809
+ width: 8px;
13810
+ height: 8px;
13811
+ }
13812
+ .sheet-grid-canvas .dvn-scroller::-webkit-scrollbar-track,
13813
+ .dvn-scroller::-webkit-scrollbar-track { background: transparent; }
13814
+ .sheet-grid-canvas .dvn-scroller::-webkit-scrollbar-thumb,
13815
+ .dvn-scroller::-webkit-scrollbar-thumb {
13816
+ background: var(--lp-scroll-thumb);
13817
+ border: 1px solid transparent;
13818
+ background-clip: padding-box;
13819
+ border-radius: var(--lp-r-md);
13820
+ }
13821
+ @media (hover: hover) and (pointer: fine) {
13822
+ .sheet-grid-canvas .dvn-scroller::-webkit-scrollbar-thumb:hover,
13823
+ .dvn-scroller::-webkit-scrollbar-thumb:hover { background-color: var(--lp-scroll-thumb-hover); }
13824
+ }
13825
+
13826
+ /* W62-T33 / D-398: every AnchoredOverlay class must scroll its inline maxHeight.
13827
+ Scope modifiers to cg-overlay so ribbons/forms outside a portal keep their layout.
13828
+ The exact-class fallback covers ViewSidebar's className="" Trash panel. */
13829
+ .cg-overlay[class="cg-overlay"],
13830
+ .cg-overlay.autoc-bigedit,
13831
+ .cg-overlay.cg-add-list-pop,
13832
+ .cg-overlay.cg-addcust-pop,
13833
+ .cg-overlay.cg-builder-add,
13834
+ .cg-overlay.cg-bulk-update-pop,
13835
+ .cg-overlay.cg-column-menu,
13836
+ .cg-overlay.cg-copycfg-pop,
13837
+ .cg-overlay.cg-create-flyout,
13838
+ .cg-overlay.cg-date-picker,
13839
+ .cg-overlay.cg-fold-addpop,
13840
+ .cg-overlay.cg-formula-ac,
13841
+ .cg-overlay.cg-fsel-pop,
13842
+ .cg-overlay.cg-lock-pop,
13843
+ .cg-overlay.cg-pick-pop,
13844
+ .cg-overlay.cg-pop,
13845
+ .cg-overlay.cg-pop--wide,
13846
+ .cg-overlay.cg-pop--measures,
13847
+ .cg-overlay.cg-pop--pair,
13848
+ .cg-overlay.cg-sum-menu,
13849
+ .cg-overlay.cg-swatch-pop,
13850
+ .cg-overlay.cg-view-menu,
13851
+ .cg-overlay.cg-view-note-pop,
13852
+ .cg-overlay.cg-w46-stop-addmenu,
13853
+ .cg-overlay.sheet-cell-export-pop,
13854
+ .cg-overlay.sheet-chart-color-list,
13855
+ .cg-overlay.sheet-dropdown,
13856
+ .cg-overlay.sheet-formula-picker,
13857
+ .cg-overlay.sheet-link-form,
13858
+ .cg-overlay.sheet-note-bubble,
13859
+ .cg-overlay.sheet-ribbon,
13860
+ .cg-overlay.sheet-ribbon-data,
13861
+ .cg-overlay.sheet-ribbon-formulas,
13862
+ .cg-overlay.sheet-ribbon-home,
13863
+ .cg-overlay.sheet-ribbon-insert,
13864
+ .cg-overlay.sheet-ribbon-insert-form,
13865
+ .cg-overlay.sheet-ribbon-overflow,
13866
+ .cg-overlay.sheet-ribbon-pop,
13867
+ .cg-overlay.sheet-ribbon-pop-portal,
13868
+ .cg-overlay.sheet-ribbon-view {
13869
+ overflow-y: auto;
13870
+ }
web/src/settings/ExternalAccessPane.tsx CHANGED
@@ -19,6 +19,13 @@ interface ExternalKeyMetadata {
19
  created: string;
20
  last_used: string | null;
21
  revoked_at: string | null;
 
 
 
 
 
 
 
22
  }
23
 
24
  interface KeyListResponse {
@@ -66,7 +73,7 @@ async function call<T>(path: string, init?: RequestInit): Promise<ApiResult<T>>
66
  ok: false,
67
  message:
68
  response.status >= 500
69
- ? "External access is unavailable right now."
70
  : messageFrom(body, "That request could not be completed."),
71
  };
72
  }
@@ -97,7 +104,7 @@ async function callText(path: string): Promise<ApiResult<string>> {
97
  ok: false,
98
  message:
99
  response.status >= 500
100
- ? "External access is unavailable right now."
101
  : messageFrom(parsed, "That request could not be completed."),
102
  };
103
  }
@@ -123,6 +130,10 @@ function parseKey(value: unknown): ExternalKeyMetadata | null {
123
  created: row.created,
124
  last_used: typeof row.last_used === "string" ? row.last_used : null,
125
  revoked_at: typeof row.revoked_at === "string" ? row.revoked_at : null,
 
 
 
 
126
  };
127
  }
128
 
@@ -137,6 +148,11 @@ export default function ExternalAccessPane() {
137
  const [keys, setKeys] = useState<ExternalKeyMetadata[] | null>(null);
138
  const [canMint, setCanMint] = useState<boolean | null>(null);
139
  const [label, setLabel] = useState("");
 
 
 
 
 
140
  const [busy, setBusy] = useState("");
141
  const [error, setError] = useState("");
142
  const [notice, setNotice] = useState("");
@@ -155,14 +171,14 @@ export default function ExternalAccessPane() {
155
  if (!Array.isArray(result.data?.keys) || typeof result.data.can_mint !== "boolean") {
156
  setKeys([]);
157
  setCanMint(null);
158
- setError("External access returned an unreadable response.");
159
  return;
160
  }
161
  const parsed = result.data.keys.map(parseKey);
162
  if (parsed.some((row) => row === null)) {
163
  setKeys([]);
164
  setCanMint(null);
165
- setError("External access returned an unreadable response.");
166
  return;
167
  }
168
  setKeys(parsed as ExternalKeyMetadata[]);
@@ -174,6 +190,40 @@ export default function ExternalAccessPane() {
174
  void load();
175
  }, [load]);
176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
  async function create(event: FormEvent) {
178
  event.preventDefault();
179
  const clean = label.trim();
@@ -181,13 +231,17 @@ export default function ExternalAccessPane() {
181
  setError("Enter a label for this credential.");
182
  return;
183
  }
 
 
 
 
184
  setBusy("create");
185
  setError("");
186
  setNotice("");
187
  const result = await call<MintResponse>("/external/keys", {
188
  method: "POST",
189
  headers: { "Content-Type": "application/json" },
190
- body: JSON.stringify({ label: clean }),
191
  });
192
  setBusy("");
193
  if (!result.ok) {
@@ -203,6 +257,9 @@ export default function ExternalAccessPane() {
203
  const minted = { key, secret: result.data.secret };
204
  setKeys((current) => [key, ...(current ?? []).filter((row) => row.id !== key.id)]);
205
  setLabel("");
 
 
 
206
  setCopied(false);
207
  setRevealed(minted);
208
  }
@@ -290,17 +347,17 @@ export default function ExternalAccessPane() {
290
  if (keys === null) {
291
  return (
292
  <div className="set-loading">
293
- <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading external access" />
294
  </div>
295
  );
296
  }
297
 
298
  return (
299
  <div className="set-pane">
300
- <h3 className="set-h">External AI</h3>
301
  <p className="set-help set-pane-intro">
302
- Create a private credential for an AI you use. It can read and build, and it is held to
303
- exactly the access you have in Loopable, so it can never reach what you cannot.
304
  Revoking it stops the next request.
305
  </p>
306
 
@@ -383,11 +440,55 @@ export default function ExternalAccessPane() {
383
  onChange={(event) => setLabel(event.currentTarget.value)}
384
  />
385
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
386
  <div className="set-actions">
387
  <button
388
  type="submit"
389
  className="set-primary"
390
- disabled={busy === "create" || label.trim() === ""}
391
  >
392
  {busy === "create" ? "Creating…" : "Create credential"}
393
  </button>
@@ -395,7 +496,7 @@ export default function ExternalAccessPane() {
395
  </form>
396
  ) : canMint === false ? (
397
  <p className="set-help set-pane-intro">
398
- External AI access requires the Analyst module. Ask an administrator to grant it.
399
  </p>
400
  ) : null}
401
 
@@ -403,12 +504,20 @@ export default function ExternalAccessPane() {
403
  <h4 className="set-h4">Credentials</h4>
404
  </div>
405
  {keys.length === 0 ? (
406
- <p className="set-help">You have no active external AI credentials.</p>
407
  ) : (
408
  <div aria-label="Active credentials">
409
  {keys.map((key) => (
410
  <section className="set-card" key={key.id}>
411
  <h4 className="set-h4">{key.label}</h4>
 
 
 
 
 
 
 
 
412
  <div className="pg-drill-row">
413
  <span className="pg-drill-key">Created</span>
414
  <span className="pg-drill-val">{when(key.created)}</span>
 
19
  created: string;
20
  last_used: string | null;
21
  revoked_at: string | null;
22
+ access: string;
23
+ databases: string[] | "all";
24
+ }
25
+
26
+ interface ScopeDatabase {
27
+ database: string;
28
+ label: string;
29
  }
30
 
31
  interface KeyListResponse {
 
73
  ok: false,
74
  message:
75
  response.status >= 500
76
+ ? "The AI API is unavailable right now."
77
  : messageFrom(body, "That request could not be completed."),
78
  };
79
  }
 
104
  ok: false,
105
  message:
106
  response.status >= 500
107
+ ? "The AI API is unavailable right now."
108
  : messageFrom(parsed, "That request could not be completed."),
109
  };
110
  }
 
130
  created: row.created,
131
  last_used: typeof row.last_used === "string" ? row.last_used : null,
132
  revoked_at: typeof row.revoked_at === "string" ? row.revoked_at : null,
133
+ access: row.access === "read" ? "read" : "readwrite",
134
+ databases: Array.isArray(row.databases) && row.databases.every(
135
+ (database): database is string => typeof database === "string" && database.trim() !== "",
136
+ ) ? row.databases.map((database) => database.trim()) : "all",
137
  };
138
  }
139
 
 
148
  const [keys, setKeys] = useState<ExternalKeyMetadata[] | null>(null);
149
  const [canMint, setCanMint] = useState<boolean | null>(null);
150
  const [label, setLabel] = useState("");
151
+ const [access, setAccess] = useState("read");
152
+ const [databaseMode, setDatabaseMode] = useState("all");
153
+ const [selectedDatabases, setSelectedDatabases] = useState<string[]>([]);
154
+ const [scopeDatabases, setScopeDatabases] = useState<ScopeDatabase[] | null>(null);
155
+ const [scopeError, setScopeError] = useState("");
156
  const [busy, setBusy] = useState("");
157
  const [error, setError] = useState("");
158
  const [notice, setNotice] = useState("");
 
171
  if (!Array.isArray(result.data?.keys) || typeof result.data.can_mint !== "boolean") {
172
  setKeys([]);
173
  setCanMint(null);
174
+ setError("The AI API returned an unreadable response.");
175
  return;
176
  }
177
  const parsed = result.data.keys.map(parseKey);
178
  if (parsed.some((row) => row === null)) {
179
  setKeys([]);
180
  setCanMint(null);
181
+ setError("The AI API returned an unreadable response.");
182
  return;
183
  }
184
  setKeys(parsed as ExternalKeyMetadata[]);
 
190
  void load();
191
  }, [load]);
192
 
193
+ useEffect(() => {
194
+ if (canMint !== true) return;
195
+ let active = true;
196
+ void call<{ databases: ScopeDatabase[] }>("/external/scope/databases").then((result) => {
197
+ if (!active) return;
198
+ if (!result.ok) {
199
+ setScopeError(result.message);
200
+ setScopeDatabases([]);
201
+ return;
202
+ }
203
+ const rows = result.data?.databases;
204
+ if (!Array.isArray(rows) || rows.some((row) => !row || typeof row.database !== "string" || !row.database.trim())) {
205
+ setScopeError("The database list could not be read.");
206
+ setScopeDatabases([]);
207
+ return;
208
+ }
209
+ setScopeError("");
210
+ setScopeDatabases(rows.map((row) => ({
211
+ database: row.database,
212
+ label: typeof row.label === "string" && row.label.trim() ? row.label : row.database,
213
+ })));
214
+ });
215
+ return () => { active = false; };
216
+ }, [canMint]);
217
+
218
+ function databaseLabels(databases: ExternalKeyMetadata["databases"]): string {
219
+ if (databases === "all") return "All databases";
220
+ if (databases.length === 0) return "No databases";
221
+ const labels = databases.slice(0, 4).map((database) => (
222
+ scopeDatabases?.find((row) => row.database === database)?.label || database
223
+ ));
224
+ return labels.join(", ") + (databases.length > 4 ? ` and ${databases.length - 4} more` : "");
225
+ }
226
+
227
  async function create(event: FormEvent) {
228
  event.preventDefault();
229
  const clean = label.trim();
 
231
  setError("Enter a label for this credential.");
232
  return;
233
  }
234
+ if (databaseMode === "subset" && selectedDatabases.length === 0) {
235
+ setError("Choose at least one database for this credential.");
236
+ return;
237
+ }
238
  setBusy("create");
239
  setError("");
240
  setNotice("");
241
  const result = await call<MintResponse>("/external/keys", {
242
  method: "POST",
243
  headers: { "Content-Type": "application/json" },
244
+ body: JSON.stringify({ label: clean, access, databases: databaseMode === "all" ? "all" : selectedDatabases }),
245
  });
246
  setBusy("");
247
  if (!result.ok) {
 
257
  const minted = { key, secret: result.data.secret };
258
  setKeys((current) => [key, ...(current ?? []).filter((row) => row.id !== key.id)]);
259
  setLabel("");
260
+ setAccess("read");
261
+ setDatabaseMode("all");
262
+ setSelectedDatabases([]);
263
  setCopied(false);
264
  setRevealed(minted);
265
  }
 
347
  if (keys === null) {
348
  return (
349
  <div className="set-loading">
350
+ <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading the AI API" />
351
  </div>
352
  );
353
  }
354
 
355
  return (
356
  <div className="set-pane">
357
+ <h3 className="set-h">AI API</h3>
358
  <p className="set-help set-pane-intro">
359
+ Create a private credential for the AI API, held to exactly the access you have in Loopable.
360
+ Each credential also carries its own access level and database scope, so it can never reach what you cannot.
361
  Revoking it stops the next request.
362
  </p>
363
 
 
440
  onChange={(event) => setLabel(event.currentTarget.value)}
441
  />
442
  </div>
443
+ <div className="set-field">
444
+ <label className="set-label" htmlFor="set-external-access">Access</label>
445
+ <select id="set-external-access" className="pg-select" value={access}
446
+ onChange={(event) => setAccess(event.currentTarget.value)}>
447
+ <option value="read">Read only</option>
448
+ <option value="readwrite">Read and write</option>
449
+ </select>
450
+ </div>
451
+ <div className="set-field">
452
+ <label className="set-label" htmlFor="set-external-databases">Databases</label>
453
+ <select id="set-external-databases" className="pg-select" value={databaseMode}
454
+ onChange={(event) => setDatabaseMode(event.currentTarget.value)}>
455
+ <option value="all">All databases</option>
456
+ <option value="subset">Selected databases</option>
457
+ </select>
458
+ </div>
459
+ {/* ⭐ W62-T16 — the subset list is BOUNDED, and inline-styled for one reason: the
460
+ `set-*` vocabulary lives in `index.css`, which is another lane's file under this
461
+ wave's FILE OWNERSHIP, so this list cannot declare a class of its own. Measured on
462
+ the staging tenant at 1440x900: 60-odd databases pushed "Create credential" three
463
+ screens below the card. The same precedent, and the same reason, is
464
+ `.shell-avatar`'s inline fit rules in `Shell.tsx`. No colour is declared here, so
465
+ W62-T33's scrollbar treatment lands on this element for free. */}
466
+ {databaseMode === "subset" ? (
467
+ <div className="set-field" style={{ maxHeight: 216, overflowY: "auto" }}>
468
+ {scopeDatabases === null ? <p className="set-help">Loading databases…</p> : null}
469
+ {scopeError ? <p className="set-error">{scopeError}</p> : null}
470
+ {scopeDatabases?.map((database) => (
471
+ <label className="set-check" key={database.database}>
472
+ <input type="checkbox" checked={selectedDatabases.includes(database.database)}
473
+ onChange={(event) => {
474
+ const checked = event.currentTarget.checked;
475
+ setSelectedDatabases((current) => checked
476
+ ? [...current, database.database]
477
+ : current.filter((key) => key !== database.database));
478
+ }} />
479
+ <span>{database.label || database.database}</span>
480
+ </label>
481
+ ))}
482
+ {selectedDatabases.length === 0 ? (
483
+ <p className="set-help">Choose at least one database for this credential.</p>
484
+ ) : null}
485
+ </div>
486
+ ) : null}
487
  <div className="set-actions">
488
  <button
489
  type="submit"
490
  className="set-primary"
491
+ disabled={busy === "create" || label.trim() === "" || (databaseMode === "subset" && selectedDatabases.length === 0)}
492
  >
493
  {busy === "create" ? "Creating…" : "Create credential"}
494
  </button>
 
496
  </form>
497
  ) : canMint === false ? (
498
  <p className="set-help set-pane-intro">
499
+ The AI API requires the Analyst module. Ask an administrator to grant it.
500
  </p>
501
  ) : null}
502
 
 
504
  <h4 className="set-h4">Credentials</h4>
505
  </div>
506
  {keys.length === 0 ? (
507
+ <p className="set-help">You have no AI API credentials yet.</p>
508
  ) : (
509
  <div aria-label="Active credentials">
510
  {keys.map((key) => (
511
  <section className="set-card" key={key.id}>
512
  <h4 className="set-h4">{key.label}</h4>
513
+ <div className="pg-drill-row">
514
+ <span className="pg-drill-key">Access</span>
515
+ <span className="pg-drill-val">{key.access === "read" ? "Read only" : "Read and write"}</span>
516
+ </div>
517
+ <div className="pg-drill-row">
518
+ <span className="pg-drill-key">Databases</span>
519
+ <span className="pg-drill-val">{databaseLabels(key.databases)}</span>
520
+ </div>
521
  <div className="pg-drill-row">
522
  <span className="pg-drill-key">Created</span>
523
  <span className="pg-drill-val">{when(key.created)}</span>
web/src/settings/SettingsModal.tsx CHANGED
@@ -164,7 +164,7 @@ const IconShortcuts = (
164
  <path d="M4.7 7.1h.01M7.3 7.1h.01M9.9 7.1h.01M12.5 7.1h.01M5.5 9.6h5" />
165
  </RailIcon>
166
  );
167
- /** External AI - a governed connection leaving this account. */
168
  const IconExternal = (
169
  <RailIcon>
170
  <circle cx="8" cy="8" r="2.2" />
@@ -810,7 +810,7 @@ export function SettingsModal({
810
  // preferences, and there is nothing behind this room a member's account cannot already do to
811
  // itself (the store is client-local, keyed to nothing server-side).
812
  ["shortcuts", "Sheet shortcuts", IconShortcuts],
813
- ["external", "External AI", IconExternal],
814
  ...(admin
815
  ? ([
816
  ["users", "Manage users", IconUsers],
 
164
  <path d="M4.7 7.1h.01M7.3 7.1h.01M9.9 7.1h.01M12.5 7.1h.01M5.5 9.6h5" />
165
  </RailIcon>
166
  );
167
+ /** AI API - a governed connection leaving this account. */
168
  const IconExternal = (
169
  <RailIcon>
170
  <circle cx="8" cy="8" r="2.2" />
 
810
  // preferences, and there is nothing behind this room a member's account cannot already do to
811
  // itself (the store is client-local, keyed to nothing server-side).
812
  ["shortcuts", "Sheet shortcuts", IconShortcuts],
813
+ ["external", "AI API", IconExternal],
814
  ...(admin
815
  ? ([
816
  ["users", "Manage users", IconUsers],
web/src/sheet/BindingEditor.tsx CHANGED
@@ -59,9 +59,11 @@ import { SheetFilterPopup } from "../filter-kit/SheetFilterPopup";
59
  import { WindowPicker } from "../filter-kit/WindowPicker";
60
  import { useEscapeClose } from "../ui/useEscapeClose";
61
  import { previewCell, readWorkbook } from "./sheetApi";
 
62
  import { formatRef, parseRef } from "./a1";
63
- import { bindingAggregate, bindingDisplay, bindingFilterClauses, bindingOnDrag, BINDING_ENDING_STEP, BINDING_PERIOD_STEP } from "./types";
64
- import type { BindingAggregate, BindingDragStep, BindingOnDrag } from "./types";
 
65
  import { bindingStepMode, bindingStepValues, resolveEndingCell, seedBindingStep,
66
  bindingRefSlots, filterValueLeaves, resolveFilterCell, updateFilterValueLeaf } from "./bindingRefs";
67
  import "../styles/wave57/binding-actions.css";
@@ -73,8 +75,12 @@ const BINDING_SECTIONS = [
73
  { key: "rows", label: "Filter", icon: <MenuIcon name="filter" /> },
74
  { key: "period", label: "Period", icon: <FieldTypeIcon type="date" size={16} /> },
75
  { key: "copied", label: "When copied", icon: <MenuIcon name="duplicate" /> },
 
76
  ] as const;
77
 
 
 
 
78
  const AGGREGATES = [
79
  { fn: "sum", label: "Sum" },
80
  { fn: "count", label: "Count" },
@@ -675,6 +681,20 @@ export default function BindingEditor({
675
  workbookId, addr, databases, initial, onSave, onCancel,
676
  }: BindingEditorProps) {
677
  const [activeSection, setActiveSection] = useState<typeof BINDING_SECTIONS[number]["key"]>("data");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
678
  const [database, setDatabase] = useState<string>(
679
  String((initial?.database as string) ?? databases[0]?.key ?? ""),
680
  );
@@ -683,9 +703,13 @@ export default function BindingEditor({
683
  // re-rendered for an unrelated reason, which is the failure the period note already describes.
684
  const savedAgg = useState(() => readAggregate(initial?.aggregate))[0];
685
  const savedSource = useState(() => bindingAggregate(initial?.aggregate))[0];
686
- const [sourceKind, setSourceKind] = useState<BindingAggregate["kind"]>(savedSource.kind);
 
 
 
687
  const [metricKey, setMetricKey] = useState(savedSource.kind === "number" ? savedSource.metric_key : "");
688
- const savedScope = useState(() => readScope(initial?.scope))[0];
 
689
  const savedView = useState(() => savedViewOf(initial))[0];
690
 
691
  const [fn, setFn] = useState<string>(savedAgg.fn);
@@ -856,7 +880,18 @@ export default function BindingEditor({
856
  // applying) and a cell narrowed to a period could not be widened back to all time from this panel
857
  // at all, which is standing rule 1's second sentence - a limit nobody was told about. The switch
858
  // below states which of the two a cell is, and either answer is one click from the other.
859
- const [periodOn, setPeriodOn] = useState<boolean>(Boolean(migrated));
 
 
 
 
 
 
 
 
 
 
 
860
  useEffect(() => {
861
  if (!periodOn || periodMode !== "window" || ending !== "cell") return;
862
  let cancelled = false;
@@ -1166,8 +1201,10 @@ export default function BindingEditor({
1166
  * column this database cannot total still shows its own name beside the notice that says so.
1167
  * That is the same three-state rule `customer-grid/FieldSelect.tsx` documents at its head. */
1168
  const chosenField = useMemo(() => fields.find((f) => f.key === field), [fields, field]);
1169
- const chosenIsMetric = sourceKind === "number";
1170
- const periodClauseLabel = `Period of ${measures.find((m) => m.key === metricKey)?.label || metricKey || "Metric"}`;
 
 
1171
  const changeSource = (kind: BindingAggregate["kind"]) => {
1172
  setSourceKind(kind);
1173
  setMetricKey("");
@@ -1186,6 +1223,8 @@ export default function BindingEditor({
1186
  updateCopySteps([]);
1187
  setPeriodOn(chosenIsMetric);
1188
  setPreview("");
 
 
1189
  };
1190
 
1191
  /** The database's own label, which the column list's heading names. Two databases can both
@@ -1229,7 +1268,7 @@ export default function BindingEditor({
1229
  } : {}) };
1230
  } else {
1231
  const period: Record<string, unknown> = {
1232
- unit, start, locked: chosenIsMetric ? locked : true,
1233
  };
1234
  if (frozen) {
1235
  period.frozen = true;
@@ -1244,16 +1283,33 @@ export default function BindingEditor({
1244
  // Metric cell step its period and one filter clause without either choice erasing the other.
1245
  const steps = copySteps.filter((step) => step.field && (step.field === BINDING_ENDING_STEP
1246
  ? periodOn && hasEnding && periodMode === "window" : step.field === BINDING_PERIOD_STEP
1247
- ? periodOn && chosenIsMetric && !locked && periodMode === "calendar" : true));
1248
  // An unchanged legacy editor keeps the old copy semantics on save as well as on read.
1249
  out.onDrag = !copyStepsEdited && !Array.isArray((initial?.onDrag as BindingOnDrag | undefined)?.steps)
1250
  ? { across: savedDrag.across, down: savedDrag.down }
1251
  : bindingOnDrag({ onDrag: { steps } });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1252
  return out;
1253
  }, [database, sourceKind, metricKey, fn, field, scopeKind, viewId, views, tree, initial,
1254
  unit, start, locked, frozen, frozenFrom, frozenTo, refOpen, periodRef, periodOn, periodMode, windowSpec,
1255
  across, copySteps, copyStepsEdited, savedDrag, chosenIsMetric, hasEnding, ending, endingFixed,
1256
- endingN, endingUnit, endingStep, endingOffset, endingRef]);
 
1257
 
1258
  // Read before either send; the server reads the stored source again independently.
1259
  const prepareBinding = async (): Promise<Record<string, unknown> | null> => {
@@ -1320,33 +1376,51 @@ export default function BindingEditor({
1320
  // Save taken then would write back a binding assembled from a list nobody had seen yet.
1321
  // W59-T11: the rail and Save share these terms; only Metrics require a period.
1322
  const dataComplete = databases.some((d) => d.key === database)
1323
- && (chosenIsMetric ? Boolean(metricKey) && measures.some((m) => m.key === metricKey)
1324
- : fn === "count" || numericFields.some((candidate) => candidate.key === field));
 
 
 
1325
  const filterComplete = scopeKind === "filter" || Boolean(viewId);
1326
  const frozenRangeComplete = !frozen || Boolean(range.from && range.to && range.from <= range.to);
1327
  const periodComplete = (!chosenIsMetric || periodOn)
1328
  && (!periodOn || periodMode !== "calendar" || frozenRangeComplete);
1329
  const copiedComplete = !savedDragDriverMissing;
1330
- const ready = optionsResolved && dataComplete && filterComplete && periodComplete && copiedComplete;
 
1331
 
1332
  const sectionComplete = {
1333
  data: dataComplete, rows: filterComplete, period: periodComplete, copied: copiedComplete,
 
1334
  };
1335
- const sectionGates = BINDING_SECTIONS.map((section, index) => {
1336
- const blocker = BINDING_SECTIONS.slice(0, index).find(({ key }) => !sectionComplete[key]);
1337
- return {
1338
- ...section,
1339
- reachable: !blocker,
1340
- blockedHint: blocker?.key === "data" ? "Pick a source"
1341
- : blocker?.key === "rows" ? "Pick rows"
1342
- : blocker?.key === "period" ? "Set a period" : undefined,
1343
- };
1344
- });
1345
- const periodReachable = sectionGates.some(({ key, reachable }) => key === "period" && reachable);
 
1346
  const lastReachableIndex = sectionGates.reduce(
1347
  (last, section, index) => section.reachable ? index : last, 0,
1348
  );
1349
 
 
 
 
 
 
 
 
 
 
 
 
 
1350
  useEffect(() => {
1351
  setActiveSection((current) => {
1352
  const currentIndex = BINDING_SECTIONS.findIndex(({ key }) => key === current);
@@ -1424,10 +1498,8 @@ export default function BindingEditor({
1424
  >
1425
  <span className="sheet-binding-rail-icon">{icon}</span>
1426
  <span className="sheet-binding-rail-label">{label}</span>
1427
- {!reachable ? (
1428
  <span className="sheet-binding-rail-hint">{blockedHint}</span>
1429
- ) : key === "period" && chosenIsMetric && !periodComplete && (
1430
- <>{" "}<span className="sheet-binding-rail-required">Required</span></>
1431
  )}
1432
  </button>
1433
  ))}
@@ -1435,6 +1507,19 @@ export default function BindingEditor({
1435
  <div className="sheet-binding-section" data-section={activeSection}>
1436
  {activeSection === "data" && (
1437
  <>
 
 
 
 
 
 
 
 
 
 
 
 
 
1438
  <label className="sheet-field">
1439
  <span>Database</span>
1440
  <select value={database} onChange={(e) => changeDatabase(e.target.value)}>
@@ -1442,6 +1527,7 @@ export default function BindingEditor({
1442
  </select>
1443
  </label>
1444
 
 
1445
  <fieldset className="sheet-source-path">
1446
  <legend>Source</legend>
1447
  <label className="sheet-radio">
@@ -1471,10 +1557,6 @@ export default function BindingEditor({
1471
  <p className="sheet-notice">{measures.length === 0
1472
  ? "No Metrics are available here. Choose another database."
1473
  : "Binding adds a Metric column to this database if one is not already there."}</p>
1474
- <button type="button" className="sheet-action" disabled={!periodReachable}
1475
- onClick={() => setActiveSection("period")}>
1476
- {periodOn ? "Edit Period / Lookback" : "Choose Period / Lookback"}
1477
- </button>
1478
  </div>
1479
  ) : (
1480
  <label className="sheet-field">
@@ -1565,6 +1647,34 @@ export default function BindingEditor({
1565
  </div>
1566
  )}
1567
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1568
  </>
1569
  )}
1570
  {activeSection === "rows" && (
@@ -1680,6 +1790,7 @@ export default function BindingEditor({
1680
  </>
1681
  )}
1682
  </fieldset>
 
1683
  </>
1684
  )}
1685
  {activeSection === "period" && (
@@ -1908,7 +2019,7 @@ export default function BindingEditor({
1908
 
1909
  {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the
1910
  sentence under it says what each one costs when the cell is copied. */}
1911
- {chosenIsMetric ? (
1912
  <div className="sheet-period-lock">
1913
  <button
1914
  type="button"
@@ -1973,6 +2084,7 @@ export default function BindingEditor({
1973
  </>
1974
  )}
1975
  </fieldset>
 
1976
  </>
1977
  )}
1978
  {activeSection === "copied" && (
@@ -2006,7 +2118,7 @@ export default function BindingEditor({
2006
  key: BINDING_ENDING_STEP, label: "Ending",
2007
  disabled: copySteps.some((held, i) => i !== index && held.field === BINDING_ENDING_STEP),
2008
  }] : []),
2009
- ...(chosenIsMetric && periodOn && periodMode === "calendar" ? [{
2010
  key: BINDING_PERIOD_STEP, label: periodClauseLabel,
2011
  disabled: copySteps.some((held, i) => i !== index && held.field === BINDING_PERIOD_STEP),
2012
  }] : []),
@@ -2057,6 +2169,16 @@ export default function BindingEditor({
2057
  {!rowsResolved && <p className="sheet-period-note" role="status">{rowsNotice || "Loading all field values…"}</p>}
2058
  {savedDragDriverMissing && <p className="sheet-notice" role="alert">The saved Step field is unavailable. Choose another field.</p>}
2059
  </fieldset>
 
 
 
 
 
 
 
 
 
 
2060
  </>
2061
  )}
2062
  </div>
@@ -2083,6 +2205,7 @@ export default function BindingEditor({
2083
  {/* C7 and the owner's Apple principle: Save is this surface's ONE primary;
2084
  Preview and Cancel are deliberately quiet. */}
2085
  <div className="sheet-binding-actions">
 
2086
  <button type="button" className="lp-btn lp-btn-quiet" onClick={runPreview} disabled={!ready}>
2087
  Preview
2088
  </button>
@@ -2092,6 +2215,7 @@ export default function BindingEditor({
2092
  disabled={!ready}>
2093
  Save
2094
  </button>
 
2095
  <button type="button" className="lp-btn lp-btn-quiet" onClick={onCancel}>
2096
  Cancel
2097
  </button>
 
59
  import { WindowPicker } from "../filter-kit/WindowPicker";
60
  import { useEscapeClose } from "../ui/useEscapeClose";
61
  import { previewCell, readWorkbook } from "./sheetApi";
62
+ import DrillModal from "./DrillModal";
63
  import { formatRef, parseRef } from "./a1";
64
+ import { bindingAggregate, bindingDisplay, bindingFilterClauses, bindingOnDrag, BINDING_ENDING_STEP, BINDING_PERIOD_STEP,
65
+ VIEW_BINDING_TYPES, VIEW_BINDING_LIMIT_DEFAULT, VIEW_BINDING_LIMIT_MAX } from "./types";
66
+ import type { BindingAggregate, BindingDragStep, BindingOnDrag, ViewBinding } from "./types";
67
  import { bindingStepMode, bindingStepValues, resolveEndingCell, seedBindingStep,
68
  bindingRefSlots, filterValueLeaves, resolveFilterCell, updateFilterValueLeaf } from "./bindingRefs";
69
  import "../styles/wave57/binding-actions.css";
 
75
  { key: "rows", label: "Filter", icon: <MenuIcon name="filter" /> },
76
  { key: "period", label: "Period", icon: <FieldTypeIcon type="date" size={16} /> },
77
  { key: "copied", label: "When copied", icon: <MenuIcon name="duplicate" /> },
78
+ { key: "place", label: "Place", icon: <MenuIcon name="addEnd" /> },
79
  ] as const;
80
 
81
+ const clampViewLimit = (value: number): number => Number.isFinite(value)
82
+ ? Math.min(VIEW_BINDING_LIMIT_MAX, Math.max(1, Math.trunc(value))) : VIEW_BINDING_LIMIT_DEFAULT;
83
+
84
  const AGGREGATES = [
85
  { fn: "sum", label: "Sum" },
86
  { fn: "count", label: "Count" },
 
681
  workbookId, addr, databases, initial, onSave, onCancel,
682
  }: BindingEditorProps) {
683
  const [activeSection, setActiveSection] = useState<typeof BINDING_SECTIONS[number]["key"]>("data");
684
+ const [shape, setShape] = useState<"value" | "view">(initial?.mode === "view" ? "view" : "value");
685
+ const [viewType, setViewType] = useState<ViewBinding["viewType"]>(() =>
686
+ VIEW_BINDING_TYPES.includes(initial?.viewType as ViewBinding["viewType"])
687
+ ? initial!.viewType as ViewBinding["viewType"] : "grid");
688
+ const [viewFields, setViewFields] = useState<string[]>(() => initial?.mode === "view"
689
+ && Array.isArray(initial.fields) ? initial.fields.filter((key): key is string => typeof key === "string") : []);
690
+ const [viewLimit, setViewLimit] = useState(() => clampViewLimit(
691
+ typeof initial?.limit === "number" ? initial.limit : VIEW_BINDING_LIMIT_DEFAULT));
692
+ const [viewSort, setViewSort] = useState<ViewBinding["sort"]>(() =>
693
+ initial?.mode === "view" && Array.isArray(initial.sort) ? initial.sort.flatMap((item) => {
694
+ if (!item || typeof item !== "object" || typeof item.field !== "string"
695
+ || (item.dir !== "asc" && item.dir !== "desc")) return [];
696
+ return [{ field: item.field, dir: item.dir }];
697
+ }) : []);
698
  const [database, setDatabase] = useState<string>(
699
  String((initial?.database as string) ?? databases[0]?.key ?? ""),
700
  );
 
703
  // re-rendered for an unrelated reason, which is the failure the period note already describes.
704
  const savedAgg = useState(() => readAggregate(initial?.aggregate))[0];
705
  const savedSource = useState(() => bindingAggregate(initial?.aggregate))[0];
706
+ // Seed new builders here; changing the shared fallback would alter other readers of saved bindings.
707
+ const [sourceKind, setSourceKind] = useState<BindingAggregate["kind"]>(
708
+ initial?.aggregate == null ? "number" : savedSource.kind,
709
+ );
710
  const [metricKey, setMetricKey] = useState(savedSource.kind === "number" ? savedSource.metric_key : "");
711
+ const savedScope = useState(() => readScope(initial?.mode === "view"
712
+ ? { filter: initial.filter ?? { conj: "and", nodes: [] } } : initial?.scope))[0];
713
  const savedView = useState(() => savedViewOf(initial))[0];
714
 
715
  const [fn, setFn] = useState<string>(savedAgg.fn);
 
880
  // applying) and a cell narrowed to a period could not be widened back to all time from this panel
881
  // at all, which is standing rule 1's second sentence - a limit nobody was told about. The switch
882
  // below states which of the two a cell is, and either answer is one click from the other.
883
+ // ⛔⛔ W62-T09 — THE SEED HAS TO AGREE WITH `changeSource`, AND BEFORE THIS TICKET NOTHING MADE
884
+ // IT. For a Metric the switch below is `disabled={chosenIsMetric}` on purpose: a Metric's period
885
+ // is MANDATORY (R25 keeps that gating), so the control states the fact rather than offering a
886
+ // choice, and `changeSource("number")` raises the flag as its side effect. R25 now opens the
887
+ // builder ON Metric, which reaches that same state WITHOUT anyone calling `changeSource` - so a
888
+ // fresh Metric binding started with the period off, the switch disabled, no way to turn it on
889
+ // and therefore `periodComplete` false and Save disabled forever. The seed says the same thing
890
+ // `changeSource` says, once, here. It repairs a saved Metric binding stored without a period too.
891
+ const [valuePeriodOn, setValuePeriodOn] = useState<boolean>(Boolean(migrated) || sourceKind === "number");
892
+ const [viewPeriodOn, setViewPeriodOn] = useState<boolean>(Boolean(migrated));
893
+ const periodOn = shape === "view" ? viewPeriodOn : valuePeriodOn;
894
+ const setPeriodOn = shape === "view" ? setViewPeriodOn : setValuePeriodOn;
895
  useEffect(() => {
896
  if (!periodOn || periodMode !== "window" || ending !== "cell") return;
897
  let cancelled = false;
 
1201
  * column this database cannot total still shows its own name beside the notice that says so.
1202
  * That is the same three-state rule `customer-grid/FieldSelect.tsx` documents at its head. */
1203
  const chosenField = useMemo(() => fields.find((f) => f.key === field), [fields, field]);
1204
+ const chosenIsMetric = shape === "value" && sourceKind === "number";
1205
+ const canStepPeriod = chosenIsMetric || shape === "view";
1206
+ const periodClauseLabel = shape === "view" ? "Period"
1207
+ : `Period of ${measures.find((m) => m.key === metricKey)?.label || metricKey || "Metric"}`;
1208
  const changeSource = (kind: BindingAggregate["kind"]) => {
1209
  setSourceKind(kind);
1210
  setMetricKey("");
 
1223
  updateCopySteps([]);
1224
  setPeriodOn(chosenIsMetric);
1225
  setPreview("");
1226
+ setViewFields([]);
1227
+ setViewSort([]);
1228
  };
1229
 
1230
  /** The database's own label, which the column list's heading names. Two databases can both
 
1268
  } : {}) };
1269
  } else {
1270
  const period: Record<string, unknown> = {
1271
+ unit, start, locked: canStepPeriod ? locked : true,
1272
  };
1273
  if (frozen) {
1274
  period.frozen = true;
 
1283
  // Metric cell step its period and one filter clause without either choice erasing the other.
1284
  const steps = copySteps.filter((step) => step.field && (step.field === BINDING_ENDING_STEP
1285
  ? periodOn && hasEnding && periodMode === "window" : step.field === BINDING_PERIOD_STEP
1286
+ ? periodOn && canStepPeriod && !locked && periodMode === "calendar" : true));
1287
  // An unchanged legacy editor keeps the old copy semantics on save as well as on read.
1288
  out.onDrag = !copyStepsEdited && !Array.isArray((initial?.onDrag as BindingOnDrag | undefined)?.steps)
1289
  ? { across: savedDrag.across, down: savedDrag.down }
1290
  : bindingOnDrag({ onDrag: { steps } });
1291
+ if (shape === "view") {
1292
+ const viewBinding: ViewBinding = {
1293
+ database, mode: "view", viewType, fields: viewFields,
1294
+ // C2 stores the selected predicate itself, including a saved view's chosen filter.
1295
+ filter: scopeKind === "filter" ? tree : {
1296
+ conj: selectedView?.config.filterConj ?? "and",
1297
+ nodes: selectedView?.config.filters ?? [],
1298
+ },
1299
+ sort: viewSort, limit: viewLimit,
1300
+ ...(out.period ? { period: out.period as Record<string, unknown> } : {}),
1301
+ onDrag: out.onDrag as BindingOnDrag,
1302
+ ...(initial?.mode === "view" && initial.database === database && initial.block
1303
+ ? { block: initial.block as ViewBinding["block"] } : {}),
1304
+ };
1305
+ return viewBinding;
1306
+ }
1307
  return out;
1308
  }, [database, sourceKind, metricKey, fn, field, scopeKind, viewId, views, tree, initial,
1309
  unit, start, locked, frozen, frozenFrom, frozenTo, refOpen, periodRef, periodOn, periodMode, windowSpec,
1310
  across, copySteps, copyStepsEdited, savedDrag, chosenIsMetric, hasEnding, ending, endingFixed,
1311
+ endingN, endingUnit, endingStep, endingOffset, endingRef,
1312
+ shape, viewType, viewFields, viewSort, viewLimit, selectedView, canStepPeriod]);
1313
 
1314
  // Read before either send; the server reads the stored source again independently.
1315
  const prepareBinding = async (): Promise<Record<string, unknown> | null> => {
 
1376
  // Save taken then would write back a binding assembled from a list nobody had seen yet.
1377
  // W59-T11: the rail and Save share these terms; only Metrics require a period.
1378
  const dataComplete = databases.some((d) => d.key === database)
1379
+ && (shape === "view" ? viewFields.length > 0
1380
+ && viewFields.every((key) => fields.some((candidate) => candidate.key === key))
1381
+ && Number.isInteger(viewLimit) && viewLimit >= 1 && viewLimit <= VIEW_BINDING_LIMIT_MAX
1382
+ : chosenIsMetric ? Boolean(metricKey) && measures.some((m) => m.key === metricKey)
1383
+ : fn === "count" || numericFields.some((candidate) => candidate.key === field));
1384
  const filterComplete = scopeKind === "filter" || Boolean(viewId);
1385
  const frozenRangeComplete = !frozen || Boolean(range.from && range.to && range.from <= range.to);
1386
  const periodComplete = (!chosenIsMetric || periodOn)
1387
  && (!periodOn || periodMode !== "calendar" || frozenRangeComplete);
1388
  const copiedComplete = !savedDragDriverMissing;
1389
+ const ready = optionsResolved && dataComplete && filterComplete && periodComplete && copiedComplete
1390
+ && (shape === "value" || activeSection === "place");
1391
 
1392
  const sectionComplete = {
1393
  data: dataComplete, rows: filterComplete, period: periodComplete, copied: copiedComplete,
1394
+ place: ready,
1395
  };
1396
+ const sectionGates = BINDING_SECTIONS.filter(({ key }) => shape === "view" || key !== "place")
1397
+ .map((section, index, sections) => {
1398
+ const blocker = sections.slice(0, index).find(({ key }) => !sectionComplete[key]);
1399
+ return {
1400
+ ...section,
1401
+ reachable: !blocker,
1402
+ blockedHint: blocker?.key === "data" ? "Pick a source"
1403
+ : blocker?.key === "rows" ? "Pick rows"
1404
+ : blocker?.key === "period" ? "Set a period"
1405
+ : blocker?.key === "copied" ? "Choose a step field" : undefined,
1406
+ };
1407
+ });
1408
  const lastReachableIndex = sectionGates.reduce(
1409
  (last, section, index) => section.reachable ? index : last, 0,
1410
  );
1411
 
1412
+ // This shared Next replaces the Metric-only Period shortcut, keeping one forward control per step.
1413
+ const renderNext = (section: typeof BINDING_SECTIONS[number]["key"]) => {
1414
+ const currentIndex = sectionGates.findIndex(({ key }) => key === section);
1415
+ const next = sectionGates.slice(currentIndex + 1).find(({ reachable }) => reachable);
1416
+ return (
1417
+ <button type="button" className="sheet-action" disabled={!sectionComplete[section] || !next}
1418
+ onClick={() => { if (next) setActiveSection(next.key); }}>
1419
+ Next
1420
+ </button>
1421
+ );
1422
+ };
1423
+
1424
  useEffect(() => {
1425
  setActiveSection((current) => {
1426
  const currentIndex = BINDING_SECTIONS.findIndex(({ key }) => key === current);
 
1498
  >
1499
  <span className="sheet-binding-rail-icon">{icon}</span>
1500
  <span className="sheet-binding-rail-label">{label}</span>
1501
+ {!reachable && (
1502
  <span className="sheet-binding-rail-hint">{blockedHint}</span>
 
 
1503
  )}
1504
  </button>
1505
  ))}
 
1507
  <div className="sheet-binding-section" data-section={activeSection}>
1508
  {activeSection === "data" && (
1509
  <>
1510
+ <fieldset className="sheet-source-path">
1511
+ <legend>Result</legend>
1512
+ <label className="sheet-radio">
1513
+ <input type="radio" name="sheet-binding-shape" checked={shape === "value"}
1514
+ onChange={() => { setShape("value"); setPreview(""); setNotice(""); }} />
1515
+ <span>One value</span>
1516
+ </label>
1517
+ <label className="sheet-radio">
1518
+ <input type="radio" name="sheet-binding-shape" checked={shape === "view"}
1519
+ onChange={() => { setShape("view"); setPreview(""); setNotice(""); }} />
1520
+ <span>A view</span>
1521
+ </label>
1522
+ </fieldset>
1523
  <label className="sheet-field">
1524
  <span>Database</span>
1525
  <select value={database} onChange={(e) => changeDatabase(e.target.value)}>
 
1527
  </select>
1528
  </label>
1529
 
1530
+ {shape === "value" ? <>
1531
  <fieldset className="sheet-source-path">
1532
  <legend>Source</legend>
1533
  <label className="sheet-radio">
 
1557
  <p className="sheet-notice">{measures.length === 0
1558
  ? "No Metrics are available here. Choose another database."
1559
  : "Binding adds a Metric column to this database if one is not already there."}</p>
 
 
 
 
1560
  </div>
1561
  ) : (
1562
  <label className="sheet-field">
 
1647
  </div>
1648
  )}
1649
  </div>
1650
+ </> : <>
1651
+ <label className="sheet-field">
1652
+ <span>View type</span>
1653
+ <select aria-label="View type" value={viewType}
1654
+ onChange={(e) => setViewType(e.target.value as ViewBinding["viewType"])}>
1655
+ {VIEW_BINDING_TYPES.map((type) => <option key={type} value={type}>
1656
+ {type[0].toUpperCase() + type.slice(1)}
1657
+ </option>)}
1658
+ </select>
1659
+ </label>
1660
+ <label className="sheet-field">
1661
+ <span>Fields to show</span>
1662
+ <select multiple required aria-label="Fields to show" value={viewFields}
1663
+ onChange={(e) => setViewFields(Array.from(e.target.selectedOptions, (option) => option.value))}>
1664
+ {fields.map((candidate) => <option key={candidate.key} value={candidate.key}>
1665
+ {candidate.label}
1666
+ </option>)}
1667
+ </select>
1668
+ </label>
1669
+ {!viewFields.length && <p className="sheet-period-note">Choose at least one field.</p>}
1670
+ <label className="sheet-field">
1671
+ <span>Row limit</span>
1672
+ <input type="number" aria-label="Row limit" min={1} max={VIEW_BINDING_LIMIT_MAX}
1673
+ step={1} value={viewLimit}
1674
+ onChange={(e) => setViewLimit(clampViewLimit(e.target.valueAsNumber))} />
1675
+ </label>
1676
+ </>}
1677
+ {renderNext("data")}
1678
  </>
1679
  )}
1680
  {activeSection === "rows" && (
 
1790
  </>
1791
  )}
1792
  </fieldset>
1793
+ {renderNext("rows")}
1794
  </>
1795
  )}
1796
  {activeSection === "period" && (
 
2019
 
2020
  {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the
2021
  sentence under it says what each one costs when the cell is copied. */}
2022
+ {canStepPeriod ? (
2023
  <div className="sheet-period-lock">
2024
  <button
2025
  type="button"
 
2084
  </>
2085
  )}
2086
  </fieldset>
2087
+ {renderNext("period")}
2088
  </>
2089
  )}
2090
  {activeSection === "copied" && (
 
2118
  key: BINDING_ENDING_STEP, label: "Ending",
2119
  disabled: copySteps.some((held, i) => i !== index && held.field === BINDING_ENDING_STEP),
2120
  }] : []),
2121
+ ...(canStepPeriod && periodOn && periodMode === "calendar" ? [{
2122
  key: BINDING_PERIOD_STEP, label: periodClauseLabel,
2123
  disabled: copySteps.some((held, i) => i !== index && held.field === BINDING_PERIOD_STEP),
2124
  }] : []),
 
2169
  {!rowsResolved && <p className="sheet-period-note" role="status">{rowsNotice || "Loading all field values…"}</p>}
2170
  {savedDragDriverMissing && <p className="sheet-notice" role="alert">The saved Step field is unavailable. Choose another field.</p>}
2171
  </fieldset>
2172
+ {renderNext("copied")}
2173
+ </>
2174
+ )}
2175
+ {shape === "view" && activeSection === "place" && (
2176
+ <>
2177
+ {ready && <DrillModal workbookId={workbookId} addr={addr} label="Place"
2178
+ previewBinding={binding as ViewBinding}
2179
+ onClose={() => setActiveSection("copied")}
2180
+ onPlace={() => { if (ready) onSave(binding); }} />}
2181
+ {renderNext("place")}
2182
  </>
2183
  )}
2184
  </div>
 
2205
  {/* C7 and the owner's Apple principle: Save is this surface's ONE primary;
2206
  Preview and Cancel are deliberately quiet. */}
2207
  <div className="sheet-binding-actions">
2208
+ {shape === "value" && <>
2209
  <button type="button" className="lp-btn lp-btn-quiet" onClick={runPreview} disabled={!ready}>
2210
  Preview
2211
  </button>
 
2215
  disabled={!ready}>
2216
  Save
2217
  </button>
2218
+ </>}
2219
  <button type="button" className="lp-btn lp-btn-quiet" onClick={onCancel}>
2220
  Cancel
2221
  </button>
web/src/sheet/DrillModal.tsx CHANGED
@@ -58,7 +58,7 @@ import { fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge";
58
  import type { SurfaceScope } from "../customer-grid/apiBridge";
59
  import type { CellDisplayChoice } from "../customer-grid/CustomerGrid";
60
  import { dataPathHash } from "../customer-grid/dataPath";
61
- import { AnchoredOverlay, OverlayProvider } from "../customer-grid/OverlaySurface";
62
  import type { Field, FilterTree, GridWorkspace, Row } from "../customer-grid/types";
63
  import { mayEditField, topicForScope } from "../customer-grid/types";
64
  import { conditionCountLabel, filterSentence } from "../filter-kit/SheetFilterPopup";
@@ -66,8 +66,9 @@ import { useEscapeClose } from "../ui/useEscapeClose";
66
  import { cellForcedFieldKeys, cellViewVisibleKeys } from "./bindingRefs";
67
  import { drillCell } from "./sheetApi";
68
  import type { CellDrill } from "./sheetApi";
69
- import type { BindingDisplay } from "./types";
70
  import { bindingDisplay } from "./types";
 
71
 
72
  /**
73
  * ⛔⛔ LAZY, AND THE BUILD IS WHAT SAID SO. A plain `import { LinkGridModal } from
@@ -242,6 +243,8 @@ export interface DrillModalProps {
242
  /** The label the popup wears. The cell's own address is the honest one: it is what was clicked. */
243
  label: string;
244
  onClose: () => void;
 
 
245
  /**
246
  * W54-T34: the drill has stopped waiting - it answered, or it was refused. The page uses this to
247
  * take the busy state back off the control that was clicked. It is NOT "the rows are on screen":
@@ -274,9 +277,88 @@ export interface DrillModalProps {
274
  onDisplayChange?: (addr: string, display: BindingDisplay) => void | Promise<void>;
275
  }
276
 
277
- export default function DrillModal(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  {
279
- workbookId, addr, label, onClose, onSettled, cellScope, onFilterChange, onDisplayChange,
280
  }: DrillModalProps,
281
  ) {
282
  const [drill, setDrill] = useState<CellDrill | null>(null);
@@ -751,6 +833,8 @@ export default function DrillModal(
751
  onCellFilterChange={shownKind === "filter" ? settleCellFilter : undefined}
752
  headerActions={(
753
  <div className="sheet-cell-view-toolbar" role="toolbar" aria-label="Cell View controls">
 
 
754
  {canEditRows && (
755
  <button type="button" className="sheet-cell-view-action" onClick={editInData}>
756
  <svg viewBox="0 0 16 16" aria-hidden="true">
 
58
  import type { SurfaceScope } from "../customer-grid/apiBridge";
59
  import type { CellDisplayChoice } from "../customer-grid/CustomerGrid";
60
  import { dataPathHash } from "../customer-grid/dataPath";
61
+ import { AnchoredOverlay, BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface";
62
  import type { Field, FilterTree, GridWorkspace, Row } from "../customer-grid/types";
63
  import { mayEditField, topicForScope } from "../customer-grid/types";
64
  import { conditionCountLabel, filterSentence } from "../filter-kit/SheetFilterPopup";
 
66
  import { cellForcedFieldKeys, cellViewVisibleKeys } from "./bindingRefs";
67
  import { drillCell } from "./sheetApi";
68
  import type { CellDrill } from "./sheetApi";
69
+ import type { BindingDisplay, ViewBinding, ViewRowsAnswer } from "./types";
70
  import { bindingDisplay } from "./types";
71
+ import { fetchViewRows, showingLine } from "./viewPlacement";
72
 
73
  /**
74
  * ⛔⛔ LAZY, AND THE BUILD IS WHAT SAID SO. A plain `import { LinkGridModal } from
 
243
  /** The label the popup wears. The cell's own address is the honest one: it is what was clicked. */
244
  label: string;
245
  onClose: () => void;
246
+ previewBinding?: ViewBinding;
247
+ onPlace?: () => void;
248
  /**
249
  * W54-T34: the drill has stopped waiting - it answered, or it was refused. The page uses this to
250
  * take the busy state back off the control that was clicked. It is NOT "the rows are on screen":
 
277
  onDisplayChange?: (addr: string, display: BindingDisplay) => void | Promise<void>;
278
  }
279
 
280
+ export default function DrillModalEntry(props: DrillModalProps) {
281
+ return props.previewBinding
282
+ ? <OverlayProvider><ViewRowsPreview {...props} previewBinding={props.previewBinding} /></OverlayProvider>
283
+ : <DrillModal {...props} />;
284
+ }
285
+
286
+ // R35 deliberately previews the resolver's own projection, not LinkGridModal's record list.
287
+ // LinkGridModal needs recordIds from a stored-cell drill, but this binding is not stored yet.
288
+ // Adding ids would change routes_sheet.py outside this ticket's fence, and a record list would
289
+ // show every field instead of the chosen fields at the chosen limit in the chosen order.
290
+ function ViewRowsPreview({ workbookId, label, previewBinding, onClose, onPlace, onSettled }:
291
+ DrillModalProps & { previewBinding: ViewBinding }) {
292
+ const requestKey = JSON.stringify([workbookId, previewBinding]);
293
+ const [viewRows, setViewRows] = useState<{
294
+ key: string; answer?: ViewRowsAnswer; error?: string;
295
+ } | null>(null);
296
+ const settledRef = useRef(onSettled);
297
+ settledRef.current = onSettled;
298
+ const panelRef = useRef<HTMLDivElement>(null);
299
+ useOverlayLayer({ panelRef, onDismiss: onClose, dismissOnOutside: false,
300
+ initialFocus: "first", restoreFocus: true, trapFocus: true });
301
+
302
+ useEffect(() => {
303
+ let live = true;
304
+ const [id, binding] = JSON.parse(requestKey) as [string, ViewBinding];
305
+ void fetchViewRows(id, binding).then((got) => {
306
+ if (!live) return;
307
+ setViewRows(got.ok ? { key: requestKey, answer: got.answer }
308
+ : { key: requestKey, error: got.message });
309
+ settledRef.current?.();
310
+ });
311
+ return () => { live = false; };
312
+ }, [requestKey]);
313
+
314
+ const current = viewRows?.key === requestKey ? viewRows : null;
315
+ const answer = current?.answer;
316
+ const headerActions = onPlace ? (
317
+ <div className="sheet-cell-view-toolbar" role="toolbar" aria-label="View controls">
318
+ <button type="button" className="lp-btn lp-btn-primary" disabled={!answer}
319
+ onClick={onPlace}>Place in sheet</button>
320
+ </div>
321
+ ) : null;
322
+ const cellText = (value: unknown) => value == null ? ""
323
+ : typeof value === "object" ? JSON.stringify(value) : String(value);
324
+
325
+ return <BodyPortal>
326
+ <div className="sheet-drill-skeleton-backdrop">
327
+ <div className="sheet-drill-skeleton" role="dialog" aria-modal="true"
328
+ aria-label={label} ref={panelRef}>
329
+ <header className="sheet-drill-skeleton-head" style={{ flexDirection: "row", alignItems: "center" }}>
330
+ <h2 className="sheet-binding-title" style={{ flex: 1 }}>{label}</h2>
331
+ {headerActions}
332
+ <button type="button" className="lp-btn lp-btn-quiet" onClick={onClose}>Close</button>
333
+ </header>
334
+ <div style={{ overflow: "auto", padding: 16, minHeight: 0 }} aria-busy={!current}>
335
+ {!current && <p role="status">Loading view…</p>}
336
+ {current?.error && <p className="sheet-notice" role="alert">{current.error}</p>}
337
+ {answer && <>
338
+ <p className="sheet-period-note" role="status">{showingLine(answer.rows.length, answer.total)}</p>
339
+ <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "var(--lp-fs-xs)" }}>
340
+ <thead><tr>{answer.fields.map((field) => <th key={field.key} scope="col"
341
+ style={{ textAlign: "left", padding: 8, borderBottom: "1px solid var(--lp-line)" }}>
342
+ {field.label}
343
+ </th>)}</tr></thead>
344
+ <tbody>{answer.rows.map((row, index) => <tr key={index}>
345
+ {answer.fields.map((field) => <td key={field.key} style={{ padding: 8,
346
+ borderBottom: "1px solid var(--lp-line)", fontVariantNumeric: "tabular-nums",
347
+ textAlign: typeof row[field.key] === "number" ? "right" : "left" }}>
348
+ {cellText(row[field.key])}
349
+ </td>)}
350
+ </tr>)}</tbody>
351
+ </table>
352
+ </>}
353
+ </div>
354
+ </div>
355
+ </div>
356
+ </BodyPortal>;
357
+ }
358
+
359
+ function DrillModal(
360
  {
361
+ workbookId, addr, label, onClose, onSettled, cellScope, onFilterChange, onDisplayChange, onPlace,
362
  }: DrillModalProps,
363
  ) {
364
  const [drill, setDrill] = useState<CellDrill | null>(null);
 
833
  onCellFilterChange={shownKind === "filter" ? settleCellFilter : undefined}
834
  headerActions={(
835
  <div className="sheet-cell-view-toolbar" role="toolbar" aria-label="Cell View controls">
836
+ {onPlace && <button type="button" className="lp-btn lp-btn-primary"
837
+ onClick={onPlace}>Place in sheet</button>}
838
  {canEditRows && (
839
  <button type="button" className="sheet-cell-view-action" onClick={editInData}>
840
  <svg viewBox="0 0 16 16" aria-hidden="true">
web/src/sheet/Ribbon.tsx CHANGED
@@ -42,7 +42,7 @@
42
  //
43
  // ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5). Buttons reset native chrome; icons are inline SVG on
44
  // `currentColor` and NEVER emoji; a colour swatch is a token-styled span, never a coloured glyph;
45
- // colour and type are token only, so no literal `font-size` and no literal hue; sentence case
46
  // labels with no ALL CAPS chrome; motion is 150 ms ease-out on opacity and transform only; z-order
47
  // rides a `--cg-z-*` token. No em dash or en dash in any string that reaches a screen.
48
 
@@ -236,14 +236,14 @@ const TABS = [HOME_TAB, INSERT_TAB, FORMULAS_TAB, DATA_TAB, VIEW_TAB] as const;
236
  * W56-T17 adds Export to that same always-visible strip for the same reason.
237
  *
238
  * ⚠ THE KEY IS HERE AND THE BUTTON IS IN THE JSX, because the five differ in shape: Import and
239
- * Export each have their own data door, three carry an icon beside a word, Full screen reports a
240
  * pressed state, and the chevron is not a plain control button at all. `ControlKey` is derived
241
  * from these keys, so the JSX still cannot render an action under a name this list does not carry.
242
  *
243
  * ⭐⭐ W54-T08 (owner instruction 7) — FULL SCREEN IS NO LONGER THE ODD ONE OUT. It used to paint
244
  * its mark with the label living only in `aria-label` and `title`, and this note used to read as
245
  * though that shape were settled. The owner has overruled it: the Sheet's control says
246
- * "Full screen" on screen, the way the Data module's always has.
247
  */
248
  const ACTIONS = [
249
  { key: "import" }, { key: "refresh" }, { key: "export" }, { key: "fullscreen" },
@@ -295,8 +295,6 @@ export interface RibbonTabContext {
295
  newWindowBlocked: boolean;
296
  openNewWindow: () => void;
297
  openCellData: () => void;
298
- formulaBarVisible: boolean;
299
- toggleFormulaBar: () => void;
300
  openPop: (which: Popover) => (event: ReactMouseEvent<HTMLButtonElement>) => void;
301
  closePop: () => void;
302
  control: (
@@ -332,7 +330,6 @@ export interface RibbonTabContext {
332
  * the state that shows every control rather than the state that hides them.
333
  */
334
  const COLLAPSE_KEY = "aios.sheet.ribbon.collapsed";
335
- const FORMULA_BAR_KEY = "aios.sheet.ribbon.formula-bar";
336
 
337
  const readCollapsed = (): boolean => {
338
  try {
@@ -350,22 +347,6 @@ const writeCollapsed = (next: boolean) => {
350
  }
351
  };
352
 
353
- const readFormulaBar = (): boolean => {
354
- try {
355
- return window.localStorage.getItem(FORMULA_BAR_KEY) !== "0";
356
- } catch {
357
- return true;
358
- }
359
- };
360
-
361
- const writeFormulaBar = (visible: boolean) => {
362
- try {
363
- window.localStorage.setItem(FORMULA_BAR_KEY, visible ? "1" : "0");
364
- } catch {
365
- // A refused storage write affects persistence only; the current view still changes.
366
- }
367
- };
368
-
369
  function IconRefresh() {
370
  return (
371
  <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
@@ -448,7 +429,6 @@ export default function Ribbon({
448
  const [exportScope, setExportScope] = useState<"sheet" | "selection">("sheet");
449
  const exportUnavailable = !exportContext;
450
  const [collapsed, setCollapsed] = useState<boolean>(readCollapsed);
451
- const [formulaBarVisible, setFormulaBarVisible] = useState<boolean>(readFormulaBar);
452
  const rootRef = useRef<HTMLDivElement | null>(null);
453
  const scrollRef = useRef<HTMLDivElement | null>(null);
454
  const overflowRef = useRef<HTMLDivElement | null>(null);
@@ -456,20 +436,6 @@ export default function Ribbon({
456
  const [overflowOpen, setOverflowOpen] = useState(false);
457
  const [groupFit, setGroupFit] = useState<{ tab: TabId; count: number } | null>(null);
458
 
459
- useEffect(() => {
460
- const wrap = rootRef.current?.closest<HTMLElement>(".sheet-grid-wrap");
461
- wrap?.classList.toggle("is-formula-bar-hidden", !formulaBarVisible);
462
- return () => wrap?.classList.remove("is-formula-bar-hidden");
463
- }, [formulaBarVisible]);
464
-
465
- const toggleFormulaBar = useCallback(() => {
466
- setFormulaBarVisible((was) => {
467
- const next = !was;
468
- writeFormulaBar(next);
469
- return next;
470
- });
471
- }, []);
472
-
473
  /** Which registered tab is showing. */
474
  const [active, setActive] = useState<TabId>(TABS[0].id);
475
  const activeTab = TABS.find((tab) => tab.id === active) ?? TABS[0];
@@ -478,7 +444,7 @@ export default function Ribbon({
478
 
479
  /**
480
  * The keys the arrows may reach right now. Collapsed, that is the strip and nothing else — and
481
- * the strip now carries Import, Refresh, Export and Full screen too.
482
  * Expanded, it is the strip plus the controls of the tab that is actually showing, read off its
483
  * own descriptor rather than a list kept beside it. Import is only in the order on a page that
484
  * actually has an import door, in both branches.
@@ -793,7 +759,7 @@ export default function Ribbon({
793
  );
794
 
795
  /** Same idiom as the Data module's own `fullscreenLabel` (`customer-grid/Toolbar.tsx`). */
796
- const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen";
797
  const exportLabel = exportUnavailable ? "Export unavailable" : "Export";
798
  const selectionRange: SheetExportRange | null = insert?.selection ? {
799
  col0: Math.min(insert.selection.col0, insert.selection.col1),
@@ -823,7 +789,7 @@ export default function Ribbon({
823
 
824
  const tabContext: RibbonTabContext = {
825
  style, frozen, open, anchorEl, onApply, apply, act,
826
- fullscreen, toggleFullscreen, formulaBarVisible, toggleFormulaBar,
827
  newWindowBlocked, openNewWindow, openCellData,
828
  openPop, closePop, control, group, word, large, stack, unavailable, item, insert,
829
  };
@@ -1008,7 +974,7 @@ export default function Ribbon({
1008
  className={"sheet-ribbon-overflow-trigger" + (hasOverflow ? "" : " is-measuring")}
1009
  aria-hidden={!hasOverflow || undefined}
1010
  >
1011
- {control("overflow", "More groups", <><IconChevron direction="down" />{word("More groups")}</>,
1012
  toggleOverflow, false, overflowOpen, hasOverflow ? "Y" : undefined, "gallery", undefined, "dialog")}
1013
  </span>
1014
  </div>
@@ -1020,7 +986,7 @@ export default function Ribbon({
1020
  className={"sheet-ribbon sheet-ribbon-overflow " + activeTab.bodyClass + (open ? "" : " sheet-ribbon-pop")}
1021
  onDismiss={closeOverflow}
1022
  role="dialog"
1023
- ariaLabel="More ribbon groups"
1024
  initialFocus="none"
1025
  restoreFocus={false}
1026
  placement="bottom-end"
 
42
  //
43
  // ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5). Buttons reset native chrome; icons are inline SVG on
44
  // `currentColor` and NEVER emoji; a colour swatch is a token-styled span, never a coloured glyph;
45
+ // colour and type are token only, so no literal `font-size` and no literal hue; Excel's Title Case (R41)
46
  // labels with no ALL CAPS chrome; motion is 150 ms ease-out on opacity and transform only; z-order
47
  // rides a `--cg-z-*` token. No em dash or en dash in any string that reaches a screen.
48
 
 
236
  * W56-T17 adds Export to that same always-visible strip for the same reason.
237
  *
238
  * ⚠ THE KEY IS HERE AND THE BUTTON IS IN THE JSX, because the five differ in shape: Import and
239
+ * Export each have their own data door, three carry an icon beside a word, Full Screen reports a
240
  * pressed state, and the chevron is not a plain control button at all. `ControlKey` is derived
241
  * from these keys, so the JSX still cannot render an action under a name this list does not carry.
242
  *
243
  * ⭐⭐ W54-T08 (owner instruction 7) — FULL SCREEN IS NO LONGER THE ODD ONE OUT. It used to paint
244
  * its mark with the label living only in `aria-label` and `title`, and this note used to read as
245
  * though that shape were settled. The owner has overruled it: the Sheet's control says
246
+ * "Full Screen" on screen, the way the Data module's always has.
247
  */
248
  const ACTIONS = [
249
  { key: "import" }, { key: "refresh" }, { key: "export" }, { key: "fullscreen" },
 
295
  newWindowBlocked: boolean;
296
  openNewWindow: () => void;
297
  openCellData: () => void;
 
 
298
  openPop: (which: Popover) => (event: ReactMouseEvent<HTMLButtonElement>) => void;
299
  closePop: () => void;
300
  control: (
 
330
  * the state that shows every control rather than the state that hides them.
331
  */
332
  const COLLAPSE_KEY = "aios.sheet.ribbon.collapsed";
 
333
 
334
  const readCollapsed = (): boolean => {
335
  try {
 
347
  }
348
  };
349
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
350
  function IconRefresh() {
351
  return (
352
  <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
 
429
  const [exportScope, setExportScope] = useState<"sheet" | "selection">("sheet");
430
  const exportUnavailable = !exportContext;
431
  const [collapsed, setCollapsed] = useState<boolean>(readCollapsed);
 
432
  const rootRef = useRef<HTMLDivElement | null>(null);
433
  const scrollRef = useRef<HTMLDivElement | null>(null);
434
  const overflowRef = useRef<HTMLDivElement | null>(null);
 
436
  const [overflowOpen, setOverflowOpen] = useState(false);
437
  const [groupFit, setGroupFit] = useState<{ tab: TabId; count: number } | null>(null);
438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
439
  /** Which registered tab is showing. */
440
  const [active, setActive] = useState<TabId>(TABS[0].id);
441
  const activeTab = TABS.find((tab) => tab.id === active) ?? TABS[0];
 
444
 
445
  /**
446
  * The keys the arrows may reach right now. Collapsed, that is the strip and nothing else — and
447
+ * the strip now carries Import, Refresh, Export and Full Screen too.
448
  * Expanded, it is the strip plus the controls of the tab that is actually showing, read off its
449
  * own descriptor rather than a list kept beside it. Import is only in the order on a page that
450
  * actually has an import door, in both branches.
 
759
  );
760
 
761
  /** Same idiom as the Data module's own `fullscreenLabel` (`customer-grid/Toolbar.tsx`). */
762
+ const fullscreenLabel = fullscreen ? "Exit Full Screen" : "Full Screen";
763
  const exportLabel = exportUnavailable ? "Export unavailable" : "Export";
764
  const selectionRange: SheetExportRange | null = insert?.selection ? {
765
  col0: Math.min(insert.selection.col0, insert.selection.col1),
 
789
 
790
  const tabContext: RibbonTabContext = {
791
  style, frozen, open, anchorEl, onApply, apply, act,
792
+ fullscreen, toggleFullscreen,
793
  newWindowBlocked, openNewWindow, openCellData,
794
  openPop, closePop, control, group, word, large, stack, unavailable, item, insert,
795
  };
 
974
  className={"sheet-ribbon-overflow-trigger" + (hasOverflow ? "" : " is-measuring")}
975
  aria-hidden={!hasOverflow || undefined}
976
  >
977
+ {control("overflow", "More Groups", <><IconChevron direction="down" />{word("More Groups")}</>,
978
  toggleOverflow, false, overflowOpen, hasOverflow ? "Y" : undefined, "gallery", undefined, "dialog")}
979
  </span>
980
  </div>
 
986
  className={"sheet-ribbon sheet-ribbon-overflow " + activeTab.bodyClass + (open ? "" : " sheet-ribbon-pop")}
987
  onDismiss={closeOverflow}
988
  role="dialog"
989
+ ariaLabel="More Ribbon Groups"
990
  initialFocus="none"
991
  restoreFocus={false}
992
  placement="bottom-end"
web/src/sheet/SheetGrid.tsx CHANGED
@@ -92,7 +92,7 @@
92
  // the canvas count in the same tick as a style change therefore reads 0 whatever the fix.
93
  // ═════════════════════════════════════════════════════════════════════════════════════════════
94
 
95
- import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
96
  import type { ChangeEvent as ReactChangeEvent, KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";
97
  import { createPortal } from "react-dom";
98
  import type {
@@ -107,6 +107,11 @@ import "@glideapps/glide-data-grid/dist/index.css";
107
  import { lightTheme } from "../customer-grid/theme";
108
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
109
  import type { AnchorRect } from "../customer-grid/OverlaySurface";
 
 
 
 
 
110
  // ⭐ INSTRUCTION 15 — clicking a sheet cell folds the nav rail exactly as a Data-module cell
111
  // click already does (`customer-grid/CustomerGrid.tsx::selectView`). One shared signal, one
112
  // shared listener (`shell/Shell.tsx::onNavMinimize`); this file never dispatched it before.
@@ -125,7 +130,7 @@ import type { SuggestItem } from "./formulaAssist";
125
  // arithmetic, so they live in `formulaEval.ts` where `verify_formula_engine.py` compiles them and
126
  // EXECUTES the claim under node. This file owns only the keystroke and the commit that call them.
127
  import {
128
- ERROR_REF, autoCloseFormula, cycleAnchorAtCaret, workbookFormulaGetter,
129
  } from "./formulaEval";
130
  import { colorForSlot } from "./refColors";
131
  import "../styles/wave52/sheet-grid.css";
@@ -142,10 +147,15 @@ import type { RibbonAction, RibbonInsertDoor } from "./Ribbon";
142
  import { RulesDialog, ValidationDialog } from "./RulesDialog";
143
  import ChartDialog from "./ChartDialog";
144
  import SheetChartLayer from "./SheetChartLayer";
 
145
  import { copyChartImage } from "./sheetExport";
146
  import { sheetPageGrid } from "./pageViews";
147
  import ShortcutsPanel from "./ShortcutsPanel";
148
- import { colToIndex, columnRangeA1, indexToCol, rowRangeA1 } from "./a1";
 
 
 
 
149
  // ⛔⛔ W51-T18 — THE RULE ENGINE AND THE VALIDATION CHECKER ARE PURE AND SHEET LOCAL, and that is
150
  // what lets `verify_api.py` compile them beside `sheetState.js` and EXECUTE the ten operators
151
  // rather than grep for their names. This component is the only place their answers meet a canvas.
@@ -179,17 +189,17 @@ import {
179
  } from "./types";
180
  import type {
181
  Cell, CellStyle, CellStylePatch, CellValign, SheetChartSpec, SheetRule, SheetTab, SheetTabView,
182
- SheetViewDoor, Workbook,
183
  } from "./types";
184
  import {
185
- addressOf, appendLineBreak, autoSumFormula, boundDragLabel, cellAt,
186
  cellShiftLabel, cellToValue, clearAll, recalcDependents, recalculateWorkbook, WorkbookCalculationSession,
187
  clearCells, clearFormats, commitTyped, cycleAnchors, dateStamp, displayText, drillAffordance,
188
  editableText, fillCells, fillDown, fillRight, findMatches,
189
  isFilled, markOf, noMatchLabel, nothingHiddenLabel, paintPatch, pasteCells,
190
- chartPaneProjections, frozenBandSize, lockstepScrollX,
191
  rememberCut, setFormula, shiftCells, splitAddress, styleCells, styleOf, usedExtent,
192
- viewIndexOf,
193
  visibleIndices, withHidden,
194
  } from "./sheetState";
195
  import type {
@@ -312,6 +322,194 @@ const SIZE_PX: Record<string, number> = { s: 11, m: 13, l: 16, xl: 20 };
312
  // numbers exactly. So a document written before the size box existed paints identically, and the
313
  // only cells that take the other branch are the ones somebody set a point size on.
314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  /** R8's size menu emits a step NAME; C2 stores a letter. One table, so the two cannot drift. */
316
  const SIZE_OF_STEP: Record<string, "s" | "m" | "l" | "xl"> = {
317
  small: "s", normal: "m", large: "l", heading: "xl",
@@ -591,6 +789,82 @@ interface SheetMenu {
591
  on: "cell" | "column" | "row";
592
  }
593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594
  /** What the find box is looking for and which match it is standing on. */
595
  interface FindState {
596
  query: string;
@@ -677,6 +951,91 @@ export default function SheetGrid({
677
  [storedWorkbook, storedTab.id],
678
  );
679
  const tab = workbook.sheets.find((sheet) => sheet.id === storedTab.id) ?? storedTab;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
680
  const pageView = tab.view?.pageView ?? "normal";
681
  const pageGrid = useMemo(() => pageView === "normal"
682
  ? null : sheetPageGrid(workbook, tab.id, workbook.printSettings), [pageView, workbook, tab.id]);
@@ -780,11 +1139,14 @@ export default function SheetGrid({
780
  * band by the band's own height. `openFormulaEditor` reads whichever ref actually owns the row.
781
  */
782
  const bandGridRef = useRef<DataEditorRef | null>(null);
 
783
  // ⛔ THE FIND BOX'S CLOSE, THROUGH THE ONE ARBITER. Declared here, beside the state it closes,
784
  // and unconditionally, so the hook order never changes between renders.
785
  useEscapeClose(find !== null, () => setFind(null));
786
  const [anchor, setAnchor] = useState<Rectangle | null>(null);
787
  const [menu, setMenu] = useState<SheetMenu | null>(null);
 
 
788
  /**
789
  * ⭐ THE FORMAT PAINTER'S WHOLE STATE: the style it picked up, waiting for the click that lands
790
  * it. `null` means the painter is off, so one value carries both the mode and its payload and
@@ -831,7 +1193,27 @@ export default function SheetGrid({
831
  * there would queue dozens of saves per drag and the reader would watch the reload notice fire.
832
  * The dragging width lives here; `onColumnResizeEnd` commits once.
833
  */
834
- const [dragWidth, setDragWidth] = useState<{ col: number; width: number } | null>(null);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
835
 
836
  // ── W51-T18: the two surfaces this ticket adds, and the one local fallback it needs ─────────
837
  /** R8's Styles group is conditional formatting's ONLY door, and this is what it opens. */
@@ -1104,11 +1486,13 @@ export default function SheetGrid({
1104
  return {
1105
  title: letters,
1106
  id: String(real),
1107
- width: dragWidth?.col === i ? dragWidth.width : Math.round((widths[letters] ?? COL_WIDTH) * zoom),
 
1108
  };
1109
  }),
1110
- [dragWidth, visCols, widths, zoom],
1111
  );
 
1112
 
1113
  /** The x offset of one column, summed rather than multiplied: widths differ now. */
1114
  const columnX = useCallback(
@@ -1117,6 +1501,23 @@ export default function SheetGrid({
1117
  );
1118
 
1119
  const cells = tab.cells ?? {};
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1120
 
1121
  // The page owns refusal/confirmation and atomically reanchors cells, sources and placement.
1122
  const requestStructure = onStructure;
@@ -1197,7 +1598,7 @@ export default function SheetGrid({
1197
  return {
1198
  kind: GridCellKind.Text,
1199
  data: editableText(cell),
1200
- displayData: formatCellText(cell, displayText(cell)),
1201
  // ⛔ A bound cell does not open glide's OWN text overlay. `onKeyDown`'s typed-character
1202
  // branch is that cell's editor instead (R5, W52-T09): it opens the SAME floating editor a
1203
  // fresh formula does, converting the cell the moment Enter commits, with no confirmation
@@ -1215,8 +1616,9 @@ export default function SheetGrid({
1215
  // cell's editor: `onCellActivated` opens it for an EXISTING formula, and `onKeyDown`'s
1216
  // typed-character branch opens it the moment a fresh "=" starts one. glide's own overlay
1217
  // would otherwise sit on top of the dropdown/ScreenTip a person may be typing INTO.
1218
- allowOverlay: cell?.kind !== "bound" && cell?.kind !== "formula" && !validationOf(cell),
1219
- readonly: cell?.kind === "bound" || validationOf(cell) !== null,
 
1220
  };
1221
  },
1222
  // `cells` is the whole dependency: a new workbook object gives a new `cells`, which is what
@@ -1465,7 +1867,10 @@ export default function SheetGrid({
1465
  message: `${ERROR_REF} This formula names a sheet that is not in this workbook.`,
1466
  };
1467
  }
1468
- return cellToValue(cellAt(target, addr));
 
 
 
1469
  });
1470
  }, [tab, workbook.sheets]);
1471
 
@@ -1479,9 +1884,87 @@ export default function SheetGrid({
1479
  * `SheetPage.tsx::commitCells`, which pushes history and queues a save; an effect watching the
1480
  * document would mutate a workbook nobody edited and write it back merely for opening a sheet.
1481
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1482
  const commitWithRecalc = useCallback((edits: Record<string, Cell | null>) => {
 
 
 
 
 
 
 
 
 
 
 
 
 
1483
  onCommit({ ...edits, ...recalcDependents(tab, edits, workbook.sheets, workbook, calculationSession.current) });
1484
- }, [onCommit, tab, workbook]);
1485
 
1486
  /** ONE typed commit. `commitTyped` picks literal or formula and drops a binding on its own. */
1487
  const onCellEdited = useCallback((item: Item, value: EditableGridCell) => {
@@ -2600,6 +3083,86 @@ export default function SheetGrid({
2600
  if (scroll && at[1] >= 0) gridRef.current?.scrollTo(at[0], at[1]);
2601
  }, [onSelectionChange]);
2602
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2603
  /**
2604
  * ⭐⭐ W56-T04: ONE OPEN, ONE OPENING CELL, THROUGH THE SAME SELECTION DOOR.
2605
  * The background binding refresh replaces the workbook object after paint, so object identity
@@ -2710,6 +3273,9 @@ export default function SheetGrid({
2710
  /** The note under the pointer, or null. `addr` is what keeps a hover from re-rendering per pixel. */
2711
  const [noteHover, setNoteHover] =
2712
  useState<{ addr: string; note: string; anchor: AnchorRect } | null>(null);
 
 
 
2713
 
2714
  /** Show a tab by id, through the SAME wrap-around door Ctrl+PgUp uses. */
2715
  const goToSheet = useCallback((sheetId: string) => {
@@ -2785,17 +3351,25 @@ export default function SheetGrid({
2785
  const onNoteHover = useCallback((args: GridMouseEventArgs, band: boolean) => {
2786
  if (args.kind !== "cell") {
2787
  setNoteHover((current) => (current ? null : current));
 
 
2788
  return;
2789
  }
2790
  const location = band ? fromBand(args.location) : args.location;
2791
  const addr = addrAt(location[0], location[1]);
2792
- const note = cells[addr]?.note ?? "";
 
 
 
 
 
 
2793
  setNoteHover((current) => {
2794
  if (!note) return current ? null : current;
2795
  if (current && current.addr === addr) return current;
2796
  return { addr, note, anchor: rectAnchor(args.bounds) };
2797
  });
2798
- }, [addrAt, cells, fromBand]);
2799
 
2800
  /**
2801
  * ⭐⭐ Ctrl+1 — CONTRACT C1's "THE SAME IMPLEMENTATION, NOT TWO COPIES OF IT", TAKEN LITERALLY.
@@ -3178,6 +3752,25 @@ export default function SheetGrid({
3178
  else commitWithRecalc(out.edits);
3179
  }, [commitWithRecalc, onCommit, onNotice, selectedAddrs, tab]);
3180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3181
  /** Hide the rows or the columns the selection covers, and remember them on the tab. */
3182
  const hideBand = useCallback((axis: "row" | "col") => {
3183
  const range = viewRange();
@@ -3195,19 +3788,8 @@ export default function SheetGrid({
3195
  for (let c = Math.min(range.col0, range.col1); c <= Math.max(range.col0, range.col1);
3196
  c += 1) indices.push(realCol(c) + 1);
3197
  }
3198
- // ⛔ A SHEET KEEPS AT LEAST ONE VISIBLE ROW AND ONE VISIBLE COLUMN. Hiding every one of them
3199
- // leaves a grid nothing can be selected in, and therefore no way to press Unhide.
3200
- const rows = axis === "row" ? withHidden(hiddenRows, indices, true) : hiddenRows;
3201
- const cols = axis === "col" ? withHidden(hiddenCols, indices, true) : hiddenCols;
3202
- if (rows.length >= extent.rows || cols.length >= extent.cols) {
3203
- onNotice("A sheet keeps at least one row and one column on screen, so these cannot all "
3204
- + "be hidden.");
3205
- return;
3206
- }
3207
- if (!onHideBands) setHiddenLocal({ tabId: tab.id, rows, cols });
3208
- onHideBands?.({ hiddenRows: rows, hiddenCols: cols });
3209
- }, [extent.cols, extent.rows, hiddenCols, hiddenRows, onHideBands, onNotice, realCol, realRow,
3210
- tab.id, viewRange]);
3211
 
3212
  /** Bring every hidden row and column back, and say so when there were none. */
3213
  const unhideAll = useCallback(() => {
@@ -3232,11 +3814,12 @@ export default function SheetGrid({
3232
  return;
3233
  }
3234
  const width = Math.max(MIN_COL_WIDTH, Math.min(MAX_COL_WIDTH, Math.round(value)));
3235
- for (let c = Math.min(range.col0, range.col1); c <= Math.max(range.col0, range.col1);
3236
- c += 1) onColumnWidth(realCol(c), width);
 
3237
  }
3238
  setAsk(null);
3239
- }, [ask, onColumnWidth, onNotice, realCol, setRowHeight, viewRange]);
3240
 
3241
  // ═══════════════════════════════════════════════════════════════════════════════════════════
3242
  // ⭐⭐ W54-T07 — AUTOFIT, AND THE TWO AXES ARE NOT SYMMETRICAL. SAY IT OUT LOUD.
@@ -3825,6 +4408,10 @@ export default function SheetGrid({
3825
  if (!primary && !event.altKey && event.key.length === 1) {
3826
  const addr = addrAt(current.cell[0], current.cell[1]);
3827
  const cell = cellAt(tab, addr);
 
 
 
 
3828
  const inBand = current.cell[1] < 0;
3829
  const viewCell: readonly [number, number] = inBand
3830
  ? [current.cell[0], current.cell[1] + bandRows] : current.cell;
@@ -4105,19 +4692,43 @@ export default function SheetGrid({
4105
  // grids makes the two follow a drag together for free. A band grid given its own column list
4106
  // would tear away from the body while the mouse was still down.
4107
  // ══════════════════════════════════════════════════════════════════════════════════════════
 
 
 
 
 
 
 
 
 
 
 
 
4108
  const onColumnResize = useCallback(
4109
- (_col: GridColumn, newSize: number, colIndex: number) =>
4110
- setDragWidth({ col: colIndex, width: newSize }),
 
 
4111
  [],
4112
  );
4113
  const onColumnResizeEnd = useCallback(
4114
  (_col: GridColumn, newSize: number, colIndex: number) => {
4115
  setDragWidth(null);
 
 
 
 
 
 
 
 
 
4116
  // ⛔ TRANSLATED. `setColumnWidth` keys the width by COLUMN LETTER, so handing it a view
4117
  // index would remember D's width against C the moment a column is hidden.
4118
- onColumnWidth(realCol(colIndex), Math.round(newSize / zoom));
 
4119
  },
4120
- [onColumnWidth, realCol, zoom],
4121
  );
4122
  const onHeaderClicked = useCallback((colIndex: number, args: { shiftKey: boolean }) => {
4123
  const from = args.shiftKey ? (selection?.current?.cell[0] ?? colIndex) : colIndex;
@@ -4152,6 +4763,9 @@ export default function SheetGrid({
4152
  // makes it a controlled horizontal position. Verified in `data-editor.js`.
4153
  // ══════════════════════════════════════════════════════════════════════════════════════════
4154
  const [bandScrollX, setBandScrollX] = useState(0);
 
 
 
4155
  /** Glide's own scroll coordinates. Chart anchors consume the same x/y and sub-cell transforms. */
4156
  const [chartViewport, setChartViewport] = useState({ x: 0, y: 0, tx: 0, ty: 0 });
4157
  const pageOverlayRef = useRef<HTMLDivElement>(null);
@@ -4181,6 +4795,65 @@ export default function SheetGrid({
4181
  setBandScrollX(lockstepScrollX(columns.map((c) => c.width), frozenCols, range.x, tx));
4182
  }, [bandRows, columns, frozenCols]);
4183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4184
  // W61-T10 / R12: measure the real glyphs, first at their natural width, then at the
4185
  // visible grid edge. The frozen band's handle remains the authority for its cell bounds.
4186
  const formulaBounds = formulaEdit
@@ -4482,20 +5155,74 @@ export default function SheetGrid({
4482
  ctx.globalAlpha = 1;
4483
  ctx.restore();
4484
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4485
  if (!cell && !ruleStyle) { drawContent(); paintRefBorder(); paintMarquee(); return; }
4486
 
4487
  const mark = cell ? MARK_STYLE[markOf(cell)] : undefined;
4488
- const caret = validationOf(cell) !== null;
 
4489
  const paintMark = () => {
4490
  // ⭐ W51-T18: THE DROPDOWN'S CARET RIDES HERE, so it is drawn in BOTH branches for
4491
  // the same reason R19's corner mark is: a validated cell that also carries a bold
4492
  // would silently lose its only affordance and read as an ordinary cell.
4493
  if (caret) {
4494
  ctx.save();
 
 
 
 
 
4495
  ctx.strokeStyle = tokenColour("--lp-muted", "#6b7280");
4496
  ctx.lineWidth = 1.4;
4497
  ctx.lineCap = "round";
4498
- const cx = rect.x + rect.width - 11;
4499
  const cy = rect.y + rect.height / 2 - 1;
4500
  ctx.beginPath();
4501
  ctx.moveTo(cx - 3.5, cy);
@@ -4529,12 +5256,14 @@ export default function SheetGrid({
4529
  // condition as it was would compute a rule's fill and then hand the cell straight
4530
  // back to glide, which knows nothing about it: the dialog would list a rule that
4531
  // paints nothing. The `|| ruleStyle` is that whole bug, in two words.
4532
- const style = ruleStyle ? overlayRuleStyle<CellStyle>(cell?.style, ruleStyle)
4533
  : cell?.style;
 
 
4534
  if ((!stylePaints(style) && !ruleStyle) || !style) {
4535
  // ⭐ `drawContent()` IS the default renderer, and it must run BEFORE the mark so
4536
  // the mark sits on top of the value rather than under it.
4537
- drawContent();
4538
  // ⭐ W54-T14 / LANE B — the link underline and the note corner, in BOTH branches for the
4539
  // same reason R19's own mark is in both: an attachment on a bold cell would otherwise
4540
  // vanish, and a cell that shows nothing of what it carries carries it invisibly.
@@ -4546,7 +5275,6 @@ export default function SheetGrid({
4546
  return;
4547
  }
4548
 
4549
- const text = formatCellText(cell, displayText(cell));
4550
  ctx.save();
4551
 
4552
  // 1. THE BACKGROUND, FIRST AND INSET BY A PIXEL so the grid's own hairlines survive.
@@ -4568,108 +5296,12 @@ export default function SheetGrid({
4568
  ctx.restore();
4569
  }
4570
 
4571
- // 2. THE TEXT, clipped to its own cell. A long bold value must stop at the column
4572
- // edge exactly as glide's does, or it paints over its neighbour's value.
4573
  ctx.beginPath();
4574
  ctx.rect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2);
4575
  ctx.clip();
4576
 
4577
- // ⭐ W51-T16: THE SIZE STEP AND THE INDENT ARE PART OF THE FONT AND THE BOX, so they
4578
- // are settled BEFORE anything is measured. A canvas measures text in the font that is
4579
- // set at the time, so choosing the size after `measureText` would centre a heading
4580
- // using the body size's width.
4581
- // ⭐⭐ W54-T03 / R11 — TWO SHAPES, ONE SLOT, AND THE PIXELS DO NOT MOVE. A `size` that is one
4582
- // of C2's four step NAMES is still read out of the table above, byte for byte as it was; a
4583
- // size that is a NUMBER is a POINT size and goes through `fontPx`. The two agree by
4584
- // construction: 8, 10, 12 and 15 points round to 11, 13, 16 and 20 px, which is exactly what
4585
- // that table holds, so every cell styled before this ticket paints at the size it always did.
4586
- // ⭐ W54-T03 / R10 — AND THE FACE IS THE CELL'S OWN. `fontStack` resolves the stored NAME to
4587
- // a stack ending in a generic family, falling back to the grid's own Inter when the cell
4588
- // names none. The app's chrome is unaffected: this is one canvas string, on cell text only.
4589
- const documentSize = typeof style.size === "number"
4590
- ? fontPx(style.size)
4591
- : SIZE_PX[style.size ?? "m"] ?? SIZE_PX.m;
4592
- const size = documentSize * zoom;
4593
- const weight = style.bold ? "600 " : "";
4594
- const slant = style.italic ? "italic " : "";
4595
- ctx.font = `${slant}${weight}${size}px ${fontStack(style.font, lightTheme.fontFamily)}`;
4596
- ctx.fillStyle = tokenColour(style.color ?? "", lightTheme.textDark ?? "#202433");
4597
- ctx.textBaseline = "middle";
4598
-
4599
- const pad = (8 + Math.max(0, Math.min(MAX_CELL_INDENT, style.indent ?? 0)) * 8) * zoom;
4600
- const lineHeight = Math.round(documentSize * 1.35) * zoom;
4601
-
4602
- /**
4603
- * ⭐⭐ WRAP IS THE ONE THAT CHANGES THE SHAPE OF THE PAINT, so it is measured rather
4604
- * than guessed: words are added to a line until the next one would cross the cell's
4605
- * inner width. A single word wider than the column stays on its own line and is
4606
- * clipped, exactly as glide clips an unwrapped value, because breaking inside a word
4607
- * would hyphenate an account code.
4608
- */
4609
- const inner = rect.width - pad - 8 * zoom;
4610
- const lines: string[] = [];
4611
- if (style.wrap && text) {
4612
- // ⭐ W54-T06 MOVED THE LOOP ITSELF to `wrapIntoLines` at the top of this file, unchanged,
4613
- // and called it from BOTH here and `wrapHeights` below. The row's height and the row's
4614
- // paint are now one measurement asked twice rather than two measurements that agree by
4615
- // inspection: a wrapped value that needs three lines is given three lines of room.
4616
- lines.push(...wrapIntoLines(ctx, text, inner));
4617
- } else {
4618
- lines.push(text);
4619
- }
4620
-
4621
- // ⭐ THE VERTICAL ALIGN. `middle` is glide's own behaviour and stays the default, so
4622
- // a cell that never asked for one paints exactly where it always did.
4623
- const block = lines.length * lineHeight;
4624
- const valign = style.valign ?? "middle";
4625
- let top = rect.y + rect.height / 2 - block / 2 + lineHeight / 2;
4626
- if (valign === "top") top = rect.y + 4 * zoom + lineHeight / 2;
4627
- else if (valign === "bottom") top = rect.y + rect.height - 4 * zoom - block + lineHeight / 2;
4628
-
4629
- // ═══════════════════════════════════════════════════════════════════════════════
4630
- // ⭐⭐ W54-T06 — THE TURN, AND THE SIGN IS THE WHOLE OF IT.
4631
- //
4632
- // `CellStyle.textRotation` is Excel's own signed degree: POSITIVE is counterclockwise, the
4633
- // way a protractor reads and the way `core/sheets.py::_clean_style` clamps it. A canvas y
4634
- // grows DOWNWARD, so the same visual turn is a NEGATIVE `rotate`, and the negation happens
4635
- // once, here, rather than in the gallery that writes the number: what the document stores
4636
- // stays the number a person asked for.
4637
- //
4638
- // ⛔ THE CONTEXT IS TURNED ABOUT THE CELL'S OWN CENTRE, INSIDE THE TEXT CLIP that was set a
4639
- // few lines above, so a turned value still stops at its own cell edge instead of writing
4640
- // over its neighbour. It is also inside the one `ctx.save()` this branch already opened, so
4641
- // the transform is undone by the `ctx.restore()` that was always there and the borders,
4642
- // marks and marquees below are painted in untouched device space.
4643
- //
4644
- // ⚠ A TURNED RUN IS CENTRED IN BOTH AXES, whatever the cell's align and valign say. Those
4645
- // two describe where a HORIZONTAL run sits against the cell's corners, and a run leaving its
4646
- // corner at an angle simply leaves the box: left-aligned at 90 degrees the whole value would
4647
- // be clipped away and the control would read as broken. Excel makes the same trade.
4648
- // ═══════════════════════════════════════════════════════════════════════════════
4649
- const turn = typeof style.textRotation === "number" ? style.textRotation : 0;
4650
- if (turn !== 0) {
4651
- const cx = rect.x + rect.width / 2;
4652
- const cy = rect.y + rect.height / 2;
4653
- ctx.translate(cx, cy);
4654
- ctx.rotate((-turn * Math.PI) / 180);
4655
- ctx.translate(-cx, -cy);
4656
- top = cy - block / 2 + lineHeight / 2;
4657
- }
4658
-
4659
- lines.forEach((line, index) => {
4660
- const width = ctx.measureText(line).width;
4661
- let x = rect.x + pad;
4662
- if (style.align === "center") x = rect.x + (rect.width - width) / 2;
4663
- else if (style.align === "right") x = rect.x + rect.width - 8 * zoom - width;
4664
- if (turn !== 0) x = rect.x + (rect.width - width) / 2;
4665
- const y = top + index * lineHeight;
4666
- ctx.fillText(line, x, y);
4667
- // 3. THE UNDERLINE is drawn, not requested: a canvas has no text decoration, so the
4668
- // rule is a 1 px fill under the measured run and nothing else.
4669
- if (style.underline && line) {
4670
- ctx.fillRect(x, Math.round(y + size / 2 + 1), width, 1);
4671
- }
4672
- });
4673
 
4674
  ctx.restore();
4675
 
@@ -4692,8 +5324,8 @@ export default function SheetGrid({
4692
  // leg reads it as exactly that. Deleting it as dead reds a gate in another ticket's
4693
  // territory for a line that was never wrong, only no longer load bearing.
4694
  return true;
4695
- }, [addrAt, cellValueGetter, cells, copyMarquee, formulaPointCells, formulaRefCells,
4696
- pasteHighlight, realCol, realRow, rules, tab.name, zoom]);
4697
 
4698
  /**
4699
  * ⭐ THE BAND'S PAINT: the SAME callback, told which row it is looking at. `fromBand` is not
@@ -4876,7 +5508,8 @@ export default function SheetGrid({
4876
  onTabVisibility, realCol, realRow, rowHeight, tab, viewRange, visCols, widths, workbook, wrapHeights, writeCharts]);
4877
 
4878
  return (
4879
- <div className="sheet-grid-wrap" ref={wrapRef}>
 
4880
  {/* ⭐ THE HOME RIBBON, THEN THE FORMULA BAR, THEN THE CELLS. That order is instruction 10
4881
  said in three lines of JSX, and it is why the bar arrives as a SLOT: it has to sit under
4882
  a ribbon that lives inside this component. The ribbon is given the ANCHOR cell's style,
@@ -4896,7 +5529,13 @@ export default function SheetGrid({
4896
  {/* ⛔ NOTHING WHEN THERE IS NOTHING. An empty wrapper here would take padding and a border
4897
  from whatever rule it matched, and every pixel above the grid is a pixel the canvas does
4898
  not get. `.sheet-fx` already carries `flex: 0 0 auto`, so the bar is rendered bare. */}
4899
- {formulaBar}
 
 
 
 
 
 
4900
 
4901
  <div
4902
  className="sheet-grid-canvas"
@@ -4933,6 +5572,7 @@ export default function SheetGrid({
4933
  {bandRows > 0 && (
4934
  <div
4935
  className="sheet-frozen-rows"
 
4936
  data-gridlines={tab.view?.gridlines !== false}
4937
  style={{ height: HEADER_HEIGHT + frozenBandHeight }}
4938
  >
@@ -4945,6 +5585,9 @@ export default function SheetGrid({
4945
  freezeColumns={frozenCols}
4946
  onColumnResize={onColumnResize}
4947
  onColumnResizeEnd={onColumnResizeEnd}
 
 
 
4948
  onHeaderClicked={onHeaderClicked}
4949
  onHeaderContextMenu={onHeaderContextMenu}
4950
  theme={gridTheme}
@@ -4971,6 +5614,8 @@ export default function SheetGrid({
4971
  const shifted = fromBand(item);
4972
  const addr = addrAt(shifted[0], shifted[1]);
4973
  const cell = cellAt(tab, addr);
 
 
4974
  if (cell?.kind === "bound") { onEdit(addr, cell); return; }
4975
  // ⭐ W52-T06: a formula cell's OWN editor, opened at the row this band grid draws
4976
  // (its own zero-based `item`, NOT `shifted` -- `bandGridRef.getBounds` is that
@@ -5000,6 +5645,7 @@ export default function SheetGrid({
5000
  return;
5001
  }
5002
  const clicked = addrAt(shifted[0], shifted[1]);
 
5003
  if (validationOf(cellAt(tab, clicked))) {
5004
  setAnchor(null);
5005
  setDropdown({ addr: clicked, anchor: rectAnchor(args.bounds), query: "" });
@@ -5053,6 +5699,9 @@ export default function SheetGrid({
5053
  // it is stale, so only the END writes.
5054
  onColumnResize={onColumnResize}
5055
  onColumnResizeEnd={onColumnResizeEnd}
 
 
 
5056
  theme={gridTheme}
5057
  // ⛔ THE COLUMN-H FIX. See the block comment at the head of this file: without an
5058
  // explicit width glide sizes its wrapper to the full 3,170 px of all 26 columns, and
@@ -5118,6 +5767,8 @@ export default function SheetGrid({
5118
  onCellActivated={(item: Item) => {
5119
  const addr = addrAt(item[0], item[1]);
5120
  const cell = cellAt(tab, addr);
 
 
5121
  if (cell?.kind === "bound") { onEdit(addr, cell); return; }
5122
  if (cell?.kind === "formula") {
5123
  openFormulaEditor(addr, editableText(cell), editableText(cell).length, item, false);
@@ -5161,6 +5812,7 @@ export default function SheetGrid({
5161
  // virtualised cell actually sits on screen; the action bar yields to it, because two
5162
  // surfaces over one cell is one too many.
5163
  const clicked = addrAt(item[0], item[1]);
 
5164
  if (validationOf(cellAt(tab, clicked))) {
5165
  setAnchor(null);
5166
  setDropdown({ addr: clicked, anchor: rectAnchor(args.bounds), query: "" });
@@ -5268,6 +5920,11 @@ export default function SheetGrid({
5268
  into it, so the anchors must stay INSIDE `.sheet-grid-canvas` (W50-T19) and the
5269
  geometry they use must stay the grid's own. Both facts, and every measurement behind
5270
  them, travelled with the code into `SheetChartLayer.tsx`. */}
 
 
 
 
 
5271
  <SheetChartLayer
5272
  charts={charts}
5273
  cells={cells}
@@ -5308,6 +5965,8 @@ export default function SheetGrid({
5308
  inventing a z-index. `cg-pop` / `cg-type-list` / `cg-type-row` are declared UNSCOPED in
5309
  `index.css`, which is what lets a ticket that may not touch a stylesheet still ship a
5310
  styled panel; `FormulaBar.tsx` uses exactly this trio one component away. */}
 
 
5311
  {menu && (
5312
  <AnchoredOverlay
5313
  anchor={menu.anchor}
@@ -5828,6 +6487,19 @@ export default function SheetGrid({
5828
  {/* ⭐ W54-T14 / LANE B — WHAT A NOTE SHOWS ON HOVER. It originates at its own cell rather
5829
  than at a trigger in the chrome (DESIGN.md 4), it takes no focus and no pointer, and it
5830
  is dismissed by moving off the cell, by an outside press or by Escape through the kit. */}
 
 
 
 
 
 
 
 
 
 
 
 
 
5831
  {noteHover && (
5832
  <NoteBubble
5833
  anchor={noteHover.anchor}
@@ -5836,7 +6508,7 @@ export default function SheetGrid({
5836
  />
5837
  )}
5838
 
5839
- {selected && anchor && !painter && (
5840
  <CellActionBar
5841
  anchor={anchor}
5842
  drill={drillAffordance(selected.cell)}
 
92
  // the canvas count in the same tick as a style change therefore reads 0 whatever the fix.
93
  // ═════════════════════════════════════════════════════════════════════════════════════════════
94
 
95
+ import { cloneElement, isValidElement, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
96
  import type { ChangeEvent as ReactChangeEvent, KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";
97
  import { createPortal } from "react-dom";
98
  import type {
 
107
  import { lightTheme } from "../customer-grid/theme";
108
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
109
  import type { AnchorRect } from "../customer-grid/OverlaySurface";
110
+ import { fetchWorkspace } from "../customer-grid/apiBridge";
111
+ import type { SurfaceScope } from "../customer-grid/apiBridge";
112
+ import type { Field, FilterTree } from "../customer-grid/types";
113
+ import { filterTreeConj, filterTreeNodes } from "../customer-grid/types";
114
+ import { FilterBuilderPanel } from "../filter-kit/FilterBuilderPanel";
115
  // ⭐ INSTRUCTION 15 — clicking a sheet cell folds the nav rail exactly as a Data-module cell
116
  // click already does (`customer-grid/CustomerGrid.tsx::selectView`). One shared signal, one
117
  // shared listener (`shell/Shell.tsx::onNavMinimize`); this file never dispatched it before.
 
130
  // arithmetic, so they live in `formulaEval.ts` where `verify_formula_engine.py` compiles them and
131
  // EXECUTES the claim under node. This file owns only the keystroke and the commit that call them.
132
  import {
133
+ ERROR_REF, ERROR_VALUE, autoCloseFormula, cycleAnchorAtCaret, workbookFormulaGetter,
134
  } from "./formulaEval";
135
  import { colorForSlot } from "./refColors";
136
  import "../styles/wave52/sheet-grid.css";
 
147
  import { RulesDialog, ValidationDialog } from "./RulesDialog";
148
  import ChartDialog from "./ChartDialog";
149
  import SheetChartLayer from "./SheetChartLayer";
150
+ import SheetViewLayer from "./SheetViewLayer";
151
  import { copyChartImage } from "./sheetExport";
152
  import { sheetPageGrid } from "./pageViews";
153
  import ShortcutsPanel from "./ShortcutsPanel";
154
+ import { colToIndex, columnRangeA1, indexToCol, rowRangeA1, shiftForStructure } from "./a1";
155
+ import {
156
+ fetchViewRows, viewBlockGeometry, viewChromeRefusal, viewHeaderAt, viewRefreshOp, writeViewCell,
157
+ } from "./viewPlacement";
158
+ import type { FormulaBarProps } from "./FormulaBar";
159
  // ⛔⛔ W51-T18 — THE RULE ENGINE AND THE VALIDATION CHECKER ARE PURE AND SHEET LOCAL, and that is
160
  // what lets `verify_api.py` compile them beside `sheetState.js` and EXECUTE the ten operators
161
  // rather than grep for their names. This component is the only place their answers meet a canvas.
 
189
  } from "./types";
190
  import type {
191
  Cell, CellStyle, CellStylePatch, CellValign, SheetChartSpec, SheetRule, SheetTab, SheetTabView,
192
+ SheetViewDoor, ViewBinding, ViewRowsAnswer, Workbook,
193
  } from "./types";
194
  import {
195
+ addressOf, appendLineBreak, applyStructureWorkbook, autoSumFormula, boundDragLabel, cellAt,
196
  cellShiftLabel, cellToValue, clearAll, recalcDependents, recalculateWorkbook, WorkbookCalculationSession,
197
  clearCells, clearFormats, commitTyped, cycleAnchors, dateStamp, displayText, drillAffordance,
198
  editableText, fillCells, fillDown, fillRight, findMatches,
199
  isFilled, markOf, noMatchLabel, nothingHiddenLabel, paintPatch, pasteCells,
200
+ chartPaneProjections, frozenBandSize, hideColumnByWidth, lastVisibleWidth, lockstepScrollX,
201
  rememberCut, setFormula, shiftCells, splitAddress, styleCells, styleOf, usedExtent,
202
+ structureRefusal, viewIndexOf,
203
  visibleIndices, withHidden,
204
  } from "./sheetState";
205
  import type {
 
322
  // numbers exactly. So a document written before the size box existed paints identically, and the
323
  // only cells that take the other branch are the ones somebody set a point size on.
324
 
325
+ const BINDING_REFUSAL_COPY: Readonly<Record<string, { display: string; message: string }>> = {
326
+ database_unreadable: { display: "#NO ACCESS", message: "You do not have access to this database." },
327
+ field_unknown: { display: "#FIELD?", message: "This field is no longer in the database." },
328
+ scope_not_applicable: { display: "#ERROR!", message: "The database cannot apply this cell's row restrictions." },
329
+ };
330
+ const BINDING_REFUSAL_FALLBACK = { display: "#ERROR!", message: "This cell's database binding could not be calculated." };
331
+
332
+ /** R48: old documents may have a blank display, but the grid always owns its refusal copy. */
333
+ function bindingRefusal(cell: Cell | null | undefined) {
334
+ if (cell?.kind !== "bound" || cell.state !== "refused" || cell.binding?.mode === "view") return null;
335
+ return BINDING_REFUSAL_COPY[cell.refusal?.code ?? ""] ?? BINDING_REFUSAL_FALLBACK;
336
+ }
337
+
338
+ /**
339
+ * Lay out a run in its owner's box. The caller clips to the cell being repainted.
340
+ * An unstyled owner uses {}: SIZE_PX.m (13 px), lightTheme.fontFamily (Inter),
341
+ * and left alignment, matching glide's baseFontStyle and its default alignment.
342
+ * This file never sets contentAlign.
343
+ */
344
+ function drawCellTextRun(
345
+ ctx: CanvasRenderingContext2D, box: Rectangle, cell: Cell | null, style: CellStyle, zoom: number,
346
+ ): void {
347
+ const refusal = bindingRefusal(cell);
348
+ const text = refusal?.display ?? formatCellText(cell, displayText(cell));
349
+ // ⭐ W51-T16: THE SIZE STEP AND THE INDENT ARE PART OF THE FONT AND THE BOX, so they
350
+ // are settled BEFORE anything is measured. A canvas measures text in the font that is
351
+ // set at the time, so choosing the size after `measureText` would centre a heading
352
+ // using the body size's width.
353
+ // ⭐⭐ W54-T03 / R11 — TWO SHAPES, ONE SLOT, AND THE PIXELS DO NOT MOVE. A `size` that is one
354
+ // of C2's four step NAMES is still read out of the table above, byte for byte as it was; a
355
+ // size that is a NUMBER is a POINT size and goes through `fontPx`. The two agree by
356
+ // construction: 8, 10, 12 and 15 points round to 11, 13, 16 and 20 px, which is exactly what
357
+ // that table holds, so every cell styled before this ticket paints at the size it always did.
358
+ // ⭐ W54-T03 / R10 — AND THE FACE IS THE CELL'S OWN. `fontStack` resolves the stored NAME to
359
+ // a stack ending in a generic family, falling back to the grid's own Inter when the cell
360
+ // names none. The app's chrome is unaffected: this is one canvas string, on cell text only.
361
+ const documentSize = typeof style.size === "number"
362
+ ? fontPx(style.size)
363
+ : SIZE_PX[style.size ?? "m"] ?? SIZE_PX.m;
364
+ const size = documentSize * zoom;
365
+ const weight = style.bold ? "600 " : "";
366
+ const slant = style.italic ? "italic " : "";
367
+ ctx.font = `${slant}${weight}${size}px ${fontStack(style.font, lightTheme.fontFamily)}`;
368
+ ctx.fillStyle = tokenColour(refusal ? "--lp-red-deep" : style.color ?? "", lightTheme.textDark ?? "#202433");
369
+ ctx.textBaseline = "middle";
370
+
371
+ const pad = (8 + Math.max(0, Math.min(MAX_CELL_INDENT, style.indent ?? 0)) * 8) * zoom;
372
+ const lineHeight = Math.round(documentSize * 1.35) * zoom;
373
+
374
+ /**
375
+ * ⭐⭐ WRAP IS THE ONE THAT CHANGES THE SHAPE OF THE PAINT, so it is measured rather
376
+ * than guessed: words are added to a line until the next one would cross the cell's
377
+ * inner width. A single word wider than the column stays on its own line and is
378
+ * clipped, exactly as glide clips an unwrapped value, because breaking inside a word
379
+ * would hyphenate an account code.
380
+ */
381
+ const inner = box.width - pad - 8 * zoom;
382
+ const lines: string[] = [];
383
+ if (style.wrap && text) {
384
+ // ⭐ W54-T06 MOVED THE LOOP ITSELF to `wrapIntoLines` at the top of this file, unchanged,
385
+ // and called it from BOTH here and `wrapHeights` below. The row's height and the row's
386
+ // paint are now one measurement asked twice rather than two measurements that agree by
387
+ // inspection: a wrapped value that needs three lines is given three lines of room.
388
+ lines.push(...wrapIntoLines(ctx, text, inner));
389
+ } else {
390
+ lines.push(text);
391
+ }
392
+
393
+ // ⭐ THE VERTICAL ALIGN. `middle` is glide's own behaviour and stays the default, so
394
+ // a cell that never asked for one paints exactly where it always did.
395
+ const block = lines.length * lineHeight;
396
+ const valign = style.valign ?? "middle";
397
+ let top = box.y + box.height / 2 - block / 2 + lineHeight / 2;
398
+ if (valign === "top") top = box.y + 4 * zoom + lineHeight / 2;
399
+ else if (valign === "bottom") top = box.y + box.height - 4 * zoom - block + lineHeight / 2;
400
+
401
+ // ═══════════════════════════════════════════════════════════════════════════════
402
+ // ⭐⭐ W54-T06 — THE TURN, AND THE SIGN IS THE WHOLE OF IT.
403
+ //
404
+ // `CellStyle.textRotation` is Excel's own signed degree: POSITIVE is counterclockwise, the
405
+ // way a protractor reads and the way `core/sheets.py::_clean_style` clamps it. A canvas y
406
+ // grows DOWNWARD, so the same visual turn is a NEGATIVE `rotate`, and the negation happens
407
+ // once, here, rather than in the gallery that writes the number: what the document stores
408
+ // stays the number a person asked for.
409
+ //
410
+ // ⛔ THE CONTEXT IS TURNED ABOUT THE CELL'S OWN CENTRE, INSIDE THE TEXT CLIP that was set a
411
+ // few lines above, so a turned value still stops at its own cell edge instead of writing
412
+ // over its neighbour. It is also inside the one `ctx.save()` this branch already opened, so
413
+ // the transform is undone by the `ctx.restore()` that was always there and the borders,
414
+ // marks and marquees below are painted in untouched device space.
415
+ //
416
+ // ⚠ A TURNED RUN IS CENTRED IN BOTH AXES, whatever the cell's align and valign say. Those
417
+ // two describe where a HORIZONTAL run sits against the cell's corners, and a run leaving its
418
+ // corner at an angle simply leaves the box: left-aligned at 90 degrees the whole value would
419
+ // be clipped away and the control would read as broken. Excel makes the same trade.
420
+ // ═══════════════════════════════════════════════════════════════════════════════
421
+ const turn = typeof style.textRotation === "number" ? style.textRotation : 0;
422
+ if (turn !== 0) {
423
+ const cx = box.x + box.width / 2;
424
+ const cy = box.y + box.height / 2;
425
+ ctx.translate(cx, cy);
426
+ ctx.rotate((-turn * Math.PI) / 180);
427
+ ctx.translate(-cx, -cy);
428
+ top = cy - block / 2 + lineHeight / 2;
429
+ }
430
+
431
+ lines.forEach((line, index) => {
432
+ const width = ctx.measureText(line).width;
433
+ let x = box.x + pad;
434
+ if (style.align === "center") x = box.x + (box.width - width) / 2;
435
+ else if (style.align === "right") x = box.x + box.width - 8 * zoom - width;
436
+ if (turn !== 0) x = box.x + (box.width - width) / 2;
437
+ const y = top + index * lineHeight;
438
+ ctx.fillText(line, x, y);
439
+ // 3. THE UNDERLINE is drawn, not requested: a canvas has no text decoration, so the
440
+ // rule is a 1 px fill under the measured run and nothing else.
441
+ if (style.underline && line) {
442
+ ctx.fillRect(x, Math.round(y + size / 2 + 1), width, 1);
443
+ }
444
+ });
445
+ }
446
+
447
+ type SpillMeasure = (text: string, cell: Cell, col: number) => number;
448
+ type SpillOwner = { ownerCol: number; ownerText: string; ownerCell: Cell };
449
+
450
+ /** Distances beyond the owner's edges, in document pixels, matching the run's layout. */
451
+ function spillReach(cell: Cell, width: number, col: number, measure: SpillMeasure) {
452
+ const style = cell.style ?? {};
453
+ // An error belongs to its own cell, even when the column is too narrow for its code.
454
+ if (cell.state === "refused") return null;
455
+ if (style.wrap || style.textRotation || displayText(cell) === "") return null;
456
+ const text = formatCellText(cell, displayText(cell));
457
+ const runWidth = measure(text, cell, col);
458
+ const pad = 8 + Math.max(0, Math.min(MAX_CELL_INDENT, style.indent ?? 0)) * 8;
459
+ const x = style.align === "center" ? (width - runWidth) / 2
460
+ : style.align === "right" ? width - 8 - runWidth : pad;
461
+ return {
462
+ left: style.align === "right" || style.align === "center" ? Math.max(0, -x) : 0,
463
+ right: style.align !== "right" ? Math.max(0, x + runWidth - width) : 0,
464
+ text,
465
+ };
466
+ }
467
+
468
+ /**
469
+ * Find the nearest non-empty neighbour whose run reaches this empty cell.
470
+ * Widths and measure use document pixels; addrAt maps visible columns and rows.
471
+ * A filled neighbour blocks the walk even if its own text cannot spill.
472
+ */
473
+ export function spillOwnerAt(
474
+ cells: Readonly<Record<string, Cell>>, addrAt: (col: number, row: number) => string,
475
+ widths: readonly number[], frozenCols: number, col: number, row: number, measure: SpillMeasure,
476
+ ): SpillOwner | null {
477
+ if (col < 0 || col >= widths.length || displayText(cells[addrAt(col, row)]) !== "") return null;
478
+ const first = col < frozenCols ? 0 : frozenCols;
479
+ const last = col < frozenCols ? frozenCols : widths.length;
480
+ for (const step of [-1, 1]) {
481
+ let gap = 0;
482
+ for (let ownerCol = col + step; ownerCol >= first && ownerCol < last; ownerCol += step) {
483
+ const ownerCell = cells[addrAt(ownerCol, row)];
484
+ if (displayText(ownerCell) !== "") {
485
+ const reach = spillReach(ownerCell, widths[ownerCol], ownerCol, measure);
486
+ if (reach && (step < 0 ? reach.right : reach.left) > gap) {
487
+ return { ownerCol, ownerText: reach.text, ownerCell };
488
+ }
489
+ break;
490
+ }
491
+ gap += widths[ownerCol];
492
+ }
493
+ }
494
+ return null;
495
+ }
496
+
497
+ /** Whether this owner's run reaches an empty adjacent cell in the same frozen pane. */
498
+ export function cellSpillsAt(
499
+ cells: Readonly<Record<string, Cell>>, addrAt: (col: number, row: number) => string,
500
+ widths: readonly number[], frozenCols: number, col: number, row: number, measure: SpillMeasure,
501
+ ): boolean {
502
+ if (col < 0 || col >= widths.length) return false;
503
+ const cell = cells[addrAt(col, row)];
504
+ if (!cell) return false;
505
+ const reach = spillReach(cell, widths[col], col, measure);
506
+ if (!reach) return false;
507
+ const first = col < frozenCols ? 0 : frozenCols;
508
+ const last = col < frozenCols ? frozenCols : widths.length;
509
+ return (reach.left > 0 && col > first && displayText(cells[addrAt(col - 1, row)]) === "")
510
+ || (reach.right > 0 && col + 1 < last && displayText(cells[addrAt(col + 1, row)]) === "");
511
+ }
512
+
513
  /** R8's size menu emits a step NAME; C2 stores a letter. One table, so the two cannot drift. */
514
  const SIZE_OF_STEP: Record<string, "s" | "m" | "l" | "xl"> = {
515
  small: "s", normal: "m", large: "l", heading: "xl",
 
789
  on: "cell" | "column" | "row";
790
  }
791
 
792
+ interface ViewHeaderMenu {
793
+ anchor: AnchorRect;
794
+ origin: string;
795
+ field: string;
796
+ item: Item;
797
+ binding: ViewBinding;
798
+ }
799
+
800
+ /** A field's own filter vocabulary, in the same overlay and builder as the rest of the app. */
801
+ function ViewHeaderDropdown({ menu, onApply, onClose }: {
802
+ menu: ViewHeaderMenu;
803
+ onApply: (patch: Pick<ViewBinding, "sort"> | Pick<ViewBinding, "filter">) => Promise<boolean>;
804
+ onClose: () => void;
805
+ }) {
806
+ const [fields, setFields] = useState<Field[] | null>(null);
807
+ const [users, setUsers] = useState<string[]>([]);
808
+ const [error, setError] = useState("");
809
+ const [applying, setApplying] = useState(false);
810
+ const pending = useRef(false);
811
+ const initial = menu.binding.filter as FilterTree | undefined;
812
+ const [filter, setFilter] = useState<FilterTree>(() => ({
813
+ conj: filterTreeConj(initial), nodes: filterTreeNodes(initial),
814
+ }));
815
+ useEffect(() => {
816
+ let live = true;
817
+ const database = menu.binding.database;
818
+ const scope = database === "customer_data" ? "customer" : database === "product_data"
819
+ ? "product" : database.startsWith("ut_") ? database as SurfaceScope : null;
820
+ void (async () => {
821
+ const workspace = scope ? await fetchWorkspace(scope, { allowCached: true }) : null;
822
+ if (!live) return;
823
+ const catalogue = workspace?.fields;
824
+ if (!catalogue?.some(field => field.key === menu.field)) {
825
+ setError("The filter fields could not be loaded.");
826
+ return;
827
+ }
828
+ // Keep other conditions' labels and types, while Add condition targets this header.
829
+ setFields(catalogue.map(field => ({ ...field,
830
+ filterable: field.key === menu.field && field.filterable !== false })));
831
+ setUsers(workspace?.userOptions ?? []);
832
+ })().catch(() => { if (live) setError("The filter fields could not be loaded."); });
833
+ return () => { live = false; };
834
+ }, [menu.binding.database, menu.field]);
835
+ const apply = async (patch: Pick<ViewBinding, "sort"> | Pick<ViewBinding, "filter">) => {
836
+ if (pending.current) return;
837
+ pending.current = true;
838
+ setApplying(true);
839
+ try {
840
+ if (await onApply(patch)) onClose();
841
+ } finally {
842
+ pending.current = false;
843
+ setApplying(false);
844
+ }
845
+ };
846
+ return (
847
+ <AnchoredOverlay anchor={menu.anchor} className="cg-pop" role="dialog"
848
+ ariaLabel="Sort and filter" onDismiss={onClose} restoreFocus dismissOnOutside>
849
+ <div className="cg-type-list" role="menu" aria-label="Sort">
850
+ <button type="button" role="menuitem" className="cg-type-row" disabled={applying}
851
+ onClick={() => void apply({ sort: [{ field: menu.field, dir: "asc" }] })}>
852
+ <span className="cg-type-label">Sort ascending</span>
853
+ </button>
854
+ <button type="button" role="menuitem" className="cg-type-row" disabled={applying}
855
+ onClick={() => void apply({ sort: [{ field: menu.field, dir: "desc" }] })}>
856
+ <span className="cg-type-label">Sort descending</span>
857
+ </button>
858
+ </div>
859
+ {fields ? <FilterBuilderPanel fields={fields} filters={filter} onChange={setFilter}
860
+ userOptions={users} footerExtra={
861
+ <button type="button" className="cg-btn" disabled={applying}
862
+ onClick={() => void apply({ filter })}>Apply filter</button>
863
+ } /> : <div className="cg-pop-title" role="status">{error || "Loading filter…"}</div>}
864
+ </AnchoredOverlay>
865
+ );
866
+ }
867
+
868
  /** What the find box is looking for and which match it is standing on. */
869
  interface FindState {
870
  query: string;
 
951
  [storedWorkbook, storedTab.id],
952
  );
953
  const tab = workbook.sheets.find((sheet) => sheet.id === storedTab.id) ?? storedTab;
954
+ // C3/R29: the existing structure door owns history and persistence. Serialize views so a
955
+ // growing first view moves the next anchor before that next view resolves. No cell PATCH or
956
+ // floating spill renderer participates in this path.
957
+ const viewRefresh = useRef({ generation: 0, scope: "", key: "", busy: false,
958
+ seen: new WeakSet<Workbook["sheets"]>() });
959
+ const viewContext = useRef({ storedWorkbook, storedTab, onStructure, onNotice });
960
+ viewContext.current = { storedWorkbook, storedTab, onStructure, onNotice };
961
+ const viewWritePending = useRef(false);
962
+ const [viewWriteRefresh, setViewWriteRefresh] = useState(0);
963
+ useEffect(() => {
964
+ const state = viewRefresh.current;
965
+ return () => { state.generation++; state.key = ""; state.seen = new WeakSet(); };
966
+ }, []);
967
+ useEffect(() => {
968
+ const state = viewRefresh.current;
969
+ const scope = `${storedWorkbook.id}/${storedTab.id}`;
970
+ if (state.scope !== scope) {
971
+ state.scope = scope;
972
+ state.key = "";
973
+ state.seen = new WeakSet();
974
+ state.generation++;
975
+ }
976
+ const refreshed = state.busy && !busy;
977
+ state.busy = busy;
978
+ if (busy) { state.generation++; return; }
979
+ const anchors = Object.entries(storedTab.cells ?? {})
980
+ .filter(([, cell]) => cell.kind === "bound" && cell.binding?.mode === "view"
981
+ && (cell.binding.viewType === "grid" || !cell.binding.block))
982
+ .map(([addr]) => addr);
983
+ if (!anchors.length) { state.generation++; state.key = ""; return; }
984
+ const key = JSON.stringify([storedWorkbook.sheets, storedWorkbook.namedRanges]);
985
+ // History restores the original sheets array. Do not immediately redo an undone push.
986
+ if (!refreshed && (key === state.key || state.seen.has(storedWorkbook.sheets))) {
987
+ if (key !== state.key) state.generation++; // Undo also cancels a pending resolver answer.
988
+ state.key = key;
989
+ state.seen.add(storedWorkbook.sheets);
990
+ return;
991
+ }
992
+ state.key = key;
993
+ state.seen.add(storedWorkbook.sheets);
994
+ const generation = ++state.generation;
995
+ const current = () => state.generation === generation && state.scope === scope;
996
+ void (async () => {
997
+ let projected = storedWorkbook;
998
+ let lastNotice = "";
999
+ const report = (message: string) => { lastNotice = message; viewContext.current.onNotice(message); };
1000
+ let pending = anchors;
1001
+ while (pending.length && current()) {
1002
+ const origin = pending.shift()!;
1003
+ const target = projected.sheets.find(sheet => sheet.id === storedTab.id)!;
1004
+ const cell = (target.cells ?? {})[origin];
1005
+ const at = splitAddress(origin);
1006
+ if (!at || cell?.kind !== "bound" || cell.binding?.mode !== "view") continue;
1007
+ const got = await fetchViewRows(projected.id, cell.binding as ViewBinding);
1008
+ if (!current()) return;
1009
+ if (!got.ok) { report(got.message); continue; }
1010
+ const op = viewRefreshOp(target, origin, got.answer);
1011
+ if (typeof op === "string") { report(op); continue; }
1012
+ const shiftAddress = (addr: string) => {
1013
+ for (const step of [op, ...(op.place?.also ? [op.place.also] : [])]) {
1014
+ if (step.delta) addr = shiftForStructure(addr,
1015
+ { sheet: target.name, axis: step.axis, at: step.at, delta: step.delta }, target.name);
1016
+ }
1017
+ return addr;
1018
+ };
1019
+ const cells = op.place!.cells;
1020
+ const refusal = structureRefusal(projected, target.id, op);
1021
+ if (refusal) { report(refusal); continue; }
1022
+ if (!op.delta && !op.place!.also?.delta && Object.entries(cells).every(([addr, value]) =>
1023
+ JSON.stringify((target.cells ?? {})[addr] ?? null) === JSON.stringify(value))) continue;
1024
+ projected = applyStructureWorkbook(projected, target.id, op);
1025
+ state.key = JSON.stringify([projected.sheets, projected.namedRanges]);
1026
+ // The prop returns the page's async structure operation at runtime. Awaiting it keeps
1027
+ // hydration/commit ordering intact without adding another history or save door.
1028
+ await viewContext.current.onStructure(op);
1029
+ if (!current()) return;
1030
+ pending = pending.map(shiftAddress).filter(addr => splitAddress(addr) !== null);
1031
+ }
1032
+ // A later successful view commits through the page, which clears its notice. Keep any
1033
+ // refused refresh visible after the batch as well as leaving that view's cells intact.
1034
+ if (current() && lastNotice) viewContext.current.onNotice(lastNotice);
1035
+ })().catch(() => {
1036
+ if (current()) viewContext.current.onNotice("The view rows could not be refreshed.");
1037
+ });
1038
+ }, [storedWorkbook, storedTab, busy, viewWriteRefresh]);
1039
  const pageView = tab.view?.pageView ?? "normal";
1040
  const pageGrid = useMemo(() => pageView === "normal"
1041
  ? null : sheetPageGrid(workbook, tab.id, workbook.printSettings), [pageView, workbook, tab.id]);
 
1139
  * band by the band's own height. `openFormulaEditor` reads whichever ref actually owns the row.
1140
  */
1141
  const bandGridRef = useRef<DataEditorRef | null>(null);
1142
+ const frozenBandRef = useRef<HTMLDivElement | null>(null);
1143
  // ⛔ THE FIND BOX'S CLOSE, THROUGH THE ONE ARBITER. Declared here, beside the state it closes,
1144
  // and unconditionally, so the hook order never changes between renders.
1145
  useEscapeClose(find !== null, () => setFind(null));
1146
  const [anchor, setAnchor] = useState<Rectangle | null>(null);
1147
  const [menu, setMenu] = useState<SheetMenu | null>(null);
1148
+ const [viewMenu, setViewMenu] = useState<ViewHeaderMenu | null>(null);
1149
+ const viewMenuRef = useRef<ViewHeaderMenu | null>(null);
1150
  /**
1151
  * ⭐ THE FORMAT PAINTER'S WHOLE STATE: the style it picked up, waiting for the click that lands
1152
  * it. `null` means the painter is off, so one value carries both the mode and its payload and
 
1193
  * there would queue dozens of saves per drag and the reader would watch the reload notice fire.
1194
  * The dragging width lives here; `onColumnResizeEnd` commits once.
1195
  */
1196
+ const [dragWidth, setDragWidth] = useState<{ cols: number[]; width: number } | null>(null);
1197
+ // Glide clamps resize callbacks to >=20px even with minColumnWidth=0. Keep the pointer's
1198
+ // actual width until release, and give both canvases a positive hairline during the gesture.
1199
+ const resizeGesture = useRef<{
1200
+ left: number; scale: number; width: number; cols: number[]; committed: boolean;
1201
+ } | null>(null);
1202
+ useEffect(() => {
1203
+ const track = (event: MouseEvent) => {
1204
+ const gesture = resizeGesture.current;
1205
+ if (gesture && !gesture.committed) {
1206
+ gesture.width = Math.max(MIN_COL_WIDTH * zoom,
1207
+ Math.min(MAX_COL_WIDTH * zoom, (event.clientX - gesture.left) / gesture.scale));
1208
+ }
1209
+ };
1210
+ window.addEventListener("mousemove", track, true);
1211
+ window.addEventListener("mouseup", track, true);
1212
+ return () => {
1213
+ window.removeEventListener("mousemove", track, true);
1214
+ window.removeEventListener("mouseup", track, true);
1215
+ };
1216
+ }, [zoom]);
1217
 
1218
  // ── W51-T18: the two surfaces this ticket adds, and the one local fallback it needs ─────────
1219
  /** R8's Styles group is conditional formatting's ONLY door, and this is what it opens. */
 
1486
  return {
1487
  title: letters,
1488
  id: String(real),
1489
+ width: Math.max(1, dragWidth?.cols.includes(i)
1490
+ ? dragWidth.width : Math.round(lastVisibleWidth(tab, real) * zoom)),
1491
  };
1492
  }),
1493
+ [dragWidth, visCols, tab, zoom],
1494
  );
1495
+ const spillWidths = useMemo(() => columns.map(column => column.width / zoom), [columns, zoom]);
1496
 
1497
  /** The x offset of one column, summed rather than multiplied: widths differ now. */
1498
  const columnX = useCallback(
 
1501
  );
1502
 
1503
  const cells = tab.cells ?? {};
1504
+ // ⛔ `tab.cells` IS LEGITIMATELY UNDEFINED ON A FIRST RENDER, which is why the line above
1505
+ // already reads it through `?? {}`. `GET /sheets/{id}?tabs=meta` answers tabs with NO cells, so
1506
+ // a tab the page has not fetched yet arrives here with none and `Object.entries(undefined)`
1507
+ // throws INSIDE A RENDER. This lane's own Kanban screenshot is what found it: the console said
1508
+ // "[Sheet] render failed TypeError: Cannot convert undefined or null to object" and the sheet
1509
+ // fell to its error boundary. Read the guarded local, never the prop.
1510
+ const reservedViewBlocks = useMemo(() => Object.entries(cells).flatMap(([origin, cell]) => {
1511
+ const at = splitAddress(origin);
1512
+ return at && cell?.kind === "bound" && cell.binding?.mode === "view"
1513
+ && cell.binding.viewType !== "grid" && cell.binding.block
1514
+ ? [viewBlockGeometry(at, cell.binding)] : [];
1515
+ }), [cells]);
1516
+ const isViewReserved = useCallback((addr: string) => {
1517
+ const pos = splitAddress(addr);
1518
+ return !!pos && reservedViewBlocks.some(box => pos.col - 1 >= box.col0 && pos.col - 1 <= box.col1
1519
+ && pos.row - 1 >= box.row0 && pos.row - 1 <= box.row1);
1520
+ }, [reservedViewBlocks]);
1521
 
1522
  // The page owns refusal/confirmation and atomically reanchors cells, sources and placement.
1523
  const requestStructure = onStructure;
 
1598
  return {
1599
  kind: GridCellKind.Text,
1600
  data: editableText(cell),
1601
+ displayData: bindingRefusal(cell)?.display ?? formatCellText(cell, displayText(cell)),
1602
  // ⛔ A bound cell does not open glide's OWN text overlay. `onKeyDown`'s typed-character
1603
  // branch is that cell's editor instead (R5, W52-T09): it opens the SAME floating editor a
1604
  // fresh formula does, converting the cell the moment Enter commits, with no confirmation
 
1616
  // cell's editor: `onCellActivated` opens it for an EXISTING formula, and `onKeyDown`'s
1617
  // typed-character branch opens it the moment a fresh "=" starts one. glide's own overlay
1618
  // would otherwise sit on top of the dropdown/ScreenTip a person may be typing INTO.
1619
+ allowOverlay: !viewChromeRefusal(cell) && cell?.kind !== "bound"
1620
+ && cell?.kind !== "formula" && !validationOf(cell),
1621
+ readonly: !!viewChromeRefusal(cell) || cell?.kind === "bound" || validationOf(cell) !== null,
1622
  };
1623
  },
1624
  // `cells` is the whole dependency: a new workbook object gives a new `cells`, which is what
 
1867
  message: `${ERROR_REF} This formula names a sheet that is not in this workbook.`,
1868
  };
1869
  }
1870
+ const cell = cellAt(target, addr);
1871
+ const refusal = bindingRefusal(cell);
1872
+ if (refusal) return { kind: "error", code: ERROR_VALUE, message: `${ERROR_VALUE} ${refusal.message}` };
1873
+ return cellToValue(cell);
1874
  });
1875
  }, [tab, workbook.sheets]);
1876
 
 
1884
  * `SheetPage.tsx::commitCells`, which pushes history and queues a save; an effect watching the
1885
  * document would mutate a workbook nobody edited and write it back merely for opening a sheet.
1886
  */
1887
+ const applyViewAnswer = useCallback(async (
1888
+ base: Workbook, target: SheetTab, origin: string, answer: ViewRowsAnswer,
1889
+ binding = (target.cells ?? {})[origin]?.binding,
1890
+ ): Promise<boolean> => {
1891
+ const latest = viewContext.current;
1892
+ const op = viewRefreshOp(target, origin, answer, binding);
1893
+ if (typeof op === "string") { latest.onNotice(op); return false; }
1894
+ const refusal = structureRefusal(base, target.id, op);
1895
+ if (refusal) { latest.onNotice(refusal); return false; }
1896
+ const projected = applyStructureWorkbook(base, target.id, op);
1897
+ const state = viewRefresh.current;
1898
+ state.seen.add(base.sheets);
1899
+ state.key = JSON.stringify([projected.sheets, projected.namedRanges]);
1900
+ await latest.onStructure(op);
1901
+ return true;
1902
+ }, []);
1903
+
1904
+ const resizeViewBlock = useCallback((origin: string, block: { cols: number; rows: number }) => {
1905
+ const context = viewContext.current;
1906
+ const cell = (context.storedTab.cells ?? {})[origin];
1907
+ if (viewRefresh.current.busy || viewWritePending.current || cell?.binding?.mode !== "view"
1908
+ || cell.binding.viewType === "grid" || !cell.binding.block) return;
1909
+ const binding = { ...cell.binding, block: { cols: block.cols, rows: block.rows } } as ViewBinding;
1910
+ if (JSON.stringify(cell.binding.block) === JSON.stringify(binding.block)) return;
1911
+ // Row data cannot change a non-grid footprint. Resize commits just its binding and the
1912
+ // displaced bands, using precisely the same atomic door as a resolved Grid refresh.
1913
+ void applyViewAnswer(context.storedWorkbook, context.storedTab, origin, {
1914
+ fields: [], rows: [], total: 0, limit: binding.limit, viewType: binding.viewType, editable: false,
1915
+ }, binding);
1916
+ }, [applyViewAnswer]);
1917
+
1918
+ const commitViewRecord = useCallback(async (addr: string, text: string) => {
1919
+ const context = viewContext.current;
1920
+ if (viewWritePending.current || viewRefresh.current.busy) {
1921
+ context.onNotice("Wait for this Grid to finish saving, then try again.");
1922
+ return;
1923
+ }
1924
+ const base = context.storedWorkbook;
1925
+ const target = context.storedTab;
1926
+ const generation = ++viewRefresh.current.generation;
1927
+ const current = () => viewRefresh.current.generation === generation
1928
+ && viewContext.current.storedWorkbook.id === base.id
1929
+ && viewContext.current.storedTab.id === target.id
1930
+ && viewContext.current.storedWorkbook.sheets === base.sheets;
1931
+ viewWritePending.current = true;
1932
+ try {
1933
+ const result = await writeViewCell(base.id, target, addr, text, current);
1934
+ if (!result.ok) { viewContext.current.onNotice(result.message); return; }
1935
+ if (!current()) {
1936
+ // A record write can finish after navigation or a neighbouring sheet edit. Let the
1937
+ // existing refresh effect resolve the CURRENT footprint; never apply the old one.
1938
+ viewRefresh.current.key = "";
1939
+ viewRefresh.current.seen = new WeakSet();
1940
+ setViewWriteRefresh(value => value + 1);
1941
+ viewContext.current.onNotice("The record was saved; the Grid is refreshing.");
1942
+ return;
1943
+ }
1944
+ await applyViewAnswer(base, target, result.origin, result.answer);
1945
+ } catch {
1946
+ viewContext.current.onNotice("The record change could not be confirmed; refresh the Grid before trying again.");
1947
+ } finally {
1948
+ viewWritePending.current = false;
1949
+ }
1950
+ }, [applyViewAnswer]);
1951
+
1952
  const commitWithRecalc = useCallback((edits: Record<string, Cell | null>) => {
1953
+ const entries = Object.entries(edits);
1954
+ const reserved = entries.some(([addr, value]) => value && isViewReserved(addr));
1955
+ if (reserved) { onNotice("Resize or remove this view before editing its reserved cells."); return; }
1956
+ const placed = entries.filter(([addr]) => cells[addr]?.viewChild
1957
+ || viewChromeRefusal(cells[addr]));
1958
+ if (placed.length) {
1959
+ const chrome = placed.map(([addr]) => viewChromeRefusal(cells[addr])).find(Boolean);
1960
+ if (chrome) { onNotice(chrome); return; }
1961
+ if (entries.length !== 1) { onNotice("Edit one Grid record cell at a time."); return; }
1962
+ const [addr, cell] = placed[0];
1963
+ void commitViewRecord(addr, editableText(cell));
1964
+ return;
1965
+ }
1966
  onCommit({ ...edits, ...recalcDependents(tab, edits, workbook.sheets, workbook, calculationSession.current) });
1967
+ }, [commitViewRecord, isViewReserved, onCommit, onNotice, tab, workbook]);
1968
 
1969
  /** ONE typed commit. `commitTyped` picks literal or formula and drops a binding on its own. */
1970
  const onCellEdited = useCallback((item: Item, value: EditableGridCell) => {
 
3083
  if (scroll && at[1] >= 0) gridRef.current?.scrollTo(at[0], at[1]);
3084
  }, [onSelectionChange]);
3085
 
3086
+ const focusViewHeader = useCallback((row: number) => {
3087
+ // Glide's focus() can retain an old accessibility cell while a portal owns focus.
3088
+ // Focus the owning canvas instead; its controlled selection identifies the header.
3089
+ const canvas = Array.from(wrapRef.current?.querySelectorAll<HTMLCanvasElement>(
3090
+ ".sheet-grid-canvas .dvn-underlay canvas[tabindex]",
3091
+ ) ?? []).find(node => Boolean(node.closest(".sheet-frozen-rows")) === (row < 0));
3092
+ canvas?.focus({ preventScroll: true });
3093
+ }, []);
3094
+
3095
+ const openViewHeader = useCallback((item: Item, args: {
3096
+ bounds: Rectangle; localEventX: number; preventDefault: () => void;
3097
+ }) => {
3098
+ const header = viewHeaderAt(cells, addrAt(item[0], item[1]));
3099
+ if (!header || args.localEventX < args.bounds.width - 24 * zoom) return false;
3100
+ args.preventDefault();
3101
+ setAnchor(null);
3102
+ setMenu(null);
3103
+ applySelection({ col0: item[0], col1: item[0], row0: item[1], row1: item[1] }, item, false);
3104
+ // The canvas is the opener the shared overlay captures for restoreFocus.
3105
+ focusViewHeader(item[1]);
3106
+ const opened = { ...header, item, anchor: rectAnchor(args.bounds),
3107
+ binding: cells[header.origin].binding as ViewBinding };
3108
+ viewMenuRef.current = opened;
3109
+ setViewMenu(opened);
3110
+ return true;
3111
+ }, [addrAt, applySelection, focusViewHeader, tab.cells, zoom]);
3112
+
3113
+ const closeViewHeader = useCallback(() => {
3114
+ if (viewMenuRef.current !== viewMenu) return;
3115
+ viewMenuRef.current = null;
3116
+ setViewMenu(null);
3117
+ if (!viewMenu) return;
3118
+ // Outside pointerdown may select another cell later in that gesture. Restore the header
3119
+ // after it, using the grid's selection door as well as AnchoredOverlay's DOM focus restore.
3120
+ const [col, row] = viewMenu.item;
3121
+ requestAnimationFrame(() => {
3122
+ applySelection({ col0: col, col1: col, row0: row, row1: row }, [col, row], false);
3123
+ focusViewHeader(row);
3124
+ });
3125
+ }, [applySelection, focusViewHeader, viewMenu]);
3126
+
3127
+ const applyViewHeader = useCallback(async (
3128
+ patch: Pick<ViewBinding, "sort"> | Pick<ViewBinding, "filter">,
3129
+ ): Promise<boolean> => {
3130
+ if (!viewMenu) return false;
3131
+ const context = viewContext.current;
3132
+ const base = context.storedWorkbook;
3133
+ const target = context.storedTab;
3134
+ const cell = (target.cells ?? {})[viewMenu.origin];
3135
+ if (viewWritePending.current || viewRefresh.current.busy
3136
+ || JSON.stringify(cell?.binding) !== JSON.stringify(viewMenu.binding)) {
3137
+ context.onNotice("The view changed. Reopen its header and try again.");
3138
+ return false;
3139
+ }
3140
+ const state = viewRefresh.current;
3141
+ const generation = ++state.generation;
3142
+ try {
3143
+ const binding = { ...viewMenu.binding, ...patch };
3144
+ const got = await fetchViewRows(base.id, binding);
3145
+ const latest = viewContext.current;
3146
+ if (viewMenuRef.current !== viewMenu) return false;
3147
+ if (state.generation !== generation || latest.storedWorkbook.id !== base.id
3148
+ || latest.storedTab.id !== target.id || latest.storedWorkbook.sheets !== base.sheets) {
3149
+ latest.onNotice("The sheet changed. Reopen the header and try again.");
3150
+ return false;
3151
+ }
3152
+ if (!got.ok) { latest.onNotice(got.message); return false; }
3153
+ // The new binding and its resolved cells share T12's single undo/persistence door.
3154
+ return await applyViewAnswer(base, target, viewMenu.origin, got.answer, binding);
3155
+ } catch {
3156
+ viewContext.current.onNotice("The view rows could not be refreshed.");
3157
+ return false;
3158
+ }
3159
+ }, [applyViewAnswer, viewMenu]);
3160
+
3161
+ useEffect(() => {
3162
+ viewMenuRef.current = null;
3163
+ setViewMenu(null);
3164
+ }, [storedWorkbook.id, storedTab.id]);
3165
+
3166
  /**
3167
  * ⭐⭐ W56-T04: ONE OPEN, ONE OPENING CELL, THROUGH THE SAME SELECTION DOOR.
3168
  * The background binding refresh replaces the workbook object after paint, so object identity
 
3273
  /** The note under the pointer, or null. `addr` is what keeps a hover from re-rendering per pixel. */
3274
  const [noteHover, setNoteHover] =
3275
  useState<{ addr: string; note: string; anchor: AnchorRect } | null>(null);
3276
+ const [refusalHover, setRefusalHover] =
3277
+ useState<{ addr: string; tabId: string; band: boolean; anchor: AnchorRect } | null>(null);
3278
+ const hoveredRefusal = refusalHover?.tabId === tab.id ? bindingRefusal(cells[refusalHover.addr]) : null;
3279
 
3280
  /** Show a tab by id, through the SAME wrap-around door Ctrl+PgUp uses. */
3281
  const goToSheet = useCallback((sheetId: string) => {
 
3351
  const onNoteHover = useCallback((args: GridMouseEventArgs, band: boolean) => {
3352
  if (args.kind !== "cell") {
3353
  setNoteHover((current) => (current ? null : current));
3354
+ // Both canvases report pointer moves; only the owning canvas may clear its tooltip.
3355
+ setRefusalHover((current) => (current?.band === band ? null : current));
3356
  return;
3357
  }
3358
  const location = band ? fromBand(args.location) : args.location;
3359
  const addr = addrAt(location[0], location[1]);
3360
+ const refusal = bindingRefusal(cells[addr]);
3361
+ setRefusalHover((current) => {
3362
+ if (!refusal) return current ? null : current;
3363
+ if (current?.addr === addr && current.tabId === tab.id) return current;
3364
+ return { addr, tabId: tab.id, band, anchor: rectAnchor(args.bounds) };
3365
+ });
3366
+ const note = refusal ? "" : cells[addr]?.note ?? "";
3367
  setNoteHover((current) => {
3368
  if (!note) return current ? null : current;
3369
  if (current && current.addr === addr) return current;
3370
  return { addr, note, anchor: rectAnchor(args.bounds) };
3371
  });
3372
+ }, [addrAt, cells, fromBand, tab.id]);
3373
 
3374
  /**
3375
  * ⭐⭐ Ctrl+1 — CONTRACT C1's "THE SAME IMPLEMENTATION, NOT TWO COPIES OF IT", TAKEN LITERALLY.
 
3752
  else commitWithRecalc(out.edits);
3753
  }, [commitWithRecalc, onCommit, onNotice, selectedAddrs, tab]);
3754
 
3755
+ /** One hide door for Home, a zero width in Format, and releasing a resize at zero. */
3756
+ const hideBands = useCallback((axis: "row" | "col", indices: number[]) => {
3757
+ const rows = axis === "row" ? withHidden(hiddenRows, indices, true) : hiddenRows;
3758
+ const hiddenTab = axis === "col"
3759
+ ? indices.reduce<SheetTab>((next, index) => hideColumnByWidth(next, index - 1), { ...tab, hiddenCols })
3760
+ : tab;
3761
+ const cols = axis === "col" ? hiddenTab.hiddenCols ?? [] : hiddenCols;
3762
+ // A sheet keeps at least one visible row and column, including when a width hides it.
3763
+ if (rows.length >= extent.rows || cols.length >= extent.cols) {
3764
+ onNotice("A sheet keeps at least one row and one column on screen, so these cannot all "
3765
+ + "be hidden.");
3766
+ return;
3767
+ }
3768
+ // The page changes only membership here. Its existing colWidths (or the implicit default)
3769
+ // remain intact; lastVisibleWidth reads them again when Unhide restores the column.
3770
+ if (!onHideBands) setHiddenLocal({ tabId: tab.id, rows, cols });
3771
+ onHideBands?.({ hiddenRows: rows, hiddenCols: cols });
3772
+ }, [extent.cols, extent.rows, hiddenCols, hiddenRows, onHideBands, onNotice, tab]);
3773
+
3774
  /** Hide the rows or the columns the selection covers, and remember them on the tab. */
3775
  const hideBand = useCallback((axis: "row" | "col") => {
3776
  const range = viewRange();
 
3788
  for (let c = Math.min(range.col0, range.col1); c <= Math.max(range.col0, range.col1);
3789
  c += 1) indices.push(realCol(c) + 1);
3790
  }
3791
+ hideBands(axis, indices);
3792
+ }, [hideBands, onNotice, realCol, realRow, viewRange]);
 
 
 
 
 
 
 
 
 
 
 
3793
 
3794
  /** Bring every hidden row and column back, and say so when there were none. */
3795
  const unhideAll = useCallback(() => {
 
3814
  return;
3815
  }
3816
  const width = Math.max(MIN_COL_WIDTH, Math.min(MAX_COL_WIDTH, Math.round(value)));
3817
+ if (width === 0) hideBand("col");
3818
+ else for (let c = Math.min(range.col0, range.col1); c <= Math.max(range.col0, range.col1);
3819
+ c += 1) onColumnWidth(realCol(c), width);
3820
  }
3821
  setAsk(null);
3822
+ }, [ask, hideBand, onColumnWidth, onNotice, realCol, setRowHeight, viewRange]);
3823
 
3824
  // ═══════════════════════════════════════════════════════════════════════════════════════════
3825
  // ⭐⭐ W54-T07 — AUTOFIT, AND THE TWO AXES ARE NOT SYMMETRICAL. SAY IT OUT LOUD.
 
4408
  if (!primary && !event.altKey && event.key.length === 1) {
4409
  const addr = addrAt(current.cell[0], current.cell[1]);
4410
  const cell = cellAt(tab, addr);
4411
+ const chrome = viewChromeRefusal(cell);
4412
+ if (chrome) { event.cancel(); event.preventDefault(); onNotice(chrome); return; }
4413
+ // Record values, including a leading '=', belong to Data's editor/write contract.
4414
+ if (cell?.viewChild) return;
4415
  const inBand = current.cell[1] < 0;
4416
  const viewCell: readonly [number, number] = inBand
4417
  ? [current.cell[0], current.cell[1] + bandRows] : current.cell;
 
4692
  // grids makes the two follow a drag together for free. A band grid given its own column list
4693
  // would tear away from the body while the mouse was still down.
4694
  // ══════════════════════════════════════════════════════════════════════════════════════════
4695
+ const onColumnResizeStart = useCallback(
4696
+ (_col: GridColumn, size: number, colIndex: number) => {
4697
+ const grid = bandRows > 0 ? bandGridRef.current : gridRef.current;
4698
+ const bounds = grid?.getBounds(colIndex, -1);
4699
+ if (!bounds) return;
4700
+ resizeGesture.current = {
4701
+ left: bounds.x, scale: bounds.width / size, width: size, committed: false,
4702
+ cols: selection?.columns.hasIndex(colIndex) ? selection.columns.toArray() : [colIndex],
4703
+ };
4704
+ },
4705
+ [bandRows, selection],
4706
+ );
4707
  const onColumnResize = useCallback(
4708
+ (_col: GridColumn, newSize: number, colIndex: number) => {
4709
+ const gesture = resizeGesture.current;
4710
+ setDragWidth({ cols: gesture?.cols ?? [colIndex], width: Math.max(1, gesture?.width ?? newSize) });
4711
+ },
4712
  [],
4713
  );
4714
  const onColumnResizeEnd = useCallback(
4715
  (_col: GridColumn, newSize: number, colIndex: number) => {
4716
  setDragWidth(null);
4717
+ const gesture = resizeGesture.current;
4718
+ if (gesture?.committed) return;
4719
+ const width = Math.max(MIN_COL_WIDTH, Math.min(MAX_COL_WIDTH,
4720
+ Math.round((gesture?.width ?? newSize) / zoom)));
4721
+ const cols = gesture?.cols ?? [colIndex];
4722
+ if (gesture) {
4723
+ gesture.committed = true;
4724
+ queueMicrotask(() => { resizeGesture.current = null; });
4725
+ }
4726
  // ⛔ TRANSLATED. `setColumnWidth` keys the width by COLUMN LETTER, so handing it a view
4727
  // index would remember D's width against C the moment a column is hidden.
4728
+ if (width === 0) hideBands("col", cols.map(col => realCol(col) + 1));
4729
+ else for (const col of cols) onColumnWidth(realCol(col), width);
4730
  },
4731
+ [hideBands, onColumnWidth, realCol, zoom],
4732
  );
4733
  const onHeaderClicked = useCallback((colIndex: number, args: { shiftKey: boolean }) => {
4734
  const from = args.shiftKey ? (selection?.current?.cell[0] ?? colIndex) : colIndex;
 
4763
  // makes it a controlled horizontal position. Verified in `data-editor.js`.
4764
  // ══════════════════════════════════════════════════════════════════════════════════════════
4765
  const [bandScrollX, setBandScrollX] = useState(0);
4766
+ /** The controlled position, readable from a listener that must not re-run on every scroll. */
4767
+ const bandScrollXRef = useRef(0);
4768
+ bandScrollXRef.current = bandScrollX;
4769
  /** Glide's own scroll coordinates. Chart anchors consume the same x/y and sub-cell transforms. */
4770
  const [chartViewport, setChartViewport] = useState({ x: 0, y: 0, tx: 0, ty: 0 });
4771
  const pageOverlayRef = useRef<HTMLDivElement>(null);
 
4795
  setBandScrollX(lockstepScrollX(columns.map((c) => c.width), frozenCols, range.x, tx));
4796
  }, [bandRows, columns, frozenCols]);
4797
 
4798
+ /**
4799
+ * W62-T01: wheel input over the frozen band scrolled it away from the body. The listener
4800
+ * must be native and non-passive so preventDefault works, unlike React's passive wheel
4801
+ * handler. Forward both axes to the body, which remains the only scroll driver.
4802
+ */
4803
+ useEffect(() => {
4804
+ const band = frozenBandRef.current;
4805
+ if (!band) return;
4806
+ const onWheel = (event: WheelEvent) => {
4807
+ // ⚠ Ctrl+wheel and Cmd+wheel are the BROWSER's zoom, not a scroll. Taking those would make
4808
+ // the frozen band the one region of the page a reader cannot zoom from.
4809
+ if (event.ctrlKey || event.metaKey) return;
4810
+ const body = [...(wrapRef.current?.querySelectorAll<HTMLElement>(
4811
+ ".sheet-grid-canvas .dvn-scroller",
4812
+ ) ?? [])].filter((scroller) => scroller.closest(".sheet-frozen-rows") === null);
4813
+ if (body.length === 0) return;
4814
+ const deltaX = event.deltaX || (event.shiftKey ? event.deltaY : 0);
4815
+ const deltaY = event.shiftKey ? 0 : event.deltaY;
4816
+ body.forEach((scroller) => {
4817
+ const unitX = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? scroller.clientWidth : 1;
4818
+ const unitY = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? scroller.clientHeight : 1;
4819
+ scroller.scrollLeft += deltaX * unitX;
4820
+ scroller.scrollTop += deltaY * unitY;
4821
+ });
4822
+ event.preventDefault();
4823
+ };
4824
+ band.addEventListener("wheel", onWheel, { passive: false });
4825
+
4826
+ // ⛔⛔ AND THE WHEEL IS NOT THE ONLY THING THAT CAN MOVE THE BAND, which a SCREENSHOT is what
4827
+ // caught. With 7 rows and 2 columns frozen, clicking a body cell and pressing Ctrl+Right put
4828
+ // the selection on GR7 - a row INSIDE THE BAND, so the band grid owns that selection, and
4829
+ // glide scrolled ITS OWN scroller to bring GR into view. The body never moved: the frame
4830
+ // showed the header and the frozen rows at columns GL..GR while the body under them still
4831
+ // drew C..I. Same defect as the wheel, a different input, and there will be others (a
4832
+ // programmatic `scrollTo`, a find that lands in the band, a future glide version).
4833
+ //
4834
+ // ⭐ SO THE RULE IS STATED ONCE, GENERALLY: the band's scroller is never the authority. Any
4835
+ // scroll it takes on its own is TRANSFERRED to the body, which is the only driver; the body's
4836
+ // own report then writes `scrollOffsetX` back and the two agree.
4837
+ // ⚠ NO LOOP, and the reason is the comparison: a scroll the BODY caused arrives here already
4838
+ // equal to the controlled value, so it transfers nothing. Only a position the body did not
4839
+ // ask for is ever pushed.
4840
+ const onBandScroll = () => {
4841
+ const scroller = band.querySelector<HTMLElement>(".dvn-scroller");
4842
+ const body = [...(wrapRef.current?.querySelectorAll<HTMLElement>(
4843
+ ".sheet-grid-canvas .dvn-scroller",
4844
+ ) ?? [])].filter((el) => el.closest(".sheet-frozen-rows") === null);
4845
+ if (!scroller || body.length === 0) return;
4846
+ if (Math.abs(scroller.scrollLeft - bandScrollXRef.current) < 1) return;
4847
+ const wanted = scroller.scrollLeft;
4848
+ body.forEach((el) => { el.scrollLeft = wanted; });
4849
+ };
4850
+ band.addEventListener("scroll", onBandScroll, { capture: true, passive: true });
4851
+ return () => {
4852
+ band.removeEventListener("wheel", onWheel);
4853
+ band.removeEventListener("scroll", onBandScroll, { capture: true } as EventListenerOptions);
4854
+ };
4855
+ }, [bandRows]);
4856
+
4857
  // W61-T10 / R12: measure the real glyphs, first at their natural width, then at the
4858
  // visible grid edge. The frozen band's handle remains the authority for its cell bounds.
4859
  const formulaBounds = formulaEdit
 
5155
  ctx.globalAlpha = 1;
5156
  ctx.restore();
5157
  };
5158
+ // Each damaged cell repaints only its own slice. The owner's box controls layout,
5159
+ // never the clip, so a later neighbour paint cannot erase or strand spilled glyphs.
5160
+ const textStyleAt = (ownerCol: number, ownerCell: Cell): CellStyle => {
5161
+ const ownerRule = ownerCol === col ? ruleStyle
5162
+ : ruleStyleAt(rules, realCol(ownerCol), realRow(row), ruleSubject(ownerCell),
5163
+ { get: cellValueGetter, sheet: tab.name });
5164
+ return ownerRule ? overlayRuleStyle<CellStyle>(ownerCell.style, ownerRule) : ownerCell.style ?? {};
5165
+ };
5166
+ const measureSpill: SpillMeasure = (text, ownerCell, ownerCol) => {
5167
+ const ownerStyle = textStyleAt(ownerCol, ownerCell);
5168
+ const size = (typeof ownerStyle.size === "number" ? fontPx(ownerStyle.size)
5169
+ : SIZE_PX[ownerStyle.size ?? "m"] ?? SIZE_PX.m) * zoom;
5170
+ ctx.save();
5171
+ ctx.font = `${ownerStyle.italic ? "italic " : ""}${ownerStyle.bold ? "600 " : ""}${size}px ${fontStack(ownerStyle.font, lightTheme.fontFamily)}`;
5172
+ const width = ctx.measureText(text).width / zoom;
5173
+ ctx.restore();
5174
+ return width;
5175
+ };
5176
+ const spill = spillOwnerAt(cells, addrAt, spillWidths, frozenCols, col, row, measureSpill);
5177
+ const spills = !spill && cellSpillsAt(cells, addrAt, spillWidths, frozenCols, col, row, measureSpill);
5178
+ const paintTextSpill = (): boolean => {
5179
+ const ownerCell = spill?.ownerCell ?? cell;
5180
+ if ((!spill && !spills) || !ownerCell) return false;
5181
+ const ownerCol = spill?.ownerCol ?? col;
5182
+ let x = rect.x;
5183
+ for (let c = ownerCol; c < col; c += 1) x -= columns[c].width;
5184
+ for (let c = col; c < ownerCol; c += 1) x += columns[c].width;
5185
+ const ownerBox = { ...rect, x, width: columns[ownerCol].width };
5186
+ ctx.save();
5187
+ ctx.beginPath();
5188
+ ctx.rect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2);
5189
+ ctx.clip();
5190
+ drawCellTextRun(ctx, ownerBox, ownerCell, textStyleAt(ownerCol, ownerCell), zoom);
5191
+ ctx.restore();
5192
+ return true;
5193
+ };
5194
+ // ⭐⭐ W62-T02 — THE SPILL FOR AN EMPTY CELL, AND IT IS A SEPARATE STATEMENT ABOVE THE EXIT
5195
+ // RATHER THAN A LINE INSIDE IT. `verify_grid_ux.py`'s [COPY PASTE MARQUEE] family (W52-T07)
5196
+ // pins the exit below BYTE FOR BYTE, because the whole of that ticket was a blank cell inside
5197
+ // a copied block still wearing its marquee. Reformatting it to make room here reds a family
5198
+ // belonging to another ticket for a line that changed no pixel, which is exactly the trap
5199
+ // this file's own D-642 note describes one screen up.
5200
+ //
5201
+ // ⚠ SO THE ORDER IS SPILL FIRST, DEFAULT RENDERER SECOND, AND IT IS SAFE FOR A STATED REASON
5202
+ // rather than by luck: glide's `drawTextCell` returns without touching the canvas when its
5203
+ // data is the empty string, which is every cell reaching this branch. The cell BACKGROUND is
5204
+ // painted by glide before `drawCell` is called at all, so nothing here can erase the run.
5205
+ if (!cell && !ruleStyle) paintTextSpill();
5206
  if (!cell && !ruleStyle) { drawContent(); paintRefBorder(); paintMarquee(); return; }
5207
 
5208
  const mark = cell ? MARK_STYLE[markOf(cell)] : undefined;
5209
+ const viewHeader = viewHeaderAt(cells, addrAt(col, row));
5210
+ const caret = validationOf(cell) !== null || viewHeader !== null;
5211
  const paintMark = () => {
5212
  // ⭐ W51-T18: THE DROPDOWN'S CARET RIDES HERE, so it is drawn in BOTH branches for
5213
  // the same reason R19's corner mark is: a validated cell that also carries a bold
5214
  // would silently lose its only affordance and read as an ordinary cell.
5215
  if (caret) {
5216
  ctx.save();
5217
+ if (viewHeader) {
5218
+ ctx.fillStyle = style?.fill ? tokenColour(style.fill, args.theme.bgCell) : args.theme.bgCell;
5219
+ ctx.fillRect(rect.x + rect.width - 24 * zoom, rect.y + 9 * zoom,
5220
+ 23 * zoom, Math.max(0, rect.height - 10 * zoom));
5221
+ }
5222
  ctx.strokeStyle = tokenColour("--lp-muted", "#6b7280");
5223
  ctx.lineWidth = 1.4;
5224
  ctx.lineCap = "round";
5225
+ const cx = rect.x + rect.width - 11 * (viewHeader ? zoom : 1);
5226
  const cy = rect.y + rect.height / 2 - 1;
5227
  ctx.beginPath();
5228
  ctx.moveTo(cx - 3.5, cy);
 
5256
  // condition as it was would compute a rule's fill and then hand the cell straight
5257
  // back to glide, which knows nothing about it: the dialog would list a rule that
5258
  // paints nothing. The `|| ruleStyle` is that whole bug, in two words.
5259
+ const baseStyle = ruleStyle ? overlayRuleStyle<CellStyle>(cell?.style, ruleStyle)
5260
  : cell?.style;
5261
+ // Give even an unstyled refusal the shared text routine and the cell's own spacing.
5262
+ const style = bindingRefusal(cell) ? { ...baseStyle, color: "--lp-red-deep" } : baseStyle;
5263
  if ((!stylePaints(style) && !ruleStyle) || !style) {
5264
  // ⭐ `drawContent()` IS the default renderer, and it must run BEFORE the mark so
5265
  // the mark sits on top of the value rather than under it.
5266
+ if (!paintTextSpill()) drawContent();
5267
  // ⭐ W54-T14 / LANE B — the link underline and the note corner, in BOTH branches for the
5268
  // same reason R19's own mark is in both: an attachment on a bold cell would otherwise
5269
  // vanish, and a cell that shows nothing of what it carries carries it invisibly.
 
5275
  return;
5276
  }
5277
 
 
5278
  ctx.save();
5279
 
5280
  // 1. THE BACKGROUND, FIRST AND INSET BY A PIXEL so the grid's own hairlines survive.
 
5296
  ctx.restore();
5297
  }
5298
 
5299
+ // 2. THE TEXT, clipped to this cell, including any run arriving from a neighbour.
 
5300
  ctx.beginPath();
5301
  ctx.rect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2);
5302
  ctx.clip();
5303
 
5304
+ if (!paintTextSpill()) drawCellTextRun(ctx, rect, cell, style, zoom);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5305
 
5306
  ctx.restore();
5307
 
 
5324
  // leg reads it as exactly that. Deleting it as dead reds a gate in another ticket's
5325
  // territory for a line that was never wrong, only no longer load bearing.
5326
  return true;
5327
+ }, [addrAt, cellValueGetter, cells, columns, copyMarquee, formulaPointCells, formulaRefCells,
5328
+ frozenCols, pasteHighlight, realCol, realRow, rules, spillWidths, tab.name, zoom]);
5329
 
5330
  /**
5331
  * ⭐ THE BAND'S PAINT: the SAME callback, told which row it is looking at. `fromBand` is not
 
5508
  onTabVisibility, realCol, realRow, rowHeight, tab, viewRange, visCols, widths, workbook, wrapHeights, writeCharts]);
5509
 
5510
  return (
5511
+ <div className="sheet-grid-wrap" ref={wrapRef} onMouseLeave={() => setRefusalHover(null)}
5512
+ onScrollCapture={() => setRefusalHover(null)}>
5513
  {/* ⭐ THE HOME RIBBON, THEN THE FORMULA BAR, THEN THE CELLS. That order is instruction 10
5514
  said in three lines of JSX, and it is why the bar arrives as a SLOT: it has to sit under
5515
  a ribbon that lives inside this component. The ribbon is given the ANCHOR cell's style,
 
5529
  {/* ⛔ NOTHING WHEN THERE IS NOTHING. An empty wrapper here would take padding and a border
5530
  from whatever rule it matched, and every pixel above the grid is a pixel the canvas does
5531
  not get. `.sheet-fx` already carries `flex: 0 0 auto`, so the bar is rendered bare. */}
5532
+ {isValidElement<FormulaBarProps>(formulaBar)
5533
+ && (isViewReserved(formulaBar.props.addr) || cells[formulaBar.props.addr]?.viewChild
5534
+ || viewChromeRefusal(cells[formulaBar.props.addr]))
5535
+ ? cloneElement(formulaBar, { onCommit: commitWithRecalc,
5536
+ disabled: formulaBar.props.disabled || isViewReserved(formulaBar.props.addr)
5537
+ || !!viewChromeRefusal(cells[formulaBar.props.addr]) })
5538
+ : formulaBar}
5539
 
5540
  <div
5541
  className="sheet-grid-canvas"
 
5572
  {bandRows > 0 && (
5573
  <div
5574
  className="sheet-frozen-rows"
5575
+ ref={frozenBandRef}
5576
  data-gridlines={tab.view?.gridlines !== false}
5577
  style={{ height: HEADER_HEIGHT + frozenBandHeight }}
5578
  >
 
5585
  freezeColumns={frozenCols}
5586
  onColumnResize={onColumnResize}
5587
  onColumnResizeEnd={onColumnResizeEnd}
5588
+ onColumnResizeStart={onColumnResizeStart}
5589
+ minColumnWidth={MIN_COL_WIDTH * zoom}
5590
+ maxColumnWidth={MAX_COL_WIDTH * zoom}
5591
  onHeaderClicked={onHeaderClicked}
5592
  onHeaderContextMenu={onHeaderContextMenu}
5593
  theme={gridTheme}
 
5614
  const shifted = fromBand(item);
5615
  const addr = addrAt(shifted[0], shifted[1]);
5616
  const cell = cellAt(tab, addr);
5617
+ const chrome = viewChromeRefusal(cell);
5618
+ if (chrome) { onNotice(chrome); return; }
5619
  if (cell?.kind === "bound") { onEdit(addr, cell); return; }
5620
  // ⭐ W52-T06: a formula cell's OWN editor, opened at the row this band grid draws
5621
  // (its own zero-based `item`, NOT `shifted` -- `bandGridRef.getBounds` is that
 
5645
  return;
5646
  }
5647
  const clicked = addrAt(shifted[0], shifted[1]);
5648
+ if (openViewHeader(shifted, args)) return;
5649
  if (validationOf(cellAt(tab, clicked))) {
5650
  setAnchor(null);
5651
  setDropdown({ addr: clicked, anchor: rectAnchor(args.bounds), query: "" });
 
5699
  // it is stale, so only the END writes.
5700
  onColumnResize={onColumnResize}
5701
  onColumnResizeEnd={onColumnResizeEnd}
5702
+ onColumnResizeStart={onColumnResizeStart}
5703
+ minColumnWidth={MIN_COL_WIDTH * zoom}
5704
+ maxColumnWidth={MAX_COL_WIDTH * zoom}
5705
  theme={gridTheme}
5706
  // ⛔ THE COLUMN-H FIX. See the block comment at the head of this file: without an
5707
  // explicit width glide sizes its wrapper to the full 3,170 px of all 26 columns, and
 
5767
  onCellActivated={(item: Item) => {
5768
  const addr = addrAt(item[0], item[1]);
5769
  const cell = cellAt(tab, addr);
5770
+ const chrome = viewChromeRefusal(cell);
5771
+ if (chrome) { onNotice(chrome); return; }
5772
  if (cell?.kind === "bound") { onEdit(addr, cell); return; }
5773
  if (cell?.kind === "formula") {
5774
  openFormulaEditor(addr, editableText(cell), editableText(cell).length, item, false);
 
5812
  // virtualised cell actually sits on screen; the action bar yields to it, because two
5813
  // surfaces over one cell is one too many.
5814
  const clicked = addrAt(item[0], item[1]);
5815
+ if (openViewHeader(item, args)) return;
5816
  if (validationOf(cellAt(tab, clicked))) {
5817
  setAnchor(null);
5818
  setDropdown({ addr: clicked, anchor: rectAnchor(args.bounds), query: "" });
 
5920
  into it, so the anchors must stay INSIDE `.sheet-grid-canvas` (W50-T19) and the
5921
  geometry they use must stay the grid's own. Both facts, and every measurement behind
5922
  them, travelled with the code into `SheetChartLayer.tsx`. */}
5923
+ <SheetViewLayer workbookId={workbook.id} tab={tab} busy={busy}
5924
+ visCols={visCols} visRows={allVisRows} columns={columns} columnX={columnX}
5925
+ rowHeightAt={allRowHeightAt} frozenCols={frozenCols} bandRows={bandRows}
5926
+ headerHeight={HEADER_HEIGHT} viewport={chartViewport}
5927
+ onResize={resizeViewBlock} onNotice={onNotice} onUndo={onUndo} onRedo={onRedo} />
5928
  <SheetChartLayer
5929
  charts={charts}
5930
  cells={cells}
 
5965
  inventing a z-index. `cg-pop` / `cg-type-list` / `cg-type-row` are declared UNSCOPED in
5966
  `index.css`, which is what lets a ticket that may not touch a stylesheet still ship a
5967
  styled panel; `FormulaBar.tsx` uses exactly this trio one component away. */}
5968
+ {viewMenu && <ViewHeaderDropdown key={`${viewMenu.origin}/${viewMenu.field}`}
5969
+ menu={viewMenu} onApply={applyViewHeader} onClose={closeViewHeader} />}
5970
  {menu && (
5971
  <AnchoredOverlay
5972
  anchor={menu.anchor}
 
6487
  {/* ⭐ W54-T14 / LANE B — WHAT A NOTE SHOWS ON HOVER. It originates at its own cell rather
6488
  than at a trigger in the chrome (DESIGN.md 4), it takes no focus and no pointer, and it
6489
  is dismissed by moving off the cell, by an outside press or by Escape through the kit. */}
6490
+ {refusalHover && hoveredRefusal && (
6491
+ <AnchoredOverlay
6492
+ anchor={refusalHover.anchor}
6493
+ className="sheet-note-bubble"
6494
+ role="tooltip"
6495
+ ariaLabel="Cell binding error"
6496
+ initialFocus="none"
6497
+ restoreFocus={false}
6498
+ onDismiss={() => setRefusalHover(null)}
6499
+ >
6500
+ <p className="sheet-note-bubble-text">{hoveredRefusal.message}</p>
6501
+ </AnchoredOverlay>
6502
+ )}
6503
  {noteHover && (
6504
  <NoteBubble
6505
  anchor={noteHover.anchor}
 
6508
  />
6509
  )}
6510
 
6511
+ {selected && anchor && !painter && !selected.cell?.viewChild && !viewChromeRefusal(selected.cell) && (
6512
  <CellActionBar
6513
  anchor={anchor}
6514
  drill={drillAffordance(selected.cell)}
web/src/sheet/SheetPage.tsx CHANGED
@@ -91,7 +91,7 @@ import {
91
  setTabVisibility, splitAddress, structureRefusal, tabCellCount, undoHistory, withCells,
92
  } from "./sheetState";
93
  import type { SheetHistory, StructureOp } from "./sheetState";
94
- import { bindingDisplay, emptyIndex, sheetExtent, withBindingDisplay } from "./types";
95
  import type { BindingDisplay, Cell, IndexRepair, SheetChartSpec, SheetPrintSettings, SheetRule, SheetTab, SheetTabView, Workbook } from "./types";
96
  import { ChartWorkbookContext } from "./ChartDialog";
97
  import { SheetExportContext } from "./Ribbon";
@@ -104,6 +104,26 @@ import { bindingOnDrag, BINDING_ENDING_STEP, BINDING_PERIOD_STEP } from "./types
104
  import type { SavedViewShadow } from "./bindingRefs";
105
  import { bindingStepValues } from "./bindingRefs";
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  /**
108
  * ⭐⭐ W51-T08 / CONTRACT C1 — THE FOUR SEAM PROPS, TYPED HERE BECAUSE `SheetGrid.tsx` IS LANE E'S.
109
  *
@@ -377,6 +397,9 @@ export default function SheetPage() {
377
  * `emptyIndex()` stays assignable because both members are optional.
378
  */
379
  const [index, setIndex] = useState<SheetIndex>(emptyIndex);
 
 
 
380
  /** The address whose rows are open, or "" for none. R11: the popup belongs to ONE cell. */
381
  const [drillAt, setDrillAt] = useState("");
382
  /**
@@ -901,7 +924,18 @@ export default function SheetPage() {
901
  // Read the whole hash, as the shell does: workbook changes keep the same route key.
902
  useEffect(() => {
903
  addressMountedRef.current = true;
904
- const onHashChange = () => setSheetHash(window.location.hash);
 
 
 
 
 
 
 
 
 
 
 
905
  window.addEventListener("hashchange", onHashChange);
906
  onHashChange();
907
  return () => {
@@ -2293,6 +2327,19 @@ export default function SheetPage() {
2293
  lastWorkbookId, prepareWorkbookOpen, refreshIndex, refreshOpenedWorkbook, discardMissingWorkbook,
2294
  rememberOpenWorkbook]);
2295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2296
  /** R2's create door: made and OPENED in one act, with no name step in between. */
2297
  const createAndOpen = useCallback(async () => {
2298
  if (workbookTransitionRef.current) return;
@@ -2440,6 +2487,7 @@ export default function SheetPage() {
2440
  * cycle, an over deep chain) re-reads instead, so the rail never keeps a tree the store refused.
2441
  */
2442
  const saveStrata = useCallback(async (next: RailStrata) => {
 
2443
  setNotice("");
2444
  setIndex((prev) => ({
2445
  ...prev,
@@ -2457,19 +2505,38 @@ export default function SheetPage() {
2457
  * absent field on some paths and as a null on others, and the server's guard would then have
2458
  * to read two spellings of "I did not send one".
2459
  */
2460
- const saved = await writeIndex(
2461
- indexRev === undefined ? next : { ...next, rev: indexRev },
2462
- );
2463
- if (!saved.ok) {
2464
- const rows = await readIndex();
2465
- if (rows.ok) setIndex(rows.value);
2466
- setNotice(saved.message);
2467
- return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2468
  }
2469
- setIndex(saved.value);
2470
- const sentence = repairSentence(saved.value.repairs);
2471
- if (sentence) setNotice(sentence);
2472
- }, [indexRev]);
2473
 
2474
  // ═══════════════════════════════════════════════════════════════════════════════════════════
2475
  // ⭐⭐ W51-T09 (owner instruction 2, ruling R12) — "ASK ABOUT THIS DATA", AND WHAT IT IS ABOUT
@@ -2722,6 +2789,7 @@ export default function SheetPage() {
2722
  itemFolders={index.itemFolders}
2723
  starred={index.starred}
2724
  activeId={book?.id ?? ""}
 
2725
  onOpen={openWorkbook}
2726
  onCreateWorkbook={createAndOpen}
2727
  onRenameWorkbook={renameWorkbook}
 
91
  setTabVisibility, splitAddress, structureRefusal, tabCellCount, undoHistory, withCells,
92
  } from "./sheetState";
93
  import type { SheetHistory, StructureOp } from "./sheetState";
94
+ import { bindingDisplay, emptyIndex, ROOT_FOLDER_ID, sheetExtent, withBindingDisplay } from "./types";
95
  import type { BindingDisplay, Cell, IndexRepair, SheetChartSpec, SheetPrintSettings, SheetRule, SheetTab, SheetTabView, Workbook } from "./types";
96
  import { ChartWorkbookContext } from "./ChartDialog";
97
  import { SheetExportContext } from "./Ribbon";
 
104
  import type { SavedViewShadow } from "./bindingRefs";
105
  import { bindingStepValues } from "./bindingRefs";
106
 
107
+ // Twin in HomePage.tsx; this ticket's file fence keeps the timeout local to each chunk.
108
+ const FOLDER_WRITE_TIMEOUT_MS = 20000;
109
+
110
+ function readSheetFolder(hash: string): string | undefined {
111
+ return hash.startsWith("#/sheet?")
112
+ ? new URLSearchParams(hash.slice(hash.indexOf("?") + 1)).get("folder") || undefined
113
+ : undefined;
114
+ }
115
+
116
+ function reattachSheetFolder(folder: string | undefined): string {
117
+ const hash = window.location.hash;
118
+ if (!folder || folder === ROOT_FOLDER_ID || !hash.startsWith("#/sheet?")
119
+ || new URLSearchParams(hash.slice(hash.indexOf("?") + 1)).has("folder")) return hash;
120
+ // The address module is another fence's file; its builder drops unknown params.
121
+ // Reattach after its writer, without a second hashchange or an extra Back entry.
122
+ const next = hash + "&folder=" + encodeURIComponent(folder);
123
+ window.history.replaceState(window.history.state, "", next);
124
+ return next;
125
+ }
126
+
127
  /**
128
  * ⭐⭐ W51-T08 / CONTRACT C1 — THE FOUR SEAM PROPS, TYPED HERE BECAUSE `SheetGrid.tsx` IS LANE E'S.
129
  *
 
397
  * `emptyIndex()` stays assignable because both members are optional.
398
  */
399
  const [index, setIndex] = useState<SheetIndex>(emptyIndex);
400
+ const folderPlacementsRef = useRef(index.itemFolders);
401
+ folderPlacementsRef.current = index.itemFolders;
402
+ const folderHashRef = useRef(sheetHash);
403
  /** The address whose rows are open, or "" for none. R11: the popup belongs to ONE cell. */
404
  const [drillAt, setDrillAt] = useState("");
405
  /**
 
924
  // Read the whole hash, as the shell does: workbook changes keep the same route key.
925
  useEffect(() => {
926
  addressMountedRef.current = true;
927
+ const onHashChange = () => {
928
+ const hash = window.location.hash;
929
+ const workbookId = readSheetAddress(hash)?.wb;
930
+ const previous = folderHashRef.current;
931
+ const folder = readSheetFolder(hash)
932
+ ?? (workbookId && workbookId === readSheetAddress(previous)?.wb ? readSheetFolder(previous) : undefined)
933
+ ?? (workbookId ? folderPlacementsRef.current[workbookId] : undefined);
934
+ const next = reattachSheetFolder(folder);
935
+ folderHashRef.current = next;
936
+ if (handledSheetHashRef.current === hash) handledSheetHashRef.current = next;
937
+ setSheetHash(next);
938
+ };
939
  window.addEventListener("hashchange", onHashChange);
940
  onHashChange();
941
  return () => {
 
2327
  lastWorkbookId, prepareWorkbookOpen, refreshIndex, refreshOpenedWorkbook, discardMissingWorkbook,
2328
  rememberOpenWorkbook]);
2329
 
2330
+ // The workbook can open before its index arrives. Enrich only after the open has settled,
2331
+ // so changing the hash cannot invalidate an in-flight workbook read's address guard.
2332
+ useEffect(() => {
2333
+ if (opening || workbookTransitionRef.current || index.rev === undefined
2334
+ || !book || readSheetAddress(sheetHash)?.wb !== book.id
2335
+ || window.location.hash !== sheetHash) return;
2336
+ const next = reattachSheetFolder(readSheetFolder(sheetHash) ?? index.itemFolders[book.id]);
2337
+ folderHashRef.current = next;
2338
+ if (next === sheetHash) return;
2339
+ if (handledSheetHashRef.current === sheetHash) handledSheetHashRef.current = next;
2340
+ setSheetHash(next);
2341
+ }, [book, index, opening, sheetHash]);
2342
+
2343
  /** R2's create door: made and OPENED in one act, with no name step in between. */
2344
  const createAndOpen = useCallback(async () => {
2345
  if (workbookTransitionRef.current) return;
 
2487
  * cycle, an over deep chain) re-reads instead, so the rail never keeps a tree the store refused.
2488
  */
2489
  const saveStrata = useCallback(async (next: RailStrata) => {
2490
+ const previousIndex = index;
2491
  setNotice("");
2492
  setIndex((prev) => ({
2493
  ...prev,
 
2505
  * absent field on some paths and as a null on others, and the server's guard would then have
2506
  * to read two spellings of "I did not send one".
2507
  */
2508
+ let timeout: ReturnType<typeof setTimeout> | undefined;
2509
+ const timeoutError = new Error("The folder move timed out. Your items were put back.");
2510
+ try {
2511
+ const saved = await Promise.race([
2512
+ writeIndex(indexRev === undefined ? next : { ...next, rev: indexRev }),
2513
+ new Promise<never>((_, reject) => {
2514
+ timeout = setTimeout(() => reject(timeoutError), FOLDER_WRITE_TIMEOUT_MS);
2515
+ }),
2516
+ ]);
2517
+ if (!saved.ok) {
2518
+ setIndex(previousIndex);
2519
+ setNotice(saved.message);
2520
+ clearTimeout(timeout);
2521
+ const rows = await Promise.race([
2522
+ readIndex(),
2523
+ new Promise<never>((_, reject) => {
2524
+ timeout = setTimeout(() => reject(timeoutError), FOLDER_WRITE_TIMEOUT_MS);
2525
+ }),
2526
+ ]);
2527
+ if (rows.ok) setIndex(rows.value);
2528
+ return;
2529
+ }
2530
+ setIndex(saved.value);
2531
+ const sentence = repairSentence(saved.value.repairs);
2532
+ if (sentence) setNotice(sentence);
2533
+ } catch (error) {
2534
+ setIndex(previousIndex);
2535
+ setNotice(error instanceof Error ? error.message : "Folders could not be saved. Reload folders to retry.");
2536
+ } finally {
2537
+ clearTimeout(timeout);
2538
  }
2539
+ }, [index, indexRev]);
 
 
 
2540
 
2541
  // ═══════════════════════════════════════════════════════════════════════════════════════════
2542
  // ⭐⭐ W51-T09 (owner instruction 2, ruling R12) — "ASK ABOUT THIS DATA", AND WHAT IT IS ABOUT
 
2789
  itemFolders={index.itemFolders}
2790
  starred={index.starred}
2791
  activeId={book?.id ?? ""}
2792
+ revealFolder={readSheetFolder(sheetHash)}
2793
  onOpen={openWorkbook}
2794
  onCreateWorkbook={createAndOpen}
2795
  onRenameWorkbook={renameWorkbook}
web/src/sheet/SheetRail.tsx CHANGED
@@ -35,7 +35,7 @@
35
  // indents a NESTED row, and a path-replacing level has no nested rows to indent.
36
  // ---------------------------------------------------------------------------
37
 
38
- import { useEffect, useMemo, useState } from "react";
39
  import type { DragEvent as ReactDragEvent } from "react";
40
  import "../styles/wave46/rail-select.css";
41
  import "../styles/wave52/parity.css";
@@ -46,6 +46,7 @@ import "../styles/wave53/sheet-rail.css";
46
  import "../styles/wave59/templates.css";
47
  import "../styles/wave61/rails.css";
48
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
 
49
  import { FolderMark, MenuLabel } from "../customer-grid/icons";
50
  import { SHARE_SHAPE, SHEET_SHAPE } from "../customer-grid/iconShapes";
51
  import { StarIcon } from "../ui/icons";
@@ -89,6 +90,7 @@ export interface SheetRailProps {
89
  itemFolders: Record<string, string>;
90
  starred: readonly string[];
91
  activeId: string;
 
92
  onOpen: (id: string) => void;
93
  onCreateWorkbook: () => void;
94
  onRenameWorkbook: (id: string, name: string) => void;
@@ -280,7 +282,7 @@ const newFolderId = () =>
280
  * ⚠ A NAME IS COLLAPSED, NOT MERELY TRIMMED. `core/sheets.py` collapses runs of whitespace on
281
  * the way in, so a client that only trimmed would show one name and store another.
282
  */
283
- const cleanName = (raw: string) => raw.trim().replace(/\s+/g, " ").slice(0, 80);
284
 
285
  export default function SheetRail({
286
  importRequest,
@@ -292,6 +294,7 @@ export default function SheetRail({
292
  itemFolders,
293
  starred,
294
  activeId,
 
295
  onOpen: requestOpen,
296
  onCreateWorkbook,
297
  onRenameWorkbook,
@@ -326,7 +329,12 @@ export default function SheetRail({
326
  return next;
327
  });
328
  /** The folder whose contents are on screen, or null for the top level. */
329
- const [at, setAt] = useState<string | null>(() => readLastFolder());
 
 
 
 
 
330
  /** Restored folders start after root, so Back reaches root and Forward returns here. */
331
  const [history, setHistory] = useState<(string | null)[]>(
332
  () => at === null ? [null] : [null, at],
@@ -401,12 +409,27 @@ export default function SheetRail({
401
 
402
  /** A folder deleted here or belonging to another tenant silently restores the top level. */
403
  useEffect(() => {
404
- if (loading || at === null || byId[at]) return;
405
  setAt(null);
406
  setHistory([null]);
407
  setStep(0);
408
  writeLastFolder(null);
409
- }, [at, byId, loading]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410
 
411
  const strata = (): RailStrata => ({
412
  folders: folders.map((f) => ({ ...f })),
@@ -640,14 +663,13 @@ export default function SheetRail({
640
  }
641
  };
642
 
643
- const createFolder = () => {
644
  if (!indexKnown) return;
645
- const clean = cleanName(folderName);
646
  if (!clean) return;
647
  const next = strata();
648
  next.folders = [...next.folders, { id: newFolderId(), name: clean, parent: at }];
649
  onStrataChange(next);
650
- setFolderName("");
651
  setNamingFolder(false);
652
  setCreateAt(null);
653
  };
@@ -1011,38 +1033,25 @@ export default function SheetRail({
1011
  <p className="cg-railsel-left" role="status" title={railNotice}>{railNotice}</p>
1012
  ) : null}
1013
 
1014
- {createAt ? (
 
 
 
 
 
 
 
 
 
 
1015
  <AnchoredOverlay
1016
  anchor={createAt}
1017
  className="cg-view-menu"
1018
- role={namingFolder ? "dialog" : "menu"}
1019
- ariaLabel={namingFolder ? "New folder" : "Create new"}
1020
  placement="right-start"
1021
  onDismiss={() => { setCreateAt(null); setNamingFolder(false); }}
1022
  >
1023
- {namingFolder ? (
1024
- <form
1025
- className="cg-data-folder-rename"
1026
- onSubmit={(event) => { event.preventDefault(); createFolder(); }}
1027
- >
1028
- <input
1029
- className="cg-input"
1030
- autoFocus
1031
- value={folderName}
1032
- maxLength={40}
1033
- aria-label="Folder name"
1034
- disabled={!indexKnown}
1035
- title={indexPendingReason}
1036
- style={indexPendingStyle}
1037
- onChange={(event) => setFolderName(event.currentTarget.value)}
1038
- />
1039
- <button type="submit" className="cg-btn cg-btn--primary"
1040
- disabled={!indexKnown || !folderName.trim()} title={indexPendingReason}>
1041
- Save
1042
- </button>
1043
- </form>
1044
- ) : (
1045
- <>
1046
  {/* ⛔ A WORKBOOK IS MADE AND OPENED IN ONE ACT, with no name step. The page shows
1047
  the new workbook the moment the server answers, which is the done-when clause,
1048
  and renaming it is one item down in its own `…` menu. */}
@@ -1064,7 +1073,7 @@ export default function SheetRail({
1064
  disabled={!indexKnown}
1065
  title={indexPendingReason}
1066
  style={indexPendingStyle}
1067
- onClick={() => { setFolderName(""); setNamingFolder(true); }}
1068
  >
1069
  <MenuLabel icon={<FolderMark size={16} />} text="Folder" />
1070
  </button>
@@ -1087,8 +1096,6 @@ export default function SheetRail({
1087
  >
1088
  <MenuLabel icon={<SheetMark size={16} />} text="From a template" />
1089
  </button>
1090
- </>
1091
- )}
1092
  </AnchoredOverlay>
1093
  ) : null}
1094
 
@@ -1117,7 +1124,7 @@ export default function SheetRail({
1117
  className="cg-input"
1118
  autoFocus
1119
  value={folderName}
1120
- maxLength={80}
1121
  aria-label={menu.kind === "folder" ? "Folder name" : "Workbook name"}
1122
  disabled={menu.kind === "folder" && !indexKnown}
1123
  title={menu.kind === "folder" ? indexPendingReason : undefined}
 
35
  // indents a NESTED row, and a path-replacing level has no nested rows to indent.
36
  // ---------------------------------------------------------------------------
37
 
38
+ import { useEffect, useMemo, useRef, useState } from "react";
39
  import type { DragEvent as ReactDragEvent } from "react";
40
  import "../styles/wave46/rail-select.css";
41
  import "../styles/wave52/parity.css";
 
46
  import "../styles/wave59/templates.css";
47
  import "../styles/wave61/rails.css";
48
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
49
+ import FolderNameDialog, { FOLDER_NAME_MAX } from "../home/FolderNameDialog";
50
  import { FolderMark, MenuLabel } from "../customer-grid/icons";
51
  import { SHARE_SHAPE, SHEET_SHAPE } from "../customer-grid/iconShapes";
52
  import { StarIcon } from "../ui/icons";
 
90
  itemFolders: Record<string, string>;
91
  starred: readonly string[];
92
  activeId: string;
93
+ revealFolder?: string;
94
  onOpen: (id: string) => void;
95
  onCreateWorkbook: () => void;
96
  onRenameWorkbook: (id: string, name: string) => void;
 
282
  * ⚠ A NAME IS COLLAPSED, NOT MERELY TRIMMED. `core/sheets.py` collapses runs of whitespace on
283
  * the way in, so a client that only trimmed would show one name and store another.
284
  */
285
+ const cleanName = (raw: string) => raw.trim().replace(/\s+/g, " ").slice(0, FOLDER_NAME_MAX);
286
 
287
  export default function SheetRail({
288
  importRequest,
 
294
  itemFolders,
295
  starred,
296
  activeId,
297
+ revealFolder,
298
  onOpen: requestOpen,
299
  onCreateWorkbook,
300
  onRenameWorkbook,
 
329
  return next;
330
  });
331
  /** The folder whose contents are on screen, or null for the top level. */
332
+ const openedFolder = (): string | null => {
333
+ const folder = revealFolder ?? itemFolders[activeId] ?? (activeId ? null : readLastFolder());
334
+ return folder === ROOT_FOLDER_ID ? null : folder;
335
+ };
336
+ const [at, setAt] = useState<string | null>(() => openedFolder());
337
+ const lastReveal = useRef<{ activeId: string; revealFolder?: string } | null>(null);
338
  /** Restored folders start after root, so Back reaches root and Forward returns here. */
339
  const [history, setHistory] = useState<(string | null)[]>(
340
  () => at === null ? [null] : [null, at],
 
409
 
410
  /** A folder deleted here or belonging to another tenant silently restores the top level. */
411
  useEffect(() => {
412
+ if (loading || !indexKnown || at === null || byId[at]) return;
413
  setAt(null);
414
  setHistory([null]);
415
  setStep(0);
416
  writeLastFolder(null);
417
+ }, [at, byId, loading, indexKnown]);
418
+
419
+ // Wait for placement metadata, then reveal each address choice once. Rail browsing stays put.
420
+ useEffect(() => {
421
+ if (loading || !indexKnown) return;
422
+ if (lastReveal.current?.activeId === activeId
423
+ && lastReveal.current?.revealFolder === revealFolder) return;
424
+ lastReveal.current = { activeId, revealFolder };
425
+ const folder = openedFolder();
426
+ const next = folder && byId[folder] ? folder : null;
427
+ setAt(next);
428
+ setHistory(next === null ? [null] : [null, next]);
429
+ setStep(next === null ? 0 : 1);
430
+ setQuery("");
431
+ writeLastFolder(next);
432
+ }, [activeId, revealFolder, itemFolders, byId, loading, indexKnown]);
433
 
434
  const strata = (): RailStrata => ({
435
  folders: folders.map((f) => ({ ...f })),
 
663
  }
664
  };
665
 
666
+ const createFolder = (name: string) => {
667
  if (!indexKnown) return;
668
+ const clean = cleanName(name);
669
  if (!clean) return;
670
  const next = strata();
671
  next.folders = [...next.folders, { id: newFolderId(), name: clean, parent: at }];
672
  onStrataChange(next);
 
673
  setNamingFolder(false);
674
  setCreateAt(null);
675
  };
 
1033
  <p className="cg-railsel-left" role="status" title={railNotice}>{railNotice}</p>
1034
  ) : null}
1035
 
1036
+ {createAt && namingFolder ? (
1037
+ <FolderNameDialog
1038
+ anchor={createAt}
1039
+ title="New folder"
1040
+ siblingNames={folders.filter((folder) => (folder.parent ?? null) === at).map((folder) => folder.name)}
1041
+ disabled={!indexKnown}
1042
+ disabledReason={indexPendingReason}
1043
+ onSubmit={createFolder}
1044
+ onDismiss={() => { setCreateAt(null); setNamingFolder(false); }}
1045
+ />
1046
+ ) : createAt ? (
1047
  <AnchoredOverlay
1048
  anchor={createAt}
1049
  className="cg-view-menu"
1050
+ role="menu"
1051
+ ariaLabel="Create new"
1052
  placement="right-start"
1053
  onDismiss={() => { setCreateAt(null); setNamingFolder(false); }}
1054
  >
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1055
  {/* ⛔ A WORKBOOK IS MADE AND OPENED IN ONE ACT, with no name step. The page shows
1056
  the new workbook the moment the server answers, which is the done-when clause,
1057
  and renaming it is one item down in its own `…` menu. */}
 
1073
  disabled={!indexKnown}
1074
  title={indexPendingReason}
1075
  style={indexPendingStyle}
1076
+ onClick={() => { setNamingFolder(true); }}
1077
  >
1078
  <MenuLabel icon={<FolderMark size={16} />} text="Folder" />
1079
  </button>
 
1096
  >
1097
  <MenuLabel icon={<SheetMark size={16} />} text="From a template" />
1098
  </button>
 
 
1099
  </AnchoredOverlay>
1100
  ) : null}
1101
 
 
1124
  className="cg-input"
1125
  autoFocus
1126
  value={folderName}
1127
+ maxLength={FOLDER_NAME_MAX}
1128
  aria-label={menu.kind === "folder" ? "Folder name" : "Workbook name"}
1129
  disabled={menu.kind === "folder" && !indexKnown}
1130
  title={menu.kind === "folder" ? indexPendingReason : undefined}
web/src/sheet/SheetViewLayer.tsx ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
2
+ import type { CSSProperties } from "react";
3
+ import { CatalogApplicationView } from "../customer-grid/CatalogView";
4
+ import { GalleryView, TimelineView } from "../customer-grid/GalleryTimelineViews";
5
+ import { MapView } from "../customer-grid/MapView";
6
+ import { SwipeView } from "../customer-grid/SwipeView";
7
+ import { CalendarView, KanbanView, ListView } from "../customer-grid/viewModes";
8
+ import type { Field, Row } from "../customer-grid/types";
9
+ import { splitAddress, chartPaneProjections, lockstepScrollX } from "./sheetState";
10
+ import { fetchViewRows, showingLine, viewBlockGeometry } from "./viewPlacement";
11
+ import type { SheetTab, ViewBinding, ViewRowsAnswer } from "./types";
12
+ import { viewBlockSize } from "./types";
13
+ // CustomerGrid normally supplies the bounded scroller used by Gallery and Timeline.
14
+ import "../styles/wave50/grid.css";
15
+ import "../styles/wave55/apps.css";
16
+
17
+ interface SheetViewLayerProps {
18
+ workbookId: string;
19
+ tab: SheetTab;
20
+ busy: boolean;
21
+ visCols: number[];
22
+ visRows: number[];
23
+ columns: readonly { width: number }[];
24
+ columnX: (index: number) => number;
25
+ rowHeightAt: (index: number) => number;
26
+ frozenCols: number;
27
+ bandRows: number;
28
+ headerHeight: number;
29
+ viewport: { x: number; y: number; tx: number; ty: number };
30
+ onResize: (origin: string, block: { cols: number; rows: number }) => void;
31
+ onNotice: (message: string) => void;
32
+ onUndo: () => void;
33
+ onRedo: () => void;
34
+ }
35
+
36
+ const boundary = (visible: number[], real: number) => {
37
+ const index = visible.findIndex(value => value >= real);
38
+ return index < 0 ? visible.length : index;
39
+ };
40
+ const ignore = () => undefined;
41
+
42
+ /** These are row renderers only. The resolver, never an embedded grid, owns their data scope. */
43
+ function ViewContent({ answer, binding, onNotice }: {
44
+ answer: ViewRowsAnswer; binding: ViewBinding; onNotice: (message: string) => void;
45
+ }) {
46
+ const fields = useMemo<Field[]>(() => answer.fields.map(field => ({
47
+ key: field.key, label: field.label,
48
+ type: (field.kind === "number" ? "int" : field.kind) as Field["type"], source: "odoo",
49
+ ...(field.kind === "select" ? { options: [...new Set(answer.rows
50
+ .map(row => String(row[field.key] ?? "")).filter(Boolean))] } : {}),
51
+ })), [answer]);
52
+ const rows = useMemo<Row[]>(() => answer.rows.filter(row => typeof row.pid === "number")
53
+ .map(row => Object.fromEntries(Object.entries(row).map(([key, value]) => [key,
54
+ value == null || typeof value === "string" || typeof value === "number" ? value
55
+ : typeof value === "object" ? JSON.stringify(value) : String(value)])) as Row), [answer]);
56
+ const fieldByKey = useMemo(() => new Map(fields.map(field => [field.key, field])), [fields]);
57
+ const visibleKeys = fields.map(field => field.key);
58
+ const title = fields[0];
59
+ const date = fields.find(field => field.type === "date" || field.type === "created_time");
60
+ const stack = fields.find(field => field.type === "select" || field.type === "status");
61
+ const [selectedPids, setSelectedPids] = useState<Set<number>>(new Set());
62
+ const onOpen = () => onNotice("Open this record in Data for details.");
63
+ if (!title) return <div className="cg-mode-empty">Choose fields for this view.</div>;
64
+ const common = { rows, fields, fieldByKey, titleKey: title.key, onOpen };
65
+ switch (binding.viewType) {
66
+ case "gallery": return <GalleryView {...common} visibleKeys={visibleKeys} />;
67
+ case "timeline": return date ? <TimelineView {...common} visibleKeys={visibleKeys} field={date} />
68
+ : <div className="cg-mode-empty">Choose a date field for this view.</div>;
69
+ case "calendar": return date ? <CalendarView {...common} field={date} />
70
+ : <div className="cg-mode-empty">Choose a date field for this view.</div>;
71
+ case "list": return <ListView {...common} visibleKeys={visibleKeys}
72
+ rows={rows.map(record => ({ kind: "data", record }))} onToggleGroup={ignore} />;
73
+ case "kanban": return stack ? <KanbanView {...common} field={stack}
74
+ cardKeys={visibleKeys.filter(key => key !== title.key && key !== stack.key)}
75
+ canMove={false} readOnlyReason={null} onMove={ignore} onAddOption={null} />
76
+ : <div className="cg-mode-empty">Choose a status or single-select field for this view.</div>;
77
+ case "map": return <MapView rows={rows} field={title} selectedPids={selectedPids}
78
+ onSelectPids={(pids, mode) => setSelectedPids(before => new Set(mode === "add"
79
+ ? [...before, ...pids] : pids))} onOpen={onOpen} routePanelOpen={false}
80
+ activeView={null} tableKey={binding.database} />;
81
+ case "catalog": return <CatalogApplicationView rows={rows} onOpen={onOpen} definition={{
82
+ id: "sheet", name: "Catalog", templateKind: "catalog", sourceDatabase: binding.database,
83
+ fieldMap: { key: "pid", title: title.key, image: fields.find(field => field.type === "image")?.key },
84
+ }} />;
85
+ case "swipe": return <SwipeView {...common} spec={undefined}
86
+ cardKeys={visibleKeys} canWrite={false} canBind={false} readOnlyReason={null}
87
+ onSpec={ignore} onSwipe={ignore} />;
88
+ default: return null;
89
+ }
90
+ }
91
+
92
+ type Projection = ReturnType<typeof chartPaneProjections>[number];
93
+
94
+ function ViewBlock({ origin, binding, workbookId, busy, projections, width, height,
95
+ resized, onResize, onNotice, onUndo, onRedo }: {
96
+ origin: string; binding: ViewBinding; workbookId: string; busy: boolean;
97
+ projections: Projection[]; width: number; height: number;
98
+ resized: (dx: number, dy: number) => { cols: number; rows: number; width: number; height: number };
99
+ onResize: SheetViewLayerProps["onResize"]; onNotice: SheetViewLayerProps["onNotice"];
100
+ onUndo: () => void; onRedo: () => void;
101
+ }) {
102
+ const query = JSON.stringify({ ...binding, block: undefined });
103
+ const [resolved, setResolved] = useState<{ key: string; answer?: ViewRowsAnswer; error?: string }>();
104
+ const [preview, setPreview] = useState<ReturnType<typeof resized> | null>(null);
105
+ const drag = useRef<{ x: number; y: number; binding: ViewBinding } | null>(null);
106
+ const root = useRef<HTMLDivElement>(null);
107
+ // The stored document contains only the binding and cell dimensions, never a second row store.
108
+ useEffect(() => {
109
+ if (busy) return;
110
+ let current = true;
111
+ setResolved(undefined);
112
+ void fetchViewRows(workbookId, JSON.parse(query) as ViewBinding).then(result => {
113
+ if (current) setResolved(result.ok ? { key: query, answer: result.answer }
114
+ : { key: query, error: result.message });
115
+ }).catch(() => { if (current) setResolved({ key: query, error: "The view rows could not be read." }); });
116
+ return () => { current = false; };
117
+ }, [workbookId, query, busy]);
118
+ useEffect(() => { setPreview(null); drag.current = null; }, [binding]);
119
+ const boxWidth = preview?.width ?? width, boxHeight = preview?.height ?? height;
120
+ const answer = !busy && resolved?.key === query ? resolved.answer : undefined;
121
+ const error = !busy && resolved?.key === query ? resolved.error : undefined;
122
+ const block = viewBlockSize(binding);
123
+ const geometry = viewBlockGeometry(splitAddress(origin)!, binding);
124
+ const buttonStyle: CSSProperties = { position: "absolute", right: 0, bottom: 0,
125
+ width: 20, height: 20, padding: 2, border: 0, background: "var(--lp-surface)",
126
+ font: "inherit", color: "var(--lp-muted)", cursor: "nwse-resize", touchAction: "none" };
127
+ return <div ref={root}>
128
+ {projections.map(p => {
129
+ const ownsHandle = p.chartLeft + boxWidth > 0 && p.chartLeft + boxWidth <= p.width
130
+ && p.chartTop + boxHeight > 0 && p.chartTop + boxHeight <= p.height;
131
+ return <div key={p.pane} data-pane={p.pane} style={{ position: "absolute", overflow: "hidden",
132
+ pointerEvents: "none", left: p.left, top: p.top, width: p.width, height: p.height }}>
133
+ <section className="sheet-view-block" data-view-origin={origin} data-view-type={binding.viewType}
134
+ data-col0={geometry.col0} data-row0={geometry.row0} data-col1={geometry.col1} data-row1={geometry.row1}
135
+ aria-label={`${binding.viewType} view at ${origin}`}
136
+ onPointerDown={event => event.stopPropagation()} onWheel={event => event.stopPropagation()}
137
+ onKeyDown={event => {
138
+ event.stopPropagation();
139
+ if (event.target instanceof Element && event.target.closest("input, textarea, select, [contenteditable=true]")) return;
140
+ if (!(event.ctrlKey || event.metaKey) || event.altKey) return;
141
+ if (event.key.toLowerCase() === "z") { event.preventDefault(); (event.shiftKey ? onRedo : onUndo)(); }
142
+ if (event.key.toLowerCase() === "y") { event.preventDefault(); onRedo(); }
143
+ }}
144
+ style={{ position: "absolute", left: p.chartLeft, top: p.chartTop,
145
+ width: boxWidth, height: boxHeight, pointerEvents: "auto", overflow: "hidden",
146
+ background: "var(--lp-surface)", border: "1px solid var(--lp-line)", boxSizing: "border-box" }}>
147
+ <div className="sheet-view-content" style={{ width: Math.max(0, boxWidth - 2),
148
+ height: Math.max(0, boxHeight - 26), overflow: "auto", overscrollBehavior: "contain" }}
149
+ onScrollCapture={event => {
150
+ // Frozen-pane copies show the same part of each renderer's internal scrollbox.
151
+ const source = event.target as HTMLElement;
152
+ const container = event.currentTarget;
153
+ const index = Array.from(container.querySelectorAll("*")).indexOf(source);
154
+ root.current?.querySelectorAll<HTMLElement>(".sheet-view-content").forEach(copy => {
155
+ if (copy === container) return;
156
+ const target = index < 0 ? copy : copy.querySelectorAll<HTMLElement>("*")[index];
157
+ if (target && (target.scrollTop !== source.scrollTop || target.scrollLeft !== source.scrollLeft)) {
158
+ target.scrollTop = source.scrollTop; target.scrollLeft = source.scrollLeft;
159
+ }
160
+ });
161
+ }}>
162
+ {answer ? <ViewContent answer={answer} binding={binding} onNotice={onNotice} />
163
+ : <div className="cg-mode-empty" role={error ? "alert" : "status"}>{error ?? "Loading view…"}</div>}
164
+ </div>
165
+ <div style={{ height: 24, padding: "4px 24px 4px 8px", boxSizing: "border-box",
166
+ color: "var(--lp-muted)", fontSize: "var(--lp-fs-3xs)", whiteSpace: "nowrap", overflow: "hidden" }}>
167
+ {answer ? showingLine(answer.rows.length, answer.total) : ""}
168
+ </div>
169
+ <button type="button" aria-label={`Resize ${binding.viewType} view at ${origin}`}
170
+ title={`${block.cols} columns × ${block.rows} rows. Drag or use the arrow keys to resize.`}
171
+ tabIndex={ownsHandle ? 0 : -1} style={buttonStyle} disabled={busy}
172
+ onPointerDown={event => {
173
+ if (event.button !== 0) return;
174
+ event.preventDefault(); event.stopPropagation(); event.currentTarget.focus();
175
+ event.currentTarget.setPointerCapture(event.pointerId);
176
+ drag.current = { x: event.clientX, y: event.clientY, binding };
177
+ }}
178
+ onPointerMove={event => { if (drag.current) setPreview(resized(
179
+ event.clientX - drag.current.x, event.clientY - drag.current.y)); }}
180
+ onPointerUp={event => {
181
+ const start = drag.current;
182
+ drag.current = null; setPreview(null);
183
+ if (!start || start.binding !== binding) return;
184
+ const next = resized(event.clientX - start.x, event.clientY - start.y);
185
+ if (next.cols !== block.cols || next.rows !== block.rows) onResize(origin, next);
186
+ }}
187
+ onPointerCancel={() => { drag.current = null; setPreview(null); }}
188
+ onLostPointerCapture={() => { drag.current = null; setPreview(null); }}
189
+ onKeyDown={event => {
190
+ if (event.key === "Escape") { drag.current = null; setPreview(null); return; }
191
+ if (!["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) return;
192
+ event.preventDefault(); event.stopPropagation();
193
+ onResize(origin, { cols: Math.max(1, block.cols + (event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0)),
194
+ rows: Math.max(1, block.rows + (event.key === "ArrowDown" ? 1 : event.key === "ArrowUp" ? -1 : 0)) });
195
+ }}>
196
+ <svg viewBox="0 0 16 16" aria-hidden="true" width="16" height="16" fill="none" stroke="currentColor">
197
+ <path d="M5 13 13 5M9 13l4-4" />
198
+ </svg>
199
+ </button>
200
+ </section>
201
+ </div>;
202
+ })}
203
+ </div>;
204
+ }
205
+
206
+ export default function SheetViewLayer({ workbookId, tab, busy, visCols, visRows, columns, columnX,
207
+ rowHeightAt, frozenCols, bandRows, headerHeight, viewport, onResize, onNotice, onUndo, onRedo }: SheetViewLayerProps) {
208
+ const root = useRef<HTMLDivElement>(null);
209
+ const [size, setSize] = useState({ width: 0, height: 0 });
210
+ useLayoutEffect(() => {
211
+ const node = root.current;
212
+ if (!node) return;
213
+ const measure = () => setSize({ width: node.clientWidth, height: node.clientHeight });
214
+ measure();
215
+ const observer = new ResizeObserver(measure); observer.observe(node);
216
+ return () => observer.disconnect();
217
+ }, []);
218
+ const rowOffsets = useMemo(() => {
219
+ const offsets = [0];
220
+ for (let i = 0; i < visRows.length; i++) offsets.push(offsets[i] + rowHeightAt(i));
221
+ return offsets;
222
+ }, [rowHeightAt, visRows.length]);
223
+ const rowY = (index: number) => rowOffsets[Math.max(0, Math.min(index, visRows.length))] ?? 0;
224
+ const frozenHeight = rowY(bandRows);
225
+ const scrollX = lockstepScrollX(columns.map(column => column.width), frozenCols, viewport.x, viewport.tx);
226
+ const scrollY = rowY(bandRows + viewport.y) - frozenHeight - viewport.ty;
227
+ return <div className="sheet-view-layer" ref={root} style={{ position: "absolute", inset: 0,
228
+ pointerEvents: "none", overflow: "hidden", zIndex: "var(--cg-z-editor)" }}>
229
+ {/* ⛔ `tab.cells` IS LEGITIMATELY UNDEFINED ON A FIRST RENDER. `GET /sheets/{id}?tabs=meta`
230
+ answers tabs with NO cells, so a tab the page has not fetched yet renders here with none,
231
+ and `Object.entries(undefined)` throws inside a render. That is what "[Sheet] render
232
+ failed TypeError: Cannot convert undefined or null to object" was, found by this lane's
233
+ own Kanban screenshot. `SheetGrid.tsx` already guards its own read one line above the
234
+ twin of this one. */}
235
+ {Object.entries(tab.cells ?? {}).map(([origin, cell]) => {
236
+ if (cell?.kind !== "bound" || cell.binding?.mode !== "view"
237
+ || cell.binding.viewType === "grid" || !cell.binding.block) return null;
238
+ const at = splitAddress(origin);
239
+ if (!at) return null;
240
+ const binding = cell.binding as ViewBinding, geometry = viewBlockGeometry(at, binding);
241
+ const col = boundary(visCols, geometry.col0), row = boundary(visRows, geometry.row0);
242
+ const endCol = boundary(visCols, geometry.col1 + 1), endRow = boundary(visRows, geometry.row1 + 1);
243
+ const width = columnX(endCol) - columnX(col), height = rowY(endRow) - rowY(row);
244
+ if (width <= 0 || height <= 0) return null;
245
+ const projections = chartPaneProjections({ left: columnX(col), top: headerHeight + rowY(row) }, {
246
+ ...size, markerWidth: columnX(0), headerHeight,
247
+ frozenWidth: columnX(frozenCols) - columnX(0), frozenHeight, scrollX, scrollY,
248
+ });
249
+ const nearest = (visible: number[], offset: (index: number) => number, start: number, target: number) => {
250
+ let best = start + 1;
251
+ for (let i = start + 2; i <= visible.length; i++) {
252
+ if (Math.abs(offset(i) - target) < Math.abs(offset(best) - target)) best = i;
253
+ }
254
+ return best;
255
+ };
256
+ return <ViewBlock key={`${workbookId}/${tab.id}/${origin}`} {...{ origin, binding, workbookId, busy,
257
+ projections, width, height, onResize, onNotice, onUndo, onRedo }} resized={(dx, dy) => {
258
+ const c = dx ? nearest(visCols, columnX, col, columnX(endCol) + dx) : endCol;
259
+ const r = dy ? nearest(visRows, rowY, row, rowY(endRow) + dy) : endRow;
260
+ return { cols: dx ? (visCols[c - 1] + 1) - geometry.col0 : viewBlockSize(binding).cols,
261
+ rows: dy ? (visRows[r - 1] + 1) - geometry.row0 : viewBlockSize(binding).rows,
262
+ width: columnX(c) - columnX(col), height: rowY(r) - rowY(row) };
263
+ }} />;
264
+ })}
265
+ </div>;
266
+ }
web/src/sheet/a1.ts CHANGED
@@ -10,7 +10,7 @@
10
  // A sheet prefix (`Sheet2!C3`) never shifts; it names a tab, not a position.
11
 
12
  /** `A` -> 1, `Z` -> 26, `AA` -> 27. Spreadsheet base-26, which has no zero digit. */
13
- import { transformSheetFormula } from "./formulaEval";
14
 
15
  export const colToIndex = (letters: string): number => {
16
  let n = 0;
@@ -74,7 +74,8 @@ export const parseRef = (text: string): CellRef | null => {
74
  */
75
  const BARE_SHEET = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
76
 
77
- export const formatRef = (ref: CellRef): string => {
 
78
  const body = `${ref.colAbs ? "$" : ""}${ref.col}${ref.rowAbs ? "$" : ""}${ref.row}`;
79
  if (!ref.sheet) return body;
80
  const name = BARE_SHEET.test(ref.sheet) ? ref.sheet : `'${ref.sheet.replace(/'/g, "")}'`;
@@ -110,7 +111,8 @@ export const shiftRef = (ref: CellRef, dRow: number, dCol: number): CellRef => (
110
  */
111
  export const rewriteRefs = (
112
  formula: string,
113
- rewrite: (ref: CellRef) => CellRef,
 
114
  ): string => {
115
  const src = String(formula || "");
116
  const scan = new RegExp(REF_SOURCE, "gy");
@@ -149,6 +151,20 @@ export const rewriteRefs = (
149
  if (!/^\s*\(/.test(after)) {
150
  const ref = parseRef(m[0]);
151
  if (ref) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  out += formatRef(rewrite(ref));
153
  i = m.index + m[0].length;
154
  continue;
@@ -236,19 +252,15 @@ const sameName = (a: string, b: string): boolean =>
236
  /**
237
  * Where one 1-based index lands after `delta` were inserted or deleted at `at`.
238
  *
239
- * ⚠ A REFERENCE INSIDE A DELETED BAND IS RE-POINTED AT THE DELETION POINT, not turned into
240
- * Excel's `#REF!`. The reason is the one `shiftRef`'s clamp already carries: `#REF!` is not a
241
- * legal address in this grammar, so it would make the whole formula unparseable and the server
242
- * would answer `bad_formula` - "this formula could not be read" - about a formula the reader never
243
- * typed. Pointing at the row that slid up into the gap keeps the text a real address, so the
244
- * ordinary `unknown_ref` refusal can name the actual problem on the next Refresh. R10 means
245
- * nothing recomputes until then either way.
246
  */
247
- const shiftIndex = (value: number, at: number, delta: number): number => {
248
  if (value < at) return value;
249
  if (delta > 0) return value + delta;
250
  const past = at - delta; // the first index BELOW the deleted band
251
- return Math.max(1, value < past ? at : value + delta);
252
  };
253
 
254
  /**
@@ -263,13 +275,31 @@ export const shiftForStructure = (
263
  ownSheet: string,
264
  ): string => {
265
  if (!shift.delta) return String(formula || "");
266
- return rewriteRefs(String(formula || ""), (ref) => {
 
 
 
267
  if (!sameName(ref.sheet || ownSheet, shift.sheet)) return ref;
268
- if (shift.axis === "row") {
269
- return { ...ref, row: shiftIndex(ref.row, shift.at, shift.delta) };
 
 
 
 
 
270
  }
271
- return { ...ref, col: indexToCol(shiftIndex(colToIndex(ref.col), shift.at, shift.delta)) };
272
- });
 
 
 
 
 
 
 
 
 
 
273
  };
274
 
275
  /**
 
10
  // A sheet prefix (`Sheet2!C3`) never shifts; it names a tab, not a position.
11
 
12
  /** `A` -> 1, `Z` -> 26, `AA` -> 27. Spreadsheet base-26, which has no zero digit. */
13
+ import { ERROR_REF, transformSheetFormula } from "./formulaEval";
14
 
15
  export const colToIndex = (letters: string): number => {
16
  let n = 0;
 
74
  */
75
  const BARE_SHEET = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
76
 
77
+ export const formatRef = (ref: CellRef | string): string => {
78
+ if (typeof ref === "string") return ref;
79
  const body = `${ref.colAbs ? "$" : ""}${ref.col}${ref.rowAbs ? "$" : ""}${ref.row}`;
80
  if (!ref.sheet) return body;
81
  const name = BARE_SHEET.test(ref.sheet) ? ref.sheet : `'${ref.sheet.replace(/'/g, "")}'`;
 
111
  */
112
  export const rewriteRefs = (
113
  formula: string,
114
+ rewrite: (ref: CellRef) => CellRef | string,
115
+ rewriteRange?: (from: CellRef, to: CellRef, separator: string) => string,
116
  ): string => {
117
  const src = String(formula || "");
118
  const scan = new RegExp(REF_SOURCE, "gy");
 
151
  if (!/^\s*\(/.test(after)) {
152
  const ref = parseRef(m[0]);
153
  if (ref) {
154
+ // Only the optional range caller consumes a pair. Other callers keep their scan.
155
+ const separator = rewriteRange && /^\s*:\s*/.exec(after)?.[0];
156
+ if (rewriteRange && separator) {
157
+ scan.lastIndex = m.index + m[0].length + separator.length;
158
+ const end = scan.exec(src);
159
+ if (end && !/^\s*\(/.test(src.slice(end.index + end[0].length))) {
160
+ const last = parseRef(end[0]);
161
+ if (last) {
162
+ out += rewriteRange(ref, last, separator);
163
+ i = end.index + end[0].length;
164
+ continue;
165
+ }
166
+ }
167
+ }
168
  out += formatRef(rewrite(ref));
169
  i = m.index + m[0].length;
170
  continue;
 
252
  /**
253
  * Where one 1-based index lands after `delta` were inserted or deleted at `at`.
254
  *
255
+ * R49 retires the deleted-reference clamp: both grammars already parse `#REF!` as an error
256
+ * token, so it cannot cause the feared `bad_formula`. A deleted index returns null; only a
257
+ * range with surviving cells may clamp its deleted endpoint and shrink.
 
 
 
 
258
  */
259
+ const shiftIndex = (value: number, at: number, delta: number): number | null => {
260
  if (value < at) return value;
261
  if (delta > 0) return value + delta;
262
  const past = at - delta; // the first index BELOW the deleted band
263
+ return value < past ? null : value + delta;
264
  };
265
 
266
  /**
 
275
  ownSheet: string,
276
  ): string => {
277
  if (!shift.delta) return String(formula || "");
278
+ const index = (ref: CellRef): number => shift.axis === "row" ? ref.row : colToIndex(ref.col);
279
+ const atIndex = (ref: CellRef, value: number): CellRef => shift.axis === "row"
280
+ ? { ...ref, row: value } : { ...ref, col: indexToCol(value) };
281
+ const rewrite = (ref: CellRef): CellRef | string => {
282
  if (!sameName(ref.sheet || ownSheet, shift.sheet)) return ref;
283
+ const moved = shiftIndex(index(ref), shift.at, shift.delta);
284
+ return moved === null ? ERROR_REF : atIndex(ref, moved);
285
+ };
286
+ const rewriteRange = (from: CellRef, to: CellRef, separator: string): string => {
287
+ const sheet = from.sheet || ownSheet;
288
+ if (to.sheet && !sameName(sheet, to.sheet)) {
289
+ return formatRef(rewrite(from)) + separator + formatRef(rewrite(to));
290
  }
291
+ // A bare right endpoint inherits the left endpoint's sheet, not the formula's tab.
292
+ if (!sameName(sheet, shift.sheet)) return formatRef(from) + separator + formatRef(to);
293
+ const first = index(from), last = index(to);
294
+ const low = Math.min(first, last), high = Math.max(first, last);
295
+ if (low >= shift.at && high < shift.at - shift.delta) return ERROR_REF;
296
+ const move = (value: number): number => shiftIndex(value, shift.at, shift.delta)
297
+ ?? (value === low ? shift.at : shift.at - 1);
298
+ return formatRef(atIndex(from, move(first))) + separator + formatRef(atIndex(to, move(last)));
299
+ };
300
+ // Insertions retain the existing per-reference behavior, as does every scanner caller
301
+ // that supplies no range callback (including reference rewrites used for copying).
302
+ return rewriteRefs(String(formula || ""), rewrite, shift.delta < 0 ? rewriteRange : undefined);
303
  };
304
 
305
  /**
web/src/sheet/ribbonData.tsx CHANGED
@@ -250,7 +250,7 @@ function flashFillSelection(door: RibbonInsertDoor | undefined): string {
250
  if (examples.length === 0) return "Nothing was filled because there is no example; type an example in the target column within your selection.";
251
  const pending = rows.filter((row) => row.target === "");
252
  if (pending.length === 0) return "Nothing was filled because there are no empty target cells left; include empty rows in your selection.";
253
- // As with Text to columns, a blank computed result does not make a formula or binding disposable.
254
  if (pending.some(({ cell }) => cell && (cell.kind === "formula" || cell.kind === "bound" || cell.sparkline))) {
255
  return "Nothing was filled because an empty-looking target contains a formula, binding or sparkline; select empty target cells or clear their contents first.";
256
  }
@@ -394,7 +394,7 @@ function DataValidationControl({ ctx }: { ctx: RibbonTabContext }) {
394
  return (
395
  <span className="sheet-ribbon-slot">
396
  {control(
397
- "data-validation", "Data validation", <><IconDataValidation />{word("Data validation")}</>,
398
  (event) => {
399
  if (open === "data-validation") { closePop(); return; }
400
  const selection = insert?.selection;
@@ -412,7 +412,7 @@ function DataValidationControl({ ctx }: { ctx: RibbonTabContext }) {
412
  className="sheet-ribbon-pop sheet-ribbon-pop-portal sheet-ribbon-insert-form"
413
  onDismiss={closePop}
414
  role="dialog"
415
- ariaLabel="Data validation"
416
  >
417
  <form className="sheet-ribbon-insert-fields" onSubmit={(event) => { event.preventDefault(); submit(); }}>
418
  <label className="sheet-ribbon-insert-caption" htmlFor="sheet-data-validation-list">
@@ -460,7 +460,7 @@ function QueriesConnectionsControl({ ctx }: { ctx: RibbonTabContext }) {
460
  return (
461
  <span className="sheet-ribbon-slot">
462
  {control(
463
- "data-queries-connections", "Queries and connections", <><IconQueriesConnections />{word("Queries and connections")}</>,
464
  (event) => {
465
  if (open === "data-queries-connections") { closePop(); return; }
466
  const found: { address: string; description: string }[] = [];
@@ -486,7 +486,7 @@ function QueriesConnectionsControl({ ctx }: { ctx: RibbonTabContext }) {
486
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
487
  onDismiss={closePop}
488
  role="dialog"
489
- ariaLabel="Queries and connections"
490
  >
491
  {connections.length === 0 ? (
492
  <p className="sheet-ribbon-insert-hint">This workbook has no connected cells.</p>
@@ -499,7 +499,7 @@ function QueriesConnectionsControl({ ctx }: { ctx: RibbonTabContext }) {
499
  ))}
500
  </ul>
501
  )}
502
- <button type="button" className="sheet-ribbon-item" onClick={() => act("refresh")}>Refresh all</button>
503
  </AnchoredOverlay>
504
  )}
505
  </span>
@@ -513,7 +513,7 @@ function TextToColumnsControl({ ctx }: { ctx: RibbonTabContext }) {
513
  return (
514
  <span className="sheet-ribbon-slot">
515
  {control(
516
- "data-text-to-columns", "Split text to columns", <><IconTextToColumns />{word("Text to columns")}</>,
517
  (event) => { setResult(null); openPop("data-text-to-columns")(event); },
518
  false, open === "data-text-to-columns", "T", "gallery", !hasDataRange(insert?.selection),
519
  )}
@@ -523,7 +523,7 @@ function TextToColumnsControl({ ctx }: { ctx: RibbonTabContext }) {
523
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
524
  onDismiss={closePop}
525
  role="menu"
526
- ariaLabel="Split text to columns delimiter"
527
  >
528
  {item("Comma", () => split(","), false, "menuitem", "C")}
529
  {item("Semicolon", () => split(";"), false, "menuitem", "M")}
@@ -546,7 +546,7 @@ function RemoveDuplicatesControl({ ctx }: { ctx: RibbonTabContext }) {
546
  return (
547
  <span className="sheet-ribbon-slot">
548
  {control(
549
- "data-remove-duplicates", "Remove duplicates", <IconRemoveDuplicates />,
550
  (event) => {
551
  // Pressing an open result closes it without deduping the already-cleared tail again.
552
  if (open === "data-remove-duplicates") { closePop(); return; }
@@ -564,7 +564,7 @@ function RemoveDuplicatesControl({ ctx }: { ctx: RibbonTabContext }) {
564
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
565
  onDismiss={closePop}
566
  role="status"
567
- ariaLabel="Remove duplicates result"
568
  initialFocus="none"
569
  >
570
  <p className="sheet-ribbon-insert-hint">{result}</p>
@@ -580,7 +580,7 @@ function FlashFillControl({ ctx }: { ctx: RibbonTabContext }) {
580
  return (
581
  <span className="sheet-ribbon-slot">
582
  {control(
583
- "data-flash-fill", "Flash fill", <IconFlashFill />,
584
  (event) => {
585
  if (open === "data-flash-fill") { closePop(); return; }
586
  setResult(flashFillSelection(insert));
@@ -594,7 +594,7 @@ function FlashFillControl({ ctx }: { ctx: RibbonTabContext }) {
594
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
595
  onDismiss={closePop}
596
  role="status"
597
- ariaLabel="Flash fill result"
598
  initialFocus="none"
599
  >
600
  <p className="sheet-ribbon-insert-hint">{result}</p>
@@ -616,10 +616,10 @@ export const dataGroups = (ctx: RibbonTabContext) => {
616
  const dataDisabled = !hasDataRange(insert?.selection);
617
  return (
618
  <>
619
- {group("Data", <>
620
  {large(<>
621
  {control(
622
- "data-refresh", "Refresh all", <><IconRefresh />{word("Refresh all")}</>,
623
  () => act("refresh"), false, undefined, "R",
624
  )}
625
  </>)}
@@ -630,22 +630,22 @@ export const dataGroups = (ctx: RibbonTabContext) => {
630
  {group("Sort", stack(
631
  <>
632
  {control(
633
- "data-sort-asc", "Sort ascending", <IconSort />,
634
  () => { transformSelectionRows(insert, (rows) => sortRows(rows, 1)); closePop(); },
635
  false, undefined, "SA", undefined, dataDisabled,
636
  )}
637
  </>,
638
  <>
639
  {control(
640
- "data-sort-desc", "Sort descending", <IconSort descending />,
641
  () => { transformSelectionRows(insert, (rows) => sortRows(rows, -1)); closePop(); },
642
  false, undefined, "SD", undefined, dataDisabled,
643
  )}
644
  </>
645
  ))}
646
- {group("Auto filter", large(unavailable("Filter", <><IconFilter />{word("Filter")}</>)))}
647
- {group("Data validation", large(<DataValidationControl ctx={ctx} />))}
648
- {group("Data tools", <>
649
  {large(<>
650
  <TextToColumnsControl ctx={ctx} />
651
  </>)}
@@ -661,19 +661,19 @@ export const dataGroups = (ctx: RibbonTabContext) => {
661
  {group("Outline", stack(
662
  <>
663
  {control(
664
- "data-hide-rows", "Hide rows", <IconBand />,
665
  () => act("hide-rows"), false, undefined, "HR",
666
  )}
667
  </>,
668
  <>
669
  {control(
670
- "data-hide-columns", "Hide columns", <IconBand column />,
671
  () => act("hide-columns"), false, undefined, "HC",
672
  )}
673
  </>,
674
  <>
675
  {control(
676
- "data-unhide", "Unhide rows and columns", <IconOutlineUnhide />,
677
  () => act("unhide"), false, undefined, "U",
678
  )}
679
  </>
 
250
  if (examples.length === 0) return "Nothing was filled because there is no example; type an example in the target column within your selection.";
251
  const pending = rows.filter((row) => row.target === "");
252
  if (pending.length === 0) return "Nothing was filled because there are no empty target cells left; include empty rows in your selection.";
253
+ // As with Text to Columns, a blank computed result does not make a formula or binding disposable.
254
  if (pending.some(({ cell }) => cell && (cell.kind === "formula" || cell.kind === "bound" || cell.sparkline))) {
255
  return "Nothing was filled because an empty-looking target contains a formula, binding or sparkline; select empty target cells or clear their contents first.";
256
  }
 
394
  return (
395
  <span className="sheet-ribbon-slot">
396
  {control(
397
+ "data-validation", "Data Validation", <><IconDataValidation />{word("Data Validation")}</>,
398
  (event) => {
399
  if (open === "data-validation") { closePop(); return; }
400
  const selection = insert?.selection;
 
412
  className="sheet-ribbon-pop sheet-ribbon-pop-portal sheet-ribbon-insert-form"
413
  onDismiss={closePop}
414
  role="dialog"
415
+ ariaLabel="Data Validation"
416
  >
417
  <form className="sheet-ribbon-insert-fields" onSubmit={(event) => { event.preventDefault(); submit(); }}>
418
  <label className="sheet-ribbon-insert-caption" htmlFor="sheet-data-validation-list">
 
460
  return (
461
  <span className="sheet-ribbon-slot">
462
  {control(
463
+ "data-queries-connections", "Queries & Connections", <><IconQueriesConnections />{word("Queries & Connections")}</>,
464
  (event) => {
465
  if (open === "data-queries-connections") { closePop(); return; }
466
  const found: { address: string; description: string }[] = [];
 
486
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
487
  onDismiss={closePop}
488
  role="dialog"
489
+ ariaLabel="Queries & Connections"
490
  >
491
  {connections.length === 0 ? (
492
  <p className="sheet-ribbon-insert-hint">This workbook has no connected cells.</p>
 
499
  ))}
500
  </ul>
501
  )}
502
+ <button type="button" className="sheet-ribbon-item" onClick={() => act("refresh")}>Refresh All</button>
503
  </AnchoredOverlay>
504
  )}
505
  </span>
 
513
  return (
514
  <span className="sheet-ribbon-slot">
515
  {control(
516
+ "data-text-to-columns", "Text to Columns", <><IconTextToColumns />{word("Text to Columns")}</>,
517
  (event) => { setResult(null); openPop("data-text-to-columns")(event); },
518
  false, open === "data-text-to-columns", "T", "gallery", !hasDataRange(insert?.selection),
519
  )}
 
523
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
524
  onDismiss={closePop}
525
  role="menu"
526
+ ariaLabel="Text to Columns delimiter"
527
  >
528
  {item("Comma", () => split(","), false, "menuitem", "C")}
529
  {item("Semicolon", () => split(";"), false, "menuitem", "M")}
 
546
  return (
547
  <span className="sheet-ribbon-slot">
548
  {control(
549
+ "data-remove-duplicates", "Remove Duplicates", <IconRemoveDuplicates />,
550
  (event) => {
551
  // Pressing an open result closes it without deduping the already-cleared tail again.
552
  if (open === "data-remove-duplicates") { closePop(); return; }
 
564
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
565
  onDismiss={closePop}
566
  role="status"
567
+ ariaLabel="Remove Duplicates result"
568
  initialFocus="none"
569
  >
570
  <p className="sheet-ribbon-insert-hint">{result}</p>
 
580
  return (
581
  <span className="sheet-ribbon-slot">
582
  {control(
583
+ "data-flash-fill", "Flash Fill", <IconFlashFill />,
584
  (event) => {
585
  if (open === "data-flash-fill") { closePop(); return; }
586
  setResult(flashFillSelection(insert));
 
594
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
595
  onDismiss={closePop}
596
  role="status"
597
+ ariaLabel="Flash Fill result"
598
  initialFocus="none"
599
  >
600
  <p className="sheet-ribbon-insert-hint">{result}</p>
 
616
  const dataDisabled = !hasDataRange(insert?.selection);
617
  return (
618
  <>
619
+ {group("Queries & Connections", <>
620
  {large(<>
621
  {control(
622
+ "data-refresh", "Refresh All", <><IconRefresh />{word("Refresh All")}</>,
623
  () => act("refresh"), false, undefined, "R",
624
  )}
625
  </>)}
 
630
  {group("Sort", stack(
631
  <>
632
  {control(
633
+ "data-sort-asc", "Sort A to Z", <IconSort />,
634
  () => { transformSelectionRows(insert, (rows) => sortRows(rows, 1)); closePop(); },
635
  false, undefined, "SA", undefined, dataDisabled,
636
  )}
637
  </>,
638
  <>
639
  {control(
640
+ "data-sort-desc", "Sort Z to A", <IconSort descending />,
641
  () => { transformSelectionRows(insert, (rows) => sortRows(rows, -1)); closePop(); },
642
  false, undefined, "SD", undefined, dataDisabled,
643
  )}
644
  </>
645
  ))}
646
+ {group("Filter", large(unavailable("Filter", <><IconFilter />{word("Filter")}</>)))}
647
+ {group("Data Validation", large(<DataValidationControl ctx={ctx} />))}
648
+ {group("Data Tools", <>
649
  {large(<>
650
  <TextToColumnsControl ctx={ctx} />
651
  </>)}
 
661
  {group("Outline", stack(
662
  <>
663
  {control(
664
+ "data-hide-rows", "Hide Rows", <IconBand />,
665
  () => act("hide-rows"), false, undefined, "HR",
666
  )}
667
  </>,
668
  <>
669
  {control(
670
+ "data-hide-columns", "Hide Columns", <IconBand column />,
671
  () => act("hide-columns"), false, undefined, "HC",
672
  )}
673
  </>,
674
  <>
675
  {control(
676
+ "data-unhide", "Unhide Rows and Columns", <IconOutlineUnhide />,
677
  () => act("unhide"), false, undefined, "U",
678
  )}
679
  </>
web/src/sheet/ribbonFormulas.tsx CHANGED
@@ -3,15 +3,15 @@
3
  // expression: it reuses the ribbon primitives and closed action vocabulary, never external
4
  // source, assets, or private class names.
5
  //
6
- // ⭐ W56-T13: Insert function and More functions now read the server-owned catalogue lazily and
7
- // write through the Sheet's existing cell door; AutoSum and Calculate now keep their established
8
  // actions. Name manager is absent because neither evaluator supports named ranges. Show formulas
9
  // is absent because the canvas renderer, not ribbon-local state or CSS, owns painted cell text.
10
  // Calculation options is absent because a truthful Manual mode must change SheetGrid's automatic
11
  // recalculation door. A command that cannot work is removed instead of rendered as a no-op.
12
  //
13
  // W56-T18 adds literal top-level shortcuts for the five Excel categories our evaluator serves.
14
- // Statistical and Information remain in More functions, and Financial remains absent because the
15
  // evaluator has no financial functions. Literal control labels also keep the parity source scrape
16
  // auditable without teaching that asset a TypeScript evaluator.
17
 
@@ -370,10 +370,10 @@ function FormulaPicker({
370
  };
371
 
372
  const title = view === "categories"
373
- ? "More functions"
374
  : view === "arguments"
375
- ? "Function arguments"
376
- : category ?? "Insert function";
377
 
378
  return (
379
  <AnchoredOverlay
@@ -540,12 +540,12 @@ export const formulasGroups = (ctx: RibbonTabContext) => {
540
  const canInsert = !!insert?.selection;
541
  return (
542
  <>
543
- {group("Function library", <>
544
  {large(<>
545
  <span className="sheet-ribbon-slot">
546
  <fieldset className="sheet-formula-trigger-fence" disabled={!canInsert}>
547
  {control(
548
- "formula-insert", "Insert function", <><IconFunction />{word("Insert function")}</>,
549
  openPop("formula-insert"), false, open === "formula-insert", "FI", "gallery",
550
  )}
551
  </fieldset>
@@ -667,7 +667,7 @@ export const formulasGroups = (ctx: RibbonTabContext) => {
667
  <span className="sheet-ribbon-slot">
668
  <fieldset className="sheet-formula-trigger-fence" disabled={!canInsert}>
669
  {control(
670
- "formula-more", "More functions", <IconMoreFunctions />,
671
  openPop("formula-more"), false, open === "formula-more", "FM", "gallery",
672
  )}
673
  </fieldset>
@@ -684,7 +684,7 @@ export const formulasGroups = (ctx: RibbonTabContext) => {
684
  )}
685
  </>)}
686
  {group("Calculation", large(control(
687
- "formula-refresh", "Calculate now", <><IconCalculate />{word("Calculate now")}</>,
688
  () => act("refresh"), false, undefined, "C",
689
  )))}
690
  </>
 
3
  // expression: it reuses the ribbon primitives and closed action vocabulary, never external
4
  // source, assets, or private class names.
5
  //
6
+ // ⭐ W56-T13: Insert Function and More Functions now read the server-owned catalogue lazily and
7
+ // write through the Sheet's existing cell door; AutoSum and Calculate Now keep their established
8
  // actions. Name manager is absent because neither evaluator supports named ranges. Show formulas
9
  // is absent because the canvas renderer, not ribbon-local state or CSS, owns painted cell text.
10
  // Calculation options is absent because a truthful Manual mode must change SheetGrid's automatic
11
  // recalculation door. A command that cannot work is removed instead of rendered as a no-op.
12
  //
13
  // W56-T18 adds literal top-level shortcuts for the five Excel categories our evaluator serves.
14
+ // Statistical and Information remain in More Functions, and Financial remains absent because the
15
  // evaluator has no financial functions. Literal control labels also keep the parity source scrape
16
  // auditable without teaching that asset a TypeScript evaluator.
17
 
 
370
  };
371
 
372
  const title = view === "categories"
373
+ ? "More Functions"
374
  : view === "arguments"
375
+ ? "Function Arguments"
376
+ : category ?? "Insert Function";
377
 
378
  return (
379
  <AnchoredOverlay
 
540
  const canInsert = !!insert?.selection;
541
  return (
542
  <>
543
+ {group("Function Library", <>
544
  {large(<>
545
  <span className="sheet-ribbon-slot">
546
  <fieldset className="sheet-formula-trigger-fence" disabled={!canInsert}>
547
  {control(
548
+ "formula-insert", "Insert Function", <><IconFunction />{word("Insert Function")}</>,
549
  openPop("formula-insert"), false, open === "formula-insert", "FI", "gallery",
550
  )}
551
  </fieldset>
 
667
  <span className="sheet-ribbon-slot">
668
  <fieldset className="sheet-formula-trigger-fence" disabled={!canInsert}>
669
  {control(
670
+ "formula-more", "More Functions", <IconMoreFunctions />,
671
  openPop("formula-more"), false, open === "formula-more", "FM", "gallery",
672
  )}
673
  </fieldset>
 
684
  )}
685
  </>)}
686
  {group("Calculation", large(control(
687
+ "formula-refresh", "Calculate Now", <><IconCalculate />{word("Calculate Now")}</>,
688
  () => act("refresh"), false, undefined, "C",
689
  )))}
690
  </>
web/src/sheet/ribbonHome.tsx CHANGED
@@ -22,7 +22,7 @@
22
  //
23
  // ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5) — unchanged and still binding here: icons are inline
24
  // SVG on `currentColor` and never emoji, a colour swatch is a token-styled span, colour and type
25
- // are token only, sentence case labels, no em dash or en dash in any string that reaches a screen.
26
 
27
  import {
28
  CELL_FONTS, CELL_FORMAT_KINDS, DEFAULT_CELL_FONT, FONT_SIZE_STEPS, FONT_STACKS,
@@ -69,11 +69,11 @@ const FONT = [
69
  ] as const;
70
  // ⭐⭐ W53-T05 (instruction 16) — TWO VISUAL ROWS, ONE ROVING ORDER, AND THE ORDER IS THE READING
71
  // ORDER. Excel lays Alignment out as two rows, so this array is re-sequenced to match what the eye
72
- // walks: top row (vertical align, then Wrap text), then bottom row (horizontal align, then the two
73
  // indents). ⛔ THE ARRAY IS THE ROVING SOURCE AND THE JSX IS NOT: a key listed here with no
74
  // `control(...)` call rendering it makes ArrowRight land on nothing, with every gate still green,
75
  // so the two are changed together or not at all.
76
- // ⭐⭐ W54-T06 (instruction 5, ruling R2) ADDS `orientation` TO THE TOP ROW, after Wrap text.
77
  // The top row carried four controls against the bottom row's five, so the group takes no extra
78
  // width at all: measured at 1440x900 the strip's group edges are unchanged by this ticket.
79
  const ALIGNMENT = [
@@ -90,7 +90,7 @@ const NUMBER = ["format", "currency", "percent", "comma", "decless", "decmore"]
90
  const STYLES = ["conditional", "cellstyles"] as const;
91
  const CELLS = ["insert", "delete", "cellformat"] as const;
92
  // ⭐⭐ W54-T07 (instruction 5, ruling R2) — EDITING IS TWO ROWS AND GAINS FIND AND SELECT.
93
- // Top row: AutoSum, Fill down, Fill right. Bottom row: Clear, then the new Find and select
94
  // gallery. ⛔ THE STACK IS A WIDTH DECISION, NOT A TIDY (D-663): Editing is the LAST group in the
95
  // strip and measured at 1440x900 it ended at 1385 of a 1440 viewport, so a fifth control laid
96
  // beside the other four would have taken most of the 55px that was left. Stacked, the group is
@@ -212,7 +212,7 @@ const previewStyle = (style: CellStyle): CSSProperties => ({
212
  /**
213
  * ⛔ THE FIVE THE DOCUMENT MODEL CARRIES, AND ONLY THOSE. `CELL_FORMAT_KINDS` is mirrored in
214
  * `platform/core/sheets.py` and a sixth spelling is REFUSED by name on the way in, so R8's
215
- * Accounting and Custom code are offered as ACTS (`format-accounting`, `format-custom`) rather
216
  * than smuggled in here as a kind the server would reject.
217
  */
218
  const FORMAT_LABEL: Record<CellFormatKind, string> = {
@@ -439,7 +439,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
439
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
440
  onDismiss={closePop}
441
  role="menu"
442
- ariaLabel={which === "color" ? "Text colour" : "Fill colour"}
443
  initialFocus="none"
444
  >
445
  <div className="sheet-ribbon-swatches">
@@ -526,7 +526,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
526
  <>
527
  {/* ⭐⭐ W52-T16 (instruction 18, ruling R4) — THE ARRANGEMENT INSTRUCTION 18 NAMES
528
  EXPLICITLY: a large split Paste on the left (icon above, caption below) with Cut,
529
- Copy and Format painter stacked as three small icon+label rows to its right,
530
  exactly like Excel's own Clipboard group.
531
  The tall Paste control opens the existing anchored menu vocabulary. Normal paste and
532
  both named paste-special layers still travel through the one `paste` act; its argument
@@ -542,12 +542,12 @@ export const homeGroups = (ctx: RibbonTabContext) => {
542
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
543
  onDismiss={closePop}
544
  role="menu"
545
- ariaLabel="Paste options"
546
  initialFocus="first"
547
  >
548
  {item("Paste", () => act("paste", "normal"))}
549
- {item("Paste values", () => act("paste", "values"))}
550
- {item("Paste formatting", () => act("paste", "formatting"))}
551
  </AnchoredOverlay>
552
  )}
553
  </>)}
@@ -560,9 +560,9 @@ export const homeGroups = (ctx: RibbonTabContext) => {
560
  the large Paste is exactly that.
561
  ⛔ THE LABEL IS NOT DELETED, ONLY THE PAINTED WORD. `control()` writes its
562
  `label` argument into BOTH `aria-label` and `title`, so a screen reader still
563
- announces "Format painter" and a hover still says it. That matters twice over:
564
  `verify_api.py`'s `_RIBBON_GROUPS` pins the literals `"Cut"`, `"Copy"` and
565
- `"Format painter"` as the proof this group still offers what R8 names, and an
566
  icon-only control with no accessible name is a regression no gate in this repo
567
  would catch. */}
568
  {stack(
@@ -575,7 +575,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
575
  false, undefined, "C")}
576
  </>,
577
  <>
578
- {control("painter", "Format painter", <IconFormatPainter />,
579
  () => act("format-painter"), false, undefined, "FP")}
580
  </>
581
  )}
@@ -584,7 +584,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
584
 
585
  {/* ⭐⭐ W54-T03 (owner instruction 4, rulings R10 + R11) — THE FONT GROUP IS EXCEL'S OWN
586
  TWO ROWS. Top row: the font FAMILY combo, then the editable font SIZE box with its own
587
- gallery caret, then Increase and Decrease font size. Bottom row: bold, italic, underline,
588
  then borders, fill colour and text colour, which is exactly what this group carried
589
  before. The mechanism is the one Clipboard and Alignment already established: a COLUMN
590
  wrapper inside `.sheet-ribbon-group-controls`, each row a plain row flex of the SAME
@@ -675,7 +675,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
675
  }}
676
  onBlur={(e) => commitPoints(e.currentTarget)}
677
  />
678
- {control("size", "Font size", <IconCaret />,
679
  openPop("size"), false, open === "size",
680
  "FS", "gallery")}
681
  {open === "size" && (
@@ -684,7 +684,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
684
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
685
  onDismiss={closePop}
686
  role="menu"
687
- ariaLabel="Font size"
688
  initialFocus="none"
689
  >
690
  {FONT_SIZE_STEPS.map((step) => item(
@@ -697,9 +697,9 @@ export const homeGroups = (ctx: RibbonTabContext) => {
697
  returns the size it was given when there is no next entry, so the largest and the
698
  smallest are quiet no-ops rather than an error or a wrap around. From a size that is
699
  not on the list at all, it walks to the nearest entry in the direction asked for. */}
700
- {control("grow", "Increase font size", <IconFontStep up />,
701
  () => apply({ size: stepFontPt(points, 1) }), false, undefined, "FG")}
702
- {control("shrink", "Decrease font size", <IconFontStep up={false} />,
703
  () => apply({ size: stepFontPt(points, -1) }), false, undefined, "FK")}
704
  </>,
705
  <>
@@ -729,24 +729,24 @@ export const homeGroups = (ctx: RibbonTabContext) => {
729
  {BORDERS.map((entry) => item(
730
  entry.label, () => apply({ border: entry.sides }), false, "menuitem", entry.kt,
731
  ))}
732
- {item("No border", () => apply({ border: null }), false, "menuitem", "N")}
733
  </AnchoredOverlay>
734
  )}
735
  </span>
736
  {/* ⚠ FILL COLOUR AND TEXT COLOUR BOTH OPEN A SWATCH POPOVER IN THIS CODEBASE
737
  (`open === "fill"` / `open === "color"`), so both carry `data-kt-opens`
738
  per the general C4 rule even though the ticket's own inline example list did
739
- not annotate Fill colour with "/opens" — a judgment call, documented here and
740
  in the HANDOFF, resolved in favour of matching the code's real behaviour. */}
741
  <span className="sheet-ribbon-slot">
742
- {control("fill", "Fill colour",
743
  <><IconFill colour={fillColour} /><IconCaret /></>,
744
  openPop("fill"), !!style?.fill, open === "fill",
745
  "H", "gallery")}
746
  {open === "fill" && swatches("fill", FILLS)}
747
  </span>
748
  <span className="sheet-ribbon-slot">
749
- {control("color", "Text colour",
750
  <><IconInk colour={inkColour} /><IconCaret /></>,
751
  openPop("color"), !!style?.color,
752
  open === "color", "FC", "gallery")}
@@ -764,7 +764,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
764
  plain row flex of the SAME `control()` buttons. No new control shape, no new
765
  button size, and the two rows total 52px, which is exactly the height Clipboard's
766
  large Paste already sets, so the ribbon does not grow by a pixel.
767
- ⚠ THE SIX ALIGNMENT BUTTONS STAY ICON ONLY, and so does Wrap text: the researched
768
  Excel convention is that only a WIDE combo box or a TALL two-row-spanning button
769
  carries a caption, and none of these is either. `control()` writes the label into
770
  both `aria-label` and `title`, so every one of them keeps its accessible name.
@@ -785,13 +785,13 @@ export const homeGroups = (ctx: RibbonTabContext) => {
785
  KeyTip LIST (it names align top/middle/bottom as one of the examples with no
786
  row to copy). `AT`/`AM`/`AB` follows the same two-letter shape the spec's
787
  real Excel sequences use for the horizontal three (`AL`/`AC`/`AR`). */}
788
- {control("top", "Align top", <IconVAlign to="top" />, () => act("align-top"),
789
  false, undefined, "AT")}
790
- {control("middle", "Align middle", <IconVAlign to="middle" />,
791
  () => act("align-middle"), false, undefined, "AM")}
792
- {control("bottom", "Align bottom", <IconVAlign to="bottom" />,
793
  () => act("align-bottom"), false, undefined, "AB")}
794
- {control("wrap", "Wrap text", <IconWrap />, () => act("wrap-text"),
795
  false, undefined, "W")}
796
  {/* ⭐⭐ W54-T06 (instruction 5, ruling R2) — TEXT ORIENTATION, AND IT NEEDED NO NEW
797
  ACT. The base kit had already declared `CellStyle.textRotation` and
@@ -801,7 +801,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
801
  member, so the shell's exhaustive switch in `SheetGrid.tsx` gains no arm and
802
  `Ribbon.tsx` is untouched. The lane's OTHER three obligations were paid in the same
803
  change - `stylePaints` counts the key, `paintCell` turns the canvas, and
804
- `cellStyleOps.ts::STYLE_KEYS` names it so the Format painter clears it.
805
  ⚠ FIVE ENTRIES, WHICH IS EXCEL'S OWN LIST MINUS THE ONE THIS SLOT CANNOT SAY.
806
  Vertical stacked text is not a rotation at all (it is a per character layout), and
807
  the slot is a signed degree between -90 and 90, so offering it would be a control
@@ -840,16 +840,16 @@ export const homeGroups = (ctx: RibbonTabContext) => {
840
  are checked as that one expression rather than per call. */}
841
  {(["left", "center", "right"] as const).map((to) => control(
842
  to,
843
- to === "left" ? "Align left" : to === "center" ? "Align centre" : "Align right",
844
  <IconAlign to={to} />,
845
  () => apply({ align: style?.align === to ? null : to }),
846
  style?.align === to,
847
  undefined,
848
  to === "left" ? "AL" : to === "center" ? "AC" : "AR",
849
  ))}
850
- {control("outdent", "Decrease indent", <IconIndent out />,
851
  () => act("indent-decrease"), false, undefined, "5")}
852
- {control("indent", "Increase indent", <IconIndent out={false} />,
853
  () => act("indent-increase"), false, undefined, "6")}
854
  </>
855
  )
@@ -858,7 +858,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
858
  {group("Number", stack(
859
  <>
860
  <span className="sheet-ribbon-slot sheet-ribbon-number-format">
861
- {control("format", "Number format",
862
  <><span className="sheet-ribbon-label">{FORMAT_LABEL[kind]}</span><IconCaret /></>,
863
  openPop("format"), kind !== "general",
864
  open === "format", "N", "gallery")}
@@ -868,7 +868,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
868
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
869
  onDismiss={closePop}
870
  role="menu"
871
- ariaLabel="Number format"
872
  initialFocus="none"
873
  >
874
  {/* ⚠ FILTERED, AND D-671 IS WHY. Wave 54's base kit widened `CELL_FORMAT_KINDS`
@@ -905,7 +905,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
905
  not kinds: `clean_cell` refuses an unknown `format.kind` BY NAME, so
906
  writing `accounting` here would refuse the whole cell. */}
907
  {item("Accounting", () => act("format-accounting"))}
908
- {item("Custom code", () => act("format-custom"))}
909
  {/* ⚠ THE TWO OPTIONS A1 NAMES BY NAME: decimals, and thousands. They are
910
  shown only where they mean something; a date has neither and a percent
911
  groups by locale. */}
@@ -962,11 +962,11 @@ export const homeGroups = (ctx: RibbonTabContext) => {
962
  <span className="sheet-ribbon-glyph">$</span>,
963
  () => apply({ format: { kind: "currency", decimals: 2 } }),
964
  kind === "currency", undefined, "CU")}
965
- {control("percent", "Percent",
966
  <span className="sheet-ribbon-glyph">%</span>,
967
  () => apply({ format: { kind: "percent", decimals: 0 } }),
968
  kind === "percent", undefined, "P")}
969
- {control("comma", "Comma",
970
  <span className="sheet-ribbon-glyph">,</span>,
971
  () => apply({ format: { kind: "number", decimals: 2, thousands: true } }),
972
  kind === "number" && format?.thousands === true, undefined, "K")}
@@ -974,9 +974,9 @@ export const homeGroups = (ctx: RibbonTabContext) => {
974
  (spec KT-T1; Corporate Finance Institute's "Alt+H+O" for Increase Decimal is almost
975
  certainly the digit rendered as a letter, since Decrease Decimal is `9`). `decless` is
976
  this file's DECREASE control, `decmore` is INCREASE. */}
977
- {control("decless", "Decrease decimals", <IconDecimals more={false} />,
978
  () => stepDecimals(-1), false, undefined, "9")}
979
- {control("decmore", "Increase decimals", <IconDecimals more />,
980
  () => stepDecimals(1), false, undefined, "0")}
981
  </>
982
  ))}
@@ -993,9 +993,9 @@ export const homeGroups = (ctx: RibbonTabContext) => {
993
  of those label literals, and they are all still right there in the call. */}
994
  {/* ⭐⭐ W54-T05 (owner instruction 5, ruling R2) — STYLES IS TWO STACKED ROWS NOW.
995
 
996
- Conditional formatting became a GALLERY: highlight-cells rules still open the editor
997
  W51-T18 built, and the two new items build a rule FROM THE SELECTION and route it through
998
- the same `saveRules` door rather than opening a second one. Cell styles is a gallery of
999
  named presets that write real `CellStyle` values.
1000
 
1001
  ⛔ FORMAT AS TABLE AND SORT AND FILTER ARE OUT, BY RULING R2, and that is a decision rather
@@ -1008,14 +1008,14 @@ export const homeGroups = (ctx: RibbonTabContext) => {
1008
  that, and two 26px rows come to exactly `--sheet-ribbon-band`, so the ribbon does not grow
1009
  by a pixel in either direction. Same mechanism Clipboard, Alignment and Font already use.
1010
 
1011
- ⛔ THE LABEL "Conditional formatting" IS BYTE-PINNED in `verify_api.py`'s `_RIBBON_GROUPS`
1012
  Styles tuple and its key-tip "L" in `verify_ui.py::_RIBBON_KEYTIPS`, so both stay exactly
1013
  where they were even though the control now opens a menu instead of firing an act. */}
1014
  {group("Styles", (
1015
  stack(
1016
  <>
1017
  <span className="sheet-ribbon-slot">
1018
- {control("conditional", "Conditional formatting",
1019
  <><IconConditional /><IconCaret /></>,
1020
  openPop("conditional"), false, open === "conditional", "L", "gallery")}
1021
  {open === "conditional" && (
@@ -1024,20 +1024,20 @@ export const homeGroups = (ctx: RibbonTabContext) => {
1024
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1025
  onDismiss={closePop}
1026
  role="menu"
1027
- ariaLabel="Conditional formatting"
1028
  initialFocus="none"
1029
  >
1030
- {item("Highlight cells rules", () => act("conditional-formatting"))}
1031
- {item("Colour scales", () => act("colour-scale"))}
1032
- {item("Data bars", () => act("data-bars"))}
1033
- {item("Manage rules", () => act("conditional-formatting"))}
1034
  </AnchoredOverlay>
1035
  )}
1036
  </span>
1037
  </>,
1038
  <>
1039
  <span className="sheet-ribbon-slot">
1040
- {control("cellstyles", "Cell styles",
1041
  <><IconCellStyles /><IconCaret /></>,
1042
  openPop("cellstyles"), false, open === "cellstyles", "J", "gallery")}
1043
  {open === "cellstyles" && (
@@ -1046,7 +1046,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
1046
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1047
  onDismiss={closePop}
1048
  role="menu"
1049
- ariaLabel="Cell styles"
1050
  initialFocus="none"
1051
  >
1052
  {/* ⛔ WRITTEN OUT RATHER THAN PASSED THROUGH `item()` FOR ONE REASON: each row
@@ -1092,10 +1092,10 @@ export const homeGroups = (ctx: RibbonTabContext) => {
1092
  ariaLabel="Insert"
1093
  initialFocus="none"
1094
  >
1095
- {item("Insert row above", () => act("insert-row"))}
1096
- {item("Insert column left", () => act("insert-column"))}
1097
- {item("Add rows", () => act("add-rows"))}
1098
- {item("Add columns", () => act("add-columns"))}
1099
  </AnchoredOverlay>
1100
  )}
1101
  </span>
@@ -1114,8 +1114,8 @@ export const homeGroups = (ctx: RibbonTabContext) => {
1114
  ariaLabel="Delete"
1115
  initialFocus="none"
1116
  >
1117
- {item("Delete row", () => act("delete-row"))}
1118
- {item("Delete column", () => act("delete-column"))}
1119
  </AnchoredOverlay>
1120
  )}
1121
  </span>
@@ -1135,8 +1135,8 @@ export const homeGroups = (ctx: RibbonTabContext) => {
1135
  ariaLabel="Format"
1136
  initialFocus="none"
1137
  >
1138
- {item("Row height", () => act("row-height"))}
1139
- {item("Column width", () => act("column-width"))}
1140
  {/* ⭐⭐ W54-T07 — THE TWO AUTOFITS SIT BESIDE THE TWO MANUAL SIZES, which is
1141
  Excel's own arrangement and also the honest one: each pair is the same
1142
  question asked once by hand and once from the content. Both act on the
@@ -1144,12 +1144,12 @@ export const homeGroups = (ctx: RibbonTabContext) => {
1144
  so `SheetGrid.tsx` states it where it is implemented: the document stores a
1145
  width PER COLUMN and one shared row height, so a column fits itself and a
1146
  row moves the base. */}
1147
- {item("AutoFit row height", () => act("autofit-rows"))}
1148
- {item("AutoFit column width", () => act("autofit-columns"))}
1149
- {item("Hide rows", () => act("hide-rows"))}
1150
- {item("Hide columns", () => act("hide-columns"))}
1151
  {item("Unhide", () => act("unhide"))}
1152
- {/* ⭐ W51-T34 LANDED, so this OPENS a Freeze panes panel offering rows and
1153
  columns rather than toggling one column. The label had to move with the
1154
  behaviour: a control that says "Freeze first column" and opens a
1155
  two-axis panel is the kind of small lie an owner finds in the first
@@ -1158,7 +1158,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
1158
  ⚠ THE LABEL IS BYTE-PINNED in `verify_api.py`'s `_RIBBON_GROUPS` Cells
1159
  tuple, so the two move in ONE commit or the rename reds a leg in a
1160
  ticket that never touched this file. */}
1161
- {item("Freeze panes", () => act("freeze"), frozen,
1162
  "menuitemcheckbox")}
1163
  </AnchoredOverlay>
1164
  )}
@@ -1169,7 +1169,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
1169
  {/* ⭐⭐ W54-T07 (owner instruction 5, ruling R2) — EDITING IS TWO ROWS AND FINISHES THE GROUP.
1170
  Excel's Editing group is AutoSum, Fill, Clear, Sort & Filter and Find & Select; R2 removes
1171
  Sort & Filter outright (owner, verbatim: the table function IS basically the data module
1172
- itself), so what completes the group is Find and select and nothing else.
1173
 
1174
  ⛔ THE STACK IS A WIDTH DECISION (D-663), and this is the group where it bites hardest:
1175
  Editing is the LAST of the seven, so everything the six before it spend comes out of its
@@ -1182,7 +1182,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
1182
  speak to that one surface, so there is no second find box in this app and no second place
1183
  for the two to disagree about what a match is.
1184
  ⛔ ITS KEY-TIP IS `SL`, NOT EXCEL'S `FD`. Excel's own Find & Select sequence collides here
1185
- with Fill down, whose `FD` is byte-pinned in `verify_ui.py::_RIBBON_KEYTIPS`; a duplicate
1186
  badge would make one of the two unreachable from the keyboard, so the newcomer takes the
1187
  free sequence rather than the incumbent giving up a pinned one. */}
1188
  {group("Editing", (
@@ -1194,14 +1194,14 @@ export const homeGroups = (ctx: RibbonTabContext) => {
1194
  {stack(
1195
  <>
1196
  {/* ⚠ FILL DOWN AND FILL RIGHT HAVE NO ROW IN THE TICKET'S OWN INLINE KeyTip LIST.
1197
- `FD`/`FR` are invented, and were checked against `FP` (Format painter), `FS` (Font
1198
- size) and `FC` (Font colour). None is a PREFIX of another, which is the property
1199
  that actually matters; the Currency note above is what happens when one is. */}
1200
- {control("filldown", "Fill down", <IconFillDown />,
1201
  () => act("fill-down"), false, undefined, "FD")}
1202
  </>,
1203
  <>
1204
- {control("fillright", "Fill right", <IconFillRight />,
1205
  () => act("fill-right"), false, undefined, "FR")}
1206
  </>,
1207
  <>
@@ -1218,9 +1218,9 @@ export const homeGroups = (ctx: RibbonTabContext) => {
1218
  ariaLabel="Clear"
1219
  initialFocus="none"
1220
  >
1221
- {item("Clear contents", () => act("clear-contents"))}
1222
- {item("Clear formats", () => act("clear-formats"))}
1223
- {item("Clear all", () => act("clear-all"))}
1224
  </AnchoredOverlay>
1225
  )}
1226
  </span>
@@ -1228,7 +1228,7 @@ export const homeGroups = (ctx: RibbonTabContext) => {
1228
  )}
1229
  {large(<>
1230
  <span className="sheet-ribbon-slot">
1231
- {control("findselect", "Find and select", <><IconFindSelect />{word("Find and select")}</>,
1232
  openPop("findselect"), false, open === "findselect",
1233
  "SL", "gallery")}
1234
  {open === "findselect" && (
@@ -1237,16 +1237,16 @@ export const homeGroups = (ctx: RibbonTabContext) => {
1237
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1238
  onDismiss={closePop}
1239
  role="menu"
1240
- ariaLabel="Find and select"
1241
  initialFocus="none"
1242
  >
1243
  {item("Find", () => act("find"))}
1244
  {item("Replace", () => act("replace"))}
1245
  {/* ⭐ GO TO ADDS NO SURFACE OF ITS OWN. Excel's Name Box is already in this app,
1246
  as the formula bar's cell address input, and it already jumps to whatever
1247
- address is typed into it; what a Go to item owes a person is therefore the
1248
  focus, not a second dialog asking the same question. */}
1249
- {item("Go to", () => act("go-to"))}
1250
  </AnchoredOverlay>
1251
  )}
1252
  </span>
 
22
  //
23
  // ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5) — unchanged and still binding here: icons are inline
24
  // SVG on `currentColor` and never emoji, a colour swatch is a token-styled span, colour and type
25
+ // are token only, Excel's Title Case labels (R41), no em dash or en dash in any string that reaches a screen.
26
 
27
  import {
28
  CELL_FONTS, CELL_FORMAT_KINDS, DEFAULT_CELL_FONT, FONT_SIZE_STEPS, FONT_STACKS,
 
69
  ] as const;
70
  // ⭐⭐ W53-T05 (instruction 16) — TWO VISUAL ROWS, ONE ROVING ORDER, AND THE ORDER IS THE READING
71
  // ORDER. Excel lays Alignment out as two rows, so this array is re-sequenced to match what the eye
72
+ // walks: top row (vertical align, then Wrap Text), then bottom row (horizontal align, then the two
73
  // indents). ⛔ THE ARRAY IS THE ROVING SOURCE AND THE JSX IS NOT: a key listed here with no
74
  // `control(...)` call rendering it makes ArrowRight land on nothing, with every gate still green,
75
  // so the two are changed together or not at all.
76
+ // ⭐⭐ W54-T06 (instruction 5, ruling R2) ADDS `orientation` TO THE TOP ROW, after Wrap Text.
77
  // The top row carried four controls against the bottom row's five, so the group takes no extra
78
  // width at all: measured at 1440x900 the strip's group edges are unchanged by this ticket.
79
  const ALIGNMENT = [
 
90
  const STYLES = ["conditional", "cellstyles"] as const;
91
  const CELLS = ["insert", "delete", "cellformat"] as const;
92
  // ⭐⭐ W54-T07 (instruction 5, ruling R2) — EDITING IS TWO ROWS AND GAINS FIND AND SELECT.
93
+ // Top row: AutoSum, Fill Down, Fill Right. Bottom row: Clear, then the new Find & Select
94
  // gallery. ⛔ THE STACK IS A WIDTH DECISION, NOT A TIDY (D-663): Editing is the LAST group in the
95
  // strip and measured at 1440x900 it ended at 1385 of a 1440 viewport, so a fifth control laid
96
  // beside the other four would have taken most of the 55px that was left. Stacked, the group is
 
212
  /**
213
  * ⛔ THE FIVE THE DOCUMENT MODEL CARRIES, AND ONLY THOSE. `CELL_FORMAT_KINDS` is mirrored in
214
  * `platform/core/sheets.py` and a sixth spelling is REFUSED by name on the way in, so R8's
215
+ * Accounting and Custom Code are offered as ACTS (`format-accounting`, `format-custom`) rather
216
  * than smuggled in here as a kind the server would reject.
217
  */
218
  const FORMAT_LABEL: Record<CellFormatKind, string> = {
 
439
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
440
  onDismiss={closePop}
441
  role="menu"
442
+ ariaLabel={which === "color" ? "Font Color" : "Fill Color"}
443
  initialFocus="none"
444
  >
445
  <div className="sheet-ribbon-swatches">
 
526
  <>
527
  {/* ⭐⭐ W52-T16 (instruction 18, ruling R4) — THE ARRANGEMENT INSTRUCTION 18 NAMES
528
  EXPLICITLY: a large split Paste on the left (icon above, caption below) with Cut,
529
+ Copy and Format Painter stacked as three small icon+label rows to its right,
530
  exactly like Excel's own Clipboard group.
531
  The tall Paste control opens the existing anchored menu vocabulary. Normal paste and
532
  both named paste-special layers still travel through the one `paste` act; its argument
 
542
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
543
  onDismiss={closePop}
544
  role="menu"
545
+ ariaLabel="Paste Options"
546
  initialFocus="first"
547
  >
548
  {item("Paste", () => act("paste", "normal"))}
549
+ {item("Paste Values", () => act("paste", "values"))}
550
+ {item("Paste Formatting", () => act("paste", "formatting"))}
551
  </AnchoredOverlay>
552
  )}
553
  </>)}
 
560
  the large Paste is exactly that.
561
  ⛔ THE LABEL IS NOT DELETED, ONLY THE PAINTED WORD. `control()` writes its
562
  `label` argument into BOTH `aria-label` and `title`, so a screen reader still
563
+ announces "Format Painter" and a hover still says it. That matters twice over:
564
  `verify_api.py`'s `_RIBBON_GROUPS` pins the literals `"Cut"`, `"Copy"` and
565
+ `"Format Painter"` as the proof this group still offers what R8 names, and an
566
  icon-only control with no accessible name is a regression no gate in this repo
567
  would catch. */}
568
  {stack(
 
575
  false, undefined, "C")}
576
  </>,
577
  <>
578
+ {control("painter", "Format Painter", <IconFormatPainter />,
579
  () => act("format-painter"), false, undefined, "FP")}
580
  </>
581
  )}
 
584
 
585
  {/* ⭐⭐ W54-T03 (owner instruction 4, rulings R10 + R11) — THE FONT GROUP IS EXCEL'S OWN
586
  TWO ROWS. Top row: the font FAMILY combo, then the editable font SIZE box with its own
587
+ gallery caret, then Increase and Decrease Font Size. Bottom row: bold, italic, underline,
588
  then borders, fill colour and text colour, which is exactly what this group carried
589
  before. The mechanism is the one Clipboard and Alignment already established: a COLUMN
590
  wrapper inside `.sheet-ribbon-group-controls`, each row a plain row flex of the SAME
 
675
  }}
676
  onBlur={(e) => commitPoints(e.currentTarget)}
677
  />
678
+ {control("size", "Font Size", <IconCaret />,
679
  openPop("size"), false, open === "size",
680
  "FS", "gallery")}
681
  {open === "size" && (
 
684
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
685
  onDismiss={closePop}
686
  role="menu"
687
+ ariaLabel="Font Size"
688
  initialFocus="none"
689
  >
690
  {FONT_SIZE_STEPS.map((step) => item(
 
697
  returns the size it was given when there is no next entry, so the largest and the
698
  smallest are quiet no-ops rather than an error or a wrap around. From a size that is
699
  not on the list at all, it walks to the nearest entry in the direction asked for. */}
700
+ {control("grow", "Increase Font Size", <IconFontStep up />,
701
  () => apply({ size: stepFontPt(points, 1) }), false, undefined, "FG")}
702
+ {control("shrink", "Decrease Font Size", <IconFontStep up={false} />,
703
  () => apply({ size: stepFontPt(points, -1) }), false, undefined, "FK")}
704
  </>,
705
  <>
 
729
  {BORDERS.map((entry) => item(
730
  entry.label, () => apply({ border: entry.sides }), false, "menuitem", entry.kt,
731
  ))}
732
+ {item("No Border", () => apply({ border: null }), false, "menuitem", "N")}
733
  </AnchoredOverlay>
734
  )}
735
  </span>
736
  {/* ⚠ FILL COLOUR AND TEXT COLOUR BOTH OPEN A SWATCH POPOVER IN THIS CODEBASE
737
  (`open === "fill"` / `open === "color"`), so both carry `data-kt-opens`
738
  per the general C4 rule even though the ticket's own inline example list did
739
+ not annotate Fill Color with "/opens" — a judgment call, documented here and
740
  in the HANDOFF, resolved in favour of matching the code's real behaviour. */}
741
  <span className="sheet-ribbon-slot">
742
+ {control("fill", "Fill Color",
743
  <><IconFill colour={fillColour} /><IconCaret /></>,
744
  openPop("fill"), !!style?.fill, open === "fill",
745
  "H", "gallery")}
746
  {open === "fill" && swatches("fill", FILLS)}
747
  </span>
748
  <span className="sheet-ribbon-slot">
749
+ {control("color", "Font Color",
750
  <><IconInk colour={inkColour} /><IconCaret /></>,
751
  openPop("color"), !!style?.color,
752
  open === "color", "FC", "gallery")}
 
764
  plain row flex of the SAME `control()` buttons. No new control shape, no new
765
  button size, and the two rows total 52px, which is exactly the height Clipboard's
766
  large Paste already sets, so the ribbon does not grow by a pixel.
767
+ ⚠ THE SIX ALIGNMENT BUTTONS STAY ICON ONLY, and so does Wrap Text: the researched
768
  Excel convention is that only a WIDE combo box or a TALL two-row-spanning button
769
  carries a caption, and none of these is either. `control()` writes the label into
770
  both `aria-label` and `title`, so every one of them keeps its accessible name.
 
785
  KeyTip LIST (it names align top/middle/bottom as one of the examples with no
786
  row to copy). `AT`/`AM`/`AB` follows the same two-letter shape the spec's
787
  real Excel sequences use for the horizontal three (`AL`/`AC`/`AR`). */}
788
+ {control("top", "Top Align", <IconVAlign to="top" />, () => act("align-top"),
789
  false, undefined, "AT")}
790
+ {control("middle", "Middle Align", <IconVAlign to="middle" />,
791
  () => act("align-middle"), false, undefined, "AM")}
792
+ {control("bottom", "Bottom Align", <IconVAlign to="bottom" />,
793
  () => act("align-bottom"), false, undefined, "AB")}
794
+ {control("wrap", "Wrap Text", <IconWrap />, () => act("wrap-text"),
795
  false, undefined, "W")}
796
  {/* ⭐⭐ W54-T06 (instruction 5, ruling R2) — TEXT ORIENTATION, AND IT NEEDED NO NEW
797
  ACT. The base kit had already declared `CellStyle.textRotation` and
 
801
  member, so the shell's exhaustive switch in `SheetGrid.tsx` gains no arm and
802
  `Ribbon.tsx` is untouched. The lane's OTHER three obligations were paid in the same
803
  change - `stylePaints` counts the key, `paintCell` turns the canvas, and
804
+ `cellStyleOps.ts::STYLE_KEYS` names it so the Format Painter clears it.
805
  ⚠ FIVE ENTRIES, WHICH IS EXCEL'S OWN LIST MINUS THE ONE THIS SLOT CANNOT SAY.
806
  Vertical stacked text is not a rotation at all (it is a per character layout), and
807
  the slot is a signed degree between -90 and 90, so offering it would be a control
 
840
  are checked as that one expression rather than per call. */}
841
  {(["left", "center", "right"] as const).map((to) => control(
842
  to,
843
+ to === "left" ? "Align Left" : to === "center" ? "Center" : "Align Right",
844
  <IconAlign to={to} />,
845
  () => apply({ align: style?.align === to ? null : to }),
846
  style?.align === to,
847
  undefined,
848
  to === "left" ? "AL" : to === "center" ? "AC" : "AR",
849
  ))}
850
+ {control("outdent", "Decrease Indent", <IconIndent out />,
851
  () => act("indent-decrease"), false, undefined, "5")}
852
+ {control("indent", "Increase Indent", <IconIndent out={false} />,
853
  () => act("indent-increase"), false, undefined, "6")}
854
  </>
855
  )
 
858
  {group("Number", stack(
859
  <>
860
  <span className="sheet-ribbon-slot sheet-ribbon-number-format">
861
+ {control("format", "Number Format",
862
  <><span className="sheet-ribbon-label">{FORMAT_LABEL[kind]}</span><IconCaret /></>,
863
  openPop("format"), kind !== "general",
864
  open === "format", "N", "gallery")}
 
868
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
869
  onDismiss={closePop}
870
  role="menu"
871
+ ariaLabel="Number Format"
872
  initialFocus="none"
873
  >
874
  {/* ⚠ FILTERED, AND D-671 IS WHY. Wave 54's base kit widened `CELL_FORMAT_KINDS`
 
905
  not kinds: `clean_cell` refuses an unknown `format.kind` BY NAME, so
906
  writing `accounting` here would refuse the whole cell. */}
907
  {item("Accounting", () => act("format-accounting"))}
908
+ {item("Custom Code", () => act("format-custom"))}
909
  {/* ⚠ THE TWO OPTIONS A1 NAMES BY NAME: decimals, and thousands. They are
910
  shown only where they mean something; a date has neither and a percent
911
  groups by locale. */}
 
962
  <span className="sheet-ribbon-glyph">$</span>,
963
  () => apply({ format: { kind: "currency", decimals: 2 } }),
964
  kind === "currency", undefined, "CU")}
965
+ {control("percent", "Percent Style",
966
  <span className="sheet-ribbon-glyph">%</span>,
967
  () => apply({ format: { kind: "percent", decimals: 0 } }),
968
  kind === "percent", undefined, "P")}
969
+ {control("comma", "Comma Style",
970
  <span className="sheet-ribbon-glyph">,</span>,
971
  () => apply({ format: { kind: "number", decimals: 2, thousands: true } }),
972
  kind === "number" && format?.thousands === true, undefined, "K")}
 
974
  (spec KT-T1; Corporate Finance Institute's "Alt+H+O" for Increase Decimal is almost
975
  certainly the digit rendered as a letter, since Decrease Decimal is `9`). `decless` is
976
  this file's DECREASE control, `decmore` is INCREASE. */}
977
+ {control("decless", "Decrease Decimal", <IconDecimals more={false} />,
978
  () => stepDecimals(-1), false, undefined, "9")}
979
+ {control("decmore", "Increase Decimal", <IconDecimals more />,
980
  () => stepDecimals(1), false, undefined, "0")}
981
  </>
982
  ))}
 
993
  of those label literals, and they are all still right there in the call. */}
994
  {/* ⭐⭐ W54-T05 (owner instruction 5, ruling R2) — STYLES IS TWO STACKED ROWS NOW.
995
 
996
+ Conditional Formatting became a GALLERY: highlight-cells rules still open the editor
997
  W51-T18 built, and the two new items build a rule FROM THE SELECTION and route it through
998
+ the same `saveRules` door rather than opening a second one. Cell Styles is a gallery of
999
  named presets that write real `CellStyle` values.
1000
 
1001
  ⛔ FORMAT AS TABLE AND SORT AND FILTER ARE OUT, BY RULING R2, and that is a decision rather
 
1008
  that, and two 26px rows come to exactly `--sheet-ribbon-band`, so the ribbon does not grow
1009
  by a pixel in either direction. Same mechanism Clipboard, Alignment and Font already use.
1010
 
1011
+ ⛔ THE LABEL "Conditional Formatting" IS BYTE-PINNED in `verify_api.py`'s `_RIBBON_GROUPS`
1012
  Styles tuple and its key-tip "L" in `verify_ui.py::_RIBBON_KEYTIPS`, so both stay exactly
1013
  where they were even though the control now opens a menu instead of firing an act. */}
1014
  {group("Styles", (
1015
  stack(
1016
  <>
1017
  <span className="sheet-ribbon-slot">
1018
+ {control("conditional", "Conditional Formatting",
1019
  <><IconConditional /><IconCaret /></>,
1020
  openPop("conditional"), false, open === "conditional", "L", "gallery")}
1021
  {open === "conditional" && (
 
1024
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1025
  onDismiss={closePop}
1026
  role="menu"
1027
+ ariaLabel="Conditional Formatting"
1028
  initialFocus="none"
1029
  >
1030
+ {item("Highlight Cells Rules", () => act("conditional-formatting"))}
1031
+ {item("Color Scales", () => act("colour-scale"))}
1032
+ {item("Data Bars", () => act("data-bars"))}
1033
+ {item("Manage Rules", () => act("conditional-formatting"))}
1034
  </AnchoredOverlay>
1035
  )}
1036
  </span>
1037
  </>,
1038
  <>
1039
  <span className="sheet-ribbon-slot">
1040
+ {control("cellstyles", "Cell Styles",
1041
  <><IconCellStyles /><IconCaret /></>,
1042
  openPop("cellstyles"), false, open === "cellstyles", "J", "gallery")}
1043
  {open === "cellstyles" && (
 
1046
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1047
  onDismiss={closePop}
1048
  role="menu"
1049
+ ariaLabel="Cell Styles"
1050
  initialFocus="none"
1051
  >
1052
  {/* ⛔ WRITTEN OUT RATHER THAN PASSED THROUGH `item()` FOR ONE REASON: each row
 
1092
  ariaLabel="Insert"
1093
  initialFocus="none"
1094
  >
1095
+ {item("Insert Row Above", () => act("insert-row"))}
1096
+ {item("Insert Column Left", () => act("insert-column"))}
1097
+ {item("Add Rows", () => act("add-rows"))}
1098
+ {item("Add Columns", () => act("add-columns"))}
1099
  </AnchoredOverlay>
1100
  )}
1101
  </span>
 
1114
  ariaLabel="Delete"
1115
  initialFocus="none"
1116
  >
1117
+ {item("Delete Row", () => act("delete-row"))}
1118
+ {item("Delete Column", () => act("delete-column"))}
1119
  </AnchoredOverlay>
1120
  )}
1121
  </span>
 
1135
  ariaLabel="Format"
1136
  initialFocus="none"
1137
  >
1138
+ {item("Row Height", () => act("row-height"))}
1139
+ {item("Column Width", () => act("column-width"))}
1140
  {/* ⭐⭐ W54-T07 — THE TWO AUTOFITS SIT BESIDE THE TWO MANUAL SIZES, which is
1141
  Excel's own arrangement and also the honest one: each pair is the same
1142
  question asked once by hand and once from the content. Both act on the
 
1144
  so `SheetGrid.tsx` states it where it is implemented: the document stores a
1145
  width PER COLUMN and one shared row height, so a column fits itself and a
1146
  row moves the base. */}
1147
+ {item("AutoFit Row Height", () => act("autofit-rows"))}
1148
+ {item("AutoFit Column Width", () => act("autofit-columns"))}
1149
+ {item("Hide Rows", () => act("hide-rows"))}
1150
+ {item("Hide Columns", () => act("hide-columns"))}
1151
  {item("Unhide", () => act("unhide"))}
1152
+ {/* ⭐ W51-T34 LANDED, so this OPENS a Freeze Panes panel offering rows and
1153
  columns rather than toggling one column. The label had to move with the
1154
  behaviour: a control that says "Freeze first column" and opens a
1155
  two-axis panel is the kind of small lie an owner finds in the first
 
1158
  ⚠ THE LABEL IS BYTE-PINNED in `verify_api.py`'s `_RIBBON_GROUPS` Cells
1159
  tuple, so the two move in ONE commit or the rename reds a leg in a
1160
  ticket that never touched this file. */}
1161
+ {item("Freeze Panes", () => act("freeze"), frozen,
1162
  "menuitemcheckbox")}
1163
  </AnchoredOverlay>
1164
  )}
 
1169
  {/* ⭐⭐ W54-T07 (owner instruction 5, ruling R2) — EDITING IS TWO ROWS AND FINISHES THE GROUP.
1170
  Excel's Editing group is AutoSum, Fill, Clear, Sort & Filter and Find & Select; R2 removes
1171
  Sort & Filter outright (owner, verbatim: the table function IS basically the data module
1172
+ itself), so what completes the group is Find & Select and nothing else.
1173
 
1174
  ⛔ THE STACK IS A WIDTH DECISION (D-663), and this is the group where it bites hardest:
1175
  Editing is the LAST of the seven, so everything the six before it spend comes out of its
 
1182
  speak to that one surface, so there is no second find box in this app and no second place
1183
  for the two to disagree about what a match is.
1184
  ⛔ ITS KEY-TIP IS `SL`, NOT EXCEL'S `FD`. Excel's own Find & Select sequence collides here
1185
+ with Fill Down, whose `FD` is byte-pinned in `verify_ui.py::_RIBBON_KEYTIPS`; a duplicate
1186
  badge would make one of the two unreachable from the keyboard, so the newcomer takes the
1187
  free sequence rather than the incumbent giving up a pinned one. */}
1188
  {group("Editing", (
 
1194
  {stack(
1195
  <>
1196
  {/* ⚠ FILL DOWN AND FILL RIGHT HAVE NO ROW IN THE TICKET'S OWN INLINE KeyTip LIST.
1197
+ `FD`/`FR` are invented, and were checked against `FP` (Format Painter), `FS` (Font
1198
+ Size) and `FC` (Font Color). None is a PREFIX of another, which is the property
1199
  that actually matters; the Currency note above is what happens when one is. */}
1200
+ {control("filldown", "Fill Down", <IconFillDown />,
1201
  () => act("fill-down"), false, undefined, "FD")}
1202
  </>,
1203
  <>
1204
+ {control("fillright", "Fill Right", <IconFillRight />,
1205
  () => act("fill-right"), false, undefined, "FR")}
1206
  </>,
1207
  <>
 
1218
  ariaLabel="Clear"
1219
  initialFocus="none"
1220
  >
1221
+ {item("Clear Contents", () => act("clear-contents"))}
1222
+ {item("Clear Formats", () => act("clear-formats"))}
1223
+ {item("Clear All", () => act("clear-all"))}
1224
  </AnchoredOverlay>
1225
  )}
1226
  </span>
 
1228
  )}
1229
  {large(<>
1230
  <span className="sheet-ribbon-slot">
1231
+ {control("findselect", "Find & Select", <><IconFindSelect />{word("Find & Select")}</>,
1232
  openPop("findselect"), false, open === "findselect",
1233
  "SL", "gallery")}
1234
  {open === "findselect" && (
 
1237
  className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1238
  onDismiss={closePop}
1239
  role="menu"
1240
+ ariaLabel="Find & Select"
1241
  initialFocus="none"
1242
  >
1243
  {item("Find", () => act("find"))}
1244
  {item("Replace", () => act("replace"))}
1245
  {/* ⭐ GO TO ADDS NO SURFACE OF ITS OWN. Excel's Name Box is already in this app,
1246
  as the formula bar's cell address input, and it already jumps to whatever
1247
+ address is typed into it; what a Go To item owes a person is therefore the
1248
  focus, not a second dialog asking the same question. */}
1249
+ {item("Go To", () => act("go-to"))}
1250
  </AnchoredOverlay>
1251
  )}
1252
  </span>
web/src/sheet/ribbonInsert.tsx CHANGED
@@ -46,7 +46,7 @@
46
  // value out of the submitted form rather than out of a `useState` this file cannot have.
47
  //
48
  // ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5): inline SVG on `currentColor` and never emoji, token
49
- // only colour and type, sentence case labels, no em dash or en dash in a string that reaches a
50
  // screen, and the two overlay shapes kept apart: POPOVERS originate at their trigger through
51
  // `AnchoredOverlay` (the link and comment forms) while MODALS REMAIN CENTRED (the chart dialog,
52
  // through `useOverlayLayer` and `BodyPortal`). Never a local keydown listener in either case.
@@ -226,9 +226,9 @@ const rangeText = (r: RuleRect): string => {
226
  const many = (n: number, word: string): string => `${n} ${word}${n === 1 ? "" : "s"}`;
227
 
228
  const KIND_LABEL: Record<SparklineKind, string> = {
229
- line: "Line sparkline",
230
- column: "Column sparkline",
231
- winloss: "Win loss sparkline",
232
  };
233
 
234
  /**
@@ -534,17 +534,17 @@ export const insertGroups = (ctx: RibbonTabContext) => {
534
  <span className="sheet-chart-gallery">
535
  {CHART_SHORTCUTS.map(({ key, moreKey, label, Icon, kt }) => (
536
  <span className="sheet-chart-kind" key={key}>
537
- {control(key, `${label} chart`, <Icon />,
538
  openPop(key), false, open === key, kt, "gallery", undefined, "dialog")}
539
  <span className="sheet-chart-kind-caret">
540
  {/* Q prefixes chart choices; the overflow trigger already owns Y. */}
541
- {control(moreKey, `${label} chart choices`, chartCaret,
542
  openPop(moreKey), false, open === moreKey, `Q${kt}`, "gallery", undefined, "dialog")}
543
  </span>
544
  </span>
545
  ))}
546
  <span className="sheet-chart-kind sheet-chart-kind-recommended">
547
- {control("chart-recommended", "Recommended charts", <IconChartRecommended />,
548
  openPop("chart-recommended"), false, open === "chart-recommended", "R", "gallery", undefined, "dialog")}
549
  </span>
550
  </span>
@@ -574,15 +574,15 @@ export const insertGroups = (ctx: RibbonTabContext) => {
574
  <>
575
  {stack(
576
  <>
577
- {control("sparkline-line", "Line sparkline", <IconSparkLine />,
578
  openPop("sparkline-line"), false, open === "sparkline-line", "SL", "gallery")}
579
  </>,
580
  <>
581
- {control("sparkline-column", "Column sparkline", <IconSparkColumn />,
582
  openPop("sparkline-column"), false, open === "sparkline-column", "SC", "gallery")}
583
  </>,
584
  <>
585
- {control("sparkline-winloss", "Win loss sparkline", <IconSparkWinLoss />,
586
  openPop("sparkline-winloss"), false, open === "sparkline-winloss", "SW", "gallery")}
587
  </>
588
  )}
@@ -679,13 +679,13 @@ export const insertGroups = (ctx: RibbonTabContext) => {
679
  )}
680
  </>)
681
  ))}
682
- {group("Cell data", large(<>
683
- {control("cell-data", "Cell database", <>
684
  <svg viewBox="0 0 16 16" stroke="currentColor" fill="none" aria-hidden="true" className="sheet-ribbon-icon">
685
  <ellipse cx="8" cy="3.5" rx="5" ry="2" />
686
  <path d="M3 3.5v9c0 1.1 2.2 2 5 2s5-.9 5-2v-9M3 8c0 1.1 2.2 2 5 2s5-.9 5-2" />
687
  </svg>
688
- {word("Cell database")}
689
  </>, openCellData, undefined, undefined, "D")}
690
  </>))}
691
  </fieldset>
 
46
  // value out of the submitted form rather than out of a `useState` this file cannot have.
47
  //
48
  // ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5): inline SVG on `currentColor` and never emoji, token
49
+ // only colour and type, Excel's Title Case labels (R41), no em dash or en dash in a string that reaches a
50
  // screen, and the two overlay shapes kept apart: POPOVERS originate at their trigger through
51
  // `AnchoredOverlay` (the link and comment forms) while MODALS REMAIN CENTRED (the chart dialog,
52
  // through `useOverlayLayer` and `BodyPortal`). Never a local keydown listener in either case.
 
226
  const many = (n: number, word: string): string => `${n} ${word}${n === 1 ? "" : "s"}`;
227
 
228
  const KIND_LABEL: Record<SparklineKind, string> = {
229
+ line: "Line Sparkline",
230
+ column: "Column Sparkline",
231
+ winloss: "Win/Loss Sparkline",
232
  };
233
 
234
  /**
 
534
  <span className="sheet-chart-gallery">
535
  {CHART_SHORTCUTS.map(({ key, moreKey, label, Icon, kt }) => (
536
  <span className="sheet-chart-kind" key={key}>
537
+ {control(key, `${label} Chart`, <Icon />,
538
  openPop(key), false, open === key, kt, "gallery", undefined, "dialog")}
539
  <span className="sheet-chart-kind-caret">
540
  {/* Q prefixes chart choices; the overflow trigger already owns Y. */}
541
+ {control(moreKey, `${label} Chart Choices`, chartCaret,
542
  openPop(moreKey), false, open === moreKey, `Q${kt}`, "gallery", undefined, "dialog")}
543
  </span>
544
  </span>
545
  ))}
546
  <span className="sheet-chart-kind sheet-chart-kind-recommended">
547
+ {control("chart-recommended", "Recommended Charts", <IconChartRecommended />,
548
  openPop("chart-recommended"), false, open === "chart-recommended", "R", "gallery", undefined, "dialog")}
549
  </span>
550
  </span>
 
574
  <>
575
  {stack(
576
  <>
577
+ {control("sparkline-line", "Line", <IconSparkLine />,
578
  openPop("sparkline-line"), false, open === "sparkline-line", "SL", "gallery")}
579
  </>,
580
  <>
581
+ {control("sparkline-column", "Column", <IconSparkColumn />,
582
  openPop("sparkline-column"), false, open === "sparkline-column", "SC", "gallery")}
583
  </>,
584
  <>
585
+ {control("sparkline-winloss", "Win/Loss", <IconSparkWinLoss />,
586
  openPop("sparkline-winloss"), false, open === "sparkline-winloss", "SW", "gallery")}
587
  </>
588
  )}
 
679
  )}
680
  </>)
681
  ))}
682
+ {group("Cell Data", large(<>
683
+ {control("cell-data", "Cell Database", <>
684
  <svg viewBox="0 0 16 16" stroke="currentColor" fill="none" aria-hidden="true" className="sheet-ribbon-icon">
685
  <ellipse cx="8" cy="3.5" rx="5" ry="2" />
686
  <path d="M3 3.5v9c0 1.1 2.2 2 5 2s5-.9 5-2v-9M3 8c0 1.1 2.2 2 5 2s5-.9 5-2" />
687
  </svg>
688
+ {word("Cell Database")}
689
  </>, openCellData, undefined, undefined, "D")}
690
  </>))}
691
  </fieldset>
web/src/sheet/ribbonView.tsx CHANGED
@@ -1,12 +1,12 @@
1
  // Sheet View ribbon, adapted from the behavior and grouping in the Wave 55 public Excel audit.
2
- // Workbook views, Show and Zoom use the tab view and formula bar doors.
3
 
4
  import type { RibbonTabContext } from "./Ribbon";
5
  import type { SheetTabView } from "./types";
6
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
7
 
8
  const WORKBOOK_VIEWS = ["view-normal", "view-page-break", "view-page-layout"] as const;
9
- const SHOW = ["view-gridlines", "view-headings", "view-formula-bar"] as const;
10
  const ZOOM = ["view-zoom", "view-zoom-100", "view-zoom-selection"] as const;
11
  const ZOOM_STEPS = [10, 25, 50, 75, 100, 125, 150, 200, 300, 400] as const;
12
  const WINDOW = ["view-new-window", "view-freeze", "view-hide", "view-unhide", "view-fullscreen"] as const;
@@ -60,15 +60,6 @@ function IconHeadings() {
60
  );
61
  }
62
 
63
- function IconFormulaBar() {
64
- return (
65
- <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
66
- <rect x="2.3" y="3.2" width="11.4" height="9.6" rx="1" />
67
- <path d="M4.5 6.2h7M4.5 9.5h4" />
68
- </svg>
69
- );
70
- }
71
-
72
  function IconZoom() {
73
  return (
74
  <svg viewBox="0 0 16 16" fill="none" aria-hidden="true" className="sheet-ribbon-icon">
@@ -163,25 +154,25 @@ export const viewGroups = (ctx: RibbonTabContext) => {
163
  const setView = (patch: Partial<SheetTabView>) => ctx.insert?.onTabView?.(patch);
164
  const zoomToSelection = () => ctx.insert?.zoomToSelection?.();
165
  const {
166
- act, anchorEl, closePop, control, formulaBarVisible, frozen, fullscreen, group, item,
167
  newWindowBlocked, open, openNewWindow, openPop,
168
- toggleFormulaBar, toggleFullscreen, unavailable, word, large, stack,
169
  } = ctx;
170
- const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen";
171
  return (
172
  <>
173
- {group("Workbook views", <>
174
  {large(<>
175
  {control("view-normal", "Normal", <><IconNormal />{word("Normal")}</>,
176
  () => setView({ pageView: "normal" }), pageView === "normal", undefined, "L")}
177
  </>)}
178
  {stack(
179
  <>
180
- {control("view-page-break", "Page break preview", <IconPageBreak />,
181
  () => setView({ pageView: "pageBreak" }), pageView === "pageBreak", undefined, "P")}
182
  </>,
183
  <>
184
- {control("view-page-layout", "Page layout", <IconPageLayout />,
185
  () => setView({ pageView: "pageLayout" }), pageView === "pageLayout", undefined, "K")}
186
  </>
187
  )}
@@ -198,12 +189,6 @@ export const viewGroups = (ctx: RibbonTabContext) => {
198
  "view-headings", "Headings", <IconHeadings />,
199
  () => setView({ headings: !headings }), headings, undefined, "H",
200
  )}
201
- </>,
202
- <>
203
- {control(
204
- "view-formula-bar", "Formula bar", <IconFormulaBar />,
205
- toggleFormulaBar, formulaBarVisible, undefined, "B",
206
- )}
207
  </>
208
  ))}
209
  {group("Zoom", <>
@@ -232,7 +217,7 @@ export const viewGroups = (ctx: RibbonTabContext) => {
232
  () => setView({ zoom: 100 }), zoomPercent === 100, undefined, "J")}
233
  </>,
234
  <>
235
- {control("view-zoom-selection", "Zoom to selection",
236
  <IconZoomSelection />,
237
  zoomToSelection, false, undefined, "S")}
238
  </>
@@ -241,14 +226,14 @@ export const viewGroups = (ctx: RibbonTabContext) => {
241
  {group("Window", <>
242
  {large(<>
243
  {control(
244
- "view-freeze", "Freeze panes", <><IconFreeze />{word("Freeze panes")}</>,
245
  () => act("freeze"), frozen, undefined, "F",
246
  )}
247
  </>)}
248
  {stack(
249
  <>
250
  {control(
251
- "view-new-window", "New window", <IconNewWindow />,
252
  openNewWindow, undefined, undefined, "W",
253
  )}
254
  </>,
@@ -277,7 +262,7 @@ export const viewGroups = (ctx: RibbonTabContext) => {
277
  )}
278
  {open === "view-unhide" && (
279
  <AnchoredOverlay anchor={anchorEl} className="sheet-ribbon-pop sheet-ribbon-pop-portal"
280
- onDismiss={closePop} role="menu" ariaLabel="Unhide a sheet" initialFocus="none">
281
  {hidden.length
282
  ? hidden.map(sheet => item(sheet.name, () => {
283
  ctx.insert?.onTabVisibility?.(sheet.id, "visible");
@@ -298,7 +283,7 @@ export const viewGroups = (ctx: RibbonTabContext) => {
298
  toggleFullscreen, fullscreen, undefined, "U",
299
  )))}
300
  {group("Navigation", large(control(
301
- "view-go-to", "Go to", <><IconGoTo />{word("Go to")}</>,
302
  () => act("go-to"), false, undefined, "N",
303
  )))}
304
  </>
 
1
  // Sheet View ribbon, adapted from the behavior and grouping in the Wave 55 public Excel audit.
2
+ // Workbook Views, Show and Zoom use the tab view.
3
 
4
  import type { RibbonTabContext } from "./Ribbon";
5
  import type { SheetTabView } from "./types";
6
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
7
 
8
  const WORKBOOK_VIEWS = ["view-normal", "view-page-break", "view-page-layout"] as const;
9
+ const SHOW = ["view-gridlines", "view-headings"] as const;
10
  const ZOOM = ["view-zoom", "view-zoom-100", "view-zoom-selection"] as const;
11
  const ZOOM_STEPS = [10, 25, 50, 75, 100, 125, 150, 200, 300, 400] as const;
12
  const WINDOW = ["view-new-window", "view-freeze", "view-hide", "view-unhide", "view-fullscreen"] as const;
 
60
  );
61
  }
62
 
 
 
 
 
 
 
 
 
 
63
  function IconZoom() {
64
  return (
65
  <svg viewBox="0 0 16 16" fill="none" aria-hidden="true" className="sheet-ribbon-icon">
 
154
  const setView = (patch: Partial<SheetTabView>) => ctx.insert?.onTabView?.(patch);
155
  const zoomToSelection = () => ctx.insert?.zoomToSelection?.();
156
  const {
157
+ act, anchorEl, closePop, control, frozen, fullscreen, group, item,
158
  newWindowBlocked, open, openNewWindow, openPop,
159
+ toggleFullscreen, unavailable, word, large, stack,
160
  } = ctx;
161
+ const fullscreenLabel = fullscreen ? "Exit Full Screen" : "Full Screen";
162
  return (
163
  <>
164
+ {group("Workbook Views", <>
165
  {large(<>
166
  {control("view-normal", "Normal", <><IconNormal />{word("Normal")}</>,
167
  () => setView({ pageView: "normal" }), pageView === "normal", undefined, "L")}
168
  </>)}
169
  {stack(
170
  <>
171
+ {control("view-page-break", "Page Break Preview", <IconPageBreak />,
172
  () => setView({ pageView: "pageBreak" }), pageView === "pageBreak", undefined, "P")}
173
  </>,
174
  <>
175
+ {control("view-page-layout", "Page Layout", <IconPageLayout />,
176
  () => setView({ pageView: "pageLayout" }), pageView === "pageLayout", undefined, "K")}
177
  </>
178
  )}
 
189
  "view-headings", "Headings", <IconHeadings />,
190
  () => setView({ headings: !headings }), headings, undefined, "H",
191
  )}
 
 
 
 
 
 
192
  </>
193
  ))}
194
  {group("Zoom", <>
 
217
  () => setView({ zoom: 100 }), zoomPercent === 100, undefined, "J")}
218
  </>,
219
  <>
220
+ {control("view-zoom-selection", "Zoom to Selection",
221
  <IconZoomSelection />,
222
  zoomToSelection, false, undefined, "S")}
223
  </>
 
226
  {group("Window", <>
227
  {large(<>
228
  {control(
229
+ "view-freeze", "Freeze Panes", <><IconFreeze />{word("Freeze Panes")}</>,
230
  () => act("freeze"), frozen, undefined, "F",
231
  )}
232
  </>)}
233
  {stack(
234
  <>
235
  {control(
236
+ "view-new-window", "New Window", <IconNewWindow />,
237
  openNewWindow, undefined, undefined, "W",
238
  )}
239
  </>,
 
262
  )}
263
  {open === "view-unhide" && (
264
  <AnchoredOverlay anchor={anchorEl} className="sheet-ribbon-pop sheet-ribbon-pop-portal"
265
+ onDismiss={closePop} role="menu" ariaLabel="Unhide a Sheet" initialFocus="none">
266
  {hidden.length
267
  ? hidden.map(sheet => item(sheet.name, () => {
268
  ctx.insert?.onTabVisibility?.(sheet.id, "visible");
 
283
  toggleFullscreen, fullscreen, undefined, "U",
284
  )))}
285
  {group("Navigation", large(control(
286
+ "view-go-to", "Go To", <><IconGoTo />{word("Go To")}</>,
287
  () => act("go-to"), false, undefined, "N",
288
  )))}
289
  </>
web/src/sheet/sheetState.ts CHANGED
@@ -12,11 +12,11 @@
12
 
13
  import type {
14
  BindingOnDrag, BindingPeriod, Cell, CellFormat, CellMap, CellState,
15
- PeriodUnit, Workbook, SheetTab, SheetTabView, SheetChartSpec,
16
  } from "./types";
17
  import {
18
  asNumber, bindingOnDrag, bindingPeriod, BINDING_PERIOD_STEP, BINDING_ENDING_STEP, formatCellText, chartDocumentGeometry, chartRangeAfterStructure,
19
- DEFAULT_COL_WIDTH, MAX_COL_WIDTH, MAX_SHEET_COLS, MAX_SHEET_ROWS, MIN_COL_WIDTH, sheetExtent,
20
  } from "./types";
21
  // ⭐ THE ONLY THING THIS FILE BORROWS. `a1.ts` owns Excel's `$` anchoring rule, the quoted-text
22
  // guard and the one reference scanner; `fillCells` and the structural doors below call it rather
@@ -438,6 +438,9 @@ export const commitTyped = (
438
  text: string,
439
  get?: (addr: string) => CellValue,
440
  ): Cell | null => {
 
 
 
441
  if (String(text ?? "") === "") return blankOf(cell);
442
  return isFormulaText(text) ? setFormula(cell, text, get) : setLiteral(cell, text);
443
  };
@@ -1867,12 +1870,8 @@ export const fillCells = (
1867
  // below the insertion point. Reusing the fill would move `=B2` when a row was inserted at 4.
1868
  // ═════════════════════════════════════════════════════════════════════════════════════════════
1869
 
1870
- /** One structural change to one axis of one tab. `at` is 1 based; `delta` inserts or deletes. */
1871
- export interface StructureOp {
1872
- axis: "row" | "col";
1873
- at: number;
1874
- delta: number;
1875
- }
1876
 
1877
  const ADDR = /^([A-Z]{1,3})([0-9]{1,7})$/;
1878
 
@@ -1935,6 +1934,36 @@ export const structureRefusal = (
1935
  op: StructureOp,
1936
  ): string => {
1937
  const tab = tabOf(book, tabId);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1938
  if (!tab || !op.delta) return "";
1939
  const extent = sheetExtent(tab);
1940
  const limit = op.axis === "row" ? extent.rows : extent.cols;
@@ -1948,10 +1977,10 @@ export const structureRefusal = (
1948
  }
1949
  return "";
1950
  }
1951
- for (const addr of Object.keys(tab.cells ?? {})) {
1952
  const pos = splitAddress(addr);
1953
  if (!pos) continue;
1954
- const value = op.axis === "row" ? pos.row : pos.col;
1955
  if (value >= op.at && value + op.delta > limit) {
1956
  return `The last ${what} of this sheet holds a value, so inserting a ${what} would push it `
1957
  + `off the sheet. Add more ${what}s first, then insert.`;
@@ -1960,6 +1989,12 @@ export const structureRefusal = (
1960
  return "";
1961
  };
1962
 
 
 
 
 
 
 
1963
  /** Re-anchor formulas, binding slots (including ending cells), and cell/sheet links on one tab. */
1964
  const reanchorCells = (tab: SheetTab, shift: StructuralShift): CellMap => {
1965
  const out: CellMap = {};
@@ -2003,9 +2038,32 @@ const moveCells = (cells: CellMap, op: StructureOp): CellMap => {
2003
  const value = op.axis === "row" ? pos.row : pos.col;
2004
  const moved = movedIndex(value, op.at, op.delta);
2005
  if (moved === null) continue;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2006
  out[op.axis === "row"
2007
  ? `${indexToCol(pos.col)}${moved}`
2008
- : `${indexToCol(moved)}${pos.row}`] = cell;
2009
  }
2010
  return out;
2011
  };
@@ -2037,6 +2095,7 @@ export const applyStructure = (
2037
  tabId: string,
2038
  op: StructureOp,
2039
  ): SheetTab[] => {
 
2040
  const target = tabOf(book, tabId);
2041
  if (!target || !op.delta) return book.sheets;
2042
  const shift: StructuralShift = {
@@ -2062,6 +2121,14 @@ export const applyStructure = (
2062
  export const applyStructureWorkbook = (
2063
  book: Workbook, tabId: string, op: StructureOp,
2064
  ): Workbook => {
 
 
 
 
 
 
 
 
2065
  const sheets = applyStructure(book, tabId, op);
2066
  if (sheets === book.sheets) return book;
2067
  const target = tabOf(book, tabId)!;
@@ -2157,8 +2224,27 @@ export const growSheet = (
2157
  };
2158
  });
2159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2160
  /**
2161
- * Remember a dragged column width. A default width is stored as an ABSENCE, like the server.
2162
  *
2163
  * ⚠ IT RETURNS THE SHEETS IT WAS GIVEN WHEN NOTHING CHANGED, and that is not a micro
2164
  * optimisation: `SheetPage.tsx::commitSheets` refuses an array it already holds, so a click on
@@ -2175,6 +2261,10 @@ export const setColumnWidth = (
2175
  if (!target) return book.sheets;
2176
  const letters = indexToCol(colIndex + 1);
2177
  const next = Math.max(MIN_COL_WIDTH, Math.min(MAX_COL_WIDTH, Math.round(width)));
 
 
 
 
2178
  const current = (target.colWidths ?? {})[letters] ?? DEFAULT_COL_WIDTH;
2179
  if (current === next) return book.sheets;
2180
  return book.sheets.map((tab) => {
 
12
 
13
  import type {
14
  BindingOnDrag, BindingPeriod, Cell, CellFormat, CellMap, CellState,
15
+ PeriodUnit, Workbook, SheetTab, SheetTabView, SheetChartSpec, StructureOp,
16
  } from "./types";
17
  import {
18
  asNumber, bindingOnDrag, bindingPeriod, BINDING_PERIOD_STEP, BINDING_ENDING_STEP, formatCellText, chartDocumentGeometry, chartRangeAfterStructure,
19
+ DEFAULT_COL_WIDTH, MAX_COL_WIDTH, MAX_SHEET_COLS, MAX_SHEET_ROWS, MIN_COL_WIDTH, sheetExtent, viewBlockSize,
20
  } from "./types";
21
  // ⭐ THE ONLY THING THIS FILE BORROWS. `a1.ts` owns Excel's `$` anchoring rule, the quoted-text
22
  // guard and the one reference scanner; `fillCells` and the structural doors below call it rather
 
438
  text: string,
439
  get?: (addr: string) => CellValue,
440
  ): Cell | null => {
441
+ // A placed row carries Data text, even when it starts with '='. SheetGrid intercepts this
442
+ // draft before persistence and routes it through the record writer instead of sheet storage.
443
+ if (cell?.viewChild) return setLiteral(cell, String(text ?? ""));
444
  if (String(text ?? "") === "") return blankOf(cell);
445
  return isFormulaText(text) ? setFormula(cell, text, get) : setLiteral(cell, text);
446
  };
 
1870
  // below the insertion point. Reusing the fill would move `=B2` when a row was inserted at 4.
1871
  // ═════════════════════════════════════════════════════════════════════════════════════════════
1872
 
1873
+ // Existing consumers keep their import path; the atomic placement contract lives in types.ts.
1874
+ export type { StructureOp } from "./types";
 
 
 
 
1875
 
1876
  const ADDR = /^([A-Z]{1,3})([0-9]{1,7})$/;
1877
 
 
1934
  op: StructureOp,
1935
  ): string => {
1936
  const tab = tabOf(book, tabId);
1937
+ if (tab && op.place) {
1938
+ // Check BOTH pushes before either is committed. A refresh refusal keeps the old cells.
1939
+ let projected = book;
1940
+ const extent = sheetExtent(tab);
1941
+ for (const step of [op, ...(op.place.also ? [op.place.also] : [])]) {
1942
+ if (!step.delta) continue;
1943
+ const limit = step.axis === "row" ? extent.rows : extent.cols;
1944
+ const code = step.axis === "row" ? "view_push_past_last_row" : "view_push_past_last_col";
1945
+ if (step.delta > 0 && (step.at < 1 || step.at + step.delta - 1 > limit)) return code;
1946
+ const current = tabOf(projected, tabId)!;
1947
+ if (step.delta > 0 && Object.entries(current.cells).some(([addr, cell]) => {
1948
+ const pos = splitAddress(addr);
1949
+ const value = pos && reservedCellEnd(pos, cell, step.axis);
1950
+ return value !== null && value >= step.at && value + step.delta > limit;
1951
+ })) return code;
1952
+ const plain = { axis: step.axis, at: step.at, delta: step.delta };
1953
+ const refusal = structureRefusal(projected, tabId, plain);
1954
+ if (refusal) return refusal;
1955
+ projected = applyStructureWorkbook(projected, tabId, plain);
1956
+ }
1957
+ for (const [addr, cell] of Object.entries(op.place.cells)) {
1958
+ if (!cell) continue;
1959
+ const pos = splitAddress(addr);
1960
+ if (pos && pos.row > extent.rows) return "view_push_past_last_row";
1961
+ if (pos && pos.col > extent.cols) return "view_push_past_last_col";
1962
+ if (pos && reservedCellEnd(pos, cell, "row") > extent.rows) return "view_push_past_last_row";
1963
+ if (pos && reservedCellEnd(pos, cell, "col") > extent.cols) return "view_push_past_last_col";
1964
+ }
1965
+ return "";
1966
+ }
1967
  if (!tab || !op.delta) return "";
1968
  const extent = sheetExtent(tab);
1969
  const limit = op.axis === "row" ? extent.rows : extent.cols;
 
1977
  }
1978
  return "";
1979
  }
1980
+ for (const [addr, cell] of Object.entries(tab.cells ?? {})) {
1981
  const pos = splitAddress(addr);
1982
  if (!pos) continue;
1983
+ const value = reservedCellEnd(pos, cell, op.axis);
1984
  if (value >= op.at && value + op.delta > limit) {
1985
  return `The last ${what} of this sheet holds a value, so inserting a ${what} would push it `
1986
  + `off the sheet. Add more ${what}s first, then insert.`;
 
1989
  return "";
1990
  };
1991
 
1992
+ /** Empty reserved cells still occupy the sheet edge, even though only their anchor is stored. */
1993
+ const reservedCellEnd = (pos: { col: number; row: number }, cell: Cell | null | undefined,
1994
+ axis: "row" | "col"): number => pos[axis] + (cell?.kind === "bound"
1995
+ && cell.binding?.mode === "view" && cell.binding.viewType !== "grid" && cell.binding.block
1996
+ ? viewBlockSize(cell.binding)[axis === "row" ? "rows" : "cols"] - 1 : 0);
1997
+
1998
  /** Re-anchor formulas, binding slots (including ending cells), and cell/sheet links on one tab. */
1999
  const reanchorCells = (tab: SheetTab, shift: StructuralShift): CellMap => {
2000
  const out: CellMap = {};
 
2038
  const value = op.axis === "row" ? pos.row : pos.col;
2039
  const moved = movedIndex(value, op.at, op.delta);
2040
  if (moved === null) continue;
2041
+ let next = cell;
2042
+ if (cell?.kind === "bound" && cell.binding?.mode === "view"
2043
+ && cell.binding.viewType !== "grid" && cell.binding.block) {
2044
+ const size = viewBlockSize(cell.binding);
2045
+ const key = op.axis === "row" ? "rows" : "cols";
2046
+ const end = value + size[key];
2047
+ // An interior insert grows the reservation; deleting its tail shrinks it. Moving a
2048
+ // whole block (including a row inserted above it) keeps its cell dimensions unchanged.
2049
+ const delta = op.delta > 0 ? (op.at > value && op.at < end ? op.delta : 0)
2050
+ : -Math.max(0, Math.min(end, op.at - op.delta) - Math.max(value, op.at));
2051
+ if (delta) next = { ...cell, binding: { ...cell.binding,
2052
+ block: { ...size, [key]: Math.max(1, size[key] + delta) } } };
2053
+ }
2054
+ if (cell?.viewChild) {
2055
+ const origin = splitAddress(cell.viewChild.origin);
2056
+ if (origin) {
2057
+ const index = movedIndex(op.axis === "row" ? origin.row : origin.col, op.at, op.delta);
2058
+ next = { ...cell };
2059
+ if (index === null) delete next.viewChild;
2060
+ else next.viewChild = { ...cell.viewChild, origin: op.axis === "row"
2061
+ ? `${indexToCol(origin.col)}${index}` : `${indexToCol(index)}${origin.row}` };
2062
+ }
2063
+ }
2064
  out[op.axis === "row"
2065
  ? `${indexToCol(pos.col)}${moved}`
2066
+ : `${indexToCol(moved)}${pos.row}`] = next;
2067
  }
2068
  return out;
2069
  };
 
2095
  tabId: string,
2096
  op: StructureOp,
2097
  ): SheetTab[] => {
2098
+ if (op.place) return applyStructureWorkbook(book, tabId, op).sheets;
2099
  const target = tabOf(book, tabId);
2100
  if (!target || !op.delta) return book.sheets;
2101
  const shift: StructuralShift = {
 
2121
  export const applyStructureWorkbook = (
2122
  book: Workbook, tabId: string, op: StructureOp,
2123
  ): Workbook => {
2124
+ if (op.place) {
2125
+ if (!tabOf(book, tabId) || structureRefusal(book, tabId, op)) return book;
2126
+ const primary = { axis: op.axis, at: op.at, delta: op.delta };
2127
+ let next = applyStructureWorkbook(book, tabId, primary);
2128
+ if (op.place.also) next = applyStructureWorkbook(next, tabId, op.place.also);
2129
+ return { ...next, sheets: next.sheets.map(tab => tab.id === tabId
2130
+ ? tabWithEdits(tab, op.place!.cells) : tab) };
2131
+ }
2132
  const sheets = applyStructure(book, tabId, op);
2133
  if (sheets === book.sheets) return book;
2134
  const target = tabOf(book, tabId)!;
 
2224
  };
2225
  });
2226
 
2227
+ /** The width Unhide restores, in document pixels; never pass a stored zero to the canvas. */
2228
+ export const lastVisibleWidth = (tab: SheetTab, colIndex: number): number => {
2229
+ const width = tab.colWidths?.[indexToCol(colIndex + 1)];
2230
+ return width !== undefined && Number.isFinite(width) && width > 0
2231
+ ? Math.max(1, Math.min(MAX_COL_WIDTH, Math.round(width))) : DEFAULT_COL_WIDTH;
2232
+ };
2233
+
2234
+ /** R14 / C1: a zero-width intent hides a zero-based column without overwriting its width. */
2235
+ export const hideColumnByWidth = (tab: SheetTab, colIndex: number): SheetTab => {
2236
+ const letters = indexToCol(colIndex + 1);
2237
+ const width = lastVisibleWidth(tab, colIndex);
2238
+ if (tab.hiddenCols?.includes(colIndex + 1) && tab.colWidths?.[letters] === width) return tab;
2239
+ return {
2240
+ ...tab,
2241
+ hiddenCols: withHidden(tab.hiddenCols, [colIndex + 1], true),
2242
+ colWidths: { ...tab.colWidths, [letters]: width },
2243
+ };
2244
+ };
2245
+
2246
  /**
2247
+ * Remember a dragged column width. Zero hides; a default width is stored as an ABSENCE.
2248
  *
2249
  * ⚠ IT RETURNS THE SHEETS IT WAS GIVEN WHEN NOTHING CHANGED, and that is not a micro
2250
  * optimisation: `SheetPage.tsx::commitSheets` refuses an array it already holds, so a click on
 
2261
  if (!target) return book.sheets;
2262
  const letters = indexToCol(colIndex + 1);
2263
  const next = Math.max(MIN_COL_WIDTH, Math.min(MAX_COL_WIDTH, Math.round(width)));
2264
+ if (next === 0) {
2265
+ const hidden = hideColumnByWidth(target, colIndex);
2266
+ return hidden === target ? book.sheets : book.sheets.map(tab => tab === target ? hidden : tab);
2267
+ }
2268
  const current = (target.colWidths ?? {})[letters] ?? DEFAULT_COL_WIDTH;
2269
  if (current === next) return book.sheets;
2270
  return book.sheets.map((tab) => {
web/src/sheet/types.ts CHANGED
@@ -74,6 +74,59 @@ export interface CellSource {
74
  */
75
  export type CellBinding = Record<string, unknown>;
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  /** C9: the persisted discriminator owns exactly one source path. */
78
  export type BindingAggregate =
79
  | { kind: "number"; metric_key: string; fn?: never; field?: never }
@@ -830,6 +883,9 @@ export interface Cell {
830
  value?: unknown;
831
  display?: string;
832
  binding?: CellBinding;
 
 
 
833
  source?: CellSource;
834
  refusal?: CellRefusal;
835
  refreshed_at?: string;
@@ -1150,8 +1206,9 @@ export const DEFAULT_COL_WIDTH = 120;
1150
  export const MAX_SHEET_COLS = 702;
1151
  /** ⛔ Mirrored in `platform/core/sheets.py::MAX_SHEET_ROWS`. */
1152
  export const MAX_SHEET_ROWS = 100000;
1153
- /** ⛔ Mirrored in `platform/core/sheets.py::MIN_COL_WIDTH` / `MAX_COL_WIDTH`. */
1154
- export const MIN_COL_WIDTH = 40;
 
1155
  export const MAX_COL_WIDTH = 1000;
1156
 
1157
  /**
 
74
  */
75
  export type CellBinding = Record<string, unknown>;
76
 
77
+ // W62 C2: platform/core/sheets.py carries the same three constants; a gate checks the pair.
78
+ export const VIEW_BINDING_TYPES = [
79
+ "grid", "kanban", "map", "gallery", "timeline", "list", "calendar", "catalog", "swipe",
80
+ ] as const;
81
+ export const VIEW_BINDING_LIMIT_DEFAULT = 100;
82
+ export const VIEW_BINDING_LIMIT_MAX = 10000;
83
+
84
+ /** Inclusive, zero-based document cells; pixels are derived only at the rendering boundary. */
85
+ export interface SheetViewGeometry { col0: number; row0: number; col1: number; row1: number }
86
+
87
+ /** C2 block dimensions are cell counts, including when an older binding omitted its size. */
88
+ export const viewBlockSize = (binding?: CellBinding): { cols: number; rows: number } => {
89
+ const block = binding?.block as { cols?: unknown; rows?: unknown } | undefined;
90
+ const dimension = (value: unknown, fallback: number) =>
91
+ typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : fallback;
92
+ return { cols: dimension(block?.cols, 8), rows: dimension(block?.rows, 20) };
93
+ };
94
+
95
+ /** A view projects ordered fields and rows, with no aggregate or saved-cell dependency. */
96
+ export interface ViewBinding extends CellBinding {
97
+ database: string;
98
+ mode: "view";
99
+ viewType: (typeof VIEW_BINDING_TYPES)[number];
100
+ fields: string[];
101
+ filter?: unknown;
102
+ sort: { field: string; dir: "asc" | "desc" }[];
103
+ /** Uses the existing calendar or lookback period dialect. */
104
+ period?: Record<string, unknown>;
105
+ limit: number;
106
+ onDrag?: BindingOnDrag;
107
+ block?: { cols: number; rows: number };
108
+ }
109
+
110
+ export interface ViewRowsAnswer {
111
+ fields: { key: string; label: string; kind: string }[];
112
+ rows: Record<string, unknown>[];
113
+ total: number;
114
+ limit: number;
115
+ viewType: ViewBinding["viewType"];
116
+ editable: boolean;
117
+ }
118
+
119
+ /** One atomic structural edit; coordinates and cell addresses are 1 based. */
120
+ export interface StructureOp {
121
+ axis: "row" | "col";
122
+ at: number;
123
+ delta: number;
124
+ place?: {
125
+ also?: { axis: "row" | "col"; at: number; delta: number };
126
+ cells: Record<string, Cell | null>;
127
+ };
128
+ }
129
+
130
  /** C9: the persisted discriminator owns exactly one source path. */
131
  export type BindingAggregate =
132
  | { kind: "number"; metric_key: string; fn?: never; field?: never }
 
883
  value?: unknown;
884
  display?: string;
885
  binding?: CellBinding;
886
+ // clean_cell in platform/core/sheets.py preserves unknown keys through _json_safe,
887
+ // so viewChild survives persistence without adding a server cell kind or cleaner branch.
888
+ viewChild?: { origin: string; field: string; line: number };
889
  source?: CellSource;
890
  refusal?: CellRefusal;
891
  refreshed_at?: string;
 
1206
  export const MAX_SHEET_COLS = 702;
1207
  /** ⛔ Mirrored in `platform/core/sheets.py::MAX_SHEET_ROWS`. */
1208
  export const MAX_SHEET_ROWS = 100000;
1209
+ /** Mirrored in `platform/core/sheets.py::MIN_COL_WIDTH` / `MAX_COL_WIDTH`: floor 0 (R14).
1210
+ * C1: 0 means hiddenCols membership; colWidths retains the last visible width for Unhide. */
1211
+ export const MIN_COL_WIDTH = 0;
1212
  export const MAX_COL_WIDTH = 1000;
1213
 
1214
  /**
web/src/sheet/viewPlacement.ts ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This reader does not live in sheetApi.ts because that file is outside this lane's fence:
2
+ // a second reader is better than an out-of-fence edit. Keep this module side-effect free so
3
+ // W62-T12 can add its placement arithmetic here.
4
+ import { API_V1, CREDENTIALS, checkTenant } from "../apiContract";
5
+ import { sheetExtent, viewBlockSize, VIEW_BINDING_LIMIT_DEFAULT } from "./types";
6
+ import type { Cell, CellBinding, SheetTab, SheetViewGeometry, StructureOp, ViewBinding, ViewRowsAnswer } from "./types";
7
+ import { colToIndex, indexToCol, shiftForStructure } from "./a1";
8
+ import { structureBindingRefs } from "./bindingRefs";
9
+ import { patchTopicRow } from "../customer-grid/apiBridge";
10
+ import { utTopic } from "../customer-grid/types";
11
+ import { fetchNav } from "../shell/nav";
12
+
13
+ /** Record identity travels with the displayed row, never inferred from its sheet position. */
14
+ type ViewRecordChild = NonNullable<Cell["viewChild"]> & { pid?: number };
15
+
16
+ export const viewChromeRefusal = (cell: Cell | null | undefined): string | null => {
17
+ if (cell?.viewChild?.line === -2) return "The Grid count row cannot be edited.";
18
+ if (cell?.viewChild?.line === -1 || (cell?.kind === "bound"
19
+ && cell.binding?.mode === "view" && cell.binding.viewType === "grid")) {
20
+ return "Grid headers cannot be edited; use the header arrow to sort or filter.";
21
+ }
22
+ return null;
23
+ };
24
+
25
+ /** Metadata explains a refusal only; the resolver's editable flag is the sole edit verdict. */
26
+ const recordEditRefusal = async (database: string): Promise<string> => {
27
+ const nav = await fetchNav();
28
+ const page = nav.ok ? nav.pages.find(item => item.key === database) : undefined;
29
+ const source = page?.source?.toLowerCase();
30
+ if (source && !["blank", "custom", "automation"].includes(source)) {
31
+ return "This connector database is read only, so its records cannot be edited.";
32
+ }
33
+ if (page?.locked) return "This database is locked, so its records cannot be edited.";
34
+ return "This database does not allow record edits for your account.";
35
+ };
36
+
37
+ export type ViewCellWrite =
38
+ | { ok: true; origin: string; answer: ViewRowsAnswer }
39
+ | { ok: false; message: string; saved?: boolean };
40
+
41
+ /** Data's writer owns validation, persistence and cache invalidation; Sheet only re-resolves. */
42
+ export async function writeViewCell(
43
+ workbookId: string, tab: SheetTab, addr: string, text: string,
44
+ isCurrent: () => boolean = () => true,
45
+ ): Promise<ViewCellWrite> {
46
+ const sheetCells = tab.cells ?? {};
47
+ const cell = sheetCells[addr];
48
+ const chrome = viewChromeRefusal(cell);
49
+ if (chrome) return { ok: false, message: chrome };
50
+ const child = cell?.viewChild as ViewRecordChild | undefined;
51
+ const anchorCell = child && sheetCells[child.origin];
52
+ if (!child || child.line < 0 || anchorCell?.binding?.mode !== "view"
53
+ || anchorCell.binding.viewType !== "grid") {
54
+ return { ok: false, message: "This Grid has changed; refresh it before editing." };
55
+ }
56
+ const binding = anchorCell.binding as ViewBinding;
57
+ const resolved = await fetchViewRows(workbookId, binding);
58
+ if (!resolved.ok) return resolved;
59
+ if (resolved.answer.editable !== true) {
60
+ return { ok: false, message: await recordEditRefusal(binding.database) };
61
+ }
62
+ // The resolver must supply each row's Data pid even when it is not a selected field.
63
+ // A response/footprint without that identity refuses rather than guessing at duplicate values.
64
+ const pid = child.pid;
65
+ const row = resolved.answer.rows.find(item => item.pid === pid);
66
+ if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0 || !row
67
+ || !resolved.answer.fields.some(field => field.key === child.field)) {
68
+ return { ok: false, message: "Refresh this Grid before editing its records." };
69
+ }
70
+ if (JSON.stringify(row[child.field] ?? null) !== JSON.stringify(cell.value ?? null)
71
+ || !isCurrent()) {
72
+ return { ok: false, message: "This Grid has changed; refresh it before editing." };
73
+ }
74
+ const accepted = await patchTopicRow(utTopic(binding.database), pid, { [child.field]: text });
75
+ if (!accepted) {
76
+ const latest = await fetchViewRows(workbookId, binding);
77
+ return { ok: false, message: latest.ok && latest.answer.editable !== true
78
+ ? await recordEditRefusal(binding.database)
79
+ : "The record change could not be saved; the cell has kept its value." };
80
+ }
81
+ const refreshed = await fetchViewRows(workbookId, binding);
82
+ if (!refreshed.ok) return { ok: false, saved: true,
83
+ message: "The record was saved, but the Grid could not refresh; refresh it to see the saved value." };
84
+ return { ok: true, origin: child.origin, answer: refreshed.answer };
85
+ }
86
+
87
+ /** Sheet coordinates, like StructureOp.at, are 1 based. */
88
+ export interface ViewAnchor { col: number; row: number }
89
+ export interface ViewFootprint { rows: number; cols: number }
90
+ /** Supply cells to check occupied edges as well as the footprint's own bounds. */
91
+ export interface ViewExtent extends ViewFootprint { cells?: Readonly<Record<string, Cell>> }
92
+ export type ViewPushRefusal = "view_push_past_last_row" | "view_push_past_last_col";
93
+
94
+ const address = ({ col, row }: ViewAnchor): string => `${indexToCol(col)}${row}`;
95
+ const position = (addr: string): ViewAnchor | null => {
96
+ const match = /^([A-Z]+)([1-9][0-9]*)$/i.exec(addr);
97
+ return match ? { col: colToIndex(match[1].toUpperCase()), row: Number(match[2]) } : null;
98
+ };
99
+
100
+ /**
101
+ * ⭐ R30's COUNT LINE, WITH ITS THOUSANDS GROUPED, and it is exported because TWO surfaces say it:
102
+ * the placed view's own last row and the Place step's preview. Said twice it drifts; the done-when
103
+ * spells "Showing 20 of 137,046" with the comma, and a bare `String(total)` loses it.
104
+ * ⚠ Grouped by hand rather than through `toLocaleString`, whose separator follows the BROWSER's
105
+ * locale: the same sheet would then read differently for two readers of one document.
106
+ */
107
+ export const showingLine = (shown: number, total: number): string =>
108
+ `Showing ${String(Math.max(0, Math.trunc(shown)))} of `
109
+ + String(Math.max(0, Math.trunc(total))).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
110
+
111
+ /** C3 Grid rows occupy cells; other renderers reserve a fixed, document-owned cell block. */
112
+ export const viewFootprint = (answer: ViewRowsAnswer, binding?: CellBinding): ViewFootprint =>
113
+ answer.viewType !== "grid" ? viewBlockSize(binding) : ({
114
+ rows: 2 + Math.min(answer.limit ?? VIEW_BINDING_LIMIT_DEFAULT, answer.total),
115
+ cols: answer.fields.length,
116
+ });
117
+
118
+ export const viewBlockGeometry = (anchor: ViewAnchor, binding?: CellBinding): SheetViewGeometry => {
119
+ const size = viewBlockSize(binding);
120
+ return { col0: anchor.col - 1, row0: anchor.row - 1,
121
+ col1: anchor.col + size.cols - 2, row1: anchor.row + size.rows - 2 };
122
+ };
123
+
124
+ const pushRefusal = (op: StructureOp, extent: ViewExtent): ViewPushRefusal | null => {
125
+ let occupied = Object.entries(extent.cells ?? {}).flatMap(([addr, cell]) => {
126
+ const at = position(addr);
127
+ if (!at) return [];
128
+ if (cell?.kind === "bound" && cell.binding?.mode === "view"
129
+ && cell.binding.viewType !== "grid" && cell.binding.block) {
130
+ const size = viewBlockSize(cell.binding);
131
+ return [at, { col: at.col + size.cols - 1, row: at.row + size.rows - 1 }];
132
+ }
133
+ return [at];
134
+ });
135
+ for (const step of [op, ...(op.place?.also ? [op.place.also] : [])]) {
136
+ if (!step.delta) continue;
137
+ const last = step.axis === "row" ? extent.rows : extent.cols;
138
+ const code = step.axis === "row" ? "view_push_past_last_row" : "view_push_past_last_col";
139
+ if (step.delta > 0) {
140
+ if (step.at < 1 || step.at + step.delta - 1 > last) return code;
141
+ if (occupied.some(at => at[step.axis] >= step.at && at[step.axis] + step.delta > last)) return code;
142
+ }
143
+ occupied = occupied.flatMap(at => {
144
+ const value = at[step.axis];
145
+ if (value < step.at) return [at];
146
+ if (step.delta < 0 && value < step.at - step.delta) return [];
147
+ return [{ ...at, [step.axis]: value + step.delta }];
148
+ });
149
+ }
150
+ return null;
151
+ };
152
+
153
+ /** One operation reserves BOTH whole bands; the caller fills place.cells before committing. */
154
+ export const viewPlacementOps = (
155
+ anchor: ViewAnchor, footprint: ViewFootprint, extent: ViewExtent,
156
+ ): StructureOp | ViewPushRefusal => {
157
+ const op: StructureOp = { axis: "row", at: anchor.row, delta: footprint.rows,
158
+ place: { also: { axis: "col", at: anchor.col, delta: footprint.cols }, cells: {} } };
159
+ return pushRefusal(op, extent) ?? op;
160
+ };
161
+
162
+ /** Growth starts after the OLD edge; contraction removes the tail after the NEW edge. */
163
+ export const viewResizeOps = (
164
+ anchor: ViewAnchor, previous: ViewFootprint, next: ViewFootprint, extent: ViewExtent,
165
+ ): StructureOp | ViewPushRefusal => {
166
+ const op: StructureOp = {
167
+ axis: "row", at: anchor.row + Math.min(previous.rows, next.rows),
168
+ delta: next.rows - previous.rows,
169
+ place: { also: { axis: "col", at: anchor.col + Math.min(previous.cols, next.cols),
170
+ delta: next.cols - previous.cols }, cells: {} },
171
+ };
172
+ if (anchor.row + next.rows - 1 > extent.rows) return "view_push_past_last_row";
173
+ if (anchor.col + next.cols - 1 > extent.cols) return "view_push_past_last_col";
174
+ return pushRefusal(op, extent) ?? op;
175
+ };
176
+
177
+ /** Only Grid materializes rows. Other views leave every reserved cell except the anchor empty. */
178
+ export const viewCells = (
179
+ anchor: ViewAnchor & { cell: Cell }, answer: ViewRowsAnswer,
180
+ ): Record<string, Cell> => {
181
+ const footprint = viewFootprint(answer, anchor.cell.binding);
182
+ const origin = address(anchor);
183
+ if (answer.viewType !== "grid") {
184
+ const cell: Cell = { ...anchor.cell, kind: "bound", state: "fresh", value: null, display: "",
185
+ binding: { ...anchor.cell.binding, block: footprint } };
186
+ delete cell.viewChild;
187
+ delete cell.refusal;
188
+ delete cell.error;
189
+ return { [origin]: cell };
190
+ }
191
+ const cells: Record<string, Cell> = {};
192
+ for (let row = 0; row < footprint.rows; row++) {
193
+ const line = row === 0 ? -1 : row === footprint.rows - 1 ? -2 : row - 1;
194
+ answer.fields.forEach((field, col) => {
195
+ const value = line === -1 ? field.label : line === -2
196
+ ? col === 0 ? showingLine(answer.rows.length, answer.total) : ""
197
+ : answer.rows[line]?.[field.key] ?? null;
198
+ const display = value == null ? "" : typeof value === "object"
199
+ ? JSON.stringify(value) : String(value);
200
+ const addr = address({ col: anchor.col + col, row: anchor.row + row });
201
+ if (addr === origin) {
202
+ const cell: Cell = { ...anchor.cell, kind: "bound", state: "fresh", value, display,
203
+ binding: { ...anchor.cell.binding, block: footprint } };
204
+ delete cell.viewChild;
205
+ delete cell.refusal;
206
+ delete cell.error;
207
+ cells[addr] = cell;
208
+ } else {
209
+ const pid = line >= 0 ? answer.rows[line]?.pid : undefined;
210
+ const child: ViewRecordChild = { origin, field: field.key, line,
211
+ ...(typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0 ? { pid } : {}) };
212
+ cells[addr] = { kind: "literal", state: "typed", value, display, viewChild: child };
213
+ }
214
+ });
215
+ }
216
+ return cells;
217
+ };
218
+
219
+ /** Includes blank footer/header cells: ownership, not truthiness of a value, decides. */
220
+ // ⛔ A TAB'S `cells` IS LEGITIMATELY UNDEFINED. `GET /sheets/{id}?tabs=meta` answers tabs with NO
221
+ // cells, so every reader here must tolerate one. Reading it unguarded threw inside a render and
222
+ // dropped the whole sheet to its error boundary: "Cannot convert undefined or null to object".
223
+ export const viewChildrenOf = (tab: SheetTab, anchor: ViewAnchor | string): string[] => {
224
+ const origin = typeof anchor === "string" ? anchor.toUpperCase() : address(anchor);
225
+ const cells = tab.cells ?? {};
226
+ return Object.keys(cells).filter(addr => cells[addr]?.viewChild?.origin === origin);
227
+ };
228
+
229
+ /** The bound anchor is also a header; only the other headers have child markers. */
230
+ export const viewHeaderAt = (
231
+ cells: Readonly<Record<string, Cell>>, addr: string,
232
+ ): { origin: string; field: string } | null => {
233
+ const cell = cells[addr];
234
+ const child = cell?.viewChild;
235
+ if (child && child.line !== -1) return null;
236
+ const origin = child?.origin ?? addr;
237
+ const owner = cells[origin];
238
+ if (owner?.kind !== "bound" || owner.binding?.mode !== "view"
239
+ || owner.binding.viewType !== "grid" || !owner.binding.block) return null;
240
+ const field = child?.field ?? (owner.binding.fields as string[] | undefined)?.[0];
241
+ return typeof field === "string" ? { origin, field } : null;
242
+ };
243
+
244
+ /** Shared refresh/re-resolve path: move the bands and replace their cells in one history step. */
245
+ export const viewRefreshOp = (
246
+ tab: SheetTab, origin: string, answer: ViewRowsAnswer,
247
+ binding = (tab.cells ?? {})[origin]?.binding,
248
+ ): StructureOp | ViewPushRefusal | "view_missing" => {
249
+ const at = position(origin);
250
+ const stored = tab.cells ?? {};
251
+ const cell = stored[origin];
252
+ if (!at || cell?.kind !== "bound" || binding?.mode !== "view") return "view_missing";
253
+ const children = viewChildrenOf(tab, origin);
254
+ const blockPlaced = cell.binding?.viewType !== "grid" && !!cell.binding?.block;
255
+ const previous = blockPlaced ? viewBlockSize(cell.binding) : children.reduce((size, addr) => {
256
+ const child = position(addr)!;
257
+ return { rows: Math.max(size.rows, child.row - at.row + 1),
258
+ cols: Math.max(size.cols, child.col - at.col + 1) };
259
+ }, { rows: 1, cols: 1 });
260
+ const next = viewFootprint(answer, binding);
261
+ const extent = { ...sheetExtent(tab), cells: stored };
262
+ const op = children.length || blockPlaced
263
+ ? viewResizeOps(at, previous, next, extent) : viewPlacementOps(at, next, extent);
264
+ if (typeof op === "string") return op;
265
+ const steps = [op, ...(op.place?.also ? [op.place.also] : [])];
266
+ const cells: Record<string, Cell | null> = {};
267
+ // Clear surviving old children at their moved addresses, never the neighbours pulled in.
268
+ for (let addr of children.length || blockPlaced ? children : [origin]) {
269
+ for (const step of steps) {
270
+ if (step.delta) addr = shiftForStructure(addr,
271
+ { sheet: tab.name, axis: step.axis, at: step.at, delta: step.delta }, tab.name);
272
+ }
273
+ if (position(addr)) cells[addr] = null;
274
+ }
275
+ let placedCell = { ...cell, binding };
276
+ for (const step of steps) {
277
+ if (!step.delta) continue;
278
+ const shifted = structureBindingRefs(placedCell.binding!,
279
+ { sheet: tab.name, axis: step.axis, at: step.at, delta: step.delta }, tab.name);
280
+ if (shifted.changed) placedCell = { ...placedCell, binding: shifted.binding };
281
+ }
282
+ Object.assign(cells, viewCells({ ...at, cell: placedCell }, answer));
283
+ op.place!.cells = cells;
284
+ return op;
285
+ };
286
+
287
+ export async function fetchViewRows(
288
+ workbookId: string,
289
+ binding: ViewBinding,
290
+ ): Promise<{ ok: true; answer: ViewRowsAnswer } | { ok: false; code: string; message: string }> {
291
+ let res: Response;
292
+ try {
293
+ res = await fetch(`${API_V1}/sheets/${encodeURIComponent(workbookId)}/view-rows`, {
294
+ method: "POST",
295
+ credentials: CREDENTIALS,
296
+ headers: { "Content-Type": "application/json" },
297
+ body: JSON.stringify({ binding }),
298
+ });
299
+ } catch {
300
+ return { ok: false, code: "unreachable", message: "Cannot reach the server." };
301
+ }
302
+ if (checkTenant(res)) return { ok: false, code: "tenant_changed",
303
+ message: "The workspace changed; reload before editing." };
304
+ const body = await res.json().catch(() => null);
305
+ if (!res.ok) {
306
+ // The view resolver names refusals directly; shared API failures may use the error bag.
307
+ const error = body?.error;
308
+ return {
309
+ ok: false,
310
+ code: typeof error === "string" ? error : error?.code ?? "unknown",
311
+ message: body?.message || error?.message || "Something went wrong.",
312
+ };
313
+ }
314
+ if (!body || !Array.isArray(body.fields) || !Array.isArray(body.rows)
315
+ || typeof body.total !== "number") {
316
+ return { ok: false, code: "invalid_answer", message: "The view rows could not be read." };
317
+ }
318
+ return { ok: true, answer: body as ViewRowsAnswer };
319
+ }
web/src/shell/Shell.tsx CHANGED
@@ -34,6 +34,7 @@ import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } fro
34
  /* ⭐ W53-T34 / contract C4 — the shell's glyphs live in ONE file now. See the tombstone where
35
  `FlowIcon` used to be drawn, further down. */
36
  import { AgentIcon, DatabaseIcon } from "./icons";
 
37
  // ⭐ W53-T35 / C4 — the shell's own sheet, imported here the way `NavExtras.tsx` imports
38
  // `navExtras.css`. It carries the one rule that keeps the DATABASE mark out of the folder
39
  // fill (`styles/wave45/data-applications.css` paints every `.cg-folder-mark path` brand
@@ -89,7 +90,7 @@ import type { SettingsSection } from "../settings/SettingsModal";
89
  import { Brand } from "./Brand";
90
  import { ErrorBoundary } from "./ErrorBoundary";
91
  import LoginPage from "./LoginPage";
92
- import { APP_ROUTE, ASSISTANT_ROUTE, CONNECTORS_ROUTE, DATA_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, agentAddressHash, appLink, canonicalRoute, databaseEntries, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchSchema, fetchTableFootprint, postOpened, QUERY_ROUTE, readAgentAddress, 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`
@@ -1690,6 +1691,10 @@ function ShellFrame() {
1690
  // invented a second vocabulary for the same thing. [[one-question-two-normalizers]]
1691
  // ⚠ The failure is silent by construction, which is why no gate saw it: a route that does not
1692
  // resolve is the SAME code path as "no route yet", and that path renders Home on purpose.
 
 
 
 
1693
  window.location.hash = dataPathHash({ database, view: viewId });
1694
  viewEmitCancel.current?.();
1695
  viewEmitCancel.current = retryEmit(
@@ -1840,11 +1845,9 @@ function ShellFrame() {
1840
  // control that strands you: the level replaces the rail's chrome rows, so with no way back to
1841
  // index 0 there would be no Home, no Inbox and no Connectors on screen at all.
1842
  //
1843
- // ⚠ NOT A ROUTE, deliberately. There is no `#/data` surface and inventing one would be the
1844
- // hard-coded page this frame refuses to have — `nav.ts::CHROME_ROUTES` is the law a new surface
1845
- // route has to join, and a route that joins it must also RENDER something. A drill is a rail
1846
- // STATE: the content pane keeps showing whatever it was showing, which is also the honest
1847
- // answer to "I opened the navigation, I did not leave the page".
1848
  // Data is one global destination. Its database hierarchy is owned by ViewSidebar, where it can
1849
  // share the same disclosure, keyboard and folder vocabulary as the views it contains.
1850
  /**
@@ -2663,6 +2666,7 @@ function ShellFrame() {
2663
  // switch to any other database honestly leaves it.
2664
  const current = readDataPath();
2665
  const stays = preserveRoute && !!current?.application && current.database === key;
 
2666
  window.location.hash = stays
2667
  ? appPathHash({ database: key, application: current.application })
2668
  : dataPathHash({ database: key });
@@ -2808,6 +2812,7 @@ function ShellFrame() {
2808
  }
2809
  setNewDb(null);
2810
  setNavEpoch((e) => e + 1);
 
2811
  window.location.hash = dataPathHash({ database: body.key });
2812
  } catch {
2813
  setNewDb({ mode: "blank", name, busy: false, err: "Cannot reach the server." });
@@ -3081,7 +3086,7 @@ function ShellFrame() {
3081
  </div>
3082
  </header>
3083
  <div className="shell-frame">
3084
- <aside
3085
  className={"shell-side" + (navCollapsed ? " is-collapsed" : "")}
3086
  style={{ position: "relative" }}
3087
  // Item 7 (R9) — background click expands. Bound only while collapsed, so the
@@ -3360,7 +3365,7 @@ function ShellFrame() {
3360
  // every addressed database share the Data route key. On that route, only having
3361
  // no database addressed honestly means "already at Data's top level".
3362
  if (route === DATA_ROUTE && !dataPath?.database) return;
3363
- window.location.hash = `#/${DATA_ROUTE}`;
3364
  }}
3365
  >
3366
  <DatabaseIcon />
@@ -3543,7 +3548,7 @@ function ShellFrame() {
3543
  onSettings={setSettings}
3544
  />
3545
  </div>
3546
- </aside>
3547
 
3548
  {/* Item 3 — the collapsed rail's hover tip: fixed beside the strip, outside the
3549
  scrolling rail that would clip it, and pointer-transparent by standing rule. */}
 
34
  /* ⭐ W53-T34 / contract C4 — the shell's glyphs live in ONE file now. See the tombstone where
35
  `FlowIcon` used to be drawn, further down. */
36
  import { AgentIcon, DatabaseIcon } from "./icons";
37
+ import { OverlayScroll } from "../ui/OverlayScroll";
38
  // ⭐ W53-T35 / C4 — the shell's own sheet, imported here the way `NavExtras.tsx` imports
39
  // `navExtras.css`. It carries the one rule that keeps the DATABASE mark out of the folder
40
  // fill (`styles/wave45/data-applications.css` paints every `.cg-folder-mark path` brand
 
90
  import { Brand } from "./Brand";
91
  import { ErrorBoundary } from "./ErrorBoundary";
92
  import LoginPage from "./LoginPage";
93
+ import { APP_ROUTE, ASSISTANT_ROUTE, CONNECTORS_ROUTE, DATA_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, agentAddressHash, appLink, canonicalRoute, databaseEntries, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchSchema, fetchTableFootprint, postOpened, QUERY_ROUTE, dataAddressHash, readAgentAddress, resolveRoute, rewrittenHash, routeKeyOf, saveNavMeta, saveNavPrefs, shapeNav, splitChrome } from "./nav";
94
  import type { NavEntry, NavMetaPatch, NavPage, NavPrefs, RailSlot, Recent, SchemaField, SchemaPayload } from "./nav";
95
  // ⭐ 2026-08-14 — the database frame, extracted so the Query module can wear the SAME one.
96
  // ⛔ W53-T35 — `DbIcon` IS NO LONGER IMPORTED HERE. The Data row wears `icons.tsx::DatabaseIcon`
 
1691
  // invented a second vocabulary for the same thing. [[one-question-two-normalizers]]
1692
  // ⚠ The failure is silent by construction, which is why no gate saw it: a route that does not
1693
  // resolve is the SAME code path as "no route yet", and that path renders Home on purpose.
1694
+ // W62-T19 (C6): NO folder is carried here on purpose. C6's own fallback is "the address
1695
+ // first, then the opened item's placement", and a view opened in another database belongs to
1696
+ // THAT database's placement - carrying the folder the reader happened to be standing in would
1697
+ // address a folder this database is not filed in. `verify_grid_ux.py` also pins this line.
1698
  window.location.hash = dataPathHash({ database, view: viewId });
1699
  viewEmitCancel.current?.();
1700
  viewEmitCancel.current = retryEmit(
 
1845
  // control that strands you: the level replaces the rail's chrome rows, so with no way back to
1846
  // index 0 there would be no Home, no Inbox and no Connectors on screen at all.
1847
  //
1848
+ // W62-T19 / R52 overturns the earlier refusal of a #/data route: Data joins nav.ts::CHROME_ROUTES.
1849
+ // A route that joins CHROME_ROUTES must also render. The existing Home/App/Data fallback branch
1850
+ // below meets that condition with <HomePage mode="data">; C6's address also carries its folder.
 
 
1851
  // Data is one global destination. Its database hierarchy is owned by ViewSidebar, where it can
1852
  // share the same disclosure, keyboard and folder vocabulary as the views it contains.
1853
  /**
 
2666
  // switch to any other database honestly leaves it.
2667
  const current = readDataPath();
2668
  const stays = preserveRoute && !!current?.application && current.database === key;
2669
+ // W62-T19 (C6): the switched-to database brings its OWN placement, so no folder rides along.
2670
  window.location.hash = stays
2671
  ? appPathHash({ database: key, application: current.application })
2672
  : dataPathHash({ database: key });
 
2812
  }
2813
  setNewDb(null);
2814
  setNavEpoch((e) => e + 1);
2815
+ // W62-T19 (C6): a database created just now is filed nowhere, so it addresses no folder.
2816
  window.location.hash = dataPathHash({ database: body.key });
2817
  } catch {
2818
  setNewDb({ mode: "blank", name, busy: false, err: "Cannot reach the server." });
 
3086
  </div>
3087
  </header>
3088
  <div className="shell-frame">
3089
+ <OverlayScroll element="aside"
3090
  className={"shell-side" + (navCollapsed ? " is-collapsed" : "")}
3091
  style={{ position: "relative" }}
3092
  // Item 7 (R9) — background click expands. Bound only while collapsed, so the
 
3365
  // every addressed database share the Data route key. On that route, only having
3366
  // no database addressed honestly means "already at Data's top level".
3367
  if (route === DATA_ROUTE && !dataPath?.database) return;
3368
+ window.location.hash = dataAddressHash({});
3369
  }}
3370
  >
3371
  <DatabaseIcon />
 
3548
  onSettings={setSettings}
3549
  />
3550
  </div>
3551
+ </OverlayScroll>
3552
 
3553
  {/* Item 3 — the collapsed rail's hover tip: fixed beside the strip, outside the
3554
  scrolling rail that would clip it, and pointer-transparent by standing rule. */}
web/src/shell/nav.ts CHANGED
@@ -1248,9 +1248,39 @@ export const CONNECTORS_ROUTE = "connectors";
1248
  * the route in chrome prevents a tenant's restricted module list from hiding its own Apps.
1249
  */
1250
  export const APP_ROUTE = "app";
1251
- /** W57-T27 (R9) names the Data key already in the address vocabulary. Like Sheet, it stays out
1252
- * of CHROME_ROUTES because that set's only consumer answers the landing preference. */
1253
  export const DATA_ROUTE = "data";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1254
  /**
1255
  * ⭐⭐ WAVE 32 (ruling R7, contract C3) — INBOX IS THE THIRD CHROME ROUTE, AND IT PASSES THE LAW
1256
  * ABOVE RATHER THAN BEING EXCEPTED FROM IT.
@@ -1352,6 +1382,7 @@ export const CHROME_ROUTES: ReadonlySet<string> = new Set([
1352
  HOME_ROUTE,
1353
  APP_ROUTE,
1354
  CONNECTORS_ROUTE,
 
1355
  INBOX_ROUTE,
1356
  QUERY_ROUTE,
1357
  ASSISTANT_ROUTE,
 
1248
  * the route in chrome prevents a tenant's restricted module list from hiding its own Apps.
1249
  */
1250
  export const APP_ROUTE = "app";
1251
+ /** W62-T19 / R52: Data is a real chrome route, rendered by Shell.tsx's Home/App/Data fallback
1252
+ * branch. Joining CHROME_ROUTES is inert for firstDestination: LANDING_PREFERENCE is [HOME_ROUTE]. */
1253
  export const DATA_ROUTE = "data";
1254
+
1255
+ /** C6's Data address, including the folder stratum above the grid's database/view path. */
1256
+ export interface DataAddress { database?: string; view?: string; folder?: string }
1257
+
1258
+ /** Build C6 addresses for shell/rail navigation. These helpers own the folder stratum;
1259
+ * dataPath.ts remains the grid's database/view reader and its path semantics are unchanged. */
1260
+ export function dataAddressHash(address: DataAddress): string {
1261
+ const params = new URLSearchParams();
1262
+ for (const key of ["database", "view", "folder"] as const) {
1263
+ if (address[key]) params.set(key, address[key]);
1264
+ }
1265
+ const query = params.toString();
1266
+ return `#/${DATA_ROUTE}${query ? `?${query}` : ""}`;
1267
+ }
1268
+
1269
+ /** Read the folder stratum and address keys for shell/rail navigation, not grid path semantics.
1270
+ * dataPath.ts remains the grid reader. An explicit hash also works when evaluated under Node. */
1271
+ export function readDataAddress(
1272
+ hash = typeof window === "undefined" ? "" : window.location.hash
1273
+ ): DataAddress {
1274
+ const [route, query = ""] = hash.split("?", 2);
1275
+ if (route !== `#/${DATA_ROUTE}`) return {};
1276
+ const params = new URLSearchParams(query);
1277
+ const address: DataAddress = {};
1278
+ for (const key of ["database", "view", "folder"] as const) {
1279
+ const value = params.get(key);
1280
+ if (value !== null) address[key] = value;
1281
+ }
1282
+ return address;
1283
+ }
1284
  /**
1285
  * ⭐⭐ WAVE 32 (ruling R7, contract C3) — INBOX IS THE THIRD CHROME ROUTE, AND IT PASSES THE LAW
1286
  * ABOVE RATHER THAN BEING EXCEPTED FROM IT.
 
1382
  HOME_ROUTE,
1383
  APP_ROUTE,
1384
  CONNECTORS_ROUTE,
1385
+ DATA_ROUTE,
1386
  INBOX_ROUTE,
1387
  QUERY_ROUTE,
1388
  ASSISTANT_ROUTE,
web/src/shell/navExtras.css CHANGED
@@ -239,7 +239,7 @@
239
  background: transparent;
240
  padding: 6px 8px;
241
  margin-top: 2px;
242
- border-radius: 7px;
243
  font: inherit;
244
  font-size: var(--lp-fs-2xs);
245
  color: var(--lp-muted);
 
239
  background: transparent;
240
  padding: 6px 8px;
241
  margin-top: 2px;
242
+ border-radius: var(--lp-r-md);
243
  font: inherit;
244
  font-size: var(--lp-fs-2xs);
245
  color: var(--lp-muted);
web/src/styles/wave55/sheet.css CHANGED
@@ -100,11 +100,6 @@
100
  white-space: nowrap;
101
  }
102
 
103
- /* Formula bar visibility is a view preference, so it changes layout without changing the sheet. */
104
- .sheet-grid-wrap.is-formula-bar-hidden > .sheet-fx {
105
- display: none;
106
- }
107
-
108
  /* W55-T07: Cell View keeps the Link-field drawer and adds one compact control row inside its
109
  existing header. No second card or floating toolbar competes with the drawer's containment. */
110
  .cg-link-grid-head > div:first-child {
 
100
  white-space: nowrap;
101
  }
102
 
 
 
 
 
 
103
  /* W55-T07: Cell View keeps the Link-field drawer and adds one compact control row inside its
104
  existing header. No second card or floating toolbar competes with the drawer's containment. */
105
  .cg-link-grid-head > div:first-child {