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

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
This view is limited to 50 files because it contains too many changes. Β  See raw diff
Files changed (50) hide show
  1. RELEASES.json +1 -1
  2. VERSION +1 -1
  3. api/application_registry.py +6 -0
  4. api/automation_engine.py +1 -1
  5. api/connectors_meta.py +1 -1
  6. api/connectors_tt.py +1 -1
  7. api/main.py +2 -0
  8. api/odoo_relational.py +252 -0
  9. api/routes_connectors.py +369 -21
  10. api/routes_external.py +399 -0
  11. api/routes_oauth.py +1 -1
  12. api/routes_slack.py +2 -2
  13. platform/core/connector_directory.py +3 -3
  14. platform/core/connector_sync.py +169 -0
  15. platform/core/external_access.py +328 -0
  16. platform/core/monid.py +1 -1
  17. platform/core/sheets.py +6 -0
  18. platform/core/user_tables.py +14 -2
  19. platform/harness/amazon_client.py +1 -1
  20. platform/harness/datastore.py +2 -2
  21. platform/harness/semantic.py +1 -1
  22. platform/harness/transforms.py +1 -1
  23. platform/model/skills/analytics.skill.yml +1 -1
  24. platform/model/topics/sales_lines.yml +1 -1
  25. platform/modules/map.py +3 -0
  26. platform/modules/reprice.py +1 -1
  27. web/src/connectors/ConnectorModal.tsx +191 -52
  28. web/src/connectors/DatabasesTab.tsx +514 -75
  29. web/src/connectors/RelationshipDiagram.tsx +66 -0
  30. web/src/customer-grid/CustomerGrid.tsx +85 -13
  31. web/src/customer-grid/MapView.tsx +99 -30
  32. web/src/customer-grid/SwipeView.tsx +586 -586
  33. web/src/customer-grid/dataPath.ts +20 -4
  34. web/src/index.css +1 -1
  35. web/src/query/queryParts.tsx +1 -1
  36. web/src/settings/ExternalAccessPane.tsx +435 -0
  37. web/src/settings/SettingsModal.tsx +10 -0
  38. web/src/settings/permsModel.ts +1 -0
  39. web/src/sheet/BindingEditor.tsx +359 -184
  40. web/src/sheet/CellActionBar.tsx +10 -21
  41. web/src/sheet/ChartDialog.tsx +25 -2
  42. web/src/sheet/DrillModal.tsx +125 -509
  43. web/src/sheet/KeyTips.tsx +1 -1
  44. web/src/sheet/Ribbon.tsx +132 -14
  45. web/src/sheet/SheetChart.tsx +48 -6
  46. web/src/sheet/SheetChartLayer.tsx +379 -0
  47. web/src/sheet/SheetGrid.tsx +249 -246
  48. web/src/sheet/SheetPage.tsx +241 -9
  49. web/src/sheet/SheetRail.tsx +31 -4
  50. web/src/sheet/a1.ts +18 -2
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "fb85b60",
3
  "releases": [
4
  {
5
  "version": "v71",
 
1
  {
2
+ "current": "25a941a",
3
  "releases": [
4
  {
5
  "version": "v71",
VERSION CHANGED
@@ -1 +1 @@
1
- fb85b60
 
1
+ 25a941a
api/application_registry.py CHANGED
@@ -27,6 +27,8 @@ _TEMPLATE_CONTRACTS = {
27
  "types": ["text", "int", "currency", "pct", "rating", "number", "float", "decimal"]},
28
  {"key": "longitude", "label": "Longitude", "required": False,
29
  "types": ["text", "int", "currency", "pct", "rating", "number", "float", "decimal"]},
 
 
30
  ],
31
  "defaultPlacement": {"section": "app", "order": 0},
32
  },
@@ -245,6 +247,10 @@ def _template_definition(kind, payload, *, semantic_records=None, field_contract
245
  raise ApplicationError("Routing needs both coordinate fields or neither")
246
  if latitude and latitude == longitude:
247
  raise ApplicationError("Routing latitude and longitude must use different fields")
 
 
 
 
248
 
249
  raw_placement = payload.get("navPlacement")
250
  if not isinstance(raw_placement, dict) or set(raw_placement) != {"section", "order"}:
 
27
  "types": ["text", "int", "currency", "pct", "rating", "number", "float", "decimal"]},
28
  {"key": "longitude", "label": "Longitude", "required": False,
29
  "types": ["text", "int", "currency", "pct", "rating", "number", "float", "decimal"]},
30
+ {"key": "address", "label": "Address", "required": False,
31
+ "types": ["text"]},
32
  ],
33
  "defaultPlacement": {"section": "app", "order": 0},
34
  },
 
247
  raise ApplicationError("Routing needs both coordinate fields or neither")
248
  if latitude and latitude == longitude:
249
  raise ApplicationError("Routing latitude and longitude must use different fields")
250
+ # A new Route must name at least one placement source. Stored definitions are not revalidated
251
+ # on read, so this create-time refusal does not retire older Applications with an empty map.
252
+ if kind == "route" and not (latitude and longitude) and not field_map.get("address"):
253
+ raise ApplicationError("Routing needs both coordinate fields or an address field")
254
 
255
  raw_placement = payload.get("navPlacement")
256
  if not isinstance(raw_placement, dict) or set(raw_placement) != {"section", "order"}:
api/automation_engine.py CHANGED
@@ -4097,7 +4097,7 @@ POST_SNAPSHOT_FIELDS = [
4097
  # β›”β›” AND THEY DO NOT MAKE "THE LAST 10 REELS" EXPRESSIBLE OVER THIS TABLE. That takes TWO
4098
  # orderings (newest measurement per post, then newest posts), the rollup bag has one `sortBy`,
4099
  # and `ut_ig_posts` already performs the first of them. See the verdict in
4100
- # `.claude/wiki/research/entity-vs-series.md` β€” these columns are for AGE and KIND, not for
4101
  # moving the window here.
4102
  field_def("posted_at", "Posted at", "date"),
4103
  field_def("type", "Type", "select", options=["image", "video", "carousel"]),
 
4097
  # β›”β›” AND THEY DO NOT MAKE "THE LAST 10 REELS" EXPRESSIBLE OVER THIS TABLE. That takes TWO
4098
  # orderings (newest measurement per post, then newest posts), the rollup bag has one `sortBy`,
4099
  # and `ut_ig_posts` already performs the first of them. See the verdict in
4100
+ # `AutoWiki/research/entity-vs-series.md` β€” these columns are for AGE and KIND, not for
4101
  # moving the window here.
4102
  field_def("posted_at", "Posted at", "date"),
4103
  field_def("type", "Type", "select", options=["image", "video", "carousel"]),
api/connectors_meta.py CHANGED
@@ -494,7 +494,7 @@ def main(argv):
494
  print(f"REFUSED: {e}")
495
  return 1
496
  report = probe()
497
- out = (Path(__file__).resolve().parents[2] / ".claude" / "wiki" / "research" / "waves"
498
  / "wave31" / "proto" / "meta-ads-schema.md")
499
  out.parent.mkdir(parents=True, exist_ok=True)
500
  out.write_text(as_markdown(report), encoding="utf-8")
 
494
  print(f"REFUSED: {e}")
495
  return 1
496
  report = probe()
497
+ out = (Path(__file__).resolve().parents[2] / "AutoWiki" / "research" / "waves"
498
  / "wave31" / "proto" / "meta-ads-schema.md")
499
  out.parent.mkdir(parents=True, exist_ok=True)
500
  out.write_text(as_markdown(report), encoding="utf-8")
api/connectors_tt.py CHANGED
@@ -7,7 +7,7 @@ exists at all rather than another thousand lines inside the engine.
7
  β›” **EVERY VENDOR FIELD NAME HERE WAS PROBED, NOT GUESSED.** The whole schema β€” 40 profile / 43
8
  post / 17 comment fields, each with the vendor's own type, description and `pii` flag β€” was read
9
  live from `GET /datasets/{id}/metadata` for **$0.00** and written down in
10
- `.claude/wiki/waves/wave29/proto/tiktok-schema.md` (promoted to `tiktok-capture.md` at
11
  close-out). That document is the AUTHORITY: do not re-probe it, and do not invent a key. Where a
12
  name below reads through a candidate list it is because the vendor has two names for one fact
13
  (`biography`/`signature`, `region`/`country`), never because the name is uncertain.
 
7
  β›” **EVERY VENDOR FIELD NAME HERE WAS PROBED, NOT GUESSED.** The whole schema β€” 40 profile / 43
8
  post / 17 comment fields, each with the vendor's own type, description and `pii` flag β€” was read
9
  live from `GET /datasets/{id}/metadata` for **$0.00** and written down in
10
+ `AutoWiki/waves/wave29/proto/tiktok-schema.md` (promoted to `tiktok-capture.md` at
11
  close-out). That document is the AUTHORITY: do not re-probe it, and do not invent a key. Where a
12
  name below reads through a candidate list it is because the vendor has two names for one fact
13
  (`biography`/`signature`, `region`/`country`), never because the name is uncertain.
api/main.py CHANGED
@@ -66,6 +66,7 @@ import routes_sheet # noqa: E402 (wave 49 instr 1 / W49-T02 / C1 β€” the Sheet
66
  import routes_customers # noqa: E402
67
  import routes_grid # noqa: E402
68
  import routes_keychain # noqa: E402 (wave 18 C7 β€” keychain + connectors admin surfaces)
 
69
  import routes_statements # noqa: E402 (EXIT-6 β€” the statement sender, off Streamlit)
70
  import routes_nav # noqa: E402
71
  import routes_pages # noqa: E402
@@ -461,6 +462,7 @@ app.include_router(routes_agent_harness.router) # R8 / C4 β€” versioned agent h
461
  # tiles = OpenStreetMap Β· routing = OSRM Β· geocoding = Nominatim, none of them keyed, all of them
462
  # rate-limited by POLITENESS rather than by a bill (~1 req/s, and bulk harvesting is forbidden).
463
  app.include_router(routes_geo.router) # R14 / A11 β€” D's router, A's line (map providers)
 
464
 
465
 
466
  # --- DEPRECATED ALIASES (removed when S2's shell flips; kept so the current bundle keeps working)
 
66
  import routes_customers # noqa: E402
67
  import routes_grid # noqa: E402
68
  import routes_keychain # noqa: E402 (wave 18 C7 β€” keychain + connectors admin surfaces)
69
+ import routes_external # noqa: E402 (wave 56 R3/C7 β€” per-user external AI credential)
70
  import routes_statements # noqa: E402 (EXIT-6 β€” the statement sender, off Streamlit)
71
  import routes_nav # noqa: E402
72
  import routes_pages # noqa: E402
 
462
  # tiles = OpenStreetMap Β· routing = OSRM Β· geocoding = Nominatim, none of them keyed, all of them
463
  # rate-limited by POLITENESS rather than by a bill (~1 req/s, and bulk harvesting is forbidden).
464
  app.include_router(routes_geo.router) # R14 / A11 β€” D's router, A's line (map providers)
465
+ app.include_router(routes_external.router)
466
 
467
 
468
  # --- DEPRECATED ALIASES (removed when S2's shell flips; kept so the current bundle keeps working)
api/odoo_relational.py CHANGED
@@ -49,6 +49,7 @@ the oracle's predicate as an explicit `payment_state` condition pair.
49
  """
50
  import datetime as _dt
51
  import json as _json
 
52
 
53
  #: β›” ROUTE ENTITLEMENT, NOT THE SPAWN GATE β€” `refresh()` stopped reading this at W53-T39 / R3,
54
  #: which admits on CONFIGURED CREDENTIALS (`available()`) so a second Odoo tenant needs no edit.
@@ -2001,6 +2002,257 @@ def refresh_readable_model_catalog(rt, connection_id=None, client=None, force=Fa
2001
  return result
2002
 
2003
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2004
  #: ⭐⭐ W53-T38 / C2 β€” THE CONNECTOR SCHEMA SPEC ODOO HAS NEVER HAD.
2005
  #:
2006
  #: Amazon and Meta each got a `ConnectorTableSpec` row per table in `platform/core/connector_spec.py`
 
49
  """
50
  import datetime as _dt
51
  import json as _json
52
+ import time as _time
53
 
54
  #: β›” ROUTE ENTITLEMENT, NOT THE SPAWN GATE β€” `refresh()` stopped reading this at W53-T39 / R3,
55
  #: which admits on CONFIGURED CREDENTIALS (`available()`) so a second Odoo tenant needs no edit.
 
2002
  return result
2003
 
2004
 
2005
+ # The population fact is deliberately separate from the readable-model catalogue. Measured on
2006
+ # Royal Imports on 2026-09-08: discovery found 499 readable models in 22.62 s, then exact
2007
+ # search_count calls took 67.87 s for 494 models at 137 ms per model; 239 held rows. A sampled
2008
+ # search_read was slower and raised on account.move, so sampling is neither the cheap nor the
2009
+ # reliable fallback. The exact pass stays explicit and cached because a cold 90.5 s pass cannot
2010
+ # sit on the connector detail request.
2011
+ POPULATION_CENSUS_KEY = "odoo_population_census"
2012
+ POPULATION_CENSUS_VERSION = 1
2013
+ FIELD_CENSUS_KEY = "odoo_field_population"
2014
+ FIELD_CENSUS_VERSION = 1
2015
+ _FIELD_CENSUS_UNCOUNTABLE_TYPES = {"one2many", "many2many"}
2016
+
2017
+
2018
+ def field_census(rt, connection_id=None):
2019
+ """Return the cached per-model field counts; this reader never contacts Odoo."""
2020
+ try:
2021
+ cached = rt.get(FIELD_CENSUS_KEY) if rt is not None else None
2022
+ except Exception: # noqa: BLE001
2023
+ cached = None
2024
+ if not isinstance(cached, dict) or cached.get("version") != FIELD_CENSUS_VERSION:
2025
+ return {}
2026
+ connections = cached.get("connections")
2027
+ if not isinstance(connections, dict):
2028
+ return {}
2029
+ stored = connections.get(_catalog_slot(connection_id))
2030
+ if not isinstance(stored, dict):
2031
+ return {}
2032
+ answer = {}
2033
+ for model, report in stored.items():
2034
+ if not str(model).strip() or not isinstance(report, dict):
2035
+ continue
2036
+ raw_counts = report.get("counts") if isinstance(report.get("counts"), dict) else {}
2037
+ counts = {str(name): int(value) for name, value in raw_counts.items()
2038
+ if str(name).strip() and isinstance(value, int)
2039
+ and not isinstance(value, bool) and value >= 0}
2040
+ raw_errors = report.get("errors")
2041
+ errors = ([str(value) for value in raw_errors]
2042
+ if isinstance(raw_errors, (list, tuple)) else [])
2043
+ try:
2044
+ duration_ms = max(0, int(report.get("durationMs") or 0))
2045
+ except (TypeError, ValueError, OverflowError):
2046
+ duration_ms = 0
2047
+ answer[str(model)] = {
2048
+ "capturedAt": str(report.get("capturedAt") or ""),
2049
+ "durationMs": duration_ms,
2050
+ "counts": counts,
2051
+ "errors": errors,
2052
+ "complete": report.get("complete") is True,
2053
+ }
2054
+ return answer
2055
+
2056
+
2057
+ def refresh_field_census(rt, model, connection_id=None, client=None, force=False):
2058
+ """Exactly count every countable field in one model using read-only ``search_count``."""
2059
+ model = str(model or "").strip()
2060
+ current = field_census(rt, connection_id).get(model)
2061
+ if current and current.get("capturedAt") and not force:
2062
+ return current
2063
+
2064
+ # Exact per-field domains measured 26 ms on res.partner, 41 ms on sale.order and 72 ms on
2065
+ # account.move on 2026-09-08, making the full models about 5.2 s, 5.1 s and 13.7 s. A sampled
2066
+ # search_read took 3.17 s and 7.68 s on the first two and failed on account.move in Odoo's
2067
+ # XML-RPC marshaller, so every countable field uses exact search_count with no cap or sample.
2068
+ started = _time.monotonic()
2069
+ catalogue = readable_model_catalog(rt, connection_id)
2070
+ row = next((item for item in (catalogue.get("models") or ())
2071
+ if isinstance(item, dict) and str(item.get("model") or "").strip() == model), None)
2072
+ fields = dict(row.get("fields") or {}) if row else {}
2073
+ counts = {}
2074
+ errors = []
2075
+ if not model:
2076
+ errors.append("model: a model name is required")
2077
+ elif row is None:
2078
+ errors.append(f"{model}: model is not in the readable model catalogue")
2079
+
2080
+ def _count_all(bound_client):
2081
+ for name, metadata in fields.items():
2082
+ field_name = str(name or "").strip()
2083
+ field_meta = metadata if isinstance(metadata, dict) else {}
2084
+ field_type = str(field_meta.get("type") or "")
2085
+ if not field_name:
2086
+ continue
2087
+ if field_type in _FIELD_CENSUS_UNCOUNTABLE_TYPES:
2088
+ # Relational collection fields do not answer `!= False` usefully. They remain
2089
+ # unknown and are never recorded as empty or selected for automatic enablement.
2090
+ errors.append(f"{model}.{field_name}: {field_type} cannot be counted usefully "
2091
+ "with a non-null domain")
2092
+ continue
2093
+ try:
2094
+ # This is the only Odoo operation in the field census. It cannot mutate data.
2095
+ counts[field_name] = int(bound_client.search_count(
2096
+ model, [(field_name, "!=", False)]))
2097
+ except Exception as exc: # noqa: BLE001
2098
+ errors.append(f"{model}.{field_name}: {type(exc).__name__}: {exc}")
2099
+
2100
+ if client is not None and fields:
2101
+ _count_all(client)
2102
+ elif fields:
2103
+ try:
2104
+ source = (rt.odoo_source() if connection_id is None
2105
+ else rt.odoo_source(connection_id))
2106
+ if source is None:
2107
+ errors.append("connection: Odoo source is unavailable")
2108
+ else:
2109
+ from core.odoo import get_odoo
2110
+ with source._bound(): # tenant credential + scope
2111
+ _count_all(get_odoo())
2112
+ except Exception as exc: # noqa: BLE001
2113
+ errors.append(f"connection: {type(exc).__name__}: {exc}")
2114
+
2115
+ countable = sum(
2116
+ 1 for name, metadata in fields.items()
2117
+ if str(name or "").strip()
2118
+ and str((metadata if isinstance(metadata, dict) else {}).get("type") or "")
2119
+ not in _FIELD_CENSUS_UNCOUNTABLE_TYPES)
2120
+ result = {
2121
+ "capturedAt": _dt.datetime.now(_dt.timezone.utc).isoformat(),
2122
+ "durationMs": int((_time.monotonic() - started) * 1000),
2123
+ "counts": counts,
2124
+ "errors": errors,
2125
+ "complete": row is not None and catalogue.get("complete") is True and not errors
2126
+ and len(counts) == countable,
2127
+ }
2128
+ slot = _catalog_slot(connection_id)
2129
+
2130
+ def _cache(current_cache):
2131
+ current_cache = dict(current_cache) if isinstance(current_cache, dict) else {}
2132
+ connections = dict(current_cache.get("connections") or {})
2133
+ models = dict(connections.get(slot) or {})
2134
+ models[model] = result
2135
+ connections[slot] = models
2136
+ return {"version": FIELD_CENSUS_VERSION, "connections": connections}
2137
+
2138
+ rt.update(FIELD_CENSUS_KEY, _cache, flush="sync")
2139
+ return result
2140
+
2141
+
2142
+ def population_census(rt, connection_id=None):
2143
+ """The last census, from the tenant store. Reading it never contacts Odoo."""
2144
+ empty = {"version": POPULATION_CENSUS_VERSION, "capturedAt": "", "complete": False,
2145
+ "durationMs": 0, "counts": {}, "errors": [], "modelsCounted": 0,
2146
+ "modelsWithRows": 0}
2147
+ try:
2148
+ cached = rt.get(POPULATION_CENSUS_KEY) if rt is not None else None
2149
+ except Exception: # noqa: BLE001
2150
+ return empty
2151
+ if not isinstance(cached, dict) or cached.get("version") != POPULATION_CENSUS_VERSION:
2152
+ return empty
2153
+ connections = cached.get("connections")
2154
+ if not isinstance(connections, dict):
2155
+ return empty
2156
+ slot = connections.get(_catalog_slot(connection_id)) or {}
2157
+ if not isinstance(slot, dict):
2158
+ return empty
2159
+ raw_counts = slot.get("counts") if isinstance(slot.get("counts"), dict) else {}
2160
+ counts = {str(model): int(value) for model, value in raw_counts.items()
2161
+ if str(model).strip() and isinstance(value, int) and not isinstance(value, bool)
2162
+ and value >= 0}
2163
+ raw_errors = slot.get("errors")
2164
+ errors = ([str(value) for value in raw_errors]
2165
+ if isinstance(raw_errors, (list, tuple)) else [])
2166
+
2167
+ def _nonnegative_int(value):
2168
+ try:
2169
+ return max(0, int(value))
2170
+ except (TypeError, ValueError, OverflowError):
2171
+ return 0
2172
+
2173
+ return {"version": POPULATION_CENSUS_VERSION,
2174
+ "capturedAt": str(slot.get("capturedAt") or ""),
2175
+ "complete": slot.get("complete") is True,
2176
+ "durationMs": _nonnegative_int(slot.get("durationMs")),
2177
+ "counts": counts,
2178
+ "errors": errors,
2179
+ "modelsCounted": _nonnegative_int(slot.get("modelsCounted")),
2180
+ "modelsWithRows": _nonnegative_int(slot.get("modelsWithRows"))}
2181
+
2182
+
2183
+ def refresh_population_census(rt, connection_id=None, client=None, force=False):
2184
+ """Count every readable model with read-only ``search_count`` and cache the result."""
2185
+ current = population_census(rt, connection_id)
2186
+ if current["capturedAt"] and not force:
2187
+ return current
2188
+
2189
+ # Start before possible discovery so durationMs is the wall clock the person waiting sees:
2190
+ # about 68 s with a warm catalogue and about 90.5 s on a fresh workspace in the measured run.
2191
+ started = _time.monotonic()
2192
+ catalogue = readable_model_catalog(rt, connection_id)
2193
+ if not catalogue["models"]:
2194
+ catalogue = refresh_readable_model_catalog(
2195
+ rt, connection_id=connection_id, client=client, force=False)
2196
+
2197
+ models = []
2198
+ seen = set()
2199
+ for row in catalogue.get("models") or ():
2200
+ model = str(row.get("model") or "").strip() if isinstance(row, dict) else ""
2201
+ if model and model not in seen:
2202
+ seen.add(model)
2203
+ models.append(model)
2204
+
2205
+ counts = {}
2206
+ errors = [str(value) for value in (catalogue.get("errors") or ())]
2207
+ if not models and catalogue.get("complete") is not True:
2208
+ errors.append("catalogue: no complete readable model catalogue is available")
2209
+
2210
+ def _count_all(bound_client):
2211
+ for model in models:
2212
+ try:
2213
+ # search_count is the only Odoo operation in the census. It cannot mutate data.
2214
+ counts[model] = int(bound_client.search_count(model, []))
2215
+ except Exception as exc: # noqa: BLE001
2216
+ errors.append(f"{model}: {type(exc).__name__}: {exc}")
2217
+
2218
+ if client is not None:
2219
+ _count_all(client)
2220
+ elif models:
2221
+ try:
2222
+ source = (rt.odoo_source() if connection_id is None
2223
+ else rt.odoo_source(connection_id))
2224
+ if source is None:
2225
+ errors.append("connection: Odoo source is unavailable")
2226
+ else:
2227
+ from core.odoo import get_odoo
2228
+ with source._bound(): # tenant credential + scope
2229
+ _count_all(get_odoo())
2230
+ except Exception as exc: # noqa: BLE001
2231
+ errors.append(f"connection: {type(exc).__name__}: {exc}")
2232
+
2233
+ result = {
2234
+ "version": POPULATION_CENSUS_VERSION,
2235
+ "capturedAt": _dt.datetime.now(_dt.timezone.utc).isoformat(),
2236
+ "complete": catalogue.get("complete") is True and not errors
2237
+ and len(counts) == len(models),
2238
+ "durationMs": int((_time.monotonic() - started) * 1000),
2239
+ "counts": counts,
2240
+ "errors": errors,
2241
+ "modelsCounted": len(counts),
2242
+ "modelsWithRows": sum(1 for value in counts.values() if value > 0),
2243
+ }
2244
+ slot = _catalog_slot(connection_id)
2245
+
2246
+ def _cache(current_cache):
2247
+ current_cache = dict(current_cache) if isinstance(current_cache, dict) else {}
2248
+ connections = dict(current_cache.get("connections") or {})
2249
+ connections[slot] = result
2250
+ return {"version": POPULATION_CENSUS_VERSION, "connections": connections}
2251
+
2252
+ rt.update(POPULATION_CENSUS_KEY, _cache, flush="sync")
2253
+ return result
2254
+
2255
+
2256
  #: ⭐⭐ W53-T38 / C2 β€” THE CONNECTOR SCHEMA SPEC ODOO HAS NEVER HAD.
2257
  #:
2258
  #: Amazon and Meta each got a `ConnectorTableSpec` row per table in `platform/core/connector_spec.py`
api/routes_connectors.py CHANGED
@@ -33,6 +33,7 @@ from deps import Session, err, require_session
33
  #: of it (a gate, a future module page) must not have to import FastAPI to ask what category a
34
  #: connector is in.
35
  from core import connector_directory
 
36
  #: ⭐ W53-T27 / R9 / C2 β€” the label RESOLVER, imported rather than re-written. "Shipped default,
37
  #: per-tenant override, absent means inherit" is one idea and `core/schema_overlay.py` already
38
  #: owns it for fields; `merge_database_labels` is that idea for a database's own name. This module
@@ -114,7 +115,7 @@ PLANNED = [
114
  # (Instagram arriving another way) is now visible ON the Scraper card, so keeping it would put
115
  # Instagram on this page twice, once as working and once as blocked. The Meta business
116
  # verification blocker itself is not lost β€” it is D-86's subject and lives in
117
- # `.claude/wiki/research/ads-connectors-owner-actions.md`, where an owner action belongs.
118
  ]
119
 
120
  #: ⭐ WAVE 30 Β· R4 β€” THE SCRAPER'S PLATFORMS, and the whole shape of the ruling in one list.
@@ -1102,6 +1103,78 @@ def _odoo_admin(session):
1102
  raise err(403, "not_admin", "only an administrator can inspect the Odoo schema")
1103
 
1104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1105
  def _schema_catalog(session):
1106
  """Rows-free Odoo field catalogue; source fields remain discoverable when every value is empty."""
1107
  return _schema_catalog_rt(session.runtime)
@@ -1157,17 +1230,86 @@ def _schema_catalog_rt(rt):
1157
 
1158
 
1159
  @router.get("/connectors/odoo/status")
1160
- def odoo_status(session: Session = Depends(require_session)):
1161
  _odoo_admin(session)
1162
  import odoo_relational
1163
  cfg = odoo_relational.read_config(session.runtime)
1164
  stored = session.runtime.get(_ODOO_SYNC_STATUS) or {}
1165
  errors = stored.get("errors") if isinstance(stored.get("errors"), list) else []
1166
  phase = str(stored.get("phase") or "unknown")
 
 
 
 
 
 
 
 
 
 
 
 
 
1167
  return {"schedule": cfg.get("syncEvery"),
1168
- "health": "paused" if cfg.get("frozen") else "error" if errors else phase,
1169
- "lastRun": stored.get("lastRun"), "errors": errors[:20],
1170
- "frozen": cfg.get("frozen") is True}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1171
 
1172
 
1173
  @router.get("/connectors/odoo/schema")
@@ -1193,6 +1335,181 @@ def odoo_schema(session: Session = Depends(require_session)):
1193
  "source": "Odoo"}
1194
 
1195
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1196
  @router.patch("/connectors/odoo/schema/{field_key}")
1197
  def odoo_schema_enable(field_key: str, body: dict = Body(default=None),
1198
  session: Session = Depends(require_session)):
@@ -1219,9 +1536,7 @@ def odoo_schema_enable(field_key: str, body: dict = Body(default=None),
1219
  _ODOO_SCHEMA_ENABLEMENTS,
1220
  lambda current: {**(current if isinstance(current, dict) else {}), key: enabled},
1221
  flush="sync")
1222
- for cache_key in list(getattr(session.runtime, "pool_cache", {}) or {}):
1223
- if isinstance(cache_key, tuple) and cache_key[:1] == ("product_pool",):
1224
- session.runtime.pool_cache.pop(cache_key, None)
1225
  return {"key": key, "enabled": enabled, "source": "Odoo",
1226
  "permissionWall": "normal field permissions"}
1227
 
@@ -1630,7 +1945,7 @@ def _database_name_overrides(rt):
1630
 
1631
 
1632
  def _rename_rights(rt, uname, is_admin, keys):
1633
- """`{table key: bool}` β€” which of these databases THIS reader may rename (R9's write wall).
1634
 
1635
  β›” THE SAME PREDICATE `routes_nav.save_nav_meta` APPLIES TO A `ut_` KEY, not a second one:
1636
  `user_tables.may_open`, i.e. the table's creator, a tenant admin, or a share grant. Two ideas
@@ -1640,20 +1955,30 @@ def _rename_rights(rt, uname, is_admin, keys):
1640
  technicality: `nav_meta` is keyed by TABLE key, so a name stored for a table nobody can open
1641
  would sit in the tenant's document naming nothing, and the rail would never show it.
1642
 
1643
- ⚠ IT IS SERVED PER ROW because the answer IS per row, and because a control the server will
1644
- refuse is R7's banned shape. One `lend_defs` read answers the whole list; that projection
1645
- carries definitions without rows (~0.1% of the document's bytes).
 
 
 
 
1646
  """
1647
  try:
1648
  import core.user_tables as user_tables # noqa: PLC0415 - lazy, as elsewhere
1649
  definitions = user_tables.lend_defs(rt)
1650
- return {key: bool(str(key).startswith("ut_")
1651
- and user_tables.get(key, st=definitions)
1652
- and user_tables.may_open(key, uname, bool(is_admin), st=definitions))
1653
- for key in keys}
 
 
 
 
 
 
1654
  except Exception: # noqa: BLE001
1655
  # Fail closed. A wall that could not be read is not a wall that admitted you.
1656
- return {key: False for key in keys}
1657
 
1658
 
1659
  def _named_databases(rt, is_admin, uname, rows):
@@ -1667,7 +1992,9 @@ def _named_databases(rt, is_admin, uname, rows):
1667
  named = schema_overlay.merge_database_labels(rows, _database_name_overrides(rt))
1668
  rights = _rename_rights(rt, uname, is_admin, [str(row.get("key") or "") for row in named])
1669
  for row in named:
1670
- row["canRename"] = bool(rights.get(str(row.get("key") or "")))
 
 
1671
  return named
1672
 
1673
 
@@ -1716,8 +2043,13 @@ def _detail_databases(rt, is_admin, connector_key, uname=""):
1716
  import odoo_relational
1717
  choices = odoo_relational.grid_choices(rt)
1718
  models = dict(getattr(odoo_relational, "ODOO_TABLE_MODELS", {}) or {})
 
 
 
1719
  except Exception: # noqa: BLE001
1720
  return []
 
 
1721
  catalog = {}
1722
  if is_admin:
1723
  try:
@@ -1742,11 +2074,16 @@ def _detail_databases(rt, is_admin, connector_key, uname=""):
1742
  # uses, so it stays derived from `ODOO_TABLE_MODELS` whatever C2 says a row is called.
1743
  # Conflating the two would let a spec edit silently change which switches move together.
1744
  declared = spec.get(key) or {}
 
 
 
1745
  out.append({"key": key,
1746
  "label": str(declared.get("label") or choice.get("label") or key),
1747
  "defaultLabel": str(declared.get("label") or choice.get("label") or key),
1748
  "native": str(declared.get("native") or model),
1749
  "enabled": bool(choice.get("enabled")),
 
 
1750
  "fields": [dict(field) for field in fields],
1751
  "excluded": [dict(item) for item in excluded],
1752
  "sharesFieldsWith": [other for other in shared.get(model, ())
@@ -1906,7 +2243,9 @@ def _detail_introspection(rt, is_admin, row):
1906
  "creates cannot be listed field by field.")
1907
  return {"introspectable": False, "reason": reason, "fieldsVisible": False,
1908
  "canToggleFields": False, "canToggleTables": False,
1909
- "catalogueComplete": False, "capturedAt": "", "excludedBasis": ""}
 
 
1910
  if key == "amazon_sp":
1911
  # ⭐⭐ W52 Β· R6. Introspectable under the AMENDED test (a real schema artifact, not a
1912
  # `fields_get`), and deliberately with NO generic toggles: there is no Amazon field-toggle
@@ -1936,14 +2275,18 @@ def _detail_introspection(rt, is_admin, row):
1936
  # unstamped pinned catalogue is a stale seed waiting to happen, and this screen is
1937
  # the only place the staleness becomes visible.
1938
  "capturedAt": captured,
1939
- "excludedBasis": _AMAZON_EXCLUDED_BASIS}
 
 
1940
  complete = False
1941
  captured = ""
 
1942
  try:
1943
  import core.user_tables as user_tables
1944
  snapshot = user_tables.odoo_schema_snapshot(rt)
1945
  import odoo_relational
1946
  discovered = odoo_relational.readable_model_catalog(rt)
 
1947
  has_discovery = bool(discovered.get("capturedAt"))
1948
  complete = (discovered.get("complete") is True if has_discovery
1949
  else snapshot.get("complete") is True)
@@ -1962,7 +2305,12 @@ def _detail_introspection(rt, is_admin, row):
1962
  "canToggleTables": bool(is_admin),
1963
  "catalogueComplete": complete,
1964
  "capturedAt": captured,
1965
- "excludedBasis": _EXCLUDED_BASIS}
 
 
 
 
 
1966
 
1967
 
1968
  def _detail_overview(row, databases, graph):
 
33
  #: of it (a gate, a future module page) must not have to import FastAPI to ask what category a
34
  #: connector is in.
35
  from core import connector_directory
36
+ from core import connector_sync
37
  #: ⭐ W53-T27 / R9 / C2 β€” the label RESOLVER, imported rather than re-written. "Shipped default,
38
  #: per-tenant override, absent means inherit" is one idea and `core/schema_overlay.py` already
39
  #: owns it for fields; `merge_database_labels` is that idea for a database's own name. This module
 
115
  # (Instagram arriving another way) is now visible ON the Scraper card, so keeping it would put
116
  # Instagram on this page twice, once as working and once as blocked. The Meta business
117
  # verification blocker itself is not lost β€” it is D-86's subject and lives in
118
+ # `AutoWiki/research/ads-connectors-owner-actions.md`, where an owner action belongs.
119
  ]
120
 
121
  #: ⭐ WAVE 30 Β· R4 β€” THE SCRAPER'S PLATFORMS, and the whole shape of the ruling in one list.
 
1103
  raise err(403, "not_admin", "only an administrator can inspect the Odoo schema")
1104
 
1105
 
1106
+ def _sync_admin(session):
1107
+ if not session.admin:
1108
+ raise err(403, "not_admin", "only an administrator can retry a connector sync")
1109
+
1110
+
1111
+ def _sync_payload(connector_key, connection_id, row=None):
1112
+ """One wire shape for every registered connector, including one not yet run."""
1113
+ meta = connector_sync.providers()[connector_key]
1114
+ slot = str(connection_id or "").strip() or "default"
1115
+ if row is None:
1116
+ return {"provider": connector_key, "label": meta["label"],
1117
+ "connectionId": slot, "recorded": False, "state": None,
1118
+ "at": None, "stateAt": None, "from": None,
1119
+ "detail": "no sync has been recorded", "errors": [], "errorsTotal": 0,
1120
+ "databases": [], "retryable": False, "retryHint": meta["retryHint"]}
1121
+ answer = dict(row)
1122
+ answer.update({"label": meta["label"], "recorded": True,
1123
+ "stateAt": row.get("at"), "retryHint": meta["retryHint"]})
1124
+ return answer
1125
+
1126
+
1127
+ def _odoo_sync_runner(session, connection_id):
1128
+ """Run Odoo through C6 without moving provider imports into the data layer."""
1129
+ connector_sync.record(session.runtime, "odoo", connection_id, "syncing")
1130
+ # The current Odoo entry point plans and applies in one call, so the closest truthful seam is
1131
+ # immediately before it starts applying the tenant mirror into governed database definitions.
1132
+ connector_sync.record(session.runtime, "odoo", connection_id, "materializing")
1133
+ import odoo_relational
1134
+ result = odoo_relational.refresh(session.runtime, session.tenant,
1135
+ username=session.uname or "automation",
1136
+ connection_id=connection_id)
1137
+ tables = result.get("tables") if isinstance(result, dict) else {}
1138
+ databases = sorted(str(key) for key in (tables or {}).keys())
1139
+ sync_errors = []
1140
+ if isinstance(result, dict):
1141
+ if result.get("failed"):
1142
+ sync_errors.append(str(result["failed"]))
1143
+ discovered = result.get("discovered")
1144
+ if isinstance(discovered, dict):
1145
+ sync_errors.extend(str(value) for value in (discovered.get("errors") or ()))
1146
+ discovered_tables = discovered.get("tables")
1147
+ if isinstance(discovered_tables, dict):
1148
+ databases.extend(str(key) for key in discovered_tables)
1149
+ if result.get("frozen"):
1150
+ sync_errors.append(str(result.get("note") or "the connector is frozen"))
1151
+ state = ("partial" if databases else "error") if sync_errors else "ready"
1152
+ return connector_sync.record(
1153
+ session.runtime, "odoo", connection_id, state,
1154
+ detail=str(result.get("note") or "") if isinstance(result, dict) else "",
1155
+ errors=sync_errors, databases=sorted(set(databases)),
1156
+ )
1157
+
1158
+
1159
+ # Provider runners are an API-layer capability. The data-layer registration proves Amazon uses
1160
+ # the same contract while this table honestly leaves it without an executable sync.
1161
+ _SYNC_RUNNERS = {"odoo": _odoo_sync_runner}
1162
+
1163
+
1164
+ def _sync_refusals():
1165
+ """The provider refusal types whose OWN sentence is the answer, as a tuple for `except`.
1166
+
1167
+ ⚠ Resolved lazily and defensively: `odoo_relational` is imported inside functions throughout
1168
+ this module to avoid an import cycle, and a refusal handler that could itself raise on import
1169
+ would turn every failed sync into a different failure.
1170
+ """
1171
+ try:
1172
+ import odoo_relational # noqa: PLC0415
1173
+ return (odoo_relational.Refused,)
1174
+ except Exception: # noqa: BLE001
1175
+ return ()
1176
+
1177
+
1178
  def _schema_catalog(session):
1179
  """Rows-free Odoo field catalogue; source fields remain discoverable when every value is empty."""
1180
  return _schema_catalog_rt(session.runtime)
 
1230
 
1231
 
1232
  @router.get("/connectors/odoo/status")
1233
+ def odoo_status(connection_id: str = None, session: Session = Depends(require_session)):
1234
  _odoo_admin(session)
1235
  import odoo_relational
1236
  cfg = odoo_relational.read_config(session.runtime)
1237
  stored = session.runtime.get(_ODOO_SYNC_STATUS) or {}
1238
  errors = stored.get("errors") if isinstance(stored.get("errors"), list) else []
1239
  phase = str(stored.get("phase") or "unknown")
1240
+ lifecycle = connector_sync.read(session.runtime, "odoo", connection_id)
1241
+ # The old keys stay the old default-connection answer. A caller that names a connection gets
1242
+ # that slot's lifecycle instead of the tenant-wide legacy document that caused the C6 defect.
1243
+ named = connection_id is not None
1244
+ shown_errors = (list(lifecycle.get("errors") or ()) if named and lifecycle else
1245
+ [] if named else errors)
1246
+ shown_phase = ((lifecycle or {}).get("state") or "unknown") if named else phase
1247
+ shown_last_run = ((lifecycle or {}).get("at") if named else stored.get("lastRun"))
1248
+ state = ((lifecycle or {}).get("state")
1249
+ or {"syncing": "syncing", "ok": "ready", "error": "error"}.get(shown_phase)
1250
+ or "queued")
1251
+ errors_total = ((lifecycle or {}).get("errorsTotal", 0) if named or lifecycle
1252
+ else len(errors))
1253
  return {"schedule": cfg.get("syncEvery"),
1254
+ "health": "paused" if cfg.get("frozen") else
1255
+ shown_phase if named else "error" if shown_errors else shown_phase,
1256
+ "lastRun": shown_last_run, "errors": shown_errors[:20],
1257
+ "frozen": cfg.get("frozen") is True,
1258
+ "state": state,
1259
+ "stateAt": (lifecycle or {}).get("at") or shown_last_run,
1260
+ "databases": list((lifecycle or {}).get("databases") or ()),
1261
+ "retryable": state in ("error", "partial"),
1262
+ "errorsTotal": int(errors_total or 0),
1263
+ "connectionId": (lifecycle or {}).get("connectionId")
1264
+ or str(connection_id or "").strip() or "default"}
1265
+
1266
+
1267
+ @router.get("/connectors/{connector_key}/sync")
1268
+ def connector_sync_status(connector_key: str, connection_id: str = None,
1269
+ session: Session = Depends(require_session)):
1270
+ registered = connector_sync.providers()
1271
+ if connector_key not in registered:
1272
+ raise err(404, "sync_provider_unknown",
1273
+ f"{connector_key} is not registered for connector sync")
1274
+ row = connector_sync.read(session.runtime, connector_key, connection_id)
1275
+ return _sync_payload(connector_key, connection_id, row)
1276
+
1277
+
1278
+ @router.post("/connectors/{connector_key}/sync/retry")
1279
+ def connector_sync_retry(connector_key: str, connection_id: str = None,
1280
+ session: Session = Depends(require_session)):
1281
+ _sync_admin(session)
1282
+ registered = connector_sync.providers()
1283
+ if connector_key not in registered:
1284
+ raise err(404, "sync_provider_unknown",
1285
+ f"{connector_key} is not registered for connector sync")
1286
+ current = connector_sync.read(session.runtime, connector_key, connection_id)
1287
+ if current and current.get("state") in ("syncing", "materializing"):
1288
+ raise err(409, "sync_already_running",
1289
+ f"{registered[connector_key]['label']} is already "
1290
+ f"{current['state']}; a second concurrent sync was not started")
1291
+ runner = _SYNC_RUNNERS.get(connector_key)
1292
+ if runner is None:
1293
+ raise err(501, "sync_runner_unavailable", registered[connector_key]["retryHint"])
1294
+ connector_sync.record(session.runtime, connector_key, connection_id, "queued",
1295
+ detail="retry requested")
1296
+ try:
1297
+ row = runner(session, connection_id)
1298
+ except _sync_refusals() as exc:
1299
+ # β›”β›” A REFUSAL CARRIES AN ACTIONABLE SENTENCE AND IT MUST REACH THE READER, VERBATIM.
1300
+ # `odoo_relational.Refused` says things like "Add an Odoo credential in the Connectors
1301
+ # panel, then run the sync again" and "tenant holds N of MAX_TABLES databases". Collapsing
1302
+ # that into a generic 500 tells the user their sync broke and hides the one line that says
1303
+ # what to do about it. This screen does not know why the provider refused and must never
1304
+ # compose a guess, which is the same rule the dependents refusal already follows.
1305
+ connector_sync.record(session.runtime, connector_key, connection_id, "error",
1306
+ detail="the connector refused the sync", errors=(str(exc),))
1307
+ raise err(409, "sync_refused", str(exc))
1308
+ except Exception as exc: # noqa: BLE001 - failure is recorded so the retry remains observable
1309
+ connector_sync.record(session.runtime, connector_key, connection_id, "error",
1310
+ detail="connector sync failed", errors=(str(exc),))
1311
+ raise err(500, "sync_failed", f"{registered[connector_key]['label']} sync failed")
1312
+ return _sync_payload(connector_key, connection_id, row)
1313
 
1314
 
1315
  @router.get("/connectors/odoo/schema")
 
1335
  "source": "Odoo"}
1336
 
1337
 
1338
+ @router.post("/connectors/odoo/census")
1339
+ def odoo_population_census(session: Session = Depends(require_session)):
1340
+ """Explicitly count every readable Odoo model; connector detail only reads this cache."""
1341
+ _odoo_admin(session)
1342
+ import odoo_relational
1343
+ census = odoo_relational.refresh_population_census(session.runtime, force=True)
1344
+ return {"capturedAt": str(census.get("capturedAt") or ""),
1345
+ "complete": census.get("complete") is True,
1346
+ "durationMs": int(census.get("durationMs") or 0),
1347
+ "modelsCounted": int(census.get("modelsCounted") or 0),
1348
+ "modelsWithRows": int(census.get("modelsWithRows") or 0),
1349
+ "errors": [str(value) for value in (census.get("errors") or ())][:50]}
1350
+
1351
+
1352
+ def _materialisation_failure_reason(result):
1353
+ """The materialiser's own reason, made safe for a sentence shown in the connector modal."""
1354
+ result = result if isinstance(result, dict) else {}
1355
+ candidates = []
1356
+ if result.get("note"):
1357
+ candidates.append(result.get("note"))
1358
+ if result.get("failed"):
1359
+ candidates.append(result.get("failed"))
1360
+ errors = result.get("errors")
1361
+ candidates.extend(errors if isinstance(errors, (list, tuple)) else (errors,))
1362
+ discovered = result.get("discovered")
1363
+ if isinstance(discovered, dict):
1364
+ errors = discovered.get("errors")
1365
+ candidates.extend(errors if isinstance(errors, (list, tuple)) else (errors,))
1366
+ reason = str(next((value for value in candidates if str(value or "").strip()), "")).strip()
1367
+ # Provider errors can carry typographic punctuation. Screen strings use plain punctuation.
1368
+ reason = reason.replace("\u2014", ",").replace("\u2013", "-")
1369
+ return reason[:1].upper() + reason[1:] if reason else ""
1370
+
1371
+
1372
+ def _evict_odoo_product_pools(rt):
1373
+ """Drop every raw-field-sensitive row pool after field enablement changes."""
1374
+ for cache_key in list(getattr(rt, "pool_cache", {}) or {}):
1375
+ if isinstance(cache_key, tuple) and cache_key[:1] == ("product_pool",):
1376
+ rt.pool_cache.pop(cache_key, None)
1377
+
1378
+
1379
+ def _enable_odoo_database(table_key, session):
1380
+ """Turn on one declared Odoo database and materialise it before reporting success."""
1381
+ if not session.admin:
1382
+ raise err(403, "not_admin", "only an administrator can enable an Odoo database")
1383
+
1384
+ import odoo_relational # noqa: PLC0415 - provider owns both paths
1385
+ key = str(table_key or "").strip()
1386
+ choices = {str(choice.get("key") or ""): choice
1387
+ for choice in odoo_relational.grid_choices(session.runtime)}
1388
+ if key not in choices:
1389
+ raise err(404, "unknown_odoo_database",
1390
+ f"Odoo does not declare a database with key {key!r}")
1391
+
1392
+ # ⭐ W56-T31: before this door, enabled meant only "will be included in the next sync".
1393
+ # `canRename` then correctly stayed false because there was no table. The flag remains in the
1394
+ # connector's one CONFIG_KEY document, but this door also creates the database before it can
1395
+ # answer green.
1396
+ def _up(cur):
1397
+ cur = cur if isinstance(cur, dict) else {}
1398
+ cur.setdefault("grids", {}).update({key: True})
1399
+ return cur
1400
+
1401
+ failure = None
1402
+ try:
1403
+ session.runtime.update(odoo_relational.CONFIG_KEY, _up, flush="sync")
1404
+ except Exception: # noqa: BLE001
1405
+ raise err(503, "store_unavailable", "the database setting was not saved. Try again.")
1406
+
1407
+ try:
1408
+ # The curated mirror and the discovered long tail have different materialisers. Choosing
1409
+ # by the provider's authored key map prevents a successful call that silently skips the
1410
+ # requested database.
1411
+ if key in odoo_relational.ODOO_TABLE_MODELS:
1412
+ result = odoo_relational.refresh(session.runtime, session.tenant)
1413
+ else:
1414
+ result = odoo_relational.sync_discovered_models(session.runtime)
1415
+ except odoo_relational.Refused as exc:
1416
+ # The provider owns this sentence. In particular it names missing credentials and the
1417
+ # MAX_TABLES refusal without this route guessing which one happened.
1418
+ failure = (409, "odoo_database_refused", str(exc))
1419
+ except Exception: # noqa: BLE001
1420
+ failure = (500, "database_materialisation_failed",
1421
+ "The setting was enabled, but the database was not created because the "
1422
+ "materialiser failed.")
1423
+
1424
+ facts = (_rename_rights(session.runtime, session.uname, bool(session.admin), [key]).get(key)
1425
+ or {"exists": False, "canRename": False})
1426
+ exists = facts.get("exists") is True
1427
+ can_rename = facts.get("canRename") is True
1428
+ # β›”β›” THE ERROR ENVELOPE STAYS THE ONE SHAPE. `deps.err` is documented as X2's single
1429
+ # non-2xx body, `{"error": {"code", "message"}}`, and an earlier draft of this door attached
1430
+ # `key`, `enabled` and the fresh facts BESIDE that key so the client could read them off a
1431
+ # failure. Two shapes for one thing is what this module's own comments call the defect it has
1432
+ # paid for twice, and a caller that learns to read a sibling off an error will keep doing it.
1433
+ # The client does not need them: the FLAG is written before materialisation is attempted, so
1434
+ # every outcome of this door can change what `/detail` answers, and `flipTable` therefore
1435
+ # re-reads on both paths.
1436
+ if failure is not None:
1437
+ raise err(*failure)
1438
+ if not exists:
1439
+ reason = _materialisation_failure_reason(result)
1440
+ message = "The setting was enabled, but the database was not created."
1441
+ if reason:
1442
+ message = f"{message} {reason}"
1443
+ else:
1444
+ message = f"{message} The materialiser completed without creating it."
1445
+ raise err(409, "database_not_created", message)
1446
+
1447
+ # W56-T32: the explicit enable action may spend a few seconds measuring one model. Exact
1448
+ # non-null search_count calls measured 26 ms per res.partner field, 41 ms on sale.order and
1449
+ # 72 ms on account.move. Sampling was rejected because search_read took seconds and Odoo's
1450
+ # XML-RPC marshaller failed on account.move. The census therefore has no cap or sample.
1451
+ model = str(choices[key].get("model") or
1452
+ odoo_relational.ODOO_TABLE_MODELS.get(key) or "").strip()
1453
+ try:
1454
+ field_report = odoo_relational.refresh_field_census(
1455
+ session.runtime, model, force=True)
1456
+ populated_keys = {
1457
+ f"{model}.{field_name}": True
1458
+ for field_name, count in (field_report.get("counts") or {}).items()
1459
+ if isinstance(count, int) and not isinstance(count, bool) and count > 0
1460
+ }
1461
+
1462
+ # One whole-document write sets every populated field. It never writes False: an empty
1463
+ # field, an unknown one2many or many2many field, and any field whose count failed retain
1464
+ # the user's existing choice rather than being switched off or guessed on.
1465
+ session.runtime.update(
1466
+ _ODOO_SCHEMA_ENABLEMENTS,
1467
+ lambda current: {
1468
+ **(current if isinstance(current, dict) else {}),
1469
+ **populated_keys,
1470
+ },
1471
+ flush="sync")
1472
+ except Exception: # noqa: BLE001
1473
+ raise err(503, "field_auto_enable_failed",
1474
+ "The database was created, but its populated fields could not be switched on. "
1475
+ "Try again.")
1476
+ _evict_odoo_product_pools(session.runtime)
1477
+
1478
+ # Read the siblings from the same detail row that powers `sharesFieldsWith`. The labels are
1479
+ # tenant-effective names, and no pair list is repeated at this write door.
1480
+ detail_rows = _detail_databases(
1481
+ session.runtime, bool(session.admin), "odoo", session.uname or "")
1482
+ detail_by_key = {str(row.get("key") or ""): row for row in detail_rows}
1483
+ detail_row = detail_by_key.get(key) or {}
1484
+ shared_rows = [
1485
+ {"key": sibling_key,
1486
+ "label": str((detail_by_key.get(sibling_key) or {}).get("label") or sibling_key)}
1487
+ for sibling_key in (detail_row.get("sharesFieldsWith") or ())
1488
+ if str(sibling_key or "") in detail_by_key
1489
+ ]
1490
+ # W56-T36: there is deliberately no navigation projection eviction here. Data's database
1491
+ # list comes from
1492
+ # `GET /nav` -> `core.user_tables.all_defs()` -> `TenantRuntime.get_projection(user_tables)`.
1493
+ # Both materialisers above synchronously update that same `user_tables` document; the HF
1494
+ # backend replaces its whole-document cache as part of that write, while Postgres performs a
1495
+ # fresh SELECT for every projection. `pool_cache` contains row pools for built-in databases,
1496
+ # not the `ut_*` definition list, and compiled registry rows never contain tenant databases.
1497
+ # The table now exists, so clients must discard navigation-derived database lists. This is a
1498
+ # wire instruction rather than a guessed client row: `/nav` remains the permission-filtered
1499
+ # authority for which databases the current reader may see.
1500
+ return {"key": key, "enabled": True, "exists": exists, "canRename": can_rename,
1501
+ "workspaceChanged": True, "populatedFieldsEnabled": len(populated_keys),
1502
+ "fieldCensusComplete": field_report.get("complete") is True,
1503
+ "fieldCensusErrors": list(field_report.get("errors") or ()),
1504
+ "autoEnableAlsoAffects": shared_rows}
1505
+
1506
+
1507
+ @router.post("/connectors/odoo/databases/{table_key}/enable")
1508
+ def odoo_database_enable(table_key: str, session: Session = Depends(require_session)):
1509
+ """Enable and create one declared Odoo database in this tenant's governed store."""
1510
+ return _enable_odoo_database(table_key, session)
1511
+
1512
+
1513
  @router.patch("/connectors/odoo/schema/{field_key}")
1514
  def odoo_schema_enable(field_key: str, body: dict = Body(default=None),
1515
  session: Session = Depends(require_session)):
 
1536
  _ODOO_SCHEMA_ENABLEMENTS,
1537
  lambda current: {**(current if isinstance(current, dict) else {}), key: enabled},
1538
  flush="sync")
1539
+ _evict_odoo_product_pools(session.runtime)
 
 
1540
  return {"key": key, "enabled": enabled, "source": "Odoo",
1541
  "permissionWall": "normal field permissions"}
1542
 
 
1945
 
1946
 
1947
  def _rename_rights(rt, uname, is_admin, keys):
1948
+ """`{table key: {exists, canRename}}` for R9's write wall and its prerequisite.
1949
 
1950
  β›” THE SAME PREDICATE `routes_nav.save_nav_meta` APPLIES TO A `ut_` KEY, not a second one:
1951
  `user_tables.may_open`, i.e. the table's creator, a tenant admin, or a share grant. Two ideas
 
1955
  technicality: `nav_meta` is keyed by TABLE key, so a name stored for a table nobody can open
1956
  would sit in the tenant's document naming nothing, and the rail would never show it.
1957
 
1958
+ ⭐ W56-T31: `enabled` USED TO MEAN "will be included in the next sync", while the screen
1959
+ read as though the database already existed. `canRename` was telling the truth about a table
1960
+ that did not exist. Returning `exists` from this same projection lets the client distinguish
1961
+ that state from a reader who may not open an existing table.
1962
+
1963
+ ⚠ IT IS SERVED PER ROW because the answers ARE per row. One `lend_defs` read answers the
1964
+ whole list; that projection carries definitions without rows (~0.1% of the document's bytes).
1965
  """
1966
  try:
1967
  import core.user_tables as user_tables # noqa: PLC0415 - lazy, as elsewhere
1968
  definitions = user_tables.lend_defs(rt)
1969
+ facts = {}
1970
+ for key in keys:
1971
+ exists = bool(user_tables.get(key, st=definitions))
1972
+ facts[key] = {
1973
+ "exists": exists,
1974
+ "canRename": bool(str(key).startswith("ut_") and exists
1975
+ and user_tables.may_open(
1976
+ key, uname, bool(is_admin), st=definitions)),
1977
+ }
1978
+ return facts
1979
  except Exception: # noqa: BLE001
1980
  # Fail closed. A wall that could not be read is not a wall that admitted you.
1981
+ return {key: {"exists": False, "canRename": False} for key in keys}
1982
 
1983
 
1984
  def _named_databases(rt, is_admin, uname, rows):
 
1992
  named = schema_overlay.merge_database_labels(rows, _database_name_overrides(rt))
1993
  rights = _rename_rights(rt, uname, is_admin, [str(row.get("key") or "") for row in named])
1994
  for row in named:
1995
+ facts = rights.get(str(row.get("key") or "")) or {}
1996
+ row["exists"] = facts.get("exists") is True
1997
+ row["canRename"] = facts.get("canRename") is True
1998
  return named
1999
 
2000
 
 
2043
  import odoo_relational
2044
  choices = odoo_relational.grid_choices(rt)
2045
  models = dict(getattr(odoo_relational, "ODOO_TABLE_MODELS", {}) or {})
2046
+ # This read never contacts Odoo. A 499-model exact pass measured 67.87 s after the
2047
+ # catalogue was warm, so modal detail must never turn a missing cache into inline work.
2048
+ census = odoo_relational.population_census(rt)
2049
  except Exception: # noqa: BLE001
2050
  return []
2051
+ census_at = str(census.get("capturedAt") or "")
2052
+ counts = census.get("counts") if isinstance(census.get("counts"), dict) else {}
2053
  catalog = {}
2054
  if is_admin:
2055
  try:
 
2074
  # uses, so it stays derived from `ODOO_TABLE_MODELS` whatever C2 says a row is called.
2075
  # Conflating the two would let a spec edit silently change which switches move together.
2076
  declared = spec.get(key) or {}
2077
+ # Counts are model-level facts. Databases backed by the same model deliberately show the
2078
+ # same sourceRows number; inventing a per-database domain here would make the number lie.
2079
+ source_rows = counts.get(model) if census_at and model in counts else None
2080
  out.append({"key": key,
2081
  "label": str(declared.get("label") or choice.get("label") or key),
2082
  "defaultLabel": str(declared.get("label") or choice.get("label") or key),
2083
  "native": str(declared.get("native") or model),
2084
  "enabled": bool(choice.get("enabled")),
2085
+ "sourceRows": source_rows,
2086
+ "populated": None if source_rows is None else source_rows > 0,
2087
  "fields": [dict(field) for field in fields],
2088
  "excluded": [dict(item) for item in excluded],
2089
  "sharesFieldsWith": [other for other in shared.get(model, ())
 
2243
  "creates cannot be listed field by field.")
2244
  return {"introspectable": False, "reason": reason, "fieldsVisible": False,
2245
  "canToggleFields": False, "canToggleTables": False,
2246
+ "catalogueComplete": False, "capturedAt": "", "excludedBasis": "",
2247
+ "censusAt": "", "censusComplete": False, "censusDurationMs": 0,
2248
+ "censusModelsCounted": 0, "censusModelsWithRows": 0}
2249
  if key == "amazon_sp":
2250
  # ⭐⭐ W52 Β· R6. Introspectable under the AMENDED test (a real schema artifact, not a
2251
  # `fields_get`), and deliberately with NO generic toggles: there is no Amazon field-toggle
 
2275
  # unstamped pinned catalogue is a stale seed waiting to happen, and this screen is
2276
  # the only place the staleness becomes visible.
2277
  "capturedAt": captured,
2278
+ "excludedBasis": _AMAZON_EXCLUDED_BASIS,
2279
+ "censusAt": "", "censusComplete": False, "censusDurationMs": 0,
2280
+ "censusModelsCounted": 0, "censusModelsWithRows": 0}
2281
  complete = False
2282
  captured = ""
2283
+ census = {}
2284
  try:
2285
  import core.user_tables as user_tables
2286
  snapshot = user_tables.odoo_schema_snapshot(rt)
2287
  import odoo_relational
2288
  discovered = odoo_relational.readable_model_catalog(rt)
2289
+ census = odoo_relational.population_census(rt)
2290
  has_discovery = bool(discovered.get("capturedAt"))
2291
  complete = (discovered.get("complete") is True if has_discovery
2292
  else snapshot.get("complete") is True)
 
2305
  "canToggleTables": bool(is_admin),
2306
  "catalogueComplete": complete,
2307
  "capturedAt": captured,
2308
+ "excludedBasis": _EXCLUDED_BASIS,
2309
+ "censusAt": str(census.get("capturedAt") or ""),
2310
+ "censusComplete": census.get("complete") is True,
2311
+ "censusDurationMs": int(census.get("durationMs") or 0),
2312
+ "censusModelsCounted": int(census.get("modelsCounted") or 0),
2313
+ "censusModelsWithRows": int(census.get("modelsWithRows") or 0)}
2314
 
2315
 
2316
  def _detail_overview(row, databases, graph):
api/routes_external.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-user credential management and the bearer-authenticated external read door."""
2
+
3
+ import json
4
+ from urllib.parse import quote
5
+
6
+ from fastapi import APIRouter, Body, Depends, Header, HTTPException, Request, Response
7
+
8
+ import deps
9
+ from deps import Session, err, require_session
10
+ from core import external_access
11
+
12
+
13
+ router = APIRouter(prefix="/api/v1/external", tags=["external"])
14
+
15
+ _CREDENTIAL_PREFIX = "lpb1."
16
+
17
+
18
+ def _auth_refusal():
19
+ raise err(401, external_access.AUTH_ERROR, "The credential is invalid or revoked.")
20
+
21
+
22
+ def require_external_session(
23
+ authorization: str | None = Header(default=None, alias="Authorization"),
24
+ ) -> Session:
25
+ """Resolve a bearer credential without consulting or extending the browser session cookie."""
26
+ if not isinstance(authorization, str):
27
+ _auth_refusal()
28
+ scheme, separator, token = authorization.strip().partition(" ")
29
+ if not separator or scheme.lower() != "bearer" or not token.strip():
30
+ _auth_refusal()
31
+ try:
32
+ verified = external_access.verify(token.strip())
33
+ except external_access.ExternalAuthError:
34
+ _auth_refusal()
35
+ return Session(
36
+ tenant=verified.tenant,
37
+ user=verified.user,
38
+ claims={
39
+ "t": verified.tenant,
40
+ "u": verified.user["username"],
41
+ "external": True,
42
+ "external_key_id": verified.key_id,
43
+ },
44
+ runtime=verified.runtime,
45
+ )
46
+
47
+
48
+ def require_external_analyst(
49
+ session: Session = Depends(require_external_session),
50
+ ) -> Session:
51
+ """Apply the same Analyst grant wall used by the in-app Assistant and Query."""
52
+ session.require("analyst")
53
+ return session
54
+
55
+
56
+ def _can_use_analyst(session: Session) -> bool:
57
+ try:
58
+ session.require("analyst")
59
+ except HTTPException as exc:
60
+ if exc.status_code == 403:
61
+ return False
62
+ raise
63
+ return True
64
+
65
+
66
+ def _management_refusal(exc: external_access.ExternalAccessError):
67
+ if exc.code == "external_label_invalid":
68
+ raise err(400, exc.code, "Enter a label between 1 and 80 characters.")
69
+ if exc.code == "external_key_not_found":
70
+ raise err(404, exc.code, "That credential was not found.")
71
+ if exc.code in {"external_identity_invalid", "external_account_unavailable"}:
72
+ raise err(409, exc.code, "This account cannot create an external credential.")
73
+ raise err(503, "external_access_unavailable", "External access is unavailable right now.")
74
+
75
+
76
+ def _resolve_external_scope(
77
+ session: Session,
78
+ databases=None,
79
+ *,
80
+ include_schema: bool = False,
81
+ strict_schema: bool = False,
82
+ ):
83
+ """Resolve the status and field contract used by every external scope description.
84
+
85
+ `strict_schema` preserves the schema route's named refusals for unknown, forbidden and
86
+ temporarily unavailable sources. The portable document uses the non-strict form so one
87
+ unavailable source can still be reported with the reason supplied by source status.
88
+ """
89
+ status = deps.assistant_source_status(session, databases=databases)
90
+ definitions = None
91
+
92
+ def fallback_label(database: str) -> str:
93
+ nonlocal definitions
94
+ built_in = deps.module_cache_source(database)
95
+ if built_in:
96
+ return str(built_in.get("label") or database)
97
+ if definitions is None:
98
+ try:
99
+ candidate = session.runtime.get_projection("user_tables", drop=("rows",))
100
+ except Exception:
101
+ candidate = {}
102
+ definitions = candidate if isinstance(candidate, dict) else {}
103
+ definition = definitions.get(database)
104
+ if isinstance(definition, dict):
105
+ return str(definition.get("label") or database)
106
+ return database
107
+
108
+ resolved = []
109
+ for database, raw in sorted(status.items()):
110
+ row = {
111
+ "database": database,
112
+ "permitted": bool(raw.get("permitted")),
113
+ "answerable": bool(raw.get("answerable")),
114
+ "visible": bool(raw.get("visible")),
115
+ "reason": raw.get("reason") or "",
116
+ }
117
+ if include_schema:
118
+ if row["answerable"] or strict_schema:
119
+ scoped = deps.assistant_read_scope(
120
+ session, database, fields=None, filters=None,
121
+ )
122
+ row["schema"] = {
123
+ key: value for key, value in scoped.items()
124
+ if key not in {"records", "filters"}
125
+ }
126
+ row["label"] = str(scoped.get("label") or database)
127
+ row["fields"] = list(scoped.get("fields") or [])
128
+ else:
129
+ row["label"] = fallback_label(database)
130
+ row["fields"] = []
131
+ resolved.append(row)
132
+ return resolved
133
+
134
+
135
+ def _markdown_inline(value) -> str:
136
+ text = str(value or "").replace(chr(0x2014), " - ").replace(chr(0x2013), "-")
137
+ return " ".join(text.replace("`", "'").split())
138
+
139
+
140
+ def _portable_skill_document(session: Session, base_url: str) -> str:
141
+ scoped = [
142
+ row for row in _resolve_external_scope(session, include_schema=True)
143
+ if row["permitted"]
144
+ ]
145
+ example = next((row for row in scoped if row["answerable"]), None)
146
+ if example is None and scoped:
147
+ example = scoped[0]
148
+
149
+ surface_url = f"{base_url.rstrip('/')}/api/v1/external"
150
+ lines = [
151
+ "---",
152
+ "name: loopable-external-data",
153
+ "description: Read this user's governed Loopable data through the external API.",
154
+ "---",
155
+ "",
156
+ "# Loopable external data",
157
+ "",
158
+ ("This surface is a read-only view of the Loopable data this user can already see. "
159
+ "It applies the same database, field, and row permissions as the Loopable app."),
160
+ "",
161
+ "## Authentication",
162
+ "",
163
+ "```http",
164
+ "Authorization: Bearer <your Loopable credential>",
165
+ "```",
166
+ "",
167
+ ("Mint the credential in Loopable Settings. It is shown once, and revoking it stops "
168
+ "the next request."),
169
+ "",
170
+ f"Base URL: `{surface_url}`",
171
+ "",
172
+ "## First call: list databases",
173
+ "",
174
+ "Endpoint: `GET /api/v1/external/databases`",
175
+ "",
176
+ "```sh",
177
+ "curl --request GET \\",
178
+ " --header 'Authorization: Bearer <your Loopable credential>' \\",
179
+ f" '{surface_url}/databases'",
180
+ "```",
181
+ "",
182
+ "Call this first. It returns only databases this user may read or already sees in the app.",
183
+ "",
184
+ "## Read a database schema",
185
+ "",
186
+ "Endpoint: `GET /api/v1/external/databases/{database}/schema`",
187
+ "",
188
+ ]
189
+
190
+ if example is not None:
191
+ database_path = quote(str(example["database"]), safe="")
192
+ fields = example.get("fields") or []
193
+ field_key = next(
194
+ (str(field.get("key")) for field in fields
195
+ if isinstance(field, dict) and field.get("key")),
196
+ None,
197
+ )
198
+ query_body = {
199
+ "fields": [field_key] if field_key else [],
200
+ "filters": None,
201
+ }
202
+ lines.extend([
203
+ "```sh",
204
+ "curl --request GET \\",
205
+ " --header 'Authorization: Bearer <your Loopable credential>' \\",
206
+ f" '{surface_url}/databases/{database_path}/schema'",
207
+ "```",
208
+ "",
209
+ "## Query a database",
210
+ "",
211
+ "Endpoint: `POST /api/v1/external/databases/{database}/query`",
212
+ "",
213
+ "```sh",
214
+ "curl --request POST \\",
215
+ " --header 'Authorization: Bearer <your Loopable credential>' \\",
216
+ " --header 'Content-Type: application/json' \\",
217
+ f" --data '{json.dumps(query_body, separators=(',', ':'))}' \\",
218
+ f" '{surface_url}/databases/{database_path}/query'",
219
+ "```",
220
+ "",
221
+ ])
222
+ if not example["answerable"]:
223
+ lines.extend([
224
+ ("This exact schema and query path names a permitted source, but it is not "
225
+ "answerable right now. The reason appears in the scope below."),
226
+ "",
227
+ ])
228
+ else:
229
+ lines.extend([
230
+ "No schema call is available because this user's current scope has no databases.",
231
+ "",
232
+ "## Query a database",
233
+ "",
234
+ "Endpoint: `POST /api/v1/external/databases/{database}/query`",
235
+ "",
236
+ "No query call is available because this user's current scope has no databases.",
237
+ "",
238
+ ])
239
+
240
+ lines.extend(["## This user's current read scope", ""])
241
+ if not scoped:
242
+ lines.extend(["No databases are currently permitted.", ""])
243
+ for row in scoped:
244
+ database = _markdown_inline(row["database"])
245
+ label = _markdown_inline(row.get("label") or row["database"])
246
+ lines.append(f"### `{database}`: {label}")
247
+ lines.append("")
248
+ if row["answerable"]:
249
+ fields = [
250
+ field for field in (row.get("fields") or [])
251
+ if isinstance(field, dict) and field.get("key")
252
+ ]
253
+ lines.append("Fields this user may read:")
254
+ lines.append("")
255
+ if fields:
256
+ for field in fields:
257
+ key = _markdown_inline(field.get("key"))
258
+ field_label = _markdown_inline(field.get("label") or field.get("key"))
259
+ lines.append(f"- `{key}`: {field_label}")
260
+ else:
261
+ lines.append("- No readable fields are currently exposed.")
262
+ else:
263
+ reason = _markdown_inline(row.get("reason") or "This source is not answerable right now.")
264
+ lines.extend([
265
+ f"Not answerable right now: {reason}",
266
+ "",
267
+ "The readable field contract is unavailable until this source is answerable.",
268
+ ])
269
+ lines.append("")
270
+
271
+ lines.extend([
272
+ "## Limits",
273
+ "",
274
+ ("This surface performs no writes. It returns no data the user cannot already see in "
275
+ "Loopable, and it provides no export beyond what the user could already export from "
276
+ "the app."),
277
+ "",
278
+ ])
279
+ document = "\n".join(lines)
280
+ if _CREDENTIAL_PREFIX in document:
281
+ raise RuntimeError("portable skill document contained a credential value")
282
+ return document
283
+
284
+
285
+ @router.post("/keys", status_code=201)
286
+ def create_key(body=Body(default=None), session: Session = Depends(require_session)):
287
+ """Mint a credential for the signed-in human. Bearer auth is not accepted here."""
288
+ session.require("analyst")
289
+ label = body.get("label") if isinstance(body, dict) else None
290
+ try:
291
+ key, token = external_access.mint(session.runtime, session.uname, session.tenant, label)
292
+ except external_access.ExternalAccessError as exc:
293
+ _management_refusal(exc)
294
+ return {"key": key, "secret": token}
295
+
296
+
297
+ @router.get("/keys")
298
+ def list_keys(session: Session = Depends(require_session)):
299
+ """List only the signed-in human's metadata. Stored hashes and secrets never leave core."""
300
+ try:
301
+ keys = external_access.list_for_user(session.runtime, session.uname, session.tenant)
302
+ except external_access.ExternalAccessError as exc:
303
+ _management_refusal(exc)
304
+ return {"keys": keys, "can_mint": _can_use_analyst(session)}
305
+
306
+
307
+ @router.post("/keys/{key_id}/revoke")
308
+ def revoke_key(key_id: str, session: Session = Depends(require_session)):
309
+ """Tombstone one key owned by the signed-in human. Bearer auth is not accepted here."""
310
+ try:
311
+ key = external_access.revoke(session.runtime, session.uname, session.tenant, key_id)
312
+ except external_access.ExternalAccessError as exc:
313
+ _management_refusal(exc)
314
+ return {"key": key}
315
+
316
+
317
+ @router.get("/skill.md")
318
+ def portable_skill(request: Request, session: Session = Depends(require_session)):
319
+ """Download the signed-in human's current governed external read instructions."""
320
+ session.require("analyst")
321
+ document = _portable_skill_document(session, str(request.base_url))
322
+ return Response(
323
+ content=document,
324
+ media_type="text/markdown",
325
+ headers={"Content-Disposition": 'attachment; filename="skill.md"'},
326
+ )
327
+
328
+
329
+ @router.get("/whoami")
330
+ def whoami(session: Session = Depends(require_external_analyst)):
331
+ """The one observable bearer route in this ticket; later tickets add governed data reads."""
332
+ return {
333
+ "username": session.uname,
334
+ "name": session.user.get("name") or session.uname,
335
+ "tenant": session.tenant,
336
+ "key_id": session.claims["external_key_id"],
337
+ "read_only": True,
338
+ }
339
+
340
+
341
+ @router.get("/databases")
342
+ def list_databases(session: Session = Depends(require_external_analyst)):
343
+ """List only sources this user may read or already sees elsewhere in the product."""
344
+ databases = []
345
+ for row in _resolve_external_scope(session):
346
+ if not (row.get("permitted") or row.get("visible")):
347
+ continue
348
+ public = {
349
+ "database": row["database"],
350
+ "permitted": bool(row.get("permitted")),
351
+ "answerable": bool(row.get("answerable")),
352
+ }
353
+ if not public["answerable"]:
354
+ public["reason"] = row.get("reason") or ""
355
+ databases.append(public)
356
+ return {"databases": databases, "read_only": True}
357
+
358
+
359
+ @router.get("/databases/{database}/schema")
360
+ def database_schema(database: str, session: Session = Depends(require_external_analyst)):
361
+ """Return the field contract after resolving the ordinary strict Assistant read wall."""
362
+ resolved = _resolve_external_scope(
363
+ session, databases=[database], include_schema=True, strict_schema=True,
364
+ )
365
+ return resolved[0]["schema"]
366
+
367
+
368
+ @router.post("/databases/{database}/query")
369
+ def query_database(
370
+ database: str,
371
+ body: dict | None = Body(default=None),
372
+ session: Session = Depends(require_external_analyst),
373
+ ):
374
+ """Read one detached Assistant snapshot; FastAPI rejects non-object request bodies."""
375
+ payload = body or {}
376
+ return deps.assistant_read_scope(
377
+ session,
378
+ database,
379
+ fields=payload.get("fields"),
380
+ filters=payload.get("filters"),
381
+ )
382
+
383
+
384
+ # C7 / R3: one import-time chokepoint makes the external bearer surface structurally read only.
385
+ # POST remains available for bounded query bodies and for the cookie-only credential lifecycle
386
+ # above. No bearer dependency appears on those lifecycle routes.
387
+ _READ_ONLY_METHODS = frozenset({"GET", "POST", "HEAD", "OPTIONS"})
388
+
389
+
390
+ def _assert_read_only_router() -> None:
391
+ for route in router.routes:
392
+ methods = set(getattr(route, "methods", set()) or set())
393
+ refused = methods - _READ_ONLY_METHODS
394
+ if refused:
395
+ joined = ", ".join(sorted(refused))
396
+ raise RuntimeError(f"external route {route.path} advertises refused method {joined}")
397
+
398
+
399
+ _assert_read_only_router()
api/routes_oauth.py CHANGED
@@ -43,7 +43,7 @@ def _redirect_uri(request: Request, provider: str) -> str:
43
  the user actually browsed plants the session on the wrong hostname and they return logged
44
  out. Moving the app to a new hostname means moving this value AND re-registering the
45
  resulting URI in the provider console; one without the other fails closed.
46
- Runbook: `.claude/wiki/research/loopable-domain-runbook.md`."""
47
  base = (os.environ.get("AIOS_PUBLIC_BASE") or "").strip().rstrip("/")
48
  if not base:
49
  base = f"{request.url.scheme}://{request.url.netloc}"
 
43
  the user actually browsed plants the session on the wrong hostname and they return logged
44
  out. Moving the app to a new hostname means moving this value AND re-registering the
45
  resulting URI in the provider console; one without the other fails closed.
46
+ Runbook: `AutoWiki/research/loopable-domain-runbook.md`."""
47
  base = (os.environ.get("AIOS_PUBLIC_BASE") or "").strip().rstrip("/")
48
  if not base:
49
  base = f"{request.url.scheme}://{request.url.netloc}"
api/routes_slack.py CHANGED
@@ -18,7 +18,7 @@ live specimen of identity that LOOKS like a permission and is not.
18
  `core/perm_scope.py` is already strictly more expressive: per database, per row, per FIELD, per
19
  principal. So item 10 is OUR engine projected onto a CHANNEL principal β€” see `agent_principal`
20
  below, which is the whole projection and is nine lines. Study:
21
- `.claude/wiki/research/opentag-adoption.md` (licence gate: MIT, PASSED).
22
 
23
  What OpenTag genuinely contributes is the WRITE-APPROVAL interceptor (`W33-T67`, `approval_card`
24
  below) and nothing else. Its TRANSPORT is AVOID wholesale β€” hosted CopilotKit Intelligence, a
@@ -615,7 +615,7 @@ def _is_empty(value):
615
  False is precisely the kind of write somebody needs to approve, and a naive `if not value`
616
  drops both rows silently β€” the approver then reads a card that does not describe the write
617
  they are approving. The MIT licence gate for this borrowing is recorded in
618
- `.claude/wiki/research/opentag-adoption.md`.
619
  """
620
  return value is None or (isinstance(value, str) and value.strip() == "")
621
 
 
18
  `core/perm_scope.py` is already strictly more expressive: per database, per row, per FIELD, per
19
  principal. So item 10 is OUR engine projected onto a CHANNEL principal β€” see `agent_principal`
20
  below, which is the whole projection and is nine lines. Study:
21
+ `AutoWiki/research/opentag-adoption.md` (licence gate: MIT, PASSED).
22
 
23
  What OpenTag genuinely contributes is the WRITE-APPROVAL interceptor (`W33-T67`, `approval_card`
24
  below) and nothing else. Its TRANSPORT is AVOID wholesale β€” hosted CopilotKit Intelligence, a
 
615
  False is precisely the kind of write somebody needs to approve, and a naive `if not value`
616
  drops both rows silently β€” the approver then reads a card that does not describe the write
617
  they are approving. The MIT licence gate for this borrowing is recorded in
618
+ `AutoWiki/research/opentag-adoption.md`.
619
  """
620
  return value is None or (isinstance(value, str) and value.strip() == "")
621
 
platform/core/connector_directory.py CHANGED
@@ -18,7 +18,7 @@ it, and there is nothing to find. Measured against the live Monid API on 2026-09
18
  tags, categories, metrics, hints`, and none of those carries a sidebar name.
19
 
20
  So the 14 categories are reachable only from Monid's WEB UI SIDEBAR, which is what
21
- `.claude/wiki/waves/wave49/proto/monid-catalogue.md` captured by hand. `MONID_PROVIDERS` is
22
  regenerated by re-reading that file, not by calling an endpoint.
23
 
24
  ⚠ AND THE CATALOGUE IS A FLOOR, NOT A CENSUS. `discover` returns providers absent from the proto
@@ -87,7 +87,7 @@ MONID_CATEGORY_ENDPOINTS = {
87
  #: ⭐⭐ THE AUTHORED CROSSWALK: (provider name, endpoint count, the categories it is filed under).
88
  #:
89
  #: REGENERATION, because there is no generator: re-read the `PROVIDERS` line of
90
- #: `.claude/wiki/waves/wave49/proto/monid-catalogue.md`, which is `name count` pairs separated by
91
  #: the middle dot. The NAME and the COUNT come from there unchanged and `verify_catalog.py` proves
92
  #: it, pair by pair, so a typo here goes red rather than quiet. The CATEGORIES are the authored
93
  #: half: a judgement about which sidebar rows a provider sits under, made once, here.
@@ -312,7 +312,7 @@ MONID_ACTION_STATE = "available"
312
  #: `("Telegram", 7, ...)`: a vendor listing, not a connector we have built or planned. Wave 53
313
  #: adopted only its CREDENTIAL SHAPE on paper and built no runtime path, so the row keeps this
314
  #: word and Telegram is deliberately absent from `routes_connectors.PLANNED`. The build plan,
315
- #: with the two keychain steps it needs first, is `.claude/wiki/research/ideation/telegram-bot.md`.
316
  CATALOGUE_STATE = "catalogue"
317
 
318
  #: ⭐⭐ W49-T14 Β· RULINGS R21 + R24 β€” WHICH CONNECTORS HAVE A FIELD CATALOGUE, AUTHORED IN CODE.
 
18
  tags, categories, metrics, hints`, and none of those carries a sidebar name.
19
 
20
  So the 14 categories are reachable only from Monid's WEB UI SIDEBAR, which is what
21
+ `AutoWiki/waves/wave49/proto/monid-catalogue.md` captured by hand. `MONID_PROVIDERS` is
22
  regenerated by re-reading that file, not by calling an endpoint.
23
 
24
  ⚠ AND THE CATALOGUE IS A FLOOR, NOT A CENSUS. `discover` returns providers absent from the proto
 
87
  #: ⭐⭐ THE AUTHORED CROSSWALK: (provider name, endpoint count, the categories it is filed under).
88
  #:
89
  #: REGENERATION, because there is no generator: re-read the `PROVIDERS` line of
90
+ #: `AutoWiki/waves/wave49/proto/monid-catalogue.md`, which is `name count` pairs separated by
91
  #: the middle dot. The NAME and the COUNT come from there unchanged and `verify_catalog.py` proves
92
  #: it, pair by pair, so a typo here goes red rather than quiet. The CATEGORIES are the authored
93
  #: half: a judgement about which sidebar rows a provider sits under, made once, here.
 
312
  #: `("Telegram", 7, ...)`: a vendor listing, not a connector we have built or planned. Wave 53
313
  #: adopted only its CREDENTIAL SHAPE on paper and built no runtime path, so the row keeps this
314
  #: word and Telegram is deliberately absent from `routes_connectors.PLANNED`. The build plan,
315
+ #: with the two keychain steps it needs first, is `AutoWiki/research/ideation/telegram-bot.md`.
316
  CATALOGUE_STATE = "catalogue"
317
 
318
  #: ⭐⭐ W49-T14 Β· RULINGS R21 + R24 β€” WHICH CONNECTORS HAVE A FIELD CATALOGUE, AUTHORED IN CODE.
platform/core/connector_sync.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tenant-and-connection scoped connector sync lifecycle state.
2
+
3
+ This data-layer module records what a provider runner did. It deliberately does not import or
4
+ call providers: the API layer owns runners while every connector shares this durable vocabulary.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import datetime as _dt
9
+
10
+ import core.store as store
11
+
12
+
13
+ STATE_KEY = "connector_sync_state"
14
+ STATES = ("queued", "syncing", "materializing", "ready", "partial", "error")
15
+ _ERROR_LIMIT = 50
16
+ _DEFAULT_CONNECTION = "default"
17
+ _PROVIDERS = {}
18
+
19
+
20
+ def _st(st):
21
+ return st if st is not None else store
22
+
23
+
24
+ def _key(value):
25
+ return str(value or "").strip()
26
+
27
+
28
+ def _slot(connection_id):
29
+ return _key(connection_id) or _DEFAULT_CONNECTION
30
+
31
+
32
+ def _target(rt, st):
33
+ return st if st is not None else rt
34
+
35
+
36
+ def _public(provider, connection_id, row):
37
+ if not isinstance(row, dict):
38
+ return None
39
+ answer = dict(row)
40
+ answer["provider"] = provider
41
+ answer["connectionId"] = connection_id
42
+ # RULE: retryability follows the state. Storing it would let the two answers drift.
43
+ answer["retryable"] = answer.get("state") in ("error", "partial")
44
+ return answer
45
+
46
+
47
+ def record(rt, provider, connection_id, state, *, detail="", errors=(), databases=(), st=None):
48
+ """Record one lifecycle transition and return its defensive public representation."""
49
+ provider_key = _key(provider)
50
+ if not provider_key:
51
+ raise ValueError("provider is required")
52
+ if state not in STATES:
53
+ # RULE: unknown states are refused. A free-form status eventually stores a typo that the
54
+ # UI cannot render as one of C6's six observable states.
55
+ raise ValueError(f"unknown connector sync state: {state}")
56
+ connection_key = _slot(connection_id)
57
+ all_errors = [str(value) for value in (errors or ())]
58
+ visible_errors = all_errors[:_ERROR_LIMIT]
59
+ now = _dt.datetime.now(_dt.timezone.utc).isoformat()
60
+ written = {}
61
+
62
+ def _apply(current):
63
+ document = dict(current or {})
64
+ providers_doc = dict(document.get(provider_key) or {})
65
+ previous = providers_doc.get(connection_key)
66
+ previous_state = previous.get("state") if isinstance(previous, dict) else None
67
+ row = {
68
+ "state": state,
69
+ # RULE: stamp every transition and name its predecessor. A resting state alone cannot
70
+ # tell the UI whether work advanced, retried, or regressed.
71
+ "at": now,
72
+ "from": previous_state,
73
+ "detail": str(detail or ""),
74
+ # RULE: partial and error stay distinct. Partial exposes databases usable now;
75
+ # error means no usable set was produced.
76
+ "errors": visible_errors,
77
+ # RULE: retain up to 50 errors and report the full count. A storage limit must be
78
+ # observable rather than silently turning additional failures into zero information.
79
+ "errorsTotal": len(all_errors),
80
+ # These are governed table keys, not copied provider rows. In Odoo, row_limit == 0
81
+ # keeps 963,783 GL lines out of the editable user_tables document.
82
+ "databases": [str(value) for value in (databases or ()) if str(value)],
83
+ }
84
+ providers_doc[connection_key] = row
85
+ # RULE: key state by provider and connection. The measured legacy defect is that
86
+ # odoo_sync_status is one tenant document, so a second Odoo connection overwrites the
87
+ # first one's status. The default slot matches Odoo's existing catalog convention.
88
+ document[provider_key] = providers_doc
89
+ written.update(row)
90
+ return document
91
+
92
+ _st(_target(rt, st)).update(STATE_KEY, _apply, flush="sync")
93
+ return _public(provider_key, connection_key, written)
94
+
95
+
96
+ def read(rt, provider, connection_id=None, st=None):
97
+ """Read one connection defensively; store failures mean no recorded state, never a 500."""
98
+ try:
99
+ provider_key = _key(provider)
100
+ connection_key = _slot(connection_id)
101
+ document = _st(_target(rt, st)).get(STATE_KEY) or {}
102
+ providers_doc = document.get(provider_key) if isinstance(document, dict) else None
103
+ row = providers_doc.get(connection_key) if isinstance(providers_doc, dict) else None
104
+ return _public(provider_key, connection_key, row)
105
+ except Exception: # noqa: BLE001 - status reads cannot take down their caller
106
+ return None
107
+
108
+
109
+ def read_all(rt, st=None):
110
+ """Read every provider and connection defensively."""
111
+ try:
112
+ document = _st(_target(rt, st)).get(STATE_KEY) or {}
113
+ answer = {}
114
+ for provider_key, connections in document.items():
115
+ if not isinstance(connections, dict):
116
+ continue
117
+ public_connections = {}
118
+ for connection_key, row in connections.items():
119
+ public = _public(str(provider_key), str(connection_key), row)
120
+ if public is not None:
121
+ public_connections[str(connection_key)] = public
122
+ if public_connections:
123
+ answer[str(provider_key)] = public_connections
124
+ return answer
125
+ except Exception: # noqa: BLE001 - status reads cannot take down their caller
126
+ return {}
127
+
128
+
129
+ def clear(rt, provider, connection_id, st=None):
130
+ """Remove only the named provider/connection state."""
131
+ provider_key = _key(provider)
132
+ connection_key = _slot(connection_id)
133
+
134
+ def _drop(current):
135
+ document = dict(current or {})
136
+ connections = dict(document.get(provider_key) or {})
137
+ connections.pop(connection_key, None)
138
+ if connections:
139
+ document[provider_key] = connections
140
+ else:
141
+ document.pop(provider_key, None)
142
+ return document
143
+
144
+ _st(_target(rt, st)).update(STATE_KEY, _drop, flush="sync")
145
+
146
+
147
+ def register_provider(provider, *, label, retry_hint):
148
+ """Register provider metadata; runners remain in the API layer."""
149
+ provider_key = _key(provider)
150
+ if not provider_key:
151
+ raise ValueError("provider is required")
152
+ _PROVIDERS[provider_key] = {
153
+ "key": provider_key,
154
+ "label": str(label or provider_key),
155
+ "retryHint": str(retry_hint or ""),
156
+ }
157
+
158
+
159
+ def providers():
160
+ """Return a copy of registered provider metadata."""
161
+ return {key: dict(value) for key, value in _PROVIDERS.items()}
162
+
163
+
164
+ register_provider("odoo", label="Odoo", retry_hint="Retry the Odoo database sync.")
165
+ register_provider(
166
+ "amazon_sp",
167
+ label="Amazon",
168
+ retry_hint="No sync runner is wired for this connector yet.",
169
+ )
platform/core/external_access.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-user credentials for the governed external read 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
9
+ from dataclasses import dataclass
10
+ import hashlib
11
+ import hmac
12
+ import secrets
13
+ import time
14
+
15
+ import core.users as users
16
+ 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)
23
+ _DUMMY_HASH = hashlib.sha256(_DUMMY_SALT + b"invalid").hexdigest()
24
+ #: Seconds between two durable `last_used` stamps for ONE credential.
25
+ #:
26
+ #: β›”β›” THE STAMP IS THROTTLED, AND THIS IS NOT AN OPTIMISATION. `st.update(..., flush="sync")` is
27
+ #: a fresh strict read plus a BLOCKING UPLOAD, i.e. one durable commit per verified request. An
28
+ #: external AI reads in bursts and the store's budget is 256 commits an hour, so an unthrottled
29
+ #: stamp would spend a tenant's whole write budget on telemetry and put an upload inside the
30
+ #: latency of every read. It would also make a surface contract C7 calls READ ONLY write on every
31
+ #: single call, which is the claim this module exists to keep true. The pane renders `last_used` to
32
+ #: the minute, so a quarter of an hour of staleness costs the reader nothing.
33
+ #: ⚠ REVOCATION IS NOT THROTTLED AND MUST NEVER BE: `revoke` and `mint` stay `flush="sync"`, and
34
+ #: verification still reads the bucket FRESH on every request, which is what makes "revoking stops
35
+ #: the next request" true.
36
+ _STAMP_EVERY = 900.0
37
+
38
+
39
+ class ExternalAccessError(RuntimeError):
40
+ """A stable core-layer refusal. HTTP status and copy belong to the API layer."""
41
+
42
+ def __init__(self, code: str):
43
+ super().__init__(code)
44
+ self.code = code
45
+
46
+
47
+ 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."""
54
+
55
+ tenant: str
56
+ key_id: str
57
+ user: dict
58
+ runtime: object
59
+
60
+
61
+ def _now() -> str:
62
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
63
+
64
+
65
+ def _stamp_is_due(last_used, now: float) -> bool:
66
+ """Is this credential's `last_used` stale enough to be worth a durable write?
67
+
68
+ An absent, unparseable or future stamp is DUE, so a corrupt value self-heals on the next
69
+ request rather than freezing the field forever.
70
+ """
71
+ if not last_used:
72
+ return True
73
+ try:
74
+ seen = calendar.timegm(time.strptime(str(last_used), "%Y-%m-%dT%H:%M:%SZ"))
75
+ except (TypeError, ValueError):
76
+ return True
77
+ return not (0.0 <= now - seen < _STAMP_EVERY)
78
+
79
+
80
+ def _digest(salt: bytes, secret: str) -> str:
81
+ """Hash one external secret with SHA-256 and its per-record random salt.
82
+
83
+ The secret has 256 bits of machine-generated randomness, not human-password entropy. A slow
84
+ password KDF therefore buys nothing against an offline attacker and would deliberately delay
85
+ every request on the read surface.
86
+ """
87
+ return hashlib.sha256(salt + secret.encode("utf-8")).hexdigest()
88
+
89
+
90
+ def _book(st, *, fresh: bool = True) -> dict:
91
+ try:
92
+ value = st.get(BUCKET, fresh=fresh)
93
+ except Exception as exc:
94
+ raise ExternalAccessError("external_access_unavailable") from exc
95
+ if value is None:
96
+ return {}
97
+ if not isinstance(value, dict):
98
+ raise ExternalAccessError("external_access_unavailable")
99
+ return value
100
+
101
+
102
+ def _normalise_owner(username: str, tenant: str) -> tuple[str, str]:
103
+ owner = str(username or "").strip().lower()
104
+ tenant_key = str(tenant or "").strip().lower()
105
+ if not owner or not tenant_key:
106
+ raise ExternalAccessError("external_identity_invalid")
107
+ return owner, tenant_key
108
+
109
+
110
+ def _assert_bound_runtime(st, tenant: str) -> None:
111
+ if str(getattr(st, "key", "") or "").strip().lower() != tenant:
112
+ raise ExternalAccessError("external_identity_invalid")
113
+
114
+
115
+ def _active_public_user(username: str, tenant: str) -> dict:
116
+ try:
117
+ registry = users.registry() or {}
118
+ except Exception as exc:
119
+ raise ExternalAccessError("external_access_unavailable") from exc
120
+ if not isinstance(registry, dict):
121
+ raise ExternalAccessError("external_access_unavailable")
122
+ record = registry.get(username)
123
+ if not isinstance(record, dict) or not record.get("active", True):
124
+ raise ExternalAccessError("external_account_unavailable")
125
+ public = users._public(username, record)
126
+ if public.get("tenant") != tenant:
127
+ raise ExternalAccessError("external_account_unavailable")
128
+ return public
129
+
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
+
142
+ def mint(st, username: str, tenant: str, label: str) -> tuple[dict, str]:
143
+ """Create one credential and return ``(metadata, token)``; the token is never persisted."""
144
+ owner, tenant_key = _normalise_owner(username, tenant)
145
+ _assert_bound_runtime(st, tenant_key)
146
+ _active_public_user(owner, tenant_key)
147
+ clean_label = str(label or "").strip()
148
+ if not clean_label or len(clean_label) > 80:
149
+ raise ExternalAccessError("external_label_invalid")
150
+
151
+ secret = secrets.token_urlsafe(32)
152
+ salt = secrets.token_bytes(32)
153
+ created = _now()
154
+ minted: dict = {}
155
+
156
+ def _set(value):
157
+ if value is None:
158
+ book = {}
159
+ elif isinstance(value, dict):
160
+ book = dict(value)
161
+ else:
162
+ raise ExternalAccessError("external_access_unavailable")
163
+ key_id = secrets.token_urlsafe(18)
164
+ while key_id in book:
165
+ key_id = secrets.token_urlsafe(18)
166
+ record = {
167
+ "id": key_id,
168
+ "username": owner,
169
+ "tenant": tenant_key,
170
+ "label": clean_label,
171
+ "salt": salt.hex(),
172
+ "hash": _digest(salt, secret),
173
+ "algo": ALGORITHM,
174
+ "created": created,
175
+ "last_used": None,
176
+ "revoked_at": None,
177
+ }
178
+ book[key_id] = record
179
+ minted["record"] = record
180
+ return book
181
+
182
+ try:
183
+ st.update(BUCKET, _set, flush="sync")
184
+ except ExternalAccessError:
185
+ raise
186
+ except Exception as exc:
187
+ raise ExternalAccessError("external_access_unavailable") from exc
188
+ record = minted.get("record")
189
+ if not isinstance(record, dict):
190
+ raise ExternalAccessError("external_access_unavailable")
191
+ token = f"lpb1.{tenant_key}.{record['id']}.{secret}"
192
+ return _metadata(record), token
193
+
194
+
195
+ def list_for_user(st, username: str, tenant: str) -> list[dict]:
196
+ """List only this user's active credential metadata, newest first."""
197
+ owner, tenant_key = _normalise_owner(username, tenant)
198
+ _assert_bound_runtime(st, tenant_key)
199
+ records = [
200
+ _metadata(record)
201
+ for record in _book(st).values()
202
+ if isinstance(record, dict)
203
+ and record.get("username") == owner
204
+ and record.get("tenant") == tenant_key
205
+ and not record.get("revoked_at")
206
+ ]
207
+ return sorted(records, key=lambda row: str(row.get("created") or ""), reverse=True)
208
+
209
+
210
+ def revoke(st, username: str, tenant: str, key_id: str) -> dict:
211
+ """Tombstone one credential owned by this user; foreign and absent IDs are identical."""
212
+ owner, tenant_key = _normalise_owner(username, tenant)
213
+ _assert_bound_runtime(st, tenant_key)
214
+ target = str(key_id or "").strip()
215
+ revoked: dict = {}
216
+
217
+ def _set(value):
218
+ if not isinstance(value, dict):
219
+ raise ExternalAccessError("external_key_not_found")
220
+ book = dict(value)
221
+ current = book.get(target)
222
+ if (not isinstance(current, dict)
223
+ or current.get("username") != owner
224
+ or current.get("tenant") != tenant_key):
225
+ raise ExternalAccessError("external_key_not_found")
226
+ record = dict(current)
227
+ if not record.get("revoked_at"):
228
+ record["revoked_at"] = _now()
229
+ book[target] = record
230
+ revoked["record"] = record
231
+ return book
232
+
233
+ try:
234
+ st.update(BUCKET, _set, flush="sync")
235
+ except ExternalAccessError:
236
+ raise
237
+ except Exception as exc:
238
+ raise ExternalAccessError("external_access_unavailable") from exc
239
+ record = revoked.get("record")
240
+ if not isinstance(record, dict):
241
+ raise ExternalAccessError("external_access_unavailable")
242
+ return _metadata(record)
243
+
244
+
245
+ def _parse_token(token: str) -> tuple[str, str, str]:
246
+ parts = str(token or "").strip().split(".")
247
+ if (len(parts) != 4 or parts[0] != "lpb1" or not all(parts[1:])
248
+ or len(parts[1]) > 128 or len(parts[2]) > 128 or len(parts[3]) > 256):
249
+ raise ExternalAuthError(AUTH_ERROR)
250
+ return parts[1].lower(), parts[2], parts[3]
251
+
252
+
253
+ def _comparison_material(record) -> tuple[bool, bytes, str]:
254
+ usable = isinstance(record, dict) and record.get("algo") == ALGORITHM
255
+ if usable:
256
+ try:
257
+ salt = bytes.fromhex(str(record.get("salt") or ""))
258
+ expected = str(record.get("hash") or "")
259
+ if len(salt) != 32 or len(expected) != 64:
260
+ raise ValueError("bad credential digest")
261
+ int(expected, 16)
262
+ return True, salt, expected
263
+ except (TypeError, ValueError):
264
+ pass
265
+ return False, _DUMMY_SALT, _DUMMY_HASH
266
+
267
+
268
+ def verify(token: str) -> VerifiedCredential:
269
+ """Verify a bearer token from fresh state and resolve its ordinary public-user principal."""
270
+ try:
271
+ tenant_key, key_id, secret = _parse_token(token)
272
+ try:
273
+ st = runtime.get_runtime(tenant_key)
274
+ except KeyError as exc:
275
+ raise ExternalAuthError(AUTH_ERROR) from exc
276
+
277
+ book = _book(st)
278
+ record = book.get(key_id)
279
+ material_ok, salt, expected = _comparison_material(record)
280
+ matched = hmac.compare_digest(_digest(salt, secret), expected)
281
+ record_ok = (
282
+ material_ok
283
+ and isinstance(record, dict)
284
+ and record.get("id") == key_id
285
+ and record.get("tenant") == tenant_key
286
+ and bool(record.get("username"))
287
+ and not record.get("revoked_at")
288
+ )
289
+ if not record_ok or not matched:
290
+ raise ExternalAuthError(AUTH_ERROR)
291
+
292
+ owner = str(record["username"]).strip().lower()
293
+ try:
294
+ public = _active_public_user(owner, tenant_key)
295
+ except ExternalAccessError as exc:
296
+ raise ExternalAuthError(AUTH_ERROR) from exc
297
+
298
+ if not _stamp_is_due(record.get("last_used"), time.time()):
299
+ return VerifiedCredential(tenant=tenant_key, key_id=key_id, user=public, runtime=st)
300
+
301
+ used_at = _now()
302
+
303
+ def _stamp(value):
304
+ if not isinstance(value, dict):
305
+ raise ExternalAuthError(AUTH_ERROR)
306
+ current = value.get(key_id)
307
+ if (not isinstance(current, dict) or current.get("revoked_at")
308
+ or current.get("username") != owner
309
+ or current.get("tenant") != tenant_key
310
+ or current.get("hash") != record.get("hash")):
311
+ raise ExternalAuthError(AUTH_ERROR)
312
+ book_now = dict(value)
313
+ stamped = dict(current)
314
+ stamped["last_used"] = used_at
315
+ book_now[key_id] = stamped
316
+ return book_now
317
+
318
+ try:
319
+ st.update(BUCKET, _stamp, flush="sync")
320
+ except ExternalAuthError:
321
+ raise
322
+ except Exception as exc:
323
+ raise ExternalAuthError(AUTH_ERROR) from exc
324
+ return VerifiedCredential(tenant=tenant_key, key_id=key_id, user=public, runtime=st)
325
+ except ExternalAuthError:
326
+ raise
327
+ except Exception as exc:
328
+ raise ExternalAuthError(AUTH_ERROR) from exc
platform/core/monid.py CHANGED
@@ -25,7 +25,7 @@ transient fault: retrying it spends nothing and tells the operator nothing, so i
25
 
26
  ⚠ THE ENDPOINT IS RECORDED, NOT REDISCOVERED. `discover("amazon reviews")` chose
27
  `apify /axesso_data/amazon-reviews-scraper` on 2026-09-02 and the losing candidates are written
28
- down in `.claude/wiki/waves/wave49/proto/monid-research.md`. Re-running discover at request time
29
  would let a ranking change silently move which vendor we pay; the constants below are the
30
  decision, and `discover` remains available for the next slice.
31
 
 
25
 
26
  ⚠ THE ENDPOINT IS RECORDED, NOT REDISCOVERED. `discover("amazon reviews")` chose
27
  `apify /axesso_data/amazon-reviews-scraper` on 2026-09-02 and the losing candidates are written
28
+ down in `AutoWiki/waves/wave49/proto/monid-research.md`. Re-running discover at request time
29
  would let a ranking change silently move which vendor we pay; the constants below are the
30
  decision, and `discover` remains available for the next slice.
31
 
platform/core/sheets.py CHANGED
@@ -47,6 +47,12 @@ read-modify-write under its lock. There is no file writer here and there must ne
47
  recomputes them. A cell goes stale by being marked stale, not by being read.
48
  """
49
 
 
 
 
 
 
 
50
  from __future__ import annotations
51
 
52
  import copy
 
47
  recomputes them. A cell goes stale by being marked stale, not by being read.
48
  """
49
 
50
+ #: β›” C5 POINTER ONLY: a bound cell's PERIOD is not validated in this workbook record;
51
+ #: `modules/sheet.py::clean_period` and `period_window` own it. They accept
52
+ #: `{unit, start, locked, ref?}` and the wave-49 `{window: <spec>}` spelling; the latter is resolved
53
+ #: by `harness/windows.py::normalize`, which accepts exactly `WINDOW_KINDS`. C5 named this file as
54
+ #: the acceptance point, but the vocabulary deliberately does not live here.
55
+
56
  from __future__ import annotations
57
 
58
  import copy
platform/core/user_tables.py CHANGED
@@ -4552,15 +4552,27 @@ def enabled_odoo_schema_fields(st=None, model=None):
4552
  return rows
4553
 
4554
 
4555
- def record_odoo_sync_status(*, phase, errors=(), st=None):
4556
  """Lifecycle writer seam for the out-of-fence sync runner."""
4557
  clean_phase = str(phase or 'unknown').strip().lower()
4558
  if clean_phase not in {'syncing', 'ok', 'error', 'unknown'}:
4559
  clean_phase = 'unknown'
 
4560
  row = {'phase': clean_phase,
4561
  'lastRun': _utc_now().isoformat(),
4562
- 'errors': [str(error)[:500] for error in errors][:50]}
4563
  _st(st).update(ODOO_SYNC_STATUS_KEY, lambda _current: row, flush='sync')
 
 
 
 
 
 
 
 
 
 
 
4564
  return row
4565
 
4566
 
 
4552
  return rows
4553
 
4554
 
4555
+ def record_odoo_sync_status(*, phase, errors=(), st=None, connection_id=None):
4556
  """Lifecycle writer seam for the out-of-fence sync runner."""
4557
  clean_phase = str(phase or 'unknown').strip().lower()
4558
  if clean_phase not in {'syncing', 'ok', 'error', 'unknown'}:
4559
  clean_phase = 'unknown'
4560
+ all_errors = tuple(errors or ())
4561
  row = {'phase': clean_phase,
4562
  'lastRun': _utc_now().isoformat(),
4563
+ 'errors': [str(error)[:500] for error in all_errors][:50]}
4564
  _st(st).update(ODOO_SYNC_STATUS_KEY, lambda _current: row, flush='sync')
4565
+ # The measured legacy vocabulary is syncing/ok/error against C6's six states, and its one
4566
+ # tenant document cannot distinguish two Odoo connections. Keep that document byte-for-byte
4567
+ # while forwarding to the provider/connection shape. This remains best-effort because a
4568
+ # status forward must never take down the boot-time resync loop that produced the actual data.
4569
+ try:
4570
+ from core import connector_sync
4571
+ mapped = {'syncing': 'syncing', 'ok': 'ready', 'error': 'error'}[clean_phase]
4572
+ connector_sync.record(_st(st), provider='odoo', connection_id=connection_id,
4573
+ state=mapped, errors=all_errors)
4574
+ except Exception: # noqa: BLE001 - additive status telemetry cannot fail a sync
4575
+ pass
4576
  return row
4577
 
4578
 
platform/harness/amazon_client.py CHANGED
@@ -42,7 +42,7 @@ records, and its second half is what applies: a limit that genuinely cannot be r
42
  REPORTED with cause and a recommended fix. `REPORT_TYPES` below is that fix, written down.
43
  Β· https://developer-docs.amazon.com/sp-api/docs/usage-plans-and-rate-limits
44
 
45
- Ideation record, with every owner ruling: `.claude/wiki/research/ideation/amazon-connector.md`
46
  """
47
  from __future__ import annotations
48
 
 
42
  REPORTED with cause and a recommended fix. `REPORT_TYPES` below is that fix, written down.
43
  Β· https://developer-docs.amazon.com/sp-api/docs/usage-plans-and-rate-limits
44
 
45
+ Ideation record, with every owner ruling: `AutoWiki/research/ideation/amazon-connector.md`
46
  """
47
  from __future__ import annotations
48
 
platform/harness/datastore.py CHANGED
@@ -3,7 +3,7 @@
3
  Incremental Odoo β†’ DuckDB mirror: the local analytical store that saved views/dashboards (OM-3)
4
  and the AI Analyst's tools (OM-4) query at warehouse speed, instead of hammering live XML-RPC
5
  per question.
6
- Plan: .claude/wiki/research/omni-adoption.md Part IV (OM-1) + [[odoo-open-source]] BUILD-NOW #1.
7
 
8
  Design rules:
9
  - The store is a RAW mirror (unscoped). Business scope (wholesale teams, GIFTWARE exclusion,
@@ -195,7 +195,7 @@ ENTITIES = {
195
  # ⭐⭐ WAVE 33 (W33-T48, owner item 13) β€” THE CONTACT/IDENTITY HALF, MEASURED BEFORE IT WAS
196
  # ADDED. The owner: *"I could have sworn we have more relevant Fields under 'Odoo vendors'
197
  # etc."* He was right, and the census
198
- # (`.claude/wiki/waves/wave33/odoo-field-census.md`, live read-only, 2026-08-14) says by how
199
  # much: `res.partner` declares 198 fields, **77 are populated on all 3,621 customers and 76
200
  # on all 658 vendors**, and this mirror carried THIRTEEN. Every one of the six added here
201
  # was measured non-empty on the live population first β€” none is added on the strength of
 
3
  Incremental Odoo β†’ DuckDB mirror: the local analytical store that saved views/dashboards (OM-3)
4
  and the AI Analyst's tools (OM-4) query at warehouse speed, instead of hammering live XML-RPC
5
  per question.
6
+ Plan: AutoWiki/research/omni-adoption.md Part IV (OM-1) + [[odoo-open-source]] BUILD-NOW #1.
7
 
8
  Design rules:
9
  - The store is a RAW mirror (unscoped). Business scope (wholesale teams, GIFTWARE exclusion,
 
195
  # ⭐⭐ WAVE 33 (W33-T48, owner item 13) β€” THE CONTACT/IDENTITY HALF, MEASURED BEFORE IT WAS
196
  # ADDED. The owner: *"I could have sworn we have more relevant Fields under 'Odoo vendors'
197
  # etc."* He was right, and the census
198
+ # (`AutoWiki/waves/wave33/odoo-field-census.md`, live read-only, 2026-08-14) says by how
199
  # much: `res.partner` declares 198 fields, **77 are populated on all 3,621 customers and 76
200
  # on all 658 vendors**, and this mirror carried THIRTEEN. Every one of the six added here
201
  # was measured non-empty on the live population first β€” none is added on the strength of
platform/harness/semantic.py CHANGED
@@ -8,7 +8,7 @@ metric carries its definition, ai_context, and an independent validate contract.
8
  Consumers (the point of the seam): the app's pages, the metric dictionary (OM-0c), the saved-
9
  dashboard viewer (OM-3; the Explore page was retired 2026-07-23), the AI Analyst's tools (OM-4:
10
  list_topics / describe_topic / run_semantic_query), and the MCP server (OM-6). Plan:
11
- .claude/wiki/research/omni-adoption.md (Part IV + the productization addendum).
12
 
13
  Design constraints honored (from /odoo-api):
14
  - read_group dot-path GROUPBY fails β†’ scalar aggregates here use sum_field/distinct_count;
 
8
  Consumers (the point of the seam): the app's pages, the metric dictionary (OM-0c), the saved-
9
  dashboard viewer (OM-3; the Explore page was retired 2026-07-23), the AI Analyst's tools (OM-4:
10
  list_topics / describe_topic / run_semantic_query), and the MCP server (OM-6). Plan:
11
+ AutoWiki/research/omni-adoption.md (Part IV + the productization addendum).
12
 
13
  Design constraints honored (from /odoo-api):
14
  - read_group dot-path GROUPBY fails β†’ scalar aggregates here use sum_field/distinct_count;
platform/harness/transforms.py CHANGED
@@ -8,7 +8,7 @@ a saved view replays query -> transforms at render time (harness/views.run_view)
8
  This is the AIOS Analyst's TABLE-CALCULATION + ANALYTICS library β€” the open-source Tableau-class
9
  capability set (Tableau table calcs + Analytics pane, Power BI DAX quick measures, pandas/polars
10
  window ops, scipy/statsmodels stats) mapped onto ONE governed dispatcher. Grounding brief:
11
- .claude/wiki/research/analytics-tools.md. Design laws (2026-07-18):
12
 
13
  1. ONE tool, many ops. Every capability is a pure function rows->rows (or rows->summary) in the
14
  OPS registry, dispatched through tools.transform_result β€” so the small model's prompt carries
 
8
  This is the AIOS Analyst's TABLE-CALCULATION + ANALYTICS library β€” the open-source Tableau-class
9
  capability set (Tableau table calcs + Analytics pane, Power BI DAX quick measures, pandas/polars
10
  window ops, scipy/statsmodels stats) mapped onto ONE governed dispatcher. Grounding brief:
11
+ AutoWiki/research/analytics-tools.md. Design laws (2026-07-18):
12
 
13
  1. ONE tool, many ops. Every capability is a pure function rows->rows (or rows->summary) in the
14
  OPS registry, dispatched through tools.transform_result β€” so the small model's prompt carries
platform/model/skills/analytics.skill.yml CHANGED
@@ -1,6 +1,6 @@
1
  # In-product SKILL: the ANALYTICS TRANSFORM LIBRARY (v1, 2026-07-18) β€” the Tableau-class
2
  # table-calc + analytics capability set, mapped onto the ONE governed transform_result tool.
3
- # Grounding: .claude/wiki/research/analytics-tools.md. Every op here EXISTS in harness/transforms.py
4
  # (OPS) and is unit-proven in _demo_analytics.py β€” recipes and code version together.
5
  #
6
  # HOW IT WORKS: run_semantic_query -> transform_result([{op, ...}, ...]) -> make_chart|make_table.
 
1
  # In-product SKILL: the ANALYTICS TRANSFORM LIBRARY (v1, 2026-07-18) β€” the Tableau-class
2
  # table-calc + analytics capability set, mapped onto the ONE governed transform_result tool.
3
+ # Grounding: AutoWiki/research/analytics-tools.md. Every op here EXISTS in harness/transforms.py
4
  # (OPS) and is unit-proven in _demo_analytics.py β€” recipes and code version together.
5
  #
6
  # HOW IT WORKS: run_semantic_query -> transform_result([{op, ...}, ...]) -> make_chart|make_table.
platform/model/topics/sales_lines.yml CHANGED
@@ -1,5 +1,5 @@
1
  # Topic: sales_lines β€” the wholesale order-line dataset (OM-0, the first topic of the semantic
2
- # layer; see .claude/wiki/research/omni-adoption.md). A topic = the curated, scoped dataset that
3
  # metrics, saved views and the AI Analyst all resolve against β€” ONE definition of what the
4
  # data MEANS, consumed by every surface.
5
  key: sales_lines
 
1
  # Topic: sales_lines β€” the wholesale order-line dataset (OM-0, the first topic of the semantic
2
+ # layer; see AutoWiki/research/omni-adoption.md). A topic = the curated, scoped dataset that
3
  # metrics, saved views and the AI Analyst all resolve against β€” ONE definition of what the
4
  # data MEANS, consumed by every surface.
5
  key: sales_lines
platform/modules/map.py CHANGED
@@ -7,6 +7,9 @@ Coordinates resolve in this order, per customer:
7
  free US Census batch geocoder (these customers are almost all US/NY-metro florists).
8
  Customers with no usable address (or a geocode that fails) fall to a list under the map.
9
 
 
 
 
10
  Odoo stays STRICTLY read-only β€” geocodes are cached in the platform's own store, never written back
11
  to Odoo. The map's purpose is select-and-export (e.g. to assign agents): box/lasso-select on the map
12
  builds an Excel list. Assigning agents happens in Odoo / via that export, never as an app write.
 
7
  free US Census batch geocoder (these customers are almost all US/NY-metro florists).
8
  Customers with no usable address (or a geocode that fails) fall to a list under the map.
9
 
10
+ This pipeline serves Odoo `res.partner` rows only, and its US Census lookup is US only. The general
11
+ on-demand geocoder for every other database is `aios-web/api/routes_geo.py`.
12
+
13
  Odoo stays STRICTLY read-only β€” geocodes are cached in the platform's own store, never written back
14
  to Odoo. The map's purpose is select-and-export (e.g. to assign agents): box/lasso-select on the map
15
  builds an Excel list. Assigning agents happens in Odoo / via that export, never as an app write.
platform/modules/reprice.py CHANGED
@@ -1,5 +1,5 @@
1
  """Reprice lifecycle β€” the price-side discipline the pricing brief found missing
2
- (.claude/wiki/research/pricing.md): rule hygiene BEFORE the reprice, realization tracking
3
  AFTER it, and the between-waves views (pocket waterfall, peer price corridor).
4
 
5
  Everything reads sale.order.line + product.pricelist.item + product masters, read-only.
 
1
  """Reprice lifecycle β€” the price-side discipline the pricing brief found missing
2
+ (AutoWiki/research/pricing.md): rule hygiene BEFORE the reprice, realization tracking
3
  AFTER it, and the between-waves views (pocket waterfall, peer price corridor).
4
 
5
  Everything reads sale.order.line + product.pricelist.item + product masters, read-only.
web/src/connectors/ConnectorModal.tsx CHANGED
@@ -44,11 +44,13 @@
44
  // later renders in the neutral tone instead of dropping the panel.
45
  // ---------------------------------------------------------------------------
46
 
47
- import { useCallback, useEffect, useRef, useState } from "react";
48
  import { API_V1, CREDENTIALS } from "../apiContract";
49
  import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
 
50
  import { brandForConnector } from "./brandMarks";
51
  import DatabasesTab from "./DatabasesTab";
 
52
  import KeychainTab from "./KeychainTab";
53
  import MonidRunDialog from "./MonidRunDialog";
54
  import { SyncCadenceTab } from "./OdooConfig";
@@ -201,7 +203,13 @@ export interface ConnectorDatabase {
201
  /** May THIS reader rename it? The server's own `may_open` answer, per row, because a control
202
  * the write door would refuse is a button that always fails. */
203
  canRename: boolean;
 
 
204
  enabled: boolean;
 
 
 
 
205
  fields: ConnectorDatabaseField[];
206
  excluded: ConnectorDatabaseExclusion[];
207
  /**
@@ -232,6 +240,11 @@ export interface ConnectorIntrospection {
232
  canToggleTables: boolean;
233
  catalogueComplete: boolean;
234
  capturedAt: string;
 
 
 
 
 
235
  /** What an EMPTY `excluded` list actually means, composed where the diff is computed. */
236
  excludedBasis: string;
237
  }
@@ -369,7 +382,13 @@ function parseDatabases(raw: unknown): ConnectorDatabase[] {
369
  defaultLabel,
370
  override: str(row.override).trim(),
371
  canRename: row.canRename === true,
 
372
  enabled: row.enabled === true,
 
 
 
 
 
373
  fields,
374
  excluded,
375
  sharesFieldsWith: parseStrings(row.sharesFieldsWith),
@@ -395,6 +414,21 @@ function parseIntrospection(raw: unknown): ConnectorIntrospection {
395
  canToggleTables: source.canToggleTables === true,
396
  catalogueComplete: source.catalogueComplete === true,
397
  capturedAt: str(source.capturedAt).trim(),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
398
  excludedBasis: str(source.excludedBasis).trim(),
399
  };
400
  }
@@ -578,7 +612,15 @@ export function ConnectorOverviewPanel({
578
  );
579
  }
580
 
581
- /** Amazon's provider-specific administrator controls, separate from Odoo's model catalogue. */
 
 
 
 
 
 
 
 
582
  export function ProviderEnablementPanel({
583
  detail,
584
  onChanged,
@@ -587,46 +629,20 @@ export function ProviderEnablementPanel({
587
  onChanged: () => void;
588
  }) {
589
  const capability = detail.enablement;
 
590
  const [busyKey, setBusyKey] = useState("");
591
  const [message, setMessage] = useState("");
592
  if (!capability?.canManage || !capability.updatePath) return null;
593
 
594
  const setEnabled = async (database: ConnectorDatabase, enabled: boolean) => {
595
- const path = capability.updatePath.replace(
596
- "{databaseKey}",
597
- encodeURIComponent(database.key)
598
- );
599
- if (path === capability.updatePath) {
600
- setMessage("This provider did not return a usable enablement path.");
601
- return;
602
- }
603
  setBusyKey(database.key);
604
  setMessage("");
605
- let saved = false;
606
- try {
607
- const res = await fetch(`${API_V1}${path}`, {
608
- method: "PATCH",
609
- credentials: CREDENTIALS,
610
- headers: { "Content-Type": "application/json" },
611
- body: JSON.stringify({ enabled }),
612
- });
613
- const body = (await res.json().catch(() => null)) as
614
- | { error?: { message?: string } }
615
- | null;
616
- if (!res.ok) {
617
- setMessage(body?.error?.message || `The server answered ${res.status}.`);
618
- return;
619
- }
620
- saved = true;
621
- onChanged();
622
- } catch {
623
- setMessage("Cannot reach the server.");
624
- } finally {
625
- // A successful write immediately asks the modal to re-read and leaves the old switches
626
- // disabled until that load guard replaces them. An error keeps the current detail and must
627
- // release the control for a retry.
628
- if (!saved) setBusyKey("");
629
- }
630
  };
631
 
632
  return (
@@ -636,30 +652,33 @@ export function ProviderEnablementPanel({
636
  <p>Choose which Amazon databases are enabled. Switching one off keeps its stored rows.</p>
637
  </div>
638
  <ul className="conn-provider-enable-list">
639
- {detail.databases.map((database) => (
 
 
640
  <li key={database.key}>
641
  <span>{database.label}</span>
642
  <span className="conn-provider-enable-control">
643
- <span className="conn-db-state">{database.enabled ? "On" : "Off"}</span>
644
  <button
645
  type="button"
646
  role="switch"
647
- aria-checked={database.enabled}
648
  aria-label={
649
- database.enabled
650
  ? `Switch the database ${database.label} off`
651
  : `Switch the database ${database.label} on`
652
  }
653
- className={"conn-db-switch" + (database.enabled ? " is-on" : "")}
654
- disabled={Boolean(busyKey)}
655
  aria-busy={busyKey === database.key}
656
- onClick={() => void setEnabled(database, !database.enabled)}
657
  >
658
  <span className="conn-db-knob" aria-hidden="true" />
659
  </button>
660
  </span>
661
  </li>
662
- ))}
 
663
  </ul>
664
  <div className="conn-provider-enable-status" role="status" aria-live="polite">
665
  {message}
@@ -697,6 +716,8 @@ type Load =
697
  | { phase: "ready"; detail: ConnectorDetail }
698
  | { phase: "error"; message: string };
699
 
 
 
700
  /**
701
  * THE MODAL. Centered, portalled to <body>, focus-trapped, dismissed by Escape or a click
702
  * outside, and it hands focus back to the control that opened it.
@@ -728,6 +749,11 @@ export default function ConnectorModal({
728
  const panelRef = useRef<HTMLDivElement>(null);
729
  const [tab, setTab] = useState<ConnectorTab>(initialTab);
730
  const [load, setLoad] = useState<Load>({ phase: "loading" });
 
 
 
 
 
731
  /**
732
  * ⭐ W49-T13 β€” THE RE-READ, AND IT IS NOT OPTIONAL POLISH. The Keychain tab WRITES: it stores,
733
  * tests, deletes and disconnects. Keying the fetch on `connectorKey` alone leaves a deleted key
@@ -735,7 +761,11 @@ export default function ConnectorModal({
735
  * so the effect below keys on this counter as well and every write bumps it.
736
  */
737
  const [reads, setReads] = useState(0);
738
- const reread = useCallback(() => setReads((n) => n + 1), []);
 
 
 
 
739
  /**
740
  * ⭐⭐ W49-T19 Β· R31 β€” THE AMAZON REVIEWS PULL, OPENED FROM THE OVERVIEW TAB.
741
  * A second overlay above this one, which is why it takes the PORTAL step and this modal keeps
@@ -750,6 +780,39 @@ export default function ConnectorModal({
750
  const [pullSurface, setPullSurface] = useState<HTMLElement | null>(null);
751
  const canPull = isAmazonConnector(row.key);
752
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
753
  useOverlayLayer({
754
  panelRef,
755
  /**
@@ -764,11 +827,12 @@ export default function ConnectorModal({
764
  * this layer's dismissal closes THAT and stops.
765
  */
766
  onDismiss: () => {
 
767
  if (pulling) {
768
  setPulling(false);
769
  return;
770
  }
771
- onClose();
772
  },
773
  dismissOnOutside: true,
774
  /**
@@ -778,7 +842,7 @@ export default function ConnectorModal({
778
  */
779
  outsideElements: pullSurface ? [pullSurface] : [],
780
  initialFocus: "[data-overlay-autofocus]",
781
- trapFocus: true,
782
  // The layer captures whatever was focused when it mounted and focuses it again on unmount,
783
  // which is the card's own open button. That is the done-when's "focus returns to the card".
784
  restoreFocus: true,
@@ -787,7 +851,7 @@ export default function ConnectorModal({
787
  const connectorKey = row.key;
788
  useEffect(() => {
789
  let dead = false;
790
- setLoad({ phase: "loading" });
791
  void (async () => {
792
  try {
793
  const res = await fetch(
@@ -849,8 +913,26 @@ export default function ConnectorModal({
849
  if (tab === "databases") {
850
  return (
851
  <>
852
- <ProviderEnablementPanel detail={load.detail} onChanged={reread} />
853
- <DatabasesTab row={row} detail={load.detail} onChanged={reread} />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
854
  </>
855
  );
856
  }
@@ -892,7 +974,31 @@ export default function ConnectorModal({
892
  onPullReviews={canPull ? () => setPulling(true) : undefined}
893
  />
894
  );
895
- }, [canPull, load, onOpenDatabases, reread, row, tab]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
896
 
897
  const status = load.phase === "ready" ? load.detail.overview.status : row.state;
898
  const title = load.phase === "ready" ? load.detail.overview.label || row.label : row.label;
@@ -919,12 +1025,35 @@ export default function ConnectorModal({
919
  {status ? (
920
  <span className={"conn-modal-pill" + stateTone(status)}>{status}</span>
921
  ) : null}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
922
  <button
923
  type="button"
924
  className="conn-modal-close"
925
  aria-label={`Close the ${row.label} connector`}
926
  data-overlay-autofocus
927
- onClick={onClose}
 
928
  >
929
  Γ—
930
  </button>
@@ -939,7 +1068,8 @@ export default function ConnectorModal({
939
  className="conn-modal-tab"
940
  aria-selected={tab === entry.key}
941
  aria-controls="conn-tab-panel"
942
- onClick={() => setTab(entry.key)}
 
943
  >
944
  {entry.label}
945
  </button>
@@ -965,6 +1095,15 @@ export default function ConnectorModal({
965
  surfaceRef={setPullSurface}
966
  />
967
  ) : null}
 
 
 
 
 
 
 
 
 
968
  </BodyPortal>
969
  );
970
  }
 
44
  // later renders in the neutral tone instead of dropping the panel.
45
  // ---------------------------------------------------------------------------
46
 
47
+ import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";
48
  import { API_V1, CREDENTIALS } from "../apiContract";
49
  import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
50
+ import { ConfirmDialog } from "../ui/ConfirmDialog";
51
  import { brandForConnector } from "./brandMarks";
52
  import DatabasesTab from "./DatabasesTab";
53
+ import type { DatabaseReveal, DatabasesTabHandle } from "./DatabasesTab";
54
  import KeychainTab from "./KeychainTab";
55
  import MonidRunDialog from "./MonidRunDialog";
56
  import { SyncCadenceTab } from "./OdooConfig";
 
203
  /** May THIS reader rename it? The server's own `may_open` answer, per row, because a control
204
  * the write door would refuse is a button that always fails. */
205
  canRename: boolean;
206
+ /** Does the governed database exist yet? This is separate from the reader's permission. */
207
+ exists: boolean;
208
  enabled: boolean;
209
+ /** Exact rows in the Odoo source model, or null until that model was counted successfully. */
210
+ sourceRows: number | null;
211
+ /** Tri-state on purpose: a model nobody counted is unknown, never empty. */
212
+ populated: boolean | null;
213
  fields: ConnectorDatabaseField[];
214
  excluded: ConnectorDatabaseExclusion[];
215
  /**
 
240
  canToggleTables: boolean;
241
  catalogueComplete: boolean;
242
  capturedAt: string;
243
+ censusAt: string;
244
+ censusComplete: boolean;
245
+ censusDurationMs: number;
246
+ censusModelsCounted: number;
247
+ censusModelsWithRows: number;
248
  /** What an EMPTY `excluded` list actually means, composed where the diff is computed. */
249
  excludedBasis: string;
250
  }
 
382
  defaultLabel,
383
  override: str(row.override).trim(),
384
  canRename: row.canRename === true,
385
+ exists: row.exists === true,
386
  enabled: row.enabled === true,
387
+ sourceRows:
388
+ typeof row.sourceRows === "number" && Number.isFinite(row.sourceRows) && row.sourceRows >= 0
389
+ ? Math.trunc(row.sourceRows)
390
+ : null,
391
+ populated: row.populated === true ? true : row.populated === false ? false : null,
392
  fields,
393
  excluded,
394
  sharesFieldsWith: parseStrings(row.sharesFieldsWith),
 
414
  canToggleTables: source.canToggleTables === true,
415
  catalogueComplete: source.catalogueComplete === true,
416
  capturedAt: str(source.capturedAt).trim(),
417
+ censusAt: str(source.censusAt).trim(),
418
+ censusComplete: source.censusComplete === true,
419
+ censusDurationMs:
420
+ typeof source.censusDurationMs === "number" && Number.isFinite(source.censusDurationMs)
421
+ ? Math.max(0, Math.trunc(source.censusDurationMs))
422
+ : 0,
423
+ censusModelsCounted:
424
+ typeof source.censusModelsCounted === "number" && Number.isFinite(source.censusModelsCounted)
425
+ ? Math.max(0, Math.trunc(source.censusModelsCounted))
426
+ : 0,
427
+ censusModelsWithRows:
428
+ typeof source.censusModelsWithRows === "number" &&
429
+ Number.isFinite(source.censusModelsWithRows)
430
+ ? Math.max(0, Math.trunc(source.censusModelsWithRows))
431
+ : 0,
432
  excludedBasis: str(source.excludedBasis).trim(),
433
  };
434
  }
 
612
  );
613
  }
614
 
615
+ interface ProviderPendingBridge {
616
+ enabled: (database: ConnectorDatabase) => boolean;
617
+ stage: (database: ConnectorDatabase, next: boolean) => Promise<void>;
618
+ busy: boolean;
619
+ }
620
+
621
+ const ProviderPendingContext = createContext<ProviderPendingBridge | null>(null);
622
+
623
+ /** Amazon's provider-specific administrator controls, committed by the modal's shared Save. */
624
  export function ProviderEnablementPanel({
625
  detail,
626
  onChanged,
 
629
  onChanged: () => void;
630
  }) {
631
  const capability = detail.enablement;
632
+ const pending = useContext(ProviderPendingContext);
633
  const [busyKey, setBusyKey] = useState("");
634
  const [message, setMessage] = useState("");
635
  if (!capability?.canManage || !capability.updatePath) return null;
636
 
637
  const setEnabled = async (database: ConnectorDatabase, enabled: boolean) => {
638
+ if (!pending || pending.busy) return;
 
 
 
 
 
 
 
639
  setBusyKey(database.key);
640
  setMessage("");
641
+ await pending.stage(database, enabled);
642
+ setBusyKey("");
643
+ // Kept in the public prop contract for the provider panel's existing callers. The shared
644
+ // Save owns the one detail re-read now, so staging deliberately does not call it.
645
+ void onChanged;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
646
  };
647
 
648
  return (
 
652
  <p>Choose which Amazon databases are enabled. Switching one off keeps its stored rows.</p>
653
  </div>
654
  <ul className="conn-provider-enable-list">
655
+ {detail.databases.map((database) => {
656
+ const enabled = pending?.enabled(database) ?? database.enabled;
657
+ return (
658
  <li key={database.key}>
659
  <span>{database.label}</span>
660
  <span className="conn-provider-enable-control">
661
+ <span className="conn-db-state">{enabled ? "On" : "Off"}</span>
662
  <button
663
  type="button"
664
  role="switch"
665
+ aria-checked={enabled}
666
  aria-label={
667
+ enabled
668
  ? `Switch the database ${database.label} off`
669
  : `Switch the database ${database.label} on`
670
  }
671
+ className={"conn-db-switch" + (enabled ? " is-on" : "")}
672
+ disabled={Boolean(busyKey) || !pending || pending.busy}
673
  aria-busy={busyKey === database.key}
674
+ onClick={() => void setEnabled(database, !enabled)}
675
  >
676
  <span className="conn-db-knob" aria-hidden="true" />
677
  </button>
678
  </span>
679
  </li>
680
+ );
681
+ })}
682
  </ul>
683
  <div className="conn-provider-enable-status" role="status" aria-live="polite">
684
  {message}
 
716
  | { phase: "ready"; detail: ConnectorDetail }
717
  | { phase: "error"; message: string };
718
 
719
+ type PendingLeave = { kind: "close" } | { kind: "tab"; tab: ConnectorTab } | null;
720
+
721
  /**
722
  * THE MODAL. Centered, portalled to <body>, focus-trapped, dismissed by Escape or a click
723
  * outside, and it hands focus back to the control that opened it.
 
749
  const panelRef = useRef<HTMLDivElement>(null);
750
  const [tab, setTab] = useState<ConnectorTab>(initialTab);
751
  const [load, setLoad] = useState<Load>({ phase: "loading" });
752
+ const databasesRef = useRef<DatabasesTabHandle>(null);
753
+ const [databasePendingCount, setDatabasePendingCount] = useState(0);
754
+ const [databaseTabBusy, setDatabaseTabBusy] = useState(false);
755
+ const [databaseSaving, setDatabaseSaving] = useState(false);
756
+ const [pendingLeave, setPendingLeave] = useState<PendingLeave>(null);
757
  /**
758
  * ⭐ W49-T13 β€” THE RE-READ, AND IT IS NOT OPTIONAL POLISH. The Keychain tab WRITES: it stores,
759
  * tests, deletes and disconnects. Keying the fetch on `connectorKey` alone leaves a deleted key
 
761
  * so the effect below keys on this counter as well and every write bumps it.
762
  */
763
  const [reads, setReads] = useState(0);
764
+ const [databaseReveal, setDatabaseReveal] = useState<DatabaseReveal | null>(null);
765
+ const reread = useCallback((reveal?: DatabaseReveal) => {
766
+ if (reveal) setDatabaseReveal(reveal);
767
+ setReads((n) => n + 1);
768
+ }, []);
769
  /**
770
  * ⭐⭐ W49-T19 Β· R31 β€” THE AMAZON REVIEWS PULL, OPENED FROM THE OVERVIEW TAB.
771
  * A second overlay above this one, which is why it takes the PORTAL step and this modal keeps
 
780
  const [pullSurface, setPullSurface] = useState<HTMLElement | null>(null);
781
  const canPull = isAmazonConnector(row.key);
782
 
783
+ const unsavedMessage = databasePendingCount === 1
784
+ ? "You have 1 unsaved change to this connection."
785
+ : `You have ${databasePendingCount} unsaved changes to this connection.`;
786
+
787
+ const requestClose = useCallback(() => {
788
+ if (databaseSaving || databaseTabBusy) return;
789
+ if (databasePendingCount) {
790
+ setPendingLeave({ kind: "close" });
791
+ return;
792
+ }
793
+ onClose();
794
+ }, [databasePendingCount, databaseSaving, databaseTabBusy, onClose]);
795
+
796
+ const requestTab = useCallback((next: ConnectorTab) => {
797
+ if (databaseSaving || databaseTabBusy) return;
798
+ if (next === tab) return;
799
+ if (databasePendingCount) {
800
+ setPendingLeave({ kind: "tab", tab: next });
801
+ return;
802
+ }
803
+ setTab(next);
804
+ }, [databasePendingCount, databaseSaving, databaseTabBusy, tab]);
805
+
806
+ useEffect(() => {
807
+ if (!databasePendingCount) return;
808
+ const warn = (event: BeforeUnloadEvent) => {
809
+ event.preventDefault();
810
+ event.returnValue = unsavedMessage;
811
+ };
812
+ window.addEventListener("beforeunload", warn);
813
+ return () => window.removeEventListener("beforeunload", warn);
814
+ }, [databasePendingCount, unsavedMessage]);
815
+
816
  useOverlayLayer({
817
  panelRef,
818
  /**
 
827
  * this layer's dismissal closes THAT and stops.
828
  */
829
  onDismiss: () => {
830
+ if (pendingLeave) return;
831
  if (pulling) {
832
  setPulling(false);
833
  return;
834
  }
835
+ requestClose();
836
  },
837
  dismissOnOutside: true,
838
  /**
 
842
  */
843
  outsideElements: pullSurface ? [pullSurface] : [],
844
  initialFocus: "[data-overlay-autofocus]",
845
+ trapFocus: pendingLeave === null,
846
  // The layer captures whatever was focused when it mounted and focuses it again on unmount,
847
  // which is the card's own open button. That is the done-when's "focus returns to the card".
848
  restoreFocus: true,
 
851
  const connectorKey = row.key;
852
  useEffect(() => {
853
  let dead = false;
854
+ setLoad((current) => reads > 0 && current.phase === "ready" ? current : { phase: "loading" });
855
  void (async () => {
856
  try {
857
  const res = await fetch(
 
913
  if (tab === "databases") {
914
  return (
915
  <>
916
+ <ProviderPendingContext.Provider
917
+ value={{
918
+ enabled: (database) =>
919
+ databasesRef.current?.tableEnabled(database) ?? database.enabled,
920
+ stage: (database, next) =>
921
+ databasesRef.current?.stageTable(database, next) ?? Promise.resolve(),
922
+ busy: databaseSaving || databaseTabBusy,
923
+ }}
924
+ >
925
+ <ProviderEnablementPanel detail={load.detail} onChanged={reread} />
926
+ </ProviderPendingContext.Provider>
927
+ <DatabasesTab
928
+ ref={databasesRef}
929
+ row={row}
930
+ detail={load.detail}
931
+ onChanged={reread}
932
+ onPendingChange={setDatabasePendingCount}
933
+ onBusyChange={setDatabaseTabBusy}
934
+ reveal={databaseReveal}
935
+ />
936
  </>
937
  );
938
  }
 
974
  onPullReviews={canPull ? () => setPulling(true) : undefined}
975
  />
976
  );
977
+ }, [canPull, databaseReveal, load, onOpenDatabases, reread, row, tab]);
978
+
979
+ const saveDatabaseChanges = useCallback(async () => {
980
+ if (!databasePendingCount || !databasesRef.current) return;
981
+ setDatabaseSaving(true);
982
+ try {
983
+ await databasesRef.current.savePending();
984
+ } finally {
985
+ setDatabaseSaving(false);
986
+ }
987
+ }, [databasePendingCount]);
988
+
989
+ const discardDatabaseChanges = useCallback(() => {
990
+ databasesRef.current?.discardPending();
991
+ setDatabasePendingCount(0);
992
+ }, []);
993
+
994
+ const confirmLeave = useCallback(() => {
995
+ if (!pendingLeave) return;
996
+ const destination = pendingLeave;
997
+ discardDatabaseChanges();
998
+ setPendingLeave(null);
999
+ if (destination.kind === "close") onClose();
1000
+ else setTab(destination.tab);
1001
+ }, [discardDatabaseChanges, onClose, pendingLeave]);
1002
 
1003
  const status = load.phase === "ready" ? load.detail.overview.status : row.state;
1004
  const title = load.phase === "ready" ? load.detail.overview.label || row.label : row.label;
 
1025
  {status ? (
1026
  <span className={"conn-modal-pill" + stateTone(status)}>{status}</span>
1027
  ) : null}
1028
+ {tab === "databases" ? (
1029
+ <div className="conn-modal-save-actions">
1030
+ <button
1031
+ type="button"
1032
+ className="conn-db-link"
1033
+ disabled={!databasePendingCount || databaseSaving || databaseTabBusy}
1034
+ onClick={discardDatabaseChanges}
1035
+ >
1036
+ Discard
1037
+ </button>
1038
+ <button
1039
+ type="button"
1040
+ className="conn-modal-go"
1041
+ disabled={!databasePendingCount || databaseSaving || databaseTabBusy}
1042
+ onClick={() => void saveDatabaseChanges()}
1043
+ >
1044
+ {databasePendingCount
1045
+ ? `Save ${databasePendingCount} ${databasePendingCount === 1 ? "change" : "changes"}`
1046
+ : "Save"}
1047
+ </button>
1048
+ </div>
1049
+ ) : null}
1050
  <button
1051
  type="button"
1052
  className="conn-modal-close"
1053
  aria-label={`Close the ${row.label} connector`}
1054
  data-overlay-autofocus
1055
+ disabled={databaseSaving || databaseTabBusy}
1056
+ onClick={requestClose}
1057
  >
1058
  Γ—
1059
  </button>
 
1068
  className="conn-modal-tab"
1069
  aria-selected={tab === entry.key}
1070
  aria-controls="conn-tab-panel"
1071
+ disabled={databaseSaving || databaseTabBusy}
1072
+ onClick={() => requestTab(entry.key)}
1073
  >
1074
  {entry.label}
1075
  </button>
 
1095
  surfaceRef={setPullSurface}
1096
  />
1097
  ) : null}
1098
+ <ConfirmDialog
1099
+ open={pendingLeave !== null}
1100
+ title="Discard unsaved changes"
1101
+ body={<p>{unsavedMessage}</p>}
1102
+ confirmLabel="Discard changes"
1103
+ tone="destructive"
1104
+ onConfirm={confirmLeave}
1105
+ onCancel={() => setPendingLeave(null)}
1106
+ />
1107
  </BodyPortal>
1108
  );
1109
  }
web/src/connectors/DatabasesTab.tsx CHANGED
@@ -56,8 +56,8 @@
56
  // `ConnectorOverviewPanel` and `KeychainTab` are exported panels.
57
  // ---------------------------------------------------------------------------
58
 
59
- import { useCallback, useMemo, useState } from "react";
60
- import { API_V1, CREDENTIALS } from "../apiContract";
61
  import type { ConnectorDatabase, ConnectorDetail } from "./ConnectorModal";
62
  import type { ConnectorRow } from "./ConnectorsPage";
63
 
@@ -109,6 +109,199 @@ async function write(path: string, method: "PUT" | "PATCH", body: unknown): Prom
109
  }
110
  }
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  /** The on/off control, one shape for both rails (DESIGN.md section 4: one control shape). */
113
  function Switch({
114
  on,
@@ -164,7 +357,7 @@ function DatabasePanel({
164
  canToggleFields,
165
  catalogueComplete,
166
  excludedBasis,
167
- busyField,
168
  onField,
169
  }: {
170
  database: ConnectorDatabase;
@@ -174,7 +367,7 @@ function DatabasePanel({
174
  canToggleFields: boolean;
175
  catalogueComplete: boolean;
176
  excludedBasis: string;
177
- busyField: string;
178
  onField: (fieldKey: string, next: boolean) => void;
179
  }) {
180
  /**
@@ -228,7 +421,7 @@ function DatabasePanel({
228
  {canToggleFields ? (
229
  <Switch
230
  on={field.enabled}
231
- busy={busyField === field.key}
232
  label={
233
  field.enabled
234
  ? `Switch the field ${field.label} off`
@@ -280,7 +473,8 @@ function DatabasePanel({
280
  * remounted, and so this whole tab still paints under `renderToStaticMarkup`.
281
  *
282
  * β›” NO CONTROL AT ALL FOR A READER WHO MAY NOT RENAME (`canRename` is the server's own `may_open`
283
- * answer). This directory's rule is that a door the write side would refuse is not drawn.
 
284
  */
285
  function NameCell({
286
  database,
@@ -322,6 +516,8 @@ function NameCell({
322
  >
323
  {database.override ? "Change" : "Rename"}
324
  </button>
 
 
325
  ) : null}
326
  </div>
327
  );
@@ -348,7 +544,7 @@ function NameCell({
348
  disabled={busy || !draft.trim()}
349
  onClick={() => onSave(draft)}
350
  >
351
- Save
352
  </button>
353
  {database.override ? (
354
  <button
@@ -370,55 +566,91 @@ function NameCell({
370
 
371
  /**
372
  * ⭐ THE TAB, PURE AND EXPORTED. Everything it lists is `detail`; the only network it does is a
373
- * write the reader asked for, plus R23's pre-flight on the way to one.
374
  */
375
- export default function DatabasesTab({
 
 
 
 
 
 
 
 
 
 
 
376
  row,
377
  detail,
378
  onChanged,
379
- }: {
380
- row: ConnectorRow;
381
- detail: ConnectorDetail;
382
- /** Re-read `/detail` after a write, so a flag that landed is a flag on screen. */
383
- onChanged: () => void;
384
- }) {
385
  const { databases, introspection } = detail;
 
386
  /**
387
  * ⚠ W53-T27 β€” EVERY ROW STARTS CLOSED, and that changed here. Until this ticket the first
388
  * database was opened for you, because the field list WAS the content of this tab. The content
389
  * is now the eight rows and their three names, and one open row buries the other seven under a
390
  * 190-field table: the reader cannot see the list they came to read.
391
  */
392
- const [open, setOpen] = useState<Record<string, boolean>>({});
 
 
393
  const [busy, setBusy] = useState("");
394
  const [refusals, setRefusals] = useState<Record<string, string>>({});
 
 
 
395
  const [error, setError] = useState("");
 
 
396
  /** The one row being renamed, and the text in its box. Empty means nobody is renaming. */
397
  const [renaming, setRenaming] = useState("");
398
  const [draft, setDraft] = useState("");
 
 
 
 
 
 
 
 
 
 
 
399
 
400
  const labels = useMemo(() => {
401
  const out: Record<string, string> = {};
402
- for (const database of databases) out[database.key] = database.label;
 
 
 
 
 
403
  return out;
404
- }, [databases]);
405
  const orderedDatabases = useMemo(
406
  () =>
407
  databases
408
  .map((database, index) => ({ database, index }))
409
  .sort(
410
  (a, b) =>
411
- Number(b.database.enabled) - Number(a.database.enabled) || a.index - b.index
 
 
 
412
  )
413
  .map(({ database }) => database),
414
- [databases]
415
  );
416
 
417
  /**
418
- * β›”β›” R23's ENFORCEMENT, AND TODAY IT LIVES HERE. The write door is
419
- * `PUT /admin/connectors/odoo/config`, which sets the flag for any key it recognises and knows
420
- * nothing about dependents, so the ASK has to happen before the write. That makes this the only
421
- * enforcer of the ruling, which is stated in the handoff rather than left to be discovered.
422
  *
423
  * β›” AND A FAILED CHECK IS NOT A PASSED ONE. Any non-answer leaves the table on and prints the
424
  * cause; proceeding would turn "REFUSED" into "usually refused".
@@ -428,6 +660,7 @@ export default function DatabasesTab({
428
  setBusy(database.key);
429
  setError("");
430
  setRefusals((current) => ({ ...current, [database.key]: "" }));
 
431
  if (!next) {
432
  const answer = await readDependents(database.key);
433
  if (!answer.ok) {
@@ -446,61 +679,179 @@ export default function DatabasesTab({
446
  return;
447
  }
448
  }
449
- const message = await write("/admin/connectors/odoo/config", "PUT", {
450
- grids: { [database.key]: next },
451
- });
452
  setBusy("");
453
- if (message) setError(message);
454
- else onChanged();
 
 
 
 
455
  },
456
- [onChanged]
457
  );
458
 
459
  const flipField = useCallback(
460
  async (fieldKey: string, next: boolean) => {
461
- setBusy(fieldKey);
462
  setError("");
463
- const message = await write(
464
- `/connectors/odoo/schema/${encodeURIComponent(fieldKey)}`,
465
- "PATCH",
466
- { enabled: next }
467
- );
468
- setBusy("");
469
- if (message) setError(message);
470
- else onChanged();
 
 
471
  },
472
- [onChanged]
473
  );
474
 
475
  /**
476
  * ⭐ W53-T27 / R9 β€” THE OVERRIDE, WRITTEN THROUGH THE DOOR THAT WRITES THE NAVIGATION RAIL'S
477
- * OWN BUCKET. An empty `name` CLEARS it, which is the half `POST /nav/meta` refuses and the
478
- * reason this door exists at all.
479
- *
480
- * β›” THE MESSAGE ON A FAILURE IS THE SERVER'S, verbatim, exactly as a dependents refusal is.
481
- * This screen does not know why a rename was refused and must not compose a guess.
482
  */
483
  const renameDatabase = useCallback(
484
  async (database: ConnectorDatabase, next: string) => {
485
- setBusy(database.key);
486
  setError("");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
487
  const message = await write(
488
  `/connectors/${encodeURIComponent(row.key)}/databases/` +
489
- `${encodeURIComponent(database.key)}/name`,
490
  "PATCH",
491
- { name: next }
492
  );
493
- setBusy("");
494
  if (message) {
495
- setError(message);
496
- return;
497
  }
498
- setRenaming("");
499
- setDraft("");
500
- onChanged();
501
- },
502
- [onChanged, row.key]
503
- );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504
 
505
  if (!introspection.introspectable) {
506
  return <DatabasesUnavailable row={row} reason={introspection.reason} />;
@@ -519,6 +870,38 @@ export default function DatabasesTab({
519
 
520
  return (
521
  <div className="conn-db">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
522
  {error ? (
523
  <p className="conn-db-error" role="alert">
524
  {error}
@@ -536,6 +919,12 @@ export default function DatabasesTab({
536
  name is ours. Your name replaces it everywhere in this workspace, including the
537
  navigation rail, and clearing it brings the default back.
538
  </p>
 
 
 
 
 
 
539
  <table className="conn-db-fields">
540
  <thead>
541
  <tr>
@@ -543,15 +932,35 @@ export default function DatabasesTab({
543
  <th scope="col">Default name</th>
544
  <th scope="col">Your name</th>
545
  <th scope="col">Fields</th>
 
546
  <th scope="col">Enabled</th>
547
  </tr>
548
  </thead>
549
  {orderedDatabases.map((database) => {
 
 
 
 
 
 
 
 
 
 
 
 
550
  const isOpen = open[database.key] === true;
551
  const refusal = refusals[database.key] || "";
 
 
 
 
552
  return (
553
  <tbody key={database.key}>
554
- <tr>
 
 
 
555
  {/* β›” AN ABSENT NATIVE NAME IS SAID, NOT FILLED IN. Amazon names a table by the
556
  report it is filled from, and a table whose report type we cannot read has no
557
  vendor identifier to show. Printing the key there would put our own word under
@@ -562,14 +971,14 @@ export default function DatabasesTab({
562
  <td>{database.defaultLabel}</td>
563
  <td>
564
  <NameCell
565
- database={database}
566
  editing={renaming === database.key}
567
  draft={draft}
568
- busy={busy === database.key}
569
  onDraft={setDraft}
570
  onEdit={() => {
571
  setRenaming(database.key);
572
- setDraft(database.override || database.defaultLabel);
573
  setError("");
574
  }}
575
  onCancel={() => {
@@ -584,7 +993,7 @@ export default function DatabasesTab({
584
  type="button"
585
  className="conn-db-more"
586
  aria-expanded={isOpen}
587
- aria-label={`Show the fields in ${database.label}`}
588
  onClick={() =>
589
  setOpen((current) => ({ ...current, [database.key]: !isOpen }))
590
  }
@@ -594,18 +1003,29 @@ export default function DatabasesTab({
594
  </span>
595
  </button>
596
  </td>
 
 
 
 
 
 
 
 
 
 
 
597
  {/* ⭐ R22 β€” ANY table can be switched off, not only the ones we mark optional.
598
  Every row gets the same control, and nothing here decides that one of them is
599
  too important to turn off: R23's ask is what protects a table in use. */}
600
  <td className="conn-db-cell-switch">
601
  {introspection.canToggleTables ? (
602
  <Switch
603
- on={database.enabled}
604
- busy={busy === database.key}
605
  label={
606
- database.enabled
607
- ? `Switch off the database ${database.label}`
608
- : `Switch on the database ${database.label}`
609
  }
610
  onFlip={(next) => void flipTable(database, next)}
611
  />
@@ -614,12 +1034,31 @@ export default function DatabasesTab({
614
  )}
615
  </td>
616
  </tr>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
617
  {refusal ? (
618
  // ⚠ A REFUSAL IS NOT AN ERROR THE READER CAUSED (DESIGN.md section 4). It states
619
  // the cause and the subject, in the server's own sentence, and offers nothing to
620
  // dismiss because the table simply stayed on.
621
  <tr>
622
- <td colSpan={5}>
623
  <p className="conn-db-refusal" role="alert">
624
  {refusal}
625
  </p>
@@ -628,17 +1067,15 @@ export default function DatabasesTab({
628
  ) : null}
629
  {isOpen ? (
630
  <tr>
631
- <td colSpan={5}>
632
  <DatabasePanel
633
- database={database}
634
- siblingLabels={database.sharesFieldsWith
635
- .map((key) => labels[key] || "")
636
- .filter((label) => label.length > 0)}
637
  fieldsVisible={introspection.fieldsVisible}
638
  canToggleFields={introspection.canToggleFields}
639
  catalogueComplete={introspection.catalogueComplete}
640
  excludedBasis={introspection.excludedBasis}
641
- busyField={busy}
642
  onField={(fieldKey, next) => void flipField(fieldKey, next)}
643
  />
644
  </td>
@@ -650,4 +1087,6 @@ export default function DatabasesTab({
650
  </table>
651
  </div>
652
  );
653
- }
 
 
 
56
  // `ConnectorOverviewPanel` and `KeychainTab` are exported panels.
57
  // ---------------------------------------------------------------------------
58
 
59
+ import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useState } from "react";
60
+ import { API_V1, CREDENTIALS, WORKSPACE_STALE_EVENT, signal } from "../apiContract";
61
  import type { ConnectorDatabase, ConnectorDetail } from "./ConnectorModal";
62
  import type { ConnectorRow } from "./ConnectorsPage";
63
 
 
109
  }
110
  }
111
 
112
+ /**
113
+ * Enabling sets the flag and THEN materialises, so a refusal can still have changed the server.
114
+ *
115
+ * β›” THE ANSWER IS A MESSAGE, NOT A FLAG READ OFF AN ERROR BODY. `deps.err` is the one non-2xx
116
+ * shape and it carries `error` alone. `reread` is therefore unconditional below: every outcome of
117
+ * this door can change what `/detail` answers, so the screen re-reads rather than trusting a
118
+ * sibling key that the error contract does not have.
119
+ */
120
+ type EnableDatabaseAnswer =
121
+ | {
122
+ ok: true;
123
+ workspaceChanged: boolean;
124
+ populatedFieldsEnabled: number;
125
+ fieldCensusComplete: boolean;
126
+ autoEnableAlsoAffects: Array<{ key: string; label: string }>;
127
+ }
128
+ | { ok: false; message: string };
129
+
130
+ async function enableDatabase(tableKey: string): Promise<EnableDatabaseAnswer> {
131
+ try {
132
+ const res = await fetch(
133
+ `${API_V1}/connectors/odoo/databases/${encodeURIComponent(tableKey)}/enable`,
134
+ { method: "POST", credentials: CREDENTIALS }
135
+ );
136
+ const payload = (await res.json().catch(() => null)) as
137
+ | {
138
+ workspaceChanged?: boolean;
139
+ populatedFieldsEnabled?: number;
140
+ fieldCensusComplete?: boolean;
141
+ autoEnableAlsoAffects?: unknown;
142
+ error?: { message?: string };
143
+ }
144
+ | null;
145
+ if (res.ok) {
146
+ const shared = Array.isArray(payload?.autoEnableAlsoAffects)
147
+ ? payload.autoEnableAlsoAffects.flatMap((value) => {
148
+ if (!value || typeof value !== "object") return [];
149
+ const row = value as Record<string, unknown>;
150
+ const key = typeof row.key === "string" ? row.key : "";
151
+ const label = typeof row.label === "string" ? row.label : "";
152
+ return key && label ? [{ key, label }] : [];
153
+ })
154
+ : [];
155
+ const count = payload?.populatedFieldsEnabled;
156
+ return {
157
+ ok: true,
158
+ workspaceChanged: payload?.workspaceChanged === true,
159
+ populatedFieldsEnabled:
160
+ typeof count === "number" && Number.isFinite(count) ? Math.max(0, Math.trunc(count)) : 0,
161
+ fieldCensusComplete: payload?.fieldCensusComplete === true,
162
+ autoEnableAlsoAffects: shared,
163
+ };
164
+ }
165
+ return {
166
+ ok: false,
167
+ message: payload?.error?.message || `The server answered ${res.status}.`,
168
+ };
169
+ } catch {
170
+ return { ok: false, message: "Cannot reach the server." };
171
+ }
172
+ }
173
+
174
+ function sentenceList(values: string[]): string {
175
+ if (values.length < 2) return values[0] || "";
176
+ if (values.length === 2) return `${values[0]} and ${values[1]}`;
177
+ return `${values.slice(0, -1).join(", ")}, and ${values[values.length - 1]}`;
178
+ }
179
+
180
+ function autoEnableResult(answer: Extract<EnableDatabaseAnswer, { ok: true }>): string {
181
+ const siblings = sentenceList(answer.autoEnableAlsoAffects.map((row) => row.label));
182
+ const unknown = answer.fieldCensusComplete
183
+ ? ""
184
+ : ", while fields that could not be counted were left unchanged";
185
+ if (!answer.populatedFieldsEnabled) {
186
+ return siblings
187
+ ? `No populated fields were found, so no field settings were changed here or in ${siblings}${unknown}.`
188
+ : `No populated fields were found, so no field settings were changed${unknown}.`;
189
+ }
190
+ const fields = answer.populatedFieldsEnabled === 1
191
+ ? "One populated field was"
192
+ : `${answer.populatedFieldsEnabled.toLocaleString()} populated fields were`;
193
+ return siblings
194
+ ? `${fields} switched on here and in ${siblings} because the databases read the same Odoo source table${unknown}.`
195
+ : `${fields} switched on${unknown}.`;
196
+ }
197
+
198
+ export interface DatabaseReveal {
199
+ key: string;
200
+ status: string;
201
+ }
202
+
203
+ export interface DatabasesTabHandle {
204
+ savePending: () => Promise<void>;
205
+ discardPending: () => void;
206
+ stageTable: (database: ConnectorDatabase, next: boolean) => Promise<void>;
207
+ tableEnabled: (database: ConnectorDatabase) => boolean;
208
+ }
209
+
210
+ interface PendingDatabaseChanges {
211
+ tables: Record<string, boolean>;
212
+ fields: Record<string, boolean>;
213
+ names: Record<string, string>;
214
+ }
215
+
216
+ const EMPTY_PENDING: PendingDatabaseChanges = { tables: {}, fields: {}, names: {} };
217
+
218
+ function pendingChangeCount(pending: PendingDatabaseChanges): number {
219
+ return Object.keys(pending.tables).length +
220
+ Object.keys(pending.fields).length +
221
+ Object.keys(pending.names).length;
222
+ }
223
+
224
+ type PopulationCountAnswer =
225
+ | {
226
+ ok: true;
227
+ complete: boolean;
228
+ capturedAt: string;
229
+ durationMs: number;
230
+ modelsCounted: number;
231
+ modelsWithRows: number;
232
+ errors: string[];
233
+ }
234
+ | { ok: false; message: string };
235
+
236
+ /** The explicit long-running door. Connector detail never starts this work. */
237
+ async function countSourceRows(): Promise<PopulationCountAnswer> {
238
+ try {
239
+ const res = await fetch(`${API_V1}/connectors/odoo/census`, {
240
+ method: "POST",
241
+ credentials: CREDENTIALS,
242
+ });
243
+ const payload = (await res.json().catch(() => null)) as Record<string, unknown> | null;
244
+ if (!res.ok) {
245
+ const error = payload?.error as { message?: unknown } | undefined;
246
+ return {
247
+ ok: false,
248
+ message: typeof error?.message === "string"
249
+ ? error.message
250
+ : `The server answered ${res.status}.`,
251
+ };
252
+ }
253
+ const number = (value: unknown) =>
254
+ typeof value === "number" && Number.isFinite(value)
255
+ ? Math.max(0, Math.trunc(value))
256
+ : 0;
257
+ const rawErrors = payload?.errors;
258
+ return {
259
+ ok: true,
260
+ complete: payload?.complete === true,
261
+ capturedAt: typeof payload?.capturedAt === "string" ? payload.capturedAt : "",
262
+ durationMs: number(payload?.durationMs),
263
+ modelsCounted: number(payload?.modelsCounted),
264
+ modelsWithRows: number(payload?.modelsWithRows),
265
+ errors: Array.isArray(rawErrors)
266
+ ? rawErrors.filter((value): value is string => typeof value === "string")
267
+ : [],
268
+ };
269
+ } catch {
270
+ return { ok: false, message: "Cannot reach the server." };
271
+ }
272
+ }
273
+
274
+ function populationSummary(modelsCounted: number, modelsWithRows: number, durationMs: number) {
275
+ const seconds = Math.max(1, Math.round(durationMs / 1000));
276
+ return `Counted ${modelsCounted.toLocaleString()} source tables in ${seconds.toLocaleString()} ` +
277
+ `seconds. ${modelsWithRows.toLocaleString()} hold data.`;
278
+ }
279
+
280
+ /** One class per tri-state, so the CSS owns the emphasis and no style prop competes with it. */
281
+ function populationClass(populated: boolean | null): string {
282
+ if (populated === true) return "conn-db-row is-populated";
283
+ if (populated === false) return "conn-db-row is-empty";
284
+ return "conn-db-row is-uncounted";
285
+ }
286
+
287
+ function populationTime(capturedAt: string) {
288
+ const millis = Date.parse(capturedAt);
289
+ return Number.isFinite(millis) ? new Date(millis).toLocaleString() : "";
290
+ }
291
+
292
+ function populationResult(
293
+ modelsCounted: number,
294
+ modelsWithRows: number,
295
+ durationMs: number,
296
+ capturedAt: string,
297
+ complete: boolean
298
+ ) {
299
+ const summary = populationSummary(modelsCounted, modelsWithRows, durationMs);
300
+ const countedAt = populationTime(capturedAt);
301
+ return summary + (countedAt ? ` Counted on ${countedAt}.` : "") +
302
+ (complete ? "" : " The count was incomplete because some source tables could not be read.");
303
+ }
304
+
305
  /** The on/off control, one shape for both rails (DESIGN.md section 4: one control shape). */
306
  function Switch({
307
  on,
 
357
  canToggleFields,
358
  catalogueComplete,
359
  excludedBasis,
360
+ busy,
361
  onField,
362
  }: {
363
  database: ConnectorDatabase;
 
367
  canToggleFields: boolean;
368
  catalogueComplete: boolean;
369
  excludedBasis: string;
370
+ busy: boolean;
371
  onField: (fieldKey: string, next: boolean) => void;
372
  }) {
373
  /**
 
421
  {canToggleFields ? (
422
  <Switch
423
  on={field.enabled}
424
+ busy={busy}
425
  label={
426
  field.enabled
427
  ? `Switch the field ${field.label} off`
 
473
  * remounted, and so this whole tab still paints under `renderToStaticMarkup`.
474
  *
475
  * β›” NO CONTROL AT ALL FOR A READER WHO MAY NOT RENAME (`canRename` is the server's own `may_open`
476
+ * answer). When `exists` is false, that is a different fact: the table is still waiting for a
477
+ * sync, so the cell says why the control is absent instead of presenting a permission refusal.
478
  */
479
  function NameCell({
480
  database,
 
516
  >
517
  {database.override ? "Change" : "Rename"}
518
  </button>
519
+ ) : database.enabled && !database.exists ? (
520
+ <span className="conn-db-state">Available after the first sync.</span>
521
  ) : null}
522
  </div>
523
  );
 
544
  disabled={busy || !draft.trim()}
545
  onClick={() => onSave(draft)}
546
  >
547
+ Done
548
  </button>
549
  {database.override ? (
550
  <button
 
566
 
567
  /**
568
  * ⭐ THE TAB, PURE AND EXPORTED. Everything it lists is `detail`; the only network it does is a
569
+ * a read the reader asked for, plus R23's pre-flight before an off change is accepted.
570
  */
571
+ const DatabasesTab = forwardRef<DatabasesTabHandle, {
572
+ row: ConnectorRow;
573
+ detail: ConnectorDetail;
574
+ /** Re-read `/detail` once after a committed batch or a population count. */
575
+ onChanged: (reveal?: DatabaseReveal) => void;
576
+ /** Reports the diff count to the modal chrome, where Save and Discard live. */
577
+ onPendingChange: (count: number) => void;
578
+ /** Locks the modal actions while the dependents check or the batch is in flight. */
579
+ onBusyChange: (busy: boolean) => void;
580
+ /** The enabled row and its result survive the modal's loading remount. */
581
+ reveal?: DatabaseReveal | null;
582
+ }>(function DatabasesTab({
583
  row,
584
  detail,
585
  onChanged,
586
+ onPendingChange,
587
+ onBusyChange,
588
+ reveal,
589
+ }, ref) {
 
 
590
  const { databases, introspection } = detail;
591
+ const showsPopulation = row.key === "odoo";
592
  /**
593
  * ⚠ W53-T27 β€” EVERY ROW STARTS CLOSED, and that changed here. Until this ticket the first
594
  * database was opened for you, because the field list WAS the content of this tab. The content
595
  * is now the eight rows and their three names, and one open row buries the other seven under a
596
  * 190-field table: the reader cannot see the list they came to read.
597
  */
598
+ const [open, setOpen] = useState<Record<string, boolean>>(
599
+ () => reveal?.key ? { [reveal.key]: true } : {}
600
+ );
601
  const [busy, setBusy] = useState("");
602
  const [refusals, setRefusals] = useState<Record<string, string>>({});
603
+ const [autoEnableResults, setAutoEnableResults] = useState<Record<string, string>>(
604
+ () => reveal?.key && reveal.status ? { [reveal.key]: reveal.status } : {}
605
+ );
606
  const [error, setError] = useState("");
607
+ const [censusBusy, setCensusBusy] = useState(false);
608
+ const [censusResult, setCensusResult] = useState("");
609
  /** The one row being renamed, and the text in its box. Empty means nobody is renaming. */
610
  const [renaming, setRenaming] = useState("");
611
  const [draft, setDraft] = useState("");
612
+ /** Only values that differ from the last server answer live here. */
613
+ const [pending, setPending] = useState<PendingDatabaseChanges>(EMPTY_PENDING);
614
+ const pendingCount = pendingChangeCount(pending);
615
+
616
+ useEffect(() => {
617
+ onPendingChange(pendingCount);
618
+ }, [onPendingChange, pendingCount]);
619
+
620
+ useEffect(() => {
621
+ onBusyChange(Boolean(busy));
622
+ }, [busy, onBusyChange]);
623
 
624
  const labels = useMemo(() => {
625
  const out: Record<string, string> = {};
626
+ for (const database of databases) {
627
+ const override = pending.names[database.key];
628
+ out[database.key] = override === undefined
629
+ ? database.label
630
+ : override || database.defaultLabel;
631
+ }
632
  return out;
633
+ }, [databases, pending.names]);
634
  const orderedDatabases = useMemo(
635
  () =>
636
  databases
637
  .map((database, index) => ({ database, index }))
638
  .sort(
639
  (a, b) =>
640
+ Number(pending.tables[b.database.key] ?? b.database.enabled) -
641
+ Number(pending.tables[a.database.key] ?? a.database.enabled) ||
642
+ Number(b.database.populated === true) - Number(a.database.populated === true) ||
643
+ a.index - b.index
644
  )
645
  .map(({ database }) => database),
646
+ [databases, pending.tables]
647
  );
648
 
649
  /**
650
+ * β›”β›” R23's OFF ENFORCEMENT, AND TODAY IT LIVES HERE. Turning a database off keeps using
651
+ * `PUT /admin/connectors/odoo/config`, which knows nothing about dependents, so the ASK has to
652
+ * happen before the change enters the pending diff. Turning one on is queued for the
653
+ * materialising door; mixing the two would bypass the only dependents check on the off path.
654
  *
655
  * β›” AND A FAILED CHECK IS NOT A PASSED ONE. Any non-answer leaves the table on and prints the
656
  * cause; proceeding would turn "REFUSED" into "usually refused".
 
660
  setBusy(database.key);
661
  setError("");
662
  setRefusals((current) => ({ ...current, [database.key]: "" }));
663
+ setAutoEnableResults((current) => ({ ...current, [database.key]: "" }));
664
  if (!next) {
665
  const answer = await readDependents(database.key);
666
  if (!answer.ok) {
 
679
  return;
680
  }
681
  }
 
 
 
682
  setBusy("");
683
+ setPending((current) => {
684
+ const tables = { ...current.tables };
685
+ if (next === database.enabled) delete tables[database.key];
686
+ else tables[database.key] = next;
687
+ return { ...current, tables };
688
+ });
689
  },
690
+ []
691
  );
692
 
693
  const flipField = useCallback(
694
  async (fieldKey: string, next: boolean) => {
 
695
  setError("");
696
+ const original = databases
697
+ .flatMap((database) => database.fields)
698
+ .find((field) => field.key === fieldKey)?.enabled;
699
+ if (original === undefined) return;
700
+ setPending((current) => {
701
+ const fields = { ...current.fields };
702
+ if (next === original) delete fields[fieldKey];
703
+ else fields[fieldKey] = next;
704
+ return { ...current, fields };
705
+ });
706
  },
707
+ [databases]
708
  );
709
 
710
  /**
711
  * ⭐ W53-T27 / R9 β€” THE OVERRIDE, WRITTEN THROUGH THE DOOR THAT WRITES THE NAVIGATION RAIL'S
712
+ * OWN BUCKET at commit time. An empty `name` CLEARS it, which is the half `POST /nav/meta`
713
+ * refuses and the reason this door exists at all.
 
 
 
714
  */
715
  const renameDatabase = useCallback(
716
  async (database: ConnectorDatabase, next: string) => {
 
717
  setError("");
718
+ const normalized = next.trim();
719
+ setPending((current) => {
720
+ const names = { ...current.names };
721
+ if (normalized === database.override) delete names[database.key];
722
+ else names[database.key] = normalized;
723
+ return { ...current, names };
724
+ });
725
+ setRenaming("");
726
+ setDraft("");
727
+ },
728
+ []
729
+ );
730
+
731
+ const discardPending = useCallback(() => {
732
+ setPending(EMPTY_PENDING);
733
+ setError("");
734
+ setRenaming("");
735
+ setDraft("");
736
+ onPendingChange(0);
737
+ }, [onPendingChange]);
738
+
739
+ const savePending = useCallback(async () => {
740
+ const snapshot = pending;
741
+ if (!pendingChangeCount(snapshot)) return;
742
+
743
+ const failed: PendingDatabaseChanges = { tables: {}, fields: {}, names: {} };
744
+ const failures: string[] = [];
745
+ setBusy("save");
746
+ setError("");
747
+
748
+ for (const [databaseKey, next] of Object.entries(snapshot.tables)) {
749
+ const database = databases.find((candidate) => candidate.key === databaseKey);
750
+ const label = database?.label || databaseKey;
751
+ const providerEnablement = detail.enablement;
752
+ if (providerEnablement?.canManage && providerEnablement.updatePath) {
753
+ const path = providerEnablement.updatePath.replace(
754
+ "{databaseKey}",
755
+ encodeURIComponent(databaseKey)
756
+ );
757
+ const message = path === providerEnablement.updatePath
758
+ ? "This provider did not return a usable enablement path."
759
+ : await write(path, "PATCH", { enabled: next });
760
+ if (message) {
761
+ failed.tables[databaseKey] = next;
762
+ failures.push(`${label}: ${message}`);
763
+ }
764
+ continue;
765
+ }
766
+ if (next) {
767
+ const answer = await enableDatabase(databaseKey);
768
+ if (!answer.ok) {
769
+ failed.tables[databaseKey] = next;
770
+ failures.push(`${label}: ${answer.message}`);
771
+ continue;
772
+ }
773
+ const status = autoEnableResult(answer);
774
+ setOpen((current) => ({ ...current, [databaseKey]: true }));
775
+ setAutoEnableResults((current) => ({ ...current, [databaseKey]: status }));
776
+ if (answer.workspaceChanged) signal(WORKSPACE_STALE_EVENT);
777
+ continue;
778
+ }
779
+ const message = await write("/admin/connectors/odoo/config", "PUT", {
780
+ grids: { [databaseKey]: false },
781
+ });
782
+ if (message) {
783
+ failed.tables[databaseKey] = next;
784
+ failures.push(`${label}: ${message}`);
785
+ }
786
+ }
787
+
788
+ for (const [fieldKey, next] of Object.entries(snapshot.fields)) {
789
+ const fieldDatabase = databases.find((database) =>
790
+ database.fields.some((candidate) => candidate.key === fieldKey)
791
+ );
792
+ const field = fieldDatabase?.fields.find((candidate) => candidate.key === fieldKey);
793
+ const message = await write(
794
+ `/connectors/odoo/schema/${encodeURIComponent(fieldKey)}`,
795
+ "PATCH",
796
+ { enabled: next }
797
+ );
798
+ if (message) {
799
+ failed.fields[fieldKey] = next;
800
+ const subject = fieldDatabase
801
+ ? `${fieldDatabase.label}, ${field?.label || fieldKey}`
802
+ : fieldKey;
803
+ failures.push(`${subject}: ${message}`);
804
+ }
805
+ }
806
+
807
+ for (const [databaseKey, name] of Object.entries(snapshot.names)) {
808
+ const database = databases.find((candidate) => candidate.key === databaseKey);
809
  const message = await write(
810
  `/connectors/${encodeURIComponent(row.key)}/databases/` +
811
+ `${encodeURIComponent(databaseKey)}/name`,
812
  "PATCH",
813
+ { name }
814
  );
 
815
  if (message) {
816
+ failed.names[databaseKey] = name;
817
+ failures.push(`${database?.label || databaseKey}: ${message}`);
818
  }
819
+ }
820
+
821
+ setPending(failed);
822
+ onPendingChange(pendingChangeCount(failed));
823
+ setBusy("");
824
+ setError(failures.join(" "));
825
+ // One batch gets one fresh detail payload. That payload also carries the newly derived graph.
826
+ onChanged();
827
+ }, [databases, detail.enablement, onChanged, onPendingChange, pending, row.key]);
828
+
829
+ useImperativeHandle(ref, () => ({
830
+ savePending,
831
+ discardPending,
832
+ stageTable: flipTable,
833
+ tableEnabled: (database) => pending.tables[database.key] ?? database.enabled,
834
+ }), [discardPending, flipTable, pending.tables, savePending]);
835
+
836
+ const runPopulationCount = useCallback(async () => {
837
+ setCensusBusy(true);
838
+ setCensusResult("");
839
+ setError("");
840
+ const answer = await countSourceRows();
841
+ setCensusBusy(false);
842
+ if (!answer.ok) {
843
+ setError(answer.message);
844
+ return;
845
+ }
846
+ setCensusResult(populationResult(
847
+ answer.modelsCounted,
848
+ answer.modelsWithRows,
849
+ answer.durationMs,
850
+ answer.capturedAt,
851
+ answer.complete
852
+ ));
853
+ onChanged();
854
+ }, [onChanged]);
855
 
856
  if (!introspection.introspectable) {
857
  return <DatabasesUnavailable row={row} reason={introspection.reason} />;
 
870
 
871
  return (
872
  <div className="conn-db">
873
+ {showsPopulation && introspection.fieldsVisible ? (
874
+ <div className="conn-db-head">
875
+ <div>
876
+ <p className="conn-db-note" id="odoo-census-warning">
877
+ Counting every source table takes about a minute and a half on a workspace this
878
+ size. You can keep this tab open while it runs.
879
+ </p>
880
+ {censusResult ? (
881
+ <p className="conn-db-note" role="status">{censusResult}</p>
882
+ ) : introspection.censusAt ? (
883
+ <p className="conn-db-note">
884
+ {populationResult(
885
+ introspection.censusModelsCounted,
886
+ introspection.censusModelsWithRows,
887
+ introspection.censusDurationMs,
888
+ introspection.censusAt,
889
+ introspection.censusComplete
890
+ )}
891
+ </p>
892
+ ) : null}
893
+ </div>
894
+ <button
895
+ type="button"
896
+ className="conn-db-link"
897
+ aria-describedby="odoo-census-warning"
898
+ disabled={censusBusy}
899
+ onClick={() => void runPopulationCount()}
900
+ >
901
+ {censusBusy ? "Counting rows..." : "Count rows"}
902
+ </button>
903
+ </div>
904
+ ) : null}
905
  {error ? (
906
  <p className="conn-db-error" role="alert">
907
  {error}
 
919
  name is ours. Your name replaces it everywhere in this workspace, including the
920
  navigation rail, and clearing it brings the default back.
921
  </p>
922
+ {showsPopulation ? (
923
+ <p className="conn-db-note">
924
+ Source rows is the source table's count. Databases sharing a source table show the same
925
+ number. Open Fields to see which databases share it.
926
+ </p>
927
+ ) : null}
928
  <table className="conn-db-fields">
929
  <thead>
930
  <tr>
 
932
  <th scope="col">Default name</th>
933
  <th scope="col">Your name</th>
934
  <th scope="col">Fields</th>
935
+ {showsPopulation ? <th scope="col">Source rows</th> : null}
936
  <th scope="col">Enabled</th>
937
  </tr>
938
  </thead>
939
  {orderedDatabases.map((database) => {
940
+ const effectiveEnabled = pending.tables[database.key] ?? database.enabled;
941
+ const effectiveOverride = pending.names[database.key] ?? database.override;
942
+ const renderedDatabase: ConnectorDatabase = {
943
+ ...database,
944
+ enabled: effectiveEnabled,
945
+ override: effectiveOverride,
946
+ label: effectiveOverride || database.defaultLabel,
947
+ fields: database.fields.map((field) => ({
948
+ ...field,
949
+ enabled: pending.fields[field.key] ?? field.enabled,
950
+ })),
951
+ };
952
  const isOpen = open[database.key] === true;
953
  const refusal = refusals[database.key] || "";
954
+ const autoEnableStatus = autoEnableResults[database.key] || "";
955
+ const siblingLabels = database.sharesFieldsWith
956
+ .map((key) => labels[key] || "")
957
+ .filter((label) => label.length > 0);
958
  return (
959
  <tbody key={database.key}>
960
+ {/* β›” THE WORDS IN THE `Source rows` CELL CARRY THE MEANING; this class only
961
+ reinforces them. Colour and weight alone would put the whole signal where a
962
+ reader with low vision or a monochrome screen cannot reach it. */}
963
+ <tr className={populationClass(database.populated)}>
964
  {/* β›” AN ABSENT NATIVE NAME IS SAID, NOT FILLED IN. Amazon names a table by the
965
  report it is filled from, and a table whose report type we cannot read has no
966
  vendor identifier to show. Printing the key there would put our own word under
 
971
  <td>{database.defaultLabel}</td>
972
  <td>
973
  <NameCell
974
+ database={renderedDatabase}
975
  editing={renaming === database.key}
976
  draft={draft}
977
+ busy={Boolean(busy)}
978
  onDraft={setDraft}
979
  onEdit={() => {
980
  setRenaming(database.key);
981
+ setDraft(effectiveOverride || database.defaultLabel);
982
  setError("");
983
  }}
984
  onCancel={() => {
 
993
  type="button"
994
  className="conn-db-more"
995
  aria-expanded={isOpen}
996
+ aria-label={`Show the fields in ${renderedDatabase.label}`}
997
  onClick={() =>
998
  setOpen((current) => ({ ...current, [database.key]: !isOpen }))
999
  }
 
1003
  </span>
1004
  </button>
1005
  </td>
1006
+ {showsPopulation ? (
1007
+ <td>
1008
+ {database.sourceRows === 0 ? (
1009
+ <span className="conn-db-state">Empty</span>
1010
+ ) : typeof database.sourceRows === "number" ? (
1011
+ database.sourceRows.toLocaleString()
1012
+ ) : (
1013
+ <span className="conn-db-state">Not counted yet</span>
1014
+ )}
1015
+ </td>
1016
+ ) : null}
1017
  {/* ⭐ R22 β€” ANY table can be switched off, not only the ones we mark optional.
1018
  Every row gets the same control, and nothing here decides that one of them is
1019
  too important to turn off: R23's ask is what protects a table in use. */}
1020
  <td className="conn-db-cell-switch">
1021
  {introspection.canToggleTables ? (
1022
  <Switch
1023
+ on={effectiveEnabled}
1024
+ busy={Boolean(busy)}
1025
  label={
1026
+ effectiveEnabled
1027
+ ? `Switch off the database ${renderedDatabase.label}`
1028
+ : `Switch on the database ${renderedDatabase.label}`
1029
  }
1030
  onFlip={(next) => void flipTable(database, next)}
1031
  />
 
1034
  )}
1035
  </td>
1036
  </tr>
1037
+ {!effectiveEnabled && siblingLabels.length ? (
1038
+ <tr>
1039
+ <td colSpan={showsPopulation ? 6 : 5}>
1040
+ <p className="conn-db-shared">
1041
+ {renderedDatabase.label} shares its Odoo source table with {sentenceList(siblingLabels)},
1042
+ so populated fields will be switched on there too.
1043
+ </p>
1044
+ </td>
1045
+ </tr>
1046
+ ) : null}
1047
+ {autoEnableStatus ? (
1048
+ <tr>
1049
+ <td colSpan={showsPopulation ? 6 : 5}>
1050
+ <p className="conn-db-note" role="status" aria-live="polite">
1051
+ {autoEnableStatus}
1052
+ </p>
1053
+ </td>
1054
+ </tr>
1055
+ ) : null}
1056
  {refusal ? (
1057
  // ⚠ A REFUSAL IS NOT AN ERROR THE READER CAUSED (DESIGN.md section 4). It states
1058
  // the cause and the subject, in the server's own sentence, and offers nothing to
1059
  // dismiss because the table simply stayed on.
1060
  <tr>
1061
+ <td colSpan={showsPopulation ? 6 : 5}>
1062
  <p className="conn-db-refusal" role="alert">
1063
  {refusal}
1064
  </p>
 
1067
  ) : null}
1068
  {isOpen ? (
1069
  <tr>
1070
+ <td colSpan={showsPopulation ? 6 : 5}>
1071
  <DatabasePanel
1072
+ database={renderedDatabase}
1073
+ siblingLabels={siblingLabels}
 
 
1074
  fieldsVisible={introspection.fieldsVisible}
1075
  canToggleFields={introspection.canToggleFields}
1076
  catalogueComplete={introspection.catalogueComplete}
1077
  excludedBasis={introspection.excludedBasis}
1078
+ busy={Boolean(busy)}
1079
  onField={(fieldKey, next) => void flipField(fieldKey, next)}
1080
  />
1081
  </td>
 
1087
  </table>
1088
  </div>
1089
  );
1090
+ });
1091
+
1092
+ export default DatabasesTab;
web/src/connectors/RelationshipDiagram.tsx CHANGED
@@ -707,6 +707,72 @@ export default function RelationshipDiagram({
707
  observer.observe(surface);
708
  return () => observer.disconnect();
709
  }, []);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
710
  const layout = useMemo(
711
  () => relationshipLayout(graph, expandedKeys, availableWidth),
712
  [availableWidth, graph, expandedKeys]
 
707
  observer.observe(surface);
708
  return () => observer.disconnect();
709
  }, []);
710
+ useEffect(() => {
711
+ const scrollElement = scrollRef.current;
712
+ if (!scrollElement) return;
713
+
714
+ // W56-T30: columns widen the uncapped diagram, while an ancestor owns vertical overflow.
715
+ // Prevent the default only when this surface or an ancestor can move, so no gesture is trapped.
716
+ const handleWheel = (event: WheelEvent) => {
717
+ const surface = scrollRef.current;
718
+ if (!surface) return;
719
+ if (surface.scrollHeight - surface.clientHeight > 1) return;
720
+ if (event.deltaX !== 0 || event.deltaY === 0) return;
721
+
722
+ const maxScrollLeft = surface.scrollWidth - surface.clientWidth;
723
+ let delta = event.deltaY;
724
+ if (event.deltaMode === 1) delta *= 16;
725
+ else if (event.deltaMode === 2) delta *= surface.clientWidth;
726
+
727
+ const nextScrollLeft = Math.min(maxScrollLeft, Math.max(0, surface.scrollLeft + delta));
728
+ if (maxScrollLeft > 1) {
729
+ const previous = surface.scrollLeft;
730
+ surface.scrollLeft = nextScrollLeft;
731
+ // W56-T30 read-back: arithmetic said 151px while Chrome clamped to 136px.
732
+ if (surface.scrollLeft !== previous) {
733
+ event.preventDefault();
734
+ return;
735
+ }
736
+ }
737
+
738
+ // W56-T30 rule: forward only wheel delta this surface cannot use. Measured: `.conn-rd-scroll`
739
+ // is `overflow: auto` but can never scroll vertically, so Chrome stops here instead of chaining;
740
+ // `overflow-y: visible` is not expressible beside `overflow-x: auto` because it computes to auto.
741
+ for (
742
+ let ancestor = surface.parentElement;
743
+ ancestor && ancestor !== document.body && ancestor !== document.documentElement;
744
+ ancestor = ancestor.parentElement
745
+ ) {
746
+ const overflowY = getComputedStyle(ancestor).overflowY;
747
+ if (overflowY !== "auto" && overflowY !== "scroll") continue;
748
+
749
+ const maxScrollTop = ancestor.scrollHeight - ancestor.clientHeight;
750
+ if (maxScrollTop <= 1) continue;
751
+
752
+ let ancestorDelta = event.deltaY;
753
+ if (event.deltaMode === 1) ancestorDelta *= 16;
754
+ else if (event.deltaMode === 2) ancestorDelta *= ancestor.clientHeight;
755
+
756
+ const canAbsorb = ancestorDelta > 0
757
+ ? ancestor.scrollTop < maxScrollTop - 1
758
+ : ancestor.scrollTop > 1;
759
+ if (!canAbsorb) continue;
760
+
761
+ const nextScrollTop = Math.min(maxScrollTop, Math.max(0, ancestor.scrollTop + ancestorDelta));
762
+ if (nextScrollTop === ancestor.scrollTop) continue;
763
+
764
+ event.preventDefault();
765
+ ancestor.scrollTop = nextScrollTop;
766
+ return;
767
+ }
768
+ };
769
+
770
+ scrollElement.addEventListener("wheel", handleWheel, { passive: false });
771
+ return () => scrollElement.removeEventListener("wheel", handleWheel);
772
+ // Re-attached when the graph changes: the two early returns below mean the scroll surface
773
+ // does not exist while a graph is refused or empty, so a `[]` list would leave a graph that
774
+ // arrives later with no wheel handler at all.
775
+ }, [graph]);
776
  const layout = useMemo(
777
  () => relationshipLayout(graph, expandedKeys, availableWidth),
778
  [availableWidth, graph, expandedKeys]
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -249,6 +249,7 @@ import type {
249
  FieldType,
250
  FilterNode,
251
  FilterRule,
 
252
  PivotResponse,
253
  PivotRefusal,
254
  PivotWindow,
@@ -1686,6 +1687,20 @@ interface CustomerGridProps {
1686
  * serialised into a saved view β€” see `pinnedChip` below for why that one is load-bearing.
1687
  */
1688
  related?: { table: string; record: number; via: RelatedVia; label: string };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1689
  /**
1690
  * ⭐ W51-T06 clause 9 β€” a row click NAVIGATES the record view instead of opening this grid's
1691
  * own drawer.
@@ -1740,17 +1755,27 @@ interface LinkGridModalProps {
1740
  editable?: boolean;
1741
  single?: boolean;
1742
  excludeRecordId?: number;
 
 
 
 
 
 
 
 
 
 
1743
  onSave?: (recordIds: number[]) => void;
1744
  onClose: () => void;
1745
  }
1746
 
1747
  // ⭐ EXPORTED FOR THE SHEET MODULE (wave 49, W49-T07, ruling R6): "clicking a cell pops up the View
1748
  // using exactly the Link field type's popup UI". Exactly the same component, not a copy of it, so
1749
- // the two surfaces cannot drift into two popups that behave almost alike. This `export` is lane A's
1750
- // ONLY change to this file, and it is additive: the single existing call site below is untouched,
1751
- // and nothing about the component's props, focus trap or portal changes.
1752
  export function LinkGridModal({ label, table, recordIds, editable = false, single = false,
1753
- excludeRecordId, onSave, onClose }: LinkGridModalProps) {
 
1754
  const panelRef = useRef<HTMLDivElement>(null);
1755
  const [selectedIds, setSelectedIds] = useState<number[]>(() => [...recordIds]);
1756
  const changeSelectedIds = useCallback((ids: number[]) => {
@@ -1775,18 +1800,21 @@ export function LinkGridModal({ label, table, recordIds, editable = false, singl
1775
  role="dialog"
1776
  aria-modal="true"
1777
  aria-label={label}
1778
- data-overlay-kind="linked-record-grid"
1779
  tabIndex={-1}
1780
  >
1781
  <header className="cg-link-grid-head">
1782
  <div>
1783
  <div className="cg-link-grid-title">{label}</div>
1784
  <div className="cg-link-grid-sub">
1785
- {(editable ? selectedIds.length : recordIds.length).toLocaleString()} linked{
 
 
1786
  single ? " (one allowed)" : ""
1787
  } {(editable ? selectedIds.length : recordIds.length) === 1 ? "record" : "records"}
1788
  </div>
1789
  </div>
 
1790
  <button
1791
  type="button"
1792
  className="cg-icon-btn"
@@ -1801,6 +1829,9 @@ export function LinkGridModal({ label, table, recordIds, editable = false, singl
1801
  <CustomerGrid
1802
  scope={table}
1803
  embedded
 
 
 
1804
  embeddedRecordIds={editable ? undefined : recordIds}
1805
  embeddedExcludeRecordId={editable ? excludeRecordId : undefined}
1806
  embeddedSelectable={editable}
@@ -1819,6 +1850,8 @@ export function LinkGridModal({ label, table, recordIds, editable = false, singl
1819
  Save links
1820
  </button>
1821
  </footer>
 
 
1822
  ) : null}
1823
  </section>
1824
  </div>
@@ -1948,6 +1981,9 @@ function CustomerGridSurface({
1948
  onEmbeddedSelectionChange,
1949
  embeddedExcludeRecordId,
1950
  related,
 
 
 
1951
  onOpenRecord,
1952
  relatedViewId,
1953
  onRelatedViewChange,
@@ -2581,6 +2617,9 @@ function CustomerGridSurface({
2581
  const storageKey = isQueryPreview && queryBinding
2582
  ? `query:${queryBinding.workspaceBinding.key}`
2583
  : payload?.workspace?.storageKey ?? `${LOCAL_KEY_PREFIX}${scope}`;
 
 
 
2584
 
2585
  // Initialize once per permission/data scope. Host state wins; local state
2586
  // fills only missing objects and keeps the standalone path useful.
@@ -2726,7 +2765,11 @@ function CustomerGridSurface({
2726
  setFields(initialFields);
2727
  setViews(initialViews);
2728
  setActiveViewId(active.id);
2729
- setConfig(active.config);
 
 
 
 
2730
  setWorkspaceReady(true);
2731
  initializedKey.current = storageKey;
2732
 
@@ -2766,7 +2809,8 @@ function CustomerGridSurface({
2766
  } else {
2767
  reemittedRef.current = { ...(local?.reemitted ?? {}) };
2768
  }
2769
- }, [payload, payloadFields, storageKey, hostWorkspace, scope, isQueryPreview, queryBinding]);
 
2770
 
2771
  /**
2772
  * ⭐ W36-T03 β€” the view-preference stamp, and it is its OWN effect on purpose.
@@ -3390,8 +3434,13 @@ function CustomerGridSurface({
3390
  // calendar/kanban compute over the whole matched set, and one page is not it (CG-3's rule,
3391
  // the same reason grouping is off there).
3392
  const displaySpec = resolvedDisplaySpec;
3393
- const displayMode: DisplayMode = serverWindowed ? "grid" : displaySpec?.mode ?? "grid";
3394
  const [routePanelOpen, setRoutePanelOpen] = useState(false);
 
 
 
 
 
 
3395
  /**
3396
  * ⭐⭐ D-673 / W54-T21 β€” THE TOP RUNG OF THE MAP'S ESCAPE LADDER, AND IT HAS TO BE HERE.
3397
  *
@@ -3413,16 +3462,24 @@ function CustomerGridSurface({
3413
  const openRoute = (event: Event) => {
3414
  const detail = (event as CustomEvent<{ routeId?: string; forwarded?: boolean }>).detail;
3415
  if (!detail?.routeId || detail.forwarded) return;
 
 
3416
  setRoutePanelOpen(true);
3417
- updateConfig({ ...config, display: { ...(displaySpec ?? {}), mode: "map" } });
3418
  window.setTimeout(() => signal("aios:route-open", { routeId: detail.routeId, forwarded: true }), 60);
3419
  };
3420
  window.addEventListener("aios:route-open", openRoute);
3421
  return () => window.removeEventListener("aios:route-open", openRoute);
3422
- }, [config, displaySpec, updateConfig]);
3423
  useEffect(() => {
3424
  if (displayMode !== "map") setRoutePanelOpen(false);
3425
  }, [displayMode]);
 
 
 
 
 
 
3426
  useEffect(() => {
3427
  if (!routePanelOpen) return;
3428
  setSelAddOpen(false);
@@ -3718,8 +3775,10 @@ function CustomerGridSurface({
3718
  }
3719
  }
3720
  updateConfig({ ...config, filters });
 
 
3721
  },
3722
- [activeViewId, views, config, updateConfig]
3723
  );
3724
 
3725
  const unresolvedCount = useMemo(
@@ -8818,6 +8877,7 @@ function CustomerGridSurface({
8818
  // callback is declared above it.)
8819
  const av = views.find((v) => v.id === activeViewId);
8820
  if (av && isModeFrozen(av)) return;
 
8821
  const spec = displaySpec;
8822
  if (m === "grid") {
8823
  updateConfig({
@@ -9460,7 +9520,17 @@ function CustomerGridSurface({
9460
  updateConfig({ ...config, order: nextOrder });
9461
  };
9462
  // Item 10 β€” the toolbar's mode switcher (grid-only on windowed tables, see displayMode).
9463
- const modeControl = serverWindowed || embedded || isQueryPreview ? undefined : (
 
 
 
 
 
 
 
 
 
 
9464
  <ModeSwitch
9465
  mode={displayMode}
9466
  onMode={setDisplayMode}
@@ -10275,6 +10345,8 @@ function CustomerGridSurface({
10275
  return;
10276
  }
10277
  updateConfig({ ...config, filterConj });
 
 
10278
  }}
10279
  filtersLocked={activeFiltersLocked}
10280
  sorts={config.sorts}
 
249
  FieldType,
250
  FilterNode,
251
  FilterRule,
252
+ FilterTree,
253
  PivotResponse,
254
  PivotRefusal,
255
  PivotWindow,
 
1687
  * serialised into a saved view β€” see `pinnedChip` below for why that one is load-bearing.
1688
  */
1689
  related?: { table: string; record: number; via: RelatedVia; label: string };
1690
+ /**
1691
+ * W56-T24 / R4 / C4 β€” the Sheet cell's View data surface.
1692
+ * A MODIFIER ON `embedded`, never a replacement for it: every write guard `embedded` installs
1693
+ * stays installed (no saved-view autosave, no cell edits, no host workspace, no view rail), and
1694
+ * this flag relaxes exactly one withholding, the display-mode switcher.
1695
+ */
1696
+ cellView?: boolean;
1697
+ /**
1698
+ * The Sheet cell's own rows-to-include, seeded into THIS surface's filter so the reader can see
1699
+ * and edit the reason the rows are here. Only meaningful with `cellView`.
1700
+ */
1701
+ cellFilter?: FilterTree;
1702
+ /** Report a filter edit from the cell View data surface; its Sheet caller owns settling. */
1703
+ onCellFilterChange?: (tree: FilterTree) => void;
1704
  /**
1705
  * ⭐ W51-T06 clause 9 β€” a row click NAVIGATES the record view instead of opening this grid's
1706
  * own drawer.
 
1755
  editable?: boolean;
1756
  single?: boolean;
1757
  excludeRecordId?: number;
1758
+ /** W56-T24: render the body as the Data module's own grid, with its display modes. */
1759
+ cellView?: boolean;
1760
+ /** W56-T25: the Sheet cell's own filter, shown in the grid's standard filter control. */
1761
+ cellFilter?: FilterTree;
1762
+ /** W56-T25: report a grid filter edit so the Sheet caller can settle and persist it. */
1763
+ onCellFilterChange?: (tree: FilterTree) => void;
1764
+ /** W56-T24: chrome the caller owns, in the header, right of the title and left of Close. */
1765
+ headerActions?: ReactNode;
1766
+ /** W56-T24: a statement under the rows. Only rendered on a non-editable modal. */
1767
+ footer?: ReactNode;
1768
  onSave?: (recordIds: number[]) => void;
1769
  onClose: () => void;
1770
  }
1771
 
1772
  // ⭐ EXPORTED FOR THE SHEET MODULE (wave 49, W49-T07, ruling R6): "clicking a cell pops up the View
1773
  // using exactly the Link field type's popup UI". Exactly the same component, not a copy of it, so
1774
+ // the two surfaces cannot drift into two popups that behave almost alike. W56-T24 adds optional
1775
+ // chrome slots and a `cellView` modifier while leaving existing callers and the focus trap intact.
 
1776
  export function LinkGridModal({ label, table, recordIds, editable = false, single = false,
1777
+ excludeRecordId, cellView = false, cellFilter, onCellFilterChange, headerActions, footer,
1778
+ onSave, onClose }: LinkGridModalProps) {
1779
  const panelRef = useRef<HTMLDivElement>(null);
1780
  const [selectedIds, setSelectedIds] = useState<number[]>(() => [...recordIds]);
1781
  const changeSelectedIds = useCallback((ids: number[]) => {
 
1800
  role="dialog"
1801
  aria-modal="true"
1802
  aria-label={label}
1803
+ data-overlay-kind={cellView ? "cell-data-grid" : "linked-record-grid"}
1804
  tabIndex={-1}
1805
  >
1806
  <header className="cg-link-grid-head">
1807
  <div>
1808
  <div className="cg-link-grid-title">{label}</div>
1809
  <div className="cg-link-grid-sub">
1810
+ {(editable ? selectedIds.length : recordIds.length).toLocaleString()} {
1811
+ cellView ? "matching" : "linked"
1812
+ }{
1813
  single ? " (one allowed)" : ""
1814
  } {(editable ? selectedIds.length : recordIds.length) === 1 ? "record" : "records"}
1815
  </div>
1816
  </div>
1817
+ {headerActions}
1818
  <button
1819
  type="button"
1820
  className="cg-icon-btn"
 
1829
  <CustomerGrid
1830
  scope={table}
1831
  embedded
1832
+ cellView={cellView}
1833
+ cellFilter={cellFilter}
1834
+ onCellFilterChange={onCellFilterChange}
1835
  embeddedRecordIds={editable ? undefined : recordIds}
1836
  embeddedExcludeRecordId={editable ? excludeRecordId : undefined}
1837
  embeddedSelectable={editable}
 
1850
  Save links
1851
  </button>
1852
  </footer>
1853
+ ) : footer ? (
1854
+ <footer className="cg-link-grid-foot">{footer}</footer>
1855
  ) : null}
1856
  </section>
1857
  </div>
 
1981
  onEmbeddedSelectionChange,
1982
  embeddedExcludeRecordId,
1983
  related,
1984
+ cellView = false,
1985
+ cellFilter,
1986
+ onCellFilterChange,
1987
  onOpenRecord,
1988
  relatedViewId,
1989
  onRelatedViewChange,
 
2617
  const storageKey = isQueryPreview && queryBinding
2618
  ? `query:${queryBinding.workspaceBinding.key}`
2619
  : payload?.workspace?.storageKey ?? `${LOCAL_KEY_PREFIX}${scope}`;
2620
+ // A parent may rebuild an equivalent tree on every render. Depend on its value, not its identity,
2621
+ // so the initialization effect cannot re-seed over an edit still settling in this surface.
2622
+ const cellFilterKey = useMemo(() => JSON.stringify(cellFilter ?? null), [cellFilter]);
2623
 
2624
  // Initialize once per permission/data scope. Host state wins; local state
2625
  // fills only missing objects and keeps the standalone path useful.
 
2765
  setFields(initialFields);
2766
  setViews(initialViews);
2767
  setActiveViewId(active.id);
2768
+ setConfig(cellView && cellFilter ? {
2769
+ ...active.config,
2770
+ filters: cellFilter.nodes ?? [],
2771
+ filterConj: cellFilter.conj ?? "and",
2772
+ } : active.config);
2773
  setWorkspaceReady(true);
2774
  initializedKey.current = storageKey;
2775
 
 
2809
  } else {
2810
  reemittedRef.current = { ...(local?.reemitted ?? {}) };
2811
  }
2812
+ }, [payload, payloadFields, storageKey, hostWorkspace, scope, isQueryPreview, queryBinding,
2813
+ cellView, cellFilterKey]);
2814
 
2815
  /**
2816
  * ⭐ W36-T03 β€” the view-preference stamp, and it is its OWN effect on purpose.
 
3434
  // calendar/kanban compute over the whole matched set, and one page is not it (CG-3's rule,
3435
  // the same reason grouping is off there).
3436
  const displaySpec = resolvedDisplaySpec;
 
3437
  const [routePanelOpen, setRoutePanelOpen] = useState(false);
3438
+ /**
3439
+ * W56-T29: a route's Map is presentation state only. `updateConfig` here writes the saved
3440
+ * View that "Default view" reads, so opening a route must not use it to change modes.
3441
+ */
3442
+ const [routeMapMode, setRouteMapMode] = useState(false);
3443
+ const displayMode: DisplayMode = serverWindowed ? "grid" : routeMapMode ? "map" : displaySpec?.mode ?? "grid";
3444
  /**
3445
  * ⭐⭐ D-673 / W54-T21 β€” THE TOP RUNG OF THE MAP'S ESCAPE LADDER, AND IT HAS TO BE HERE.
3446
  *
 
3462
  const openRoute = (event: Event) => {
3463
  const detail = (event as CustomEvent<{ routeId?: string; forwarded?: boolean }>).detail;
3464
  if (!detail?.routeId || detail.forwarded) return;
3465
+ const activeRouteView = views.find((view) => view.id === activeViewId);
3466
+ if (activeRouteView && isModeFrozen(activeRouteView) && displaySpec?.mode !== "map") return;
3467
  setRoutePanelOpen(true);
3468
+ setRouteMapMode(true);
3469
  window.setTimeout(() => signal("aios:route-open", { routeId: detail.routeId, forwarded: true }), 60);
3470
  };
3471
  window.addEventListener("aios:route-open", openRoute);
3472
  return () => window.removeEventListener("aios:route-open", openRoute);
3473
+ }, [activeViewId, displaySpec, views]);
3474
  useEffect(() => {
3475
  if (displayMode !== "map") setRoutePanelOpen(false);
3476
  }, [displayMode]);
3477
+ useEffect(() => {
3478
+ if (!routePanelOpen) setRouteMapMode(false);
3479
+ }, [routePanelOpen]);
3480
+ useEffect(() => {
3481
+ setRouteMapMode(false);
3482
+ }, [scope]);
3483
  useEffect(() => {
3484
  if (!routePanelOpen) return;
3485
  setSelAddOpen(false);
 
3775
  }
3776
  }
3777
  updateConfig({ ...config, filters });
3778
+ if (cellView)
3779
+ onCellFilterChange?.({ conj: config.filterConj ?? "and", nodes: filters });
3780
  },
3781
+ [activeViewId, views, config, updateConfig, cellView, onCellFilterChange]
3782
  );
3783
 
3784
  const unresolvedCount = useMemo(
 
8877
  // callback is declared above it.)
8878
  const av = views.find((v) => v.id === activeViewId);
8879
  if (av && isModeFrozen(av)) return;
8880
+ setRouteMapMode(false);
8881
  const spec = displaySpec;
8882
  if (m === "grid") {
8883
  updateConfig({
 
9520
  updateConfig({ ...config, order: nextOrder });
9521
  };
9522
  // Item 10 β€” the toolbar's mode switcher (grid-only on windowed tables, see displayMode).
9523
+ //
9524
+ // ⭐⭐ W56-T24 / R4 β€” `cellView` IS THE ONE RELAXATION, AND THE PREDICATE IS SPELT IN TWO PARTS
9525
+ // ON PURPOSE. `modeWithheld` is the original three-way test, unchanged and unrewritten, because
9526
+ // `verify_grid_ux.py` reads it as a LITERAL to prove W33-T74's claim that the artefact's KIND is
9527
+ // not a Query preview's to change. Folding `cellView` into that expression made the gate red on a
9528
+ // claim this ticket never touched: a Query preview still has no switcher, since `cellViewModes`
9529
+ // demands `!isQueryPreview` as well. A windowed table is refused for the same reason it always
9530
+ // was - list, kanban and calendar compute over the whole matched set, and a page is not it.
9531
+ const modeWithheld = serverWindowed || embedded || isQueryPreview;
9532
+ const cellViewModes = cellView && !serverWindowed && !isQueryPreview;
9533
+ const modeControl = modeWithheld && !cellViewModes ? undefined : (
9534
  <ModeSwitch
9535
  mode={displayMode}
9536
  onMode={setDisplayMode}
 
10345
  return;
10346
  }
10347
  updateConfig({ ...config, filterConj });
10348
+ if (cellView)
10349
+ onCellFilterChange?.({ conj: filterConj, nodes: config.filters });
10350
  }}
10351
  filtersLocked={activeFiltersLocked}
10352
  sorts={config.sorts}
web/src/customer-grid/MapView.tsx CHANGED
@@ -610,16 +610,18 @@ function rowCoordinates(
610
  row: Row,
611
  coordinateFields?: CoordinateFields,
612
  coordField?: Field,
 
613
  ): { lat: number; lon: number } | null {
 
614
  if (coordinateFields) {
615
  const lat = coord(row[coordinateFields.latitude.key]);
616
  const lon = coord(row[coordinateFields.longitude.key]);
617
- return lat == null || lon == null || !isPlottable(lat, lon) ? null : { lat, lon };
618
  }
619
- if (coordField) return parseLatLon(row[coordField.key]);
620
  const lat = coord(row.lat);
621
  const lon = coord(row.lon);
622
- return lat == null || lon == null || !isPlottable(lat, lon) ? null : { lat, lon };
623
  }
624
 
625
  function numOrNull(v: Row[keyof Row]): number | null {
@@ -657,13 +659,15 @@ function MapViewSurface({
657
  onOpen,
658
  onGeocoded,
659
  onRouteFieldCreated,
660
- routePanelOpen,
661
  allRows,
662
  activeView,
663
  tableKey,
664
  onManagedRouteViewState,
665
  onZoneChanged,
666
  applicationName,
 
 
667
  }: {
668
  /** DISTINCT data rows from the full pipeline, overlay edits layered β€” the
669
  * calendar/kanban contract, verbatim. */
@@ -698,8 +702,8 @@ function MapViewSurface({
698
  *
699
  * β›” THE MAP DELIBERATELY HAS NO WRITER OF ITS OWN. A second path that can put values into cells
700
  * would sit outside every guard the grid's own edit door carries, and this view is the last place
701
- * that should own one. Absent callback = the control does not render at all, so there is no
702
- * arrangement in which a person can run a lookup whose results have nowhere to land.
703
  */
704
  onGeocoded?: (writes: { pid: number; value: string }[]) => void;
705
  onRouteFieldCreated?: (key: string) => void;
@@ -716,6 +720,12 @@ function MapViewSurface({
716
  /** Saved Routing Application identity, shown in the route navigator without changing the
717
  * existing View or its route assets. */
718
  applicationName?: string;
 
 
 
 
 
 
719
  /**
720
  * ⭐⭐ OWNER ITEM 9 β€” THE WHOLE BOOK, so a stop can be added that the VIEW filtered out.
721
  *
@@ -728,6 +738,15 @@ function MapViewSurface({
728
  allRows?: Row[];
729
  }) {
730
  const [hoverPid, setHoverPid] = useState<number | null>(null);
 
 
 
 
 
 
 
 
 
731
  /* R10 β€” READ ON MOUNT, BEFORE THE FIRST FIT, and that is why this is a lazy initializer rather
732
  than an effect. The auto-fit below seeds `view` from the first `fit` it can compute; a restore
733
  that ran afterwards would be overwritten by it, and one that ran just before would still have
@@ -922,10 +941,9 @@ function MapViewSurface({
922
  the close effect then wiped in the same commit. Declared after, and gated on the panel being
923
  OPEN, they can only ever run when the close effect has taken its early return.
924
 
925
- ⚠ WHAT THIS CANNOT DO, and it is worth naming rather than leaving as a mystery: whether the
926
- Routes panel is open at all is `routePanelOpen`, a PROP owned by the host grid. The map
927
- remembers which route and which navigator were open and puts them back the moment the panel
928
- is; it cannot open the panel itself. */
929
  const navigatorRestored = useRef(false);
930
  useEffect(() => {
931
  if (navigatorRestored.current || !routePanelOpen) return;
@@ -1030,6 +1048,9 @@ function MapViewSurface({
1030
  const [geo, setGeo] = useState<{
1031
  busy: boolean; done: number; total: number; found: number; error: string | null;
1032
  }>({ busy: false, done: 0, total: 0, found: 0, error: null });
 
 
 
1033
  const [view, setView] = useState<View | null>(() => restoredMap?.view ?? null);
1034
  /**
1035
  * The selection gesture in flight. Two shapes, never a mode for SELECTING
@@ -1169,7 +1190,7 @@ function MapViewSurface({
1169
  const points = useMemo(() => {
1170
  const out: MapPoint[] = [];
1171
  for (const r of mapRows) {
1172
- const at = rowCoordinates(r, coordinateFields, coordField);
1173
  if (!at) continue;
1174
  const { lat, lon } = at;
1175
  out.push({
@@ -1185,7 +1206,7 @@ function MapViewSurface({
1185
  });
1186
  }
1187
  return out;
1188
- }, [mapRows, field.key, coordinateFields, coordField, colorField, sizeField]);
1189
  const noCoords = mapRows.length - points.length;
1190
 
1191
  /**
@@ -1232,11 +1253,11 @@ function MapViewSurface({
1232
  const out: Record<number, { lat: number; lon: number }> = {};
1233
  for (const row of (allRows?.length ? allRows : mapRows)) {
1234
  if (out[row.pid]) continue;
1235
- const at = rowCoordinates(row, coordinateFields, coordField);
1236
  if (at) out[row.pid] = { lat: at.lat, lon: at.lon };
1237
  }
1238
  return out;
1239
- }, [allRows, mapRows, coordinateFields, coordField]);
1240
 
1241
  const loadZones = useCallback(async () => {
1242
  zoneRequestRef.current.controller?.abort();
@@ -2089,11 +2110,21 @@ function MapViewSurface({
2089
  const mapCanvasMounted = view != null && fit != null;
2090
  const zoneChooserPanelOpen = zones !== null && mapNavigator === "zones" && !zoneEditorOpen;
2091
  const zoneEditorPanelOpen = zones !== null && mapNavigator === "zones" && zoneEditorOpen;
 
 
 
 
2092
  const closeZoneChooser = useCallback(() => setZoneNavigatorOpen(false), []);
2093
  const closeZoneEditor = useCallback(() => {
2094
  setZoneErr(null);
2095
  setZoneEditorOpen(false);
2096
  }, []);
 
 
 
 
 
 
2097
  useEscapeClose(mapCanvasMounted && zoneChooserPanelOpen, closeZoneChooser);
2098
  useEscapeClose(mapCanvasMounted && zoneEditorPanelOpen, closeZoneEditor);
2099
 
@@ -2243,11 +2274,11 @@ function MapViewSurface({
2243
  const located = [] as { pid: number; lat: number; lon: number }[];
2244
  for (const row of (allRows?.length ? allRows : mapRows)) {
2245
  if (!wanted.has(row.pid)) continue;
2246
- const at = rowCoordinates(row, coordinateFields, coordField);
2247
  if (at) located.push({ pid: row.pid, lat: at.lat, lon: at.lon });
2248
  }
2249
  return normalizedRouteMapLinks(activeNamedRoute.visibleStopIds, located, coarsePointer);
2250
- }, [activeNamedRoute, allRows, coarsePointer, coordinateFields, coordField, mapRows]);
2251
  const activeRouteMapsRefusal = activeRouteMaps.missingStopIds.length
2252
  ? `${activeRouteMaps.missingStopIds.length.toLocaleString()} Route stop${activeRouteMaps.missingStopIds.length === 1 ? " has" : "s have"} no map location. Add coordinates before opening Maps links.`
2253
  : activeRouteMaps.refusal;
@@ -2800,7 +2831,7 @@ function MapViewSurface({
2800
 
2801
  const runGeocode = useCallback(async () => {
2802
  const addrKey = coordField?.geocode?.addressField;
2803
- if (!addrKey || !onGeocoded || geocodable.length === 0) return;
2804
  setGeo({ busy: true, done: 0, total: geocodable.length, found: 0, error: null });
2805
  let found = 0;
2806
  try {
@@ -2828,25 +2859,36 @@ function MapViewSurface({
2828
  }));
2829
  return;
2830
  }
2831
- const writes = (body.results || [])
2832
  .filter((r: { found?: boolean }) => r && r.found)
2833
  .map((r: { key: number; lat: number; lon: number }) => ({
2834
- pid: Number(r.key),
2835
- // The cell shape contract C7 fixes, at the precision `googleMapsUrl` already uses so
2836
- // the cell, the pin and the hand-off link agree to the digit.
2837
- value: `${r.lat.toFixed(6)},${r.lon.toFixed(6)}`,
2838
  }));
2839
- found += writes.length;
 
 
 
 
 
 
2840
  // ⭐ HANDED OVER PER BATCH, not at the end. A run over 300 records is minutes long, and
2841
  // a person who navigates away mid-run should keep every coordinate already paid for.
2842
- if (writes.length) onGeocoded(writes);
 
 
 
 
 
 
 
 
2843
  setGeo((g) => ({ ...g, done: Math.min(g.total, i + slice.length), found }));
2844
  }
2845
  setGeo((g) => ({ ...g, busy: false }));
2846
  } catch {
2847
  setGeo((g) => ({ ...g, busy: false, error: "The address lookup could not be reached." }));
2848
  }
2849
- }, [coordField, onGeocoded, geocodable, geoBatch]);
2850
 
2851
  /** The depot has no row, so it uses the address-list form of the same bounded lookup and wait. */
2852
 
@@ -3549,7 +3591,7 @@ function MapViewSurface({
3549
  * longer needed it. Every gate was green: the door scan found the control, `tsc` was clean, and
3550
  * the component rendered. [[reachable-is-not-the-same-as-built]] is this exact shape.
3551
  */
3552
- const geoControl = coordField?.geocode?.addressField && onGeocoded ? (
3553
  <span className="cg-map-geo">
3554
  {geo.busy ? (
3555
  <>
@@ -3568,9 +3610,13 @@ function MapViewSurface({
3568
  type="button"
3569
  className="cg-btn cg-map-geo-cta"
3570
  onClick={() => void runGeocode()}
3571
- title={`Look up ${geocodable.length.toLocaleString()} address${
3572
- geocodable.length === 1 ? "" : "es"
3573
- } and fill ${coordField.label}. Takes ${geoEstimate}.`}
 
 
 
 
3574
  >
3575
  Look up {geocodable.length.toLocaleString()} address
3576
  {geocodable.length === 1 ? "" : "es"} ({geoEstimate})
@@ -3580,6 +3626,7 @@ function MapViewSurface({
3580
  <span className="cg-map-geo-note">
3581
  Located {geo.found.toLocaleString()} of {geo.total.toLocaleString()}
3582
  {geo.found < geo.total && ". The rest had no address on file or could not be matched."}
 
3583
  </span>
3584
  )}
3585
  {geo.error && <span className="cg-cal-nodate">{geo.error}</span>}
@@ -3589,7 +3636,9 @@ function MapViewSurface({
3589
  if (!view || !fit) {
3590
  return (
3591
  <div className={"cg-mode-empty" + (applicationName ? " cg-app-route-surface" : "")}>
3592
- No records with a location to map yet. Set latitude and longitude fields in View schema to plot records.
 
 
3593
  {noCoords > 0 &&
3594
  ` ${noCoords.toLocaleString()} matching record${noCoords === 1 ? "" : "s"} have no location.`}
3595
  {/* The way OUT of the empty state, offered from inside it. Selecting records and looking
@@ -5080,18 +5129,38 @@ export function MapView(props: MapViewProps) {
5080
  const titleKey = String(fieldMap.title ?? "");
5081
  const latitudeKey = String(fieldMap.latitude ?? "");
5082
  const longitudeKey = String(fieldMap.longitude ?? "");
 
5083
  const coordinateFields = latitudeKey && longitudeKey
5084
  ? {
5085
  latitude: { ...props.field, key: latitudeKey, label: "Latitude" },
5086
  longitude: { ...props.field, key: longitudeKey, label: "Longitude" },
5087
  }
5088
  : props.coordinateFields;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5089
  return (
5090
  <MapViewSurface
 
5091
  {...props}
5092
  field={titleKey ? { ...props.field, key: titleKey, label: "Record title" } : props.field}
5093
  coordinateFields={coordinateFields}
 
5094
  applicationName={application.name}
 
 
5095
  />
5096
  );
5097
  }
 
610
  row: Row,
611
  coordinateFields?: CoordinateFields,
612
  coordField?: Field,
613
+ sessionCoordinates?: ReadonlyMap<number, { lat: number; lon: number }>,
614
  ): { lat: number; lon: number } | null {
615
+ const sessionPoint = sessionCoordinates?.get(row.pid) ?? null;
616
  if (coordinateFields) {
617
  const lat = coord(row[coordinateFields.latitude.key]);
618
  const lon = coord(row[coordinateFields.longitude.key]);
619
+ return lat == null || lon == null || !isPlottable(lat, lon) ? sessionPoint : { lat, lon };
620
  }
621
+ if (coordField?.key) return parseLatLon(row[coordField.key]) ?? sessionPoint;
622
  const lat = coord(row.lat);
623
  const lon = coord(row.lon);
624
+ return lat == null || lon == null || !isPlottable(lat, lon) ? sessionPoint : { lat, lon };
625
  }
626
 
627
  function numOrNull(v: Row[keyof Row]): number | null {
 
659
  onOpen,
660
  onGeocoded,
661
  onRouteFieldCreated,
662
+ routePanelOpen: requestedRoutePanelOpen,
663
  allRows,
664
  activeView,
665
  tableKey,
666
  onManagedRouteViewState,
667
  onZoneChanged,
668
  applicationName,
669
+ routeApplication = false,
670
+ geocodeSessionOnly = false,
671
  }: {
672
  /** DISTINCT data rows from the full pipeline, overlay edits layered β€” the
673
  * calendar/kanban contract, verbatim. */
 
702
  *
703
  * β›” THE MAP DELIBERATELY HAS NO WRITER OF ITS OWN. A second path that can put values into cells
704
  * would sit outside every guard the grid's own edit door carries, and this view is the last place
705
+ * that should own one. Absent callback = the control does not render unless a Route Application
706
+ * explicitly keeps its results in this map session, so every lookup still has somewhere to land.
707
  */
708
  onGeocoded?: (writes: { pid: number; value: string }[]) => void;
709
  onRouteFieldCreated?: (key: string) => void;
 
720
  /** Saved Routing Application identity, shown in the route navigator without changing the
721
  * existing View or its route assets. */
722
  applicationName?: string;
723
+ /** Opens the Routes navigator as presentation state for a Routing Application. The host's
724
+ * ordinary route toggle remains authoritative everywhere else. */
725
+ routeApplication?: boolean;
726
+ /** Route templates may map an address without owning a coordinate cell. Successful lookups
727
+ * stay in this mounted map so the Application can plot them without inventing a database field. */
728
+ geocodeSessionOnly?: boolean;
729
  /**
730
  * ⭐⭐ OWNER ITEM 9 β€” THE WHOLE BOOK, so a stop can be added that the VIEW filtered out.
731
  *
 
738
  allRows?: Row[];
739
  }) {
740
  const [hoverPid, setHoverPid] = useState<number | null>(null);
741
+ // A Routing Application opens its navigator without writing the saved View configuration. The
742
+ // host prop still joins the same effective state, so every existing restore effect runs intact.
743
+ const [routeApplicationPanelOpen, setRouteApplicationPanelOpen] = useState(routeApplication);
744
+ // The Application value is a first-paint seed only. Once the host opens Routes, its toggle owns
745
+ // every later transition, so clearing the seed lets the host's next close take effect.
746
+ useEffect(() => {
747
+ if (requestedRoutePanelOpen) setRouteApplicationPanelOpen(false);
748
+ }, [requestedRoutePanelOpen]);
749
+ const routePanelOpen = requestedRoutePanelOpen || (routeApplication && routeApplicationPanelOpen);
750
  /* R10 β€” READ ON MOUNT, BEFORE THE FIRST FIT, and that is why this is a lazy initializer rather
751
  than an effect. The auto-fit below seeds `view` from the first `fit` it can compute; a restore
752
  that ran afterwards would be overwritten by it, and one that ran just before would still have
 
941
  the close effect then wiped in the same commit. Declared after, and gated on the panel being
942
  OPEN, they can only ever run when the close effect has taken its early return.
943
 
944
+ ⚠ `routePanelOpen` is the effective presentation answer: the host's ordinary toggle OR the
945
+ Routing Application's local first-paint seed. Both therefore reach these same restore effects;
946
+ the Application path does not bypass them or write the saved View configuration. */
 
947
  const navigatorRestored = useRef(false);
948
  useEffect(() => {
949
  if (navigatorRestored.current || !routePanelOpen) return;
 
1048
  const [geo, setGeo] = useState<{
1049
  busy: boolean; done: number; total: number; found: number; error: string | null;
1050
  }>({ busy: false, done: 0, total: 0, found: 0, error: null });
1051
+ const [sessionCoordinates, setSessionCoordinates] = useState<
1052
+ ReadonlyMap<number, { lat: number; lon: number }>
1053
+ >(() => new Map());
1054
  const [view, setView] = useState<View | null>(() => restoredMap?.view ?? null);
1055
  /**
1056
  * The selection gesture in flight. Two shapes, never a mode for SELECTING
 
1190
  const points = useMemo(() => {
1191
  const out: MapPoint[] = [];
1192
  for (const r of mapRows) {
1193
+ const at = rowCoordinates(r, coordinateFields, coordField, sessionCoordinates);
1194
  if (!at) continue;
1195
  const { lat, lon } = at;
1196
  out.push({
 
1206
  });
1207
  }
1208
  return out;
1209
+ }, [mapRows, field.key, coordinateFields, coordField, sessionCoordinates, colorField, sizeField]);
1210
  const noCoords = mapRows.length - points.length;
1211
 
1212
  /**
 
1253
  const out: Record<number, { lat: number; lon: number }> = {};
1254
  for (const row of (allRows?.length ? allRows : mapRows)) {
1255
  if (out[row.pid]) continue;
1256
+ const at = rowCoordinates(row, coordinateFields, coordField, sessionCoordinates);
1257
  if (at) out[row.pid] = { lat: at.lat, lon: at.lon };
1258
  }
1259
  return out;
1260
+ }, [allRows, mapRows, coordinateFields, coordField, sessionCoordinates]);
1261
 
1262
  const loadZones = useCallback(async () => {
1263
  zoneRequestRef.current.controller?.abort();
 
2110
  const mapCanvasMounted = view != null && fit != null;
2111
  const zoneChooserPanelOpen = zones !== null && mapNavigator === "zones" && !zoneEditorOpen;
2112
  const zoneEditorPanelOpen = zones !== null && mapNavigator === "zones" && zoneEditorOpen;
2113
+ const closeRouteApplicationNavigator = useCallback(
2114
+ () => setRouteApplicationPanelOpen(false),
2115
+ [],
2116
+ );
2117
  const closeZoneChooser = useCallback(() => setZoneNavigatorOpen(false), []);
2118
  const closeZoneEditor = useCallback(() => {
2119
  setZoneErr(null);
2120
  setZoneEditorOpen(false);
2121
  }, []);
2122
+ // The host already owns Escape for its toggle. An Application-opened navigator needs the same
2123
+ // reversible presentation behavior locally because opening it must never write saved config.
2124
+ useEscapeClose(
2125
+ mapCanvasMounted && routeApplicationPanelOpen && !requestedRoutePanelOpen && mapNavigator === "routes",
2126
+ closeRouteApplicationNavigator,
2127
+ );
2128
  useEscapeClose(mapCanvasMounted && zoneChooserPanelOpen, closeZoneChooser);
2129
  useEscapeClose(mapCanvasMounted && zoneEditorPanelOpen, closeZoneEditor);
2130
 
 
2274
  const located = [] as { pid: number; lat: number; lon: number }[];
2275
  for (const row of (allRows?.length ? allRows : mapRows)) {
2276
  if (!wanted.has(row.pid)) continue;
2277
+ const at = rowCoordinates(row, coordinateFields, coordField, sessionCoordinates);
2278
  if (at) located.push({ pid: row.pid, lat: at.lat, lon: at.lon });
2279
  }
2280
  return normalizedRouteMapLinks(activeNamedRoute.visibleStopIds, located, coarsePointer);
2281
+ }, [activeNamedRoute, allRows, coarsePointer, coordinateFields, coordField, mapRows, sessionCoordinates]);
2282
  const activeRouteMapsRefusal = activeRouteMaps.missingStopIds.length
2283
  ? `${activeRouteMaps.missingStopIds.length.toLocaleString()} Route stop${activeRouteMaps.missingStopIds.length === 1 ? " has" : "s have"} no map location. Add coordinates before opening Maps links.`
2284
  : activeRouteMaps.refusal;
 
2831
 
2832
  const runGeocode = useCallback(async () => {
2833
  const addrKey = coordField?.geocode?.addressField;
2834
+ if (!addrKey || (!onGeocoded && !geocodeSessionOnly) || geocodable.length === 0) return;
2835
  setGeo({ busy: true, done: 0, total: geocodable.length, found: 0, error: null });
2836
  let found = 0;
2837
  try {
 
2859
  }));
2860
  return;
2861
  }
2862
+ const located = (body.results || [])
2863
  .filter((r: { found?: boolean }) => r && r.found)
2864
  .map((r: { key: number; lat: number; lon: number }) => ({
2865
+ pid: Number(r.key), lat: r.lat, lon: r.lon,
 
 
 
2866
  }));
2867
+ const writes = located.map((r: { pid: number; lat: number; lon: number }) => ({
2868
+ pid: r.pid,
2869
+ // The cell shape contract C7 fixes, at the precision `googleMapsUrl` already uses so
2870
+ // the cell, the pin and the hand-off link agree to the digit.
2871
+ value: `${r.lat.toFixed(6)},${r.lon.toFixed(6)}`,
2872
+ }));
2873
+ found += located.length;
2874
  // ⭐ HANDED OVER PER BATCH, not at the end. A run over 300 records is minutes long, and
2875
  // a person who navigates away mid-run should keep every coordinate already paid for.
2876
+ if (located.length && geocodeSessionOnly) {
2877
+ setSessionCoordinates((current) => {
2878
+ const next = new Map(current);
2879
+ for (const point of located) next.set(point.pid, { lat: point.lat, lon: point.lon });
2880
+ return next;
2881
+ });
2882
+ } else if (writes.length) {
2883
+ onGeocoded?.(writes);
2884
+ }
2885
  setGeo((g) => ({ ...g, done: Math.min(g.total, i + slice.length), found }));
2886
  }
2887
  setGeo((g) => ({ ...g, busy: false }));
2888
  } catch {
2889
  setGeo((g) => ({ ...g, busy: false, error: "The address lookup could not be reached." }));
2890
  }
2891
+ }, [coordField, onGeocoded, geocodable, geoBatch, geocodeSessionOnly]);
2892
 
2893
  /** The depot has no row, so it uses the address-list form of the same bounded lookup and wait. */
2894
 
 
3591
  * longer needed it. Every gate was green: the door scan found the control, `tsc` was clean, and
3592
  * the component rendered. [[reachable-is-not-the-same-as-built]] is this exact shape.
3593
  */
3594
+ const geoControl = coordField?.geocode?.addressField && (onGeocoded || geocodeSessionOnly) ? (
3595
  <span className="cg-map-geo">
3596
  {geo.busy ? (
3597
  <>
 
3610
  type="button"
3611
  className="cg-btn cg-map-geo-cta"
3612
  onClick={() => void runGeocode()}
3613
+ title={geocodeSessionOnly
3614
+ ? `Look up ${geocodable.length.toLocaleString()} address${
3615
+ geocodable.length === 1 ? "" : "es"
3616
+ } and place the records on this map. Takes ${geoEstimate}.`
3617
+ : `Look up ${geocodable.length.toLocaleString()} address${
3618
+ geocodable.length === 1 ? "" : "es"
3619
+ } and fill ${coordField.label}. Takes ${geoEstimate}.`}
3620
  >
3621
  Look up {geocodable.length.toLocaleString()} address
3622
  {geocodable.length === 1 ? "" : "es"} ({geoEstimate})
 
3626
  <span className="cg-map-geo-note">
3627
  Located {geo.found.toLocaleString()} of {geo.total.toLocaleString()}
3628
  {geo.found < geo.total && ". The rest had no address on file or could not be matched."}
3629
+ {geocodeSessionOnly && geo.found > 0 && " These locations stay on this map for this session."}
3630
  </span>
3631
  )}
3632
  {geo.error && <span className="cg-cal-nodate">{geo.error}</span>}
 
3636
  if (!view || !fit) {
3637
  return (
3638
  <div className={"cg-mode-empty" + (applicationName ? " cg-app-route-surface" : "")}>
3639
+ {geocodeSessionOnly
3640
+ ? "No records with a location to map yet."
3641
+ : "No records with a location to map yet. Set latitude and longitude fields in View schema to plot records."}
3642
  {noCoords > 0 &&
3643
  ` ${noCoords.toLocaleString()} matching record${noCoords === 1 ? "" : "s"} have no location.`}
3644
  {/* The way OUT of the empty state, offered from inside it. Selecting records and looking
 
5129
  const titleKey = String(fieldMap.title ?? "");
5130
  const latitudeKey = String(fieldMap.latitude ?? "");
5131
  const longitudeKey = String(fieldMap.longitude ?? "");
5132
+ const addressKey = String(fieldMap.address ?? "");
5133
  const coordinateFields = latitudeKey && longitudeKey
5134
  ? {
5135
  latitude: { ...props.field, key: latitudeKey, label: "Latitude" },
5136
  longitude: { ...props.field, key: longitudeKey, label: "Longitude" },
5137
  }
5138
  : props.coordinateFields;
5139
+ // The general geocoder reads its address contract from coordField. An empty key carries that
5140
+ // contract without pretending an address-only Application owns a coordinate column.
5141
+ const routeCoordField = addressKey
5142
+ ? {
5143
+ ...(props.coordField ?? props.field),
5144
+ key: props.coordField?.key ?? "",
5145
+ label: props.coordField?.label ?? "Route location",
5146
+ geocode: {
5147
+ addressField: addressKey,
5148
+ ...(props.coordField?.geocode?.country
5149
+ ? { country: props.coordField.geocode.country }
5150
+ : {}),
5151
+ },
5152
+ }
5153
+ : props.coordField;
5154
  return (
5155
  <MapViewSurface
5156
+ key={application.id}
5157
  {...props}
5158
  field={titleKey ? { ...props.field, key: titleKey, label: "Record title" } : props.field}
5159
  coordinateFields={coordinateFields}
5160
+ coordField={routeCoordField}
5161
  applicationName={application.name}
5162
+ geocodeSessionOnly={Boolean(addressKey)}
5163
+ routeApplication
5164
  />
5165
  );
5166
  }
web/src/customer-grid/SwipeView.tsx CHANGED
@@ -1,586 +1,586 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / SwipeView.tsx
3
- // ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) β€” the SWIPE deck.
4
- //
5
- // One record at a time, decided left or right into two options of ONE
6
- // single-select. R2 fixes the shape and it is narrow on purpose:
7
- // Β· SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.
8
- // Β· the deck holds only the records whose bound field is EMPTY β€” a record
9
- // that already has a value has been decided, and re-asking is not triage.
10
- // Β· a swipe writes through the NORMAL cell door (`onSwipe`, which the host
11
- // maps to the same `patchAndRecord` a kanban card move uses), so undo,
12
- // echo-suppression and the permission wall all hold without being
13
- // re-implemented here.
14
- //
15
- // Honesty rules carried from the other modes:
16
- // Β· nothing is silently hidden β€” the deck states what is left, and the
17
- // empty state names the bound field rather than saying "all done".
18
- // Β· a lost binding is SHOWN, never repaired by guessing. `_clean_display`
19
- // validates that `fieldKey` names a field the table HAS and stops there;
20
- // it cannot know the field is still a select, or that the two options are
21
- // still in its vocabulary (its docstring draws that line explicitly). So
22
- // those three losses land here, and each one says what happened and
23
- // re-opens the picker β€” the `viewModes.tsx:190-194` rule, which exists
24
- // because the wave-7 trap was a picker silently falling back to its first
25
- // option.
26
- // ---------------------------------------------------------------------------
27
-
28
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
- // ⭐⭐ W41-T48 (owner instruction 22) β€” opening a record from the swipe deck folds the shell's
30
- // navigation rail exactly as a grid cell click does. Guard rationale: `MapView.tsx:2755`.
31
- import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
32
- import { choiceOptions } from "./types";
33
- import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
34
- // ⚠ `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is
35
- // loaded here) β€” the same import `RecordComments` takes for the same prop.
36
- import type { SurfaceScope } from "./apiBridge";
37
- import RecordComments from "./RecordComments";
38
- import { Documents } from "./Documents";
39
- import { formatDisplay } from "./cells";
40
- import { actionHref } from "./display";
41
- import { optionTint } from "./choiceColors";
42
- import { ModeIcon } from "./icons";
43
- // ⭐ W29-T73 β€” the line its three siblings all have, and the one this file shipped without.
44
- // `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered
45
- // unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right β€”
46
- // a partially-styled surface reads as a design choice, which is why nobody reported it and no
47
- // gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).
48
- import "./SwipeView.css";
49
-
50
- export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;
51
-
52
- /** The three ways a stored binding can rot that the host cannot see (see the header note). */
53
- type BindingFault =
54
- | { kind: "unbound" }
55
- | { kind: "field-gone"; fieldKey: string }
56
- | { kind: "not-select"; field: Field }
57
- | { kind: "option-gone"; field: Field; missing: string[] };
58
-
59
- function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map<string, Field>):
60
- { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {
61
- if (!spec) return { ok: false, fault: { kind: "unbound" } };
62
- const field = fieldByKey.get(spec.fieldKey);
63
- if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };
64
- // R2 β€” SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,
65
- // so "write this option" would mean append-or-replace, and a triage gesture that sometimes
66
- // adds and sometimes overwrites is two gestures wearing one button.
67
- if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };
68
- const options = choiceOptions(field);
69
- const has = new Set(options.map((o) => o.toLowerCase()));
70
- const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));
71
- if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };
72
- return { ok: true, field, spec };
73
- }
74
-
75
- /** The bound cell is EMPTY β€” the one predicate that decides deck membership (R2). */
76
- const isUndecided = (row: Row, key: string): boolean =>
77
- String(row[key] ?? "").trim() === "";
78
-
79
- export function SwipeView({
80
- rows,
81
- fields,
82
- fieldByKey,
83
- spec,
84
- cardKeys,
85
- detailKeys,
86
- scope,
87
- viewer,
88
- docs,
89
- docPayload,
90
- onDocAdd,
91
- onDocFetch,
92
- onDocDelete,
93
- titleKey,
94
- canWrite,
95
- readOnlyReason,
96
- canBind,
97
- onSpec,
98
- onSwipe,
99
- onOpen,
100
- }: {
101
- /** DISTINCT data rows from the full pipeline, overlay edits layered β€” the kanban's contract.
102
- * The deck re-derives from these, so a written record leaves it as soon as the optimistic
103
- * patch lands; there is no local cursor to drift out of step with the data. */
104
- rows: Row[];
105
- /** Every field, for the picker's field list. */
106
- fields: Field[];
107
- fieldByKey: Map<string, Field>;
108
- /** The stored binding, or undefined for a deck nobody has configured yet. */
109
- spec: SwipeSpec | undefined;
110
- /** The handful of visible fields the card lists under its title. */
111
- cardKeys: string[];
112
- titleKey: string;
113
- /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */
114
- canWrite: boolean;
115
- /** Stated when the deck cannot be decided β€” permissions, or a computed column. */
116
- readOnlyReason: string | null;
117
- /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the
118
- * view-editing permission and NOT `canWrite` β€” conflating the two is
119
- * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does
120
- * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */
121
- canBind: boolean;
122
- /** `undefined` DELETES the binding β€” absent is the honest unconfigured state, and storing a
123
- * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */
124
- onSpec: (next: SwipeSpec | undefined) => void;
125
- onSwipe: (pid: number, value: string) => void;
126
- onOpen: (pid: number) => void;
127
- /**
128
- * ⭐⭐ WAVE-29 T26 (owner R9) β€” WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.
129
- *
130
- * R9: *"the swipe CARD itself renders the record detail inline β€” fields, comments and
131
- * attachments β€” so a reviewer decides without leaving the deck."* Everything below is that,
132
- * and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply
133
- * different amounts. A card must render with none of them rather than throw β€” the standalone
134
- * embed has no `scope`, and a deployment with no document storage serves no handlers.
135
- */
136
- /** Every field the VIEW shows, in its order β€” not the three-key card summary. */
137
- detailKeys?: string[];
138
- /** The surface these records live on. Comments are keyed by it; absent β‡’ no comments section,
139
- * which is the pre-existing precondition `RecordDetail` already carries. */
140
- scope?: SurfaceScope;
141
- viewer?: Viewer;
142
- /** This record's attachments, and the plumbing. Handlers absent β‡’ the section is not rendered
143
- * at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app
144
- * cannot keep). */
145
- /** Keyed by pid, because a deck shows many records β€” `RecordDetail` takes ONE record's list
146
- * and that shape cannot serve a deck. */
147
- docs?: Record<string, CustomerDoc[]>;
148
- docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };
149
- /** ⚠ EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE
150
- * open record. A deck paints many records at once, so a handler bound to a single pid would
151
- * attach every reviewer's upload to whichever card happened to be open. */
152
- onDocAdd?: (
153
- pid: number,
154
- file: { name: string; mime: string; size: number; data_b64: string }
155
- ) => void;
156
- onDocFetch?: (pid: number, docId: string) => void;
157
- onDocDelete?: (pid: number, docId: string) => void;
158
- }) {
159
- // "Later" β€” session-only, never stored. A deck with no way past a record you cannot decide
160
- // blocks on that record forever, so this is navigation WITHIN the deck rather than a third
161
- // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty
162
- // state rather than quietly shrinking the deck (rule 8b).
163
- const [later, setLater] = useState<Set<number>>(new Set());
164
- const deckRef = useRef<HTMLDivElement>(null);
165
-
166
- const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);
167
- const boundKey = binding.ok ? binding.field.key : null;
168
-
169
- const undecided = useMemo(
170
- () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),
171
- [rows, boundKey]
172
- );
173
- const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);
174
- const card = deck[0];
175
-
176
- // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever β€”
177
- // otherwise the disclosed skip count drifts away from what is actually on the deck.
178
- useEffect(() => {
179
- setLater((prev) => {
180
- if (prev.size === 0) return prev;
181
- const live = new Set(undecided.map((r) => r.pid));
182
- const next = new Set([...prev].filter((pid) => live.has(pid)));
183
- return next.size === prev.size ? prev : next;
184
- });
185
- }, [undecided]);
186
-
187
- const decide = useCallback(
188
- (value: string) => {
189
- if (!card || !canWrite) return;
190
- onSwipe(card.pid, value);
191
- },
192
- [card, canWrite, onSwipe]
193
- );
194
-
195
- // οΏ½οΏ½ / β†’ decide, and they are the SAME two actions the buttons are rather than a second code
196
- // path: the whole point of the mode is that one hand can clear a queue.
197
- useEffect(() => {
198
- if (!binding.ok || !canWrite || !card) return;
199
- const onKey = (e: KeyboardEvent) => {
200
- if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
201
- const el = document.activeElement as HTMLElement | null;
202
- // Never steal an arrow key from a text field or a native control the user is inside.
203
- if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))
204
- return;
205
- if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;
206
- e.preventDefault();
207
- decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);
208
- };
209
- window.addEventListener("keydown", onKey);
210
- return () => window.removeEventListener("keydown", onKey);
211
- }, [binding, canWrite, card, decide]);
212
-
213
- if (!binding.ok) {
214
- return (
215
- <div className="cg-swipe" ref={deckRef}>
216
- <SwipeBinder
217
- fault={binding.fault}
218
- fields={fields}
219
- fieldByKey={fieldByKey}
220
- spec={spec}
221
- canBind={canBind}
222
- onSpec={onSpec}
223
- />
224
- </div>
225
- );
226
- }
227
-
228
- const { field } = binding;
229
- const leftTint = optionTint(field, binding.spec.leftOption);
230
- const rightTint = optionTint(field, binding.spec.rightOption);
231
-
232
- return (
233
- <div className="cg-swipe" ref={deckRef} tabIndex={-1}>
234
- <div className="cg-swipe-bar">
235
- <span className="cg-swipe-bound">
236
- <ModeIcon mode="swipe" />
237
- Sorting into <strong>{field.label}</strong>
238
- </span>
239
- <span className="cg-swipe-left">
240
- {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort
241
- </span>
242
- {canBind && (
243
- <button
244
- type="button"
245
- className="cg-link-btn"
246
- onClick={() => onSpec(undefined)}
247
- title="Choose a different field or different options for this deck"
248
- >
249
- Change
250
- </button>
251
- )}
252
- </div>
253
- {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
254
- {card ? (
255
- <div className="cg-swipe-deck">
256
- <button
257
- type="button"
258
- className="cg-swipe-side cg-swipe-side--left"
259
- disabled={!canWrite}
260
- style={leftTint ? { background: leftTint.bg, color: leftTint.fg } : undefined}
261
- onClick={() => decide(binding.spec.leftOption)}
262
- title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}
263
- >
264
- <span aria-hidden className="cg-swipe-arrow">
265
- <svg width="16" height="16" viewBox="0 0 16 16">
266
- <path
267
- d="M11 3.2 6.2 8l4.8 4.8"
268
- fill="none"
269
- stroke="currentColor"
270
- strokeWidth="1.6"
271
- strokeLinecap="round"
272
- strokeLinejoin="round"
273
- />
274
- </svg>
275
- </span>
276
- {binding.spec.leftOption}
277
- </button>
278
- <article
279
- className="cg-swipe-card"
280
- role="button"
281
- tabIndex={0}
282
- onClick={(e) => {
283
- // ⭐ W41-T48 β€” the card IS the deck's record open, so it folds the rail.
284
- // ⚠ Nothing that is NOT an open can reach this line: every control inside the
285
- // card (a url cell, the comments box, the document tray) already stops its own
286
- // click, and the left/right decision buttons are siblings of the card, not
287
- // children of it. The deck also has no pointer drag to disambiguate β€” its swipe
288
- // is the two buttons and the arrow keys, neither of which opens anything.
289
- // ⚠ `<article role="button">`, not a native button, so a keyboard activation
290
- // never arrives here as a synthetic click; the keydown path below is the whole
291
- // keyboard story and the two cannot both fire for one gesture.
292
- if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT);
293
- onOpen(card.pid);
294
- }}
295
- onKeyDown={(e) => {
296
- if (e.key !== "Enter" && e.key !== " ") return;
297
- e.preventDefault();
298
- // W41-T48 β€” `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space
299
- // auto-repeats keydown, and every one of those repeats is the SAME gesture.
300
- if (!e.repeat) signal(NAV_MINIMIZE_EVENT);
301
- onOpen(card.pid);
302
- }}
303
- >
304
- <h3 className="cg-swipe-title">{String(card[titleKey] ?? "")}</h3>
305
- <div className="cg-swipe-cells">
306
- {/* ⭐ WAVE-29 T26 (R9) β€” the RECORD's visible fields, not the three-key summary the
307
- kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not
308
- been widened yet renders exactly what it rendered before. */}
309
- {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {
310
- const f = fieldByKey.get(k);
311
- if (!f) return null;
312
- const text = formatDisplay(f, card[k]);
313
- if (!text) return null;
314
- // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one
315
- // scheme guard β€” and every gesture that reaches it must be stopped from also
316
- // reaching the card, which is a button (the kanban card's note, same trap).
317
- const href = actionHref(f, card[k]);
318
- return (
319
- <div key={k} className="cg-swipe-cell">
320
- <span className="cg-lv-k">{f.label}</span>
321
- {href ? (
322
- <a
323
- className="cg-lv-v"
324
- href={href}
325
- target="_blank"
326
- rel="noopener noreferrer"
327
- title={text}
328
- onClick={(e) => e.stopPropagation()}
329
- onKeyDown={(e) => e.stopPropagation()}
330
- >
331
- {text}
332
- </a>
333
- ) : (
334
- <span className="cg-lv-v">{text}</span>
335
- )}
336
- </div>
337
- );
338
- })}
339
- </div>
340
- {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"`
341
- that opens the record, and a click on a comment box or an upload control must not
342
- also open the modal it exists to make unnecessary (the kanban card's link trap,
343
- one surface over). */}
344
- {onDocAdd && onDocFetch && onDocDelete && (
345
- <div
346
- className="cg-swipe-docs"
347
- onClick={(e) => e.stopPropagation()}
348
- onKeyDown={(e) => e.stopPropagation()}
349
- role="presentation"
350
- >
351
- <Documents
352
- pid={Number(card.pid)}
353
- docs={docs?.[String(card.pid)] ?? []}
354
- docPayload={docPayload}
355
- onAdd={(file) => onDocAdd(card.pid, file)}
356
- onFetch={(docId) => onDocFetch(card.pid, docId)}
357
- onDelete={(docId) => onDocDelete(card.pid, docId)}
358
- />
359
- </div>
360
- )}
361
- {scope != null && (
362
- <div
363
- className="cg-swipe-comments"
364
- onClick={(e) => e.stopPropagation()}
365
- onKeyDown={(e) => e.stopPropagation()}
366
- role="presentation"
367
- >
368
- {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React
369
- reuses the mounted instance across a card change and paints one record's
370
- comments under another's name until the fetch returns. */}
371
- <RecordComments
372
- key={`${scope}:${Number(card.pid)}`}
373
- scope={scope}
374
- pid={Number(card.pid)}
375
- viewer={viewer}
376
- />
377
- </div>
378
- )}
379
- {canWrite && (
380
- <button
381
- type="button"
382
- className="cg-link-btn cg-swipe-later"
383
- onClick={(e) => {
384
- e.stopPropagation();
385
- setLater((prev) => new Set(prev).add(card.pid));
386
- }}
387
- >
388
- Decide later
389
- </button>
390
- )}
391
- </article>
392
- <button
393
- type="button"
394
- className="cg-swipe-side cg-swipe-side--right"
395
- disabled={!canWrite}
396
- style={rightTint ? { background: rightTint.bg, color: rightTint.fg } : undefined}
397
- onClick={() => decide(binding.spec.rightOption)}
398
- title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}
399
- >
400
- {binding.spec.rightOption}
401
- <span aria-hidden className="cg-swipe-arrow">
402
- <svg width="16" height="16" viewBox="0 0 16 16">
403
- <path
404
- d="M5 3.2 9.8 8 5 12.8"
405
- fill="none"
406
- stroke="currentColor"
407
- strokeWidth="1.6"
408
- strokeLinecap="round"
409
- strokeLinejoin="round"
410
- />
411
- </svg>
412
- </span>
413
- </button>
414
- </div>
415
- ) : (
416
- // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous
417
- // between "the deck is finished" and "the filter hid everything", and the two want
418
- // different next actions. `later` is disclosed rather than quietly subtracted.
419
- <div className="cg-mode-empty cg-swipe-empty">
420
- {later.size > 0 ? (
421
- <>
422
- <p>
423
- {later.size.toLocaleString()}{" "}
424
- {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else
425
- in this view is missing a <strong>{field.label}</strong>.
426
- </p>
427
- <button type="button" className="cg-btn" onClick={() => setLater(new Set())}>
428
- Bring them back
429
- </button>
430
- </>
431
- ) : (
432
- <p>
433
- Every record in this view already has a <strong>{field.label}</strong>. Widen the
434
- view's filters to sort more.
435
- </p>
436
- )}
437
- </div>
438
- )}
439
- </div>
440
- );
441
- }
442
-
443
- /**
444
- * The binding picker: field + two options. It is also the surface every LOST binding lands on,
445
- * with the loss stated above it β€” one place that answers "what is this deck for", rather than an
446
- * error screen beside a separate setup screen.
447
- */
448
- function SwipeBinder({
449
- fault,
450
- fields,
451
- fieldByKey,
452
- spec,
453
- canBind,
454
- onSpec,
455
- }: {
456
- fault: BindingFault;
457
- fields: Field[];
458
- fieldByKey: Map<string, Field>;
459
- spec: SwipeSpec | undefined;
460
- canBind: boolean;
461
- onSpec: (next: SwipeSpec | undefined) => void;
462
- }) {
463
- const selects = useMemo(
464
- () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),
465
- [fields]
466
- );
467
- const [fieldKey, setFieldKey] = useState<string>(() => {
468
- if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;
469
- return selects[0]?.key ?? "";
470
- });
471
- const chosen = fieldByKey.get(fieldKey);
472
- const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);
473
- const [left, setLeft] = useState<string>("");
474
- const [right, setRight] = useState<string>("");
475
-
476
- // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's
477
- // pick survives re-renders, and reset whenever the field changes β€” carrying an option from the
478
- // previous field would offer a value the new field cannot hold.
479
- useEffect(() => {
480
- setLeft(options[0] ?? "");
481
- setRight(options.find((o) => o !== options[0]) ?? "");
482
- }, [options]);
483
-
484
- const message = ((): string => {
485
- switch (fault.kind) {
486
- case "field-gone":
487
- return "The field this deck sorted into has been deleted. Pick another one.";
488
- case "not-select":
489
- return `β€œ${fault.field.label}” is no longer a single-select, so it has no options to`
490
- + " sort into. Pick another field.";
491
- case "option-gone":
492
- return `${fault.missing.map((m) => `β€œ${m}”`).join(" and ")} ${
493
- fault.missing.length === 1 ? "is" : "are"
494
- } no longer ${fault.missing.length === 1 ? "an option" : "options"} on β€œ${
495
- fault.field.label
496
- }”. Pick the sides again.`;
497
- default:
498
- return "Sort records one at a time into two options of a single-select field.";
499
- }
500
- })();
501
-
502
- if (!canBind) {
503
- return (
504
- <div className="cg-mode-empty">
505
- <p>{message}</p>
506
- <p>Its creator or an admin can set this view up.</p>
507
- </div>
508
- );
509
- }
510
- if (selects.length === 0) {
511
- // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the
512
- // requirement is what turns a dead end into a next action.
513
- return (
514
- <div className="cg-mode-empty">
515
- <p>
516
- A swipe deck sorts into a single-select field with at least two options. This database
517
- does not have one yet β€” add a single-select column, then come back.
518
- </p>
519
- </div>
520
- );
521
- }
522
- const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();
523
- return (
524
- <div className="cg-swipe-setup">
525
- <p className="cg-swipe-setup-note">{message}</p>
526
- <label className="cg-swipe-setup-row">
527
- <span>Sort into</span>
528
- <select
529
- className="cg-select"
530
- value={fieldKey}
531
- onChange={(e) => setFieldKey(e.target.value)}
532
- >
533
- {/* Every option carries an explicit `value`: a <select> whose value names nothing
534
- renders its FIRST option and reports a choice the user never made
535
- ([[cg-condition-builder-items]]). */}
536
- {selects.map((f) => (
537
- <option key={f.key} value={f.key}>
538
- {f.label}
539
- </option>
540
- ))}
541
- </select>
542
- </label>
543
- <div className="cg-swipe-setup-sides">
544
- <label className="cg-swipe-setup-row">
545
- <span>Swipe left</span>
546
- <select className="cg-select" value={left} onChange={(e) => setLeft(e.target.value)}>
547
- {options.map((o) => (
548
- <option key={o} value={o}>
549
- {o}
550
- </option>
551
- ))}
552
- </select>
553
- </label>
554
- <label className="cg-swipe-setup-row">
555
- <span>Swipe right</span>
556
- <select className="cg-select" value={right} onChange={(e) => setRight(e.target.value)}>
557
- {options.map((o) => (
558
- <option key={o} value={o}>
559
- {o}
560
- </option>
561
- ))}
562
- </select>
563
- </label>
564
- </div>
565
- {!ready && left && right && (
566
- // Stated, not silently refused: both engines DROP a binding whose sides are the same
567
- // option, so a Save that looked like it worked would simply not persist.
568
- <p className="cg-swipe-setup-warn">
569
- The two sides must be different options β€” otherwise both gestures do the same thing.
570
- </p>
571
- )}
572
- <button
573
- type="button"
574
- className="cg-btn cg-btn--primary"
575
- disabled={!ready}
576
- onClick={() =>
577
- chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })
578
- }
579
- >
580
- Start sorting
581
- </button>
582
- </div>
583
- );
584
- }
585
-
586
- export default SwipeView;
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / SwipeView.tsx
3
+ // ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) β€” the SWIPE deck.
4
+ //
5
+ // One record at a time, decided left or right into two options of ONE
6
+ // single-select. R2 fixes the shape and it is narrow on purpose:
7
+ // Β· SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.
8
+ // Β· the deck holds only the records whose bound field is EMPTY β€” a record
9
+ // that already has a value has been decided, and re-asking is not triage.
10
+ // Β· a swipe writes through the NORMAL cell door (`onSwipe`, which the host
11
+ // maps to the same `patchAndRecord` a kanban card move uses), so undo,
12
+ // echo-suppression and the permission wall all hold without being
13
+ // re-implemented here.
14
+ //
15
+ // Honesty rules carried from the other modes:
16
+ // Β· nothing is silently hidden β€” the deck states what is left, and the
17
+ // empty state names the bound field rather than saying "all done".
18
+ // Β· a lost binding is SHOWN, never repaired by guessing. `_clean_display`
19
+ // validates that `fieldKey` names a field the table HAS and stops there;
20
+ // it cannot know the field is still a select, or that the two options are
21
+ // still in its vocabulary (its docstring draws that line explicitly). So
22
+ // those three losses land here, and each one says what happened and
23
+ // re-opens the picker β€” the `viewModes.tsx:190-194` rule, which exists
24
+ // because the wave-7 trap was a picker silently falling back to its first
25
+ // option.
26
+ // ---------------------------------------------------------------------------
27
+
28
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
+ // ⭐⭐ W41-T48 (owner instruction 22) β€” opening a record from the swipe deck folds the shell's
30
+ // navigation rail exactly as a grid cell click does. Guard rationale: `MapView.tsx:2755`.
31
+ import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
32
+ import { choiceOptions } from "./types";
33
+ import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
34
+ // ⚠ `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is
35
+ // loaded here) β€” the same import `RecordComments` takes for the same prop.
36
+ import type { SurfaceScope } from "./apiBridge";
37
+ import RecordComments from "./RecordComments";
38
+ import { Documents } from "./Documents";
39
+ import { formatDisplay } from "./cells";
40
+ import { actionHref } from "./display";
41
+ import { optionTint } from "./choiceColors";
42
+ import { ModeIcon } from "./icons";
43
+ // ⭐ W29-T73 β€” the line its three siblings all have, and the one this file shipped without.
44
+ // `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered
45
+ // unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right β€”
46
+ // a partially-styled surface reads as a design choice, which is why nobody reported it and no
47
+ // gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).
48
+ import "./SwipeView.css";
49
+
50
+ export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;
51
+
52
+ /** The three ways a stored binding can rot that the host cannot see (see the header note). */
53
+ type BindingFault =
54
+ | { kind: "unbound" }
55
+ | { kind: "field-gone"; fieldKey: string }
56
+ | { kind: "not-select"; field: Field }
57
+ | { kind: "option-gone"; field: Field; missing: string[] };
58
+
59
+ function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map<string, Field>):
60
+ { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {
61
+ if (!spec) return { ok: false, fault: { kind: "unbound" } };
62
+ const field = fieldByKey.get(spec.fieldKey);
63
+ if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };
64
+ // R2 β€” SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,
65
+ // so "write this option" would mean append-or-replace, and a triage gesture that sometimes
66
+ // adds and sometimes overwrites is two gestures wearing one button.
67
+ if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };
68
+ const options = choiceOptions(field);
69
+ const has = new Set(options.map((o) => o.toLowerCase()));
70
+ const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));
71
+ if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };
72
+ return { ok: true, field, spec };
73
+ }
74
+
75
+ /** The bound cell is EMPTY β€” the one predicate that decides deck membership (R2). */
76
+ const isUndecided = (row: Row, key: string): boolean =>
77
+ String(row[key] ?? "").trim() === "";
78
+
79
+ export function SwipeView({
80
+ rows,
81
+ fields,
82
+ fieldByKey,
83
+ spec,
84
+ cardKeys,
85
+ detailKeys,
86
+ scope,
87
+ viewer,
88
+ docs,
89
+ docPayload,
90
+ onDocAdd,
91
+ onDocFetch,
92
+ onDocDelete,
93
+ titleKey,
94
+ canWrite,
95
+ readOnlyReason,
96
+ canBind,
97
+ onSpec,
98
+ onSwipe,
99
+ onOpen,
100
+ }: {
101
+ /** DISTINCT data rows from the full pipeline, overlay edits layered β€” the kanban's contract.
102
+ * The deck re-derives from these, so a written record leaves it as soon as the optimistic
103
+ * patch lands; there is no local cursor to drift out of step with the data. */
104
+ rows: Row[];
105
+ /** Every field, for the picker's field list. */
106
+ fields: Field[];
107
+ fieldByKey: Map<string, Field>;
108
+ /** The stored binding, or undefined for a deck nobody has configured yet. */
109
+ spec: SwipeSpec | undefined;
110
+ /** The handful of visible fields the card lists under its title. */
111
+ cardKeys: string[];
112
+ titleKey: string;
113
+ /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */
114
+ canWrite: boolean;
115
+ /** Stated when the deck cannot be decided β€” permissions, or a computed column. */
116
+ readOnlyReason: string | null;
117
+ /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the
118
+ * view-editing permission and NOT `canWrite` β€” conflating the two is
119
+ * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does
120
+ * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */
121
+ canBind: boolean;
122
+ /** `undefined` DELETES the binding β€” absent is the honest unconfigured state, and storing a
123
+ * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */
124
+ onSpec: (next: SwipeSpec | undefined) => void;
125
+ onSwipe: (pid: number, value: string) => void;
126
+ onOpen: (pid: number) => void;
127
+ /**
128
+ * ⭐⭐ WAVE-29 T26 (owner R9) β€” WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.
129
+ *
130
+ * R9: *"the swipe CARD itself renders the record detail inline β€” fields, comments and
131
+ * attachments β€” so a reviewer decides without leaving the deck."* Everything below is that,
132
+ * and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply
133
+ * different amounts. A card must render with none of them rather than throw β€” the standalone
134
+ * embed has no `scope`, and a deployment with no document storage serves no handlers.
135
+ */
136
+ /** Every field the VIEW shows, in its order β€” not the three-key card summary. */
137
+ detailKeys?: string[];
138
+ /** The surface these records live on. Comments are keyed by it; absent β‡’ no comments section,
139
+ * which is the pre-existing precondition `RecordDetail` already carries. */
140
+ scope?: SurfaceScope;
141
+ viewer?: Viewer;
142
+ /** This record's attachments, and the plumbing. Handlers absent β‡’ the section is not rendered
143
+ * at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app
144
+ * cannot keep). */
145
+ /** Keyed by pid, because a deck shows many records β€” `RecordDetail` takes ONE record's list
146
+ * and that shape cannot serve a deck. */
147
+ docs?: Record<string, CustomerDoc[]>;
148
+ docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };
149
+ /** ⚠ EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE
150
+ * open record. A deck paints many records at once, so a handler bound to a single pid would
151
+ * attach every reviewer's upload to whichever card happened to be open. */
152
+ onDocAdd?: (
153
+ pid: number,
154
+ file: { name: string; mime: string; size: number; data_b64: string }
155
+ ) => void;
156
+ onDocFetch?: (pid: number, docId: string) => void;
157
+ onDocDelete?: (pid: number, docId: string) => void;
158
+ }) {
159
+ // "Later" β€” session-only, never stored. A deck with no way past a record you cannot decide
160
+ // blocks on that record forever, so this is navigation WITHIN the deck rather than a third
161
+ // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty
162
+ // state rather than quietly shrinking the deck (rule 8b).
163
+ const [later, setLater] = useState<Set<number>>(new Set());
164
+ const deckRef = useRef<HTMLDivElement>(null);
165
+
166
+ const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);
167
+ const boundKey = binding.ok ? binding.field.key : null;
168
+
169
+ const undecided = useMemo(
170
+ () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),
171
+ [rows, boundKey]
172
+ );
173
+ const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);
174
+ const card = deck[0];
175
+
176
+ // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever β€”
177
+ // otherwise the disclosed skip count drifts away from what is actually on the deck.
178
+ useEffect(() => {
179
+ setLater((prev) => {
180
+ if (prev.size === 0) return prev;
181
+ const live = new Set(undecided.map((r) => r.pid));
182
+ const next = new Set([...prev].filter((pid) => live.has(pid)));
183
+ return next.size === prev.size ? prev : next;
184
+ });
185
+ }, [undecided]);
186
+
187
+ const decide = useCallback(
188
+ (value: string) => {
189
+ if (!card || !canWrite) return;
190
+ onSwipe(card.pid, value);
191
+ },
192
+ [card, canWrite, onSwipe]
193
+ );
194
+
195
+ // ← / β†’ decide, and they are the SAME two actions the buttons are rather than a second code
196
+ // path: the whole point of the mode is that one hand can clear a queue.
197
+ useEffect(() => {
198
+ if (!binding.ok || !canWrite || !card) return;
199
+ const onKey = (e: KeyboardEvent) => {
200
+ if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
201
+ const el = document.activeElement as HTMLElement | null;
202
+ // Never steal an arrow key from a text field or a native control the user is inside.
203
+ if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))
204
+ return;
205
+ if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;
206
+ e.preventDefault();
207
+ decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);
208
+ };
209
+ window.addEventListener("keydown", onKey);
210
+ return () => window.removeEventListener("keydown", onKey);
211
+ }, [binding, canWrite, card, decide]);
212
+
213
+ if (!binding.ok) {
214
+ return (
215
+ <div className="cg-swipe" ref={deckRef}>
216
+ <SwipeBinder
217
+ fault={binding.fault}
218
+ fields={fields}
219
+ fieldByKey={fieldByKey}
220
+ spec={spec}
221
+ canBind={canBind}
222
+ onSpec={onSpec}
223
+ />
224
+ </div>
225
+ );
226
+ }
227
+
228
+ const { field } = binding;
229
+ const leftTint = optionTint(field, binding.spec.leftOption);
230
+ const rightTint = optionTint(field, binding.spec.rightOption);
231
+
232
+ return (
233
+ <div className="cg-swipe" ref={deckRef} tabIndex={-1}>
234
+ <div className="cg-swipe-bar">
235
+ <span className="cg-swipe-bound">
236
+ <ModeIcon mode="swipe" />
237
+ Sorting into <strong>{field.label}</strong>
238
+ </span>
239
+ <span className="cg-swipe-left">
240
+ {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort
241
+ </span>
242
+ {canBind && (
243
+ <button
244
+ type="button"
245
+ className="cg-link-btn"
246
+ onClick={() => onSpec(undefined)}
247
+ title="Choose a different field or different options for this deck"
248
+ >
249
+ Change
250
+ </button>
251
+ )}
252
+ </div>
253
+ {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
254
+ {card ? (
255
+ <div className="cg-swipe-deck">
256
+ <button
257
+ type="button"
258
+ className="cg-swipe-side cg-swipe-side--left"
259
+ disabled={!canWrite}
260
+ style={leftTint ? { background: leftTint.bg, color: leftTint.fg } : undefined}
261
+ onClick={() => decide(binding.spec.leftOption)}
262
+ title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}
263
+ >
264
+ <span aria-hidden className="cg-swipe-arrow">
265
+ <svg width="16" height="16" viewBox="0 0 16 16">
266
+ <path
267
+ d="M11 3.2 6.2 8l4.8 4.8"
268
+ fill="none"
269
+ stroke="currentColor"
270
+ strokeWidth="1.6"
271
+ strokeLinecap="round"
272
+ strokeLinejoin="round"
273
+ />
274
+ </svg>
275
+ </span>
276
+ {binding.spec.leftOption}
277
+ </button>
278
+ <article
279
+ className="cg-swipe-card"
280
+ role="button"
281
+ tabIndex={0}
282
+ onClick={(e) => {
283
+ // ⭐ W41-T48 β€” the card IS the deck's record open, so it folds the rail.
284
+ // ⚠ Nothing that is NOT an open can reach this line: every control inside the
285
+ // card (a url cell, the comments box, the document tray) already stops its own
286
+ // click, and the left/right decision buttons are siblings of the card, not
287
+ // children of it. The deck also has no pointer drag to disambiguate β€” its swipe
288
+ // is the two buttons and the arrow keys, neither of which opens anything.
289
+ // ⚠ `<article role="button">`, not a native button, so a keyboard activation
290
+ // never arrives here as a synthetic click; the keydown path below is the whole
291
+ // keyboard story and the two cannot both fire for one gesture.
292
+ if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT);
293
+ onOpen(card.pid);
294
+ }}
295
+ onKeyDown={(e) => {
296
+ if (e.key !== "Enter" && e.key !== " ") return;
297
+ e.preventDefault();
298
+ // W41-T48 β€” `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space
299
+ // auto-repeats keydown, and every one of those repeats is the SAME gesture.
300
+ if (!e.repeat) signal(NAV_MINIMIZE_EVENT);
301
+ onOpen(card.pid);
302
+ }}
303
+ >
304
+ <h3 className="cg-swipe-title">{String(card[titleKey] ?? "")}</h3>
305
+ <div className="cg-swipe-cells">
306
+ {/* ⭐ WAVE-29 T26 (R9) β€” the RECORD's visible fields, not the three-key summary the
307
+ kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not
308
+ been widened yet renders exactly what it rendered before. */}
309
+ {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {
310
+ const f = fieldByKey.get(k);
311
+ if (!f) return null;
312
+ const text = formatDisplay(f, card[k]);
313
+ if (!text) return null;
314
+ // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one
315
+ // scheme guard β€” and every gesture that reaches it must be stopped from also
316
+ // reaching the card, which is a button (the kanban card's note, same trap).
317
+ const href = actionHref(f, card[k]);
318
+ return (
319
+ <div key={k} className="cg-swipe-cell">
320
+ <span className="cg-lv-k">{f.label}</span>
321
+ {href ? (
322
+ <a
323
+ className="cg-lv-v"
324
+ href={href}
325
+ target="_blank"
326
+ rel="noopener noreferrer"
327
+ title={text}
328
+ onClick={(e) => e.stopPropagation()}
329
+ onKeyDown={(e) => e.stopPropagation()}
330
+ >
331
+ {text}
332
+ </a>
333
+ ) : (
334
+ <span className="cg-lv-v">{text}</span>
335
+ )}
336
+ </div>
337
+ );
338
+ })}
339
+ </div>
340
+ {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"`
341
+ that opens the record, and a click on a comment box or an upload control must not
342
+ also open the modal it exists to make unnecessary (the kanban card's link trap,
343
+ one surface over). */}
344
+ {onDocAdd && onDocFetch && onDocDelete && (
345
+ <div
346
+ className="cg-swipe-docs"
347
+ onClick={(e) => e.stopPropagation()}
348
+ onKeyDown={(e) => e.stopPropagation()}
349
+ role="presentation"
350
+ >
351
+ <Documents
352
+ pid={Number(card.pid)}
353
+ docs={docs?.[String(card.pid)] ?? []}
354
+ docPayload={docPayload}
355
+ onAdd={(file) => onDocAdd(card.pid, file)}
356
+ onFetch={(docId) => onDocFetch(card.pid, docId)}
357
+ onDelete={(docId) => onDocDelete(card.pid, docId)}
358
+ />
359
+ </div>
360
+ )}
361
+ {scope != null && (
362
+ <div
363
+ className="cg-swipe-comments"
364
+ onClick={(e) => e.stopPropagation()}
365
+ onKeyDown={(e) => e.stopPropagation()}
366
+ role="presentation"
367
+ >
368
+ {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React
369
+ reuses the mounted instance across a card change and paints one record's
370
+ comments under another's name until the fetch returns. */}
371
+ <RecordComments
372
+ key={`${scope}:${Number(card.pid)}`}
373
+ scope={scope}
374
+ pid={Number(card.pid)}
375
+ viewer={viewer}
376
+ />
377
+ </div>
378
+ )}
379
+ {canWrite && (
380
+ <button
381
+ type="button"
382
+ className="cg-link-btn cg-swipe-later"
383
+ onClick={(e) => {
384
+ e.stopPropagation();
385
+ setLater((prev) => new Set(prev).add(card.pid));
386
+ }}
387
+ >
388
+ Decide later
389
+ </button>
390
+ )}
391
+ </article>
392
+ <button
393
+ type="button"
394
+ className="cg-swipe-side cg-swipe-side--right"
395
+ disabled={!canWrite}
396
+ style={rightTint ? { background: rightTint.bg, color: rightTint.fg } : undefined}
397
+ onClick={() => decide(binding.spec.rightOption)}
398
+ title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}
399
+ >
400
+ {binding.spec.rightOption}
401
+ <span aria-hidden className="cg-swipe-arrow">
402
+ <svg width="16" height="16" viewBox="0 0 16 16">
403
+ <path
404
+ d="M5 3.2 9.8 8 5 12.8"
405
+ fill="none"
406
+ stroke="currentColor"
407
+ strokeWidth="1.6"
408
+ strokeLinecap="round"
409
+ strokeLinejoin="round"
410
+ />
411
+ </svg>
412
+ </span>
413
+ </button>
414
+ </div>
415
+ ) : (
416
+ // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous
417
+ // between "the deck is finished" and "the filter hid everything", and the two want
418
+ // different next actions. `later` is disclosed rather than quietly subtracted.
419
+ <div className="cg-mode-empty cg-swipe-empty">
420
+ {later.size > 0 ? (
421
+ <>
422
+ <p>
423
+ {later.size.toLocaleString()}{" "}
424
+ {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else
425
+ in this view is missing a <strong>{field.label}</strong>.
426
+ </p>
427
+ <button type="button" className="cg-btn" onClick={() => setLater(new Set())}>
428
+ Bring them back
429
+ </button>
430
+ </>
431
+ ) : (
432
+ <p>
433
+ Every record in this view already has a <strong>{field.label}</strong>. Widen the
434
+ view's filters to sort more.
435
+ </p>
436
+ )}
437
+ </div>
438
+ )}
439
+ </div>
440
+ );
441
+ }
442
+
443
+ /**
444
+ * The binding picker: field + two options. It is also the surface every LOST binding lands on,
445
+ * with the loss stated above it β€” one place that answers "what is this deck for", rather than an
446
+ * error screen beside a separate setup screen.
447
+ */
448
+ function SwipeBinder({
449
+ fault,
450
+ fields,
451
+ fieldByKey,
452
+ spec,
453
+ canBind,
454
+ onSpec,
455
+ }: {
456
+ fault: BindingFault;
457
+ fields: Field[];
458
+ fieldByKey: Map<string, Field>;
459
+ spec: SwipeSpec | undefined;
460
+ canBind: boolean;
461
+ onSpec: (next: SwipeSpec | undefined) => void;
462
+ }) {
463
+ const selects = useMemo(
464
+ () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),
465
+ [fields]
466
+ );
467
+ const [fieldKey, setFieldKey] = useState<string>(() => {
468
+ if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;
469
+ return selects[0]?.key ?? "";
470
+ });
471
+ const chosen = fieldByKey.get(fieldKey);
472
+ const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);
473
+ const [left, setLeft] = useState<string>("");
474
+ const [right, setRight] = useState<string>("");
475
+
476
+ // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's
477
+ // pick survives re-renders, and reset whenever the field changes β€” carrying an option from the
478
+ // previous field would offer a value the new field cannot hold.
479
+ useEffect(() => {
480
+ setLeft(options[0] ?? "");
481
+ setRight(options.find((o) => o !== options[0]) ?? "");
482
+ }, [options]);
483
+
484
+ const message = ((): string => {
485
+ switch (fault.kind) {
486
+ case "field-gone":
487
+ return "The field this deck sorted into has been deleted. Pick another one.";
488
+ case "not-select":
489
+ return `β€œ${fault.field.label}” is no longer a single-select, so it has no options to`
490
+ + " sort into. Pick another field.";
491
+ case "option-gone":
492
+ return `${fault.missing.map((m) => `β€œ${m}”`).join(" and ")} ${
493
+ fault.missing.length === 1 ? "is" : "are"
494
+ } no longer ${fault.missing.length === 1 ? "an option" : "options"} on β€œ${
495
+ fault.field.label
496
+ }”. Pick the sides again.`;
497
+ default:
498
+ return "Sort records one at a time into two options of a single-select field.";
499
+ }
500
+ })();
501
+
502
+ if (!canBind) {
503
+ return (
504
+ <div className="cg-mode-empty">
505
+ <p>{message}</p>
506
+ <p>Its creator or an admin can set this view up.</p>
507
+ </div>
508
+ );
509
+ }
510
+ if (selects.length === 0) {
511
+ // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the
512
+ // requirement is what turns a dead end into a next action.
513
+ return (
514
+ <div className="cg-mode-empty">
515
+ <p>
516
+ A swipe deck sorts into a single-select field with at least two options. This database
517
+ does not have one yet β€” add a single-select column, then come back.
518
+ </p>
519
+ </div>
520
+ );
521
+ }
522
+ const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();
523
+ return (
524
+ <div className="cg-swipe-setup">
525
+ <p className="cg-swipe-setup-note">{message}</p>
526
+ <label className="cg-swipe-setup-row">
527
+ <span>Sort into</span>
528
+ <select
529
+ className="cg-select"
530
+ value={fieldKey}
531
+ onChange={(e) => setFieldKey(e.target.value)}
532
+ >
533
+ {/* Every option carries an explicit `value`: a <select> whose value names nothing
534
+ renders its FIRST option and reports a choice the user never made
535
+ ([[cg-condition-builder-items]]). */}
536
+ {selects.map((f) => (
537
+ <option key={f.key} value={f.key}>
538
+ {f.label}
539
+ </option>
540
+ ))}
541
+ </select>
542
+ </label>
543
+ <div className="cg-swipe-setup-sides">
544
+ <label className="cg-swipe-setup-row">
545
+ <span>Swipe left</span>
546
+ <select className="cg-select" value={left} onChange={(e) => setLeft(e.target.value)}>
547
+ {options.map((o) => (
548
+ <option key={o} value={o}>
549
+ {o}
550
+ </option>
551
+ ))}
552
+ </select>
553
+ </label>
554
+ <label className="cg-swipe-setup-row">
555
+ <span>Swipe right</span>
556
+ <select className="cg-select" value={right} onChange={(e) => setRight(e.target.value)}>
557
+ {options.map((o) => (
558
+ <option key={o} value={o}>
559
+ {o}
560
+ </option>
561
+ ))}
562
+ </select>
563
+ </label>
564
+ </div>
565
+ {!ready && left && right && (
566
+ // Stated, not silently refused: both engines DROP a binding whose sides are the same
567
+ // option, so a Save that looked like it worked would simply not persist.
568
+ <p className="cg-swipe-setup-warn">
569
+ The two sides must be different options β€” otherwise both gestures do the same thing.
570
+ </p>
571
+ )}
572
+ <button
573
+ type="button"
574
+ className="cg-btn cg-btn--primary"
575
+ disabled={!ready}
576
+ onClick={() =>
577
+ chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })
578
+ }
579
+ >
580
+ Start sorting
581
+ </button>
582
+ </div>
583
+ );
584
+ }
585
+
586
+ export default SwipeView;
web/src/customer-grid/dataPath.ts CHANGED
@@ -160,18 +160,34 @@ export function groupDataDatabases(databases: readonly DataDatabase[]): DataData
160
  return [...groups].map(([label, grouped]) => ({ label, databases: grouped }));
161
  }
162
 
163
- export function dataPathHash(path: DataPath): string {
 
 
 
164
  const query = new URLSearchParams({ database: path.database });
165
  if (path.view) query.set("view", path.view);
166
  if (path.field) query.set("field", path.field);
167
  if (path.application) query.set("application", path.application);
168
- return `#/data?${query.toString()}`;
 
 
 
 
 
 
 
 
169
  }
170
 
171
  export function readDataPath(hash?: string): DataPath | null {
172
  const source = hash ?? (typeof window === "undefined" ? "" : window.location.hash);
173
- if (!source.startsWith("#/data?")) return null;
174
- const query = new URLSearchParams(source.slice("#/data?".length));
 
 
 
 
 
175
  const database = query.get("database");
176
  if (!database) return null;
177
  return {
 
160
  return [...groups].map(([label, grouped]) => ({ label, databases: grouped }));
161
  }
162
 
163
+ const DATA_PATH_PREFIX = "#/data?";
164
+ export const APP_PATH_PREFIX = "#/app?";
165
+
166
+ function addressedPathHash(prefix: string, path: DataPath): string {
167
  const query = new URLSearchParams({ database: path.database });
168
  if (path.view) query.set("view", path.view);
169
  if (path.field) query.set("field", path.field);
170
  if (path.application) query.set("application", path.application);
171
+ return `${prefix}${query.toString()}`;
172
+ }
173
+
174
+ export function dataPathHash(path: DataPath): string {
175
+ return addressedPathHash(DATA_PATH_PREFIX, path);
176
+ }
177
+
178
+ export function appPathHash(path: DataPath): string {
179
+ return addressedPathHash(APP_PATH_PREFIX, path);
180
  }
181
 
182
  export function readDataPath(hash?: string): DataPath | null {
183
  const source = hash ?? (typeof window === "undefined" ? "" : window.location.hash);
184
+ // App and Data address the same database/Application question under different module headings.
185
+ // One reader avoids the one-question-two-normalizers defect that has broken deep links before.
186
+ const prefix = source.startsWith(DATA_PATH_PREFIX)
187
+ ? DATA_PATH_PREFIX
188
+ : source.startsWith(APP_PATH_PREFIX) ? APP_PATH_PREFIX : null;
189
+ if (!prefix) return null;
190
+ const query = new URLSearchParams(source.slice(prefix.length));
191
  const database = query.get("database");
192
  if (!database) return null;
193
  return {
web/src/index.css CHANGED
@@ -13391,7 +13391,7 @@ textarea.cg-json-raw:focus {
13391
  /* β›”β›” WAVE 35 Β· T11 (owner item 9, R4) β€” THE DATABASE-LEVEL TOTAL IS GONE, AND SO IS EVERY RULE
13392
  THAT DRESSED IT. Owner item 9: the count belongs to the VIEW itself and nowhere else. Wave 33's
13393
  T16 put a per-database total at the top of this rail and wave 34's T20 stripped its label; both
13394
- notes are now history and live in `.claude/wiki/waves/wave35/` rather than here.
13395
  ⚠ FOUR RULES DIED TOGETHER ON PURPOSE, and this note is what stops one of them coming back
13396
  alone: `.cg-views-important` (the wrapper's `margin-left: auto`, which outranked
13397
  `.cg-views-top`'s `justify-content` and is why the fold toggle sat left on a database with a
 
13391
  /* β›”β›” WAVE 35 Β· T11 (owner item 9, R4) β€” THE DATABASE-LEVEL TOTAL IS GONE, AND SO IS EVERY RULE
13392
  THAT DRESSED IT. Owner item 9: the count belongs to the VIEW itself and nowhere else. Wave 33's
13393
  T16 put a per-database total at the top of this rail and wave 34's T20 stripped its label; both
13394
+ notes are now history and live in `AutoWiki/waves/wave35/` rather than here.
13395
  ⚠ FOUR RULES DIED TOGETHER ON PURPOSE, and this note is what stops one of them coming back
13396
  alone: `.cg-views-important` (the wrapper's `margin-left: auto`, which outranked
13397
  `.cg-views-top`'s `justify-content` and is why the fold toggle sat left on a database with a
web/src/query/queryParts.tsx CHANGED
@@ -40,7 +40,7 @@ import type { SavedQuery } from "./queryApi";
40
  * underlined link. That is the "outdated format".
41
  *
42
  * Γ’Ε‘Β  It is NOT the Suspense fallback (a bare spinner) and NOT the empty state, the two candidates
43
- * the wave listed. Capture of both states: `.claude/wiki/waves/wave35/proto/T22-query-flash/`.
44
  *
45
  * Γ’Ε‘Β  KEEP THE TWIN IMPORT IN `QueryPage.tsx`. Vite emits one stylesheet either way, and the
46
  * standalone `#/query` host reaches the page without passing through here.
 
40
  * underlined link. That is the "outdated format".
41
  *
42
  * Γ’Ε‘Β  It is NOT the Suspense fallback (a bare spinner) and NOT the empty state, the two candidates
43
+ * the wave listed. Capture of both states: `AutoWiki/waves/wave35/proto/T22-query-flash/`.
44
  *
45
  * Γ’Ε‘Β  KEEP THE TWIN IMPORT IN `QueryPage.tsx`. Vite emits one stylesheet either way, and the
46
  * standalone `#/query` host reaches the page without passing through here.
web/src/settings/ExternalAccessPane.tsx ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // settings / ExternalAccessPane.tsx - W56-T38, ruling R3, contract C7.
2
+ //
3
+ // A self-contained settings pane for the signed-in user's own external credential. The browser
4
+ // never derives permission from its session payload: the list response reports whether the same
5
+ // server-side Analyst wall permits minting, and every write is checked again by the route.
6
+
7
+ import { useCallback, useEffect, useState } from "react";
8
+ import type { FormEvent } from "react";
9
+ import {
10
+ API_V1,
11
+ CREDENTIALS,
12
+ UNAUTHORIZED_EVENT,
13
+ checkTenant,
14
+ } from "../apiContract";
15
+
16
+ interface ExternalKeyMetadata {
17
+ id: string;
18
+ label: string;
19
+ created: string;
20
+ last_used: string | null;
21
+ revoked_at: string | null;
22
+ }
23
+
24
+ interface KeyListResponse {
25
+ keys: ExternalKeyMetadata[];
26
+ can_mint: boolean;
27
+ }
28
+
29
+ interface MintResponse {
30
+ key: ExternalKeyMetadata;
31
+ secret: string;
32
+ }
33
+
34
+ type ApiResult<T> =
35
+ | { ok: true; data: T }
36
+ | { ok: false; message: string };
37
+
38
+ function messageFrom(body: unknown, fallback: string): string {
39
+ if (!body || typeof body !== "object") return fallback;
40
+ const error = (body as { error?: unknown }).error;
41
+ if (!error || typeof error !== "object") return fallback;
42
+ const message = (error as { message?: unknown }).message;
43
+ return typeof message === "string" && message.trim() !== "" ? message : fallback;
44
+ }
45
+
46
+ async function call<T>(path: string, init?: RequestInit): Promise<ApiResult<T>> {
47
+ try {
48
+ const response = await fetch(`${API_V1}${path}`, {
49
+ credentials: CREDENTIALS,
50
+ ...init,
51
+ });
52
+ if (checkTenant(response)) {
53
+ return { ok: false, message: "This workspace changed. Reloading." };
54
+ }
55
+ let body: unknown = null;
56
+ try {
57
+ body = await response.json();
58
+ } catch {
59
+ // A refused or unavailable endpoint can answer without JSON. The stable fallback remains.
60
+ }
61
+ if (!response.ok) {
62
+ if (response.status === 401 && typeof window !== "undefined") {
63
+ window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT));
64
+ }
65
+ return {
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
+ }
73
+ return { ok: true, data: body as T };
74
+ } catch {
75
+ return { ok: false, message: "The server could not be reached." };
76
+ }
77
+ }
78
+
79
+ async function callText(path: string): Promise<ApiResult<string>> {
80
+ try {
81
+ const response = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS });
82
+ if (checkTenant(response)) {
83
+ return { ok: false, message: "This workspace changed. Reloading." };
84
+ }
85
+ const body = await response.text();
86
+ if (!response.ok) {
87
+ if (response.status === 401 && typeof window !== "undefined") {
88
+ window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT));
89
+ }
90
+ let parsed: unknown = null;
91
+ try {
92
+ parsed = JSON.parse(body);
93
+ } catch {
94
+ // Markdown is the success shape. A non-JSON refusal uses the stable fallback below.
95
+ }
96
+ return {
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
+ }
104
+ return { ok: true, data: body };
105
+ } catch {
106
+ return { ok: false, message: "The server could not be reached." };
107
+ }
108
+ }
109
+
110
+ function parseKey(value: unknown): ExternalKeyMetadata | null {
111
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
112
+ const row = value as Record<string, unknown>;
113
+ if (
114
+ typeof row.id !== "string" ||
115
+ typeof row.label !== "string" ||
116
+ typeof row.created !== "string"
117
+ ) {
118
+ return null;
119
+ }
120
+ return {
121
+ id: row.id,
122
+ label: row.label,
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
+
129
+ function when(value: string | null): string {
130
+ if (!value) return "Never";
131
+ const parsed = new Date(value);
132
+ if (Number.isNaN(parsed.getTime())) return "Unknown";
133
+ return parsed.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });
134
+ }
135
+
136
+ 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("");
143
+ const [revealed, setRevealed] = useState<MintResponse | null>(null);
144
+ const [copied, setCopied] = useState(false);
145
+ const [skillCopied, setSkillCopied] = useState(false);
146
+
147
+ const load = useCallback(async () => {
148
+ const result = await call<KeyListResponse>("/external/keys");
149
+ if (!result.ok) {
150
+ setKeys([]);
151
+ setCanMint(null);
152
+ setError(result.message);
153
+ return;
154
+ }
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[]);
169
+ setCanMint(result.data.can_mint);
170
+ setError("");
171
+ }, []);
172
+
173
+ useEffect(() => {
174
+ void load();
175
+ }, [load]);
176
+
177
+ async function create(event: FormEvent) {
178
+ event.preventDefault();
179
+ const clean = label.trim();
180
+ if (!clean) {
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) {
194
+ setError(result.message);
195
+ return;
196
+ }
197
+ const key = parseKey(result.data?.key);
198
+ if (!key || typeof result.data?.secret !== "string" || result.data.secret === "") {
199
+ setError("The credential was created, but its secret could not be read.");
200
+ void load();
201
+ return;
202
+ }
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
+ }
209
+
210
+ async function copyCredential() {
211
+ if (!revealed) return;
212
+ try {
213
+ await navigator.clipboard.writeText(revealed.secret);
214
+ setCopied(true);
215
+ setError("");
216
+ } catch {
217
+ setCopied(false);
218
+ setError("The credential could not be copied. Select it and copy it manually.");
219
+ }
220
+ }
221
+
222
+ async function skillDocument(action: "copy" | "download"): Promise<string | null> {
223
+ setBusy(`skill-${action}`);
224
+ setError("");
225
+ setNotice("");
226
+ const result = await callText("/external/skill.md");
227
+ setBusy("");
228
+ if (!result.ok) {
229
+ setError(result.message);
230
+ return null;
231
+ }
232
+ return result.data;
233
+ }
234
+
235
+ async function copySkill() {
236
+ const document = await skillDocument("copy");
237
+ if (document === null) return;
238
+ try {
239
+ await navigator.clipboard.writeText(document);
240
+ setSkillCopied(true);
241
+ setNotice("skill.md copied. It contains no credential or other secret.");
242
+ } catch {
243
+ setSkillCopied(false);
244
+ setError("skill.md could not be copied. Download it instead.");
245
+ }
246
+ }
247
+
248
+ async function downloadSkill() {
249
+ const document = await skillDocument("download");
250
+ if (document === null) return;
251
+ try {
252
+ const url = URL.createObjectURL(
253
+ new Blob([document], { type: "text/markdown;charset=utf-8" }),
254
+ );
255
+ const anchor = window.document.createElement("a");
256
+ anchor.href = url;
257
+ anchor.download = "skill.md";
258
+ window.document.body.appendChild(anchor);
259
+ anchor.click();
260
+ anchor.remove();
261
+ window.setTimeout(() => URL.revokeObjectURL(url), 0);
262
+ setNotice("skill.md downloaded. It contains no credential or other secret.");
263
+ } catch {
264
+ setError("skill.md could not be downloaded. Copy it instead.");
265
+ }
266
+ }
267
+
268
+ async function revoke(key: ExternalKeyMetadata) {
269
+ const confirmed = window.confirm(
270
+ `Revoke "${key.label}"? The next request using it will be refused.`,
271
+ );
272
+ if (!confirmed) return;
273
+ setBusy(key.id);
274
+ setError("");
275
+ setNotice("");
276
+ const result = await call<{ key: ExternalKeyMetadata }>(
277
+ `/external/keys/${encodeURIComponent(key.id)}/revoke`,
278
+ { method: "POST" },
279
+ );
280
+ setBusy("");
281
+ if (!result.ok) {
282
+ setError(result.message);
283
+ return;
284
+ }
285
+ setKeys((current) => (current ?? []).filter((row) => row.id !== key.id));
286
+ if (revealed?.key.id === key.id) setRevealed(null);
287
+ setNotice("Credential revoked. Its next request will be refused.");
288
+ }
289
+
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 is read only and sees exactly what you
303
+ see in Loopable. Revoking it stops the next request.
304
+ </p>
305
+
306
+ {error ? <p className="set-error">{error}</p> : null}
307
+ {notice ? <p className="set-notice">{notice}</p> : null}
308
+
309
+ <section className="set-card">
310
+ <h4 className="set-h4">Portable skill</h4>
311
+ <p className="set-help">
312
+ Download or copy a skill.md for your AI. It describes your current read scope and carries
313
+ no credential or other secret.
314
+ </p>
315
+ <div className="set-actions">
316
+ <button
317
+ type="button"
318
+ className="set-primary"
319
+ disabled={canMint !== true || busy === "skill-download"}
320
+ onClick={() => void downloadSkill()}
321
+ >
322
+ {busy === "skill-download" ? "Preparing…" : "Download skill.md"}
323
+ </button>
324
+ <button
325
+ type="button"
326
+ className="set-secondary"
327
+ disabled={canMint !== true || busy === "skill-copy"}
328
+ onClick={() => void copySkill()}
329
+ >
330
+ {busy === "skill-copy" ? "Copying…" : skillCopied ? "Copied" : "Copy skill.md"}
331
+ </button>
332
+ </div>
333
+ </section>
334
+
335
+ {revealed ? (
336
+ <section className="set-card">
337
+ <h4 className="set-h4">Save this credential</h4>
338
+ <p className="set-help">
339
+ Copy it now. The secret is shown once and cannot be recovered.
340
+ </p>
341
+ <div className="set-field">
342
+ <label className="set-label" htmlFor="set-external-secret">Credential</label>
343
+ <input
344
+ id="set-external-secret"
345
+ className="set-input"
346
+ type="text"
347
+ value={revealed.secret}
348
+ readOnly
349
+ autoComplete="off"
350
+ spellCheck={false}
351
+ />
352
+ </div>
353
+ <div className="set-actions">
354
+ <button type="button" className="set-primary" onClick={() => void copyCredential()}>
355
+ {copied ? "Copied" : "Copy credential"}
356
+ </button>
357
+ <button
358
+ type="button"
359
+ className="set-secondary"
360
+ onClick={() => {
361
+ setRevealed(null);
362
+ setCopied(false);
363
+ }}
364
+ >
365
+ Done
366
+ </button>
367
+ </div>
368
+ </section>
369
+ ) : canMint ? (
370
+ <form className="set-card" onSubmit={(event) => void create(event)}>
371
+ <h4 className="set-h4">New credential</h4>
372
+ <div className="set-field">
373
+ <label className="set-label" htmlFor="set-external-label">Label</label>
374
+ <input
375
+ id="set-external-label"
376
+ className="set-input"
377
+ type="text"
378
+ maxLength={80}
379
+ value={label}
380
+ autoComplete="off"
381
+ placeholder="My AI assistant"
382
+ onChange={(event) => setLabel(event.currentTarget.value)}
383
+ />
384
+ </div>
385
+ <div className="set-actions">
386
+ <button
387
+ type="submit"
388
+ className="set-primary"
389
+ disabled={busy === "create" || label.trim() === ""}
390
+ >
391
+ {busy === "create" ? "Creating…" : "Create credential"}
392
+ </button>
393
+ </div>
394
+ </form>
395
+ ) : canMint === false ? (
396
+ <p className="set-help set-pane-intro">
397
+ External AI access requires the Analyst module. Ask an administrator to grant it.
398
+ </p>
399
+ ) : null}
400
+
401
+ <div className="set-perm-sect">
402
+ <h4 className="set-h4">Credentials</h4>
403
+ </div>
404
+ {keys.length === 0 ? (
405
+ <p className="set-help">You have no active external AI credentials.</p>
406
+ ) : (
407
+ <div aria-label="Active credentials">
408
+ {keys.map((key) => (
409
+ <section className="set-card" key={key.id}>
410
+ <h4 className="set-h4">{key.label}</h4>
411
+ <div className="pg-drill-row">
412
+ <span className="pg-drill-key">Created</span>
413
+ <span className="pg-drill-val">{when(key.created)}</span>
414
+ </div>
415
+ <div className="pg-drill-row">
416
+ <span className="pg-drill-key">Last used</span>
417
+ <span className="pg-drill-val">{when(key.last_used)}</span>
418
+ </div>
419
+ <div className="set-actions">
420
+ <button
421
+ type="button"
422
+ className="set-secondary kc-danger"
423
+ disabled={busy === key.id}
424
+ onClick={() => void revoke(key)}
425
+ >
426
+ {busy === key.id ? "Revoking…" : "Revoke"}
427
+ </button>
428
+ </div>
429
+ </section>
430
+ ))}
431
+ </div>
432
+ )}
433
+ </div>
434
+ );
435
+ }
web/src/settings/SettingsModal.tsx CHANGED
@@ -76,6 +76,7 @@ import { ManageDatabasePane } from "./ManageDatabase";
76
  // Wave 52 Β· T19 (owner instruction 21, ruling R7) β€” sheet shortcut toggles + rebinding. A
77
  // client-local preference pane, self-contained like `ManageDatabasePane`; see the mount below.
78
  import ShortcutSettings from "./ShortcutSettings";
 
79
  import OperatorPage from "../operator/OperatorPage";
80
  /* β›” `StatementsPane` LEFT WITH ITS RAIL ROW (wave 35 Β· T38): the file is DELETED, not merely
81
  unmounted. An orphaned component with no importer is the shape this repo books as
@@ -155,6 +156,13 @@ const IconShortcuts = (
155
  <path d="M4.7 7.1h.01M7.3 7.1h.01M9.9 7.1h.01M12.5 7.1h.01M5.5 9.6h5" />
156
  </RailIcon>
157
  );
 
 
 
 
 
 
 
158
  /** Manage users β€” more than one person. */
159
  const IconUsers = (
160
  <RailIcon>
@@ -793,6 +801,7 @@ export function SettingsModal({
793
  // preferences, and there is nothing behind this room a member's account cannot already do to
794
  // itself (the store is client-local, keyed to nothing server-side).
795
  ["shortcuts", "Sheet shortcuts", IconShortcuts],
 
796
  ...(admin
797
  ? ([
798
  ["users", "Manage users", IconUsers],
@@ -900,6 +909,7 @@ export function SettingsModal({
900
  `sheet/shortcuts.ts`'s own localStorage store directly and needs nothing passed
901
  in, because a keyboard preference is not server data. */}
902
  {active === "shortcuts" ? <ShortcutSettings /> : null}
 
903
  {active === "keychains" ? <KeychainPane /> : null}
904
  {active === "connectors" ? <ConnectorsPane /> : null}
905
  {/* Wave 19 contract C2 β€” the wiring record, verified at the MOUNT SITE
 
76
  // Wave 52 Β· T19 (owner instruction 21, ruling R7) β€” sheet shortcut toggles + rebinding. A
77
  // client-local preference pane, self-contained like `ManageDatabasePane`; see the mount below.
78
  import ShortcutSettings from "./ShortcutSettings";
79
+ import ExternalAccessPane from "./ExternalAccessPane";
80
  import OperatorPage from "../operator/OperatorPage";
81
  /* β›” `StatementsPane` LEFT WITH ITS RAIL ROW (wave 35 Β· T38): the file is DELETED, not merely
82
  unmounted. An orphaned component with no importer is the shape this repo books as
 
156
  <path d="M4.7 7.1h.01M7.3 7.1h.01M9.9 7.1h.01M12.5 7.1h.01M5.5 9.6h5" />
157
  </RailIcon>
158
  );
159
+ /** External AI - a governed connection leaving this account. */
160
+ const IconExternal = (
161
+ <RailIcon>
162
+ <circle cx="8" cy="8" r="2.2" />
163
+ <path d="M5.8 8H2.2M10.2 8h3.6M8 5.8V2.2M8 10.2v3.6" />
164
+ </RailIcon>
165
+ );
166
  /** Manage users β€” more than one person. */
167
  const IconUsers = (
168
  <RailIcon>
 
801
  // preferences, and there is nothing behind this room a member's account cannot already do to
802
  // itself (the store is client-local, keyed to nothing server-side).
803
  ["shortcuts", "Sheet shortcuts", IconShortcuts],
804
+ ["external", "External AI", IconExternal],
805
  ...(admin
806
  ? ([
807
  ["users", "Manage users", IconUsers],
 
909
  `sheet/shortcuts.ts`'s own localStorage store directly and needs nothing passed
910
  in, because a keyboard preference is not server data. */}
911
  {active === "shortcuts" ? <ShortcutSettings /> : null}
912
+ {active === "external" ? <ExternalAccessPane /> : null}
913
  {active === "keychains" ? <KeychainPane /> : null}
914
  {active === "connectors" ? <ConnectorsPane /> : null}
915
  {/* Wave 19 contract C2 β€” the wiring record, verified at the MOUNT SITE
web/src/settings/permsModel.ts CHANGED
@@ -49,6 +49,7 @@ export type SettingsSection =
49
  * store, never on this wire: there is nothing here for a server to enforce.
50
  */
51
  | "shortcuts"
 
52
  | "users"
53
  /**
54
  * ⭐ WAVE 33 (owner item 10) β€” MANAGE AGENT: a bot per Slack channel, walled by
 
49
  * store, never on this wire: there is nothing here for a server to enforce.
50
  */
51
  | "shortcuts"
52
+ | "external"
53
  | "users"
54
  /**
55
  * ⭐ WAVE 33 (owner item 10) β€” MANAGE AGENT: a bot per Slack channel, walled by
web/src/sheet/BindingEditor.tsx CHANGED
@@ -43,15 +43,18 @@ import { FieldTypeIcon } from "../customer-grid/icons";
43
  import { BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface";
44
  import type { Field, FilterTree, Row } from "../customer-grid/types";
45
  import { choiceVocabulary, topicForScope } from "../customer-grid/types";
 
 
46
  // ⭐⭐ W53-T15 (ruling R8) β€” THE FILTER BUILDER IS NO LONGER MOUNTED IN THIS COLUMN. The SHARED
47
  // `FilterBuilderPanel` the Data module also uses is untouched; `SheetFilterPopup` wraps it in the
48
  // base kit's centred dialog so its condition rows have room, and only the Sheet mounts that
49
  // wrapper. This file therefore stops importing the panel itself.
50
  import { countConditions, isNumericType } from "../filter-kit/ops";
51
  import { SheetFilterPopup } from "../filter-kit/SheetFilterPopup";
 
52
  import { useEscapeClose } from "../ui/useEscapeClose";
53
  import { previewCell } from "./sheetApi";
54
- import { bindingDisplay } from "./types";
55
 
56
  const AGGREGATES = [
57
  { fn: "sum", label: "Sum" },
@@ -94,6 +97,14 @@ const NUMERIC_ROLLUP_FNS = [
94
  * the field's `type` (the two live ones on `customer_data` are typed `currency` and `int`). */
95
  const isMetricField = (f: Field): boolean => Boolean(f.measure);
96
 
 
 
 
 
 
 
 
 
97
  /** Can this database add this column up? Mirrors `modules/sheet.py::aggregate_refusal`. */
98
  const canTotal = (f: Field): boolean => {
99
  if (f.type === "formula") return false;
@@ -133,6 +144,7 @@ export interface PeriodBinding {
133
  start: string;
134
  locked: boolean;
135
  ref?: string;
 
136
  }
137
 
138
  export const PERIOD_UNITS: { unit: PeriodUnit; label: string }[] = [
@@ -217,6 +229,18 @@ export function migratePeriod(raw: unknown): PeriodBinding | null {
217
  if (!raw || typeof raw !== "object") return null;
218
  const p = raw as Record<string, unknown>;
219
  const ref = typeof p.ref === "string" && p.ref.trim() ? p.ref.trim() : "";
 
 
 
 
 
 
 
 
 
 
 
 
220
  const declared = PERIOD_UNITS.some((u) => u.unit === p.unit);
221
  if (!declared) {
222
  // The legacy shape. Nothing shifts by surprise: it reads back LOCKED.
@@ -411,7 +435,10 @@ function ColumnPickerDialog({
411
  trapFocus: true,
412
  });
413
 
414
- const offersMetric = offered.some(isMetricField);
 
 
 
415
 
416
  return (
417
  <BodyPortal>
@@ -514,9 +541,9 @@ function ColumnPickerDialog({
514
  </div>
515
  )}
516
 
517
- {/* β›” AN EMPTY LIST SAYS WHY (R16). The three causes need different acts from the
518
- reader, and a database CAN carry number columns this database cannot total. */}
519
- {shown.length === 0 && (
520
  <p className="sheet-pick-empty">
521
  {offered.length > 0
522
  ? "No column matches that search."
@@ -527,12 +554,19 @@ function ColumnPickerDialog({
527
  </p>
528
  )}
529
 
530
- {/* ⭐ R7, said where the choice is made: a Metric is the one kind of column here that
531
- answers over the period the panel sets. */}
532
- {offersMetric && shown.length > 0 && (
533
  <p className="sheet-pick-empty">
534
- A Metric column is measured over the period you choose in the panel. Every other
535
- column holds one stored value per record.
 
 
 
 
 
 
 
 
 
536
  </p>
537
  )}
538
  </div>
@@ -693,6 +727,12 @@ export default function BindingEditor({
693
  );
694
  const [locked, setLocked] = useState<boolean>(migrated?.locked ?? false);
695
  const [periodRef, setPeriodRef] = useState<string>(migrated?.ref ?? "");
 
 
 
 
 
 
696
  // "Use a cell" is a LINK that REVEALS the A1 input (R9). The input was the whole period control
697
  // before this ticket and it is not deleted, only demoted to the thing behind that link.
698
  const [refOpen, setRefOpen] = useState<boolean>(Boolean(migrated?.ref));
@@ -871,8 +911,14 @@ export default function BindingEditor({
871
  // column behaves like a number; `canTotal` says this database holds a number to add up. Offering
872
  // a column that fails the second one hands back a refusal instead of a value, which is the exact
873
  // shape of the report this ticket answers.
 
 
874
  const numericFields = useMemo(
875
- () => fields.filter((f) => isNumericType(f.type) && canTotal(f)),
 
 
 
 
876
  [fields],
877
  );
878
 
@@ -898,6 +944,59 @@ export default function BindingEditor({
898
  [fields],
899
  );
900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
901
  /**
902
  * ⭐⭐ W50-T21 (owner instruction 24: *"Sheet column picker (sum/count) shows the Field icons."*)
903
  *
@@ -931,6 +1030,13 @@ export default function BindingEditor({
931
  const chosenField = useMemo(() => fields.find((f) => f.key === field), [fields, field]);
932
  /** Metric columns step their period; every other aggregate steps one chosen filter driver. */
933
  const chosenIsMetric = Boolean(chosenField && isMetricField(chosenField));
 
 
 
 
 
 
 
934
 
935
  /** The database's own label, which the column list's heading names. Two databases can both
936
  * carry a column called "Total", and the heading is where that ambiguity is answered. */
@@ -959,18 +1065,29 @@ export default function BindingEditor({
959
  // stamped to this month's default, and turning the switch off drops the key rather than writing
960
  // an empty period the server would have to guess about.
961
  if (periodOn) {
962
- const period: Record<string, unknown> = {
963
- unit, start, locked: chosenIsMetric ? locked : true,
964
- };
965
- if (refOpen && periodRef.trim()) period.ref = periodRef.trim();
966
- out.period = period;
 
 
 
 
 
 
967
  }
968
- out.onDrag = chosenIsMetric
969
- ? { across: periodOn && !locked ? across : "none", down: "none" }
970
- : { across: "none", down: downField ? { field: downField } : "none" };
 
 
 
 
971
  return out;
972
  }, [database, fn, field, scopeKind, viewId, views, tree, initial,
973
- unit, start, locked, refOpen, periodRef, periodOn, across, downField, chosenIsMetric]);
 
974
 
975
  // ⭐ THE NUMBER APPEARS BEFORE SAVING. `preview` evaluates the binding without persisting it,
976
  // which is what lets someone see whether they picked the right thing while they can still change
@@ -990,7 +1107,8 @@ export default function BindingEditor({
990
  // A cell bound to a live view satisfies every other clause the moment the panel mounts, and a
991
  // Save taken then would write back a binding assembled from a list nobody had seen yet.
992
  const ready = optionsResolved && Boolean(database) && (fn === "count" || Boolean(field))
993
- && (scopeKind === "filter" || Boolean(viewId));
 
994
 
995
  const { y: startYear, m: startMonth } = splitYm(start);
996
  const thisYear = new Date().getFullYear();
@@ -1212,6 +1330,8 @@ export default function BindingEditor({
1212
  type="button"
1213
  role="switch"
1214
  aria-checked={periodOn}
 
 
1215
  className={"sheet-lock-toggle" + (periodOn ? " is-on" : "")}
1216
  onClick={() => setPeriodOn((v) => !v)}
1217
  >
@@ -1219,143 +1339,156 @@ export default function BindingEditor({
1219
  <span>Limit this cell to a period</span>
1220
  </button>
1221
  <p className="sheet-period-note">
1222
- {periodOn
1223
- ? "Only rows dated inside the period below are counted."
1224
- : "All time, so every row this cell's filter matches is counted whatever its date. "
1225
- + "Saving leaves it that way."}
 
 
1226
  </p>
1227
  </div>
1228
 
1229
  {periodOn && (
1230
  <>
 
 
1231
  <label className="sheet-field">
1232
- <span>Unit</span>
1233
  <select
1234
- value={unit}
1235
- aria-label="Period unit"
1236
- onChange={(e) => {
1237
- const next = e.target.value as PeriodUnit;
1238
- setUnit(next);
1239
- // Re-seat the start on the new unit's first month, or the pair stops naming one
1240
- // period: `2026-08` under `quarter` is not a quarter anybody can compile.
1241
- setStart(normalizePeriodStart(next, start));
1242
- }}
1243
  >
1244
- {PERIOD_UNITS.map((u) => <option key={u.unit} value={u.unit}>{u.label}</option>)}
 
1245
  </select>
1246
  </label>
1247
 
1248
- <div className="sheet-field-row">
1249
  <label className="sheet-field">
1250
- <span>Year</span>
1251
- <select
1252
- value={String(startYear)}
1253
- aria-label="Period year"
1254
- onChange={(e) => setYear(Number(e.target.value))}
1255
- >
1256
- {years.map((y) => <option key={y} value={String(y)}>{y}</option>)}
1257
- </select>
1258
  </label>
1259
- {unit === "month" && (
1260
- <label className="sheet-field">
1261
- <span>Month</span>
1262
- <select
1263
- value={String(startMonth)}
1264
- aria-label="Period month"
1265
- onChange={(e) => setMonthOfYear(Number(e.target.value))}
1266
- >
1267
- {MONTH_NAMES.map((name, i) => (
1268
- <option key={name} value={String(i + 1)}>{name}</option>
1269
- ))}
1270
- </select>
1271
- </label>
1272
- )}
1273
- {unit === "quarter" && (
1274
  <label className="sheet-field">
1275
- <span>Quarter</span>
1276
  <select
1277
- value={String(Math.floor((startMonth - 1) / 3) + 1)}
1278
- aria-label="Period quarter"
1279
- onChange={(e) => setMonthOfYear(1 + 3 * (Number(e.target.value) - 1))}
 
 
 
 
 
 
1280
  >
1281
- {[1, 2, 3, 4].map((q) => <option key={q} value={String(q)}>{`Q${q}`}</option>)}
1282
  </select>
1283
  </label>
1284
- )}
1285
- </div>
1286
-
1287
- {/* THE QUICK PICKS. They normalize through the same function the pickers do, so This
1288
- never stamps today's month under a quarter or a year. */}
1289
- <div className="sheet-period-quick">
1290
- <button
1291
- type="button"
1292
- className="sheet-period-pick"
1293
- onClick={() => setStart(normalizePeriodStart(unit, todayYm()))}
1294
- >
1295
- This {UNIT_NOUN[unit]}
1296
- </button>
1297
- <button
1298
- type="button"
1299
- className="sheet-period-pick"
1300
- onClick={() => setStart(shiftPeriodStart(unit, todayYm(), -1))}
1301
- >
1302
- Last {UNIT_NOUN[unit]}
1303
- </button>
1304
- </div>
1305
-
1306
- {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the
1307
- sentence under it says what each one costs when the cell is copied. */}
1308
- {chosenIsMetric ? (
1309
- <div className="sheet-period-lock">
1310
- <button
1311
- type="button"
1312
- role="switch"
1313
- aria-checked={locked}
1314
- className={"sheet-lock-toggle" + (locked ? " is-on" : "")}
1315
- onClick={() => {
1316
- const next = !locked;
1317
- setLocked(next);
1318
- setAcross(next ? "none" : "period");
1319
- }}
1320
- >
1321
- <span className="sheet-lock-dot" aria-hidden />
1322
- <span>Lock this period</span>
1323
- </button>
1324
- <p className="sheet-period-note">
1325
- {locked
1326
- ? "Locked, so any copy of this cell keeps this period."
1327
- : `Not locked, so a stepped copy moves by one ${UNIT_NOUN[unit]} per cell. `
1328
- + "Right and down move forward. Left and up move backward."}
1329
- </p>
1330
- </div>
1331
- ) : (
1332
- <p className="sheet-period-note">
1333
- This period stays fixed when copied. The filter driver below is what changes.
1334
- </p>
1335
- )}
1336
 
1337
- {/* ⭐ "Use a cell" STAYS A LINK (R9). It reveals the A1 input rather than replacing the
1338
- picker, so the ordinary reader never meets a cell reference and the person who wants
1339
- one is one click away from it. */}
1340
- {!refOpen && (
1341
- <button
1342
- type="button"
1343
- className="sheet-period-link"
1344
- onClick={() => setRefOpen(true)}
1345
- >
1346
- Use a cell
1347
- </button>
1348
- )}
1349
- {refOpen && (
1350
- <label className="sheet-field">
1351
- <span>Period from a cell</span>
1352
- <input
1353
- type="text"
1354
- value={periodRef}
1355
- onChange={(e) => setPeriodRef(e.target.value)}
1356
- placeholder="$B$1"
1357
- />
1358
- </label>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1359
  )}
1360
  </>
1361
  )}
@@ -1365,59 +1498,101 @@ export default function BindingEditor({
1365
  <fieldset className="sheet-scope sheet-drag">
1366
  <legend>When copied</legend>
1367
 
1368
- {chosenIsMetric ? (
1369
- periodOn ? (
1370
- <>
1371
- <label className="sheet-field">
1372
- <span>Period</span>
1373
- <select
1374
- value={!locked && across === "period" ? "period" : "none"}
1375
- aria-label="Period step when copied"
1376
- onChange={(e) => {
1377
- const step = e.target.value === "period";
1378
- setAcross(step ? "period" : "none");
1379
- setLocked(!step);
1380
- }}
1381
- >
1382
- <option value="period">{`Step by ${UNIT_NOUN[unit]}`}</option>
1383
- <option value="none">Keep this period</option>
1384
- </select>
1385
- </label>
1386
- <p className="sheet-period-note">
1387
- Right and down move forward. Left and up move backward.
1388
- </p>
1389
- </>
1390
- ) : (
1391
- <p className="sheet-period-note">
1392
- This metric is all time, so copied cells keep the same all-time period.
1393
- </p>
1394
- )
1395
- ) : (
1396
  <>
1397
  <label className="sheet-field">
1398
- <span>Filter driver</span>
1399
  <select
1400
- value={downField}
1401
- aria-label="Filter driver when copied"
1402
- onChange={(e) => setDownField(e.target.value)}
 
 
 
 
1403
  >
1404
- <option value="">Keep this filter</option>
1405
- {dragDownFields.map((f) => (
1406
- <option key={f.key} value={f.key}>{`Step by ${f.label}`}</option>
1407
- ))}
1408
  </select>
1409
  </label>
1410
- {dragDownFields.length === 0 ? (
1411
- <p className="sheet-period-note">
1412
- This database has no single select or link field with ordered options.
1413
- </p>
1414
- ) : (
1415
- <p className="sheet-period-note">
1416
- Right and down choose later options. Left and up choose earlier options.
1417
- </p>
1418
- )}
1419
  </>
1420
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1421
  </fieldset>
1422
 
1423
  {/* β›”β›” W53-T16 (owner instruction 13) - THE FOUR SENTENCE SUMMARY IS DELETED, NOT HIDDEN.
 
43
  import { BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface";
44
  import type { Field, FilterTree, Row } from "../customer-grid/types";
45
  import { choiceVocabulary, topicForScope } from "../customer-grid/types";
46
+ import type { WindowSpec } from "../customer-grid/windows";
47
+ import { normalizeWindow } from "../customer-grid/windows";
48
  // ⭐⭐ W53-T15 (ruling R8) β€” THE FILTER BUILDER IS NO LONGER MOUNTED IN THIS COLUMN. The SHARED
49
  // `FilterBuilderPanel` the Data module also uses is untouched; `SheetFilterPopup` wraps it in the
50
  // base kit's centred dialog so its condition rows have room, and only the Sheet mounts that
51
  // wrapper. This file therefore stops importing the panel itself.
52
  import { countConditions, isNumericType } from "../filter-kit/ops";
53
  import { SheetFilterPopup } from "../filter-kit/SheetFilterPopup";
54
+ import { WindowPicker } from "../filter-kit/WindowPicker";
55
  import { useEscapeClose } from "../ui/useEscapeClose";
56
  import { previewCell } from "./sheetApi";
57
+ import { bindingDisplay, bindingFilterClauses } from "./types";
58
 
59
  const AGGREGATES = [
60
  { fn: "sum", label: "Sum" },
 
97
  * the field's `type` (the two live ones on `customer_data` are typed `currency` and `int`). */
98
  const isMetricField = (f: Field): boolean => Boolean(f.measure);
99
 
100
+ /** ⭐ `custom`, not `measure`, identifies a Metric made in the table. `isMetricField` alone is the
101
+ * trap: it includes exactly the user-created Metric columns the cell picker must exclude. */
102
+ const isUserMetricField = (f: Field): boolean => isMetricField(f) && f.custom === true;
103
+
104
+ /** ⭐ `custom`, not `measure`, separates supplied templates from table-made Metrics.
105
+ * `isMetricField` alone is the trap because it includes both kinds. */
106
+ const isTemplateMetricField = (f: Field): boolean => isMetricField(f) && f.custom !== true;
107
+
108
  /** Can this database add this column up? Mirrors `modules/sheet.py::aggregate_refusal`. */
109
  const canTotal = (f: Field): boolean => {
110
  if (f.type === "formula") return false;
 
144
  start: string;
145
  locked: boolean;
146
  ref?: string;
147
+ window?: WindowSpec;
148
  }
149
 
150
  export const PERIOD_UNITS: { unit: PeriodUnit; label: string }[] = [
 
229
  if (!raw || typeof raw !== "object") return null;
230
  const p = raw as Record<string, unknown>;
231
  const ref = typeof p.ref === "string" && p.ref.trim() ? p.ref.trim() : "";
232
+ // β›” C5 - A DECLARED WINDOW MUST VALIDATE AS THE SHARED WINDOW VOCABULARY. Letting an invalid
233
+ // window fall through would misread it as the legacy ref-only dialect or invent a calendar month.
234
+ if ("window" in p) {
235
+ const window = normalizeWindow(p.window);
236
+ if (!window) return null;
237
+ return {
238
+ unit: "month",
239
+ start: normalizePeriodStart("month", todayYm()),
240
+ locked: true,
241
+ window,
242
+ };
243
+ }
244
  const declared = PERIOD_UNITS.some((u) => u.unit === p.unit);
245
  if (!declared) {
246
  // The legacy shape. Nothing shifts by surprise: it reads back LOCKED.
 
435
  trapFocus: true,
436
  });
437
 
438
+ const offersTemplateMetric = offered.some(isTemplateMetricField);
439
+ // β›” W56-T19 - A NARROWED LIST MUST SAY WHAT WAS WITHHELD. Without this cause, a database whose
440
+ // only usable-looking Metrics were made here would present a silent empty picker as if it had none.
441
+ const hasOnlyUnofferedUserMetrics = all.some(isUserMetricField) && !offersTemplateMetric;
442
 
443
  return (
444
  <BodyPortal>
 
541
  </div>
542
  )}
543
 
544
+ {/* β›” AN EMPTY LIST SAYS WHY (R16). The causes need different acts from the reader,
545
+ and the user-Metric-only cause has its own honest explanation directly below. */}
546
+ {shown.length === 0 && (offered.length > 0 || !hasOnlyUnofferedUserMetrics) && (
547
  <p className="sheet-pick-empty">
548
  {offered.length > 0
549
  ? "No column matches that search."
 
554
  </p>
555
  )}
556
 
557
+ {hasOnlyUnofferedUserMetrics && (
 
 
558
  <p className="sheet-pick-empty">
559
+ This database&apos;s Metric columns were created here rather than supplied as templates,
560
+ so they are not offered for a cell; a template metric is measured over the period this
561
+ panel sets.
562
+ </p>
563
+ )}
564
+
565
+ {/* ⭐ W56-T19, said where the choice is made: a template Metric is the one offered kind
566
+ whose value is measured over the period the panel sets. */}
567
+ {offersTemplateMetric && shown.length > 0 && (
568
+ <p className="sheet-pick-empty">
569
+ A template Metric column is measured over the period you choose in the panel.
570
  </p>
571
  )}
572
  </div>
 
727
  );
728
  const [locked, setLocked] = useState<boolean>(migrated?.locked ?? false);
729
  const [periodRef, setPeriodRef] = useState<string>(migrated?.ref ?? "");
730
+ // ⭐ C5 - THE TWO PERIOD SPELLINGS ARE SIBLINGS. The mode is seeded from the saved dialect so
731
+ // opening and saving a rolling window cannot silently turn it into this month's calendar period.
732
+ const [periodMode, setPeriodMode] = useState<"calendar" | "window">(
733
+ migrated?.window ? "window" : "calendar",
734
+ );
735
+ const [windowSpec, setWindowSpec] = useState<WindowSpec>(migrated?.window ?? { kind: "ytd" });
736
  // "Use a cell" is a LINK that REVEALS the A1 input (R9). The input was the whole period control
737
  // before this ticket and it is not deleted, only demoted to the thing behind that link.
738
  const [refOpen, setRefOpen] = useState<boolean>(Boolean(migrated?.ref));
 
911
  // column behaves like a number; `canTotal` says this database holds a number to add up. Offering
912
  // a column that fails the second one hands back a refusal instead of a value, which is the exact
913
  // shape of the report this ticket answers.
914
+ // β›” W56-T19 - METRICS MADE HERE ARE NOT TEMPLATE OFFERS. The `custom` flag is the separator;
915
+ // testing `measure` alone would put every excluded user-created Metric straight back in the list.
916
  const numericFields = useMemo(
917
+ () => fields.filter((f) => {
918
+ // β›” DATE METRICS ARE EXCLUDED BY TYPE, never by a mutable label or key naming convention.
919
+ if (isMetricField(f) && (f.type === "date" || f.type === "created_time")) return false;
920
+ return isNumericType(f.type) && canTotal(f) && !isUserMetricField(f);
921
+ }),
922
  [fields],
923
  );
924
 
 
944
  [fields],
945
  );
946
 
947
+ /**
948
+ * ⭐⭐ R8 OFFERS THE CELL'S CLAUSES, NOT THE DATABASE'S WHOLE FIELD LIST. The filter tree says
949
+ * which values a drag can actually rewrite; `dragDownFields` remains the one steppability set.
950
+ *
951
+ * β›” Every clause stays in the offer even when it cannot step. Omitting a set, measure, missing
952
+ * column or unordered field would make a configured filter disappear without explaining why.
953
+ * The full reason remains the option's hover title; `shortReason` keeps the closed select legible
954
+ * in this narrow panel without throwing that explanation away.
955
+ */
956
+ const filterClauseOffers = useMemo(() => {
957
+ const fieldsByKey = new Map(fields.map((candidate) => [candidate.key, candidate]));
958
+ const steppableKeys = new Set(dragDownFields.map((candidate) => candidate.key));
959
+ return bindingFilterClauses(tree).map((clause) => {
960
+ const clauseField = fieldsByKey.get(clause.colId);
961
+ const label = clauseField?.label?.trim() || clause.colId;
962
+ let reason = "";
963
+ let shortReason = "";
964
+ if (clause.measure) {
965
+ reason = "This measure condition compares a number over a window, not an option.";
966
+ shortReason = "compares a number over a window";
967
+ } else if (clause.multiValued) {
968
+ reason = "This clause holds a set of values (is any of), so it has no next value; it has several.";
969
+ shortReason = "a set of values, so there is no next one";
970
+ } else if (!clauseField) {
971
+ reason = "This column is not on this database any more, so nothing can look up its options.";
972
+ shortReason = "not on this database any more";
973
+ } else if (clauseField.multi || clauseField.type === "multiselect") {
974
+ reason = "This column is multi-valued or a multiselect, so it has no next value; it has several.";
975
+ shortReason = "several values per record";
976
+ } else if (!steppableKeys.has(clause.colId)) {
977
+ reason = "This column is not a single select, status or link, so it has no option order to advance through.";
978
+ shortReason = "no option order to advance through";
979
+ }
980
+ return {
981
+ colId: clause.colId,
982
+ label,
983
+ value: clause.value,
984
+ canStep: !reason,
985
+ reason,
986
+ shortReason,
987
+ };
988
+ });
989
+ }, [tree, fields, dragDownFields]);
990
+
991
+ /**
992
+ * β›” A SAVED DRIVER STAYS VISIBLE WHEN THE CURRENT OFFER SET NO LONGER CARRIES IT. Letting the
993
+ * native select fall back to its first row would paint "Keep this filter" and silently overwrite
994
+ * the saved choice on Save, the same narrowing failure shape as D-660.
995
+ */
996
+ const savedDragDriverMissing = Boolean(downField) && (scopeKind === "view"
997
+ ? !dragDownFields.some((candidate) => candidate.key === downField)
998
+ : !filterClauseOffers.some((clause) => clause.colId === downField));
999
+
1000
  /**
1001
  * ⭐⭐ W50-T21 (owner instruction 24: *"Sheet column picker (sum/count) shows the Field icons."*)
1002
  *
 
1030
  const chosenField = useMemo(() => fields.find((f) => f.key === field), [fields, field]);
1031
  /** Metric columns step their period; every other aggregate steps one chosen filter driver. */
1032
  const chosenIsMetric = Boolean(chosenField && isMetricField(chosenField));
1033
+ const chosenIsTemplateMetric = Boolean(chosenField && isTemplateMetricField(chosenField));
1034
+
1035
+ // ⭐⭐ W56-T19 - A TEMPLATE METRIC HAS NO ALL-TIME READING. Raising the existing switch in an
1036
+ // effect reveals the period controls immediately, while the ready gate below covers this render.
1037
+ useEffect(() => {
1038
+ if (chosenIsTemplateMetric) setPeriodOn(true);
1039
+ }, [chosenIsTemplateMetric]);
1040
 
1041
  /** The database's own label, which the column list's heading names. Two databases can both
1042
  * carry a column called "Total", and the heading is where that ambiguity is answered. */
 
1065
  // stamped to this month's default, and turning the switch off drops the key rather than writing
1066
  // an empty period the server would have to guess about.
1067
  if (periodOn) {
1068
+ // β›” C5 - EMIT EXACTLY ONE DIALECT. `clean_period` prefers unit/start when both are present,
1069
+ // so combining these branches would silently discard the rolling window.
1070
+ if (periodMode === "window") {
1071
+ out.period = { window: windowSpec };
1072
+ } else {
1073
+ const period: Record<string, unknown> = {
1074
+ unit, start, locked: chosenIsMetric ? locked : true,
1075
+ };
1076
+ if (refOpen && periodRef.trim()) period.ref = periodRef.trim();
1077
+ out.period = period;
1078
+ }
1079
  }
1080
+ // β›”β›” R8 REVOKED W51-T12'S ONE-AXIS-AT-A-TIME RULE. The wire keys keep C2's spelling
1081
+ // because `clean_on_drag` rebuilds anything else; emitting both slots independently lets one
1082
+ // Metric cell step its period and one filter clause without either choice erasing the other.
1083
+ out.onDrag = {
1084
+ across: chosenIsMetric && periodOn && periodMode === "calendar" && !locked ? across : "none",
1085
+ down: downField ? { field: downField } : "none",
1086
+ };
1087
  return out;
1088
  }, [database, fn, field, scopeKind, viewId, views, tree, initial,
1089
+ unit, start, locked, refOpen, periodRef, periodOn, periodMode, windowSpec,
1090
+ across, downField, chosenIsMetric]);
1091
 
1092
  // ⭐ THE NUMBER APPEARS BEFORE SAVING. `preview` evaluates the binding without persisting it,
1093
  // which is what lets someone see whether they picked the right thing while they can still change
 
1107
  // A cell bound to a live view satisfies every other clause the moment the panel mounts, and a
1108
  // Save taken then would write back a binding assembled from a list nobody had seen yet.
1109
  const ready = optionsResolved && Boolean(database) && (fn === "count" || Boolean(field))
1110
+ && (scopeKind === "filter" || Boolean(viewId))
1111
+ && (!chosenIsTemplateMetric || periodOn);
1112
 
1113
  const { y: startYear, m: startMonth } = splitYm(start);
1114
  const thisYear = new Date().getFullYear();
 
1330
  type="button"
1331
  role="switch"
1332
  aria-checked={periodOn}
1333
+ aria-disabled={chosenIsTemplateMetric}
1334
+ disabled={chosenIsTemplateMetric}
1335
  className={"sheet-lock-toggle" + (periodOn ? " is-on" : "")}
1336
  onClick={() => setPeriodOn((v) => !v)}
1337
  >
 
1339
  <span>Limit this cell to a period</span>
1340
  </button>
1341
  <p className="sheet-period-note">
1342
+ {chosenIsTemplateMetric
1343
+ ? "The period is required because this column is measured over one."
1344
+ : (periodOn
1345
+ ? "Only rows dated inside the period below are counted."
1346
+ : "All time, so every row this cell's filter matches is counted whatever its date. "
1347
+ + "Saving leaves it that way.")}
1348
  </p>
1349
  </div>
1350
 
1351
  {periodOn && (
1352
  <>
1353
+ {/* ⭐ C5 - THE MODE LABELS SAY WHAT EACH CHOICE DOES. Internal dialect names
1354
+ would make the reader guess which one can step and which one follows today. */}
1355
  <label className="sheet-field">
1356
+ <span>How to choose the period</span>
1357
  <select
1358
+ value={periodMode}
1359
+ aria-label="How this period is chosen"
1360
+ onChange={(e) => setPeriodMode(e.target.value as "calendar" | "window")}
 
 
 
 
 
 
1361
  >
1362
+ <option value="calendar">Pick a calendar period by year and month</option>
1363
+ <option value="window">Use a rolling window such as year to date</option>
1364
  </select>
1365
  </label>
1366
 
1367
+ {periodMode === "window" ? (
1368
  <label className="sheet-field">
1369
+ <span>Window</span>
1370
+ <WindowPicker window={windowSpec} onWindow={setWindowSpec} />
 
 
 
 
 
 
1371
  </label>
1372
+ ) : (
1373
+ <>
 
 
 
 
 
 
 
 
 
 
 
 
 
1374
  <label className="sheet-field">
1375
+ <span>Unit</span>
1376
  <select
1377
+ value={unit}
1378
+ aria-label="Period unit"
1379
+ onChange={(e) => {
1380
+ const next = e.target.value as PeriodUnit;
1381
+ setUnit(next);
1382
+ // Re-seat the start on the new unit's first month, or the pair stops naming one
1383
+ // period: `2026-08` under `quarter` is not a quarter anybody can compile.
1384
+ setStart(normalizePeriodStart(next, start));
1385
+ }}
1386
  >
1387
+ {PERIOD_UNITS.map((u) => <option key={u.unit} value={u.unit}>{u.label}</option>)}
1388
  </select>
1389
  </label>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1390
 
1391
+ <div className="sheet-field-row">
1392
+ <label className="sheet-field">
1393
+ <span>Year</span>
1394
+ <select
1395
+ value={String(startYear)}
1396
+ aria-label="Period year"
1397
+ onChange={(e) => setYear(Number(e.target.value))}
1398
+ >
1399
+ {years.map((y) => <option key={y} value={String(y)}>{y}</option>)}
1400
+ </select>
1401
+ </label>
1402
+ {unit === "month" && (
1403
+ <label className="sheet-field">
1404
+ <span>Month</span>
1405
+ <select
1406
+ value={String(startMonth)}
1407
+ aria-label="Period month"
1408
+ onChange={(e) => setMonthOfYear(Number(e.target.value))}
1409
+ >
1410
+ {MONTH_NAMES.map((name, i) => (
1411
+ <option key={name} value={String(i + 1)}>{name}</option>
1412
+ ))}
1413
+ </select>
1414
+ </label>
1415
+ )}
1416
+ {unit === "quarter" && (
1417
+ <label className="sheet-field">
1418
+ <span>Quarter</span>
1419
+ <select
1420
+ value={String(Math.floor((startMonth - 1) / 3) + 1)}
1421
+ aria-label="Period quarter"
1422
+ onChange={(e) => setMonthOfYear(1 + 3 * (Number(e.target.value) - 1))}
1423
+ >
1424
+ {[1, 2, 3, 4].map((q) => <option key={q} value={String(q)}>{`Q${q}`}</option>)}
1425
+ </select>
1426
+ </label>
1427
+ )}
1428
+ </div>
1429
+
1430
+ {/* W56-T21 (owner instruction 13) - THE QUICK PICKS ARE GONE. Unit, year and
1431
+ month-or-quarter already reach every period the This and Last buttons
1432
+ could, so a second control for the same value was a second way to say one
1433
+ thing. `normalizePeriodStart` still normalises all three selects, and
1434
+ `shiftPeriodStart` stays exported for the drag arithmetic. */}
1435
+
1436
+ {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the
1437
+ sentence under it says what each one costs when the cell is copied. */}
1438
+ {chosenIsMetric ? (
1439
+ <div className="sheet-period-lock">
1440
+ <button
1441
+ type="button"
1442
+ role="switch"
1443
+ aria-checked={locked}
1444
+ className={"sheet-lock-toggle" + (locked ? " is-on" : "")}
1445
+ onClick={() => {
1446
+ const next = !locked;
1447
+ setLocked(next);
1448
+ setAcross(next ? "none" : "period");
1449
+ }}
1450
+ >
1451
+ <span className="sheet-lock-dot" aria-hidden />
1452
+ <span>Lock this period</span>
1453
+ </button>
1454
+ <p className="sheet-period-note">
1455
+ {locked
1456
+ ? "Locked, so any copy of this cell keeps this period."
1457
+ : `Not locked, so a stepped copy moves by one ${UNIT_NOUN[unit]} per cell. `
1458
+ + "Right and down move forward. Left and up move backward."}
1459
+ </p>
1460
+ </div>
1461
+ ) : (
1462
+ <p className="sheet-period-note">
1463
+ This period stays fixed when copied. The filter clause below is what
1464
+ changes.
1465
+ </p>
1466
+ )}
1467
+
1468
+ {/* ⭐ "Use a cell" STAYS A LINK (R9). It reveals the A1 input rather than replacing the
1469
+ picker, so the ordinary reader never meets a cell reference and the person who wants
1470
+ one is one click away from it. */}
1471
+ {!refOpen && (
1472
+ <button
1473
+ type="button"
1474
+ className="sheet-period-link"
1475
+ onClick={() => setRefOpen(true)}
1476
+ >
1477
+ Use a cell
1478
+ </button>
1479
+ )}
1480
+ {refOpen && (
1481
+ <label className="sheet-field">
1482
+ <span>Period from a cell</span>
1483
+ <input
1484
+ type="text"
1485
+ value={periodRef}
1486
+ onChange={(e) => setPeriodRef(e.target.value)}
1487
+ placeholder="$B$1"
1488
+ />
1489
+ </label>
1490
+ )}
1491
+ </>
1492
  )}
1493
  </>
1494
  )}
 
1498
  <fieldset className="sheet-scope sheet-drag">
1499
  <legend>When copied</legend>
1500
 
1501
+ {chosenIsMetric && periodOn && periodMode === "calendar" && (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1502
  <>
1503
  <label className="sheet-field">
1504
+ <span>Period</span>
1505
  <select
1506
+ value={!locked && across === "period" ? "period" : "none"}
1507
+ aria-label="Period step when copied"
1508
+ onChange={(e) => {
1509
+ const step = e.target.value === "period";
1510
+ setAcross(step ? "period" : "none");
1511
+ setLocked(!step);
1512
+ }}
1513
  >
1514
+ <option value="period">{`Step by ${UNIT_NOUN[unit]}`}</option>
1515
+ <option value="none">Keep this period</option>
 
 
1516
  </select>
1517
  </label>
1518
+ <p className="sheet-period-note">
1519
+ Right and down move forward. Left and up move backward.
1520
+ </p>
 
 
 
 
 
 
1521
  </>
1522
  )}
1523
+
1524
+ {/* β›” C5 - A ROLLING WINDOW HAS NO START TO SHIFT. Offering the calendar step here
1525
+ would promise an action `dragBoundCell` cannot perform. */}
1526
+ {periodOn && periodMode === "window" && (
1527
+ <p className="sheet-period-note">
1528
+ A rolling window is measured from today, so every copy of this cell answers the
1529
+ same window. Use a calendar period when the period should step as the cell is copied.
1530
+ </p>
1531
+ )}
1532
+
1533
+ {/* ⚠ AN ALL-TIME METRIC SAYS WHY NO PERIOD PICKER IS PRESENT. Without this note the
1534
+ absent control looks like a loading or configuration failure. */}
1535
+ {chosenIsMetric && !periodOn && (
1536
+ <p className="sheet-period-note">
1537
+ This metric is all time, so copied cells keep the same all-time period.
1538
+ </p>
1539
+ )}
1540
+
1541
+ <label className="sheet-field">
1542
+ <span>Filter clause</span>
1543
+ <select
1544
+ value={downField}
1545
+ aria-label="Filter clause when copied"
1546
+ onChange={(e) => setDownField(e.target.value)}
1547
+ >
1548
+ <option value="">Keep this filter</option>
1549
+ {/* β›” A SAVED VIEW'S FILTER IS NOT LOADED IN THIS PANEL. Restoring the database's
1550
+ steppable columns for this branch prevents the working driver picker from
1551
+ disappearing while materialisation continues to resolve the real view filter. */}
1552
+ {scopeKind === "view"
1553
+ ? dragDownFields.map((f) => (
1554
+ <option key={f.key} value={f.key}>{`Step by ${f.label}`}</option>
1555
+ ))
1556
+ : filterClauseOffers.map((clause) => (
1557
+ <option
1558
+ key={clause.colId}
1559
+ value={clause.colId}
1560
+ disabled={!clause.canStep}
1561
+ title={clause.canStep ? undefined : clause.reason}
1562
+ >
1563
+ {clause.canStep
1564
+ ? `Step ${clause.label}, now ${clause.value || "no value"}`
1565
+ : `${clause.label} cannot step: ${clause.shortReason}`}
1566
+ </option>
1567
+ ))}
1568
+ {savedDragDriverMissing && (
1569
+ <option value={downField}>
1570
+ {`${downField}: not in this cell's filter any more`}
1571
+ </option>
1572
+ )}
1573
+ </select>
1574
+ </label>
1575
+ {savedDragDriverMissing && (
1576
+ <p className="sheet-notice" role="alert">
1577
+ The saved driver is not in this cell&apos;s filter, so copying this cell will not
1578
+ change it. Pick a driver that is in the filter, or keep the filter.
1579
+ </p>
1580
+ )}
1581
+ {scopeKind === "view" ? (
1582
+ <p className="sheet-period-note">
1583
+ These rows come from a saved view, so the view&apos;s filter clauses cannot be listed
1584
+ here. This database&apos;s steppable columns are offered instead. A driver that is not
1585
+ in the view&apos;s filter changes nothing, and the sheet says so when dragged.
1586
+ </p>
1587
+ ) : filterClauseOffers.length === 0 ? (
1588
+ <p className="sheet-period-note">
1589
+ This cell has no filter clauses to step.
1590
+ </p>
1591
+ ) : (
1592
+ <p className="sheet-period-note">
1593
+ Right and down choose later options. Left and up choose earlier options.
1594
+ </p>
1595
+ )}
1596
  </fieldset>
1597
 
1598
  {/* β›”β›” W53-T16 (owner instruction 13) - THE FOUR SENTENCE SUMMARY IS DELETED, NOT HIDDEN.
web/src/sheet/CellActionBar.tsx CHANGED
@@ -1,10 +1,11 @@
1
  // sheet/CellActionBar.tsx β€” the non-modal bar that appears beside a selected cell (W49-T05, R11).
2
  //
3
  // ⭐⭐ NON-MODAL IS THE RULING, AND IT DICTATES THREE THINGS THIS COMPONENT DOES NOT DO. R11 says a
4
- // cell click SELECTS and the bar carries Edit / View rows / Refresh. So it does NOT trap focus, it
5
- // does NOT render a backdrop, and it does NOT autofocus anything: the grid keeps the keyboard the
6
- // whole time, which is what lets someone arrow to the next cell without dismissing anything. That
7
- // is the opposite discipline from `LinkGridModal`, which is modal and traps focus deliberately.
 
8
  //
9
  // ⚠ `onMouseDown` PREVENTS DEFAULT ON THE BAR ITSELF. Without it, pressing a button blurs the grid
10
  // canvas, glide-data-grid drops its selection, and the bar unmounts before the click lands. The
@@ -25,7 +26,8 @@ export interface CellActionBarProps {
25
  busy?: boolean;
26
  onEdit: () => void;
27
  onViewRows: () => void;
28
- onRefresh: () => void;
 
29
  }
30
 
31
  function IconEdit() {
@@ -46,17 +48,8 @@ function IconRows() {
46
  );
47
  }
48
 
49
- function IconRefresh() {
50
- return (
51
- <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-action-icon">
52
- <path d="M13 8a5 5 0 1 1-1.6-3.7" />
53
- <path d="M13.2 2.6v2.9h-2.9" />
54
- </svg>
55
- );
56
- }
57
-
58
  export default function CellActionBar({
59
- anchor, drill, canEdit, busy = false, onEdit, onViewRows, onRefresh,
60
  }: CellActionBarProps) {
61
  // Clamped so a cell at the very top or the right edge still shows its bar on screen.
62
  const style: CSSProperties = {
@@ -84,15 +77,11 @@ export default function CellActionBar({
84
  // ⭐ R17: the reason is NAMED rather than left to a disabled control with no explanation.
85
  // `title` carries it on hover and `aria-description` carries it to a screen reader, so the
86
  // two audiences get the same sentence.
87
- title={drill.enabled ? "View the rows behind this cell" : drill.reason}
88
  aria-description={drill.enabled ? undefined : drill.reason}
89
  >
90
  <IconRows />
91
- <span>View rows</span>
92
- </button>
93
- <button type="button" className="sheet-action" onClick={onRefresh} disabled={busy}>
94
- <IconRefresh />
95
- <span>Refresh</span>
96
  </button>
97
  </div>
98
  );
 
1
  // sheet/CellActionBar.tsx β€” the non-modal bar that appears beside a selected cell (W49-T05, R11).
2
  //
3
  // ⭐⭐ NON-MODAL IS THE RULING, AND IT DICTATES THREE THINGS THIS COMPONENT DOES NOT DO. R11 says a
4
+ // cell click SELECTS and the bar carries Edit / View data. W56-T23 (owner instruction 16) retired
5
+ // the Refresh entry because the ribbon already carries one. So it does NOT trap focus, it does NOT
6
+ // render a backdrop, and it does NOT autofocus anything: the grid keeps the keyboard the whole time,
7
+ // which is what lets someone arrow to the next cell without dismissing anything. That is the opposite
8
+ // discipline from `LinkGridModal`, which is modal and traps focus deliberately.
9
  //
10
  // ⚠ `onMouseDown` PREVENTS DEFAULT ON THE BAR ITSELF. Without it, pressing a button blurs the grid
11
  // canvas, glide-data-grid drops its selection, and the bar unmounts before the click lands. The
 
26
  busy?: boolean;
27
  onEdit: () => void;
28
  onViewRows: () => void;
29
+ /** W56-T23 retired the button; kept only so sibling SheetGrid compiles. Drop once that file is free. */
30
+ onRefresh?: () => void;
31
  }
32
 
33
  function IconEdit() {
 
48
  );
49
  }
50
 
 
 
 
 
 
 
 
 
 
51
  export default function CellActionBar({
52
+ anchor, drill, canEdit, busy = false, onEdit, onViewRows,
53
  }: CellActionBarProps) {
54
  // Clamped so a cell at the very top or the right edge still shows its bar on screen.
55
  const style: CSSProperties = {
 
77
  // ⭐ R17: the reason is NAMED rather than left to a disabled control with no explanation.
78
  // `title` carries it on hover and `aria-description` carries it to a screen reader, so the
79
  // two audiences get the same sentence.
80
+ title={drill.enabled ? "View the data behind this cell" : drill.reason}
81
  aria-description={drill.enabled ? undefined : drill.reason}
82
  >
83
  <IconRows />
84
+ <span>View data</span>
 
 
 
 
85
  </button>
86
  </div>
87
  );
web/src/sheet/ChartDialog.tsx CHANGED
@@ -327,6 +327,11 @@ export interface ChartDialogProps {
327
  ) => void;
328
  /** The existing chart's one persisted settings write. */
329
  onUpdate?: (chart: SheetChartSpec) => void;
 
 
 
 
 
330
  /** Ribbon openers restore themselves; a chart settings button delegates restoration here. */
331
  restoreFocus?: boolean;
332
  }
@@ -337,6 +342,7 @@ export default function ChartDialog({
337
  onClose,
338
  onCreate,
339
  onUpdate,
 
340
  restoreFocus = false,
341
  }: ChartDialogProps) {
342
  const panelRef = useRef<HTMLDivElement>(null);
@@ -429,16 +435,21 @@ export default function ChartDialog({
429
 
430
  const rangeField = (
431
  <div className="sheet-chart-fields">
432
- <label className="sheet-chart-label" htmlFor={`${titleId}-range`}>Cell range</label>
433
  <input
434
  id={`${titleId}-range`}
435
  className="sheet-chart-text"
436
  type="text"
437
  value={rangeDraft}
438
  aria-invalid={range === null}
439
- aria-describedby={range === null ? `${titleId}-range-error` : undefined}
 
 
440
  onChange={(event) => setRangeDraft(event.target.value)}
441
  />
 
 
 
442
  {range === null ? (
443
  <p className="sheet-chart-caption" id={`${titleId}-range-error`} role="alert">
444
  Enter a cell range such as B2:E8.
@@ -622,6 +633,18 @@ export default function ChartDialog({
622
  </div>
623
 
624
  <div className="lp-dialog-actions">
 
 
 
 
 
 
 
 
 
 
 
 
625
  <button type="button" className="lp-dialog-btn lp-dialog-btn-quiet" onClick={onClose}>
626
  Cancel
627
  </button>
 
327
  ) => void;
328
  /** The existing chart's one persisted settings write. */
329
  onUpdate?: (chart: SheetChartSpec) => void;
330
+ /**
331
+ * R6's delete door. The mount supplies it for an existing chart, and the control stays hidden
332
+ * when the mount cannot delete.
333
+ */
334
+ onDelete?: () => void;
335
  /** Ribbon openers restore themselves; a chart settings button delegates restoration here. */
336
  restoreFocus?: boolean;
337
  }
 
342
  onClose,
343
  onCreate,
344
  onUpdate,
345
+ onDelete,
346
  restoreFocus = false,
347
  }: ChartDialogProps) {
348
  const panelRef = useRef<HTMLDivElement>(null);
 
435
 
436
  const rangeField = (
437
  <div className="sheet-chart-fields">
438
+ <label className="sheet-chart-label" htmlFor={`${titleId}-range`}>Data range</label>
439
  <input
440
  id={`${titleId}-range`}
441
  className="sheet-chart-text"
442
  type="text"
443
  value={rangeDraft}
444
  aria-invalid={range === null}
445
+ aria-describedby={range === null
446
+ ? `${titleId}-range-note ${titleId}-range-error`
447
+ : `${titleId}-range-note`}
448
  onChange={(event) => setRangeDraft(event.target.value)}
449
  />
450
+ <p className="sheet-chart-caption" id={`${titleId}-range-note`}>
451
+ The chart reads these cells, and moving or resizing it does not change them.
452
+ </p>
453
  {range === null ? (
454
  <p className="sheet-chart-caption" id={`${titleId}-range-error`} role="alert">
455
  Enter a cell range such as B2:E8.
 
633
  </div>
634
 
635
  <div className="lp-dialog-actions">
636
+ {editing && onDelete ? (
637
+ <button
638
+ type="button"
639
+ className="lp-dialog-btn sheet-chart-delete"
640
+ onClick={() => {
641
+ onDelete();
642
+ onClose();
643
+ }}
644
+ >
645
+ Delete chart
646
+ </button>
647
+ ) : null}
648
  <button type="button" className="lp-dialog-btn lp-dialog-btn-quiet" onClick={onClose}>
649
  Cancel
650
  </button>
web/src/sheet/DrillModal.tsx CHANGED
@@ -1,8 +1,8 @@
1
  // sheet/DrillModal.tsx β€” a bound cell's rows, in the Link field's own popup (W49-T07, R6/R13/R17).
2
  //
3
  // ⭐⭐ R6 SAYS "EXACTLY THE LINK FIELD TYPE'S POPUP UI", SO THIS REUSES THE COMPONENT RATHER THAN
4
- // ITS APPEARANCE. `LinkGridModal` is imported from `customer-grid/CustomerGrid.tsx`, which lane A
5
- // touched for exactly one line (its `export`). Rebuilding a lookalike would give the product two
6
  // popups that behave almost the same, and "almost" is where a focus trap or an escape key goes
7
  // missing on one of them.
8
  //
@@ -21,7 +21,7 @@
21
  // Owner, verbatim: *"Clicking View rows still takes a long time; if it must, we need a loading
22
  // button so the user knows their click worked."* This component used to render `null` for the whole
23
  // of that wait, so a drill that was working and a click that never landed looked identical. Measured
24
- // on tenant #0 (`.claude/wiki/waves/wave54/lanes/E/T36-baseline.md`): `drill_cell` costs 55 to 90 ms
25
  // against a `ut_*` table but 9,248 to 9,448 ms against `customer_data`, which goes through the
26
  // registry-module mirror rather than a DuckDB query. So the wait is real and it is long.
27
  //
@@ -42,31 +42,22 @@
42
  // Edit filter action opens the shared `SheetFilterDialog`, and one cell-scoped step of undo takes
43
  // it back.
44
  //
45
- // β›”β›” THE BAND IS PORTALLED INTO `LinkGridModal`'s OWN CARD, WHICH LOOKS LIKE A LIBERTY AND IS
46
- // THE CONSERVATIVE CHOICE. `LinkGridModal` has no slot for extra chrome and it is not this lane's
47
- // file, so the two alternatives were a floating strip positioned over its header by copied
48
- // geometry, or this. A floating strip fails three ways at once and every one of them is silent:
49
- // it is OUTSIDE `panelRef`, so the shared dismissal contract reads a click on it as an outside
50
- // pointerdown and closes the drill the instant you reach for Edit; it is outside the focus trap,
51
- // so the control is mouse-only; and it re-derives a card size it does not own. A portal into the
52
- // card is inside all three. The host is found by `data-overlay-kind="linked-record-grid"`, the
53
- // attribute that component already publishes for exactly this kind of identification, and when
54
- // it is absent the band simply does not render.
55
  //
56
- // β›” AND THE BAND MAY WEAR `.cg-link-grid-foot`, WHICH THE SKELETON ABOVE MAY NOT. The rule that
57
  // stops `DrillSkeleton` borrowing `customer-grid/RecordDetail.css` is that the skeleton stands in
58
  // for a chunk that has not arrived, so on a cold cache its class names would exist and its rules
59
- // would not. This band renders ONLY as a child of a mounted `LinkGridModal`, i.e. only once that
60
- // same chunk is in hand, so the stylesheet is guaranteed present. Same file, opposite verdict,
61
- // for one reason: WHEN it paints.
62
 
63
  import { Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from "react";
64
- import { createPortal } from "react-dom";
65
  import { fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge";
66
  import type { SurfaceScope } from "../customer-grid/apiBridge";
67
  import { dataPathHash } from "../customer-grid/dataPath";
68
- import { formatDisplay } from "../customer-grid/display";
69
- import { ModeIcon } from "../customer-grid/icons";
70
  import { AnchoredOverlay, OverlayProvider } from "../customer-grid/OverlaySurface";
71
  import type { Field, FilterTree, GridWorkspace, Row } from "../customer-grid/types";
72
  import { choiceVocabulary, mayEditField, topicForScope } from "../customer-grid/types";
@@ -77,8 +68,7 @@ import { useEscapeClose } from "../ui/useEscapeClose";
77
  import { cellViewVisibleKeys, filterFieldKeys } from "./bindingRefs";
78
  import { drillCell } from "./sheetApi";
79
  import type { CellDrill } from "./sheetApi";
80
- import { CELL_VIEW_MODES } from "./types";
81
- import type { BindingDisplay, CellViewMode } from "./types";
82
 
83
  /**
84
  * β›”β›” LAZY, AND THE BUILD IS WHAT SAID SO. A plain `import { LinkGridModal } from
@@ -90,8 +80,8 @@ import type { BindingDisplay, CellViewMode } from "./types";
90
  * Sheet page downloads the whole customer grid before anyone has drilled into anything.
91
  *
92
  * ⚠ `React.lazy` wants a DEFAULT export and `LinkGridModal` is a named one, so the promise is
93
- * mapped. That is the whole trick, and it keeps lane A's single-line change to `CustomerGrid.tsx`
94
- * intact: the export stays named, and the split is restored here rather than by widening the fence.
95
  */
96
  const LinkGridModal = lazy(() =>
97
  import("../customer-grid/CustomerGrid").then((m) => ({ default: m.LinkGridModal })),
@@ -114,191 +104,6 @@ const LinkGridModal = lazy(() =>
114
  */
115
  const warmLinkChunk = () => import("../customer-grid/CustomerGrid");
116
 
117
- const CELL_VIEW_LABELS: Record<CellViewMode, string> = {
118
- grid: "Grid",
119
- list: "List",
120
- map: "Map",
121
- };
122
-
123
- /** Compact Grid projection for a cell; values use the Data grid's one formatter. */
124
- function CellGridView(
125
- { rows, fields, identityKey }: { rows: Row[]; fields: Field[]; identityKey: string },
126
- ) {
127
- return (
128
- <div className="sheet-cell-grid" role="table" aria-label="Matching records">
129
- <div className="sheet-cell-grid-head" role="row">
130
- {fields.map((field) => <span role="columnheader" key={field.key}>{field.label}</span>)}
131
- </div>
132
- {rows.map((row) => (
133
- <div className="sheet-cell-grid-row" role="row" key={row.pid}>
134
- {fields.map((field) => (
135
- <span
136
- role="cell"
137
- className={field.key === identityKey ? "is-identity" : undefined}
138
- key={field.key}
139
- title={formatDisplay(field, row[field.key])}
140
- >
141
- {formatDisplay(field, row[field.key]) || " "}
142
- </span>
143
- ))}
144
- </div>
145
- ))}
146
- {rows.length === 0 && <div className="sheet-cell-view-empty">No records match this cell.</div>}
147
- </div>
148
- );
149
- }
150
-
151
- /** List projection keeps one record together and labels every secondary value. */
152
- function CellListView(
153
- { rows, fields, identityKey }: { rows: Row[]; fields: Field[]; identityKey: string },
154
- ) {
155
- const identity = fields.find((field) => field.key === identityKey) ?? fields[0] ?? null;
156
- const details = fields.filter((field) => field.key !== identity?.key);
157
- return (
158
- <div className="sheet-cell-list" role="list" aria-label="Matching records">
159
- {rows.map((row) => (
160
- <article className="sheet-cell-list-row" role="listitem" key={row.pid}>
161
- <h3>{identity ? formatDisplay(identity, row[identity.key]) : `Record ${row.pid}`}</h3>
162
- <div className="sheet-cell-list-fields">
163
- {details.map((field) => (
164
- <span key={field.key}>
165
- <small>{field.label}</small>
166
- <strong title={formatDisplay(field, row[field.key])}>
167
- {formatDisplay(field, row[field.key]) || " "}
168
- </strong>
169
- </span>
170
- ))}
171
- </div>
172
- </article>
173
- ))}
174
- {rows.length === 0 && <div className="sheet-cell-view-empty">No records match this cell.</div>}
175
- </div>
176
- );
177
- }
178
-
179
- interface CellMapAssets {
180
- land: string;
181
- lakes: string[];
182
- project: (lon: number, lat: number) => { x: number; y: number };
183
- parse: (value: unknown) => { lat: number; lon: number } | null;
184
- }
185
-
186
- interface CellMapSetup {
187
- latField?: string;
188
- lonField?: string;
189
- coordField?: string;
190
- }
191
-
192
- const numberAt = (value: unknown): number | null => {
193
- if (value == null || value === "") return null;
194
- const number = typeof value === "number" ? value : Number(value);
195
- return Number.isFinite(number) ? number : null;
196
- };
197
-
198
- /** The ordinary map projection, narrowed to the cell's exact row ids and without route writers. */
199
- function CellMapView({
200
- rows, identityKey, setup, assets,
201
- }: {
202
- rows: Row[];
203
- identityKey: string;
204
- setup: CellMapSetup | null;
205
- assets: CellMapAssets | null;
206
- }) {
207
- if (!assets) {
208
- return (
209
- <div className="sheet-cell-view-loading" role="status" aria-label="Loading map">
210
- <span /><span /><span /><span />
211
- </div>
212
- );
213
- }
214
- const points: { pid: number; title: string; x: number; y: number }[] = [];
215
- for (const row of rows) {
216
- let at: { lat: number; lon: number } | null = null;
217
- if (setup?.latField && setup.lonField) {
218
- const lat = numberAt(row[setup.latField]);
219
- const lon = numberAt(row[setup.lonField]);
220
- if (lat != null && lon != null) at = { lat, lon };
221
- } else if (setup?.coordField) {
222
- at = assets.parse(row[setup.coordField]);
223
- } else {
224
- const lat = numberAt(row.lat);
225
- const lon = numberAt(row.lon);
226
- if (lat != null && lon != null) at = { lat, lon };
227
- }
228
- if (!at || Math.abs(at.lat) > 85.05112878 || Math.abs(at.lon) > 180) continue;
229
- const projected = assets.project(at.lon, at.lat);
230
- points.push({
231
- pid: row.pid,
232
- title: String(row[identityKey] ?? `Record ${row.pid}`),
233
- x: projected.x,
234
- y: projected.y,
235
- });
236
- }
237
-
238
- let minX = 0;
239
- let minY = 850;
240
- let width = 4096;
241
- let height = 1450;
242
- if (points.length) {
243
- const xs = points.map((point) => point.x);
244
- const ys = points.map((point) => point.y);
245
- minX = Math.min(...xs);
246
- minY = Math.min(...ys);
247
- width = Math.max(420, Math.max(...xs) - minX);
248
- height = Math.max(260, Math.max(...ys) - minY);
249
- const pad = Math.max(width, height) * 0.18;
250
- minX -= pad;
251
- minY -= pad;
252
- width += pad * 2;
253
- height += pad * 2;
254
- const ratio = 1.72;
255
- if (width / height < ratio) {
256
- const next = height * ratio;
257
- minX -= (next - width) / 2;
258
- width = next;
259
- } else {
260
- const next = width / ratio;
261
- minY -= (next - height) / 2;
262
- height = next;
263
- }
264
- }
265
- const radius = Math.max(width, height) / 125;
266
- const missing = rows.length - points.length;
267
- return (
268
- <div className="sheet-cell-map">
269
- <svg
270
- className="sheet-cell-map-canvas"
271
- viewBox={`${minX} ${minY} ${width} ${height}`}
272
- role="img"
273
- aria-label={`${points.length.toLocaleString()} matching records on a map`}
274
- >
275
- <rect className="sheet-cell-map-water" x={minX} y={minY} width={width} height={height} />
276
- <path className="sheet-cell-map-land" d={assets.land} />
277
- {assets.lakes.map((path, index) => (
278
- <path className="sheet-cell-map-lake" d={path} key={index} />
279
- ))}
280
- {points.map((point) => (
281
- <circle
282
- className="sheet-cell-map-pin"
283
- cx={point.x}
284
- cy={point.y}
285
- r={radius}
286
- key={point.pid}
287
- >
288
- <title>{point.title}</title>
289
- </circle>
290
- ))}
291
- </svg>
292
- {missing > 0 && (
293
- <span className="sheet-cell-map-note">
294
- {`${missing.toLocaleString()} matching ${missing === 1 ? "record has" : "records have"} no location`}
295
- </span>
296
- )}
297
- {rows.length === 0 && <div className="sheet-cell-view-empty">No records match this cell.</div>}
298
- </div>
299
- );
300
- }
301
-
302
  /**
303
  * A Sheet binding names a DATABASE KEY; `LinkGridModal` wants a `SurfaceScope`. The two are not
304
  * the same vocabulary and the difference is only visible for the two compiled modules.
@@ -375,7 +180,7 @@ export type DrillCellScope = (
375
  | { kind: "view"; name: string }
376
  )
377
  & {
378
- /** W55-T07: the cell binding's own display bag, never the saved View's config. */
379
  display?: BindingDisplay;
380
  };
381
 
@@ -403,33 +208,28 @@ const sameTree = (a: FilterTree | null, b: FilterTree | null): boolean =>
403
  * The sentence is the whole of the owner's first clause, so it takes the width and truncates with
404
  * an ellipsis rather than being shortened into a count; the full text stays reachable as the
405
  * element's `title`. W55-T07 moves Edit filter to the top-right toolbar and leaves this band one
406
- * statement with one job.
 
407
  */
408
  function DrillFilterBand(
409
  { text }: { text: string },
410
  ) {
411
  return (
412
- <div
413
- // `cg-link-grid-foot` is the paint (a 52px hairline-topped band, already declared for this
414
- // card); `sheet-drill-filter` carries no rule anywhere and is not meant to, exactly like
415
- // `sheet-filter-popup`: it is the name a gate, a screenshot or a person in the inspector
416
- // can point at.
417
- className="cg-link-grid-foot sheet-drill-filter"
 
 
 
 
 
 
418
  >
419
- <span
420
- className="sheet-drill-filter-text"
421
- style={{
422
- minWidth: 0,
423
- overflow: "hidden",
424
- textOverflow: "ellipsis",
425
- whiteSpace: "nowrap",
426
- color: "var(--lp-muted)",
427
- }}
428
- title={text}
429
- >
430
- {text}
431
- </span>
432
- </div>
433
  );
434
  }
435
 
@@ -465,16 +265,15 @@ export interface DrillModalProps {
465
  */
466
  onFilterChange?: (addr: string, tree: FilterTree) => void | Promise<void>;
467
  /**
468
- * W55-T07 / R6: persist presentation on this cell's binding. The current Sheet host does not
469
- * expose this writer yet, so absence leaves a working session-local switch and no false save
470
- * claim; the typed seam is what the host must connect to its existing one-cell binding writer.
471
  */
472
  onDisplayChange?: (addr: string, display: BindingDisplay) => void | Promise<void>;
473
  }
474
 
475
  export default function DrillModal(
476
  {
477
- workbookId, addr, label, onClose, onSettled, cellScope, onFilterChange, onDisplayChange,
478
  }: DrillModalProps,
479
  ) {
480
  const [drill, setDrill] = useState<CellDrill | null>(null);
@@ -490,28 +289,6 @@ export default function DrillModal(
490
  /** Same reason, one ticket later: the page hands this an inline arrow too. */
491
  const filterChangeRef = useRef(onFilterChange);
492
  filterChangeRef.current = onFilterChange;
493
- const displayChangeRef = useRef(onDisplayChange);
494
- displayChangeRef.current = onDisplayChange;
495
-
496
- // R6: hydrate from the binding seam, not from a database View and not from localStorage.
497
- const displayKey = JSON.stringify(cellScope?.display ?? null);
498
- const hydratedDisplayRef = useRef("");
499
- const [cellDisplay, setCellDisplay] = useState<BindingDisplay>(
500
- () => cellScope?.display ?? { mode: "grid", visible: [] },
501
- );
502
- useEffect(() => {
503
- const key = `${workbookId}:${addr}:${displayKey}`;
504
- if (hydratedDisplayRef.current === key) return;
505
- hydratedDisplayRef.current = key;
506
- setCellDisplay(cellScope?.display ?? { mode: "grid", visible: [] });
507
- }, [addr, cellScope?.display, displayKey, workbookId]);
508
-
509
- const changeDisplay = useCallback((next: BindingDisplay) => {
510
- setCellDisplay(next);
511
- // No callback means no durable writer. The switch still answers the current gesture, but it
512
- // never falls back to a second browser store that would violate R6's cell-local contract.
513
- void Promise.resolve(displayChangeRef.current?.(addr, next));
514
- }, [addr]);
515
 
516
  // ── W54-T35 state ─────────────────────────────────────────────────────────────────────────
517
  /** Is the centred filter dialog on screen? */
@@ -541,19 +318,20 @@ export default function DrillModal(
541
  const [undoTree, setUndoTree] = useState<FilterTree | null>(null);
542
  /** The tree as it stood when the Edit door was last opened. See `openFilter`. */
543
  const preEditRef = useRef<FilterTree | null>(null);
 
 
 
544
  /** Bumped when a filter change has landed, so the rows are read again. */
545
  const [reloadSeq, setReloadSeq] = useState(0);
546
  /** The filter kit's two vocabularies for this database. Fetched once the drill has answered. */
547
  const [fields, setFields] = useState<Field[]>([]);
548
  const [statusValues, setStatusValues] = useState<Record<string, string[]>>({});
549
- /** Raw, permission-scoped rows back the List, Map and export projections. */
550
  const [rawRows, setRawRows] = useState<Row[]>([]);
551
  const [workspace, setWorkspace] = useState<GridWorkspace | null>(null);
552
  const [rowsResolved, setRowsResolved] = useState(false);
553
  const [rowsError, setRowsError] = useState("");
554
  const [today, setToday] = useState<string | undefined>(undefined);
555
- const [mapAssets, setMapAssets] = useState<CellMapAssets | null>(null);
556
- const [mapError, setMapError] = useState(false);
557
 
558
  useEffect(() => {
559
  let live = true;
@@ -643,6 +421,9 @@ export default function DrillModal(
643
  const shown = cellScope ?? scopeFromDrill(drill);
644
  const shownKind = shown?.kind ?? "";
645
  const shownTree = shown?.kind === "filter" ? shown.tree : null;
 
 
 
646
 
647
  /**
648
  * ⭐ THE FIELD AND VALUE VOCABULARIES, FETCHED THE WAY `BindingEditor` FETCHES THEM, and warmed
@@ -671,7 +452,7 @@ export default function DrillModal(
671
  ]);
672
  if (!live) return;
673
  if (!ws && !rowsPayload) {
674
- setRowsError("These records could not be loaded for List, Map or Export.");
675
  setRowsResolved(true);
676
  return;
677
  }
@@ -699,32 +480,44 @@ export default function DrillModal(
699
  return () => { live = false; };
700
  }, [scope]);
701
 
702
- /** Load only the two leaf geometry modules when Map is actually selected. */
703
- useEffect(() => {
704
- if (cellDisplay.mode !== "map" || mapAssets) return;
705
- let live = true;
706
- setMapError(false);
707
- void Promise.all([
708
- import("../customer-grid/mapGeometry"),
709
- import("../customer-grid/mapProjection"),
710
- ]).then(([geometry, projection]) => {
711
- if (!live) return;
712
- setMapAssets({
713
- land: geometry.LAND_PATH,
714
- lakes: geometry.LAKE_PATHS,
715
- project: projection.project,
716
- parse: (value) => projection.parseLatLon(value as Row[keyof Row]),
717
- });
718
- }, () => { if (live) setMapError(true); });
719
- return () => { live = false; };
720
- }, [cellDisplay.mode, mapAssets]);
721
-
722
  /** Persist a tree through the page's one binding writer, then read the rows again. */
723
  const applyTree = useCallback(async (tree: FilterTree) => {
724
  await Promise.resolve(filterChangeRef.current?.(addr, tree));
725
  setReloadSeq((n) => n + 1);
726
  }, [addr]);
727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
728
  /**
729
  * β›” CLOSING THE DIALOG IS THE COMMIT, and an unchanged tree commits nothing. Without that test
730
  * every open-and-look would write the cell back to itself, which is a PUT, a recompute and a
@@ -800,41 +593,6 @@ export default function DrillModal(
800
  return () => window.removeEventListener("keydown", onKey, true);
801
  }, []);
802
 
803
- /**
804
- * ⭐ THE CARD THE BAND IS PORTALLED INTO. `LinkGridModal` publishes
805
- * `data-overlay-kind="linked-record-grid"` on its own `<section>`, so this identifies it by the
806
- * attribute it already declares rather than by a class the stylesheet owns.
807
- *
808
- * ⚠ ONE RETRY ON THE NEXT FRAME, AND NO MORE. Effects run after commit, so the card is normally
809
- * in the DOM by the time this runs; the frame is there for the commit in which Suspense reveals
810
- * the chunk. A poll would be a component watching for a sibling forever.
811
- */
812
- const showRows = Boolean(drill && scope && linkReady);
813
- const [host, setHost] = useState<HTMLElement | null>(null);
814
- useEffect(() => {
815
- if (!showRows) {
816
- setHost(null);
817
- return;
818
- }
819
- const find = () =>
820
- document.querySelector<HTMLElement>('[data-overlay-kind="linked-record-grid"]');
821
- const found = find();
822
- if (found) {
823
- setHost(found);
824
- return;
825
- }
826
- const frame = window.requestAnimationFrame(() => setHost(find()));
827
- return () => window.cancelAnimationFrame(frame);
828
- }, [showRows]);
829
-
830
- const headerHost = host?.querySelector<HTMLElement>(".cg-link-grid-head") ?? null;
831
- const bodyHost = host?.querySelector<HTMLElement>(".cg-link-grid-body") ?? null;
832
- useEffect(() => {
833
- if (!bodyHost) return;
834
- bodyHost.classList.add("sheet-cell-view-custom");
835
- return () => bodyHost.classList.remove("sheet-cell-view-custom");
836
- }, [bodyHost]);
837
-
838
  /** Exact record order from the drill answer; a topic payload is only the row book. */
839
  const recordRows = useMemo(() => {
840
  if (!drill) return [];
@@ -857,7 +615,7 @@ export default function DrillModal(
857
  .map((field) => field.key);
858
  const visibleKeys = cellViewVisibleKeys(
859
  defaultFieldKeys,
860
- cellDisplay.visible,
861
  forcedFieldKeys,
862
  fields.map((field) => field.key),
863
  identityField?.key ?? "",
@@ -865,14 +623,6 @@ export default function DrillModal(
865
  const visibleFields = visibleKeys
866
  .map((key) => fields.find((field) => field.key === key))
867
  .filter((field): field is Field => Boolean(field));
868
- const mapSetup = (workspace?.mapSetup ?? null) as CellMapSetup | null;
869
- const fieldKeys = new Set(fields.map((field) => field.key));
870
- const mapSupported = Boolean(
871
- (mapSetup?.latField && mapSetup.lonField
872
- && fieldKeys.has(mapSetup.latField) && fieldKeys.has(mapSetup.lonField))
873
- || (mapSetup?.coordField && fieldKeys.has(mapSetup.coordField))
874
- || (fieldKeys.has("lat") && fieldKeys.has("lon")),
875
- );
876
 
877
  // CustomerGrid's own value-edit predicate. It distinguishes source-locked values, machine-
878
  // written pre-set fields and viewer grants field by field instead of inventing one read-only flag.
@@ -890,28 +640,10 @@ export default function DrillModal(
890
  });
891
  }, [canEditRows, drill, onClose]);
892
 
893
- const fieldsButtonRef = useRef<HTMLButtonElement>(null);
894
  const exportButtonRef = useRef<HTMLButtonElement>(null);
895
- const [fieldsOpen, setFieldsOpen] = useState(false);
896
  const [exportOpen, setExportOpen] = useState(false);
897
  const [exporting, setExporting] = useState(false);
898
 
899
- const setMode = useCallback((mode: CellViewMode) => {
900
- if (mode === "map" && rowsResolved && !mapSupported) return;
901
- changeDisplay({ ...cellDisplay, mode });
902
- }, [cellDisplay, changeDisplay, mapSupported, rowsResolved]);
903
-
904
- const setFieldVisible = useCallback((key: string, checked: boolean) => {
905
- if (!identityField || forcedFieldKeys.includes(key) || key === identityField.key) return;
906
- const chosen = new Set(visibleKeys);
907
- if (checked) chosen.add(key);
908
- else chosen.delete(key);
909
- changeDisplay({
910
- ...cellDisplay,
911
- visible: fields.map((field) => field.key).filter((fieldKey) => chosen.has(fieldKey)),
912
- });
913
- }, [cellDisplay, changeDisplay, fields, forcedFieldKeys, identityField, visibleKeys]);
914
-
915
  const exportCell = useCallback(async (format: "csv" | "xlsx" | "pdf" | "json") => {
916
  if (!allRowsLoaded || exporting) return;
917
  setExportOpen(false);
@@ -1006,171 +738,59 @@ export default function DrillModal(
1006
  table={scope}
1007
  recordIds={drill.record_ids}
1008
  editable={false}
1009
- onClose={onClose}
1010
- />
1011
- </Suspense>
1012
- {headerHost && createPortal(
1013
- <div className="sheet-cell-view-toolbar" role="toolbar" aria-label="Cell View controls">
1014
- <div className="sheet-cell-view-modes" role="group" aria-label="View mode">
1015
- {CELL_VIEW_MODES.map((mode) => {
1016
- const unavailable = mode === "map" && (!rowsResolved || !mapSupported);
1017
- return (
1018
- <button
1019
- type="button"
1020
- className="sheet-cell-view-mode"
1021
- data-active={cellDisplay.mode === mode ? "true" : undefined}
1022
- aria-pressed={cellDisplay.mode === mode}
1023
- disabled={unavailable}
1024
- title={unavailable
1025
- ? rowsResolved
1026
- ? "Map needs location fields in this database."
1027
- : "Map is loading this database's location fields."
1028
- : CELL_VIEW_LABELS[mode]}
1029
- onClick={() => setMode(mode)}
1030
- key={mode}
1031
- >
1032
- <ModeIcon mode={mode} size={13} />
1033
- <span>{CELL_VIEW_LABELS[mode]}</span>
 
 
 
1034
  </button>
1035
- );
1036
- })}
1037
- </div>
1038
- <button
1039
- ref={fieldsButtonRef}
1040
- type="button"
1041
- className="sheet-cell-view-action"
1042
- aria-haspopup="dialog"
1043
- aria-expanded={fieldsOpen}
1044
- disabled={!rowsResolved || fields.length === 0}
1045
- onClick={() => { setExportOpen(false); setFieldsOpen((open) => !open); }}
1046
- >
1047
- <svg viewBox="0 0 16 16" aria-hidden="true">
1048
- <path d="M2.5 3.5h11M2.5 8h11M2.5 12.5h11M5.5 2v12" />
1049
- </svg>
1050
- <span>Fields</span>
1051
- </button>
1052
- <button
1053
- type="button"
1054
- className="sheet-cell-view-action"
1055
- aria-haspopup="dialog"
1056
- aria-expanded={filterOpen}
1057
- disabled={shownKind !== "filter" || !onFilterChange}
1058
- title={shownKind === "view"
1059
- ? "This cell follows a saved view, so its filter is changed in Data."
1060
- : undefined}
1061
- onClick={openFilter}
1062
- >
1063
- <svg viewBox="0 0 16 16" aria-hidden="true">
1064
- <path d="M2.5 3h11L9.2 8v4.2l-2.4 1V8z" />
1065
- </svg>
1066
- <span>Edit filter</span>
1067
- </button>
1068
- {canEditRows && (
1069
- <button type="button" className="sheet-cell-view-action" onClick={editInData}>
1070
- <svg viewBox="0 0 16 16" aria-hidden="true">
1071
- <path d="m3 11.8-.3 2.1 2.1-.3 7.9-7.9-1.8-1.8zM9.9 4.9l1.8 1.8" />
1072
- </svg>
1073
- <span>Edit rows</span>
1074
- </button>
1075
- )}
1076
- <button
1077
- ref={exportButtonRef}
1078
- type="button"
1079
- className="sheet-cell-view-action"
1080
- aria-haspopup="menu"
1081
- aria-expanded={exportOpen}
1082
- disabled={!allRowsLoaded || exporting}
1083
- title={!allRowsLoaded && rowsResolved
1084
- ? "Export waits until every matching record is loaded."
1085
- : undefined}
1086
- onClick={() => { setFieldsOpen(false); setExportOpen((open) => !open); }}
1087
- >
1088
- <svg viewBox="0 0 16 16" aria-hidden="true">
1089
- <path d="M8 2v8M5 7l3 3 3-3M3 12.5h10" />
1090
- </svg>
1091
- <span>{exporting ? "Preparing" : "Export"}</span>
1092
- </button>
1093
- </div>,
1094
- headerHost,
1095
- )}
1096
- {bodyHost && createPortal(
1097
- <div className="sheet-cell-view-surface" data-mode={cellDisplay.mode}>
1098
- {!rowsResolved ? (
1099
- <div className="sheet-cell-view-loading" role="status" aria-label="Loading records">
1100
- <span /><span /><span /><span />
1101
- </div>
1102
- ) : rowsError ? (
1103
- <div className="sheet-cell-view-empty" role="alert">{rowsError}</div>
1104
- ) : cellDisplay.mode === "grid" ? (
1105
- <CellGridView
1106
- rows={recordRows}
1107
- fields={visibleFields}
1108
- identityKey={identityField?.key ?? ""}
1109
- />
1110
- ) : cellDisplay.mode === "list" ? (
1111
- <CellListView
1112
- rows={recordRows}
1113
- fields={visibleFields}
1114
- identityKey={identityField?.key ?? ""}
1115
- />
1116
- ) : mapSupported && mapError ? (
1117
- <div className="sheet-cell-view-empty" role="alert">
1118
- Map could not be loaded.
1119
- </div>
1120
- ) : mapSupported ? (
1121
- <CellMapView
1122
- rows={recordRows}
1123
- identityKey={identityField?.key ?? ""}
1124
- setup={mapSetup}
1125
- assets={mapAssets}
1126
- />
1127
- ) : (
1128
- <div className="sheet-cell-view-empty">
1129
- Map needs latitude and longitude fields in this database.
1130
  </div>
1131
  )}
1132
- {rowsResolved && !rowsError && !allRowsLoaded && (
1133
- <div className="sheet-cell-view-limit" role="status">
1134
- {`${recordRows.length.toLocaleString()} of ${(drill?.record_ids.length ?? 0).toLocaleString()} matching records are loaded.`}
1135
- </div>
1136
- )}
1137
- </div>,
1138
- bodyHost,
1139
- )}
1140
- {fieldsOpen && fieldsButtonRef.current && (
1141
- <AnchoredOverlay
1142
- anchor={fieldsButtonRef.current}
1143
- className="sheet-cell-fields-pop"
1144
- placement="bottom-end"
1145
- onDismiss={() => setFieldsOpen(false)}
1146
- role="dialog"
1147
- ariaLabel="Fields shown in this cell"
1148
- dataKind="sheet-cell-fields"
1149
- >
1150
- <div className="sheet-cell-fields-title">Fields shown in this cell</div>
1151
- <div className="sheet-cell-fields-list">
1152
- {fields.map((field) => {
1153
- const forced = field.key === identityField?.key || forcedFieldKeys.includes(field.key);
1154
- return (
1155
- <label className="sheet-cell-field-choice" key={field.key}>
1156
- <input
1157
- type="checkbox"
1158
- checked={visibleKeys.includes(field.key)}
1159
- disabled={forced}
1160
- onChange={(event) => setFieldVisible(field.key, event.target.checked)}
1161
- />
1162
- <span>{field.label}</span>
1163
- {forcedFieldKeys.includes(field.key)
1164
- ? <small>Used by filter</small>
1165
- : field.key === identityField?.key
1166
- ? <small>Identity</small>
1167
- : null}
1168
- </label>
1169
- );
1170
- })}
1171
- </div>
1172
- </AnchoredOverlay>
1173
- )}
1174
  {exportOpen && exportButtonRef.current && (
1175
  <AnchoredOverlay
1176
  anchor={exportButtonRef.current}
@@ -1194,10 +814,6 @@ export default function DrillModal(
1194
  ))}
1195
  </AnchoredOverlay>
1196
  )}
1197
- {host && bandText && createPortal(
1198
- <DrillFilterBand text={bandText} />,
1199
- host,
1200
- )}
1201
  {filterOpen && draft && (
1202
  <SheetFilterDialog
1203
  addr={addr}
 
1
  // sheet/DrillModal.tsx β€” a bound cell's rows, in the Link field's own popup (W49-T07, R6/R13/R17).
2
  //
3
  // ⭐⭐ R6 SAYS "EXACTLY THE LINK FIELD TYPE'S POPUP UI", SO THIS REUSES THE COMPONENT RATHER THAN
4
+ // ITS APPEARANCE. `LinkGridModal` is imported from `customer-grid/CustomerGrid.tsx`. Rebuilding a
5
+ // lookalike would give the product two
6
  // popups that behave almost the same, and "almost" is where a focus trap or an escape key goes
7
  // missing on one of them.
8
  //
 
21
  // Owner, verbatim: *"Clicking View rows still takes a long time; if it must, we need a loading
22
  // button so the user knows their click worked."* This component used to render `null` for the whole
23
  // of that wait, so a drill that was working and a click that never landed looked identical. Measured
24
+ // on tenant #0 (`AutoWiki/waves/wave54/lanes/E/T36-baseline.md`): `drill_cell` costs 55 to 90 ms
25
  // against a `ut_*` table but 9,248 to 9,448 ms against `customer_data`, which goes through the
26
  // registry-module mirror rather than a DuckDB query. So the wait is real and it is long.
27
  //
 
42
  // Edit filter action opens the shared `SheetFilterDialog`, and one cell-scoped step of undo takes
43
  // it back.
44
  //
45
+ // ⭐⭐ W56-T24 / R4 / C4 β€” THE LINK MODAL NOW OWNS ORDINARY SLOTS FOR THE SHEET'S CHROME.
46
+ // The toolbar and filter statement are children of the modal's header and footer, so they remain
47
+ // inside its focus trap and dismissal boundary without querying the DOM or waiting for a frame.
48
+ // The body is the default `CustomerGrid` export itself, with `cellView` relaxing only its embedded
49
+ // mode-switcher withholding. The embedded write and workspace guards remain untouched.
 
 
 
 
 
50
  //
51
+ // β›” THE REAL FOOTER MAY WEAR `.cg-link-grid-foot`, WHICH THE SKELETON ABOVE MAY NOT. The rule that
52
  // stops `DrillSkeleton` borrowing `customer-grid/RecordDetail.css` is that the skeleton stands in
53
  // for a chunk that has not arrived, so on a cold cache its class names would exist and its rules
54
+ // would not. `LinkGridModal` renders that footer only after the same chunk is in hand, so its
55
+ // stylesheet is guaranteed present. Same file, opposite verdict, for one reason: WHEN it paints.
 
56
 
57
  import { Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from "react";
 
58
  import { fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge";
59
  import type { SurfaceScope } from "../customer-grid/apiBridge";
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 { choiceVocabulary, mayEditField, topicForScope } from "../customer-grid/types";
 
68
  import { cellViewVisibleKeys, filterFieldKeys } from "./bindingRefs";
69
  import { drillCell } from "./sheetApi";
70
  import type { CellDrill } from "./sheetApi";
71
+ import type { BindingDisplay } from "./types";
 
72
 
73
  /**
74
  * β›”β›” LAZY, AND THE BUILD IS WHAT SAID SO. A plain `import { LinkGridModal } from
 
80
  * Sheet page downloads the whole customer grid before anyone has drilled into anything.
81
  *
82
  * ⚠ `React.lazy` wants a DEFAULT export and `LinkGridModal` is a named one, so the promise is
83
+ * mapped. That is the whole trick: the export stays named and the split remains intact while
84
+ * W56-T24 extends the modal through optional props.
85
  */
86
  const LinkGridModal = lazy(() =>
87
  import("../customer-grid/CustomerGrid").then((m) => ({ default: m.LinkGridModal })),
 
104
  */
105
  const warmLinkChunk = () => import("../customer-grid/CustomerGrid");
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  /**
108
  * A Sheet binding names a DATABASE KEY; `LinkGridModal` wants a `SurfaceScope`. The two are not
109
  * the same vocabulary and the difference is only visible for the two compiled modules.
 
180
  | { kind: "view"; name: string }
181
  )
182
  & {
183
+ /** W56-T24: accepted legacy cell display bag; the grid now owns presentation itself. */
184
  display?: BindingDisplay;
185
  };
186
 
 
208
  * The sentence is the whole of the owner's first clause, so it takes the width and truncates with
209
  * an ellipsis rather than being shortened into a count; the full text stays reachable as the
210
  * element's `title`. W55-T07 moves Edit filter to the top-right toolbar and leaves this band one
211
+ * statement with one job. W56-T24 seats it inside `LinkGridModal`'s footer slot, so that shell now
212
+ * supplies the `cg-link-grid-foot` paint instead of this child impersonating the footer itself.
213
  */
214
  function DrillFilterBand(
215
  { text }: { text: string },
216
  ) {
217
  return (
218
+ <span
219
+ // The modal's real `cg-link-grid-foot` wrapper supplies the paint. These classes name the
220
+ // statement itself for a gate, a screenshot or a person in the inspector.
221
+ className="sheet-drill-filter sheet-drill-filter-text"
222
+ style={{
223
+ minWidth: 0,
224
+ overflow: "hidden",
225
+ textOverflow: "ellipsis",
226
+ whiteSpace: "nowrap",
227
+ color: "var(--lp-muted)",
228
+ }}
229
+ title={text}
230
  >
231
+ {text}
232
+ </span>
 
 
 
 
 
 
 
 
 
 
 
 
233
  );
234
  }
235
 
 
265
  */
266
  onFilterChange?: (addr: string, tree: FilterTree) => void | Promise<void>;
267
  /**
268
+ * W56-T24 moved presentation to the Data grid's own switcher. This accepted-but-unused seam stays
269
+ * optional so an existing Sheet host does not need a coordinated edit.
 
270
  */
271
  onDisplayChange?: (addr: string, display: BindingDisplay) => void | Promise<void>;
272
  }
273
 
274
  export default function DrillModal(
275
  {
276
+ workbookId, addr, label, onClose, onSettled, cellScope, onFilterChange,
277
  }: DrillModalProps,
278
  ) {
279
  const [drill, setDrill] = useState<CellDrill | null>(null);
 
289
  /** Same reason, one ticket later: the page hands this an inline arrow too. */
290
  const filterChangeRef = useRef(onFilterChange);
291
  filterChangeRef.current = onFilterChange;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
 
293
  // ── W54-T35 state ─────────────────────────────────────────────────────────────────────────
294
  /** Is the centred filter dialog on screen? */
 
318
  const [undoTree, setUndoTree] = useState<FilterTree | null>(null);
319
  /** The tree as it stood when the Edit door was last opened. See `openFilter`. */
320
  const preEditRef = useRef<FilterTree | null>(null);
321
+ /** Latest grid-owned filter edit waiting for 800 ms of quiet before it reaches the cell. */
322
+ const pendingCellFilterRef = useRef<FilterTree | null>(null);
323
+ const cellFilterTimerRef = useRef<number | null>(null);
324
  /** Bumped when a filter change has landed, so the rows are read again. */
325
  const [reloadSeq, setReloadSeq] = useState(0);
326
  /** The filter kit's two vocabularies for this database. Fetched once the drill has answered. */
327
  const [fields, setFields] = useState<Field[]>([]);
328
  const [statusValues, setStatusValues] = useState<Record<string, string[]>>({});
329
+ /** Raw, permission-scoped rows back the export projection. */
330
  const [rawRows, setRawRows] = useState<Row[]>([]);
331
  const [workspace, setWorkspace] = useState<GridWorkspace | null>(null);
332
  const [rowsResolved, setRowsResolved] = useState(false);
333
  const [rowsError, setRowsError] = useState("");
334
  const [today, setToday] = useState<string | undefined>(undefined);
 
 
335
 
336
  useEffect(() => {
337
  let live = true;
 
421
  const shown = cellScope ?? scopeFromDrill(drill);
422
  const shownKind = shown?.kind ?? "";
423
  const shownTree = shown?.kind === "filter" ? shown.tree : null;
424
+ /** The cell's current tree at the instant a delayed grid edit settles. */
425
+ const shownTreeRef = useRef<FilterTree | null>(shownTree);
426
+ shownTreeRef.current = shownTree;
427
 
428
  /**
429
  * ⭐ THE FIELD AND VALUE VOCABULARIES, FETCHED THE WAY `BindingEditor` FETCHES THEM, and warmed
 
452
  ]);
453
  if (!live) return;
454
  if (!ws && !rowsPayload) {
455
+ setRowsError("These records could not be loaded for Export.");
456
  setRowsResolved(true);
457
  return;
458
  }
 
480
  return () => { live = false; };
481
  }, [scope]);
482
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
483
  /** Persist a tree through the page's one binding writer, then read the rows again. */
484
  const applyTree = useCallback(async (tree: FilterTree) => {
485
  await Promise.resolve(filterChangeRef.current?.(addr, tree));
486
  setReloadSeq((n) => n + 1);
487
  }, [addr]);
488
 
489
+ /**
490
+ * The grid filter panel reports every change. The cell commits only after the edit has been
491
+ * quiet for 800 ms, so typing one condition produces one write and one re-drill.
492
+ */
493
+ const settleCellFilter = useCallback((tree: FilterTree) => {
494
+ const current = shownTreeRef.current;
495
+ if (!current) return;
496
+ if (cellFilterTimerRef.current === null) {
497
+ // One burst gets one undo step: the tree held before its first reported change.
498
+ preEditRef.current = current;
499
+ } else {
500
+ window.clearTimeout(cellFilterTimerRef.current);
501
+ }
502
+ pendingCellFilterRef.current = tree;
503
+ cellFilterTimerRef.current = window.setTimeout(() => {
504
+ cellFilterTimerRef.current = null;
505
+ const next = pendingCellFilterRef.current;
506
+ pendingCellFilterRef.current = null;
507
+ const currentTree = shownTreeRef.current;
508
+ if (!next || !currentTree || sameTree(next, currentTree)) return;
509
+ setUndoTree(preEditRef.current);
510
+ void applyTree(next);
511
+ }, 800);
512
+ }, [applyTree]);
513
+
514
+ useEffect(() => () => {
515
+ if (cellFilterTimerRef.current !== null)
516
+ window.clearTimeout(cellFilterTimerRef.current);
517
+ cellFilterTimerRef.current = null;
518
+ pendingCellFilterRef.current = null;
519
+ }, []);
520
+
521
  /**
522
  * β›” CLOSING THE DIALOG IS THE COMMIT, and an unchanged tree commits nothing. Without that test
523
  * every open-and-look would write the cell back to itself, which is a PUT, a recompute and a
 
593
  return () => window.removeEventListener("keydown", onKey, true);
594
  }, []);
595
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
596
  /** Exact record order from the drill answer; a topic payload is only the row book. */
597
  const recordRows = useMemo(() => {
598
  if (!drill) return [];
 
615
  .map((field) => field.key);
616
  const visibleKeys = cellViewVisibleKeys(
617
  defaultFieldKeys,
618
+ [],
619
  forcedFieldKeys,
620
  fields.map((field) => field.key),
621
  identityField?.key ?? "",
 
623
  const visibleFields = visibleKeys
624
  .map((key) => fields.find((field) => field.key === key))
625
  .filter((field): field is Field => Boolean(field));
 
 
 
 
 
 
 
 
626
 
627
  // CustomerGrid's own value-edit predicate. It distinguishes source-locked values, machine-
628
  // written pre-set fields and viewer grants field by field instead of inventing one read-only flag.
 
640
  });
641
  }, [canEditRows, drill, onClose]);
642
 
 
643
  const exportButtonRef = useRef<HTMLButtonElement>(null);
 
644
  const [exportOpen, setExportOpen] = useState(false);
645
  const [exporting, setExporting] = useState(false);
646
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
647
  const exportCell = useCallback(async (format: "csv" | "xlsx" | "pdf" | "json") => {
648
  if (!allRowsLoaded || exporting) return;
649
  setExportOpen(false);
 
738
  table={scope}
739
  recordIds={drill.record_ids}
740
  editable={false}
741
+ cellView
742
+ // A view-bound cell passes neither prop: its rows remain the saved view's business.
743
+ cellFilter={shownTree ?? undefined}
744
+ onCellFilterChange={shownKind === "filter" ? settleCellFilter : undefined}
745
+ headerActions={(
746
+ <div className="sheet-cell-view-toolbar" role="toolbar" aria-label="Cell View controls">
747
+ <button
748
+ type="button"
749
+ className="sheet-cell-view-action"
750
+ aria-haspopup="dialog"
751
+ aria-expanded={filterOpen}
752
+ disabled={shownKind !== "filter" || !onFilterChange}
753
+ title={shownKind === "view"
754
+ ? "This cell follows a saved view, so its filter is changed in Data."
755
+ : undefined}
756
+ onClick={openFilter}
757
+ >
758
+ <svg viewBox="0 0 16 16" aria-hidden="true">
759
+ <path d="M2.5 3h11L9.2 8v4.2l-2.4 1V8z" />
760
+ </svg>
761
+ <span>Edit filter</span>
762
+ </button>
763
+ {canEditRows && (
764
+ <button type="button" className="sheet-cell-view-action" onClick={editInData}>
765
+ <svg viewBox="0 0 16 16" aria-hidden="true">
766
+ <path d="m3 11.8-.3 2.1 2.1-.3 7.9-7.9-1.8-1.8zM9.9 4.9l1.8 1.8" />
767
+ </svg>
768
+ <span>Edit rows</span>
769
  </button>
770
+ )}
771
+ <button
772
+ ref={exportButtonRef}
773
+ type="button"
774
+ className="sheet-cell-view-action"
775
+ aria-haspopup="menu"
776
+ aria-expanded={exportOpen}
777
+ disabled={!allRowsLoaded || exporting}
778
+ title={!allRowsLoaded && rowsResolved
779
+ ? "Export waits until every matching record is loaded."
780
+ : undefined}
781
+ onClick={() => setExportOpen((open) => !open)}
782
+ >
783
+ <svg viewBox="0 0 16 16" aria-hidden="true">
784
+ <path d="M8 2v8M5 7l3 3 3-3M3 12.5h10" />
785
+ </svg>
786
+ <span>{exporting ? "Preparing" : "Export"}</span>
787
+ </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
788
  </div>
789
  )}
790
+ footer={bandText ? <DrillFilterBand text={bandText} /> : undefined}
791
+ onClose={onClose}
792
+ />
793
+ </Suspense>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
794
  {exportOpen && exportButtonRef.current && (
795
  <AnchoredOverlay
796
  anchor={exportButtonRef.current}
 
814
  ))}
815
  </AnchoredOverlay>
816
  )}
 
 
 
 
817
  {filterOpen && draft && (
818
  <SheetFilterDialog
819
  addr={addr}
web/src/sheet/KeyTips.tsx CHANGED
@@ -1,5 +1,5 @@
1
  // sheet/KeyTips.tsx β€” Excel-style Alt key tips over the Home ribbon (wave 52, W52-T17, owner
2
- // instruction 20, ruling R7; .claude/wiki/waves/wave52/proto/excel-behaviour-spec.md Part B,
3
  // rules KT-1 through KT-21 and D-1/D-2/D-3/D-6/D-7).
4
  //
5
  // ⭐⭐ WHAT THIS COMPONENT IS. A SEPARATE keyboard-capture layer, entirely independent of
 
1
  // sheet/KeyTips.tsx β€” Excel-style Alt key tips over the Home ribbon (wave 52, W52-T17, owner
2
+ // instruction 20, ruling R7; AutoWiki/waves/wave52/proto/excel-behaviour-spec.md Part B,
3
  // rules KT-1 through KT-21 and D-1/D-2/D-3/D-6/D-7).
4
  //
5
  // ⭐⭐ WHAT THIS COMPONENT IS. A SEPARATE keyboard-capture layer, entirely independent of
web/src/sheet/Ribbon.tsx CHANGED
@@ -2,7 +2,7 @@
2
  // split per tab by wave 54's base kit).
3
  //
4
  // ⭐⭐ W54 BASE KIT 2a β€” THIS FILE IS THE FRAME, AND THE TABS ARE MODULES. It carries the tab
5
- // strip, the four action buttons, the roving-focus handler, the shared control vocabulary
6
  // (`control`, `group`, `word`, `item`) and a REGISTRY. Every Home group lives in `ribbonHome.tsx`;
7
  // a second tab is a second module registered in `TABS`, and neither module edits the other. The
8
  // reason is mechanical rather than tidy: two wave-54 lanes both extend the ribbon, and two lanes
@@ -49,6 +49,17 @@
49
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
50
  import type { KeyboardEvent, MouseEvent as ReactMouseEvent, ReactNode } from "react";
51
  import type { Cell, CellStyle, CellStylePatch, SheetChartSpec } from "./types";
 
 
 
 
 
 
 
 
 
 
 
52
  // ⭐ W52-T15 β€” a component-owned side-effect import, exactly like `customer-grid/Toolbar.tsx`'s
53
  // own `import "./filters.css"`. See the stylesheet's own header for why this is not an
54
  // `index.css` `@import` line.
@@ -203,11 +214,12 @@ const TABS = [HOME_TAB, INSERT_TAB, FORMULAS_TAB, DATA_TAB, VIEW_TAB] as const;
203
  * STRIP, NOT IN A RIBBON GROUP. They render in `sheet-ribbon-tabs`, which is on screen whether the
204
  * groups row is collapsed or not, so they belong with the collapse chevron in the set the roving
205
  * handler reaches even when collapsed rather than in a group array that vanishes with the rest.
 
206
  *
207
- * ⚠ THE KEY IS HERE AND THE BUTTON IS IN THE JSX, because the four differ in shape: one is gated
208
- * on `canImport`, two carry an icon beside a word, one of those two also reports a pressed state,
209
- * and the chevron is not a plain control button at all. `ControlKey` is derived from these keys,
210
- * so the JSX still cannot render an action under a name this list does not carry.
211
  *
212
  * ⭐⭐ W54-T08 (owner instruction 7) β€” FULL SCREEN IS NO LONGER THE ODD ONE OUT. It used to paint
213
  * its mark with the label living only in `aria-label` and `title`, and this note used to read as
@@ -215,7 +227,8 @@ const TABS = [HOME_TAB, INSERT_TAB, FORMULAS_TAB, DATA_TAB, VIEW_TAB] as const;
215
  * "Full screen" on screen, the way the Data module's always has.
216
  */
217
  const ACTIONS = [
218
- { key: "import" }, { key: "refresh" }, { key: "fullscreen" }, { key: "collapse" },
 
219
  ] as const;
220
 
221
  type TabId = (typeof TABS)[number]["id"];
@@ -233,7 +246,7 @@ type ControlKey =
233
  export type Popover = "" | ControlKey;
234
 
235
  /**
236
- * The strip: the tab buttons and the four actions. This is exactly what stays on screen when the
237
  * groups row is collapsed, which is why it is also the collapsed roving order.
238
  */
239
  const STRIP: readonly ControlKey[] = [
@@ -272,6 +285,7 @@ export interface RibbonTabContext {
272
  expanded?: boolean,
273
  kt?: string,
274
  ktOpens?: "gallery",
 
275
  ) => ReactNode;
276
  group: (name: string, body: ReactNode, extra?: string) => ReactNode;
277
  word: (text: string) => ReactNode;
@@ -335,6 +349,16 @@ function IconRefresh() {
335
  );
336
  }
337
 
 
 
 
 
 
 
 
 
 
 
338
  /**
339
  * ⭐ W52-T15 (instruction 26, contract C4) β€” THE SAME MARK THE DATA MODULE'S FULL SCREEN CONTROL
340
  * WEARS. `customer-grid/Toolbar.tsx::IconFullScreen` draws this exact path (four corner brackets
@@ -375,6 +399,18 @@ export default function Ribbon({
375
  * render-time TypeError.
376
  */
377
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
 
 
 
 
 
 
 
 
 
 
 
 
378
  const [collapsed, setCollapsed] = useState<boolean>(readCollapsed);
379
  const [formulaBarVisible, setFormulaBarVisible] = useState<boolean>(readFormulaBar);
380
  const rootRef = useRef<HTMLDivElement | null>(null);
@@ -399,15 +435,16 @@ export default function Ribbon({
399
 
400
  /**
401
  * The keys the arrows may reach right now. Collapsed, that is the strip and nothing else β€” and
402
- * the strip now carries Import, Refresh and Full screen too, since W52-T15 moved them there.
403
  * Expanded, it is the strip plus the controls of the tab that is actually showing, read off its
404
  * own descriptor rather than a list kept beside it. Import is only in the order on a page that
405
  * actually has an import door, in both branches.
406
  */
407
  const reachable = useMemo<readonly ControlKey[]>(
408
  () => (collapsed ? STRIP : [...STRIP, ...activeTab.keys])
409
- .filter((key) => key !== "import" || canImport),
410
- [activeTab, canImport, collapsed],
 
411
  );
412
 
413
  // β›” FOCUS MUST LAND ON SOMETHING THAT EXISTS. Collapsing while the focus sits on a control that
@@ -536,6 +573,23 @@ export default function Ribbon({
536
  setOpen((was) => (was === which ? "" : which));
537
  };
538
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
539
  /**
540
  * One control. `data-ribbon` is what the roving handler finds; `tabIndex` is the roving part.
541
  *
@@ -553,12 +607,13 @@ export default function Ribbon({
553
  body: ReactNode,
554
  // ⚠ W53-T07 widened this from `() => void`. A zero-argument lambda is assignable to a
555
  // one-argument function type, so every existing call site compiles unchanged; only the
556
- // nine popover triggers actually read the event, for `event.currentTarget` as the anchor.
557
  onClick: (event: ReactMouseEvent<HTMLButtonElement>) => void,
558
  pressed?: boolean,
559
  expanded?: boolean,
560
  kt?: string,
561
  ktOpens?: "gallery",
 
562
  ) => (
563
  <button
564
  type="button"
@@ -572,7 +627,7 @@ export default function Ribbon({
572
  aria-expanded={expanded}
573
  aria-haspopup={expanded === undefined ? undefined : "menu"}
574
  tabIndex={focus === key ? 0 : -1}
575
- disabled={disabled}
576
  onFocus={() => setFocus(key)}
577
  // The grid keeps the keyboard: pressing a ribbon button must not blur the canvas, or glide
578
  // drops its selection and the act lands on nothing. Same reason as `CellActionBar`.
@@ -637,6 +692,30 @@ export default function Ribbon({
637
 
638
  /** Same idiom as the Data module's own `fullscreenLabel` (`customer-grid/Toolbar.tsx`). */
639
  const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
640
 
641
  const tabContext: RibbonTabContext = {
642
  style, frozen, open, anchorEl, onApply, apply, act,
@@ -651,7 +730,8 @@ export default function Ribbon({
651
  moving anything, because the button below is written once for whatever is registered.
652
  ⭐⭐ W52-T15 (instruction 14, contract C4) β€” IMPORT, REFRESH AND FULL SCREEN SIT HERE
653
  NOW, in the SAME HORIZONTAL STRIP as the tabs, rather than in a "Workbook" ribbon
654
- group that Excel has no equivalent of. That group is gone from this file entirely. */}
 
655
  <div className="sheet-ribbon-tabs">
656
  <div className="sheet-ribbon-tablist" role="tablist" aria-label="Ribbon tabs">
657
  {TABS.map((tab) => (
@@ -679,6 +759,44 @@ export default function Ribbon({
679
  {canImport && control("import", "Import", word("Import"), () => act("import"))}
680
  {control("refresh", "Refresh", <><IconRefresh />{word("Refresh")}</>,
681
  () => act("refresh"))}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
682
  {/* ⭐⭐ W54-T08 (owner instruction 7) β€” THE WORD IS PAINTED, exactly like Refresh one
683
  line above and exactly like the Data module's own control, which renders its
684
  `fullscreenLabel` in a span beside the same mark. This used to be the mark alone.
@@ -709,7 +827,7 @@ export default function Ribbon({
709
  aria-label={activeTab.toolbarLabel}
710
  >
711
  {/* β›” `min-width: 0` ON THE SCROLLER IS LOAD BEARING. A flex child will not scroll
712
- without it. Import, Refresh and Full screen no longer live in this row at all
713
  (W52-T15 moved them to the tab strip above), so the only thing that can walk off
714
  the right edge at a narrow window now is a group itself, which scrolling permits. */}
715
  <div className="sheet-ribbon-scroll">
 
2
  // split per tab by wave 54's base kit).
3
  //
4
  // ⭐⭐ W54 BASE KIT 2a β€” THIS FILE IS THE FRAME, AND THE TABS ARE MODULES. It carries the tab
5
+ // strip, the five action buttons, the roving-focus handler, the shared control vocabulary
6
  // (`control`, `group`, `word`, `item`) and a REGISTRY. Every Home group lives in `ribbonHome.tsx`;
7
  // a second tab is a second module registered in `TABS`, and neither module edits the other. The
8
  // reason is mechanical rather than tidy: two wave-54 lanes both extend the ribbon, and two lanes
 
49
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
50
  import type { KeyboardEvent, MouseEvent as ReactMouseEvent, ReactNode } from "react";
51
  import type { Cell, CellStyle, CellStylePatch, SheetChartSpec } from "./types";
52
+ import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
53
+ import { indexToCol } from "./a1";
54
+ import {
55
+ EXPORT_FORMATS,
56
+ SHEET_EXPORT_SCAN_LIMIT,
57
+ runSheetExport,
58
+ usedRange,
59
+ workbookLabel,
60
+ type SheetExportRange,
61
+ type UsedSheetRange,
62
+ } from "./sheetExport";
63
  // ⭐ W52-T15 β€” a component-owned side-effect import, exactly like `customer-grid/Toolbar.tsx`'s
64
  // own `import "./filters.css"`. See the stylesheet's own header for why this is not an
65
  // `index.css` `@import` line.
 
214
  * STRIP, NOT IN A RIBBON GROUP. They render in `sheet-ribbon-tabs`, which is on screen whether the
215
  * groups row is collapsed or not, so they belong with the collapse chevron in the set the roving
216
  * handler reaches even when collapsed rather than in a group array that vanishes with the rest.
217
+ * W56-T17 adds Export to that same always-visible strip for the same reason.
218
  *
219
+ * ⚠ THE KEY IS HERE AND THE BUTTON IS IN THE JSX, because the five differ in shape: Import and
220
+ * Export each have their own data door, three carry an icon beside a word, Full screen reports a
221
+ * pressed state, and the chevron is not a plain control button at all. `ControlKey` is derived
222
+ * from these keys, so the JSX still cannot render an action under a name this list does not carry.
223
  *
224
  * ⭐⭐ W54-T08 (owner instruction 7) β€” FULL SCREEN IS NO LONGER THE ODD ONE OUT. It used to paint
225
  * its mark with the label living only in `aria-label` and `title`, and this note used to read as
 
227
  * "Full screen" on screen, the way the Data module's always has.
228
  */
229
  const ACTIONS = [
230
+ { key: "import" }, { key: "refresh" }, { key: "export" }, { key: "fullscreen" },
231
+ { key: "collapse" },
232
  ] as const;
233
 
234
  type TabId = (typeof TABS)[number]["id"];
 
246
  export type Popover = "" | ControlKey;
247
 
248
  /**
249
+ * The strip: the tab buttons and the five actions. This is exactly what stays on screen when the
250
  * groups row is collapsed, which is why it is also the collapsed roving order.
251
  */
252
  const STRIP: readonly ControlKey[] = [
 
285
  expanded?: boolean,
286
  kt?: string,
287
  ktOpens?: "gallery",
288
+ controlDisabled?: boolean,
289
  ) => ReactNode;
290
  group: (name: string, body: ReactNode, extra?: string) => ReactNode;
291
  word: (text: string) => ReactNode;
 
349
  );
350
  }
351
 
352
+ /** A document leaving through a downward arrow, in the same hand-drawn line style as Refresh. */
353
+ function IconExport() {
354
+ return (
355
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
356
+ <path d="M3 2.5h6l3 3v3M9 2.5v3h3M3 2.5v11h3" />
357
+ <path d="M9.5 9v4M7.5 11.5l2 2 2-2" />
358
+ </svg>
359
+ );
360
+ }
361
+
362
  /**
363
  * ⭐ W52-T15 (instruction 26, contract C4) β€” THE SAME MARK THE DATA MODULE'S FULL SCREEN CONTROL
364
  * WEARS. `customer-grid/Toolbar.tsx::IconFullScreen` draws this exact path (four corner brackets
 
399
  * render-time TypeError.
400
  */
401
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
402
+ /**
403
+ * The scan is cached against the exact document door that produced it. A changed tab/cell map
404
+ * supplies a new memoized door, making the old answer unknown without paying for another scan
405
+ * during render. `null` means the completed scan found an empty sheet.
406
+ */
407
+ const [exportScan, setExportScan] = useState<{
408
+ door: RibbonInsertDoor;
409
+ range: UsedSheetRange | null;
410
+ } | null>(null);
411
+ const [exportScope, setExportScope] = useState<"sheet" | "selection">("sheet");
412
+ const exportRange = exportScan && exportScan.door === insert ? exportScan.range : undefined;
413
+ const exportUnavailable = !insert || exportRange === null;
414
  const [collapsed, setCollapsed] = useState<boolean>(readCollapsed);
415
  const [formulaBarVisible, setFormulaBarVisible] = useState<boolean>(readFormulaBar);
416
  const rootRef = useRef<HTMLDivElement | null>(null);
 
435
 
436
  /**
437
  * The keys the arrows may reach right now. Collapsed, that is the strip and nothing else β€” and
438
+ * the strip now carries Import, Refresh, Export and Full screen too.
439
  * Expanded, it is the strip plus the controls of the tab that is actually showing, read off its
440
  * own descriptor rather than a list kept beside it. Import is only in the order on a page that
441
  * actually has an import door, in both branches.
442
  */
443
  const reachable = useMemo<readonly ControlKey[]>(
444
  () => (collapsed ? STRIP : [...STRIP, ...activeTab.keys])
445
+ .filter((key) => (key !== "import" || canImport)
446
+ && (key !== "export" || !exportUnavailable)),
447
+ [activeTab, canImport, collapsed, exportUnavailable],
448
  );
449
 
450
  // β›” FOCUS MUST LAND ON SOMETHING THAT EXISTS. Collapsing while the focus sits on a control that
 
573
  setOpen((was) => (was === which ? "" : which));
574
  };
575
 
576
+ /**
577
+ * The used-range walk costs up to two million cell reads, so it belongs to the opening gesture,
578
+ * never render. An empty result leaves a real disabled Export control instead of downloading a
579
+ * blank row. Clicking an already open trigger only closes it and does not repeat the scan.
580
+ */
581
+ const toggleExport = (event: ReactMouseEvent<HTMLButtonElement>) => {
582
+ if (open === "export") {
583
+ openPop("export")(event);
584
+ return;
585
+ }
586
+ if (!insert) return;
587
+ const range = usedRange(insert.cellAt);
588
+ setExportScan({ door: insert, range });
589
+ setExportScope("sheet");
590
+ if (range) openPop("export")(event);
591
+ };
592
+
593
  /**
594
  * One control. `data-ribbon` is what the roving handler finds; `tabIndex` is the roving part.
595
  *
 
607
  body: ReactNode,
608
  // ⚠ W53-T07 widened this from `() => void`. A zero-argument lambda is assignable to a
609
  // one-argument function type, so every existing call site compiles unchanged; only the
610
+ // popover triggers actually read the event, for `event.currentTarget` as the anchor.
611
  onClick: (event: ReactMouseEvent<HTMLButtonElement>) => void,
612
  pressed?: boolean,
613
  expanded?: boolean,
614
  kt?: string,
615
  ktOpens?: "gallery",
616
+ controlDisabled?: boolean,
617
  ) => (
618
  <button
619
  type="button"
 
627
  aria-expanded={expanded}
628
  aria-haspopup={expanded === undefined ? undefined : "menu"}
629
  tabIndex={focus === key ? 0 : -1}
630
+ disabled={disabled || controlDisabled}
631
  onFocus={() => setFocus(key)}
632
  // The grid keeps the keyboard: pressing a ribbon button must not blur the canvas, or glide
633
  // drops its selection and the act lands on nothing. Same reason as `CellActionBar`.
 
692
 
693
  /** Same idiom as the Data module's own `fullscreenLabel` (`customer-grid/Toolbar.tsx`). */
694
  const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen";
695
+ const exportLabel = !insert
696
+ ? "Export unavailable"
697
+ : exportRange === null
698
+ ? "Export, sheet is empty"
699
+ : "Export";
700
+ const selectionRange: SheetExportRange | null = insert?.selection ? {
701
+ col0: Math.min(insert.selection.col0, insert.selection.col1),
702
+ row0: Math.min(insert.selection.row0, insert.selection.row1),
703
+ col1: Math.max(insert.selection.col0, insert.selection.col1),
704
+ row1: Math.max(insert.selection.row0, insert.selection.row1),
705
+ } : null;
706
+ const selectionChoice = !!selectionRange
707
+ && (selectionRange.col0 !== selectionRange.col1 || selectionRange.row0 !== selectionRange.row1);
708
+ const chosenExportRange = exportScope === "selection" && selectionChoice
709
+ ? selectionRange
710
+ : exportRange ?? null;
711
+ const exportRangeName = chosenExportRange ? (() => {
712
+ const first = `${indexToCol(chosenExportRange.col0 + 1)}${chosenExportRange.row0 + 1}`;
713
+ const last = `${indexToCol(chosenExportRange.col1 + 1)}${chosenExportRange.row1 + 1}`;
714
+ return first === last ? first : `${first}:${last}`;
715
+ })() : "";
716
+ const exportRowCount = chosenExportRange
717
+ ? chosenExportRange.row1 - chosenExportRange.row0 + 1
718
+ : 0;
719
 
720
  const tabContext: RibbonTabContext = {
721
  style, frozen, open, anchorEl, onApply, apply, act,
 
730
  moving anything, because the button below is written once for whatever is registered.
731
  ⭐⭐ W52-T15 (instruction 14, contract C4) β€” IMPORT, REFRESH AND FULL SCREEN SIT HERE
732
  NOW, in the SAME HORIZONTAL STRIP as the tabs, rather than in a "Workbook" ribbon
733
+ group that Excel has no equivalent of. W56-T17 adds Export beside them without moving
734
+ it into the collapsible group row. */}
735
  <div className="sheet-ribbon-tabs">
736
  <div className="sheet-ribbon-tablist" role="tablist" aria-label="Ribbon tabs">
737
  {TABS.map((tab) => (
 
759
  {canImport && control("import", "Import", word("Import"), () => act("import"))}
760
  {control("refresh", "Refresh", <><IconRefresh />{word("Refresh")}</>,
761
  () => act("refresh"))}
762
+ <span className="sheet-ribbon-slot">
763
+ {control("export", exportLabel, <><IconExport />{word("Export")}</>,
764
+ toggleExport, false, open === "export", "E", "gallery", exportUnavailable)}
765
+ {open === "export" && insert && exportRange && chosenExportRange && (
766
+ <AnchoredOverlay
767
+ anchor={anchorEl}
768
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
769
+ onDismiss={closePop}
770
+ role="menu"
771
+ ariaLabel="Export workbook"
772
+ dataKind="sheet-export"
773
+ >
774
+ <span className="sheet-ribbon-label">
775
+ {`Ready to export ${exportRangeName}, ${exportRowCount} ${exportRowCount === 1 ? "row" : "rows"}`}
776
+ </span>
777
+ {exportRange.truncated && (
778
+ <span className="sheet-ribbon-label">
779
+ {`Only the first ${SHEET_EXPORT_SCAN_LIMIT.cols} columns and `}
780
+ {`${SHEET_EXPORT_SCAN_LIMIT.rows.toLocaleString()} rows were scanned, so a `}
781
+ {"larger sheet may hold cells this file does not include."}
782
+ </span>
783
+ )}
784
+ {selectionChoice && (
785
+ <>
786
+ {item("Whole sheet", () => setExportScope("sheet"),
787
+ exportScope === "sheet", "menuitemradio", "W")}
788
+ {item("Selection", () => setExportScope("selection"),
789
+ exportScope === "selection", "menuitemradio", "S")}
790
+ </>
791
+ )}
792
+ {EXPORT_FORMATS.map(({ format, label }) => item(label, () => {
793
+ void runSheetExport(format, insert.cellAt, chosenExportRange, workbookLabel());
794
+ closePop();
795
+ }, false, "menuitem", format === "csv" ? "C"
796
+ : format === "xlsx" ? "X" : format === "pdf" ? "P" : "J"))}
797
+ </AnchoredOverlay>
798
+ )}
799
+ </span>
800
  {/* ⭐⭐ W54-T08 (owner instruction 7) β€” THE WORD IS PAINTED, exactly like Refresh one
801
  line above and exactly like the Data module's own control, which renders its
802
  `fullscreenLabel` in a span beside the same mark. This used to be the mark alone.
 
827
  aria-label={activeTab.toolbarLabel}
828
  >
829
  {/* β›” `min-width: 0` ON THE SCROLLER IS LOAD BEARING. A flex child will not scroll
830
+ without it. Import, Refresh, Export and Full screen do not live in this row
831
  (W52-T15 moved them to the tab strip above), so the only thing that can walk off
832
  the right edge at a narrow window now is a group itself, which scrolling permits. */}
833
  <div className="sheet-ribbon-scroll">
web/src/sheet/SheetChart.tsx CHANGED
@@ -76,6 +76,8 @@ export interface SheetChartProps {
76
  range: SheetChartRange;
77
  cells: CellMap;
78
  kind?: SheetChartSpec["kind"];
 
 
79
  /** Rendered size in px. The SVG scales to it; the renderer is not resized. */
80
  width: number;
81
  height: number;
@@ -91,6 +93,8 @@ export interface SheetChartProps {
91
  onResize?: (dx: number, dy: number) => ChartAnchorDelta;
92
  /** Reopens this chart's persisted kind and range in the shared chart dialog. */
93
  onEdit?: () => void;
 
 
94
  }
95
 
96
  /** How far the persisted cell anchor actually moved after a pointer gesture snapped to the grid. */
@@ -277,7 +281,10 @@ const VIZ_KIND: Record<SheetChartSpec["kind"], SheetChartSpec["kind"] | null> =
277
  // The same viewBox `SeriesChart` bakes in, deliberately: two charts of different kinds sitting on
278
  // one sheet have to share a plot area, an axis inset and a label size, or the sheet reads as two
279
  // products. The wrapper is still what sizes them (see the note above).
280
- const W = 720;
 
 
 
281
  const H = 230;
282
  const PAD_L = 52;
283
  const PAD_R = 10;
@@ -794,11 +801,13 @@ export default function SheetChart({
794
  range,
795
  cells,
796
  kind = "bar",
 
797
  width,
798
  height,
799
  onMove,
800
  onResize,
801
  onEdit,
 
802
  }: SheetChartProps) {
803
  const { fields, rows, series } = useMemo(
804
  () => chartDataForRange(cells, range),
@@ -962,13 +971,17 @@ export default function SheetChart({
962
  event.preventDefault();
963
  }, [onMove, onResize, stepX, stepY]);
964
 
965
- const tools = (onMove || onResize || onEdit) ? (
966
  <div className="sheet-chart-tools">
967
  {onMove ? (
968
  <button
969
  type="button"
970
  className="sheet-chart-tool sheet-chart-grip"
971
- style={{ left: 3, right: onEdit ? 27 : 3, width: "auto" }}
 
 
 
 
972
  aria-label="Move chart. Drag this top area, or use the arrow keys."
973
  onPointerDown={beginDrag("move")}
974
  onPointerMove={duringDrag}
@@ -987,7 +1000,7 @@ export default function SheetChart({
987
  <button
988
  type="button"
989
  className="sheet-chart-tool"
990
- style={{ top: 3, right: 3 }}
991
  aria-label="Open chart settings"
992
  onPointerDown={(event) => event.stopPropagation()}
993
  onClick={(event) => {
@@ -1000,6 +1013,25 @@ export default function SheetChart({
1000
  </svg>
1001
  </button>
1002
  ) : null}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1003
  {onResize ? (
1004
  <button
1005
  type="button"
@@ -1027,11 +1059,18 @@ export default function SheetChart({
1027
  opacity: flash ? 0.72 : undefined,
1028
  };
1029
 
 
 
 
 
 
1030
  if (!series.length) {
1031
  // Named rather than drawn empty: a chart frame with no series reads as "the data is zero",
1032
  // which is a different and wrong statement.
1033
  return (
1034
- <div className="sheet-chart is-empty" style={shell} role="img"
 
 
1035
  aria-label="This range has no numeric column to chart">
1036
  <p>This range has no numeric column to chart.</p>
1037
  {tools}
@@ -1044,7 +1083,10 @@ export default function SheetChart({
1044
  // scaling it to an arbitrary cell rectangle is the wrapper's job and the renderer stays
1045
  // untouched. `viz/**` belongs to no lane in this wave, and the own-drawn kinds use the same
1046
  // viewBox for the same reason.
1047
- <div className="sheet-chart" style={shell}>
 
 
 
1048
  {delegated
1049
  ? <SeriesChart spec={spec} series={series} fields={fields} rows={rows} />
1050
  : (
 
76
  range: SheetChartRange;
77
  cells: CellMap;
78
  kind?: SheetChartSpec["kind"];
79
+ /** Whether this chart is selected in the sheet overlay. */
80
+ selected?: boolean;
81
  /** Rendered size in px. The SVG scales to it; the renderer is not resized. */
82
  width: number;
83
  height: number;
 
93
  onResize?: (dx: number, dy: number) => ChartAnchorDelta;
94
  /** Reopens this chart's persisted kind and range in the shared chart dialog. */
95
  onEdit?: () => void;
96
+ /** R6's direct removal door for the selected chart. */
97
+ onDelete?: () => void;
98
  }
99
 
100
  /** How far the persisted cell anchor actually moved after a pointer gesture snapped to the grid. */
 
281
  // The same viewBox `SeriesChart` bakes in, deliberately: two charts of different kinds sitting on
282
  // one sheet have to share a plot area, an axis inset and a label size, or the sheet reads as two
283
  // products. The wrapper is still what sizes them (see the note above).
284
+ // `viz/SeriesChart` owns this viewBox width and this file draws into the same box, so they must
285
+ // not drift.
286
+ const VIEWBOX_W = 720;
287
+ const W = VIEWBOX_W;
288
  const H = 230;
289
  const PAD_L = 52;
290
  const PAD_R = 10;
 
801
  range,
802
  cells,
803
  kind = "bar",
804
+ selected = false,
805
  width,
806
  height,
807
  onMove,
808
  onResize,
809
  onEdit,
810
+ onDelete,
811
  }: SheetChartProps) {
812
  const { fields, rows, series } = useMemo(
813
  () => chartDataForRange(cells, range),
 
971
  event.preventDefault();
972
  }, [onMove, onResize, stepX, stepY]);
973
 
974
+ const tools = (onMove || onResize || onEdit || onDelete) ? (
975
  <div className="sheet-chart-tools">
976
  {onMove ? (
977
  <button
978
  type="button"
979
  className="sheet-chart-tool sheet-chart-grip"
980
+ style={{
981
+ left: 3,
982
+ right: onDelete ? (onEdit ? 75 : 51) : (onEdit ? 27 : 3),
983
+ width: "auto",
984
+ }}
985
  aria-label="Move chart. Drag this top area, or use the arrow keys."
986
  onPointerDown={beginDrag("move")}
987
  onPointerMove={duringDrag}
 
1000
  <button
1001
  type="button"
1002
  className="sheet-chart-tool"
1003
+ style={{ top: 3, right: onDelete ? 51 : 3 }}
1004
  aria-label="Open chart settings"
1005
  onPointerDown={(event) => event.stopPropagation()}
1006
  onClick={(event) => {
 
1013
  </svg>
1014
  </button>
1015
  ) : null}
1016
+ {onDelete ? (
1017
+ <button
1018
+ type="button"
1019
+ className="sheet-chart-tool"
1020
+ style={{ top: 3, right: 27 }}
1021
+ aria-label="Delete this chart"
1022
+ onPointerDown={(event) => event.stopPropagation()}
1023
+ onClick={(event) => {
1024
+ event.stopPropagation();
1025
+ onDelete();
1026
+ }}
1027
+ >
1028
+ <svg className="sheet-chart-tool-icon" viewBox="0 0 16 16" aria-hidden="true">
1029
+ <path d="M3 4.5h10M6 2.5h4" />
1030
+ <path d="M4.5 4.5l.7 9h5.6l.7-9" />
1031
+ <path d="M7 7v4M9 7v4" />
1032
+ </svg>
1033
+ </button>
1034
+ ) : null}
1035
  {onResize ? (
1036
  <button
1037
  type="button"
 
1059
  opacity: flash ? 0.72 : undefined,
1060
  };
1061
 
1062
+ // ⭐ W56-T12, R6 and instruction 9: font-size inside a scaled viewBox is measured in user
1063
+ // units, so a constant token changes size on screen with the person's chart box. Dividing by
1064
+ // this scale keeps axis labels at one legible screen size whatever box they choose.
1065
+ const drawScale = Math.min(1, Math.max(0.3, (width + nudge.dw) / VIEWBOX_W));
1066
+
1067
  if (!series.length) {
1068
  // Named rather than drawn empty: a chart frame with no series reads as "the data is zero",
1069
  // which is a different and wrong statement.
1070
  return (
1071
+ <div className={`sheet-chart is-empty${selected ? " is-selected" : ""}`}
1072
+ style={{ ...shell, "--sheet-chart-scale": String(drawScale) } as React.CSSProperties}
1073
+ role="img"
1074
  aria-label="This range has no numeric column to chart">
1075
  <p>This range has no numeric column to chart.</p>
1076
  {tools}
 
1083
  // scaling it to an arbitrary cell rectangle is the wrapper's job and the renderer stays
1084
  // untouched. `viz/**` belongs to no lane in this wave, and the own-drawn kinds use the same
1085
  // viewBox for the same reason.
1086
+ <div
1087
+ className={`sheet-chart${selected ? " is-selected" : ""}`}
1088
+ style={{ ...shell, "--sheet-chart-scale": String(drawScale) } as React.CSSProperties}
1089
+ >
1090
  {delegated
1091
  ? <SeriesChart spec={spec} series={series} fields={fields} rows={rows} />
1092
  : (
web/src/sheet/SheetChartLayer.tsx ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * ⭐⭐ WAVE 56 BASE β€” THE CHART OVERLAY LAYER, LIFTED OUT OF `SheetGrid.tsx` UNCHANGED.
3
+ *
4
+ * β›” THIS IS A MOVE, NOT A REWRITE. Every line below arrived from `SheetGrid.tsx` byte for
5
+ * byte, comments included, because each of those comments records a MEASURED defect (D-642's
6
+ * anchor origin, W50-T19's positioning parent, W50-T20's summed column widths) and a summary of
7
+ * a scar is not a scar. The reason the code moved is a file-ownership one: recalculation,
8
+ * selection and the chart overlay were three unrelated features sharing one 5,300 line file, so
9
+ * three lanes could not own them at once. Nothing here behaves differently for having a module.
10
+ *
11
+ * β›” THE GEOMETRY IS PASSED IN, NOT RE-DERIVED. `columnX`, `rowHeightAt`, `visCols`, `visRows`,
12
+ * `frozenCols`, `bandRows`, `rowHeight` and `headerHeight` are the grid's OWN numbers, handed
13
+ * down. A second copy of any of them here would be a second answer to "where does column 12
14
+ * start", and a chart would slide off its cells the first time the two disagreed β€” which is the
15
+ * class of defect `SheetGrid.tsx`'s "Geometry shared by the grid and by any chart positioned
16
+ * over it, so the two cannot disagree" note was written about.
17
+ *
18
+ * β›” IT RENDERS A FRAGMENT AND MUST KEEP DOING SO. `.sheet-chart-anchor` is `position: absolute`
19
+ * and resolves against `.sheet-grid-canvas` (W50-T19), so wrapping these anchors in a div of our
20
+ * own would silently re-parent every one of them and reintroduce the offset that fix removed.
21
+ */
22
+ import "../styles/wave56/charts.css";
23
+
24
+ import { useCallback, useEffect, useMemo, useState } from "react";
25
+
26
+ import SheetChart from "./SheetChart";
27
+ import type { ChartAnchorDelta } from "./SheetChart";
28
+ import { lockstepScrollX } from "./sheetState";
29
+ import type { CellMap, SheetChartSpec } from "./types";
30
+
31
+ export interface SheetChartLayerProps {
32
+ /** The tab's chart list, already resolved through the document-or-local fallback. */
33
+ charts: SheetChartSpec[];
34
+ /** What every chart DRAWS: the same map the grid paints, so the two cannot show two numbers. */
35
+ cells: CellMap;
36
+ /** The visible column and row indices, in the grid's own coordinates. */
37
+ visCols: number[];
38
+ visRows: number[];
39
+ /** The grid's columns, read here only for their widths (`lockstepScrollX`). */
40
+ columns: readonly { width: number }[];
41
+ /** The x offset of one column, summed rather than multiplied: widths differ (W50-T20). */
42
+ columnX: (index: number) => number;
43
+ /** One visible row's height, wrapped rows included (W54-T06). */
44
+ rowHeightAt: (index: number) => number;
45
+ frozenCols: number;
46
+ /** How many DRAWN rows the frozen band covers, and the base height of one row. */
47
+ bandRows: number;
48
+ rowHeight: number;
49
+ /**
50
+ * `SheetGrid.tsx::HEADER_HEIGHT` β€” glide's own header height, declared there so it can be
51
+ * depended on. PASSED rather than imported: importing it back out of `SheetGrid.tsx` would
52
+ * make these two modules circular for the sake of one number.
53
+ */
54
+ headerHeight: number;
55
+ /** Glide's own scroll coordinates: x/y plus the sub-cell transforms. */
56
+ viewport: { x: number; y: number; tx: number; ty: number };
57
+ /** The tab's persisted chart writer. Settings changes use this door from the owning grid. */
58
+ onWriteCharts: (next: SheetChartSpec[]) => void;
59
+ /** Opens this chart's persisted kind and range in the shared dialog, which the grid owns. */
60
+ onEditChart: (id: string) => void;
61
+ }
62
+
63
+ export default function SheetChartLayer({
64
+ charts,
65
+ cells,
66
+ visCols,
67
+ visRows,
68
+ columns,
69
+ columnX,
70
+ rowHeightAt,
71
+ frozenCols,
72
+ bandRows,
73
+ rowHeight,
74
+ headerHeight,
75
+ viewport,
76
+ onWriteCharts,
77
+ onEditChart,
78
+ }: SheetChartLayerProps) {
79
+ /**
80
+ * ⭐ W56-T08 / R6: "R6: Charts - override all four documented decisions: the chart becomes a
81
+ * real click target (arrow keys still reach cells), resize changes SIZE only and never the data
82
+ * range, a Delete control is added, and chart fonts are raised to a legible floor and
83
+ * screenshot-verified."
84
+ *
85
+ * This ticket owns the first override. The layer holds selection because C1 gives it chart hit
86
+ * testing; the grid beneath keeps its own cell selection and keyboard cursor.
87
+ */
88
+ const [selectedId, setSelectedId] = useState<string | null>(null);
89
+
90
+ /**
91
+ * R6 removes the chart through the tab's whole-list write door and clears its layer selection,
92
+ * so no stale selected id survives after the chart disappears.
93
+ */
94
+ const deleteChart = useCallback((id: string) => {
95
+ onWriteCharts(charts.filter((chart) => chart.id !== id));
96
+ setSelectedId((current) => current === id ? null : current);
97
+ }, [charts, onWriteCharts]);
98
+
99
+ /**
100
+ * ⭐ W56-T09 / W56-T10 / R6 / instruction 9: `chart.range` is the DATA range, while the box's
101
+ * origin and span are presentation. Moving or resizing must therefore change only this
102
+ * layer-owned placement. It cannot persist yet: the server's `_clean_charts` allow-list keeps
103
+ * only `id`, `kind` and the four data-range corners. Until that contract grows, a reload
104
+ * intentionally lays the chart back over its data without ever changing the numbers it reads.
105
+ */
106
+ type ChartPlacement = { col: number; row: number; cols: number; rows: number };
107
+ const [placements, setPlacements] = useState<Record<string, ChartPlacement>>({});
108
+ /** The single answer used by gestures and paint for where this chart's presentation box is. */
109
+ const chartBox = useCallback(
110
+ (chart: SheetChartSpec): ChartPlacement => placements[chart.id] ?? {
111
+ col: Math.min(chart.range.col0, chart.range.col1),
112
+ row: Math.min(chart.range.row0, chart.range.row1),
113
+ cols: Math.abs(chart.range.col1 - chart.range.col0) + 1,
114
+ rows: Math.abs(chart.range.row1 - chart.range.row0) + 1,
115
+ },
116
+ [placements],
117
+ );
118
+
119
+ useEffect(() => {
120
+ if (selectedId === null || typeof document === "undefined") return undefined;
121
+
122
+ const clearOutsideChart = (event: PointerEvent) => {
123
+ const target = event.target;
124
+ if (!(target instanceof Element) || !target.closest(".sheet-chart-anchor")) {
125
+ setSelectedId(null);
126
+ }
127
+ };
128
+ const handleSelectionKey = (event: KeyboardEvent) => {
129
+ if (event.key === "Escape") {
130
+ setSelectedId(null);
131
+ return;
132
+ }
133
+ if (event.key !== "Delete" && event.key !== "Backspace") return;
134
+ // R6 consumes only these removal keys, otherwise the grid beneath would also clear a cell.
135
+ // Arrow keys, typing and every other key keep reaching the sheet.
136
+ event.preventDefault();
137
+ event.stopPropagation();
138
+ deleteChart(selectedId);
139
+ };
140
+
141
+ // Capture observes an outside press before the grid handles it, without consuming its event.
142
+ document.addEventListener("pointerdown", clearOutsideChart, true);
143
+ // The grid's key handler is on a descendant, so bubble phase arrives too late to stop it;
144
+ // this is the one handler in this file that deliberately consumes a key.
145
+ document.addEventListener("keydown", handleSelectionKey, true);
146
+ return () => {
147
+ document.removeEventListener("pointerdown", clearOutsideChart, true);
148
+ document.removeEventListener("keydown", handleSelectionKey, true);
149
+ };
150
+ }, [deleteChart, selectedId]);
151
+
152
+ /**
153
+ * Every main-grid row boundary, cached because wrapped rows are not uniformly tall. Building
154
+ * this once makes each chart's scroll geometry and each pointer-release snap an O(1) lookup.
155
+ */
156
+ const chartRowOffsets = useMemo(() => {
157
+ const offsets = [0];
158
+ for (let row = 0; row < visRows.length; row += 1) {
159
+ offsets.push(offsets[row] + rowHeightAt(row));
160
+ }
161
+ return offsets;
162
+ }, [rowHeightAt, visRows.length]);
163
+ const chartRowY = useCallback(
164
+ (index: number) => chartRowOffsets[Math.max(0, Math.min(index, visRows.length))] ?? 0,
165
+ [chartRowOffsets, visRows.length],
166
+ );
167
+ const chartScrollX = useMemo(
168
+ () => lockstepScrollX(
169
+ columns.map((column) => column.width), frozenCols, viewport.x, viewport.tx,
170
+ ),
171
+ [viewport.tx, viewport.x, columns, frozenCols],
172
+ );
173
+ const chartScrollY = chartRowY(viewport.y) - viewport.ty;
174
+ /**
175
+ * ⭐⭐ W54-T12 / LANE B β€” A PIXEL DELTA BECOMES CELL GEOMETRY, AND ONLY THIS FILE CAN DO IT.
176
+ *
177
+ * β›” A CHART ANCHORS TO A RECTANGLE OF CELLS. `SheetChart.tsx` owns the GESTURE and reports
178
+ * what the pointer travelled; the geometry that turns that into columns and rows is here,
179
+ * because only this component knows each column's own width, which rows are hidden, and where
180
+ * the visible table starts. R6 and instruction 9 separate the outcomes: move changes the
181
+ * layer-owned box origin, resize changes its span, and neither changes the DATA range.
182
+ *
183
+ * ⚠ THE COLUMN STEP IS A NEAREST-BOUNDARY WALK RATHER THAN A DIVISION. Column widths differ
184
+ * since W50-T20, so dividing by an average drifts by a whole column as soon as somebody has
185
+ * dragged one, and it drifts more the further right the chart sits.
186
+ *
187
+ * β›” IT CLAMPS AT BOTH ENDS AND NEVER INVERTS. A resize moves the BOX'S FAR corner only and is
188
+ * held at or past the near one, so the box cannot turn inside out and cannot leave the sheet.
189
+ */
190
+ const nudgeChart = useCallback(
191
+ (
192
+ chart: SheetChartSpec,
193
+ dx: number,
194
+ dy: number,
195
+ mode: "move" | "resize",
196
+ ): ChartAnchorDelta => {
197
+ const box = chartBox(chart);
198
+ const viewLo = visCols.indexOf(box.col);
199
+ const viewTop = visRows.indexOf(box.row);
200
+ if (viewLo < 0 || viewTop < 0) {
201
+ return { dx: 0, dy: 0 };
202
+ }
203
+ const { cols, rows } = box;
204
+ const viewHiBox = Math.min(visCols.length - 1, viewLo + cols - 1);
205
+ const viewBottomBox = Math.min(visRows.length - 1, viewTop + rows - 1);
206
+
207
+ const nearestView = (x: number) => {
208
+ let best = 0;
209
+ let bestGap = Infinity;
210
+ for (let i = 0; i < visCols.length; i += 1) {
211
+ const gap = Math.abs(columnX(i) - x);
212
+ if (gap < bestGap) { bestGap = gap; best = i; }
213
+ }
214
+ return best;
215
+ };
216
+ const nearestColumnBoundary = (x: number) => {
217
+ let best = 0;
218
+ let bestGap = Infinity;
219
+ for (let col = 0; col <= visCols.length; col += 1) {
220
+ const gap = Math.abs(columnX(col) - x);
221
+ if (gap < bestGap) { bestGap = gap; best = col; }
222
+ }
223
+ return best;
224
+ };
225
+ const nearestRow = (y: number) => {
226
+ let best = 0;
227
+ let bestGap = Infinity;
228
+ for (let row = 0; row <= visRows.length; row += 1) {
229
+ const gap = Math.abs(chartRowY(row) - y);
230
+ if (gap < bestGap) { bestGap = gap; best = row; }
231
+ }
232
+ return best;
233
+ };
234
+ const clamp = (v: number, low: number, high: number) => Math.min(high, Math.max(low, v));
235
+ const lastCol = visCols.length - 1;
236
+ const lastRow = visRows.length - 1;
237
+
238
+ if (mode === "move") {
239
+ const stepCols = clamp(
240
+ nearestView(columnX(viewLo) + dx) - viewLo, -viewLo, lastCol - viewHiBox,
241
+ );
242
+ const stepRows = clamp(
243
+ nearestRow(chartRowY(viewTop) + dy) - viewTop, -viewTop, lastRow - viewBottomBox,
244
+ );
245
+ if (stepCols === 0 && stepRows === 0) {
246
+ return { dx: 0, dy: 0 };
247
+ }
248
+ const nextLo = viewLo + stepCols;
249
+ const nextTop = viewTop + stepRows;
250
+ setPlacements((current) => ({
251
+ ...current,
252
+ [chart.id]: {
253
+ ...box,
254
+ col: visCols[nextLo],
255
+ row: visRows[nextTop],
256
+ },
257
+ }));
258
+ return {
259
+ dx: columnX(nextLo) - columnX(viewLo),
260
+ dy: chartRowY(nextTop) - chartRowY(viewTop),
261
+ };
262
+ }
263
+
264
+ const nextHiBox = clamp(
265
+ nearestColumnBoundary(columnX(viewHiBox + 1) + dx) - 1, viewLo, lastCol,
266
+ );
267
+ const nextBottomBox = clamp(
268
+ nearestRow(chartRowY(viewBottomBox + 1) + dy) - 1, viewTop, lastRow,
269
+ );
270
+ if (nextHiBox === viewHiBox && nextBottomBox === viewBottomBox) {
271
+ return { dx: 0, dy: 0 };
272
+ }
273
+ setPlacements((current) => ({
274
+ ...current,
275
+ [chart.id]: {
276
+ ...box,
277
+ cols: nextHiBox - viewLo + 1,
278
+ rows: nextBottomBox - viewTop + 1,
279
+ },
280
+ }));
281
+ return {
282
+ dx: columnX(nextHiBox + 1) - columnX(viewHiBox + 1),
283
+ dy: chartRowY(nextBottomBox + 1) - chartRowY(viewBottomBox + 1),
284
+ };
285
+ },
286
+ [chartBox, chartRowY, columnX, visCols, visRows],
287
+ );
288
+
289
+ return (
290
+ <>
291
+ {/* ⭐ R9: A CHART OCCUPIES A RECTANGLE OF CELLS. It is positioned over the canvas rather
292
+ than drawn into it, because glide owns the canvas and a chart is not a cell. The
293
+ geometry is derived from the same column width and row height the grid uses, so the
294
+ chart lands on the cells it reads and moves with them.
295
+ ⚠ The charts live on the TAB, not among the cells (contract C1 freezes the cell kinds),
296
+ so a sheet written before W49-T08 simply has none.
297
+ β›” THE ANCHORS MOVED INSIDE `.sheet-grid-canvas` (W50-T19), AND THAT IS A FIX, NOT A
298
+ TIDY. Their offsets are glide's own origin plus one header row, so they were only ever
299
+ right if the positioning parent WAS the canvas box; sitting in `.sheet-grid-wrap` they
300
+ were already the height of `.sheet-grid-head` too low, and the ribbon above would have
301
+ added its own height to the same error. */}
302
+ {/* ⭐ W54-T10 / lane B β€” `charts` rather than `tab.charts` directly: the same
303
+ document-or-local expression the rules list already uses, resolved once above. */}
304
+ {charts.map((chart) => {
305
+ const box = chartBox(chart);
306
+ // β›” W51-T16: THE PLACEMENT IS IN SHEET COORDINATES AND THE CANVAS IS NOT, so its origin
307
+ // is looked up in the visible table. A hidden origin has no honest canvas position.
308
+ const viewLo = visCols.indexOf(box.col);
309
+ const viewTop = visRows.indexOf(box.row);
310
+ if (viewLo < 0 || viewTop < 0) return null;
311
+ const { cols, rows } = box;
312
+ const viewHiBox = Math.min(visCols.length - 1, viewLo + cols - 1);
313
+ const viewBottomBox = Math.min(visRows.length - 1, viewTop + rows - 1);
314
+ // ⚠ SUMMED, NOT MULTIPLIED (W50-T20). A column width is per column now, so
315
+ // `lo * COL_WIDTH` would drift as soon as anybody dragged one.
316
+ const left = columnX(viewLo) - (viewLo >= frozenCols ? chartScrollX : 0);
317
+ const right = columnX(viewHiBox + 1) - (viewHiBox >= frozenCols ? chartScrollX : 0);
318
+ const width = Math.max(24, right - left);
319
+ const topPx = headerHeight + bandRows * rowHeight
320
+ + chartRowY(viewTop) - chartScrollY;
321
+ const height = Math.max(24, chartRowY(viewBottomBox + 1) - chartRowY(viewTop));
322
+ // β›” W56-T08 / R6 OVERRIDES THE DOCUMENTED POINTER TRANSPARENCY. The anchor now selects
323
+ // the chart, while preventing both pointer and mouse defaults keeps DOM focus on glide's
324
+ // canvas, so arrow keys and typing still have a keyboard path to the cells underneath.
325
+ return (
326
+ <div
327
+ key={chart.id}
328
+ className="sheet-chart-anchor sheet-chart-hit"
329
+ data-chart-id={chart.id}
330
+ data-selected={chart.id === selectedId ? "true" : undefined}
331
+ onPointerDown={(event) => {
332
+ event.preventDefault();
333
+ event.stopPropagation();
334
+ setSelectedId(chart.id);
335
+ }}
336
+ onMouseDown={(event) => {
337
+ event.preventDefault();
338
+ event.stopPropagation();
339
+ }}
340
+ // β›”β›” W54-T12 / lane B β€” D-642 ANSWERED, AND THE ANSWER WAS A DEFECT. `top` read
341
+ // `(viewTop + 1) * rowHeight`, which says "one header row is one data row tall".
342
+ // MEASURED in a browser on the `qa-b` workbook `4c5474ff9ef0`: the header is
343
+ // `HEADER_HEIGHT` 36 and a row is 34, so every chart sat 2px high on a plain sheet
344
+ // and a FULL 36px high on this one, which freezes a row. The frozen band is a
345
+ // second grid of its own above the body, `bandRows` rows plus its header tall, and
346
+ // `visRows` excludes those rows, so the offset it contributes was missing twice
347
+ // over. Origin measured 102 against a true row top of 138.
348
+ style={{
349
+ left,
350
+ top: topPx,
351
+ width,
352
+ height,
353
+ }}
354
+ >
355
+ {/* ⭐ W54-T12 / lane B β€” THE KIND GOES THROUGH RAW. It used to be narrowed to the
356
+ four the shared viz renderer draws, which meant a person who chose Pie got a bar
357
+ chart with nothing on screen saying so; `SheetChart.tsx` now owns that switch and
358
+ draws the rest itself. The two callbacks below carry a PIXEL delta, because a
359
+ chart anchors to CELLS and only this file can turn pixels into a range. */}
360
+ <SheetChart
361
+ range={chart.range}
362
+ cells={cells}
363
+ kind={chart.kind}
364
+ width={width}
365
+ height={height}
366
+ selected={chart.id === selectedId}
367
+ onMove={(dx, dy) => nudgeChart(chart, dx, dy, "move")}
368
+ onResize={(dx, dy) => nudgeChart(chart, dx, dy, "resize")}
369
+ onEdit={() => onEditChart(chart.id)}
370
+ // R6 exposes a visible, working delete door on the chart before the dialog mount
371
+ // gains its optional deletion callback.
372
+ onDelete={() => deleteChart(chart.id)}
373
+ />
374
+ </div>
375
+ );
376
+ })}
377
+ </>
378
+ );
379
+ }
web/src/sheet/SheetGrid.tsx CHANGED
@@ -124,7 +124,9 @@ import type { SuggestItem } from "./formulaAssist";
124
  // unfinished formula and walking one reference through Excel's four anchor states are both string
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 { autoCloseFormula, cycleAnchorAtCaret } from "./formulaEval";
 
 
128
  import { colorForSlot } from "./refColors";
129
  import "../styles/wave52/sheet-grid.css";
130
  // β›”β›” CONTRACT C8: ONE ESCAPE ARBITER FOR THE WHOLE APP, topmost wins. Nothing in this tree adds
@@ -138,8 +140,7 @@ import Ribbon from "./Ribbon";
138
  import type { RibbonAction, RibbonInsertDoor } from "./Ribbon";
139
  import { RulesDialog, ValidationDialog } from "./RulesDialog";
140
  import ChartDialog from "./ChartDialog";
141
- import SheetChart from "./SheetChart";
142
- import type { ChartAnchorDelta } from "./SheetChart";
143
  import ShortcutsPanel from "./ShortcutsPanel";
144
  import { colToIndex, indexToCol } from "./a1";
145
  // β›”β›” W51-T18 β€” THE RULE ENGINE AND THE VALIDATION CHECKER ARE PURE AND SHEET LOCAL, and that is
@@ -179,7 +180,7 @@ import type {
179
  } from "./types";
180
  import {
181
  addressOf, appendLineBreak, applyStructure, autoSumFormula, boundDragLabel, cellAt,
182
- cellShiftLabel, cellToValue, clearAll, recalcDependents,
183
  clearCells, clearFormats, commitTyped, cycleAnchors, dateStamp, displayText, drillAffordance,
184
  editableText, fillCells, fillDown, fillRight, findMatches,
185
  isFilled, markOf, noMatchLabel, nothingHiddenLabel, paintPatch, pasteCells,
@@ -364,8 +365,10 @@ export interface SheetGridProps {
364
  /**
365
  * One or many cells, committed and SAVED AS ONE STEP. `null` clears a cell. A paste, a fill and
366
  * a range delete each arrive here once, so they take one history step and one PUT.
367
- */
368
  onCommit: (edits: Record<string, Cell | null>) => void;
 
 
369
  onUndo: () => void;
370
  onRedo: () => void;
371
  onNotice: (message: string) => void;
@@ -383,7 +386,12 @@ export interface SheetGridProps {
383
  * own name box. This fires the `{addr, cell}` the `selected` memo already computes, and
384
  * `SheetPage.tsx` feeds it to `setBarAddr`. NOTHING IN `FormulaBar.tsx` CHANGED.
385
  */
386
- onSelect?: (selection: { addr: string; cell: Cell | null } | null) => void;
 
 
 
 
 
387
  /**
388
  * Insert or delete rows and columns. The GRID raises the intent and the PAGE decides: the
389
  * refusal wall (R18) and the bound-cell confirmation both need the whole workbook, which is
@@ -610,15 +618,80 @@ interface FormulaEditState {
610
  rangeAnchor: RealCell | null;
611
  }
612
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
613
  export default function SheetGrid({
614
- workbook, tab, busy = false, onEdit, onViewRows,
615
  formulaBar, onRefresh, onSaveNow, onOpenImport,
616
- onCommit, onUndo, onRedo, onNotice, onEvaluateBindings,
617
  onSelect, onStructure, onGrow, onFreeze, onColumnWidth, onHideBands, onRules, onCharts,
618
  onSelectTab,
619
  options, viewShadows,
620
  }: SheetGridProps) {
 
 
 
 
 
 
 
 
 
 
621
  const [selection, setSelection] = useState<GridSelection | undefined>(undefined);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
622
  /**
623
  * ⭐⭐ W54-T28 / R9(iv) β€” THE TAB RUN'S MEMORY, AND THE ONE BIT THAT SAYS WHO MOVED.
624
  *
@@ -991,15 +1064,15 @@ export default function SheetGrid({
991
 
992
  /**
993
  * A structural write can be accepted immediately, refused, or pause in the page's bound-cell
994
- * confirmation. Remember the exact expected cell map and update chart anchors only after the
995
- * accepted structure paints back. Comparing the contents as well as the addresses means a
996
- * cancelled confirmation followed by an ordinary edit cannot masquerade as acceptance. This
997
- * retains the page as the one refusal/confirmation authority.
998
  */
999
  const pendingChartStructure = useRef<{
1000
  tabId: string;
1001
  beforeCells: typeof cells;
1002
- expectedCells: string;
1003
  charts: SheetChartSpec[];
1004
  op: StructureOp;
1005
  } | null>(null);
@@ -1016,7 +1089,7 @@ export default function SheetGrid({
1016
  pendingChartStructure.current = {
1017
  tabId: tab.id,
1018
  beforeCells: cells,
1019
- expectedCells: JSON.stringify(expected),
1020
  charts: [...charts],
1021
  op,
1022
  };
@@ -1028,7 +1101,7 @@ export default function SheetGrid({
1028
  const pending = pendingChartStructure.current;
1029
  if (!pending || pending.tabId !== tab.id || pending.beforeCells === cells) return;
1030
  pendingChartStructure.current = null;
1031
- if (JSON.stringify(cells) !== pending.expectedCells) return;
1032
  const next = pending.charts.map((chart) => ({
1033
  ...chart,
1034
  range: chartRangeAfterStructure(chart.range, pending.op, extent),
@@ -1163,8 +1236,71 @@ export default function SheetGrid({
1163
  return { addr, cell: cellAt(tab, addr) };
1164
  }, [addrAt, selection, tab]);
1165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1166
  const onSelectionChange = useCallback((next: GridSelection) => {
1167
- setSelection(next);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1168
  // ⭐⭐ W54-T28 / R9(iv): "the run resets when the selection is moved by anything other than
1169
  // Tab", said in the one place every move arrives at. The commit arm raises the flag for its
1170
  // own move and this consumes it, so a Tab keeps the run and everything else ends it.
@@ -1196,18 +1332,14 @@ export default function SheetGrid({
1196
  // somebody moves the grid, and the name box owns the address the rest of the time. Two
1197
  // writers, one state, and neither one overwrites the other's act.
1198
  //
1199
- // ⚠ A CLEARED SELECTION SENDS `null`, and the page deliberately ignores it: losing focus
1200
- // should not blank the bar.
1201
  // ═════════════════════════════════════════════════════════════════════════════════════════
1202
- if (!onSelect) return;
1203
- const cur = next.current?.cell;
1204
- if (!cur) {
1205
- onSelect(null);
1206
- return;
1207
- }
1208
- const addr = addrAt(cur[0], cur[1]);
1209
- onSelect({ addr, cell: cellAt(tab, addr) });
1210
- }, [addrAt, onSelect, tab]);
1211
 
1212
  // ═══════════════════════════════════════════════════════════════════════════════════════════
1213
  // ⭐⭐ W51-T34 β€” ONE SELECTION, TWO GRIDS, AND THE MAIN GRID OWNS IT.
@@ -1263,12 +1395,31 @@ export default function SheetGrid({
1263
  }, [bandRows, fromBand, onSelectionChange]);
1264
 
1265
  /**
1266
- * ⭐⭐ W53-T01 / RULING R2 β€” THE `get` CALLBACK THAT MAKES A COMMITTED FORMULA COMPUTE OFFLINE.
1267
- * One closure over the CURRENT `tab`, handed to `commitTyped`/`setFormula` at every commit door
1268
- * below: `evaluateFormula` never reads a `Cell` itself, so this is the one place that answers
1269
- * its `get(addr)` question in terms of what this component already has in scope.
 
1270
  */
1271
- const cellValueGetter = useCallback((addr: string) => cellToValue(cellAt(tab, addr)), [tab]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1272
 
1273
  /**
1274
  * ⭐⭐ W53-T01 / INSTRUCTION 11 β€” EVERY COMMIT DOOR IN THIS FILE LANDS THROUGH HERE, so a write
@@ -1279,10 +1430,10 @@ export default function SheetGrid({
1279
  * β›” IT IS A CALLBACK, NOT AN EFFECT, AND THAT IS THE WHOLE DIFFERENCE. `onCommit` is
1280
  * `SheetPage.tsx::commitCells`, which pushes history and queues a save; an effect watching the
1281
  * document would mutate a workbook nobody edited and write it back merely for opening a sheet.
1282
- */
1283
  const commitWithRecalc = useCallback((edits: Record<string, Cell | null>) => {
1284
- onCommit({ ...edits, ...recalcDependents(tab, edits) });
1285
- }, [onCommit, tab]);
1286
 
1287
  /** ONE typed commit. `commitTyped` picks literal or formula and drops a binding on its own. */
1288
  const onCellEdited = useCallback((item: Item, value: EditableGridCell) => {
@@ -1407,6 +1558,7 @@ export default function SheetGrid({
1407
  // this callback is defined ahead of it. `onSelectionChange` is the same door one layer down.
1408
  if (!inBand) {
1409
  const next: Item = [viewCell[0], viewCell[1] + 1];
 
1410
  onSelectionChange({
1411
  columns: CompactSelection.empty(),
1412
  rows: CompactSelection.empty(),
@@ -2200,12 +2352,18 @@ export default function SheetGrid({
2200
  // translation happens where a REAL index is produced or consumed, which is the edge jump, the
2201
  // used extent, the structure ops and the find walk, and nowhere else.
2202
  // ═══════════════════════════════════════════════════════════════════════════════════════════
2203
- const applySelection = useCallback((range: CellRange, cell?: Item, scroll = true) => {
 
 
 
 
 
2204
  const col0 = Math.min(range.col0, range.col1);
2205
  const row0 = Math.min(range.row0, range.row1);
2206
  const col1 = Math.max(range.col0, range.col1);
2207
  const row1 = Math.max(range.row0, range.row1);
2208
  const at: Item = cell ?? [col0, row0];
 
2209
  onSelectionChange({
2210
  columns: CompactSelection.empty(),
2211
  rows: CompactSelection.empty(),
@@ -2227,6 +2385,28 @@ export default function SheetGrid({
2227
  if (scroll && at[1] >= 0) gridRef.current?.scrollTo(at[0], at[1]);
2228
  }, [onSelectionChange]);
2229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2230
  /**
2231
  * W55-T05 / R4: KeyTips consumes its capture-phase key while focus is on the ribbon, then
2232
  * dispatches one scoped semantic arrow on this wrapper. Move through `applySelection`, the same
@@ -3312,6 +3492,10 @@ export default function SheetGrid({
3312
  key: string; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean; altKey: boolean;
3313
  cancel: () => void; preventDefault: () => void;
3314
  }) => {
 
 
 
 
3315
  // ═════════════════════════════════════════════════════════════════════════════════════
3316
  // ⭐⭐ W54-T28 (INSTRUCTION 19, R9(iv)) β€” ENTER DOWN, TAB RIGHT, AND THE RETURN.
3317
  //
@@ -4235,139 +4419,6 @@ export default function SheetGrid({
4235
  (index: number) => Math.max(rowHeight, wrapHeights.get(realRow(index)) ?? 0),
4236
  [realRow, rowHeight, wrapHeights],
4237
  );
4238
- /**
4239
- * Every main-grid row boundary, cached because wrapped rows are not uniformly tall. Building
4240
- * this once makes each chart's scroll geometry and each pointer-release snap an O(1) lookup.
4241
- */
4242
- const chartRowOffsets = useMemo(() => {
4243
- const offsets = [0];
4244
- for (let row = 0; row < visRows.length; row += 1) {
4245
- offsets.push(offsets[row] + rowHeightAt(row));
4246
- }
4247
- return offsets;
4248
- }, [rowHeightAt, visRows.length]);
4249
- const chartRowY = useCallback(
4250
- (index: number) => chartRowOffsets[Math.max(0, Math.min(index, visRows.length))] ?? 0,
4251
- [chartRowOffsets, visRows.length],
4252
- );
4253
- const chartScrollX = useMemo(
4254
- () => lockstepScrollX(
4255
- columns.map((column) => column.width), frozenCols, chartViewport.x, chartViewport.tx,
4256
- ),
4257
- [chartViewport.tx, chartViewport.x, columns, frozenCols],
4258
- );
4259
- const chartScrollY = chartRowY(chartViewport.y) - chartViewport.ty;
4260
- /**
4261
- * ⭐⭐ W54-T12 / LANE B β€” A PIXEL DELTA BECOMES A CELL RANGE, AND ONLY THIS FILE CAN DO IT.
4262
- *
4263
- * β›” A CHART ANCHORS TO A RECTANGLE OF CELLS, so "move" and "resize" both mean editing `range`
4264
- * and neither means storing a pixel. `SheetChart.tsx` owns the GESTURE and reports what the
4265
- * pointer travelled; the geometry that turns that into columns and rows is here, because only
4266
- * this component knows each column's own width, which rows are hidden, and where the visible
4267
- * table starts.
4268
- *
4269
- * ⚠ THE COLUMN STEP IS A NEAREST-BOUNDARY WALK RATHER THAN A DIVISION. Column widths differ
4270
- * since W50-T20, so dividing by an average drifts by a whole column as soon as somebody has
4271
- * dragged one, and it drifts more the further right the chart sits.
4272
- *
4273
- * β›” IT CLAMPS AT BOTH ENDS AND NEVER INVERTS. A resize moves the FAR corner only and is held
4274
- * at or past the near one, so a range cannot turn inside out and cannot leave the sheet.
4275
- */
4276
- const nudgeChart = useCallback(
4277
- (
4278
- chart: SheetChartSpec,
4279
- dx: number,
4280
- dy: number,
4281
- mode: "move" | "resize",
4282
- ): ChartAnchorDelta => {
4283
- const lo = Math.min(chart.range.col0, chart.range.col1);
4284
- const hi = Math.max(chart.range.col0, chart.range.col1);
4285
- const top = Math.min(chart.range.row0, chart.range.row1);
4286
- const bottom = Math.max(chart.range.row0, chart.range.row1);
4287
- const viewLo = visCols.indexOf(lo);
4288
- const viewHi = visCols.indexOf(hi);
4289
- const viewTop = visRows.indexOf(top);
4290
- const viewBottom = visRows.indexOf(bottom);
4291
- if (viewLo < 0 || viewHi < 0 || viewTop < 0 || viewBottom < 0) {
4292
- return { dx: 0, dy: 0 };
4293
- }
4294
-
4295
- const nearestView = (x: number) => {
4296
- let best = 0;
4297
- let bestGap = Infinity;
4298
- for (let i = 0; i < visCols.length; i += 1) {
4299
- const gap = Math.abs(columnX(i) - x);
4300
- if (gap < bestGap) { bestGap = gap; best = i; }
4301
- }
4302
- return best;
4303
- };
4304
- const nearestColumnBoundary = (x: number) => {
4305
- let best = 0;
4306
- let bestGap = Infinity;
4307
- for (let col = 0; col <= visCols.length; col += 1) {
4308
- const gap = Math.abs(columnX(col) - x);
4309
- if (gap < bestGap) { bestGap = gap; best = col; }
4310
- }
4311
- return best;
4312
- };
4313
- const nearestRow = (y: number) => {
4314
- let best = 0;
4315
- let bestGap = Infinity;
4316
- for (let row = 0; row <= visRows.length; row += 1) {
4317
- const gap = Math.abs(chartRowY(row) - y);
4318
- if (gap < bestGap) { bestGap = gap; best = row; }
4319
- }
4320
- return best;
4321
- };
4322
- const clamp = (v: number, low: number, high: number) => Math.min(high, Math.max(low, v));
4323
- const lastCol = visCols.length - 1;
4324
- const lastRow = visRows.length - 1;
4325
-
4326
- let nextLo = viewLo;
4327
- let nextHi = viewHi;
4328
- let nextTop = viewTop;
4329
- let nextBottom = viewBottom;
4330
- if (mode === "move") {
4331
- const stepCols = clamp(
4332
- nearestView(columnX(viewLo) + dx) - viewLo, -viewLo, lastCol - viewHi,
4333
- );
4334
- const stepRows = clamp(
4335
- nearestRow(chartRowY(viewTop) + dy) - viewTop, -viewTop, lastRow - viewBottom,
4336
- );
4337
- nextLo = viewLo + stepCols;
4338
- nextHi = viewHi + stepCols;
4339
- nextTop = viewTop + stepRows;
4340
- nextBottom = viewBottom + stepRows;
4341
- } else {
4342
- nextHi = clamp(
4343
- nearestColumnBoundary(columnX(viewHi + 1) + dx) - 1, viewLo, lastCol,
4344
- );
4345
- nextBottom = clamp(
4346
- nearestRow(chartRowY(viewBottom + 1) + dy) - 1, viewTop, lastRow,
4347
- );
4348
- }
4349
- const range = {
4350
- col0: visCols[nextLo], col1: visCols[nextHi],
4351
- row0: visRows[nextTop], row1: visRows[nextBottom],
4352
- };
4353
- if (range.col0 === chart.range.col0 && range.col1 === chart.range.col1
4354
- && range.row0 === chart.range.row0 && range.row1 === chart.range.row1) {
4355
- return { dx: 0, dy: 0 };
4356
- }
4357
- const snapped = mode === "move"
4358
- ? {
4359
- dx: columnX(nextLo) - columnX(viewLo),
4360
- dy: chartRowY(nextTop) - chartRowY(viewTop),
4361
- }
4362
- : {
4363
- dx: columnX(nextHi + 1) - columnX(viewHi + 1),
4364
- dy: chartRowY(nextBottom + 1) - chartRowY(viewBottom + 1),
4365
- };
4366
- writeCharts(charts.map((c) => (c.id === chart.id ? { ...c, range } : c)));
4367
- return snapped;
4368
- },
4369
- [chartRowY, charts, columnX, visCols, visRows, writeCharts],
4370
- );
4371
 
4372
  /**
4373
  * ⭐⭐ W54-T10 / LANE B β€” THE INSERT TAB'S DOOR, BUILT WHERE THE DOCUMENT ACTUALLY IS.
@@ -4422,11 +4473,14 @@ export default function SheetGrid({
4422
  not get. `.sheet-fx` already carries `flex: 0 0 auto`, so the bar is rendered bare. */}
4423
  {formulaBar}
4424
 
4425
- <div className="sheet-grid-head">
4426
- <p className="sheet-grid-tab">{tab.name}</p>
4427
- </div>
4428
-
4429
- <div className="sheet-grid-canvas">
 
 
 
4430
  {/* ══════════════════════════════════════════════════════════════════════════
4431
  ⭐⭐ W51-T34 / R17 β€” THE FROZEN ROWS, AS A SECOND GRID.
4432
 
@@ -4735,78 +4789,27 @@ export default function SheetGrid({
4735
  drawCell={paintCell}
4736
  />
4737
 
4738
- {/* ⭐ R9: A CHART OCCUPIES A RECTANGLE OF CELLS. It is positioned over the canvas rather
4739
- than drawn into it, because glide owns the canvas and a chart is not a cell. The
4740
- geometry is derived from the same column width and row height the grid uses, so the
4741
- chart lands on the cells it reads and moves with them.
4742
- ⚠ The charts live on the TAB, not among the cells (contract C1 freezes the cell kinds),
4743
- so a sheet written before W49-T08 simply has none.
4744
- β›” THE ANCHORS MOVED INSIDE `.sheet-grid-canvas` (W50-T19), AND THAT IS A FIX, NOT A
4745
- TIDY. Their offsets are glide's own origin plus one header row, so they were only ever
4746
- right if the positioning parent WAS the canvas box; sitting in `.sheet-grid-wrap` they
4747
- were already the height of `.sheet-grid-head` too low, and the ribbon above would have
4748
- added its own height to the same error. */}
4749
- {/* ⭐ W54-T10 / lane B β€” `charts` rather than `tab.charts` directly: the same
4750
- document-or-local expression the rules list already uses, resolved once above. */}
4751
- {charts.map((chart) => {
4752
- const lo = Math.min(chart.range.col0, chart.range.col1);
4753
- const hi = Math.max(chart.range.col0, chart.range.col1);
4754
- const top = Math.min(chart.range.row0, chart.range.row1);
4755
- const bottom = Math.max(chart.range.row0, chart.range.row1);
4756
- // β›” W51-T16: A CHART'S RANGE IS IN THE SHEET'S COORDINATES AND THE CANVAS IS NOT, so
4757
- // both corners are looked up in the visible table. A chart whose first column is hidden
4758
- // has no place to sit and is not drawn, which is the honest answer: drawing it over the
4759
- // wrong columns would put a picture beside numbers it does not read.
4760
- const viewLo = visCols.indexOf(lo);
4761
- const viewHi = visCols.indexOf(hi);
4762
- const viewTop = visRows.indexOf(top);
4763
- const viewBottom = visRows.indexOf(bottom);
4764
- if (viewLo < 0 || viewHi < 0 || viewTop < 0 || viewBottom < 0) return null;
4765
- // ⚠ SUMMED, NOT MULTIPLIED (W50-T20). A column width is per column now, so
4766
- // `lo * COL_WIDTH` would drift as soon as anybody dragged one.
4767
- const left = columnX(viewLo) - (viewLo >= frozenCols ? chartScrollX : 0);
4768
- const right = columnX(viewHi + 1) - (viewHi >= frozenCols ? chartScrollX : 0);
4769
- const width = Math.max(24, right - left);
4770
- const topPx = HEADER_HEIGHT + bandRows * rowHeight
4771
- + chartRowY(viewTop) - chartScrollY;
4772
- const height = Math.max(24, chartRowY(viewBottom + 1) - chartRowY(viewTop));
4773
- return (
4774
- <div
4775
- key={chart.id}
4776
- className="sheet-chart-anchor"
4777
- // β›”β›” W54-T12 / lane B β€” D-642 ANSWERED, AND THE ANSWER WAS A DEFECT. `top` read
4778
- // `(viewTop + 1) * rowHeight`, which says "one header row is one data row tall".
4779
- // MEASURED in a browser on the `qa-b` workbook `4c5474ff9ef0`: the header is
4780
- // `HEADER_HEIGHT` 36 and a row is 34, so every chart sat 2px high on a plain sheet
4781
- // and a FULL 36px high on this one, which freezes a row. The frozen band is a
4782
- // second grid of its own above the body, `bandRows` rows plus its header tall, and
4783
- // `visRows` excludes those rows, so the offset it contributes was missing twice
4784
- // over. Origin measured 102 against a true row top of 138.
4785
- style={{
4786
- left,
4787
- top: topPx,
4788
- width,
4789
- height,
4790
- }}
4791
- >
4792
- {/* ⭐ W54-T12 / lane B β€” THE KIND GOES THROUGH RAW. It used to be narrowed to the
4793
- four the shared viz renderer draws, which meant a person who chose Pie got a bar
4794
- chart with nothing on screen saying so; `SheetChart.tsx` now owns that switch and
4795
- draws the rest itself. The two callbacks below carry a PIXEL delta, because a
4796
- chart anchors to CELLS and only this file can turn pixels into a range. */}
4797
- <SheetChart
4798
- range={chart.range}
4799
- cells={cells}
4800
- kind={chart.kind}
4801
- width={width}
4802
- height={height}
4803
- onMove={(dx, dy) => nudgeChart(chart, dx, dy, "move")}
4804
- onResize={(dx, dy) => nudgeChart(chart, dx, dy, "resize")}
4805
- onEdit={() => setChartEditId(chart.id)}
4806
- />
4807
- </div>
4808
- );
4809
- })}
4810
  {editingChart ? (
4811
  <ChartDialog
4812
  key={editingChart.id}
 
124
  // unfinished formula and walking one reference through Excel's four anchor states are both string
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";
132
  // β›”β›” CONTRACT C8: ONE ESCAPE ARBITER FOR THE WHOLE APP, topmost wins. Nothing in this tree adds
 
140
  import type { RibbonAction, RibbonInsertDoor } from "./Ribbon";
141
  import { RulesDialog, ValidationDialog } from "./RulesDialog";
142
  import ChartDialog from "./ChartDialog";
143
+ import SheetChartLayer from "./SheetChartLayer";
 
144
  import ShortcutsPanel from "./ShortcutsPanel";
145
  import { colToIndex, indexToCol } from "./a1";
146
  // β›”β›” W51-T18 β€” THE RULE ENGINE AND THE VALIDATION CHECKER ARE PURE AND SHEET LOCAL, and that is
 
180
  } from "./types";
181
  import {
182
  addressOf, appendLineBreak, applyStructure, autoSumFormula, boundDragLabel, cellAt,
183
+ cellShiftLabel, cellToValue, clearAll, recalcDependents, recalculateWorkbook,
184
  clearCells, clearFormats, commitTyped, cycleAnchors, dateStamp, displayText, drillAffordance,
185
  editableText, fillCells, fillDown, fillRight, findMatches,
186
  isFilled, markOf, noMatchLabel, nothingHiddenLabel, paintPatch, pasteCells,
 
365
  /**
366
  * One or many cells, committed and SAVED AS ONE STEP. `null` clears a cell. A paste, a fill and
367
  * a range delete each arrive here once, so they take one history step and one PUT.
368
+ */
369
  onCommit: (edits: Record<string, Cell | null>) => void;
370
+ /** The one cell selected when this workbook and tab are adopted. */
371
+ openAt: { workbookId: string; tabId: string; addr: string };
372
  onUndo: () => void;
373
  onRedo: () => void;
374
  onNotice: (message: string) => void;
 
386
  * own name box. This fires the `{addr, cell}` the `selected` memo already computes, and
387
  * `SheetPage.tsx` feeds it to `setBarAddr`. NOTHING IN `FormulaBar.tsx` CHANGED.
388
  */
389
+ onSelect?: (selection: {
390
+ addr: string;
391
+ cell: Cell | null;
392
+ /** True only when the reader moved to this cell, never for a restore or library default. */
393
+ readerCaused: boolean;
394
+ } | null) => void;
395
  /**
396
  * Insert or delete rows and columns. The GRID raises the intent and the PAGE decides: the
397
  * refusal wall (R18) and the bound-cell confirmation both need the whole workbook, which is
 
618
  rangeAnchor: RealCell | null;
619
  }
620
 
621
+ /**
622
+ * Did the requested structure paint back? Only address PRESENCE changes caused by the operation
623
+ * answer that question. Cell contents may legitimately change in the same commit, and object key
624
+ * order, re-serialised numbers or a new optional field are not evidence that the operation failed.
625
+ * A whole-map `JSON.stringify` comparison could therefore decline a real chart re-anchor silently.
626
+ *
627
+ * When no occupied address moves, the operation cannot be waiting on the bound-cell confirmation;
628
+ * the caller's changed cell-map identity is then the accepted structure paint in its own right.
629
+ */
630
+ function chartStructureLanded(
631
+ before: Record<string, Cell>,
632
+ expected: Record<string, Cell>,
633
+ current: Record<string, Cell>,
634
+ ): boolean {
635
+ let hasFootprint = false;
636
+ const addresses = new Set([...Object.keys(before), ...Object.keys(expected)]);
637
+ for (const addr of addresses) {
638
+ const beforeHas = Object.prototype.hasOwnProperty.call(before, addr);
639
+ const expectedHas = Object.prototype.hasOwnProperty.call(expected, addr);
640
+ if (beforeHas === expectedHas) continue;
641
+ hasFootprint = true;
642
+ if (Object.prototype.hasOwnProperty.call(current, addr) !== expectedHas) return false;
643
+ }
644
+ return hasFootprint || before !== current;
645
+ }
646
+
647
  export default function SheetGrid({
648
+ workbook: storedWorkbook, tab: storedTab, busy = false, onEdit, onViewRows,
649
  formulaBar, onRefresh, onSaveNow, onOpenImport,
650
+ onCommit, openAt, onUndo, onRedo, onNotice, onEvaluateBindings,
651
  onSelect, onStructure, onGrow, onFreeze, onColumnWidth, onHideBands, onRules, onCharts,
652
  onSelectTab,
653
  options, viewShadows,
654
  }: SheetGridProps) {
655
+ /**
656
+ * ⭐ THE CLIENT VIEW IS RECALCULATED FROM THE WHOLE WORKBOOK. This is a projection, not an
657
+ * effect and not a write: opening a workbook creates no undo step, while a formula on Sheet1
658
+ * can paint from a changed Sheet2 cell as soon as the workbook object changes.
659
+ */
660
+ const workbook = useMemo(
661
+ () => recalculateWorkbook(storedWorkbook, storedTab.id),
662
+ [storedWorkbook, storedTab.id],
663
+ );
664
+ const tab = workbook.sheets.find((sheet) => sheet.id === storedTab.id) ?? storedTab;
665
  const [selection, setSelection] = useState<GridSelection | undefined>(undefined);
666
+ /** The live value used to floor glide's empty Escape payload without adding selection state. */
667
+ const selectionRef = useRef<GridSelection | undefined>(undefined);
668
+ /** Pointer and keyboard provenance for selection callbacks emitted by glide itself. */
669
+ const pointerSelectingRef = useRef(false);
670
+ const keyboardSelectingRef = useRef(false);
671
+ /** Workbook and tab identity, never workbook object identity, owns the one opening selection. */
672
+ const openedSelectionRef = useRef("");
673
+ /**
674
+ * A same-place workbook replacement can make glide offer its default A1 while reconciling the
675
+ * new data object. Remember the selection that was live immediately before that render so the
676
+ * one callback caused by reconciliation can be distinguished from ordinary navigation.
677
+ *
678
+ * This comparison happens during render deliberately: glide may reconcile in its own layout
679
+ * work before a parent effect could arm the handoff. The handoff contains no drawn state and is
680
+ * consumed by the next selection event, so later reader input is never pinned.
681
+ */
682
+ const reconciledWorkbookRef = useRef<{ object: Workbook; key: string } | null>(null);
683
+ const replacementSelectionRef = useRef<GridSelection | null>(null);
684
+ const renderedWorkbookKey = `${workbook.id}:${tab.id}`;
685
+ const reconciledWorkbook = reconciledWorkbookRef.current;
686
+ if (!reconciledWorkbook
687
+ || reconciledWorkbook.object !== workbook
688
+ || reconciledWorkbook.key !== renderedWorkbookKey) {
689
+ const samePlace = reconciledWorkbook?.object.id === workbook.id
690
+ && reconciledWorkbook.key === renderedWorkbookKey;
691
+ const current = selectionRef.current;
692
+ replacementSelectionRef.current = samePlace && current?.current ? current : null;
693
+ reconciledWorkbookRef.current = { object: workbook, key: renderedWorkbookKey };
694
+ }
695
  /**
696
  * ⭐⭐ W54-T28 / R9(iv) β€” THE TAB RUN'S MEMORY, AND THE ONE BIT THAT SAYS WHO MOVED.
697
  *
 
1064
 
1065
  /**
1066
  * A structural write can be accepted immediately, refused, or pause in the page's bound-cell
1067
+ * confirmation. Remember the operation's expected address footprint and update chart anchors
1068
+ * only after that footprint paints back. A cancelled confirmation followed by an ordinary edit
1069
+ * does not match it, while unrelated cell-content edits may ride the accepted structure commit.
1070
+ * This retains the page as the one refusal/confirmation authority.
1071
  */
1072
  const pendingChartStructure = useRef<{
1073
  tabId: string;
1074
  beforeCells: typeof cells;
1075
+ expectedCells: typeof cells;
1076
  charts: SheetChartSpec[];
1077
  op: StructureOp;
1078
  } | null>(null);
 
1089
  pendingChartStructure.current = {
1090
  tabId: tab.id,
1091
  beforeCells: cells,
1092
+ expectedCells: expected,
1093
  charts: [...charts],
1094
  op,
1095
  };
 
1101
  const pending = pendingChartStructure.current;
1102
  if (!pending || pending.tabId !== tab.id || pending.beforeCells === cells) return;
1103
  pendingChartStructure.current = null;
1104
+ if (!chartStructureLanded(pending.beforeCells, pending.expectedCells, cells)) return;
1105
  const next = pending.charts.map((chart) => ({
1106
  ...chart,
1107
  range: chartRangeAfterStructure(chart.range, pending.op, extent),
 
1236
  return { addr, cell: cellAt(tab, addr) };
1237
  }, [addrAt, selection, tab]);
1238
 
1239
+ /**
1240
+ * The values needed by the selection door move as the workbook tree moves, but the door itself
1241
+ * must not. glide retains selection internally and can emit its default A1 when a new data
1242
+ * identity also gives it a new callback identity. Keeping one callback lets a same-tab refresh
1243
+ * remain a repaint rather than look like navigation.
1244
+ */
1245
+ const selectionContextRef = useRef({ addrAt, onSelect, tab, viewRowOf, visCols });
1246
+ selectionContextRef.current = { addrAt, onSelect, tab, viewRowOf, visCols };
1247
+
1248
+ /**
1249
+ * What the NEXT call to `onSelectionChange` is: a reader gesture or an app-owned move.
1250
+ * β›” This is a ref, not a parameter: W54-T28 finds the selection door by its exact declaration.
1251
+ */
1252
+ const selectionIntentRef = useRef<"reader" | "app" | null>(null);
1253
+
1254
  const onSelectionChange = useCallback((next: GridSelection) => {
1255
+ const selectionIntent = selectionIntentRef.current;
1256
+ selectionIntentRef.current = null;
1257
+ const context = selectionContextRef.current;
1258
+ // ⭐⭐ W56-T04 / INSTRUCTION 26: ESCAPE MAY DISMISS, BUT IT MAY NOT CLEAR THE LAST CELL.
1259
+ // glide owns Escape and reports an empty selection here. Correct that payload ONCE at this
1260
+ // door; recursively calling this handler, or repairing selection from an effect, makes the
1261
+ // controlled update re-enter glide's own Escape handling and loop. A first-render Escape has
1262
+ // no prior cell, so it starts at the sheet's first visible representation of A1.
1263
+ const prior = selectionRef.current?.current?.cell;
1264
+ const first: Item = [viewIndexOf(context.visCols, 0), context.viewRowOf(0)];
1265
+ const fromGlide = selectionIntent === null;
1266
+ const readerCaused = (selectionIntent === "reader"
1267
+ || (fromGlide && (pointerSelectingRef.current || keyboardSelectingRef.current)))
1268
+ && next.current?.cell !== undefined;
1269
+
1270
+ // Only the first callback after a same-workbook, same-tab object replacement is suspect.
1271
+ // Shape cannot distinguish glide's default A1 from a real click on A1, so reader provenance
1272
+ // wins and always consumes the handoff. A gesture-less differing cell is reconciliation: feed
1273
+ // a fresh copy of the prior controlled selection through this same door so React makes glide
1274
+ // paint it again. Consuming before acceptance prevents the controlled repaint from looping.
1275
+ const replacementSelection = replacementSelectionRef.current;
1276
+ replacementSelectionRef.current = null;
1277
+ const replacementCell = replacementSelection?.current?.cell;
1278
+ const offeredCell = next.current?.cell;
1279
+ let offered = next;
1280
+ if (replacementSelection && replacementCell && offeredCell
1281
+ && fromGlide && !readerCaused
1282
+ && (replacementCell[0] !== offeredCell[0] || replacementCell[1] !== offeredCell[1])) {
1283
+ offered = {
1284
+ ...replacementSelection,
1285
+ current: {
1286
+ ...replacementSelection.current!,
1287
+ cell: [replacementCell[0], replacementCell[1]] as Item,
1288
+ },
1289
+ };
1290
+ }
1291
+
1292
+ const cell = prior ?? first;
1293
+ const accepted: GridSelection = offered.current?.cell ? offered : {
1294
+ columns: CompactSelection.empty(),
1295
+ rows: CompactSelection.empty(),
1296
+ current: {
1297
+ cell,
1298
+ range: { x: cell[0], y: cell[1], width: 1, height: 1 },
1299
+ rangeStack: [],
1300
+ },
1301
+ };
1302
+ selectionRef.current = accepted;
1303
+ setSelection(accepted);
1304
  // ⭐⭐ W54-T28 / R9(iv): "the run resets when the selection is moved by anything other than
1305
  // Tab", said in the one place every move arrives at. The commit arm raises the flag for its
1306
  // own move and this consumes it, so a Tab keeps the run and everything else ends it.
 
1332
  // somebody moves the grid, and the name box owns the address the rest of the time. Two
1333
  // writers, one state, and neither one overwrites the other's act.
1334
  //
1335
+ // ⭐ The floor above means every selection gesture now sends the selected cell. There is no
1336
+ // cleared-selection branch left to blank the bar or the workbook's remembered position.
1337
  // ═════════════════════════════════════════════════════════════════════════════════════════
1338
+ if (!context.onSelect) return;
1339
+ const cur = accepted.current!.cell;
1340
+ const addr = context.addrAt(cur[0], cur[1]);
1341
+ context.onSelect({ addr, cell: cellAt(context.tab, addr), readerCaused });
1342
+ }, []);
 
 
 
 
1343
 
1344
  // ═══════════════════════════════════════════════════════════════════════════════════════════
1345
  // ⭐⭐ W51-T34 β€” ONE SELECTION, TWO GRIDS, AND THE MAIN GRID OWNS IT.
 
1395
  }, [bandRows, fromBand, onSelectionChange]);
1396
 
1397
  /**
1398
+ * ⭐⭐ THE WORKBOOK GETTER. Bare `A1` reads this tab exactly as before; `SHEET2!A1` resolves
1399
+ * through a case-insensitive name index whose value is the real tab object and stable tab ID.
1400
+ *
1401
+ * β›” AN UNKNOWN NAME IS `#REF!`, NEVER AN EMPTY CELL. Blank would be a confident numeric zero
1402
+ * in arithmetic and would make a correct formula look successfully calculated from no sheet.
1403
  */
1404
+ const cellValueGetter = useMemo(() => {
1405
+ const byName = new Map(
1406
+ (workbook.sheets ?? []).map((sheet) => [sheet.name.trim().toUpperCase(), sheet]),
1407
+ );
1408
+ return workbookFormulaGetter((key: string) => {
1409
+ const bang = key.lastIndexOf("!");
1410
+ const sheetName = bang < 0 ? "" : key.slice(0, bang).toUpperCase();
1411
+ const addr = (bang < 0 ? key : key.slice(bang + 1)).toUpperCase();
1412
+ const target = sheetName ? byName.get(sheetName) : tab;
1413
+ if (!target) {
1414
+ return {
1415
+ kind: "error",
1416
+ code: ERROR_REF,
1417
+ message: `${ERROR_REF} This formula names a sheet that is not in this workbook.`,
1418
+ };
1419
+ }
1420
+ return cellToValue(cellAt(target, addr));
1421
+ });
1422
+ }, [tab, workbook.sheets]);
1423
 
1424
  /**
1425
  * ⭐⭐ W53-T01 / INSTRUCTION 11 β€” EVERY COMMIT DOOR IN THIS FILE LANDS THROUGH HERE, so a write
 
1430
  * β›” IT IS A CALLBACK, NOT AN EFFECT, AND THAT IS THE WHOLE DIFFERENCE. `onCommit` is
1431
  * `SheetPage.tsx::commitCells`, which pushes history and queues a save; an effect watching the
1432
  * document would mutate a workbook nobody edited and write it back merely for opening a sheet.
1433
+ */
1434
  const commitWithRecalc = useCallback((edits: Record<string, Cell | null>) => {
1435
+ onCommit({ ...edits, ...recalcDependents(tab, edits, workbook.sheets) });
1436
+ }, [onCommit, tab, workbook.sheets]);
1437
 
1438
  /** ONE typed commit. `commitTyped` picks literal or formula and drops a binding on its own. */
1439
  const onCellEdited = useCallback((item: Item, value: EditableGridCell) => {
 
1558
  // this callback is defined ahead of it. `onSelectionChange` is the same door one layer down.
1559
  if (!inBand) {
1560
  const next: Item = [viewCell[0], viewCell[1] + 1];
1561
+ selectionIntentRef.current = "reader";
1562
  onSelectionChange({
1563
  columns: CompactSelection.empty(),
1564
  rows: CompactSelection.empty(),
 
2352
  // translation happens where a REAL index is produced or consumed, which is the edge jump, the
2353
  // used extent, the structure ops and the find walk, and nowhere else.
2354
  // ═══════════════════════════════════════════════════════════════════════════════════════════
2355
+ const applySelection = useCallback((
2356
+ range: CellRange,
2357
+ cell?: Item,
2358
+ scroll = true,
2359
+ readerCaused = true,
2360
+ ) => {
2361
  const col0 = Math.min(range.col0, range.col1);
2362
  const row0 = Math.min(range.row0, range.row1);
2363
  const col1 = Math.max(range.col0, range.col1);
2364
  const row1 = Math.max(range.row0, range.row1);
2365
  const at: Item = cell ?? [col0, row0];
2366
+ selectionIntentRef.current = readerCaused ? "reader" : "app";
2367
  onSelectionChange({
2368
  columns: CompactSelection.empty(),
2369
  rows: CompactSelection.empty(),
 
2385
  if (scroll && at[1] >= 0) gridRef.current?.scrollTo(at[0], at[1]);
2386
  }, [onSelectionChange]);
2387
 
2388
+ /**
2389
+ * ⭐⭐ W56-T04: ONE OPEN, ONE OPENING CELL, THROUGH THE SAME SELECTION DOOR.
2390
+ * The background binding refresh replaces the workbook object after paint, so object identity
2391
+ * cannot own this effect. The workbook and tab ids do; the ref prevents those later replacements
2392
+ * from pulling the reader back after they have already moved.
2393
+ */
2394
+ useEffect(() => {
2395
+ const key = `${workbook.id}:${tab.id}`;
2396
+ if (openAt.workbookId !== workbook.id || openAt.tabId !== tab.id
2397
+ || openedSelectionRef.current === key) return;
2398
+ openedSelectionRef.current = key;
2399
+
2400
+ const requested = splitAddress(openAt.addr) ?? { col: 1, row: 1 };
2401
+ let col = viewIndexOf(visCols, requested.col - 1);
2402
+ let row = viewRowOf(requested.row - 1);
2403
+ if (realCol(col) !== requested.col - 1 || realRow(row) !== requested.row - 1) {
2404
+ col = viewIndexOf(visCols, 0);
2405
+ row = viewRowOf(0);
2406
+ }
2407
+ applySelection({ col0: col, row0: row, col1: col, row1: row }, [col, row], true, false);
2408
+ }, [applySelection, openAt, realCol, realRow, tab.id, viewRowOf, visCols, workbook.id]);
2409
+
2410
  /**
2411
  * W55-T05 / R4: KeyTips consumes its capture-phase key while focus is on the ribbon, then
2412
  * dispatches one scoped semantic arrow on this wrapper. Move through `applySelection`, the same
 
3492
  key: string; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean; altKey: boolean;
3493
  cancel: () => void; preventDefault: () => void;
3494
  }) => {
3495
+ // glide invokes this before applying its own key-driven selection. Keep that callback tied
3496
+ // to the reader's key for this event only; a later data-identity reconciliation has no key.
3497
+ keyboardSelectingRef.current = true;
3498
+ queueMicrotask(() => { keyboardSelectingRef.current = false; });
3499
  // ═════════════════════════════════════════════════════════════════════════════════════
3500
  // ⭐⭐ W54-T28 (INSTRUCTION 19, R9(iv)) β€” ENTER DOWN, TAB RIGHT, AND THE RETURN.
3501
  //
 
4419
  (index: number) => Math.max(rowHeight, wrapHeights.get(realRow(index)) ?? 0),
4420
  [realRow, rowHeight, wrapHeights],
4421
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4422
 
4423
  /**
4424
  * ⭐⭐ W54-T10 / LANE B β€” THE INSERT TAB'S DOOR, BUILT WHERE THE DOCUMENT ACTUALLY IS.
 
4473
  not get. `.sheet-fx` already carries `flex: 0 0 auto`, so the bar is rendered bare. */}
4474
  {formulaBar}
4475
 
4476
+ <div
4477
+ className="sheet-grid-canvas"
4478
+ onPointerDownCapture={() => { pointerSelectingRef.current = true; }}
4479
+ onPointerUpCapture={() => {
4480
+ queueMicrotask(() => { pointerSelectingRef.current = false; });
4481
+ }}
4482
+ onPointerCancelCapture={() => { pointerSelectingRef.current = false; }}
4483
+ >
4484
  {/* ══════════════════════════════════════════════════════════════════════════
4485
  ⭐⭐ W51-T34 / R17 β€” THE FROZEN ROWS, AS A SECOND GRID.
4486
 
 
4789
  drawCell={paintCell}
4790
  />
4791
 
4792
+ {/* ⭐ R9 / WAVE 56 BASE β€” THE CHART OVERLAY, WHICH IS ITS OWN MODULE NOW. A chart
4793
+ occupies a rectangle of CELLS and is positioned over the canvas rather than drawn
4794
+ into it, so the anchors must stay INSIDE `.sheet-grid-canvas` (W50-T19) and the
4795
+ geometry they use must stay the grid's own. Both facts, and every measurement behind
4796
+ them, travelled with the code into `SheetChartLayer.tsx`. */}
4797
+ <SheetChartLayer
4798
+ charts={charts}
4799
+ cells={cells}
4800
+ visCols={visCols}
4801
+ visRows={visRows}
4802
+ columns={columns}
4803
+ columnX={columnX}
4804
+ rowHeightAt={rowHeightAt}
4805
+ frozenCols={frozenCols}
4806
+ bandRows={bandRows}
4807
+ rowHeight={rowHeight}
4808
+ headerHeight={HEADER_HEIGHT}
4809
+ viewport={chartViewport}
4810
+ onWriteCharts={writeCharts}
4811
+ onEditChart={setChartEditId}
4812
+ />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4813
  {editingChart ? (
4814
  <ChartDialog
4815
  key={editingChart.id}
web/src/sheet/SheetPage.tsx CHANGED
@@ -55,7 +55,7 @@ import DrillModal from "./DrillModal";
55
  import type { DrillCellScope } from "./DrillModal";
56
  import FormulaBar from "./FormulaBar";
57
  import SheetGridBase from "./SheetGrid";
58
- import type { SheetGridProps } from "./SheetGrid";
59
  import SheetRail from "./SheetRail";
60
  import type { RailStrata } from "./SheetRail";
61
  import {
@@ -255,6 +255,54 @@ interface TabDrag {
255
  /** The cache key for one tab's cells. Workbook scoped, so switching books cannot reuse them. */
256
  const tabKeyOf = (workbookId: string, tabId: string): string => `${workbookId}:${tabId}`;
257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
258
  /**
259
  * Does this tab carry anything an undo could destroy?
260
  *
@@ -281,6 +329,8 @@ const tabRevOf = (tab: SheetTab, book: Workbook): number => {
281
 
282
  export default function SheetPage() {
283
  const [book, setBook] = useState<Workbook | null>(null);
 
 
284
  const [tabId, setTabId] = useState<string>("");
285
  const [busy, setBusy] = useState(false);
286
  const [notice, setNotice] = useState("");
@@ -295,7 +345,7 @@ export default function SheetPage() {
295
  * longer something a person waits on and is told about afterwards. Excel agrees and it is worth
296
  * recording why: its status bar shows "Calculating (n%)" only WHILE a long recalculation runs,
297
  * and it shows no completion notice of any kind
298
- * (`.claude/wiki/research/excel-formula-ux.md` section 5).
299
  * β›” NOTHING REPLACES IT HERE. Per R2 the per-cell shimmer on a database-bound cell is what
300
  * reports work in progress, and that lives on the cell rather than in a page-level strip.
301
  * ⚠ `notice` DIRECTLY BELOW IS A DIFFERENT LINE AND IT STAYS. It carries refusals - an edit
@@ -377,6 +427,11 @@ export default function SheetPage() {
377
 
378
  const bookRef = useRef<Workbook | null>(null);
379
  const tabIdRef = useRef<string>("");
 
 
 
 
 
380
  const historyRef = useRef<SheetHistory>(emptyHistory());
381
  const saveChainRef = useRef<Promise<void>>(Promise.resolve());
382
  /** Bumped by every local edit, so a save knows whether the tree moved under it. */
@@ -388,6 +443,8 @@ export default function SheetPage() {
388
  * synchronously and prevents an older, slower read from winning after a newer choice.
389
  */
390
  const workbookTransitionRef = useRef(false);
 
 
391
  /** The bottom tab strip and its one pointer-captured drag. High-frequency motion stays in DOM. */
392
  const tabStripRef = useRef<HTMLDivElement | null>(null);
393
  const tabDragRef = useRef<TabDrag | null>(null);
@@ -419,7 +476,7 @@ export default function SheetPage() {
419
  const patchModeRef = useRef<"unknown" | "patch" | "put">("unknown");
420
  /** The same answer for the per-tab READ, learned the same way and kept for the same reason. */
421
  const tabRouteRef = useRef<"unknown" | "yes" | "no">("unknown");
422
- /** Which tabs have had their cells read. Keyed `workbookId:tabId`, so a switch cannot reuse. */
423
  const tabLoadedRef = useRef<Set<string>>(new Set());
424
  /** The pending debounce, or null when nothing is waiting. */
425
  const saveTimerRef = useRef<number | null>(null);
@@ -455,6 +512,24 @@ export default function SheetPage() {
455
  setBook(next);
456
  }, []);
457
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
458
  useEffect(() => { tabIdRef.current = tabId; }, [tabId]);
459
 
460
  const markDirty = useCallback((tabId2: string, addr: string) => {
@@ -501,7 +576,8 @@ export default function SheetPage() {
501
  * ⭐⭐ MAKE SURE THE NAMED TABS ARE IN MEMORY, AND ANSWER WHETHER THEY NOW ARE.
502
  *
503
  * This is the lazy fetch, its cache and its repair path in one door, because all three have to
504
- * agree about what "loaded" means. A tab already in `tabLoadedRef` is never fetched twice.
 
505
  *
506
  * β›” THE REPAIR IS WHAT MAKES THIS SAFE ON A SERVER THAT SERVES NEITHER NEW ROUTE. If the
507
  * per-tab read answers `status >= 400` and not 403, the route is absent, so the WHOLE workbook
@@ -590,7 +666,8 @@ export default function SheetPage() {
590
  return;
591
  }
592
  setIndex(got.value);
593
- const first = got.value.workbooks[0];
 
594
  // ⭐⭐ W51-T11 / R4 β€” OPENING IS `?tabs=meta` AND THEN THE ACTIVE TAB, in that order and
595
  // never the whole document. A workbook at R4's cap is 100,000 cells a tab; fetching every
596
  // tab to show one is the load this split exists to stop paying.
@@ -609,7 +686,7 @@ export default function SheetPage() {
609
  }
610
  bookRef.current = opened.value;
611
  setBook(opened.value);
612
- const firstTab = opened.value.sheets[0]?.id ?? "";
613
  setTabId(firstTab);
614
  // β›” A WORKBOOK THIS PAGE JUST CREATED IS EMPTY AND WHOLLY IN HAND, so it is marked loaded
615
  // outright; a workbook read as META carries no cells for any tab, so only the one being
@@ -1458,6 +1535,65 @@ export default function SheetPage() {
1458
  })();
1459
  }, [applyLocal, commitCells, flushSave]);
1460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1461
  /** The binding panel's Save. It names the cell the panel is editing, and nothing else. */
1462
  const onSaveBinding = useCallback((binding: Record<string, unknown>) => {
1463
  const addr = editAt;
@@ -1543,14 +1679,103 @@ export default function SheetPage() {
1543
  // The dirty set names addresses in the workbook being left. It does not travel.
1544
  dirtyRef.current = new Map();
1545
  structureDirtyRef.current = false;
 
 
 
1546
  if (held === "all") markAllLoaded(next);
 
 
 
 
 
 
 
 
 
 
1547
  applyLocal(next);
1548
- setTabId(next.sheets[0]?.id ?? "");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1549
  }, [applyLocal, markAllLoaded]);
1550
 
1551
  const openWorkbook = useCallback(async (id: string) => {
1552
  if (id === bookRef.current?.id || workbookTransitionRef.current) return;
1553
  workbookTransitionRef.current = true;
 
 
1554
  setOpening(true);
1555
  setNotice("");
1556
  if (!await flushBeforeWorkbookChange()) {
@@ -1571,7 +1796,8 @@ export default function SheetPage() {
1571
  if (firstTab) await ensureTabs(got.value.id, [firstTab]);
1572
  workbookTransitionRef.current = false;
1573
  setOpening(false);
1574
- }, [adoptWorkbook, ensureTabs, flushBeforeWorkbookChange]);
 
1575
 
1576
  /** R2's create door: made and OPENED in one act, with no name step in between. */
1577
  const createAndOpen = useCallback(async () => {
@@ -2061,12 +2287,18 @@ export default function SheetPage() {
2061
  onViewRows={onViewRows}
2062
  onRefresh={onRefresh}
2063
  onCommit={commitCells}
 
 
2064
  onUndo={onUndo}
2065
  onRedo={onRedo}
2066
  onNotice={setNotice}
2067
  // ⭐ W50-T21's HANDOVER. The bar now mirrors the SELECTED cell; its name box still
2068
  // works, because both write the same state. `FormulaBar.tsx` was not touched.
2069
- onSelect={(sel) => { if (sel) setBarAddr(sel.addr); }}
 
 
 
 
2070
  onStructure={onStructure}
2071
  onGrow={onGrow}
2072
  onFreeze={onFreeze}
 
55
  import type { DrillCellScope } from "./DrillModal";
56
  import FormulaBar from "./FormulaBar";
57
  import SheetGridBase from "./SheetGrid";
58
+ import type { BoundEvaluationRequest, SheetGridProps } from "./SheetGrid";
59
  import SheetRail from "./SheetRail";
60
  import type { RailStrata } from "./SheetRail";
61
  import {
 
255
  /** The cache key for one tab's cells. Workbook scoped, so switching books cannot reuse them. */
256
  const tabKeyOf = (workbookId: string, tabId: string): string => `${workbookId}:${tabId}`;
257
 
258
+ // W56-T05: the last open workbook is one scalar, separate from the bounded per-workbook cell map.
259
+ const LAST_WORKBOOK_KEY = "aios-sheet-last-workbook";
260
+
261
+ function readLastWorkbook(): string {
262
+ try { return localStorage.getItem(LAST_WORKBOOK_KEY) ?? ""; } catch { return ""; }
263
+ }
264
+
265
+ function writeLastWorkbook(workbookId: string): void {
266
+ try { localStorage.setItem(LAST_WORKBOOK_KEY, workbookId); } catch { /* session only */ }
267
+ }
268
+
269
+ // ⭐⭐ W56-T04: LAST CELL IS ONE BOUNDED MAP, NOT ONE UNBOUNDED KEY PER WORKBOOK.
270
+ // Object insertion order is the recency order: touching a workbook deletes and re-adds its row,
271
+ // and the oldest row is the first one dropped when the 50-workbook cap is reached.
272
+ const LAST_CELLS_KEY = "aios-sheet-last-cells";
273
+ const LAST_CELLS_LIMIT = 50;
274
+ type LastCells = Record<string, string>;
275
+
276
+ function readLastCells(): LastCells {
277
+ try {
278
+ const raw = localStorage.getItem(LAST_CELLS_KEY);
279
+ if (!raw) return {};
280
+ const parsed = JSON.parse(raw) as unknown;
281
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
282
+ const out: LastCells = {};
283
+ for (const [id, addr] of Object.entries(parsed).slice(-LAST_CELLS_LIMIT)) {
284
+ if (id && typeof addr === "string" && addr) out[id] = addr;
285
+ }
286
+ return out;
287
+ } catch {
288
+ return {};
289
+ }
290
+ }
291
+
292
+ function writeLastCells(next: LastCells): void {
293
+ try { localStorage.setItem(LAST_CELLS_KEY, JSON.stringify(next)); } catch { /* session only */ }
294
+ }
295
+
296
+ function touchLastCell(current: LastCells, workbookId: string, addr: string): LastCells {
297
+ const next = { ...current };
298
+ delete next[workbookId];
299
+ next[workbookId] = addr;
300
+ const ids = Object.keys(next);
301
+ const expired = ids.slice(0, Math.max(0, ids.length - LAST_CELLS_LIMIT));
302
+ for (const id of expired) delete next[id];
303
+ return next;
304
+ }
305
+
306
  /**
307
  * Does this tab carry anything an undo could destroy?
308
  *
 
329
 
330
  export default function SheetPage() {
331
  const [book, setBook] = useState<Workbook | null>(null);
332
+ /** Read once for the mount decision; later opens write through `prepareWorkbookOpen`. */
333
+ const [lastWorkbookId] = useState<string>(() => readLastWorkbook());
334
  const [tabId, setTabId] = useState<string>("");
335
  const [busy, setBusy] = useState(false);
336
  const [notice, setNotice] = useState("");
 
345
  * longer something a person waits on and is told about afterwards. Excel agrees and it is worth
346
  * recording why: its status bar shows "Calculating (n%)" only WHILE a long recalculation runs,
347
  * and it shows no completion notice of any kind
348
+ * (`AutoWiki/research/excel-formula-ux.md` section 5).
349
  * β›” NOTHING REPLACES IT HERE. Per R2 the per-cell shimmer on a database-bound cell is what
350
  * reports work in progress, and that lives on the cell rather than in a page-level strip.
351
  * ⚠ `notice` DIRECTLY BELOW IS A DIFFERENT LINE AND IT STAYS. It carries refusals - an edit
 
427
 
428
  const bookRef = useRef<Workbook | null>(null);
429
  const tabIdRef = useRef<string>("");
430
+ /** Live session copy; blocked storage still remembers positions until this page unmounts. */
431
+ const lastCellsRef = useRef<LastCells | null>(null);
432
+ if (lastCellsRef.current === null) lastCellsRef.current = readLastCells();
433
+ /** The target is replaced only by workbook adoption, never by a later refresh object. */
434
+ const openAtRef = useRef<SheetGridProps["openAt"]>({ workbookId: "", tabId: "", addr: "A1" });
435
  const historyRef = useRef<SheetHistory>(emptyHistory());
436
  const saveChainRef = useRef<Promise<void>>(Promise.resolve());
437
  /** Bumped by every local edit, so a save knows whether the tree moved under it. */
 
443
  * synchronously and prevents an older, slower read from winning after a newer choice.
444
  */
445
  const workbookTransitionRef = useRef(false);
446
+ /** The one background refresh allowed to replace the workbook opened on screen. */
447
+ const openRefreshRef = useRef<{ id: string } | null>(null);
448
  /** The bottom tab strip and its one pointer-captured drag. High-frequency motion stays in DOM. */
449
  const tabStripRef = useRef<HTMLDivElement | null>(null);
450
  const tabDragRef = useRef<TabDrag | null>(null);
 
476
  const patchModeRef = useRef<"unknown" | "patch" | "put">("unknown");
477
  /** The same answer for the per-tab READ, learned the same way and kept for the same reason. */
478
  const tabRouteRef = useRef<"unknown" | "yes" | "no">("unknown");
479
+ /** Tabs holding cells in the adopted tree. Keyed `workbookId:tabId`, so books cannot collide. */
480
  const tabLoadedRef = useRef<Set<string>>(new Set());
481
  /** The pending debounce, or null when nothing is waiting. */
482
  const saveTimerRef = useRef<number | null>(null);
 
512
  setBook(next);
513
  }, []);
514
 
515
+ /** Decide the opening cell in the same act that adopts the workbook. */
516
+ const prepareWorkbookOpen = useCallback((next: Workbook): string => {
517
+ writeLastWorkbook(next.id);
518
+ const nextTab = next.sheets[0]?.id ?? "";
519
+ const addr = lastCellsRef.current?.[next.id] ?? "A1";
520
+ openAtRef.current = { workbookId: next.id, tabId: nextTab, addr };
521
+ setBarAddr(addr);
522
+ return nextTab;
523
+ }, []);
524
+
525
+ const rememberLastCell = useCallback((addr: string) => {
526
+ const workbookId = bookRef.current?.id;
527
+ if (!workbookId) return;
528
+ const next = touchLastCell(lastCellsRef.current ?? {}, workbookId, addr);
529
+ lastCellsRef.current = next;
530
+ writeLastCells(next);
531
+ }, []);
532
+
533
  useEffect(() => { tabIdRef.current = tabId; }, [tabId]);
534
 
535
  const markDirty = useCallback((tabId2: string, addr: string) => {
 
576
  * ⭐⭐ MAKE SURE THE NAMED TABS ARE IN MEMORY, AND ANSWER WHETHER THEY NOW ARE.
577
  *
578
  * This is the lazy fetch, its cache and its repair path in one door, because all three have to
579
+ * agree about what "loaded" means. A tab already loaded in the current adopted tree is not
580
+ * fetched twice; adopting fresh metadata invalidates the entries for the empty tabs it brings.
581
  *
582
  * β›” THE REPAIR IS WHAT MAKES THIS SAFE ON A SERVER THAT SERVES NEITHER NEW ROUTE. If the
583
  * per-tab read answers `status >= 400` and not 403, the route is absent, so the WHOLE workbook
 
666
  return;
667
  }
668
  setIndex(got.value);
669
+ const first = got.value.workbooks.find((row) => row.id === lastWorkbookId)
670
+ ?? got.value.workbooks[0];
671
  // ⭐⭐ W51-T11 / R4 β€” OPENING IS `?tabs=meta` AND THEN THE ACTIVE TAB, in that order and
672
  // never the whole document. A workbook at R4's cap is 100,000 cells a tab; fetching every
673
  // tab to show one is the load this split exists to stop paying.
 
686
  }
687
  bookRef.current = opened.value;
688
  setBook(opened.value);
689
+ const firstTab = prepareWorkbookOpen(opened.value);
690
  setTabId(firstTab);
691
  // β›” A WORKBOOK THIS PAGE JUST CREATED IS EMPTY AND WHOLLY IN HAND, so it is marked loaded
692
  // outright; a workbook read as META carries no cells for any tab, so only the one being
 
1535
  })();
1536
  }, [applyLocal, commitCells, flushSave]);
1537
 
1538
+ /**
1539
+ * ⭐⭐ W56-T01 / C2 + R7 - A PASTED BOUND BLOCK TAKES SAVE'S SCOPED COMPUTE PATH TOO.
1540
+ * The grid has already committed every landed cell through `commitWithRecalc` before this
1541
+ * callback runs, so the stale cells paint immediately and this remains a second, async step.
1542
+ *
1543
+ * β›” ONE FLUSH FOR THE BLOCK, THEN ONE COMPUTE AT A TIME. `computeCell` persists its answer and
1544
+ * advances the workbook revision, so parallel calls could return revisions out of order and
1545
+ * make the next PATCH conflict with a revision this client caused itself. `refreshWorkbook`
1546
+ * would avoid neither race and would recompute cells outside the pasted range.
1547
+ *
1548
+ * ⚠ THE SCHEDULED BINDING OBJECT IS THE LEASE. An undo, retype or second paste that replaces
1549
+ * it while a round trip is out wins; the old answer may advance the revision, but never replaces
1550
+ * the newer cell.
1551
+ */
1552
+ const onEvaluateBindings = useCallback(({ tabId: target, cells }: BoundEvaluationRequest) => {
1553
+ const base = bookRef.current;
1554
+ const scheduled = Object.entries(cells);
1555
+ if (!base || scheduled.length === 0) return;
1556
+ const wid = base.id;
1557
+ void (async () => {
1558
+ await flushSave();
1559
+ const settled = bookRef.current;
1560
+ if (!settled || settled.id !== wid || !savedCleanRef.current) return;
1561
+ let spoke = false;
1562
+ for (const [addr, cell] of scheduled) {
1563
+ if (cell.kind !== "bound" || !cell.binding) continue;
1564
+ const before = bookRef.current;
1565
+ if (!before || before.id !== wid) return;
1566
+ const heldBefore = before.sheets.find((tab) => tab.id === target)?.cells?.[addr];
1567
+ if (!heldBefore || heldBefore.binding !== cell.binding) continue;
1568
+
1569
+ const got = await computeCell(wid, addr, target);
1570
+ const live = bookRef.current;
1571
+ if (!live || live.id !== wid) return;
1572
+ if (!got.ok) {
1573
+ if (!spoke) {
1574
+ setNotice(got.message);
1575
+ spoke = true;
1576
+ }
1577
+ continue;
1578
+ }
1579
+
1580
+ const rev = got.value.rev || live.rev;
1581
+ const held = live.sheets.find((tab) => tab.id === target)?.cells?.[addr];
1582
+ if (!held || held.binding !== cell.binding) {
1583
+ // β›” THE REVISION STILL LANDS WHEN THE CELL ANSWER DOES NOT. The server persisted the
1584
+ // compute before the local identity changed, so dropping its rev would manufacture the
1585
+ // next save conflict even though the newer cell correctly wins the screen.
1586
+ applyLocal({ ...live, rev });
1587
+ continue;
1588
+ }
1589
+ applyLocal({
1590
+ ...withCells(live, target, { [addr]: got.value.cell }),
1591
+ rev,
1592
+ });
1593
+ }
1594
+ })();
1595
+ }, [applyLocal, flushSave]);
1596
+
1597
  /** The binding panel's Save. It names the cell the panel is editing, and nothing else. */
1598
  const onSaveBinding = useCallback((binding: Record<string, unknown>) => {
1599
  const addr = editAt;
 
1679
  // The dirty set names addresses in the workbook being left. It does not travel.
1680
  dirtyRef.current = new Map();
1681
  structureDirtyRef.current = false;
1682
+ // β›” THE ONE LINER IS LOAD BEARING. `verify_wiring`'s W51-T11 row asserts the literal
1683
+ // `if (held === "all") markAllLoaded(next);`, so wrapping it in braces to gain an `else`
1684
+ // makes that row red about a rule this code still obeys. The `else` hangs off it instead.
1685
  if (held === "all") markAllLoaded(next);
1686
+ else {
1687
+ // A meta read deliberately replaces these tabs with empty cell maps, so their loaded memo
1688
+ // must be replaced too. We do not preserve cells in a second client-side workbook cache:
1689
+ // the meta response is the authoritative tab list, and reconciling an old tree and revision
1690
+ // would create another source of workbook truth. `ensureTabs` now fetches only the open tab.
1691
+ for (const tab of next.sheets) {
1692
+ tabLoadedRef.current.delete(tabKeyOf(next.id, tab.id));
1693
+ }
1694
+ }
1695
+ const firstTab = prepareWorkbookOpen(next);
1696
  applyLocal(next);
1697
+ setTabId(firstTab);
1698
+ }, [applyLocal, markAllLoaded, prepareWorkbookOpen]);
1699
+
1700
+ /**
1701
+ * ⭐⭐ W56-T03 / R7 REVERSES W52-T12 / R3 FOR WORKBOOK OPEN.
1702
+ * R3 deliberately left each viewer's cached bound values in place until Refresh was pressed;
1703
+ * R7 supersedes that decision by painting those cached values first, marking the loaded bound
1704
+ * cells pending locally, then taking the same whole-workbook refresh door in the background.
1705
+ *
1706
+ * β›” THIS PASS NEVER SETS `busy`. The grid stays usable while a large workbook recomputes,
1707
+ * and the existing per-cell stale mark is the progress signal. Its answer is abandoned when a
1708
+ * newer open owns the pass, the reader moved to another workbook, the reader typed while it was
1709
+ * away, or the read failed. In every abandon path only the pending cell objects this pass painted
1710
+ * are restored, so neither cached values nor newer edits are replaced.
1711
+ */
1712
+ const refreshOpenedWorkbook = useCallback((wid: string, loadedTab: string) => {
1713
+ const pass = { id: wid };
1714
+ openRefreshRef.current = pass;
1715
+ const painted = bookRef.current;
1716
+ if (!painted || painted.id !== wid) {
1717
+ if (openRefreshRef.current === pass) openRefreshRef.current = null;
1718
+ return;
1719
+ }
1720
+
1721
+ const marked = new Map<string, { before: Cell; pending: Cell }>();
1722
+ const sheets = painted.sheets.map((tab) => {
1723
+ if (tab.id !== loadedTab || !tabLoadedRef.current.has(tabKeyOf(wid, tab.id))) return tab;
1724
+ let changed = false;
1725
+ const cells = { ...tab.cells };
1726
+ for (const [addr, cell] of Object.entries(tab.cells)) {
1727
+ if (cell.kind !== "bound" || cell.state === "stale") continue;
1728
+ const pending: Cell = { ...cell, state: "stale" };
1729
+ marked.set(addr, { before: cell, pending });
1730
+ cells[addr] = pending;
1731
+ changed = true;
1732
+ }
1733
+ return changed ? { ...tab, cells } : tab;
1734
+ });
1735
+ if (marked.size > 0) applyLocal({ ...painted, sheets });
1736
+
1737
+ const restoreMarkedCells = () => {
1738
+ if (marked.size === 0) return;
1739
+ const live = bookRef.current;
1740
+ if (!live || live.id !== wid) return;
1741
+ let restored = false;
1742
+ const restoredSheets = live.sheets.map((tab) => {
1743
+ if (tab.id !== loadedTab) return tab;
1744
+ const cells = { ...tab.cells };
1745
+ for (const [addr, held] of marked.entries()) {
1746
+ if (cells[addr] !== held.pending) continue;
1747
+ cells[addr] = held.before;
1748
+ restored = true;
1749
+ }
1750
+ return restored ? { ...tab, cells } : tab;
1751
+ });
1752
+ if (restored) applyLocal({ ...live, sheets: restoredSheets });
1753
+ };
1754
+
1755
+ void (async () => {
1756
+ const got = await refreshWorkbook(wid);
1757
+ const live = bookRef.current;
1758
+ if (openRefreshRef.current !== pass || !live || live.id !== wid
1759
+ || dirtyRef.current.size > 0 || !got.ok) {
1760
+ restoreMarkedCells();
1761
+ if (openRefreshRef.current === pass) openRefreshRef.current = null;
1762
+ return;
1763
+ }
1764
+ // A refresh replaces the same tree and dirty addresses as the button's refresh does.
1765
+ historyRef.current = emptyHistory();
1766
+ editSeqRef.current += 1;
1767
+ dirtyRef.current = new Map();
1768
+ markAllLoaded(got.value.workbook);
1769
+ applyLocal(got.value.workbook);
1770
+ if (openRefreshRef.current === pass) openRefreshRef.current = null;
1771
+ })();
1772
  }, [applyLocal, markAllLoaded]);
1773
 
1774
  const openWorkbook = useCallback(async (id: string) => {
1775
  if (id === bookRef.current?.id || workbookTransitionRef.current) return;
1776
  workbookTransitionRef.current = true;
1777
+ // Invalidate an older pass before the first transition await, so it cannot win this open.
1778
+ openRefreshRef.current = null;
1779
  setOpening(true);
1780
  setNotice("");
1781
  if (!await flushBeforeWorkbookChange()) {
 
1796
  if (firstTab) await ensureTabs(got.value.id, [firstTab]);
1797
  workbookTransitionRef.current = false;
1798
  setOpening(false);
1799
+ refreshOpenedWorkbook(got.value.id, firstTab);
1800
+ }, [adoptWorkbook, ensureTabs, flushBeforeWorkbookChange, refreshOpenedWorkbook]);
1801
 
1802
  /** R2's create door: made and OPENED in one act, with no name step in between. */
1803
  const createAndOpen = useCallback(async () => {
 
2287
  onViewRows={onViewRows}
2288
  onRefresh={onRefresh}
2289
  onCommit={commitCells}
2290
+ openAt={openAtRef.current}
2291
+ onEvaluateBindings={onEvaluateBindings}
2292
  onUndo={onUndo}
2293
  onRedo={onRedo}
2294
  onNotice={setNotice}
2295
  // ⭐ W50-T21's HANDOVER. The bar now mirrors the SELECTED cell; its name box still
2296
  // works, because both write the same state. `FormulaBar.tsx` was not touched.
2297
+ onSelect={(sel) => {
2298
+ if (!sel) return;
2299
+ setBarAddr(sel.addr);
2300
+ if (sel.readerCaused) rememberLastCell(sel.addr);
2301
+ }}
2302
  onStructure={onStructure}
2303
  onGrow={onGrow}
2304
  onFreeze={onFreeze}
web/src/sheet/SheetRail.tsx CHANGED
@@ -108,6 +108,20 @@ export interface SheetRailProps {
108
  */
109
  const RAIL_FOLD_KEY = "aios-views-rail";
110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  /** How many rows the rail draws while it is loading. Matches `Shell.tsx::RAIL_SKELETON_ROWS`. */
112
  const SKELETON_ROWS = 6;
113
 
@@ -288,10 +302,12 @@ export default function SheetRail({
288
  return next;
289
  });
290
  /** The folder whose contents are on screen, or null for the top level. */
291
- const [at, setAt] = useState<string | null>(null);
292
- /** Windows-style history for the path row's back and forward buttons. */
293
- const [history, setHistory] = useState<(string | null)[]>([null]);
294
- const [step, setStep] = useState(0);
 
 
295
  const [query, setQuery] = useState("");
296
  const [menu, setMenu] = useState<Menu | null>(null);
297
  const [renaming, setRenaming] = useState("");
@@ -351,6 +367,15 @@ export default function SheetRail({
351
  return map;
352
  }, [folders]);
353
 
 
 
 
 
 
 
 
 
 
354
  const strata = (): RailStrata => ({
355
  folders: folders.map((f) => ({ ...f })),
356
  itemFolders: { ...itemFolders },
@@ -364,6 +389,7 @@ export default function SheetRail({
364
  };
365
 
366
  const goTo = (next: string | null) => {
 
367
  setAt(next);
368
  setQuery("");
369
  setHistory((prev) => [...prev.slice(0, step + 1), next]);
@@ -373,6 +399,7 @@ export default function SheetRail({
373
  const walk = (delta: number) => {
374
  const target = step + delta;
375
  if (target < 0 || target >= history.length) return;
 
376
  setStep(target);
377
  setAt(history[target]);
378
  setQuery("");
 
108
  */
109
  const RAIL_FOLD_KEY = "aios-views-rail";
110
 
111
+ /** W56-T05: one last folder id, separate from the rail-fold and workbook stores. */
112
+ const LAST_FOLDER_KEY = "aios-sheet-last-folder";
113
+
114
+ function readLastFolder(): string | null {
115
+ try { return localStorage.getItem(LAST_FOLDER_KEY) || null; } catch { return null; }
116
+ }
117
+
118
+ function writeLastFolder(folderId: string | null): void {
119
+ try {
120
+ if (folderId) localStorage.setItem(LAST_FOLDER_KEY, folderId);
121
+ else localStorage.removeItem(LAST_FOLDER_KEY);
122
+ } catch { /* session only */ }
123
+ }
124
+
125
  /** How many rows the rail draws while it is loading. Matches `Shell.tsx::RAIL_SKELETON_ROWS`. */
126
  const SKELETON_ROWS = 6;
127
 
 
302
  return next;
303
  });
304
  /** The folder whose contents are on screen, or null for the top level. */
305
+ const [at, setAt] = useState<string | null>(() => readLastFolder());
306
+ /** Restored folders start after root, so Back reaches root and Forward returns here. */
307
+ const [history, setHistory] = useState<(string | null)[]>(
308
+ () => at === null ? [null] : [null, at],
309
+ );
310
+ const [step, setStep] = useState(() => at === null ? 0 : 1);
311
  const [query, setQuery] = useState("");
312
  const [menu, setMenu] = useState<Menu | null>(null);
313
  const [renaming, setRenaming] = useState("");
 
367
  return map;
368
  }, [folders]);
369
 
370
+ /** A folder deleted here or belonging to another tenant silently restores the top level. */
371
+ useEffect(() => {
372
+ if (loading || at === null || byId[at]) return;
373
+ setAt(null);
374
+ setHistory([null]);
375
+ setStep(0);
376
+ writeLastFolder(null);
377
+ }, [at, byId, loading]);
378
+
379
  const strata = (): RailStrata => ({
380
  folders: folders.map((f) => ({ ...f })),
381
  itemFolders: { ...itemFolders },
 
389
  };
390
 
391
  const goTo = (next: string | null) => {
392
+ writeLastFolder(next);
393
  setAt(next);
394
  setQuery("");
395
  setHistory((prev) => [...prev.slice(0, step + 1), next]);
 
399
  const walk = (delta: number) => {
400
  const target = step + delta;
401
  if (target < 0 || target >= history.length) return;
402
+ writeLastFolder(history[target]);
403
  setStep(target);
404
  setAt(history[target]);
405
  setQuery("");
web/src/sheet/a1.ts CHANGED
@@ -154,8 +154,9 @@ export const rewriteRefs = (
154
  /**
155
  * Drag-fill: rewrite every reference in a formula's TEXT by the given delta.
156
  *
157
- * A fill is a MOVE of the formula, so every unpinned part shifts by the same amount wherever it
158
- * points. That is what makes it different from a structural insert, which shifts by POSITION.
 
159
  */
160
  export const fillFormula = (formula: string, dRow: number, dCol: number): string => {
161
  const src = String(formula || "");
@@ -163,6 +164,21 @@ export const fillFormula = (formula: string, dRow: number, dCol: number): string
163
  return rewriteRefs(src, (ref) => shiftRef(ref, dRow, dCol));
164
  };
165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  // ═════════════════════════════════════════════════════════════════════════════════════════════
167
  // ⭐⭐ W50-T20 β€” STRUCTURAL RE-ANCHORING, AND WHY IT IS NOT A FILL.
168
  //
 
154
  /**
155
  * Drag-fill: rewrite every reference in a formula's TEXT by the given delta.
156
  *
157
+ * A fill copies the formula to another cell, so every unpinned part shifts by the same amount
158
+ * wherever it points. That is what makes it different from a structural insert, which shifts by
159
+ * POSITION.
160
  */
161
  export const fillFormula = (formula: string, dRow: number, dCol: number): string => {
162
  const src = String(formula || "");
 
164
  return rewriteRefs(src, (ref) => shiftRef(ref, dRow, dCol));
165
  };
166
 
167
+ export type RefMove = "copy" | "cut";
168
+
169
+ /**
170
+ * Copy or cut a formula to another cell, using the same reference scan as drag-fill.
171
+ *
172
+ * A COPY walks every unpinned reference by the block delta. A CUT is a move, so its formula
173
+ * arrives verbatim: shifting it would change which cells the moved formula reads.
174
+ */
175
+ export const moveFormula = (
176
+ formula: string,
177
+ dRow: number,
178
+ dCol: number,
179
+ mode: RefMove,
180
+ ): string => mode === "cut" ? String(formula || "") : fillFormula(formula, dRow, dCol);
181
+
182
  // ═════════════════════════════════════════════════════════════════════════════════════════════
183
  // ⭐⭐ W50-T20 β€” STRUCTURAL RE-ANCHORING, AND WHY IT IS NOT A FILL.
184
  //