diff --git a/RELEASES.json b/RELEASES.json index 37197088ea8f7e64e3f177d97cdd2222d2be0d09..e4655b635e35e08e855b8ab6f62ac7479e63494d 100644 --- a/RELEASES.json +++ b/RELEASES.json @@ -1,4 +1,4 @@ { - "current": "859ae4071", + "current": "abfaec338", "releases": [] } \ No newline at end of file diff --git a/VERSION b/VERSION index b5ab5bb684a50c51e23d630c72065687350b0e40..4abf8bed63b2c8dd8e37bb46c01d436c7a33f420 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -859ae4071 +abfaec338 diff --git a/api/app_guide.py b/api/app_guide.py index be0164331a303f20f08a4bc2c0fca24152105973..d03bab7ad15cdbe229efb7259effd477f2e2f6d7 100644 --- a/api/app_guide.py +++ b/api/app_guide.py @@ -225,19 +225,16 @@ def _chart_guidance(): def _catalog_guidance(): """Append the same template library as the client and the current build argument schema.""" - from core import external_tools from loopy_catalog_tools import build_schema library = json.dumps(app_rules.catalog_templates(), ensure_ascii=True, indent=2) - collapsed, used = external_tools.guide_schema(build_schema()) - schema = json.dumps(collapsed, ensure_ascii=True, indent=2) - nodes = "\n" + external_tools.filter_node_guide() + "\n" if used else "" + schema = json.dumps(build_schema(), ensure_ascii=True, indent=2) return ("\n# Current Catalog template library\n\n" "These IDs, slots and design defaults also come from GET /api/v1/catalogs/templates.\n" f"```json\n{library}\n```\n" "\n# Current catalog_build argument schema\n\n" "This schema describes arguments only. Put about and intent beside action and arguments.\n" - f"```json\n{schema}\n```\n{nodes}") + f"```json\n{schema}\n```\n") def read(section=None): diff --git a/api/automation_engine.py b/api/automation_engine.py index d639b6bcff8550c2dadd8dbe1ba865947d373c7e..d4651aebe8fdcb8be6397f7dbee0d361b3e9b855 100644 --- a/api/automation_engine.py +++ b/api/automation_engine.py @@ -2518,6 +2518,8 @@ def clean_definition(raw, previous=None, username="", notes=None, rt=None): # a set the vendor is already building (and already counting against the funds gate). "state": dict(prev.get("state") or {}), "created": prev.get("created") or _authored_iso(), + # S76-T37: carried here, stamped only by `create` and `patch` (a re-clean is not an update). + "updatedAt": prev.get("updatedAt") or prev.get("created") or "", "createdBy": prev.get("createdBy") or username, # ⭐⭐ WAVE 35 · T37 — `system` IS STICKY ACROSS A PATCH, AND IT IS **NEVER READ FROM `raw`**. # @@ -3439,6 +3441,7 @@ def create(rt, raw, username="", notes=None): f"{RETIRED_KIND_REPLACEMENT.get(defn['kind'], '')}") # Retired run histories reserve their ids so a new definition cannot overwrite them. defn["id"] = _new_id(rt.get(STORE_KEY) or {}) + defn["updatedAt"] = defn.get("created") or _authored_iso() def _up(cur): cur = cur if isinstance(cur, dict) else {} @@ -3480,6 +3483,7 @@ def patch(rt, auto_id, raw, username="", notes=None): if err: return None, err defn["id"] = str(auto_id) + defn["updatedAt"] = _authored_iso() def _up(cur): cur = cur if isinstance(cur, dict) else {} diff --git a/api/external_freshness.py b/api/external_freshness.py index fe47226f83d5ca98f8417d166fc4f32de8fd5d5e..1b525b873777b92df91a3a997867890b98d66f47 100644 --- a/api/external_freshness.py +++ b/api/external_freshness.py @@ -59,6 +59,40 @@ def _sync_date(value): return None +def amazon_sync_stamp(cur, table_key): + """Read a table's last successful source pass before its legacy raw-table receipt.""" + import amazon_relational + + raw = amazon_relational.SOURCE.get(table_key) + if not raw or cur is None: + return None + marker = "amzn_sync_mark_" + raw.removeprefix("amzn_") + for entity in (marker, raw): + row = cur.execute("SELECT updated_at FROM _sync_state WHERE entity = ? AND phase = 'done'", + [entity]).fetchone() + if row: + return row[0] + return None + + +def _amazon_refreshes(session, keys): + """Read only sync metadata for the authorized Amazon databases on this tenant's cursor.""" + import assistant_mirror + + cur, refreshed = None, {} + for key in keys: + try: + if cur is None: + cur, refusal = assistant_mirror.open_cursor(session, key) + if refusal is not None or cur is None: + cur = None + continue + refreshed[key] = amazon_sync_stamp(cur, key) + except Exception: + continue + return refreshed + + def _mirror_refreshes(session, definitions, keys): """Read authorized mirror stamps with cached successful cursors and no product-row reads.""" import assistant_mirror @@ -149,7 +183,9 @@ def snapshot(session, databases): except Exception: docs[name] = {} odoo = odoo_relational.sync_freshness(user_tables.lend(rt, **docs)) - mirror_keys = {key for key in connected + amazon_keys = {key for key in connected if key.startswith("ut_amzn_")} + amazon = _amazon_refreshes(session, amazon_keys) if amazon_keys else {} + mirror_keys = {key for key in connected - amazon_keys if not user_tables.materialises(key, st=lent, defn=definitions[key])} mirror = _mirror_refreshes(session, definitions, mirror_keys) if mirror_keys else {} facts = {} @@ -168,7 +204,7 @@ def snapshot(session, databases): successes.append(odoo.get("lastGoodSyncAt")) if job.get("state") == "ready": successes.append(job.get("at")) - values = [mirror.get(key), *successes] + values = [amazon.get(key)] if key.startswith("ut_amzn_") else [mirror.get(key), *successes] stamp = next((stamp for value in values if (stamp := utc_stamp(value)) is not None), None) synced_on = next((day for value in values if (day := _sync_date(value)) is not None), None) if stamp is not None: @@ -203,6 +239,11 @@ def add(result, session, *, facts=None): result.pop("source_synced_on", None) result.pop("last_edited_at", None) result.update(source_synced_at=None, source_sync="never_synced") + if str(result.get("database") or "").startswith("ut_amzn_"): + if facts is None: + facts = snapshot(session, [result.get("database")]) + result.update(facts.get(result.get("database"), {})) + return result refreshed = _refresh_value(version) if kind == "mirror_user_table" else None if kind == "mirror_user_table" and isinstance(version, dict): stamp = utc_stamp(refreshed) diff --git a/api/intelligence_store.py b/api/intelligence_store.py index 13f177dcb17f3890156a43f86a72cd2e55474fb5..320b56eee128b0e82c2eec4aa809a2ecb4099a82 100644 --- a/api/intelligence_store.py +++ b/api/intelligence_store.py @@ -6,6 +6,7 @@ from functools import lru_cache from pathlib import Path import importlib import difflib +import hashlib import json import re @@ -267,10 +268,10 @@ def _document(raw): return raw -def _files(session, *, include_generated=False, wiki_only=False): +def _files(session, *, include_generated=False, wiki_only=False, raw=None): """Read authored files, adding reader-scoped system pages only for Wiki requests.""" try: - raw = _document(session.runtime.get(STORE_KEY)) + raw = _document(session.runtime.get(STORE_KEY) if raw is None else raw) _check_file_capacity(session, raw) import wiki_log files = _project_templates(session, raw) @@ -332,9 +333,9 @@ def _database_note_record(session, key, *, stored=None, with_body=False): if not definition or not can_read(session, {"reads": [definition["key"]]}): raise IntelligenceError("no_file", "This workspace has no file at that path.", 404) note = user_tables.shared_note("database", key, st=session.runtime) - if not note: + if not note or note.get("deleted"): raise IntelligenceError("no_file", "This workspace has no file at that path.", 404) - meta = {"title": definition["label"], "section": "database-notes", "owner": definition["owner"], + meta = {"title": note.get("title") or definition["label"], "section": "database-notes", "owner": definition["owner"], "description": f"Shared note for {definition['label']}.", "reads": [definition["key"]], "approvers": [], "approvals_needed": 1, "tools": [], "databaseKey": key} text = note.get("body") or "" @@ -391,7 +392,7 @@ def _database_note_file(session, path, *, version=0): "latestVersion": current["version"], "history": history, "versions": len(history), "limits": limits()} -def _put_database_note(session, key, body, actor, base_version, base_updated): +def _put_database_note(session, key, body, actor, base_version, base_updated, *, title=None, deleted=False): """Let the canonical writer enforce admission and its exact base on every atomic attempt.""" from core import user_tables @@ -409,7 +410,13 @@ def _put_database_note(session, key, body, actor, base_version, base_updated): prior = (_document(raw).get("database:" + key) or {}) if int(prior.get("version") or 0) != base_version or prior.get("updated") != base_updated: raise IntelligenceError("version_conflict", "The note changed. Reload it before saving.", 409) - return callback(raw) + updated = callback(raw) + note = updated["database:" + key] + if title is not None or prior.get("title"): + note["title"] = title if title is not None else prior["title"] + if deleted: + note["deleted"] = True + return updated return session.runtime.update(bucket, checked, **kwargs) @@ -694,6 +701,8 @@ def _row(record, entry=None, *, session=None): **{key: deepcopy(entry[key]) for key in ("agent", "onBehalfOf", "approvedBy", "proposalId", "restoredFrom") if key in entry}, "created": record["created"], "lastUsed": record.get("lastUsed"), **{key: record[key] for key in ("databaseKey", "canEdit", "revisionHistory") if key in record}, + "canEdit": bool(session and (record.get("canEdit") if "databaseKey" in record + else can_edit(session, _head(record)["metadata"]))), "versions": sum(session is None or can_read(session, version["metadata"]) for version in record["versions"]), "trimmed": record.get("trimmed", 0), **({"fieldCheck": _field_check(session, meta)} if session and meta.get("required_fields") else {})} @@ -728,7 +737,13 @@ def list_files(session, *, section="", query="", folder="", offset=0, limit=100, needle = str(query or "").strip().casefold() rows = [] wiki_requested = selected == "wiki" or prefix.casefold().startswith("wiki/") - for path, record in sorted(_files(session, include_generated=wiki_requested).items()): + try: + raw = _document(session.runtime.get(STORE_KEY)) + except IntelligenceError: + raise + except Exception: + raise IntelligenceError("store_unavailable", "Brain files could not be read. Try again.", 503) from None + for path, record in sorted(_files(session, include_generated=wiki_requested, raw=raw).items()): if not _head(record): continue meta = _head(record)["metadata"] @@ -745,7 +760,78 @@ def list_files(session, *, section="", query="", folder="", offset=0, limit=100, if direct: rows = [row for row in rows if "/" not in row["path"][len(prefix):]] return {"files": rows[offset:offset + limit], "total": len(rows), "offset": offset, - "limit": limit, "sections": sections(), "folders": folders, "limits": limits()} + "limit": limit, "sections": sections(), "folders": folders, "limits": limits(), + "canManageFolders": bool(getattr(session, "admin", False) and not trusted_identity(session)[1].get("agent")), + **({"folderRevision": _folder_revision(raw)} if getattr(session, "admin", False) else {})} + + +def _folder_revision(raw): + """Bind folder changes to the exact file identities and versions in their atomic update.""" + heads = [(path, record.get("created"), (_head(record) or {}).get("version", 0)) + for path, record in sorted(_document(raw).items())] + return int(hashlib.sha256(json.dumps(heads, sort_keys=True).encode()).hexdigest()[:13], 16) + + +def change_folder(caller, path, *, name=None, expected_revision): + """Rename a folder or promote its children in one revision-checked update.""" + session, identity = trusted_identity(caller) + _authorize(session) + if not session.admin or identity.get("agent"): + raise IntelligenceError("folder_admin_required", "Only an Administrator can change Brain folders.", 403) + if type(expected_revision) is not int or expected_revision < 0: + raise IntelligenceError("bad_revision", "Reload the folders before trying again.") + path = normalize_path(path, folder=True) + def reserved(folder): + folded = folder.casefold() + return (folded in ("database-notes", "wiki") or folded.startswith(DATABASE_NOTES_PREFIX) + or any(folded == root or folded.startswith(root + "/") + for root in ("wiki/log", "wiki/index", "wiki/purposes"))) + + if reserved(path): + raise IntelligenceError("folder_reserved", "This folder is maintained by the workspace.", 403) + parent = path.rpartition("/")[0] + target = parent + if name is not None: + name = normalize_path(name, folder=True) + if "/" in name: + raise IntelligenceError("bad_name", "Use one folder name without slashes.") + target = normalize_path((parent + "/" if parent else "") + name, folder=True) + if reserved(target): + raise IntelligenceError("folder_reserved", "This folder name is reserved.", 403) + + def move(raw): + files = dict(_document(raw)) + if _folder_revision(files) != expected_revision: + raise IntelligenceError("folder_revision_stale", "Folders changed. Reload before trying again.", 409) + prefix = path + "/" + projected = _project_templates(session, files) + if any(key.startswith(prefix) and key in _template_catalog() and _head(record) + for key, record in projected.items()): + raise IntelligenceError("folder_reserved", "This folder contains a maintained file.", 403) + moving = {key: record for key, record in files.items() if key.startswith(prefix)} + if not moving or not any(_head(record) for record in moving.values()): + raise IntelligenceError("no_folder", "This folder is no longer available.", 404) + if name is not None and target != path and any(key.startswith(target + "/") for key in projected): + raise IntelligenceError("folder_exists", "A folder with that name already exists.", 409) + destinations = {key: normalize_path((target + "/" if target else "") + key[len(prefix):]) for key in moving} + if any((destination in files and destination not in moving) or destination in _template_catalog() + for destination in destinations.values()): + raise IntelligenceError("file_exists", "A child has the same path as an existing file. Rename it first.", 409) + for key, record in moving.items(): + _assert_authored_path(key) + if key in _template_catalog() or (_head(record) or {}).get("metadata", {}).get("generated"): + raise IntelligenceError("folder_reserved", "This folder contains a maintained file.", 403) + del files[key] + for key, record in moving.items(): + destination = destinations[key] + _assert_authored_path(destination) + files[destination] = {**record, "path": destination, + "proposals": {pid: {**proposal, "path": destination} + for pid, proposal in (record.get("proposals") or {}).items()}} + return files + + _update(session, move) + return {"path": target} if name is not None else {"deleted": path} def _summaries(session): @@ -1859,15 +1945,76 @@ def decide_proposal(session, proposal_id, decision): return saved -def delete_file(caller, path): - """Delete one workspace file and its versions without touching agent files.""" +def rename_file(caller, path, title, *, expected_version): + """Append a title revision at the same path through the current file edit right.""" session, identity = trusted_identity(caller) _authorize(session) path = normalize_path(path) _assert_authored_path(path) + if not isinstance(title, str) or not title.strip() or len(title.strip()) > 200: + raise IntelligenceError("bad_title", "Use a title of 1 to 200 characters.") + if type(expected_version) is not int or expected_version < 1: + raise IntelligenceError("bad_version", "Reload the file before trying again.") if _database_note_path(path): - _database_note_file(session, path) - raise IntelligenceError("database_note_reserved", "A Database note belongs to its database.", 403) + if identity.get("agent"): + raise IntelligenceError("approval_required", "An agent cannot rename a shared note.", 403) + record = _database_note_record(session, path[len(DATABASE_NOTES_PREFIX):-3], with_body=True) + if record["path"] != path: + raise IntelligenceError("no_file", "This workspace has no file at that path.", 404) + entry = _head(record) + _put_database_note(session, record["databaseKey"], entry["body"], session.uname, + expected_version, entry["created"], title=title.strip()) + saved = _database_note_file(session, path) + _log_write(session, path, identity, expected_version, saved["version"]) + return saved + saved = {} + + def rename(raw): + saved.clear() + files = _editable_files(session, raw, path) + record = _readable_record(session, files, path) + head = _head(record) + if not can_edit(session, head["metadata"]): + raise IntelligenceError("file_read_only", "Your current rights do not allow renaming this file.", 403) + if head["version"] != expected_version: + raise IntelligenceError("version_conflict", "The file changed. Reload it before renaming.", 409) + if len(record["versions"]) >= MAX_VERSIONS: + raise IntelligenceError("too_many_versions", "This file already has 100 versions.", 409) + metadata = {**head["metadata"], "title": title.strip()} + body, metadata = prepare_markdown("---\n" + yaml.safe_dump(metadata, sort_keys=False, allow_unicode=True) + + "---\n" + head["body"].partition("\n---\n")[2], session.uname) + record = {**record, "versions": [*record["versions"], _entry(body, metadata, expected_version + 1, identity)], + "proposals": {key: {**row, "status": "stale"} if row["status"] in ("pending", "approving") else row + for key, row in (record.get("proposals") or {}).items()}} + files[path] = record + saved.update(_file(record, session=session)) + return files + + _update(session, rename) + _log_write(session, path, identity, expected_version, saved["version"]) + return saved + + +def delete_file(caller, path, *, expected_version=None): + """Delete an editable workspace file or clear its canonical database note.""" + session, identity = trusted_identity(caller) + _authorize(session) + path = normalize_path(path) + _assert_authored_path(path) + if expected_version is not None and (type(expected_version) is not int or expected_version < 1): + raise IntelligenceError("bad_version", "Reload the file before trying again.") + if _database_note_path(path): + if identity.get("agent"): + raise IntelligenceError("approval_required", "An agent cannot delete a shared note.", 403) + record = _database_note_record(session, path[len(DATABASE_NOTES_PREFIX):-3], with_body=True) + if record["path"] != path: + raise IntelligenceError("no_file", "This workspace has no file at that path.", 404) + entry = _head(record) + _put_database_note(session, record["databaseKey"], "", session.uname, + expected_version if expected_version is not None else entry["version"], + entry["created"], deleted=True) + _log_write(session, path, identity, entry["version"], None) + return {"deleted": path} removed = {} def remove(raw): @@ -1875,6 +2022,10 @@ def delete_file(caller, path): files = _editable_files(session, raw, path) record = _readable_record(session, files, path) removed["version"] = _head(record)["version"] + if not identity.get("agent") and not can_edit(session, _head(record)["metadata"]): + raise IntelligenceError("file_read_only", "Your current rights do not allow deleting this file.", 403) + if expected_version is not None and expected_version != removed["version"]: + raise IntelligenceError("version_conflict", "The file changed. Reload it before deleting.", 409) if identity.get("agent") and (record.get("memoryScope") != [identity["agent"], session.uname] or not _head(record) or _head(record)["metadata"]["section"] != "agent-memory"): raise IntelligenceError("approval_required", "An agent cannot delete a shared file.", 403) diff --git a/api/routes_agent_harness.py b/api/routes_agent_harness.py index 2c9e24f2423043046f40bc61d2b9c34e21b5fa93..e66826803af22a1dbbfb17dff29e486f389710c2 100644 --- a/api/routes_agent_harness.py +++ b/api/routes_agent_harness.py @@ -197,13 +197,54 @@ def decide_intelligence_proposal(proposal_id: str, decision: str, body: dict = B @router.delete("/intelligence/files") -def delete_intelligence_file(path: str = "", +def delete_intelligence_file(path: str = "", expectedVersion: int = None, session: Session = Depends(module_gate("intelligence"))): """Delete a workspace file under the Intelligence module grant.""" import intelligence_store as intelligence try: - return intelligence.delete_file(session, path) + if type(expectedVersion) is not int or expectedVersion < 1: + raise intelligence.IntelligenceError("bad_version", "Reload the file before trying again.") + return {"deleted": intelligence.delete_file(session, path, expected_version=expectedVersion)["deleted"]} + except intelligence.IntelligenceError as exc: + raise _intelligence_error(exc) from None + + +@router.patch("/intelligence/files") +def rename_intelligence_file(body: dict = Body(default=None), + session: Session = Depends(module_gate("intelligence"))): + import intelligence_store as intelligence + + body = body or {} + try: + return intelligence.rename_file(session, body.get("path"), body.get("title"), + expected_version=body.get("expectedVersion")) + except intelligence.IntelligenceError as exc: + raise _intelligence_error(exc) from None + + +@router.patch("/intelligence/folders") +def rename_intelligence_folder(body: dict = Body(default=None), + session: Session = Depends(module_gate("intelligence"))): + import intelligence_store as intelligence + + body = body or {} + try: + if "name" not in body or not isinstance(body["name"], str): + raise intelligence.IntelligenceError("bad_name", "Enter a folder name.") + return intelligence.change_folder(session, body.get("path"), name=body["name"], + expected_revision=body.get("expectedRevision")) + except intelligence.IntelligenceError as exc: + raise _intelligence_error(exc) from None + + +@router.delete("/intelligence/folders") +def delete_intelligence_folder(path: str = "", expectedRevision: int = None, + session: Session = Depends(module_gate("intelligence"))): + import intelligence_store as intelligence + + try: + return intelligence.change_folder(session, path, expected_revision=expectedRevision) except intelligence.IntelligenceError as exc: raise _intelligence_error(exc) from None diff --git a/api/routes_alerts.py b/api/routes_alerts.py index 8bc57edc2bb9e7b9698dbd519b969a3da5d4f1a8..630594e2be9e3863ae74b79451d5fa2abf27a253 100644 --- a/api/routes_alerts.py +++ b/api/routes_alerts.py @@ -279,34 +279,48 @@ def list_alerts(session: Session = Depends(require_session)): st=session.runtime)} -def _notification_visible(session, item): +def _notification_visible(session, item, *, memo=None): """Apply the current database admission doors without evaluating or changing alerts.""" from assistant_feed import _target target = _target(item) if not target: return True - module = str(target.get("module") or "") - database = (str(target.get("id") or "") if module == "database" else + module = str(target.get("module") or "").strip() + database = (str(target.get("id") or "").strip() if module == "database" else module if module.startswith("ut_") or module in {"customer_data", "product_data"} else "") if not database: return module != "database" + if memo is not None and database in memo["databases"]: + return memo["databases"][database] + visible = True try: session.require(database) if database.startswith("ut_"): from routes_tables import _defn_or_refuse - _defn_or_refuse(session, database, defs_only=True, scope_applied=True) + if memo is None: + _defn_or_refuse(session, database, defs_only=True, scope_applied=True) + else: + from core import user_tables + if memo["definitions"] is None: + memo["definitions"] = user_tables.lend_defs(session.runtime) + _defn_or_refuse(session, database, st=memo["definitions"], + defs_only=True, scope_applied=True) except HTTPException as exc: if exc.status_code in {403, 404, 409}: - return False - raise - return True + visible = False + else: + raise + if memo is not None: + memo["databases"][database] = visible + return visible @router.get("/notifications") def list_notifications(session: Session = Depends(require_session)): items = (session.runtime.get(alerts.NOTIFICATIONS_KEY) or {}).get(str(session.uname)) or [] + memo = {"databases": {}, "definitions": None} visible = [dict(item) for item in items if isinstance(item, dict) - and _notification_visible(session, item)] + and _notification_visible(session, item, memo=memo)] visible.sort(key=lambda item: str(item.get("at") or ""), reverse=True) return {"unread": sum(not item.get("read") for item in visible), "items": visible} diff --git a/api/routes_automation.py b/api/routes_automation.py index 741d49a7ab54308c7aae40fa7d251171989e03b8..c100952dcec45c352e3bedf66a6f603c8567c9ef 100644 --- a/api/routes_automation.py +++ b/api/routes_automation.py @@ -61,6 +61,29 @@ MODULE = "automation" _GATE = module_gate(MODULE) +def _item_rights(session, item): + """Use the item's owner for writes, with Administrator authority and system exclusions.""" + if item and item.get("id") == ODOO_SYNC_ID: + return {"edit": bool(session.admin), "delete": False} + editable = bool(item and session.uname and not item.get("system") and not item.get("retired") + and not str(item.get("id") or "").startswith(("field:", "system:")) + and not item.get("retiredOnceAt") and (session.admin or session.uname == + (item.get("createdBy") or item.get("created_by")))) + return {"edit": editable, "delete": editable} + + +def _require_item_edit(session, item): + if not item: + raise err(404, "unknown_automation", "This item is no longer available.") + if not _item_rights(session, item)["edit"]: + raise err(403, "automation_read_only", "Your current rights do not allow changes to this item.") + + +def _voice_item_rights(session, row, record): + row["capabilities"] = {**row.get("capabilities", {}), **_item_rights(session, record)} + return row + + def _governed_query_tool(session, database=""): """Adapt C4 dry-runs to B's mounted C2 Query door without owning Query authority.""" def invoke(prompt, context): @@ -248,8 +271,11 @@ def list_voice_agents(session: Session = Depends(_GATE)): """ rows = voice.list_browser_dtos(session.runtime) options = _voice_options(session) if rows else None + records = voice._store(session.runtime)["voice_agent"] if rows else {} for row in rows: row["audienceOptions"] = options + voice_id = row.get("automationId") or row.get("voiceAgentId") + _voice_item_rights(session, row, records.get(voice_id)) return {"voiceAgents": rows} @@ -264,6 +290,7 @@ def create_voice_agent(body: dict = Body(default=None), session: Session = Depen saved = voice.save_draft(session.runtime, body or {}, session.uname, tenant_id=session.tenant) row = voice.get_browser_dto(session.runtime, saved["id"]) row["audienceOptions"] = _voice_options(session) + _voice_item_rights(session, row, saved) return {"voiceAgent": row} except voice.VoiceRefusal as exc: raise err(400, "voice_refused", str(exc)) @@ -272,14 +299,36 @@ def create_voice_agent(body: dict = Body(default=None), session: Session = Depen @router.patch("/voice-agents/{voice_id}") def patch_voice_agent(voice_id: str, body: dict = Body(default=None), session: Session = Depends(_GATE)): try: - voice.patch_draft(session.runtime, voice_id, body or {}, session.uname) + record = voice._store(session.runtime)["voice_agent"].get(voice_id) + _require_item_edit(session, record) + saved = voice.patch_draft(session.runtime, voice_id, body or {}, session.uname) row = voice.get_browser_dto(session.runtime, voice_id) row["audienceOptions"] = _voice_options(session) + _voice_item_rights(session, row, saved) return {"voiceAgent": row} except voice.VoiceRefusal as exc: raise err(400 if "unknown" not in str(exc) else 404, "voice_refused", str(exc)) +@router.delete("/voice-agents/{voice_id}") +def delete_voice_agent(voice_id: str, session: Session = Depends(_GATE)): + """Remove a local Voice definition and disable local routes without changing provider resources.""" + def remove(doc): + _require_item_edit(session, doc["voice_agent"].get(voice_id)) + if any(row.get("voice_agent_id") == voice_id and row.get("state") == "active" + and row.get("expires_at", 0) > time.time() + for row in doc["voice_outbound_lease"].values()): + raise err(409, "voice_running", "Wait for this Voice agent's active work to finish.") + del doc["voice_agent"][voice_id] + for route in doc["voice_number_route"].values(): + if route.get("voice_agent_id") == voice_id: + route["status"] = "inactive" + return doc + + voice._update(session.runtime, remove) + return {"deleted": voice_id} + + @router.post("/voice-agents/{voice_id}/harness/dry-run") def voice_dry_run(voice_id: str, body: dict = Body(default=None), session: Session = Depends(_GATE)): body = body or {} @@ -485,7 +534,7 @@ def _sync_schedule_or_503(tenant, defn): f"Nothing was reported as armed: {exc}") -def _wire(defn, tenant, rt=None): +def _wire(defn, tenant, rt=None, session=None): """One automation, as the client reads it. `running` is PROCESS state, never store state — see the engine header on why a persisted 'running' is a permanent lock.""" live = engine.running(tenant, defn.get("id")) @@ -497,7 +546,7 @@ def _wire(defn, tenant, rt=None): status = {**status, "state": "running", "startedAt": live.get("startedAt"), "step": live.get("step")} agent_contract = engine.agent_contract_dto(rt, defn.get("id")) if rt else None - return { + row = { "id": defn.get("id"), "name": defn.get("name"), "kind": defn.get("kind"), "config": defn.get("config") or {}, "schedule": sched, "status": status, "runs": list(defn.get("runs") or [])[:engine.MAX_RUNS], @@ -600,6 +649,9 @@ def _wire(defn, tenant, rt=None): "This system Agent is configured at its source."} }), } + row["capabilities"] = {**row.get("capabilities", {}), + **(_item_rights(session, defn) if session else {"edit": False, "delete": False})} + return row #: ⭐⭐ WAVE 34 · CONTRACTS C3 + C4 — WHY A ROW CANNOT BE DELETED, as a slug. @@ -701,7 +753,7 @@ def _field_agent_rows(session): # — the exact way `awaitingResults` shipped inert for a whole wave. Passing the # synthetic DEFINITION through the same function makes them identical by # construction; only `system` is stamped afterwards, because no stored row has it. - row = _wire(defn_syn, session.tenant, rt=session.runtime) + row = _wire(defn_syn, session.tenant, rt=session.runtime, session=session) row["system"] = SYSTEM_FIELD_AGENT out.append(row) return out @@ -860,7 +912,7 @@ def _odoo_sync_row(session, detail=False): "config": {"connector": "odoo", "every": every, "frozen": frozen}}]}, } - row = _wire(defn, session.tenant, rt=session.runtime) + row = _wire(defn, session.tenant, rt=session.runtime, session=session) row["system"] = SYSTEM_ODOO_SYNC # ⛔ THE SENTENCE IS OVERRIDDEN, AND IT IS A FIX RATHER THAN A PREFERENCE. `compose_sentence` # speaks the automation vocabulary — it builds "When , run N actions" out of @@ -1319,7 +1371,7 @@ def list_automations(session: Session = Depends(_GATE)): pass _STATEMENTS_SEEDED.add(session.tenant) defs = engine.all_definitions(session.runtime) - items = [_wire(d, session.tenant, rt=session.runtime) for _, d in + items = [_wire(d, session.tenant, rt=session.runtime, session=session) for _, d in sorted(defs.items(), key=lambda kv: (kv[1].get("name") or "").lower())] # ⭐⭐ WAVE 34 · CONTRACT C3 (W34-T48) — field agents join the list as SYNTHETIC rows. # ⚠ MERGED AND RE-SORTED, not appended in a block at the end. R13 asks for a field agent to be @@ -2117,7 +2169,7 @@ def agent_author_action(auto_id: str, body: dict = Body(default=None), session.runtime.update(AGENT_ACTIONS_KEY, _set, flush="sync") _prune_marks(session, auto_id) - return {"automation": _wire(updated, session.tenant, rt=session.runtime), + return {"automation": _wire(updated, session.tenant, rt=session.runtime, session=session), "actionId": action_id, "agent": agent_id, "notes": notes} @@ -2188,7 +2240,7 @@ def get_automation(auto_id: str, session: Session = Depends(_GATE)): defn = engine.all_definitions(session.runtime).get(str(auto_id)) if defn is None: raise err(404, "unknown_automation", "no automation with that id") - return {"automation": _wire(defn, session.tenant, rt=session.runtime)} + return {"automation": _wire(defn, session.tenant, rt=session.runtime, session=session)} @router.post("/automations") @@ -2213,7 +2265,7 @@ def create_automation(body: dict = Body(default=None), session: Session = Depend engine.ensure_agent_contract(session.runtime, defn.get("id"), session.uname, defn.get("name") or "") _sync_schedule_or_503(session.tenant, defn) - return {"automation": _wire(defn, session.tenant, rt=session.runtime), "notes": _notes} + return {"automation": _wire(defn, session.tenant, rt=session.runtime, session=session), "notes": _notes} @router.patch("/automations/{auto_id}") @@ -2244,7 +2296,10 @@ def patch_automation(auto_id: str, body: dict = Body(default=None), # now but still the guard for any other caller of that function. if not _odoo_connected(session): raise err(404, "unknown_automation", "no automation with that id") + if not session.admin: + raise err(403, "automation_read_only", "Only an Administrator can change the connector schedule.") return _patch_odoo_sync(session, body or {}) + _require_item_edit(session, engine.all_definitions(session.runtime).get(str(auto_id))) # D-75, same channel as `create` above — an EDIT is where this matters most, because the # person has just typed the thing that gets dropped. # ⛔⛔ W36-T38 / R9 — THE AGENT-OWNED WALL, AT THE DOOR, BEFORE ANY WRITE. A `disabled` @@ -2265,7 +2320,7 @@ def patch_automation(auto_id: str, body: dict = Body(default=None), # and refuses an id nobody can see. _prune_marks(session, auto_id) _sync_schedule_or_503(session.tenant, defn) - return {"automation": _wire(defn, session.tenant, rt=session.runtime), "notes": _notes} + return {"automation": _wire(defn, session.tenant, rt=session.runtime, session=session), "notes": _notes} def _stored_agent_or_404(session, agent_id): @@ -2447,6 +2502,7 @@ def delete_automation(auto_id: str, session: Session = Depends(_GATE)): _sys = str(_defn.get("system") or "").strip() if _sys: raise err(409, "system_agent", engine.system_agent_refusal(_sys)) + _require_item_edit(session, _defn) engine.remove(session.runtime, auto_id) # R9's other half: the user MAY delete an agent-authored step, and deleting the whole # automation takes its annotations with it rather than stranding them in the document. @@ -2518,7 +2574,7 @@ def toggle_automation_node(auto_id: str, node_id: str, session: Session = Depend "unknown_automation" if error == "no such automation" else "node_not_toggleable", error) _sync_schedule_or_503(session.tenant, defn) - return {"automation": _wire(defn, session.tenant, rt=session.runtime)} + return {"automation": _wire(defn, session.tenant, rt=session.runtime, session=session)} @router.post("/automations/{auto_id}/hook/{token}") diff --git a/api/routes_external.py b/api/routes_external.py index c31671a60c75fb2ad0309e784be8af11c5f3b37e..083e281501ef0aa3331c4dae77e5443346516b14 100644 --- a/api/routes_external.py +++ b/api/routes_external.py @@ -156,10 +156,8 @@ class _PreviewRuntime: def _load(self, name): key = str(name) if key not in self._docs: - try: - value = self._real.get(key, fresh=True) - except TypeError: - value = self._real.get(key) + import application_registry + value = application_registry._read_strict(self._real, key) value = copy.deepcopy(value) self._initial[key] = copy.deepcopy(value) self._docs[key] = value @@ -174,6 +172,9 @@ class _PreviewRuntime: def get(self, name, *args, **kwargs): return copy.deepcopy(self._load(name)) + def _read_strict(self, name): + return self.get(name) + def get_projection(self, name, drop=()): value = self.get(name) if isinstance(value, dict): @@ -3120,12 +3121,12 @@ def _bucket_revision(st, key, fallback): return {"rev": None, "token": _json_digest(fallback)} -def _database_value_plan(session, database, record_id, values, fields): +def _database_value_plan(session, database, record_id, values, fields, *, apply_defaults=False): """Apply the grid's field/value vocabulary without calling its event side effects.""" from core import grid_events, user_tables import aios_grid - if not isinstance(values, dict) or not values: + if not isinstance(values, dict) or (not values and not apply_defaults): raise err(400, "tool_arguments_invalid", "Record values must be a non-empty object.") field_by_key = {str(field.get("key")): field for field in fields if isinstance(field, dict)} unknown = sorted(str(key) for key in values if str(key) not in field_by_key) @@ -3133,8 +3134,7 @@ def _database_value_plan(session, database, record_id, values, fields): raise err(403, "field_unavailable", "Every changed field must be readable and editable in this database.") ctx = _view_context(session, database, {"pid": record_id}) - planned = {} - for key, raw in values.items(): + for key in values: key = str(key) definition = field_by_key[key] if key in (ctx.hidden_keys or frozenset()) or not grid_events._may_edit_field_value( @@ -3143,6 +3143,26 @@ def _database_value_plan(session, database, record_id, values, fields): "Every changed field must be readable and editable in this database.") if user_tables.is_computed_cell(definition) or definition.get("type") == "automation": raise err(403, "computed_field", "A computed or automation field is read only.") + if apply_defaults: + editable = [definition for key, definition in field_by_key.items() + if key not in (ctx.hidden_keys or frozenset()) + and grid_events._may_edit_field_value(ctx, key, definition) + and not user_tables.is_computed_cell(definition) + and definition.get("type") != "automation"] + try: + expanded = user_tables._new_row_values(editable, values) + except ValueError as exc: + raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300]) from exc + if expanded is None: + raise err(400, "bad_value", "A field default is not valid for its field.") + # Supplied arrays and typed cells must reach their normalizers unchanged. + values = {**expanded, **values} + if not values: + raise err(400, "tool_arguments_invalid", "Record values must be a non-empty object.") + planned = {} + for key, raw in values.items(): + key = str(key) + definition = field_by_key[key] why = user_tables.cell_type_refusal(definition, raw) if why: raise err(400, "bad_value", why) @@ -3150,8 +3170,15 @@ def _database_value_plan(session, database, record_id, values, fields): bag = definition.get("link") if isinstance(definition.get("link"), dict) else {} if bag.get("on") or bag.get("inverse"): raise err(403, "computed_field", "A derived link field is read only.") - target = user_tables.get(str(bag.get("table") or ""), st=session.runtime) or {} - available = set((target.get("rows") or {}).keys()) + target_database = str(bag.get("table") or "") + _assert_database_scope(session, target_database) + target = _external_read_scope(session, target_database) + target_fields = target["fields"] + available = {str(row["pid"]): row for row in target["records"]} + if ("selectionFilter" in bag and user_tables.clean_link_selection_filter( + bag["selectionFilter"], target_fields) is None): + raise err(400, "link_selection_refused", + "The link selection condition is invalid or names an unavailable field.") raw_ids = raw if isinstance(raw, (list, tuple, set)) else str(raw or "").split(",") selected = [] for item in raw_ids: @@ -3160,6 +3187,9 @@ def _database_value_plan(session, database, record_id, values, fields): continue if candidate not in available or len(selected) >= user_tables.LINK_MAX_IDS: raise err(400, "bad_value", "A linked record is unavailable.") + if not user_tables.link_selection_permits(definition, available[candidate], target_fields): + raise err(400, "link_selection_refused", + "That record does not match the link selection condition. Choose an available record.") selected.append(candidate) if bag.get("single"): break @@ -3232,9 +3262,8 @@ def _plan_database_write(session, args): rows = table.get("rows") or {} if action == "record_create": raw_values = args.get("values") - # An empty object is a valid create when field defaults fill it (checked below). - values = ({} if isinstance(raw_values, dict) and not raw_values else - _database_value_plan(session, database, None, raw_values, g["fields"])) + values = _database_value_plan( + session, database, None, raw_values, g["fields"], apply_defaults=True) record_id = str(max((int(key) for key in rows if str(key).isdigit()), default=0) + 1) before, after = None, values else: @@ -3263,16 +3292,8 @@ def _plan_database_write(session, args): else: try: if action == "record_create": - # The grid's core insert rules: defaults, server-owned numbers, creation order. - after = user_tables._new_row_values(target.get("fields") or [], after) - if after is None: - raise err(400, "bad_value", "A field default is not valid for its field.") - if not after: - raise err(400, "tool_arguments_invalid", "Record values must be a non-empty object.") user_tables.allocate_autonumbers(target, after) user_tables._stamp_row_creation(target, record_id) - user_tables._validate_link_selection_values( - target.get("fields") or [], values, bucket_after) except ValueError as exc: raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300]) target.setdefault("rows", {})[record_id] = copy.deepcopy(after) @@ -4024,6 +4045,8 @@ def _preview_external_write(session, name, arguments, *, issue_token=True, execu response["purpose"] = purpose if name == "views" and normalised.get("action") == "share": response.update({key: copy.deepcopy(result[key]) for key in ("view", "audience")}) + if name == "apps" and normalised.get("action") == "catalog_build": + response.update({key: copy.deepcopy(result[key]) for key in _CATALOG_BUILD_RESULT_FIELDS}) if payload["strong"]: response["confirmation_phrase"] = _CONFIRMATION_PHRASE if issue_token: @@ -4265,6 +4288,7 @@ def _confirmation_status(session, operation_id, status, result=None): def _committed_build_evidence(session, writer, arguments, *, build_kind=None): """Resolve identities from committed documents and this writer's native inserts.""" import application_registry + import catalog_store import automation_engine import intelligence_store as files import wiki_log @@ -4303,6 +4327,11 @@ def _committed_build_evidence(session, writer, arguments, *, build_kind=None): for identity in before.keys() | after.keys(): if before.get(identity) != after.get(identity): add("schedule", identity) + elif key == catalog_store.STORE_KEY: + before, after = before.get("catalogs") or {}, after.get("catalogs") or {} + for identity in before.keys() | after.keys(): + if before.get(identity) != after.get(identity): + add("app", (after.get(identity) or before.get(identity) or {}).get("appId")) elif key in (application_registry._KEY, automation_engine.STORE_KEY): kind = "app" if key == application_registry._KEY else "automation" if kind == "app": @@ -4524,6 +4553,7 @@ MCP_RESULT_CODES = { code: reason for reason, codes in _MCP_CODE_GROUPS for code in codes.split() } MCP_RESULT_CODES.update({ + "link_selection_refused": "Choose a readable linked record that matches the field's selection condition.", "app_rule": "Correct the App rule named in the refusal before saving it.", "audience_not_allowed": "A person must choose sharing with everyone on screen.", "not_owner": "You cannot administer this item's audience.", @@ -4655,7 +4685,7 @@ _MCP_RESULT_IDENTIFIERS = frozenset({ "resourceUri", "deepLink", "pdfLink", "src", "websiteUrl", "fileId", "link", "href", "id", "ids", "operation_id", "key", "keys", "pid", "pids", "database", "databases", "sourceDatabase", "compatibleDatabases", "field", "fields", "field_key", "colId", "metric_key", "groupBy", - "workbook_id", "worksheet", "tab", "view_id", "app_id", "chart_id", "record_id", "contextId", + "workbook_id", "worksheet", "tab", "view_id", "app_id", "catalog_id", "chart_id", "record_id", "contextId", "path", "paths", "address", "addresses", "range", "cursor", "next_cursor", "token", "source_version", "code", "tool", "action", "person", "agent", "owner", "author", "from", "to", "username", "tenant", "createdBy", "updatedBy", "by", "byName", "reads", "approvers", "tags", "updated", @@ -5166,9 +5196,7 @@ def _mcp_guide(session: Session, group=None) -> str: "Call a group with action and arguments. Each action keeps its own read or write rules.", "Every tool accepts optional intent beside action and arguments. Every write requires it, including " "previews, confirm_change, requests.send and intelligence.create_wiki. Use 1 to 500 characters. " - 'Example: {"intent":"Prepare the weekly sales review"}. Intent is stripped before dispatch. ' - "A client that cannot send keys beside action and arguments may put intent, about and purpose " - "inside arguments. The value beside action and arguments wins.", + 'Example: {"intent":"Prepare the weekly sales review"}. Intent is stripped before dispatch.', "Each tool call records one external.query event with tool, action, outcome and argument keys and types. " "Large shapes continue in argument_shape_1 and later numbered fields. Unknown keys are redacted. " "Argument values are never recorded. Intent is retained only when sent, with credential patterns redacted. " @@ -5180,7 +5208,7 @@ def _mcp_guide(session: Session, group=None) -> str: "characters, and one or more distinct tags below. intelligence.create_wiki needs the same about " "and still publishes directly. The tool supplies the build kind. Confirmation uses the saved about.", "Build tags: " + ", ".join(external_tools.BUILD_TAGS) + ".", - "For a previewed build, put optional purpose beside action and arguments. " + "For a previewed build, put optional purpose beside action and arguments, not inside arguments. " "Use one line of 1 to 240 characters without control characters or long dashes. " "Confirmation uses that saved purpose; do not send a new purpose to confirm_change.", "Previous tool names remain callable for one release, but are absent from tools/list.", ""] @@ -5195,7 +5223,6 @@ def _mcp_guide(session: Session, group=None) -> str: from tool_groups.data import query_guide lines += [query_guide(rows), ""] states = {row["action"]: row for row in capabilities if row["group"] == group} - uses_filter_node = False for action, entry in selected["actions"].items(): lines += ["### " + action, "State: " + states[action]["state"] + "." @@ -5207,11 +5234,7 @@ def _mcp_guide(session: Session, group=None) -> str: lines.append("Previous name: `" + entry["legacy_name"] + "`.") schema = copy.deepcopy(entry["schema"]) schema.get("properties", {}).pop("about", None) - schema, collapsed = external_tools.guide_schema(schema) - uses_filter_node = uses_filter_node or collapsed lines += ["```json", json.dumps(_mcp_schema_copy(schema), ensure_ascii=True, indent=2), "```", ""] - if uses_filter_node: - lines += [external_tools.filter_node_guide(), ""] return _MCPGuideText("\n".join(lines) + "\n") lines += ["## Connected AI clients", "", "Client names and who connected them in this workspace. No entries means none are connected.", @@ -5342,14 +5365,13 @@ def _handle_mcp(req, session: Session, base_url: str = ""): return reply params = req.get("params") params = params if isinstance(params, dict) else {} - arguments = _mcp_hoist_call_metadata(params.get("name"), params.get("arguments", {})) - tool, schema = _mcp_audit_schema(params.get("name"), arguments) - limitation_tool, limitation_action = _mcp_limitation_address(tool, arguments) + tool, schema = _mcp_audit_schema(params.get("name"), params.get("arguments")) + limitation_tool, limitation_action = _mcp_limitation_address(tool, params.get("arguments")) try: with external_activity.capture_call(session, tool) as call: if tool == limitation_tool: external_activity.note_action(limitation_action) - external_activity.note_arguments(arguments, schema) + external_activity.note_arguments(params.get("arguments", {}), schema) metadata = params.get("_meta") call["question"] = metadata.get("loopable/question") if isinstance(metadata, dict) else None reply = _dispatch_mcp(req, session, base_url) @@ -5429,23 +5451,6 @@ def _mcp_call_intent(arguments): return value -def _mcp_hoist_call_metadata(name, arguments): - """Return group call arguments with intent, about and purpose lifted out of the inner arguments.""" - import tool_groups - keys = ("intent", "about", "purpose") - if (not isinstance(name, str) or name not in tool_groups.groups() or not isinstance(arguments, dict) - or not isinstance(arguments.get("arguments"), dict) - or not any(key in arguments["arguments"] for key in keys)): - return arguments - inner = arguments["arguments"] - hoisted = {**arguments, "arguments": {key: value for key, value in inner.items() if key not in keys}} - # The value beside action and arguments wins over the nested copy. - for key in keys: - if key in inner and key not in arguments: - hoisted[key] = inner[key] - return hoisted - - def _mcp_requires_intent(name, arguments): """Classify declared writes before argument validation can mask the intent requirement.""" if name == "confirm_change": @@ -5520,7 +5525,7 @@ def _dispatch_mcp(req, session: Session, base_url: str = ""): return {"jsonrpc": "2.0", "id": rid, "result": {"contents": [resource]}} if method != "tools/call": return protocol_error(rid, -32601, "The requested MCP method was not found.") - arguments = _mcp_hoist_call_metadata(name, params.get("arguments", {})) + arguments = params.get("arguments", {}) intent = _mcp_call_intent(arguments) if intent is None and _mcp_requires_intent(name, arguments): raise err(400, "call_intent_required", "Send intent explaining why you are making this write.", @@ -5543,6 +5548,10 @@ def _dispatch_mcp(req, session: Session, base_url: str = ""): purpose = _build_purpose(arguments.pop("purpose")) if "about" in metadata_keys: about = arguments.pop("about") + if (name in tool_groups.groups() and isinstance(arguments, dict) + and isinstance(arguments.get("arguments"), dict) + and {"about", "purpose", "intent"} & arguments["arguments"].keys()): + raise err(400, "tool_arguments_invalid", "Send intent and build metadata beside action and arguments.") _assert_tool_query_filter_bounds(name, arguments) resolved = tool_groups.resolve(name, arguments) confirm = True diff --git a/api/routes_geo.py b/api/routes_geo.py index a0f00c7ac995e12dce4209931f72e8db0317a38b..c43bf9441efa92d5c66f52b35ea5b528391d396c 100644 --- a/api/routes_geo.py +++ b/api/routes_geo.py @@ -327,10 +327,40 @@ def _zone_context(session, raw_table_key): return table_key, fields, set(grid.get("pids") or ()), list(grid.get("rows_src") or ()) -def _zone_subject(session, table_key, zone_id): +def _zone_application(session, table_key, application, *, write=False): + """Authorize an explicit App and its bound database before reading its Zones.""" + if application is None: + return None + if not isinstance(application, str) or not application.strip() or len(application) > 120: + raise err(400, "invalid_route_application", "choose a Routing App id") + application = application.strip() + table_key = str(table_key or "").strip() + import application_registry as registry + from core import route_system + try: + doc = registry._read_strict(session.runtime, registry._KEY) or {} + if not isinstance(doc, dict) or not isinstance(doc.get("applications", {}), dict): + raise ValueError("invalid Application registry") + except Exception: + raise err(503, "application_store_unavailable", "the Application registry is unavailable") + app = doc.get("applications", {}).get(application) + if app is None and session.admin and not write and route_system.list_zones( + session.runtime, table_key=table_key, application=application): + return application + if not isinstance(app, dict) or app.get("tenant") != session.tenant: + raise err(404, "route_application_not_found", "that Routing App does not exist") + if not registry.may_read(app, session.uname, is_admin=session.admin): + raise err(403, "route_application_forbidden", "your account cannot open this Routing App") + source = app.get("sourceDatabase") + if (source != table_key if source else table_key not in (app.get("compatibleDatabases") or ())): + raise err(409, "route_application_source", "this App does not use the selected database") + return application + + +def _zone_subject(session, table_key, zone_id, application=None): from core import route_system zone = next((item for item in route_system.list_zones( - session.runtime, table_key=table_key) + session.runtime, table_key=table_key, application=application) if str(item.get("id") or "") == str(zone_id)), None) if not isinstance(zone, dict): raise err(404, "unknown_zone", "no Zone with that id") @@ -573,11 +603,13 @@ def geo_providers(session: Session = Depends(require_session)): @router.get("/geo/zones") -def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(require_session)): +def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(require_session), + application: str = None): """The canonical table-scoped Zone DTOs a Map may draw or filter by.""" from core import route_system + application = _zone_application(session, tableKey, application) table_key, _fields, pids, rows = _zone_context(session, tableKey) - zones = route_system.list_zones(session.runtime, rows, table_key=table_key) + zones = route_system.list_zones(session.runtime, rows, table_key=table_key, application=application) # A hidden Zone remains recoverable to its creator/admin, but cannot become visible through a # second table simply because row ids happen to collide there. visible = [zone for zone in zones if zone.get("visible", True) @@ -588,10 +620,14 @@ def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(requ @router.post("/geo/zones") -def geo_zone_create(body: dict = Body(default=None), session: Session = Depends(require_session)): +def geo_zone_create(body: dict = Body(default=None), session: Session = Depends(require_session), + application: str = None): """Persist one Zone in the existing table-scoped Zone store and field/filter contract.""" from core import route_system body = body if isinstance(body, dict) else {} + from routes_customers import _route_application_body + _route_application_body(body, application) + application = _zone_application(session, body.get("tableKey"), application, write=True) table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey")) try: if any(key in body for key in ("memberships", "memberPids", "member_pids")): @@ -601,7 +637,7 @@ def geo_zone_create(body: dict = Body(default=None), session: Session = Depends( "geometryGeoJson": body.get("geometryGeoJson"), "zipCodes": body.get("zipCodes"), "visible": body.get("visible"), "geographicField": body.get("geographicField") }, rows=rows, tenant_id=session.tenant, created_by=session.uname, - table_key=table_key) + table_key=table_key, application=application) if zone is None: raise ValueError("the Zone does not match this database's fields and records") except ValueError as exc: @@ -613,12 +649,15 @@ def geo_zone_create(body: dict = Body(default=None), session: Session = Depends( @router.patch("/geo/zones/{zone_id}") def geo_zone_update(zone_id: str, body: dict = Body(default=None), - session: Session = Depends(require_session)): + session: Session = Depends(require_session), application: str = None): """Edit a table-scoped Zone while retaining creator, geometry and membership invariants.""" from core import route_system body = body if isinstance(body, dict) else {} + from routes_customers import _route_application_body + _route_application_body(body, application) + application = _zone_application(session, body.get("tableKey"), application, write=True) table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey")) - previous = _zone_subject(session, table_key, zone_id) + previous = _zone_subject(session, table_key, zone_id, application) try: if any(key in body for key in ("memberships", "memberPids", "member_pids")): raise ValueError("Zone membership is derived from current permitted rows") @@ -630,7 +669,7 @@ def geo_zone_update(zone_id: str, body: dict = Body(default=None), "visible": body.get("visible", previous.get("visible")), "geographicField": body.get("geographicField", previous.get("geographicField")) }, rows=rows, tenant_id=session.tenant, created_by=session.uname, - table_key=table_key) + table_key=table_key, application=application) if zone is None: raise ValueError("the Zone does not match this database's fields and records") except ValueError as exc: @@ -640,13 +679,16 @@ def geo_zone_update(zone_id: str, body: dict = Body(default=None), @router.delete("/geo/zones/{zone_id}") def geo_zone_delete(zone_id: str, body: dict = Body(default=None), - session: Session = Depends(require_session)): + session: Session = Depends(require_session), application: str = None): """Delete exactly one table-scoped Zone; record values are never mutated here.""" body = body if isinstance(body, dict) else {} + from routes_customers import _route_application_body + _route_application_body(body, application) + application = _zone_application(session, body.get("tableKey"), application, write=True) table_key, _fields, _pids, _rows = _zone_context(session, body.get("tableKey")) - _zone_subject(session, table_key, zone_id) + _zone_subject(session, table_key, zone_id, application) from core import route_system - if not route_system.delete_zone(session.runtime, zone_id, table_key=table_key): + if not route_system.delete_zone(session.runtime, zone_id, table_key=table_key, application=application): raise err(404, "unknown_zone", "no Zone with that id") return {"deleted": str(zone_id)} diff --git a/api/routes_grid.py b/api/routes_grid.py index c2566480e528e58372c37091ee8f911ec7d71c9b..5918779d115f9517a2fd8466628849bed1855c29 100644 --- a/api/routes_grid.py +++ b/api/routes_grid.py @@ -1816,7 +1816,7 @@ def _materialise_recurrence_cells(session, scope, events, results, fields): # admin route over the CALLING TENANT, and a scheduler must call it once per tenant. -def refresh_recurrence_columns(st, scope, today=None, defn=None): +def refresh_recurrence_columns(st, scope, today=None, defn=None, by=None): """R2's roll-forward for ONE database: `{field_key: rows_written}`; `{}` when nothing moved. Callable WITHOUT an HTTP request — `st` is a store handle (`session.runtime`) and `scope` a @@ -1880,7 +1880,8 @@ def refresh_recurrence_columns(st, scope, today=None, defn=None): counts[key] = counts.get(key, 0) + 1 if not updates: return {} - written = user_tables.patch_many_cells(scope, updates, st=st) + # S76-T32: `by` is the signed-in admin who asked; a scheduler passes None and stamps no person. + written = user_tables.patch_many_cells(scope, updates, st=st, by=by) if not written: return {} if written != len(updates): @@ -1891,7 +1892,7 @@ def refresh_recurrence_columns(st, scope, today=None, defn=None): return counts -def refresh_recurrence_tenant(st, today=None): +def refresh_recurrence_tenant(st, today=None, by=None): """Every user database in ONE tenant: `{table_key: {field_key: rows_written}}`. ONE `all_tables` read for the whole walk, with each definition LENT onward — see @@ -1903,7 +1904,7 @@ def refresh_recurrence_tenant(st, today=None): today = str(today or time.strftime("%Y-%m-%d")) out = {} for scope, defn in (user_tables.all_tables(st=st) or {}).items(): - counts = refresh_recurrence_columns(st, scope, today=today, defn=defn) + counts = refresh_recurrence_columns(st, scope, today=today, defn=defn, by=by) if counts: out[str(scope)] = counts return out @@ -1929,7 +1930,7 @@ def recurrence_refresh(session: Session = Depends(require_session)): raise err(503, "store_unavailable", "the tenant store is unavailable. Nothing was refreshed") today = time.strftime("%Y-%m-%d") - tables = refresh_recurrence_tenant(session.runtime, today=today) + tables = refresh_recurrence_tenant(session.runtime, today=today, by=getattr(session, "uname", None)) return {"today": today, "tables": tables, "cells": sum(sum(counts.values()) for counts in tables.values()), "columns": sum(len(counts) for counts in tables.values())} diff --git a/api/routes_nav.py b/api/routes_nav.py index b95d8dc1e3d425b0fc6037501e295799c23c4b23..1e44da884199676c99a5836a4fc5d878b8822878 100644 --- a/api/routes_nav.py +++ b/api/routes_nav.py @@ -28,6 +28,7 @@ router = APIRouter(prefix="/api/v1") _NAV_PREFS_KEY = "nav_prefs" _MAX_NAV_FOLDERS = 16 + #: WAVE 19 (R8 / contract C1): the database's NAME and ICON overrides. #: #: ⚠ TENANT-WIDE, which is the whole difference from `nav_prefs` above and the reason it is a diff --git a/api/routes_odoo_tables.py b/api/routes_odoo_tables.py index ca19e58647fb0e9023ddd830979742dc5779b189..d897219cae2cc8f52a9f0e473ff99f51af01557a 100644 --- a/api/routes_odoo_tables.py +++ b/api/routes_odoo_tables.py @@ -4532,6 +4532,12 @@ def mirror_stamp(spec, cur=None, table_key="", rt=None, defn=None): return "" except Exception: # noqa: BLE001 return "" + if str(table_key).startswith("ut_amzn_"): + try: + from external_freshness import amazon_sync_stamp + return str(amazon_sync_stamp(cur, table_key) or "")[:10] + except Exception: + return "" ident = str(spec.get("id") or "") alias = ident.split(".", 1)[0] if "." in ident else "" table = str((spec.get("tables") or {}).get(alias) or spec.get("table") diff --git a/api/routes_query.py b/api/routes_query.py index 32192f903147e57a0057f30668efd0e07fd27238..9718fca1ae72f2e2d26497c46397a081e32d452c 100644 --- a/api/routes_query.py +++ b/api/routes_query.py @@ -124,18 +124,6 @@ QUERY_NO_SOURCE_MATCHED = ( "None of the databases you can read cover that question. Pick one from the list, " "or ask about a database you can open." ) -# A fresh turn made only of these words names no data subject, so it is conversation (D-2673). -_CHAT_WORDS = ( - "hello hi hey hiya good morning afternoon evening thanks thank please ok okay yes no yeah yep sure " - "cool great nice sorry bye goodbye cheers welcome i me you your yours we it its they them can could " - "would will should might have has had be am been being does doing done get got there here then " - "just also too so really still now hear see know help think say ask mean understand need want like " - "try talk chat explain database table field data workspace loopable assistant loopy app question answer" -) -CONVERSATION_PROMPT = ( - "\nNo database is chosen for this turn and no tool is available. Reply in plain sentences with no " - "markdown, and never state a figure from data. If the user asks about their data, ask which database to use." -) QUERY_DRAFT_ADMIN = "This database has no approved fields yet. Pick the ones this answer should use and they will be approved for everyone." QUERY_DRAFT_MEMBER = "This database has no approved fields yet. Pick the ones you need and your administrators will be asked to approve them." QUERY_DRAFT_SENT = "Sent to your administrators. Ask again once one of them approves." @@ -1035,8 +1023,6 @@ def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, s tools.extend(agent_runtime.tool_specs(session, snapshot=snapshot)) if turn.get("openWork"): tools = [tool for tool in tools if tool["function"]["name"] == "open_items"] - if turn.get("conversation"): - tools = [] if turn.get("admittedTools"): tools = [tool for tool in tools if tool["function"]["name"] in set(turn["admittedTools"])] if turn.get("memoryOnly"): @@ -1047,11 +1033,6 @@ def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, s "You are the Loopable Assistant. Use tools for facts. Writes run at once. Deletes need the user's yes.") if turn.get("context"): prompt += "\n\n" + turn["context"] - if turn.get("conversation"): - names = turn.get("conversationSources") - prompt += CONVERSATION_PROMPT + ("" if names is None else - " The databases this user can open: " + "; ".join(names) + "." - if names else " This user can open no database yet.") if turn.get("toolShareRequests"): prompt += ("\nThis turn concerns a pending tool-share approval only. Use the prior conversation to identify " "the request. Ask which request when the user's approval is ambiguous. " @@ -2032,13 +2013,8 @@ def _submit_active(body, session, question, selected_model, context_hint, dock, memory_only = dock is None and not target and replay is None and assistant_memory.admits(question) routed = _route(session, question) if dock is None and not open_work and not admitted and not memory_only and not share_requests and not agent_runtime.has_attachments() and not target and replay is None else { "database": target, "auto": False, "alternatives": []} - # D-2673: an app turn with no data subject reaches the model with no tools, never the no-source refusal. - conversation = (door == "app" and dock is None and replay is None and not also_as - and _conversation(question, routed)) - if conversation: - routed = {"database": "", "label": "", "reason": "", "auto": True, "alternatives": []} target = routed["database"] - route_refusal = (None if conversation or dock is not None or open_work or admitted or memory_only or share_requests or agent_runtime.has_attachments() else + route_refusal = (None if dock is not None or open_work or admitted or memory_only or share_requests or agent_runtime.has_attachments() else QUERY_NO_SOURCE_MATCHED if not target and replay is None else routed.get("refusal")) # Snapshot turns plan mirrors from schema. Dock turns read through permissioned tools. @@ -2088,9 +2064,6 @@ def _submit_active(body, session, question, selected_model, context_hint, dock, turn["admittedTools"] = sorted(admitted) if memory_only: turn["memoryOnly"] = True - if conversation: - turn["conversation"] = True - turn["conversationSources"] = _readable_labels(session) turn["memoryCompanyRequested"] = assistant_memory.company_requested(question) if snapshot is not None: turn["memorySources"] = [{"database": snapshot["database"], @@ -2409,7 +2382,48 @@ def _recorded_artifacts(session): yield from assistant_artifacts._rows(session.runtime, h, index) -def _artifact_actions(item): +def _artifact_can_edit(session, item, *, query_views=None): + """Resolve current item authority before offering or executing an Artifact mutation.""" + try: + session.require("analyst") + if not session.uname or item.get("status") == "deleted": + return False + kind, ref = item["kind"], item.get("ref") + owner = assistant_log._hash(session.runtime, session.uname) + legacy_query = kind == "query" and item["id"] == "query:" + str(ref) + # Every caller already resolved the row through this principal's catalog or Query namespace. + if not legacy_query and assistant_artifacts._seq(owner, item["id"]) is None: + return False + if kind == "query": + if query_views is not None: + # The list already admitted these sources in its current permission batch. + return ref in query_views + _artifact_or_404(session, ref) + return True + if kind == "view": + from routes_starred import _find_view + from routes_starred import _home_view_row + found = _find_view(session, ref, item["toolCall"]["args"].get("database") or "") + return bool(found and _home_view_row(session, found)["capabilities"]["edit"]) + if kind == "sheet": + from core import sheets + import routes_sheet + book = sheets.get_workbook(session.runtime, ref) + routes_sheet._require_reader(session, book) + return routes_sheet._role_on_workbook(session, book) in ("owner", "edit") + if kind == "schedule": + import schedules + schedule = schedules.get(session.runtime, ref) + return bool(schedule and schedule.get("owner") == session.uname and not schedule.get("system")) + if kind == "snapshot": + # The owner's own frozen copy; its content stays behind the serve route's source check. + return item.get("status") == "active" + return kind in ("report", "run", "pdf", "xlsx", "image") + except Exception: + return False + + +def _artifact_actions(item, session=None, *, query_views=None): actions = ["run"] if item["kind"] in ("sheet", "view", "query") and item.get("ref"): actions.insert(0, "open") @@ -2417,6 +2431,15 @@ def _artifact_actions(item): actions.extend(["resume" if item.get("status") == "paused" else "pause", "delete"]) elif item["kind"] in ("view", "query") and item.get("ref"): actions.append("delete") + if session is not None: + # Extracted projections without an item authority resolver keep mutation actions closed. + can_edit = globals().get("_artifact_can_edit") + if callable(can_edit) and can_edit(session, item, query_views=query_views): + actions.append("rename") + if "delete" not in actions: + actions.append("delete") + else: + actions = [action for action in actions if action not in ("delete", "pause", "resume")] return actions @@ -2458,7 +2481,7 @@ def _artifact_rows(session, views_only=False): "database": view["source"]["database"], "question": view["question"]}}}) for row in rows: row["title"] = _no_dashes(row["title"])[:200] - row["actions"] = _artifact_actions(row) + row["actions"] = _artifact_actions(row, session, query_views=by_ref) return sorted(rows, key=lambda row: (row["createdAt"], row["id"]), reverse=True) @@ -2496,7 +2519,7 @@ def _artifact_item(session, item_id): if stored and stored["status"] != "deleted": if stored["kind"] == "query": _artifact_or_404(session, stored["ref"]) - stored["actions"] = _artifact_actions(stored) + stored["actions"] = _artifact_actions(stored, session) return stored item = next((row for row in _artifact_rows(session) if row["id"] == item_id), None) if item is None: @@ -2614,18 +2637,23 @@ def resume_artifact(id: str, session: Session = Depends(require_session)): def delete_artifact(id: str, session: Session = Depends(require_session)): import agent_runtime item = _artifact_item(session, id) + if not _artifact_can_edit(session, item): + raise err(403, "artifact_read_only", "Your current rights do not allow deleting this artifact.") if item["kind"] == "schedule": name, args = "schedule_delete", {"id": item["ref"]} elif item["kind"] == "view": - name, args = "view_delete", {"database": item["toolCall"]["args"].get("database"), "view_id": item["ref"]} + name, args = "artifact_entry_delete", {"id": item["id"]} elif item["kind"] == "query": name, args = "query_view_delete", {"qid": item["ref"]} + elif item["kind"] in ("sheet", "report", "run", "pdf", "xlsx", "image", "snapshot"): + name, args = "artifact_entry_delete", {"id": item["id"]} else: raise err(400, "not_deletable", "This artifact cannot be deleted here.") pending = agent_runtime._pending(session, "app", name, args) - if item["kind"] in ("query", "schedule"): + if item["kind"] in ("query", "schedule", "view", "sheet", "report", "run", "pdf", "xlsx", "image", "snapshot"): # The artifact carries the name the reader knows; a schedule id or a Query id is not one. - noun = "Query answer" if item["kind"] == "query" else "schedule" + noun = ("Query answer" if item["kind"] == "query" else item["kind"] + if item["kind"] in ("schedule", "view") else "artifact") pending["summary"] = f"Remove {noun} {_no_dashes(item['title']).rstrip('. ')}." def name_request(raw): current = copy.deepcopy(raw) @@ -2639,6 +2667,79 @@ def delete_artifact(id: str, session: Session = Depends(require_session)): return {"pendingDelete": pending} +def _update_artifact_entry(session, item_id, patch): + """Update only this principal's catalog entry while preserving its backing object.""" + owner = assistant_log._hash(session.runtime, session.uname) + seq = assistant_artifacts._seq(owner, item_id) + if seq is None: + raise err(404, "unknown_artifact", "That artifact does not exist.") + saved = {} + + def update(raw): + saved.clear() + doc = copy.deepcopy(raw or {}) + row = next((row for row in doc.get("items", []) if row.get("id") == item_id), None) + if row is None or row.get("status") == "deleted": + raise err(404, "unknown_artifact", "That artifact does not exist.") + if not _artifact_can_edit(session, row): + raise err(403, "artifact_read_only", "Your current rights do not allow changing this artifact.") + row.update(patch) + saved.update(row) + return doc + + session.runtime.update(assistant_artifacts._chunk_key(owner, seq // assistant_artifacts.CHUNK_ITEMS), + update, flush="sync") + if not saved: + raise err(503, "store_unavailable", "The artifact change could not be confirmed. Reload and try again.") + saved["actions"] = _artifact_actions(saved, session) + return saved + + +@router.patch("/artifacts/{id}") +def rename_artifact(id: str, body: dict = Body(default=None), session: Session = Depends(require_session)): + """Rename an authorized Artifact's label without changing its generated content.""" + title = (body or {}).get("title") + if not isinstance(title, str) or not title.strip() or len(title.strip()) > 200: + raise err(400, "bad_title", "Use a title of 1 to 200 characters.") + item = _artifact_item(session, id) + if not _artifact_can_edit(session, item): + raise err(403, "artifact_read_only", "Your current rights do not allow renaming this artifact.") + title = title.strip() + if item["kind"] == "query": + if len(title) > 60 or title != " ".join(title.split()): + raise err(400, "bad_title", "Use a title of at most 60 characters with single spaces.") + title = rename_query(item["ref"], {"name": title}, session)["name"] + if id.startswith("query:"): + return {"artifact": _artifact_item(session, id)} + return {"artifact": _update_artifact_entry(session, id, {"title": title})} + + +def _delete_artifact_entry(session, args): + item = _artifact_item(session, args["id"]) + if item["kind"] == "view": + if not _artifact_can_edit(session, item): + raise err(403, "artifact_read_only", "Your current rights do not allow deleting this artifact.") + from routes_starred import delete_home_view + delete_home_view(item["toolCall"]["args"]["database"], item["ref"], None, session) + assistant_artifacts.set_status(session.runtime, session.uname, item["id"], "deleted") + return {"deleted": item["id"]} + if item["kind"] not in ("sheet", "report", "run", "pdf", "xlsx", "image", "snapshot"): + raise err(400, "not_deletable", "This artifact cannot be deleted through this action.") + _update_artifact_entry(session, item["id"], {"status": "deleted"}) + return {"deleted": item["id"]} + + +def _register_artifact_entry_delete(): + import agent_tools + agent_tools.register("artifact_entry_delete", { + "type": "object", "description": "Remove your Artifact entry after confirmation while retaining its backing data.", + "properties": {"id": {"type": "string"}}, "required": ["id"], "additionalProperties": False, + }, _delete_artifact_entry, effect="delete") + + +_register_artifact_entry_delete() + + def _settle_artifact_delete(session, call): kind = {"schedule_delete": "schedule", "view_delete": "view", "query_view_delete": "query"}.get(call["name"]) if kind is None: @@ -2771,32 +2872,6 @@ def _route_candidates(session): return candidates -def _readable_labels(session): - """The names of the databases this session may open: the picker's set, no record read. - - None when the status wall cannot be read, so a greeting still gets its reply.""" - from harness import semantic as sem - try: - projection = getattr(session.runtime, "get_projection", None) - definitions = (projection("user_tables", drop=("rows",)) or {}) if projection else {} - topics = {row.get("grid"): row.get("label") for row in sem.topics().values()} - statuses = assistant_source_status(session, None) - except Exception: # noqa: BLE001 - return None - return sorted({_said(status.get("label") or (definitions.get(database) or {}).get("label") - or topics.get(database) or database.removeprefix("ut_").replace("_", " ")) or database - for database, status in statuses.items() - if status.get("permitted")}) - - -def _conversation(question, routed): - """True when an auto route found no database or the question holds no data word.""" - from harness import semantic as sem - return bool(routed.get("auto")) and ( - not routed.get("database") - or not set(sem._route_tokens(question)) - set(sem._route_tokens(_CHAT_WORDS))) - - def _route(session, question): from harness import semantic as sem candidates = _route_candidates(session) @@ -3363,10 +3438,6 @@ def governed_query(body: dict = Body(default=None), "database": "", "label": "", "reason": "", "auto": False, "alternatives": []}} routed = _route(session, question) if not database else { "database": database, "label": "", "reason": "", "auto": False, "alternatives": []} - if _conversation(question, routed): - # D-2673: a greeting or a question no database covers continues to chat, never a Clarify card. - return {"status": "continue_chat", "routedTo": { - "database": "", "label": "", "reason": "", "auto": False, "alternatives": []}} database = routed["database"] if database: _semantic_authorize(session, database, require_answerable=not routed["auto"]) diff --git a/api/routes_sheet.py b/api/routes_sheet.py index f5bdff298aad4a3c062d4c34c6e5000bdd68a6d1..2482f7f75aa270e379d644e7c9b077afcec33462 100644 --- a/api/routes_sheet.py +++ b/api/routes_sheet.py @@ -1412,7 +1412,7 @@ _MISSING_CODES = ("workbook_missing", "folder_missing", "tab_missing", "unknown_ #: it, which is what 403 means and is the only status a client can act on. #: #: `workbook_read_only` is a VIEWER at a write door; `workbook_owner_only` is a non-owner at a -#: door C5 reserves for the owner (the two share doors, and DELETE). Two codes rather than one +#: door C5 reserves for the owner (the two share doors). Two codes rather than one #: because they send the reader to two different places: one asks for edit access, the other #: cannot be granted at all. _FORBIDDEN_CODES = ("workbook_read_only", "workbook_owner_only", "tenant_mismatch", "sheet_actor_required") @@ -3443,18 +3443,10 @@ def duplicate_sheet_tab(workbook_id: str, tab: str, body: dict = Body(default=No @router.delete("/sheets/{workbook_id}") def drop_sheet(workbook_id: str, session: Session = Depends(require_session)): - """Delete a workbook. THE OWNER's door, and an editor is refused by name (C5). - - ⛔ AN `edit` GRANT IS PERMISSION TO CHANGE THE CONTENT, NOT TO DESTROY THE OBJECT, and the - fail-closed reading is the one that ships: an editor who deletes the owner's workbook has - taken it from everybody it was shared with, and nothing in this system can put it back. The - refusal is `workbook_owner_only` rather than `workbook_read_only` because the sentences send - the reader to two different places, and telling an editor their workbook is read only would be - flatly false. - """ + """Delete a workbook through its current edit right under R26.""" from core import sheets try: - _require_owner(session, sheets.get_workbook(_store(session), workbook_id)) + _require_editor(session, sheets.get_workbook(_store(session), workbook_id)) removed = sheets.delete_workbook(_store(session), workbook_id) except sheets.SheetRefusal as exc: raise _refuse(exc) diff --git a/api/routes_starred.py b/api/routes_starred.py index e023040953e08b22064f590570434a8c4e0a4f97..790c9a30c5cf267ca2e9b54f0fb85062e5119ae4 100644 --- a/api/routes_starred.py +++ b/api/routes_starred.py @@ -34,7 +34,7 @@ import json import time from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait -from fastapi import APIRouter, Body, Depends +from fastapi import APIRouter, Body, Depends, Request import routes_nav from deps import Session, err, require_session @@ -304,7 +304,7 @@ def _refresh_one(session, cache, key): return (order, docs, unread) -def _scan_starred_views(session, keys=None, cache=None, include=None): +def _scan_starred_views(session, keys=None, cache=None, include=None, with_rights=False): """`(rows, unread)` — every view this caller has starred, newest-worked database first. A row is `{"id", "database", "name", "config"}`. ⚠ `config` is carried so the COUNTS route does @@ -367,11 +367,12 @@ def _scan_starred_views(session, keys=None, cache=None, include=None): doc = session.runtime.get_projection(ws_key, drop=("overlays", "fields")) or {} docs[key] = doc - found = {} + found, owners = {}, {} own = doc.get(session.uname) for vid, view in ((own.get("views") or {}) if isinstance(own, dict) else {}).items(): if isinstance(view, dict): found[str(vid)] = view + owners[str(vid)] = session.uname for vid in pending: owner = granted.get(vid) @@ -391,12 +392,17 @@ def _scan_starred_views(session, keys=None, cache=None, include=None): break if isinstance(view, dict): found.setdefault(vid, view) + owners.setdefault(vid, owner if owner else candidate_owner) resolved.add(vid) for vid, view in found.items(): cfg = view.get("config") or {} if (include(view) if include else cfg.get("important") is True): - out.append({"id": vid, "database": key, - "name": str(view.get("name") or vid)[:120], "config": cfg}) + row = {"id": vid, "database": key, + "name": str(view.get("name") or vid)[:120], "config": cfg} + if with_rights: + row.update(routes_nav._home_view_row( + session, (key, ws_key, owners[vid], {**view, "id": vid}, None))) + out.append(row) return out, unread @@ -516,15 +522,82 @@ def _payload(session, keys=None, cache=None): @router.get("/nav/views") def nav_views(session: Session = Depends(require_session)): - """S76-T17: every saved View this caller may open, as names only, for the module home. + """Project readable saved View names and their current item rights.""" + rows, unread = _scan_starred_views(session, include=lambda view: True, with_rights=True) + return {"views": [{key: row[key] for key in ("database", "id", "name", "capabilities")} + for row in rows], "unread": unread} + + +# S76-T17: the Home Views section's rename and delete live beside its GET, never in routes_nav (R7). + +def _home_view_row(session, found): + """Project only a saved View's identity, name and current edit right.""" + database, _, owner, view, _ = found + editable = (view.get("id") != SYSTEM_VIEW_ID and view.get("kind") != "system" + and _may_star_view(session, owner, view)) + return {"database": database, "id": view["id"], "name": str(view.get("name") or view["id"])[:120], + "capabilities": {"edit": bool(editable), "delete": bool(editable)}} + + +def _editable_home_view(session, database, view_id): + found = _find_view(session, view_id, database) + if found is None: + raise err(404, "view_not_found", "That saved View is no longer available.") + if not _home_view_row(session, found)["capabilities"]["edit"]: + raise err(403, "view_read_only", "Your current rights do not allow changes to this View.") + return found + + +@router.patch("/nav/views/{database}/{view_id}") +def rename_home_view(database: str, view_id: str, request: Request, body: dict = Body(default=None), + session: Session = Depends(require_session)): + """Rename the canonical saved View without reading or returning database records.""" + from core import table_store, view_audit, write_execution + from routes_tables import _audit_origin + + name = (body or {}).get("name") + if not isinstance(name, str) or not name.strip() or len(name.strip()) > 120: + raise err(400, "bad_name", "Use a View name of 1 to 120 characters.") + found = _editable_home_view(session, database, view_id) + key, workspace, owner, _, cache = found + views = table_store.make(workspace, st=session.runtime) + saved, changes = {}, {} + + def rename(data, audit): + saved.clear() + current = ((data.get(owner) or {}).get("views") or {}).get(view_id) + if not isinstance(current, dict): + raise err(404, "view_not_found", "That saved View is no longer available.") + if not _may_star_view(session, owner, current): + raise err(403, "view_read_only", "Your current rights do not allow changes to this View.") + names = [candidate.get("name") for who, personal in data.items() + if who not in table_store.RESERVED_MEMBERS and isinstance(personal, dict) + for candidate_id, candidate in (personal.get("views") or {}).items() + if candidate_id != view_id and isinstance(candidate, dict)] + updated = {**current, "name": table_store._unique_name(name.strip(), names), + "updatedAt": write_execution.utcnow().isoformat()} # S76-T37 + changes.update(before=view_audit.summary(current), after=view_audit.summary(updated)) + data[owner]["views"][view_id] = updated + audit(action=view_audit.derive_action(current, updated), owner=owner, view_id=view_id, + actor=session.uname, origin=_audit_origin(request), **changes) + saved.update(updated) + return data - Read-only: rename and delete stay closed (capabilities false) until their governed doors exist - (D-9736). The config never goes on the wire, for `_starred_views`' reason. - """ - rows, unread = _scan_starred_views(session, include=lambda view: True) - return {"views": [{"database": r["database"], "id": r["id"], "name": r["name"], - "capabilities": {"edit": False, "delete": False}} for r in rows], - "unread": unread} + views._audited_update(rename) + views.log_view_activity(view_id, "saved", by=session.uname, via=_audit_origin(request), **changes) + return {"view": _home_view_row(session, (key, workspace, owner, saved, cache))} + + +@router.delete("/nav/views/{database}/{view_id}") +def delete_home_view(database: str, view_id: str, request: Request, session: Session = Depends(require_session)): + """Move the canonical saved View to trash through its own edit right.""" + from core import table_store + from routes_tables import _audit_origin + + _, workspace, owner, _, _ = _editable_home_view(session, database, view_id) + table_store.make(workspace, st=session.runtime).delete_view( + owner, view_id, actor=session.uname, origin=_audit_origin(request)) + return {"deleted": view_id} @router.get("/starred") diff --git a/api/routes_tables.py b/api/routes_tables.py index 47bb44268f63dbf628fd9dec2b16f42bce484fe5..74248dfc69f2adb4489306911f44ae60088f3951 100644 --- a/api/routes_tables.py +++ b/api/routes_tables.py @@ -2957,9 +2957,13 @@ def add_row(table_key: str, body: dict = Body(default=None), if ut.ZONE_FIELD_KEY in values or "zone" in values: raise err(400, "zone_membership_read_only", "Zone membership is worked out from the record's current location") + # S76-T32: an undo restores a deleted record's retained server facts only when it says so. + restore = (body or {}).get("restore", False) + if not isinstance(restore, bool): + raise err(400, "bad_restore", "restore must be true or false") try: rid = ut.add_row(table_key, values, session.uname, st=session.runtime, - rid=(body or {}).get("rid"), via=via) + rid=(body or {}).get("rid"), restore=restore, via=via) except ValueError as exc: # A core value rule (negative policy, link condition, server-owned cell) names its reason. raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300] or "the row was refused") @@ -2982,7 +2986,23 @@ def add_row(table_key: str, body: dict = Body(default=None), _refresh_relations(session) from routes_alerts import after_write after_write(session, table_key) - return {"rid": rid, "pid": int(rid)} + return {"rid": rid, "pid": int(rid), "values": _added_row_values(session, table_key, rid)} + + +def _added_row_values(session, table_key, rid): + """The stored row as this session may read it: generated cells included, hidden fields and + server-only keys (`_rowAudit`, `_created`) never.""" + import core.perm_scope as perm_scope + try: + entry = _table_entry(session.runtime, table_key) or {} + except Exception: + return {} # the row is saved; a failed read-back must not report a failed write + row = (entry.get("rows") or {}).get(str(rid)) + if not isinstance(row, dict): + return {} + hidden = _ut_hidden(session, table_key, entry.get("fields") or [], st=session.runtime) + return perm_scope.strip_row({key: value for key, value in row.items() + if not str(key).startswith("_")}, hidden) @router.post("/tables/{table_key}/rows/import", status_code=201) @@ -3041,6 +3061,10 @@ def import_rows(table_key: str, body: dict = Body(default=None), raise err(400, "bad_value", f"row {index + 1}: {why}. Nothing was imported") try: made = ut.add_rows(table_key, rows_in, session.uname, st=session.runtime) + except ValueError as exc: + # S76-T33: a Link condition or value rule refuses the batch with its own code and reason. + raise err(400, getattr(exc, "code", "bad_value"), + (str(exc)[:280].rstrip(". ") or "a value was refused") + ". Nothing was imported") except Exception: raise err(503, "store_unavailable", "nothing was imported. The store refused") if made is None: @@ -3127,6 +3151,33 @@ def _admit_if_sources(session, table_key, body, definition, fkey=''): raise err(403 if exc.code == 'if_source_forbidden' else 400, exc.code, str(exc)) +def _admit_link_selection(session, body): + """S76-T33: a Link condition may name only target fields this session can read.""" + raw = body if isinstance(body, dict) else {} + bag = raw.get("link") + if not isinstance(bag, dict) or not isinstance(bag.get("selectionFilter"), dict): + return + target = str(bag.get("table") or "") + if not target.startswith(_ut().KEY_PREFIX): + return # a registry target is checked in core, which fails closed + import core.perm_scope as perm_scope + if not perm_scope.may_read(session.user, target, st=session.runtime): + raise err(403, "link_selection_forbidden", + "You cannot read the linked database, so its records cannot set a condition.") + named, stack = set(), list(bag["selectionFilter"].get("nodes") or []) + while stack: + node = stack.pop() + if not isinstance(node, dict): + continue + stack.extend(node.get("children") or []) + rhs = node.get("rhs") if isinstance(node.get("rhs"), dict) else {} + named.update(ref for ref in (node.get("colId"), rhs.get("colId")) if isinstance(ref, str) and ref) + fields = (_table_entry(session.runtime, target) or {}).get("fields") or [] + if named & set(_ut_hidden(session, target, fields, st=session.runtime) or ()): + raise err(403, "link_selection_forbidden", + "The link condition names a field you cannot read in the linked database.") + + @router.post("/tables/{table_key}/fields", status_code=201) @_c8_write def add_field(table_key: str, body: dict = Body(default=None), @@ -3134,6 +3185,7 @@ def add_field(table_key: str, body: dict = Body(default=None), _managed_or_refuse(session, table_key, mutation=True) definition = _field_or_refuse(session, table_key) _admit_if_sources(session, table_key, body, definition) + _admit_link_selection(session, body) ut = _ut() from routes_grid import govern_date_recurrence # Only recurrence admission needs the merged workspace. Plain creates need no row audience. @@ -3269,6 +3321,7 @@ def patch_field(table_key: str, fkey: str, body: dict = Body(default=None), _managed_or_refuse(session, table_key, mutation=True) definition = _field_or_refuse(session, table_key, fkey) _admit_if_sources(session, table_key, body, definition, fkey) + _admit_link_selection(session, body) ut = _ut() body = body or {} from routes_grid import govern_date_recurrence @@ -3602,6 +3655,12 @@ def patch_row(table_key: str, pid: int, body: dict = Body(default=None), except ValueError as exc: # A core value rule refused the cell before anything was stored. Name its reason (C4). raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300] or "the edit was refused") + # S76-T29: `overlay_patch` records a value rule's refusal instead of raising; answer it the same way. + for _refusal in getattr(ctx.out, "refusals", None) or (): + if _refusal.get("event") == "overlay_patch" and _refusal.get("code") not in ( + "cell_write_refused", "row_outside_audience", "bad_row_id"): + raise err(400, _refusal.get("code") or "bad_value", + _refusal.get("message") or "the edit was refused") # ⚠ THE READ-BACK IS THE DEFINITION ROW, AND ON A `ut_` SCOPE THAT IS THE WHOLE OF IT. # # ⛔ CORRECTED, wave-29 T22 (owner item 2a): this note used to say "THE READ-BACK SPANS BOTH diff --git a/api/schedules.py b/api/schedules.py index a0ddfe8bd32e796358c97346e21679d257e145d2..831ef11de93a1a388279471b6aff2e57f0c3cf03 100644 --- a/api/schedules.py +++ b/api/schedules.py @@ -224,7 +224,7 @@ def create(rt, owner, *, cron=None, tz, action, label, system=False, once_at=Non item = {"id": schedule_id, "owner": owner, "label": label, "cron": None if once or trigger else " ".join(cron.split()), "tz": tz, "action": action, "paused": False, "nextRunAt": next_stamp, - "createdAt": _iso(now), "lastFiredMinute": None, "lastFiredAt": None, + "createdAt": _iso(now), "updatedAt": _iso(now), "lastFiredMinute": None, "lastFiredAt": None, "lastOutcome": None, "runs": [], "system": bool(system)} if once: item.update(once=True, onceAt=next_stamp) @@ -261,6 +261,7 @@ def _set_paused(rt, schedule_id, paused): or _utc(instant) <= now): raise ValueError("That reminder already ran.") item["paused"] = paused + item["updatedAt"] = _iso(now) # S76-T37: pausing or resuming is an update if not paused and item.get("trigger") == "sync" and item.get("syncFallback"): item["nextRunAt"] = _iso(now + dt.timedelta(hours=1)) if not paused and not item.get("once") and item.get("trigger") != "sync": diff --git a/api/tool_groups/sheet.py b/api/tool_groups/sheet.py index a498c0a6b9aa40741cc8d7596f0c692a2c8a3327..e7bca114ab9292bc3176c49eef3db87e9a7debec 100644 --- a/api/tool_groups/sheet.py +++ b/api/tool_groups/sheet.py @@ -49,6 +49,13 @@ def _workbook_view(ctx, args): "editable": not bool(reason), "reason": reason, "sheets": tabs}} +def _object_available(operation): + """Promise only object actions implemented by the compatibility dispatcher.""" + from core import sheet_compat + return (callable(getattr(sheet_compat, "dispatch_object_operation", None)) + and operation in sheet_compat.OBJECT_OPERATIONS) + + GROUP = { "name": "sheet", "title": "Sheets", "guide": ("Read and change workbooks, tabs, cells, styles and charts. " @@ -64,6 +71,8 @@ for name, actions in external_tools._SHEET_OBJECT_ACTIONS.items(): GROUP["actions"][name.removesuffix("_object") + "." + action] = legacy_action( name, action=action, read=action in external_tools._OBJECT_READ_ACTIONS[name], destructive=action in {"delete", "clear"}) + operation = name.removesuffix("_object") + "." + action + GROUP["actions"][operation]["available"] = lambda operation=operation: _object_available(operation) GROUP["actions"]["read_batch"] = legacy_action("validated_batch", read=True) GROUP["actions"]["write_batch"] = legacy_action("validated_batch", read=False, destructive=True) GROUP["actions"]["workbook.view"] = { @@ -74,6 +83,22 @@ GROUP["actions"]["workbook.view"] = { "required": ["workbook_id"], "additionalProperties": False}, } GROUP["guide"] += " Use workbook.view with workbook_id to open the workbook view." +GROUP["guide"] += ( + " Use workbook.list to find readable workbook ids, names and revisions. " + "Send action='list' in the action arguments, with page_size and cursor inside its arguments object. " + "Follow next_cursor until it is null to read every workbook. " + "Use workbook.get with action='get' and workbook_id, or put an exact case-insensitive name in arguments.name. " + "A near name refuses with readable close names." +) +GROUP["actions"]["workbook.list"]["schema"]["properties"]["arguments"] = { + "type": "object", "properties": {"cursor": {"type": "string"}, + "page_size": {"type": "integer", "minimum": 1}}, "additionalProperties": False, +} +GROUP["actions"]["workbook.get"]["schema"]["properties"]["arguments"] = { + "type": "object", "properties": {"name": {"type": "string", "minLength": 1}, + "workbook_id": {"type": "string", "minLength": 1}, "id_or_name": {"type": "string", "minLength": 1}}, + "additionalProperties": False, +} GROUP["guide"] += ' Under MCP rule 9, ask "Do you want me to build a Sheet workbook in Loopable?".' _BATCH_GUIDE = ( " A batch has 1 to 50 operations for one workbook. Use name and arguments for each operation. " diff --git a/platform/core/external_tools.py b/platform/core/external_tools.py index 5fffd1244b7b94613937d6a291bb8c8014bcc300..530cde20712472b8a2fff0fae00d7fbde81df00e 100644 --- a/platform/core/external_tools.py +++ b/platform/core/external_tools.py @@ -140,46 +140,6 @@ _QUERY_FILTER = {"oneOf": [ _object({"link": _STRING, "where": _query_filter_node(allow_link=False)}, ("link", "where"), additionalProperties=False), ]} -FILTER_NODE_REF = "#/$defs/filter_node" -FILTER_NODE_EXAMPLE = {"conj": "and", "nodes": [ - {"colId": "status", "op": "eq", "value": "open"}, - {"conj": "or", "children": [{"colId": "amount", "op": "gt", "value": 100}, - {"colId": "region", "op": "eq", "value": "West"}]}, -]} - - -def _is_filter_node(value): - """Tell a published query filter node from any other schema.""" - branches = value.get("oneOf") if isinstance(value, dict) and set(value) == {"oneOf"} else None - first = branches[0] if isinstance(branches, list) and branches and isinstance(branches[0], dict) else {} - properties = first.get("properties") - return isinstance(properties, dict) and "colId" in properties and "op" in properties - - -def guide_schema(schema): - """Return a guide copy with each query filter node replaced by one reference, and whether any was.""" - if _is_filter_node(schema): - return {"$ref": FILTER_NODE_REF}, True - if isinstance(schema, list): - pairs = [guide_schema(item) for item in schema] - return [item for item, _ in pairs], any(used for _, used in pairs) - if not isinstance(schema, dict): - return copy.deepcopy(schema), False - pairs = {key: guide_schema(child) for key, child in schema.items()} - return {key: item for key, (item, _) in pairs.items()}, any(used for _, used in pairs.values()) - - -def filter_node_guide(): - """Return the one markdown section that defines the filter_node reference in a guide.""" - node = {"oneOf": [guide_schema(branch)[0] for branch in _QUERY_FILTER_NODE["oneOf"]]} - return ("## filter_node\n\n" - "A filter_node is a condition {colId, op, ...}, a group {conj, children: 1 to 50 filter_node}, " - "or a link {link, where}.\n" - "Groups nest at most two deep inside one node. A link's where holds no link.\n" - "Example filter: `" + json.dumps(FILTER_NODE_EXAMPLE, ensure_ascii=True) + "`\n" - "```json\n" + json.dumps({"$defs": {"filter_node": node}}, ensure_ascii=True, indent=2) + "\n```") - - _BINDING = _object({ "database": _STRING, "aggregate": _object({"fn": _STRING, "field": _STRING, "metric_key": _STRING}), diff --git a/platform/core/grid_events.py b/platform/core/grid_events.py index ef535dd6a8e87b7171ae640aac966b290fd15bba..808023949f5f84d1080a3c5686b1cc5937de4138 100644 --- a/platform/core/grid_events.py +++ b/platform/core/grid_events.py @@ -78,7 +78,9 @@ _FIELD_ECHO_PROPS = ('label', 'type', 'note', 'options', 'colorCodeOptions', # echo while the route still answers 200 - so the reader sees the change # land and then lose it. `showAs` is a DISPLAY mode, never an aggregate. 'showAs', - 'recurrence', 'if') + 'recurrence', 'if', + # S76-T28: '' , 0 and false are real defaults, so this key compares by type. + 'defaultValue') class StoreUnavailable(RuntimeError): @@ -1101,6 +1103,13 @@ def _field_echo_equal(accepted, raw): empty = ('', [], {}) for k in _FIELD_ECHO_PROPS: a, b = accepted.get(k), raw.get(k) if isinstance(raw, dict) else None + if k == 'defaultValue': + # Absence, '', False and 0 render differently, so no empty-collapse and no 0 == False. + have = (a is not None, type(a), a) # an explicit null is a clear, stored as absent + sent = (b is not None, type(b), b) + if have != sent: + return False + continue if k == 'scope': # 'global' and absent are the SAME rendering (an unscoped field) — the event may # say 'global' explicitly while the stored def says it by omission. @@ -2270,6 +2279,19 @@ def handle_one(event, ctx): fmt = _ag2._clean_format(raw.get('format'), ftype) if fmt: field['format'] = fmt + # S76-T28: explicit null clears a default; omission keeps it only from a same-type definition. + if 'defaultValue' in raw: + _default = raw.get('defaultValue') + else: + _prior_def = shared_prior if shared_field else (ws.get('fields') or {}).get(key) + _default = (_prior_def.get('defaultValue') if isinstance(_prior_def, dict) + and _prior_def.get('type') == ftype else None) + if _default is not None: + from core import user_tables as _ut_default + if readonly or not _ut_default._default_value_valid(field, _default): + return _refuse(ctx, 'bad_default_value', + 'The default value does not fit this field type.', key) + field['defaultValue'] = _default else: # ⛔ THE FALL-THROUGH, AND IT IS THE WIDEST OF THE EIGHT: the key is neither a base # contract field (a note/format override) nor a `custom_`/`measure_` key, so there is @@ -3662,20 +3684,31 @@ def handle_one(event, ctx): if updates: if _connector_cells: # Source refreshes own source rows. Authored cells use the same overlay as REST. - if choice_additions: - updates = _connector_overlay.put_cells_and_choice_options( - _history_table, pid, updates, choice_additions, st=ctx.table.st) - else: - updates = _connector_overlay.put_cells( - _history_table, pid, updates, st=ctx.table.st) + try: + if choice_additions: + updates = _connector_overlay.put_cells_and_choice_options( + _history_table, pid, updates, choice_additions, st=ctx.table.st) + else: + updates = _connector_overlay.put_cells( + _history_table, pid, updates, st=ctx.table.st) + except ValueError as exc: + # S76-T33: a registry Link condition refusal keeps its code and reason. + return _folder_refuse(ctx, kind, getattr(exc, 'code', None) or 'bad_value', + str(exc) or 'The edit was refused.', key=','.join(updates)) elif str(ctx.scope_key or '').startswith('ut_') and ctx.table is not None: # User-table cells are collaborative record data. Views/layout remain personal, # but record values live in the definition rows so Links, Rollups, automations, # and every viewer observe one truth. import core.user_tables as _ut_values - if not _ut_values.patch_cells( + try: + _cells_taken = _ut_values.patch_cells( ctx.scope_key, pid, updates, st=ctx.table.st, - by=ctx.by if ctx.by is not None else uname, via=ctx.via): + by=ctx.by if ctx.by is not None else uname, via=ctx.via) + except ValueError as exc: + # S76-T29/T33: a core value rule (number policy, Link condition) names its reason. + return _folder_refuse(ctx, kind, getattr(exc, 'code', None) or 'number_value_refused', + str(exc) or 'The edit was refused.', key=','.join(updates)) + if not _cells_taken: updates = {} refused = True elif _store_of(ctx).available(): diff --git a/platform/core/sheet_compat.py b/platform/core/sheet_compat.py index a30d704797250bf889ca03beac3d55195037a265..3d4f1c792b1b9be9433bdeaf500fdff21a43701a 100644 --- a/platform/core/sheet_compat.py +++ b/platform/core/sheet_compat.py @@ -48,6 +48,12 @@ _FPA = ".agents/skills/refresh-fpa/SKILL.md" # The evidence references are intentionally literal and machine-readable. Section 26 of the # Sheet gate re-censuses the source operations and requires every token to land on one row here. _OPERATIONS = ( + _cap("workbook.list", True, "List(cursor=None, page_size=100)", + "Pages every readable workbook's id, name and revision through the existing workbook permission resolver.", + ["aios-web/api/verify_sheet.py:section_s76_t47_workbook_discovery"]), + _cap("workbook.get", True, "Get(workbook_id | name)", + "Resolves a readable workbook by stable id or exact case-insensitive name, with readable close-name suggestions.", + ["aios-web/api/verify_api.py:section_s76_t47_workbook_discovery"]), _cap("workbooks.open", True, "Open(id_or_name, UpdateLinks=0, ReadOnly=False)", "Looks up one existing workbook by stable id, then exact case-insensitive name.", [f"{_SALES}:421", f"{_FPA}:153"]), @@ -886,6 +892,76 @@ def execute(st, workbook_id, operation, arguments=None, *, actor="", actor_name= return out +OBJECT_OPERATIONS = frozenset({"workbook.list", "workbook.get"}) + + +def dispatch_object_operation(*, session, object_name, action, arguments): + """Discover workbook identities through the same role resolver as the Sheet index.""" + import difflib + + operation = str(object_name) + "." + str(action) + if operation not in OBJECT_OPERATIONS: + raise CompatibilityRefusal("tool_capability_unsupported", "This Sheet action is not available yet.") + require_supported(operation) + session.require("sheets") + options = arguments.get("arguments") or {} + if not isinstance(options, dict): + raise CompatibilityRefusal("tool_arguments_invalid", "Workbook lookup arguments must be an object.") + st = session.runtime + visible = sheets.project_shares(st, sheets.list_workbooks(st), session.uname, is_admin=session.admin) + visible.sort(key=lambda row: str(row["id"])) + + def identity(row): + return {"id": row["id"], "name": row["name"], "rev": row["rev"]} + + if action == "list": + size = options.get("page_size", 100) + if type(size) is not int or size < 1: + raise CompatibilityRefusal("tool_arguments_invalid", "Workbook page_size must be a positive integer.") + cursor = options.get("cursor") + principal = [str(session.tenant), str(session.uname).casefold()] + after = "" + if cursor is not None: + try: + if not isinstance(cursor, str) or not cursor: + raise ValueError("empty cursor") + position = json.loads(base64.b64decode(cursor + "=" * (-len(cursor) % 4), altchars=b"-_", validate=True)) + if (not isinstance(position, dict) or position.get("principal") != principal + or not isinstance(position.get("after"), str) or not position["after"]): + raise ValueError("invalid cursor") + after = position["after"] + except (ValueError, TypeError, UnicodeError) as exc: + raise CompatibilityRefusal("tool_arguments_invalid", "That workbook cursor is invalid. Start a new list.") from exc + remaining = [row for row in visible if str(row["id"]) > after] + page = remaining[:size] + next_cursor = None + if len(remaining) > len(page): + next_cursor = base64.urlsafe_b64encode(json.dumps({ + "principal": principal, "after": str(page[-1]["id"]) + }, separators=(",", ":")).encode()).decode().rstrip("=") + return {"workbooks": [identity(row) for row in page], "next_cursor": next_cursor, "total": len(visible)} + + target = arguments.get("workbook_id") or options.get("workbook_id") or options.get("name") or options.get("id_or_name") + if not isinstance(target, str) or not target.strip(): + raise CompatibilityRefusal("tool_arguments_invalid", "Choose a workbook_id or an exact workbook name.") + target = target.strip() + matches = [row for row in visible if row["id"] == target] + if not matches: + matches = [row for row in visible if str(row["name"]).casefold() == target.casefold()] + if len(matches) > 1: + raise CompatibilityRefusal("workbook_unavailable", "More than one readable workbook has that exact name. Choose its workbook_id.") + if matches: + book = sheets.get_workbook(st, matches[0]["id"]) + if sheets.may_read_workbook(book, sheets.workbook_role(st, book, session.uname, is_admin=session.admin)): + return {"workbook": identity(book)} + names = {str(row["name"]).casefold(): str(row["name"]) for row in visible} + close = difflib.get_close_matches(target.casefold(), list(names), n=5, cutoff=0.5) + reason = "That workbook is not available to this account." + if close: + reason += " Close names: " + ", ".join(names[name] for name in close) + ". Use an exact name." + raise CompatibilityRefusal("workbook_missing", reason) + + def dispatch_validated_batch(*, runtime, operations, staging, dispatch, actor="", actor_name=""): """Stage native Sheet operations, then publish one workbook revision through its guarded writer.""" if not isinstance(operations, list) or not 1 <= len(operations) <= 50: diff --git a/platform/core/table_store.py b/platform/core/table_store.py index 07838471e9568fa9f7072cb873aa59ced90e6bc0..8c2679a046ce3b6a223a0373f9ebf2bd0e1f584b 100644 --- a/platform/core/table_store.py +++ b/platform/core/table_store.py @@ -1528,6 +1528,7 @@ class TableStore: if k not in ('filters', 'filterConj', 'memberPids')}, } def _up(data, audit): + record['updatedAt'] = write_execution.utcnow().isoformat() bucket = data.setdefault(ASSIGNED_KEY, {}).setdefault('views', {}) bucket.setdefault(who, {})[assignment_id] = record # ⭐ W50-T25 — C3's `share` action. The audit `owner` is the SOURCE VIEW's owner, @@ -1666,6 +1667,8 @@ class TableStore: ) payload = dict(requested) payload['name'] = _unique_name(payload.get('name'), names) + # S76-T37: the server stamps every View update; a client-sent updatedAt is never kept. + payload['updatedAt'] = write_execution.utcnow().isoformat() accepted.clear() accepted.update(payload) ws = data.setdefault(username, {}) @@ -2008,6 +2011,7 @@ class TableStore: payload = dict(entry.get('view') or {}) payload['id'] = vid payload['name'] = _unique_name(payload.get('name'), names) + payload['updatedAt'] = write_execution.utcnow().isoformat() data.setdefault(owner, {}).setdefault('views', {})[vid] = payload carried = entry.get('assignments') if isinstance(carried, dict) and carried: diff --git a/web/public/AIOS_DEPLOY_RECEIPT b/web/public/AIOS_DEPLOY_RECEIPT index 84bb9578baf0618966cabb52696cb51904ac764e..ac6c98bff43aca2a6ea1cdebca82da93062ec7e8 100644 --- a/web/public/AIOS_DEPLOY_RECEIPT +++ b/web/public/AIOS_DEPLOY_RECEIPT @@ -1 +1 @@ -3860b2103007bea62cccf6249230c80ce9f6f5b35c01af56ed6ea30aa116dcee +d0e73eb58bdf73f0d800c2e85fcb14924bcfd264e50cda5e7aa6449507d2cdd5 diff --git a/web/s71_frontend_contracts.py b/web/s71_frontend_contracts.py index f178f5fc2a58dbc2ddf84c30be70ac189efdc27a..5116acd9a7c5303d96e39f87c1bfbb5b4d5650ef 100644 --- a/web/s71_frontend_contracts.py +++ b/web/s71_frontend_contracts.py @@ -64,6 +64,53 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool = import json from playwright.sync_api import sync_playwright from verify_w45_data_applications import AppRoutingFixture + from verify_catalog import s76_t09_fixture_record, s76_t09_template_registry + + class CatalogHostFixture(AppRoutingFixture): + def __init__(self): + super().__init__() + self.catalog = s76_t09_fixture_record() + self.catalog["pages"][3]["bindings"]["products"] = ["WF-1", "CS-2"] + self.typed_cursors = [] + self.fields.extend([{"key": key, "label": key, "type": kind, "source": "odoo"} + for key, kind in (("stock", "text"), ("list_price", "int"), + ("category", "text"), ("description", "text"))]) + self.applications[0]["fieldMap"].update(sku="stock", price="list_price", + category="category", description="description") + for row in self.rows: + row.update(stock="Mapped sku", list_price=19.975, + category="Mapped category", description="Mapped description") + self.original_workspace = __import__("copy").deepcopy(self.workspace) + + def route(self, route): + from urllib.parse import urlsplit + request = route.request + path = urlsplit(request.url).path.removeprefix("/api/v1/") + result = None + if path == "typed/openapi.json": + properties = {field["key"]: {"type": "number" if field["type"] == "int" else "string"} + for field in self.fields} + properties["pid"] = {"type": "integer"} + result = {"components": {"schemas": {"Record_customer_data": {"properties": properties}}}} + elif path == "typed/databases/customer_data/query": + body = request.post_data_json + self.typed_cursors.append(body.get("cursor")) + if not self.rows: + result = {"database": self.database, "fields": self.fields, "records": [], + "page": {"returned": 0, "has_more": False, "next_cursor": None}} + elif request.method == "GET" and path == "apps/app-fixture/catalogs": + result = {"catalogs": [self.catalog] if self.catalog else [], "nextCursor": None} + elif request.method == "GET" and path == "catalogs/catalog-six": + result = {"catalog": self.catalog} + elif request.method == "GET" and path == "catalogs/templates": + result = s76_t09_template_registry() + result["kinds"][3]["templates"][0]["slots"] = [ + "title", "body", "products", "price", "sku", "category", "description"] + if result is None: + return super().route(route) + self.requests.append({"path": path, "method": request.method}) + route.fulfill(status=200, content_type="application/json", body=json.dumps(result)) + out_dir.mkdir(parents=True, exist_ok=True) evidence = {"checks": [], "controls": [], "errors": []} def check(name, value): @@ -76,12 +123,16 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool = with sync_playwright() as playwright: browser = playwright.chromium.launch(headless=True) try: - cases = ['catalog'] + (['settings-discriminator', 'route-listener', 'legacy-loader'] if negative_controls else []) + cases = ['catalog', 'empty-source', 'mobile'] + (['settings-discriminator', 'route-listener', 'legacy-loader'] if negative_controls else []) for case in cases: - fixture = AppRoutingFixture() + fixture = CatalogHostFixture() + if case == 'empty-source': + fixture.rows = [] + fixture.catalog = None + fixture.applications[0]['capabilities']['edit'] = True fixture.legacy_unavailable = True fixture.hold_registry = True - context = browser.new_context(viewport={"width": 1440, "height": 1000}) + context = browser.new_context(viewport={"width": 390 if case == 'mobile' else 1440, "height": 1000}) context.add_init_script("""window.catalogRouteListeners = []; const ordinaryAdd = window.addEventListener; window.addEventListener = function(type, ...args) { @@ -90,7 +141,7 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool = };""") context.route('**/api/**', fixture.route) applied = [] - if case != 'catalog': + if case in ('settings-discriminator', 'route-listener', 'legacy-loader'): old, new = ('applicationTemplateSurface(resolvedApplication) !== "catalog"', 'true') if case == 'settings-discriminator' \ else ('rowsEnabled: legacyRowsEnabled', 'rowsEnabled: true') if case == 'legacy-loader' \ else (r'if \(!routeApplicationSurface\) return;\s*const openRoute', 'const openRoute') @@ -135,7 +186,19 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool = continue check('held registry has no legacy rows', not early_legacy) fixture.release_registry() - page.locator('.cg-cat-stage .cg-cat-card').first.wait_for(timeout=30000) + page.locator('.cg-catalog-library').wait_for(timeout=30000) + check('Catalog library withholds source footer', page.locator('.cg-grid-footer, .cg-sum-bar').count() == 0) + if case == 'empty-source': + check('empty source opens the empty library', page.get_by_text('No catalogs yet', exact=True).count() == 1 + and page.get_by_role('button', name='New catalog', exact=True).count() == 1 + and page.locator('.cg-catalog-library-card').count() == 0) + check('empty source preserves the saved View', not fixture.view_events + and fixture.workspace == fixture.original_workspace) + page.screenshot(path=str(out_dir / 'catalog-empty-source.png'), full_page=True) + continue + page.get_by_role('button', name='Open Seasonal collection', exact=True).click() + page.locator('.cg-catalog-page-thumb[data-page-kind="grid"]').click() + page.locator('.cg-catalog-canvas .cg-catalog-product-open').first.wait_for(timeout=30000) page.wait_for_timeout(600) if case == 'settings-discriminator': check('Catalog discriminator removal fails controls absence', bool(applied) and not no_controls(page)) @@ -143,13 +206,40 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool = continue check('resolved Catalog has no Map/Bubble size/Routes', no_controls(page)) check('resolved Catalog registers no route-open handler', page.evaluate('window.catalogRouteListeners.length') == 0) - check('all cursor pages painted', sorted(page.locator('.cg-cat-stage .cg-cat-desc').all_text_contents()) + check('six editor page kinds remain available', + page.locator('.cg-catalog-page-thumb').evaluate_all("nodes => nodes.map(node => node.dataset.pageKind)") + == ['cover', 'toc', 'product', 'grid', 'section', 'closing']) + check('typed pool walks both cursor pages', None in fixture.typed_cursors + and 'fixture-next' in fixture.typed_cursors) + check('all cursor pages painted', sorted(page.locator('.cg-catalog-canvas .cg-catalog-product-open').evaluate_all( + "nodes => nodes.map(node => node.getAttribute('aria-label').slice(5))")) == ['Cedar Supply', 'Willow Floral']) - before = page.locator('.cg-cat-stage').inner_text() + before = page.locator('.cg-catalog-canvas').inner_text() + evidence['mapped_products'] = before + check('Catalog registry keeps every optional product role', + all(value in before for value in + ('19.975', 'Mapped sku', 'Mapped category', 'Mapped description'))) page.evaluate("window.dispatchEvent(new CustomEvent('aios:route-open', {detail:{routeId:'refused-route'}}))") page.wait_for_timeout(200) - check('Catalog ignores route-open', no_controls(page) and page.locator('.cg-cat-stage').inner_text() == before) - page.get_by_role('button', name='Open Cedar Supply', exact=True).click() + check('Catalog ignores route-open', no_controls(page) and page.locator('.cg-catalog-canvas').inner_text() == before) + check('Catalog editor withholds source footer', page.locator('.cg-grid-footer, .cg-sum-bar').count() == 0) + if case == 'mobile': + geometry = page.locator('.cg-catalog-canvas').bounding_box() + check('390px editor keeps a usable full-width canvas', geometry is not None + and geometry['width'] >= 250 and geometry['x'] + geometry['width'] <= 391) + check('390px editor preserves the shared App frame', + page.locator('.cg-app-frame-header').count() == 1 + and page.get_by_role('link', name='Back to Apps', exact=True).count() == 1) + heading = page.locator('.cg-catalog-record-head h2').evaluate( + 'node => {const range=document.createRange(); range.selectNodeContents(node); const r=range.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height};}') + actions = page.locator('.cg-catalog-record-head button').evaluate_all( + 'nodes => nodes.map(node => {const r=node.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height};})') + check('390px catalog title does not overlap its actions', len(actions) >= 3 and all( + heading['x'] + heading['width'] <= action['x'] or action['x'] + action['width'] <= heading['x'] + or heading['y'] + heading['height'] <= action['y'] or action['y'] + action['height'] <= heading['y'] + for action in actions)) + page.screenshot(path=str(out_dir / 'catalog-editor-390.png'), full_page=True) + page.locator('.cg-catalog-canvas').get_by_role('button', name='Open Cedar Supply', exact=True).click() page.locator('.cg-record-modal').wait_for(timeout=10000) check('real typed tail card drawer', 'Cedar Supply' in page.locator('.cg-record-modal').inner_text()) check('unavailable legacy endpoint never requested', not any(request['path'] == 'customers' for request in fixture.requests)) @@ -158,10 +248,15 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool = page.screenshot(path=str(out_dir / 'catalog-cold-drawer.png'), full_page=True) finally: context.close() - for surface in ('data-map', 'route'): + for surface in ('data-map', 'route', 'legacy-catalog'): fixture = AppRoutingFixture() fixture.config['display'] = {'mode': 'map'} fixture.workspace['views'][0]['config']['display'] = {'mode': 'map'} + if surface == 'legacy-catalog': + display = {'mode': 'catalog', + 'catalogs': fixture.applications[0]['config']['display']['catalogs']} + fixture.config['display'] = display + fixture.workspace['views'][0]['config']['display'] = display fixture.original_workspace = __import__('copy').deepcopy(fixture.workspace) if surface == 'route': fixture.fields.extend([{'key': 'lat', 'label': 'Latitude', 'type': 'number', 'source': 'odoo'}, @@ -171,14 +266,24 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool = fixture.applications[0]['templateKind'] = 'route' fixture.applications[0]['fieldMap'] = {'title': 'name', 'latitude': 'lat', 'longitude': 'lon'} fixture.applications[0]['config'] = {'display': {'mode': 'map'}} - context = browser.new_context(viewport={"width": 1440, "height": 1000}) + context = browser.new_context(viewport={"width": 390 if surface == 'legacy-catalog' else 1440, "height": 1000}) context.route('**/api/**', fixture.route) # Keep the product's offline map; a synthetic transport cannot make an outward tile read. context.route('https://tile.openstreetmap.org/**', lambda route: route.abort()) page = context.new_page() try: - page.goto(base_url + ('/#/data?database=customer_data&view=saved-check' if surface == 'data-map' + page.goto(base_url + ('/#/data?database=customer_data&view=saved-check' if surface != 'route' else '/#/app?database=customer_data&application=app-fixture')) + if surface == 'legacy-catalog': + page.locator('.cg-cat-stage').wait_for(timeout=30000) + stage = page.locator('.cg-cat-stage').bounding_box() + rail = page.locator('.cg-cat-rail').bounding_box() + check('390px legacy rail collapses above a usable page', stage is not None and rail is not None + and stage['width'] >= 200 and stage['x'] + stage['width'] <= 391 + and rail['height'] <= 129 and stage['y'] >= rail['y'] + rail['height']) + check('Data Catalog keeps its own footer', page.locator('.cg-grid-footer').count() == 1) + page.screenshot(path=str(out_dir / 'catalog-legacy-390.png'), full_page=True) + continue page.locator('.cg-map-settings').wait_for(timeout=30000) check(surface + ' keeps Map settings', page.get_by_text('Bubble size', exact=True).count() > 0) if surface == 'route': @@ -197,3 +302,213 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool = (out_dir / 'catalog-host.json').write_text(json.dumps(evidence, indent=2), encoding='utf-8') print(f"PASS S71 Catalog host mounted: {len(evidence['checks'])} checks, {len(evidence['controls'])} controls") return evidence + +def client_amend_contracts() -> int: + """Execute the edited callbacks with held acknowledgements and whole-batch refusals.""" + import subprocess + script = r''' +const fs = require("fs"), vm = require("vm"), ts = require("typescript"), assert = require("node:assert/strict"); +const grid = ts.createSourceFile("grid.tsx", fs.readFileSync("src/customer-grid/CustomerGrid.tsx", "utf8"), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); +const bridge = ts.createSourceFile("bridge.ts", fs.readFileSync("src/customer-grid/apiBridge.ts", "utf8"), ts.ScriptTarget.Latest, true); +const display = ts.createSourceFile("display.ts", fs.readFileSync("src/customer-grid/display.ts", "utf8"), ts.ScriptTarget.Latest, true); +let checks = 0; +function check(value, why) { assert.ok(value, why); checks++; } +function declaration(file, name) { + let found; + function visit(node) { + if ((ts.isVariableDeclaration(node) || ts.isFunctionDeclaration(node)) && node.name?.getText(file) === name) found = node; + ts.forEachChild(node, visit); + } + visit(file); assert.ok(found, "missing executable " + name); + return ts.isVariableDeclaration(found) ? "const " + found.getText(file) + ";" : found.getText(file).replace(/^export\s+/, ""); +} +function bind(name, context, file = grid) { + const source = declaration(file, name) + "\nglobalThis.subject = " + name + ";"; + const js = ts.transpileModule(source, {compilerOptions:{target:ts.ScriptTarget.ES2022, module:ts.ModuleKind.CommonJS}}).outputText; + const box = {useCallback: fn => fn, ...context}; + vm.runInNewContext(js, box); return box.subject; +} +function pure(name, context = {}, file = grid) { return bind(name, context, file); } +async function run() { + const numericOrUndefined = pure("numericOrUndefined", {}, display); + const numberWriteRefusal = pure("numberWriteRefusal", {numericOrUndefined}, display); + const numberBatchRefusal = pure("numberBatchRefusal", {numberWriteRefusal}); + const number = {key:"amount", label:"Amount", type:"currency", format:{currencySymbol:"EUR", allowNegative:false}}; + const fields = [number, {key:"note",label:"Note",type:"text"}]; + const writes = [], entries = [], toasts = []; + const ctx = {fields, numberBatchRefusal, currentValue:()=> "before", + patchOverlay:(...args)=>writes.push(args), recordCells:(...args)=>entries.push(args), + TOAST_EVENT:"toast", CustomEvent: class {constructor(type, init) {this.type=type;this.detail=init.detail;}}, + window:{dispatchEvent:event=>toasts.push(event)}}; + const single = bind("patchAndRecord", ctx), batch = bind("patchManyAndRecord", ctx); + single(1, {amount:"-1",note:"must stay unchanged"}); + check(writes.length === 0 && entries.length === 0 && toasts.at(-1).detail.tone === "error", "single negative is a C4 refusal before writes or undo"); + batch([{pid:1,updates:{amount:"5"}},{pid:2,updates:{amount:"Infinity"}}], "paste"); + check(writes.length === 0 && entries.length === 0, "mixed valid and invalid paste is atomic"); + for (const value of ["", "0", "125.6789"]) single(1, {amount:value}); + check(writes.length === 3 && entries.length === 3, "blank, zero and unrounded valid writes retain undo"); + const changedFields = [{...number, format:{...number.format, allowNegative:true}}]; + bind("patchAndRecord", {...ctx,fields:changedFields})(1,{amount:"-5"}); + check(writes.length === 4, "current field policy admits a valid negative"); + let fetched = 0, closed = 0, busy = 0; + const noop = () => {}; + await bind("applyBulkUpdate", {...ctx, bulkField:number,bulkSelectedCount:20,bulkValue:"-2", + clearSelection:noop,dropTableRowsCache:noop,patchManyAndRecord:batch,requestWindow:noop,scope:"ut_fixture", + selectedPids:new Set([1]),serverBulkPending:false,serverFilteredSelection:{token:"selection"}, + windowRequest:noop,setServerBulkPending:()=>busy++,setBulkUpdateOpen:()=>closed++,fetch:()=>fetched++})(); + check(fetched === 0 && closed === 0 && busy === 0, "server filtered bulk refuses before request, busy state or dialog dismissal"); + const buildOverlayField = pure("buildOverlayField", {DEFAULT_SUMMED_TYPES:[],slugify:pure("slugify")}); + for (const value of [0,false,""]) check(buildOverlayField("Default","text",[],{defaultValue:value}).defaultValue === value, "falsy default survives constructor"); + check(Object.hasOwn(buildOverlayField("Clear","text",[],{defaultValue:null}),"defaultValue"), "explicit default clear retains property presence"); + const createdDefinitions = []; + let createdFields = []; + const create = bind("createField",{canAddField:true,scopeChoice:false,isUserTable:true,scope:"ut_fixture", + buildOverlayField,insertColumn:noop,saveField:()=>{throw Error("wrong definition door");},stampFieldEdit:noop,stampFieldDelete:noop, + setFields:update=>{createdFields=update(createdFields);}, + addTableField:(_scope,definition)=>{createdDefinitions.push(definition);return new Promise(()=>{});}}); + for (const [kind,value] of [["text",""],["int",0],["checkbox",false],["text",null]]) + create("Default",kind,null,"end",undefined,undefined,{defaultValue:value}); + check(createdDefinitions.slice(0,4).map(field=>JSON.stringify(field.defaultValue)).join() === '"",0,false,null', + "field creation forwards blank, zero, false and explicit clear through the definition body"); + create("Choice","select",null,"end",["Active"],undefined,{defaultValue:"Active"}); + create("Date","date",null,"end",undefined,undefined,{defaultValue:"2026-10-19"}); + check(createdDefinitions[4].defaultValue === "Active" && createdDefinitions[5].defaultValue === "2026-10-19", + "select and date defaults use the same field creation body"); + const patches = []; + const old = {key:"amount",label:"Amount",type:"int",source:"overlay",custom:true,defaultValue:0}; + const retype = bind("retypeField", {fieldByKey:new Map([["amount",old]]),saveField:()=>{throw Error("wrong definition door");}, + scope:"ut_fixture",isUserTable:true,emitHostEvent:noop,isUserSchemaField:()=>true, + patchTableField:async(_scope,_key,patch)=>{patches.push(patch);return null;},setFields:noop,signal:noop}); + retype("amount","int"); retype("amount","int",[],{defaultValue:null}); + check(patches[0].defaultValue === 0 && patches[1].defaultValue === null, "retype preserves zero or sends explicit clear on the schema PATCH"); + let pending = [], overlays = {}, undo = {past:[],future:[]}, resolveAdd, request; + const scope = "ut_fixture", workspaceScopeRef = {current:scope}; + const setPendingRows = update => {pending = update(pending);}; + const setOverlayEdits = update => {overlays = update(overlays);}; + const acceptPendingRow = bind("acceptPendingRow",{scope,workspaceScopeRef,setPendingRows,setOverlayEdits}); + const undoBook = {current:{}}, stackFor=()=>undo, pushUndo=(_state,entry)=>{undo={...undo,past:[...undo.past,entry]};return undo;}; + const defaults = [{key:"name",type:"text",defaultValue:"base"},{key:"zero",type:"int",defaultValue:0}, + {key:"tick",type:"checkbox",defaultValue:false},{key:"choice",type:"select",defaultValue:"Active"}, + {key:"starts",type:"date",defaultValue:"2026-11-01"},{key:"date",type:"date",defaultValue:"2026-10-19"},{key:"denied",type:"text",defaultValue:"hidden",denied:true}]; + const append = bind("appendRow", {canMutateRecords:true,scope,seedValues:()=>({name:"seed",date:""}),mintRid:()=>7, + fields:defaults,payload:{viewer:{username:"qa"}},mayEditField:field=>!field.denied, + setPendingRows,setNewRowPid:noop,addTableRow:(...args)=>{request=args;return new Promise(resolve=>{resolveAdd=resolve;});}, + acceptPendingRow,workspaceScopeRef,undoBook,stackFor,pushUndo}); + const adding = append(); + check(pending[0].zero === "0" && pending[0].tick === "False" && pending[0].name === "seed" && pending[0].date === "" && pending[0].choice === "Active" && pending[0].starts === "2026-11-01" + && !Object.hasOwn(pending[0],"denied"), "authorized defaults paint immediately below explicit seeds"); + check(request[1].zero === "0" && request[1].tick === "False" && request.length === 3, "append sends painted defaults with ordinary restore=false call"); + overlays[7]={name:"typed while pending"}; + resolveAdd({rid:"8",pid:8,values:{name:"server",sequence:"51",creator:"qa"}}); + await adding; + check(pending[0].pid === 8 && pending[0].sequence === "51" && overlays[8].name === "typed while pending" && !overlays[7], + "acknowledgement supplies generated cells and moves later local overlay to returned identity"); + check(undo.past[0].rows[0].values.zero === "0" && undo.past[0].rows[0].rid === "8", "append undo captures defaults and accepted identity"); + const stale = [], restores = [], deleted = []; + const restoreEntry = {kind:"rowAdd",table:scope,rows:[{rid:"9",values:{name:"restored",sequence:"old",creator:"forged",modified:"old",modifier:"forged"}}]}; + let resolveRestore; + const restoreRowsRef = {current:[]}; + const applyEntry = bind("applyEntry", {fields:[{key:"sequence",type:"autonumber"},{key:"creator",type:"created_by"}, + {key:"modified",type:"last_modified_time"},{key:"modifier",type:"last_modified_by"}], + AUDIT_FIELD_TYPES:["created_by","last_modified_time","last_modified_by"],directed:entry=>entry,patchOverlay:noop, + withdrawPending:ids=>{pending=pending.filter(row=>!ids.map(Number).includes(row.pid));},emitHostEvent:noop, + acceptPendingRow,workspaceScopeRef,setPendingRows,setOverlayEdits,rowsRef:restoreRowsRef,mintRid:()=>11,addTableRow:(...args)=>{restores.push(args);return new Promise(resolve=>{resolveRestore=resolve;});}, + deleteTableRow:async(_table,rid)=>{deleted.push(rid);return true;},signal:(...args)=>stale.push(args), + ROWS_STALE_EVENT:"stale",TOAST_EVENT:"toast",describe:()=>"undo",applyingUndo:{current:false}}); + const restoring = applyEntry(restoreEntry,"forward"); + const optimistic = pending.find(row=>row.pid === 9); + check(optimistic && Object.keys(optimistic).sort().join() === "name,pid" + && Object.keys(restores[0][1]).join() === "name" && restores[0][3] === true, "all four generated kinds stay out of restore request and optimistic cells"); + resolveRestore({rid:"10",pid:10,values:{sequence:"52",creator:"original",modified:"fresh",modifier:"qa"}}); + await restoring; + check(pending.find(row=>row.pid === 10)?.creator === "original" && !stale.some(event=>event[0] === "stale"), + "restored creator, counter and modifier paint from ack without a full refresh"); + await applyEntry({...restoreEntry,kind:"rowDelete"},"forward"); + check(deleted[0] === "10" && !pending.some(row=>row.pid === 10), "redo deletes the accepted restored identity without a ghost"); + restoreRowsRef.current = pending; + const occupied = {kind:"rowAdd",table:scope,rows:[{rid:"8",values:{name:"other restored row"}}]}; + const colliding = applyEntry(occupied,"forward"); + check(pending.find(row=>row.pid === 8)?.name === "server" && pending.find(row=>row.pid === 11)?.name === "other restored row", + "occupied restore keeps the existing pending row and paints a separate temporary identity"); + resolveRestore({rid:"12",pid:12,values:{sequence:"53",creator:"original"}}); + await colliding; + check(pending.some(row=>row.pid === 8) && pending.some(row=>row.pid === 12) && occupied.rows[0].rid === "12", + "collision acknowledgement and next undo retain both real identities"); + restoreRowsRef.current = pending; + const refusedRestore=applyEntry({kind:"rowAdd",table:scope,rows:[{rid:"8",values:{name:"refused"}}]},"forward"); + resolveRestore(null); await refusedRestore; + check(pending.some(row=>row.pid === 8) && !pending.some(row=>row.pid === 11), + "a refused collision withdraws only its temporary row and preserves the occupied record"); + const linkSelectionPredicate = pure("linkSelectionPredicate"); + const restriction = {conj:"and",nodes:[{colId:"status",op:"eq",value:"Active"}]}; + const candidate = {filterConj:"or",filters:[{colId:"name",op:"contains",value:"Cedar"},{colId:"name",op:"contains",value:"Willow"}]}; + const narrowed = linkSelectionPredicate(candidate,restriction); + check(narrowed.filterConj === "and" && narrowed.filters[0].children === restriction.nodes + && narrowed.filters[1].conj === "or" && narrowed.filters[1].children === candidate.filters, "candidate OR search remains inside the immutable AND restriction"); + check(linkSelectionPredicate({filters:[]},restriction).filters[0].children === restriction.nodes, "clearing search cannot relax link restriction"); + const hookSlots = [], windowCalls = [], completions = []; + let cursor = 0, unavailableCondition = false; + const hookContext = { + useRef:initial=>{const i=cursor++;return hookSlots[i]??=( {current:initial} );}, + useState:initial=>{const i=cursor++;if (!(i in hookSlots)) hookSlots[i]=initial; + return [hookSlots[i],value=>{hookSlots[i]=typeof value === "function" ? value(hookSlots[i]) : value;}];}, + useCallback:fn=>fn,useEffect:()=>{},linkSelectionPredicate,ROWS_STALE_EVENT:"stale", + unresolvedConditions:()=>unavailableCondition ? 1 : 0,window:ctx.window,CustomEvent:ctx.CustomEvent,TOAST_EVENT:"toast", + fetchTableWindow:(table,request)=>{windowCalls.push({table,request});return new Promise(resolve=>completions.push(resolve));}}; + const windowHook = pure("useRecordIdWindow",hookContext); + const renderWindow = filter=>{cursor=0;return windowHook("ut_target",undefined,null,undefined,false,false,filter);}; + const firstWindow = renderWindow(restriction); + check(firstWindow.payload === null && firstWindow.pending, "restricted picker withholds an unfiltered initial payload"); + firstWindow.requestWindow({...candidate,offset:50,limit:50,search:"Cedar"}); + check(windowCalls[0].request.filterConj === "and" && windowCalls[0].request.filters[0].children === restriction.nodes + && windowCalls[0].request.offset === 50 && windowCalls[0].request.search === "Cedar", + "real window callback sends immutable restriction with search and page before server counts"); + const changedRestriction={conj:"and",nodes:[{colId:"status",op:"eq",value:"Ready"}]}; + const secondWindow=renderWindow(changedRestriction); + completions[0]({rows:[{pid:1}],counts:{matched:99}}); await Promise.resolve(); + check(renderWindow(changedRestriction).payload === null, "stale response from an older link condition cannot populate the picker"); + secondWindow.requestWindow({offset:0,limit:50,filters:[],search:""}); + completions[1]({fields:[{key:"status",type:"text"}],rows:[{pid:2}],counts:{matched:1}}); await Promise.resolve(); + check(renderWindow(changedRestriction).payload?.counts.matched === 1, "fresh restricted response owns rows and count"); + unavailableCondition = true; + const toastCount = toasts.length; + renderWindow(changedRestriction).requestWindow({offset:0,limit:50,filters:[]}); + completions[2]({fields:[],rows:[{pid:3}],counts:{matched:99}}); await Promise.resolve(); + check(renderWindow(changedRestriction).payload === null && toasts.length === toastCount + 1 && toasts.at(-1).detail.tone === "error", + "an unavailable restriction withholds broader rows and counts with a C4 refusal"); + const posts = []; + let reply = {rid:"12",pid:12,values:{pid:999,zero:0,blank:null,tick:false,private:{secret:"no"}}}; + const add = bind("addTableRow", {API_V1:"/api/v1",CREDENTIALS:"include",JSON_HEADERS:{"Content-Type":"application/json"}, + fetch:async(_url,init)=>{posts.push(JSON.parse(init.body));return {ok:true};},handledSession:()=>false, + readJson:async()=>reply,dropTableRowsCache:noop,signal:noop,TOAST_EVENT:"toast",DATA_ERROR_EVENT:"error"}, bridge); + const ack = await add(scope,{name:"new"},12); + check(posts[0].restore === false && ack.pid === 12 && ack.values.zero === 0 && ack.values.blank === null && ack.values.tick === "False" + && !Object.hasOwn(ack.values,"pid") && !Object.hasOwn(ack.values,"private"), "ordinary create sends false and normalizes authorized scalar acknowledgement cells"); + reply={rid:"12",pid:12}; const legacy=await add(scope,{},12,true); + check(posts[1].restore === true && !Object.hasOwn(legacy,"values"), "restore transport tolerates an older identity-only acknowledgement"); + console.log("PASS W3 client amendments: " + checks + "/" + checks + " checks"); +} +run().catch(error=>{console.error(error.stack);process.exitCode=1;}); +''' + result = subprocess.run(["node", "-"], input=script, text=True, cwd=WEB, timeout=45) + return result.returncode + + +if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--client", action="store_true") + parser.add_argument("--base-url") + parser.add_argument("--out-dir", type=Path, default=Path("/tmp/aios-w3-host")) + args = parser.parse_args() + if args.client: + result = client_amend_contracts() + if result or not args.base_url: + raise SystemExit(result) + if args.base_url: + from urllib.parse import urlsplit + if urlsplit(args.base_url).hostname not in ("127.0.0.1", "localhost", "::1"): + parser.error("The synthetic fixture requires a local Vite origin") + mounted_catalog_host(args.base_url, args.out_dir) + else: + raise SystemExit(catalog_host_scan()) diff --git a/web/src/apps/catalog/CatalogApp.tsx b/web/src/apps/catalog/CatalogApp.tsx index 3ec161b28d6bb2f6e08033a420def9fe37588055..dd6d3b694b7d78fda40c05594045b578bd74768f 100644 --- a/web/src/apps/catalog/CatalogApp.tsx +++ b/web/src/apps/catalog/CatalogApp.tsx @@ -45,9 +45,6 @@ export function CatalogApp({ definition, database, scope, onOpen, onData, editor ; } const filteredCodes = data.rows.map((row) => String(row[definition.fieldMap.key] ?? "").trim()).filter(Boolean); - if (!filteredCodes.length) { - return
No records have a value in the mapped key field.
; - } return
diff --git a/web/src/apps/code/CodeAppPage.tsx b/web/src/apps/code/CodeAppPage.tsx index c4924f32b29d6e2dc4259437233dc3f6a6d74cf9..96e087b18e31a55068940b8dcfc98c43cf0a9e84 100644 --- a/web/src/apps/code/CodeAppPage.tsx +++ b/web/src/apps/code/CodeAppPage.tsx @@ -1,5 +1,5 @@ -import { useEffect, useState } from "react"; -import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../../apiContract"; +import { useEffect, useRef, useState } from "react"; +import { API_V1, CREDENTIALS, TOAST_EVENT, UNAUTHORIZED_EVENT, checkTenant, signal } from "../../apiContract"; import CodeAppFrame from "./CodeAppFrame"; import { checkCodeAppSize } from "./frameDocument"; import ConfirmDelete, { useConfirmDelete } from "./ConfirmDelete"; @@ -49,6 +49,12 @@ function Loading() { export default function CodeAppPage({ applicationId, bootstrapBase }: { applicationId: string; bootstrapBase?: string }) { const [retry, setRetry] = useState(0); const [state, setState] = useState({ kind: "loading", id: applicationId }); + const announced = useRef(null); + useEffect(() => { + if (state.id !== applicationId || state.kind !== "refused" || announced.current === state) return; + announced.current = state; + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text: state.message, tone: "error" } })); + }, [state, applicationId]); const { request, confirmDelete, confirmTool } = useConfirmDelete(); useEffect(() => { const controller = new AbortController(); @@ -86,11 +92,11 @@ export default function CodeAppPage({ applicationId, bootstrapBase }: { applicat onReady={() => setState((value) => value.kind === "ready" && value.id === current.id ? { ...value, started: true } : value)} onRefused={(message) => setState({ kind: "refused", id: current.id, message })} />} - {(current.kind === "error" || current.kind === "refused") &&

{current.message}

- {current.kind === "error" && } +
} ; } diff --git a/web/src/apps/customer-card/CustomerCardView.tsx b/web/src/apps/customer-card/CustomerCardView.tsx index 2d9b99861dc7ff9b2962473aac9cee299ba9b04a..e55382a81012206400de6a05ef28b218eb5e26ca 100644 --- a/web/src/apps/customer-card/CustomerCardView.tsx +++ b/web/src/apps/customer-card/CustomerCardView.tsx @@ -1,5 +1,5 @@ import { useEffect, useRef, useState } from "react"; -import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../../apiContract"; +import { API_V1, CREDENTIALS, TOAST_EVENT, UNAUTHORIZED_EVENT, checkTenant, signal } from "../../apiContract"; import { ConfirmDialog } from "../../ui/ConfirmDialog"; import "../../styles/sdlc74/customer-card.css"; @@ -87,6 +87,30 @@ function dueDate(value: string | null): string { type EmailPreview = { previewToken: string; to: string; subject: string; body: string; refusal?: string | null }; type EmailResult = { state: "queued" | "refused"; created: number; message?: string }; +class EmailRefused extends Error {} + +function useRefusalToast() { + const [messages, setMessages] = useState<{ id: number; text: string }[]>([]); + const sequence = useRef(0); + const delivered = useRef(0); + useEffect(() => { + if (!messages.length) return; + const through = messages[messages.length - 1].id; + for (const message of messages) { + if (message.id <= delivered.current) continue; + delivered.current = message.id; + const text = message.text; + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } })); + } + setMessages((current) => current.filter((message) => message.id > through)); + }, [messages]); + return (text: string) => { + if (!text) return; + const message = { id: ++sequence.current, text }; + setMessages((current) => [...current, message]); + }; +} + async function emailRequest(path: string, body: object, abort: AbortSignal): Promise { const response = await fetch(`${API_V1}${path}`, { method: "POST", credentials: CREDENTIALS, @@ -94,7 +118,11 @@ async function emailRequest(path: string, body: object, abort: AbortSignal): if (checkTenant(response)) throw new Error("Workspace changed."); if (response.status === 401) signal(UNAUTHORIZED_EVENT); const result = await response.json(); - if (!response.ok) throw new Error(result?.error?.message || "The email could not be prepared."); + if (!response.ok) { + const message = result?.error?.message || "The email could not be prepared."; + if ([401, 403, 404].includes(response.status)) throw new EmailRefused(message); + throw new Error(message); + } return result as T; } @@ -102,6 +130,7 @@ function CustomerCardEmail({ context, onEmailLink }: { context: CustomerCardPrivatePreview; onEmailLink?: CustomerCardViewProps["onEmailLink"]; }) { + const emailRefusal = useRefusalToast(); const [preview, setPreview] = useState(null); const [preparing, setPreparing] = useState(false); const [queueing, setQueueing] = useState(false); @@ -147,10 +176,14 @@ function CustomerCardEmail({ context, onEmailLink }: { if (typeof next.previewToken !== "string" || !next.previewToken || typeof next.to !== "string" || typeof next.subject !== "string" || typeof next.body !== "string") throw new Error("The email could not be prepared."); setPreview(next); + if (next.refusal) emailRefusal(next.refusal); } catch (error) { if (mounted.current && !request.signal.aborted) { - setResult(error instanceof Error ? error.message : "The email could not be prepared."); - setFailed(true); + if (error instanceof EmailRefused) emailRefusal(error.message); + else { + setResult(error instanceof Error ? error.message : "The email could not be prepared."); + setFailed(true); + } } } finally { if (mounted.current && !request.signal.aborted) { pending.current = false; setPreparing(false); } @@ -159,6 +192,7 @@ function CustomerCardEmail({ context, onEmailLink }: { async function queueEmail() { if (!preview || pending.current) return; + if (preview.refusal) { emailRefusal(preview.refusal); return; } const request = new AbortController(); controller.current = request; pending.current = true; @@ -168,12 +202,21 @@ function CustomerCardEmail({ context, onEmailLink }: { { previewToken: preview.previewToken, confirm: true }, request.signal); if (!mounted.current || request.signal.aborted) return; if (next.state !== "queued" && next.state !== "refused") throw new Error("Queueing was not confirmed. Check Odoo before trying again."); - setResult(next.state === "queued" ? "Queued" : "Safe mode does not allow this recipient address."); - setFailed(next.state === "refused"); + if (next.state === "refused") { + setResult(""); + setFailed(false); + emailRefusal("Safe mode does not allow this recipient address."); + } else { + setResult("Queued"); + setFailed(false); + } } catch (error) { if (mounted.current && !request.signal.aborted) { - setResult(error instanceof Error ? error.message : "Queueing was not confirmed. Check Odoo before trying again."); - setFailed(true); + if (error instanceof EmailRefused) { setResult(""); emailRefusal(error.message); } + else { + setResult(error instanceof Error ? error.message : "Queueing was not confirmed. Check Odoo before trying again."); + setFailed(true); + } } } finally { if (mounted.current && !request.signal.aborted) { @@ -199,7 +242,6 @@ function CustomerCardEmail({ context, onEmailLink }: {

Subject

{preview.subject}

Body

{preview.body}

- {preview.refusal &&

{preview.refusal}

} } /> ; } diff --git a/web/src/artifacts/ArtifactsPage.tsx b/web/src/artifacts/ArtifactsPage.tsx index ca6d5e78cf26f5f72e96520ea762806e267958a1..8b3d3e6fbf8242f4abf22b62727c4189f930abc4 100644 --- a/web/src/artifacts/ArtifactsPage.tsx +++ b/web/src/artifacts/ArtifactsPage.tsx @@ -505,6 +505,14 @@ export default function ArtifactsPage({ granted }: { granted: NavEntry[] }) { const frozenValue = snapshot?.page?.frozen_at ?? (selected as FileFields | undefined)?.frozen_at; const frozenAt = typeof frozenValue === "string" && Number.isFinite(Date.parse(frozenValue)) ? frozenValue : undefined; const queryId = selected?.kind === "query" ? selected.ref || undefined : selection.view; + const unavailableKey = selected + ? ((selected.kind === "pdf" && !selected.ref) || fileMissing || worklist?.refused ? selected.id : "") + : loaded && !loading && !problem && !nextCursor && !queryId + ? selection.item || selection.view || "" : ""; + useEffect(() => { + if (!unavailableKey) return; + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text: ARTIFACT_UNAVAILABLE, tone: "error" } })); + }, [unavailableKey]); const isSavedQuery = (item: Artifact) => item.kind === "query" && views.some((view) => view.id === item.ref); const resolveHref = safeWorklistLink(worklist?.page?.resolve.href); const queryItems = items.filter(isSavedQuery); @@ -638,7 +646,6 @@ export default function ArtifactsPage({ granted }: { granted: NavEntry[] }) {
: null} {replies[selected.id] ?

{replies[selected.id]}

: null} {made[selected.id] ?

{made[selected.id]}

: null} - {selected.kind === "pdf" && !selected.ref || fileMissing || worklist?.refused ?

{ARTIFACT_UNAVAILABLE}

: null} {selectedKind === "image" && fileHref ?
{plain(selected.title)}
: null} {selectedKind === "snapshot" ?
@@ -653,8 +660,7 @@ export default function ArtifactsPage({ granted }: { granted: NavEntry[] }) { {selected.kind === "report" && !worklist?.refused ? void showMoreWorklist()} onRetry={() => setWorklistToken((value) => value + 1)} /> : null} - : loaded && (selection.item || selection.view) && !loading && !nextCursor && !queryId - ?

{replies[selection.item || ""] || ARTIFACT_UNAVAILABLE}

: null} + : null} {queryId ?
}>
: null} diff --git a/web/src/automation/AutomationDetail.tsx b/web/src/automation/AutomationDetail.tsx index 0530dbcb7d061f1ee50c6677890a183f86cdf48a..72db1b75a08f03b57cc6e3d7e664546fe7f6517d 100644 --- a/web/src/automation/AutomationDetail.tsx +++ b/web/src/automation/AutomationDetail.tsx @@ -22,6 +22,7 @@ import PanelToggleIcon from "../shell/PanelToggleIcon"; // what this codebase treats as a defect rather than a summary. // --------------------------------------------------------------------------- import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { TOAST_EVENT } from "../apiContract"; import AutomationBuilder from "./AutomationBuilder"; import HarnessPanel from "./HarnessPanel"; @@ -334,6 +335,28 @@ function RetiredAutomationResult({ automation }: { automation: Automation }) { ); } +function useRefusalToast() { + const [messages, setMessages] = useState<{ id: number; text: string }[]>([]); + const sequence = useRef(0); + const delivered = useRef(0); + useEffect(() => { + if (!messages.length) return; + const through = messages[messages.length - 1].id; + for (const message of messages) { + if (message.id <= delivered.current) continue; + delivered.current = message.id; + const text = message.text; + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } })); + } + setMessages((current) => current.filter((message) => message.id > through)); + }, [messages]); + return useCallback((text: string) => { + if (!text) return; + const message = { id: ++sequence.current, text }; + setMessages((current) => [...current, message]); + }, []); +} + export default function AutomationDetailView(props: Props) { return props.automation.retired ? @@ -391,7 +414,16 @@ function AutomationDetail({ const [name, setName] = useState(automation.name || ""); const [cron, setCron] = useState(automation.schedule?.cron || "0 6 * * *"); const [message, setMessage] = useState(""); - const [problem, setProblem] = useState(""); + const [problem, setInlineProblem] = useState(""); + const refuse = useRefusalToast(); + const setProblem = useCallback((text: string, error?: unknown) => { + if (error instanceof AutomationError && [401, 403, 404].includes(error.status)) { + setInlineProblem(""); + refuse(text); + } else setInlineProblem(text); + }, [refuse]); + const mutationProblem = (error: unknown, fallback: string) => + setProblem(error instanceof Error ? error.message : fallback, error); const [saving, setSaving] = useState(false); const [touched, setTouched] = useState(false); const [triggerBusy, setTriggerBusy] = useState(false); @@ -626,7 +658,7 @@ function AutomationDetail({ try { const { workflow, agent } = await createAgentWorkflow(automation.id, asked); setAgentContract(agent); setActiveWorkflow(workflow.id); - } catch (error) { setProblem(error instanceof Error ? error.message : "Workflow could not be created."); } + } catch (error) { mutationProblem(error, "Workflow could not be created."); } }; /** * ⭐ W47-T20 — `forDatabase` IS THE ONE ADDITION, AND IT CLOSES A REAL HAZARD RATHER THAN @@ -657,7 +689,7 @@ function AutomationDetail({ workflows: { ...existing, [activeWorkflow]: workflowGrants }, }); setAgentContract(agent); - } catch (error) { setProblem(error instanceof Error ? error.message : "Automation governance could not be saved."); } + } catch (error) { mutationProblem(error, "Automation governance could not be saved."); } }; // The panel fold persists across visits. const [railShut, setRailShut] = useState(() => { @@ -1081,7 +1113,7 @@ function AutomationDetail({ setMessage(heldNote()); await onSaved(fresh.id, fresh); // W31-T31: the response, not a second read } catch (e) { - setProblem(e instanceof AutomationError ? e.message : "That schedule was not saved."); + mutationProblem(e, "That schedule was not saved."); } finally { setTriggerBusy(false); } @@ -1118,7 +1150,7 @@ function AutomationDetail({ setMessage(heldNote()); await onSaved(fresh.id, fresh); // W31-T31: the response, not a second read } catch (e) { - setProblem(e instanceof AutomationError ? e.message : "That trigger was not saved."); + mutationProblem(e, "That trigger was not saved."); } finally { setTriggerBusy(false); } @@ -1163,7 +1195,7 @@ function AutomationDetail({ try { fresh = await persist(); } catch (e) { - setProblem(e instanceof AutomationError ? e.message : "That could not be saved."); + mutationProblem(e, "That could not be saved."); return; } finally { // ⭐ HERE, not after `onSaved`. This is the whole ticket. @@ -1192,7 +1224,7 @@ function AutomationDetail({ const { automation: fresh } = await toggleNode(automation.id, nodeId); await onSaved(fresh.id, fresh); } catch (e) { - setProblem(e instanceof AutomationError ? e.message : "That step was not changed."); + mutationProblem(e, "That step was not changed."); } }; @@ -1238,7 +1270,7 @@ function AutomationDetail({ ); await onSaved(automation.id); } catch (e) { - setProblem(e instanceof AutomationError ? e.message : "It did not start."); + mutationProblem(e, "It did not start."); } }; @@ -1249,7 +1281,11 @@ function AutomationDetail({ itemDeleted({ kind: "automation", id: automation.id }); await onDeleted(); } catch (e) { - setProblem(e instanceof AutomationError ? e.message : "It was not deleted."); + if (e instanceof AutomationError && [401, 403, 404].includes(e.status)) { + setProblem(e.message, e); + } else { + setProblem(e instanceof AutomationError ? e.message : "It was not deleted."); + } } }; @@ -1283,7 +1319,7 @@ function AutomationDetail({ const { automation: fresh } = await getAutomation(automation.id); await onSaved(fresh.id, fresh); } catch (e) { - setProblem(e instanceof AutomationError ? e.message : "Those statements were not sent."); + mutationProblem(e, "Those statements were not sent."); } finally { setSending(false); } @@ -1355,7 +1391,7 @@ function AutomationDetail({ // action kind, a valueless compare — each with a reason worth reading. A client that // predicted those refusals would be a second validator free to disagree with the one // that decides. - setProblem(e instanceof AutomationError ? e.message : "That change was not saved."); + mutationProblem(e, "That change was not saved."); } finally { setTriggerBusy(false); } @@ -1964,7 +2000,7 @@ function AutomationDetail({ ? Array.from(new Set([...agentContract.sharing.sharedWith, recipient!])) : [], workflows: agentContract.capabilities.workflows, }); setAgentContract(agent); - } catch (error) { setProblem(error instanceof Error ? error.message : "Sharing could not be saved."); } + } catch (error) { mutationProblem(error, "Sharing could not be saved."); } }}>{agentContract.sharing.visibility === "private" ? "Share automation" : "Make private"} ) : null} diff --git a/web/src/automation/AutomationSurface.tsx b/web/src/automation/AutomationSurface.tsx index 66023af94858ba4f9b67604423ec8c6fa720b09d..e519a8d86549514dba04e951c50dbfd022b5bbad 100644 --- a/web/src/automation/AutomationSurface.tsx +++ b/web/src/automation/AutomationSurface.tsx @@ -18,7 +18,7 @@ import type { KeyboardEvent as ReactKeyboardEvent } from "react"; import { Suspense, lazy, useCallback, useEffect, useRef, useState } from "react"; import type { AutomationOpenDetail } from "../apiContract"; -import { AUTOMATION_OPEN_EVENT, UNAUTHORIZED_EVENT, currentTenant } from "../apiContract"; +import { AUTOMATION_OPEN_EVENT, TOAST_EVENT, UNAUTHORIZED_EVENT, currentTenant } from "../apiContract"; // ⭐ WAVE 26 · ITEM 18 / R14 + C7 — THE LOOPABLE LOOP MARK, CONSUMED, NEVER REDRAWN. // The owner's reason is the mark's own geometry: *"these automations are basically loops."* // C7 says consume the existing icon component and do not inline a new SVG path, and @@ -207,6 +207,28 @@ if (typeof window !== "undefined") { * that a database can be created BY asking for an automation. */ +function useRefusalToast() { + const [messages, setMessages] = useState<{ id: number; text: string }[]>([]); + const sequence = useRef(0); + const delivered = useRef(0); + useEffect(() => { + if (!messages.length) return; + const through = messages[messages.length - 1].id; + for (const message of messages) { + if (message.id <= delivered.current) continue; + delivered.current = message.id; + const text = message.text; + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } })); + } + setMessages((current) => current.filter((message) => message.id > through)); + }, [messages]); + return (text: string) => { + if (!text) return; + const message = { id: ++sequence.current, text }; + setMessages((current) => [...current, message]); + }; +} + export default function AutomationSurface() { /* ⭐ T22 — SEEDED FROM THE CLIENT MEMO, so a revisit inside the freshness window never passes through `data === null` and therefore never paints the skeleton. The lazy initialiser runs @@ -217,6 +239,7 @@ export default function AutomationSurface() { const [voiceAgents, setVoiceAgents] = useState([]); const [voiceLoadError, setVoiceLoadError] = useState(""); const [error, setError] = useState(""); + const refuse = useRefusalToast(); const [activeId, setActiveId] = useState(""); const [activeVoiceId, setActiveVoiceId] = useState(""); const [railShut, setRailShut] = useState(false); @@ -442,9 +465,11 @@ export default function AutomationSurface() { const next = await load(); if (id && next) select(id); } catch (e) { - setError( - e instanceof AutomationError ? e.message : "The automation was not created." - ); + if (e instanceof AutomationError && [401, 403, 404].includes(e.status)) { + refuse(e.message); + } else { + setError(e instanceof AutomationError ? e.message : "The automation was not created."); + } } finally { creatingRef.current = false; setCreatingNow(false); diff --git a/web/src/connectors/ConnectorModal.tsx b/web/src/connectors/ConnectorModal.tsx index 008dce824511cda34a277ee5c03526e02ada719f..8a2ac5333472635babc6cce457204acffd23dbd0 100644 --- a/web/src/connectors/ConnectorModal.tsx +++ b/web/src/connectors/ConnectorModal.tsx @@ -1371,6 +1371,7 @@ export default function ConnectorModal({ setGraphRead(null) : reread} /> ); } diff --git a/web/src/connectors/DatabasesTab.tsx b/web/src/connectors/DatabasesTab.tsx index fcea91093f3396b11598defce3245c780d525255..ffd04722b405f20167c91235bbf552026863ce90 100644 --- a/web/src/connectors/DatabasesTab.tsx +++ b/web/src/connectors/DatabasesTab.tsx @@ -58,7 +58,30 @@ import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react"; import type { MouseEvent } from "react"; -import { API_V1, CREDENTIALS, WORKSPACE_STALE_EVENT, signal } from "../apiContract"; +import { API_V1, CREDENTIALS, TOAST_EVENT, WORKSPACE_STALE_EVENT, signal } from "../apiContract"; + +function useRefusalToast() { + const [messages, setMessages] = useState<{ id: number; text: string }[]>([]); + const sequence = useRef(0); + const delivered = useRef(0); + useEffect(() => { + if (!messages.length) return; + const through = messages[messages.length - 1].id; + for (const message of messages) { + if (message.id <= delivered.current) continue; + delivered.current = message.id; + const text = message.text; + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } })); + } + setMessages((current) => current.filter((message) => message.id > through)); + }, [messages]); + return (text: string) => { + if (!text) return; + const message = { id: ++sequence.current, text }; + setMessages((current) => [...current, message]); + }; +} + import { ConfirmDialog } from "../ui/ConfirmDialog"; import { useEscapeClose } from "../ui/useEscapeClose"; import { DatabaseFieldsEditor } from "../settings/ManageDatabase"; @@ -817,6 +840,7 @@ async function readSyncNow(path: string, provider: string): Promise< } export function useSyncNow(capability: ConnectorDetail["syncNow"]) { + const databaseRefusal = useRefusalToast(); const path = capability?.path; const provider = capability?.provider; const [receipt, setReceipt] = useState(null); @@ -860,7 +884,8 @@ export function useSyncNow(capability: ConnectorDetail["syncNow"]) { const error = await write(path, "POST", {}); postInFlight.current = false; if (generation !== readGeneration.current) return; - setRequestError(error); + setRequestError(""); + if (error) databaseRefusal(error); // Read after every response, including an uncertain network failure. The server may have // accepted the intent already. Only a readback may claim that it is queued or finished. setReads((value) => value + 1); @@ -1287,6 +1312,7 @@ function ScraperDatabases({ const [postType, setPostType] = useState("video"); const [preview, setPreview] = useState(null); const [busy, setBusy] = useState(""); + const databaseRefusal = useRefusalToast(); const [error, setError] = useState(""); const [status, setStatus] = useState(""); const [tabs, setTabs] = useState>({}); @@ -1316,9 +1342,9 @@ function ScraperDatabases({ setBusy("create"); setError(""); setStatus(""); const answer = await scraperPost("/connectors/scraper/databases", { label, recipe: preview.recipe }); setBusy(""); - if (answer.ok === false) { setError(answer.message); return; } + if (answer.ok === false) { databaseRefusal(answer.message); return; } const key = syncText(answer.payload.key); - if (!key) { setError("The server created no readable database."); return; } + if (!key) { databaseRefusal("The server created no readable database."); return; } setCreating(false); setPreview(null); setLabel(""); setSeed(""); setSearch(""); setGeography(""); setStatus("Database created. No provider was called and no cost was incurred."); signal(WORKSPACE_STALE_EVENT); @@ -1330,7 +1356,7 @@ function ScraperDatabases({ setBusy(database.key); setError(""); setStatus(""); const answer = await scraperPost(database.runPath, {}); setBusy(""); - if (answer.ok === false) { setError(answer.message); return; } + if (answer.ok === false) { databaseRefusal(answer.message); return; } const state = syncText(answer.payload.state) || "finished"; setStatus(`${database.label} run ${state}. Run history has been refreshed.`); signal(WORKSPACE_STALE_EVENT); @@ -1833,6 +1859,7 @@ const DatabasesTab = forwardRef>( () => reveal?.key && reveal.status ? { [reveal.key]: reveal.status } : {} ); + const databaseRefusal = useRefusalToast(); const [error, setError] = useState(""); const [jobs, setJobs] = useState([]); const [jobError, setJobError] = useState(""); @@ -1933,7 +1960,7 @@ const DatabasesTab = forwardRef ({ ...current, [database.key]: answer.refusal })); - setRefusalDependents((current) => ({ ...current, [database.key]: answer.dependents })); + if (answer.dependents.length > 0) { + setRefusals((current) => ({ ...current, [database.key]: answer.refusal })); + setRefusalDependents((current) => ({ ...current, [database.key]: answer.dependents })); + } else databaseRefusal(answer.refusal); return; } if (!usesProviderEnablement) { @@ -2024,6 +2053,7 @@ const DatabasesTab = forwardRef([]); + const sequence = useRef(0); + const delivered = useRef(0); + useEffect(() => { + if (!messages.length) return; + const through = messages[messages.length - 1].id; + for (const message of messages) { + if (message.id <= delivered.current) continue; + delivered.current = message.id; + const text = message.text; + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } })); + } + setMessages((current) => current.filter((message) => message.id > through)); + }, [messages]); + return (text: string) => { + if (!text) return; + const message = { id: ++sequence.current, text }; + setMessages((current) => [...current, message]); + }; +} + export default function MonidRunDialog({ label, onClose, @@ -171,6 +193,8 @@ export default function MonidRunDialog({ const [meta, setMeta] = useState(null); const [phase, setPhase] = useState({ kind: "meta" }); const [text, setText] = useState(""); + const lifetime = useRef(null); + const refuse = useRefusalToast(); useOverlayLayer({ panelRef, @@ -184,10 +208,12 @@ export default function MonidRunDialog({ useEffect(() => { let dead = false; + const controller = new AbortController(); + lifetime.current = controller; void (async () => { try { const res = await fetch(`${API_V1}/monid/amazon-reviews/meta`, { - credentials: CREDENTIALS, + credentials: CREDENTIALS, signal: controller.signal, }); const body = (await res.json().catch(() => null)) as | (MonidRunMeta & { error?: { message?: string; code?: string } }) @@ -198,16 +224,23 @@ export default function MonidRunDialog({ kind: "refused", message: reviewRefusal(body?.error?.code, res.status), }); + refuse(reviewRefusal(body?.error?.code, res.status)); return; } setMeta(body); setPhase({ kind: "ready" }); + if (!body.configured) refuse("Not connected."); + else if (!body.canRun) refuse("Administrator only."); } catch { - if (!dead) setPhase({ kind: "refused", message: "Cannot reach the server." }); + if (!dead) { + setPhase({ kind: "refused", message: "Cannot reach the server." }); + refuse("Cannot reach the server."); + } } })(); return () => { dead = true; + controller.abort(); }; }, []); @@ -225,27 +258,33 @@ export default function MonidRunDialog({ const submit = async () => { if (!canSubmit) return; + const request = lifetime.current?.signal; + if (!request || request.aborted) return; setPhase({ kind: "running" }); try { const res = await fetch(`${API_V1}/monid/amazon-reviews/run`, { method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ asins: parsed.good }), + body: JSON.stringify({ asins: parsed.good }), signal: request, }); const body = (await res.json().catch(() => null)) as | (MonidRunResult & { error?: { message?: string; code?: string } }) | null; + if (request.aborted) return; if (!res.ok || !body) { setPhase({ kind: "refused", message: reviewRefusal(body?.error?.code, res.status), }); + refuse(reviewRefusal(body?.error?.code, res.status)); return; } setPhase({ kind: "done", result: body }); } catch { + if (request.aborted) return; setPhase({ kind: "refused", message: "Cannot reach the server." }); + refuse("Cannot reach the server."); } }; @@ -289,23 +328,6 @@ export default function MonidRunDialog({

) : null} - {phase.kind === "refused" ? ( -

- {phase.message} -

- ) : null} - - {meta && !meta.configured ? ( -

- Not connected. -

- ) : null} - - {meta && meta.configured && !meta.canRun ? ( -

- Administrator only. -

- ) : null} {meta && phase.kind === "done" ? (
diff --git a/web/src/connectors/RelationshipDiagram.tsx b/web/src/connectors/RelationshipDiagram.tsx index 08db7b4b063800ca31c2f2662c15cef83713f9d5..70aeb3387d4c38897a12918327cfc8e820135ea6 100644 --- a/web/src/connectors/RelationshipDiagram.tsx +++ b/web/src/connectors/RelationshipDiagram.tsx @@ -685,9 +685,12 @@ export function edgeSummary(connector: string, graph: DiagramInput): string { export default function RelationshipDiagram({ connector, graph, + onRetry, }: { connector: string; graph: ConnectorRelationshipGraph; + /** S76-T23: re-reads the graph after a refusal; the owner of the fetch supplies it. */ + onRetry?: () => void; }) { const [expandedKeys, setExpandedKeys] = useState([]); const scrollRef = useRef(null); @@ -783,9 +786,16 @@ export default function RelationshipDiagram({ if (graph.status !== "ready") { return ( -

- {graph.reason || "This connection did not make an actual relationship graph available."} -

+
+

+ {graph.reason || "This connection did not make an actual relationship graph available."} +

+ {onRetry ? ( + + ) : null} +
); } if (!graph.tables.length) { diff --git a/web/src/customer-grid/CatalogView.tsx b/web/src/customer-grid/CatalogView.tsx index e0b3ad56bc4119183f38b4b4f9412a8737bdca5c..694dbe04ffb3bfc5c43f56b3c57c9cbd42257054 100644 --- a/web/src/customer-grid/CatalogView.tsx +++ b/web/src/customer-grid/CatalogView.tsx @@ -97,6 +97,7 @@ import { applyPrintCss, awaitImages, printOnce } from "./catalogPrint"; import { formatDisplay } from "./display"; import "./catalog.css"; import "../styles/sdlc76/catalog-library.css"; +import "../styles/sdlc76/catalog-editor.css"; /** * ⭐⭐ W37 CONTRACT C3 — THE PER-VIEW CATALOG SPEC, client side. Mirrors @@ -1738,7 +1739,7 @@ export const CatalogView = memo(function CatalogView({ return (
{/* ------------------------------------------------------------ rail */} diff --git a/web/src/customer-grid/CustomerGrid.tsx b/web/src/customer-grid/CustomerGrid.tsx index 9e3fd2394857126620c9f68a8fd6b510019fa0ed..c17e239efb47bba08b5e4fed07aaa6a6bd266e20 100644 --- a/web/src/customer-grid/CustomerGrid.tsx +++ b/web/src/customer-grid/CustomerGrid.tsx @@ -30,7 +30,7 @@ import { addressScope, embedStorageKey, hostedFirstView, useCustomerData, useHos usePersonalGridLayout, withoutRetiredChoiceEdits } from "./useCustomerData"; import type { SurfaceAddress } from "./useCustomerData"; import { AMAZON_STILL_LOADING_MESSAGE } from "./mirrorLoading"; -import type { RowWindowRequest, SurfaceScope } from "./apiBridge"; +import type { RowWindowRequest, SurfaceScope, TableRowAcknowledgement } from "./apiBridge"; import { mutateQueryWorkspace, QUERY_BINDING_EVENT, refuseQueryMutation } from "../query/queryApi"; import type { QueryVirtualBinding } from "../query/queryApi"; import { acceptsQueryPreview, routeQueryViewMutation } from "./queryPreview"; @@ -197,7 +197,7 @@ import { avatarInitials, formatDisplay, imageCellRenderer, matchChoices, pickerT ratingCellRenderer, setAvatarRepaint, userCellRenderer } from "./cells"; // ⭐ W50-T05 — ONE numeric reading of a stored cell, the same one `aggregations.ts` folds with. // A second parse here is how a cell painted blank while the total under it counted 1,234.50. -import { actionHref, numericOrUndefined } from "./display"; +import { actionHref, numberWriteRefusal, numericOrUndefined } from "./display"; // ⭐ W50-T05 — the value/share COMPOSITION. The share arithmetic stays in `formatShare`. import { withShare } from "../ui/fmt"; import { optionTint, pickTint } from "./choiceColors"; @@ -1105,6 +1105,16 @@ function slugify(label: string): string { ); } +function numberBatchRefusal(fields: readonly Field[], updates: readonly Partial[]): string | undefined { + const definitions = new Map(fields.map((field) => [field.key, field])); + for (const row of updates) for (const [key, value] of Object.entries(row)) { + const field = definitions.get(key); + const reason = field && numberWriteRefusal(field, value); + if (reason) return reason; + } + return undefined; +} + interface FieldBuildExtra { if?: Field["if"]; formula?: string; @@ -1275,8 +1285,8 @@ function buildOverlayField( : {}), ...(type === "multiselect" ? { multi: true } : {}), ...(type === "rating" ? { max: extra?.max ?? 5 } : {}), - ...(extra?.defaultValue !== undefined && extra.defaultValue !== null - ? { defaultValue: extra.defaultValue } : {}), + ...(extra && "defaultValue" in extra + ? { defaultValue: extra.defaultValue ?? undefined } : {}), }; } @@ -1553,7 +1563,6 @@ function MirrorKanban({ table, request, field, fieldByKey, cardKeys, titleKey, s return
-
Cards are read-only.
{error ? : !data ? : data.groups.length === 0 ?
No records match this view.
:
{data.groups.map((group) => { @@ -2461,10 +2470,27 @@ function CustomerGrid(props: CustomerGridProps = {}) { return ; } -/** An ID-backed grid supplies pages through the existing caller-owned payload seam. */ +function linkSelectionPredicate(request: Pick, + restriction?: FilterTree): Pick { + if (!restriction?.nodes?.length) return request; + return { + filterConj: "and", + filters: [ + { conj: restriction.conj === "or" ? "or" : "and", children: restriction.nodes }, + ...(request.filters?.length + ? [{ conj: request.filterConj === "or" ? "or" as const : "and" as const, + children: request.filters }] : []), + ], + }; +} + +/** Linked grids page their immutable restrictions through the caller-owned payload seam. */ function useRecordIdWindow(scope: SurfaceScope, ids: readonly number[] | undefined, - related: RelatedPin | null, initialPage?: RecordIdInitialPage, idsPending = false, cellView = false) { - const key = JSON.stringify([scope, ids, related, initialPage, idsPending, cellView]); + related: RelatedPin | null, initialPage?: RecordIdInitialPage, idsPending = false, cellView = false, + selectionFilter?: FilterTree) { + const candidates = !!selectionFilter?.nodes?.length; + const baseKey = JSON.stringify([scope, ids, related, initialPage, idsPending, cellView]); + const key = candidates ? baseKey + "::" + JSON.stringify(selectionFilter) : baseKey; const appliedCellFilters = cellView && ids !== undefined; const seed = !idsPending && ids !== undefined && !related && initialPage && initialPage.offset === 0 ? initialPage.payload : null; @@ -2480,7 +2506,9 @@ function useRecordIdWindow(scope: SurfaceScope, ids: readonly number[] | undefin key: string; payload: CustomersPayload | null; pending: boolean; } | null>(null); const requestWindow = useCallback((req: RowWindowRequest, fresh = false) => { - if (idsPending || ids === undefined) return; + if (!candidates) { + if (idsPending || ids === undefined) return; + } else if (idsPending) return; const seq = ++sequence.current; lastRequest.current = req; if (!fresh && seed && initialPage && req.offset === 0 @@ -2498,11 +2526,22 @@ function useRecordIdWindow(scope: SurfaceScope, ids: readonly number[] | undefin return; } setPage((prev) => ({ key, payload: prev?.key === key ? prev.payload : null, pending: true })); - void fetchTableWindow(scope, { ...req, ids, related }).then((payload) => { + void fetchTableWindow(scope, { ...req, + ...(candidates ? linkSelectionPredicate(req, selectionFilter) : {}), + ...(ids !== undefined ? { ids } : {}), related }).then((payload) => { if (seq !== sequence.current || currentKey.current !== key) return; + if (candidates && selectionFilter && payload && unresolvedConditions(selectionFilter.nodes, { + fieldByKey: new Map(payload.fields.map((field) => [field.key, field])), today: payload.today, + }) > 0) { + setPage({ key, payload: null, pending: false }); + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { + text: "The link condition is unavailable. Ask the field owner to update it.", tone: "error", + } })); + return; + } setPage({ key, payload, pending: false }); }); - }, [scope, ids, related, key, seed, initialPage, idsPending, appliedCellFilters]); + }, [scope, ids, related, key, seed, initialPage, idsPending, appliedCellFilters, candidates, selectionFilter]); useEffect(() => { const refresh = () => { if (lastRequest.current) requestWindow(lastRequest.current, true); }; // React can replay effect setup after cancelling its first request in StrictMode. @@ -2515,7 +2554,7 @@ function useRecordIdWindow(scope: SurfaceScope, ids: readonly number[] | undefin }, [requestWindow]); return { payload: idsPending ? null : page?.key === key ? page.payload : seed, - pending: idsPending || (page?.key === key ? page.pending : !seed && ids !== undefined), + pending: idsPending || (page?.key === key ? page.pending : !seed && (ids !== undefined || candidates)), requestWindow, }; } @@ -2600,7 +2639,9 @@ function CustomerGridSurface({ const embeddedIdsKey = recordIdsKey(embeddedPayload === undefined ? embeddedRecordIds : undefined); const embeddedIds = useMemo( () => embeddedIdsKey ? JSON.parse(embeddedIdsKey) as number[] : undefined, [embeddedIdsKey]); - const idWindow = useRecordIdWindow(scope, embeddedIds, relatedPin, embeddedInitialPage, embeddedIdsPending, cellView); + const selectionWindow = embedded && !!embeddedSelectionFilter?.nodes?.length; + const idWindow = useRecordIdWindow(scope, embeddedIds, relatedPin, embeddedInitialPage, embeddedIdsPending, cellView, + selectionWindow ? embeddedSelectionFilter : undefined); /** * ⭐⭐ W35-T23 (owner item 4 / R2) — **`previewReadOnly` IS GONE, AND THE SPLIT IS THE TICKET.** * @@ -2714,9 +2755,11 @@ function CustomerGridSurface({ related: relatedPin, // C3: a hosted open asks for its addressed View's rows first (`viewWindowPredicate`). firstView: hosted ? hostedFirstView(hostedAddress.path) : undefined, + ...(selectionWindow ? { embeddedPayload: idWindow.payload } : {}), }); - const windowPending = embeddedIds !== undefined ? idWindow.pending : ordinaryWindowPending; - const requestWindow = embeddedIds !== undefined ? idWindow.requestWindow : ordinaryRequestWindow; + const windowPending = embeddedIds !== undefined ? idWindow.pending : selectionWindow ? idWindow.pending : ordinaryWindowPending; + const requestWindow = embeddedIds !== undefined ? idWindow.requestWindow + : selectionWindow ? idWindow.requestWindow : ordinaryRequestWindow; useEffect(() => { onEmbeddedTotalChange?.(payload?.counts?.matched ?? null); }, [onEmbeddedTotalChange, payload?.counts?.matched]); @@ -4090,17 +4133,30 @@ function CustomerGridSurface({ * overlay edit rather than lost data — the alternative, blocking the paint until the POST * resolves, is the defect being fixed. */ + const acceptPendingRow = useCallback((pid: number, made: TableRowAcknowledgement) => { + if (workspaceScopeRef.current !== scope) return; + setPendingRows((current) => current.map((row) => row.pid === pid + ? { ...row, ...made.values, pid: made.pid } : row)); + if (made.pid !== pid) setOverlayEdits((current) => { + if (!current[pid]) return current; + const next = { ...current, [made.pid]: { ...current[made.pid], ...current[pid] } }; + delete next[pid]; + return next; + }); + }, [scope, setOverlayEdits]); + const appendRow = useCallback(async (): Promise => { if (!canMutateRecords) return undefined; - const seeded = seedValues(); + const seeds = seedValues(); const minted = mintRid(); // S76-T28: paint the server's defaults at once. Core stores a boolean as Python's str(). const defaults: Record = Object.fromEntries(fields .filter((field) => field.defaultValue !== undefined && field.defaultValue !== null - && !(field.key in seeded)) + && mayEditField(field, payload?.viewer)) .map((field) => [field.key, typeof field.defaultValue === "boolean" ? (field.defaultValue ? "True" : "False") : String(field.defaultValue)])); - const optimistic: Row = { ...defaults, ...seeded, pid: minted }; + const seeded = { ...defaults, ...seeds }; + const optimistic: Row = { ...seeded, pid: minted }; setPendingRows((cur) => [...cur, optimistic]); setNewRowPid(minted); const made = await addTableRow(scope, seeded, minted); @@ -4112,11 +4168,9 @@ function CustomerGridSurface({ setNewRowPid(null); return undefined; } + acceptPendingRow(minted, made); if (made.pid !== minted) { - setPendingRows((cur) => - cur.map((r) => (r.pid === minted ? { ...r, pid: made.pid } : r)) - ); - setNewRowPid(made.pid); + if (workspaceScopeRef.current === scope) setNewRowPid(made.pid); } // R4 — the append is undoable: Ctrl+Z deletes the row it just created, and a redo restores // it under the SAME rid (the server's `{rid}` passthrough, C-ADDROW). @@ -4137,7 +4191,7 @@ function CustomerGridSurface({ // `undefined` is returned rather than glide's "bottom": "bottom" is resolved against the // rows glide knew about when the gesture started, which is the row BEFORE this one. return undefined; - }, [canMutateRecords, scope, seedValues, mintRid, fields]); + }, [canMutateRecords, scope, seedValues, mintRid, fields, payload?.viewer, acceptPendingRow]); /* wave20 item 2 — measure key + window -> the columns that display it. Built ONCE per field list and handed to every consumer of "which column is this rule about", so the tint @@ -4252,7 +4306,7 @@ function CustomerGridSurface({ // `TableMode` for why both engines running at once is the failure this prevents. // S66-T48: an id-backed grid is a window BY CONSTRUCTION (its rows only ever come from the // rows door), so it is windowed before its first page arrives and the pager can ask for it. - const mode = embeddedIds !== undefined ? "server-windowed" : tableMode(payload?.counts); + const mode = embeddedIds !== undefined ? "server-windowed" : selectionWindow ? "server-windowed" : tableMode(payload?.counts); const serverWindowed = mode === "server-windowed"; // Owner items 4+6 — the Cohort page's grid renders without the Views sidebar. const hideViews = (!hostWorkspace && !related) || payload?.workspace?.hideViews === true; @@ -4399,8 +4453,10 @@ function CustomerGridSurface({ // ⛔ THE SAVED VIEW'S OWN OBJECTS GO ON THE WIRE, UNTRANSLATED (see `windowRowsPath`). const windowPredicate = useMemo( () => windowPredicateKey(config.filters, config.filterConj, config.sorts, search) - + (embeddedIdsKey ? JSON.stringify([scope, embeddedIdsKey, relatedPinKey, cellView]) : ""), - [config.filters, config.filterConj, config.sorts, search, scope, embeddedIdsKey, relatedPinKey, cellView] + + (embeddedIdsKey || selectionWindow + ? JSON.stringify([scope, embeddedIdsKey, relatedPinKey, cellView, embeddedSelectionFilter]) : ""), + [config.filters, config.filterConj, config.sorts, search, scope, embeddedIdsKey, relatedPinKey, cellView, + selectionWindow, embeddedSelectionFilter] ); /* HOTFIX 2026-09-24 — ONE PAGE SIZE FOR EVERY DATABASE (50 / 100 / 200, default 100). */ const windowRequest = useCallback( @@ -4924,8 +4980,10 @@ function CustomerGridSurface({ let live = true; void fetchAggregates(topic.key, { ...(embeddedIds !== undefined ? { ids: embeddedIds } : {}), - filters: cellView && embeddedIds !== undefined ? withoutAppliedLeaves(config.filters) : config.filters, - filterConj: config.filterConj, + ...linkSelectionPredicate({ + filters: cellView && embeddedIds !== undefined ? withoutAppliedLeaves(config.filters) : config.filters, + filterConj: config.filterConj, + }, embeddedSelectionFilter), search, /* ⭐⭐ W51-T06 / C6 — THE SAME PIN THE ROWS WINDOW CARRIES, AND THIS ONE LINE IS THE HALF THAT GETS LEFT OUT. Wire only the rows and a related tab shows one record's rows under @@ -4957,7 +5015,7 @@ function CustomerGridSurface({ // is part of the question, so moving between two tabs on one target table must re-ask. Its // identity is stable (see `relatedPinKey`), so this cannot loop. }, [serverWindowed, topic.key, summaryRequestKey, windowPredicate, config.groupBy, relatedPin, embeddedIds, - serverAggRequestKey, cellView]); + serverAggRequestKey, cellView, embeddedSelectionFilter]); /** * What the bar actually paints: C1's numbers when the server answered, this browser's fold * over the loaded window otherwise — and the two are never mixed within one paint, because a @@ -5012,7 +5070,7 @@ function CustomerGridSurface({ ); /** The bar renders as soon as one column resolves to something to show. Under R2's defaults * that is every table carrying a numeric column, which is the point of the ruling. */ - const summaryShown = summaryRequestKey !== "[]"; + const summaryShown = !isCatalogApplication && summaryRequestKey !== "[]"; const summaryColumns = useMemo( () => visibleCols.map((col) => ({ key: String(col.id), @@ -6061,6 +6119,11 @@ function CustomerGridSurface({ /** ONE cell write, recorded. Every editor, picker and drag goes through this. */ const patchAndRecord = useCallback( (pid: number, updates: Partial, label = "an edit") => { + const reason = numberBatchRefusal(fields, [updates]); + if (reason) { + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text: reason, tone: "error" } })); + return; + } const changes: CellChange[] = Object.entries(updates).map(([key, value]) => ({ pid, key, before: currentValue(pid, key), @@ -6069,7 +6132,7 @@ function CustomerGridSurface({ patchOverlay(pid, updates); recordCells(changes, label); }, - [currentValue, patchOverlay, recordCells] + [currentValue, patchOverlay, recordCells, fields] ); const [chatOpen, setChatOpen] = useState(false); @@ -6098,6 +6161,11 @@ function CustomerGridSurface({ /** MANY cells, ONE stack entry — a paste and a bulk clear are each one user action (R4). */ const patchManyAndRecord = useCallback( (writes: { pid: number; updates: Partial }[], label: string) => { + const reason = numberBatchRefusal(fields, writes.map((write) => write.updates)); + if (reason) { + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text: reason, tone: "error" } })); + return; + } const changes: CellChange[] = []; for (const w of writes) for (const [key, value] of Object.entries(w.updates)) @@ -6109,7 +6177,7 @@ function CustomerGridSurface({ for (const w of writes) patchOverlay(w.pid, w.updates); recordCells(changes, label); }, - [currentValue, patchOverlay, recordCells] + [currentValue, patchOverlay, recordCells, fields] ); const bulkEditableFields = useMemo( () => fields.filter((field) => ( @@ -6126,6 +6194,11 @@ function CustomerGridSurface({ const applyBulkUpdate = useCallback(async () => { if (!bulkField || bulkSelectedCount === 0 || serverBulkPending) return; const value = bulkField.type === "checkbox" ? (bulkValue === "1" ? "1" : "") : bulkValue; + const reason = numberBatchRefusal(fields, [{ [bulkField.key]: value }]); + if (reason) { + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text: reason, tone: "error" } })); + return; + } if (serverFilteredSelection) { setServerBulkPending(true); try { @@ -6166,7 +6239,7 @@ function CustomerGridSurface({ patchManyAndRecord([...selectedPids].map((pid) => ({ pid, updates: { [bulkField.key]: value } })), "a bulk update"); setBulkUpdateOpen(false); }, [bulkField, bulkSelectedCount, bulkValue, clearSelection, dropTableRowsCache, patchManyAndRecord, - requestWindow, scope, selectedPids, serverBulkPending, serverFilteredSelection, windowRequest]); + requestWindow, scope, selectedPids, serverBulkPending, serverFilteredSelection, windowRequest, fields]); /** * Apply one stack entry in one direction. The INVERSE lives in `undoStack.directed` — this @@ -6192,8 +6265,7 @@ function CustomerGridSurface({ applyingUndo.current = false; } } else if (op.kind === "rowAdd") { - // Restore under the OLD id where the store still has it free; the server answers with - // what it actually wrote and the re-read is what puts the rows back on screen. + // Restore writable cells immediately; the acknowledgement supplies generated values. // // ⚠ SEQUENTIAL, not `Promise.all`. `add_row` picks `max(id)+1` when the requested id is // taken, and it reads the store to do it — firing ten restores concurrently is ten @@ -6205,8 +6277,24 @@ function CustomerGridSurface({ || AUDIT_FIELD_TYPES.includes(field.type)).map((field) => field.key)); for (const r of op.rows) { const values = Object.fromEntries(Object.entries(r.values as Record) - .filter(([key]) => !generated.has(key))); - const made = await addTableRow(op.table, values, r.rid); + .filter(([key]) => !generated.has(key))) as Record; + const requestedPid = Number(r.rid); + const pid = !Number.isFinite(requestedPid) || rowsRef.current.some((row) => row.pid === requestedPid) + ? mintRid() : requestedPid; + if (workspaceScopeRef.current === op.table) setOverlayEdits((current) => { + if (!current[pid]) return current; + const writable = Object.fromEntries(Object.entries(current[pid]).filter(([key]) => !generated.has(key))); + return { ...current, [pid]: writable }; + }); + if (workspaceScopeRef.current === op.table) + setPendingRows((current) => [...current.filter((row) => row.pid !== pid), { ...values, pid }]); + const made = await addTableRow(op.table, values, r.rid, true); + if (!made) { + if (workspaceScopeRef.current === op.table) + setPendingRows((current) => current.filter((row) => row.pid !== pid)); + continue; + } + acceptPendingRow(pid, made); any = any || !!made; // a refusal already said why, in the server's words // ⚠ THE ID IS PART OF WHAT IS BEING UNDONE, and `add_row` falls back to `max(id)+1` // when the one it was asked for is no longer free — which happens if anything created @@ -6215,6 +6303,8 @@ function CustomerGridSurface({ // and a redo would then look for an id that is not there. Said out loud rather than // discovered later. if (made && String(made.rid) !== String(r.rid)) moved += 1; + r.rid = made.rid; + r.values = { ...values, ...made.values }; } if (!any) return; if (moved) @@ -6223,7 +6313,6 @@ function CustomerGridSurface({ `${moved} restored record${moved === 1 ? "" : "s"} came back under a new id. ` + `Something had taken the original while it was gone.` ); - signal(ROWS_STALE_EVENT); } else if (op.kind === "rowDelete") { let any = false; for (const r of op.rows) any = (await deleteTableRow(op.table, r.rid)) || any; @@ -6246,7 +6335,7 @@ function CustomerGridSurface({ } signal(TOAST_EVENT, describe(entry, dir)); }, - [patchOverlay, withdrawPending, emitHostEvent, fields] + [patchOverlay, withdrawPending, emitHostEvent, fields, acceptPendingRow, mintRid, setOverlayEdits] ); /** @@ -9432,7 +9521,7 @@ function CustomerGridSurface({ per surface. Fixing the validator and the offer left the SEND still broken. */ ...(extra?.geocode ? { geocode: extra.geocode } : {}), ...(field.agg ? { agg: field.agg } : {}), - ...(field.defaultValue !== undefined ? { defaultValue: field.defaultValue } : {}), + ...("defaultValue" in field ? { defaultValue: field.defaultValue ?? null } : {}), }).then((made) => { const reconcile = (current: Field[]) => { const without = current.filter((item) => item.key !== field.key && item.key !== made?.key); @@ -9541,6 +9630,8 @@ function CustomerGridSurface({ const setFieldConfig = useCallback( (key: string, patch: { label?: string; link?: unknown; rollup?: unknown; if?: Field["if"]; formula?: string; agg?: string; + defaultValue?: Field["defaultValue"] | null; + format?: Field["format"]; /* ⭐ W50-T05 — the display mode rides the DEFINITION door for D-468/D-275's reason: on a shared column the overlay stratum would fork it, and this one edits it in place. */ showAs?: ShowAs; @@ -9743,6 +9834,9 @@ function CustomerGridSurface({ ...(old.createdBy ? { createdBy: old.createdBy } : {}), ...(old.permissions ? { permissions: old.permissions } : {}), ...(keepFormat ? { format: old.format } : {}), + ...(extra && "defaultValue" in extra + ? { defaultValue: extra.defaultValue ?? undefined } + : "defaultValue" in old ? { defaultValue: old.defaultValue } : {}), ...((type === "select" || type === "multiselect") && options?.length ? { options } : {}), @@ -9757,7 +9851,7 @@ function CustomerGridSurface({ ...(type === "multiselect" ? { multi: true } : {}), ...(type === "rating" ? { max: extra?.max ?? 5 } : {}), }; - if (isUserTable && !old.custom) { + const writeDefinition = () => { /* THE DEFINITION DOOR. `patch_field` merges the body through the same `_clean_field` the create used, so the type, the options, the colours and a rating's max all land in the one validator — and the SERVER's echo replaces the local field, exactly as the create @@ -9773,12 +9867,18 @@ function CustomerGridSurface({ ...(next.max !== undefined ? { max: next.max } : {}), ...(next.agg ? { agg: next.agg } : {}), ...(next.format ? { format: next.format } : {}), + ...("defaultValue" in next ? { defaultValue: next.defaultValue ?? null } : {}), }).then((made) => { if (!made) return; // the bridge has already said why setFields((current) => current.map((f) => (f.key === made.key ? made : f))); signal(WORKSPACE_STALE_EVENT); signal(ROWS_STALE_EVENT); }); + }; + if (isUserTable && !old.custom) { + writeDefinition(); + } else if (isUserTable && "defaultValue" in next) { + writeDefinition(); } else { saveField(next); } @@ -12761,7 +12861,7 @@ function CustomerGridSurface({ every page reachable: `matched` is the server's own count, so this is a view onto the whole population rather than a cap on it (standing rule 1). Grouped, each open group pages on its own footer instead. */} -
+ {!isCatalogApplication &&
{!nativeActivity && !rowsLoading && !mirrorUnavailable && <> {((!config.groupBy && (displayMode === "grid" || (serverWindowed && displayMode === "list"))) || (serverWindowed && displayMode === "gallery")) && !loading && ( @@ -12783,7 +12883,7 @@ function CustomerGridSurface({ {nativeActivity && activityPage.error && Activity could not be loaded.} {!embedded && !isQueryPreview && } -
+
} {embedded && menuField && columnMenu && ( diff --git a/web/src/customer-grid/GridActivity.tsx b/web/src/customer-grid/GridActivity.tsx index 4f1e200d08839aed59e30aba9c10d54dff306689..6df2272cbaed3578432161372a2c79c0f1de8cd0 100644 --- a/web/src/customer-grid/GridActivity.tsx +++ b/web/src/customer-grid/GridActivity.tsx @@ -83,8 +83,8 @@ export function activityPerson(record: ActivityRecord): string { return record.via ? `${person} via ${record.via}` : person; } -function ActivityDrawer({ records, failed, now, onClose }: { - records: ActivityRecord[]; failed: boolean; now: number; onClose: () => void; +function ActivityDrawer({ records, failed, now, onClose, onRetry }: { + records: ActivityRecord[]; failed: boolean; now: number; onClose: () => void; onRetry: () => void; }) { const panelRef = useRef(null); const title = useId(); @@ -95,7 +95,8 @@ function ActivityDrawer({ records, failed, now, onClose }: {

Activity

- {failed ?

Activity could not be loaded.

: records.length === 0 ? + {failed ?

Activity could not be loaded.{" "} +

: records.length === 0 ?

No activity

:
    {records.map(record =>
  1. {activityPerson(record)} @@ -116,6 +117,7 @@ export function GridActivity({ database }: { database: string }) { const [failed, setFailed] = useState(false); const [now, setNow] = useState(Date.now); const activeDatabase = useRef(database); + const retryRead = useRef<(() => void) | null>(null); const [loadedDatabase, setLoadedDatabase] = useState(database); activeDatabase.current = database; useEffect(() => { @@ -163,7 +165,8 @@ export function GridActivity({ database }: { database: string }) { setFailed(false); setLoadedDatabase(database); const read = async () => { - controller = new AbortController(); + const request = new AbortController(); + controller = request; try { let cursor: string | null = null; let answer: ActivityPage; @@ -178,20 +181,25 @@ export function GridActivity({ database }: { database: string }) { if (!response.ok) throw new Error("activity unavailable"); answer = await response.json() as ActivityPage; cursor = answer.next_cursor; - } while (answer.records.length === 0 && cursor && live); - if (live && activeDatabase.current === database) { + } while (answer.records.length === 0 && cursor && live && !request.signal.aborted); + if (live && !request.signal.aborted && activeDatabase.current === database) { setPage(answer); setFailed(false); setNow(Date.now()); } } catch { - if (live) { setPage(null); setFailed(true); } + if (live && !request.signal.aborted) { setPage(null); setFailed(true); } } finally { - if (live) timer = setTimeout(read, 5000); + if (live && !request.signal.aborted) timer = setTimeout(read, 5000); } }; + retryRead.current = () => { + clearTimeout(timer); + controller?.abort(); + void read(); + }; void read(); - return () => { live = false; clearTimeout(timer); controller?.abort(); }; + return () => { live = false; retryRead.current = null; clearTimeout(timer); controller?.abort(); }; }, [database]); const records = loadedDatabase === database ? page?.records ?? [] : []; const last = records[0]; @@ -208,6 +216,6 @@ export function GridActivity({ database }: { database: string }) { ) : null} {open && loadedDatabase === database && setOpen(false)} />} + failed={failed} now={now} onClose={() => setOpen(false)} onRetry={() => retryRead.current?.()} />} ; } diff --git a/web/src/customer-grid/MapView.tsx b/web/src/customer-grid/MapView.tsx index fb3f181622738e52fd647a69321c7ee6f4bba203..161bce515e10caab3ea9a0748826312ed1c23492 100644 --- a/web/src/customer-grid/MapView.tsx +++ b/web/src/customer-grid/MapView.tsx @@ -5252,6 +5252,10 @@ export function MapView(props: MapViewProps) { key, title, ...(fieldMap.image ? { image: String(fieldMap.image) } : {}), + ...(fieldMap.sku ? { sku: String(fieldMap.sku) } : {}), + ...(fieldMap.price ? { price: String(fieldMap.price) } : {}), + ...(fieldMap.category ? { category: String(fieldMap.category) } : {}), + ...(fieldMap.description ? { description: String(fieldMap.description) } : {}), }, }; const display = application.config?.display ?? {}; diff --git a/web/src/customer-grid/RecordDetail.tsx b/web/src/customer-grid/RecordDetail.tsx index 8d05d056f26b83b2c1d9b39f44c9740561b27038..f4e87472311022ed5ea1956d202981b37ce5b359 100644 --- a/web/src/customer-grid/RecordDetail.tsx +++ b/web/src/customer-grid/RecordDetail.tsx @@ -67,7 +67,7 @@ import { dropTableRowsCache, fetchLinkTargets, fetchRecordMeasureValues, fetchRe fetchRelatedMeasureValues, fetchTableWindow, fetchTopicRows, isRelatedMetricScope, isRelatedProductMetricScope, probeRelatedRead, readThroughTables, usesPinnedRows, WINDOW_ROWS } from "./apiBridge"; -import { API_V1, CREDENTIALS, ROWS_STALE_EVENT, WORKSPACE_STALE_EVENT, UNAUTHORIZED_EVENT, checkTenant, signal } from "../apiContract"; +import { API_V1, CREDENTIALS, ROWS_STALE_EVENT, WORKSPACE_STALE_EVENT, TOAST_EVENT, UNAUTHORIZED_EVENT, checkTenant, signal } from "../apiContract"; /** * ⭐⭐ WAVE-34 (owner ruling R13) — whose value sits in this enrichment cell, in words. @@ -669,6 +669,15 @@ function RelatedRefusalNote( { code, subject, message, details }: { code: string; subject: string; message: string; details: string[] }, ) { + const denial = code !== "no_related_rows"; + const text = [subject, message, ...details].filter(Boolean).join(" "); + const announced = useRef(null); + useEffect(() => { + if (!denial || announced.current === text) return; + announced.current = text; + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } })); + }, [denial, text]); + if (denial) return null; if (details.length === 0) { return (

    ` whose summary is a real disclosure control, and wrapping every one of them in its own live region would announce the same strip N times. */} {groupedRefusals.length > 0 && ( -

    + <> {groupedRefusals.map((refusal) => ( ))} -
    + )}
) : ( diff --git a/web/src/customer-grid/apiBridge.ts b/web/src/customer-grid/apiBridge.ts index e2859cd8fdc384837f800360bf04a1d83e116593..361ee1e595bb8c06654c07bb5ee8720d22dc335e 100644 --- a/web/src/customer-grid/apiBridge.ts +++ b/web/src/customer-grid/apiBridge.ts @@ -1825,20 +1825,27 @@ export function patchCustomer(pid: number, updates: Partial): Promise; +} + export async function addTableRow( tableKey: string, values: Record = {}, - rid?: string | number -): Promise<{ rid: string | number; pid: number } | null> { + rid?: string | number, + restore = false +): Promise { try { const res = await fetch(`${API_V1}/tables/${encodeURIComponent(tableKey)}/rows`, { method: "POST", credentials: CREDENTIALS, headers: JSON_HEADERS, - body: JSON.stringify(rid === undefined ? { values } : { rid, values }), + body: JSON.stringify(rid === undefined ? { values, restore } : { rid, values, restore }), }); if (handledSession(res)) return null; - const body = (await readJson(res)) as { rid?: string | number; pid?: number; + const body = (await readJson(res)) as { rid?: string | number; pid?: number; values?: unknown; error?: { message?: string } } | null; if (!res.ok) { // The server states WHY (a row cap, a store refusal). Surfacing its sentence beats a @@ -1852,7 +1859,15 @@ export async function addTableRow( return null; } dropTableRowsCache(tableKey); - return { rid: body.rid, pid: body.pid }; + const accepted: TableRowAcknowledgement["values"] = body.values && + typeof body.values === "object" && !Array.isArray(body.values) ? {} : undefined; + if (accepted) for (const [key, value] of Object.entries(body.values as Record)) { + if (key === "pid") continue; + if (value === null || typeof value === "string" || + (typeof value === "number" && Number.isFinite(value))) accepted[key] = value; + else if (typeof value === "boolean") accepted[key] = value ? "True" : "False"; + } + return { rid: body.rid, pid: body.pid, ...(accepted ? { values: accepted } : {}) }; } catch { signal(DATA_ERROR_EVENT, "Cannot reach the server."); return null; diff --git a/web/src/filter-kit/FieldsHidePanel.tsx b/web/src/filter-kit/FieldsHidePanel.tsx index db8215e9334dc0a7d8d3c9f04aab988632bf577b..fb4bbd0bf7d2db4aacfbefe4ea6dea02749729c5 100644 --- a/web/src/filter-kit/FieldsHidePanel.tsx +++ b/web/src/filter-kit/FieldsHidePanel.tsx @@ -15,6 +15,7 @@ import { useEffect, useMemo, useRef, useState } from "react"; import { useEscapeClose } from "../ui/useEscapeClose"; +import { TOAST_EVENT } from "../apiContract"; import { useOverlayLayer } from "../customer-grid/OverlaySurface"; // ⭐⭐ W46-T31 (contract C6) — the lane's own sheet, imported from the COMPONENT and never from // `index.css`. An @imported sheet is inlined at the TOP of the bundle's cascade and loses every @@ -787,7 +788,12 @@ export function FieldsHidePanel({ if (action === "reassign" && onReassignFields && passed.length > 0) onReassignFields(passed); if (action === "share" || action === "reassign") done += passed.length; const text = bulkOutcomeLine(action, done, refused); - setBulkNote(text ? { text, refused: refused.length > 0 } : null); + if (text && refused.length > 0) { + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } })); + setBulkNote(null); + } else { + setBulkNote(text ? { text, refused: false } : null); + } /** * ⭐ AFTER A DELETE THE SELECTION BECOMES EXACTLY WHAT SURVIVED IT, and that is one * decision doing two jobs: the deleted keys are gone from `fields` and must not linger in a @@ -1619,7 +1625,7 @@ export function FieldsHidePanel({ `bulkOutcomeLine` and never here, so R6(a)'s refusal has exactly one producer. */} {bulkNote && (
{bulkNote.text} diff --git a/web/src/index.css b/web/src/index.css index dd8a9292864b6d49402c283cef5e4f30928ce99c..5393074d53c6dd7d34e5e5764f1c144639be3b12 100644 --- a/web/src/index.css +++ b/web/src/index.css @@ -30,6 +30,7 @@ @import "./styles/wave51/sheet-chrome.css"; @import "./styles/wave51/sheet-engine.css"; @import "./styles/sdlc74/settings.css"; +@import "./styles/sdlc76/overlays.css"; @font-face { font-family: "Inter"; diff --git a/web/src/intelligence/intelligenceApi.ts b/web/src/intelligence/intelligenceApi.ts index f7ce85725a159e758f3c3db46d6952c0cfc3fd97..acce23cd11f1c2a10273f2e04baa8d984282f2a4 100644 --- a/web/src/intelligence/intelligenceApi.ts +++ b/web/src/intelligence/intelligenceApi.ts @@ -104,6 +104,8 @@ export interface IntelligenceList { offset: number; limit: number; folders: string[]; + canManageFolders?: boolean; + folderRevision?: number; } export interface IntelligenceQuery { q: string; @@ -132,6 +134,10 @@ export interface IntelligenceApi { history(path: string, version: number, signal?: AbortSignal): Promise; restore(path: string, version: number, expectedVersion: number): Promise; insights(signal?: AbortSignal): Promise; + renameFile?: (path: string, title: string, expectedVersion: number) => Promise; + deleteFile?: (path: string, expectedVersion: number) => Promise<{ deleted: string }>; + renameFolder?: (path: string, name: string, expectedRevision: number) => Promise<{ path: string }>; + deleteFolder?: (path: string, expectedRevision: number) => Promise<{ deleted: string }>; } export class IntelligenceApiError extends Error { @@ -157,6 +163,7 @@ function readRow(value: unknown): IntelligenceFileRow { if (value.section === "database-notes" && (typeof value.databaseKey !== "string" || !value.databaseKey || value.databaseKey.includes("/") || value.path !== `database-notes/${value.databaseKey}.md` || typeof value.canEdit !== "boolean" || value.revisionHistory !== "database-note")) throw new Error("Invalid note."); + if (value.canEdit != null && typeof value.canEdit !== "boolean") throw new Error("Invalid permission."); return value as unknown as IntelligenceFileRow; } function readFile(value: unknown): IntelligenceFile { @@ -189,7 +196,16 @@ function readList(value: unknown): IntelligenceList { || (value.files.length > 0 && value.offset + value.files.length > value.total)) throw new Error("Invalid list."); const files = value.files.map(readRow); if (new Set(files.map((file) => file.path)).size !== files.length) throw new Error("Invalid list."); - return { files, total: value.total, offset: value.offset, limit: value.limit, folders: value.folders as string[] }; + if ((value.canManageFolders != null && typeof value.canManageFolders !== "boolean") + || (value.folderRevision != null && !count(value.folderRevision))) throw new Error("Invalid folder permission."); + return { files, total: value.total, offset: value.offset, limit: value.limit, folders: value.folders as string[], + ...(typeof value.canManageFolders === "boolean" ? { canManageFolders: value.canManageFolders } : {}), + ...(count(value.folderRevision) ? { folderRevision: value.folderRevision } : {}) }; +} + +function readDeleted(value: unknown, path: string): { deleted: string } { + if (!object(value) || value.deleted !== path) throw new Error("Invalid deletion."); + return { deleted: path }; } function readHistory(value: unknown): IntelligenceHistory { @@ -242,7 +258,8 @@ async function request(query: string, init: RequestInit, parse: (value: unkno const body: unknown = await response.json().catch(() => null); if (!response.ok) { const refusal = refusalPair(body); - const message = response.status >= 500 ? (init.method === "PUT" + const message = response.status >= 500 ? (init.method === "PATCH" || init.method === "DELETE" + ? "The change could not be confirmed. Reload and try again." : init.method === "PUT" ? "The file save could not be confirmed. Reload and try again." : init.method === "POST" ? resource === "restore" ? "The restore could not be confirmed. Reload and try again." : "The decision could not be confirmed. Reload and try again." : "Brain files could not be read. Try again.") : refusal.message; @@ -271,6 +288,29 @@ export function newFilePayload(input: NewIntelligenceFile): { path: string; body } export const intelligenceApi: IntelligenceApi = { + renameFile(path, title, expectedVersion) { + return request("", { method: "PATCH", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ path, title, expectedVersion }) }, (value) => { + const file = readFile(value); + if (file.path !== path || file.version <= expectedVersion) throw new Error("Invalid rename."); + return file; + }); + }, + deleteFile(path, expectedVersion) { + return request(`?${new URLSearchParams({ path, expectedVersion: String(expectedVersion) })}`, + { method: "DELETE" }, (value) => readDeleted(value, path)); + }, + renameFolder(path, name, expectedRevision) { + return request("", { method: "PATCH", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ path, name, expectedRevision }) }, (value) => { + if (!object(value) || typeof value.path !== "string" || !value.path) throw new Error("Invalid folder rename."); + return { path: value.path }; + }, "folders"); + }, + deleteFolder(path, expectedRevision) { + return request(`?${new URLSearchParams({ path, expectedRevision: String(expectedRevision) })}`, + { method: "DELETE" }, (value) => readDeleted(value, path), "folders"); + }, history(path, version, signal) { return request(`?${new URLSearchParams({ path, version: String(version) })}`, { method: "GET", signal }, readHistory, "history"); }, diff --git a/web/src/operator/OperatorPage.tsx b/web/src/operator/OperatorPage.tsx index 7d49f910e370db172c3bdd51cdc01d5c2d5b5fa3..e0280ffbd316192fbb3e5294b106b294fa91d916 100644 --- a/web/src/operator/OperatorPage.tsx +++ b/web/src/operator/OperatorPage.tsx @@ -1,10 +1,10 @@ -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { AutomationError, createOperatorGrant, getOperatorAudit, getOperatorSetup, getOperatorVoiceSetup, getSystemData, type OperatorAudit, type OperatorGrant, type OperatorSetup, type OperatorSetupField, type OperatorVoiceSetup, type SystemData, } from "../automation/automationApi"; -import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../apiContract"; +import { API_V1, CREDENTIALS, TOAST_EVENT, UNAUTHORIZED_EVENT, checkTenant, signal } from "../apiContract"; import "./operator.css"; export interface OperatorPageProps { platformAdmin: boolean } @@ -13,7 +13,30 @@ const SAFE_SETUP_FIELDS: OperatorSetupField[] = [ "displayName", "timezone", "voicePurpose", "consentPolicy", "queryEnabled", "providerLabel", ]; +function useRefusalToast() { + const [messages, setMessages] = useState<{ id: number; text: string }[]>([]); + const sequence = useRef(0); + const delivered = useRef(0); + useEffect(() => { + if (!messages.length) return; + const through = messages[messages.length - 1].id; + for (const message of messages) { + if (message.id <= delivered.current) continue; + delivered.current = message.id; + const text = message.text; + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } })); + } + setMessages((current) => current.filter((message) => message.id > through)); + }, [messages]); + return (text: string) => { + if (!text) return; + const message = { id: ++sequence.current, text }; + setMessages((current) => [...current, message]); + }; +} + export default function OperatorPage({ platformAdmin }: OperatorPageProps) { + const refuse = useRefusalToast(); const [audit, setAudit] = useState(null); const [system, setSystem] = useState(null); const [tenant, setTenant] = useState(""); @@ -57,13 +80,20 @@ export default function OperatorPage({ platformAdmin }: OperatorPageProps) { const voiceSetup = await getOperatorVoiceSetup(target, granted.token); setSetup(tenantSetup); setVoice(voiceSetup); } catch (error) { - const refused = error instanceof AutomationError && (error.status === 403 || error.status === 404); - setProblem((refused ? "That tenant or capability is unavailable. " : "") + (error instanceof Error ? error.message : "Tenant setup unavailable.")); + const refused = error instanceof AutomationError && [401, 403, 404].includes(error.status); + const text = (refused ? "That tenant or capability is unavailable. " : "") + + (error instanceof Error ? error.message : "Tenant setup unavailable."); + if (refused) refuse(text); + else setProblem(text); } finally { // Both allowed and refused inspections append an audit result. Refresh after either path so // the visible receipt is the final server outcome, not the preflight list. try { setAudit((await getOperatorAudit()).audit); } - catch (error) { setProblem((current) => current || (error instanceof Error ? error.message : "Audit refresh unavailable.")); } + catch (error) { + const text = error instanceof Error ? error.message : "Audit refresh unavailable."; + if (error instanceof AutomationError && [401, 403, 404].includes(error.status)) refuse(text); + else setLoadError({ sentence: "Could not refresh the audit history.", detail: text }); + } setBusy(false); } } diff --git a/web/src/query/queryApi.ts b/web/src/query/queryApi.ts index c084fbf8b359d3e8a7a5c95cf011fd0c648b5134..5271b3b7efd1f013bb2c55620a62499ffd496e21 100644 --- a/web/src/query/queryApi.ts +++ b/web/src/query/queryApi.ts @@ -254,7 +254,7 @@ export interface AssistantArtifact { createdAt: string; status: "active" | "paused" | "deleted"; toolCall: ArtifactToolCall; file_id?: string; mime?: string; link?: string; frozen_at?: string; - actions: Array<"open" | "run" | "pause" | "resume" | "delete">; + actions: Array<"open" | "run" | "pause" | "resume" | "rename" | "delete">; } export interface ArtifactIndex { items: AssistantArtifact[]; nextCursor: string | null; } diff --git a/web/src/query/queryParts.tsx b/web/src/query/queryParts.tsx index fd7c4e1dce84ea1a7d37420f1493ced5df0de68c..cccf6cbc446924f13e0a1f0770bd94a2183fd293 100644 --- a/web/src/query/queryParts.tsx +++ b/web/src/query/queryParts.tsx @@ -1,6 +1,7 @@ -import { useRef, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import type { ReactNode } from "react"; import { useEscapeClose } from "../ui/useEscapeClose"; +import { TOAST_EVENT } from "../apiContract"; import { useOverlayLayer } from "../customer-grid/OverlaySurface"; import { FolderMark } from "../customer-grid/icons"; @@ -51,6 +52,28 @@ import type { SavedQuery } from "./queryApi"; import "./query.css"; /** Which label of which row is being typed into. One at a time, by construction. */ +function useRefusalToast() { + const [messages, setMessages] = useState<{ id: number; text: string }[]>([]); + const sequence = useRef(0); + const delivered = useRef(0); + useEffect(() => { + if (!messages.length) return; + const through = messages[messages.length - 1].id; + for (const message of messages) { + if (message.id <= delivered.current) continue; + delivered.current = message.id; + const text = message.text; + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } })); + } + setMessages((current) => current.filter((message) => message.id > through)); + }, [messages]); + return (text: string) => { + if (!text) return; + const message = { id: ++sequence.current, text }; + setMessages((current) => [...current, message]); + }; +} + interface Editing { id: string; field: "name" | "description"; value: string; } function QueryActionMenu({ anchor, onClose, children }: { @@ -196,20 +219,23 @@ export function QueryRail({ groups, activeId, onSelect, onDelete, onChanged }: { const [editing, setEditing] = useState(null); const menuOpenerRef = useRef(null); const editingFinishedRef = useRef(false); + const editingSequence = useRef(0); useEscapeClose(editing !== null, () => { + editingSequence.current += 1; editingFinishedRef.current = true; setEditing(null); menuOpenerRef.current?.focus(); }); const beginEditing = (next: Editing) => { + editingSequence.current += 1; editingFinishedRef.current = false; setMenuFor(""); setEditing(next); }; // âš  TWO STATES, NOT ONE. A refusal and a confirmation read differently and are coloured // differently; sharing one slot painted "Saved as ..." in the refusal red. - const [problem, setProblem] = useState(""); const [notice, setNotice] = useState(""); + const refuse = useRefusalToast(); /** * ⭐ C2's star list, read AFTER PAINT and never blocking the rail (E-2: `GET /starred` scans * every visible database's view bucket and was MEASURED at 7,331 ms on a cold container). The @@ -219,17 +245,28 @@ export function QueryRail({ groups, activeId, onSelect, onDelete, onChanged }: { */ const stars = useStarred(); const starred = new Set(stars.starred.queries); - const said = (message: string) => { setNotice(message); setProblem(""); }; - const failed = (message: string) => { setProblem(message); setNotice(""); }; + const said = (message: string) => setNotice(message); + const failed = (text: string) => { + setNotice(""); + refuse(text); + }; const commit = async () => { if (!editing || editingFinishedRef.current) return; editingFinishedRef.current = true; const current = editing; + const sequence = editingSequence.current; setEditing(null); const result = await renameQuery(current.id, current.field === "name" ? { name: current.value } : { description: current.value }); - if (!result.ok) { failed(result.message); return; } + if (!result.ok) { + if (sequence === editingSequence.current) { + editingFinishedRef.current = false; + setEditing((next) => next ?? current); + } + failed(result.message); + return; + } said(""); onChanged?.(result.value); }; @@ -291,7 +328,6 @@ export function QueryRail({ groups, activeId, onSelect, onDelete, onChanged }: { +

; } @@ -3292,7 +3340,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN onEvaluateBindings={onEvaluateBindings} onUndo={onUndo} onRedo={onRedo} - onNotice={setNotice} + onNotice={showRefusal} // ⭐ W50-T21's HANDOVER. The bar now mirrors the SELECTED cell; its name box still // works, because both write the same state. `FormulaBar.tsx` was not touched. onSelect={(sel) => { @@ -3356,19 +3404,19 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN {tabReadError ? tabReadError : notice - ? "Use Create new in the rail to try again." + ? notice : "No workbook is open. Use Create new in the rail to start one."}

+ {notice || tabReadError ? : null}
)} - {/* `.sheet-notice` is a transient sentence about a refusal, not chrome. - Keep messages above the tab strip so they cannot move the ribbon or the grid's - origin (owner instructions 6 and 12). */} -
- {/* A tab that could not be read says so once, in the grid area, not again here. */} - {tabReadError ? null : <>{notice &&

{notice}

}} -
+ {book && notice && !tabReadError ?

+ {notice}{" "} +

: null} {/* ⭐⭐ THE TAB BAR (wave-49 R7), AND IT SITS AT THE BOTTOM OF THE WORKBOOK. R7 says one rail entry is a WORKBOOK WITH TABS, so the tabs belong INSIDE the workbook diff --git a/web/src/styles/sdlc76/catalog-editor.css b/web/src/styles/sdlc76/catalog-editor.css new file mode 100644 index 0000000000000000000000000000000000000000..4dd33a3b05257516f9c0f84b6b6518cebdf82db9 --- /dev/null +++ b/web/src/styles/sdlc76/catalog-editor.css @@ -0,0 +1,43 @@ +@media (max-width: 390px) { + .cg-cat { + --cg-catalog-legacy-columns: minmax(0, 1fr); + --cg-catalog-mobile-rail-height: 128px; + --cg-catalog-mobile-inspector-height: 180px; + --cg-catalog-mobile-stage-height: 240px; + grid-template-columns: minmax(0, 1fr); + grid-template-rows: auto minmax(var(--cg-catalog-mobile-stage-height), 1fr) auto; + overflow: auto; + } + + .cg-cat-rail { + max-height: var(--cg-catalog-mobile-rail-height); + border-right: 0; + border-bottom: var(--lp-hairline-width) solid var(--lp-line); + } + + .cg-cat-insp { + max-height: var(--cg-catalog-mobile-inspector-height); + border-left: 0; + border-top: var(--lp-hairline-width) solid var(--lp-line); + } + + .cg-cat-bar { + flex-wrap: wrap; + } + + .cg-catalog-editor .cg-catalog-record-head h2 { + flex: 1 0 100%; + order: -1; + overflow-wrap: anywhere; + } + + .cg-catalog-workspace.has-templates { + --cg-catalog-mobile-template-height: 160px; + grid-template-columns: minmax(0, 1fr); + grid-template-rows: minmax(0, var(--cg-catalog-mobile-template-height)) minmax(0, 1fr); + } + + .cg-catalog-template-list { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} diff --git a/web/src/styles/sdlc76/overlays.css b/web/src/styles/sdlc76/overlays.css new file mode 100644 index 0000000000000000000000000000000000000000..e98fc452eb01df06844bd8f413dab8e0ac225e70 --- /dev/null +++ b/web/src/styles/sdlc76/overlays.css @@ -0,0 +1,6 @@ +/* W62-T33: an anchored panel scrolls inside itself; SDLC 76's three new menus join the shared rule. */ +.cg-overlay.home-item-menu, +.cg-overlay.auto-row-menu, +.cg-overlay.cg-catalog-library-menu { + overflow-y: auto; +} diff --git a/web/src/views-trash/TrashPanel.tsx b/web/src/views-trash/TrashPanel.tsx index 6fa008e4e0a0ff09b2cb8193503475cdd555cd09..52dbcce9b9fbab95a97b2e1a743c780532ce1273 100644 --- a/web/src/views-trash/TrashPanel.tsx +++ b/web/src/views-trash/TrashPanel.tsx @@ -27,6 +27,7 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { ConfirmDialog } from '../ui/ConfirmDialog' import { useEscapeClose } from '../ui/useEscapeClose' +import { TOAST_EVENT } from '../apiContract' import { fetchTrail, fetchTrash, @@ -147,7 +148,30 @@ function TrashIcon() { ) } +function useRefusalToast() { + const [messages, setMessages] = useState<{ id: number; text: string }[]>([]) + const sequence = useRef(0) + const delivered = useRef(0) + useEffect(() => { + if (!messages.length) return + const through = messages[messages.length - 1].id + for (const message of messages) { + if (message.id <= delivered.current) continue + delivered.current = message.id + const text = message.text + window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: 'error' } })) + } + setMessages((current) => current.filter((message) => message.id > through)) + }, [messages]) + return (text: string) => { + if (!text) return + const message = { id: ++sequence.current, text } + setMessages((current) => [...current, message]) + } +} + export function TrashPanel({ tableKey, onRestored, onClose }: TrashPanelProps) { + const refuse = useRefusalToast() const [tab, setTab] = useState('trash') const [rows, setRows] = useState(null) const [retentionDays, setRetentionDays] = useState(30) @@ -172,6 +196,7 @@ export function TrashPanel({ tableKey, onRestored, onClose }: TrashPanelProps) { }, []) const loadTrash = useCallback(async () => { + setProblem('') try { const answer = await fetchTrash(tableKey) if (!alive.current) return @@ -226,7 +251,8 @@ export function TrashPanel({ tableKey, onRestored, onClose }: TrashPanelProps) { onRestored?.(viewId) } catch (err) { if (!alive.current) return - setProblem(err instanceof Error ? err.message : 'that view could not be restored.') + const text = err instanceof Error ? err.message : 'That view could not be restored.' + refuse(text) } finally { if (alive.current) setBusyId('') } @@ -247,7 +273,8 @@ export function TrashPanel({ tableKey, onRestored, onClose }: TrashPanelProps) { setPurging({ id: row.id, name: preview.name || row.name, cells: preview.cells }) } catch (err) { if (!alive.current) return - setProblem(err instanceof Error ? err.message : 'that view could not be read.') + const text = err instanceof Error ? err.message : 'That view could not be read.' + refuse(text) } finally { if (alive.current) setBusyId('') } @@ -266,7 +293,8 @@ export function TrashPanel({ tableKey, onRestored, onClose }: TrashPanelProps) { setPurging(null) } catch (err) { if (!alive.current) return - setProblem(err instanceof Error ? err.message : 'that view could not be deleted.') + const text = err instanceof Error ? err.message : 'That view could not be deleted.' + refuse(text) setPurging(null) } finally { if (alive.current) setPurgeBusy(false) @@ -317,6 +345,8 @@ export function TrashPanel({ tableKey, onRestored, onClose }: TrashPanelProps) { {problem ? (

{problem} + {' '} +

) : null} diff --git a/web/wiring_rows/s76_e.py b/web/wiring_rows/s76_e.py new file mode 100644 index 0000000000000000000000000000000000000000..30432df83130753d4c6473954c758b2b61f66c05 --- /dev/null +++ b/web/wiring_rows/s76_e.py @@ -0,0 +1,8 @@ +"""SDLC 76 C4 toast mount.""" + +ROWS = [ + ("S76-T22 C4 toast stack", + "shell/ToastStack.tsx", r"export function ToastStack\(", + "shell/Shell.tsx", + r"