diff --git a/RELEASES.json b/RELEASES.json index a29aeb84c2fb4b8ea3ff469c7c6692eede88c7d1..f3a1294dfb0151f0b2ec4b29a63b97ed638d47b1 100644 --- a/RELEASES.json +++ b/RELEASES.json @@ -1,5 +1,5 @@ { - "current": "fb85b60", + "current": "25a941a", "releases": [ { "version": "v71", diff --git a/VERSION b/VERSION index bf828be3d91d7e7f8e1fb36ba29faf84e5e49021..b89dc5168ae062104d0e9eabe0bc0c3642cf2518 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -fb85b60 +25a941a diff --git a/api/application_registry.py b/api/application_registry.py index e62d6e5e1e48b962a929733b33e232535ec76793..91b6a24cb7cafadad6adfc04366c8ae4608aad5b 100644 --- a/api/application_registry.py +++ b/api/application_registry.py @@ -27,6 +27,8 @@ _TEMPLATE_CONTRACTS = { "types": ["text", "int", "currency", "pct", "rating", "number", "float", "decimal"]}, {"key": "longitude", "label": "Longitude", "required": False, "types": ["text", "int", "currency", "pct", "rating", "number", "float", "decimal"]}, + {"key": "address", "label": "Address", "required": False, + "types": ["text"]}, ], "defaultPlacement": {"section": "app", "order": 0}, }, @@ -245,6 +247,10 @@ def _template_definition(kind, payload, *, semantic_records=None, field_contract raise ApplicationError("Routing needs both coordinate fields or neither") if latitude and latitude == longitude: raise ApplicationError("Routing latitude and longitude must use different fields") + # A new Route must name at least one placement source. Stored definitions are not revalidated + # on read, so this create-time refusal does not retire older Applications with an empty map. + if kind == "route" and not (latitude and longitude) and not field_map.get("address"): + raise ApplicationError("Routing needs both coordinate fields or an address field") raw_placement = payload.get("navPlacement") if not isinstance(raw_placement, dict) or set(raw_placement) != {"section", "order"}: diff --git a/api/automation_engine.py b/api/automation_engine.py index 95a6e2909358f6df1c26c6fb55e8e9216537279d..84b01ee1dcc5cd1088b5e8e6556f854ac15e3794 100644 --- a/api/automation_engine.py +++ b/api/automation_engine.py @@ -4097,7 +4097,7 @@ POST_SNAPSHOT_FIELDS = [ # ⛔⛔ AND THEY DO NOT MAKE "THE LAST 10 REELS" EXPRESSIBLE OVER THIS TABLE. That takes TWO # orderings (newest measurement per post, then newest posts), the rollup bag has one `sortBy`, # and `ut_ig_posts` already performs the first of them. See the verdict in - # `.claude/wiki/research/entity-vs-series.md` — these columns are for AGE and KIND, not for + # `AutoWiki/research/entity-vs-series.md` — these columns are for AGE and KIND, not for # moving the window here. field_def("posted_at", "Posted at", "date"), field_def("type", "Type", "select", options=["image", "video", "carousel"]), diff --git a/api/connectors_meta.py b/api/connectors_meta.py index 11bfd80dfed0bab72ec191fa627db58d25786161..77970eb8581e751d5fcce8cdb75e0eeedee7bb04 100644 --- a/api/connectors_meta.py +++ b/api/connectors_meta.py @@ -494,7 +494,7 @@ def main(argv): print(f"REFUSED: {e}") return 1 report = probe() - out = (Path(__file__).resolve().parents[2] / ".claude" / "wiki" / "research" / "waves" + out = (Path(__file__).resolve().parents[2] / "AutoWiki" / "research" / "waves" / "wave31" / "proto" / "meta-ads-schema.md") out.parent.mkdir(parents=True, exist_ok=True) out.write_text(as_markdown(report), encoding="utf-8") diff --git a/api/connectors_tt.py b/api/connectors_tt.py index 0603f4f23f7075252fdcef06ce19371ac1620523..3a692a7f2505cee8db8e0f3cf6950c4d7045e52b 100644 --- a/api/connectors_tt.py +++ b/api/connectors_tt.py @@ -7,7 +7,7 @@ exists at all rather than another thousand lines inside the engine. ⛔ **EVERY VENDOR FIELD NAME HERE WAS PROBED, NOT GUESSED.** The whole schema — 40 profile / 43 post / 17 comment fields, each with the vendor's own type, description and `pii` flag — was read live from `GET /datasets/{id}/metadata` for **$0.00** and written down in -`.claude/wiki/waves/wave29/proto/tiktok-schema.md` (promoted to `tiktok-capture.md` at +`AutoWiki/waves/wave29/proto/tiktok-schema.md` (promoted to `tiktok-capture.md` at close-out). That document is the AUTHORITY: do not re-probe it, and do not invent a key. Where a name below reads through a candidate list it is because the vendor has two names for one fact (`biography`/`signature`, `region`/`country`), never because the name is uncertain. diff --git a/api/main.py b/api/main.py index 5db2889aeef9de7266d427785cd3c101cdd099ae..189550b3f9c253d1b57a5645b28e6541472f48ff 100644 --- a/api/main.py +++ b/api/main.py @@ -66,6 +66,7 @@ import routes_sheet # noqa: E402 (wave 49 instr 1 / W49-T02 / C1 — the Sheet import routes_customers # noqa: E402 import routes_grid # noqa: E402 import routes_keychain # noqa: E402 (wave 18 C7 — keychain + connectors admin surfaces) +import routes_external # noqa: E402 (wave 56 R3/C7 — per-user external AI credential) import routes_statements # noqa: E402 (EXIT-6 — the statement sender, off Streamlit) import routes_nav # noqa: E402 import routes_pages # noqa: E402 @@ -461,6 +462,7 @@ app.include_router(routes_agent_harness.router) # R8 / C4 — versioned agent h # tiles = OpenStreetMap · routing = OSRM · geocoding = Nominatim, none of them keyed, all of them # rate-limited by POLITENESS rather than by a bill (~1 req/s, and bulk harvesting is forbidden). app.include_router(routes_geo.router) # R14 / A11 — D's router, A's line (map providers) +app.include_router(routes_external.router) # --- DEPRECATED ALIASES (removed when S2's shell flips; kept so the current bundle keeps working) diff --git a/api/odoo_relational.py b/api/odoo_relational.py index 611086cff46e784c919b8a1d849a8ec2ca8be8e6..3279a56cda0cd5e8a3acf780466bfa5fc61da5ee 100644 --- a/api/odoo_relational.py +++ b/api/odoo_relational.py @@ -49,6 +49,7 @@ the oracle's predicate as an explicit `payment_state` condition pair. """ import datetime as _dt import json as _json +import time as _time #: ⛔ ROUTE ENTITLEMENT, NOT THE SPAWN GATE — `refresh()` stopped reading this at W53-T39 / R3, #: 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 return result +# The population fact is deliberately separate from the readable-model catalogue. Measured on +# Royal Imports on 2026-09-08: discovery found 499 readable models in 22.62 s, then exact +# search_count calls took 67.87 s for 494 models at 137 ms per model; 239 held rows. A sampled +# search_read was slower and raised on account.move, so sampling is neither the cheap nor the +# reliable fallback. The exact pass stays explicit and cached because a cold 90.5 s pass cannot +# sit on the connector detail request. +POPULATION_CENSUS_KEY = "odoo_population_census" +POPULATION_CENSUS_VERSION = 1 +FIELD_CENSUS_KEY = "odoo_field_population" +FIELD_CENSUS_VERSION = 1 +_FIELD_CENSUS_UNCOUNTABLE_TYPES = {"one2many", "many2many"} + + +def field_census(rt, connection_id=None): + """Return the cached per-model field counts; this reader never contacts Odoo.""" + try: + cached = rt.get(FIELD_CENSUS_KEY) if rt is not None else None + except Exception: # noqa: BLE001 + cached = None + if not isinstance(cached, dict) or cached.get("version") != FIELD_CENSUS_VERSION: + return {} + connections = cached.get("connections") + if not isinstance(connections, dict): + return {} + stored = connections.get(_catalog_slot(connection_id)) + if not isinstance(stored, dict): + return {} + answer = {} + for model, report in stored.items(): + if not str(model).strip() or not isinstance(report, dict): + continue + raw_counts = report.get("counts") if isinstance(report.get("counts"), dict) else {} + counts = {str(name): int(value) for name, value in raw_counts.items() + if str(name).strip() and isinstance(value, int) + and not isinstance(value, bool) and value >= 0} + raw_errors = report.get("errors") + errors = ([str(value) for value in raw_errors] + if isinstance(raw_errors, (list, tuple)) else []) + try: + duration_ms = max(0, int(report.get("durationMs") or 0)) + except (TypeError, ValueError, OverflowError): + duration_ms = 0 + answer[str(model)] = { + "capturedAt": str(report.get("capturedAt") or ""), + "durationMs": duration_ms, + "counts": counts, + "errors": errors, + "complete": report.get("complete") is True, + } + return answer + + +def refresh_field_census(rt, model, connection_id=None, client=None, force=False): + """Exactly count every countable field in one model using read-only ``search_count``.""" + model = str(model or "").strip() + current = field_census(rt, connection_id).get(model) + if current and current.get("capturedAt") and not force: + return current + + # Exact per-field domains measured 26 ms on res.partner, 41 ms on sale.order and 72 ms on + # account.move on 2026-09-08, making the full models about 5.2 s, 5.1 s and 13.7 s. A sampled + # search_read took 3.17 s and 7.68 s on the first two and failed on account.move in Odoo's + # XML-RPC marshaller, so every countable field uses exact search_count with no cap or sample. + started = _time.monotonic() + catalogue = readable_model_catalog(rt, connection_id) + row = next((item for item in (catalogue.get("models") or ()) + if isinstance(item, dict) and str(item.get("model") or "").strip() == model), None) + fields = dict(row.get("fields") or {}) if row else {} + counts = {} + errors = [] + if not model: + errors.append("model: a model name is required") + elif row is None: + errors.append(f"{model}: model is not in the readable model catalogue") + + def _count_all(bound_client): + for name, metadata in fields.items(): + field_name = str(name or "").strip() + field_meta = metadata if isinstance(metadata, dict) else {} + field_type = str(field_meta.get("type") or "") + if not field_name: + continue + if field_type in _FIELD_CENSUS_UNCOUNTABLE_TYPES: + # Relational collection fields do not answer `!= False` usefully. They remain + # unknown and are never recorded as empty or selected for automatic enablement. + errors.append(f"{model}.{field_name}: {field_type} cannot be counted usefully " + "with a non-null domain") + continue + try: + # This is the only Odoo operation in the field census. It cannot mutate data. + counts[field_name] = int(bound_client.search_count( + model, [(field_name, "!=", False)])) + except Exception as exc: # noqa: BLE001 + errors.append(f"{model}.{field_name}: {type(exc).__name__}: {exc}") + + if client is not None and fields: + _count_all(client) + elif fields: + try: + source = (rt.odoo_source() if connection_id is None + else rt.odoo_source(connection_id)) + if source is None: + errors.append("connection: Odoo source is unavailable") + else: + from core.odoo import get_odoo + with source._bound(): # tenant credential + scope + _count_all(get_odoo()) + except Exception as exc: # noqa: BLE001 + errors.append(f"connection: {type(exc).__name__}: {exc}") + + countable = sum( + 1 for name, metadata in fields.items() + if str(name or "").strip() + and str((metadata if isinstance(metadata, dict) else {}).get("type") or "") + not in _FIELD_CENSUS_UNCOUNTABLE_TYPES) + result = { + "capturedAt": _dt.datetime.now(_dt.timezone.utc).isoformat(), + "durationMs": int((_time.monotonic() - started) * 1000), + "counts": counts, + "errors": errors, + "complete": row is not None and catalogue.get("complete") is True and not errors + and len(counts) == countable, + } + slot = _catalog_slot(connection_id) + + def _cache(current_cache): + current_cache = dict(current_cache) if isinstance(current_cache, dict) else {} + connections = dict(current_cache.get("connections") or {}) + models = dict(connections.get(slot) or {}) + models[model] = result + connections[slot] = models + return {"version": FIELD_CENSUS_VERSION, "connections": connections} + + rt.update(FIELD_CENSUS_KEY, _cache, flush="sync") + return result + + +def population_census(rt, connection_id=None): + """The last census, from the tenant store. Reading it never contacts Odoo.""" + empty = {"version": POPULATION_CENSUS_VERSION, "capturedAt": "", "complete": False, + "durationMs": 0, "counts": {}, "errors": [], "modelsCounted": 0, + "modelsWithRows": 0} + try: + cached = rt.get(POPULATION_CENSUS_KEY) if rt is not None else None + except Exception: # noqa: BLE001 + return empty + if not isinstance(cached, dict) or cached.get("version") != POPULATION_CENSUS_VERSION: + return empty + connections = cached.get("connections") + if not isinstance(connections, dict): + return empty + slot = connections.get(_catalog_slot(connection_id)) or {} + if not isinstance(slot, dict): + return empty + raw_counts = slot.get("counts") if isinstance(slot.get("counts"), dict) else {} + counts = {str(model): int(value) for model, value in raw_counts.items() + if str(model).strip() and isinstance(value, int) and not isinstance(value, bool) + and value >= 0} + raw_errors = slot.get("errors") + errors = ([str(value) for value in raw_errors] + if isinstance(raw_errors, (list, tuple)) else []) + + def _nonnegative_int(value): + try: + return max(0, int(value)) + except (TypeError, ValueError, OverflowError): + return 0 + + return {"version": POPULATION_CENSUS_VERSION, + "capturedAt": str(slot.get("capturedAt") or ""), + "complete": slot.get("complete") is True, + "durationMs": _nonnegative_int(slot.get("durationMs")), + "counts": counts, + "errors": errors, + "modelsCounted": _nonnegative_int(slot.get("modelsCounted")), + "modelsWithRows": _nonnegative_int(slot.get("modelsWithRows"))} + + +def refresh_population_census(rt, connection_id=None, client=None, force=False): + """Count every readable model with read-only ``search_count`` and cache the result.""" + current = population_census(rt, connection_id) + if current["capturedAt"] and not force: + return current + + # Start before possible discovery so durationMs is the wall clock the person waiting sees: + # about 68 s with a warm catalogue and about 90.5 s on a fresh workspace in the measured run. + started = _time.monotonic() + catalogue = readable_model_catalog(rt, connection_id) + if not catalogue["models"]: + catalogue = refresh_readable_model_catalog( + rt, connection_id=connection_id, client=client, force=False) + + models = [] + seen = set() + for row in catalogue.get("models") or (): + model = str(row.get("model") or "").strip() if isinstance(row, dict) else "" + if model and model not in seen: + seen.add(model) + models.append(model) + + counts = {} + errors = [str(value) for value in (catalogue.get("errors") or ())] + if not models and catalogue.get("complete") is not True: + errors.append("catalogue: no complete readable model catalogue is available") + + def _count_all(bound_client): + for model in models: + try: + # search_count is the only Odoo operation in the census. It cannot mutate data. + counts[model] = int(bound_client.search_count(model, [])) + except Exception as exc: # noqa: BLE001 + errors.append(f"{model}: {type(exc).__name__}: {exc}") + + if client is not None: + _count_all(client) + elif models: + try: + source = (rt.odoo_source() if connection_id is None + else rt.odoo_source(connection_id)) + if source is None: + errors.append("connection: Odoo source is unavailable") + else: + from core.odoo import get_odoo + with source._bound(): # tenant credential + scope + _count_all(get_odoo()) + except Exception as exc: # noqa: BLE001 + errors.append(f"connection: {type(exc).__name__}: {exc}") + + result = { + "version": POPULATION_CENSUS_VERSION, + "capturedAt": _dt.datetime.now(_dt.timezone.utc).isoformat(), + "complete": catalogue.get("complete") is True and not errors + and len(counts) == len(models), + "durationMs": int((_time.monotonic() - started) * 1000), + "counts": counts, + "errors": errors, + "modelsCounted": len(counts), + "modelsWithRows": sum(1 for value in counts.values() if value > 0), + } + slot = _catalog_slot(connection_id) + + def _cache(current_cache): + current_cache = dict(current_cache) if isinstance(current_cache, dict) else {} + connections = dict(current_cache.get("connections") or {}) + connections[slot] = result + return {"version": POPULATION_CENSUS_VERSION, "connections": connections} + + rt.update(POPULATION_CENSUS_KEY, _cache, flush="sync") + return result + + #: ⭐⭐ W53-T38 / C2 — THE CONNECTOR SCHEMA SPEC ODOO HAS NEVER HAD. #: #: Amazon and Meta each got a `ConnectorTableSpec` row per table in `platform/core/connector_spec.py` diff --git a/api/routes_connectors.py b/api/routes_connectors.py index 8060022ff5bfa231be2f729296db9a187e944ee6..3d2d3c9fc762949230d7bf92e20745e7ae1f2e1e 100644 --- a/api/routes_connectors.py +++ b/api/routes_connectors.py @@ -33,6 +33,7 @@ from deps import Session, err, require_session #: of it (a gate, a future module page) must not have to import FastAPI to ask what category a #: connector is in. from core import connector_directory +from core import connector_sync #: ⭐ W53-T27 / R9 / C2 — the label RESOLVER, imported rather than re-written. "Shipped default, #: per-tenant override, absent means inherit" is one idea and `core/schema_overlay.py` already #: owns it for fields; `merge_database_labels` is that idea for a database's own name. This module @@ -114,7 +115,7 @@ PLANNED = [ # (Instagram arriving another way) is now visible ON the Scraper card, so keeping it would put # Instagram on this page twice, once as working and once as blocked. The Meta business # verification blocker itself is not lost — it is D-86's subject and lives in - # `.claude/wiki/research/ads-connectors-owner-actions.md`, where an owner action belongs. + # `AutoWiki/research/ads-connectors-owner-actions.md`, where an owner action belongs. ] #: ⭐ 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): raise err(403, "not_admin", "only an administrator can inspect the Odoo schema") +def _sync_admin(session): + if not session.admin: + raise err(403, "not_admin", "only an administrator can retry a connector sync") + + +def _sync_payload(connector_key, connection_id, row=None): + """One wire shape for every registered connector, including one not yet run.""" + meta = connector_sync.providers()[connector_key] + slot = str(connection_id or "").strip() or "default" + if row is None: + return {"provider": connector_key, "label": meta["label"], + "connectionId": slot, "recorded": False, "state": None, + "at": None, "stateAt": None, "from": None, + "detail": "no sync has been recorded", "errors": [], "errorsTotal": 0, + "databases": [], "retryable": False, "retryHint": meta["retryHint"]} + answer = dict(row) + answer.update({"label": meta["label"], "recorded": True, + "stateAt": row.get("at"), "retryHint": meta["retryHint"]}) + return answer + + +def _odoo_sync_runner(session, connection_id): + """Run Odoo through C6 without moving provider imports into the data layer.""" + connector_sync.record(session.runtime, "odoo", connection_id, "syncing") + # The current Odoo entry point plans and applies in one call, so the closest truthful seam is + # immediately before it starts applying the tenant mirror into governed database definitions. + connector_sync.record(session.runtime, "odoo", connection_id, "materializing") + import odoo_relational + result = odoo_relational.refresh(session.runtime, session.tenant, + username=session.uname or "automation", + connection_id=connection_id) + tables = result.get("tables") if isinstance(result, dict) else {} + databases = sorted(str(key) for key in (tables or {}).keys()) + sync_errors = [] + if isinstance(result, dict): + if result.get("failed"): + sync_errors.append(str(result["failed"])) + discovered = result.get("discovered") + if isinstance(discovered, dict): + sync_errors.extend(str(value) for value in (discovered.get("errors") or ())) + discovered_tables = discovered.get("tables") + if isinstance(discovered_tables, dict): + databases.extend(str(key) for key in discovered_tables) + if result.get("frozen"): + sync_errors.append(str(result.get("note") or "the connector is frozen")) + state = ("partial" if databases else "error") if sync_errors else "ready" + return connector_sync.record( + session.runtime, "odoo", connection_id, state, + detail=str(result.get("note") or "") if isinstance(result, dict) else "", + errors=sync_errors, databases=sorted(set(databases)), + ) + + +# Provider runners are an API-layer capability. The data-layer registration proves Amazon uses +# the same contract while this table honestly leaves it without an executable sync. +_SYNC_RUNNERS = {"odoo": _odoo_sync_runner} + + +def _sync_refusals(): + """The provider refusal types whose OWN sentence is the answer, as a tuple for `except`. + + ⚠ Resolved lazily and defensively: `odoo_relational` is imported inside functions throughout + this module to avoid an import cycle, and a refusal handler that could itself raise on import + would turn every failed sync into a different failure. + """ + try: + import odoo_relational # noqa: PLC0415 + return (odoo_relational.Refused,) + except Exception: # noqa: BLE001 + return () + + def _schema_catalog(session): """Rows-free Odoo field catalogue; source fields remain discoverable when every value is empty.""" return _schema_catalog_rt(session.runtime) @@ -1157,17 +1230,86 @@ def _schema_catalog_rt(rt): @router.get("/connectors/odoo/status") -def odoo_status(session: Session = Depends(require_session)): +def odoo_status(connection_id: str = None, session: Session = Depends(require_session)): _odoo_admin(session) import odoo_relational cfg = odoo_relational.read_config(session.runtime) stored = session.runtime.get(_ODOO_SYNC_STATUS) or {} errors = stored.get("errors") if isinstance(stored.get("errors"), list) else [] phase = str(stored.get("phase") or "unknown") + lifecycle = connector_sync.read(session.runtime, "odoo", connection_id) + # The old keys stay the old default-connection answer. A caller that names a connection gets + # that slot's lifecycle instead of the tenant-wide legacy document that caused the C6 defect. + named = connection_id is not None + shown_errors = (list(lifecycle.get("errors") or ()) if named and lifecycle else + [] if named else errors) + shown_phase = ((lifecycle or {}).get("state") or "unknown") if named else phase + shown_last_run = ((lifecycle or {}).get("at") if named else stored.get("lastRun")) + state = ((lifecycle or {}).get("state") + or {"syncing": "syncing", "ok": "ready", "error": "error"}.get(shown_phase) + or "queued") + errors_total = ((lifecycle or {}).get("errorsTotal", 0) if named or lifecycle + else len(errors)) return {"schedule": cfg.get("syncEvery"), - "health": "paused" if cfg.get("frozen") else "error" if errors else phase, - "lastRun": stored.get("lastRun"), "errors": errors[:20], - "frozen": cfg.get("frozen") is True} + "health": "paused" if cfg.get("frozen") else + shown_phase if named else "error" if shown_errors else shown_phase, + "lastRun": shown_last_run, "errors": shown_errors[:20], + "frozen": cfg.get("frozen") is True, + "state": state, + "stateAt": (lifecycle or {}).get("at") or shown_last_run, + "databases": list((lifecycle or {}).get("databases") or ()), + "retryable": state in ("error", "partial"), + "errorsTotal": int(errors_total or 0), + "connectionId": (lifecycle or {}).get("connectionId") + or str(connection_id or "").strip() or "default"} + + +@router.get("/connectors/{connector_key}/sync") +def connector_sync_status(connector_key: str, connection_id: str = None, + session: Session = Depends(require_session)): + registered = connector_sync.providers() + if connector_key not in registered: + raise err(404, "sync_provider_unknown", + f"{connector_key} is not registered for connector sync") + row = connector_sync.read(session.runtime, connector_key, connection_id) + return _sync_payload(connector_key, connection_id, row) + + +@router.post("/connectors/{connector_key}/sync/retry") +def connector_sync_retry(connector_key: str, connection_id: str = None, + session: Session = Depends(require_session)): + _sync_admin(session) + registered = connector_sync.providers() + if connector_key not in registered: + raise err(404, "sync_provider_unknown", + f"{connector_key} is not registered for connector sync") + current = connector_sync.read(session.runtime, connector_key, connection_id) + if current and current.get("state") in ("syncing", "materializing"): + raise err(409, "sync_already_running", + f"{registered[connector_key]['label']} is already " + f"{current['state']}; a second concurrent sync was not started") + runner = _SYNC_RUNNERS.get(connector_key) + if runner is None: + raise err(501, "sync_runner_unavailable", registered[connector_key]["retryHint"]) + connector_sync.record(session.runtime, connector_key, connection_id, "queued", + detail="retry requested") + try: + row = runner(session, connection_id) + except _sync_refusals() as exc: + # ⛔⛔ A REFUSAL CARRIES AN ACTIONABLE SENTENCE AND IT MUST REACH THE READER, VERBATIM. + # `odoo_relational.Refused` says things like "Add an Odoo credential in the Connectors + # panel, then run the sync again" and "tenant holds N of MAX_TABLES databases". Collapsing + # that into a generic 500 tells the user their sync broke and hides the one line that says + # what to do about it. This screen does not know why the provider refused and must never + # compose a guess, which is the same rule the dependents refusal already follows. + connector_sync.record(session.runtime, connector_key, connection_id, "error", + detail="the connector refused the sync", errors=(str(exc),)) + raise err(409, "sync_refused", str(exc)) + except Exception as exc: # noqa: BLE001 - failure is recorded so the retry remains observable + connector_sync.record(session.runtime, connector_key, connection_id, "error", + detail="connector sync failed", errors=(str(exc),)) + raise err(500, "sync_failed", f"{registered[connector_key]['label']} sync failed") + return _sync_payload(connector_key, connection_id, row) @router.get("/connectors/odoo/schema") @@ -1193,6 +1335,181 @@ def odoo_schema(session: Session = Depends(require_session)): "source": "Odoo"} +@router.post("/connectors/odoo/census") +def odoo_population_census(session: Session = Depends(require_session)): + """Explicitly count every readable Odoo model; connector detail only reads this cache.""" + _odoo_admin(session) + import odoo_relational + census = odoo_relational.refresh_population_census(session.runtime, force=True) + return {"capturedAt": str(census.get("capturedAt") or ""), + "complete": census.get("complete") is True, + "durationMs": int(census.get("durationMs") or 0), + "modelsCounted": int(census.get("modelsCounted") or 0), + "modelsWithRows": int(census.get("modelsWithRows") or 0), + "errors": [str(value) for value in (census.get("errors") or ())][:50]} + + +def _materialisation_failure_reason(result): + """The materialiser's own reason, made safe for a sentence shown in the connector modal.""" + result = result if isinstance(result, dict) else {} + candidates = [] + if result.get("note"): + candidates.append(result.get("note")) + if result.get("failed"): + candidates.append(result.get("failed")) + errors = result.get("errors") + candidates.extend(errors if isinstance(errors, (list, tuple)) else (errors,)) + discovered = result.get("discovered") + if isinstance(discovered, dict): + errors = discovered.get("errors") + candidates.extend(errors if isinstance(errors, (list, tuple)) else (errors,)) + reason = str(next((value for value in candidates if str(value or "").strip()), "")).strip() + # Provider errors can carry typographic punctuation. Screen strings use plain punctuation. + reason = reason.replace("\u2014", ",").replace("\u2013", "-") + return reason[:1].upper() + reason[1:] if reason else "" + + +def _evict_odoo_product_pools(rt): + """Drop every raw-field-sensitive row pool after field enablement changes.""" + for cache_key in list(getattr(rt, "pool_cache", {}) or {}): + if isinstance(cache_key, tuple) and cache_key[:1] == ("product_pool",): + rt.pool_cache.pop(cache_key, None) + + +def _enable_odoo_database(table_key, session): + """Turn on one declared Odoo database and materialise it before reporting success.""" + if not session.admin: + raise err(403, "not_admin", "only an administrator can enable an Odoo database") + + import odoo_relational # noqa: PLC0415 - provider owns both paths + key = str(table_key or "").strip() + choices = {str(choice.get("key") or ""): choice + for choice in odoo_relational.grid_choices(session.runtime)} + if key not in choices: + raise err(404, "unknown_odoo_database", + f"Odoo does not declare a database with key {key!r}") + + # ⭐ W56-T31: before this door, enabled meant only "will be included in the next sync". + # `canRename` then correctly stayed false because there was no table. The flag remains in the + # connector's one CONFIG_KEY document, but this door also creates the database before it can + # answer green. + def _up(cur): + cur = cur if isinstance(cur, dict) else {} + cur.setdefault("grids", {}).update({key: True}) + return cur + + failure = None + try: + session.runtime.update(odoo_relational.CONFIG_KEY, _up, flush="sync") + except Exception: # noqa: BLE001 + raise err(503, "store_unavailable", "the database setting was not saved. Try again.") + + try: + # The curated mirror and the discovered long tail have different materialisers. Choosing + # by the provider's authored key map prevents a successful call that silently skips the + # requested database. + if key in odoo_relational.ODOO_TABLE_MODELS: + result = odoo_relational.refresh(session.runtime, session.tenant) + else: + result = odoo_relational.sync_discovered_models(session.runtime) + except odoo_relational.Refused as exc: + # The provider owns this sentence. In particular it names missing credentials and the + # MAX_TABLES refusal without this route guessing which one happened. + failure = (409, "odoo_database_refused", str(exc)) + except Exception: # noqa: BLE001 + failure = (500, "database_materialisation_failed", + "The setting was enabled, but the database was not created because the " + "materialiser failed.") + + facts = (_rename_rights(session.runtime, session.uname, bool(session.admin), [key]).get(key) + or {"exists": False, "canRename": False}) + exists = facts.get("exists") is True + can_rename = facts.get("canRename") is True + # ⛔⛔ THE ERROR ENVELOPE STAYS THE ONE SHAPE. `deps.err` is documented as X2's single + # non-2xx body, `{"error": {"code", "message"}}`, and an earlier draft of this door attached + # `key`, `enabled` and the fresh facts BESIDE that key so the client could read them off a + # failure. Two shapes for one thing is what this module's own comments call the defect it has + # paid for twice, and a caller that learns to read a sibling off an error will keep doing it. + # The client does not need them: the FLAG is written before materialisation is attempted, so + # every outcome of this door can change what `/detail` answers, and `flipTable` therefore + # re-reads on both paths. + if failure is not None: + raise err(*failure) + if not exists: + reason = _materialisation_failure_reason(result) + message = "The setting was enabled, but the database was not created." + if reason: + message = f"{message} {reason}" + else: + message = f"{message} The materialiser completed without creating it." + raise err(409, "database_not_created", message) + + # W56-T32: the explicit enable action may spend a few seconds measuring one model. Exact + # non-null search_count calls measured 26 ms per res.partner field, 41 ms on sale.order and + # 72 ms on account.move. Sampling was rejected because search_read took seconds and Odoo's + # XML-RPC marshaller failed on account.move. The census therefore has no cap or sample. + model = str(choices[key].get("model") or + odoo_relational.ODOO_TABLE_MODELS.get(key) or "").strip() + try: + field_report = odoo_relational.refresh_field_census( + session.runtime, model, force=True) + populated_keys = { + f"{model}.{field_name}": True + for field_name, count in (field_report.get("counts") or {}).items() + if isinstance(count, int) and not isinstance(count, bool) and count > 0 + } + + # One whole-document write sets every populated field. It never writes False: an empty + # field, an unknown one2many or many2many field, and any field whose count failed retain + # the user's existing choice rather than being switched off or guessed on. + session.runtime.update( + _ODOO_SCHEMA_ENABLEMENTS, + lambda current: { + **(current if isinstance(current, dict) else {}), + **populated_keys, + }, + flush="sync") + except Exception: # noqa: BLE001 + raise err(503, "field_auto_enable_failed", + "The database was created, but its populated fields could not be switched on. " + "Try again.") + _evict_odoo_product_pools(session.runtime) + + # Read the siblings from the same detail row that powers `sharesFieldsWith`. The labels are + # tenant-effective names, and no pair list is repeated at this write door. + detail_rows = _detail_databases( + session.runtime, bool(session.admin), "odoo", session.uname or "") + detail_by_key = {str(row.get("key") or ""): row for row in detail_rows} + detail_row = detail_by_key.get(key) or {} + shared_rows = [ + {"key": sibling_key, + "label": str((detail_by_key.get(sibling_key) or {}).get("label") or sibling_key)} + for sibling_key in (detail_row.get("sharesFieldsWith") or ()) + if str(sibling_key or "") in detail_by_key + ] + # W56-T36: there is deliberately no navigation projection eviction here. Data's database + # list comes from + # `GET /nav` -> `core.user_tables.all_defs()` -> `TenantRuntime.get_projection(user_tables)`. + # Both materialisers above synchronously update that same `user_tables` document; the HF + # backend replaces its whole-document cache as part of that write, while Postgres performs a + # fresh SELECT for every projection. `pool_cache` contains row pools for built-in databases, + # not the `ut_*` definition list, and compiled registry rows never contain tenant databases. + # The table now exists, so clients must discard navigation-derived database lists. This is a + # wire instruction rather than a guessed client row: `/nav` remains the permission-filtered + # authority for which databases the current reader may see. + return {"key": key, "enabled": True, "exists": exists, "canRename": can_rename, + "workspaceChanged": True, "populatedFieldsEnabled": len(populated_keys), + "fieldCensusComplete": field_report.get("complete") is True, + "fieldCensusErrors": list(field_report.get("errors") or ()), + "autoEnableAlsoAffects": shared_rows} + + +@router.post("/connectors/odoo/databases/{table_key}/enable") +def odoo_database_enable(table_key: str, session: Session = Depends(require_session)): + """Enable and create one declared Odoo database in this tenant's governed store.""" + return _enable_odoo_database(table_key, session) + + @router.patch("/connectors/odoo/schema/{field_key}") def odoo_schema_enable(field_key: str, body: dict = Body(default=None), session: Session = Depends(require_session)): @@ -1219,9 +1536,7 @@ def odoo_schema_enable(field_key: str, body: dict = Body(default=None), _ODOO_SCHEMA_ENABLEMENTS, lambda current: {**(current if isinstance(current, dict) else {}), key: enabled}, flush="sync") - for cache_key in list(getattr(session.runtime, "pool_cache", {}) or {}): - if isinstance(cache_key, tuple) and cache_key[:1] == ("product_pool",): - session.runtime.pool_cache.pop(cache_key, None) + _evict_odoo_product_pools(session.runtime) return {"key": key, "enabled": enabled, "source": "Odoo", "permissionWall": "normal field permissions"} @@ -1630,7 +1945,7 @@ def _database_name_overrides(rt): def _rename_rights(rt, uname, is_admin, keys): - """`{table key: bool}` — which of these databases THIS reader may rename (R9's write wall). + """`{table key: {exists, canRename}}` for R9's write wall and its prerequisite. ⛔ THE SAME PREDICATE `routes_nav.save_nav_meta` APPLIES TO A `ut_` KEY, not a second one: `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): technicality: `nav_meta` is keyed by TABLE key, so a name stored for a table nobody can open would sit in the tenant's document naming nothing, and the rail would never show it. - ⚠ IT IS SERVED PER ROW because the answer IS per row, and because a control the server will - refuse is R7's banned shape. One `lend_defs` read answers the whole list; that projection - carries definitions without rows (~0.1% of the document's bytes). + ⭐ W56-T31: `enabled` USED TO MEAN "will be included in the next sync", while the screen + read as though the database already existed. `canRename` was telling the truth about a table + that did not exist. Returning `exists` from this same projection lets the client distinguish + that state from a reader who may not open an existing table. + + ⚠ IT IS SERVED PER ROW because the answers ARE per row. One `lend_defs` read answers the + whole list; that projection carries definitions without rows (~0.1% of the document's bytes). """ try: import core.user_tables as user_tables # noqa: PLC0415 - lazy, as elsewhere definitions = user_tables.lend_defs(rt) - return {key: bool(str(key).startswith("ut_") - and user_tables.get(key, st=definitions) - and user_tables.may_open(key, uname, bool(is_admin), st=definitions)) - for key in keys} + facts = {} + for key in keys: + exists = bool(user_tables.get(key, st=definitions)) + facts[key] = { + "exists": exists, + "canRename": bool(str(key).startswith("ut_") and exists + and user_tables.may_open( + key, uname, bool(is_admin), st=definitions)), + } + return facts except Exception: # noqa: BLE001 # Fail closed. A wall that could not be read is not a wall that admitted you. - return {key: False for key in keys} + return {key: {"exists": False, "canRename": False} for key in keys} def _named_databases(rt, is_admin, uname, rows): @@ -1667,7 +1992,9 @@ def _named_databases(rt, is_admin, uname, rows): named = schema_overlay.merge_database_labels(rows, _database_name_overrides(rt)) rights = _rename_rights(rt, uname, is_admin, [str(row.get("key") or "") for row in named]) for row in named: - row["canRename"] = bool(rights.get(str(row.get("key") or ""))) + facts = rights.get(str(row.get("key") or "")) or {} + row["exists"] = facts.get("exists") is True + row["canRename"] = facts.get("canRename") is True return named @@ -1716,8 +2043,13 @@ def _detail_databases(rt, is_admin, connector_key, uname=""): import odoo_relational choices = odoo_relational.grid_choices(rt) models = dict(getattr(odoo_relational, "ODOO_TABLE_MODELS", {}) or {}) + # This read never contacts Odoo. A 499-model exact pass measured 67.87 s after the + # catalogue was warm, so modal detail must never turn a missing cache into inline work. + census = odoo_relational.population_census(rt) except Exception: # noqa: BLE001 return [] + census_at = str(census.get("capturedAt") or "") + counts = census.get("counts") if isinstance(census.get("counts"), dict) else {} catalog = {} if is_admin: try: @@ -1742,11 +2074,16 @@ def _detail_databases(rt, is_admin, connector_key, uname=""): # uses, so it stays derived from `ODOO_TABLE_MODELS` whatever C2 says a row is called. # Conflating the two would let a spec edit silently change which switches move together. declared = spec.get(key) or {} + # Counts are model-level facts. Databases backed by the same model deliberately show the + # same sourceRows number; inventing a per-database domain here would make the number lie. + source_rows = counts.get(model) if census_at and model in counts else None out.append({"key": key, "label": str(declared.get("label") or choice.get("label") or key), "defaultLabel": str(declared.get("label") or choice.get("label") or key), "native": str(declared.get("native") or model), "enabled": bool(choice.get("enabled")), + "sourceRows": source_rows, + "populated": None if source_rows is None else source_rows > 0, "fields": [dict(field) for field in fields], "excluded": [dict(item) for item in excluded], "sharesFieldsWith": [other for other in shared.get(model, ()) @@ -1906,7 +2243,9 @@ def _detail_introspection(rt, is_admin, row): "creates cannot be listed field by field.") return {"introspectable": False, "reason": reason, "fieldsVisible": False, "canToggleFields": False, "canToggleTables": False, - "catalogueComplete": False, "capturedAt": "", "excludedBasis": ""} + "catalogueComplete": False, "capturedAt": "", "excludedBasis": "", + "censusAt": "", "censusComplete": False, "censusDurationMs": 0, + "censusModelsCounted": 0, "censusModelsWithRows": 0} if key == "amazon_sp": # ⭐⭐ W52 · R6. Introspectable under the AMENDED test (a real schema artifact, not a # `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): # unstamped pinned catalogue is a stale seed waiting to happen, and this screen is # the only place the staleness becomes visible. "capturedAt": captured, - "excludedBasis": _AMAZON_EXCLUDED_BASIS} + "excludedBasis": _AMAZON_EXCLUDED_BASIS, + "censusAt": "", "censusComplete": False, "censusDurationMs": 0, + "censusModelsCounted": 0, "censusModelsWithRows": 0} complete = False captured = "" + census = {} try: import core.user_tables as user_tables snapshot = user_tables.odoo_schema_snapshot(rt) import odoo_relational discovered = odoo_relational.readable_model_catalog(rt) + census = odoo_relational.population_census(rt) has_discovery = bool(discovered.get("capturedAt")) complete = (discovered.get("complete") is True if has_discovery else snapshot.get("complete") is True) @@ -1962,7 +2305,12 @@ def _detail_introspection(rt, is_admin, row): "canToggleTables": bool(is_admin), "catalogueComplete": complete, "capturedAt": captured, - "excludedBasis": _EXCLUDED_BASIS} + "excludedBasis": _EXCLUDED_BASIS, + "censusAt": str(census.get("capturedAt") or ""), + "censusComplete": census.get("complete") is True, + "censusDurationMs": int(census.get("durationMs") or 0), + "censusModelsCounted": int(census.get("modelsCounted") or 0), + "censusModelsWithRows": int(census.get("modelsWithRows") or 0)} def _detail_overview(row, databases, graph): diff --git a/api/routes_external.py b/api/routes_external.py new file mode 100644 index 0000000000000000000000000000000000000000..0c98858f01e4ec3fff3d938f1cc8db2434f8e158 --- /dev/null +++ b/api/routes_external.py @@ -0,0 +1,399 @@ +"""Per-user credential management and the bearer-authenticated external read door.""" + +import json +from urllib.parse import quote + +from fastapi import APIRouter, Body, Depends, Header, HTTPException, Request, Response + +import deps +from deps import Session, err, require_session +from core import external_access + + +router = APIRouter(prefix="/api/v1/external", tags=["external"]) + +_CREDENTIAL_PREFIX = "lpb1." + + +def _auth_refusal(): + raise err(401, external_access.AUTH_ERROR, "The credential is invalid or revoked.") + + +def require_external_session( + authorization: str | None = Header(default=None, alias="Authorization"), +) -> Session: + """Resolve a bearer credential without consulting or extending the browser session cookie.""" + if not isinstance(authorization, str): + _auth_refusal() + scheme, separator, token = authorization.strip().partition(" ") + if not separator or scheme.lower() != "bearer" or not token.strip(): + _auth_refusal() + try: + verified = external_access.verify(token.strip()) + except external_access.ExternalAuthError: + _auth_refusal() + return Session( + tenant=verified.tenant, + user=verified.user, + claims={ + "t": verified.tenant, + "u": verified.user["username"], + "external": True, + "external_key_id": verified.key_id, + }, + runtime=verified.runtime, + ) + + +def require_external_analyst( + session: Session = Depends(require_external_session), +) -> Session: + """Apply the same Analyst grant wall used by the in-app Assistant and Query.""" + session.require("analyst") + return session + + +def _can_use_analyst(session: Session) -> bool: + try: + session.require("analyst") + except HTTPException as exc: + if exc.status_code == 403: + return False + raise + return True + + +def _management_refusal(exc: external_access.ExternalAccessError): + if exc.code == "external_label_invalid": + raise err(400, exc.code, "Enter a label between 1 and 80 characters.") + if exc.code == "external_key_not_found": + raise err(404, exc.code, "That credential was not found.") + if exc.code in {"external_identity_invalid", "external_account_unavailable"}: + raise err(409, exc.code, "This account cannot create an external credential.") + raise err(503, "external_access_unavailable", "External access is unavailable right now.") + + +def _resolve_external_scope( + session: Session, + databases=None, + *, + include_schema: bool = False, + strict_schema: bool = False, +): + """Resolve the status and field contract used by every external scope description. + + `strict_schema` preserves the schema route's named refusals for unknown, forbidden and + temporarily unavailable sources. The portable document uses the non-strict form so one + unavailable source can still be reported with the reason supplied by source status. + """ + status = deps.assistant_source_status(session, databases=databases) + definitions = None + + def fallback_label(database: str) -> str: + nonlocal definitions + built_in = deps.module_cache_source(database) + if built_in: + return str(built_in.get("label") or database) + if definitions is None: + try: + candidate = session.runtime.get_projection("user_tables", drop=("rows",)) + except Exception: + candidate = {} + definitions = candidate if isinstance(candidate, dict) else {} + definition = definitions.get(database) + if isinstance(definition, dict): + return str(definition.get("label") or database) + return database + + resolved = [] + for database, raw in sorted(status.items()): + row = { + "database": database, + "permitted": bool(raw.get("permitted")), + "answerable": bool(raw.get("answerable")), + "visible": bool(raw.get("visible")), + "reason": raw.get("reason") or "", + } + if include_schema: + if row["answerable"] or strict_schema: + scoped = deps.assistant_read_scope( + session, database, fields=None, filters=None, + ) + row["schema"] = { + key: value for key, value in scoped.items() + if key not in {"records", "filters"} + } + row["label"] = str(scoped.get("label") or database) + row["fields"] = list(scoped.get("fields") or []) + else: + row["label"] = fallback_label(database) + row["fields"] = [] + resolved.append(row) + return resolved + + +def _markdown_inline(value) -> str: + text = str(value or "").replace(chr(0x2014), " - ").replace(chr(0x2013), "-") + return " ".join(text.replace("`", "'").split()) + + +def _portable_skill_document(session: Session, base_url: str) -> str: + scoped = [ + row for row in _resolve_external_scope(session, include_schema=True) + if row["permitted"] + ] + example = next((row for row in scoped if row["answerable"]), None) + if example is None and scoped: + example = scoped[0] + + surface_url = f"{base_url.rstrip('/')}/api/v1/external" + lines = [ + "---", + "name: loopable-external-data", + "description: Read this user's governed Loopable data through the external API.", + "---", + "", + "# Loopable external data", + "", + ("This surface is a read-only view of the Loopable data this user can already see. " + "It applies the same database, field, and row permissions as the Loopable app."), + "", + "## Authentication", + "", + "```http", + "Authorization: Bearer ", + "```", + "", + ("Mint the credential in Loopable Settings. It is shown once, and revoking it stops " + "the next request."), + "", + f"Base URL: `{surface_url}`", + "", + "## First call: list databases", + "", + "Endpoint: `GET /api/v1/external/databases`", + "", + "```sh", + "curl --request GET \\", + " --header 'Authorization: Bearer ' \\", + f" '{surface_url}/databases'", + "```", + "", + "Call this first. It returns only databases this user may read or already sees in the app.", + "", + "## Read a database schema", + "", + "Endpoint: `GET /api/v1/external/databases/{database}/schema`", + "", + ] + + if example is not None: + database_path = quote(str(example["database"]), safe="") + fields = example.get("fields") or [] + field_key = next( + (str(field.get("key")) for field in fields + if isinstance(field, dict) and field.get("key")), + None, + ) + query_body = { + "fields": [field_key] if field_key else [], + "filters": None, + } + lines.extend([ + "```sh", + "curl --request GET \\", + " --header 'Authorization: Bearer ' \\", + f" '{surface_url}/databases/{database_path}/schema'", + "```", + "", + "## Query a database", + "", + "Endpoint: `POST /api/v1/external/databases/{database}/query`", + "", + "```sh", + "curl --request POST \\", + " --header 'Authorization: Bearer ' \\", + " --header 'Content-Type: application/json' \\", + f" --data '{json.dumps(query_body, separators=(',', ':'))}' \\", + f" '{surface_url}/databases/{database_path}/query'", + "```", + "", + ]) + if not example["answerable"]: + lines.extend([ + ("This exact schema and query path names a permitted source, but it is not " + "answerable right now. The reason appears in the scope below."), + "", + ]) + else: + lines.extend([ + "No schema call is available because this user's current scope has no databases.", + "", + "## Query a database", + "", + "Endpoint: `POST /api/v1/external/databases/{database}/query`", + "", + "No query call is available because this user's current scope has no databases.", + "", + ]) + + lines.extend(["## This user's current read scope", ""]) + if not scoped: + lines.extend(["No databases are currently permitted.", ""]) + for row in scoped: + database = _markdown_inline(row["database"]) + label = _markdown_inline(row.get("label") or row["database"]) + lines.append(f"### `{database}`: {label}") + lines.append("") + if row["answerable"]: + fields = [ + field for field in (row.get("fields") or []) + if isinstance(field, dict) and field.get("key") + ] + lines.append("Fields this user may read:") + lines.append("") + if fields: + for field in fields: + key = _markdown_inline(field.get("key")) + field_label = _markdown_inline(field.get("label") or field.get("key")) + lines.append(f"- `{key}`: {field_label}") + else: + lines.append("- No readable fields are currently exposed.") + else: + reason = _markdown_inline(row.get("reason") or "This source is not answerable right now.") + lines.extend([ + f"Not answerable right now: {reason}", + "", + "The readable field contract is unavailable until this source is answerable.", + ]) + lines.append("") + + lines.extend([ + "## Limits", + "", + ("This surface performs no writes. It returns no data the user cannot already see in " + "Loopable, and it provides no export beyond what the user could already export from " + "the app."), + "", + ]) + document = "\n".join(lines) + if _CREDENTIAL_PREFIX in document: + raise RuntimeError("portable skill document contained a credential value") + return document + + +@router.post("/keys", status_code=201) +def create_key(body=Body(default=None), session: Session = Depends(require_session)): + """Mint a credential for the signed-in human. Bearer auth is not accepted here.""" + session.require("analyst") + label = body.get("label") if isinstance(body, dict) else None + try: + key, token = external_access.mint(session.runtime, session.uname, session.tenant, label) + except external_access.ExternalAccessError as exc: + _management_refusal(exc) + return {"key": key, "secret": token} + + +@router.get("/keys") +def list_keys(session: Session = Depends(require_session)): + """List only the signed-in human's metadata. Stored hashes and secrets never leave core.""" + try: + keys = external_access.list_for_user(session.runtime, session.uname, session.tenant) + except external_access.ExternalAccessError as exc: + _management_refusal(exc) + return {"keys": keys, "can_mint": _can_use_analyst(session)} + + +@router.post("/keys/{key_id}/revoke") +def revoke_key(key_id: str, session: Session = Depends(require_session)): + """Tombstone one key owned by the signed-in human. Bearer auth is not accepted here.""" + try: + key = external_access.revoke(session.runtime, session.uname, session.tenant, key_id) + except external_access.ExternalAccessError as exc: + _management_refusal(exc) + return {"key": key} + + +@router.get("/skill.md") +def portable_skill(request: Request, session: Session = Depends(require_session)): + """Download the signed-in human's current governed external read instructions.""" + session.require("analyst") + document = _portable_skill_document(session, str(request.base_url)) + return Response( + content=document, + media_type="text/markdown", + headers={"Content-Disposition": 'attachment; filename="skill.md"'}, + ) + + +@router.get("/whoami") +def whoami(session: Session = Depends(require_external_analyst)): + """The one observable bearer route in this ticket; later tickets add governed data reads.""" + return { + "username": session.uname, + "name": session.user.get("name") or session.uname, + "tenant": session.tenant, + "key_id": session.claims["external_key_id"], + "read_only": True, + } + + +@router.get("/databases") +def list_databases(session: Session = Depends(require_external_analyst)): + """List only sources this user may read or already sees elsewhere in the product.""" + databases = [] + for row in _resolve_external_scope(session): + if not (row.get("permitted") or row.get("visible")): + continue + public = { + "database": row["database"], + "permitted": bool(row.get("permitted")), + "answerable": bool(row.get("answerable")), + } + if not public["answerable"]: + public["reason"] = row.get("reason") or "" + databases.append(public) + return {"databases": databases, "read_only": True} + + +@router.get("/databases/{database}/schema") +def database_schema(database: str, session: Session = Depends(require_external_analyst)): + """Return the field contract after resolving the ordinary strict Assistant read wall.""" + resolved = _resolve_external_scope( + session, databases=[database], include_schema=True, strict_schema=True, + ) + return resolved[0]["schema"] + + +@router.post("/databases/{database}/query") +def query_database( + database: str, + body: dict | None = Body(default=None), + session: Session = Depends(require_external_analyst), +): + """Read one detached Assistant snapshot; FastAPI rejects non-object request bodies.""" + payload = body or {} + return deps.assistant_read_scope( + session, + database, + fields=payload.get("fields"), + filters=payload.get("filters"), + ) + + +# C7 / R3: one import-time chokepoint makes the external bearer surface structurally read only. +# POST remains available for bounded query bodies and for the cookie-only credential lifecycle +# above. No bearer dependency appears on those lifecycle routes. +_READ_ONLY_METHODS = frozenset({"GET", "POST", "HEAD", "OPTIONS"}) + + +def _assert_read_only_router() -> None: + for route in router.routes: + methods = set(getattr(route, "methods", set()) or set()) + refused = methods - _READ_ONLY_METHODS + if refused: + joined = ", ".join(sorted(refused)) + raise RuntimeError(f"external route {route.path} advertises refused method {joined}") + + +_assert_read_only_router() diff --git a/api/routes_oauth.py b/api/routes_oauth.py index 8e49c41134aafde8a9738e53d63775c2d76fea88..84111558e1184cd5094de13f4ddaa0438e53cb6d 100644 --- a/api/routes_oauth.py +++ b/api/routes_oauth.py @@ -43,7 +43,7 @@ def _redirect_uri(request: Request, provider: str) -> str: the user actually browsed plants the session on the wrong hostname and they return logged out. Moving the app to a new hostname means moving this value AND re-registering the resulting URI in the provider console; one without the other fails closed. - Runbook: `.claude/wiki/research/loopable-domain-runbook.md`.""" + Runbook: `AutoWiki/research/loopable-domain-runbook.md`.""" base = (os.environ.get("AIOS_PUBLIC_BASE") or "").strip().rstrip("/") if not base: base = f"{request.url.scheme}://{request.url.netloc}" diff --git a/api/routes_slack.py b/api/routes_slack.py index 6f49fe88dd7fc8679153bd9ffacadef5999a890d..951c71c57bf95afd2f9345229e765324e58ad4da 100644 --- a/api/routes_slack.py +++ b/api/routes_slack.py @@ -18,7 +18,7 @@ live specimen of identity that LOOKS like a permission and is not. `core/perm_scope.py` is already strictly more expressive: per database, per row, per FIELD, per principal. So item 10 is OUR engine projected onto a CHANNEL principal — see `agent_principal` below, which is the whole projection and is nine lines. Study: -`.claude/wiki/research/opentag-adoption.md` (licence gate: MIT, PASSED). +`AutoWiki/research/opentag-adoption.md` (licence gate: MIT, PASSED). What OpenTag genuinely contributes is the WRITE-APPROVAL interceptor (`W33-T67`, `approval_card` below) and nothing else. Its TRANSPORT is AVOID wholesale — hosted CopilotKit Intelligence, a @@ -615,7 +615,7 @@ def _is_empty(value): False is precisely the kind of write somebody needs to approve, and a naive `if not value` drops both rows silently — the approver then reads a card that does not describe the write they are approving. The MIT licence gate for this borrowing is recorded in - `.claude/wiki/research/opentag-adoption.md`. + `AutoWiki/research/opentag-adoption.md`. """ return value is None or (isinstance(value, str) and value.strip() == "") diff --git a/platform/core/connector_directory.py b/platform/core/connector_directory.py index d67fad42b5ef1d7334d70b89f880d1df416a37c2..44d1091244c03c39c2074372fe99def3486d9e48 100644 --- a/platform/core/connector_directory.py +++ b/platform/core/connector_directory.py @@ -18,7 +18,7 @@ it, and there is nothing to find. Measured against the live Monid API on 2026-09 tags, categories, metrics, hints`, and none of those carries a sidebar name. So the 14 categories are reachable only from Monid's WEB UI SIDEBAR, which is what - `.claude/wiki/waves/wave49/proto/monid-catalogue.md` captured by hand. `MONID_PROVIDERS` is + `AutoWiki/waves/wave49/proto/monid-catalogue.md` captured by hand. `MONID_PROVIDERS` is regenerated by re-reading that file, not by calling an endpoint. ⚠ AND THE CATALOGUE IS A FLOOR, NOT A CENSUS. `discover` returns providers absent from the proto @@ -87,7 +87,7 @@ MONID_CATEGORY_ENDPOINTS = { #: ⭐⭐ THE AUTHORED CROSSWALK: (provider name, endpoint count, the categories it is filed under). #: #: REGENERATION, because there is no generator: re-read the `PROVIDERS` line of -#: `.claude/wiki/waves/wave49/proto/monid-catalogue.md`, which is `name count` pairs separated by +#: `AutoWiki/waves/wave49/proto/monid-catalogue.md`, which is `name count` pairs separated by #: the middle dot. The NAME and the COUNT come from there unchanged and `verify_catalog.py` proves #: it, pair by pair, so a typo here goes red rather than quiet. The CATEGORIES are the authored #: half: a judgement about which sidebar rows a provider sits under, made once, here. @@ -312,7 +312,7 @@ MONID_ACTION_STATE = "available" #: `("Telegram", 7, ...)`: a vendor listing, not a connector we have built or planned. Wave 53 #: adopted only its CREDENTIAL SHAPE on paper and built no runtime path, so the row keeps this #: word and Telegram is deliberately absent from `routes_connectors.PLANNED`. The build plan, -#: with the two keychain steps it needs first, is `.claude/wiki/research/ideation/telegram-bot.md`. +#: with the two keychain steps it needs first, is `AutoWiki/research/ideation/telegram-bot.md`. CATALOGUE_STATE = "catalogue" #: ⭐⭐ W49-T14 · RULINGS R21 + R24 — WHICH CONNECTORS HAVE A FIELD CATALOGUE, AUTHORED IN CODE. diff --git a/platform/core/connector_sync.py b/platform/core/connector_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..10d83bc092b0a55742dce3029535f71a56631a42 --- /dev/null +++ b/platform/core/connector_sync.py @@ -0,0 +1,169 @@ +"""Tenant-and-connection scoped connector sync lifecycle state. + +This data-layer module records what a provider runner did. It deliberately does not import or +call providers: the API layer owns runners while every connector shares this durable vocabulary. +""" +from __future__ import annotations + +import datetime as _dt + +import core.store as store + + +STATE_KEY = "connector_sync_state" +STATES = ("queued", "syncing", "materializing", "ready", "partial", "error") +_ERROR_LIMIT = 50 +_DEFAULT_CONNECTION = "default" +_PROVIDERS = {} + + +def _st(st): + return st if st is not None else store + + +def _key(value): + return str(value or "").strip() + + +def _slot(connection_id): + return _key(connection_id) or _DEFAULT_CONNECTION + + +def _target(rt, st): + return st if st is not None else rt + + +def _public(provider, connection_id, row): + if not isinstance(row, dict): + return None + answer = dict(row) + answer["provider"] = provider + answer["connectionId"] = connection_id + # RULE: retryability follows the state. Storing it would let the two answers drift. + answer["retryable"] = answer.get("state") in ("error", "partial") + return answer + + +def record(rt, provider, connection_id, state, *, detail="", errors=(), databases=(), st=None): + """Record one lifecycle transition and return its defensive public representation.""" + provider_key = _key(provider) + if not provider_key: + raise ValueError("provider is required") + if state not in STATES: + # RULE: unknown states are refused. A free-form status eventually stores a typo that the + # UI cannot render as one of C6's six observable states. + raise ValueError(f"unknown connector sync state: {state}") + connection_key = _slot(connection_id) + all_errors = [str(value) for value in (errors or ())] + visible_errors = all_errors[:_ERROR_LIMIT] + now = _dt.datetime.now(_dt.timezone.utc).isoformat() + written = {} + + def _apply(current): + document = dict(current or {}) + providers_doc = dict(document.get(provider_key) or {}) + previous = providers_doc.get(connection_key) + previous_state = previous.get("state") if isinstance(previous, dict) else None + row = { + "state": state, + # RULE: stamp every transition and name its predecessor. A resting state alone cannot + # tell the UI whether work advanced, retried, or regressed. + "at": now, + "from": previous_state, + "detail": str(detail or ""), + # RULE: partial and error stay distinct. Partial exposes databases usable now; + # error means no usable set was produced. + "errors": visible_errors, + # RULE: retain up to 50 errors and report the full count. A storage limit must be + # observable rather than silently turning additional failures into zero information. + "errorsTotal": len(all_errors), + # These are governed table keys, not copied provider rows. In Odoo, row_limit == 0 + # keeps 963,783 GL lines out of the editable user_tables document. + "databases": [str(value) for value in (databases or ()) if str(value)], + } + providers_doc[connection_key] = row + # RULE: key state by provider and connection. The measured legacy defect is that + # odoo_sync_status is one tenant document, so a second Odoo connection overwrites the + # first one's status. The default slot matches Odoo's existing catalog convention. + document[provider_key] = providers_doc + written.update(row) + return document + + _st(_target(rt, st)).update(STATE_KEY, _apply, flush="sync") + return _public(provider_key, connection_key, written) + + +def read(rt, provider, connection_id=None, st=None): + """Read one connection defensively; store failures mean no recorded state, never a 500.""" + try: + provider_key = _key(provider) + connection_key = _slot(connection_id) + document = _st(_target(rt, st)).get(STATE_KEY) or {} + providers_doc = document.get(provider_key) if isinstance(document, dict) else None + row = providers_doc.get(connection_key) if isinstance(providers_doc, dict) else None + return _public(provider_key, connection_key, row) + except Exception: # noqa: BLE001 - status reads cannot take down their caller + return None + + +def read_all(rt, st=None): + """Read every provider and connection defensively.""" + try: + document = _st(_target(rt, st)).get(STATE_KEY) or {} + answer = {} + for provider_key, connections in document.items(): + if not isinstance(connections, dict): + continue + public_connections = {} + for connection_key, row in connections.items(): + public = _public(str(provider_key), str(connection_key), row) + if public is not None: + public_connections[str(connection_key)] = public + if public_connections: + answer[str(provider_key)] = public_connections + return answer + except Exception: # noqa: BLE001 - status reads cannot take down their caller + return {} + + +def clear(rt, provider, connection_id, st=None): + """Remove only the named provider/connection state.""" + provider_key = _key(provider) + connection_key = _slot(connection_id) + + def _drop(current): + document = dict(current or {}) + connections = dict(document.get(provider_key) or {}) + connections.pop(connection_key, None) + if connections: + document[provider_key] = connections + else: + document.pop(provider_key, None) + return document + + _st(_target(rt, st)).update(STATE_KEY, _drop, flush="sync") + + +def register_provider(provider, *, label, retry_hint): + """Register provider metadata; runners remain in the API layer.""" + provider_key = _key(provider) + if not provider_key: + raise ValueError("provider is required") + _PROVIDERS[provider_key] = { + "key": provider_key, + "label": str(label or provider_key), + "retryHint": str(retry_hint or ""), + } + + +def providers(): + """Return a copy of registered provider metadata.""" + return {key: dict(value) for key, value in _PROVIDERS.items()} + + +register_provider("odoo", label="Odoo", retry_hint="Retry the Odoo database sync.") +register_provider( + "amazon_sp", + label="Amazon", + retry_hint="No sync runner is wired for this connector yet.", +) diff --git a/platform/core/external_access.py b/platform/core/external_access.py new file mode 100644 index 0000000000000000000000000000000000000000..cf2cbb6dcb6fa95c14255033e30ab72fe502b0b0 --- /dev/null +++ b/platform/core/external_access.py @@ -0,0 +1,328 @@ +"""Per-user credentials for the governed external read surface. + +The credential is authentication only. Verification reconstructs the same PUBLIC user record +the normal API session carries, so every later database read still goes through ``perm_scope`` +and the existing Assistant mirror. This module never reads product rows and never caches a +credential, user, bucket, or tenant runtime. +""" +import calendar +from dataclasses import dataclass +import hashlib +import hmac +import secrets +import time + +import core.users as users +from harness import runtime + + +BUCKET = "external_access" +ALGORITHM = "sha256-salt-v1" +AUTH_ERROR = "invalid_external_credential" +_DUMMY_SALT = bytes(32) +_DUMMY_HASH = hashlib.sha256(_DUMMY_SALT + b"invalid").hexdigest() +#: Seconds between two durable `last_used` stamps for ONE credential. +#: +#: ⛔⛔ THE STAMP IS THROTTLED, AND THIS IS NOT AN OPTIMISATION. `st.update(..., flush="sync")` is +#: a fresh strict read plus a BLOCKING UPLOAD, i.e. one durable commit per verified request. An +#: external AI reads in bursts and the store's budget is 256 commits an hour, so an unthrottled +#: stamp would spend a tenant's whole write budget on telemetry and put an upload inside the +#: latency of every read. It would also make a surface contract C7 calls READ ONLY write on every +#: single call, which is the claim this module exists to keep true. The pane renders `last_used` to +#: the minute, so a quarter of an hour of staleness costs the reader nothing. +#: ⚠ REVOCATION IS NOT THROTTLED AND MUST NEVER BE: `revoke` and `mint` stay `flush="sync"`, and +#: verification still reads the bucket FRESH on every request, which is what makes "revoking stops +#: the next request" true. +_STAMP_EVERY = 900.0 + + +class ExternalAccessError(RuntimeError): + """A stable core-layer refusal. HTTP status and copy belong to the API layer.""" + + def __init__(self, code: str): + super().__init__(code) + self.code = code + + +class ExternalAuthError(ExternalAccessError): + """A uniform authentication refusal that reveals no credential or tenant detail.""" + + +@dataclass(frozen=True) +class VerifiedCredential: + """The authenticated public principal plus the request-scoped tenant runtime.""" + + tenant: str + key_id: str + user: dict + runtime: object + + +def _now() -> str: + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + + +def _stamp_is_due(last_used, now: float) -> bool: + """Is this credential's `last_used` stale enough to be worth a durable write? + + An absent, unparseable or future stamp is DUE, so a corrupt value self-heals on the next + request rather than freezing the field forever. + """ + if not last_used: + return True + try: + seen = calendar.timegm(time.strptime(str(last_used), "%Y-%m-%dT%H:%M:%SZ")) + except (TypeError, ValueError): + return True + return not (0.0 <= now - seen < _STAMP_EVERY) + + +def _digest(salt: bytes, secret: str) -> str: + """Hash one external secret with SHA-256 and its per-record random salt. + + The secret has 256 bits of machine-generated randomness, not human-password entropy. A slow + password KDF therefore buys nothing against an offline attacker and would deliberately delay + every request on the read surface. + """ + return hashlib.sha256(salt + secret.encode("utf-8")).hexdigest() + + +def _book(st, *, fresh: bool = True) -> dict: + try: + value = st.get(BUCKET, fresh=fresh) + except Exception as exc: + raise ExternalAccessError("external_access_unavailable") from exc + if value is None: + return {} + if not isinstance(value, dict): + raise ExternalAccessError("external_access_unavailable") + return value + + +def _normalise_owner(username: str, tenant: str) -> tuple[str, str]: + owner = str(username or "").strip().lower() + tenant_key = str(tenant or "").strip().lower() + if not owner or not tenant_key: + raise ExternalAccessError("external_identity_invalid") + return owner, tenant_key + + +def _assert_bound_runtime(st, tenant: str) -> None: + if str(getattr(st, "key", "") or "").strip().lower() != tenant: + raise ExternalAccessError("external_identity_invalid") + + +def _active_public_user(username: str, tenant: str) -> dict: + try: + registry = users.registry() or {} + except Exception as exc: + raise ExternalAccessError("external_access_unavailable") from exc + if not isinstance(registry, dict): + raise ExternalAccessError("external_access_unavailable") + record = registry.get(username) + if not isinstance(record, dict) or not record.get("active", True): + raise ExternalAccessError("external_account_unavailable") + public = users._public(username, record) + if public.get("tenant") != tenant: + raise ExternalAccessError("external_account_unavailable") + return public + + +def _metadata(record: dict) -> dict: + """Return list-safe metadata. Salt, digest, algorithm and owner never cross this seam.""" + return { + "id": record.get("id"), + "label": record.get("label"), + "created": record.get("created"), + "last_used": record.get("last_used"), + "revoked_at": record.get("revoked_at"), + } + + +def mint(st, username: str, tenant: str, label: str) -> tuple[dict, str]: + """Create one credential and return ``(metadata, token)``; the token is never persisted.""" + owner, tenant_key = _normalise_owner(username, tenant) + _assert_bound_runtime(st, tenant_key) + _active_public_user(owner, tenant_key) + clean_label = str(label or "").strip() + if not clean_label or len(clean_label) > 80: + raise ExternalAccessError("external_label_invalid") + + secret = secrets.token_urlsafe(32) + salt = secrets.token_bytes(32) + created = _now() + minted: dict = {} + + def _set(value): + if value is None: + book = {} + elif isinstance(value, dict): + book = dict(value) + else: + raise ExternalAccessError("external_access_unavailable") + key_id = secrets.token_urlsafe(18) + while key_id in book: + key_id = secrets.token_urlsafe(18) + record = { + "id": key_id, + "username": owner, + "tenant": tenant_key, + "label": clean_label, + "salt": salt.hex(), + "hash": _digest(salt, secret), + "algo": ALGORITHM, + "created": created, + "last_used": None, + "revoked_at": None, + } + book[key_id] = record + minted["record"] = record + return book + + try: + st.update(BUCKET, _set, flush="sync") + except ExternalAccessError: + raise + except Exception as exc: + raise ExternalAccessError("external_access_unavailable") from exc + record = minted.get("record") + if not isinstance(record, dict): + raise ExternalAccessError("external_access_unavailable") + token = f"lpb1.{tenant_key}.{record['id']}.{secret}" + return _metadata(record), token + + +def list_for_user(st, username: str, tenant: str) -> list[dict]: + """List only this user's active credential metadata, newest first.""" + owner, tenant_key = _normalise_owner(username, tenant) + _assert_bound_runtime(st, tenant_key) + records = [ + _metadata(record) + for record in _book(st).values() + if isinstance(record, dict) + and record.get("username") == owner + and record.get("tenant") == tenant_key + and not record.get("revoked_at") + ] + return sorted(records, key=lambda row: str(row.get("created") or ""), reverse=True) + + +def revoke(st, username: str, tenant: str, key_id: str) -> dict: + """Tombstone one credential owned by this user; foreign and absent IDs are identical.""" + owner, tenant_key = _normalise_owner(username, tenant) + _assert_bound_runtime(st, tenant_key) + target = str(key_id or "").strip() + revoked: dict = {} + + def _set(value): + if not isinstance(value, dict): + raise ExternalAccessError("external_key_not_found") + book = dict(value) + current = book.get(target) + if (not isinstance(current, dict) + or current.get("username") != owner + or current.get("tenant") != tenant_key): + raise ExternalAccessError("external_key_not_found") + record = dict(current) + if not record.get("revoked_at"): + record["revoked_at"] = _now() + book[target] = record + revoked["record"] = record + return book + + try: + st.update(BUCKET, _set, flush="sync") + except ExternalAccessError: + raise + except Exception as exc: + raise ExternalAccessError("external_access_unavailable") from exc + record = revoked.get("record") + if not isinstance(record, dict): + raise ExternalAccessError("external_access_unavailable") + return _metadata(record) + + +def _parse_token(token: str) -> tuple[str, str, str]: + parts = str(token or "").strip().split(".") + if (len(parts) != 4 or parts[0] != "lpb1" or not all(parts[1:]) + or len(parts[1]) > 128 or len(parts[2]) > 128 or len(parts[3]) > 256): + raise ExternalAuthError(AUTH_ERROR) + return parts[1].lower(), parts[2], parts[3] + + +def _comparison_material(record) -> tuple[bool, bytes, str]: + usable = isinstance(record, dict) and record.get("algo") == ALGORITHM + if usable: + try: + salt = bytes.fromhex(str(record.get("salt") or "")) + expected = str(record.get("hash") or "") + if len(salt) != 32 or len(expected) != 64: + raise ValueError("bad credential digest") + int(expected, 16) + return True, salt, expected + except (TypeError, ValueError): + pass + return False, _DUMMY_SALT, _DUMMY_HASH + + +def verify(token: str) -> VerifiedCredential: + """Verify a bearer token from fresh state and resolve its ordinary public-user principal.""" + try: + tenant_key, key_id, secret = _parse_token(token) + try: + st = runtime.get_runtime(tenant_key) + except KeyError as exc: + raise ExternalAuthError(AUTH_ERROR) from exc + + book = _book(st) + record = book.get(key_id) + material_ok, salt, expected = _comparison_material(record) + matched = hmac.compare_digest(_digest(salt, secret), expected) + record_ok = ( + material_ok + and isinstance(record, dict) + and record.get("id") == key_id + and record.get("tenant") == tenant_key + and bool(record.get("username")) + and not record.get("revoked_at") + ) + if not record_ok or not matched: + raise ExternalAuthError(AUTH_ERROR) + + owner = str(record["username"]).strip().lower() + try: + public = _active_public_user(owner, tenant_key) + except ExternalAccessError as exc: + raise ExternalAuthError(AUTH_ERROR) from exc + + if not _stamp_is_due(record.get("last_used"), time.time()): + return VerifiedCredential(tenant=tenant_key, key_id=key_id, user=public, runtime=st) + + used_at = _now() + + def _stamp(value): + if not isinstance(value, dict): + raise ExternalAuthError(AUTH_ERROR) + current = value.get(key_id) + if (not isinstance(current, dict) or current.get("revoked_at") + or current.get("username") != owner + or current.get("tenant") != tenant_key + or current.get("hash") != record.get("hash")): + raise ExternalAuthError(AUTH_ERROR) + book_now = dict(value) + stamped = dict(current) + stamped["last_used"] = used_at + book_now[key_id] = stamped + return book_now + + try: + st.update(BUCKET, _stamp, flush="sync") + except ExternalAuthError: + raise + except Exception as exc: + raise ExternalAuthError(AUTH_ERROR) from exc + return VerifiedCredential(tenant=tenant_key, key_id=key_id, user=public, runtime=st) + except ExternalAuthError: + raise + except Exception as exc: + raise ExternalAuthError(AUTH_ERROR) from exc diff --git a/platform/core/monid.py b/platform/core/monid.py index a20331bd6214ef82d108d89003473906d6a27c32..657260a568f7eabf28862cde28c70cfc29cdc198 100644 --- a/platform/core/monid.py +++ b/platform/core/monid.py @@ -25,7 +25,7 @@ transient fault: retrying it spends nothing and tells the operator nothing, so i ⚠ THE ENDPOINT IS RECORDED, NOT REDISCOVERED. `discover("amazon reviews")` chose `apify /axesso_data/amazon-reviews-scraper` on 2026-09-02 and the losing candidates are written -down in `.claude/wiki/waves/wave49/proto/monid-research.md`. Re-running discover at request time +down in `AutoWiki/waves/wave49/proto/monid-research.md`. Re-running discover at request time would let a ranking change silently move which vendor we pay; the constants below are the decision, and `discover` remains available for the next slice. diff --git a/platform/core/sheets.py b/platform/core/sheets.py index 567a6c11b62280f3736e948139753d1e6ab8f42b..b1e787bde11c2116b0219657da488f65b1c558d6 100644 --- a/platform/core/sheets.py +++ b/platform/core/sheets.py @@ -47,6 +47,12 @@ read-modify-write under its lock. There is no file writer here and there must ne recomputes them. A cell goes stale by being marked stale, not by being read. """ +#: ⛔ C5 POINTER ONLY: a bound cell's PERIOD is not validated in this workbook record; +#: `modules/sheet.py::clean_period` and `period_window` own it. They accept +#: `{unit, start, locked, ref?}` and the wave-49 `{window: }` spelling; the latter is resolved +#: by `harness/windows.py::normalize`, which accepts exactly `WINDOW_KINDS`. C5 named this file as +#: the acceptance point, but the vocabulary deliberately does not live here. + from __future__ import annotations import copy diff --git a/platform/core/user_tables.py b/platform/core/user_tables.py index 32c5ce2d3c228c1deb1cb046e13a5c0d1754d3d5..e574b223cfd0e2d5993fe19a1eea3e95265d0b16 100644 --- a/platform/core/user_tables.py +++ b/platform/core/user_tables.py @@ -4552,15 +4552,27 @@ def enabled_odoo_schema_fields(st=None, model=None): return rows -def record_odoo_sync_status(*, phase, errors=(), st=None): +def record_odoo_sync_status(*, phase, errors=(), st=None, connection_id=None): """Lifecycle writer seam for the out-of-fence sync runner.""" clean_phase = str(phase or 'unknown').strip().lower() if clean_phase not in {'syncing', 'ok', 'error', 'unknown'}: clean_phase = 'unknown' + all_errors = tuple(errors or ()) row = {'phase': clean_phase, 'lastRun': _utc_now().isoformat(), - 'errors': [str(error)[:500] for error in errors][:50]} + 'errors': [str(error)[:500] for error in all_errors][:50]} _st(st).update(ODOO_SYNC_STATUS_KEY, lambda _current: row, flush='sync') + # The measured legacy vocabulary is syncing/ok/error against C6's six states, and its one + # tenant document cannot distinguish two Odoo connections. Keep that document byte-for-byte + # while forwarding to the provider/connection shape. This remains best-effort because a + # status forward must never take down the boot-time resync loop that produced the actual data. + try: + from core import connector_sync + mapped = {'syncing': 'syncing', 'ok': 'ready', 'error': 'error'}[clean_phase] + connector_sync.record(_st(st), provider='odoo', connection_id=connection_id, + state=mapped, errors=all_errors) + except Exception: # noqa: BLE001 - additive status telemetry cannot fail a sync + pass return row diff --git a/platform/harness/amazon_client.py b/platform/harness/amazon_client.py index 1727e9c68c76b29295fa4a7dd1a1d300c45bec5b..12bd512f3321132368cd1b113f4bfe467ffb6b19 100644 --- a/platform/harness/amazon_client.py +++ b/platform/harness/amazon_client.py @@ -42,7 +42,7 @@ records, and its second half is what applies: a limit that genuinely cannot be r REPORTED with cause and a recommended fix. `REPORT_TYPES` below is that fix, written down. · https://developer-docs.amazon.com/sp-api/docs/usage-plans-and-rate-limits -Ideation record, with every owner ruling: `.claude/wiki/research/ideation/amazon-connector.md` +Ideation record, with every owner ruling: `AutoWiki/research/ideation/amazon-connector.md` """ from __future__ import annotations diff --git a/platform/harness/datastore.py b/platform/harness/datastore.py index 2297e0ea815393303530097e1245556ef37fac2d..62481152e53834c00a6a63ba3f92fe2229882fd6 100644 --- a/platform/harness/datastore.py +++ b/platform/harness/datastore.py @@ -3,7 +3,7 @@ Incremental Odoo → DuckDB mirror: the local analytical store that saved views/dashboards (OM-3) and the AI Analyst's tools (OM-4) query at warehouse speed, instead of hammering live XML-RPC per question. -Plan: .claude/wiki/research/omni-adoption.md Part IV (OM-1) + [[odoo-open-source]] BUILD-NOW #1. +Plan: AutoWiki/research/omni-adoption.md Part IV (OM-1) + [[odoo-open-source]] BUILD-NOW #1. Design rules: - The store is a RAW mirror (unscoped). Business scope (wholesale teams, GIFTWARE exclusion, @@ -195,7 +195,7 @@ ENTITIES = { # ⭐⭐ WAVE 33 (W33-T48, owner item 13) — THE CONTACT/IDENTITY HALF, MEASURED BEFORE IT WAS # ADDED. The owner: *"I could have sworn we have more relevant Fields under 'Odoo vendors' # etc."* He was right, and the census - # (`.claude/wiki/waves/wave33/odoo-field-census.md`, live read-only, 2026-08-14) says by how + # (`AutoWiki/waves/wave33/odoo-field-census.md`, live read-only, 2026-08-14) says by how # much: `res.partner` declares 198 fields, **77 are populated on all 3,621 customers and 76 # on all 658 vendors**, and this mirror carried THIRTEEN. Every one of the six added here # was measured non-empty on the live population first — none is added on the strength of diff --git a/platform/harness/semantic.py b/platform/harness/semantic.py index c72c3d203b3a92de7c5d1b6391ef32c8a52a3f70..1de3e2bcfb725c3525cef7d5a6beb8b84031063e 100644 --- a/platform/harness/semantic.py +++ b/platform/harness/semantic.py @@ -8,7 +8,7 @@ metric carries its definition, ai_context, and an independent validate contract. Consumers (the point of the seam): the app's pages, the metric dictionary (OM-0c), the saved- dashboard viewer (OM-3; the Explore page was retired 2026-07-23), the AI Analyst's tools (OM-4: list_topics / describe_topic / run_semantic_query), and the MCP server (OM-6). Plan: -.claude/wiki/research/omni-adoption.md (Part IV + the productization addendum). +AutoWiki/research/omni-adoption.md (Part IV + the productization addendum). Design constraints honored (from /odoo-api): - read_group dot-path GROUPBY fails → scalar aggregates here use sum_field/distinct_count; diff --git a/platform/harness/transforms.py b/platform/harness/transforms.py index a3a133b8e3c75a2590596a38fa87acac79855bb1..3cdde6cba0603931386255677153257c3764006b 100644 --- a/platform/harness/transforms.py +++ b/platform/harness/transforms.py @@ -8,7 +8,7 @@ a saved view replays query -> transforms at render time (harness/views.run_view) This is the AIOS Analyst's TABLE-CALCULATION + ANALYTICS library — the open-source Tableau-class capability set (Tableau table calcs + Analytics pane, Power BI DAX quick measures, pandas/polars window ops, scipy/statsmodels stats) mapped onto ONE governed dispatcher. Grounding brief: -.claude/wiki/research/analytics-tools.md. Design laws (2026-07-18): +AutoWiki/research/analytics-tools.md. Design laws (2026-07-18): 1. ONE tool, many ops. Every capability is a pure function rows->rows (or rows->summary) in the OPS registry, dispatched through tools.transform_result — so the small model's prompt carries diff --git a/platform/model/skills/analytics.skill.yml b/platform/model/skills/analytics.skill.yml index c481cffad883374ea062182e9cd1a1eba91903ce..a09e58dd11449ddcfc62f8e1d15126756a713c28 100644 --- a/platform/model/skills/analytics.skill.yml +++ b/platform/model/skills/analytics.skill.yml @@ -1,6 +1,6 @@ # In-product SKILL: the ANALYTICS TRANSFORM LIBRARY (v1, 2026-07-18) — the Tableau-class # table-calc + analytics capability set, mapped onto the ONE governed transform_result tool. -# Grounding: .claude/wiki/research/analytics-tools.md. Every op here EXISTS in harness/transforms.py +# Grounding: AutoWiki/research/analytics-tools.md. Every op here EXISTS in harness/transforms.py # (OPS) and is unit-proven in _demo_analytics.py — recipes and code version together. # # HOW IT WORKS: run_semantic_query -> transform_result([{op, ...}, ...]) -> make_chart|make_table. diff --git a/platform/model/topics/sales_lines.yml b/platform/model/topics/sales_lines.yml index cc2bb51cce26a0a86ab55a2b325746ad89769266..bb5143460f2e3843ec8e17fb180ae9d3b8e0a70c 100644 --- a/platform/model/topics/sales_lines.yml +++ b/platform/model/topics/sales_lines.yml @@ -1,5 +1,5 @@ # Topic: sales_lines — the wholesale order-line dataset (OM-0, the first topic of the semantic -# layer; see .claude/wiki/research/omni-adoption.md). A topic = the curated, scoped dataset that +# layer; see AutoWiki/research/omni-adoption.md). A topic = the curated, scoped dataset that # metrics, saved views and the AI Analyst all resolve against — ONE definition of what the # data MEANS, consumed by every surface. key: sales_lines diff --git a/platform/modules/map.py b/platform/modules/map.py index e627e16180d3bda185a6c3b0dbe38bd7c7e59049..b5079e64b81edf48401bbb85ec5ab41e968b99a0 100644 --- a/platform/modules/map.py +++ b/platform/modules/map.py @@ -7,6 +7,9 @@ Coordinates resolve in this order, per customer: free US Census batch geocoder (these customers are almost all US/NY-metro florists). Customers with no usable address (or a geocode that fails) fall to a list under the map. +This pipeline serves Odoo `res.partner` rows only, and its US Census lookup is US only. The general +on-demand geocoder for every other database is `aios-web/api/routes_geo.py`. + Odoo stays STRICTLY read-only — geocodes are cached in the platform's own store, never written back to Odoo. The map's purpose is select-and-export (e.g. to assign agents): box/lasso-select on the map builds an Excel list. Assigning agents happens in Odoo / via that export, never as an app write. diff --git a/platform/modules/reprice.py b/platform/modules/reprice.py index 55925be809309769276b68d6ef0e2f6cd011aa55..1244396a31c6a4e01ec8093b259ce81ba23151c5 100644 --- a/platform/modules/reprice.py +++ b/platform/modules/reprice.py @@ -1,5 +1,5 @@ """Reprice lifecycle — the price-side discipline the pricing brief found missing -(.claude/wiki/research/pricing.md): rule hygiene BEFORE the reprice, realization tracking +(AutoWiki/research/pricing.md): rule hygiene BEFORE the reprice, realization tracking AFTER it, and the between-waves views (pocket waterfall, peer price corridor). Everything reads sale.order.line + product.pricelist.item + product masters, read-only. diff --git a/web/src/connectors/ConnectorModal.tsx b/web/src/connectors/ConnectorModal.tsx index 79316f5f733391f56a2b5aa11442b8007dee8785..e4bd2f32f1e22070b366855a3962562485fefbc2 100644 --- a/web/src/connectors/ConnectorModal.tsx +++ b/web/src/connectors/ConnectorModal.tsx @@ -44,11 +44,13 @@ // later renders in the neutral tone instead of dropping the panel. // --------------------------------------------------------------------------- -import { useCallback, useEffect, useRef, useState } from "react"; +import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react"; import { API_V1, CREDENTIALS } from "../apiContract"; import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface"; +import { ConfirmDialog } from "../ui/ConfirmDialog"; import { brandForConnector } from "./brandMarks"; import DatabasesTab from "./DatabasesTab"; +import type { DatabaseReveal, DatabasesTabHandle } from "./DatabasesTab"; import KeychainTab from "./KeychainTab"; import MonidRunDialog from "./MonidRunDialog"; import { SyncCadenceTab } from "./OdooConfig"; @@ -201,7 +203,13 @@ export interface ConnectorDatabase { /** May THIS reader rename it? The server's own `may_open` answer, per row, because a control * the write door would refuse is a button that always fails. */ canRename: boolean; + /** Does the governed database exist yet? This is separate from the reader's permission. */ + exists: boolean; enabled: boolean; + /** Exact rows in the Odoo source model, or null until that model was counted successfully. */ + sourceRows: number | null; + /** Tri-state on purpose: a model nobody counted is unknown, never empty. */ + populated: boolean | null; fields: ConnectorDatabaseField[]; excluded: ConnectorDatabaseExclusion[]; /** @@ -232,6 +240,11 @@ export interface ConnectorIntrospection { canToggleTables: boolean; catalogueComplete: boolean; capturedAt: string; + censusAt: string; + censusComplete: boolean; + censusDurationMs: number; + censusModelsCounted: number; + censusModelsWithRows: number; /** What an EMPTY `excluded` list actually means, composed where the diff is computed. */ excludedBasis: string; } @@ -369,7 +382,13 @@ function parseDatabases(raw: unknown): ConnectorDatabase[] { defaultLabel, override: str(row.override).trim(), canRename: row.canRename === true, + exists: row.exists === true, enabled: row.enabled === true, + sourceRows: + typeof row.sourceRows === "number" && Number.isFinite(row.sourceRows) && row.sourceRows >= 0 + ? Math.trunc(row.sourceRows) + : null, + populated: row.populated === true ? true : row.populated === false ? false : null, fields, excluded, sharesFieldsWith: parseStrings(row.sharesFieldsWith), @@ -395,6 +414,21 @@ function parseIntrospection(raw: unknown): ConnectorIntrospection { canToggleTables: source.canToggleTables === true, catalogueComplete: source.catalogueComplete === true, capturedAt: str(source.capturedAt).trim(), + censusAt: str(source.censusAt).trim(), + censusComplete: source.censusComplete === true, + censusDurationMs: + typeof source.censusDurationMs === "number" && Number.isFinite(source.censusDurationMs) + ? Math.max(0, Math.trunc(source.censusDurationMs)) + : 0, + censusModelsCounted: + typeof source.censusModelsCounted === "number" && Number.isFinite(source.censusModelsCounted) + ? Math.max(0, Math.trunc(source.censusModelsCounted)) + : 0, + censusModelsWithRows: + typeof source.censusModelsWithRows === "number" && + Number.isFinite(source.censusModelsWithRows) + ? Math.max(0, Math.trunc(source.censusModelsWithRows)) + : 0, excludedBasis: str(source.excludedBasis).trim(), }; } @@ -578,7 +612,15 @@ export function ConnectorOverviewPanel({ ); } -/** Amazon's provider-specific administrator controls, separate from Odoo's model catalogue. */ +interface ProviderPendingBridge { + enabled: (database: ConnectorDatabase) => boolean; + stage: (database: ConnectorDatabase, next: boolean) => Promise; + busy: boolean; +} + +const ProviderPendingContext = createContext(null); + +/** Amazon's provider-specific administrator controls, committed by the modal's shared Save. */ export function ProviderEnablementPanel({ detail, onChanged, @@ -587,46 +629,20 @@ export function ProviderEnablementPanel({ onChanged: () => void; }) { const capability = detail.enablement; + const pending = useContext(ProviderPendingContext); const [busyKey, setBusyKey] = useState(""); const [message, setMessage] = useState(""); if (!capability?.canManage || !capability.updatePath) return null; const setEnabled = async (database: ConnectorDatabase, enabled: boolean) => { - const path = capability.updatePath.replace( - "{databaseKey}", - encodeURIComponent(database.key) - ); - if (path === capability.updatePath) { - setMessage("This provider did not return a usable enablement path."); - return; - } + if (!pending || pending.busy) return; setBusyKey(database.key); setMessage(""); - let saved = false; - try { - const res = await fetch(`${API_V1}${path}`, { - method: "PATCH", - credentials: CREDENTIALS, - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ enabled }), - }); - const body = (await res.json().catch(() => null)) as - | { error?: { message?: string } } - | null; - if (!res.ok) { - setMessage(body?.error?.message || `The server answered ${res.status}.`); - return; - } - saved = true; - onChanged(); - } catch { - setMessage("Cannot reach the server."); - } finally { - // A successful write immediately asks the modal to re-read and leaves the old switches - // disabled until that load guard replaces them. An error keeps the current detail and must - // release the control for a retry. - if (!saved) setBusyKey(""); - } + await pending.stage(database, enabled); + setBusyKey(""); + // Kept in the public prop contract for the provider panel's existing callers. The shared + // Save owns the one detail re-read now, so staging deliberately does not call it. + void onChanged; }; return ( @@ -636,30 +652,33 @@ export function ProviderEnablementPanel({

Choose which Amazon databases are enabled. Switching one off keeps its stored rows.

    - {detail.databases.map((database) => ( + {detail.databases.map((database) => { + const enabled = pending?.enabled(database) ?? database.enabled; + return (
  • {database.label} - {database.enabled ? "On" : "Off"} + {enabled ? "On" : "Off"}
  • - ))} + ); + })}
{message} @@ -697,6 +716,8 @@ type Load = | { phase: "ready"; detail: ConnectorDetail } | { phase: "error"; message: string }; +type PendingLeave = { kind: "close" } | { kind: "tab"; tab: ConnectorTab } | null; + /** * THE MODAL. Centered, portalled to , focus-trapped, dismissed by Escape or a click * outside, and it hands focus back to the control that opened it. @@ -728,6 +749,11 @@ export default function ConnectorModal({ const panelRef = useRef(null); const [tab, setTab] = useState(initialTab); const [load, setLoad] = useState({ phase: "loading" }); + const databasesRef = useRef(null); + const [databasePendingCount, setDatabasePendingCount] = useState(0); + const [databaseTabBusy, setDatabaseTabBusy] = useState(false); + const [databaseSaving, setDatabaseSaving] = useState(false); + const [pendingLeave, setPendingLeave] = useState(null); /** * ⭐ W49-T13 — THE RE-READ, AND IT IS NOT OPTIONAL POLISH. The Keychain tab WRITES: it stores, * tests, deletes and disconnects. Keying the fetch on `connectorKey` alone leaves a deleted key @@ -735,7 +761,11 @@ export default function ConnectorModal({ * so the effect below keys on this counter as well and every write bumps it. */ const [reads, setReads] = useState(0); - const reread = useCallback(() => setReads((n) => n + 1), []); + const [databaseReveal, setDatabaseReveal] = useState(null); + const reread = useCallback((reveal?: DatabaseReveal) => { + if (reveal) setDatabaseReveal(reveal); + setReads((n) => n + 1); + }, []); /** * ⭐⭐ W49-T19 · R31 — THE AMAZON REVIEWS PULL, OPENED FROM THE OVERVIEW TAB. * 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({ const [pullSurface, setPullSurface] = useState(null); const canPull = isAmazonConnector(row.key); + const unsavedMessage = databasePendingCount === 1 + ? "You have 1 unsaved change to this connection." + : `You have ${databasePendingCount} unsaved changes to this connection.`; + + const requestClose = useCallback(() => { + if (databaseSaving || databaseTabBusy) return; + if (databasePendingCount) { + setPendingLeave({ kind: "close" }); + return; + } + onClose(); + }, [databasePendingCount, databaseSaving, databaseTabBusy, onClose]); + + const requestTab = useCallback((next: ConnectorTab) => { + if (databaseSaving || databaseTabBusy) return; + if (next === tab) return; + if (databasePendingCount) { + setPendingLeave({ kind: "tab", tab: next }); + return; + } + setTab(next); + }, [databasePendingCount, databaseSaving, databaseTabBusy, tab]); + + useEffect(() => { + if (!databasePendingCount) return; + const warn = (event: BeforeUnloadEvent) => { + event.preventDefault(); + event.returnValue = unsavedMessage; + }; + window.addEventListener("beforeunload", warn); + return () => window.removeEventListener("beforeunload", warn); + }, [databasePendingCount, unsavedMessage]); + useOverlayLayer({ panelRef, /** @@ -764,11 +827,12 @@ export default function ConnectorModal({ * this layer's dismissal closes THAT and stops. */ onDismiss: () => { + if (pendingLeave) return; if (pulling) { setPulling(false); return; } - onClose(); + requestClose(); }, dismissOnOutside: true, /** @@ -778,7 +842,7 @@ export default function ConnectorModal({ */ outsideElements: pullSurface ? [pullSurface] : [], initialFocus: "[data-overlay-autofocus]", - trapFocus: true, + trapFocus: pendingLeave === null, // The layer captures whatever was focused when it mounted and focuses it again on unmount, // which is the card's own open button. That is the done-when's "focus returns to the card". restoreFocus: true, @@ -787,7 +851,7 @@ export default function ConnectorModal({ const connectorKey = row.key; useEffect(() => { let dead = false; - setLoad({ phase: "loading" }); + setLoad((current) => reads > 0 && current.phase === "ready" ? current : { phase: "loading" }); void (async () => { try { const res = await fetch( @@ -849,8 +913,26 @@ export default function ConnectorModal({ if (tab === "databases") { return ( <> - - + + databasesRef.current?.tableEnabled(database) ?? database.enabled, + stage: (database, next) => + databasesRef.current?.stageTable(database, next) ?? Promise.resolve(), + busy: databaseSaving || databaseTabBusy, + }} + > + + + ); } @@ -892,7 +974,31 @@ export default function ConnectorModal({ onPullReviews={canPull ? () => setPulling(true) : undefined} /> ); - }, [canPull, load, onOpenDatabases, reread, row, tab]); + }, [canPull, databaseReveal, load, onOpenDatabases, reread, row, tab]); + + const saveDatabaseChanges = useCallback(async () => { + if (!databasePendingCount || !databasesRef.current) return; + setDatabaseSaving(true); + try { + await databasesRef.current.savePending(); + } finally { + setDatabaseSaving(false); + } + }, [databasePendingCount]); + + const discardDatabaseChanges = useCallback(() => { + databasesRef.current?.discardPending(); + setDatabasePendingCount(0); + }, []); + + const confirmLeave = useCallback(() => { + if (!pendingLeave) return; + const destination = pendingLeave; + discardDatabaseChanges(); + setPendingLeave(null); + if (destination.kind === "close") onClose(); + else setTab(destination.tab); + }, [discardDatabaseChanges, onClose, pendingLeave]); const status = load.phase === "ready" ? load.detail.overview.status : row.state; const title = load.phase === "ready" ? load.detail.overview.label || row.label : row.label; @@ -919,12 +1025,35 @@ export default function ConnectorModal({ {status ? ( {status} ) : null} + {tab === "databases" ? ( +
+ + +
+ ) : null} @@ -939,7 +1068,8 @@ export default function ConnectorModal({ className="conn-modal-tab" aria-selected={tab === entry.key} aria-controls="conn-tab-panel" - onClick={() => setTab(entry.key)} + disabled={databaseSaving || databaseTabBusy} + onClick={() => requestTab(entry.key)} > {entry.label} @@ -965,6 +1095,15 @@ export default function ConnectorModal({ surfaceRef={setPullSurface} /> ) : null} + {unsavedMessage}

} + confirmLabel="Discard changes" + tone="destructive" + onConfirm={confirmLeave} + onCancel={() => setPendingLeave(null)} + /> ); } diff --git a/web/src/connectors/DatabasesTab.tsx b/web/src/connectors/DatabasesTab.tsx index 0f706dc6a60be958771ba075e3da8eb490652656..f470c98fd98c42494677565048841b41c2423838 100644 --- a/web/src/connectors/DatabasesTab.tsx +++ b/web/src/connectors/DatabasesTab.tsx @@ -56,8 +56,8 @@ // `ConnectorOverviewPanel` and `KeychainTab` are exported panels. // --------------------------------------------------------------------------- -import { useCallback, useMemo, useState } from "react"; -import { API_V1, CREDENTIALS } from "../apiContract"; +import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useState } from "react"; +import { API_V1, CREDENTIALS, WORKSPACE_STALE_EVENT, signal } from "../apiContract"; import type { ConnectorDatabase, ConnectorDetail } from "./ConnectorModal"; import type { ConnectorRow } from "./ConnectorsPage"; @@ -109,6 +109,199 @@ async function write(path: string, method: "PUT" | "PATCH", body: unknown): Prom } } +/** + * Enabling sets the flag and THEN materialises, so a refusal can still have changed the server. + * + * ⛔ THE ANSWER IS A MESSAGE, NOT A FLAG READ OFF AN ERROR BODY. `deps.err` is the one non-2xx + * shape and it carries `error` alone. `reread` is therefore unconditional below: every outcome of + * this door can change what `/detail` answers, so the screen re-reads rather than trusting a + * sibling key that the error contract does not have. + */ +type EnableDatabaseAnswer = + | { + ok: true; + workspaceChanged: boolean; + populatedFieldsEnabled: number; + fieldCensusComplete: boolean; + autoEnableAlsoAffects: Array<{ key: string; label: string }>; + } + | { ok: false; message: string }; + +async function enableDatabase(tableKey: string): Promise { + try { + const res = await fetch( + `${API_V1}/connectors/odoo/databases/${encodeURIComponent(tableKey)}/enable`, + { method: "POST", credentials: CREDENTIALS } + ); + const payload = (await res.json().catch(() => null)) as + | { + workspaceChanged?: boolean; + populatedFieldsEnabled?: number; + fieldCensusComplete?: boolean; + autoEnableAlsoAffects?: unknown; + error?: { message?: string }; + } + | null; + if (res.ok) { + const shared = Array.isArray(payload?.autoEnableAlsoAffects) + ? payload.autoEnableAlsoAffects.flatMap((value) => { + if (!value || typeof value !== "object") return []; + const row = value as Record; + const key = typeof row.key === "string" ? row.key : ""; + const label = typeof row.label === "string" ? row.label : ""; + return key && label ? [{ key, label }] : []; + }) + : []; + const count = payload?.populatedFieldsEnabled; + return { + ok: true, + workspaceChanged: payload?.workspaceChanged === true, + populatedFieldsEnabled: + typeof count === "number" && Number.isFinite(count) ? Math.max(0, Math.trunc(count)) : 0, + fieldCensusComplete: payload?.fieldCensusComplete === true, + autoEnableAlsoAffects: shared, + }; + } + return { + ok: false, + message: payload?.error?.message || `The server answered ${res.status}.`, + }; + } catch { + return { ok: false, message: "Cannot reach the server." }; + } +} + +function sentenceList(values: string[]): string { + if (values.length < 2) return values[0] || ""; + if (values.length === 2) return `${values[0]} and ${values[1]}`; + return `${values.slice(0, -1).join(", ")}, and ${values[values.length - 1]}`; +} + +function autoEnableResult(answer: Extract): string { + const siblings = sentenceList(answer.autoEnableAlsoAffects.map((row) => row.label)); + const unknown = answer.fieldCensusComplete + ? "" + : ", while fields that could not be counted were left unchanged"; + if (!answer.populatedFieldsEnabled) { + return siblings + ? `No populated fields were found, so no field settings were changed here or in ${siblings}${unknown}.` + : `No populated fields were found, so no field settings were changed${unknown}.`; + } + const fields = answer.populatedFieldsEnabled === 1 + ? "One populated field was" + : `${answer.populatedFieldsEnabled.toLocaleString()} populated fields were`; + return siblings + ? `${fields} switched on here and in ${siblings} because the databases read the same Odoo source table${unknown}.` + : `${fields} switched on${unknown}.`; +} + +export interface DatabaseReveal { + key: string; + status: string; +} + +export interface DatabasesTabHandle { + savePending: () => Promise; + discardPending: () => void; + stageTable: (database: ConnectorDatabase, next: boolean) => Promise; + tableEnabled: (database: ConnectorDatabase) => boolean; +} + +interface PendingDatabaseChanges { + tables: Record; + fields: Record; + names: Record; +} + +const EMPTY_PENDING: PendingDatabaseChanges = { tables: {}, fields: {}, names: {} }; + +function pendingChangeCount(pending: PendingDatabaseChanges): number { + return Object.keys(pending.tables).length + + Object.keys(pending.fields).length + + Object.keys(pending.names).length; +} + +type PopulationCountAnswer = + | { + ok: true; + complete: boolean; + capturedAt: string; + durationMs: number; + modelsCounted: number; + modelsWithRows: number; + errors: string[]; + } + | { ok: false; message: string }; + +/** The explicit long-running door. Connector detail never starts this work. */ +async function countSourceRows(): Promise { + try { + const res = await fetch(`${API_V1}/connectors/odoo/census`, { + method: "POST", + credentials: CREDENTIALS, + }); + const payload = (await res.json().catch(() => null)) as Record | null; + if (!res.ok) { + const error = payload?.error as { message?: unknown } | undefined; + return { + ok: false, + message: typeof error?.message === "string" + ? error.message + : `The server answered ${res.status}.`, + }; + } + const number = (value: unknown) => + typeof value === "number" && Number.isFinite(value) + ? Math.max(0, Math.trunc(value)) + : 0; + const rawErrors = payload?.errors; + return { + ok: true, + complete: payload?.complete === true, + capturedAt: typeof payload?.capturedAt === "string" ? payload.capturedAt : "", + durationMs: number(payload?.durationMs), + modelsCounted: number(payload?.modelsCounted), + modelsWithRows: number(payload?.modelsWithRows), + errors: Array.isArray(rawErrors) + ? rawErrors.filter((value): value is string => typeof value === "string") + : [], + }; + } catch { + return { ok: false, message: "Cannot reach the server." }; + } +} + +function populationSummary(modelsCounted: number, modelsWithRows: number, durationMs: number) { + const seconds = Math.max(1, Math.round(durationMs / 1000)); + return `Counted ${modelsCounted.toLocaleString()} source tables in ${seconds.toLocaleString()} ` + + `seconds. ${modelsWithRows.toLocaleString()} hold data.`; +} + +/** One class per tri-state, so the CSS owns the emphasis and no style prop competes with it. */ +function populationClass(populated: boolean | null): string { + if (populated === true) return "conn-db-row is-populated"; + if (populated === false) return "conn-db-row is-empty"; + return "conn-db-row is-uncounted"; +} + +function populationTime(capturedAt: string) { + const millis = Date.parse(capturedAt); + return Number.isFinite(millis) ? new Date(millis).toLocaleString() : ""; +} + +function populationResult( + modelsCounted: number, + modelsWithRows: number, + durationMs: number, + capturedAt: string, + complete: boolean +) { + const summary = populationSummary(modelsCounted, modelsWithRows, durationMs); + const countedAt = populationTime(capturedAt); + return summary + (countedAt ? ` Counted on ${countedAt}.` : "") + + (complete ? "" : " The count was incomplete because some source tables could not be read."); +} + /** The on/off control, one shape for both rails (DESIGN.md section 4: one control shape). */ function Switch({ on, @@ -164,7 +357,7 @@ function DatabasePanel({ canToggleFields, catalogueComplete, excludedBasis, - busyField, + busy, onField, }: { database: ConnectorDatabase; @@ -174,7 +367,7 @@ function DatabasePanel({ canToggleFields: boolean; catalogueComplete: boolean; excludedBasis: string; - busyField: string; + busy: boolean; onField: (fieldKey: string, next: boolean) => void; }) { /** @@ -228,7 +421,7 @@ function DatabasePanel({ {canToggleFields ? ( {database.override ? "Change" : "Rename"} + ) : database.enabled && !database.exists ? ( + Available after the first sync. ) : null}
); @@ -348,7 +544,7 @@ function NameCell({ disabled={busy || !draft.trim()} onClick={() => onSave(draft)} > - Save + Done {database.override ? ( + + ) : null} {error ? (

{error} @@ -536,6 +919,12 @@ export default function DatabasesTab({ name is ours. Your name replaces it everywhere in this workspace, including the navigation rail, and clearing it brings the default back.

+ {showsPopulation ? ( +

+ Source rows is the source table's count. Databases sharing a source table show the same + number. Open Fields to see which databases share it. +

+ ) : null} @@ -543,15 +932,35 @@ export default function DatabasesTab({ + {showsPopulation ? : null} {orderedDatabases.map((database) => { + const effectiveEnabled = pending.tables[database.key] ?? database.enabled; + const effectiveOverride = pending.names[database.key] ?? database.override; + const renderedDatabase: ConnectorDatabase = { + ...database, + enabled: effectiveEnabled, + override: effectiveOverride, + label: effectiveOverride || database.defaultLabel, + fields: database.fields.map((field) => ({ + ...field, + enabled: pending.fields[field.key] ?? field.enabled, + })), + }; const isOpen = open[database.key] === true; const refusal = refusals[database.key] || ""; + const autoEnableStatus = autoEnableResults[database.key] || ""; + const siblingLabels = database.sharesFieldsWith + .map((key) => labels[key] || "") + .filter((label) => label.length > 0); return ( - + {/* ⛔ THE WORDS IN THE `Source rows` CELL CARRY THE MEANING; this class only + reinforces them. Colour and weight alone would put the whole signal where a + reader with low vision or a monochrome screen cannot reach it. */} + {/* ⛔ AN ABSENT NATIVE NAME IS SAID, NOT FILLED IN. Amazon names a table by the report it is filled from, and a table whose report type we cannot read has no vendor identifier to show. Printing the key there would put our own word under @@ -562,14 +971,14 @@ export default function DatabasesTab({ + {showsPopulation ? ( + + ) : null} {/* ⭐ R22 — ANY table can be switched off, not only the ones we mark optional. Every row gets the same control, and nothing here decides that one of them is too important to turn off: R23's ask is what protects a table in use. */} + {!effectiveEnabled && siblingLabels.length ? ( + + + + ) : null} + {autoEnableStatus ? ( + + + + ) : null} {refusal ? ( // ⚠ A REFUSAL IS NOT AN ERROR THE READER CAUSED (DESIGN.md section 4). It states // the cause and the subject, in the server's own sentence, and offers nothing to // dismiss because the table simply stayed on. - - @@ -650,4 +1087,6 @@ export default function DatabasesTab({
Default name Your name FieldsSource rowsEnabled
{database.defaultLabel} { setRenaming(database.key); - setDraft(database.override || database.defaultLabel); + setDraft(effectiveOverride || database.defaultLabel); setError(""); }} onCancel={() => { @@ -584,7 +993,7 @@ export default function DatabasesTab({ type="button" className="conn-db-more" aria-expanded={isOpen} - aria-label={`Show the fields in ${database.label}`} + aria-label={`Show the fields in ${renderedDatabase.label}`} onClick={() => setOpen((current) => ({ ...current, [database.key]: !isOpen })) } @@ -594,18 +1003,29 @@ export default function DatabasesTab({ + {database.sourceRows === 0 ? ( + Empty + ) : typeof database.sourceRows === "number" ? ( + database.sourceRows.toLocaleString() + ) : ( + Not counted yet + )} + {introspection.canToggleTables ? ( void flipTable(database, next)} /> @@ -614,12 +1034,31 @@ export default function DatabasesTab({ )}
+

+ {renderedDatabase.label} shares its Odoo source table with {sentenceList(siblingLabels)}, + so populated fields will be switched on there too. +

+
+

+ {autoEnableStatus} +

+
+

{refusal}

@@ -628,17 +1067,15 @@ export default function DatabasesTab({ ) : null} {isOpen ? (
+ labels[key] || "") - .filter((label) => label.length > 0)} + database={renderedDatabase} + siblingLabels={siblingLabels} fieldsVisible={introspection.fieldsVisible} canToggleFields={introspection.canToggleFields} catalogueComplete={introspection.catalogueComplete} excludedBasis={introspection.excludedBasis} - busyField={busy} + busy={Boolean(busy)} onField={(fieldKey, next) => void flipField(fieldKey, next)} />
); -} +}); + +export default DatabasesTab; diff --git a/web/src/connectors/RelationshipDiagram.tsx b/web/src/connectors/RelationshipDiagram.tsx index d83bd9471f6f83648b309255761c0693403523f9..08db7b4b063800ca31c2f2662c15cef83713f9d5 100644 --- a/web/src/connectors/RelationshipDiagram.tsx +++ b/web/src/connectors/RelationshipDiagram.tsx @@ -707,6 +707,72 @@ export default function RelationshipDiagram({ observer.observe(surface); return () => observer.disconnect(); }, []); + useEffect(() => { + const scrollElement = scrollRef.current; + if (!scrollElement) return; + + // W56-T30: columns widen the uncapped diagram, while an ancestor owns vertical overflow. + // Prevent the default only when this surface or an ancestor can move, so no gesture is trapped. + const handleWheel = (event: WheelEvent) => { + const surface = scrollRef.current; + if (!surface) return; + if (surface.scrollHeight - surface.clientHeight > 1) return; + if (event.deltaX !== 0 || event.deltaY === 0) return; + + const maxScrollLeft = surface.scrollWidth - surface.clientWidth; + let delta = event.deltaY; + if (event.deltaMode === 1) delta *= 16; + else if (event.deltaMode === 2) delta *= surface.clientWidth; + + const nextScrollLeft = Math.min(maxScrollLeft, Math.max(0, surface.scrollLeft + delta)); + if (maxScrollLeft > 1) { + const previous = surface.scrollLeft; + surface.scrollLeft = nextScrollLeft; + // W56-T30 read-back: arithmetic said 151px while Chrome clamped to 136px. + if (surface.scrollLeft !== previous) { + event.preventDefault(); + return; + } + } + + // W56-T30 rule: forward only wheel delta this surface cannot use. Measured: `.conn-rd-scroll` + // is `overflow: auto` but can never scroll vertically, so Chrome stops here instead of chaining; + // `overflow-y: visible` is not expressible beside `overflow-x: auto` because it computes to auto. + for ( + let ancestor = surface.parentElement; + ancestor && ancestor !== document.body && ancestor !== document.documentElement; + ancestor = ancestor.parentElement + ) { + const overflowY = getComputedStyle(ancestor).overflowY; + if (overflowY !== "auto" && overflowY !== "scroll") continue; + + const maxScrollTop = ancestor.scrollHeight - ancestor.clientHeight; + if (maxScrollTop <= 1) continue; + + let ancestorDelta = event.deltaY; + if (event.deltaMode === 1) ancestorDelta *= 16; + else if (event.deltaMode === 2) ancestorDelta *= ancestor.clientHeight; + + const canAbsorb = ancestorDelta > 0 + ? ancestor.scrollTop < maxScrollTop - 1 + : ancestor.scrollTop > 1; + if (!canAbsorb) continue; + + const nextScrollTop = Math.min(maxScrollTop, Math.max(0, ancestor.scrollTop + ancestorDelta)); + if (nextScrollTop === ancestor.scrollTop) continue; + + event.preventDefault(); + ancestor.scrollTop = nextScrollTop; + return; + } + }; + + scrollElement.addEventListener("wheel", handleWheel, { passive: false }); + return () => scrollElement.removeEventListener("wheel", handleWheel); + // Re-attached when the graph changes: the two early returns below mean the scroll surface + // does not exist while a graph is refused or empty, so a `[]` list would leave a graph that + // arrives later with no wheel handler at all. + }, [graph]); const layout = useMemo( () => relationshipLayout(graph, expandedKeys, availableWidth), [availableWidth, graph, expandedKeys] diff --git a/web/src/customer-grid/CustomerGrid.tsx b/web/src/customer-grid/CustomerGrid.tsx index ec7b2579ca1256252d4c3d15746c63dfa15d2aaf..b25a7ac61f5fd0819091b8a85a84e581eb8c716c 100644 --- a/web/src/customer-grid/CustomerGrid.tsx +++ b/web/src/customer-grid/CustomerGrid.tsx @@ -249,6 +249,7 @@ import type { FieldType, FilterNode, FilterRule, + FilterTree, PivotResponse, PivotRefusal, PivotWindow, @@ -1686,6 +1687,20 @@ interface CustomerGridProps { * serialised into a saved view — see `pinnedChip` below for why that one is load-bearing. */ related?: { table: string; record: number; via: RelatedVia; label: string }; + /** + * W56-T24 / R4 / C4 — the Sheet cell's View data surface. + * A MODIFIER ON `embedded`, never a replacement for it: every write guard `embedded` installs + * stays installed (no saved-view autosave, no cell edits, no host workspace, no view rail), and + * this flag relaxes exactly one withholding, the display-mode switcher. + */ + cellView?: boolean; + /** + * The Sheet cell's own rows-to-include, seeded into THIS surface's filter so the reader can see + * and edit the reason the rows are here. Only meaningful with `cellView`. + */ + cellFilter?: FilterTree; + /** Report a filter edit from the cell View data surface; its Sheet caller owns settling. */ + onCellFilterChange?: (tree: FilterTree) => void; /** * ⭐ W51-T06 clause 9 — a row click NAVIGATES the record view instead of opening this grid's * own drawer. @@ -1740,17 +1755,27 @@ interface LinkGridModalProps { editable?: boolean; single?: boolean; excludeRecordId?: number; + /** W56-T24: render the body as the Data module's own grid, with its display modes. */ + cellView?: boolean; + /** W56-T25: the Sheet cell's own filter, shown in the grid's standard filter control. */ + cellFilter?: FilterTree; + /** W56-T25: report a grid filter edit so the Sheet caller can settle and persist it. */ + onCellFilterChange?: (tree: FilterTree) => void; + /** W56-T24: chrome the caller owns, in the header, right of the title and left of Close. */ + headerActions?: ReactNode; + /** W56-T24: a statement under the rows. Only rendered on a non-editable modal. */ + footer?: ReactNode; onSave?: (recordIds: number[]) => void; onClose: () => void; } // ⭐ EXPORTED FOR THE SHEET MODULE (wave 49, W49-T07, ruling R6): "clicking a cell pops up the View // using exactly the Link field type's popup UI". Exactly the same component, not a copy of it, so -// the two surfaces cannot drift into two popups that behave almost alike. This `export` is lane A's -// ONLY change to this file, and it is additive: the single existing call site below is untouched, -// and nothing about the component's props, focus trap or portal changes. +// the two surfaces cannot drift into two popups that behave almost alike. W56-T24 adds optional +// chrome slots and a `cellView` modifier while leaving existing callers and the focus trap intact. export function LinkGridModal({ label, table, recordIds, editable = false, single = false, - excludeRecordId, onSave, onClose }: LinkGridModalProps) { + excludeRecordId, cellView = false, cellFilter, onCellFilterChange, headerActions, footer, + onSave, onClose }: LinkGridModalProps) { const panelRef = useRef(null); const [selectedIds, setSelectedIds] = useState(() => [...recordIds]); const changeSelectedIds = useCallback((ids: number[]) => { @@ -1775,18 +1800,21 @@ export function LinkGridModal({ label, table, recordIds, editable = false, singl role="dialog" aria-modal="true" aria-label={label} - data-overlay-kind="linked-record-grid" + data-overlay-kind={cellView ? "cell-data-grid" : "linked-record-grid"} tabIndex={-1} >
{label}
- {(editable ? selectedIds.length : recordIds.length).toLocaleString()} linked{ + {(editable ? selectedIds.length : recordIds.length).toLocaleString()} { + cellView ? "matching" : "linked" + }{ single ? " (one allowed)" : "" } {(editable ? selectedIds.length : recordIds.length) === 1 ? "record" : "records"}
+ {headerActions} - )} - - {readOnlyReason &&
{readOnlyReason}
} - {card ? ( -
- -
{ - // ⭐ W41-T48 — the card IS the deck's record open, so it folds the rail. - // ⚠ Nothing that is NOT an open can reach this line: every control inside the - // card (a url cell, the comments box, the document tray) already stops its own - // click, and the left/right decision buttons are siblings of the card, not - // children of it. The deck also has no pointer drag to disambiguate — its swipe - // is the two buttons and the arrow keys, neither of which opens anything. - // ⚠ `
`, not a native button, so a keyboard activation - // never arrives here as a synthetic click; the keydown path below is the whole - // keyboard story and the two cannot both fire for one gesture. - if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT); - onOpen(card.pid); - }} - onKeyDown={(e) => { - if (e.key !== "Enter" && e.key !== " ") return; - e.preventDefault(); - // W41-T48 — `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space - // auto-repeats keydown, and every one of those repeats is the SAME gesture. - if (!e.repeat) signal(NAV_MINIMIZE_EVENT); - onOpen(card.pid); - }} - > -

{String(card[titleKey] ?? "")}

-
- {/* ⭐ WAVE-29 T26 (R9) — the RECORD's visible fields, not the three-key summary the - kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not - been widened yet renders exactly what it rendered before. */} - {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => { - const f = fieldByKey.get(k); - if (!f) return null; - const text = formatDisplay(f, card[k]); - if (!text) return null; - // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one - // scheme guard — and every gesture that reaches it must be stopped from also - // reaching the card, which is a button (the kanban card's note, same trap). - const href = actionHref(f, card[k]); - return ( - - ); - })} -
- {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"` - that opens the record, and a click on a comment box or an upload control must not - also open the modal it exists to make unnecessary (the kanban card's link trap, - one surface over). */} - {onDocAdd && onDocFetch && onDocDelete && ( -
e.stopPropagation()} - onKeyDown={(e) => e.stopPropagation()} - role="presentation" - > - onDocAdd(card.pid, file)} - onFetch={(docId) => onDocFetch(card.pid, docId)} - onDelete={(docId) => onDocDelete(card.pid, docId)} - /> -
- )} - {scope != null && ( -
e.stopPropagation()} - onKeyDown={(e) => e.stopPropagation()} - role="presentation" - > - {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React - reuses the mounted instance across a card change and paints one record's - comments under another's name until the fetch returns. */} - -
- )} - {canWrite && ( - - )} -
- -
- ) : ( - // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous - // between "the deck is finished" and "the filter hid everything", and the two want - // different next actions. `later` is disclosed rather than quietly subtracted. -
- {later.size > 0 ? ( - <> -

- {later.size.toLocaleString()}{" "} - {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else - in this view is missing a {field.label}. -

- - - ) : ( -

- Every record in this view already has a {field.label}. Widen the - view's filters to sort more. -

- )} -
- )} - - ); -} - -/** - * The binding picker: field + two options. It is also the surface every LOST binding lands on, - * with the loss stated above it — one place that answers "what is this deck for", rather than an - * error screen beside a separate setup screen. - */ -function SwipeBinder({ - fault, - fields, - fieldByKey, - spec, - canBind, - onSpec, -}: { - fault: BindingFault; - fields: Field[]; - fieldByKey: Map; - spec: SwipeSpec | undefined; - canBind: boolean; - onSpec: (next: SwipeSpec | undefined) => void; -}) { - const selects = useMemo( - () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2), - [fields] - ); - const [fieldKey, setFieldKey] = useState(() => { - if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey; - return selects[0]?.key ?? ""; - }); - const chosen = fieldByKey.get(fieldKey); - const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]); - const [left, setLeft] = useState(""); - const [right, setRight] = useState(""); - - // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's - // pick survives re-renders, and reset whenever the field changes — carrying an option from the - // previous field would offer a value the new field cannot hold. - useEffect(() => { - setLeft(options[0] ?? ""); - setRight(options.find((o) => o !== options[0]) ?? ""); - }, [options]); - - const message = ((): string => { - switch (fault.kind) { - case "field-gone": - return "The field this deck sorted into has been deleted. Pick another one."; - case "not-select": - return `“${fault.field.label}” is no longer a single-select, so it has no options to` - + " sort into. Pick another field."; - case "option-gone": - return `${fault.missing.map((m) => `“${m}”`).join(" and ")} ${ - fault.missing.length === 1 ? "is" : "are" - } no longer ${fault.missing.length === 1 ? "an option" : "options"} on “${ - fault.field.label - }”. Pick the sides again.`; - default: - return "Sort records one at a time into two options of a single-select field."; - } - })(); - - if (!canBind) { - return ( -
-

{message}

-

Its creator or an admin can set this view up.

-
- ); - } - if (selects.length === 0) { - // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the - // requirement is what turns a dead end into a next action. - return ( -
-

- A swipe deck sorts into a single-select field with at least two options. This database - does not have one yet — add a single-select column, then come back. -

-
- ); - } - const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase(); - return ( -
-

{message}

- -
- - -
- {!ready && left && right && ( - // Stated, not silently refused: both engines DROP a binding whose sides are the same - // option, so a Save that looked like it worked would simply not persist. -

- The two sides must be different options — otherwise both gestures do the same thing. -

- )} - -
- ); -} - -export default SwipeView; +// --------------------------------------------------------------------------- +// customer-grid / SwipeView.tsx +// ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) — the SWIPE deck. +// +// One record at a time, decided left or right into two options of ONE +// single-select. R2 fixes the shape and it is narrow on purpose: +// · SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding. +// · the deck holds only the records whose bound field is EMPTY — a record +// that already has a value has been decided, and re-asking is not triage. +// · a swipe writes through the NORMAL cell door (`onSwipe`, which the host +// maps to the same `patchAndRecord` a kanban card move uses), so undo, +// echo-suppression and the permission wall all hold without being +// re-implemented here. +// +// Honesty rules carried from the other modes: +// · nothing is silently hidden — the deck states what is left, and the +// empty state names the bound field rather than saying "all done". +// · a lost binding is SHOWN, never repaired by guessing. `_clean_display` +// validates that `fieldKey` names a field the table HAS and stops there; +// it cannot know the field is still a select, or that the two options are +// still in its vocabulary (its docstring draws that line explicitly). So +// those three losses land here, and each one says what happened and +// re-opens the picker — the `viewModes.tsx:190-194` rule, which exists +// because the wave-7 trap was a picker silently falling back to its first +// option. +// --------------------------------------------------------------------------- + +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +// ⭐⭐ W41-T48 (owner instruction 22) — opening a record from the swipe deck folds the shell's +// navigation rail exactly as a grid cell click does. Guard rationale: `MapView.tsx:2755`. +import { NAV_MINIMIZE_EVENT, signal } from "../apiContract"; +import { choiceOptions } from "./types"; +import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types"; +// ⚠ `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is +// loaded here) — the same import `RecordComments` takes for the same prop. +import type { SurfaceScope } from "./apiBridge"; +import RecordComments from "./RecordComments"; +import { Documents } from "./Documents"; +import { formatDisplay } from "./cells"; +import { actionHref } from "./display"; +import { optionTint } from "./choiceColors"; +import { ModeIcon } from "./icons"; +// ⭐ W29-T73 — the line its three siblings all have, and the one this file shipped without. +// `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered +// unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right — +// a partially-styled surface reads as a design choice, which is why nobody reported it and no +// gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]). +import "./SwipeView.css"; + +export type SwipeSpec = NonNullable; + +/** The three ways a stored binding can rot that the host cannot see (see the header note). */ +type BindingFault = + | { kind: "unbound" } + | { kind: "field-gone"; fieldKey: string } + | { kind: "not-select"; field: Field } + | { kind: "option-gone"; field: Field; missing: string[] }; + +function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map): + { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } { + if (!spec) return { ok: false, fault: { kind: "unbound" } }; + const field = fieldByKey.get(spec.fieldKey); + if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } }; + // R2 — SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET, + // so "write this option" would mean append-or-replace, and a triage gesture that sometimes + // adds and sometimes overwrites is two gestures wearing one button. + if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } }; + const options = choiceOptions(field); + const has = new Set(options.map((o) => o.toLowerCase())); + const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase())); + if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } }; + return { ok: true, field, spec }; +} + +/** The bound cell is EMPTY — the one predicate that decides deck membership (R2). */ +const isUndecided = (row: Row, key: string): boolean => + String(row[key] ?? "").trim() === ""; + +export function SwipeView({ + rows, + fields, + fieldByKey, + spec, + cardKeys, + detailKeys, + scope, + viewer, + docs, + docPayload, + onDocAdd, + onDocFetch, + onDocDelete, + titleKey, + canWrite, + readOnlyReason, + canBind, + onSpec, + onSwipe, + onOpen, +}: { + /** DISTINCT data rows from the full pipeline, overlay edits layered — the kanban's contract. + * The deck re-derives from these, so a written record leaves it as soon as the optimistic + * patch lands; there is no local cursor to drift out of step with the data. */ + rows: Row[]; + /** Every field, for the picker's field list. */ + fields: Field[]; + fieldByKey: Map; + /** The stored binding, or undefined for a deck nobody has configured yet. */ + spec: SwipeSpec | undefined; + /** The handful of visible fields the card lists under its title. */ + cardKeys: string[]; + titleKey: string; + /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */ + canWrite: boolean; + /** Stated when the deck cannot be decided — permissions, or a computed column. */ + readOnlyReason: string | null; + /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the + * view-editing permission and NOT `canWrite` — conflating the two is + * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does + * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */ + canBind: boolean; + /** `undefined` DELETES the binding — absent is the honest unconfigured state, and storing a + * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */ + onSpec: (next: SwipeSpec | undefined) => void; + onSwipe: (pid: number, value: string) => void; + onOpen: (pid: number) => void; + /** + * ⭐⭐ WAVE-29 T26 (owner R9) — WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY. + * + * R9: *"the swipe CARD itself renders the record detail inline — fields, comments and + * attachments — so a reviewer decides without leaving the deck."* Everything below is that, + * and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply + * different amounts. A card must render with none of them rather than throw — the standalone + * embed has no `scope`, and a deployment with no document storage serves no handlers. + */ + /** Every field the VIEW shows, in its order — not the three-key card summary. */ + detailKeys?: string[]; + /** The surface these records live on. Comments are keyed by it; absent ⇒ no comments section, + * which is the pre-existing precondition `RecordDetail` already carries. */ + scope?: SurfaceScope; + viewer?: Viewer; + /** This record's attachments, and the plumbing. Handlers absent ⇒ the section is not rendered + * at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app + * cannot keep). */ + /** Keyed by pid, because a deck shows many records — `RecordDetail` takes ONE record's list + * and that shape cannot serve a deck. */ + docs?: Record; + docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string }; + /** ⚠ EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE + * open record. A deck paints many records at once, so a handler bound to a single pid would + * attach every reviewer's upload to whichever card happened to be open. */ + onDocAdd?: ( + pid: number, + file: { name: string; mime: string; size: number; data_b64: string } + ) => void; + onDocFetch?: (pid: number, docId: string) => void; + onDocDelete?: (pid: number, docId: string) => void; +}) { + // "Later" — session-only, never stored. A deck with no way past a record you cannot decide + // blocks on that record forever, so this is navigation WITHIN the deck rather than a third + // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty + // state rather than quietly shrinking the deck (rule 8b). + const [later, setLater] = useState>(new Set()); + const deckRef = useRef(null); + + const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]); + const boundKey = binding.ok ? binding.field.key : null; + + const undecided = useMemo( + () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []), + [rows, boundKey] + ); + const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]); + const card = deck[0]; + + // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever — + // otherwise the disclosed skip count drifts away from what is actually on the deck. + useEffect(() => { + setLater((prev) => { + if (prev.size === 0) return prev; + const live = new Set(undecided.map((r) => r.pid)); + const next = new Set([...prev].filter((pid) => live.has(pid))); + return next.size === prev.size ? prev : next; + }); + }, [undecided]); + + const decide = useCallback( + (value: string) => { + if (!card || !canWrite) return; + onSwipe(card.pid, value); + }, + [card, canWrite, onSwipe] + ); + + // ← / → decide, and they are the SAME two actions the buttons are rather than a second code + // path: the whole point of the mode is that one hand can clear a queue. + useEffect(() => { + if (!binding.ok || !canWrite || !card) return; + const onKey = (e: KeyboardEvent) => { + if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return; + const el = document.activeElement as HTMLElement | null; + // Never steal an arrow key from a text field or a native control the user is inside. + if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA")) + return; + if (!deckRef.current?.contains(el ?? null) && el !== document.body) return; + e.preventDefault(); + decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [binding, canWrite, card, decide]); + + if (!binding.ok) { + return ( +
+ +
+ ); + } + + const { field } = binding; + const leftTint = optionTint(field, binding.spec.leftOption); + const rightTint = optionTint(field, binding.spec.rightOption); + + return ( +
+
+ + + Sorting into {field.label} + + + {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort + + {canBind && ( + + )} +
+ {readOnlyReason &&
{readOnlyReason}
} + {card ? ( +
+ +
{ + // ⭐ W41-T48 — the card IS the deck's record open, so it folds the rail. + // ⚠ Nothing that is NOT an open can reach this line: every control inside the + // card (a url cell, the comments box, the document tray) already stops its own + // click, and the left/right decision buttons are siblings of the card, not + // children of it. The deck also has no pointer drag to disambiguate — its swipe + // is the two buttons and the arrow keys, neither of which opens anything. + // ⚠ `
`, not a native button, so a keyboard activation + // never arrives here as a synthetic click; the keydown path below is the whole + // keyboard story and the two cannot both fire for one gesture. + if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT); + onOpen(card.pid); + }} + onKeyDown={(e) => { + if (e.key !== "Enter" && e.key !== " ") return; + e.preventDefault(); + // W41-T48 — `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space + // auto-repeats keydown, and every one of those repeats is the SAME gesture. + if (!e.repeat) signal(NAV_MINIMIZE_EVENT); + onOpen(card.pid); + }} + > +

{String(card[titleKey] ?? "")}

+
+ {/* ⭐ WAVE-29 T26 (R9) — the RECORD's visible fields, not the three-key summary the + kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not + been widened yet renders exactly what it rendered before. */} + {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => { + const f = fieldByKey.get(k); + if (!f) return null; + const text = formatDisplay(f, card[k]); + if (!text) return null; + // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one + // scheme guard — and every gesture that reaches it must be stopped from also + // reaching the card, which is a button (the kanban card's note, same trap). + const href = actionHref(f, card[k]); + return ( + + ); + })} +
+ {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"` + that opens the record, and a click on a comment box or an upload control must not + also open the modal it exists to make unnecessary (the kanban card's link trap, + one surface over). */} + {onDocAdd && onDocFetch && onDocDelete && ( +
e.stopPropagation()} + onKeyDown={(e) => e.stopPropagation()} + role="presentation" + > + onDocAdd(card.pid, file)} + onFetch={(docId) => onDocFetch(card.pid, docId)} + onDelete={(docId) => onDocDelete(card.pid, docId)} + /> +
+ )} + {scope != null && ( +
e.stopPropagation()} + onKeyDown={(e) => e.stopPropagation()} + role="presentation" + > + {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React + reuses the mounted instance across a card change and paints one record's + comments under another's name until the fetch returns. */} + +
+ )} + {canWrite && ( + + )} +
+ +
+ ) : ( + // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous + // between "the deck is finished" and "the filter hid everything", and the two want + // different next actions. `later` is disclosed rather than quietly subtracted. +
+ {later.size > 0 ? ( + <> +

+ {later.size.toLocaleString()}{" "} + {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else + in this view is missing a {field.label}. +

+ + + ) : ( +

+ Every record in this view already has a {field.label}. Widen the + view's filters to sort more. +

+ )} +
+ )} +
+ ); +} + +/** + * The binding picker: field + two options. It is also the surface every LOST binding lands on, + * with the loss stated above it — one place that answers "what is this deck for", rather than an + * error screen beside a separate setup screen. + */ +function SwipeBinder({ + fault, + fields, + fieldByKey, + spec, + canBind, + onSpec, +}: { + fault: BindingFault; + fields: Field[]; + fieldByKey: Map; + spec: SwipeSpec | undefined; + canBind: boolean; + onSpec: (next: SwipeSpec | undefined) => void; +}) { + const selects = useMemo( + () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2), + [fields] + ); + const [fieldKey, setFieldKey] = useState(() => { + if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey; + return selects[0]?.key ?? ""; + }); + const chosen = fieldByKey.get(fieldKey); + const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]); + const [left, setLeft] = useState(""); + const [right, setRight] = useState(""); + + // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's + // pick survives re-renders, and reset whenever the field changes — carrying an option from the + // previous field would offer a value the new field cannot hold. + useEffect(() => { + setLeft(options[0] ?? ""); + setRight(options.find((o) => o !== options[0]) ?? ""); + }, [options]); + + const message = ((): string => { + switch (fault.kind) { + case "field-gone": + return "The field this deck sorted into has been deleted. Pick another one."; + case "not-select": + return `“${fault.field.label}” is no longer a single-select, so it has no options to` + + " sort into. Pick another field."; + case "option-gone": + return `${fault.missing.map((m) => `“${m}”`).join(" and ")} ${ + fault.missing.length === 1 ? "is" : "are" + } no longer ${fault.missing.length === 1 ? "an option" : "options"} on “${ + fault.field.label + }”. Pick the sides again.`; + default: + return "Sort records one at a time into two options of a single-select field."; + } + })(); + + if (!canBind) { + return ( +
+

{message}

+

Its creator or an admin can set this view up.

+
+ ); + } + if (selects.length === 0) { + // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the + // requirement is what turns a dead end into a next action. + return ( +
+

+ A swipe deck sorts into a single-select field with at least two options. This database + does not have one yet — add a single-select column, then come back. +

+
+ ); + } + const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase(); + return ( +
+

{message}

+ +
+ + +
+ {!ready && left && right && ( + // Stated, not silently refused: both engines DROP a binding whose sides are the same + // option, so a Save that looked like it worked would simply not persist. +

+ The two sides must be different options — otherwise both gestures do the same thing. +

+ )} + +
+ ); +} + +export default SwipeView; diff --git a/web/src/customer-grid/dataPath.ts b/web/src/customer-grid/dataPath.ts index 5568590bb90c70775b8e5d484a4714c986e53b1e..4f108fe9c31ac48195000fdab50a1be6061d5caa 100644 --- a/web/src/customer-grid/dataPath.ts +++ b/web/src/customer-grid/dataPath.ts @@ -160,18 +160,34 @@ export function groupDataDatabases(databases: readonly DataDatabase[]): DataData return [...groups].map(([label, grouped]) => ({ label, databases: grouped })); } -export function dataPathHash(path: DataPath): string { +const DATA_PATH_PREFIX = "#/data?"; +export const APP_PATH_PREFIX = "#/app?"; + +function addressedPathHash(prefix: string, path: DataPath): string { const query = new URLSearchParams({ database: path.database }); if (path.view) query.set("view", path.view); if (path.field) query.set("field", path.field); if (path.application) query.set("application", path.application); - return `#/data?${query.toString()}`; + return `${prefix}${query.toString()}`; +} + +export function dataPathHash(path: DataPath): string { + return addressedPathHash(DATA_PATH_PREFIX, path); +} + +export function appPathHash(path: DataPath): string { + return addressedPathHash(APP_PATH_PREFIX, path); } export function readDataPath(hash?: string): DataPath | null { const source = hash ?? (typeof window === "undefined" ? "" : window.location.hash); - if (!source.startsWith("#/data?")) return null; - const query = new URLSearchParams(source.slice("#/data?".length)); + // App and Data address the same database/Application question under different module headings. + // One reader avoids the one-question-two-normalizers defect that has broken deep links before. + const prefix = source.startsWith(DATA_PATH_PREFIX) + ? DATA_PATH_PREFIX + : source.startsWith(APP_PATH_PREFIX) ? APP_PATH_PREFIX : null; + if (!prefix) return null; + const query = new URLSearchParams(source.slice(prefix.length)); const database = query.get("database"); if (!database) return null; return { diff --git a/web/src/index.css b/web/src/index.css index 2f69337eeb2d8ac9ce613a7d3af04051d1f0bceb..884e27330817fc922736d12ecd98eb03c95d0a69 100644 --- a/web/src/index.css +++ b/web/src/index.css @@ -13391,7 +13391,7 @@ textarea.cg-json-raw:focus { /* ⛔⛔ WAVE 35 · T11 (owner item 9, R4) — THE DATABASE-LEVEL TOTAL IS GONE, AND SO IS EVERY RULE THAT DRESSED IT. Owner item 9: the count belongs to the VIEW itself and nowhere else. Wave 33's T16 put a per-database total at the top of this rail and wave 34's T20 stripped its label; both - notes are now history and live in `.claude/wiki/waves/wave35/` rather than here. + notes are now history and live in `AutoWiki/waves/wave35/` rather than here. ⚠ FOUR RULES DIED TOGETHER ON PURPOSE, and this note is what stops one of them coming back alone: `.cg-views-important` (the wrapper's `margin-left: auto`, which outranked `.cg-views-top`'s `justify-content` and is why the fold toggle sat left on a database with a diff --git a/web/src/query/queryParts.tsx b/web/src/query/queryParts.tsx index 206f2bdcb687c03467e5524e477895b1066b685c..2e3a493070afada7d0df9815bf055cd92368e775 100644 --- a/web/src/query/queryParts.tsx +++ b/web/src/query/queryParts.tsx @@ -40,7 +40,7 @@ import type { SavedQuery } from "./queryApi"; * underlined link. That is the "outdated format". * * âš  It is NOT the Suspense fallback (a bare spinner) and NOT the empty state, the two candidates - * the wave listed. Capture of both states: `.claude/wiki/waves/wave35/proto/T22-query-flash/`. + * the wave listed. Capture of both states: `AutoWiki/waves/wave35/proto/T22-query-flash/`. * * âš  KEEP THE TWIN IMPORT IN `QueryPage.tsx`. Vite emits one stylesheet either way, and the * standalone `#/query` host reaches the page without passing through here. diff --git a/web/src/settings/ExternalAccessPane.tsx b/web/src/settings/ExternalAccessPane.tsx new file mode 100644 index 0000000000000000000000000000000000000000..12a2b7f45bc45b949f7ac0a7b5f61d81adaf195f --- /dev/null +++ b/web/src/settings/ExternalAccessPane.tsx @@ -0,0 +1,435 @@ +// settings / ExternalAccessPane.tsx - W56-T38, ruling R3, contract C7. +// +// A self-contained settings pane for the signed-in user's own external credential. The browser +// never derives permission from its session payload: the list response reports whether the same +// server-side Analyst wall permits minting, and every write is checked again by the route. + +import { useCallback, useEffect, useState } from "react"; +import type { FormEvent } from "react"; +import { + API_V1, + CREDENTIALS, + UNAUTHORIZED_EVENT, + checkTenant, +} from "../apiContract"; + +interface ExternalKeyMetadata { + id: string; + label: string; + created: string; + last_used: string | null; + revoked_at: string | null; +} + +interface KeyListResponse { + keys: ExternalKeyMetadata[]; + can_mint: boolean; +} + +interface MintResponse { + key: ExternalKeyMetadata; + secret: string; +} + +type ApiResult = + | { ok: true; data: T } + | { ok: false; message: string }; + +function messageFrom(body: unknown, fallback: string): string { + if (!body || typeof body !== "object") return fallback; + const error = (body as { error?: unknown }).error; + if (!error || typeof error !== "object") return fallback; + const message = (error as { message?: unknown }).message; + return typeof message === "string" && message.trim() !== "" ? message : fallback; +} + +async function call(path: string, init?: RequestInit): Promise> { + try { + const response = await fetch(`${API_V1}${path}`, { + credentials: CREDENTIALS, + ...init, + }); + if (checkTenant(response)) { + return { ok: false, message: "This workspace changed. Reloading." }; + } + let body: unknown = null; + try { + body = await response.json(); + } catch { + // A refused or unavailable endpoint can answer without JSON. The stable fallback remains. + } + if (!response.ok) { + if (response.status === 401 && typeof window !== "undefined") { + window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT)); + } + return { + ok: false, + message: + response.status >= 500 + ? "External access is unavailable right now." + : messageFrom(body, "That request could not be completed."), + }; + } + return { ok: true, data: body as T }; + } catch { + return { ok: false, message: "The server could not be reached." }; + } +} + +async function callText(path: string): Promise> { + try { + const response = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS }); + if (checkTenant(response)) { + return { ok: false, message: "This workspace changed. Reloading." }; + } + const body = await response.text(); + if (!response.ok) { + if (response.status === 401 && typeof window !== "undefined") { + window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT)); + } + let parsed: unknown = null; + try { + parsed = JSON.parse(body); + } catch { + // Markdown is the success shape. A non-JSON refusal uses the stable fallback below. + } + return { + ok: false, + message: + response.status >= 500 + ? "External access is unavailable right now." + : messageFrom(parsed, "That request could not be completed."), + }; + } + return { ok: true, data: body }; + } catch { + return { ok: false, message: "The server could not be reached." }; + } +} + +function parseKey(value: unknown): ExternalKeyMetadata | null { + if (!value || typeof value !== "object" || Array.isArray(value)) return null; + const row = value as Record; + if ( + typeof row.id !== "string" || + typeof row.label !== "string" || + typeof row.created !== "string" + ) { + return null; + } + return { + id: row.id, + label: row.label, + created: row.created, + last_used: typeof row.last_used === "string" ? row.last_used : null, + revoked_at: typeof row.revoked_at === "string" ? row.revoked_at : null, + }; +} + +function when(value: string | null): string { + if (!value) return "Never"; + const parsed = new Date(value); + if (Number.isNaN(parsed.getTime())) return "Unknown"; + return parsed.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" }); +} + +export default function ExternalAccessPane() { + const [keys, setKeys] = useState(null); + const [canMint, setCanMint] = useState(null); + const [label, setLabel] = useState(""); + const [busy, setBusy] = useState(""); + const [error, setError] = useState(""); + const [notice, setNotice] = useState(""); + const [revealed, setRevealed] = useState(null); + const [copied, setCopied] = useState(false); + const [skillCopied, setSkillCopied] = useState(false); + + const load = useCallback(async () => { + const result = await call("/external/keys"); + if (!result.ok) { + setKeys([]); + setCanMint(null); + setError(result.message); + return; + } + if (!Array.isArray(result.data?.keys) || typeof result.data.can_mint !== "boolean") { + setKeys([]); + setCanMint(null); + setError("External access returned an unreadable response."); + return; + } + const parsed = result.data.keys.map(parseKey); + if (parsed.some((row) => row === null)) { + setKeys([]); + setCanMint(null); + setError("External access returned an unreadable response."); + return; + } + setKeys(parsed as ExternalKeyMetadata[]); + setCanMint(result.data.can_mint); + setError(""); + }, []); + + useEffect(() => { + void load(); + }, [load]); + + async function create(event: FormEvent) { + event.preventDefault(); + const clean = label.trim(); + if (!clean) { + setError("Enter a label for this credential."); + return; + } + setBusy("create"); + setError(""); + setNotice(""); + const result = await call("/external/keys", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ label: clean }), + }); + setBusy(""); + if (!result.ok) { + setError(result.message); + return; + } + const key = parseKey(result.data?.key); + if (!key || typeof result.data?.secret !== "string" || result.data.secret === "") { + setError("The credential was created, but its secret could not be read."); + void load(); + return; + } + const minted = { key, secret: result.data.secret }; + setKeys((current) => [key, ...(current ?? []).filter((row) => row.id !== key.id)]); + setLabel(""); + setCopied(false); + setRevealed(minted); + } + + async function copyCredential() { + if (!revealed) return; + try { + await navigator.clipboard.writeText(revealed.secret); + setCopied(true); + setError(""); + } catch { + setCopied(false); + setError("The credential could not be copied. Select it and copy it manually."); + } + } + + async function skillDocument(action: "copy" | "download"): Promise { + setBusy(`skill-${action}`); + setError(""); + setNotice(""); + const result = await callText("/external/skill.md"); + setBusy(""); + if (!result.ok) { + setError(result.message); + return null; + } + return result.data; + } + + async function copySkill() { + const document = await skillDocument("copy"); + if (document === null) return; + try { + await navigator.clipboard.writeText(document); + setSkillCopied(true); + setNotice("skill.md copied. It contains no credential or other secret."); + } catch { + setSkillCopied(false); + setError("skill.md could not be copied. Download it instead."); + } + } + + async function downloadSkill() { + const document = await skillDocument("download"); + if (document === null) return; + try { + const url = URL.createObjectURL( + new Blob([document], { type: "text/markdown;charset=utf-8" }), + ); + const anchor = window.document.createElement("a"); + anchor.href = url; + anchor.download = "skill.md"; + window.document.body.appendChild(anchor); + anchor.click(); + anchor.remove(); + window.setTimeout(() => URL.revokeObjectURL(url), 0); + setNotice("skill.md downloaded. It contains no credential or other secret."); + } catch { + setError("skill.md could not be downloaded. Copy it instead."); + } + } + + async function revoke(key: ExternalKeyMetadata) { + const confirmed = window.confirm( + `Revoke "${key.label}"? The next request using it will be refused.`, + ); + if (!confirmed) return; + setBusy(key.id); + setError(""); + setNotice(""); + const result = await call<{ key: ExternalKeyMetadata }>( + `/external/keys/${encodeURIComponent(key.id)}/revoke`, + { method: "POST" }, + ); + setBusy(""); + if (!result.ok) { + setError(result.message); + return; + } + setKeys((current) => (current ?? []).filter((row) => row.id !== key.id)); + if (revealed?.key.id === key.id) setRevealed(null); + setNotice("Credential revoked. Its next request will be refused."); + } + + if (keys === null) { + return ( +
+ +
+ ); + } + + return ( +
+

External AI

+

+ Create a private credential for an AI you use. It is read only and sees exactly what you + see in Loopable. Revoking it stops the next request. +

+ + {error ?

{error}

: null} + {notice ?

{notice}

: null} + +
+

Portable skill

+

+ Download or copy a skill.md for your AI. It describes your current read scope and carries + no credential or other secret. +

+
+ + +
+
+ + {revealed ? ( +
+

Save this credential

+

+ Copy it now. The secret is shown once and cannot be recovered. +

+
+ + +
+
+ + +
+
+ ) : canMint ? ( +
void create(event)}> +

New credential

+
+ + setLabel(event.currentTarget.value)} + /> +
+
+ +
+
+ ) : canMint === false ? ( +

+ External AI access requires the Analyst module. Ask an administrator to grant it. +

+ ) : null} + +
+

Credentials

+
+ {keys.length === 0 ? ( +

You have no active external AI credentials.

+ ) : ( +
+ {keys.map((key) => ( +
+

{key.label}

+
+ Created + {when(key.created)} +
+
+ Last used + {when(key.last_used)} +
+
+ +
+
+ ))} +
+ )} +
+ ); +} diff --git a/web/src/settings/SettingsModal.tsx b/web/src/settings/SettingsModal.tsx index 1d3679999514c46cbd9a5657ed54871136d3e719..4516fc4613f067e4687bca8d7494779febf466c7 100644 --- a/web/src/settings/SettingsModal.tsx +++ b/web/src/settings/SettingsModal.tsx @@ -76,6 +76,7 @@ import { ManageDatabasePane } from "./ManageDatabase"; // Wave 52 · T19 (owner instruction 21, ruling R7) — sheet shortcut toggles + rebinding. A // client-local preference pane, self-contained like `ManageDatabasePane`; see the mount below. import ShortcutSettings from "./ShortcutSettings"; +import ExternalAccessPane from "./ExternalAccessPane"; import OperatorPage from "../operator/OperatorPage"; /* ⛔ `StatementsPane` LEFT WITH ITS RAIL ROW (wave 35 · T38): the file is DELETED, not merely unmounted. An orphaned component with no importer is the shape this repo books as @@ -155,6 +156,13 @@ const IconShortcuts = ( ); +/** External AI - a governed connection leaving this account. */ +const IconExternal = ( + + + + +); /** Manage users — more than one person. */ const IconUsers = ( @@ -793,6 +801,7 @@ export function SettingsModal({ // preferences, and there is nothing behind this room a member's account cannot already do to // itself (the store is client-local, keyed to nothing server-side). ["shortcuts", "Sheet shortcuts", IconShortcuts], + ["external", "External AI", IconExternal], ...(admin ? ([ ["users", "Manage users", IconUsers], @@ -900,6 +909,7 @@ export function SettingsModal({ `sheet/shortcuts.ts`'s own localStorage store directly and needs nothing passed in, because a keyboard preference is not server data. */} {active === "shortcuts" ? : null} + {active === "external" ? : null} {active === "keychains" ? : null} {active === "connectors" ? : null} {/* Wave 19 contract C2 — the wiring record, verified at the MOUNT SITE diff --git a/web/src/settings/permsModel.ts b/web/src/settings/permsModel.ts index 97b4c00f0b258b7fd6775803ca558ace6075c1c5..62bacf76f127468a41361e923f49f4ce96340e73 100644 --- a/web/src/settings/permsModel.ts +++ b/web/src/settings/permsModel.ts @@ -49,6 +49,7 @@ export type SettingsSection = * store, never on this wire: there is nothing here for a server to enforce. */ | "shortcuts" + | "external" | "users" /** * ⭐ WAVE 33 (owner item 10) — MANAGE AGENT: a bot per Slack channel, walled by diff --git a/web/src/sheet/BindingEditor.tsx b/web/src/sheet/BindingEditor.tsx index 46415973b37589415c5f80a38ef6b0a61d9bd201..b7cadb14dc47a20bc841f7514d90df7d8c3f0710 100644 --- a/web/src/sheet/BindingEditor.tsx +++ b/web/src/sheet/BindingEditor.tsx @@ -43,15 +43,18 @@ import { FieldTypeIcon } from "../customer-grid/icons"; import { BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface"; import type { Field, FilterTree, Row } from "../customer-grid/types"; import { choiceVocabulary, topicForScope } from "../customer-grid/types"; +import type { WindowSpec } from "../customer-grid/windows"; +import { normalizeWindow } from "../customer-grid/windows"; // ⭐⭐ W53-T15 (ruling R8) — THE FILTER BUILDER IS NO LONGER MOUNTED IN THIS COLUMN. The SHARED // `FilterBuilderPanel` the Data module also uses is untouched; `SheetFilterPopup` wraps it in the // base kit's centred dialog so its condition rows have room, and only the Sheet mounts that // wrapper. This file therefore stops importing the panel itself. import { countConditions, isNumericType } from "../filter-kit/ops"; import { SheetFilterPopup } from "../filter-kit/SheetFilterPopup"; +import { WindowPicker } from "../filter-kit/WindowPicker"; import { useEscapeClose } from "../ui/useEscapeClose"; import { previewCell } from "./sheetApi"; -import { bindingDisplay } from "./types"; +import { bindingDisplay, bindingFilterClauses } from "./types"; const AGGREGATES = [ { fn: "sum", label: "Sum" }, @@ -94,6 +97,14 @@ const NUMERIC_ROLLUP_FNS = [ * the field's `type` (the two live ones on `customer_data` are typed `currency` and `int`). */ const isMetricField = (f: Field): boolean => Boolean(f.measure); +/** ⭐ `custom`, not `measure`, identifies a Metric made in the table. `isMetricField` alone is the + * trap: it includes exactly the user-created Metric columns the cell picker must exclude. */ +const isUserMetricField = (f: Field): boolean => isMetricField(f) && f.custom === true; + +/** ⭐ `custom`, not `measure`, separates supplied templates from table-made Metrics. + * `isMetricField` alone is the trap because it includes both kinds. */ +const isTemplateMetricField = (f: Field): boolean => isMetricField(f) && f.custom !== true; + /** Can this database add this column up? Mirrors `modules/sheet.py::aggregate_refusal`. */ const canTotal = (f: Field): boolean => { if (f.type === "formula") return false; @@ -133,6 +144,7 @@ export interface PeriodBinding { start: string; locked: boolean; ref?: string; + window?: WindowSpec; } export const PERIOD_UNITS: { unit: PeriodUnit; label: string }[] = [ @@ -217,6 +229,18 @@ export function migratePeriod(raw: unknown): PeriodBinding | null { if (!raw || typeof raw !== "object") return null; const p = raw as Record; const ref = typeof p.ref === "string" && p.ref.trim() ? p.ref.trim() : ""; + // ⛔ C5 - A DECLARED WINDOW MUST VALIDATE AS THE SHARED WINDOW VOCABULARY. Letting an invalid + // window fall through would misread it as the legacy ref-only dialect or invent a calendar month. + if ("window" in p) { + const window = normalizeWindow(p.window); + if (!window) return null; + return { + unit: "month", + start: normalizePeriodStart("month", todayYm()), + locked: true, + window, + }; + } const declared = PERIOD_UNITS.some((u) => u.unit === p.unit); if (!declared) { // The legacy shape. Nothing shifts by surprise: it reads back LOCKED. @@ -411,7 +435,10 @@ function ColumnPickerDialog({ trapFocus: true, }); - const offersMetric = offered.some(isMetricField); + const offersTemplateMetric = offered.some(isTemplateMetricField); + // ⛔ W56-T19 - A NARROWED LIST MUST SAY WHAT WAS WITHHELD. Without this cause, a database whose + // only usable-looking Metrics were made here would present a silent empty picker as if it had none. + const hasOnlyUnofferedUserMetrics = all.some(isUserMetricField) && !offersTemplateMetric; return ( @@ -514,9 +541,9 @@ function ColumnPickerDialog({ )} - {/* ⛔ AN EMPTY LIST SAYS WHY (R16). The three causes need different acts from the - reader, and a database CAN carry number columns this database cannot total. */} - {shown.length === 0 && ( + {/* ⛔ AN EMPTY LIST SAYS WHY (R16). The causes need different acts from the reader, + and the user-Metric-only cause has its own honest explanation directly below. */} + {shown.length === 0 && (offered.length > 0 || !hasOnlyUnofferedUserMetrics) && (

{offered.length > 0 ? "No column matches that search." @@ -527,12 +554,19 @@ function ColumnPickerDialog({

)} - {/* ⭐ R7, said where the choice is made: a Metric is the one kind of column here that - answers over the period the panel sets. */} - {offersMetric && shown.length > 0 && ( + {hasOnlyUnofferedUserMetrics && (

- A Metric column is measured over the period you choose in the panel. Every other - column holds one stored value per record. + This database's Metric columns were created here rather than supplied as templates, + so they are not offered for a cell; a template metric is measured over the period this + panel sets. +

+ )} + + {/* ⭐ W56-T19, said where the choice is made: a template Metric is the one offered kind + whose value is measured over the period the panel sets. */} + {offersTemplateMetric && shown.length > 0 && ( +

+ A template Metric column is measured over the period you choose in the panel.

)} @@ -693,6 +727,12 @@ export default function BindingEditor({ ); const [locked, setLocked] = useState(migrated?.locked ?? false); const [periodRef, setPeriodRef] = useState(migrated?.ref ?? ""); + // ⭐ C5 - THE TWO PERIOD SPELLINGS ARE SIBLINGS. The mode is seeded from the saved dialect so + // opening and saving a rolling window cannot silently turn it into this month's calendar period. + const [periodMode, setPeriodMode] = useState<"calendar" | "window">( + migrated?.window ? "window" : "calendar", + ); + const [windowSpec, setWindowSpec] = useState(migrated?.window ?? { kind: "ytd" }); // "Use a cell" is a LINK that REVEALS the A1 input (R9). The input was the whole period control // before this ticket and it is not deleted, only demoted to the thing behind that link. const [refOpen, setRefOpen] = useState(Boolean(migrated?.ref)); @@ -871,8 +911,14 @@ export default function BindingEditor({ // column behaves like a number; `canTotal` says this database holds a number to add up. Offering // a column that fails the second one hands back a refusal instead of a value, which is the exact // shape of the report this ticket answers. + // ⛔ W56-T19 - METRICS MADE HERE ARE NOT TEMPLATE OFFERS. The `custom` flag is the separator; + // testing `measure` alone would put every excluded user-created Metric straight back in the list. const numericFields = useMemo( - () => fields.filter((f) => isNumericType(f.type) && canTotal(f)), + () => fields.filter((f) => { + // ⛔ DATE METRICS ARE EXCLUDED BY TYPE, never by a mutable label or key naming convention. + if (isMetricField(f) && (f.type === "date" || f.type === "created_time")) return false; + return isNumericType(f.type) && canTotal(f) && !isUserMetricField(f); + }), [fields], ); @@ -898,6 +944,59 @@ export default function BindingEditor({ [fields], ); + /** + * ⭐⭐ R8 OFFERS THE CELL'S CLAUSES, NOT THE DATABASE'S WHOLE FIELD LIST. The filter tree says + * which values a drag can actually rewrite; `dragDownFields` remains the one steppability set. + * + * ⛔ Every clause stays in the offer even when it cannot step. Omitting a set, measure, missing + * column or unordered field would make a configured filter disappear without explaining why. + * The full reason remains the option's hover title; `shortReason` keeps the closed select legible + * in this narrow panel without throwing that explanation away. + */ + const filterClauseOffers = useMemo(() => { + const fieldsByKey = new Map(fields.map((candidate) => [candidate.key, candidate])); + const steppableKeys = new Set(dragDownFields.map((candidate) => candidate.key)); + return bindingFilterClauses(tree).map((clause) => { + const clauseField = fieldsByKey.get(clause.colId); + const label = clauseField?.label?.trim() || clause.colId; + let reason = ""; + let shortReason = ""; + if (clause.measure) { + reason = "This measure condition compares a number over a window, not an option."; + shortReason = "compares a number over a window"; + } else if (clause.multiValued) { + reason = "This clause holds a set of values (is any of), so it has no next value; it has several."; + shortReason = "a set of values, so there is no next one"; + } else if (!clauseField) { + reason = "This column is not on this database any more, so nothing can look up its options."; + shortReason = "not on this database any more"; + } else if (clauseField.multi || clauseField.type === "multiselect") { + reason = "This column is multi-valued or a multiselect, so it has no next value; it has several."; + shortReason = "several values per record"; + } else if (!steppableKeys.has(clause.colId)) { + reason = "This column is not a single select, status or link, so it has no option order to advance through."; + shortReason = "no option order to advance through"; + } + return { + colId: clause.colId, + label, + value: clause.value, + canStep: !reason, + reason, + shortReason, + }; + }); + }, [tree, fields, dragDownFields]); + + /** + * ⛔ A SAVED DRIVER STAYS VISIBLE WHEN THE CURRENT OFFER SET NO LONGER CARRIES IT. Letting the + * native select fall back to its first row would paint "Keep this filter" and silently overwrite + * the saved choice on Save, the same narrowing failure shape as D-660. + */ + const savedDragDriverMissing = Boolean(downField) && (scopeKind === "view" + ? !dragDownFields.some((candidate) => candidate.key === downField) + : !filterClauseOffers.some((clause) => clause.colId === downField)); + /** * ⭐⭐ W50-T21 (owner instruction 24: *"Sheet column picker (sum/count) shows the Field icons."*) * @@ -931,6 +1030,13 @@ export default function BindingEditor({ const chosenField = useMemo(() => fields.find((f) => f.key === field), [fields, field]); /** Metric columns step their period; every other aggregate steps one chosen filter driver. */ const chosenIsMetric = Boolean(chosenField && isMetricField(chosenField)); + const chosenIsTemplateMetric = Boolean(chosenField && isTemplateMetricField(chosenField)); + + // ⭐⭐ W56-T19 - A TEMPLATE METRIC HAS NO ALL-TIME READING. Raising the existing switch in an + // effect reveals the period controls immediately, while the ready gate below covers this render. + useEffect(() => { + if (chosenIsTemplateMetric) setPeriodOn(true); + }, [chosenIsTemplateMetric]); /** The database's own label, which the column list's heading names. Two databases can both * carry a column called "Total", and the heading is where that ambiguity is answered. */ @@ -959,18 +1065,29 @@ export default function BindingEditor({ // stamped to this month's default, and turning the switch off drops the key rather than writing // an empty period the server would have to guess about. if (periodOn) { - const period: Record = { - unit, start, locked: chosenIsMetric ? locked : true, - }; - if (refOpen && periodRef.trim()) period.ref = periodRef.trim(); - out.period = period; + // ⛔ C5 - EMIT EXACTLY ONE DIALECT. `clean_period` prefers unit/start when both are present, + // so combining these branches would silently discard the rolling window. + if (periodMode === "window") { + out.period = { window: windowSpec }; + } else { + const period: Record = { + unit, start, locked: chosenIsMetric ? locked : true, + }; + if (refOpen && periodRef.trim()) period.ref = periodRef.trim(); + out.period = period; + } } - out.onDrag = chosenIsMetric - ? { across: periodOn && !locked ? across : "none", down: "none" } - : { across: "none", down: downField ? { field: downField } : "none" }; + // ⛔⛔ R8 REVOKED W51-T12'S ONE-AXIS-AT-A-TIME RULE. The wire keys keep C2's spelling + // because `clean_on_drag` rebuilds anything else; emitting both slots independently lets one + // Metric cell step its period and one filter clause without either choice erasing the other. + out.onDrag = { + across: chosenIsMetric && periodOn && periodMode === "calendar" && !locked ? across : "none", + down: downField ? { field: downField } : "none", + }; return out; }, [database, fn, field, scopeKind, viewId, views, tree, initial, - unit, start, locked, refOpen, periodRef, periodOn, across, downField, chosenIsMetric]); + unit, start, locked, refOpen, periodRef, periodOn, periodMode, windowSpec, + across, downField, chosenIsMetric]); // ⭐ THE NUMBER APPEARS BEFORE SAVING. `preview` evaluates the binding without persisting it, // 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({ // A cell bound to a live view satisfies every other clause the moment the panel mounts, and a // Save taken then would write back a binding assembled from a list nobody had seen yet. const ready = optionsResolved && Boolean(database) && (fn === "count" || Boolean(field)) - && (scopeKind === "filter" || Boolean(viewId)); + && (scopeKind === "filter" || Boolean(viewId)) + && (!chosenIsTemplateMetric || periodOn); const { y: startYear, m: startMonth } = splitYm(start); const thisYear = new Date().getFullYear(); @@ -1212,6 +1330,8 @@ export default function BindingEditor({ type="button" role="switch" aria-checked={periodOn} + aria-disabled={chosenIsTemplateMetric} + disabled={chosenIsTemplateMetric} className={"sheet-lock-toggle" + (periodOn ? " is-on" : "")} onClick={() => setPeriodOn((v) => !v)} > @@ -1219,143 +1339,156 @@ export default function BindingEditor({ Limit this cell to a period

- {periodOn - ? "Only rows dated inside the period below are counted." - : "All time, so every row this cell's filter matches is counted whatever its date. " - + "Saving leaves it that way."} + {chosenIsTemplateMetric + ? "The period is required because this column is measured over one." + : (periodOn + ? "Only rows dated inside the period below are counted." + : "All time, so every row this cell's filter matches is counted whatever its date. " + + "Saving leaves it that way.")}

{periodOn && ( <> + {/* ⭐ C5 - THE MODE LABELS SAY WHAT EACH CHOICE DOES. Internal dialect names + would make the reader guess which one can step and which one follows today. */} -
+ {periodMode === "window" ? ( - {unit === "month" && ( - - )} - {unit === "quarter" && ( + ) : ( + <> - )} -
- - {/* THE QUICK PICKS. They normalize through the same function the pickers do, so This - never stamps today's month under a quarter or a year. */} -
- - -
- - {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the - sentence under it says what each one costs when the cell is copied. */} - {chosenIsMetric ? ( -
- -

- {locked - ? "Locked, so any copy of this cell keeps this period." - : `Not locked, so a stepped copy moves by one ${UNIT_NOUN[unit]} per cell. ` - + "Right and down move forward. Left and up move backward."} -

-
- ) : ( -

- This period stays fixed when copied. The filter driver below is what changes. -

- )} - {/* ⭐ "Use a cell" STAYS A LINK (R9). It reveals the A1 input rather than replacing the - picker, so the ordinary reader never meets a cell reference and the person who wants - one is one click away from it. */} - {!refOpen && ( - - )} - {refOpen && ( - +
+ + {unit === "month" && ( + + )} + {unit === "quarter" && ( + + )} +
+ + {/* W56-T21 (owner instruction 13) - THE QUICK PICKS ARE GONE. Unit, year and + month-or-quarter already reach every period the This and Last buttons + could, so a second control for the same value was a second way to say one + thing. `normalizePeriodStart` still normalises all three selects, and + `shiftPeriodStart` stays exported for the drag arithmetic. */} + + {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the + sentence under it says what each one costs when the cell is copied. */} + {chosenIsMetric ? ( +
+ +

+ {locked + ? "Locked, so any copy of this cell keeps this period." + : `Not locked, so a stepped copy moves by one ${UNIT_NOUN[unit]} per cell. ` + + "Right and down move forward. Left and up move backward."} +

+
+ ) : ( +

+ This period stays fixed when copied. The filter clause below is what + changes. +

+ )} + + {/* ⭐ "Use a cell" STAYS A LINK (R9). It reveals the A1 input rather than replacing the + picker, so the ordinary reader never meets a cell reference and the person who wants + one is one click away from it. */} + {!refOpen && ( + + )} + {refOpen && ( + + )} + )} )} @@ -1365,59 +1498,101 @@ export default function BindingEditor({
When copied - {chosenIsMetric ? ( - periodOn ? ( - <> - -

- Right and down move forward. Left and up move backward. -

- - ) : ( -

- This metric is all time, so copied cells keep the same all-time period. -

- ) - ) : ( + {chosenIsMetric && periodOn && periodMode === "calendar" && ( <> - {dragDownFields.length === 0 ? ( -

- This database has no single select or link field with ordered options. -

- ) : ( -

- Right and down choose later options. Left and up choose earlier options. -

- )} +

+ Right and down move forward. Left and up move backward. +

)} + + {/* ⛔ C5 - A ROLLING WINDOW HAS NO START TO SHIFT. Offering the calendar step here + would promise an action `dragBoundCell` cannot perform. */} + {periodOn && periodMode === "window" && ( +

+ A rolling window is measured from today, so every copy of this cell answers the + same window. Use a calendar period when the period should step as the cell is copied. +

+ )} + + {/* ⚠ AN ALL-TIME METRIC SAYS WHY NO PERIOD PICKER IS PRESENT. Without this note the + absent control looks like a loading or configuration failure. */} + {chosenIsMetric && !periodOn && ( +

+ This metric is all time, so copied cells keep the same all-time period. +

+ )} + + + {savedDragDriverMissing && ( +

+ The saved driver is not in this cell's filter, so copying this cell will not + change it. Pick a driver that is in the filter, or keep the filter. +

+ )} + {scopeKind === "view" ? ( +

+ These rows come from a saved view, so the view's filter clauses cannot be listed + here. This database's steppable columns are offered instead. A driver that is not + in the view's filter changes nothing, and the sheet says so when dragged. +

+ ) : filterClauseOffers.length === 0 ? ( +

+ This cell has no filter clauses to step. +

+ ) : ( +

+ Right and down choose later options. Left and up choose earlier options. +

+ )}
{/* ⛔⛔ W53-T16 (owner instruction 13) - THE FOUR SENTENCE SUMMARY IS DELETED, NOT HIDDEN. diff --git a/web/src/sheet/CellActionBar.tsx b/web/src/sheet/CellActionBar.tsx index 696593989a6c4439fbc8ee4a17b3b8af9009c3ce..765b311d651008ca99d392919ca837bde29f2529 100644 --- a/web/src/sheet/CellActionBar.tsx +++ b/web/src/sheet/CellActionBar.tsx @@ -1,10 +1,11 @@ // sheet/CellActionBar.tsx — the non-modal bar that appears beside a selected cell (W49-T05, R11). // // ⭐⭐ NON-MODAL IS THE RULING, AND IT DICTATES THREE THINGS THIS COMPONENT DOES NOT DO. R11 says a -// cell click SELECTS and the bar carries Edit / View rows / Refresh. So it does NOT trap focus, it -// does NOT render a backdrop, and it does NOT autofocus anything: the grid keeps the keyboard the -// whole time, which is what lets someone arrow to the next cell without dismissing anything. That -// is the opposite discipline from `LinkGridModal`, which is modal and traps focus deliberately. +// cell click SELECTS and the bar carries Edit / View data. W56-T23 (owner instruction 16) retired +// the Refresh entry because the ribbon already carries one. So it does NOT trap focus, it does NOT +// render a backdrop, and it does NOT autofocus anything: the grid keeps the keyboard the whole time, +// which is what lets someone arrow to the next cell without dismissing anything. That is the opposite +// discipline from `LinkGridModal`, which is modal and traps focus deliberately. // // ⚠ `onMouseDown` PREVENTS DEFAULT ON THE BAR ITSELF. Without it, pressing a button blurs the grid // canvas, glide-data-grid drops its selection, and the bar unmounts before the click lands. The @@ -25,7 +26,8 @@ export interface CellActionBarProps { busy?: boolean; onEdit: () => void; onViewRows: () => void; - onRefresh: () => void; + /** W56-T23 retired the button; kept only so sibling SheetGrid compiles. Drop once that file is free. */ + onRefresh?: () => void; } function IconEdit() { @@ -46,17 +48,8 @@ function IconRows() { ); } -function IconRefresh() { - return ( - - ); -} - export default function CellActionBar({ - anchor, drill, canEdit, busy = false, onEdit, onViewRows, onRefresh, + anchor, drill, canEdit, busy = false, onEdit, onViewRows, }: CellActionBarProps) { // Clamped so a cell at the very top or the right edge still shows its bar on screen. const style: CSSProperties = { @@ -84,15 +77,11 @@ export default function CellActionBar({ // ⭐ R17: the reason is NAMED rather than left to a disabled control with no explanation. // `title` carries it on hover and `aria-description` carries it to a screen reader, so the // two audiences get the same sentence. - title={drill.enabled ? "View the rows behind this cell" : drill.reason} + title={drill.enabled ? "View the data behind this cell" : drill.reason} aria-description={drill.enabled ? undefined : drill.reason} > - View rows - - ); diff --git a/web/src/sheet/ChartDialog.tsx b/web/src/sheet/ChartDialog.tsx index fa1b8f3c27a40ddc0029f7865ce1f104588ee07d..040ca72c1ab0da620042f1bc8296692b9cc1413b 100644 --- a/web/src/sheet/ChartDialog.tsx +++ b/web/src/sheet/ChartDialog.tsx @@ -327,6 +327,11 @@ export interface ChartDialogProps { ) => void; /** The existing chart's one persisted settings write. */ onUpdate?: (chart: SheetChartSpec) => void; + /** + * R6's delete door. The mount supplies it for an existing chart, and the control stays hidden + * when the mount cannot delete. + */ + onDelete?: () => void; /** Ribbon openers restore themselves; a chart settings button delegates restoration here. */ restoreFocus?: boolean; } @@ -337,6 +342,7 @@ export default function ChartDialog({ onClose, onCreate, onUpdate, + onDelete, restoreFocus = false, }: ChartDialogProps) { const panelRef = useRef(null); @@ -429,16 +435,21 @@ export default function ChartDialog({ const rangeField = (
- + setRangeDraft(event.target.value)} /> +

+ The chart reads these cells, and moving or resizing it does not change them. +

{range === null ? (
+ {editing && onDelete ? ( + + ) : null} diff --git a/web/src/sheet/DrillModal.tsx b/web/src/sheet/DrillModal.tsx index 0da26ab7c2ea154c380d5a66e473c9b41cbbc3c8..76e1a3f35f633285216f89c14e023989d4bc727d 100644 --- a/web/src/sheet/DrillModal.tsx +++ b/web/src/sheet/DrillModal.tsx @@ -1,8 +1,8 @@ // sheet/DrillModal.tsx — a bound cell's rows, in the Link field's own popup (W49-T07, R6/R13/R17). // // ⭐⭐ R6 SAYS "EXACTLY THE LINK FIELD TYPE'S POPUP UI", SO THIS REUSES THE COMPONENT RATHER THAN -// ITS APPEARANCE. `LinkGridModal` is imported from `customer-grid/CustomerGrid.tsx`, which lane A -// touched for exactly one line (its `export`). Rebuilding a lookalike would give the product two +// ITS APPEARANCE. `LinkGridModal` is imported from `customer-grid/CustomerGrid.tsx`. Rebuilding a +// lookalike would give the product two // popups that behave almost the same, and "almost" is where a focus trap or an escape key goes // missing on one of them. // @@ -21,7 +21,7 @@ // Owner, verbatim: *"Clicking View rows still takes a long time; if it must, we need a loading // button so the user knows their click worked."* This component used to render `null` for the whole // of that wait, so a drill that was working and a click that never landed looked identical. Measured -// on tenant #0 (`.claude/wiki/waves/wave54/lanes/E/T36-baseline.md`): `drill_cell` costs 55 to 90 ms +// on tenant #0 (`AutoWiki/waves/wave54/lanes/E/T36-baseline.md`): `drill_cell` costs 55 to 90 ms // against a `ut_*` table but 9,248 to 9,448 ms against `customer_data`, which goes through the // registry-module mirror rather than a DuckDB query. So the wait is real and it is long. // @@ -42,31 +42,22 @@ // Edit filter action opens the shared `SheetFilterDialog`, and one cell-scoped step of undo takes // it back. // -// ⛔⛔ THE BAND IS PORTALLED INTO `LinkGridModal`'s OWN CARD, WHICH LOOKS LIKE A LIBERTY AND IS -// THE CONSERVATIVE CHOICE. `LinkGridModal` has no slot for extra chrome and it is not this lane's -// file, so the two alternatives were a floating strip positioned over its header by copied -// geometry, or this. A floating strip fails three ways at once and every one of them is silent: -// it is OUTSIDE `panelRef`, so the shared dismissal contract reads a click on it as an outside -// pointerdown and closes the drill the instant you reach for Edit; it is outside the focus trap, -// so the control is mouse-only; and it re-derives a card size it does not own. A portal into the -// card is inside all three. The host is found by `data-overlay-kind="linked-record-grid"`, the -// attribute that component already publishes for exactly this kind of identification, and when -// it is absent the band simply does not render. +// ⭐⭐ W56-T24 / R4 / C4 — THE LINK MODAL NOW OWNS ORDINARY SLOTS FOR THE SHEET'S CHROME. +// The toolbar and filter statement are children of the modal's header and footer, so they remain +// inside its focus trap and dismissal boundary without querying the DOM or waiting for a frame. +// The body is the default `CustomerGrid` export itself, with `cellView` relaxing only its embedded +// mode-switcher withholding. The embedded write and workspace guards remain untouched. // -// ⛔ AND THE BAND MAY WEAR `.cg-link-grid-foot`, WHICH THE SKELETON ABOVE MAY NOT. The rule that +// ⛔ THE REAL FOOTER MAY WEAR `.cg-link-grid-foot`, WHICH THE SKELETON ABOVE MAY NOT. The rule that // stops `DrillSkeleton` borrowing `customer-grid/RecordDetail.css` is that the skeleton stands in // for a chunk that has not arrived, so on a cold cache its class names would exist and its rules -// would not. This band renders ONLY as a child of a mounted `LinkGridModal`, i.e. only once that -// same chunk is in hand, so the stylesheet is guaranteed present. Same file, opposite verdict, -// for one reason: WHEN it paints. +// would not. `LinkGridModal` renders that footer only after the same chunk is in hand, so its +// stylesheet is guaranteed present. Same file, opposite verdict, for one reason: WHEN it paints. import { Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { createPortal } from "react-dom"; import { fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge"; import type { SurfaceScope } from "../customer-grid/apiBridge"; import { dataPathHash } from "../customer-grid/dataPath"; -import { formatDisplay } from "../customer-grid/display"; -import { ModeIcon } from "../customer-grid/icons"; import { AnchoredOverlay, OverlayProvider } from "../customer-grid/OverlaySurface"; import type { Field, FilterTree, GridWorkspace, Row } from "../customer-grid/types"; import { choiceVocabulary, mayEditField, topicForScope } from "../customer-grid/types"; @@ -77,8 +68,7 @@ import { useEscapeClose } from "../ui/useEscapeClose"; import { cellViewVisibleKeys, filterFieldKeys } from "./bindingRefs"; import { drillCell } from "./sheetApi"; import type { CellDrill } from "./sheetApi"; -import { CELL_VIEW_MODES } from "./types"; -import type { BindingDisplay, CellViewMode } from "./types"; +import type { BindingDisplay } from "./types"; /** * ⛔⛔ LAZY, AND THE BUILD IS WHAT SAID SO. A plain `import { LinkGridModal } from @@ -90,8 +80,8 @@ import type { BindingDisplay, CellViewMode } from "./types"; * Sheet page downloads the whole customer grid before anyone has drilled into anything. * * ⚠ `React.lazy` wants a DEFAULT export and `LinkGridModal` is a named one, so the promise is - * mapped. That is the whole trick, and it keeps lane A's single-line change to `CustomerGrid.tsx` - * intact: the export stays named, and the split is restored here rather than by widening the fence. + * mapped. That is the whole trick: the export stays named and the split remains intact while + * W56-T24 extends the modal through optional props. */ const LinkGridModal = lazy(() => import("../customer-grid/CustomerGrid").then((m) => ({ default: m.LinkGridModal })), @@ -114,191 +104,6 @@ const LinkGridModal = lazy(() => */ const warmLinkChunk = () => import("../customer-grid/CustomerGrid"); -const CELL_VIEW_LABELS: Record = { - grid: "Grid", - list: "List", - map: "Map", -}; - -/** Compact Grid projection for a cell; values use the Data grid's one formatter. */ -function CellGridView( - { rows, fields, identityKey }: { rows: Row[]; fields: Field[]; identityKey: string }, -) { - return ( -
-
- {fields.map((field) => {field.label})} -
- {rows.map((row) => ( -
- {fields.map((field) => ( - - {formatDisplay(field, row[field.key]) || " "} - - ))} -
- ))} - {rows.length === 0 &&
No records match this cell.
} -
- ); -} - -/** List projection keeps one record together and labels every secondary value. */ -function CellListView( - { rows, fields, identityKey }: { rows: Row[]; fields: Field[]; identityKey: string }, -) { - const identity = fields.find((field) => field.key === identityKey) ?? fields[0] ?? null; - const details = fields.filter((field) => field.key !== identity?.key); - return ( -
- {rows.map((row) => ( -
-

{identity ? formatDisplay(identity, row[identity.key]) : `Record ${row.pid}`}

-
- {details.map((field) => ( - - {field.label} - - {formatDisplay(field, row[field.key]) || " "} - - - ))} -
-
- ))} - {rows.length === 0 &&
No records match this cell.
} -
- ); -} - -interface CellMapAssets { - land: string; - lakes: string[]; - project: (lon: number, lat: number) => { x: number; y: number }; - parse: (value: unknown) => { lat: number; lon: number } | null; -} - -interface CellMapSetup { - latField?: string; - lonField?: string; - coordField?: string; -} - -const numberAt = (value: unknown): number | null => { - if (value == null || value === "") return null; - const number = typeof value === "number" ? value : Number(value); - return Number.isFinite(number) ? number : null; -}; - -/** The ordinary map projection, narrowed to the cell's exact row ids and without route writers. */ -function CellMapView({ - rows, identityKey, setup, assets, -}: { - rows: Row[]; - identityKey: string; - setup: CellMapSetup | null; - assets: CellMapAssets | null; -}) { - if (!assets) { - return ( -
- -
- ); - } - const points: { pid: number; title: string; x: number; y: number }[] = []; - for (const row of rows) { - let at: { lat: number; lon: number } | null = null; - if (setup?.latField && setup.lonField) { - const lat = numberAt(row[setup.latField]); - const lon = numberAt(row[setup.lonField]); - if (lat != null && lon != null) at = { lat, lon }; - } else if (setup?.coordField) { - at = assets.parse(row[setup.coordField]); - } else { - const lat = numberAt(row.lat); - const lon = numberAt(row.lon); - if (lat != null && lon != null) at = { lat, lon }; - } - if (!at || Math.abs(at.lat) > 85.05112878 || Math.abs(at.lon) > 180) continue; - const projected = assets.project(at.lon, at.lat); - points.push({ - pid: row.pid, - title: String(row[identityKey] ?? `Record ${row.pid}`), - x: projected.x, - y: projected.y, - }); - } - - let minX = 0; - let minY = 850; - let width = 4096; - let height = 1450; - if (points.length) { - const xs = points.map((point) => point.x); - const ys = points.map((point) => point.y); - minX = Math.min(...xs); - minY = Math.min(...ys); - width = Math.max(420, Math.max(...xs) - minX); - height = Math.max(260, Math.max(...ys) - minY); - const pad = Math.max(width, height) * 0.18; - minX -= pad; - minY -= pad; - width += pad * 2; - height += pad * 2; - const ratio = 1.72; - if (width / height < ratio) { - const next = height * ratio; - minX -= (next - width) / 2; - width = next; - } else { - const next = width / ratio; - minY -= (next - height) / 2; - height = next; - } - } - const radius = Math.max(width, height) / 125; - const missing = rows.length - points.length; - return ( -
- - - - {assets.lakes.map((path, index) => ( - - ))} - {points.map((point) => ( - - {point.title} - - ))} - - {missing > 0 && ( - - {`${missing.toLocaleString()} matching ${missing === 1 ? "record has" : "records have"} no location`} - - )} - {rows.length === 0 &&
No records match this cell.
} -
- ); -} - /** * A Sheet binding names a DATABASE KEY; `LinkGridModal` wants a `SurfaceScope`. The two are not * the same vocabulary and the difference is only visible for the two compiled modules. @@ -375,7 +180,7 @@ export type DrillCellScope = ( | { kind: "view"; name: string } ) & { - /** W55-T07: the cell binding's own display bag, never the saved View's config. */ + /** W56-T24: accepted legacy cell display bag; the grid now owns presentation itself. */ display?: BindingDisplay; }; @@ -403,33 +208,28 @@ const sameTree = (a: FilterTree | null, b: FilterTree | null): boolean => * The sentence is the whole of the owner's first clause, so it takes the width and truncates with * an ellipsis rather than being shortened into a count; the full text stays reachable as the * element's `title`. W55-T07 moves Edit filter to the top-right toolbar and leaves this band one - * statement with one job. + * statement with one job. W56-T24 seats it inside `LinkGridModal`'s footer slot, so that shell now + * supplies the `cg-link-grid-foot` paint instead of this child impersonating the footer itself. */ function DrillFilterBand( { text }: { text: string }, ) { return ( -
- - {text} - -
+ {text} + ); } @@ -465,16 +265,15 @@ export interface DrillModalProps { */ onFilterChange?: (addr: string, tree: FilterTree) => void | Promise; /** - * W55-T07 / R6: persist presentation on this cell's binding. The current Sheet host does not - * expose this writer yet, so absence leaves a working session-local switch and no false save - * claim; the typed seam is what the host must connect to its existing one-cell binding writer. + * W56-T24 moved presentation to the Data grid's own switcher. This accepted-but-unused seam stays + * optional so an existing Sheet host does not need a coordinated edit. */ onDisplayChange?: (addr: string, display: BindingDisplay) => void | Promise; } export default function DrillModal( { - workbookId, addr, label, onClose, onSettled, cellScope, onFilterChange, onDisplayChange, + workbookId, addr, label, onClose, onSettled, cellScope, onFilterChange, }: DrillModalProps, ) { const [drill, setDrill] = useState(null); @@ -490,28 +289,6 @@ export default function DrillModal( /** Same reason, one ticket later: the page hands this an inline arrow too. */ const filterChangeRef = useRef(onFilterChange); filterChangeRef.current = onFilterChange; - const displayChangeRef = useRef(onDisplayChange); - displayChangeRef.current = onDisplayChange; - - // R6: hydrate from the binding seam, not from a database View and not from localStorage. - const displayKey = JSON.stringify(cellScope?.display ?? null); - const hydratedDisplayRef = useRef(""); - const [cellDisplay, setCellDisplay] = useState( - () => cellScope?.display ?? { mode: "grid", visible: [] }, - ); - useEffect(() => { - const key = `${workbookId}:${addr}:${displayKey}`; - if (hydratedDisplayRef.current === key) return; - hydratedDisplayRef.current = key; - setCellDisplay(cellScope?.display ?? { mode: "grid", visible: [] }); - }, [addr, cellScope?.display, displayKey, workbookId]); - - const changeDisplay = useCallback((next: BindingDisplay) => { - setCellDisplay(next); - // No callback means no durable writer. The switch still answers the current gesture, but it - // never falls back to a second browser store that would violate R6's cell-local contract. - void Promise.resolve(displayChangeRef.current?.(addr, next)); - }, [addr]); // ── W54-T35 state ───────────────────────────────────────────────────────────────────────── /** Is the centred filter dialog on screen? */ @@ -541,19 +318,20 @@ export default function DrillModal( const [undoTree, setUndoTree] = useState(null); /** The tree as it stood when the Edit door was last opened. See `openFilter`. */ const preEditRef = useRef(null); + /** Latest grid-owned filter edit waiting for 800 ms of quiet before it reaches the cell. */ + const pendingCellFilterRef = useRef(null); + const cellFilterTimerRef = useRef(null); /** Bumped when a filter change has landed, so the rows are read again. */ const [reloadSeq, setReloadSeq] = useState(0); /** The filter kit's two vocabularies for this database. Fetched once the drill has answered. */ const [fields, setFields] = useState([]); const [statusValues, setStatusValues] = useState>({}); - /** Raw, permission-scoped rows back the List, Map and export projections. */ + /** Raw, permission-scoped rows back the export projection. */ const [rawRows, setRawRows] = useState([]); const [workspace, setWorkspace] = useState(null); const [rowsResolved, setRowsResolved] = useState(false); const [rowsError, setRowsError] = useState(""); const [today, setToday] = useState(undefined); - const [mapAssets, setMapAssets] = useState(null); - const [mapError, setMapError] = useState(false); useEffect(() => { let live = true; @@ -643,6 +421,9 @@ export default function DrillModal( const shown = cellScope ?? scopeFromDrill(drill); const shownKind = shown?.kind ?? ""; const shownTree = shown?.kind === "filter" ? shown.tree : null; + /** The cell's current tree at the instant a delayed grid edit settles. */ + const shownTreeRef = useRef(shownTree); + shownTreeRef.current = shownTree; /** * ⭐ THE FIELD AND VALUE VOCABULARIES, FETCHED THE WAY `BindingEditor` FETCHES THEM, and warmed @@ -671,7 +452,7 @@ export default function DrillModal( ]); if (!live) return; if (!ws && !rowsPayload) { - setRowsError("These records could not be loaded for List, Map or Export."); + setRowsError("These records could not be loaded for Export."); setRowsResolved(true); return; } @@ -699,32 +480,44 @@ export default function DrillModal( return () => { live = false; }; }, [scope]); - /** Load only the two leaf geometry modules when Map is actually selected. */ - useEffect(() => { - if (cellDisplay.mode !== "map" || mapAssets) return; - let live = true; - setMapError(false); - void Promise.all([ - import("../customer-grid/mapGeometry"), - import("../customer-grid/mapProjection"), - ]).then(([geometry, projection]) => { - if (!live) return; - setMapAssets({ - land: geometry.LAND_PATH, - lakes: geometry.LAKE_PATHS, - project: projection.project, - parse: (value) => projection.parseLatLon(value as Row[keyof Row]), - }); - }, () => { if (live) setMapError(true); }); - return () => { live = false; }; - }, [cellDisplay.mode, mapAssets]); - /** Persist a tree through the page's one binding writer, then read the rows again. */ const applyTree = useCallback(async (tree: FilterTree) => { await Promise.resolve(filterChangeRef.current?.(addr, tree)); setReloadSeq((n) => n + 1); }, [addr]); + /** + * The grid filter panel reports every change. The cell commits only after the edit has been + * quiet for 800 ms, so typing one condition produces one write and one re-drill. + */ + const settleCellFilter = useCallback((tree: FilterTree) => { + const current = shownTreeRef.current; + if (!current) return; + if (cellFilterTimerRef.current === null) { + // One burst gets one undo step: the tree held before its first reported change. + preEditRef.current = current; + } else { + window.clearTimeout(cellFilterTimerRef.current); + } + pendingCellFilterRef.current = tree; + cellFilterTimerRef.current = window.setTimeout(() => { + cellFilterTimerRef.current = null; + const next = pendingCellFilterRef.current; + pendingCellFilterRef.current = null; + const currentTree = shownTreeRef.current; + if (!next || !currentTree || sameTree(next, currentTree)) return; + setUndoTree(preEditRef.current); + void applyTree(next); + }, 800); + }, [applyTree]); + + useEffect(() => () => { + if (cellFilterTimerRef.current !== null) + window.clearTimeout(cellFilterTimerRef.current); + cellFilterTimerRef.current = null; + pendingCellFilterRef.current = null; + }, []); + /** * ⛔ CLOSING THE DIALOG IS THE COMMIT, and an unchanged tree commits nothing. Without that test * 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( return () => window.removeEventListener("keydown", onKey, true); }, []); - /** - * ⭐ THE CARD THE BAND IS PORTALLED INTO. `LinkGridModal` publishes - * `data-overlay-kind="linked-record-grid"` on its own `
`, so this identifies it by the - * attribute it already declares rather than by a class the stylesheet owns. - * - * ⚠ ONE RETRY ON THE NEXT FRAME, AND NO MORE. Effects run after commit, so the card is normally - * in the DOM by the time this runs; the frame is there for the commit in which Suspense reveals - * the chunk. A poll would be a component watching for a sibling forever. - */ - const showRows = Boolean(drill && scope && linkReady); - const [host, setHost] = useState(null); - useEffect(() => { - if (!showRows) { - setHost(null); - return; - } - const find = () => - document.querySelector('[data-overlay-kind="linked-record-grid"]'); - const found = find(); - if (found) { - setHost(found); - return; - } - const frame = window.requestAnimationFrame(() => setHost(find())); - return () => window.cancelAnimationFrame(frame); - }, [showRows]); - - const headerHost = host?.querySelector(".cg-link-grid-head") ?? null; - const bodyHost = host?.querySelector(".cg-link-grid-body") ?? null; - useEffect(() => { - if (!bodyHost) return; - bodyHost.classList.add("sheet-cell-view-custom"); - return () => bodyHost.classList.remove("sheet-cell-view-custom"); - }, [bodyHost]); - /** Exact record order from the drill answer; a topic payload is only the row book. */ const recordRows = useMemo(() => { if (!drill) return []; @@ -857,7 +615,7 @@ export default function DrillModal( .map((field) => field.key); const visibleKeys = cellViewVisibleKeys( defaultFieldKeys, - cellDisplay.visible, + [], forcedFieldKeys, fields.map((field) => field.key), identityField?.key ?? "", @@ -865,14 +623,6 @@ export default function DrillModal( const visibleFields = visibleKeys .map((key) => fields.find((field) => field.key === key)) .filter((field): field is Field => Boolean(field)); - const mapSetup = (workspace?.mapSetup ?? null) as CellMapSetup | null; - const fieldKeys = new Set(fields.map((field) => field.key)); - const mapSupported = Boolean( - (mapSetup?.latField && mapSetup.lonField - && fieldKeys.has(mapSetup.latField) && fieldKeys.has(mapSetup.lonField)) - || (mapSetup?.coordField && fieldKeys.has(mapSetup.coordField)) - || (fieldKeys.has("lat") && fieldKeys.has("lon")), - ); // CustomerGrid's own value-edit predicate. It distinguishes source-locked values, machine- // 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( }); }, [canEditRows, drill, onClose]); - const fieldsButtonRef = useRef(null); const exportButtonRef = useRef(null); - const [fieldsOpen, setFieldsOpen] = useState(false); const [exportOpen, setExportOpen] = useState(false); const [exporting, setExporting] = useState(false); - const setMode = useCallback((mode: CellViewMode) => { - if (mode === "map" && rowsResolved && !mapSupported) return; - changeDisplay({ ...cellDisplay, mode }); - }, [cellDisplay, changeDisplay, mapSupported, rowsResolved]); - - const setFieldVisible = useCallback((key: string, checked: boolean) => { - if (!identityField || forcedFieldKeys.includes(key) || key === identityField.key) return; - const chosen = new Set(visibleKeys); - if (checked) chosen.add(key); - else chosen.delete(key); - changeDisplay({ - ...cellDisplay, - visible: fields.map((field) => field.key).filter((fieldKey) => chosen.has(fieldKey)), - }); - }, [cellDisplay, changeDisplay, fields, forcedFieldKeys, identityField, visibleKeys]); - const exportCell = useCallback(async (format: "csv" | "xlsx" | "pdf" | "json") => { if (!allRowsLoaded || exporting) return; setExportOpen(false); @@ -1006,171 +738,59 @@ export default function DrillModal( table={scope} recordIds={drill.record_ids} editable={false} - onClose={onClose} - /> - - {headerHost && createPortal( -
-
- {CELL_VIEW_MODES.map((mode) => { - const unavailable = mode === "map" && (!rowsResolved || !mapSupported); - return ( - + {canEditRows && ( + - ); - })} -
- - - {canEditRows && ( - - )} - -
, - headerHost, - )} - {bodyHost && createPortal( -
- {!rowsResolved ? ( -
- -
- ) : rowsError ? ( -
{rowsError}
- ) : cellDisplay.mode === "grid" ? ( - - ) : cellDisplay.mode === "list" ? ( - - ) : mapSupported && mapError ? ( -
- Map could not be loaded. -
- ) : mapSupported ? ( - - ) : ( -
- Map needs latitude and longitude fields in this database. + )} +
)} - {rowsResolved && !rowsError && !allRowsLoaded && ( -
- {`${recordRows.length.toLocaleString()} of ${(drill?.record_ids.length ?? 0).toLocaleString()} matching records are loaded.`} -
- )} -
, - bodyHost, - )} - {fieldsOpen && fieldsButtonRef.current && ( - setFieldsOpen(false)} - role="dialog" - ariaLabel="Fields shown in this cell" - dataKind="sheet-cell-fields" - > -
Fields shown in this cell
-
- {fields.map((field) => { - const forced = field.key === identityField?.key || forcedFieldKeys.includes(field.key); - return ( - - ); - })} -
-
- )} + footer={bandText ? : undefined} + onClose={onClose} + /> + {exportOpen && exportButtonRef.current && ( )} - {host && bandText && createPortal( - , - host, - )} {filterOpen && draft && ( ReactNode; group: (name: string, body: ReactNode, extra?: string) => ReactNode; word: (text: string) => ReactNode; @@ -335,6 +349,16 @@ function IconRefresh() { ); } +/** A document leaving through a downward arrow, in the same hand-drawn line style as Refresh. */ +function IconExport() { + return ( + + ); +} + /** * ⭐ W52-T15 (instruction 26, contract C4) — THE SAME MARK THE DATA MODULE'S FULL SCREEN CONTROL * WEARS. `customer-grid/Toolbar.tsx::IconFullScreen` draws this exact path (four corner brackets @@ -375,6 +399,18 @@ export default function Ribbon({ * render-time TypeError. */ const [anchorEl, setAnchorEl] = useState(null); + /** + * The scan is cached against the exact document door that produced it. A changed tab/cell map + * supplies a new memoized door, making the old answer unknown without paying for another scan + * during render. `null` means the completed scan found an empty sheet. + */ + const [exportScan, setExportScan] = useState<{ + door: RibbonInsertDoor; + range: UsedSheetRange | null; + } | null>(null); + const [exportScope, setExportScope] = useState<"sheet" | "selection">("sheet"); + const exportRange = exportScan && exportScan.door === insert ? exportScan.range : undefined; + const exportUnavailable = !insert || exportRange === null; const [collapsed, setCollapsed] = useState(readCollapsed); const [formulaBarVisible, setFormulaBarVisible] = useState(readFormulaBar); const rootRef = useRef(null); @@ -399,15 +435,16 @@ export default function Ribbon({ /** * The keys the arrows may reach right now. Collapsed, that is the strip and nothing else — and - * the strip now carries Import, Refresh and Full screen too, since W52-T15 moved them there. + * the strip now carries Import, Refresh, Export and Full screen too. * Expanded, it is the strip plus the controls of the tab that is actually showing, read off its * own descriptor rather than a list kept beside it. Import is only in the order on a page that * actually has an import door, in both branches. */ const reachable = useMemo( () => (collapsed ? STRIP : [...STRIP, ...activeTab.keys]) - .filter((key) => key !== "import" || canImport), - [activeTab, canImport, collapsed], + .filter((key) => (key !== "import" || canImport) + && (key !== "export" || !exportUnavailable)), + [activeTab, canImport, collapsed, exportUnavailable], ); // ⛔ FOCUS MUST LAND ON SOMETHING THAT EXISTS. Collapsing while the focus sits on a control that @@ -536,6 +573,23 @@ export default function Ribbon({ setOpen((was) => (was === which ? "" : which)); }; + /** + * The used-range walk costs up to two million cell reads, so it belongs to the opening gesture, + * never render. An empty result leaves a real disabled Export control instead of downloading a + * blank row. Clicking an already open trigger only closes it and does not repeat the scan. + */ + const toggleExport = (event: ReactMouseEvent) => { + if (open === "export") { + openPop("export")(event); + return; + } + if (!insert) return; + const range = usedRange(insert.cellAt); + setExportScan({ door: insert, range }); + setExportScope("sheet"); + if (range) openPop("export")(event); + }; + /** * One control. `data-ribbon` is what the roving handler finds; `tabIndex` is the roving part. * @@ -553,12 +607,13 @@ export default function Ribbon({ body: ReactNode, // ⚠ W53-T07 widened this from `() => void`. A zero-argument lambda is assignable to a // one-argument function type, so every existing call site compiles unchanged; only the - // nine popover triggers actually read the event, for `event.currentTarget` as the anchor. + // popover triggers actually read the event, for `event.currentTarget` as the anchor. onClick: (event: ReactMouseEvent) => void, pressed?: boolean, expanded?: boolean, kt?: string, ktOpens?: "gallery", + controlDisabled?: boolean, ) => ( ) : null} + {onDelete ? ( + + ) : null} {onResize ? ( + )} + {view === "functions" && initialView === "categories" && ( + + )} +

{title}

+
+ + {!catalogue && ( +

Loading functions

+ )} + + {catalogue?.fallback && ( +

+ Showing the built in list. The server catalogue could not be reached. +

+ )} + + {catalogue && view === "categories" && ( +
+ {categories.map((entry, index) => ( + + ))} +
+ )} + + {catalogue && view === "functions" && ( + <> + setQuery(event.target.value)} + onKeyDown={(event) => { + if (event.key !== "ArrowDown") return; + const first = document.getElementById(listId) + ?.querySelector('button[role="option"]'); + if (first) { + event.preventDefault(); + first.focus(); + } + }} + /> +
+ {visibleFunctions.map((fn) => ( + + ))} + {visibleFunctions.length === 0 && ( +

No functions match this search.

+ )} +
+ + )} + + {catalogue && view === "arguments" && chosen && ( +
+

{chosen.signature}

+ {fields.map((field, index) => ( + + ))} + +
+ )} + + ); +} + export const formulasGroups = (ctx: RibbonTabContext) => { - const { act, control, group, unavailable, word } = ctx; + const { act, anchorEl, closePop, control, group, insert, open, openPop, word } = ctx; + const canInsert = !!insert?.selection; return ( <> {group("Function library", ( <> - {unavailable("Insert function", word("Insert function"))} + +
+ {control( + "formula-insert", "Insert function", <>{word("Insert function")}, + openPop("formula-insert"), false, open === "formula-insert", "FI", "gallery", + )} +
+ {open === "formula-insert" && insert?.selection && ( + + )} +
{control( "formula-autosum", "AutoSum", <>{word("AutoSum")}, () => act("autosum"), false, undefined, "U", )} - {unavailable("More functions", word("More functions"))} + +
+ {control( + "formula-logical", "Logical", word("Logical"), openPop("formula-logical"), + false, open === "formula-logical", "L", "gallery", + )} +
+ {open === "formula-logical" && insert?.selection && ( + + )} +
+ +
+ {control( + "formula-text", "Text", word("Text"), openPop("formula-text"), + false, open === "formula-text", "T", "gallery", + )} +
+ {open === "formula-text" && insert?.selection && ( + + )} +
+ +
+ {control( + "formula-date", "Date", word("Date"), openPop("formula-date"), + false, open === "formula-date", "D", "gallery", + )} +
+ {open === "formula-date" && insert?.selection && ( + + )} +
+ +
+ {control( + "formula-lookup", "Lookup", word("Lookup"), openPop("formula-lookup"), + false, open === "formula-lookup", "K", "gallery", + )} +
+ {open === "formula-lookup" && insert?.selection && ( + + )} +
+ +
+ {control( + "formula-math", "Math", word("Math"), openPop("formula-math"), + false, open === "formula-math", "MH", "gallery", + )} +
+ {open === "formula-math" && insert?.selection && ( + + )} +
+ +
+ {control( + "formula-more", "More functions", <>{word("More functions")}, + openPop("formula-more"), false, open === "formula-more", "FM", "gallery", + )} +
+ {open === "formula-more" && insert?.selection && ( + + )} +
))} - {group("Name manager", unavailable("Name manager", word("Name manager")))} - {group("Show formulas", unavailable("Show formulas", word("Show formulas")))} - {group("Data", ( - <> - {control( - "formula-refresh", "Calculate now", <>{word("Calculate now")}, - () => act("refresh"), false, undefined, "C", - )} - {unavailable("Calculation options", word("Calculation options"))} - + {group("Calculation", ( + control( + "formula-refresh", "Calculate now", <>{word("Calculate now")}, + () => act("refresh"), false, undefined, "C", + ) ))} ); diff --git a/web/src/sheet/ribbonIcons.tsx b/web/src/sheet/ribbonIcons.tsx index 7ebd5d574048dce9dde35241968a24f7b083a75a..ce83a3da1fae1a1b842427121d8e14e921ce1119 100644 --- a/web/src/sheet/ribbonIcons.tsx +++ b/web/src/sheet/ribbonIcons.tsx @@ -7,12 +7,14 @@ // rebuild needs, in a new file so the growing icon set does not keep making an already-long // component file longer. `viewBox="0 0 16 16"`, `aria-hidden="true"`, `className="sheet-ribbon-icon"` // (stroke: currentColor, fill: none — declared once in `styles/wave50/sheet.css`), 1-3 simple -// paths. Never lucide, never an icon font, never traced pixel-for-pixel from a screenshot. +// paths. Never lucide, never an icon font, never traced pixel-for-pixel from a screenshot. Accent +// classes carry category and destructive semantics while the hand-drawn geometry stays reusable. /** A clipboard holding a page: the clip at top, three rule lines standing in for pasted text. */ export function IconPaste() { return (

Map each Application role to a field in {schema.value.label}.

+ {template.kind === "route" ? ( +

Coordinates are used when present, and you can look up the address for selected records when they are empty.

+ ) : null} {template.fieldRoles.map((role) => { const options = schema.value.fields.filter((field) => !role.types.length || role.types.includes(field.type.toLowerCase()), @@ -537,6 +543,11 @@ function ApplicationWizard({ Routing needs both coordinate fields or neither, and they must be different.

) : null} + {routeLocationError ? ( +

+ Choose both coordinate fields or an address field. +

+ ) : null}
) : null} @@ -781,8 +792,8 @@ const findAutomation = (entries: NavEntry[]) => * `degraded` are UNCHANGED: they draw the real rows with their unavailable arms, because there * the answer has arrived and is bad news, which is a fact worth showing rather than a wait. * - * ⚠ The count is the rail's own maximum, not a guess. WAVE 55 instruction 2 fixes it at **8**: - * Home · Inbox · Assistant · Sheet · Data · Agents · App · Connectors. Starred moved into Home's + * ⚠ The count is the rail's own maximum, not a guess. WAVE 56 instruction 20 fixes it at **8**: + * Home · Inbox · Assistant · Sheet · Data · App · Agents · Connectors. Starred moved into Home's * filter, while App became the tenant Application directory. * ⛔ KEEP THIS NUMBER >= THE SETTLED ROW COUNT AND NEVER BELOW IT. A skeleton one bar TALLER than * the settled rail is a shrink, which is fine; one bar SHORTER is the appear-from-nowhere shove @@ -886,12 +897,12 @@ function StranglerPage({ entry }: { entry: NavEntry }) { that vocabulary lives now. */ -/** The host's `auto_awesome` sparkle for the AI-assistant slot (app.py:8166). */ +/** The retained `is-spark` hook suppresses the parent stroke, so this dotted ring reuses the + * row's `currentColor` directly while the shared glyph rule still owns width and round caps. */ function SparkIcon() { return ( ); } @@ -2711,6 +2722,10 @@ function ShellFrame() { * W35-T03 leg all read it. */ const dbAt = !!active && dataDatabases.some((database) => database.key === active.key); + /** An App instance resolves through its database so the existing grid can render, but the route + * key remains the one rail authority. Without this guard Data and App both claim the same click. */ + const dataRailCurrent = route !== APP_ROUTE && + (dbAt || (!!active && dbEntries.some((entry) => entry.key === active.key))); return (
@@ -2856,7 +2871,7 @@ function ShellFrame() { {/* The Analyst slot closes the first rail group: Home / Inbox / Assistant. (app.py:8166 pins "AI assistant" over the nav tree, same label, - same sparkle). Wave 18 (owner item 3): the hand-off into Streamlit + now represented here by the dotted ring). Wave 18 (owner item 3): the hand-off into Streamlit is PAUSED — the click opens an in-app "under construction" note instead. The nav item, the registry row and the Streamlit Analyst page all stay (kept-not-ported, never delete); only the door is @@ -2945,9 +2960,10 @@ function ShellFrame() { Found again at the close-out dead-code sweep, which greps every deleted symbol and reads each survivor: this one was a stale CLAIM rather than a live caller. */} - {/* WAVE 55 instruction 2: Sheet starts the application-building group and remains an - unconditional chrome destination. It is followed by Data, Agents and App. The gate - reads rendered JSX with comments removed, so this note cannot satisfy the order. + {/* WAVE 56 instruction 20: Sheet starts the application-building group and remains an + unconditional chrome destination. It is followed by Data, App and Agents so the + fixed module band matches the owner's reading order without rewriting any route. + The gate reads rendered JSX with comments removed, so this note cannot satisfy the order. ⛔ AN `` LIKE CONNECTORS, UNCONDITIONAL, AND BOTH HALVES MATTER. A ` - {/* Agents stays permission-aware, but its literal position is now after Data. The label - still comes from the server registry when present; the unavailable arm names the - intended destination without inventing access. */} + + + App + + + {/* Agents stays permission-aware after App. Its label still comes from the server + registry when present; moving all three arms together prevents a missing grant from + changing the module band's order or spacing. */} {automation ? ( )} - - - App - -
{/* ⭐ WAVE 23 item 10 (R8, contract C11, wiring W23-W3) — CONNECTORS. diff --git a/web/src/shell/nav.ts b/web/src/shell/nav.ts index 969cbbcdfcab1d39681bfe325ab96dd58770fd7f..1918457c90c0cd05c0b1aeda83d8eef388e6143c 100644 --- a/web/src/shell/nav.ts +++ b/web/src/shell/nav.ts @@ -21,6 +21,7 @@ // --------------------------------------------------------------------------- import { API_V1, CREDENTIALS } from "../apiContract"; +import { APP_PATH_PREFIX } from "../customer-grid/dataPath"; // ⚠ WAVE 19 R8 / C1 — the icon vocabulary is the GRID's, imported not redefined. // A VALUE import (not type-only) because the whitelist has to exist at runtime: // `FolderMark` indexes `FOLDER_SHAPE_PATHS[shape]` and maps the result, so one @@ -1448,8 +1449,18 @@ export function routeKeyOf(hash: string): string { * answers null. One rewrite, never a cycle. */ export function rewrittenHash(hash: string): string | null { - const target = REWRITTEN_ROUTES[routeKeyOf(hash)]; - return target ? `#/${target}` : null; + const routeKey = routeKeyOf(hash); + const target = REWRITTEN_ROUTES[routeKey]; + if (target) return `#/${target}`; + if (routeKey !== "data") return null; + const queryAt = hash.indexOf("?"); + if (queryAt < 0) return null; + const query = hash.slice(queryAt + 1); + // Existing doors keep writing Data addresses; the shell moves only Application instances under + // App. Preserving the query byte-for-byte keeps one address vocabulary and the `app` key makes + // the next rewrite a no-op, so the established loop-safety contract still holds. + const application = new URLSearchParams(query).get("application")?.trim(); + return application ? `${APP_PATH_PREFIX}${query}` : null; } /** The current key for a hash that may name a retired one. Identity for everything else. */ diff --git a/web/src/styles/wave49/connectors.css b/web/src/styles/wave49/connectors.css index 0dacf4413a76971129f62b07a61ef082a8d709a1..30a6158d6e732aaa412309ee78e990a7a5ed21c8 100644 --- a/web/src/styles/wave49/connectors.css +++ b/web/src/styles/wave49/connectors.css @@ -101,6 +101,29 @@ border-bottom: 1px solid var(--lp-line); } +.conn-modal-save-actions { + display: inline-flex; + flex: 0 0 auto; + align-items: center; + gap: 10px; +} + +.conn-modal-save-actions .conn-db-link { + margin-top: 0; +} + +.conn-modal-save-actions button:disabled { + opacity: 0.48; + cursor: default; + text-decoration: none; +} + +.conn-modal-close:disabled, +.conn-modal-tab:disabled { + opacity: 0.48; + cursor: default; +} + .conn-modal-mark { display: inline-flex; align-items: center; @@ -347,6 +370,7 @@ .conn-rd-scroll { overflow: auto; + overscroll-behavior-x: contain; border: 1px solid var(--lp-line); border-radius: var(--lp-r-md); background: var(--lp-surface-2); @@ -1196,10 +1220,27 @@ .conn-db-head { display: flex; - align-items: center; + align-items: flex-start; + justify-content: space-between; gap: 10px; } +/* ⭐ W56-T33 — THE POPULATION SIGNAL IS THE WORD IN THE CELL, and these three rules are + reinforcement only. `Not counted yet` and `Empty` are printed in the row itself, so a reader + who cannot see weight or tint still gets the whole answer (DESIGN.md section 4). */ +.conn-db-row.is-populated .conn-db-src, +.conn-db-row.is-populated td { + font-weight: 600; +} + +.conn-db-row.is-empty td { + color: var(--lp-muted); +} + +.conn-db-row.is-uncounted td { + color: inherit; +} + /* The disclosure control. Native chrome reset in the base rule (DESIGN.md section 4): a class styled button that leaks UA border and background is the wave-19 item-3 bug. */ diff --git a/web/src/styles/wave49/sheet.css b/web/src/styles/wave49/sheet.css index 36536ffe5b1b47d1a758f2fa9e531d33ad0e1653..3ee8f969f55671e2ffb8f617ea26f11241d04ddc 100644 --- a/web/src/styles/wave49/sheet.css +++ b/web/src/styles/wave49/sheet.css @@ -587,7 +587,7 @@ Measured, so this is not a hypothetical: `drill_cell` costs 55 to 90 ms against a `ut_*` table and 9,248 to 9,448 ms against `customer_data`, which reads through the registry-module mirror - rather than DuckDB (`.claude/wiki/waves/wave54/lanes/E/T36-baseline.md`). For all of that, + rather than DuckDB (`AutoWiki/waves/wave54/lanes/E/T36-baseline.md`). For all of that, `DrillModal` rendered `null`. ⭐ TWO HALVES, THE WAY THE DESIGN CONTRACT SPLITS THEM. The CONTROL responds at pointer-down diff --git a/web/src/styles/wave50/sheet.css b/web/src/styles/wave50/sheet.css index 041107337db341fd4c3e177f2618f5996d22166f..a8085b1d0f813154b0bdb7aad533bc9a0abe4dd9 100644 --- a/web/src/styles/wave50/sheet.css +++ b/web/src/styles/wave50/sheet.css @@ -96,15 +96,34 @@ and no literal z-index: the popover rides `--cg-z-menu`, the same layer as the cell bar. */ .sheet-ribbon { + --sheet-icon-navy: var(--lp-blue-deep); /* interactive and structural */ + --sheet-icon-gold: var(--lp-yellow-deep); /* content and attention */ + --sheet-icon-danger: var(--lp-red-deep); /* destructive only */ flex: 0 0 auto; display: flex; - align-items: center; - gap: 1px; - padding: 4px 12px; border-bottom: 1px solid var(--lp-line); background: var(--lp-surface); } +/* The worksheet tab strip borrows the ribbon class but is not a ribbon band. Exclude it so the + five ribbon tabs share one row shape without overriding the strip's own spacing. */ +.sheet-ribbon:not(.sheet-tab-strip) { + --sheet-ribbon-band: 52px; + --sheet-ribbon-group-gap: 8px; + align-items: stretch; + gap: 0; + padding: 4px 8px; +} + +.sheet-ribbon:not(.sheet-tab-strip) .sheet-ribbon-group { + justify-content: flex-start; + gap: var(--sheet-ribbon-group-gap); +} + +.sheet-ribbon:not(.sheet-tab-strip) .sheet-ribbon-group-controls { + height: var(--sheet-ribbon-band); +} + .sheet-ribbon-btn { appearance: none; border: 0; @@ -148,6 +167,23 @@ stroke-linejoin: round; } +.sheet-ribbon .sheet-ribbon-icon { + color: var(--sheet-icon-navy); +} + +.sheet-ribbon-group[aria-label="Clipboard"] .sheet-ribbon-icon, +.sheet-ribbon-group[aria-label="Editing"] .sheet-ribbon-icon, +.sheet-ribbon-group[aria-label="Styles"] .sheet-ribbon-icon, +.sheet-ribbon-group[aria-label="Charts"] .sheet-ribbon-icon, +.sheet-ribbon-group[aria-label="Sparklines"] .sheet-ribbon-icon { + color: var(--sheet-icon-gold); +} + +/* Match the group accent's selector weight so destructive red wins inside Editing. */ +.sheet-ribbon-group .sheet-ribbon-icon.sheet-ribbon-icon--danger { + color: var(--sheet-icon-danger); +} + .sheet-ribbon-caret { width: 11px; height: 11px; diff --git a/web/src/styles/wave54/ribbon-home.css b/web/src/styles/wave54/ribbon-home.css index 3ea36d8e9252ce62c44672c6bfa9dce5a283cc33..b75b509c6bf0cab96a1aeb7cbe798bb0cab52a73 100644 --- a/web/src/styles/wave54/ribbon-home.css +++ b/web/src/styles/wave54/ribbon-home.css @@ -34,33 +34,19 @@ floated far BELOW their icons. Seven groups, seven different controls-to-label distances, which is exactly what DESIGN.md 4 forbids: controls in a row share height and baseline. - THE FIX IS ONE DECISION, DECLARED ONCE. `--sheet-ribbon-band` is the height every Home group's - control block takes, and `--sheet-ribbon-group-gap` is the distance from that block to the group - name. Both are read by a `.sheet-ribbon-home .sheet-ribbon-group*` selector, so they land on ALL - seven groups at once and no group carries a gap of its own. Change the rhythm here and the whole - ribbon moves together. - - ⭐ THE RIBBON DOES NOT GROW, AND THE ARITHMETIC IS THE PROOF. The strip's tallest group measured - 54px of controls plus a 2px gap plus an 11px name. It now measures 52px of controls plus a 4px - gap plus the same 11px name: 67px either way. The two pixels the gap gained are the two the - overshooting icon stack gave back, which is what "take it from the slack" means -- the band - itself is still the 52px the Alignment group's two 26px rows require, and no button changed - shape. `justify-content` becomes flex-start because a fixed band leaves nothing to distribute; - the gap token, not leftover space, is what now sets the distance. */ - -.sheet-ribbon-home { - --sheet-ribbon-band: 52px; - --sheet-ribbon-group-gap: 4px; -} - -.sheet-ribbon-home .sheet-ribbon-group { - justify-content: flex-start; - gap: var(--sheet-ribbon-group-gap); -} - -.sheet-ribbon-home .sheet-ribbon-group-controls { - height: var(--sheet-ribbon-band); -} + THE FIX REMAINS ONE DECISION. When wave 54 introduced the fixed band, the strip's tallest group + measured 54px of controls plus a 2px gap plus an 11px name. The replacement measured 52px of + controls plus a 4px gap plus the same 11px name: 67px either way. The two pixels the gap gained + were the two the overshooting icon stack gave back. The band itself stayed at the 52px the + Alignment group's two 26px rows require, and no button changed shape. + + `--sheet-ribbon-band` is now the fixed height every tab's group control block takes, and + `--sheet-ribbon-group-gap` is the shared distance from that block to the group name. Wave 55 + standardized that gap at 8px. Both tokens and their shared child rules now live on the ribbon + row in `styles/wave50/sheet.css`, so Home, Insert, Formulas, Data and View resolve one band and + one current gap. Insert was the tab that had no band of its own. `justify-content` is flex-start + because a fixed band leaves nothing to distribute; the gap token, not leftover space, sets the + distance. Change the shared rhythm there and all five tabs move together. */ /* -- The Clipboard group's split layout (W52-T16, instruction 18, ruling R4): a large Paste on the left, spanning close to the group's full height with its icon above a caption below, and @@ -142,7 +128,8 @@ the strip keeps its height. The `gap: 0` is deliberate for the same reason - a gap here would be the one thing that pushes past the band. ⚠ W54-T02 MOVED THE SOURCE OF THAT 52: it used to be a `min-height` on the large Paste button, which meant one group set the strip's height for all - seven; it is now the token declared at the top of this file, which every group reads. + seven; it is now the token on the shared ribbon row in `styles/wave50/sheet.css`, which every + group reads. ⚠ THE ROW DIVS CARRY NO PADDING. Horizontal rhythm stays with `.sheet-ribbon-group-controls`'s own `gap: 1px`, restated here rather than inherited because these rows are its GRANDCHILDREN diff --git a/web/src/styles/wave55/sheet.css b/web/src/styles/wave55/sheet.css index e99e4647f1d562aa1d3a48a3ff065000cdb48030..5c675f9aab7ba7ff62bd4b7b46f118bf84390bba 100644 --- a/web/src/styles/wave55/sheet.css +++ b/web/src/styles/wave55/sheet.css @@ -35,6 +35,7 @@ .sheet-tab-strip .sheet-ribbon-label { min-width: 0; + font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; diff --git a/web/src/styles/wave56/charts.css b/web/src/styles/wave56/charts.css new file mode 100644 index 0000000000000000000000000000000000000000..3845e2860b6eef0a6b118d67243b473a371476d5 --- /dev/null +++ b/web/src/styles/wave56/charts.css @@ -0,0 +1,74 @@ +/* + * Wave 56, lane B, W56-T08, ruling R6. + * This file exists because `.sheet-chart-anchor` has `pointer-events: none` in a stylesheet this + * lane may not edit. + */ + +/* + * R6 overrides the documented pointer transparency: the chart is now a real click target. The + * anchor handlers never take DOM focus, so the keyboard path to the cells underneath survives. + */ +.sheet-chart-anchor.sheet-chart-hit { + pointer-events: auto; +} + +.sheet-chart.is-selected { + outline: 2px solid var(--lp-blue-deep); + outline-offset: 1px; +} + +.sheet-chart.is-selected .sheet-chart-tool { + opacity: 1; +} + +/* + * W56-T10, and this rule was written by the LANE LEAD after looking at the frame rather than by + * the ticket's worker. `.sheet-chart-fields` is a two column grid, `116px minmax(0, 1fr)`, in a + * stylesheet this lane may not edit, so the caption W56-T10 added under the Data range input + * landed in the 116px LABEL column and wrapped to five lines beside the field. A caption belongs + * under the control it describes, across the whole row. This also straightens the pre-existing + * "Enter a cell range such as B2:E8." error caption, which had the same latent placement and was + * simply rarer to see. + */ +.sheet-chart-fields .sheet-chart-caption { + grid-column: 1 / -1; +} + +/* R6 gives deletion its destructive colour while keeping it on the dialog's ordinary surface. */ +.sheet-chart-delete { + margin-right: auto; + color: var(--lp-red-deep); + background: var(--lp-surface); +} + +.sheet-chart-delete:focus-visible { + outline: 2px solid var(--lp-blue-deep); + outline-offset: 1px; +} + +/* + * W56-T12, R6: category labels keep compensating for the chart draw scale, but end-anchored + * values must fit the 46-unit gutter set by `viz/SeriesChart`'s `PAD_L`. No lane owns that file + * this wave, so the value label is capped by the space it has rather than by taste: a clipped + * number is worse than a small one. Once the draw scale reaches 1, both labels land at the same + * size anyway. These rules stay scoped because `.pg-ax-lab` also belongs to Dashboard charts. + */ +.sheet-chart .pg-ax-lab { + font-size: calc(var(--lp-fs-2xs) / var(--sheet-chart-scale, 1)); +} + +.sheet-chart .pg-ax-lab[text-anchor="end"] { + font-size: var(--lp-fs-2xs); +} + +.sheet-chart .sheet-chart-cat { + font-size: calc(var(--lp-fs-2xs) / var(--sheet-chart-scale, 1)); +} + +.sheet-chart .pg-legend { + font-size: var(--lp-fs-xs); +} + +.sheet-chart .sheet-chart-foot { + font-size: var(--lp-fs-2xs); +} diff --git a/web/src/styles/wave56/ribbon-formulas.css b/web/src/styles/wave56/ribbon-formulas.css new file mode 100644 index 0000000000000000000000000000000000000000..c2b1498951ff5cbd981adcc13199d8755e57bf04 --- /dev/null +++ b/web/src/styles/wave56/ribbon-formulas.css @@ -0,0 +1,292 @@ +/* wave 56 -- the Formulas tab's catalogue picker (W56-T13). + + Imported by `sheet/ribbonFormulas.tsx` as a component-owned side effect. The picker is a + body-level `AnchoredOverlay`, so every selector that paints its contents is portal-safe and + does not depend on a ribbon ancestor. The shared `.sheet-ribbon-pop-portal` supplies the + overlay surface; this file owns only the picker layout and states. + + Tokens only: no literal font size, no literal colour and no invented z-index. Sentence case, + Inter by inheritance, restrained overlay depth, focus outlines that do not change border width, + and reduced-motion handling follow DESIGN.md sections 2 through 5. */ + +/* The Formulas row is the same species as Home and Insert. Its body class needs the three layout + rules those tabs own under their own scoped selectors. */ +.sheet-ribbon-formulas { + align-items: stretch; + gap: 0; + padding: 4px 8px; +} + +.sheet-ribbon-formulas .sheet-ribbon-btn { + gap: 4px; +} + +.sheet-ribbon-formulas .sheet-ribbon-label { + white-space: nowrap; +} + +/* One native disabled boundary per document-writing trigger. It has no visible box and does not + disturb the ribbon control's own dimensions or roving-focus key. */ +.sheet-formula-trigger-fence { + display: inline-flex; + min-inline-size: 0; + margin: 0; + padding: 0; + border: 0; +} + +.sheet-formula-picker { + z-index: var(--cg-z-overlay); + width: min(424px, calc(100vw - 16px)); + gap: 8px; + padding: 10px; + overflow: auto; +} + +.sheet-formula-picker-head { + display: flex; + align-items: center; + gap: 8px; + min-height: 24px; +} + +.sheet-formula-title { + margin: 0; + font-size: var(--lp-fs-sm); + line-height: 1.25; + font-weight: 600; + color: var(--lp-ink); +} + +.sheet-formula-status, +.sheet-formula-fallback, +.sheet-formula-empty, +.sheet-formula-signature { + margin: 0; + font-size: var(--lp-fs-2xs); + line-height: 1.4; +} + +.sheet-formula-status, +.sheet-formula-empty, +.sheet-formula-signature { + color: var(--lp-muted); +} + +.sheet-formula-fallback { + padding: 6px 8px; + color: var(--lp-ink); + background: var(--lp-surface-2); + border-radius: var(--lp-r-sm); +} + +/* Custom buttons reset native chrome before their own state rules. */ +.sheet-formula-back, +.sheet-formula-category, +.sheet-formula-option, +.sheet-formula-submit { + appearance: none; + border: 0; + background: transparent; + font: inherit; + color: inherit; + cursor: pointer; +} + +.sheet-formula-back { + flex: 0 0 auto; + padding: 3px 6px; + border-radius: var(--lp-r-sm); + font-size: var(--lp-fs-2xs); + color: var(--lp-blue-solid); +} + +.sheet-formula-categories { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 6px; +} + +.sheet-formula-category { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + min-width: 0; + padding: 8px 10px; + text-align: left; + font-size: var(--lp-fs-xs); + color: var(--lp-ink); + border: 1px solid var(--lp-line); + border-radius: var(--lp-r-md); +} + +.sheet-formula-count { + flex: 0 0 auto; + min-width: 2ch; + color: var(--lp-muted); + text-align: right; + font-variant-numeric: tabular-nums; +} + +.sheet-formula-search, +.sheet-formula-argument { + appearance: none; + width: 100%; + box-sizing: border-box; + padding: 6px 8px; + font: inherit; + font-size: var(--lp-fs-xs); + color: var(--lp-ink); + background: var(--lp-surface); + border: 1px solid var(--lp-line); + border-radius: var(--lp-r-sm); +} + +.sheet-formula-search::placeholder, +.sheet-formula-argument::placeholder { + color: var(--lp-muted); +} + +.sheet-formula-search:focus-visible, +.sheet-formula-argument:focus-visible, +.sheet-formula-back:focus-visible, +.sheet-formula-category:focus-visible, +.sheet-formula-option:focus-visible { + outline: 2px solid var(--lp-blue-deep); + outline-offset: 1px; +} + +.sheet-formula-list { + display: flex; + flex-direction: column; + max-height: 272px; + overflow-y: auto; + border: 1px solid var(--lp-line); + border-radius: var(--lp-r-md); +} + +.sheet-formula-option { + display: flex; + flex-direction: column; + gap: 3px; + width: 100%; + padding: 8px 10px; + text-align: left; + border-bottom: 1px solid var(--lp-line); + color: var(--lp-ink); +} + +.sheet-formula-option:last-of-type { + border-bottom: 0; +} + +.sheet-formula-option-line { + display: flex; + align-items: baseline; + gap: 8px; + min-width: 0; + font-size: var(--lp-fs-xs); +} + +.sheet-formula-option-line strong { + flex: 0 0 auto; + font-weight: 600; + color: var(--lp-blue-solid); +} + +.sheet-formula-option-line > span { + min-width: 0; + overflow: hidden; + color: var(--lp-muted); + text-overflow: ellipsis; + white-space: nowrap; +} + +.sheet-formula-description { + font-size: var(--lp-fs-2xs); + line-height: 1.35; + color: var(--lp-muted); +} + +.sheet-formula-empty { + padding: 12px 10px; +} + +.sheet-formula-arguments { + display: flex; + flex-direction: column; + gap: 8px; + max-height: 336px; + overflow-y: auto; + padding-right: 2px; +} + +.sheet-formula-arguments label { + display: flex; + flex-direction: column; + gap: 4px; +} + +.sheet-formula-argument-label { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + font-size: var(--lp-fs-2xs); + color: var(--lp-ink); +} + +.sheet-formula-argument-label > span:last-child { + color: var(--lp-muted); +} + +.sheet-formula-submit { + align-self: flex-start; + padding: 6px 12px; + border: 1px solid var(--lp-primary); + border-radius: var(--lp-r-md); + background: var(--lp-primary); + color: var(--lp-surface); + font-size: var(--lp-fs-xs); + font-weight: 600; +} + +.sheet-formula-submit:focus-visible { + outline: 2px solid var(--lp-primary); + outline-offset: 2px; +} + +.sheet-formula-submit:disabled { + opacity: 0.45; + cursor: not-allowed; +} + +@media (hover: hover) and (pointer: fine) { + .sheet-formula-back:hover, + .sheet-formula-category:hover, + .sheet-formula-option:hover { + background: var(--lp-surface-2); + } + + .sheet-formula-submit:hover:not(:disabled) { + border-color: var(--lp-primary-hover); + background: var(--lp-primary-hover); + } +} + +.sheet-formula-back:active, +.sheet-formula-category:active, +.sheet-formula-option:active, +.sheet-formula-submit:active:not(:disabled) { + transform: scale(0.97); +} + +@media (prefers-reduced-motion: reduce) { + .sheet-formula-back:active, + .sheet-formula-category:active, + .sheet-formula-option:active, + .sheet-formula-submit:active:not(:disabled) { + transform: none; + } +}