Deploy AIOS web (React glide grid + FastAPI slice)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- RELEASES.json +1 -1
- VERSION +1 -1
- api/app_guide.py +5 -2
- api/automation_engine.py +0 -4
- api/external_freshness.py +2 -43
- api/intelligence_store.py +12 -163
- api/routes_agent_harness.py +2 -43
- api/routes_alerts.py +8 -22
- api/routes_automation.py +11 -67
- api/routes_external.py +53 -62
- api/routes_geo.py +12 -54
- api/routes_grid.py +5 -6
- api/routes_nav.py +0 -1
- api/routes_odoo_tables.py +0 -6
- api/routes_query.py +64 -135
- api/routes_sheet.py +11 -3
- api/routes_starred.py +13 -86
- api/routes_tables.py +2 -61
- api/schedules.py +1 -2
- api/tool_groups/sheet.py +0 -25
- platform/core/external_tools.py +40 -0
- platform/core/grid_events.py +9 -42
- platform/core/sheet_compat.py +0 -76
- platform/core/table_store.py +0 -4
- web/public/AIOS_DEPLOY_RECEIPT +1 -1
- web/s71_frontend_contracts.py +12 -327
- web/src/apps/catalog/CatalogApp.tsx +3 -0
- web/src/apps/code/CodeAppPage.tsx +5 -11
- web/src/apps/customer-card/CustomerCardView.tsx +9 -51
- web/src/artifacts/ArtifactsPage.tsx +3 -9
- web/src/automation/AutomationDetail.tsx +12 -48
- web/src/automation/AutomationSurface.tsx +4 -29
- web/src/connectors/ConnectorModal.tsx +0 -1
- web/src/connectors/DatabasesTab.tsx +11 -42
- web/src/connectors/MonidRunDialog.tsx +21 -43
- web/src/connectors/RelationshipDiagram.tsx +3 -13
- web/src/customer-grid/CatalogView.tsx +1 -2
- web/src/customer-grid/CustomerGrid.tsx +43 -143
- web/src/customer-grid/GridActivity.tsx +10 -18
- web/src/customer-grid/MapView.tsx +0 -4
- web/src/customer-grid/RecordDetail.tsx +3 -12
- web/src/customer-grid/apiBridge.ts +5 -20
- web/src/filter-kit/FieldsHidePanel.tsx +2 -8
- web/src/index.css +0 -1
- web/src/intelligence/intelligenceApi.ts +2 -42
- web/src/operator/OperatorPage.tsx +5 -35
- web/src/query/queryApi.ts +1 -1
- web/src/query/queryParts.tsx +6 -42
- web/src/settings/SettingsModal.tsx +3 -19
- web/src/sheet/SheetPage.tsx +54 -102
RELEASES.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
{
|
| 2 |
-
"current": "
|
| 3 |
"releases": []
|
| 4 |
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"current": "859ae4071",
|
| 3 |
"releases": []
|
| 4 |
}
|
VERSION
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
|
|
|
|
| 1 |
+
859ae4071
|
api/app_guide.py
CHANGED
|
@@ -225,16 +225,19 @@ def _chart_guidance():
|
|
| 225 |
|
| 226 |
def _catalog_guidance():
|
| 227 |
"""Append the same template library as the client and the current build argument schema."""
|
|
|
|
| 228 |
from loopy_catalog_tools import build_schema
|
| 229 |
|
| 230 |
library = json.dumps(app_rules.catalog_templates(), ensure_ascii=True, indent=2)
|
| 231 |
-
|
|
|
|
|
|
|
| 232 |
return ("\n# Current Catalog template library\n\n"
|
| 233 |
"These IDs, slots and design defaults also come from GET /api/v1/catalogs/templates.\n"
|
| 234 |
f"```json\n{library}\n```\n"
|
| 235 |
"\n# Current catalog_build argument schema\n\n"
|
| 236 |
"This schema describes arguments only. Put about and intent beside action and arguments.\n"
|
| 237 |
-
f"```json\n{schema}\n```\n")
|
| 238 |
|
| 239 |
|
| 240 |
def read(section=None):
|
|
|
|
| 225 |
|
| 226 |
def _catalog_guidance():
|
| 227 |
"""Append the same template library as the client and the current build argument schema."""
|
| 228 |
+
from core import external_tools
|
| 229 |
from loopy_catalog_tools import build_schema
|
| 230 |
|
| 231 |
library = json.dumps(app_rules.catalog_templates(), ensure_ascii=True, indent=2)
|
| 232 |
+
collapsed, used = external_tools.guide_schema(build_schema())
|
| 233 |
+
schema = json.dumps(collapsed, ensure_ascii=True, indent=2)
|
| 234 |
+
nodes = "\n" + external_tools.filter_node_guide() + "\n" if used else ""
|
| 235 |
return ("\n# Current Catalog template library\n\n"
|
| 236 |
"These IDs, slots and design defaults also come from GET /api/v1/catalogs/templates.\n"
|
| 237 |
f"```json\n{library}\n```\n"
|
| 238 |
"\n# Current catalog_build argument schema\n\n"
|
| 239 |
"This schema describes arguments only. Put about and intent beside action and arguments.\n"
|
| 240 |
+
f"```json\n{schema}\n```\n{nodes}")
|
| 241 |
|
| 242 |
|
| 243 |
def read(section=None):
|
api/automation_engine.py
CHANGED
|
@@ -2518,8 +2518,6 @@ def clean_definition(raw, previous=None, username="", notes=None, rt=None):
|
|
| 2518 |
# a set the vendor is already building (and already counting against the funds gate).
|
| 2519 |
"state": dict(prev.get("state") or {}),
|
| 2520 |
"created": prev.get("created") or _authored_iso(),
|
| 2521 |
-
# S76-T37: carried here, stamped only by `create` and `patch` (a re-clean is not an update).
|
| 2522 |
-
"updatedAt": prev.get("updatedAt") or prev.get("created") or "",
|
| 2523 |
"createdBy": prev.get("createdBy") or username,
|
| 2524 |
# ⭐⭐ WAVE 35 · T37 — `system` IS STICKY ACROSS A PATCH, AND IT IS **NEVER READ FROM `raw`**.
|
| 2525 |
#
|
|
@@ -3441,7 +3439,6 @@ def create(rt, raw, username="", notes=None):
|
|
| 3441 |
f"{RETIRED_KIND_REPLACEMENT.get(defn['kind'], '')}")
|
| 3442 |
# Retired run histories reserve their ids so a new definition cannot overwrite them.
|
| 3443 |
defn["id"] = _new_id(rt.get(STORE_KEY) or {})
|
| 3444 |
-
defn["updatedAt"] = defn.get("created") or _authored_iso()
|
| 3445 |
|
| 3446 |
def _up(cur):
|
| 3447 |
cur = cur if isinstance(cur, dict) else {}
|
|
@@ -3483,7 +3480,6 @@ def patch(rt, auto_id, raw, username="", notes=None):
|
|
| 3483 |
if err:
|
| 3484 |
return None, err
|
| 3485 |
defn["id"] = str(auto_id)
|
| 3486 |
-
defn["updatedAt"] = _authored_iso()
|
| 3487 |
|
| 3488 |
def _up(cur):
|
| 3489 |
cur = cur if isinstance(cur, dict) else {}
|
|
|
|
| 2518 |
# a set the vendor is already building (and already counting against the funds gate).
|
| 2519 |
"state": dict(prev.get("state") or {}),
|
| 2520 |
"created": prev.get("created") or _authored_iso(),
|
|
|
|
|
|
|
| 2521 |
"createdBy": prev.get("createdBy") or username,
|
| 2522 |
# ⭐⭐ WAVE 35 · T37 — `system` IS STICKY ACROSS A PATCH, AND IT IS **NEVER READ FROM `raw`**.
|
| 2523 |
#
|
|
|
|
| 3439 |
f"{RETIRED_KIND_REPLACEMENT.get(defn['kind'], '')}")
|
| 3440 |
# Retired run histories reserve their ids so a new definition cannot overwrite them.
|
| 3441 |
defn["id"] = _new_id(rt.get(STORE_KEY) or {})
|
|
|
|
| 3442 |
|
| 3443 |
def _up(cur):
|
| 3444 |
cur = cur if isinstance(cur, dict) else {}
|
|
|
|
| 3480 |
if err:
|
| 3481 |
return None, err
|
| 3482 |
defn["id"] = str(auto_id)
|
|
|
|
| 3483 |
|
| 3484 |
def _up(cur):
|
| 3485 |
cur = cur if isinstance(cur, dict) else {}
|
api/external_freshness.py
CHANGED
|
@@ -59,40 +59,6 @@ def _sync_date(value):
|
|
| 59 |
return None
|
| 60 |
|
| 61 |
|
| 62 |
-
def amazon_sync_stamp(cur, table_key):
|
| 63 |
-
"""Read a table's last successful source pass before its legacy raw-table receipt."""
|
| 64 |
-
import amazon_relational
|
| 65 |
-
|
| 66 |
-
raw = amazon_relational.SOURCE.get(table_key)
|
| 67 |
-
if not raw or cur is None:
|
| 68 |
-
return None
|
| 69 |
-
marker = "amzn_sync_mark_" + raw.removeprefix("amzn_")
|
| 70 |
-
for entity in (marker, raw):
|
| 71 |
-
row = cur.execute("SELECT updated_at FROM _sync_state WHERE entity = ? AND phase = 'done'",
|
| 72 |
-
[entity]).fetchone()
|
| 73 |
-
if row:
|
| 74 |
-
return row[0]
|
| 75 |
-
return None
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
def _amazon_refreshes(session, keys):
|
| 79 |
-
"""Read only sync metadata for the authorized Amazon databases on this tenant's cursor."""
|
| 80 |
-
import assistant_mirror
|
| 81 |
-
|
| 82 |
-
cur, refreshed = None, {}
|
| 83 |
-
for key in keys:
|
| 84 |
-
try:
|
| 85 |
-
if cur is None:
|
| 86 |
-
cur, refusal = assistant_mirror.open_cursor(session, key)
|
| 87 |
-
if refusal is not None or cur is None:
|
| 88 |
-
cur = None
|
| 89 |
-
continue
|
| 90 |
-
refreshed[key] = amazon_sync_stamp(cur, key)
|
| 91 |
-
except Exception:
|
| 92 |
-
continue
|
| 93 |
-
return refreshed
|
| 94 |
-
|
| 95 |
-
|
| 96 |
def _mirror_refreshes(session, definitions, keys):
|
| 97 |
"""Read authorized mirror stamps with cached successful cursors and no product-row reads."""
|
| 98 |
import assistant_mirror
|
|
@@ -183,9 +149,7 @@ def snapshot(session, databases):
|
|
| 183 |
except Exception:
|
| 184 |
docs[name] = {}
|
| 185 |
odoo = odoo_relational.sync_freshness(user_tables.lend(rt, **docs))
|
| 186 |
-
|
| 187 |
-
amazon = _amazon_refreshes(session, amazon_keys) if amazon_keys else {}
|
| 188 |
-
mirror_keys = {key for key in connected - amazon_keys
|
| 189 |
if not user_tables.materialises(key, st=lent, defn=definitions[key])}
|
| 190 |
mirror = _mirror_refreshes(session, definitions, mirror_keys) if mirror_keys else {}
|
| 191 |
facts = {}
|
|
@@ -204,7 +168,7 @@ def snapshot(session, databases):
|
|
| 204 |
successes.append(odoo.get("lastGoodSyncAt"))
|
| 205 |
if job.get("state") == "ready":
|
| 206 |
successes.append(job.get("at"))
|
| 207 |
-
values = [
|
| 208 |
stamp = next((stamp for value in values if (stamp := utc_stamp(value)) is not None), None)
|
| 209 |
synced_on = next((day for value in values if (day := _sync_date(value)) is not None), None)
|
| 210 |
if stamp is not None:
|
|
@@ -239,11 +203,6 @@ def add(result, session, *, facts=None):
|
|
| 239 |
result.pop("source_synced_on", None)
|
| 240 |
result.pop("last_edited_at", None)
|
| 241 |
result.update(source_synced_at=None, source_sync="never_synced")
|
| 242 |
-
if str(result.get("database") or "").startswith("ut_amzn_"):
|
| 243 |
-
if facts is None:
|
| 244 |
-
facts = snapshot(session, [result.get("database")])
|
| 245 |
-
result.update(facts.get(result.get("database"), {}))
|
| 246 |
-
return result
|
| 247 |
refreshed = _refresh_value(version) if kind == "mirror_user_table" else None
|
| 248 |
if kind == "mirror_user_table" and isinstance(version, dict):
|
| 249 |
stamp = utc_stamp(refreshed)
|
|
|
|
| 59 |
return None
|
| 60 |
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
def _mirror_refreshes(session, definitions, keys):
|
| 63 |
"""Read authorized mirror stamps with cached successful cursors and no product-row reads."""
|
| 64 |
import assistant_mirror
|
|
|
|
| 149 |
except Exception:
|
| 150 |
docs[name] = {}
|
| 151 |
odoo = odoo_relational.sync_freshness(user_tables.lend(rt, **docs))
|
| 152 |
+
mirror_keys = {key for key in connected
|
|
|
|
|
|
|
| 153 |
if not user_tables.materialises(key, st=lent, defn=definitions[key])}
|
| 154 |
mirror = _mirror_refreshes(session, definitions, mirror_keys) if mirror_keys else {}
|
| 155 |
facts = {}
|
|
|
|
| 168 |
successes.append(odoo.get("lastGoodSyncAt"))
|
| 169 |
if job.get("state") == "ready":
|
| 170 |
successes.append(job.get("at"))
|
| 171 |
+
values = [mirror.get(key), *successes]
|
| 172 |
stamp = next((stamp for value in values if (stamp := utc_stamp(value)) is not None), None)
|
| 173 |
synced_on = next((day for value in values if (day := _sync_date(value)) is not None), None)
|
| 174 |
if stamp is not None:
|
|
|
|
| 203 |
result.pop("source_synced_on", None)
|
| 204 |
result.pop("last_edited_at", None)
|
| 205 |
result.update(source_synced_at=None, source_sync="never_synced")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
refreshed = _refresh_value(version) if kind == "mirror_user_table" else None
|
| 207 |
if kind == "mirror_user_table" and isinstance(version, dict):
|
| 208 |
stamp = utc_stamp(refreshed)
|
api/intelligence_store.py
CHANGED
|
@@ -6,7 +6,6 @@ from functools import lru_cache
|
|
| 6 |
from pathlib import Path
|
| 7 |
import importlib
|
| 8 |
import difflib
|
| 9 |
-
import hashlib
|
| 10 |
import json
|
| 11 |
import re
|
| 12 |
|
|
@@ -268,10 +267,10 @@ def _document(raw):
|
|
| 268 |
return raw
|
| 269 |
|
| 270 |
|
| 271 |
-
def _files(session, *, include_generated=False, wiki_only=False
|
| 272 |
"""Read authored files, adding reader-scoped system pages only for Wiki requests."""
|
| 273 |
try:
|
| 274 |
-
raw = _document(session.runtime.get(STORE_KEY)
|
| 275 |
_check_file_capacity(session, raw)
|
| 276 |
import wiki_log
|
| 277 |
files = _project_templates(session, raw)
|
|
@@ -333,9 +332,9 @@ def _database_note_record(session, key, *, stored=None, with_body=False):
|
|
| 333 |
if not definition or not can_read(session, {"reads": [definition["key"]]}):
|
| 334 |
raise IntelligenceError("no_file", "This workspace has no file at that path.", 404)
|
| 335 |
note = user_tables.shared_note("database", key, st=session.runtime)
|
| 336 |
-
if not note
|
| 337 |
raise IntelligenceError("no_file", "This workspace has no file at that path.", 404)
|
| 338 |
-
meta = {"title":
|
| 339 |
"description": f"Shared note for {definition['label']}.", "reads": [definition["key"]],
|
| 340 |
"approvers": [], "approvals_needed": 1, "tools": [], "databaseKey": key}
|
| 341 |
text = note.get("body") or ""
|
|
@@ -392,7 +391,7 @@ def _database_note_file(session, path, *, version=0):
|
|
| 392 |
"latestVersion": current["version"], "history": history, "versions": len(history), "limits": limits()}
|
| 393 |
|
| 394 |
|
| 395 |
-
def _put_database_note(session, key, body, actor, base_version, base_updated
|
| 396 |
"""Let the canonical writer enforce admission and its exact base on every atomic attempt."""
|
| 397 |
from core import user_tables
|
| 398 |
|
|
@@ -410,13 +409,7 @@ def _put_database_note(session, key, body, actor, base_version, base_updated, *,
|
|
| 410 |
prior = (_document(raw).get("database:" + key) or {})
|
| 411 |
if int(prior.get("version") or 0) != base_version or prior.get("updated") != base_updated:
|
| 412 |
raise IntelligenceError("version_conflict", "The note changed. Reload it before saving.", 409)
|
| 413 |
-
|
| 414 |
-
note = updated["database:" + key]
|
| 415 |
-
if title is not None or prior.get("title"):
|
| 416 |
-
note["title"] = title if title is not None else prior["title"]
|
| 417 |
-
if deleted:
|
| 418 |
-
note["deleted"] = True
|
| 419 |
-
return updated
|
| 420 |
|
| 421 |
return session.runtime.update(bucket, checked, **kwargs)
|
| 422 |
|
|
@@ -701,8 +694,6 @@ def _row(record, entry=None, *, session=None):
|
|
| 701 |
**{key: deepcopy(entry[key]) for key in ("agent", "onBehalfOf", "approvedBy", "proposalId", "restoredFrom") if key in entry},
|
| 702 |
"created": record["created"], "lastUsed": record.get("lastUsed"),
|
| 703 |
**{key: record[key] for key in ("databaseKey", "canEdit", "revisionHistory") if key in record},
|
| 704 |
-
"canEdit": bool(session and (record.get("canEdit") if "databaseKey" in record
|
| 705 |
-
else can_edit(session, _head(record)["metadata"]))),
|
| 706 |
"versions": sum(session is None or can_read(session, version["metadata"])
|
| 707 |
for version in record["versions"]), "trimmed": record.get("trimmed", 0),
|
| 708 |
**({"fieldCheck": _field_check(session, meta)} if session and meta.get("required_fields") else {})}
|
|
@@ -737,13 +728,7 @@ def list_files(session, *, section="", query="", folder="", offset=0, limit=100,
|
|
| 737 |
needle = str(query or "").strip().casefold()
|
| 738 |
rows = []
|
| 739 |
wiki_requested = selected == "wiki" or prefix.casefold().startswith("wiki/")
|
| 740 |
-
|
| 741 |
-
raw = _document(session.runtime.get(STORE_KEY))
|
| 742 |
-
except IntelligenceError:
|
| 743 |
-
raise
|
| 744 |
-
except Exception:
|
| 745 |
-
raise IntelligenceError("store_unavailable", "Brain files could not be read. Try again.", 503) from None
|
| 746 |
-
for path, record in sorted(_files(session, include_generated=wiki_requested, raw=raw).items()):
|
| 747 |
if not _head(record):
|
| 748 |
continue
|
| 749 |
meta = _head(record)["metadata"]
|
|
@@ -760,78 +745,7 @@ def list_files(session, *, section="", query="", folder="", offset=0, limit=100,
|
|
| 760 |
if direct:
|
| 761 |
rows = [row for row in rows if "/" not in row["path"][len(prefix):]]
|
| 762 |
return {"files": rows[offset:offset + limit], "total": len(rows), "offset": offset,
|
| 763 |
-
"limit": limit, "sections": sections(), "folders": folders, "limits": limits()
|
| 764 |
-
"canManageFolders": bool(getattr(session, "admin", False) and not trusted_identity(session)[1].get("agent")),
|
| 765 |
-
**({"folderRevision": _folder_revision(raw)} if getattr(session, "admin", False) else {})}
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
def _folder_revision(raw):
|
| 769 |
-
"""Bind folder changes to the exact file identities and versions in their atomic update."""
|
| 770 |
-
heads = [(path, record.get("created"), (_head(record) or {}).get("version", 0))
|
| 771 |
-
for path, record in sorted(_document(raw).items())]
|
| 772 |
-
return int(hashlib.sha256(json.dumps(heads, sort_keys=True).encode()).hexdigest()[:13], 16)
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
def change_folder(caller, path, *, name=None, expected_revision):
|
| 776 |
-
"""Rename a folder or promote its children in one revision-checked update."""
|
| 777 |
-
session, identity = trusted_identity(caller)
|
| 778 |
-
_authorize(session)
|
| 779 |
-
if not session.admin or identity.get("agent"):
|
| 780 |
-
raise IntelligenceError("folder_admin_required", "Only an Administrator can change Brain folders.", 403)
|
| 781 |
-
if type(expected_revision) is not int or expected_revision < 0:
|
| 782 |
-
raise IntelligenceError("bad_revision", "Reload the folders before trying again.")
|
| 783 |
-
path = normalize_path(path, folder=True)
|
| 784 |
-
def reserved(folder):
|
| 785 |
-
folded = folder.casefold()
|
| 786 |
-
return (folded in ("database-notes", "wiki") or folded.startswith(DATABASE_NOTES_PREFIX)
|
| 787 |
-
or any(folded == root or folded.startswith(root + "/")
|
| 788 |
-
for root in ("wiki/log", "wiki/index", "wiki/purposes")))
|
| 789 |
-
|
| 790 |
-
if reserved(path):
|
| 791 |
-
raise IntelligenceError("folder_reserved", "This folder is maintained by the workspace.", 403)
|
| 792 |
-
parent = path.rpartition("/")[0]
|
| 793 |
-
target = parent
|
| 794 |
-
if name is not None:
|
| 795 |
-
name = normalize_path(name, folder=True)
|
| 796 |
-
if "/" in name:
|
| 797 |
-
raise IntelligenceError("bad_name", "Use one folder name without slashes.")
|
| 798 |
-
target = normalize_path((parent + "/" if parent else "") + name, folder=True)
|
| 799 |
-
if reserved(target):
|
| 800 |
-
raise IntelligenceError("folder_reserved", "This folder name is reserved.", 403)
|
| 801 |
-
|
| 802 |
-
def move(raw):
|
| 803 |
-
files = dict(_document(raw))
|
| 804 |
-
if _folder_revision(files) != expected_revision:
|
| 805 |
-
raise IntelligenceError("folder_revision_stale", "Folders changed. Reload before trying again.", 409)
|
| 806 |
-
prefix = path + "/"
|
| 807 |
-
projected = _project_templates(session, files)
|
| 808 |
-
if any(key.startswith(prefix) and key in _template_catalog() and _head(record)
|
| 809 |
-
for key, record in projected.items()):
|
| 810 |
-
raise IntelligenceError("folder_reserved", "This folder contains a maintained file.", 403)
|
| 811 |
-
moving = {key: record for key, record in files.items() if key.startswith(prefix)}
|
| 812 |
-
if not moving or not any(_head(record) for record in moving.values()):
|
| 813 |
-
raise IntelligenceError("no_folder", "This folder is no longer available.", 404)
|
| 814 |
-
if name is not None and target != path and any(key.startswith(target + "/") for key in projected):
|
| 815 |
-
raise IntelligenceError("folder_exists", "A folder with that name already exists.", 409)
|
| 816 |
-
destinations = {key: normalize_path((target + "/" if target else "") + key[len(prefix):]) for key in moving}
|
| 817 |
-
if any((destination in files and destination not in moving) or destination in _template_catalog()
|
| 818 |
-
for destination in destinations.values()):
|
| 819 |
-
raise IntelligenceError("file_exists", "A child has the same path as an existing file. Rename it first.", 409)
|
| 820 |
-
for key, record in moving.items():
|
| 821 |
-
_assert_authored_path(key)
|
| 822 |
-
if key in _template_catalog() or (_head(record) or {}).get("metadata", {}).get("generated"):
|
| 823 |
-
raise IntelligenceError("folder_reserved", "This folder contains a maintained file.", 403)
|
| 824 |
-
del files[key]
|
| 825 |
-
for key, record in moving.items():
|
| 826 |
-
destination = destinations[key]
|
| 827 |
-
_assert_authored_path(destination)
|
| 828 |
-
files[destination] = {**record, "path": destination,
|
| 829 |
-
"proposals": {pid: {**proposal, "path": destination}
|
| 830 |
-
for pid, proposal in (record.get("proposals") or {}).items()}}
|
| 831 |
-
return files
|
| 832 |
-
|
| 833 |
-
_update(session, move)
|
| 834 |
-
return {"path": target} if name is not None else {"deleted": path}
|
| 835 |
|
| 836 |
|
| 837 |
def _summaries(session):
|
|
@@ -1945,76 +1859,15 @@ def decide_proposal(session, proposal_id, decision):
|
|
| 1945 |
return saved
|
| 1946 |
|
| 1947 |
|
| 1948 |
-
def
|
| 1949 |
-
"""
|
| 1950 |
-
session, identity = trusted_identity(caller)
|
| 1951 |
-
_authorize(session)
|
| 1952 |
-
path = normalize_path(path)
|
| 1953 |
-
_assert_authored_path(path)
|
| 1954 |
-
if not isinstance(title, str) or not title.strip() or len(title.strip()) > 200:
|
| 1955 |
-
raise IntelligenceError("bad_title", "Use a title of 1 to 200 characters.")
|
| 1956 |
-
if type(expected_version) is not int or expected_version < 1:
|
| 1957 |
-
raise IntelligenceError("bad_version", "Reload the file before trying again.")
|
| 1958 |
-
if _database_note_path(path):
|
| 1959 |
-
if identity.get("agent"):
|
| 1960 |
-
raise IntelligenceError("approval_required", "An agent cannot rename a shared note.", 403)
|
| 1961 |
-
record = _database_note_record(session, path[len(DATABASE_NOTES_PREFIX):-3], with_body=True)
|
| 1962 |
-
if record["path"] != path:
|
| 1963 |
-
raise IntelligenceError("no_file", "This workspace has no file at that path.", 404)
|
| 1964 |
-
entry = _head(record)
|
| 1965 |
-
_put_database_note(session, record["databaseKey"], entry["body"], session.uname,
|
| 1966 |
-
expected_version, entry["created"], title=title.strip())
|
| 1967 |
-
saved = _database_note_file(session, path)
|
| 1968 |
-
_log_write(session, path, identity, expected_version, saved["version"])
|
| 1969 |
-
return saved
|
| 1970 |
-
saved = {}
|
| 1971 |
-
|
| 1972 |
-
def rename(raw):
|
| 1973 |
-
saved.clear()
|
| 1974 |
-
files = _editable_files(session, raw, path)
|
| 1975 |
-
record = _readable_record(session, files, path)
|
| 1976 |
-
head = _head(record)
|
| 1977 |
-
if not can_edit(session, head["metadata"]):
|
| 1978 |
-
raise IntelligenceError("file_read_only", "Your current rights do not allow renaming this file.", 403)
|
| 1979 |
-
if head["version"] != expected_version:
|
| 1980 |
-
raise IntelligenceError("version_conflict", "The file changed. Reload it before renaming.", 409)
|
| 1981 |
-
if len(record["versions"]) >= MAX_VERSIONS:
|
| 1982 |
-
raise IntelligenceError("too_many_versions", "This file already has 100 versions.", 409)
|
| 1983 |
-
metadata = {**head["metadata"], "title": title.strip()}
|
| 1984 |
-
body, metadata = prepare_markdown("---\n" + yaml.safe_dump(metadata, sort_keys=False, allow_unicode=True)
|
| 1985 |
-
+ "---\n" + head["body"].partition("\n---\n")[2], session.uname)
|
| 1986 |
-
record = {**record, "versions": [*record["versions"], _entry(body, metadata, expected_version + 1, identity)],
|
| 1987 |
-
"proposals": {key: {**row, "status": "stale"} if row["status"] in ("pending", "approving") else row
|
| 1988 |
-
for key, row in (record.get("proposals") or {}).items()}}
|
| 1989 |
-
files[path] = record
|
| 1990 |
-
saved.update(_file(record, session=session))
|
| 1991 |
-
return files
|
| 1992 |
-
|
| 1993 |
-
_update(session, rename)
|
| 1994 |
-
_log_write(session, path, identity, expected_version, saved["version"])
|
| 1995 |
-
return saved
|
| 1996 |
-
|
| 1997 |
-
|
| 1998 |
-
def delete_file(caller, path, *, expected_version=None):
|
| 1999 |
-
"""Delete an editable workspace file or clear its canonical database note."""
|
| 2000 |
session, identity = trusted_identity(caller)
|
| 2001 |
_authorize(session)
|
| 2002 |
path = normalize_path(path)
|
| 2003 |
_assert_authored_path(path)
|
| 2004 |
-
if expected_version is not None and (type(expected_version) is not int or expected_version < 1):
|
| 2005 |
-
raise IntelligenceError("bad_version", "Reload the file before trying again.")
|
| 2006 |
if _database_note_path(path):
|
| 2007 |
-
|
| 2008 |
-
|
| 2009 |
-
record = _database_note_record(session, path[len(DATABASE_NOTES_PREFIX):-3], with_body=True)
|
| 2010 |
-
if record["path"] != path:
|
| 2011 |
-
raise IntelligenceError("no_file", "This workspace has no file at that path.", 404)
|
| 2012 |
-
entry = _head(record)
|
| 2013 |
-
_put_database_note(session, record["databaseKey"], "", session.uname,
|
| 2014 |
-
expected_version if expected_version is not None else entry["version"],
|
| 2015 |
-
entry["created"], deleted=True)
|
| 2016 |
-
_log_write(session, path, identity, entry["version"], None)
|
| 2017 |
-
return {"deleted": path}
|
| 2018 |
removed = {}
|
| 2019 |
|
| 2020 |
def remove(raw):
|
|
@@ -2022,10 +1875,6 @@ def delete_file(caller, path, *, expected_version=None):
|
|
| 2022 |
files = _editable_files(session, raw, path)
|
| 2023 |
record = _readable_record(session, files, path)
|
| 2024 |
removed["version"] = _head(record)["version"]
|
| 2025 |
-
if not identity.get("agent") and not can_edit(session, _head(record)["metadata"]):
|
| 2026 |
-
raise IntelligenceError("file_read_only", "Your current rights do not allow deleting this file.", 403)
|
| 2027 |
-
if expected_version is not None and expected_version != removed["version"]:
|
| 2028 |
-
raise IntelligenceError("version_conflict", "The file changed. Reload it before deleting.", 409)
|
| 2029 |
if identity.get("agent") and (record.get("memoryScope") != [identity["agent"], session.uname]
|
| 2030 |
or not _head(record) or _head(record)["metadata"]["section"] != "agent-memory"):
|
| 2031 |
raise IntelligenceError("approval_required", "An agent cannot delete a shared file.", 403)
|
|
|
|
| 6 |
from pathlib import Path
|
| 7 |
import importlib
|
| 8 |
import difflib
|
|
|
|
| 9 |
import json
|
| 10 |
import re
|
| 11 |
|
|
|
|
| 267 |
return raw
|
| 268 |
|
| 269 |
|
| 270 |
+
def _files(session, *, include_generated=False, wiki_only=False):
|
| 271 |
"""Read authored files, adding reader-scoped system pages only for Wiki requests."""
|
| 272 |
try:
|
| 273 |
+
raw = _document(session.runtime.get(STORE_KEY))
|
| 274 |
_check_file_capacity(session, raw)
|
| 275 |
import wiki_log
|
| 276 |
files = _project_templates(session, raw)
|
|
|
|
| 332 |
if not definition or not can_read(session, {"reads": [definition["key"]]}):
|
| 333 |
raise IntelligenceError("no_file", "This workspace has no file at that path.", 404)
|
| 334 |
note = user_tables.shared_note("database", key, st=session.runtime)
|
| 335 |
+
if not note:
|
| 336 |
raise IntelligenceError("no_file", "This workspace has no file at that path.", 404)
|
| 337 |
+
meta = {"title": definition["label"], "section": "database-notes", "owner": definition["owner"],
|
| 338 |
"description": f"Shared note for {definition['label']}.", "reads": [definition["key"]],
|
| 339 |
"approvers": [], "approvals_needed": 1, "tools": [], "databaseKey": key}
|
| 340 |
text = note.get("body") or ""
|
|
|
|
| 391 |
"latestVersion": current["version"], "history": history, "versions": len(history), "limits": limits()}
|
| 392 |
|
| 393 |
|
| 394 |
+
def _put_database_note(session, key, body, actor, base_version, base_updated):
|
| 395 |
"""Let the canonical writer enforce admission and its exact base on every atomic attempt."""
|
| 396 |
from core import user_tables
|
| 397 |
|
|
|
|
| 409 |
prior = (_document(raw).get("database:" + key) or {})
|
| 410 |
if int(prior.get("version") or 0) != base_version or prior.get("updated") != base_updated:
|
| 411 |
raise IntelligenceError("version_conflict", "The note changed. Reload it before saving.", 409)
|
| 412 |
+
return callback(raw)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
|
| 414 |
return session.runtime.update(bucket, checked, **kwargs)
|
| 415 |
|
|
|
|
| 694 |
**{key: deepcopy(entry[key]) for key in ("agent", "onBehalfOf", "approvedBy", "proposalId", "restoredFrom") if key in entry},
|
| 695 |
"created": record["created"], "lastUsed": record.get("lastUsed"),
|
| 696 |
**{key: record[key] for key in ("databaseKey", "canEdit", "revisionHistory") if key in record},
|
|
|
|
|
|
|
| 697 |
"versions": sum(session is None or can_read(session, version["metadata"])
|
| 698 |
for version in record["versions"]), "trimmed": record.get("trimmed", 0),
|
| 699 |
**({"fieldCheck": _field_check(session, meta)} if session and meta.get("required_fields") else {})}
|
|
|
|
| 728 |
needle = str(query or "").strip().casefold()
|
| 729 |
rows = []
|
| 730 |
wiki_requested = selected == "wiki" or prefix.casefold().startswith("wiki/")
|
| 731 |
+
for path, record in sorted(_files(session, include_generated=wiki_requested).items()):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 732 |
if not _head(record):
|
| 733 |
continue
|
| 734 |
meta = _head(record)["metadata"]
|
|
|
|
| 745 |
if direct:
|
| 746 |
rows = [row for row in rows if "/" not in row["path"][len(prefix):]]
|
| 747 |
return {"files": rows[offset:offset + limit], "total": len(rows), "offset": offset,
|
| 748 |
+
"limit": limit, "sections": sections(), "folders": folders, "limits": limits()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 749 |
|
| 750 |
|
| 751 |
def _summaries(session):
|
|
|
|
| 1859 |
return saved
|
| 1860 |
|
| 1861 |
|
| 1862 |
+
def delete_file(caller, path):
|
| 1863 |
+
"""Delete one workspace file and its versions without touching agent files."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1864 |
session, identity = trusted_identity(caller)
|
| 1865 |
_authorize(session)
|
| 1866 |
path = normalize_path(path)
|
| 1867 |
_assert_authored_path(path)
|
|
|
|
|
|
|
| 1868 |
if _database_note_path(path):
|
| 1869 |
+
_database_note_file(session, path)
|
| 1870 |
+
raise IntelligenceError("database_note_reserved", "A Database note belongs to its database.", 403)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1871 |
removed = {}
|
| 1872 |
|
| 1873 |
def remove(raw):
|
|
|
|
| 1875 |
files = _editable_files(session, raw, path)
|
| 1876 |
record = _readable_record(session, files, path)
|
| 1877 |
removed["version"] = _head(record)["version"]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1878 |
if identity.get("agent") and (record.get("memoryScope") != [identity["agent"], session.uname]
|
| 1879 |
or not _head(record) or _head(record)["metadata"]["section"] != "agent-memory"):
|
| 1880 |
raise IntelligenceError("approval_required", "An agent cannot delete a shared file.", 403)
|
api/routes_agent_harness.py
CHANGED
|
@@ -197,54 +197,13 @@ def decide_intelligence_proposal(proposal_id: str, decision: str, body: dict = B
|
|
| 197 |
|
| 198 |
|
| 199 |
@router.delete("/intelligence/files")
|
| 200 |
-
def delete_intelligence_file(path: str = "",
|
| 201 |
session: Session = Depends(module_gate("intelligence"))):
|
| 202 |
"""Delete a workspace file under the Intelligence module grant."""
|
| 203 |
import intelligence_store as intelligence
|
| 204 |
|
| 205 |
try:
|
| 206 |
-
|
| 207 |
-
raise intelligence.IntelligenceError("bad_version", "Reload the file before trying again.")
|
| 208 |
-
return {"deleted": intelligence.delete_file(session, path, expected_version=expectedVersion)["deleted"]}
|
| 209 |
-
except intelligence.IntelligenceError as exc:
|
| 210 |
-
raise _intelligence_error(exc) from None
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
@router.patch("/intelligence/files")
|
| 214 |
-
def rename_intelligence_file(body: dict = Body(default=None),
|
| 215 |
-
session: Session = Depends(module_gate("intelligence"))):
|
| 216 |
-
import intelligence_store as intelligence
|
| 217 |
-
|
| 218 |
-
body = body or {}
|
| 219 |
-
try:
|
| 220 |
-
return intelligence.rename_file(session, body.get("path"), body.get("title"),
|
| 221 |
-
expected_version=body.get("expectedVersion"))
|
| 222 |
-
except intelligence.IntelligenceError as exc:
|
| 223 |
-
raise _intelligence_error(exc) from None
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
@router.patch("/intelligence/folders")
|
| 227 |
-
def rename_intelligence_folder(body: dict = Body(default=None),
|
| 228 |
-
session: Session = Depends(module_gate("intelligence"))):
|
| 229 |
-
import intelligence_store as intelligence
|
| 230 |
-
|
| 231 |
-
body = body or {}
|
| 232 |
-
try:
|
| 233 |
-
if "name" not in body or not isinstance(body["name"], str):
|
| 234 |
-
raise intelligence.IntelligenceError("bad_name", "Enter a folder name.")
|
| 235 |
-
return intelligence.change_folder(session, body.get("path"), name=body["name"],
|
| 236 |
-
expected_revision=body.get("expectedRevision"))
|
| 237 |
-
except intelligence.IntelligenceError as exc:
|
| 238 |
-
raise _intelligence_error(exc) from None
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
@router.delete("/intelligence/folders")
|
| 242 |
-
def delete_intelligence_folder(path: str = "", expectedRevision: int = None,
|
| 243 |
-
session: Session = Depends(module_gate("intelligence"))):
|
| 244 |
-
import intelligence_store as intelligence
|
| 245 |
-
|
| 246 |
-
try:
|
| 247 |
-
return intelligence.change_folder(session, path, expected_revision=expectedRevision)
|
| 248 |
except intelligence.IntelligenceError as exc:
|
| 249 |
raise _intelligence_error(exc) from None
|
| 250 |
|
|
|
|
| 197 |
|
| 198 |
|
| 199 |
@router.delete("/intelligence/files")
|
| 200 |
+
def delete_intelligence_file(path: str = "",
|
| 201 |
session: Session = Depends(module_gate("intelligence"))):
|
| 202 |
"""Delete a workspace file under the Intelligence module grant."""
|
| 203 |
import intelligence_store as intelligence
|
| 204 |
|
| 205 |
try:
|
| 206 |
+
return intelligence.delete_file(session, path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
except intelligence.IntelligenceError as exc:
|
| 208 |
raise _intelligence_error(exc) from None
|
| 209 |
|
api/routes_alerts.py
CHANGED
|
@@ -279,48 +279,34 @@ def list_alerts(session: Session = Depends(require_session)):
|
|
| 279 |
st=session.runtime)}
|
| 280 |
|
| 281 |
|
| 282 |
-
def _notification_visible(session, item
|
| 283 |
"""Apply the current database admission doors without evaluating or changing alerts."""
|
| 284 |
from assistant_feed import _target
|
| 285 |
target = _target(item)
|
| 286 |
if not target:
|
| 287 |
return True
|
| 288 |
-
module = str(target.get("module") or "")
|
| 289 |
-
database = (str(target.get("id") or "")
|
| 290 |
module if module.startswith("ut_") or module in {"customer_data", "product_data"} else "")
|
| 291 |
if not database:
|
| 292 |
return module != "database"
|
| 293 |
-
if memo is not None and database in memo["databases"]:
|
| 294 |
-
return memo["databases"][database]
|
| 295 |
-
visible = True
|
| 296 |
try:
|
| 297 |
session.require(database)
|
| 298 |
if database.startswith("ut_"):
|
| 299 |
from routes_tables import _defn_or_refuse
|
| 300 |
-
|
| 301 |
-
_defn_or_refuse(session, database, defs_only=True, scope_applied=True)
|
| 302 |
-
else:
|
| 303 |
-
from core import user_tables
|
| 304 |
-
if memo["definitions"] is None:
|
| 305 |
-
memo["definitions"] = user_tables.lend_defs(session.runtime)
|
| 306 |
-
_defn_or_refuse(session, database, st=memo["definitions"],
|
| 307 |
-
defs_only=True, scope_applied=True)
|
| 308 |
except HTTPException as exc:
|
| 309 |
if exc.status_code in {403, 404, 409}:
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
if memo is not None:
|
| 314 |
-
memo["databases"][database] = visible
|
| 315 |
-
return visible
|
| 316 |
|
| 317 |
|
| 318 |
@router.get("/notifications")
|
| 319 |
def list_notifications(session: Session = Depends(require_session)):
|
| 320 |
items = (session.runtime.get(alerts.NOTIFICATIONS_KEY) or {}).get(str(session.uname)) or []
|
| 321 |
-
memo = {"databases": {}, "definitions": None}
|
| 322 |
visible = [dict(item) for item in items if isinstance(item, dict)
|
| 323 |
-
and _notification_visible(session, item
|
| 324 |
visible.sort(key=lambda item: str(item.get("at") or ""), reverse=True)
|
| 325 |
return {"unread": sum(not item.get("read") for item in visible), "items": visible}
|
| 326 |
|
|
|
|
| 279 |
st=session.runtime)}
|
| 280 |
|
| 281 |
|
| 282 |
+
def _notification_visible(session, item):
|
| 283 |
"""Apply the current database admission doors without evaluating or changing alerts."""
|
| 284 |
from assistant_feed import _target
|
| 285 |
target = _target(item)
|
| 286 |
if not target:
|
| 287 |
return True
|
| 288 |
+
module = str(target.get("module") or "")
|
| 289 |
+
database = (str(target.get("id") or "") if module == "database" else
|
| 290 |
module if module.startswith("ut_") or module in {"customer_data", "product_data"} else "")
|
| 291 |
if not database:
|
| 292 |
return module != "database"
|
|
|
|
|
|
|
|
|
|
| 293 |
try:
|
| 294 |
session.require(database)
|
| 295 |
if database.startswith("ut_"):
|
| 296 |
from routes_tables import _defn_or_refuse
|
| 297 |
+
_defn_or_refuse(session, database, defs_only=True, scope_applied=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
except HTTPException as exc:
|
| 299 |
if exc.status_code in {403, 404, 409}:
|
| 300 |
+
return False
|
| 301 |
+
raise
|
| 302 |
+
return True
|
|
|
|
|
|
|
|
|
|
| 303 |
|
| 304 |
|
| 305 |
@router.get("/notifications")
|
| 306 |
def list_notifications(session: Session = Depends(require_session)):
|
| 307 |
items = (session.runtime.get(alerts.NOTIFICATIONS_KEY) or {}).get(str(session.uname)) or []
|
|
|
|
| 308 |
visible = [dict(item) for item in items if isinstance(item, dict)
|
| 309 |
+
and _notification_visible(session, item)]
|
| 310 |
visible.sort(key=lambda item: str(item.get("at") or ""), reverse=True)
|
| 311 |
return {"unread": sum(not item.get("read") for item in visible), "items": visible}
|
| 312 |
|
api/routes_automation.py
CHANGED
|
@@ -61,29 +61,6 @@ MODULE = "automation"
|
|
| 61 |
_GATE = module_gate(MODULE)
|
| 62 |
|
| 63 |
|
| 64 |
-
def _item_rights(session, item):
|
| 65 |
-
"""Use the item's owner for writes, with Administrator authority and system exclusions."""
|
| 66 |
-
if item and item.get("id") == ODOO_SYNC_ID:
|
| 67 |
-
return {"edit": bool(session.admin), "delete": False}
|
| 68 |
-
editable = bool(item and session.uname and not item.get("system") and not item.get("retired")
|
| 69 |
-
and not str(item.get("id") or "").startswith(("field:", "system:"))
|
| 70 |
-
and not item.get("retiredOnceAt") and (session.admin or session.uname ==
|
| 71 |
-
(item.get("createdBy") or item.get("created_by"))))
|
| 72 |
-
return {"edit": editable, "delete": editable}
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
def _require_item_edit(session, item):
|
| 76 |
-
if not item:
|
| 77 |
-
raise err(404, "unknown_automation", "This item is no longer available.")
|
| 78 |
-
if not _item_rights(session, item)["edit"]:
|
| 79 |
-
raise err(403, "automation_read_only", "Your current rights do not allow changes to this item.")
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
def _voice_item_rights(session, row, record):
|
| 83 |
-
row["capabilities"] = {**row.get("capabilities", {}), **_item_rights(session, record)}
|
| 84 |
-
return row
|
| 85 |
-
|
| 86 |
-
|
| 87 |
def _governed_query_tool(session, database=""):
|
| 88 |
"""Adapt C4 dry-runs to B's mounted C2 Query door without owning Query authority."""
|
| 89 |
def invoke(prompt, context):
|
|
@@ -271,11 +248,8 @@ def list_voice_agents(session: Session = Depends(_GATE)):
|
|
| 271 |
"""
|
| 272 |
rows = voice.list_browser_dtos(session.runtime)
|
| 273 |
options = _voice_options(session) if rows else None
|
| 274 |
-
records = voice._store(session.runtime)["voice_agent"] if rows else {}
|
| 275 |
for row in rows:
|
| 276 |
row["audienceOptions"] = options
|
| 277 |
-
voice_id = row.get("automationId") or row.get("voiceAgentId")
|
| 278 |
-
_voice_item_rights(session, row, records.get(voice_id))
|
| 279 |
return {"voiceAgents": rows}
|
| 280 |
|
| 281 |
|
|
@@ -290,7 +264,6 @@ def create_voice_agent(body: dict = Body(default=None), session: Session = Depen
|
|
| 290 |
saved = voice.save_draft(session.runtime, body or {}, session.uname, tenant_id=session.tenant)
|
| 291 |
row = voice.get_browser_dto(session.runtime, saved["id"])
|
| 292 |
row["audienceOptions"] = _voice_options(session)
|
| 293 |
-
_voice_item_rights(session, row, saved)
|
| 294 |
return {"voiceAgent": row}
|
| 295 |
except voice.VoiceRefusal as exc:
|
| 296 |
raise err(400, "voice_refused", str(exc))
|
|
@@ -299,36 +272,14 @@ def create_voice_agent(body: dict = Body(default=None), session: Session = Depen
|
|
| 299 |
@router.patch("/voice-agents/{voice_id}")
|
| 300 |
def patch_voice_agent(voice_id: str, body: dict = Body(default=None), session: Session = Depends(_GATE)):
|
| 301 |
try:
|
| 302 |
-
|
| 303 |
-
_require_item_edit(session, record)
|
| 304 |
-
saved = voice.patch_draft(session.runtime, voice_id, body or {}, session.uname)
|
| 305 |
row = voice.get_browser_dto(session.runtime, voice_id)
|
| 306 |
row["audienceOptions"] = _voice_options(session)
|
| 307 |
-
_voice_item_rights(session, row, saved)
|
| 308 |
return {"voiceAgent": row}
|
| 309 |
except voice.VoiceRefusal as exc:
|
| 310 |
raise err(400 if "unknown" not in str(exc) else 404, "voice_refused", str(exc))
|
| 311 |
|
| 312 |
|
| 313 |
-
@router.delete("/voice-agents/{voice_id}")
|
| 314 |
-
def delete_voice_agent(voice_id: str, session: Session = Depends(_GATE)):
|
| 315 |
-
"""Remove a local Voice definition and disable local routes without changing provider resources."""
|
| 316 |
-
def remove(doc):
|
| 317 |
-
_require_item_edit(session, doc["voice_agent"].get(voice_id))
|
| 318 |
-
if any(row.get("voice_agent_id") == voice_id and row.get("state") == "active"
|
| 319 |
-
and row.get("expires_at", 0) > time.time()
|
| 320 |
-
for row in doc["voice_outbound_lease"].values()):
|
| 321 |
-
raise err(409, "voice_running", "Wait for this Voice agent's active work to finish.")
|
| 322 |
-
del doc["voice_agent"][voice_id]
|
| 323 |
-
for route in doc["voice_number_route"].values():
|
| 324 |
-
if route.get("voice_agent_id") == voice_id:
|
| 325 |
-
route["status"] = "inactive"
|
| 326 |
-
return doc
|
| 327 |
-
|
| 328 |
-
voice._update(session.runtime, remove)
|
| 329 |
-
return {"deleted": voice_id}
|
| 330 |
-
|
| 331 |
-
|
| 332 |
@router.post("/voice-agents/{voice_id}/harness/dry-run")
|
| 333 |
def voice_dry_run(voice_id: str, body: dict = Body(default=None), session: Session = Depends(_GATE)):
|
| 334 |
body = body or {}
|
|
@@ -534,7 +485,7 @@ def _sync_schedule_or_503(tenant, defn):
|
|
| 534 |
f"Nothing was reported as armed: {exc}")
|
| 535 |
|
| 536 |
|
| 537 |
-
def _wire(defn, tenant, rt=None
|
| 538 |
"""One automation, as the client reads it. `running` is PROCESS state, never store state —
|
| 539 |
see the engine header on why a persisted 'running' is a permanent lock."""
|
| 540 |
live = engine.running(tenant, defn.get("id"))
|
|
@@ -546,7 +497,7 @@ def _wire(defn, tenant, rt=None, session=None):
|
|
| 546 |
status = {**status, "state": "running", "startedAt": live.get("startedAt"),
|
| 547 |
"step": live.get("step")}
|
| 548 |
agent_contract = engine.agent_contract_dto(rt, defn.get("id")) if rt else None
|
| 549 |
-
|
| 550 |
"id": defn.get("id"), "name": defn.get("name"), "kind": defn.get("kind"),
|
| 551 |
"config": defn.get("config") or {}, "schedule": sched, "status": status,
|
| 552 |
"runs": list(defn.get("runs") or [])[:engine.MAX_RUNS],
|
|
@@ -649,9 +600,6 @@ def _wire(defn, tenant, rt=None, session=None):
|
|
| 649 |
"This system Agent is configured at its source."}
|
| 650 |
}),
|
| 651 |
}
|
| 652 |
-
row["capabilities"] = {**row.get("capabilities", {}),
|
| 653 |
-
**(_item_rights(session, defn) if session else {"edit": False, "delete": False})}
|
| 654 |
-
return row
|
| 655 |
|
| 656 |
|
| 657 |
#: ⭐⭐ WAVE 34 · CONTRACTS C3 + C4 — WHY A ROW CANNOT BE DELETED, as a slug.
|
|
@@ -753,7 +701,7 @@ def _field_agent_rows(session):
|
|
| 753 |
# — the exact way `awaitingResults` shipped inert for a whole wave. Passing the
|
| 754 |
# synthetic DEFINITION through the same function makes them identical by
|
| 755 |
# construction; only `system` is stamped afterwards, because no stored row has it.
|
| 756 |
-
row = _wire(defn_syn, session.tenant, rt=session.runtime
|
| 757 |
row["system"] = SYSTEM_FIELD_AGENT
|
| 758 |
out.append(row)
|
| 759 |
return out
|
|
@@ -912,7 +860,7 @@ def _odoo_sync_row(session, detail=False):
|
|
| 912 |
"config": {"connector": "odoo", "every": every,
|
| 913 |
"frozen": frozen}}]},
|
| 914 |
}
|
| 915 |
-
row = _wire(defn, session.tenant, rt=session.runtime
|
| 916 |
row["system"] = SYSTEM_ODOO_SYNC
|
| 917 |
# ⛔ THE SENTENCE IS OVERRIDDEN, AND IT IS A FIX RATHER THAN A PREFERENCE. `compose_sentence`
|
| 918 |
# speaks the automation vocabulary — it builds "When <cron phrase>, run N actions" out of
|
|
@@ -1371,7 +1319,7 @@ def list_automations(session: Session = Depends(_GATE)):
|
|
| 1371 |
pass
|
| 1372 |
_STATEMENTS_SEEDED.add(session.tenant)
|
| 1373 |
defs = engine.all_definitions(session.runtime)
|
| 1374 |
-
items = [_wire(d, session.tenant, rt=session.runtime
|
| 1375 |
sorted(defs.items(), key=lambda kv: (kv[1].get("name") or "").lower())]
|
| 1376 |
# ⭐⭐ WAVE 34 · CONTRACT C3 (W34-T48) — field agents join the list as SYNTHETIC rows.
|
| 1377 |
# ⚠ MERGED AND RE-SORTED, not appended in a block at the end. R13 asks for a field agent to be
|
|
@@ -2169,7 +2117,7 @@ def agent_author_action(auto_id: str, body: dict = Body(default=None),
|
|
| 2169 |
|
| 2170 |
session.runtime.update(AGENT_ACTIONS_KEY, _set, flush="sync")
|
| 2171 |
_prune_marks(session, auto_id)
|
| 2172 |
-
return {"automation": _wire(updated, session.tenant, rt=session.runtime
|
| 2173 |
"actionId": action_id, "agent": agent_id, "notes": notes}
|
| 2174 |
|
| 2175 |
|
|
@@ -2240,7 +2188,7 @@ def get_automation(auto_id: str, session: Session = Depends(_GATE)):
|
|
| 2240 |
defn = engine.all_definitions(session.runtime).get(str(auto_id))
|
| 2241 |
if defn is None:
|
| 2242 |
raise err(404, "unknown_automation", "no automation with that id")
|
| 2243 |
-
return {"automation": _wire(defn, session.tenant, rt=session.runtime
|
| 2244 |
|
| 2245 |
|
| 2246 |
@router.post("/automations")
|
|
@@ -2265,7 +2213,7 @@ def create_automation(body: dict = Body(default=None), session: Session = Depend
|
|
| 2265 |
engine.ensure_agent_contract(session.runtime, defn.get("id"), session.uname,
|
| 2266 |
defn.get("name") or "")
|
| 2267 |
_sync_schedule_or_503(session.tenant, defn)
|
| 2268 |
-
return {"automation": _wire(defn, session.tenant, rt=session.runtime
|
| 2269 |
|
| 2270 |
|
| 2271 |
@router.patch("/automations/{auto_id}")
|
|
@@ -2296,10 +2244,7 @@ def patch_automation(auto_id: str, body: dict = Body(default=None),
|
|
| 2296 |
# now but still the guard for any other caller of that function.
|
| 2297 |
if not _odoo_connected(session):
|
| 2298 |
raise err(404, "unknown_automation", "no automation with that id")
|
| 2299 |
-
if not session.admin:
|
| 2300 |
-
raise err(403, "automation_read_only", "Only an Administrator can change the connector schedule.")
|
| 2301 |
return _patch_odoo_sync(session, body or {})
|
| 2302 |
-
_require_item_edit(session, engine.all_definitions(session.runtime).get(str(auto_id)))
|
| 2303 |
# D-75, same channel as `create` above — an EDIT is where this matters most, because the
|
| 2304 |
# person has just typed the thing that gets dropped.
|
| 2305 |
# ⛔⛔ W36-T38 / R9 — THE AGENT-OWNED WALL, AT THE DOOR, BEFORE ANY WRITE. A `disabled`
|
|
@@ -2320,7 +2265,7 @@ def patch_automation(auto_id: str, body: dict = Body(default=None),
|
|
| 2320 |
# and refuses an id nobody can see.
|
| 2321 |
_prune_marks(session, auto_id)
|
| 2322 |
_sync_schedule_or_503(session.tenant, defn)
|
| 2323 |
-
return {"automation": _wire(defn, session.tenant, rt=session.runtime
|
| 2324 |
|
| 2325 |
|
| 2326 |
def _stored_agent_or_404(session, agent_id):
|
|
@@ -2502,7 +2447,6 @@ def delete_automation(auto_id: str, session: Session = Depends(_GATE)):
|
|
| 2502 |
_sys = str(_defn.get("system") or "").strip()
|
| 2503 |
if _sys:
|
| 2504 |
raise err(409, "system_agent", engine.system_agent_refusal(_sys))
|
| 2505 |
-
_require_item_edit(session, _defn)
|
| 2506 |
engine.remove(session.runtime, auto_id)
|
| 2507 |
# R9's other half: the user MAY delete an agent-authored step, and deleting the whole
|
| 2508 |
# automation takes its annotations with it rather than stranding them in the document.
|
|
@@ -2574,7 +2518,7 @@ def toggle_automation_node(auto_id: str, node_id: str, session: Session = Depend
|
|
| 2574 |
"unknown_automation" if error == "no such automation" else "node_not_toggleable",
|
| 2575 |
error)
|
| 2576 |
_sync_schedule_or_503(session.tenant, defn)
|
| 2577 |
-
return {"automation": _wire(defn, session.tenant, rt=session.runtime
|
| 2578 |
|
| 2579 |
|
| 2580 |
@router.post("/automations/{auto_id}/hook/{token}")
|
|
|
|
| 61 |
_GATE = module_gate(MODULE)
|
| 62 |
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
def _governed_query_tool(session, database=""):
|
| 65 |
"""Adapt C4 dry-runs to B's mounted C2 Query door without owning Query authority."""
|
| 66 |
def invoke(prompt, context):
|
|
|
|
| 248 |
"""
|
| 249 |
rows = voice.list_browser_dtos(session.runtime)
|
| 250 |
options = _voice_options(session) if rows else None
|
|
|
|
| 251 |
for row in rows:
|
| 252 |
row["audienceOptions"] = options
|
|
|
|
|
|
|
| 253 |
return {"voiceAgents": rows}
|
| 254 |
|
| 255 |
|
|
|
|
| 264 |
saved = voice.save_draft(session.runtime, body or {}, session.uname, tenant_id=session.tenant)
|
| 265 |
row = voice.get_browser_dto(session.runtime, saved["id"])
|
| 266 |
row["audienceOptions"] = _voice_options(session)
|
|
|
|
| 267 |
return {"voiceAgent": row}
|
| 268 |
except voice.VoiceRefusal as exc:
|
| 269 |
raise err(400, "voice_refused", str(exc))
|
|
|
|
| 272 |
@router.patch("/voice-agents/{voice_id}")
|
| 273 |
def patch_voice_agent(voice_id: str, body: dict = Body(default=None), session: Session = Depends(_GATE)):
|
| 274 |
try:
|
| 275 |
+
voice.patch_draft(session.runtime, voice_id, body or {}, session.uname)
|
|
|
|
|
|
|
| 276 |
row = voice.get_browser_dto(session.runtime, voice_id)
|
| 277 |
row["audienceOptions"] = _voice_options(session)
|
|
|
|
| 278 |
return {"voiceAgent": row}
|
| 279 |
except voice.VoiceRefusal as exc:
|
| 280 |
raise err(400 if "unknown" not in str(exc) else 404, "voice_refused", str(exc))
|
| 281 |
|
| 282 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
@router.post("/voice-agents/{voice_id}/harness/dry-run")
|
| 284 |
def voice_dry_run(voice_id: str, body: dict = Body(default=None), session: Session = Depends(_GATE)):
|
| 285 |
body = body or {}
|
|
|
|
| 485 |
f"Nothing was reported as armed: {exc}")
|
| 486 |
|
| 487 |
|
| 488 |
+
def _wire(defn, tenant, rt=None):
|
| 489 |
"""One automation, as the client reads it. `running` is PROCESS state, never store state —
|
| 490 |
see the engine header on why a persisted 'running' is a permanent lock."""
|
| 491 |
live = engine.running(tenant, defn.get("id"))
|
|
|
|
| 497 |
status = {**status, "state": "running", "startedAt": live.get("startedAt"),
|
| 498 |
"step": live.get("step")}
|
| 499 |
agent_contract = engine.agent_contract_dto(rt, defn.get("id")) if rt else None
|
| 500 |
+
return {
|
| 501 |
"id": defn.get("id"), "name": defn.get("name"), "kind": defn.get("kind"),
|
| 502 |
"config": defn.get("config") or {}, "schedule": sched, "status": status,
|
| 503 |
"runs": list(defn.get("runs") or [])[:engine.MAX_RUNS],
|
|
|
|
| 600 |
"This system Agent is configured at its source."}
|
| 601 |
}),
|
| 602 |
}
|
|
|
|
|
|
|
|
|
|
| 603 |
|
| 604 |
|
| 605 |
#: ⭐⭐ WAVE 34 · CONTRACTS C3 + C4 — WHY A ROW CANNOT BE DELETED, as a slug.
|
|
|
|
| 701 |
# — the exact way `awaitingResults` shipped inert for a whole wave. Passing the
|
| 702 |
# synthetic DEFINITION through the same function makes them identical by
|
| 703 |
# construction; only `system` is stamped afterwards, because no stored row has it.
|
| 704 |
+
row = _wire(defn_syn, session.tenant, rt=session.runtime)
|
| 705 |
row["system"] = SYSTEM_FIELD_AGENT
|
| 706 |
out.append(row)
|
| 707 |
return out
|
|
|
|
| 860 |
"config": {"connector": "odoo", "every": every,
|
| 861 |
"frozen": frozen}}]},
|
| 862 |
}
|
| 863 |
+
row = _wire(defn, session.tenant, rt=session.runtime)
|
| 864 |
row["system"] = SYSTEM_ODOO_SYNC
|
| 865 |
# ⛔ THE SENTENCE IS OVERRIDDEN, AND IT IS A FIX RATHER THAN A PREFERENCE. `compose_sentence`
|
| 866 |
# speaks the automation vocabulary — it builds "When <cron phrase>, run N actions" out of
|
|
|
|
| 1319 |
pass
|
| 1320 |
_STATEMENTS_SEEDED.add(session.tenant)
|
| 1321 |
defs = engine.all_definitions(session.runtime)
|
| 1322 |
+
items = [_wire(d, session.tenant, rt=session.runtime) for _, d in
|
| 1323 |
sorted(defs.items(), key=lambda kv: (kv[1].get("name") or "").lower())]
|
| 1324 |
# ⭐⭐ WAVE 34 · CONTRACT C3 (W34-T48) — field agents join the list as SYNTHETIC rows.
|
| 1325 |
# ⚠ MERGED AND RE-SORTED, not appended in a block at the end. R13 asks for a field agent to be
|
|
|
|
| 2117 |
|
| 2118 |
session.runtime.update(AGENT_ACTIONS_KEY, _set, flush="sync")
|
| 2119 |
_prune_marks(session, auto_id)
|
| 2120 |
+
return {"automation": _wire(updated, session.tenant, rt=session.runtime),
|
| 2121 |
"actionId": action_id, "agent": agent_id, "notes": notes}
|
| 2122 |
|
| 2123 |
|
|
|
|
| 2188 |
defn = engine.all_definitions(session.runtime).get(str(auto_id))
|
| 2189 |
if defn is None:
|
| 2190 |
raise err(404, "unknown_automation", "no automation with that id")
|
| 2191 |
+
return {"automation": _wire(defn, session.tenant, rt=session.runtime)}
|
| 2192 |
|
| 2193 |
|
| 2194 |
@router.post("/automations")
|
|
|
|
| 2213 |
engine.ensure_agent_contract(session.runtime, defn.get("id"), session.uname,
|
| 2214 |
defn.get("name") or "")
|
| 2215 |
_sync_schedule_or_503(session.tenant, defn)
|
| 2216 |
+
return {"automation": _wire(defn, session.tenant, rt=session.runtime), "notes": _notes}
|
| 2217 |
|
| 2218 |
|
| 2219 |
@router.patch("/automations/{auto_id}")
|
|
|
|
| 2244 |
# now but still the guard for any other caller of that function.
|
| 2245 |
if not _odoo_connected(session):
|
| 2246 |
raise err(404, "unknown_automation", "no automation with that id")
|
|
|
|
|
|
|
| 2247 |
return _patch_odoo_sync(session, body or {})
|
|
|
|
| 2248 |
# D-75, same channel as `create` above — an EDIT is where this matters most, because the
|
| 2249 |
# person has just typed the thing that gets dropped.
|
| 2250 |
# ⛔⛔ W36-T38 / R9 — THE AGENT-OWNED WALL, AT THE DOOR, BEFORE ANY WRITE. A `disabled`
|
|
|
|
| 2265 |
# and refuses an id nobody can see.
|
| 2266 |
_prune_marks(session, auto_id)
|
| 2267 |
_sync_schedule_or_503(session.tenant, defn)
|
| 2268 |
+
return {"automation": _wire(defn, session.tenant, rt=session.runtime), "notes": _notes}
|
| 2269 |
|
| 2270 |
|
| 2271 |
def _stored_agent_or_404(session, agent_id):
|
|
|
|
| 2447 |
_sys = str(_defn.get("system") or "").strip()
|
| 2448 |
if _sys:
|
| 2449 |
raise err(409, "system_agent", engine.system_agent_refusal(_sys))
|
|
|
|
| 2450 |
engine.remove(session.runtime, auto_id)
|
| 2451 |
# R9's other half: the user MAY delete an agent-authored step, and deleting the whole
|
| 2452 |
# automation takes its annotations with it rather than stranding them in the document.
|
|
|
|
| 2518 |
"unknown_automation" if error == "no such automation" else "node_not_toggleable",
|
| 2519 |
error)
|
| 2520 |
_sync_schedule_or_503(session.tenant, defn)
|
| 2521 |
+
return {"automation": _wire(defn, session.tenant, rt=session.runtime)}
|
| 2522 |
|
| 2523 |
|
| 2524 |
@router.post("/automations/{auto_id}/hook/{token}")
|
api/routes_external.py
CHANGED
|
@@ -156,8 +156,10 @@ class _PreviewRuntime:
|
|
| 156 |
def _load(self, name):
|
| 157 |
key = str(name)
|
| 158 |
if key not in self._docs:
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
| 161 |
value = copy.deepcopy(value)
|
| 162 |
self._initial[key] = copy.deepcopy(value)
|
| 163 |
self._docs[key] = value
|
|
@@ -172,9 +174,6 @@ class _PreviewRuntime:
|
|
| 172 |
def get(self, name, *args, **kwargs):
|
| 173 |
return copy.deepcopy(self._load(name))
|
| 174 |
|
| 175 |
-
def _read_strict(self, name):
|
| 176 |
-
return self.get(name)
|
| 177 |
-
|
| 178 |
def get_projection(self, name, drop=()):
|
| 179 |
value = self.get(name)
|
| 180 |
if isinstance(value, dict):
|
|
@@ -3121,12 +3120,12 @@ def _bucket_revision(st, key, fallback):
|
|
| 3121 |
return {"rev": None, "token": _json_digest(fallback)}
|
| 3122 |
|
| 3123 |
|
| 3124 |
-
def _database_value_plan(session, database, record_id, values, fields
|
| 3125 |
"""Apply the grid's field/value vocabulary without calling its event side effects."""
|
| 3126 |
from core import grid_events, user_tables
|
| 3127 |
import aios_grid
|
| 3128 |
|
| 3129 |
-
if not isinstance(values, dict) or
|
| 3130 |
raise err(400, "tool_arguments_invalid", "Record values must be a non-empty object.")
|
| 3131 |
field_by_key = {str(field.get("key")): field for field in fields if isinstance(field, dict)}
|
| 3132 |
unknown = sorted(str(key) for key in values if str(key) not in field_by_key)
|
|
@@ -3134,7 +3133,8 @@ def _database_value_plan(session, database, record_id, values, fields, *, apply_
|
|
| 3134 |
raise err(403, "field_unavailable",
|
| 3135 |
"Every changed field must be readable and editable in this database.")
|
| 3136 |
ctx = _view_context(session, database, {"pid": record_id})
|
| 3137 |
-
|
|
|
|
| 3138 |
key = str(key)
|
| 3139 |
definition = field_by_key[key]
|
| 3140 |
if key in (ctx.hidden_keys or frozenset()) or not grid_events._may_edit_field_value(
|
|
@@ -3143,26 +3143,6 @@ def _database_value_plan(session, database, record_id, values, fields, *, apply_
|
|
| 3143 |
"Every changed field must be readable and editable in this database.")
|
| 3144 |
if user_tables.is_computed_cell(definition) or definition.get("type") == "automation":
|
| 3145 |
raise err(403, "computed_field", "A computed or automation field is read only.")
|
| 3146 |
-
if apply_defaults:
|
| 3147 |
-
editable = [definition for key, definition in field_by_key.items()
|
| 3148 |
-
if key not in (ctx.hidden_keys or frozenset())
|
| 3149 |
-
and grid_events._may_edit_field_value(ctx, key, definition)
|
| 3150 |
-
and not user_tables.is_computed_cell(definition)
|
| 3151 |
-
and definition.get("type") != "automation"]
|
| 3152 |
-
try:
|
| 3153 |
-
expanded = user_tables._new_row_values(editable, values)
|
| 3154 |
-
except ValueError as exc:
|
| 3155 |
-
raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300]) from exc
|
| 3156 |
-
if expanded is None:
|
| 3157 |
-
raise err(400, "bad_value", "A field default is not valid for its field.")
|
| 3158 |
-
# Supplied arrays and typed cells must reach their normalizers unchanged.
|
| 3159 |
-
values = {**expanded, **values}
|
| 3160 |
-
if not values:
|
| 3161 |
-
raise err(400, "tool_arguments_invalid", "Record values must be a non-empty object.")
|
| 3162 |
-
planned = {}
|
| 3163 |
-
for key, raw in values.items():
|
| 3164 |
-
key = str(key)
|
| 3165 |
-
definition = field_by_key[key]
|
| 3166 |
why = user_tables.cell_type_refusal(definition, raw)
|
| 3167 |
if why:
|
| 3168 |
raise err(400, "bad_value", why)
|
|
@@ -3170,15 +3150,8 @@ def _database_value_plan(session, database, record_id, values, fields, *, apply_
|
|
| 3170 |
bag = definition.get("link") if isinstance(definition.get("link"), dict) else {}
|
| 3171 |
if bag.get("on") or bag.get("inverse"):
|
| 3172 |
raise err(403, "computed_field", "A derived link field is read only.")
|
| 3173 |
-
|
| 3174 |
-
|
| 3175 |
-
target = _external_read_scope(session, target_database)
|
| 3176 |
-
target_fields = target["fields"]
|
| 3177 |
-
available = {str(row["pid"]): row for row in target["records"]}
|
| 3178 |
-
if ("selectionFilter" in bag and user_tables.clean_link_selection_filter(
|
| 3179 |
-
bag["selectionFilter"], target_fields) is None):
|
| 3180 |
-
raise err(400, "link_selection_refused",
|
| 3181 |
-
"The link selection condition is invalid or names an unavailable field.")
|
| 3182 |
raw_ids = raw if isinstance(raw, (list, tuple, set)) else str(raw or "").split(",")
|
| 3183 |
selected = []
|
| 3184 |
for item in raw_ids:
|
|
@@ -3187,9 +3160,6 @@ def _database_value_plan(session, database, record_id, values, fields, *, apply_
|
|
| 3187 |
continue
|
| 3188 |
if candidate not in available or len(selected) >= user_tables.LINK_MAX_IDS:
|
| 3189 |
raise err(400, "bad_value", "A linked record is unavailable.")
|
| 3190 |
-
if not user_tables.link_selection_permits(definition, available[candidate], target_fields):
|
| 3191 |
-
raise err(400, "link_selection_refused",
|
| 3192 |
-
"That record does not match the link selection condition. Choose an available record.")
|
| 3193 |
selected.append(candidate)
|
| 3194 |
if bag.get("single"):
|
| 3195 |
break
|
|
@@ -3262,8 +3232,9 @@ def _plan_database_write(session, args):
|
|
| 3262 |
rows = table.get("rows") or {}
|
| 3263 |
if action == "record_create":
|
| 3264 |
raw_values = args.get("values")
|
| 3265 |
-
|
| 3266 |
-
|
|
|
|
| 3267 |
record_id = str(max((int(key) for key in rows if str(key).isdigit()), default=0) + 1)
|
| 3268 |
before, after = None, values
|
| 3269 |
else:
|
|
@@ -3292,8 +3263,16 @@ def _plan_database_write(session, args):
|
|
| 3292 |
else:
|
| 3293 |
try:
|
| 3294 |
if action == "record_create":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3295 |
user_tables.allocate_autonumbers(target, after)
|
| 3296 |
user_tables._stamp_row_creation(target, record_id)
|
|
|
|
|
|
|
| 3297 |
except ValueError as exc:
|
| 3298 |
raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300])
|
| 3299 |
target.setdefault("rows", {})[record_id] = copy.deepcopy(after)
|
|
@@ -4045,8 +4024,6 @@ def _preview_external_write(session, name, arguments, *, issue_token=True, execu
|
|
| 4045 |
response["purpose"] = purpose
|
| 4046 |
if name == "views" and normalised.get("action") == "share":
|
| 4047 |
response.update({key: copy.deepcopy(result[key]) for key in ("view", "audience")})
|
| 4048 |
-
if name == "apps" and normalised.get("action") == "catalog_build":
|
| 4049 |
-
response.update({key: copy.deepcopy(result[key]) for key in _CATALOG_BUILD_RESULT_FIELDS})
|
| 4050 |
if payload["strong"]:
|
| 4051 |
response["confirmation_phrase"] = _CONFIRMATION_PHRASE
|
| 4052 |
if issue_token:
|
|
@@ -4288,7 +4265,6 @@ def _confirmation_status(session, operation_id, status, result=None):
|
|
| 4288 |
def _committed_build_evidence(session, writer, arguments, *, build_kind=None):
|
| 4289 |
"""Resolve identities from committed documents and this writer's native inserts."""
|
| 4290 |
import application_registry
|
| 4291 |
-
import catalog_store
|
| 4292 |
import automation_engine
|
| 4293 |
import intelligence_store as files
|
| 4294 |
import wiki_log
|
|
@@ -4327,11 +4303,6 @@ def _committed_build_evidence(session, writer, arguments, *, build_kind=None):
|
|
| 4327 |
for identity in before.keys() | after.keys():
|
| 4328 |
if before.get(identity) != after.get(identity):
|
| 4329 |
add("schedule", identity)
|
| 4330 |
-
elif key == catalog_store.STORE_KEY:
|
| 4331 |
-
before, after = before.get("catalogs") or {}, after.get("catalogs") or {}
|
| 4332 |
-
for identity in before.keys() | after.keys():
|
| 4333 |
-
if before.get(identity) != after.get(identity):
|
| 4334 |
-
add("app", (after.get(identity) or before.get(identity) or {}).get("appId"))
|
| 4335 |
elif key in (application_registry._KEY, automation_engine.STORE_KEY):
|
| 4336 |
kind = "app" if key == application_registry._KEY else "automation"
|
| 4337 |
if kind == "app":
|
|
@@ -4553,7 +4524,6 @@ MCP_RESULT_CODES = {
|
|
| 4553 |
code: reason for reason, codes in _MCP_CODE_GROUPS for code in codes.split()
|
| 4554 |
}
|
| 4555 |
MCP_RESULT_CODES.update({
|
| 4556 |
-
"link_selection_refused": "Choose a readable linked record that matches the field's selection condition.",
|
| 4557 |
"app_rule": "Correct the App rule named in the refusal before saving it.",
|
| 4558 |
"audience_not_allowed": "A person must choose sharing with everyone on screen.",
|
| 4559 |
"not_owner": "You cannot administer this item's audience.",
|
|
@@ -4685,7 +4655,7 @@ _MCP_RESULT_IDENTIFIERS = frozenset({
|
|
| 4685 |
"resourceUri", "deepLink", "pdfLink", "src", "websiteUrl", "fileId", "link", "href",
|
| 4686 |
"id", "ids", "operation_id", "key", "keys", "pid", "pids", "database", "databases", "sourceDatabase",
|
| 4687 |
"compatibleDatabases", "field", "fields", "field_key", "colId", "metric_key", "groupBy",
|
| 4688 |
-
"workbook_id", "worksheet", "tab", "view_id", "app_id", "
|
| 4689 |
"path", "paths", "address", "addresses", "range", "cursor", "next_cursor", "token",
|
| 4690 |
"source_version", "code", "tool", "action", "person", "agent", "owner", "author", "from", "to",
|
| 4691 |
"username", "tenant", "createdBy", "updatedBy", "by", "byName", "reads", "approvers", "tags", "updated",
|
|
@@ -5196,7 +5166,9 @@ def _mcp_guide(session: Session, group=None) -> str:
|
|
| 5196 |
"Call a group with action and arguments. Each action keeps its own read or write rules.",
|
| 5197 |
"Every tool accepts optional intent beside action and arguments. Every write requires it, including "
|
| 5198 |
"previews, confirm_change, requests.send and intelligence.create_wiki. Use 1 to 500 characters. "
|
| 5199 |
-
'Example: {"intent":"Prepare the weekly sales review"}. Intent is stripped before dispatch.'
|
|
|
|
|
|
|
| 5200 |
"Each tool call records one external.query event with tool, action, outcome and argument keys and types. "
|
| 5201 |
"Large shapes continue in argument_shape_1 and later numbered fields. Unknown keys are redacted. "
|
| 5202 |
"Argument values are never recorded. Intent is retained only when sent, with credential patterns redacted. "
|
|
@@ -5208,7 +5180,7 @@ def _mcp_guide(session: Session, group=None) -> str:
|
|
| 5208 |
"characters, and one or more distinct tags below. intelligence.create_wiki needs the same about "
|
| 5209 |
"and still publishes directly. The tool supplies the build kind. Confirmation uses the saved about.",
|
| 5210 |
"Build tags: " + ", ".join(external_tools.BUILD_TAGS) + ".",
|
| 5211 |
-
"For a previewed build, put optional purpose beside action and arguments
|
| 5212 |
"Use one line of 1 to 240 characters without control characters or long dashes. "
|
| 5213 |
"Confirmation uses that saved purpose; do not send a new purpose to confirm_change.",
|
| 5214 |
"Previous tool names remain callable for one release, but are absent from tools/list.", ""]
|
|
@@ -5223,6 +5195,7 @@ def _mcp_guide(session: Session, group=None) -> str:
|
|
| 5223 |
from tool_groups.data import query_guide
|
| 5224 |
lines += [query_guide(rows), ""]
|
| 5225 |
states = {row["action"]: row for row in capabilities if row["group"] == group}
|
|
|
|
| 5226 |
for action, entry in selected["actions"].items():
|
| 5227 |
lines += ["### " + action,
|
| 5228 |
"State: " + states[action]["state"] + "."
|
|
@@ -5234,7 +5207,11 @@ def _mcp_guide(session: Session, group=None) -> str:
|
|
| 5234 |
lines.append("Previous name: `" + entry["legacy_name"] + "`.")
|
| 5235 |
schema = copy.deepcopy(entry["schema"])
|
| 5236 |
schema.get("properties", {}).pop("about", None)
|
|
|
|
|
|
|
| 5237 |
lines += ["```json", json.dumps(_mcp_schema_copy(schema), ensure_ascii=True, indent=2), "```", ""]
|
|
|
|
|
|
|
| 5238 |
return _MCPGuideText("\n".join(lines) + "\n")
|
| 5239 |
lines += ["## Connected AI clients", "",
|
| 5240 |
"Client names and who connected them in this workspace. No entries means none are connected.",
|
|
@@ -5365,13 +5342,14 @@ def _handle_mcp(req, session: Session, base_url: str = ""):
|
|
| 5365 |
return reply
|
| 5366 |
params = req.get("params")
|
| 5367 |
params = params if isinstance(params, dict) else {}
|
| 5368 |
-
|
| 5369 |
-
|
|
|
|
| 5370 |
try:
|
| 5371 |
with external_activity.capture_call(session, tool) as call:
|
| 5372 |
if tool == limitation_tool:
|
| 5373 |
external_activity.note_action(limitation_action)
|
| 5374 |
-
external_activity.note_arguments(
|
| 5375 |
metadata = params.get("_meta")
|
| 5376 |
call["question"] = metadata.get("loopable/question") if isinstance(metadata, dict) else None
|
| 5377 |
reply = _dispatch_mcp(req, session, base_url)
|
|
@@ -5451,6 +5429,23 @@ def _mcp_call_intent(arguments):
|
|
| 5451 |
return value
|
| 5452 |
|
| 5453 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5454 |
def _mcp_requires_intent(name, arguments):
|
| 5455 |
"""Classify declared writes before argument validation can mask the intent requirement."""
|
| 5456 |
if name == "confirm_change":
|
|
@@ -5525,7 +5520,7 @@ def _dispatch_mcp(req, session: Session, base_url: str = ""):
|
|
| 5525 |
return {"jsonrpc": "2.0", "id": rid, "result": {"contents": [resource]}}
|
| 5526 |
if method != "tools/call":
|
| 5527 |
return protocol_error(rid, -32601, "The requested MCP method was not found.")
|
| 5528 |
-
arguments = params.get("arguments", {})
|
| 5529 |
intent = _mcp_call_intent(arguments)
|
| 5530 |
if intent is None and _mcp_requires_intent(name, arguments):
|
| 5531 |
raise err(400, "call_intent_required", "Send intent explaining why you are making this write.",
|
|
@@ -5548,10 +5543,6 @@ def _dispatch_mcp(req, session: Session, base_url: str = ""):
|
|
| 5548 |
purpose = _build_purpose(arguments.pop("purpose"))
|
| 5549 |
if "about" in metadata_keys:
|
| 5550 |
about = arguments.pop("about")
|
| 5551 |
-
if (name in tool_groups.groups() and isinstance(arguments, dict)
|
| 5552 |
-
and isinstance(arguments.get("arguments"), dict)
|
| 5553 |
-
and {"about", "purpose", "intent"} & arguments["arguments"].keys()):
|
| 5554 |
-
raise err(400, "tool_arguments_invalid", "Send intent and build metadata beside action and arguments.")
|
| 5555 |
_assert_tool_query_filter_bounds(name, arguments)
|
| 5556 |
resolved = tool_groups.resolve(name, arguments)
|
| 5557 |
confirm = True
|
|
|
|
| 156 |
def _load(self, name):
|
| 157 |
key = str(name)
|
| 158 |
if key not in self._docs:
|
| 159 |
+
try:
|
| 160 |
+
value = self._real.get(key, fresh=True)
|
| 161 |
+
except TypeError:
|
| 162 |
+
value = self._real.get(key)
|
| 163 |
value = copy.deepcopy(value)
|
| 164 |
self._initial[key] = copy.deepcopy(value)
|
| 165 |
self._docs[key] = value
|
|
|
|
| 174 |
def get(self, name, *args, **kwargs):
|
| 175 |
return copy.deepcopy(self._load(name))
|
| 176 |
|
|
|
|
|
|
|
|
|
|
| 177 |
def get_projection(self, name, drop=()):
|
| 178 |
value = self.get(name)
|
| 179 |
if isinstance(value, dict):
|
|
|
|
| 3120 |
return {"rev": None, "token": _json_digest(fallback)}
|
| 3121 |
|
| 3122 |
|
| 3123 |
+
def _database_value_plan(session, database, record_id, values, fields):
|
| 3124 |
"""Apply the grid's field/value vocabulary without calling its event side effects."""
|
| 3125 |
from core import grid_events, user_tables
|
| 3126 |
import aios_grid
|
| 3127 |
|
| 3128 |
+
if not isinstance(values, dict) or not values:
|
| 3129 |
raise err(400, "tool_arguments_invalid", "Record values must be a non-empty object.")
|
| 3130 |
field_by_key = {str(field.get("key")): field for field in fields if isinstance(field, dict)}
|
| 3131 |
unknown = sorted(str(key) for key in values if str(key) not in field_by_key)
|
|
|
|
| 3133 |
raise err(403, "field_unavailable",
|
| 3134 |
"Every changed field must be readable and editable in this database.")
|
| 3135 |
ctx = _view_context(session, database, {"pid": record_id})
|
| 3136 |
+
planned = {}
|
| 3137 |
+
for key, raw in values.items():
|
| 3138 |
key = str(key)
|
| 3139 |
definition = field_by_key[key]
|
| 3140 |
if key in (ctx.hidden_keys or frozenset()) or not grid_events._may_edit_field_value(
|
|
|
|
| 3143 |
"Every changed field must be readable and editable in this database.")
|
| 3144 |
if user_tables.is_computed_cell(definition) or definition.get("type") == "automation":
|
| 3145 |
raise err(403, "computed_field", "A computed or automation field is read only.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3146 |
why = user_tables.cell_type_refusal(definition, raw)
|
| 3147 |
if why:
|
| 3148 |
raise err(400, "bad_value", why)
|
|
|
|
| 3150 |
bag = definition.get("link") if isinstance(definition.get("link"), dict) else {}
|
| 3151 |
if bag.get("on") or bag.get("inverse"):
|
| 3152 |
raise err(403, "computed_field", "A derived link field is read only.")
|
| 3153 |
+
target = user_tables.get(str(bag.get("table") or ""), st=session.runtime) or {}
|
| 3154 |
+
available = set((target.get("rows") or {}).keys())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3155 |
raw_ids = raw if isinstance(raw, (list, tuple, set)) else str(raw or "").split(",")
|
| 3156 |
selected = []
|
| 3157 |
for item in raw_ids:
|
|
|
|
| 3160 |
continue
|
| 3161 |
if candidate not in available or len(selected) >= user_tables.LINK_MAX_IDS:
|
| 3162 |
raise err(400, "bad_value", "A linked record is unavailable.")
|
|
|
|
|
|
|
|
|
|
| 3163 |
selected.append(candidate)
|
| 3164 |
if bag.get("single"):
|
| 3165 |
break
|
|
|
|
| 3232 |
rows = table.get("rows") or {}
|
| 3233 |
if action == "record_create":
|
| 3234 |
raw_values = args.get("values")
|
| 3235 |
+
# An empty object is a valid create when field defaults fill it (checked below).
|
| 3236 |
+
values = ({} if isinstance(raw_values, dict) and not raw_values else
|
| 3237 |
+
_database_value_plan(session, database, None, raw_values, g["fields"]))
|
| 3238 |
record_id = str(max((int(key) for key in rows if str(key).isdigit()), default=0) + 1)
|
| 3239 |
before, after = None, values
|
| 3240 |
else:
|
|
|
|
| 3263 |
else:
|
| 3264 |
try:
|
| 3265 |
if action == "record_create":
|
| 3266 |
+
# The grid's core insert rules: defaults, server-owned numbers, creation order.
|
| 3267 |
+
after = user_tables._new_row_values(target.get("fields") or [], after)
|
| 3268 |
+
if after is None:
|
| 3269 |
+
raise err(400, "bad_value", "A field default is not valid for its field.")
|
| 3270 |
+
if not after:
|
| 3271 |
+
raise err(400, "tool_arguments_invalid", "Record values must be a non-empty object.")
|
| 3272 |
user_tables.allocate_autonumbers(target, after)
|
| 3273 |
user_tables._stamp_row_creation(target, record_id)
|
| 3274 |
+
user_tables._validate_link_selection_values(
|
| 3275 |
+
target.get("fields") or [], values, bucket_after)
|
| 3276 |
except ValueError as exc:
|
| 3277 |
raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300])
|
| 3278 |
target.setdefault("rows", {})[record_id] = copy.deepcopy(after)
|
|
|
|
| 4024 |
response["purpose"] = purpose
|
| 4025 |
if name == "views" and normalised.get("action") == "share":
|
| 4026 |
response.update({key: copy.deepcopy(result[key]) for key in ("view", "audience")})
|
|
|
|
|
|
|
| 4027 |
if payload["strong"]:
|
| 4028 |
response["confirmation_phrase"] = _CONFIRMATION_PHRASE
|
| 4029 |
if issue_token:
|
|
|
|
| 4265 |
def _committed_build_evidence(session, writer, arguments, *, build_kind=None):
|
| 4266 |
"""Resolve identities from committed documents and this writer's native inserts."""
|
| 4267 |
import application_registry
|
|
|
|
| 4268 |
import automation_engine
|
| 4269 |
import intelligence_store as files
|
| 4270 |
import wiki_log
|
|
|
|
| 4303 |
for identity in before.keys() | after.keys():
|
| 4304 |
if before.get(identity) != after.get(identity):
|
| 4305 |
add("schedule", identity)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4306 |
elif key in (application_registry._KEY, automation_engine.STORE_KEY):
|
| 4307 |
kind = "app" if key == application_registry._KEY else "automation"
|
| 4308 |
if kind == "app":
|
|
|
|
| 4524 |
code: reason for reason, codes in _MCP_CODE_GROUPS for code in codes.split()
|
| 4525 |
}
|
| 4526 |
MCP_RESULT_CODES.update({
|
|
|
|
| 4527 |
"app_rule": "Correct the App rule named in the refusal before saving it.",
|
| 4528 |
"audience_not_allowed": "A person must choose sharing with everyone on screen.",
|
| 4529 |
"not_owner": "You cannot administer this item's audience.",
|
|
|
|
| 4655 |
"resourceUri", "deepLink", "pdfLink", "src", "websiteUrl", "fileId", "link", "href",
|
| 4656 |
"id", "ids", "operation_id", "key", "keys", "pid", "pids", "database", "databases", "sourceDatabase",
|
| 4657 |
"compatibleDatabases", "field", "fields", "field_key", "colId", "metric_key", "groupBy",
|
| 4658 |
+
"workbook_id", "worksheet", "tab", "view_id", "app_id", "chart_id", "record_id", "contextId",
|
| 4659 |
"path", "paths", "address", "addresses", "range", "cursor", "next_cursor", "token",
|
| 4660 |
"source_version", "code", "tool", "action", "person", "agent", "owner", "author", "from", "to",
|
| 4661 |
"username", "tenant", "createdBy", "updatedBy", "by", "byName", "reads", "approvers", "tags", "updated",
|
|
|
|
| 5166 |
"Call a group with action and arguments. Each action keeps its own read or write rules.",
|
| 5167 |
"Every tool accepts optional intent beside action and arguments. Every write requires it, including "
|
| 5168 |
"previews, confirm_change, requests.send and intelligence.create_wiki. Use 1 to 500 characters. "
|
| 5169 |
+
'Example: {"intent":"Prepare the weekly sales review"}. Intent is stripped before dispatch. '
|
| 5170 |
+
"A client that cannot send keys beside action and arguments may put intent, about and purpose "
|
| 5171 |
+
"inside arguments. The value beside action and arguments wins.",
|
| 5172 |
"Each tool call records one external.query event with tool, action, outcome and argument keys and types. "
|
| 5173 |
"Large shapes continue in argument_shape_1 and later numbered fields. Unknown keys are redacted. "
|
| 5174 |
"Argument values are never recorded. Intent is retained only when sent, with credential patterns redacted. "
|
|
|
|
| 5180 |
"characters, and one or more distinct tags below. intelligence.create_wiki needs the same about "
|
| 5181 |
"and still publishes directly. The tool supplies the build kind. Confirmation uses the saved about.",
|
| 5182 |
"Build tags: " + ", ".join(external_tools.BUILD_TAGS) + ".",
|
| 5183 |
+
"For a previewed build, put optional purpose beside action and arguments. "
|
| 5184 |
"Use one line of 1 to 240 characters without control characters or long dashes. "
|
| 5185 |
"Confirmation uses that saved purpose; do not send a new purpose to confirm_change.",
|
| 5186 |
"Previous tool names remain callable for one release, but are absent from tools/list.", ""]
|
|
|
|
| 5195 |
from tool_groups.data import query_guide
|
| 5196 |
lines += [query_guide(rows), ""]
|
| 5197 |
states = {row["action"]: row for row in capabilities if row["group"] == group}
|
| 5198 |
+
uses_filter_node = False
|
| 5199 |
for action, entry in selected["actions"].items():
|
| 5200 |
lines += ["### " + action,
|
| 5201 |
"State: " + states[action]["state"] + "."
|
|
|
|
| 5207 |
lines.append("Previous name: `" + entry["legacy_name"] + "`.")
|
| 5208 |
schema = copy.deepcopy(entry["schema"])
|
| 5209 |
schema.get("properties", {}).pop("about", None)
|
| 5210 |
+
schema, collapsed = external_tools.guide_schema(schema)
|
| 5211 |
+
uses_filter_node = uses_filter_node or collapsed
|
| 5212 |
lines += ["```json", json.dumps(_mcp_schema_copy(schema), ensure_ascii=True, indent=2), "```", ""]
|
| 5213 |
+
if uses_filter_node:
|
| 5214 |
+
lines += [external_tools.filter_node_guide(), ""]
|
| 5215 |
return _MCPGuideText("\n".join(lines) + "\n")
|
| 5216 |
lines += ["## Connected AI clients", "",
|
| 5217 |
"Client names and who connected them in this workspace. No entries means none are connected.",
|
|
|
|
| 5342 |
return reply
|
| 5343 |
params = req.get("params")
|
| 5344 |
params = params if isinstance(params, dict) else {}
|
| 5345 |
+
arguments = _mcp_hoist_call_metadata(params.get("name"), params.get("arguments", {}))
|
| 5346 |
+
tool, schema = _mcp_audit_schema(params.get("name"), arguments)
|
| 5347 |
+
limitation_tool, limitation_action = _mcp_limitation_address(tool, arguments)
|
| 5348 |
try:
|
| 5349 |
with external_activity.capture_call(session, tool) as call:
|
| 5350 |
if tool == limitation_tool:
|
| 5351 |
external_activity.note_action(limitation_action)
|
| 5352 |
+
external_activity.note_arguments(arguments, schema)
|
| 5353 |
metadata = params.get("_meta")
|
| 5354 |
call["question"] = metadata.get("loopable/question") if isinstance(metadata, dict) else None
|
| 5355 |
reply = _dispatch_mcp(req, session, base_url)
|
|
|
|
| 5429 |
return value
|
| 5430 |
|
| 5431 |
|
| 5432 |
+
def _mcp_hoist_call_metadata(name, arguments):
|
| 5433 |
+
"""Return group call arguments with intent, about and purpose lifted out of the inner arguments."""
|
| 5434 |
+
import tool_groups
|
| 5435 |
+
keys = ("intent", "about", "purpose")
|
| 5436 |
+
if (not isinstance(name, str) or name not in tool_groups.groups() or not isinstance(arguments, dict)
|
| 5437 |
+
or not isinstance(arguments.get("arguments"), dict)
|
| 5438 |
+
or not any(key in arguments["arguments"] for key in keys)):
|
| 5439 |
+
return arguments
|
| 5440 |
+
inner = arguments["arguments"]
|
| 5441 |
+
hoisted = {**arguments, "arguments": {key: value for key, value in inner.items() if key not in keys}}
|
| 5442 |
+
# The value beside action and arguments wins over the nested copy.
|
| 5443 |
+
for key in keys:
|
| 5444 |
+
if key in inner and key not in arguments:
|
| 5445 |
+
hoisted[key] = inner[key]
|
| 5446 |
+
return hoisted
|
| 5447 |
+
|
| 5448 |
+
|
| 5449 |
def _mcp_requires_intent(name, arguments):
|
| 5450 |
"""Classify declared writes before argument validation can mask the intent requirement."""
|
| 5451 |
if name == "confirm_change":
|
|
|
|
| 5520 |
return {"jsonrpc": "2.0", "id": rid, "result": {"contents": [resource]}}
|
| 5521 |
if method != "tools/call":
|
| 5522 |
return protocol_error(rid, -32601, "The requested MCP method was not found.")
|
| 5523 |
+
arguments = _mcp_hoist_call_metadata(name, params.get("arguments", {}))
|
| 5524 |
intent = _mcp_call_intent(arguments)
|
| 5525 |
if intent is None and _mcp_requires_intent(name, arguments):
|
| 5526 |
raise err(400, "call_intent_required", "Send intent explaining why you are making this write.",
|
|
|
|
| 5543 |
purpose = _build_purpose(arguments.pop("purpose"))
|
| 5544 |
if "about" in metadata_keys:
|
| 5545 |
about = arguments.pop("about")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5546 |
_assert_tool_query_filter_bounds(name, arguments)
|
| 5547 |
resolved = tool_groups.resolve(name, arguments)
|
| 5548 |
confirm = True
|
api/routes_geo.py
CHANGED
|
@@ -327,40 +327,10 @@ def _zone_context(session, raw_table_key):
|
|
| 327 |
return table_key, fields, set(grid.get("pids") or ()), list(grid.get("rows_src") or ())
|
| 328 |
|
| 329 |
|
| 330 |
-
def
|
| 331 |
-
"""Authorize an explicit App and its bound database before reading its Zones."""
|
| 332 |
-
if application is None:
|
| 333 |
-
return None
|
| 334 |
-
if not isinstance(application, str) or not application.strip() or len(application) > 120:
|
| 335 |
-
raise err(400, "invalid_route_application", "choose a Routing App id")
|
| 336 |
-
application = application.strip()
|
| 337 |
-
table_key = str(table_key or "").strip()
|
| 338 |
-
import application_registry as registry
|
| 339 |
-
from core import route_system
|
| 340 |
-
try:
|
| 341 |
-
doc = registry._read_strict(session.runtime, registry._KEY) or {}
|
| 342 |
-
if not isinstance(doc, dict) or not isinstance(doc.get("applications", {}), dict):
|
| 343 |
-
raise ValueError("invalid Application registry")
|
| 344 |
-
except Exception:
|
| 345 |
-
raise err(503, "application_store_unavailable", "the Application registry is unavailable")
|
| 346 |
-
app = doc.get("applications", {}).get(application)
|
| 347 |
-
if app is None and session.admin and not write and route_system.list_zones(
|
| 348 |
-
session.runtime, table_key=table_key, application=application):
|
| 349 |
-
return application
|
| 350 |
-
if not isinstance(app, dict) or app.get("tenant") != session.tenant:
|
| 351 |
-
raise err(404, "route_application_not_found", "that Routing App does not exist")
|
| 352 |
-
if not registry.may_read(app, session.uname, is_admin=session.admin):
|
| 353 |
-
raise err(403, "route_application_forbidden", "your account cannot open this Routing App")
|
| 354 |
-
source = app.get("sourceDatabase")
|
| 355 |
-
if (source != table_key if source else table_key not in (app.get("compatibleDatabases") or ())):
|
| 356 |
-
raise err(409, "route_application_source", "this App does not use the selected database")
|
| 357 |
-
return application
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
def _zone_subject(session, table_key, zone_id, application=None):
|
| 361 |
from core import route_system
|
| 362 |
zone = next((item for item in route_system.list_zones(
|
| 363 |
-
session.runtime, table_key=table_key
|
| 364 |
if str(item.get("id") or "") == str(zone_id)), None)
|
| 365 |
if not isinstance(zone, dict):
|
| 366 |
raise err(404, "unknown_zone", "no Zone with that id")
|
|
@@ -603,13 +573,11 @@ def geo_providers(session: Session = Depends(require_session)):
|
|
| 603 |
|
| 604 |
|
| 605 |
@router.get("/geo/zones")
|
| 606 |
-
def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(require_session)
|
| 607 |
-
application: str = None):
|
| 608 |
"""The canonical table-scoped Zone DTOs a Map may draw or filter by."""
|
| 609 |
from core import route_system
|
| 610 |
-
application = _zone_application(session, tableKey, application)
|
| 611 |
table_key, _fields, pids, rows = _zone_context(session, tableKey)
|
| 612 |
-
zones = route_system.list_zones(session.runtime, rows, table_key=table_key
|
| 613 |
# A hidden Zone remains recoverable to its creator/admin, but cannot become visible through a
|
| 614 |
# second table simply because row ids happen to collide there.
|
| 615 |
visible = [zone for zone in zones if zone.get("visible", True)
|
|
@@ -620,14 +588,10 @@ def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(requ
|
|
| 620 |
|
| 621 |
|
| 622 |
@router.post("/geo/zones")
|
| 623 |
-
def geo_zone_create(body: dict = Body(default=None), session: Session = Depends(require_session)
|
| 624 |
-
application: str = None):
|
| 625 |
"""Persist one Zone in the existing table-scoped Zone store and field/filter contract."""
|
| 626 |
from core import route_system
|
| 627 |
body = body if isinstance(body, dict) else {}
|
| 628 |
-
from routes_customers import _route_application_body
|
| 629 |
-
_route_application_body(body, application)
|
| 630 |
-
application = _zone_application(session, body.get("tableKey"), application, write=True)
|
| 631 |
table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey"))
|
| 632 |
try:
|
| 633 |
if any(key in body for key in ("memberships", "memberPids", "member_pids")):
|
|
@@ -637,7 +601,7 @@ def geo_zone_create(body: dict = Body(default=None), session: Session = Depends(
|
|
| 637 |
"geometryGeoJson": body.get("geometryGeoJson"), "zipCodes": body.get("zipCodes"),
|
| 638 |
"visible": body.get("visible"), "geographicField": body.get("geographicField")
|
| 639 |
}, rows=rows, tenant_id=session.tenant, created_by=session.uname,
|
| 640 |
-
table_key=table_key
|
| 641 |
if zone is None:
|
| 642 |
raise ValueError("the Zone does not match this database's fields and records")
|
| 643 |
except ValueError as exc:
|
|
@@ -649,15 +613,12 @@ def geo_zone_create(body: dict = Body(default=None), session: Session = Depends(
|
|
| 649 |
|
| 650 |
@router.patch("/geo/zones/{zone_id}")
|
| 651 |
def geo_zone_update(zone_id: str, body: dict = Body(default=None),
|
| 652 |
-
session: Session = Depends(require_session)
|
| 653 |
"""Edit a table-scoped Zone while retaining creator, geometry and membership invariants."""
|
| 654 |
from core import route_system
|
| 655 |
body = body if isinstance(body, dict) else {}
|
| 656 |
-
from routes_customers import _route_application_body
|
| 657 |
-
_route_application_body(body, application)
|
| 658 |
-
application = _zone_application(session, body.get("tableKey"), application, write=True)
|
| 659 |
table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey"))
|
| 660 |
-
previous = _zone_subject(session, table_key, zone_id
|
| 661 |
try:
|
| 662 |
if any(key in body for key in ("memberships", "memberPids", "member_pids")):
|
| 663 |
raise ValueError("Zone membership is derived from current permitted rows")
|
|
@@ -669,7 +630,7 @@ def geo_zone_update(zone_id: str, body: dict = Body(default=None),
|
|
| 669 |
"visible": body.get("visible", previous.get("visible")),
|
| 670 |
"geographicField": body.get("geographicField", previous.get("geographicField"))
|
| 671 |
}, rows=rows, tenant_id=session.tenant, created_by=session.uname,
|
| 672 |
-
table_key=table_key
|
| 673 |
if zone is None:
|
| 674 |
raise ValueError("the Zone does not match this database's fields and records")
|
| 675 |
except ValueError as exc:
|
|
@@ -679,16 +640,13 @@ def geo_zone_update(zone_id: str, body: dict = Body(default=None),
|
|
| 679 |
|
| 680 |
@router.delete("/geo/zones/{zone_id}")
|
| 681 |
def geo_zone_delete(zone_id: str, body: dict = Body(default=None),
|
| 682 |
-
session: Session = Depends(require_session)
|
| 683 |
"""Delete exactly one table-scoped Zone; record values are never mutated here."""
|
| 684 |
body = body if isinstance(body, dict) else {}
|
| 685 |
-
from routes_customers import _route_application_body
|
| 686 |
-
_route_application_body(body, application)
|
| 687 |
-
application = _zone_application(session, body.get("tableKey"), application, write=True)
|
| 688 |
table_key, _fields, _pids, _rows = _zone_context(session, body.get("tableKey"))
|
| 689 |
-
_zone_subject(session, table_key, zone_id
|
| 690 |
from core import route_system
|
| 691 |
-
if not route_system.delete_zone(session.runtime, zone_id, table_key=table_key
|
| 692 |
raise err(404, "unknown_zone", "no Zone with that id")
|
| 693 |
return {"deleted": str(zone_id)}
|
| 694 |
|
|
|
|
| 327 |
return table_key, fields, set(grid.get("pids") or ()), list(grid.get("rows_src") or ())
|
| 328 |
|
| 329 |
|
| 330 |
+
def _zone_subject(session, table_key, zone_id):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
from core import route_system
|
| 332 |
zone = next((item for item in route_system.list_zones(
|
| 333 |
+
session.runtime, table_key=table_key)
|
| 334 |
if str(item.get("id") or "") == str(zone_id)), None)
|
| 335 |
if not isinstance(zone, dict):
|
| 336 |
raise err(404, "unknown_zone", "no Zone with that id")
|
|
|
|
| 573 |
|
| 574 |
|
| 575 |
@router.get("/geo/zones")
|
| 576 |
+
def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(require_session)):
|
|
|
|
| 577 |
"""The canonical table-scoped Zone DTOs a Map may draw or filter by."""
|
| 578 |
from core import route_system
|
|
|
|
| 579 |
table_key, _fields, pids, rows = _zone_context(session, tableKey)
|
| 580 |
+
zones = route_system.list_zones(session.runtime, rows, table_key=table_key)
|
| 581 |
# A hidden Zone remains recoverable to its creator/admin, but cannot become visible through a
|
| 582 |
# second table simply because row ids happen to collide there.
|
| 583 |
visible = [zone for zone in zones if zone.get("visible", True)
|
|
|
|
| 588 |
|
| 589 |
|
| 590 |
@router.post("/geo/zones")
|
| 591 |
+
def geo_zone_create(body: dict = Body(default=None), session: Session = Depends(require_session)):
|
|
|
|
| 592 |
"""Persist one Zone in the existing table-scoped Zone store and field/filter contract."""
|
| 593 |
from core import route_system
|
| 594 |
body = body if isinstance(body, dict) else {}
|
|
|
|
|
|
|
|
|
|
| 595 |
table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey"))
|
| 596 |
try:
|
| 597 |
if any(key in body for key in ("memberships", "memberPids", "member_pids")):
|
|
|
|
| 601 |
"geometryGeoJson": body.get("geometryGeoJson"), "zipCodes": body.get("zipCodes"),
|
| 602 |
"visible": body.get("visible"), "geographicField": body.get("geographicField")
|
| 603 |
}, rows=rows, tenant_id=session.tenant, created_by=session.uname,
|
| 604 |
+
table_key=table_key)
|
| 605 |
if zone is None:
|
| 606 |
raise ValueError("the Zone does not match this database's fields and records")
|
| 607 |
except ValueError as exc:
|
|
|
|
| 613 |
|
| 614 |
@router.patch("/geo/zones/{zone_id}")
|
| 615 |
def geo_zone_update(zone_id: str, body: dict = Body(default=None),
|
| 616 |
+
session: Session = Depends(require_session)):
|
| 617 |
"""Edit a table-scoped Zone while retaining creator, geometry and membership invariants."""
|
| 618 |
from core import route_system
|
| 619 |
body = body if isinstance(body, dict) else {}
|
|
|
|
|
|
|
|
|
|
| 620 |
table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey"))
|
| 621 |
+
previous = _zone_subject(session, table_key, zone_id)
|
| 622 |
try:
|
| 623 |
if any(key in body for key in ("memberships", "memberPids", "member_pids")):
|
| 624 |
raise ValueError("Zone membership is derived from current permitted rows")
|
|
|
|
| 630 |
"visible": body.get("visible", previous.get("visible")),
|
| 631 |
"geographicField": body.get("geographicField", previous.get("geographicField"))
|
| 632 |
}, rows=rows, tenant_id=session.tenant, created_by=session.uname,
|
| 633 |
+
table_key=table_key)
|
| 634 |
if zone is None:
|
| 635 |
raise ValueError("the Zone does not match this database's fields and records")
|
| 636 |
except ValueError as exc:
|
|
|
|
| 640 |
|
| 641 |
@router.delete("/geo/zones/{zone_id}")
|
| 642 |
def geo_zone_delete(zone_id: str, body: dict = Body(default=None),
|
| 643 |
+
session: Session = Depends(require_session)):
|
| 644 |
"""Delete exactly one table-scoped Zone; record values are never mutated here."""
|
| 645 |
body = body if isinstance(body, dict) else {}
|
|
|
|
|
|
|
|
|
|
| 646 |
table_key, _fields, _pids, _rows = _zone_context(session, body.get("tableKey"))
|
| 647 |
+
_zone_subject(session, table_key, zone_id)
|
| 648 |
from core import route_system
|
| 649 |
+
if not route_system.delete_zone(session.runtime, zone_id, table_key=table_key):
|
| 650 |
raise err(404, "unknown_zone", "no Zone with that id")
|
| 651 |
return {"deleted": str(zone_id)}
|
| 652 |
|
api/routes_grid.py
CHANGED
|
@@ -1816,7 +1816,7 @@ def _materialise_recurrence_cells(session, scope, events, results, fields):
|
|
| 1816 |
# admin route over the CALLING TENANT, and a scheduler must call it once per tenant.
|
| 1817 |
|
| 1818 |
|
| 1819 |
-
def refresh_recurrence_columns(st, scope, today=None, defn=None
|
| 1820 |
"""R2's roll-forward for ONE database: `{field_key: rows_written}`; `{}` when nothing moved.
|
| 1821 |
|
| 1822 |
Callable WITHOUT an HTTP request — `st` is a store handle (`session.runtime`) and `scope` a
|
|
@@ -1880,8 +1880,7 @@ def refresh_recurrence_columns(st, scope, today=None, defn=None, by=None):
|
|
| 1880 |
counts[key] = counts.get(key, 0) + 1
|
| 1881 |
if not updates:
|
| 1882 |
return {}
|
| 1883 |
-
|
| 1884 |
-
written = user_tables.patch_many_cells(scope, updates, st=st, by=by)
|
| 1885 |
if not written:
|
| 1886 |
return {}
|
| 1887 |
if written != len(updates):
|
|
@@ -1892,7 +1891,7 @@ def refresh_recurrence_columns(st, scope, today=None, defn=None, by=None):
|
|
| 1892 |
return counts
|
| 1893 |
|
| 1894 |
|
| 1895 |
-
def refresh_recurrence_tenant(st, today=None
|
| 1896 |
"""Every user database in ONE tenant: `{table_key: {field_key: rows_written}}`.
|
| 1897 |
|
| 1898 |
ONE `all_tables` read for the whole walk, with each definition LENT onward — see
|
|
@@ -1904,7 +1903,7 @@ def refresh_recurrence_tenant(st, today=None, by=None):
|
|
| 1904 |
today = str(today or time.strftime("%Y-%m-%d"))
|
| 1905 |
out = {}
|
| 1906 |
for scope, defn in (user_tables.all_tables(st=st) or {}).items():
|
| 1907 |
-
counts = refresh_recurrence_columns(st, scope, today=today, defn=defn
|
| 1908 |
if counts:
|
| 1909 |
out[str(scope)] = counts
|
| 1910 |
return out
|
|
@@ -1930,7 +1929,7 @@ def recurrence_refresh(session: Session = Depends(require_session)):
|
|
| 1930 |
raise err(503, "store_unavailable",
|
| 1931 |
"the tenant store is unavailable. Nothing was refreshed")
|
| 1932 |
today = time.strftime("%Y-%m-%d")
|
| 1933 |
-
tables = refresh_recurrence_tenant(session.runtime, today=today
|
| 1934 |
return {"today": today, "tables": tables,
|
| 1935 |
"cells": sum(sum(counts.values()) for counts in tables.values()),
|
| 1936 |
"columns": sum(len(counts) for counts in tables.values())}
|
|
|
|
| 1816 |
# admin route over the CALLING TENANT, and a scheduler must call it once per tenant.
|
| 1817 |
|
| 1818 |
|
| 1819 |
+
def refresh_recurrence_columns(st, scope, today=None, defn=None):
|
| 1820 |
"""R2's roll-forward for ONE database: `{field_key: rows_written}`; `{}` when nothing moved.
|
| 1821 |
|
| 1822 |
Callable WITHOUT an HTTP request — `st` is a store handle (`session.runtime`) and `scope` a
|
|
|
|
| 1880 |
counts[key] = counts.get(key, 0) + 1
|
| 1881 |
if not updates:
|
| 1882 |
return {}
|
| 1883 |
+
written = user_tables.patch_many_cells(scope, updates, st=st)
|
|
|
|
| 1884 |
if not written:
|
| 1885 |
return {}
|
| 1886 |
if written != len(updates):
|
|
|
|
| 1891 |
return counts
|
| 1892 |
|
| 1893 |
|
| 1894 |
+
def refresh_recurrence_tenant(st, today=None):
|
| 1895 |
"""Every user database in ONE tenant: `{table_key: {field_key: rows_written}}`.
|
| 1896 |
|
| 1897 |
ONE `all_tables` read for the whole walk, with each definition LENT onward — see
|
|
|
|
| 1903 |
today = str(today or time.strftime("%Y-%m-%d"))
|
| 1904 |
out = {}
|
| 1905 |
for scope, defn in (user_tables.all_tables(st=st) or {}).items():
|
| 1906 |
+
counts = refresh_recurrence_columns(st, scope, today=today, defn=defn)
|
| 1907 |
if counts:
|
| 1908 |
out[str(scope)] = counts
|
| 1909 |
return out
|
|
|
|
| 1929 |
raise err(503, "store_unavailable",
|
| 1930 |
"the tenant store is unavailable. Nothing was refreshed")
|
| 1931 |
today = time.strftime("%Y-%m-%d")
|
| 1932 |
+
tables = refresh_recurrence_tenant(session.runtime, today=today)
|
| 1933 |
return {"today": today, "tables": tables,
|
| 1934 |
"cells": sum(sum(counts.values()) for counts in tables.values()),
|
| 1935 |
"columns": sum(len(counts) for counts in tables.values())}
|
api/routes_nav.py
CHANGED
|
@@ -28,7 +28,6 @@ router = APIRouter(prefix="/api/v1")
|
|
| 28 |
_NAV_PREFS_KEY = "nav_prefs"
|
| 29 |
_MAX_NAV_FOLDERS = 16
|
| 30 |
|
| 31 |
-
|
| 32 |
#: WAVE 19 (R8 / contract C1): the database's NAME and ICON overrides.
|
| 33 |
#:
|
| 34 |
#: ⚠ TENANT-WIDE, which is the whole difference from `nav_prefs` above and the reason it is a
|
|
|
|
| 28 |
_NAV_PREFS_KEY = "nav_prefs"
|
| 29 |
_MAX_NAV_FOLDERS = 16
|
| 30 |
|
|
|
|
| 31 |
#: WAVE 19 (R8 / contract C1): the database's NAME and ICON overrides.
|
| 32 |
#:
|
| 33 |
#: ⚠ TENANT-WIDE, which is the whole difference from `nav_prefs` above and the reason it is a
|
api/routes_odoo_tables.py
CHANGED
|
@@ -4532,12 +4532,6 @@ def mirror_stamp(spec, cur=None, table_key="", rt=None, defn=None):
|
|
| 4532 |
return ""
|
| 4533 |
except Exception: # noqa: BLE001
|
| 4534 |
return ""
|
| 4535 |
-
if str(table_key).startswith("ut_amzn_"):
|
| 4536 |
-
try:
|
| 4537 |
-
from external_freshness import amazon_sync_stamp
|
| 4538 |
-
return str(amazon_sync_stamp(cur, table_key) or "")[:10]
|
| 4539 |
-
except Exception:
|
| 4540 |
-
return ""
|
| 4541 |
ident = str(spec.get("id") or "")
|
| 4542 |
alias = ident.split(".", 1)[0] if "." in ident else ""
|
| 4543 |
table = str((spec.get("tables") or {}).get(alias) or spec.get("table")
|
|
|
|
| 4532 |
return ""
|
| 4533 |
except Exception: # noqa: BLE001
|
| 4534 |
return ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4535 |
ident = str(spec.get("id") or "")
|
| 4536 |
alias = ident.split(".", 1)[0] if "." in ident else ""
|
| 4537 |
table = str((spec.get("tables") or {}).get(alias) or spec.get("table")
|
api/routes_query.py
CHANGED
|
@@ -124,6 +124,18 @@ QUERY_NO_SOURCE_MATCHED = (
|
|
| 124 |
"None of the databases you can read cover that question. Pick one from the list, "
|
| 125 |
"or ask about a database you can open."
|
| 126 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
QUERY_DRAFT_ADMIN = "This database has no approved fields yet. Pick the ones this answer should use and they will be approved for everyone."
|
| 128 |
QUERY_DRAFT_MEMBER = "This database has no approved fields yet. Pick the ones you need and your administrators will be asked to approve them."
|
| 129 |
QUERY_DRAFT_SENT = "Sent to your administrators. Ask again once one of them approves."
|
|
@@ -1023,6 +1035,8 @@ def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, s
|
|
| 1023 |
tools.extend(agent_runtime.tool_specs(session, snapshot=snapshot))
|
| 1024 |
if turn.get("openWork"):
|
| 1025 |
tools = [tool for tool in tools if tool["function"]["name"] == "open_items"]
|
|
|
|
|
|
|
| 1026 |
if turn.get("admittedTools"):
|
| 1027 |
tools = [tool for tool in tools if tool["function"]["name"] in set(turn["admittedTools"])]
|
| 1028 |
if turn.get("memoryOnly"):
|
|
@@ -1033,6 +1047,11 @@ def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, s
|
|
| 1033 |
"You are the Loopable Assistant. Use tools for facts. Writes run at once. Deletes need the user's yes.")
|
| 1034 |
if turn.get("context"):
|
| 1035 |
prompt += "\n\n" + turn["context"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1036 |
if turn.get("toolShareRequests"):
|
| 1037 |
prompt += ("\nThis turn concerns a pending tool-share approval only. Use the prior conversation to identify "
|
| 1038 |
"the request. Ask which request when the user's approval is ambiguous. "
|
|
@@ -2013,8 +2032,13 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
|
|
| 2013 |
memory_only = dock is None and not target and replay is None and assistant_memory.admits(question)
|
| 2014 |
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 {
|
| 2015 |
"database": target, "auto": False, "alternatives": []}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2016 |
target = routed["database"]
|
| 2017 |
-
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
|
| 2018 |
QUERY_NO_SOURCE_MATCHED if not target and replay is None else routed.get("refusal"))
|
| 2019 |
|
| 2020 |
# Snapshot turns plan mirrors from schema. Dock turns read through permissioned tools.
|
|
@@ -2064,6 +2088,9 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
|
|
| 2064 |
turn["admittedTools"] = sorted(admitted)
|
| 2065 |
if memory_only:
|
| 2066 |
turn["memoryOnly"] = True
|
|
|
|
|
|
|
|
|
|
| 2067 |
turn["memoryCompanyRequested"] = assistant_memory.company_requested(question)
|
| 2068 |
if snapshot is not None:
|
| 2069 |
turn["memorySources"] = [{"database": snapshot["database"],
|
|
@@ -2382,48 +2409,7 @@ def _recorded_artifacts(session):
|
|
| 2382 |
yield from assistant_artifacts._rows(session.runtime, h, index)
|
| 2383 |
|
| 2384 |
|
| 2385 |
-
def
|
| 2386 |
-
"""Resolve current item authority before offering or executing an Artifact mutation."""
|
| 2387 |
-
try:
|
| 2388 |
-
session.require("analyst")
|
| 2389 |
-
if not session.uname or item.get("status") == "deleted":
|
| 2390 |
-
return False
|
| 2391 |
-
kind, ref = item["kind"], item.get("ref")
|
| 2392 |
-
owner = assistant_log._hash(session.runtime, session.uname)
|
| 2393 |
-
legacy_query = kind == "query" and item["id"] == "query:" + str(ref)
|
| 2394 |
-
# Every caller already resolved the row through this principal's catalog or Query namespace.
|
| 2395 |
-
if not legacy_query and assistant_artifacts._seq(owner, item["id"]) is None:
|
| 2396 |
-
return False
|
| 2397 |
-
if kind == "query":
|
| 2398 |
-
if query_views is not None:
|
| 2399 |
-
# The list already admitted these sources in its current permission batch.
|
| 2400 |
-
return ref in query_views
|
| 2401 |
-
_artifact_or_404(session, ref)
|
| 2402 |
-
return True
|
| 2403 |
-
if kind == "view":
|
| 2404 |
-
from routes_starred import _find_view
|
| 2405 |
-
from routes_starred import _home_view_row
|
| 2406 |
-
found = _find_view(session, ref, item["toolCall"]["args"].get("database") or "")
|
| 2407 |
-
return bool(found and _home_view_row(session, found)["capabilities"]["edit"])
|
| 2408 |
-
if kind == "sheet":
|
| 2409 |
-
from core import sheets
|
| 2410 |
-
import routes_sheet
|
| 2411 |
-
book = sheets.get_workbook(session.runtime, ref)
|
| 2412 |
-
routes_sheet._require_reader(session, book)
|
| 2413 |
-
return routes_sheet._role_on_workbook(session, book) in ("owner", "edit")
|
| 2414 |
-
if kind == "schedule":
|
| 2415 |
-
import schedules
|
| 2416 |
-
schedule = schedules.get(session.runtime, ref)
|
| 2417 |
-
return bool(schedule and schedule.get("owner") == session.uname and not schedule.get("system"))
|
| 2418 |
-
if kind == "snapshot":
|
| 2419 |
-
_snapshot_content(session, item)
|
| 2420 |
-
return True
|
| 2421 |
-
return kind in ("report", "run", "pdf", "xlsx", "image")
|
| 2422 |
-
except Exception:
|
| 2423 |
-
return False
|
| 2424 |
-
|
| 2425 |
-
|
| 2426 |
-
def _artifact_actions(item, session=None, *, query_views=None):
|
| 2427 |
actions = ["run"]
|
| 2428 |
if item["kind"] in ("sheet", "view", "query") and item.get("ref"):
|
| 2429 |
actions.insert(0, "open")
|
|
@@ -2431,15 +2417,6 @@ def _artifact_actions(item, session=None, *, query_views=None):
|
|
| 2431 |
actions.extend(["resume" if item.get("status") == "paused" else "pause", "delete"])
|
| 2432 |
elif item["kind"] in ("view", "query") and item.get("ref"):
|
| 2433 |
actions.append("delete")
|
| 2434 |
-
if session is not None:
|
| 2435 |
-
# Extracted projections without an item authority resolver keep mutation actions closed.
|
| 2436 |
-
can_edit = globals().get("_artifact_can_edit")
|
| 2437 |
-
if callable(can_edit) and can_edit(session, item, query_views=query_views):
|
| 2438 |
-
actions.append("rename")
|
| 2439 |
-
if "delete" not in actions:
|
| 2440 |
-
actions.append("delete")
|
| 2441 |
-
else:
|
| 2442 |
-
actions = [action for action in actions if action not in ("delete", "pause", "resume")]
|
| 2443 |
return actions
|
| 2444 |
|
| 2445 |
|
|
@@ -2481,7 +2458,7 @@ def _artifact_rows(session, views_only=False):
|
|
| 2481 |
"database": view["source"]["database"], "question": view["question"]}}})
|
| 2482 |
for row in rows:
|
| 2483 |
row["title"] = _no_dashes(row["title"])[:200]
|
| 2484 |
-
row["actions"] = _artifact_actions(row
|
| 2485 |
return sorted(rows, key=lambda row: (row["createdAt"], row["id"]), reverse=True)
|
| 2486 |
|
| 2487 |
|
|
@@ -2519,7 +2496,7 @@ def _artifact_item(session, item_id):
|
|
| 2519 |
if stored and stored["status"] != "deleted":
|
| 2520 |
if stored["kind"] == "query":
|
| 2521 |
_artifact_or_404(session, stored["ref"])
|
| 2522 |
-
stored["actions"] = _artifact_actions(stored
|
| 2523 |
return stored
|
| 2524 |
item = next((row for row in _artifact_rows(session) if row["id"] == item_id), None)
|
| 2525 |
if item is None:
|
|
@@ -2637,23 +2614,18 @@ def resume_artifact(id: str, session: Session = Depends(require_session)):
|
|
| 2637 |
def delete_artifact(id: str, session: Session = Depends(require_session)):
|
| 2638 |
import agent_runtime
|
| 2639 |
item = _artifact_item(session, id)
|
| 2640 |
-
if not _artifact_can_edit(session, item):
|
| 2641 |
-
raise err(403, "artifact_read_only", "Your current rights do not allow deleting this artifact.")
|
| 2642 |
if item["kind"] == "schedule":
|
| 2643 |
name, args = "schedule_delete", {"id": item["ref"]}
|
| 2644 |
elif item["kind"] == "view":
|
| 2645 |
-
name, args = "
|
| 2646 |
elif item["kind"] == "query":
|
| 2647 |
name, args = "query_view_delete", {"qid": item["ref"]}
|
| 2648 |
-
elif item["kind"] in ("sheet", "report", "run", "pdf", "xlsx", "image", "snapshot"):
|
| 2649 |
-
name, args = "artifact_entry_delete", {"id": item["id"]}
|
| 2650 |
else:
|
| 2651 |
raise err(400, "not_deletable", "This artifact cannot be deleted here.")
|
| 2652 |
pending = agent_runtime._pending(session, "app", name, args)
|
| 2653 |
-
if item["kind"] in ("query", "schedule"
|
| 2654 |
# The artifact carries the name the reader knows; a schedule id or a Query id is not one.
|
| 2655 |
-
noun =
|
| 2656 |
-
if item["kind"] in ("schedule", "view") else "artifact")
|
| 2657 |
pending["summary"] = f"Remove {noun} {_no_dashes(item['title']).rstrip('. ')}."
|
| 2658 |
def name_request(raw):
|
| 2659 |
current = copy.deepcopy(raw)
|
|
@@ -2667,79 +2639,6 @@ def delete_artifact(id: str, session: Session = Depends(require_session)):
|
|
| 2667 |
return {"pendingDelete": pending}
|
| 2668 |
|
| 2669 |
|
| 2670 |
-
def _update_artifact_entry(session, item_id, patch):
|
| 2671 |
-
"""Update only this principal's catalog entry while preserving its backing object."""
|
| 2672 |
-
owner = assistant_log._hash(session.runtime, session.uname)
|
| 2673 |
-
seq = assistant_artifacts._seq(owner, item_id)
|
| 2674 |
-
if seq is None:
|
| 2675 |
-
raise err(404, "unknown_artifact", "That artifact does not exist.")
|
| 2676 |
-
saved = {}
|
| 2677 |
-
|
| 2678 |
-
def update(raw):
|
| 2679 |
-
saved.clear()
|
| 2680 |
-
doc = copy.deepcopy(raw or {})
|
| 2681 |
-
row = next((row for row in doc.get("items", []) if row.get("id") == item_id), None)
|
| 2682 |
-
if row is None or row.get("status") == "deleted":
|
| 2683 |
-
raise err(404, "unknown_artifact", "That artifact does not exist.")
|
| 2684 |
-
if not _artifact_can_edit(session, row):
|
| 2685 |
-
raise err(403, "artifact_read_only", "Your current rights do not allow changing this artifact.")
|
| 2686 |
-
row.update(patch)
|
| 2687 |
-
saved.update(row)
|
| 2688 |
-
return doc
|
| 2689 |
-
|
| 2690 |
-
session.runtime.update(assistant_artifacts._chunk_key(owner, seq // assistant_artifacts.CHUNK_ITEMS),
|
| 2691 |
-
update, flush="sync")
|
| 2692 |
-
if not saved:
|
| 2693 |
-
raise err(503, "store_unavailable", "The artifact change could not be confirmed. Reload and try again.")
|
| 2694 |
-
saved["actions"] = _artifact_actions(saved, session)
|
| 2695 |
-
return saved
|
| 2696 |
-
|
| 2697 |
-
|
| 2698 |
-
@router.patch("/artifacts/{id}")
|
| 2699 |
-
def rename_artifact(id: str, body: dict = Body(default=None), session: Session = Depends(require_session)):
|
| 2700 |
-
"""Rename an authorized Artifact's label without changing its generated content."""
|
| 2701 |
-
title = (body or {}).get("title")
|
| 2702 |
-
if not isinstance(title, str) or not title.strip() or len(title.strip()) > 200:
|
| 2703 |
-
raise err(400, "bad_title", "Use a title of 1 to 200 characters.")
|
| 2704 |
-
item = _artifact_item(session, id)
|
| 2705 |
-
if not _artifact_can_edit(session, item):
|
| 2706 |
-
raise err(403, "artifact_read_only", "Your current rights do not allow renaming this artifact.")
|
| 2707 |
-
title = title.strip()
|
| 2708 |
-
if item["kind"] == "query":
|
| 2709 |
-
if len(title) > 60 or title != " ".join(title.split()):
|
| 2710 |
-
raise err(400, "bad_title", "Use a title of at most 60 characters with single spaces.")
|
| 2711 |
-
title = rename_query(item["ref"], {"name": title}, session)["name"]
|
| 2712 |
-
if id.startswith("query:"):
|
| 2713 |
-
return {"artifact": _artifact_item(session, id)}
|
| 2714 |
-
return {"artifact": _update_artifact_entry(session, id, {"title": title})}
|
| 2715 |
-
|
| 2716 |
-
|
| 2717 |
-
def _delete_artifact_entry(session, args):
|
| 2718 |
-
item = _artifact_item(session, args["id"])
|
| 2719 |
-
if item["kind"] == "view":
|
| 2720 |
-
if not _artifact_can_edit(session, item):
|
| 2721 |
-
raise err(403, "artifact_read_only", "Your current rights do not allow deleting this artifact.")
|
| 2722 |
-
from routes_starred import delete_home_view
|
| 2723 |
-
delete_home_view(item["toolCall"]["args"]["database"], item["ref"], None, session)
|
| 2724 |
-
assistant_artifacts.set_status(session.runtime, session.uname, item["id"], "deleted")
|
| 2725 |
-
return {"deleted": item["id"]}
|
| 2726 |
-
if item["kind"] not in ("sheet", "report", "run", "pdf", "xlsx", "image", "snapshot"):
|
| 2727 |
-
raise err(400, "not_deletable", "This artifact cannot be deleted through this action.")
|
| 2728 |
-
_update_artifact_entry(session, item["id"], {"status": "deleted"})
|
| 2729 |
-
return {"deleted": item["id"]}
|
| 2730 |
-
|
| 2731 |
-
|
| 2732 |
-
def _register_artifact_entry_delete():
|
| 2733 |
-
import agent_tools
|
| 2734 |
-
agent_tools.register("artifact_entry_delete", {
|
| 2735 |
-
"type": "object", "description": "Remove your Artifact entry after confirmation while retaining its backing data.",
|
| 2736 |
-
"properties": {"id": {"type": "string"}}, "required": ["id"], "additionalProperties": False,
|
| 2737 |
-
}, _delete_artifact_entry, effect="delete")
|
| 2738 |
-
|
| 2739 |
-
|
| 2740 |
-
_register_artifact_entry_delete()
|
| 2741 |
-
|
| 2742 |
-
|
| 2743 |
def _settle_artifact_delete(session, call):
|
| 2744 |
kind = {"schedule_delete": "schedule", "view_delete": "view", "query_view_delete": "query"}.get(call["name"])
|
| 2745 |
if kind is None:
|
|
@@ -2872,6 +2771,32 @@ def _route_candidates(session):
|
|
| 2872 |
return candidates
|
| 2873 |
|
| 2874 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2875 |
def _route(session, question):
|
| 2876 |
from harness import semantic as sem
|
| 2877 |
candidates = _route_candidates(session)
|
|
@@ -3438,6 +3363,10 @@ def governed_query(body: dict = Body(default=None),
|
|
| 3438 |
"database": "", "label": "", "reason": "", "auto": False, "alternatives": []}}
|
| 3439 |
routed = _route(session, question) if not database else {
|
| 3440 |
"database": database, "label": "", "reason": "", "auto": False, "alternatives": []}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3441 |
database = routed["database"]
|
| 3442 |
if database:
|
| 3443 |
_semantic_authorize(session, database, require_answerable=not routed["auto"])
|
|
|
|
| 124 |
"None of the databases you can read cover that question. Pick one from the list, "
|
| 125 |
"or ask about a database you can open."
|
| 126 |
)
|
| 127 |
+
# A fresh turn made only of these words names no data subject, so it is conversation (D-2673).
|
| 128 |
+
_CHAT_WORDS = (
|
| 129 |
+
"hello hi hey hiya good morning afternoon evening thanks thank please ok okay yes no yeah yep sure "
|
| 130 |
+
"cool great nice sorry bye goodbye cheers welcome i me you your yours we it its they them can could "
|
| 131 |
+
"would will should might have has had be am been being does doing done get got there here then "
|
| 132 |
+
"just also too so really still now hear see know help think say ask mean understand need want like "
|
| 133 |
+
"try talk chat explain database table field data workspace loopable assistant loopy app question answer"
|
| 134 |
+
)
|
| 135 |
+
CONVERSATION_PROMPT = (
|
| 136 |
+
"\nNo database is chosen for this turn and no tool is available. Reply in plain sentences with no "
|
| 137 |
+
"markdown, and never state a figure from data. If the user asks about their data, ask which database to use."
|
| 138 |
+
)
|
| 139 |
QUERY_DRAFT_ADMIN = "This database has no approved fields yet. Pick the ones this answer should use and they will be approved for everyone."
|
| 140 |
QUERY_DRAFT_MEMBER = "This database has no approved fields yet. Pick the ones you need and your administrators will be asked to approve them."
|
| 141 |
QUERY_DRAFT_SENT = "Sent to your administrators. Ask again once one of them approves."
|
|
|
|
| 1035 |
tools.extend(agent_runtime.tool_specs(session, snapshot=snapshot))
|
| 1036 |
if turn.get("openWork"):
|
| 1037 |
tools = [tool for tool in tools if tool["function"]["name"] == "open_items"]
|
| 1038 |
+
if turn.get("conversation"):
|
| 1039 |
+
tools = []
|
| 1040 |
if turn.get("admittedTools"):
|
| 1041 |
tools = [tool for tool in tools if tool["function"]["name"] in set(turn["admittedTools"])]
|
| 1042 |
if turn.get("memoryOnly"):
|
|
|
|
| 1047 |
"You are the Loopable Assistant. Use tools for facts. Writes run at once. Deletes need the user's yes.")
|
| 1048 |
if turn.get("context"):
|
| 1049 |
prompt += "\n\n" + turn["context"]
|
| 1050 |
+
if turn.get("conversation"):
|
| 1051 |
+
names = turn.get("conversationSources")
|
| 1052 |
+
prompt += CONVERSATION_PROMPT + ("" if names is None else
|
| 1053 |
+
" The databases this user can open: " + "; ".join(names) + "."
|
| 1054 |
+
if names else " This user can open no database yet.")
|
| 1055 |
if turn.get("toolShareRequests"):
|
| 1056 |
prompt += ("\nThis turn concerns a pending tool-share approval only. Use the prior conversation to identify "
|
| 1057 |
"the request. Ask which request when the user's approval is ambiguous. "
|
|
|
|
| 2032 |
memory_only = dock is None and not target and replay is None and assistant_memory.admits(question)
|
| 2033 |
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 {
|
| 2034 |
"database": target, "auto": False, "alternatives": []}
|
| 2035 |
+
# D-2673: an app turn with no data subject reaches the model with no tools, never the no-source refusal.
|
| 2036 |
+
conversation = (door == "app" and dock is None and replay is None and not also_as
|
| 2037 |
+
and _conversation(question, routed))
|
| 2038 |
+
if conversation:
|
| 2039 |
+
routed = {"database": "", "label": "", "reason": "", "auto": True, "alternatives": []}
|
| 2040 |
target = routed["database"]
|
| 2041 |
+
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
|
| 2042 |
QUERY_NO_SOURCE_MATCHED if not target and replay is None else routed.get("refusal"))
|
| 2043 |
|
| 2044 |
# Snapshot turns plan mirrors from schema. Dock turns read through permissioned tools.
|
|
|
|
| 2088 |
turn["admittedTools"] = sorted(admitted)
|
| 2089 |
if memory_only:
|
| 2090 |
turn["memoryOnly"] = True
|
| 2091 |
+
if conversation:
|
| 2092 |
+
turn["conversation"] = True
|
| 2093 |
+
turn["conversationSources"] = _readable_labels(session)
|
| 2094 |
turn["memoryCompanyRequested"] = assistant_memory.company_requested(question)
|
| 2095 |
if snapshot is not None:
|
| 2096 |
turn["memorySources"] = [{"database": snapshot["database"],
|
|
|
|
| 2409 |
yield from assistant_artifacts._rows(session.runtime, h, index)
|
| 2410 |
|
| 2411 |
|
| 2412 |
+
def _artifact_actions(item):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2413 |
actions = ["run"]
|
| 2414 |
if item["kind"] in ("sheet", "view", "query") and item.get("ref"):
|
| 2415 |
actions.insert(0, "open")
|
|
|
|
| 2417 |
actions.extend(["resume" if item.get("status") == "paused" else "pause", "delete"])
|
| 2418 |
elif item["kind"] in ("view", "query") and item.get("ref"):
|
| 2419 |
actions.append("delete")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2420 |
return actions
|
| 2421 |
|
| 2422 |
|
|
|
|
| 2458 |
"database": view["source"]["database"], "question": view["question"]}}})
|
| 2459 |
for row in rows:
|
| 2460 |
row["title"] = _no_dashes(row["title"])[:200]
|
| 2461 |
+
row["actions"] = _artifact_actions(row)
|
| 2462 |
return sorted(rows, key=lambda row: (row["createdAt"], row["id"]), reverse=True)
|
| 2463 |
|
| 2464 |
|
|
|
|
| 2496 |
if stored and stored["status"] != "deleted":
|
| 2497 |
if stored["kind"] == "query":
|
| 2498 |
_artifact_or_404(session, stored["ref"])
|
| 2499 |
+
stored["actions"] = _artifact_actions(stored)
|
| 2500 |
return stored
|
| 2501 |
item = next((row for row in _artifact_rows(session) if row["id"] == item_id), None)
|
| 2502 |
if item is None:
|
|
|
|
| 2614 |
def delete_artifact(id: str, session: Session = Depends(require_session)):
|
| 2615 |
import agent_runtime
|
| 2616 |
item = _artifact_item(session, id)
|
|
|
|
|
|
|
| 2617 |
if item["kind"] == "schedule":
|
| 2618 |
name, args = "schedule_delete", {"id": item["ref"]}
|
| 2619 |
elif item["kind"] == "view":
|
| 2620 |
+
name, args = "view_delete", {"database": item["toolCall"]["args"].get("database"), "view_id": item["ref"]}
|
| 2621 |
elif item["kind"] == "query":
|
| 2622 |
name, args = "query_view_delete", {"qid": item["ref"]}
|
|
|
|
|
|
|
| 2623 |
else:
|
| 2624 |
raise err(400, "not_deletable", "This artifact cannot be deleted here.")
|
| 2625 |
pending = agent_runtime._pending(session, "app", name, args)
|
| 2626 |
+
if item["kind"] in ("query", "schedule"):
|
| 2627 |
# The artifact carries the name the reader knows; a schedule id or a Query id is not one.
|
| 2628 |
+
noun = "Query answer" if item["kind"] == "query" else "schedule"
|
|
|
|
| 2629 |
pending["summary"] = f"Remove {noun} {_no_dashes(item['title']).rstrip('. ')}."
|
| 2630 |
def name_request(raw):
|
| 2631 |
current = copy.deepcopy(raw)
|
|
|
|
| 2639 |
return {"pendingDelete": pending}
|
| 2640 |
|
| 2641 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2642 |
def _settle_artifact_delete(session, call):
|
| 2643 |
kind = {"schedule_delete": "schedule", "view_delete": "view", "query_view_delete": "query"}.get(call["name"])
|
| 2644 |
if kind is None:
|
|
|
|
| 2771 |
return candidates
|
| 2772 |
|
| 2773 |
|
| 2774 |
+
def _readable_labels(session):
|
| 2775 |
+
"""The names of the databases this session may open: the picker's set, no record read.
|
| 2776 |
+
|
| 2777 |
+
None when the status wall cannot be read, so a greeting still gets its reply."""
|
| 2778 |
+
from harness import semantic as sem
|
| 2779 |
+
try:
|
| 2780 |
+
projection = getattr(session.runtime, "get_projection", None)
|
| 2781 |
+
definitions = (projection("user_tables", drop=("rows",)) or {}) if projection else {}
|
| 2782 |
+
topics = {row.get("grid"): row.get("label") for row in sem.topics().values()}
|
| 2783 |
+
statuses = assistant_source_status(session, None)
|
| 2784 |
+
except Exception: # noqa: BLE001
|
| 2785 |
+
return None
|
| 2786 |
+
return sorted({_said(status.get("label") or (definitions.get(database) or {}).get("label")
|
| 2787 |
+
or topics.get(database) or database.removeprefix("ut_").replace("_", " ")) or database
|
| 2788 |
+
for database, status in statuses.items()
|
| 2789 |
+
if status.get("permitted")})
|
| 2790 |
+
|
| 2791 |
+
|
| 2792 |
+
def _conversation(question, routed):
|
| 2793 |
+
"""True when an auto route found no database or the question holds no data word."""
|
| 2794 |
+
from harness import semantic as sem
|
| 2795 |
+
return bool(routed.get("auto")) and (
|
| 2796 |
+
not routed.get("database")
|
| 2797 |
+
or not set(sem._route_tokens(question)) - set(sem._route_tokens(_CHAT_WORDS)))
|
| 2798 |
+
|
| 2799 |
+
|
| 2800 |
def _route(session, question):
|
| 2801 |
from harness import semantic as sem
|
| 2802 |
candidates = _route_candidates(session)
|
|
|
|
| 3363 |
"database": "", "label": "", "reason": "", "auto": False, "alternatives": []}}
|
| 3364 |
routed = _route(session, question) if not database else {
|
| 3365 |
"database": database, "label": "", "reason": "", "auto": False, "alternatives": []}
|
| 3366 |
+
if _conversation(question, routed):
|
| 3367 |
+
# D-2673: a greeting or a question no database covers continues to chat, never a Clarify card.
|
| 3368 |
+
return {"status": "continue_chat", "routedTo": {
|
| 3369 |
+
"database": "", "label": "", "reason": "", "auto": False, "alternatives": []}}
|
| 3370 |
database = routed["database"]
|
| 3371 |
if database:
|
| 3372 |
_semantic_authorize(session, database, require_answerable=not routed["auto"])
|
api/routes_sheet.py
CHANGED
|
@@ -1412,7 +1412,7 @@ _MISSING_CODES = ("workbook_missing", "folder_missing", "tab_missing", "unknown_
|
|
| 1412 |
#: it, which is what 403 means and is the only status a client can act on.
|
| 1413 |
#:
|
| 1414 |
#: `workbook_read_only` is a VIEWER at a write door; `workbook_owner_only` is a non-owner at a
|
| 1415 |
-
#: door C5 reserves for the owner (the two share doors). Two codes rather than one
|
| 1416 |
#: because they send the reader to two different places: one asks for edit access, the other
|
| 1417 |
#: cannot be granted at all.
|
| 1418 |
_FORBIDDEN_CODES = ("workbook_read_only", "workbook_owner_only", "tenant_mismatch", "sheet_actor_required")
|
|
@@ -3443,10 +3443,18 @@ def duplicate_sheet_tab(workbook_id: str, tab: str, body: dict = Body(default=No
|
|
| 3443 |
|
| 3444 |
@router.delete("/sheets/{workbook_id}")
|
| 3445 |
def drop_sheet(workbook_id: str, session: Session = Depends(require_session)):
|
| 3446 |
-
"""Delete a workbook
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3447 |
from core import sheets
|
| 3448 |
try:
|
| 3449 |
-
|
| 3450 |
removed = sheets.delete_workbook(_store(session), workbook_id)
|
| 3451 |
except sheets.SheetRefusal as exc:
|
| 3452 |
raise _refuse(exc)
|
|
|
|
| 1412 |
#: it, which is what 403 means and is the only status a client can act on.
|
| 1413 |
#:
|
| 1414 |
#: `workbook_read_only` is a VIEWER at a write door; `workbook_owner_only` is a non-owner at a
|
| 1415 |
+
#: door C5 reserves for the owner (the two share doors, and DELETE). Two codes rather than one
|
| 1416 |
#: because they send the reader to two different places: one asks for edit access, the other
|
| 1417 |
#: cannot be granted at all.
|
| 1418 |
_FORBIDDEN_CODES = ("workbook_read_only", "workbook_owner_only", "tenant_mismatch", "sheet_actor_required")
|
|
|
|
| 3443 |
|
| 3444 |
@router.delete("/sheets/{workbook_id}")
|
| 3445 |
def drop_sheet(workbook_id: str, session: Session = Depends(require_session)):
|
| 3446 |
+
"""Delete a workbook. THE OWNER's door, and an editor is refused by name (C5).
|
| 3447 |
+
|
| 3448 |
+
⛔ AN `edit` GRANT IS PERMISSION TO CHANGE THE CONTENT, NOT TO DESTROY THE OBJECT, and the
|
| 3449 |
+
fail-closed reading is the one that ships: an editor who deletes the owner's workbook has
|
| 3450 |
+
taken it from everybody it was shared with, and nothing in this system can put it back. The
|
| 3451 |
+
refusal is `workbook_owner_only` rather than `workbook_read_only` because the sentences send
|
| 3452 |
+
the reader to two different places, and telling an editor their workbook is read only would be
|
| 3453 |
+
flatly false.
|
| 3454 |
+
"""
|
| 3455 |
from core import sheets
|
| 3456 |
try:
|
| 3457 |
+
_require_owner(session, sheets.get_workbook(_store(session), workbook_id))
|
| 3458 |
removed = sheets.delete_workbook(_store(session), workbook_id)
|
| 3459 |
except sheets.SheetRefusal as exc:
|
| 3460 |
raise _refuse(exc)
|
api/routes_starred.py
CHANGED
|
@@ -34,7 +34,7 @@ import json
|
|
| 34 |
import time
|
| 35 |
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
|
| 36 |
|
| 37 |
-
from fastapi import APIRouter, Body, Depends
|
| 38 |
|
| 39 |
import routes_nav
|
| 40 |
from deps import Session, err, require_session
|
|
@@ -304,7 +304,7 @@ def _refresh_one(session, cache, key):
|
|
| 304 |
return (order, docs, unread)
|
| 305 |
|
| 306 |
|
| 307 |
-
def _scan_starred_views(session, keys=None, cache=None, include=None
|
| 308 |
"""`(rows, unread)` — every view this caller has starred, newest-worked database first.
|
| 309 |
|
| 310 |
A row is `{"id", "database", "name", "config"}`. ⚠ `config` is carried so the COUNTS route does
|
|
@@ -367,12 +367,11 @@ def _scan_starred_views(session, keys=None, cache=None, include=None, with_right
|
|
| 367 |
doc = session.runtime.get_projection(ws_key, drop=("overlays", "fields")) or {}
|
| 368 |
docs[key] = doc
|
| 369 |
|
| 370 |
-
found
|
| 371 |
own = doc.get(session.uname)
|
| 372 |
for vid, view in ((own.get("views") or {}) if isinstance(own, dict) else {}).items():
|
| 373 |
if isinstance(view, dict):
|
| 374 |
found[str(vid)] = view
|
| 375 |
-
owners[str(vid)] = session.uname
|
| 376 |
|
| 377 |
for vid in pending:
|
| 378 |
owner = granted.get(vid)
|
|
@@ -392,17 +391,12 @@ def _scan_starred_views(session, keys=None, cache=None, include=None, with_right
|
|
| 392 |
break
|
| 393 |
if isinstance(view, dict):
|
| 394 |
found.setdefault(vid, view)
|
| 395 |
-
owners.setdefault(vid, owner if owner else candidate_owner)
|
| 396 |
resolved.add(vid)
|
| 397 |
for vid, view in found.items():
|
| 398 |
cfg = view.get("config") or {}
|
| 399 |
if (include(view) if include else cfg.get("important") is True):
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
if with_rights:
|
| 403 |
-
row.update(routes_nav._home_view_row(
|
| 404 |
-
session, (key, ws_key, owners[vid], {**view, "id": vid}, None)))
|
| 405 |
-
out.append(row)
|
| 406 |
return out, unread
|
| 407 |
|
| 408 |
|
|
@@ -522,82 +516,15 @@ def _payload(session, keys=None, cache=None):
|
|
| 522 |
|
| 523 |
@router.get("/nav/views")
|
| 524 |
def nav_views(session: Session = Depends(require_session)):
|
| 525 |
-
"""
|
| 526 |
-
rows, unread = _scan_starred_views(session, include=lambda view: True, with_rights=True)
|
| 527 |
-
return {"views": [{key: row[key] for key in ("database", "id", "name", "capabilities")}
|
| 528 |
-
for row in rows], "unread": unread}
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
# S76-T17: the Home Views section's rename and delete live beside its GET, never in routes_nav (R7).
|
| 532 |
-
|
| 533 |
-
def _home_view_row(session, found):
|
| 534 |
-
"""Project only a saved View's identity, name and current edit right."""
|
| 535 |
-
database, _, owner, view, _ = found
|
| 536 |
-
editable = (view.get("id") != SYSTEM_VIEW_ID and view.get("kind") != "system"
|
| 537 |
-
and _may_star_view(session, owner, view))
|
| 538 |
-
return {"database": database, "id": view["id"], "name": str(view.get("name") or view["id"])[:120],
|
| 539 |
-
"capabilities": {"edit": bool(editable), "delete": bool(editable)}}
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
def _editable_home_view(session, database, view_id):
|
| 543 |
-
found = _find_view(session, view_id, database)
|
| 544 |
-
if found is None:
|
| 545 |
-
raise err(404, "view_not_found", "That saved View is no longer available.")
|
| 546 |
-
if not _home_view_row(session, found)["capabilities"]["edit"]:
|
| 547 |
-
raise err(403, "view_read_only", "Your current rights do not allow changes to this View.")
|
| 548 |
-
return found
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
@router.patch("/nav/views/{database}/{view_id}")
|
| 552 |
-
def rename_home_view(database: str, view_id: str, request: Request, body: dict = Body(default=None),
|
| 553 |
-
session: Session = Depends(require_session)):
|
| 554 |
-
"""Rename the canonical saved View without reading or returning database records."""
|
| 555 |
-
from core import table_store, view_audit, write_execution
|
| 556 |
-
from routes_tables import _audit_origin
|
| 557 |
-
|
| 558 |
-
name = (body or {}).get("name")
|
| 559 |
-
if not isinstance(name, str) or not name.strip() or len(name.strip()) > 120:
|
| 560 |
-
raise err(400, "bad_name", "Use a View name of 1 to 120 characters.")
|
| 561 |
-
found = _editable_home_view(session, database, view_id)
|
| 562 |
-
key, workspace, owner, _, cache = found
|
| 563 |
-
views = table_store.make(workspace, st=session.runtime)
|
| 564 |
-
saved, changes = {}, {}
|
| 565 |
-
|
| 566 |
-
def rename(data, audit):
|
| 567 |
-
saved.clear()
|
| 568 |
-
current = ((data.get(owner) or {}).get("views") or {}).get(view_id)
|
| 569 |
-
if not isinstance(current, dict):
|
| 570 |
-
raise err(404, "view_not_found", "That saved View is no longer available.")
|
| 571 |
-
if not _may_star_view(session, owner, current):
|
| 572 |
-
raise err(403, "view_read_only", "Your current rights do not allow changes to this View.")
|
| 573 |
-
names = [candidate.get("name") for who, personal in data.items()
|
| 574 |
-
if who not in table_store.RESERVED_MEMBERS and isinstance(personal, dict)
|
| 575 |
-
for candidate_id, candidate in (personal.get("views") or {}).items()
|
| 576 |
-
if candidate_id != view_id and isinstance(candidate, dict)]
|
| 577 |
-
updated = {**current, "name": table_store._unique_name(name.strip(), names),
|
| 578 |
-
"updatedAt": write_execution.utcnow().isoformat()} # S76-T37
|
| 579 |
-
changes.update(before=view_audit.summary(current), after=view_audit.summary(updated))
|
| 580 |
-
data[owner]["views"][view_id] = updated
|
| 581 |
-
audit(action=view_audit.derive_action(current, updated), owner=owner, view_id=view_id,
|
| 582 |
-
actor=session.uname, origin=_audit_origin(request), **changes)
|
| 583 |
-
saved.update(updated)
|
| 584 |
-
return data
|
| 585 |
-
|
| 586 |
-
views._audited_update(rename)
|
| 587 |
-
views.log_view_activity(view_id, "saved", by=session.uname, via=_audit_origin(request), **changes)
|
| 588 |
-
return {"view": _home_view_row(session, (key, workspace, owner, saved, cache))}
|
| 589 |
-
|
| 590 |
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
"""
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
table_store.make(workspace, st=session.runtime).delete_view(
|
| 599 |
-
owner, view_id, actor=session.uname, origin=_audit_origin(request))
|
| 600 |
-
return {"deleted": view_id}
|
| 601 |
|
| 602 |
|
| 603 |
@router.get("/starred")
|
|
|
|
| 34 |
import time
|
| 35 |
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
|
| 36 |
|
| 37 |
+
from fastapi import APIRouter, Body, Depends
|
| 38 |
|
| 39 |
import routes_nav
|
| 40 |
from deps import Session, err, require_session
|
|
|
|
| 304 |
return (order, docs, unread)
|
| 305 |
|
| 306 |
|
| 307 |
+
def _scan_starred_views(session, keys=None, cache=None, include=None):
|
| 308 |
"""`(rows, unread)` — every view this caller has starred, newest-worked database first.
|
| 309 |
|
| 310 |
A row is `{"id", "database", "name", "config"}`. ⚠ `config` is carried so the COUNTS route does
|
|
|
|
| 367 |
doc = session.runtime.get_projection(ws_key, drop=("overlays", "fields")) or {}
|
| 368 |
docs[key] = doc
|
| 369 |
|
| 370 |
+
found = {}
|
| 371 |
own = doc.get(session.uname)
|
| 372 |
for vid, view in ((own.get("views") or {}) if isinstance(own, dict) else {}).items():
|
| 373 |
if isinstance(view, dict):
|
| 374 |
found[str(vid)] = view
|
|
|
|
| 375 |
|
| 376 |
for vid in pending:
|
| 377 |
owner = granted.get(vid)
|
|
|
|
| 391 |
break
|
| 392 |
if isinstance(view, dict):
|
| 393 |
found.setdefault(vid, view)
|
|
|
|
| 394 |
resolved.add(vid)
|
| 395 |
for vid, view in found.items():
|
| 396 |
cfg = view.get("config") or {}
|
| 397 |
if (include(view) if include else cfg.get("important") is True):
|
| 398 |
+
out.append({"id": vid, "database": key,
|
| 399 |
+
"name": str(view.get("name") or vid)[:120], "config": cfg})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 400 |
return out, unread
|
| 401 |
|
| 402 |
|
|
|
|
| 516 |
|
| 517 |
@router.get("/nav/views")
|
| 518 |
def nav_views(session: Session = Depends(require_session)):
|
| 519 |
+
"""S76-T17: every saved View this caller may open, as names only, for the module home.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 520 |
|
| 521 |
+
Read-only: rename and delete stay closed (capabilities false) until their governed doors exist
|
| 522 |
+
(D-9736). The config never goes on the wire, for `_starred_views`' reason.
|
| 523 |
+
"""
|
| 524 |
+
rows, unread = _scan_starred_views(session, include=lambda view: True)
|
| 525 |
+
return {"views": [{"database": r["database"], "id": r["id"], "name": r["name"],
|
| 526 |
+
"capabilities": {"edit": False, "delete": False}} for r in rows],
|
| 527 |
+
"unread": unread}
|
|
|
|
|
|
|
|
|
|
| 528 |
|
| 529 |
|
| 530 |
@router.get("/starred")
|
api/routes_tables.py
CHANGED
|
@@ -2957,13 +2957,9 @@ def add_row(table_key: str, body: dict = Body(default=None),
|
|
| 2957 |
if ut.ZONE_FIELD_KEY in values or "zone" in values:
|
| 2958 |
raise err(400, "zone_membership_read_only",
|
| 2959 |
"Zone membership is worked out from the record's current location")
|
| 2960 |
-
# S76-T32: an undo restores a deleted record's retained server facts only when it says so.
|
| 2961 |
-
restore = (body or {}).get("restore", False)
|
| 2962 |
-
if not isinstance(restore, bool):
|
| 2963 |
-
raise err(400, "bad_restore", "restore must be true or false")
|
| 2964 |
try:
|
| 2965 |
rid = ut.add_row(table_key, values, session.uname, st=session.runtime,
|
| 2966 |
-
rid=(body or {}).get("rid"),
|
| 2967 |
except ValueError as exc:
|
| 2968 |
# A core value rule (negative policy, link condition, server-owned cell) names its reason.
|
| 2969 |
raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300] or "the row was refused")
|
|
@@ -2986,23 +2982,7 @@ def add_row(table_key: str, body: dict = Body(default=None),
|
|
| 2986 |
_refresh_relations(session)
|
| 2987 |
from routes_alerts import after_write
|
| 2988 |
after_write(session, table_key)
|
| 2989 |
-
return {"rid": rid, "pid": int(rid)
|
| 2990 |
-
|
| 2991 |
-
|
| 2992 |
-
def _added_row_values(session, table_key, rid):
|
| 2993 |
-
"""The stored row as this session may read it: generated cells included, hidden fields and
|
| 2994 |
-
server-only keys (`_rowAudit`, `_created`) never."""
|
| 2995 |
-
import core.perm_scope as perm_scope
|
| 2996 |
-
try:
|
| 2997 |
-
entry = _table_entry(session.runtime, table_key) or {}
|
| 2998 |
-
except Exception:
|
| 2999 |
-
return {} # the row is saved; a failed read-back must not report a failed write
|
| 3000 |
-
row = (entry.get("rows") or {}).get(str(rid))
|
| 3001 |
-
if not isinstance(row, dict):
|
| 3002 |
-
return {}
|
| 3003 |
-
hidden = _ut_hidden(session, table_key, entry.get("fields") or [], st=session.runtime)
|
| 3004 |
-
return perm_scope.strip_row({key: value for key, value in row.items()
|
| 3005 |
-
if not str(key).startswith("_")}, hidden)
|
| 3006 |
|
| 3007 |
|
| 3008 |
@router.post("/tables/{table_key}/rows/import", status_code=201)
|
|
@@ -3061,10 +3041,6 @@ def import_rows(table_key: str, body: dict = Body(default=None),
|
|
| 3061 |
raise err(400, "bad_value", f"row {index + 1}: {why}. Nothing was imported")
|
| 3062 |
try:
|
| 3063 |
made = ut.add_rows(table_key, rows_in, session.uname, st=session.runtime)
|
| 3064 |
-
except ValueError as exc:
|
| 3065 |
-
# S76-T33: a Link condition or value rule refuses the batch with its own code and reason.
|
| 3066 |
-
raise err(400, getattr(exc, "code", "bad_value"),
|
| 3067 |
-
(str(exc)[:280].rstrip(". ") or "a value was refused") + ". Nothing was imported")
|
| 3068 |
except Exception:
|
| 3069 |
raise err(503, "store_unavailable", "nothing was imported. The store refused")
|
| 3070 |
if made is None:
|
|
@@ -3151,33 +3127,6 @@ def _admit_if_sources(session, table_key, body, definition, fkey=''):
|
|
| 3151 |
raise err(403 if exc.code == 'if_source_forbidden' else 400, exc.code, str(exc))
|
| 3152 |
|
| 3153 |
|
| 3154 |
-
def _admit_link_selection(session, body):
|
| 3155 |
-
"""S76-T33: a Link condition may name only target fields this session can read."""
|
| 3156 |
-
raw = body if isinstance(body, dict) else {}
|
| 3157 |
-
bag = raw.get("link")
|
| 3158 |
-
if not isinstance(bag, dict) or not isinstance(bag.get("selectionFilter"), dict):
|
| 3159 |
-
return
|
| 3160 |
-
target = str(bag.get("table") or "")
|
| 3161 |
-
if not target.startswith(_ut().KEY_PREFIX):
|
| 3162 |
-
return # a registry target is checked in core, which fails closed
|
| 3163 |
-
import core.perm_scope as perm_scope
|
| 3164 |
-
if not perm_scope.may_read(session.user, target, st=session.runtime):
|
| 3165 |
-
raise err(403, "link_selection_forbidden",
|
| 3166 |
-
"You cannot read the linked database, so its records cannot set a condition.")
|
| 3167 |
-
named, stack = set(), list(bag["selectionFilter"].get("nodes") or [])
|
| 3168 |
-
while stack:
|
| 3169 |
-
node = stack.pop()
|
| 3170 |
-
if not isinstance(node, dict):
|
| 3171 |
-
continue
|
| 3172 |
-
stack.extend(node.get("children") or [])
|
| 3173 |
-
rhs = node.get("rhs") if isinstance(node.get("rhs"), dict) else {}
|
| 3174 |
-
named.update(ref for ref in (node.get("colId"), rhs.get("colId")) if isinstance(ref, str) and ref)
|
| 3175 |
-
fields = (_table_entry(session.runtime, target) or {}).get("fields") or []
|
| 3176 |
-
if named & set(_ut_hidden(session, target, fields, st=session.runtime) or ()):
|
| 3177 |
-
raise err(403, "link_selection_forbidden",
|
| 3178 |
-
"The link condition names a field you cannot read in the linked database.")
|
| 3179 |
-
|
| 3180 |
-
|
| 3181 |
@router.post("/tables/{table_key}/fields", status_code=201)
|
| 3182 |
@_c8_write
|
| 3183 |
def add_field(table_key: str, body: dict = Body(default=None),
|
|
@@ -3185,7 +3134,6 @@ def add_field(table_key: str, body: dict = Body(default=None),
|
|
| 3185 |
_managed_or_refuse(session, table_key, mutation=True)
|
| 3186 |
definition = _field_or_refuse(session, table_key)
|
| 3187 |
_admit_if_sources(session, table_key, body, definition)
|
| 3188 |
-
_admit_link_selection(session, body)
|
| 3189 |
ut = _ut()
|
| 3190 |
from routes_grid import govern_date_recurrence
|
| 3191 |
# Only recurrence admission needs the merged workspace. Plain creates need no row audience.
|
|
@@ -3321,7 +3269,6 @@ def patch_field(table_key: str, fkey: str, body: dict = Body(default=None),
|
|
| 3321 |
_managed_or_refuse(session, table_key, mutation=True)
|
| 3322 |
definition = _field_or_refuse(session, table_key, fkey)
|
| 3323 |
_admit_if_sources(session, table_key, body, definition, fkey)
|
| 3324 |
-
_admit_link_selection(session, body)
|
| 3325 |
ut = _ut()
|
| 3326 |
body = body or {}
|
| 3327 |
from routes_grid import govern_date_recurrence
|
|
@@ -3655,12 +3602,6 @@ def patch_row(table_key: str, pid: int, body: dict = Body(default=None),
|
|
| 3655 |
except ValueError as exc:
|
| 3656 |
# A core value rule refused the cell before anything was stored. Name its reason (C4).
|
| 3657 |
raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300] or "the edit was refused")
|
| 3658 |
-
# S76-T29: `overlay_patch` records a value rule's refusal instead of raising; answer it the same way.
|
| 3659 |
-
for _refusal in getattr(ctx.out, "refusals", None) or ():
|
| 3660 |
-
if _refusal.get("event") == "overlay_patch" and _refusal.get("code") not in (
|
| 3661 |
-
"cell_write_refused", "row_outside_audience", "bad_row_id"):
|
| 3662 |
-
raise err(400, _refusal.get("code") or "bad_value",
|
| 3663 |
-
_refusal.get("message") or "the edit was refused")
|
| 3664 |
# ⚠ THE READ-BACK IS THE DEFINITION ROW, AND ON A `ut_` SCOPE THAT IS THE WHOLE OF IT.
|
| 3665 |
#
|
| 3666 |
# ⛔ CORRECTED, wave-29 T22 (owner item 2a): this note used to say "THE READ-BACK SPANS BOTH
|
|
|
|
| 2957 |
if ut.ZONE_FIELD_KEY in values or "zone" in values:
|
| 2958 |
raise err(400, "zone_membership_read_only",
|
| 2959 |
"Zone membership is worked out from the record's current location")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2960 |
try:
|
| 2961 |
rid = ut.add_row(table_key, values, session.uname, st=session.runtime,
|
| 2962 |
+
rid=(body or {}).get("rid"), via=via)
|
| 2963 |
except ValueError as exc:
|
| 2964 |
# A core value rule (negative policy, link condition, server-owned cell) names its reason.
|
| 2965 |
raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300] or "the row was refused")
|
|
|
|
| 2982 |
_refresh_relations(session)
|
| 2983 |
from routes_alerts import after_write
|
| 2984 |
after_write(session, table_key)
|
| 2985 |
+
return {"rid": rid, "pid": int(rid)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2986 |
|
| 2987 |
|
| 2988 |
@router.post("/tables/{table_key}/rows/import", status_code=201)
|
|
|
|
| 3041 |
raise err(400, "bad_value", f"row {index + 1}: {why}. Nothing was imported")
|
| 3042 |
try:
|
| 3043 |
made = ut.add_rows(table_key, rows_in, session.uname, st=session.runtime)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3044 |
except Exception:
|
| 3045 |
raise err(503, "store_unavailable", "nothing was imported. The store refused")
|
| 3046 |
if made is None:
|
|
|
|
| 3127 |
raise err(403 if exc.code == 'if_source_forbidden' else 400, exc.code, str(exc))
|
| 3128 |
|
| 3129 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3130 |
@router.post("/tables/{table_key}/fields", status_code=201)
|
| 3131 |
@_c8_write
|
| 3132 |
def add_field(table_key: str, body: dict = Body(default=None),
|
|
|
|
| 3134 |
_managed_or_refuse(session, table_key, mutation=True)
|
| 3135 |
definition = _field_or_refuse(session, table_key)
|
| 3136 |
_admit_if_sources(session, table_key, body, definition)
|
|
|
|
| 3137 |
ut = _ut()
|
| 3138 |
from routes_grid import govern_date_recurrence
|
| 3139 |
# Only recurrence admission needs the merged workspace. Plain creates need no row audience.
|
|
|
|
| 3269 |
_managed_or_refuse(session, table_key, mutation=True)
|
| 3270 |
definition = _field_or_refuse(session, table_key, fkey)
|
| 3271 |
_admit_if_sources(session, table_key, body, definition, fkey)
|
|
|
|
| 3272 |
ut = _ut()
|
| 3273 |
body = body or {}
|
| 3274 |
from routes_grid import govern_date_recurrence
|
|
|
|
| 3602 |
except ValueError as exc:
|
| 3603 |
# A core value rule refused the cell before anything was stored. Name its reason (C4).
|
| 3604 |
raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300] or "the edit was refused")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3605 |
# ⚠ THE READ-BACK IS THE DEFINITION ROW, AND ON A `ut_` SCOPE THAT IS THE WHOLE OF IT.
|
| 3606 |
#
|
| 3607 |
# ⛔ CORRECTED, wave-29 T22 (owner item 2a): this note used to say "THE READ-BACK SPANS BOTH
|
api/schedules.py
CHANGED
|
@@ -224,7 +224,7 @@ def create(rt, owner, *, cron=None, tz, action, label, system=False, once_at=Non
|
|
| 224 |
item = {"id": schedule_id, "owner": owner, "label": label,
|
| 225 |
"cron": None if once or trigger else " ".join(cron.split()),
|
| 226 |
"tz": tz, "action": action, "paused": False, "nextRunAt": next_stamp,
|
| 227 |
-
"createdAt": _iso(now), "
|
| 228 |
"lastOutcome": None, "runs": [], "system": bool(system)}
|
| 229 |
if once:
|
| 230 |
item.update(once=True, onceAt=next_stamp)
|
|
@@ -261,7 +261,6 @@ def _set_paused(rt, schedule_id, paused):
|
|
| 261 |
or _utc(instant) <= now):
|
| 262 |
raise ValueError("That reminder already ran.")
|
| 263 |
item["paused"] = paused
|
| 264 |
-
item["updatedAt"] = _iso(now) # S76-T37: pausing or resuming is an update
|
| 265 |
if not paused and item.get("trigger") == "sync" and item.get("syncFallback"):
|
| 266 |
item["nextRunAt"] = _iso(now + dt.timedelta(hours=1))
|
| 267 |
if not paused and not item.get("once") and item.get("trigger") != "sync":
|
|
|
|
| 224 |
item = {"id": schedule_id, "owner": owner, "label": label,
|
| 225 |
"cron": None if once or trigger else " ".join(cron.split()),
|
| 226 |
"tz": tz, "action": action, "paused": False, "nextRunAt": next_stamp,
|
| 227 |
+
"createdAt": _iso(now), "lastFiredMinute": None, "lastFiredAt": None,
|
| 228 |
"lastOutcome": None, "runs": [], "system": bool(system)}
|
| 229 |
if once:
|
| 230 |
item.update(once=True, onceAt=next_stamp)
|
|
|
|
| 261 |
or _utc(instant) <= now):
|
| 262 |
raise ValueError("That reminder already ran.")
|
| 263 |
item["paused"] = paused
|
|
|
|
| 264 |
if not paused and item.get("trigger") == "sync" and item.get("syncFallback"):
|
| 265 |
item["nextRunAt"] = _iso(now + dt.timedelta(hours=1))
|
| 266 |
if not paused and not item.get("once") and item.get("trigger") != "sync":
|
api/tool_groups/sheet.py
CHANGED
|
@@ -49,13 +49,6 @@ def _workbook_view(ctx, args):
|
|
| 49 |
"editable": not bool(reason), "reason": reason, "sheets": tabs}}
|
| 50 |
|
| 51 |
|
| 52 |
-
def _object_available(operation):
|
| 53 |
-
"""Promise only object actions implemented by the compatibility dispatcher."""
|
| 54 |
-
from core import sheet_compat
|
| 55 |
-
return (callable(getattr(sheet_compat, "dispatch_object_operation", None))
|
| 56 |
-
and operation in sheet_compat.OBJECT_OPERATIONS)
|
| 57 |
-
|
| 58 |
-
|
| 59 |
GROUP = {
|
| 60 |
"name": "sheet", "title": "Sheets",
|
| 61 |
"guide": ("Read and change workbooks, tabs, cells, styles and charts. "
|
|
@@ -71,8 +64,6 @@ for name, actions in external_tools._SHEET_OBJECT_ACTIONS.items():
|
|
| 71 |
GROUP["actions"][name.removesuffix("_object") + "." + action] = legacy_action(
|
| 72 |
name, action=action, read=action in external_tools._OBJECT_READ_ACTIONS[name],
|
| 73 |
destructive=action in {"delete", "clear"})
|
| 74 |
-
operation = name.removesuffix("_object") + "." + action
|
| 75 |
-
GROUP["actions"][operation]["available"] = lambda operation=operation: _object_available(operation)
|
| 76 |
GROUP["actions"]["read_batch"] = legacy_action("validated_batch", read=True)
|
| 77 |
GROUP["actions"]["write_batch"] = legacy_action("validated_batch", read=False, destructive=True)
|
| 78 |
GROUP["actions"]["workbook.view"] = {
|
|
@@ -83,22 +74,6 @@ GROUP["actions"]["workbook.view"] = {
|
|
| 83 |
"required": ["workbook_id"], "additionalProperties": False},
|
| 84 |
}
|
| 85 |
GROUP["guide"] += " Use workbook.view with workbook_id to open the workbook view."
|
| 86 |
-
GROUP["guide"] += (
|
| 87 |
-
" Use workbook.list to find readable workbook ids, names and revisions. "
|
| 88 |
-
"Send action='list' in the action arguments, with page_size and cursor inside its arguments object. "
|
| 89 |
-
"Follow next_cursor until it is null to read every workbook. "
|
| 90 |
-
"Use workbook.get with action='get' and workbook_id, or put an exact case-insensitive name in arguments.name. "
|
| 91 |
-
"A near name refuses with readable close names."
|
| 92 |
-
)
|
| 93 |
-
GROUP["actions"]["workbook.list"]["schema"]["properties"]["arguments"] = {
|
| 94 |
-
"type": "object", "properties": {"cursor": {"type": "string"},
|
| 95 |
-
"page_size": {"type": "integer", "minimum": 1}}, "additionalProperties": False,
|
| 96 |
-
}
|
| 97 |
-
GROUP["actions"]["workbook.get"]["schema"]["properties"]["arguments"] = {
|
| 98 |
-
"type": "object", "properties": {"name": {"type": "string", "minLength": 1},
|
| 99 |
-
"workbook_id": {"type": "string", "minLength": 1}, "id_or_name": {"type": "string", "minLength": 1}},
|
| 100 |
-
"additionalProperties": False,
|
| 101 |
-
}
|
| 102 |
GROUP["guide"] += ' Under MCP rule 9, ask "Do you want me to build a Sheet workbook in Loopable?".'
|
| 103 |
_BATCH_GUIDE = (
|
| 104 |
" A batch has 1 to 50 operations for one workbook. Use name and arguments for each operation. "
|
|
|
|
| 49 |
"editable": not bool(reason), "reason": reason, "sheets": tabs}}
|
| 50 |
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
GROUP = {
|
| 53 |
"name": "sheet", "title": "Sheets",
|
| 54 |
"guide": ("Read and change workbooks, tabs, cells, styles and charts. "
|
|
|
|
| 64 |
GROUP["actions"][name.removesuffix("_object") + "." + action] = legacy_action(
|
| 65 |
name, action=action, read=action in external_tools._OBJECT_READ_ACTIONS[name],
|
| 66 |
destructive=action in {"delete", "clear"})
|
|
|
|
|
|
|
| 67 |
GROUP["actions"]["read_batch"] = legacy_action("validated_batch", read=True)
|
| 68 |
GROUP["actions"]["write_batch"] = legacy_action("validated_batch", read=False, destructive=True)
|
| 69 |
GROUP["actions"]["workbook.view"] = {
|
|
|
|
| 74 |
"required": ["workbook_id"], "additionalProperties": False},
|
| 75 |
}
|
| 76 |
GROUP["guide"] += " Use workbook.view with workbook_id to open the workbook view."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
GROUP["guide"] += ' Under MCP rule 9, ask "Do you want me to build a Sheet workbook in Loopable?".'
|
| 78 |
_BATCH_GUIDE = (
|
| 79 |
" A batch has 1 to 50 operations for one workbook. Use name and arguments for each operation. "
|
platform/core/external_tools.py
CHANGED
|
@@ -140,6 +140,46 @@ _QUERY_FILTER = {"oneOf": [
|
|
| 140 |
_object({"link": _STRING, "where": _query_filter_node(allow_link=False)},
|
| 141 |
("link", "where"), additionalProperties=False),
|
| 142 |
]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
_BINDING = _object({
|
| 144 |
"database": _STRING,
|
| 145 |
"aggregate": _object({"fn": _STRING, "field": _STRING, "metric_key": _STRING}),
|
|
|
|
| 140 |
_object({"link": _STRING, "where": _query_filter_node(allow_link=False)},
|
| 141 |
("link", "where"), additionalProperties=False),
|
| 142 |
]}
|
| 143 |
+
FILTER_NODE_REF = "#/$defs/filter_node"
|
| 144 |
+
FILTER_NODE_EXAMPLE = {"conj": "and", "nodes": [
|
| 145 |
+
{"colId": "status", "op": "eq", "value": "open"},
|
| 146 |
+
{"conj": "or", "children": [{"colId": "amount", "op": "gt", "value": 100},
|
| 147 |
+
{"colId": "region", "op": "eq", "value": "West"}]},
|
| 148 |
+
]}
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _is_filter_node(value):
|
| 152 |
+
"""Tell a published query filter node from any other schema."""
|
| 153 |
+
branches = value.get("oneOf") if isinstance(value, dict) and set(value) == {"oneOf"} else None
|
| 154 |
+
first = branches[0] if isinstance(branches, list) and branches and isinstance(branches[0], dict) else {}
|
| 155 |
+
properties = first.get("properties")
|
| 156 |
+
return isinstance(properties, dict) and "colId" in properties and "op" in properties
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def guide_schema(schema):
|
| 160 |
+
"""Return a guide copy with each query filter node replaced by one reference, and whether any was."""
|
| 161 |
+
if _is_filter_node(schema):
|
| 162 |
+
return {"$ref": FILTER_NODE_REF}, True
|
| 163 |
+
if isinstance(schema, list):
|
| 164 |
+
pairs = [guide_schema(item) for item in schema]
|
| 165 |
+
return [item for item, _ in pairs], any(used for _, used in pairs)
|
| 166 |
+
if not isinstance(schema, dict):
|
| 167 |
+
return copy.deepcopy(schema), False
|
| 168 |
+
pairs = {key: guide_schema(child) for key, child in schema.items()}
|
| 169 |
+
return {key: item for key, (item, _) in pairs.items()}, any(used for _, used in pairs.values())
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def filter_node_guide():
|
| 173 |
+
"""Return the one markdown section that defines the filter_node reference in a guide."""
|
| 174 |
+
node = {"oneOf": [guide_schema(branch)[0] for branch in _QUERY_FILTER_NODE["oneOf"]]}
|
| 175 |
+
return ("## filter_node\n\n"
|
| 176 |
+
"A filter_node is a condition {colId, op, ...}, a group {conj, children: 1 to 50 filter_node}, "
|
| 177 |
+
"or a link {link, where}.\n"
|
| 178 |
+
"Groups nest at most two deep inside one node. A link's where holds no link.\n"
|
| 179 |
+
"Example filter: `" + json.dumps(FILTER_NODE_EXAMPLE, ensure_ascii=True) + "`\n"
|
| 180 |
+
"```json\n" + json.dumps({"$defs": {"filter_node": node}}, ensure_ascii=True, indent=2) + "\n```")
|
| 181 |
+
|
| 182 |
+
|
| 183 |
_BINDING = _object({
|
| 184 |
"database": _STRING,
|
| 185 |
"aggregate": _object({"fn": _STRING, "field": _STRING, "metric_key": _STRING}),
|
platform/core/grid_events.py
CHANGED
|
@@ -78,9 +78,7 @@ _FIELD_ECHO_PROPS = ('label', 'type', 'note', 'options', 'colorCodeOptions',
|
|
| 78 |
# echo while the route still answers 200 - so the reader sees the change
|
| 79 |
# land and then lose it. `showAs` is a DISPLAY mode, never an aggregate.
|
| 80 |
'showAs',
|
| 81 |
-
'recurrence', 'if'
|
| 82 |
-
# S76-T28: '' , 0 and false are real defaults, so this key compares by type.
|
| 83 |
-
'defaultValue')
|
| 84 |
|
| 85 |
|
| 86 |
class StoreUnavailable(RuntimeError):
|
|
@@ -1103,13 +1101,6 @@ def _field_echo_equal(accepted, raw):
|
|
| 1103 |
empty = ('', [], {})
|
| 1104 |
for k in _FIELD_ECHO_PROPS:
|
| 1105 |
a, b = accepted.get(k), raw.get(k) if isinstance(raw, dict) else None
|
| 1106 |
-
if k == 'defaultValue':
|
| 1107 |
-
# Absence, '', False and 0 render differently, so no empty-collapse and no 0 == False.
|
| 1108 |
-
have = (a is not None, type(a), a) # an explicit null is a clear, stored as absent
|
| 1109 |
-
sent = (b is not None, type(b), b)
|
| 1110 |
-
if have != sent:
|
| 1111 |
-
return False
|
| 1112 |
-
continue
|
| 1113 |
if k == 'scope':
|
| 1114 |
# 'global' and absent are the SAME rendering (an unscoped field) — the event may
|
| 1115 |
# say 'global' explicitly while the stored def says it by omission.
|
|
@@ -2279,19 +2270,6 @@ def handle_one(event, ctx):
|
|
| 2279 |
fmt = _ag2._clean_format(raw.get('format'), ftype)
|
| 2280 |
if fmt:
|
| 2281 |
field['format'] = fmt
|
| 2282 |
-
# S76-T28: explicit null clears a default; omission keeps it only from a same-type definition.
|
| 2283 |
-
if 'defaultValue' in raw:
|
| 2284 |
-
_default = raw.get('defaultValue')
|
| 2285 |
-
else:
|
| 2286 |
-
_prior_def = shared_prior if shared_field else (ws.get('fields') or {}).get(key)
|
| 2287 |
-
_default = (_prior_def.get('defaultValue') if isinstance(_prior_def, dict)
|
| 2288 |
-
and _prior_def.get('type') == ftype else None)
|
| 2289 |
-
if _default is not None:
|
| 2290 |
-
from core import user_tables as _ut_default
|
| 2291 |
-
if readonly or not _ut_default._default_value_valid(field, _default):
|
| 2292 |
-
return _refuse(ctx, 'bad_default_value',
|
| 2293 |
-
'The default value does not fit this field type.', key)
|
| 2294 |
-
field['defaultValue'] = _default
|
| 2295 |
else:
|
| 2296 |
# ⛔ THE FALL-THROUGH, AND IT IS THE WIDEST OF THE EIGHT: the key is neither a base
|
| 2297 |
# contract field (a note/format override) nor a `custom_`/`measure_` key, so there is
|
|
@@ -3684,31 +3662,20 @@ def handle_one(event, ctx):
|
|
| 3684 |
if updates:
|
| 3685 |
if _connector_cells:
|
| 3686 |
# Source refreshes own source rows. Authored cells use the same overlay as REST.
|
| 3687 |
-
|
| 3688 |
-
|
| 3689 |
-
updates
|
| 3690 |
-
|
| 3691 |
-
|
| 3692 |
-
updates =
|
| 3693 |
-
_history_table, pid, updates, st=ctx.table.st)
|
| 3694 |
-
except ValueError as exc:
|
| 3695 |
-
# S76-T33: a registry Link condition refusal keeps its code and reason.
|
| 3696 |
-
return _folder_refuse(ctx, kind, getattr(exc, 'code', None) or 'bad_value',
|
| 3697 |
-
str(exc) or 'The edit was refused.', key=','.join(updates))
|
| 3698 |
elif str(ctx.scope_key or '').startswith('ut_') and ctx.table is not None:
|
| 3699 |
# User-table cells are collaborative record data. Views/layout remain personal,
|
| 3700 |
# but record values live in the definition rows so Links, Rollups, automations,
|
| 3701 |
# and every viewer observe one truth.
|
| 3702 |
import core.user_tables as _ut_values
|
| 3703 |
-
|
| 3704 |
-
_cells_taken = _ut_values.patch_cells(
|
| 3705 |
ctx.scope_key, pid, updates, st=ctx.table.st,
|
| 3706 |
-
by=ctx.by if ctx.by is not None else uname, via=ctx.via)
|
| 3707 |
-
except ValueError as exc:
|
| 3708 |
-
# S76-T29/T33: a core value rule (number policy, Link condition) names its reason.
|
| 3709 |
-
return _folder_refuse(ctx, kind, getattr(exc, 'code', None) or 'number_value_refused',
|
| 3710 |
-
str(exc) or 'The edit was refused.', key=','.join(updates))
|
| 3711 |
-
if not _cells_taken:
|
| 3712 |
updates = {}
|
| 3713 |
refused = True
|
| 3714 |
elif _store_of(ctx).available():
|
|
|
|
| 78 |
# echo while the route still answers 200 - so the reader sees the change
|
| 79 |
# land and then lose it. `showAs` is a DISPLAY mode, never an aggregate.
|
| 80 |
'showAs',
|
| 81 |
+
'recurrence', 'if')
|
|
|
|
|
|
|
| 82 |
|
| 83 |
|
| 84 |
class StoreUnavailable(RuntimeError):
|
|
|
|
| 1101 |
empty = ('', [], {})
|
| 1102 |
for k in _FIELD_ECHO_PROPS:
|
| 1103 |
a, b = accepted.get(k), raw.get(k) if isinstance(raw, dict) else None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1104 |
if k == 'scope':
|
| 1105 |
# 'global' and absent are the SAME rendering (an unscoped field) — the event may
|
| 1106 |
# say 'global' explicitly while the stored def says it by omission.
|
|
|
|
| 2270 |
fmt = _ag2._clean_format(raw.get('format'), ftype)
|
| 2271 |
if fmt:
|
| 2272 |
field['format'] = fmt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2273 |
else:
|
| 2274 |
# ⛔ THE FALL-THROUGH, AND IT IS THE WIDEST OF THE EIGHT: the key is neither a base
|
| 2275 |
# contract field (a note/format override) nor a `custom_`/`measure_` key, so there is
|
|
|
|
| 3662 |
if updates:
|
| 3663 |
if _connector_cells:
|
| 3664 |
# Source refreshes own source rows. Authored cells use the same overlay as REST.
|
| 3665 |
+
if choice_additions:
|
| 3666 |
+
updates = _connector_overlay.put_cells_and_choice_options(
|
| 3667 |
+
_history_table, pid, updates, choice_additions, st=ctx.table.st)
|
| 3668 |
+
else:
|
| 3669 |
+
updates = _connector_overlay.put_cells(
|
| 3670 |
+
_history_table, pid, updates, st=ctx.table.st)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3671 |
elif str(ctx.scope_key or '').startswith('ut_') and ctx.table is not None:
|
| 3672 |
# User-table cells are collaborative record data. Views/layout remain personal,
|
| 3673 |
# but record values live in the definition rows so Links, Rollups, automations,
|
| 3674 |
# and every viewer observe one truth.
|
| 3675 |
import core.user_tables as _ut_values
|
| 3676 |
+
if not _ut_values.patch_cells(
|
|
|
|
| 3677 |
ctx.scope_key, pid, updates, st=ctx.table.st,
|
| 3678 |
+
by=ctx.by if ctx.by is not None else uname, via=ctx.via):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3679 |
updates = {}
|
| 3680 |
refused = True
|
| 3681 |
elif _store_of(ctx).available():
|
platform/core/sheet_compat.py
CHANGED
|
@@ -48,12 +48,6 @@ _FPA = ".agents/skills/refresh-fpa/SKILL.md"
|
|
| 48 |
# The evidence references are intentionally literal and machine-readable. Section 26 of the
|
| 49 |
# Sheet gate re-censuses the source operations and requires every token to land on one row here.
|
| 50 |
_OPERATIONS = (
|
| 51 |
-
_cap("workbook.list", True, "List(cursor=None, page_size=100)",
|
| 52 |
-
"Pages every readable workbook's id, name and revision through the existing workbook permission resolver.",
|
| 53 |
-
["aios-web/api/verify_sheet.py:section_s76_t47_workbook_discovery"]),
|
| 54 |
-
_cap("workbook.get", True, "Get(workbook_id | name)",
|
| 55 |
-
"Resolves a readable workbook by stable id or exact case-insensitive name, with readable close-name suggestions.",
|
| 56 |
-
["aios-web/api/verify_api.py:section_s76_t47_workbook_discovery"]),
|
| 57 |
_cap("workbooks.open", True, "Open(id_or_name, UpdateLinks=0, ReadOnly=False)",
|
| 58 |
"Looks up one existing workbook by stable id, then exact case-insensitive name.",
|
| 59 |
[f"{_SALES}:421", f"{_FPA}:153"]),
|
|
@@ -892,76 +886,6 @@ def execute(st, workbook_id, operation, arguments=None, *, actor="", actor_name=
|
|
| 892 |
return out
|
| 893 |
|
| 894 |
|
| 895 |
-
OBJECT_OPERATIONS = frozenset({"workbook.list", "workbook.get"})
|
| 896 |
-
|
| 897 |
-
|
| 898 |
-
def dispatch_object_operation(*, session, object_name, action, arguments):
|
| 899 |
-
"""Discover workbook identities through the same role resolver as the Sheet index."""
|
| 900 |
-
import difflib
|
| 901 |
-
|
| 902 |
-
operation = str(object_name) + "." + str(action)
|
| 903 |
-
if operation not in OBJECT_OPERATIONS:
|
| 904 |
-
raise CompatibilityRefusal("tool_capability_unsupported", "This Sheet action is not available yet.")
|
| 905 |
-
require_supported(operation)
|
| 906 |
-
session.require("sheets")
|
| 907 |
-
options = arguments.get("arguments") or {}
|
| 908 |
-
if not isinstance(options, dict):
|
| 909 |
-
raise CompatibilityRefusal("tool_arguments_invalid", "Workbook lookup arguments must be an object.")
|
| 910 |
-
st = session.runtime
|
| 911 |
-
visible = sheets.project_shares(st, sheets.list_workbooks(st), session.uname, is_admin=session.admin)
|
| 912 |
-
visible.sort(key=lambda row: str(row["id"]))
|
| 913 |
-
|
| 914 |
-
def identity(row):
|
| 915 |
-
return {"id": row["id"], "name": row["name"], "rev": row["rev"]}
|
| 916 |
-
|
| 917 |
-
if action == "list":
|
| 918 |
-
size = options.get("page_size", 100)
|
| 919 |
-
if type(size) is not int or size < 1:
|
| 920 |
-
raise CompatibilityRefusal("tool_arguments_invalid", "Workbook page_size must be a positive integer.")
|
| 921 |
-
cursor = options.get("cursor")
|
| 922 |
-
principal = [str(session.tenant), str(session.uname).casefold()]
|
| 923 |
-
after = ""
|
| 924 |
-
if cursor is not None:
|
| 925 |
-
try:
|
| 926 |
-
if not isinstance(cursor, str) or not cursor:
|
| 927 |
-
raise ValueError("empty cursor")
|
| 928 |
-
position = json.loads(base64.b64decode(cursor + "=" * (-len(cursor) % 4), altchars=b"-_", validate=True))
|
| 929 |
-
if (not isinstance(position, dict) or position.get("principal") != principal
|
| 930 |
-
or not isinstance(position.get("after"), str) or not position["after"]):
|
| 931 |
-
raise ValueError("invalid cursor")
|
| 932 |
-
after = position["after"]
|
| 933 |
-
except (ValueError, TypeError, UnicodeError) as exc:
|
| 934 |
-
raise CompatibilityRefusal("tool_arguments_invalid", "That workbook cursor is invalid. Start a new list.") from exc
|
| 935 |
-
remaining = [row for row in visible if str(row["id"]) > after]
|
| 936 |
-
page = remaining[:size]
|
| 937 |
-
next_cursor = None
|
| 938 |
-
if len(remaining) > len(page):
|
| 939 |
-
next_cursor = base64.urlsafe_b64encode(json.dumps({
|
| 940 |
-
"principal": principal, "after": str(page[-1]["id"])
|
| 941 |
-
}, separators=(",", ":")).encode()).decode().rstrip("=")
|
| 942 |
-
return {"workbooks": [identity(row) for row in page], "next_cursor": next_cursor, "total": len(visible)}
|
| 943 |
-
|
| 944 |
-
target = arguments.get("workbook_id") or options.get("workbook_id") or options.get("name") or options.get("id_or_name")
|
| 945 |
-
if not isinstance(target, str) or not target.strip():
|
| 946 |
-
raise CompatibilityRefusal("tool_arguments_invalid", "Choose a workbook_id or an exact workbook name.")
|
| 947 |
-
target = target.strip()
|
| 948 |
-
matches = [row for row in visible if row["id"] == target]
|
| 949 |
-
if not matches:
|
| 950 |
-
matches = [row for row in visible if str(row["name"]).casefold() == target.casefold()]
|
| 951 |
-
if len(matches) > 1:
|
| 952 |
-
raise CompatibilityRefusal("workbook_unavailable", "More than one readable workbook has that exact name. Choose its workbook_id.")
|
| 953 |
-
if matches:
|
| 954 |
-
book = sheets.get_workbook(st, matches[0]["id"])
|
| 955 |
-
if sheets.may_read_workbook(book, sheets.workbook_role(st, book, session.uname, is_admin=session.admin)):
|
| 956 |
-
return {"workbook": identity(book)}
|
| 957 |
-
names = {str(row["name"]).casefold(): str(row["name"]) for row in visible}
|
| 958 |
-
close = difflib.get_close_matches(target.casefold(), list(names), n=5, cutoff=0.5)
|
| 959 |
-
reason = "That workbook is not available to this account."
|
| 960 |
-
if close:
|
| 961 |
-
reason += " Close names: " + ", ".join(names[name] for name in close) + ". Use an exact name."
|
| 962 |
-
raise CompatibilityRefusal("workbook_missing", reason)
|
| 963 |
-
|
| 964 |
-
|
| 965 |
def dispatch_validated_batch(*, runtime, operations, staging, dispatch, actor="", actor_name=""):
|
| 966 |
"""Stage native Sheet operations, then publish one workbook revision through its guarded writer."""
|
| 967 |
if not isinstance(operations, list) or not 1 <= len(operations) <= 50:
|
|
|
|
| 48 |
# The evidence references are intentionally literal and machine-readable. Section 26 of the
|
| 49 |
# Sheet gate re-censuses the source operations and requires every token to land on one row here.
|
| 50 |
_OPERATIONS = (
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
_cap("workbooks.open", True, "Open(id_or_name, UpdateLinks=0, ReadOnly=False)",
|
| 52 |
"Looks up one existing workbook by stable id, then exact case-insensitive name.",
|
| 53 |
[f"{_SALES}:421", f"{_FPA}:153"]),
|
|
|
|
| 886 |
return out
|
| 887 |
|
| 888 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 889 |
def dispatch_validated_batch(*, runtime, operations, staging, dispatch, actor="", actor_name=""):
|
| 890 |
"""Stage native Sheet operations, then publish one workbook revision through its guarded writer."""
|
| 891 |
if not isinstance(operations, list) or not 1 <= len(operations) <= 50:
|
platform/core/table_store.py
CHANGED
|
@@ -1528,7 +1528,6 @@ class TableStore:
|
|
| 1528 |
if k not in ('filters', 'filterConj', 'memberPids')},
|
| 1529 |
}
|
| 1530 |
def _up(data, audit):
|
| 1531 |
-
record['updatedAt'] = write_execution.utcnow().isoformat()
|
| 1532 |
bucket = data.setdefault(ASSIGNED_KEY, {}).setdefault('views', {})
|
| 1533 |
bucket.setdefault(who, {})[assignment_id] = record
|
| 1534 |
# ⭐ W50-T25 — C3's `share` action. The audit `owner` is the SOURCE VIEW's owner,
|
|
@@ -1667,8 +1666,6 @@ class TableStore:
|
|
| 1667 |
)
|
| 1668 |
payload = dict(requested)
|
| 1669 |
payload['name'] = _unique_name(payload.get('name'), names)
|
| 1670 |
-
# S76-T37: the server stamps every View update; a client-sent updatedAt is never kept.
|
| 1671 |
-
payload['updatedAt'] = write_execution.utcnow().isoformat()
|
| 1672 |
accepted.clear()
|
| 1673 |
accepted.update(payload)
|
| 1674 |
ws = data.setdefault(username, {})
|
|
@@ -2011,7 +2008,6 @@ class TableStore:
|
|
| 2011 |
payload = dict(entry.get('view') or {})
|
| 2012 |
payload['id'] = vid
|
| 2013 |
payload['name'] = _unique_name(payload.get('name'), names)
|
| 2014 |
-
payload['updatedAt'] = write_execution.utcnow().isoformat()
|
| 2015 |
data.setdefault(owner, {}).setdefault('views', {})[vid] = payload
|
| 2016 |
carried = entry.get('assignments')
|
| 2017 |
if isinstance(carried, dict) and carried:
|
|
|
|
| 1528 |
if k not in ('filters', 'filterConj', 'memberPids')},
|
| 1529 |
}
|
| 1530 |
def _up(data, audit):
|
|
|
|
| 1531 |
bucket = data.setdefault(ASSIGNED_KEY, {}).setdefault('views', {})
|
| 1532 |
bucket.setdefault(who, {})[assignment_id] = record
|
| 1533 |
# ⭐ W50-T25 — C3's `share` action. The audit `owner` is the SOURCE VIEW's owner,
|
|
|
|
| 1666 |
)
|
| 1667 |
payload = dict(requested)
|
| 1668 |
payload['name'] = _unique_name(payload.get('name'), names)
|
|
|
|
|
|
|
| 1669 |
accepted.clear()
|
| 1670 |
accepted.update(payload)
|
| 1671 |
ws = data.setdefault(username, {})
|
|
|
|
| 2008 |
payload = dict(entry.get('view') or {})
|
| 2009 |
payload['id'] = vid
|
| 2010 |
payload['name'] = _unique_name(payload.get('name'), names)
|
|
|
|
| 2011 |
data.setdefault(owner, {}).setdefault('views', {})[vid] = payload
|
| 2012 |
carried = entry.get('assignments')
|
| 2013 |
if isinstance(carried, dict) and carried:
|
web/public/AIOS_DEPLOY_RECEIPT
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
|
|
|
|
| 1 |
+
3860b2103007bea62cccf6249230c80ce9f6f5b35c01af56ed6ea30aa116dcee
|
web/s71_frontend_contracts.py
CHANGED
|
@@ -64,53 +64,6 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
|
|
| 64 |
import json
|
| 65 |
from playwright.sync_api import sync_playwright
|
| 66 |
from verify_w45_data_applications import AppRoutingFixture
|
| 67 |
-
from verify_catalog import s76_t09_fixture_record, s76_t09_template_registry
|
| 68 |
-
|
| 69 |
-
class CatalogHostFixture(AppRoutingFixture):
|
| 70 |
-
def __init__(self):
|
| 71 |
-
super().__init__()
|
| 72 |
-
self.catalog = s76_t09_fixture_record()
|
| 73 |
-
self.catalog["pages"][3]["bindings"]["products"] = ["WF-1", "CS-2"]
|
| 74 |
-
self.typed_cursors = []
|
| 75 |
-
self.fields.extend([{"key": key, "label": key, "type": kind, "source": "odoo"}
|
| 76 |
-
for key, kind in (("stock", "text"), ("list_price", "int"),
|
| 77 |
-
("category", "text"), ("description", "text"))])
|
| 78 |
-
self.applications[0]["fieldMap"].update(sku="stock", price="list_price",
|
| 79 |
-
category="category", description="description")
|
| 80 |
-
for row in self.rows:
|
| 81 |
-
row.update(stock="Mapped sku", list_price=19.975,
|
| 82 |
-
category="Mapped category", description="Mapped description")
|
| 83 |
-
self.original_workspace = __import__("copy").deepcopy(self.workspace)
|
| 84 |
-
|
| 85 |
-
def route(self, route):
|
| 86 |
-
from urllib.parse import urlsplit
|
| 87 |
-
request = route.request
|
| 88 |
-
path = urlsplit(request.url).path.removeprefix("/api/v1/")
|
| 89 |
-
result = None
|
| 90 |
-
if path == "typed/openapi.json":
|
| 91 |
-
properties = {field["key"]: {"type": "number" if field["type"] == "int" else "string"}
|
| 92 |
-
for field in self.fields}
|
| 93 |
-
properties["pid"] = {"type": "integer"}
|
| 94 |
-
result = {"components": {"schemas": {"Record_customer_data": {"properties": properties}}}}
|
| 95 |
-
elif path == "typed/databases/customer_data/query":
|
| 96 |
-
body = request.post_data_json
|
| 97 |
-
self.typed_cursors.append(body.get("cursor"))
|
| 98 |
-
if not self.rows:
|
| 99 |
-
result = {"database": self.database, "fields": self.fields, "records": [],
|
| 100 |
-
"page": {"returned": 0, "has_more": False, "next_cursor": None}}
|
| 101 |
-
elif request.method == "GET" and path == "apps/app-fixture/catalogs":
|
| 102 |
-
result = {"catalogs": [self.catalog] if self.catalog else [], "nextCursor": None}
|
| 103 |
-
elif request.method == "GET" and path == "catalogs/catalog-six":
|
| 104 |
-
result = {"catalog": self.catalog}
|
| 105 |
-
elif request.method == "GET" and path == "catalogs/templates":
|
| 106 |
-
result = s76_t09_template_registry()
|
| 107 |
-
result["kinds"][3]["templates"][0]["slots"] = [
|
| 108 |
-
"title", "body", "products", "price", "sku", "category", "description"]
|
| 109 |
-
if result is None:
|
| 110 |
-
return super().route(route)
|
| 111 |
-
self.requests.append({"path": path, "method": request.method})
|
| 112 |
-
route.fulfill(status=200, content_type="application/json", body=json.dumps(result))
|
| 113 |
-
|
| 114 |
out_dir.mkdir(parents=True, exist_ok=True)
|
| 115 |
evidence = {"checks": [], "controls": [], "errors": []}
|
| 116 |
def check(name, value):
|
|
@@ -123,16 +76,12 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
|
|
| 123 |
with sync_playwright() as playwright:
|
| 124 |
browser = playwright.chromium.launch(headless=True)
|
| 125 |
try:
|
| 126 |
-
cases = ['catalog'
|
| 127 |
for case in cases:
|
| 128 |
-
fixture =
|
| 129 |
-
if case == 'empty-source':
|
| 130 |
-
fixture.rows = []
|
| 131 |
-
fixture.catalog = None
|
| 132 |
-
fixture.applications[0]['capabilities']['edit'] = True
|
| 133 |
fixture.legacy_unavailable = True
|
| 134 |
fixture.hold_registry = True
|
| 135 |
-
context = browser.new_context(viewport={"width":
|
| 136 |
context.add_init_script("""window.catalogRouteListeners = [];
|
| 137 |
const ordinaryAdd = window.addEventListener;
|
| 138 |
window.addEventListener = function(type, ...args) {
|
|
@@ -141,7 +90,7 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
|
|
| 141 |
};""")
|
| 142 |
context.route('**/api/**', fixture.route)
|
| 143 |
applied = []
|
| 144 |
-
if case
|
| 145 |
old, new = ('applicationTemplateSurface(resolvedApplication) !== "catalog"', 'true') if case == 'settings-discriminator' \
|
| 146 |
else ('rowsEnabled: legacyRowsEnabled', 'rowsEnabled: true') if case == 'legacy-loader' \
|
| 147 |
else (r'if \(!routeApplicationSurface\) return;\s*const openRoute', 'const openRoute')
|
|
@@ -186,19 +135,7 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
|
|
| 186 |
continue
|
| 187 |
check('held registry has no legacy rows', not early_legacy)
|
| 188 |
fixture.release_registry()
|
| 189 |
-
page.locator('.cg-
|
| 190 |
-
check('Catalog library withholds source footer', page.locator('.cg-grid-footer, .cg-sum-bar').count() == 0)
|
| 191 |
-
if case == 'empty-source':
|
| 192 |
-
check('empty source opens the empty library', page.get_by_text('No catalogs yet', exact=True).count() == 1
|
| 193 |
-
and page.get_by_role('button', name='New catalog', exact=True).count() == 1
|
| 194 |
-
and page.locator('.cg-catalog-library-card').count() == 0)
|
| 195 |
-
check('empty source preserves the saved View', not fixture.view_events
|
| 196 |
-
and fixture.workspace == fixture.original_workspace)
|
| 197 |
-
page.screenshot(path=str(out_dir / 'catalog-empty-source.png'), full_page=True)
|
| 198 |
-
continue
|
| 199 |
-
page.get_by_role('button', name='Open Seasonal collection', exact=True).click()
|
| 200 |
-
page.locator('.cg-catalog-page-thumb[data-page-kind="grid"]').click()
|
| 201 |
-
page.locator('.cg-catalog-canvas .cg-catalog-product-open').first.wait_for(timeout=30000)
|
| 202 |
page.wait_for_timeout(600)
|
| 203 |
if case == 'settings-discriminator':
|
| 204 |
check('Catalog discriminator removal fails controls absence', bool(applied) and not no_controls(page))
|
|
@@ -206,40 +143,13 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
|
|
| 206 |
continue
|
| 207 |
check('resolved Catalog has no Map/Bubble size/Routes', no_controls(page))
|
| 208 |
check('resolved Catalog registers no route-open handler', page.evaluate('window.catalogRouteListeners.length') == 0)
|
| 209 |
-
check('
|
| 210 |
-
page.locator('.cg-catalog-page-thumb').evaluate_all("nodes => nodes.map(node => node.dataset.pageKind)")
|
| 211 |
-
== ['cover', 'toc', 'product', 'grid', 'section', 'closing'])
|
| 212 |
-
check('typed pool walks both cursor pages', None in fixture.typed_cursors
|
| 213 |
-
and 'fixture-next' in fixture.typed_cursors)
|
| 214 |
-
check('all cursor pages painted', sorted(page.locator('.cg-catalog-canvas .cg-catalog-product-open').evaluate_all(
|
| 215 |
-
"nodes => nodes.map(node => node.getAttribute('aria-label').slice(5))"))
|
| 216 |
== ['Cedar Supply', 'Willow Floral'])
|
| 217 |
-
before = page.locator('.cg-
|
| 218 |
-
evidence['mapped_products'] = before
|
| 219 |
-
check('Catalog registry keeps every optional product role',
|
| 220 |
-
all(value in before for value in
|
| 221 |
-
('19.975', 'Mapped sku', 'Mapped category', 'Mapped description')))
|
| 222 |
page.evaluate("window.dispatchEvent(new CustomEvent('aios:route-open', {detail:{routeId:'refused-route'}}))")
|
| 223 |
page.wait_for_timeout(200)
|
| 224 |
-
check('Catalog ignores route-open', no_controls(page) and page.locator('.cg-
|
| 225 |
-
|
| 226 |
-
if case == 'mobile':
|
| 227 |
-
geometry = page.locator('.cg-catalog-canvas').bounding_box()
|
| 228 |
-
check('390px editor keeps a usable full-width canvas', geometry is not None
|
| 229 |
-
and geometry['width'] >= 250 and geometry['x'] + geometry['width'] <= 391)
|
| 230 |
-
check('390px editor preserves the shared App frame',
|
| 231 |
-
page.locator('.cg-app-frame-header').count() == 1
|
| 232 |
-
and page.get_by_role('link', name='Back to Apps', exact=True).count() == 1)
|
| 233 |
-
heading = page.locator('.cg-catalog-record-head h2').evaluate(
|
| 234 |
-
'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};}')
|
| 235 |
-
actions = page.locator('.cg-catalog-record-head button').evaluate_all(
|
| 236 |
-
'nodes => nodes.map(node => {const r=node.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height};})')
|
| 237 |
-
check('390px catalog title does not overlap its actions', len(actions) >= 3 and all(
|
| 238 |
-
heading['x'] + heading['width'] <= action['x'] or action['x'] + action['width'] <= heading['x']
|
| 239 |
-
or heading['y'] + heading['height'] <= action['y'] or action['y'] + action['height'] <= heading['y']
|
| 240 |
-
for action in actions))
|
| 241 |
-
page.screenshot(path=str(out_dir / 'catalog-editor-390.png'), full_page=True)
|
| 242 |
-
page.locator('.cg-catalog-canvas').get_by_role('button', name='Open Cedar Supply', exact=True).click()
|
| 243 |
page.locator('.cg-record-modal').wait_for(timeout=10000)
|
| 244 |
check('real typed tail card drawer', 'Cedar Supply' in page.locator('.cg-record-modal').inner_text())
|
| 245 |
check('unavailable legacy endpoint never requested', not any(request['path'] == 'customers' for request in fixture.requests))
|
|
@@ -248,15 +158,10 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
|
|
| 248 |
page.screenshot(path=str(out_dir / 'catalog-cold-drawer.png'), full_page=True)
|
| 249 |
finally:
|
| 250 |
context.close()
|
| 251 |
-
for surface in ('data-map', 'route'
|
| 252 |
fixture = AppRoutingFixture()
|
| 253 |
fixture.config['display'] = {'mode': 'map'}
|
| 254 |
fixture.workspace['views'][0]['config']['display'] = {'mode': 'map'}
|
| 255 |
-
if surface == 'legacy-catalog':
|
| 256 |
-
display = {'mode': 'catalog',
|
| 257 |
-
'catalogs': fixture.applications[0]['config']['display']['catalogs']}
|
| 258 |
-
fixture.config['display'] = display
|
| 259 |
-
fixture.workspace['views'][0]['config']['display'] = display
|
| 260 |
fixture.original_workspace = __import__('copy').deepcopy(fixture.workspace)
|
| 261 |
if surface == 'route':
|
| 262 |
fixture.fields.extend([{'key': 'lat', 'label': 'Latitude', 'type': 'number', 'source': 'odoo'},
|
|
@@ -266,24 +171,14 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
|
|
| 266 |
fixture.applications[0]['templateKind'] = 'route'
|
| 267 |
fixture.applications[0]['fieldMap'] = {'title': 'name', 'latitude': 'lat', 'longitude': 'lon'}
|
| 268 |
fixture.applications[0]['config'] = {'display': {'mode': 'map'}}
|
| 269 |
-
context = browser.new_context(viewport={"width":
|
| 270 |
context.route('**/api/**', fixture.route)
|
| 271 |
# Keep the product's offline map; a synthetic transport cannot make an outward tile read.
|
| 272 |
context.route('https://tile.openstreetmap.org/**', lambda route: route.abort())
|
| 273 |
page = context.new_page()
|
| 274 |
try:
|
| 275 |
-
page.goto(base_url + ('/#/data?database=customer_data&view=saved-check' if surface
|
| 276 |
else '/#/app?database=customer_data&application=app-fixture'))
|
| 277 |
-
if surface == 'legacy-catalog':
|
| 278 |
-
page.locator('.cg-cat-stage').wait_for(timeout=30000)
|
| 279 |
-
stage = page.locator('.cg-cat-stage').bounding_box()
|
| 280 |
-
rail = page.locator('.cg-cat-rail').bounding_box()
|
| 281 |
-
check('390px legacy rail collapses above a usable page', stage is not None and rail is not None
|
| 282 |
-
and stage['width'] >= 200 and stage['x'] + stage['width'] <= 391
|
| 283 |
-
and rail['height'] <= 129 and stage['y'] >= rail['y'] + rail['height'])
|
| 284 |
-
check('Data Catalog keeps its own footer', page.locator('.cg-grid-footer').count() == 1)
|
| 285 |
-
page.screenshot(path=str(out_dir / 'catalog-legacy-390.png'), full_page=True)
|
| 286 |
-
continue
|
| 287 |
page.locator('.cg-map-settings').wait_for(timeout=30000)
|
| 288 |
check(surface + ' keeps Map settings', page.get_by_text('Bubble size', exact=True).count() > 0)
|
| 289 |
if surface == 'route':
|
|
@@ -302,213 +197,3 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
|
|
| 302 |
(out_dir / 'catalog-host.json').write_text(json.dumps(evidence, indent=2), encoding='utf-8')
|
| 303 |
print(f"PASS S71 Catalog host mounted: {len(evidence['checks'])} checks, {len(evidence['controls'])} controls")
|
| 304 |
return evidence
|
| 305 |
-
|
| 306 |
-
def client_amend_contracts() -> int:
|
| 307 |
-
"""Execute the edited callbacks with held acknowledgements and whole-batch refusals."""
|
| 308 |
-
import subprocess
|
| 309 |
-
script = r'''
|
| 310 |
-
const fs = require("fs"), vm = require("vm"), ts = require("typescript"), assert = require("node:assert/strict");
|
| 311 |
-
const grid = ts.createSourceFile("grid.tsx", fs.readFileSync("src/customer-grid/CustomerGrid.tsx", "utf8"), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
| 312 |
-
const bridge = ts.createSourceFile("bridge.ts", fs.readFileSync("src/customer-grid/apiBridge.ts", "utf8"), ts.ScriptTarget.Latest, true);
|
| 313 |
-
const display = ts.createSourceFile("display.ts", fs.readFileSync("src/customer-grid/display.ts", "utf8"), ts.ScriptTarget.Latest, true);
|
| 314 |
-
let checks = 0;
|
| 315 |
-
function check(value, why) { assert.ok(value, why); checks++; }
|
| 316 |
-
function declaration(file, name) {
|
| 317 |
-
let found;
|
| 318 |
-
function visit(node) {
|
| 319 |
-
if ((ts.isVariableDeclaration(node) || ts.isFunctionDeclaration(node)) && node.name?.getText(file) === name) found = node;
|
| 320 |
-
ts.forEachChild(node, visit);
|
| 321 |
-
}
|
| 322 |
-
visit(file); assert.ok(found, "missing executable " + name);
|
| 323 |
-
return ts.isVariableDeclaration(found) ? "const " + found.getText(file) + ";" : found.getText(file).replace(/^export\s+/, "");
|
| 324 |
-
}
|
| 325 |
-
function bind(name, context, file = grid) {
|
| 326 |
-
const source = declaration(file, name) + "\nglobalThis.subject = " + name + ";";
|
| 327 |
-
const js = ts.transpileModule(source, {compilerOptions:{target:ts.ScriptTarget.ES2022, module:ts.ModuleKind.CommonJS}}).outputText;
|
| 328 |
-
const box = {useCallback: fn => fn, ...context};
|
| 329 |
-
vm.runInNewContext(js, box); return box.subject;
|
| 330 |
-
}
|
| 331 |
-
function pure(name, context = {}, file = grid) { return bind(name, context, file); }
|
| 332 |
-
async function run() {
|
| 333 |
-
const numericOrUndefined = pure("numericOrUndefined", {}, display);
|
| 334 |
-
const numberWriteRefusal = pure("numberWriteRefusal", {numericOrUndefined}, display);
|
| 335 |
-
const numberBatchRefusal = pure("numberBatchRefusal", {numberWriteRefusal});
|
| 336 |
-
const number = {key:"amount", label:"Amount", type:"currency", format:{currencySymbol:"EUR", allowNegative:false}};
|
| 337 |
-
const fields = [number, {key:"note",label:"Note",type:"text"}];
|
| 338 |
-
const writes = [], entries = [], toasts = [];
|
| 339 |
-
const ctx = {fields, numberBatchRefusal, currentValue:()=> "before",
|
| 340 |
-
patchOverlay:(...args)=>writes.push(args), recordCells:(...args)=>entries.push(args),
|
| 341 |
-
TOAST_EVENT:"toast", CustomEvent: class {constructor(type, init) {this.type=type;this.detail=init.detail;}},
|
| 342 |
-
window:{dispatchEvent:event=>toasts.push(event)}};
|
| 343 |
-
const single = bind("patchAndRecord", ctx), batch = bind("patchManyAndRecord", ctx);
|
| 344 |
-
single(1, {amount:"-1",note:"must stay unchanged"});
|
| 345 |
-
check(writes.length === 0 && entries.length === 0 && toasts.at(-1).detail.tone === "error", "single negative is a C4 refusal before writes or undo");
|
| 346 |
-
batch([{pid:1,updates:{amount:"5"}},{pid:2,updates:{amount:"Infinity"}}], "paste");
|
| 347 |
-
check(writes.length === 0 && entries.length === 0, "mixed valid and invalid paste is atomic");
|
| 348 |
-
for (const value of ["", "0", "125.6789"]) single(1, {amount:value});
|
| 349 |
-
check(writes.length === 3 && entries.length === 3, "blank, zero and unrounded valid writes retain undo");
|
| 350 |
-
const changedFields = [{...number, format:{...number.format, allowNegative:true}}];
|
| 351 |
-
bind("patchAndRecord", {...ctx,fields:changedFields})(1,{amount:"-5"});
|
| 352 |
-
check(writes.length === 4, "current field policy admits a valid negative");
|
| 353 |
-
let fetched = 0, closed = 0, busy = 0;
|
| 354 |
-
const noop = () => {};
|
| 355 |
-
await bind("applyBulkUpdate", {...ctx, bulkField:number,bulkSelectedCount:20,bulkValue:"-2",
|
| 356 |
-
clearSelection:noop,dropTableRowsCache:noop,patchManyAndRecord:batch,requestWindow:noop,scope:"ut_fixture",
|
| 357 |
-
selectedPids:new Set([1]),serverBulkPending:false,serverFilteredSelection:{token:"selection"},
|
| 358 |
-
windowRequest:noop,setServerBulkPending:()=>busy++,setBulkUpdateOpen:()=>closed++,fetch:()=>fetched++})();
|
| 359 |
-
check(fetched === 0 && closed === 0 && busy === 0, "server filtered bulk refuses before request, busy state or dialog dismissal");
|
| 360 |
-
const buildOverlayField = pure("buildOverlayField", {DEFAULT_SUMMED_TYPES:[],slugify:pure("slugify")});
|
| 361 |
-
for (const value of [0,false,""]) check(buildOverlayField("Default","text",[],{defaultValue:value}).defaultValue === value, "falsy default survives constructor");
|
| 362 |
-
check(Object.hasOwn(buildOverlayField("Clear","text",[],{defaultValue:null}),"defaultValue"), "explicit default clear retains property presence");
|
| 363 |
-
const createdDefinitions = [];
|
| 364 |
-
let createdFields = [];
|
| 365 |
-
const create = bind("createField",{canAddField:true,scopeChoice:false,isUserTable:true,scope:"ut_fixture",
|
| 366 |
-
buildOverlayField,insertColumn:noop,saveField:()=>{throw Error("wrong definition door");},stampFieldEdit:noop,stampFieldDelete:noop,
|
| 367 |
-
setFields:update=>{createdFields=update(createdFields);},
|
| 368 |
-
addTableField:(_scope,definition)=>{createdDefinitions.push(definition);return new Promise(()=>{});}});
|
| 369 |
-
for (const [kind,value] of [["text",""],["int",0],["checkbox",false],["text",null]])
|
| 370 |
-
create("Default",kind,null,"end",undefined,undefined,{defaultValue:value});
|
| 371 |
-
check(createdDefinitions.slice(0,4).map(field=>JSON.stringify(field.defaultValue)).join() === '"",0,false,null',
|
| 372 |
-
"field creation forwards blank, zero, false and explicit clear through the definition body");
|
| 373 |
-
create("Choice","select",null,"end",["Active"],undefined,{defaultValue:"Active"});
|
| 374 |
-
create("Date","date",null,"end",undefined,undefined,{defaultValue:"2026-10-19"});
|
| 375 |
-
check(createdDefinitions[4].defaultValue === "Active" && createdDefinitions[5].defaultValue === "2026-10-19",
|
| 376 |
-
"select and date defaults use the same field creation body");
|
| 377 |
-
const patches = [];
|
| 378 |
-
const old = {key:"amount",label:"Amount",type:"int",source:"overlay",custom:true,defaultValue:0};
|
| 379 |
-
const retype = bind("retypeField", {fieldByKey:new Map([["amount",old]]),saveField:()=>{throw Error("wrong definition door");},
|
| 380 |
-
scope:"ut_fixture",isUserTable:true,emitHostEvent:noop,isUserSchemaField:()=>true,
|
| 381 |
-
patchTableField:async(_scope,_key,patch)=>{patches.push(patch);return null;},setFields:noop,signal:noop});
|
| 382 |
-
retype("amount","int"); retype("amount","int",[],{defaultValue:null});
|
| 383 |
-
check(patches[0].defaultValue === 0 && patches[1].defaultValue === null, "retype preserves zero or sends explicit clear on the schema PATCH");
|
| 384 |
-
let pending = [], overlays = {}, undo = {past:[],future:[]}, resolveAdd, request;
|
| 385 |
-
const scope = "ut_fixture", workspaceScopeRef = {current:scope};
|
| 386 |
-
const setPendingRows = update => {pending = update(pending);};
|
| 387 |
-
const setOverlayEdits = update => {overlays = update(overlays);};
|
| 388 |
-
const acceptPendingRow = bind("acceptPendingRow",{scope,workspaceScopeRef,setPendingRows,setOverlayEdits});
|
| 389 |
-
const undoBook = {current:{}}, stackFor=()=>undo, pushUndo=(_state,entry)=>{undo={...undo,past:[...undo.past,entry]};return undo;};
|
| 390 |
-
const defaults = [{key:"name",type:"text",defaultValue:"base"},{key:"zero",type:"int",defaultValue:0},
|
| 391 |
-
{key:"tick",type:"checkbox",defaultValue:false},{key:"choice",type:"select",defaultValue:"Active"},
|
| 392 |
-
{key:"starts",type:"date",defaultValue:"2026-11-01"},{key:"date",type:"date",defaultValue:"2026-10-19"},{key:"denied",type:"text",defaultValue:"hidden",denied:true}];
|
| 393 |
-
const append = bind("appendRow", {canMutateRecords:true,scope,seedValues:()=>({name:"seed",date:""}),mintRid:()=>7,
|
| 394 |
-
fields:defaults,payload:{viewer:{username:"qa"}},mayEditField:field=>!field.denied,
|
| 395 |
-
setPendingRows,setNewRowPid:noop,addTableRow:(...args)=>{request=args;return new Promise(resolve=>{resolveAdd=resolve;});},
|
| 396 |
-
acceptPendingRow,workspaceScopeRef,undoBook,stackFor,pushUndo});
|
| 397 |
-
const adding = append();
|
| 398 |
-
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"
|
| 399 |
-
&& !Object.hasOwn(pending[0],"denied"), "authorized defaults paint immediately below explicit seeds");
|
| 400 |
-
check(request[1].zero === "0" && request[1].tick === "False" && request.length === 3, "append sends painted defaults with ordinary restore=false call");
|
| 401 |
-
overlays[7]={name:"typed while pending"};
|
| 402 |
-
resolveAdd({rid:"8",pid:8,values:{name:"server",sequence:"51",creator:"qa"}});
|
| 403 |
-
await adding;
|
| 404 |
-
check(pending[0].pid === 8 && pending[0].sequence === "51" && overlays[8].name === "typed while pending" && !overlays[7],
|
| 405 |
-
"acknowledgement supplies generated cells and moves later local overlay to returned identity");
|
| 406 |
-
check(undo.past[0].rows[0].values.zero === "0" && undo.past[0].rows[0].rid === "8", "append undo captures defaults and accepted identity");
|
| 407 |
-
const stale = [], restores = [], deleted = [];
|
| 408 |
-
const restoreEntry = {kind:"rowAdd",table:scope,rows:[{rid:"9",values:{name:"restored",sequence:"old",creator:"forged",modified:"old",modifier:"forged"}}]};
|
| 409 |
-
let resolveRestore;
|
| 410 |
-
const restoreRowsRef = {current:[]};
|
| 411 |
-
const applyEntry = bind("applyEntry", {fields:[{key:"sequence",type:"autonumber"},{key:"creator",type:"created_by"},
|
| 412 |
-
{key:"modified",type:"last_modified_time"},{key:"modifier",type:"last_modified_by"}],
|
| 413 |
-
AUDIT_FIELD_TYPES:["created_by","last_modified_time","last_modified_by"],directed:entry=>entry,patchOverlay:noop,
|
| 414 |
-
withdrawPending:ids=>{pending=pending.filter(row=>!ids.map(Number).includes(row.pid));},emitHostEvent:noop,
|
| 415 |
-
acceptPendingRow,workspaceScopeRef,setPendingRows,setOverlayEdits,rowsRef:restoreRowsRef,mintRid:()=>11,addTableRow:(...args)=>{restores.push(args);return new Promise(resolve=>{resolveRestore=resolve;});},
|
| 416 |
-
deleteTableRow:async(_table,rid)=>{deleted.push(rid);return true;},signal:(...args)=>stale.push(args),
|
| 417 |
-
ROWS_STALE_EVENT:"stale",TOAST_EVENT:"toast",describe:()=>"undo",applyingUndo:{current:false}});
|
| 418 |
-
const restoring = applyEntry(restoreEntry,"forward");
|
| 419 |
-
const optimistic = pending.find(row=>row.pid === 9);
|
| 420 |
-
check(optimistic && Object.keys(optimistic).sort().join() === "name,pid"
|
| 421 |
-
&& Object.keys(restores[0][1]).join() === "name" && restores[0][3] === true, "all four generated kinds stay out of restore request and optimistic cells");
|
| 422 |
-
resolveRestore({rid:"10",pid:10,values:{sequence:"52",creator:"original",modified:"fresh",modifier:"qa"}});
|
| 423 |
-
await restoring;
|
| 424 |
-
check(pending.find(row=>row.pid === 10)?.creator === "original" && !stale.some(event=>event[0] === "stale"),
|
| 425 |
-
"restored creator, counter and modifier paint from ack without a full refresh");
|
| 426 |
-
await applyEntry({...restoreEntry,kind:"rowDelete"},"forward");
|
| 427 |
-
check(deleted[0] === "10" && !pending.some(row=>row.pid === 10), "redo deletes the accepted restored identity without a ghost");
|
| 428 |
-
restoreRowsRef.current = pending;
|
| 429 |
-
const occupied = {kind:"rowAdd",table:scope,rows:[{rid:"8",values:{name:"other restored row"}}]};
|
| 430 |
-
const colliding = applyEntry(occupied,"forward");
|
| 431 |
-
check(pending.find(row=>row.pid === 8)?.name === "server" && pending.find(row=>row.pid === 11)?.name === "other restored row",
|
| 432 |
-
"occupied restore keeps the existing pending row and paints a separate temporary identity");
|
| 433 |
-
resolveRestore({rid:"12",pid:12,values:{sequence:"53",creator:"original"}});
|
| 434 |
-
await colliding;
|
| 435 |
-
check(pending.some(row=>row.pid === 8) && pending.some(row=>row.pid === 12) && occupied.rows[0].rid === "12",
|
| 436 |
-
"collision acknowledgement and next undo retain both real identities");
|
| 437 |
-
restoreRowsRef.current = pending;
|
| 438 |
-
const refusedRestore=applyEntry({kind:"rowAdd",table:scope,rows:[{rid:"8",values:{name:"refused"}}]},"forward");
|
| 439 |
-
resolveRestore(null); await refusedRestore;
|
| 440 |
-
check(pending.some(row=>row.pid === 8) && !pending.some(row=>row.pid === 11),
|
| 441 |
-
"a refused collision withdraws only its temporary row and preserves the occupied record");
|
| 442 |
-
const linkSelectionPredicate = pure("linkSelectionPredicate");
|
| 443 |
-
const restriction = {conj:"and",nodes:[{colId:"status",op:"eq",value:"Active"}]};
|
| 444 |
-
const candidate = {filterConj:"or",filters:[{colId:"name",op:"contains",value:"Cedar"},{colId:"name",op:"contains",value:"Willow"}]};
|
| 445 |
-
const narrowed = linkSelectionPredicate(candidate,restriction);
|
| 446 |
-
check(narrowed.filterConj === "and" && narrowed.filters[0].children === restriction.nodes
|
| 447 |
-
&& narrowed.filters[1].conj === "or" && narrowed.filters[1].children === candidate.filters, "candidate OR search remains inside the immutable AND restriction");
|
| 448 |
-
check(linkSelectionPredicate({filters:[]},restriction).filters[0].children === restriction.nodes, "clearing search cannot relax link restriction");
|
| 449 |
-
const hookSlots = [], windowCalls = [], completions = [];
|
| 450 |
-
let cursor = 0, unavailableCondition = false;
|
| 451 |
-
const hookContext = {
|
| 452 |
-
useRef:initial=>{const i=cursor++;return hookSlots[i]??=( {current:initial} );},
|
| 453 |
-
useState:initial=>{const i=cursor++;if (!(i in hookSlots)) hookSlots[i]=initial;
|
| 454 |
-
return [hookSlots[i],value=>{hookSlots[i]=typeof value === "function" ? value(hookSlots[i]) : value;}];},
|
| 455 |
-
useCallback:fn=>fn,useEffect:()=>{},linkSelectionPredicate,ROWS_STALE_EVENT:"stale",
|
| 456 |
-
unresolvedConditions:()=>unavailableCondition ? 1 : 0,window:ctx.window,CustomEvent:ctx.CustomEvent,TOAST_EVENT:"toast",
|
| 457 |
-
fetchTableWindow:(table,request)=>{windowCalls.push({table,request});return new Promise(resolve=>completions.push(resolve));}};
|
| 458 |
-
const windowHook = pure("useRecordIdWindow",hookContext);
|
| 459 |
-
const renderWindow = filter=>{cursor=0;return windowHook("ut_target",undefined,null,undefined,false,false,filter);};
|
| 460 |
-
const firstWindow = renderWindow(restriction);
|
| 461 |
-
check(firstWindow.payload === null && firstWindow.pending, "restricted picker withholds an unfiltered initial payload");
|
| 462 |
-
firstWindow.requestWindow({...candidate,offset:50,limit:50,search:"Cedar"});
|
| 463 |
-
check(windowCalls[0].request.filterConj === "and" && windowCalls[0].request.filters[0].children === restriction.nodes
|
| 464 |
-
&& windowCalls[0].request.offset === 50 && windowCalls[0].request.search === "Cedar",
|
| 465 |
-
"real window callback sends immutable restriction with search and page before server counts");
|
| 466 |
-
const changedRestriction={conj:"and",nodes:[{colId:"status",op:"eq",value:"Ready"}]};
|
| 467 |
-
const secondWindow=renderWindow(changedRestriction);
|
| 468 |
-
completions[0]({rows:[{pid:1}],counts:{matched:99}}); await Promise.resolve();
|
| 469 |
-
check(renderWindow(changedRestriction).payload === null, "stale response from an older link condition cannot populate the picker");
|
| 470 |
-
secondWindow.requestWindow({offset:0,limit:50,filters:[],search:""});
|
| 471 |
-
completions[1]({fields:[{key:"status",type:"text"}],rows:[{pid:2}],counts:{matched:1}}); await Promise.resolve();
|
| 472 |
-
check(renderWindow(changedRestriction).payload?.counts.matched === 1, "fresh restricted response owns rows and count");
|
| 473 |
-
unavailableCondition = true;
|
| 474 |
-
const toastCount = toasts.length;
|
| 475 |
-
renderWindow(changedRestriction).requestWindow({offset:0,limit:50,filters:[]});
|
| 476 |
-
completions[2]({fields:[],rows:[{pid:3}],counts:{matched:99}}); await Promise.resolve();
|
| 477 |
-
check(renderWindow(changedRestriction).payload === null && toasts.length === toastCount + 1 && toasts.at(-1).detail.tone === "error",
|
| 478 |
-
"an unavailable restriction withholds broader rows and counts with a C4 refusal");
|
| 479 |
-
const posts = [];
|
| 480 |
-
let reply = {rid:"12",pid:12,values:{pid:999,zero:0,blank:null,tick:false,private:{secret:"no"}}};
|
| 481 |
-
const add = bind("addTableRow", {API_V1:"/api/v1",CREDENTIALS:"include",JSON_HEADERS:{"Content-Type":"application/json"},
|
| 482 |
-
fetch:async(_url,init)=>{posts.push(JSON.parse(init.body));return {ok:true};},handledSession:()=>false,
|
| 483 |
-
readJson:async()=>reply,dropTableRowsCache:noop,signal:noop,TOAST_EVENT:"toast",DATA_ERROR_EVENT:"error"}, bridge);
|
| 484 |
-
const ack = await add(scope,{name:"new"},12);
|
| 485 |
-
check(posts[0].restore === false && ack.pid === 12 && ack.values.zero === 0 && ack.values.blank === null && ack.values.tick === "False"
|
| 486 |
-
&& !Object.hasOwn(ack.values,"pid") && !Object.hasOwn(ack.values,"private"), "ordinary create sends false and normalizes authorized scalar acknowledgement cells");
|
| 487 |
-
reply={rid:"12",pid:12}; const legacy=await add(scope,{},12,true);
|
| 488 |
-
check(posts[1].restore === true && !Object.hasOwn(legacy,"values"), "restore transport tolerates an older identity-only acknowledgement");
|
| 489 |
-
console.log("PASS W3 client amendments: " + checks + "/" + checks + " checks");
|
| 490 |
-
}
|
| 491 |
-
run().catch(error=>{console.error(error.stack);process.exitCode=1;});
|
| 492 |
-
'''
|
| 493 |
-
result = subprocess.run(["node", "-"], input=script, text=True, cwd=WEB, timeout=45)
|
| 494 |
-
return result.returncode
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
if __name__ == "__main__":
|
| 498 |
-
import argparse
|
| 499 |
-
parser = argparse.ArgumentParser(description=__doc__)
|
| 500 |
-
parser.add_argument("--client", action="store_true")
|
| 501 |
-
parser.add_argument("--base-url")
|
| 502 |
-
parser.add_argument("--out-dir", type=Path, default=Path("/tmp/aios-w3-host"))
|
| 503 |
-
args = parser.parse_args()
|
| 504 |
-
if args.client:
|
| 505 |
-
result = client_amend_contracts()
|
| 506 |
-
if result or not args.base_url:
|
| 507 |
-
raise SystemExit(result)
|
| 508 |
-
if args.base_url:
|
| 509 |
-
from urllib.parse import urlsplit
|
| 510 |
-
if urlsplit(args.base_url).hostname not in ("127.0.0.1", "localhost", "::1"):
|
| 511 |
-
parser.error("The synthetic fixture requires a local Vite origin")
|
| 512 |
-
mounted_catalog_host(args.base_url, args.out_dir)
|
| 513 |
-
else:
|
| 514 |
-
raise SystemExit(catalog_host_scan())
|
|
|
|
| 64 |
import json
|
| 65 |
from playwright.sync_api import sync_playwright
|
| 66 |
from verify_w45_data_applications import AppRoutingFixture
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
out_dir.mkdir(parents=True, exist_ok=True)
|
| 68 |
evidence = {"checks": [], "controls": [], "errors": []}
|
| 69 |
def check(name, value):
|
|
|
|
| 76 |
with sync_playwright() as playwright:
|
| 77 |
browser = playwright.chromium.launch(headless=True)
|
| 78 |
try:
|
| 79 |
+
cases = ['catalog'] + (['settings-discriminator', 'route-listener', 'legacy-loader'] if negative_controls else [])
|
| 80 |
for case in cases:
|
| 81 |
+
fixture = AppRoutingFixture()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
fixture.legacy_unavailable = True
|
| 83 |
fixture.hold_registry = True
|
| 84 |
+
context = browser.new_context(viewport={"width": 1440, "height": 1000})
|
| 85 |
context.add_init_script("""window.catalogRouteListeners = [];
|
| 86 |
const ordinaryAdd = window.addEventListener;
|
| 87 |
window.addEventListener = function(type, ...args) {
|
|
|
|
| 90 |
};""")
|
| 91 |
context.route('**/api/**', fixture.route)
|
| 92 |
applied = []
|
| 93 |
+
if case != 'catalog':
|
| 94 |
old, new = ('applicationTemplateSurface(resolvedApplication) !== "catalog"', 'true') if case == 'settings-discriminator' \
|
| 95 |
else ('rowsEnabled: legacyRowsEnabled', 'rowsEnabled: true') if case == 'legacy-loader' \
|
| 96 |
else (r'if \(!routeApplicationSurface\) return;\s*const openRoute', 'const openRoute')
|
|
|
|
| 135 |
continue
|
| 136 |
check('held registry has no legacy rows', not early_legacy)
|
| 137 |
fixture.release_registry()
|
| 138 |
+
page.locator('.cg-cat-stage .cg-cat-card').first.wait_for(timeout=30000)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
page.wait_for_timeout(600)
|
| 140 |
if case == 'settings-discriminator':
|
| 141 |
check('Catalog discriminator removal fails controls absence', bool(applied) and not no_controls(page))
|
|
|
|
| 143 |
continue
|
| 144 |
check('resolved Catalog has no Map/Bubble size/Routes', no_controls(page))
|
| 145 |
check('resolved Catalog registers no route-open handler', page.evaluate('window.catalogRouteListeners.length') == 0)
|
| 146 |
+
check('all cursor pages painted', sorted(page.locator('.cg-cat-stage .cg-cat-desc').all_text_contents())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
== ['Cedar Supply', 'Willow Floral'])
|
| 148 |
+
before = page.locator('.cg-cat-stage').inner_text()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
page.evaluate("window.dispatchEvent(new CustomEvent('aios:route-open', {detail:{routeId:'refused-route'}}))")
|
| 150 |
page.wait_for_timeout(200)
|
| 151 |
+
check('Catalog ignores route-open', no_controls(page) and page.locator('.cg-cat-stage').inner_text() == before)
|
| 152 |
+
page.get_by_role('button', name='Open Cedar Supply', exact=True).click()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
page.locator('.cg-record-modal').wait_for(timeout=10000)
|
| 154 |
check('real typed tail card drawer', 'Cedar Supply' in page.locator('.cg-record-modal').inner_text())
|
| 155 |
check('unavailable legacy endpoint never requested', not any(request['path'] == 'customers' for request in fixture.requests))
|
|
|
|
| 158 |
page.screenshot(path=str(out_dir / 'catalog-cold-drawer.png'), full_page=True)
|
| 159 |
finally:
|
| 160 |
context.close()
|
| 161 |
+
for surface in ('data-map', 'route'):
|
| 162 |
fixture = AppRoutingFixture()
|
| 163 |
fixture.config['display'] = {'mode': 'map'}
|
| 164 |
fixture.workspace['views'][0]['config']['display'] = {'mode': 'map'}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
fixture.original_workspace = __import__('copy').deepcopy(fixture.workspace)
|
| 166 |
if surface == 'route':
|
| 167 |
fixture.fields.extend([{'key': 'lat', 'label': 'Latitude', 'type': 'number', 'source': 'odoo'},
|
|
|
|
| 171 |
fixture.applications[0]['templateKind'] = 'route'
|
| 172 |
fixture.applications[0]['fieldMap'] = {'title': 'name', 'latitude': 'lat', 'longitude': 'lon'}
|
| 173 |
fixture.applications[0]['config'] = {'display': {'mode': 'map'}}
|
| 174 |
+
context = browser.new_context(viewport={"width": 1440, "height": 1000})
|
| 175 |
context.route('**/api/**', fixture.route)
|
| 176 |
# Keep the product's offline map; a synthetic transport cannot make an outward tile read.
|
| 177 |
context.route('https://tile.openstreetmap.org/**', lambda route: route.abort())
|
| 178 |
page = context.new_page()
|
| 179 |
try:
|
| 180 |
+
page.goto(base_url + ('/#/data?database=customer_data&view=saved-check' if surface == 'data-map'
|
| 181 |
else '/#/app?database=customer_data&application=app-fixture'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
page.locator('.cg-map-settings').wait_for(timeout=30000)
|
| 183 |
check(surface + ' keeps Map settings', page.get_by_text('Bubble size', exact=True).count() > 0)
|
| 184 |
if surface == 'route':
|
|
|
|
| 197 |
(out_dir / 'catalog-host.json').write_text(json.dumps(evidence, indent=2), encoding='utf-8')
|
| 198 |
print(f"PASS S71 Catalog host mounted: {len(evidence['checks'])} checks, {len(evidence['controls'])} controls")
|
| 199 |
return evidence
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
web/src/apps/catalog/CatalogApp.tsx
CHANGED
|
@@ -45,6 +45,9 @@ export function CatalogApp({ definition, database, scope, onOpen, onData, editor
|
|
| 45 |
</div>;
|
| 46 |
}
|
| 47 |
const filteredCodes = data.rows.map((row) => String(row[definition.fieldMap.key] ?? "").trim()).filter(Boolean);
|
|
|
|
|
|
|
|
|
|
| 48 |
return <section className="cg-app-catalog is-print-editor" aria-label={`${definition.name} catalog`}>
|
| 49 |
<CatalogApplicationView definition={definition} rows={data.rows} onOpen={onOpen}
|
| 50 |
editor={{ ...editor, fields: data.fields, fieldByKey, poolRows: data.allRows, filteredCodes, identityField }} />
|
|
|
|
| 45 |
</div>;
|
| 46 |
}
|
| 47 |
const filteredCodes = data.rows.map((row) => String(row[definition.fieldMap.key] ?? "").trim()).filter(Boolean);
|
| 48 |
+
if (!filteredCodes.length) {
|
| 49 |
+
return <div className="cg-mode-empty" role="status">No records have a value in the mapped key field.</div>;
|
| 50 |
+
}
|
| 51 |
return <section className="cg-app-catalog is-print-editor" aria-label={`${definition.name} catalog`}>
|
| 52 |
<CatalogApplicationView definition={definition} rows={data.rows} onOpen={onOpen}
|
| 53 |
editor={{ ...editor, fields: data.fields, fieldByKey, poolRows: data.allRows, filteredCodes, identityField }} />
|
web/src/apps/code/CodeAppPage.tsx
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
-
import { useEffect,
|
| 2 |
-
import { API_V1, CREDENTIALS,
|
| 3 |
import CodeAppFrame from "./CodeAppFrame";
|
| 4 |
import { checkCodeAppSize } from "./frameDocument";
|
| 5 |
import ConfirmDelete, { useConfirmDelete } from "./ConfirmDelete";
|
|
@@ -49,12 +49,6 @@ function Loading() {
|
|
| 49 |
export default function CodeAppPage({ applicationId, bootstrapBase }: { applicationId: string; bootstrapBase?: string }) {
|
| 50 |
const [retry, setRetry] = useState(0);
|
| 51 |
const [state, setState] = useState<PageState>({ kind: "loading", id: applicationId });
|
| 52 |
-
const announced = useRef<PageState | null>(null);
|
| 53 |
-
useEffect(() => {
|
| 54 |
-
if (state.id !== applicationId || state.kind !== "refused" || announced.current === state) return;
|
| 55 |
-
announced.current = state;
|
| 56 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text: state.message, tone: "error" } }));
|
| 57 |
-
}, [state, applicationId]);
|
| 58 |
const { request, confirmDelete, confirmTool } = useConfirmDelete();
|
| 59 |
useEffect(() => {
|
| 60 |
const controller = new AbortController();
|
|
@@ -92,11 +86,11 @@ export default function CodeAppPage({ applicationId, bootstrapBase }: { applicat
|
|
| 92 |
onReady={() => setState((value) => value.kind === "ready" && value.id === current.id ? { ...value, started: true } : value)}
|
| 93 |
onRefused={(message) => setState({ kind: "refused", id: current.id, message })} />}
|
| 94 |
<ConfirmDelete request={request} appName={current.kind === "ready" ? current.app.name : "App"} />
|
| 95 |
-
{current.kind === "error" && <div role="alert"
|
| 96 |
style={{ padding: "var(--lp-content-inset)", color: "var(--lp-ink)", fontSize: "var(--lp-fs-sm)" }}>
|
| 97 |
<p>{current.message}</p>
|
| 98 |
-
<button type="button" className="set-secondary" onClick={() => setRetry((value) => value + 1)}
|
| 99 |
-
style={{ border: 0, background: "transparent", font: "inherit", color: "var(--lp-blue-deep)", cursor: "pointer" }}>Retry</button>
|
| 100 |
</div>}
|
| 101 |
</div>;
|
| 102 |
}
|
|
|
|
| 1 |
+
import { useEffect, useState } from "react";
|
| 2 |
+
import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../../apiContract";
|
| 3 |
import CodeAppFrame from "./CodeAppFrame";
|
| 4 |
import { checkCodeAppSize } from "./frameDocument";
|
| 5 |
import ConfirmDelete, { useConfirmDelete } from "./ConfirmDelete";
|
|
|
|
| 49 |
export default function CodeAppPage({ applicationId, bootstrapBase }: { applicationId: string; bootstrapBase?: string }) {
|
| 50 |
const [retry, setRetry] = useState(0);
|
| 51 |
const [state, setState] = useState<PageState>({ kind: "loading", id: applicationId });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
const { request, confirmDelete, confirmTool } = useConfirmDelete();
|
| 53 |
useEffect(() => {
|
| 54 |
const controller = new AbortController();
|
|
|
|
| 86 |
onReady={() => setState((value) => value.kind === "ready" && value.id === current.id ? { ...value, started: true } : value)}
|
| 87 |
onRefused={(message) => setState({ kind: "refused", id: current.id, message })} />}
|
| 88 |
<ConfirmDelete request={request} appName={current.kind === "ready" ? current.app.name : "App"} />
|
| 89 |
+
{(current.kind === "error" || current.kind === "refused") && <div role="alert"
|
| 90 |
style={{ padding: "var(--lp-content-inset)", color: "var(--lp-ink)", fontSize: "var(--lp-fs-sm)" }}>
|
| 91 |
<p>{current.message}</p>
|
| 92 |
+
{current.kind === "error" && <button type="button" className="set-secondary" onClick={() => setRetry((value) => value + 1)}
|
| 93 |
+
style={{ border: 0, background: "transparent", font: "inherit", color: "var(--lp-blue-deep)", cursor: "pointer" }}>Retry</button>}
|
| 94 |
</div>}
|
| 95 |
</div>;
|
| 96 |
}
|
web/src/apps/customer-card/CustomerCardView.tsx
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
import { useEffect, useRef, useState } from "react";
|
| 2 |
-
import { API_V1, CREDENTIALS,
|
| 3 |
import { ConfirmDialog } from "../../ui/ConfirmDialog";
|
| 4 |
import "../../styles/sdlc74/customer-card.css";
|
| 5 |
|
|
@@ -87,30 +87,6 @@ function dueDate(value: string | null): string {
|
|
| 87 |
|
| 88 |
type EmailPreview = { previewToken: string; to: string; subject: string; body: string; refusal?: string | null };
|
| 89 |
type EmailResult = { state: "queued" | "refused"; created: number; message?: string };
|
| 90 |
-
class EmailRefused extends Error {}
|
| 91 |
-
|
| 92 |
-
function useRefusalToast() {
|
| 93 |
-
const [messages, setMessages] = useState<{ id: number; text: string }[]>([]);
|
| 94 |
-
const sequence = useRef(0);
|
| 95 |
-
const delivered = useRef(0);
|
| 96 |
-
useEffect(() => {
|
| 97 |
-
if (!messages.length) return;
|
| 98 |
-
const through = messages[messages.length - 1].id;
|
| 99 |
-
for (const message of messages) {
|
| 100 |
-
if (message.id <= delivered.current) continue;
|
| 101 |
-
delivered.current = message.id;
|
| 102 |
-
const text = message.text;
|
| 103 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
|
| 104 |
-
}
|
| 105 |
-
setMessages((current) => current.filter((message) => message.id > through));
|
| 106 |
-
}, [messages]);
|
| 107 |
-
return (text: string) => {
|
| 108 |
-
if (!text) return;
|
| 109 |
-
const message = { id: ++sequence.current, text };
|
| 110 |
-
setMessages((current) => [...current, message]);
|
| 111 |
-
};
|
| 112 |
-
}
|
| 113 |
-
|
| 114 |
|
| 115 |
async function emailRequest<T>(path: string, body: object, abort: AbortSignal): Promise<T> {
|
| 116 |
const response = await fetch(`${API_V1}${path}`, { method: "POST", credentials: CREDENTIALS,
|
|
@@ -118,11 +94,7 @@ async function emailRequest<T>(path: string, body: object, abort: AbortSignal):
|
|
| 118 |
if (checkTenant(response)) throw new Error("Workspace changed.");
|
| 119 |
if (response.status === 401) signal(UNAUTHORIZED_EVENT);
|
| 120 |
const result = await response.json();
|
| 121 |
-
if (!response.ok)
|
| 122 |
-
const message = result?.error?.message || "The email could not be prepared.";
|
| 123 |
-
if ([401, 403, 404].includes(response.status)) throw new EmailRefused(message);
|
| 124 |
-
throw new Error(message);
|
| 125 |
-
}
|
| 126 |
return result as T;
|
| 127 |
}
|
| 128 |
|
|
@@ -130,7 +102,6 @@ function CustomerCardEmail({ context, onEmailLink }: {
|
|
| 130 |
context: CustomerCardPrivatePreview;
|
| 131 |
onEmailLink?: CustomerCardViewProps["onEmailLink"];
|
| 132 |
}) {
|
| 133 |
-
const emailRefusal = useRefusalToast();
|
| 134 |
const [preview, setPreview] = useState<EmailPreview | null>(null);
|
| 135 |
const [preparing, setPreparing] = useState(false);
|
| 136 |
const [queueing, setQueueing] = useState(false);
|
|
@@ -176,14 +147,10 @@ function CustomerCardEmail({ context, onEmailLink }: {
|
|
| 176 |
if (typeof next.previewToken !== "string" || !next.previewToken || typeof next.to !== "string"
|
| 177 |
|| typeof next.subject !== "string" || typeof next.body !== "string") throw new Error("The email could not be prepared.");
|
| 178 |
setPreview(next);
|
| 179 |
-
if (next.refusal) emailRefusal(next.refusal);
|
| 180 |
} catch (error) {
|
| 181 |
if (mounted.current && !request.signal.aborted) {
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
setResult(error instanceof Error ? error.message : "The email could not be prepared.");
|
| 185 |
-
setFailed(true);
|
| 186 |
-
}
|
| 187 |
}
|
| 188 |
} finally {
|
| 189 |
if (mounted.current && !request.signal.aborted) { pending.current = false; setPreparing(false); }
|
|
@@ -192,7 +159,6 @@ function CustomerCardEmail({ context, onEmailLink }: {
|
|
| 192 |
|
| 193 |
async function queueEmail() {
|
| 194 |
if (!preview || pending.current) return;
|
| 195 |
-
if (preview.refusal) { emailRefusal(preview.refusal); return; }
|
| 196 |
const request = new AbortController();
|
| 197 |
controller.current = request;
|
| 198 |
pending.current = true;
|
|
@@ -202,21 +168,12 @@ function CustomerCardEmail({ context, onEmailLink }: {
|
|
| 202 |
{ previewToken: preview.previewToken, confirm: true }, request.signal);
|
| 203 |
if (!mounted.current || request.signal.aborted) return;
|
| 204 |
if (next.state !== "queued" && next.state !== "refused") throw new Error("Queueing was not confirmed. Check Odoo before trying again.");
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
setFailed(false);
|
| 208 |
-
emailRefusal("Safe mode does not allow this recipient address.");
|
| 209 |
-
} else {
|
| 210 |
-
setResult("Queued");
|
| 211 |
-
setFailed(false);
|
| 212 |
-
}
|
| 213 |
} catch (error) {
|
| 214 |
if (mounted.current && !request.signal.aborted) {
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
setResult(error instanceof Error ? error.message : "Queueing was not confirmed. Check Odoo before trying again.");
|
| 218 |
-
setFailed(true);
|
| 219 |
-
}
|
| 220 |
}
|
| 221 |
} finally {
|
| 222 |
if (mounted.current && !request.signal.aborted) {
|
|
@@ -242,6 +199,7 @@ function CustomerCardEmail({ context, onEmailLink }: {
|
|
| 242 |
<p className="customer-card-label">Subject</p><p data-email-subject="">{preview.subject}</p>
|
| 243 |
<p className="customer-card-label">Body</p>
|
| 244 |
<p data-email-body="" style={{ whiteSpace: "pre-wrap" }}>{preview.body}</p>
|
|
|
|
| 245 |
</div>} />
|
| 246 |
</>;
|
| 247 |
}
|
|
|
|
| 1 |
import { useEffect, useRef, useState } from "react";
|
| 2 |
+
import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../../apiContract";
|
| 3 |
import { ConfirmDialog } from "../../ui/ConfirmDialog";
|
| 4 |
import "../../styles/sdlc74/customer-card.css";
|
| 5 |
|
|
|
|
| 87 |
|
| 88 |
type EmailPreview = { previewToken: string; to: string; subject: string; body: string; refusal?: string | null };
|
| 89 |
type EmailResult = { state: "queued" | "refused"; created: number; message?: string };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
async function emailRequest<T>(path: string, body: object, abort: AbortSignal): Promise<T> {
|
| 92 |
const response = await fetch(`${API_V1}${path}`, { method: "POST", credentials: CREDENTIALS,
|
|
|
|
| 94 |
if (checkTenant(response)) throw new Error("Workspace changed.");
|
| 95 |
if (response.status === 401) signal(UNAUTHORIZED_EVENT);
|
| 96 |
const result = await response.json();
|
| 97 |
+
if (!response.ok) throw new Error(result?.error?.message || "The email could not be prepared.");
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
return result as T;
|
| 99 |
}
|
| 100 |
|
|
|
|
| 102 |
context: CustomerCardPrivatePreview;
|
| 103 |
onEmailLink?: CustomerCardViewProps["onEmailLink"];
|
| 104 |
}) {
|
|
|
|
| 105 |
const [preview, setPreview] = useState<EmailPreview | null>(null);
|
| 106 |
const [preparing, setPreparing] = useState(false);
|
| 107 |
const [queueing, setQueueing] = useState(false);
|
|
|
|
| 147 |
if (typeof next.previewToken !== "string" || !next.previewToken || typeof next.to !== "string"
|
| 148 |
|| typeof next.subject !== "string" || typeof next.body !== "string") throw new Error("The email could not be prepared.");
|
| 149 |
setPreview(next);
|
|
|
|
| 150 |
} catch (error) {
|
| 151 |
if (mounted.current && !request.signal.aborted) {
|
| 152 |
+
setResult(error instanceof Error ? error.message : "The email could not be prepared.");
|
| 153 |
+
setFailed(true);
|
|
|
|
|
|
|
|
|
|
| 154 |
}
|
| 155 |
} finally {
|
| 156 |
if (mounted.current && !request.signal.aborted) { pending.current = false; setPreparing(false); }
|
|
|
|
| 159 |
|
| 160 |
async function queueEmail() {
|
| 161 |
if (!preview || pending.current) return;
|
|
|
|
| 162 |
const request = new AbortController();
|
| 163 |
controller.current = request;
|
| 164 |
pending.current = true;
|
|
|
|
| 168 |
{ previewToken: preview.previewToken, confirm: true }, request.signal);
|
| 169 |
if (!mounted.current || request.signal.aborted) return;
|
| 170 |
if (next.state !== "queued" && next.state !== "refused") throw new Error("Queueing was not confirmed. Check Odoo before trying again.");
|
| 171 |
+
setResult(next.state === "queued" ? "Queued" : "Safe mode does not allow this recipient address.");
|
| 172 |
+
setFailed(next.state === "refused");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
} catch (error) {
|
| 174 |
if (mounted.current && !request.signal.aborted) {
|
| 175 |
+
setResult(error instanceof Error ? error.message : "Queueing was not confirmed. Check Odoo before trying again.");
|
| 176 |
+
setFailed(true);
|
|
|
|
|
|
|
|
|
|
| 177 |
}
|
| 178 |
} finally {
|
| 179 |
if (mounted.current && !request.signal.aborted) {
|
|
|
|
| 199 |
<p className="customer-card-label">Subject</p><p data-email-subject="">{preview.subject}</p>
|
| 200 |
<p className="customer-card-label">Body</p>
|
| 201 |
<p data-email-body="" style={{ whiteSpace: "pre-wrap" }}>{preview.body}</p>
|
| 202 |
+
{preview.refusal && <p role="alert">{preview.refusal}</p>}
|
| 203 |
</div>} />
|
| 204 |
</>;
|
| 205 |
}
|
web/src/artifacts/ArtifactsPage.tsx
CHANGED
|
@@ -505,14 +505,6 @@ export default function ArtifactsPage({ granted }: { granted: NavEntry[] }) {
|
|
| 505 |
const frozenValue = snapshot?.page?.frozen_at ?? (selected as FileFields | undefined)?.frozen_at;
|
| 506 |
const frozenAt = typeof frozenValue === "string" && Number.isFinite(Date.parse(frozenValue)) ? frozenValue : undefined;
|
| 507 |
const queryId = selected?.kind === "query" ? selected.ref || undefined : selection.view;
|
| 508 |
-
const unavailableKey = selected
|
| 509 |
-
? ((selected.kind === "pdf" && !selected.ref) || fileMissing || worklist?.refused ? selected.id : "")
|
| 510 |
-
: loaded && !loading && !problem && !nextCursor && !queryId
|
| 511 |
-
? selection.item || selection.view || "" : "";
|
| 512 |
-
useEffect(() => {
|
| 513 |
-
if (!unavailableKey) return;
|
| 514 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text: ARTIFACT_UNAVAILABLE, tone: "error" } }));
|
| 515 |
-
}, [unavailableKey]);
|
| 516 |
const isSavedQuery = (item: Artifact) => item.kind === "query" && views.some((view) => view.id === item.ref);
|
| 517 |
const resolveHref = safeWorklistLink(worklist?.page?.resolve.href);
|
| 518 |
const queryItems = items.filter(isSavedQuery);
|
|
@@ -646,6 +638,7 @@ export default function ArtifactsPage({ granted }: { granted: NavEntry[] }) {
|
|
| 646 |
</div></section> : null}
|
| 647 |
{replies[selected.id] ? <p className="ar-result" role="status">{replies[selected.id]}</p> : null}
|
| 648 |
{made[selected.id] ? <p className="ar-result">{made[selected.id]}</p> : null}
|
|
|
|
| 649 |
{selectedKind === "image" && fileHref ? <figure className="ar-image">
|
| 650 |
<img src={fileHref} alt={plain(selected.title)} /></figure> : null}
|
| 651 |
{selectedKind === "snapshot" ? <section className="ar-worklist ar-snapshot" aria-label="Frozen snapshot" aria-busy={snapshot?.loading ?? true}>
|
|
@@ -660,7 +653,8 @@ export default function ArtifactsPage({ granted }: { granted: NavEntry[] }) {
|
|
| 660 |
{selected.kind === "report" && !worklist?.refused ? <WorklistTable key={selected.id} page={worklist?.page ?? null} details={artifactDetails}
|
| 661 |
loading={worklist?.loading ?? true} problem={worklist?.problem ?? ""} onShowMore={() => void showMoreWorklist()}
|
| 662 |
onRetry={() => setWorklistToken((value) => value + 1)} /> : null}
|
| 663 |
-
</> :
|
|
|
|
| 664 |
{queryId ? <div className="ar-query"><Suspense fallback={<SkeletonRows />}>
|
| 665 |
<QueryPage granted={granted} hostedRail selectedId={queryId} refreshToken={refreshToken} />
|
| 666 |
</Suspense></div> : null}
|
|
|
|
| 505 |
const frozenValue = snapshot?.page?.frozen_at ?? (selected as FileFields | undefined)?.frozen_at;
|
| 506 |
const frozenAt = typeof frozenValue === "string" && Number.isFinite(Date.parse(frozenValue)) ? frozenValue : undefined;
|
| 507 |
const queryId = selected?.kind === "query" ? selected.ref || undefined : selection.view;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 508 |
const isSavedQuery = (item: Artifact) => item.kind === "query" && views.some((view) => view.id === item.ref);
|
| 509 |
const resolveHref = safeWorklistLink(worklist?.page?.resolve.href);
|
| 510 |
const queryItems = items.filter(isSavedQuery);
|
|
|
|
| 638 |
</div></section> : null}
|
| 639 |
{replies[selected.id] ? <p className="ar-result" role="status">{replies[selected.id]}</p> : null}
|
| 640 |
{made[selected.id] ? <p className="ar-result">{made[selected.id]}</p> : null}
|
| 641 |
+
{selected.kind === "pdf" && !selected.ref || fileMissing || worklist?.refused ? <p className="ar-empty ar-refused" role="status">{ARTIFACT_UNAVAILABLE}</p> : null}
|
| 642 |
{selectedKind === "image" && fileHref ? <figure className="ar-image">
|
| 643 |
<img src={fileHref} alt={plain(selected.title)} /></figure> : null}
|
| 644 |
{selectedKind === "snapshot" ? <section className="ar-worklist ar-snapshot" aria-label="Frozen snapshot" aria-busy={snapshot?.loading ?? true}>
|
|
|
|
| 653 |
{selected.kind === "report" && !worklist?.refused ? <WorklistTable key={selected.id} page={worklist?.page ?? null} details={artifactDetails}
|
| 654 |
loading={worklist?.loading ?? true} problem={worklist?.problem ?? ""} onShowMore={() => void showMoreWorklist()}
|
| 655 |
onRetry={() => setWorklistToken((value) => value + 1)} /> : null}
|
| 656 |
+
</> : loaded && (selection.item || selection.view) && !loading && !nextCursor && !queryId
|
| 657 |
+
? <p className="ar-empty ar-refused" role="status">{replies[selection.item || ""] || ARTIFACT_UNAVAILABLE}</p> : null}
|
| 658 |
{queryId ? <div className="ar-query"><Suspense fallback={<SkeletonRows />}>
|
| 659 |
<QueryPage granted={granted} hostedRail selectedId={queryId} refreshToken={refreshToken} />
|
| 660 |
</Suspense></div> : null}
|
web/src/automation/AutomationDetail.tsx
CHANGED
|
@@ -22,7 +22,6 @@ import PanelToggleIcon from "../shell/PanelToggleIcon";
|
|
| 22 |
// what this codebase treats as a defect rather than a summary.
|
| 23 |
// ---------------------------------------------------------------------------
|
| 24 |
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
| 25 |
-
import { TOAST_EVENT } from "../apiContract";
|
| 26 |
|
| 27 |
import AutomationBuilder from "./AutomationBuilder";
|
| 28 |
import HarnessPanel from "./HarnessPanel";
|
|
@@ -335,28 +334,6 @@ function RetiredAutomationResult({ automation }: { automation: Automation }) {
|
|
| 335 |
);
|
| 336 |
}
|
| 337 |
|
| 338 |
-
function useRefusalToast() {
|
| 339 |
-
const [messages, setMessages] = useState<{ id: number; text: string }[]>([]);
|
| 340 |
-
const sequence = useRef(0);
|
| 341 |
-
const delivered = useRef(0);
|
| 342 |
-
useEffect(() => {
|
| 343 |
-
if (!messages.length) return;
|
| 344 |
-
const through = messages[messages.length - 1].id;
|
| 345 |
-
for (const message of messages) {
|
| 346 |
-
if (message.id <= delivered.current) continue;
|
| 347 |
-
delivered.current = message.id;
|
| 348 |
-
const text = message.text;
|
| 349 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
|
| 350 |
-
}
|
| 351 |
-
setMessages((current) => current.filter((message) => message.id > through));
|
| 352 |
-
}, [messages]);
|
| 353 |
-
return useCallback((text: string) => {
|
| 354 |
-
if (!text) return;
|
| 355 |
-
const message = { id: ++sequence.current, text };
|
| 356 |
-
setMessages((current) => [...current, message]);
|
| 357 |
-
}, []);
|
| 358 |
-
}
|
| 359 |
-
|
| 360 |
export default function AutomationDetailView(props: Props) {
|
| 361 |
return props.automation.retired
|
| 362 |
? <RetiredAutomationResult automation={props.automation} />
|
|
@@ -414,16 +391,7 @@ function AutomationDetail({
|
|
| 414 |
const [name, setName] = useState(automation.name || "");
|
| 415 |
const [cron, setCron] = useState(automation.schedule?.cron || "0 6 * * *");
|
| 416 |
const [message, setMessage] = useState("");
|
| 417 |
-
const [problem,
|
| 418 |
-
const refuse = useRefusalToast();
|
| 419 |
-
const setProblem = useCallback((text: string, error?: unknown) => {
|
| 420 |
-
if (error instanceof AutomationError && [401, 403, 404].includes(error.status)) {
|
| 421 |
-
setInlineProblem("");
|
| 422 |
-
refuse(text);
|
| 423 |
-
} else setInlineProblem(text);
|
| 424 |
-
}, [refuse]);
|
| 425 |
-
const mutationProblem = (error: unknown, fallback: string) =>
|
| 426 |
-
setProblem(error instanceof Error ? error.message : fallback, error);
|
| 427 |
const [saving, setSaving] = useState(false);
|
| 428 |
const [touched, setTouched] = useState(false);
|
| 429 |
const [triggerBusy, setTriggerBusy] = useState(false);
|
|
@@ -658,7 +626,7 @@ function AutomationDetail({
|
|
| 658 |
try {
|
| 659 |
const { workflow, agent } = await createAgentWorkflow(automation.id, asked);
|
| 660 |
setAgentContract(agent); setActiveWorkflow(workflow.id);
|
| 661 |
-
} catch (error) {
|
| 662 |
};
|
| 663 |
/**
|
| 664 |
* ⭐ W47-T20 — `forDatabase` IS THE ONE ADDITION, AND IT CLOSES A REAL HAZARD RATHER THAN
|
|
@@ -689,7 +657,7 @@ function AutomationDetail({
|
|
| 689 |
workflows: { ...existing, [activeWorkflow]: workflowGrants },
|
| 690 |
});
|
| 691 |
setAgentContract(agent);
|
| 692 |
-
} catch (error) {
|
| 693 |
};
|
| 694 |
// The panel fold persists across visits.
|
| 695 |
const [railShut, setRailShut] = useState<boolean>(() => {
|
|
@@ -1113,7 +1081,7 @@ function AutomationDetail({
|
|
| 1113 |
setMessage(heldNote());
|
| 1114 |
await onSaved(fresh.id, fresh); // W31-T31: the response, not a second read
|
| 1115 |
} catch (e) {
|
| 1116 |
-
|
| 1117 |
} finally {
|
| 1118 |
setTriggerBusy(false);
|
| 1119 |
}
|
|
@@ -1150,7 +1118,7 @@ function AutomationDetail({
|
|
| 1150 |
setMessage(heldNote());
|
| 1151 |
await onSaved(fresh.id, fresh); // W31-T31: the response, not a second read
|
| 1152 |
} catch (e) {
|
| 1153 |
-
|
| 1154 |
} finally {
|
| 1155 |
setTriggerBusy(false);
|
| 1156 |
}
|
|
@@ -1195,7 +1163,7 @@ function AutomationDetail({
|
|
| 1195 |
try {
|
| 1196 |
fresh = await persist();
|
| 1197 |
} catch (e) {
|
| 1198 |
-
|
| 1199 |
return;
|
| 1200 |
} finally {
|
| 1201 |
// ⭐ HERE, not after `onSaved`. This is the whole ticket.
|
|
@@ -1224,7 +1192,7 @@ function AutomationDetail({
|
|
| 1224 |
const { automation: fresh } = await toggleNode(automation.id, nodeId);
|
| 1225 |
await onSaved(fresh.id, fresh);
|
| 1226 |
} catch (e) {
|
| 1227 |
-
|
| 1228 |
}
|
| 1229 |
};
|
| 1230 |
|
|
@@ -1270,7 +1238,7 @@ function AutomationDetail({
|
|
| 1270 |
);
|
| 1271 |
await onSaved(automation.id);
|
| 1272 |
} catch (e) {
|
| 1273 |
-
|
| 1274 |
}
|
| 1275 |
};
|
| 1276 |
|
|
@@ -1281,11 +1249,7 @@ function AutomationDetail({
|
|
| 1281 |
itemDeleted({ kind: "automation", id: automation.id });
|
| 1282 |
await onDeleted();
|
| 1283 |
} catch (e) {
|
| 1284 |
-
|
| 1285 |
-
setProblem(e.message, e);
|
| 1286 |
-
} else {
|
| 1287 |
-
setProblem(e instanceof AutomationError ? e.message : "It was not deleted.");
|
| 1288 |
-
}
|
| 1289 |
}
|
| 1290 |
};
|
| 1291 |
|
|
@@ -1319,7 +1283,7 @@ function AutomationDetail({
|
|
| 1319 |
const { automation: fresh } = await getAutomation(automation.id);
|
| 1320 |
await onSaved(fresh.id, fresh);
|
| 1321 |
} catch (e) {
|
| 1322 |
-
|
| 1323 |
} finally {
|
| 1324 |
setSending(false);
|
| 1325 |
}
|
|
@@ -1391,7 +1355,7 @@ function AutomationDetail({
|
|
| 1391 |
// action kind, a valueless compare — each with a reason worth reading. A client that
|
| 1392 |
// predicted those refusals would be a second validator free to disagree with the one
|
| 1393 |
// that decides.
|
| 1394 |
-
|
| 1395 |
} finally {
|
| 1396 |
setTriggerBusy(false);
|
| 1397 |
}
|
|
@@ -2000,7 +1964,7 @@ function AutomationDetail({
|
|
| 2000 |
? Array.from(new Set([...agentContract.sharing.sharedWith, recipient!])) : [],
|
| 2001 |
workflows: agentContract.capabilities.workflows,
|
| 2002 |
}); setAgentContract(agent);
|
| 2003 |
-
} catch (error) {
|
| 2004 |
}}>{agentContract.sharing.visibility === "private" ? "Share automation" : "Make private"}</button>
|
| 2005 |
</>
|
| 2006 |
) : null}
|
|
|
|
| 22 |
// what this codebase treats as a defect rather than a summary.
|
| 23 |
// ---------------------------------------------------------------------------
|
| 24 |
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
|
|
| 25 |
|
| 26 |
import AutomationBuilder from "./AutomationBuilder";
|
| 27 |
import HarnessPanel from "./HarnessPanel";
|
|
|
|
| 334 |
);
|
| 335 |
}
|
| 336 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
export default function AutomationDetailView(props: Props) {
|
| 338 |
return props.automation.retired
|
| 339 |
? <RetiredAutomationResult automation={props.automation} />
|
|
|
|
| 391 |
const [name, setName] = useState(automation.name || "");
|
| 392 |
const [cron, setCron] = useState(automation.schedule?.cron || "0 6 * * *");
|
| 393 |
const [message, setMessage] = useState("");
|
| 394 |
+
const [problem, setProblem] = useState("");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 395 |
const [saving, setSaving] = useState(false);
|
| 396 |
const [touched, setTouched] = useState(false);
|
| 397 |
const [triggerBusy, setTriggerBusy] = useState(false);
|
|
|
|
| 626 |
try {
|
| 627 |
const { workflow, agent } = await createAgentWorkflow(automation.id, asked);
|
| 628 |
setAgentContract(agent); setActiveWorkflow(workflow.id);
|
| 629 |
+
} catch (error) { setProblem(error instanceof Error ? error.message : "Workflow could not be created."); }
|
| 630 |
};
|
| 631 |
/**
|
| 632 |
* ⭐ W47-T20 — `forDatabase` IS THE ONE ADDITION, AND IT CLOSES A REAL HAZARD RATHER THAN
|
|
|
|
| 657 |
workflows: { ...existing, [activeWorkflow]: workflowGrants },
|
| 658 |
});
|
| 659 |
setAgentContract(agent);
|
| 660 |
+
} catch (error) { setProblem(error instanceof Error ? error.message : "Automation governance could not be saved."); }
|
| 661 |
};
|
| 662 |
// The panel fold persists across visits.
|
| 663 |
const [railShut, setRailShut] = useState<boolean>(() => {
|
|
|
|
| 1081 |
setMessage(heldNote());
|
| 1082 |
await onSaved(fresh.id, fresh); // W31-T31: the response, not a second read
|
| 1083 |
} catch (e) {
|
| 1084 |
+
setProblem(e instanceof AutomationError ? e.message : "That schedule was not saved.");
|
| 1085 |
} finally {
|
| 1086 |
setTriggerBusy(false);
|
| 1087 |
}
|
|
|
|
| 1118 |
setMessage(heldNote());
|
| 1119 |
await onSaved(fresh.id, fresh); // W31-T31: the response, not a second read
|
| 1120 |
} catch (e) {
|
| 1121 |
+
setProblem(e instanceof AutomationError ? e.message : "That trigger was not saved.");
|
| 1122 |
} finally {
|
| 1123 |
setTriggerBusy(false);
|
| 1124 |
}
|
|
|
|
| 1163 |
try {
|
| 1164 |
fresh = await persist();
|
| 1165 |
} catch (e) {
|
| 1166 |
+
setProblem(e instanceof AutomationError ? e.message : "That could not be saved.");
|
| 1167 |
return;
|
| 1168 |
} finally {
|
| 1169 |
// ⭐ HERE, not after `onSaved`. This is the whole ticket.
|
|
|
|
| 1192 |
const { automation: fresh } = await toggleNode(automation.id, nodeId);
|
| 1193 |
await onSaved(fresh.id, fresh);
|
| 1194 |
} catch (e) {
|
| 1195 |
+
setProblem(e instanceof AutomationError ? e.message : "That step was not changed.");
|
| 1196 |
}
|
| 1197 |
};
|
| 1198 |
|
|
|
|
| 1238 |
);
|
| 1239 |
await onSaved(automation.id);
|
| 1240 |
} catch (e) {
|
| 1241 |
+
setProblem(e instanceof AutomationError ? e.message : "It did not start.");
|
| 1242 |
}
|
| 1243 |
};
|
| 1244 |
|
|
|
|
| 1249 |
itemDeleted({ kind: "automation", id: automation.id });
|
| 1250 |
await onDeleted();
|
| 1251 |
} catch (e) {
|
| 1252 |
+
setProblem(e instanceof AutomationError ? e.message : "It was not deleted.");
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1253 |
}
|
| 1254 |
};
|
| 1255 |
|
|
|
|
| 1283 |
const { automation: fresh } = await getAutomation(automation.id);
|
| 1284 |
await onSaved(fresh.id, fresh);
|
| 1285 |
} catch (e) {
|
| 1286 |
+
setProblem(e instanceof AutomationError ? e.message : "Those statements were not sent.");
|
| 1287 |
} finally {
|
| 1288 |
setSending(false);
|
| 1289 |
}
|
|
|
|
| 1355 |
// action kind, a valueless compare — each with a reason worth reading. A client that
|
| 1356 |
// predicted those refusals would be a second validator free to disagree with the one
|
| 1357 |
// that decides.
|
| 1358 |
+
setProblem(e instanceof AutomationError ? e.message : "That change was not saved.");
|
| 1359 |
} finally {
|
| 1360 |
setTriggerBusy(false);
|
| 1361 |
}
|
|
|
|
| 1964 |
? Array.from(new Set([...agentContract.sharing.sharedWith, recipient!])) : [],
|
| 1965 |
workflows: agentContract.capabilities.workflows,
|
| 1966 |
}); setAgentContract(agent);
|
| 1967 |
+
} catch (error) { setProblem(error instanceof Error ? error.message : "Sharing could not be saved."); }
|
| 1968 |
}}>{agentContract.sharing.visibility === "private" ? "Share automation" : "Make private"}</button>
|
| 1969 |
</>
|
| 1970 |
) : null}
|
web/src/automation/AutomationSurface.tsx
CHANGED
|
@@ -18,7 +18,7 @@ import type { KeyboardEvent as ReactKeyboardEvent } from "react";
|
|
| 18 |
import { Suspense, lazy, useCallback, useEffect, useRef, useState } from "react";
|
| 19 |
|
| 20 |
import type { AutomationOpenDetail } from "../apiContract";
|
| 21 |
-
import { AUTOMATION_OPEN_EVENT,
|
| 22 |
// ⭐ WAVE 26 · ITEM 18 / R14 + C7 — THE LOOPABLE LOOP MARK, CONSUMED, NEVER REDRAWN.
|
| 23 |
// The owner's reason is the mark's own geometry: *"these automations are basically loops."*
|
| 24 |
// C7 says consume the existing icon component and do not inline a new SVG path, and
|
|
@@ -207,28 +207,6 @@ if (typeof window !== "undefined") {
|
|
| 207 |
* that a database can be created BY asking for an automation.
|
| 208 |
*/
|
| 209 |
|
| 210 |
-
function useRefusalToast() {
|
| 211 |
-
const [messages, setMessages] = useState<{ id: number; text: string }[]>([]);
|
| 212 |
-
const sequence = useRef(0);
|
| 213 |
-
const delivered = useRef(0);
|
| 214 |
-
useEffect(() => {
|
| 215 |
-
if (!messages.length) return;
|
| 216 |
-
const through = messages[messages.length - 1].id;
|
| 217 |
-
for (const message of messages) {
|
| 218 |
-
if (message.id <= delivered.current) continue;
|
| 219 |
-
delivered.current = message.id;
|
| 220 |
-
const text = message.text;
|
| 221 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
|
| 222 |
-
}
|
| 223 |
-
setMessages((current) => current.filter((message) => message.id > through));
|
| 224 |
-
}, [messages]);
|
| 225 |
-
return (text: string) => {
|
| 226 |
-
if (!text) return;
|
| 227 |
-
const message = { id: ++sequence.current, text };
|
| 228 |
-
setMessages((current) => [...current, message]);
|
| 229 |
-
};
|
| 230 |
-
}
|
| 231 |
-
|
| 232 |
export default function AutomationSurface() {
|
| 233 |
/* ⭐ T22 — SEEDED FROM THE CLIENT MEMO, so a revisit inside the freshness window never passes
|
| 234 |
through `data === null` and therefore never paints the skeleton. The lazy initialiser runs
|
|
@@ -239,7 +217,6 @@ export default function AutomationSurface() {
|
|
| 239 |
const [voiceAgents, setVoiceAgents] = useState<VoiceAgent[]>([]);
|
| 240 |
const [voiceLoadError, setVoiceLoadError] = useState("");
|
| 241 |
const [error, setError] = useState("");
|
| 242 |
-
const refuse = useRefusalToast();
|
| 243 |
const [activeId, setActiveId] = useState<string>("");
|
| 244 |
const [activeVoiceId, setActiveVoiceId] = useState<string>("");
|
| 245 |
const [railShut, setRailShut] = useState(false);
|
|
@@ -465,11 +442,9 @@ export default function AutomationSurface() {
|
|
| 465 |
const next = await load();
|
| 466 |
if (id && next) select(id);
|
| 467 |
} catch (e) {
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
setError(e instanceof AutomationError ? e.message : "The automation was not created.");
|
| 472 |
-
}
|
| 473 |
} finally {
|
| 474 |
creatingRef.current = false;
|
| 475 |
setCreatingNow(false);
|
|
|
|
| 18 |
import { Suspense, lazy, useCallback, useEffect, useRef, useState } from "react";
|
| 19 |
|
| 20 |
import type { AutomationOpenDetail } from "../apiContract";
|
| 21 |
+
import { AUTOMATION_OPEN_EVENT, UNAUTHORIZED_EVENT, currentTenant } from "../apiContract";
|
| 22 |
// ⭐ WAVE 26 · ITEM 18 / R14 + C7 — THE LOOPABLE LOOP MARK, CONSUMED, NEVER REDRAWN.
|
| 23 |
// The owner's reason is the mark's own geometry: *"these automations are basically loops."*
|
| 24 |
// C7 says consume the existing icon component and do not inline a new SVG path, and
|
|
|
|
| 207 |
* that a database can be created BY asking for an automation.
|
| 208 |
*/
|
| 209 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
export default function AutomationSurface() {
|
| 211 |
/* ⭐ T22 — SEEDED FROM THE CLIENT MEMO, so a revisit inside the freshness window never passes
|
| 212 |
through `data === null` and therefore never paints the skeleton. The lazy initialiser runs
|
|
|
|
| 217 |
const [voiceAgents, setVoiceAgents] = useState<VoiceAgent[]>([]);
|
| 218 |
const [voiceLoadError, setVoiceLoadError] = useState("");
|
| 219 |
const [error, setError] = useState("");
|
|
|
|
| 220 |
const [activeId, setActiveId] = useState<string>("");
|
| 221 |
const [activeVoiceId, setActiveVoiceId] = useState<string>("");
|
| 222 |
const [railShut, setRailShut] = useState(false);
|
|
|
|
| 442 |
const next = await load();
|
| 443 |
if (id && next) select(id);
|
| 444 |
} catch (e) {
|
| 445 |
+
setError(
|
| 446 |
+
e instanceof AutomationError ? e.message : "The automation was not created."
|
| 447 |
+
);
|
|
|
|
|
|
|
| 448 |
} finally {
|
| 449 |
creatingRef.current = false;
|
| 450 |
setCreatingNow(false);
|
web/src/connectors/ConnectorModal.tsx
CHANGED
|
@@ -1371,7 +1371,6 @@ export default function ConnectorModal({
|
|
| 1371 |
<RelationshipDiagram
|
| 1372 |
connector={row.label}
|
| 1373 |
graph={deferredGraph ? deferredGraph.graph : load.detail.relationships}
|
| 1374 |
-
onRetry={deferredGraph ? () => setGraphRead(null) : reread}
|
| 1375 |
/>
|
| 1376 |
);
|
| 1377 |
}
|
|
|
|
| 1371 |
<RelationshipDiagram
|
| 1372 |
connector={row.label}
|
| 1373 |
graph={deferredGraph ? deferredGraph.graph : load.detail.relationships}
|
|
|
|
| 1374 |
/>
|
| 1375 |
);
|
| 1376 |
}
|
web/src/connectors/DatabasesTab.tsx
CHANGED
|
@@ -58,30 +58,7 @@
|
|
| 58 |
|
| 59 |
import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
|
| 60 |
import type { MouseEvent } from "react";
|
| 61 |
-
import { API_V1, CREDENTIALS,
|
| 62 |
-
|
| 63 |
-
function useRefusalToast() {
|
| 64 |
-
const [messages, setMessages] = useState<{ id: number; text: string }[]>([]);
|
| 65 |
-
const sequence = useRef(0);
|
| 66 |
-
const delivered = useRef(0);
|
| 67 |
-
useEffect(() => {
|
| 68 |
-
if (!messages.length) return;
|
| 69 |
-
const through = messages[messages.length - 1].id;
|
| 70 |
-
for (const message of messages) {
|
| 71 |
-
if (message.id <= delivered.current) continue;
|
| 72 |
-
delivered.current = message.id;
|
| 73 |
-
const text = message.text;
|
| 74 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
|
| 75 |
-
}
|
| 76 |
-
setMessages((current) => current.filter((message) => message.id > through));
|
| 77 |
-
}, [messages]);
|
| 78 |
-
return (text: string) => {
|
| 79 |
-
if (!text) return;
|
| 80 |
-
const message = { id: ++sequence.current, text };
|
| 81 |
-
setMessages((current) => [...current, message]);
|
| 82 |
-
};
|
| 83 |
-
}
|
| 84 |
-
|
| 85 |
import { ConfirmDialog } from "../ui/ConfirmDialog";
|
| 86 |
import { useEscapeClose } from "../ui/useEscapeClose";
|
| 87 |
import { DatabaseFieldsEditor } from "../settings/ManageDatabase";
|
|
@@ -840,7 +817,6 @@ async function readSyncNow(path: string, provider: string): Promise<
|
|
| 840 |
}
|
| 841 |
|
| 842 |
export function useSyncNow(capability: ConnectorDetail["syncNow"]) {
|
| 843 |
-
const databaseRefusal = useRefusalToast();
|
| 844 |
const path = capability?.path;
|
| 845 |
const provider = capability?.provider;
|
| 846 |
const [receipt, setReceipt] = useState<SyncNowReceipt | null>(null);
|
|
@@ -884,8 +860,7 @@ export function useSyncNow(capability: ConnectorDetail["syncNow"]) {
|
|
| 884 |
const error = await write(path, "POST", {});
|
| 885 |
postInFlight.current = false;
|
| 886 |
if (generation !== readGeneration.current) return;
|
| 887 |
-
setRequestError(
|
| 888 |
-
if (error) databaseRefusal(error);
|
| 889 |
// Read after every response, including an uncertain network failure. The server may have
|
| 890 |
// accepted the intent already. Only a readback may claim that it is queued or finished.
|
| 891 |
setReads((value) => value + 1);
|
|
@@ -1312,7 +1287,6 @@ function ScraperDatabases({
|
|
| 1312 |
const [postType, setPostType] = useState("video");
|
| 1313 |
const [preview, setPreview] = useState<ScraperPreview | null>(null);
|
| 1314 |
const [busy, setBusy] = useState("");
|
| 1315 |
-
const databaseRefusal = useRefusalToast();
|
| 1316 |
const [error, setError] = useState("");
|
| 1317 |
const [status, setStatus] = useState("");
|
| 1318 |
const [tabs, setTabs] = useState<Record<string, ScraperDatabaseTab>>({});
|
|
@@ -1342,9 +1316,9 @@ function ScraperDatabases({
|
|
| 1342 |
setBusy("create"); setError(""); setStatus("");
|
| 1343 |
const answer = await scraperPost("/connectors/scraper/databases", { label, recipe: preview.recipe });
|
| 1344 |
setBusy("");
|
| 1345 |
-
if (answer.ok === false) {
|
| 1346 |
const key = syncText(answer.payload.key);
|
| 1347 |
-
if (!key) {
|
| 1348 |
setCreating(false); setPreview(null); setLabel(""); setSeed(""); setSearch(""); setGeography("");
|
| 1349 |
setStatus("Database created. No provider was called and no cost was incurred.");
|
| 1350 |
signal(WORKSPACE_STALE_EVENT);
|
|
@@ -1356,7 +1330,7 @@ function ScraperDatabases({
|
|
| 1356 |
setBusy(database.key); setError(""); setStatus("");
|
| 1357 |
const answer = await scraperPost(database.runPath, {});
|
| 1358 |
setBusy("");
|
| 1359 |
-
if (answer.ok === false) {
|
| 1360 |
const state = syncText(answer.payload.state) || "finished";
|
| 1361 |
setStatus(`${database.label} run ${state}. Run history has been refreshed.`);
|
| 1362 |
signal(WORKSPACE_STALE_EVENT);
|
|
@@ -1859,7 +1833,6 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
|
|
| 1859 |
const [autoEnableResults, setAutoEnableResults] = useState<Record<string, string>>(
|
| 1860 |
() => reveal?.key && reveal.status ? { [reveal.key]: reveal.status } : {}
|
| 1861 |
);
|
| 1862 |
-
const databaseRefusal = useRefusalToast();
|
| 1863 |
const [error, setError] = useState("");
|
| 1864 |
const [jobs, setJobs] = useState<MaterializationJob[]>([]);
|
| 1865 |
const [jobError, setJobError] = useState("");
|
|
@@ -1960,7 +1933,7 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
|
|
| 1960 |
const answer = await readDependents(database.key);
|
| 1961 |
if (!answer.ok) {
|
| 1962 |
setBusy("");
|
| 1963 |
-
|
| 1964 |
`${database.label} was left switched on: the check for what depends on it did not ` +
|
| 1965 |
`answer. ${answer.message}`
|
| 1966 |
);
|
|
@@ -1970,10 +1943,8 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
|
|
| 1970 |
setBusy("");
|
| 1971 |
// The server's sentence, verbatim. C3 omits every zero-count kind, so this cannot
|
| 1972 |
// claim a count it does not have.
|
| 1973 |
-
|
| 1974 |
-
|
| 1975 |
-
setRefusalDependents((current) => ({ ...current, [database.key]: answer.dependents }));
|
| 1976 |
-
} else databaseRefusal(answer.refusal);
|
| 1977 |
return;
|
| 1978 |
}
|
| 1979 |
if (!usesProviderEnablement) {
|
|
@@ -2053,7 +2024,6 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
|
|
| 2053 |
|
| 2054 |
const failed: PendingDatabaseChanges = { tables: {}, fields: {}, names: {} };
|
| 2055 |
const failures: string[] = [];
|
| 2056 |
-
const fieldFailures: string[] = [];
|
| 2057 |
setBusy("save");
|
| 2058 |
setError("");
|
| 2059 |
|
|
@@ -2112,7 +2082,7 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
|
|
| 2112 |
const subject = fieldDatabase
|
| 2113 |
? `${fieldDatabase.label}, ${field?.label || fieldKey}`
|
| 2114 |
: fieldKey;
|
| 2115 |
-
|
| 2116 |
} else signal(WORKSPACE_STALE_EVENT);
|
| 2117 |
}
|
| 2118 |
|
|
@@ -2133,8 +2103,7 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
|
|
| 2133 |
setPending(failed);
|
| 2134 |
onPendingChange(pendingChangeCount(failed));
|
| 2135 |
setBusy("");
|
| 2136 |
-
setError(
|
| 2137 |
-
databaseRefusal(failures.join(" "));
|
| 2138 |
if (detail.materialization && row.key !== "amazon_sp") watchMaterialization(detail.materialization);
|
| 2139 |
// One batch gets one fresh detail payload. That payload also carries the newly derived graph.
|
| 2140 |
onChanged();
|
|
@@ -2155,7 +2124,7 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
|
|
| 2155 |
const answer = await countSourceRows(exact);
|
| 2156 |
setCensusBusy(false);
|
| 2157 |
if (!answer.ok) {
|
| 2158 |
-
|
| 2159 |
return;
|
| 2160 |
}
|
| 2161 |
setExactCounts(answer.exactCounts);
|
|
|
|
| 58 |
|
| 59 |
import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
|
| 60 |
import type { MouseEvent } from "react";
|
| 61 |
+
import { API_V1, CREDENTIALS, WORKSPACE_STALE_EVENT, signal } from "../apiContract";
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
import { ConfirmDialog } from "../ui/ConfirmDialog";
|
| 63 |
import { useEscapeClose } from "../ui/useEscapeClose";
|
| 64 |
import { DatabaseFieldsEditor } from "../settings/ManageDatabase";
|
|
|
|
| 817 |
}
|
| 818 |
|
| 819 |
export function useSyncNow(capability: ConnectorDetail["syncNow"]) {
|
|
|
|
| 820 |
const path = capability?.path;
|
| 821 |
const provider = capability?.provider;
|
| 822 |
const [receipt, setReceipt] = useState<SyncNowReceipt | null>(null);
|
|
|
|
| 860 |
const error = await write(path, "POST", {});
|
| 861 |
postInFlight.current = false;
|
| 862 |
if (generation !== readGeneration.current) return;
|
| 863 |
+
setRequestError(error);
|
|
|
|
| 864 |
// Read after every response, including an uncertain network failure. The server may have
|
| 865 |
// accepted the intent already. Only a readback may claim that it is queued or finished.
|
| 866 |
setReads((value) => value + 1);
|
|
|
|
| 1287 |
const [postType, setPostType] = useState("video");
|
| 1288 |
const [preview, setPreview] = useState<ScraperPreview | null>(null);
|
| 1289 |
const [busy, setBusy] = useState("");
|
|
|
|
| 1290 |
const [error, setError] = useState("");
|
| 1291 |
const [status, setStatus] = useState("");
|
| 1292 |
const [tabs, setTabs] = useState<Record<string, ScraperDatabaseTab>>({});
|
|
|
|
| 1316 |
setBusy("create"); setError(""); setStatus("");
|
| 1317 |
const answer = await scraperPost("/connectors/scraper/databases", { label, recipe: preview.recipe });
|
| 1318 |
setBusy("");
|
| 1319 |
+
if (answer.ok === false) { setError(answer.message); return; }
|
| 1320 |
const key = syncText(answer.payload.key);
|
| 1321 |
+
if (!key) { setError("The server created no readable database."); return; }
|
| 1322 |
setCreating(false); setPreview(null); setLabel(""); setSeed(""); setSearch(""); setGeography("");
|
| 1323 |
setStatus("Database created. No provider was called and no cost was incurred.");
|
| 1324 |
signal(WORKSPACE_STALE_EVENT);
|
|
|
|
| 1330 |
setBusy(database.key); setError(""); setStatus("");
|
| 1331 |
const answer = await scraperPost(database.runPath, {});
|
| 1332 |
setBusy("");
|
| 1333 |
+
if (answer.ok === false) { setError(answer.message); return; }
|
| 1334 |
const state = syncText(answer.payload.state) || "finished";
|
| 1335 |
setStatus(`${database.label} run ${state}. Run history has been refreshed.`);
|
| 1336 |
signal(WORKSPACE_STALE_EVENT);
|
|
|
|
| 1833 |
const [autoEnableResults, setAutoEnableResults] = useState<Record<string, string>>(
|
| 1834 |
() => reveal?.key && reveal.status ? { [reveal.key]: reveal.status } : {}
|
| 1835 |
);
|
|
|
|
| 1836 |
const [error, setError] = useState("");
|
| 1837 |
const [jobs, setJobs] = useState<MaterializationJob[]>([]);
|
| 1838 |
const [jobError, setJobError] = useState("");
|
|
|
|
| 1933 |
const answer = await readDependents(database.key);
|
| 1934 |
if (!answer.ok) {
|
| 1935 |
setBusy("");
|
| 1936 |
+
setError(
|
| 1937 |
`${database.label} was left switched on: the check for what depends on it did not ` +
|
| 1938 |
`answer. ${answer.message}`
|
| 1939 |
);
|
|
|
|
| 1943 |
setBusy("");
|
| 1944 |
// The server's sentence, verbatim. C3 omits every zero-count kind, so this cannot
|
| 1945 |
// claim a count it does not have.
|
| 1946 |
+
setRefusals((current) => ({ ...current, [database.key]: answer.refusal }));
|
| 1947 |
+
setRefusalDependents((current) => ({ ...current, [database.key]: answer.dependents }));
|
|
|
|
|
|
|
| 1948 |
return;
|
| 1949 |
}
|
| 1950 |
if (!usesProviderEnablement) {
|
|
|
|
| 2024 |
|
| 2025 |
const failed: PendingDatabaseChanges = { tables: {}, fields: {}, names: {} };
|
| 2026 |
const failures: string[] = [];
|
|
|
|
| 2027 |
setBusy("save");
|
| 2028 |
setError("");
|
| 2029 |
|
|
|
|
| 2082 |
const subject = fieldDatabase
|
| 2083 |
? `${fieldDatabase.label}, ${field?.label || fieldKey}`
|
| 2084 |
: fieldKey;
|
| 2085 |
+
failures.push(`${subject}: ${message}`);
|
| 2086 |
} else signal(WORKSPACE_STALE_EVENT);
|
| 2087 |
}
|
| 2088 |
|
|
|
|
| 2103 |
setPending(failed);
|
| 2104 |
onPendingChange(pendingChangeCount(failed));
|
| 2105 |
setBusy("");
|
| 2106 |
+
setError(failures.join(" "));
|
|
|
|
| 2107 |
if (detail.materialization && row.key !== "amazon_sp") watchMaterialization(detail.materialization);
|
| 2108 |
// One batch gets one fresh detail payload. That payload also carries the newly derived graph.
|
| 2109 |
onChanged();
|
|
|
|
| 2124 |
const answer = await countSourceRows(exact);
|
| 2125 |
setCensusBusy(false);
|
| 2126 |
if (!answer.ok) {
|
| 2127 |
+
setError(answer.message);
|
| 2128 |
return;
|
| 2129 |
}
|
| 2130 |
setExactCounts(answer.exactCounts);
|
web/src/connectors/MonidRunDialog.tsx
CHANGED
|
@@ -51,7 +51,7 @@
|
|
| 51 |
// ---------------------------------------------------------------------------
|
| 52 |
|
| 53 |
import { useEffect, useMemo, useRef, useState } from "react";
|
| 54 |
-
import { API_V1, CREDENTIALS
|
| 55 |
import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
|
| 56 |
import "../styles/wave49/connectors.css";
|
| 57 |
|
|
@@ -146,28 +146,6 @@ type Phase =
|
|
| 146 |
* THE DIALOG. Portalled, focus-trapped, dismissed deliberately or by Escape, and it hands
|
| 147 |
* focus back to the control that opened it.
|
| 148 |
*/
|
| 149 |
-
function useRefusalToast() {
|
| 150 |
-
const [messages, setMessages] = useState<{ id: number; text: string }[]>([]);
|
| 151 |
-
const sequence = useRef(0);
|
| 152 |
-
const delivered = useRef(0);
|
| 153 |
-
useEffect(() => {
|
| 154 |
-
if (!messages.length) return;
|
| 155 |
-
const through = messages[messages.length - 1].id;
|
| 156 |
-
for (const message of messages) {
|
| 157 |
-
if (message.id <= delivered.current) continue;
|
| 158 |
-
delivered.current = message.id;
|
| 159 |
-
const text = message.text;
|
| 160 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
|
| 161 |
-
}
|
| 162 |
-
setMessages((current) => current.filter((message) => message.id > through));
|
| 163 |
-
}, [messages]);
|
| 164 |
-
return (text: string) => {
|
| 165 |
-
if (!text) return;
|
| 166 |
-
const message = { id: ++sequence.current, text };
|
| 167 |
-
setMessages((current) => [...current, message]);
|
| 168 |
-
};
|
| 169 |
-
}
|
| 170 |
-
|
| 171 |
export default function MonidRunDialog({
|
| 172 |
label,
|
| 173 |
onClose,
|
|
@@ -193,8 +171,6 @@ export default function MonidRunDialog({
|
|
| 193 |
const [meta, setMeta] = useState<MonidRunMeta | null>(null);
|
| 194 |
const [phase, setPhase] = useState<Phase>({ kind: "meta" });
|
| 195 |
const [text, setText] = useState("");
|
| 196 |
-
const lifetime = useRef<AbortController | null>(null);
|
| 197 |
-
const refuse = useRefusalToast();
|
| 198 |
|
| 199 |
useOverlayLayer({
|
| 200 |
panelRef,
|
|
@@ -208,12 +184,10 @@ export default function MonidRunDialog({
|
|
| 208 |
|
| 209 |
useEffect(() => {
|
| 210 |
let dead = false;
|
| 211 |
-
const controller = new AbortController();
|
| 212 |
-
lifetime.current = controller;
|
| 213 |
void (async () => {
|
| 214 |
try {
|
| 215 |
const res = await fetch(`${API_V1}/monid/amazon-reviews/meta`, {
|
| 216 |
-
credentials: CREDENTIALS,
|
| 217 |
});
|
| 218 |
const body = (await res.json().catch(() => null)) as
|
| 219 |
| (MonidRunMeta & { error?: { message?: string; code?: string } })
|
|
@@ -224,23 +198,16 @@ export default function MonidRunDialog({
|
|
| 224 |
kind: "refused",
|
| 225 |
message: reviewRefusal(body?.error?.code, res.status),
|
| 226 |
});
|
| 227 |
-
refuse(reviewRefusal(body?.error?.code, res.status));
|
| 228 |
return;
|
| 229 |
}
|
| 230 |
setMeta(body);
|
| 231 |
setPhase({ kind: "ready" });
|
| 232 |
-
if (!body.configured) refuse("Not connected.");
|
| 233 |
-
else if (!body.canRun) refuse("Administrator only.");
|
| 234 |
} catch {
|
| 235 |
-
if (!dead) {
|
| 236 |
-
setPhase({ kind: "refused", message: "Cannot reach the server." });
|
| 237 |
-
refuse("Cannot reach the server.");
|
| 238 |
-
}
|
| 239 |
}
|
| 240 |
})();
|
| 241 |
return () => {
|
| 242 |
dead = true;
|
| 243 |
-
controller.abort();
|
| 244 |
};
|
| 245 |
}, []);
|
| 246 |
|
|
@@ -258,33 +225,27 @@ export default function MonidRunDialog({
|
|
| 258 |
|
| 259 |
const submit = async () => {
|
| 260 |
if (!canSubmit) return;
|
| 261 |
-
const request = lifetime.current?.signal;
|
| 262 |
-
if (!request || request.aborted) return;
|
| 263 |
setPhase({ kind: "running" });
|
| 264 |
try {
|
| 265 |
const res = await fetch(`${API_V1}/monid/amazon-reviews/run`, {
|
| 266 |
method: "POST",
|
| 267 |
credentials: CREDENTIALS,
|
| 268 |
headers: { "Content-Type": "application/json" },
|
| 269 |
-
body: JSON.stringify({ asins: parsed.good }),
|
| 270 |
});
|
| 271 |
const body = (await res.json().catch(() => null)) as
|
| 272 |
| (MonidRunResult & { error?: { message?: string; code?: string } })
|
| 273 |
| null;
|
| 274 |
-
if (request.aborted) return;
|
| 275 |
if (!res.ok || !body) {
|
| 276 |
setPhase({
|
| 277 |
kind: "refused",
|
| 278 |
message: reviewRefusal(body?.error?.code, res.status),
|
| 279 |
});
|
| 280 |
-
refuse(reviewRefusal(body?.error?.code, res.status));
|
| 281 |
return;
|
| 282 |
}
|
| 283 |
setPhase({ kind: "done", result: body });
|
| 284 |
} catch {
|
| 285 |
-
if (request.aborted) return;
|
| 286 |
setPhase({ kind: "refused", message: "Cannot reach the server." });
|
| 287 |
-
refuse("Cannot reach the server.");
|
| 288 |
}
|
| 289 |
};
|
| 290 |
|
|
@@ -328,6 +289,23 @@ export default function MonidRunDialog({
|
|
| 328 |
</p>
|
| 329 |
) : null}
|
| 330 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
|
| 332 |
{meta && phase.kind === "done" ? (
|
| 333 |
<div className="monid-run-done" role="status" aria-live="polite">
|
|
|
|
| 51 |
// ---------------------------------------------------------------------------
|
| 52 |
|
| 53 |
import { useEffect, useMemo, useRef, useState } from "react";
|
| 54 |
+
import { API_V1, CREDENTIALS } from "../apiContract";
|
| 55 |
import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
|
| 56 |
import "../styles/wave49/connectors.css";
|
| 57 |
|
|
|
|
| 146 |
* THE DIALOG. Portalled, focus-trapped, dismissed deliberately or by Escape, and it hands
|
| 147 |
* focus back to the control that opened it.
|
| 148 |
*/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
export default function MonidRunDialog({
|
| 150 |
label,
|
| 151 |
onClose,
|
|
|
|
| 171 |
const [meta, setMeta] = useState<MonidRunMeta | null>(null);
|
| 172 |
const [phase, setPhase] = useState<Phase>({ kind: "meta" });
|
| 173 |
const [text, setText] = useState("");
|
|
|
|
|
|
|
| 174 |
|
| 175 |
useOverlayLayer({
|
| 176 |
panelRef,
|
|
|
|
| 184 |
|
| 185 |
useEffect(() => {
|
| 186 |
let dead = false;
|
|
|
|
|
|
|
| 187 |
void (async () => {
|
| 188 |
try {
|
| 189 |
const res = await fetch(`${API_V1}/monid/amazon-reviews/meta`, {
|
| 190 |
+
credentials: CREDENTIALS,
|
| 191 |
});
|
| 192 |
const body = (await res.json().catch(() => null)) as
|
| 193 |
| (MonidRunMeta & { error?: { message?: string; code?: string } })
|
|
|
|
| 198 |
kind: "refused",
|
| 199 |
message: reviewRefusal(body?.error?.code, res.status),
|
| 200 |
});
|
|
|
|
| 201 |
return;
|
| 202 |
}
|
| 203 |
setMeta(body);
|
| 204 |
setPhase({ kind: "ready" });
|
|
|
|
|
|
|
| 205 |
} catch {
|
| 206 |
+
if (!dead) setPhase({ kind: "refused", message: "Cannot reach the server." });
|
|
|
|
|
|
|
|
|
|
| 207 |
}
|
| 208 |
})();
|
| 209 |
return () => {
|
| 210 |
dead = true;
|
|
|
|
| 211 |
};
|
| 212 |
}, []);
|
| 213 |
|
|
|
|
| 225 |
|
| 226 |
const submit = async () => {
|
| 227 |
if (!canSubmit) return;
|
|
|
|
|
|
|
| 228 |
setPhase({ kind: "running" });
|
| 229 |
try {
|
| 230 |
const res = await fetch(`${API_V1}/monid/amazon-reviews/run`, {
|
| 231 |
method: "POST",
|
| 232 |
credentials: CREDENTIALS,
|
| 233 |
headers: { "Content-Type": "application/json" },
|
| 234 |
+
body: JSON.stringify({ asins: parsed.good }),
|
| 235 |
});
|
| 236 |
const body = (await res.json().catch(() => null)) as
|
| 237 |
| (MonidRunResult & { error?: { message?: string; code?: string } })
|
| 238 |
| null;
|
|
|
|
| 239 |
if (!res.ok || !body) {
|
| 240 |
setPhase({
|
| 241 |
kind: "refused",
|
| 242 |
message: reviewRefusal(body?.error?.code, res.status),
|
| 243 |
});
|
|
|
|
| 244 |
return;
|
| 245 |
}
|
| 246 |
setPhase({ kind: "done", result: body });
|
| 247 |
} catch {
|
|
|
|
| 248 |
setPhase({ kind: "refused", message: "Cannot reach the server." });
|
|
|
|
| 249 |
}
|
| 250 |
};
|
| 251 |
|
|
|
|
| 289 |
</p>
|
| 290 |
) : null}
|
| 291 |
|
| 292 |
+
{phase.kind === "refused" ? (
|
| 293 |
+
<p className="monid-run-refusal" role="alert">
|
| 294 |
+
{phase.message}
|
| 295 |
+
</p>
|
| 296 |
+
) : null}
|
| 297 |
+
|
| 298 |
+
{meta && !meta.configured ? (
|
| 299 |
+
<p className="monid-run-refusal" role="alert">
|
| 300 |
+
Not connected.
|
| 301 |
+
</p>
|
| 302 |
+
) : null}
|
| 303 |
+
|
| 304 |
+
{meta && meta.configured && !meta.canRun ? (
|
| 305 |
+
<p className="monid-run-refusal" role="alert">
|
| 306 |
+
Administrator only.
|
| 307 |
+
</p>
|
| 308 |
+
) : null}
|
| 309 |
|
| 310 |
{meta && phase.kind === "done" ? (
|
| 311 |
<div className="monid-run-done" role="status" aria-live="polite">
|
web/src/connectors/RelationshipDiagram.tsx
CHANGED
|
@@ -685,12 +685,9 @@ export function edgeSummary(connector: string, graph: DiagramInput): string {
|
|
| 685 |
export default function RelationshipDiagram({
|
| 686 |
connector,
|
| 687 |
graph,
|
| 688 |
-
onRetry,
|
| 689 |
}: {
|
| 690 |
connector: string;
|
| 691 |
graph: ConnectorRelationshipGraph;
|
| 692 |
-
/** S76-T23: re-reads the graph after a refusal; the owner of the fetch supplies it. */
|
| 693 |
-
onRetry?: () => void;
|
| 694 |
}) {
|
| 695 |
const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
|
| 696 |
const scrollRef = useRef<HTMLDivElement>(null);
|
|
@@ -786,16 +783,9 @@ export default function RelationshipDiagram({
|
|
| 786 |
|
| 787 |
if (graph.status !== "ready") {
|
| 788 |
return (
|
| 789 |
-
<
|
| 790 |
-
|
| 791 |
-
|
| 792 |
-
</p>
|
| 793 |
-
{onRetry ? (
|
| 794 |
-
<button className="conn-modal-retry" type="button" onClick={() => onRetry()}>
|
| 795 |
-
Try again
|
| 796 |
-
</button>
|
| 797 |
-
) : null}
|
| 798 |
-
</div>
|
| 799 |
);
|
| 800 |
}
|
| 801 |
if (!graph.tables.length) {
|
|
|
|
| 685 |
export default function RelationshipDiagram({
|
| 686 |
connector,
|
| 687 |
graph,
|
|
|
|
| 688 |
}: {
|
| 689 |
connector: string;
|
| 690 |
graph: ConnectorRelationshipGraph;
|
|
|
|
|
|
|
| 691 |
}) {
|
| 692 |
const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
|
| 693 |
const scrollRef = useRef<HTMLDivElement>(null);
|
|
|
|
| 783 |
|
| 784 |
if (graph.status !== "ready") {
|
| 785 |
return (
|
| 786 |
+
<p className="conn-rd-note" role="status">
|
| 787 |
+
{graph.reason || "This connection did not make an actual relationship graph available."}
|
| 788 |
+
</p>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 789 |
);
|
| 790 |
}
|
| 791 |
if (!graph.tables.length) {
|
web/src/customer-grid/CatalogView.tsx
CHANGED
|
@@ -97,7 +97,6 @@ import { applyPrintCss, awaitImages, printOnce } from "./catalogPrint";
|
|
| 97 |
import { formatDisplay } from "./display";
|
| 98 |
import "./catalog.css";
|
| 99 |
import "../styles/sdlc76/catalog-library.css";
|
| 100 |
-
import "../styles/sdlc76/catalog-editor.css";
|
| 101 |
|
| 102 |
/**
|
| 103 |
* ⭐⭐ W37 CONTRACT C3 — THE PER-VIEW CATALOG SPEC, client side. Mirrors
|
|
@@ -1739,7 +1738,7 @@ export const CatalogView = memo(function CatalogView({
|
|
| 1739 |
return (
|
| 1740 |
<div
|
| 1741 |
className="cg-cat"
|
| 1742 |
-
style={locked ? { gridTemplateColumns: "
|
| 1743 |
onPointerDown={foldNavOnWorkSurface}
|
| 1744 |
>
|
| 1745 |
{/* ------------------------------------------------------------ rail */}
|
|
|
|
| 97 |
import { formatDisplay } from "./display";
|
| 98 |
import "./catalog.css";
|
| 99 |
import "../styles/sdlc76/catalog-library.css";
|
|
|
|
| 100 |
|
| 101 |
/**
|
| 102 |
* ⭐⭐ W37 CONTRACT C3 — THE PER-VIEW CATALOG SPEC, client side. Mirrors
|
|
|
|
| 1738 |
return (
|
| 1739 |
<div
|
| 1740 |
className="cg-cat"
|
| 1741 |
+
style={locked ? { gridTemplateColumns: "232px minmax(0, 1fr)" } : undefined}
|
| 1742 |
onPointerDown={foldNavOnWorkSurface}
|
| 1743 |
>
|
| 1744 |
{/* ------------------------------------------------------------ rail */}
|
web/src/customer-grid/CustomerGrid.tsx
CHANGED
|
@@ -30,7 +30,7 @@ import { addressScope, embedStorageKey, hostedFirstView, useCustomerData, useHos
|
|
| 30 |
usePersonalGridLayout, withoutRetiredChoiceEdits } from "./useCustomerData";
|
| 31 |
import type { SurfaceAddress } from "./useCustomerData";
|
| 32 |
import { AMAZON_STILL_LOADING_MESSAGE } from "./mirrorLoading";
|
| 33 |
-
import type { RowWindowRequest, SurfaceScope
|
| 34 |
import { mutateQueryWorkspace, QUERY_BINDING_EVENT, refuseQueryMutation } from "../query/queryApi";
|
| 35 |
import type { QueryVirtualBinding } from "../query/queryApi";
|
| 36 |
import { acceptsQueryPreview, routeQueryViewMutation } from "./queryPreview";
|
|
@@ -197,7 +197,7 @@ import { avatarInitials, formatDisplay, imageCellRenderer, matchChoices, pickerT
|
|
| 197 |
ratingCellRenderer, setAvatarRepaint, userCellRenderer } from "./cells";
|
| 198 |
// ⭐ W50-T05 — ONE numeric reading of a stored cell, the same one `aggregations.ts` folds with.
|
| 199 |
// A second parse here is how a cell painted blank while the total under it counted 1,234.50.
|
| 200 |
-
import { actionHref,
|
| 201 |
// ⭐ W50-T05 — the value/share COMPOSITION. The share arithmetic stays in `formatShare`.
|
| 202 |
import { withShare } from "../ui/fmt";
|
| 203 |
import { optionTint, pickTint } from "./choiceColors";
|
|
@@ -1105,16 +1105,6 @@ function slugify(label: string): string {
|
|
| 1105 |
);
|
| 1106 |
}
|
| 1107 |
|
| 1108 |
-
function numberBatchRefusal(fields: readonly Field[], updates: readonly Partial<Row>[]): string | undefined {
|
| 1109 |
-
const definitions = new Map(fields.map((field) => [field.key, field]));
|
| 1110 |
-
for (const row of updates) for (const [key, value] of Object.entries(row)) {
|
| 1111 |
-
const field = definitions.get(key);
|
| 1112 |
-
const reason = field && numberWriteRefusal(field, value);
|
| 1113 |
-
if (reason) return reason;
|
| 1114 |
-
}
|
| 1115 |
-
return undefined;
|
| 1116 |
-
}
|
| 1117 |
-
|
| 1118 |
interface FieldBuildExtra {
|
| 1119 |
if?: Field["if"];
|
| 1120 |
formula?: string;
|
|
@@ -1285,8 +1275,8 @@ function buildOverlayField(
|
|
| 1285 |
: {}),
|
| 1286 |
...(type === "multiselect" ? { multi: true } : {}),
|
| 1287 |
...(type === "rating" ? { max: extra?.max ?? 5 } : {}),
|
| 1288 |
-
...(extra &&
|
| 1289 |
-
? { defaultValue: extra.defaultValue
|
| 1290 |
};
|
| 1291 |
}
|
| 1292 |
|
|
@@ -1563,6 +1553,7 @@ function MirrorKanban({ table, request, field, fieldByKey, cardKeys, titleKey, s
|
|
| 1563 |
return <div className={"cg-kbview" + (clamped ? " is-clamped" : "")}
|
| 1564 |
style={{ "--cg-kb-card-h": "auto", "--cg-kb-title-h": "auto", "--cg-kb-cell-h": "auto",
|
| 1565 |
"--cg-kb-line-h": "1.4em", "--cg-kb-card-gap": "8px" } as CSSProperties}>
|
|
|
|
| 1566 |
{error ? <MirrorModeFailure message={error} retry={retry} /> : !data ? <MirrorModeSkeleton />
|
| 1567 |
: data.groups.length === 0 ? <div className="cg-mode-empty">No records match this view.</div>
|
| 1568 |
: <div className="cg-kb-lanes">{data.groups.map((group) => {
|
|
@@ -2470,27 +2461,10 @@ function CustomerGrid(props: CustomerGridProps = {}) {
|
|
| 2470 |
return <CustomerGridSurface {...props} queryBinding={queryBinding} />;
|
| 2471 |
}
|
| 2472 |
|
| 2473 |
-
|
| 2474 |
-
restriction?: FilterTree): Pick<RowWindowRequest, "filters" | "filterConj"> {
|
| 2475 |
-
if (!restriction?.nodes?.length) return request;
|
| 2476 |
-
return {
|
| 2477 |
-
filterConj: "and",
|
| 2478 |
-
filters: [
|
| 2479 |
-
{ conj: restriction.conj === "or" ? "or" : "and", children: restriction.nodes },
|
| 2480 |
-
...(request.filters?.length
|
| 2481 |
-
? [{ conj: request.filterConj === "or" ? "or" as const : "and" as const,
|
| 2482 |
-
children: request.filters }] : []),
|
| 2483 |
-
],
|
| 2484 |
-
};
|
| 2485 |
-
}
|
| 2486 |
-
|
| 2487 |
-
/** Linked grids page their immutable restrictions through the caller-owned payload seam. */
|
| 2488 |
function useRecordIdWindow(scope: SurfaceScope, ids: readonly number[] | undefined,
|
| 2489 |
-
related: RelatedPin | null, initialPage?: RecordIdInitialPage, idsPending = false, cellView = false
|
| 2490 |
-
|
| 2491 |
-
const candidates = !!selectionFilter?.nodes?.length;
|
| 2492 |
-
const baseKey = JSON.stringify([scope, ids, related, initialPage, idsPending, cellView]);
|
| 2493 |
-
const key = candidates ? baseKey + "::" + JSON.stringify(selectionFilter) : baseKey;
|
| 2494 |
const appliedCellFilters = cellView && ids !== undefined;
|
| 2495 |
const seed = !idsPending && ids !== undefined && !related && initialPage && initialPage.offset === 0
|
| 2496 |
? initialPage.payload : null;
|
|
@@ -2506,9 +2480,7 @@ function useRecordIdWindow(scope: SurfaceScope, ids: readonly number[] | undefin
|
|
| 2506 |
key: string; payload: CustomersPayload | null; pending: boolean;
|
| 2507 |
} | null>(null);
|
| 2508 |
const requestWindow = useCallback((req: RowWindowRequest, fresh = false) => {
|
| 2509 |
-
if (
|
| 2510 |
-
if (idsPending || ids === undefined) return;
|
| 2511 |
-
} else if (idsPending) return;
|
| 2512 |
const seq = ++sequence.current;
|
| 2513 |
lastRequest.current = req;
|
| 2514 |
if (!fresh && seed && initialPage && req.offset === 0
|
|
@@ -2526,22 +2498,11 @@ function useRecordIdWindow(scope: SurfaceScope, ids: readonly number[] | undefin
|
|
| 2526 |
return;
|
| 2527 |
}
|
| 2528 |
setPage((prev) => ({ key, payload: prev?.key === key ? prev.payload : null, pending: true }));
|
| 2529 |
-
void fetchTableWindow(scope, { ...req,
|
| 2530 |
-
...(candidates ? linkSelectionPredicate(req, selectionFilter) : {}),
|
| 2531 |
-
...(ids !== undefined ? { ids } : {}), related }).then((payload) => {
|
| 2532 |
if (seq !== sequence.current || currentKey.current !== key) return;
|
| 2533 |
-
if (candidates && selectionFilter && payload && unresolvedConditions(selectionFilter.nodes, {
|
| 2534 |
-
fieldByKey: new Map(payload.fields.map((field) => [field.key, field])), today: payload.today,
|
| 2535 |
-
}) > 0) {
|
| 2536 |
-
setPage({ key, payload: null, pending: false });
|
| 2537 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: {
|
| 2538 |
-
text: "The link condition is unavailable. Ask the field owner to update it.", tone: "error",
|
| 2539 |
-
} }));
|
| 2540 |
-
return;
|
| 2541 |
-
}
|
| 2542 |
setPage({ key, payload, pending: false });
|
| 2543 |
});
|
| 2544 |
-
}, [scope, ids, related, key, seed, initialPage, idsPending, appliedCellFilters
|
| 2545 |
useEffect(() => {
|
| 2546 |
const refresh = () => { if (lastRequest.current) requestWindow(lastRequest.current, true); };
|
| 2547 |
// React can replay effect setup after cancelling its first request in StrictMode.
|
|
@@ -2554,7 +2515,7 @@ function useRecordIdWindow(scope: SurfaceScope, ids: readonly number[] | undefin
|
|
| 2554 |
}, [requestWindow]);
|
| 2555 |
return {
|
| 2556 |
payload: idsPending ? null : page?.key === key ? page.payload : seed,
|
| 2557 |
-
pending: idsPending || (page?.key === key ? page.pending : !seed &&
|
| 2558 |
requestWindow,
|
| 2559 |
};
|
| 2560 |
}
|
|
@@ -2639,9 +2600,7 @@ function CustomerGridSurface({
|
|
| 2639 |
const embeddedIdsKey = recordIdsKey(embeddedPayload === undefined ? embeddedRecordIds : undefined);
|
| 2640 |
const embeddedIds = useMemo<readonly number[] | undefined>(
|
| 2641 |
() => embeddedIdsKey ? JSON.parse(embeddedIdsKey) as number[] : undefined, [embeddedIdsKey]);
|
| 2642 |
-
const
|
| 2643 |
-
const idWindow = useRecordIdWindow(scope, embeddedIds, relatedPin, embeddedInitialPage, embeddedIdsPending, cellView,
|
| 2644 |
-
selectionWindow ? embeddedSelectionFilter : undefined);
|
| 2645 |
/**
|
| 2646 |
* ⭐⭐ W35-T23 (owner item 4 / R2) — **`previewReadOnly` IS GONE, AND THE SPLIT IS THE TICKET.**
|
| 2647 |
*
|
|
@@ -2755,11 +2714,9 @@ function CustomerGridSurface({
|
|
| 2755 |
related: relatedPin,
|
| 2756 |
// C3: a hosted open asks for its addressed View's rows first (`viewWindowPredicate`).
|
| 2757 |
firstView: hosted ? hostedFirstView(hostedAddress.path) : undefined,
|
| 2758 |
-
...(selectionWindow ? { embeddedPayload: idWindow.payload } : {}),
|
| 2759 |
});
|
| 2760 |
-
const windowPending = embeddedIds !== undefined ? idWindow.pending :
|
| 2761 |
-
const requestWindow = embeddedIds !== undefined ? idWindow.requestWindow
|
| 2762 |
-
: selectionWindow ? idWindow.requestWindow : ordinaryRequestWindow;
|
| 2763 |
useEffect(() => {
|
| 2764 |
onEmbeddedTotalChange?.(payload?.counts?.matched ?? null);
|
| 2765 |
}, [onEmbeddedTotalChange, payload?.counts?.matched]);
|
|
@@ -4133,30 +4090,17 @@ function CustomerGridSurface({
|
|
| 4133 |
* overlay edit rather than lost data — the alternative, blocking the paint until the POST
|
| 4134 |
* resolves, is the defect being fixed.
|
| 4135 |
*/
|
| 4136 |
-
const acceptPendingRow = useCallback((pid: number, made: TableRowAcknowledgement) => {
|
| 4137 |
-
if (workspaceScopeRef.current !== scope) return;
|
| 4138 |
-
setPendingRows((current) => current.map((row) => row.pid === pid
|
| 4139 |
-
? { ...row, ...made.values, pid: made.pid } : row));
|
| 4140 |
-
if (made.pid !== pid) setOverlayEdits((current) => {
|
| 4141 |
-
if (!current[pid]) return current;
|
| 4142 |
-
const next = { ...current, [made.pid]: { ...current[made.pid], ...current[pid] } };
|
| 4143 |
-
delete next[pid];
|
| 4144 |
-
return next;
|
| 4145 |
-
});
|
| 4146 |
-
}, [scope, setOverlayEdits]);
|
| 4147 |
-
|
| 4148 |
const appendRow = useCallback(async (): Promise<undefined> => {
|
| 4149 |
if (!canMutateRecords) return undefined;
|
| 4150 |
-
const
|
| 4151 |
const minted = mintRid();
|
| 4152 |
// S76-T28: paint the server's defaults at once. Core stores a boolean as Python's str().
|
| 4153 |
const defaults: Record<string, string> = Object.fromEntries(fields
|
| 4154 |
.filter((field) => field.defaultValue !== undefined && field.defaultValue !== null
|
| 4155 |
-
&&
|
| 4156 |
.map((field) => [field.key, typeof field.defaultValue === "boolean"
|
| 4157 |
? (field.defaultValue ? "True" : "False") : String(field.defaultValue)]));
|
| 4158 |
-
const
|
| 4159 |
-
const optimistic: Row = { ...seeded, pid: minted };
|
| 4160 |
setPendingRows((cur) => [...cur, optimistic]);
|
| 4161 |
setNewRowPid(minted);
|
| 4162 |
const made = await addTableRow(scope, seeded, minted);
|
|
@@ -4168,9 +4112,11 @@ function CustomerGridSurface({
|
|
| 4168 |
setNewRowPid(null);
|
| 4169 |
return undefined;
|
| 4170 |
}
|
| 4171 |
-
acceptPendingRow(minted, made);
|
| 4172 |
if (made.pid !== minted) {
|
| 4173 |
-
|
|
|
|
|
|
|
|
|
|
| 4174 |
}
|
| 4175 |
// R4 — the append is undoable: Ctrl+Z deletes the row it just created, and a redo restores
|
| 4176 |
// it under the SAME rid (the server's `{rid}` passthrough, C-ADDROW).
|
|
@@ -4191,7 +4137,7 @@ function CustomerGridSurface({
|
|
| 4191 |
// `undefined` is returned rather than glide's "bottom": "bottom" is resolved against the
|
| 4192 |
// rows glide knew about when the gesture started, which is the row BEFORE this one.
|
| 4193 |
return undefined;
|
| 4194 |
-
}, [canMutateRecords, scope, seedValues, mintRid, fields
|
| 4195 |
|
| 4196 |
/* wave20 item 2 — measure key + window -> the columns that display it. Built ONCE per field
|
| 4197 |
list and handed to every consumer of "which column is this rule about", so the tint
|
|
@@ -4306,7 +4252,7 @@ function CustomerGridSurface({
|
|
| 4306 |
// `TableMode` for why both engines running at once is the failure this prevents.
|
| 4307 |
// S66-T48: an id-backed grid is a window BY CONSTRUCTION (its rows only ever come from the
|
| 4308 |
// rows door), so it is windowed before its first page arrives and the pager can ask for it.
|
| 4309 |
-
const mode = embeddedIds !== undefined ? "server-windowed" :
|
| 4310 |
const serverWindowed = mode === "server-windowed";
|
| 4311 |
// Owner items 4+6 — the Cohort page's grid renders without the Views sidebar.
|
| 4312 |
const hideViews = (!hostWorkspace && !related) || payload?.workspace?.hideViews === true;
|
|
@@ -4453,10 +4399,8 @@ function CustomerGridSurface({
|
|
| 4453 |
// ⛔ THE SAVED VIEW'S OWN OBJECTS GO ON THE WIRE, UNTRANSLATED (see `windowRowsPath`).
|
| 4454 |
const windowPredicate = useMemo(
|
| 4455 |
() => windowPredicateKey(config.filters, config.filterConj, config.sorts, search)
|
| 4456 |
-
+ (embeddedIdsKey
|
| 4457 |
-
|
| 4458 |
-
[config.filters, config.filterConj, config.sorts, search, scope, embeddedIdsKey, relatedPinKey, cellView,
|
| 4459 |
-
selectionWindow, embeddedSelectionFilter]
|
| 4460 |
);
|
| 4461 |
/* HOTFIX 2026-09-24 — ONE PAGE SIZE FOR EVERY DATABASE (50 / 100 / 200, default 100). */
|
| 4462 |
const windowRequest = useCallback(
|
|
@@ -4980,10 +4924,8 @@ function CustomerGridSurface({
|
|
| 4980 |
let live = true;
|
| 4981 |
void fetchAggregates(topic.key, {
|
| 4982 |
...(embeddedIds !== undefined ? { ids: embeddedIds } : {}),
|
| 4983 |
-
..
|
| 4984 |
-
|
| 4985 |
-
filterConj: config.filterConj,
|
| 4986 |
-
}, embeddedSelectionFilter),
|
| 4987 |
search,
|
| 4988 |
/* ⭐⭐ W51-T06 / C6 — THE SAME PIN THE ROWS WINDOW CARRIES, AND THIS ONE LINE IS THE HALF
|
| 4989 |
THAT GETS LEFT OUT. Wire only the rows and a related tab shows one record's rows under
|
|
@@ -5015,7 +4957,7 @@ function CustomerGridSurface({
|
|
| 5015 |
// is part of the question, so moving between two tabs on one target table must re-ask. Its
|
| 5016 |
// identity is stable (see `relatedPinKey`), so this cannot loop.
|
| 5017 |
}, [serverWindowed, topic.key, summaryRequestKey, windowPredicate, config.groupBy, relatedPin, embeddedIds,
|
| 5018 |
-
serverAggRequestKey, cellView
|
| 5019 |
/**
|
| 5020 |
* What the bar actually paints: C1's numbers when the server answered, this browser's fold
|
| 5021 |
* over the loaded window otherwise — and the two are never mixed within one paint, because a
|
|
@@ -5070,7 +5012,7 @@ function CustomerGridSurface({
|
|
| 5070 |
);
|
| 5071 |
/** The bar renders as soon as one column resolves to something to show. Under R2's defaults
|
| 5072 |
* that is every table carrying a numeric column, which is the point of the ruling. */
|
| 5073 |
-
const summaryShown =
|
| 5074 |
const summaryColumns = useMemo(
|
| 5075 |
() => visibleCols.map((col) => ({
|
| 5076 |
key: String(col.id),
|
|
@@ -6119,11 +6061,6 @@ function CustomerGridSurface({
|
|
| 6119 |
/** ONE cell write, recorded. Every editor, picker and drag goes through this. */
|
| 6120 |
const patchAndRecord = useCallback(
|
| 6121 |
(pid: number, updates: Partial<Row>, label = "an edit") => {
|
| 6122 |
-
const reason = numberBatchRefusal(fields, [updates]);
|
| 6123 |
-
if (reason) {
|
| 6124 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text: reason, tone: "error" } }));
|
| 6125 |
-
return;
|
| 6126 |
-
}
|
| 6127 |
const changes: CellChange[] = Object.entries(updates).map(([key, value]) => ({
|
| 6128 |
pid, key,
|
| 6129 |
before: currentValue(pid, key),
|
|
@@ -6132,7 +6069,7 @@ function CustomerGridSurface({
|
|
| 6132 |
patchOverlay(pid, updates);
|
| 6133 |
recordCells(changes, label);
|
| 6134 |
},
|
| 6135 |
-
[currentValue, patchOverlay, recordCells
|
| 6136 |
);
|
| 6137 |
|
| 6138 |
const [chatOpen, setChatOpen] = useState(false);
|
|
@@ -6161,11 +6098,6 @@ function CustomerGridSurface({
|
|
| 6161 |
/** MANY cells, ONE stack entry — a paste and a bulk clear are each one user action (R4). */
|
| 6162 |
const patchManyAndRecord = useCallback(
|
| 6163 |
(writes: { pid: number; updates: Partial<Row> }[], label: string) => {
|
| 6164 |
-
const reason = numberBatchRefusal(fields, writes.map((write) => write.updates));
|
| 6165 |
-
if (reason) {
|
| 6166 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text: reason, tone: "error" } }));
|
| 6167 |
-
return;
|
| 6168 |
-
}
|
| 6169 |
const changes: CellChange[] = [];
|
| 6170 |
for (const w of writes)
|
| 6171 |
for (const [key, value] of Object.entries(w.updates))
|
|
@@ -6177,7 +6109,7 @@ function CustomerGridSurface({
|
|
| 6177 |
for (const w of writes) patchOverlay(w.pid, w.updates);
|
| 6178 |
recordCells(changes, label);
|
| 6179 |
},
|
| 6180 |
-
[currentValue, patchOverlay, recordCells
|
| 6181 |
);
|
| 6182 |
const bulkEditableFields = useMemo(
|
| 6183 |
() => fields.filter((field) => (
|
|
@@ -6194,11 +6126,6 @@ function CustomerGridSurface({
|
|
| 6194 |
const applyBulkUpdate = useCallback(async () => {
|
| 6195 |
if (!bulkField || bulkSelectedCount === 0 || serverBulkPending) return;
|
| 6196 |
const value = bulkField.type === "checkbox" ? (bulkValue === "1" ? "1" : "") : bulkValue;
|
| 6197 |
-
const reason = numberBatchRefusal(fields, [{ [bulkField.key]: value }]);
|
| 6198 |
-
if (reason) {
|
| 6199 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text: reason, tone: "error" } }));
|
| 6200 |
-
return;
|
| 6201 |
-
}
|
| 6202 |
if (serverFilteredSelection) {
|
| 6203 |
setServerBulkPending(true);
|
| 6204 |
try {
|
|
@@ -6239,7 +6166,7 @@ function CustomerGridSurface({
|
|
| 6239 |
patchManyAndRecord([...selectedPids].map((pid) => ({ pid, updates: { [bulkField.key]: value } })), "a bulk update");
|
| 6240 |
setBulkUpdateOpen(false);
|
| 6241 |
}, [bulkField, bulkSelectedCount, bulkValue, clearSelection, dropTableRowsCache, patchManyAndRecord,
|
| 6242 |
-
requestWindow, scope, selectedPids, serverBulkPending, serverFilteredSelection, windowRequest
|
| 6243 |
|
| 6244 |
/**
|
| 6245 |
* Apply one stack entry in one direction. The INVERSE lives in `undoStack.directed` — this
|
|
@@ -6265,7 +6192,8 @@ function CustomerGridSurface({
|
|
| 6265 |
applyingUndo.current = false;
|
| 6266 |
}
|
| 6267 |
} else if (op.kind === "rowAdd") {
|
| 6268 |
-
// Restore
|
|
|
|
| 6269 |
//
|
| 6270 |
// ⚠ SEQUENTIAL, not `Promise.all`. `add_row` picks `max(id)+1` when the requested id is
|
| 6271 |
// taken, and it reads the store to do it — firing ten restores concurrently is ten
|
|
@@ -6277,24 +6205,8 @@ function CustomerGridSurface({
|
|
| 6277 |
|| AUDIT_FIELD_TYPES.includes(field.type)).map((field) => field.key));
|
| 6278 |
for (const r of op.rows) {
|
| 6279 |
const values = Object.fromEntries(Object.entries(r.values as Record<string, unknown>)
|
| 6280 |
-
.filter(([key]) => !generated.has(key)))
|
| 6281 |
-
const
|
| 6282 |
-
const pid = !Number.isFinite(requestedPid) || rowsRef.current.some((row) => row.pid === requestedPid)
|
| 6283 |
-
? mintRid() : requestedPid;
|
| 6284 |
-
if (workspaceScopeRef.current === op.table) setOverlayEdits((current) => {
|
| 6285 |
-
if (!current[pid]) return current;
|
| 6286 |
-
const writable = Object.fromEntries(Object.entries(current[pid]).filter(([key]) => !generated.has(key)));
|
| 6287 |
-
return { ...current, [pid]: writable };
|
| 6288 |
-
});
|
| 6289 |
-
if (workspaceScopeRef.current === op.table)
|
| 6290 |
-
setPendingRows((current) => [...current.filter((row) => row.pid !== pid), { ...values, pid }]);
|
| 6291 |
-
const made = await addTableRow(op.table, values, r.rid, true);
|
| 6292 |
-
if (!made) {
|
| 6293 |
-
if (workspaceScopeRef.current === op.table)
|
| 6294 |
-
setPendingRows((current) => current.filter((row) => row.pid !== pid));
|
| 6295 |
-
continue;
|
| 6296 |
-
}
|
| 6297 |
-
acceptPendingRow(pid, made);
|
| 6298 |
any = any || !!made; // a refusal already said why, in the server's words
|
| 6299 |
// ⚠ THE ID IS PART OF WHAT IS BEING UNDONE, and `add_row` falls back to `max(id)+1`
|
| 6300 |
// when the one it was asked for is no longer free — which happens if anything created
|
|
@@ -6303,8 +6215,6 @@ function CustomerGridSurface({
|
|
| 6303 |
// and a redo would then look for an id that is not there. Said out loud rather than
|
| 6304 |
// discovered later.
|
| 6305 |
if (made && String(made.rid) !== String(r.rid)) moved += 1;
|
| 6306 |
-
r.rid = made.rid;
|
| 6307 |
-
r.values = { ...values, ...made.values };
|
| 6308 |
}
|
| 6309 |
if (!any) return;
|
| 6310 |
if (moved)
|
|
@@ -6313,6 +6223,7 @@ function CustomerGridSurface({
|
|
| 6313 |
`${moved} restored record${moved === 1 ? "" : "s"} came back under a new id. ` +
|
| 6314 |
`Something had taken the original while it was gone.`
|
| 6315 |
);
|
|
|
|
| 6316 |
} else if (op.kind === "rowDelete") {
|
| 6317 |
let any = false;
|
| 6318 |
for (const r of op.rows) any = (await deleteTableRow(op.table, r.rid)) || any;
|
|
@@ -6335,7 +6246,7 @@ function CustomerGridSurface({
|
|
| 6335 |
}
|
| 6336 |
signal(TOAST_EVENT, describe(entry, dir));
|
| 6337 |
},
|
| 6338 |
-
[patchOverlay, withdrawPending, emitHostEvent, fields
|
| 6339 |
);
|
| 6340 |
|
| 6341 |
/**
|
|
@@ -9521,7 +9432,7 @@ function CustomerGridSurface({
|
|
| 9521 |
per surface. Fixing the validator and the offer left the SEND still broken. */
|
| 9522 |
...(extra?.geocode ? { geocode: extra.geocode } : {}),
|
| 9523 |
...(field.agg ? { agg: field.agg } : {}),
|
| 9524 |
-
...(
|
| 9525 |
}).then((made) => {
|
| 9526 |
const reconcile = (current: Field[]) => {
|
| 9527 |
const without = current.filter((item) => item.key !== field.key && item.key !== made?.key);
|
|
@@ -9630,8 +9541,6 @@ function CustomerGridSurface({
|
|
| 9630 |
const setFieldConfig = useCallback(
|
| 9631 |
(key: string, patch: {
|
| 9632 |
label?: string; link?: unknown; rollup?: unknown; if?: Field["if"]; formula?: string; agg?: string;
|
| 9633 |
-
defaultValue?: Field["defaultValue"] | null;
|
| 9634 |
-
format?: Field["format"];
|
| 9635 |
/* ⭐ W50-T05 — the display mode rides the DEFINITION door for D-468/D-275's reason: on a
|
| 9636 |
shared column the overlay stratum would fork it, and this one edits it in place. */
|
| 9637 |
showAs?: ShowAs;
|
|
@@ -9834,9 +9743,6 @@ function CustomerGridSurface({
|
|
| 9834 |
...(old.createdBy ? { createdBy: old.createdBy } : {}),
|
| 9835 |
...(old.permissions ? { permissions: old.permissions } : {}),
|
| 9836 |
...(keepFormat ? { format: old.format } : {}),
|
| 9837 |
-
...(extra && "defaultValue" in extra
|
| 9838 |
-
? { defaultValue: extra.defaultValue ?? undefined }
|
| 9839 |
-
: "defaultValue" in old ? { defaultValue: old.defaultValue } : {}),
|
| 9840 |
...((type === "select" || type === "multiselect") && options?.length
|
| 9841 |
? { options }
|
| 9842 |
: {}),
|
|
@@ -9851,7 +9757,7 @@ function CustomerGridSurface({
|
|
| 9851 |
...(type === "multiselect" ? { multi: true } : {}),
|
| 9852 |
...(type === "rating" ? { max: extra?.max ?? 5 } : {}),
|
| 9853 |
};
|
| 9854 |
-
|
| 9855 |
/* THE DEFINITION DOOR. `patch_field` merges the body through the same `_clean_field` the
|
| 9856 |
create used, so the type, the options, the colours and a rating's max all land in the
|
| 9857 |
one validator — and the SERVER's echo replaces the local field, exactly as the create
|
|
@@ -9867,18 +9773,12 @@ function CustomerGridSurface({
|
|
| 9867 |
...(next.max !== undefined ? { max: next.max } : {}),
|
| 9868 |
...(next.agg ? { agg: next.agg } : {}),
|
| 9869 |
...(next.format ? { format: next.format } : {}),
|
| 9870 |
-
...("defaultValue" in next ? { defaultValue: next.defaultValue ?? null } : {}),
|
| 9871 |
}).then((made) => {
|
| 9872 |
if (!made) return; // the bridge has already said why
|
| 9873 |
setFields((current) => current.map((f) => (f.key === made.key ? made : f)));
|
| 9874 |
signal(WORKSPACE_STALE_EVENT);
|
| 9875 |
signal(ROWS_STALE_EVENT);
|
| 9876 |
});
|
| 9877 |
-
};
|
| 9878 |
-
if (isUserTable && !old.custom) {
|
| 9879 |
-
writeDefinition();
|
| 9880 |
-
} else if (isUserTable && "defaultValue" in next) {
|
| 9881 |
-
writeDefinition();
|
| 9882 |
} else {
|
| 9883 |
saveField(next);
|
| 9884 |
}
|
|
@@ -12861,7 +12761,7 @@ function CustomerGridSurface({
|
|
| 12861 |
every page reachable: `matched` is the server's own count, so this is a view onto the
|
| 12862 |
whole population rather than a cap on it (standing rule 1). Grouped, each open group
|
| 12863 |
pages on its own footer instead. */}
|
| 12864 |
-
|
| 12865 |
{!nativeActivity && !rowsLoading && !mirrorUnavailable && <>
|
| 12866 |
{((!config.groupBy && (displayMode === "grid" || (serverWindowed && displayMode === "list")))
|
| 12867 |
|| (serverWindowed && displayMode === "gallery")) && !loading && (
|
|
@@ -12883,7 +12783,7 @@ function CustomerGridSurface({
|
|
| 12883 |
{nativeActivity && activityPage.error && <span role="alert">Activity could not be loaded.</span>}
|
| 12884 |
{!embedded && !isQueryPreview && <GridActivity key={scope}
|
| 12885 |
database={scope === "customer" || scope === "cohort" ? "customer_data" : scope === "product" ? "product_data" : scope} />}
|
| 12886 |
-
</div>
|
| 12887 |
</main>
|
| 12888 |
|
| 12889 |
{embedded && menuField && columnMenu && (
|
|
|
|
| 30 |
usePersonalGridLayout, withoutRetiredChoiceEdits } from "./useCustomerData";
|
| 31 |
import type { SurfaceAddress } from "./useCustomerData";
|
| 32 |
import { AMAZON_STILL_LOADING_MESSAGE } from "./mirrorLoading";
|
| 33 |
+
import type { RowWindowRequest, SurfaceScope } from "./apiBridge";
|
| 34 |
import { mutateQueryWorkspace, QUERY_BINDING_EVENT, refuseQueryMutation } from "../query/queryApi";
|
| 35 |
import type { QueryVirtualBinding } from "../query/queryApi";
|
| 36 |
import { acceptsQueryPreview, routeQueryViewMutation } from "./queryPreview";
|
|
|
|
| 197 |
ratingCellRenderer, setAvatarRepaint, userCellRenderer } from "./cells";
|
| 198 |
// ⭐ W50-T05 — ONE numeric reading of a stored cell, the same one `aggregations.ts` folds with.
|
| 199 |
// A second parse here is how a cell painted blank while the total under it counted 1,234.50.
|
| 200 |
+
import { actionHref, numericOrUndefined } from "./display";
|
| 201 |
// ⭐ W50-T05 — the value/share COMPOSITION. The share arithmetic stays in `formatShare`.
|
| 202 |
import { withShare } from "../ui/fmt";
|
| 203 |
import { optionTint, pickTint } from "./choiceColors";
|
|
|
|
| 1105 |
);
|
| 1106 |
}
|
| 1107 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1108 |
interface FieldBuildExtra {
|
| 1109 |
if?: Field["if"];
|
| 1110 |
formula?: string;
|
|
|
|
| 1275 |
: {}),
|
| 1276 |
...(type === "multiselect" ? { multi: true } : {}),
|
| 1277 |
...(type === "rating" ? { max: extra?.max ?? 5 } : {}),
|
| 1278 |
+
...(extra?.defaultValue !== undefined && extra.defaultValue !== null
|
| 1279 |
+
? { defaultValue: extra.defaultValue } : {}),
|
| 1280 |
};
|
| 1281 |
}
|
| 1282 |
|
|
|
|
| 1553 |
return <div className={"cg-kbview" + (clamped ? " is-clamped" : "")}
|
| 1554 |
style={{ "--cg-kb-card-h": "auto", "--cg-kb-title-h": "auto", "--cg-kb-cell-h": "auto",
|
| 1555 |
"--cg-kb-line-h": "1.4em", "--cg-kb-card-gap": "8px" } as CSSProperties}>
|
| 1556 |
+
<div className="cg-kb-note">Cards are read-only.</div>
|
| 1557 |
{error ? <MirrorModeFailure message={error} retry={retry} /> : !data ? <MirrorModeSkeleton />
|
| 1558 |
: data.groups.length === 0 ? <div className="cg-mode-empty">No records match this view.</div>
|
| 1559 |
: <div className="cg-kb-lanes">{data.groups.map((group) => {
|
|
|
|
| 2461 |
return <CustomerGridSurface {...props} queryBinding={queryBinding} />;
|
| 2462 |
}
|
| 2463 |
|
| 2464 |
+
/** An ID-backed grid supplies pages through the existing caller-owned payload seam. */
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2465 |
function useRecordIdWindow(scope: SurfaceScope, ids: readonly number[] | undefined,
|
| 2466 |
+
related: RelatedPin | null, initialPage?: RecordIdInitialPage, idsPending = false, cellView = false) {
|
| 2467 |
+
const key = JSON.stringify([scope, ids, related, initialPage, idsPending, cellView]);
|
|
|
|
|
|
|
|
|
|
| 2468 |
const appliedCellFilters = cellView && ids !== undefined;
|
| 2469 |
const seed = !idsPending && ids !== undefined && !related && initialPage && initialPage.offset === 0
|
| 2470 |
? initialPage.payload : null;
|
|
|
|
| 2480 |
key: string; payload: CustomersPayload | null; pending: boolean;
|
| 2481 |
} | null>(null);
|
| 2482 |
const requestWindow = useCallback((req: RowWindowRequest, fresh = false) => {
|
| 2483 |
+
if (idsPending || ids === undefined) return;
|
|
|
|
|
|
|
| 2484 |
const seq = ++sequence.current;
|
| 2485 |
lastRequest.current = req;
|
| 2486 |
if (!fresh && seed && initialPage && req.offset === 0
|
|
|
|
| 2498 |
return;
|
| 2499 |
}
|
| 2500 |
setPage((prev) => ({ key, payload: prev?.key === key ? prev.payload : null, pending: true }));
|
| 2501 |
+
void fetchTableWindow(scope, { ...req, ids, related }).then((payload) => {
|
|
|
|
|
|
|
| 2502 |
if (seq !== sequence.current || currentKey.current !== key) return;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2503 |
setPage({ key, payload, pending: false });
|
| 2504 |
});
|
| 2505 |
+
}, [scope, ids, related, key, seed, initialPage, idsPending, appliedCellFilters]);
|
| 2506 |
useEffect(() => {
|
| 2507 |
const refresh = () => { if (lastRequest.current) requestWindow(lastRequest.current, true); };
|
| 2508 |
// React can replay effect setup after cancelling its first request in StrictMode.
|
|
|
|
| 2515 |
}, [requestWindow]);
|
| 2516 |
return {
|
| 2517 |
payload: idsPending ? null : page?.key === key ? page.payload : seed,
|
| 2518 |
+
pending: idsPending || (page?.key === key ? page.pending : !seed && ids !== undefined),
|
| 2519 |
requestWindow,
|
| 2520 |
};
|
| 2521 |
}
|
|
|
|
| 2600 |
const embeddedIdsKey = recordIdsKey(embeddedPayload === undefined ? embeddedRecordIds : undefined);
|
| 2601 |
const embeddedIds = useMemo<readonly number[] | undefined>(
|
| 2602 |
() => embeddedIdsKey ? JSON.parse(embeddedIdsKey) as number[] : undefined, [embeddedIdsKey]);
|
| 2603 |
+
const idWindow = useRecordIdWindow(scope, embeddedIds, relatedPin, embeddedInitialPage, embeddedIdsPending, cellView);
|
|
|
|
|
|
|
| 2604 |
/**
|
| 2605 |
* ⭐⭐ W35-T23 (owner item 4 / R2) — **`previewReadOnly` IS GONE, AND THE SPLIT IS THE TICKET.**
|
| 2606 |
*
|
|
|
|
| 2714 |
related: relatedPin,
|
| 2715 |
// C3: a hosted open asks for its addressed View's rows first (`viewWindowPredicate`).
|
| 2716 |
firstView: hosted ? hostedFirstView(hostedAddress.path) : undefined,
|
|
|
|
| 2717 |
});
|
| 2718 |
+
const windowPending = embeddedIds !== undefined ? idWindow.pending : ordinaryWindowPending;
|
| 2719 |
+
const requestWindow = embeddedIds !== undefined ? idWindow.requestWindow : ordinaryRequestWindow;
|
|
|
|
| 2720 |
useEffect(() => {
|
| 2721 |
onEmbeddedTotalChange?.(payload?.counts?.matched ?? null);
|
| 2722 |
}, [onEmbeddedTotalChange, payload?.counts?.matched]);
|
|
|
|
| 4090 |
* overlay edit rather than lost data — the alternative, blocking the paint until the POST
|
| 4091 |
* resolves, is the defect being fixed.
|
| 4092 |
*/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4093 |
const appendRow = useCallback(async (): Promise<undefined> => {
|
| 4094 |
if (!canMutateRecords) return undefined;
|
| 4095 |
+
const seeded = seedValues();
|
| 4096 |
const minted = mintRid();
|
| 4097 |
// S76-T28: paint the server's defaults at once. Core stores a boolean as Python's str().
|
| 4098 |
const defaults: Record<string, string> = Object.fromEntries(fields
|
| 4099 |
.filter((field) => field.defaultValue !== undefined && field.defaultValue !== null
|
| 4100 |
+
&& !(field.key in seeded))
|
| 4101 |
.map((field) => [field.key, typeof field.defaultValue === "boolean"
|
| 4102 |
? (field.defaultValue ? "True" : "False") : String(field.defaultValue)]));
|
| 4103 |
+
const optimistic: Row = { ...defaults, ...seeded, pid: minted };
|
|
|
|
| 4104 |
setPendingRows((cur) => [...cur, optimistic]);
|
| 4105 |
setNewRowPid(minted);
|
| 4106 |
const made = await addTableRow(scope, seeded, minted);
|
|
|
|
| 4112 |
setNewRowPid(null);
|
| 4113 |
return undefined;
|
| 4114 |
}
|
|
|
|
| 4115 |
if (made.pid !== minted) {
|
| 4116 |
+
setPendingRows((cur) =>
|
| 4117 |
+
cur.map((r) => (r.pid === minted ? { ...r, pid: made.pid } : r))
|
| 4118 |
+
);
|
| 4119 |
+
setNewRowPid(made.pid);
|
| 4120 |
}
|
| 4121 |
// R4 — the append is undoable: Ctrl+Z deletes the row it just created, and a redo restores
|
| 4122 |
// it under the SAME rid (the server's `{rid}` passthrough, C-ADDROW).
|
|
|
|
| 4137 |
// `undefined` is returned rather than glide's "bottom": "bottom" is resolved against the
|
| 4138 |
// rows glide knew about when the gesture started, which is the row BEFORE this one.
|
| 4139 |
return undefined;
|
| 4140 |
+
}, [canMutateRecords, scope, seedValues, mintRid, fields]);
|
| 4141 |
|
| 4142 |
/* wave20 item 2 — measure key + window -> the columns that display it. Built ONCE per field
|
| 4143 |
list and handed to every consumer of "which column is this rule about", so the tint
|
|
|
|
| 4252 |
// `TableMode` for why both engines running at once is the failure this prevents.
|
| 4253 |
// S66-T48: an id-backed grid is a window BY CONSTRUCTION (its rows only ever come from the
|
| 4254 |
// rows door), so it is windowed before its first page arrives and the pager can ask for it.
|
| 4255 |
+
const mode = embeddedIds !== undefined ? "server-windowed" : tableMode(payload?.counts);
|
| 4256 |
const serverWindowed = mode === "server-windowed";
|
| 4257 |
// Owner items 4+6 — the Cohort page's grid renders without the Views sidebar.
|
| 4258 |
const hideViews = (!hostWorkspace && !related) || payload?.workspace?.hideViews === true;
|
|
|
|
| 4399 |
// ⛔ THE SAVED VIEW'S OWN OBJECTS GO ON THE WIRE, UNTRANSLATED (see `windowRowsPath`).
|
| 4400 |
const windowPredicate = useMemo(
|
| 4401 |
() => windowPredicateKey(config.filters, config.filterConj, config.sorts, search)
|
| 4402 |
+
+ (embeddedIdsKey ? JSON.stringify([scope, embeddedIdsKey, relatedPinKey, cellView]) : ""),
|
| 4403 |
+
[config.filters, config.filterConj, config.sorts, search, scope, embeddedIdsKey, relatedPinKey, cellView]
|
|
|
|
|
|
|
| 4404 |
);
|
| 4405 |
/* HOTFIX 2026-09-24 — ONE PAGE SIZE FOR EVERY DATABASE (50 / 100 / 200, default 100). */
|
| 4406 |
const windowRequest = useCallback(
|
|
|
|
| 4924 |
let live = true;
|
| 4925 |
void fetchAggregates(topic.key, {
|
| 4926 |
...(embeddedIds !== undefined ? { ids: embeddedIds } : {}),
|
| 4927 |
+
filters: cellView && embeddedIds !== undefined ? withoutAppliedLeaves(config.filters) : config.filters,
|
| 4928 |
+
filterConj: config.filterConj,
|
|
|
|
|
|
|
| 4929 |
search,
|
| 4930 |
/* ⭐⭐ W51-T06 / C6 — THE SAME PIN THE ROWS WINDOW CARRIES, AND THIS ONE LINE IS THE HALF
|
| 4931 |
THAT GETS LEFT OUT. Wire only the rows and a related tab shows one record's rows under
|
|
|
|
| 4957 |
// is part of the question, so moving between two tabs on one target table must re-ask. Its
|
| 4958 |
// identity is stable (see `relatedPinKey`), so this cannot loop.
|
| 4959 |
}, [serverWindowed, topic.key, summaryRequestKey, windowPredicate, config.groupBy, relatedPin, embeddedIds,
|
| 4960 |
+
serverAggRequestKey, cellView]);
|
| 4961 |
/**
|
| 4962 |
* What the bar actually paints: C1's numbers when the server answered, this browser's fold
|
| 4963 |
* over the loaded window otherwise — and the two are never mixed within one paint, because a
|
|
|
|
| 5012 |
);
|
| 5013 |
/** The bar renders as soon as one column resolves to something to show. Under R2's defaults
|
| 5014 |
* that is every table carrying a numeric column, which is the point of the ruling. */
|
| 5015 |
+
const summaryShown = summaryRequestKey !== "[]";
|
| 5016 |
const summaryColumns = useMemo(
|
| 5017 |
() => visibleCols.map((col) => ({
|
| 5018 |
key: String(col.id),
|
|
|
|
| 6061 |
/** ONE cell write, recorded. Every editor, picker and drag goes through this. */
|
| 6062 |
const patchAndRecord = useCallback(
|
| 6063 |
(pid: number, updates: Partial<Row>, label = "an edit") => {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6064 |
const changes: CellChange[] = Object.entries(updates).map(([key, value]) => ({
|
| 6065 |
pid, key,
|
| 6066 |
before: currentValue(pid, key),
|
|
|
|
| 6069 |
patchOverlay(pid, updates);
|
| 6070 |
recordCells(changes, label);
|
| 6071 |
},
|
| 6072 |
+
[currentValue, patchOverlay, recordCells]
|
| 6073 |
);
|
| 6074 |
|
| 6075 |
const [chatOpen, setChatOpen] = useState(false);
|
|
|
|
| 6098 |
/** MANY cells, ONE stack entry — a paste and a bulk clear are each one user action (R4). */
|
| 6099 |
const patchManyAndRecord = useCallback(
|
| 6100 |
(writes: { pid: number; updates: Partial<Row> }[], label: string) => {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6101 |
const changes: CellChange[] = [];
|
| 6102 |
for (const w of writes)
|
| 6103 |
for (const [key, value] of Object.entries(w.updates))
|
|
|
|
| 6109 |
for (const w of writes) patchOverlay(w.pid, w.updates);
|
| 6110 |
recordCells(changes, label);
|
| 6111 |
},
|
| 6112 |
+
[currentValue, patchOverlay, recordCells]
|
| 6113 |
);
|
| 6114 |
const bulkEditableFields = useMemo(
|
| 6115 |
() => fields.filter((field) => (
|
|
|
|
| 6126 |
const applyBulkUpdate = useCallback(async () => {
|
| 6127 |
if (!bulkField || bulkSelectedCount === 0 || serverBulkPending) return;
|
| 6128 |
const value = bulkField.type === "checkbox" ? (bulkValue === "1" ? "1" : "") : bulkValue;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6129 |
if (serverFilteredSelection) {
|
| 6130 |
setServerBulkPending(true);
|
| 6131 |
try {
|
|
|
|
| 6166 |
patchManyAndRecord([...selectedPids].map((pid) => ({ pid, updates: { [bulkField.key]: value } })), "a bulk update");
|
| 6167 |
setBulkUpdateOpen(false);
|
| 6168 |
}, [bulkField, bulkSelectedCount, bulkValue, clearSelection, dropTableRowsCache, patchManyAndRecord,
|
| 6169 |
+
requestWindow, scope, selectedPids, serverBulkPending, serverFilteredSelection, windowRequest]);
|
| 6170 |
|
| 6171 |
/**
|
| 6172 |
* Apply one stack entry in one direction. The INVERSE lives in `undoStack.directed` — this
|
|
|
|
| 6192 |
applyingUndo.current = false;
|
| 6193 |
}
|
| 6194 |
} else if (op.kind === "rowAdd") {
|
| 6195 |
+
// Restore under the OLD id where the store still has it free; the server answers with
|
| 6196 |
+
// what it actually wrote and the re-read is what puts the rows back on screen.
|
| 6197 |
//
|
| 6198 |
// ⚠ SEQUENTIAL, not `Promise.all`. `add_row` picks `max(id)+1` when the requested id is
|
| 6199 |
// taken, and it reads the store to do it — firing ten restores concurrently is ten
|
|
|
|
| 6205 |
|| AUDIT_FIELD_TYPES.includes(field.type)).map((field) => field.key));
|
| 6206 |
for (const r of op.rows) {
|
| 6207 |
const values = Object.fromEntries(Object.entries(r.values as Record<string, unknown>)
|
| 6208 |
+
.filter(([key]) => !generated.has(key)));
|
| 6209 |
+
const made = await addTableRow(op.table, values, r.rid);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6210 |
any = any || !!made; // a refusal already said why, in the server's words
|
| 6211 |
// ⚠ THE ID IS PART OF WHAT IS BEING UNDONE, and `add_row` falls back to `max(id)+1`
|
| 6212 |
// when the one it was asked for is no longer free — which happens if anything created
|
|
|
|
| 6215 |
// and a redo would then look for an id that is not there. Said out loud rather than
|
| 6216 |
// discovered later.
|
| 6217 |
if (made && String(made.rid) !== String(r.rid)) moved += 1;
|
|
|
|
|
|
|
| 6218 |
}
|
| 6219 |
if (!any) return;
|
| 6220 |
if (moved)
|
|
|
|
| 6223 |
`${moved} restored record${moved === 1 ? "" : "s"} came back under a new id. ` +
|
| 6224 |
`Something had taken the original while it was gone.`
|
| 6225 |
);
|
| 6226 |
+
signal(ROWS_STALE_EVENT);
|
| 6227 |
} else if (op.kind === "rowDelete") {
|
| 6228 |
let any = false;
|
| 6229 |
for (const r of op.rows) any = (await deleteTableRow(op.table, r.rid)) || any;
|
|
|
|
| 6246 |
}
|
| 6247 |
signal(TOAST_EVENT, describe(entry, dir));
|
| 6248 |
},
|
| 6249 |
+
[patchOverlay, withdrawPending, emitHostEvent, fields]
|
| 6250 |
);
|
| 6251 |
|
| 6252 |
/**
|
|
|
|
| 9432 |
per surface. Fixing the validator and the offer left the SEND still broken. */
|
| 9433 |
...(extra?.geocode ? { geocode: extra.geocode } : {}),
|
| 9434 |
...(field.agg ? { agg: field.agg } : {}),
|
| 9435 |
+
...(field.defaultValue !== undefined ? { defaultValue: field.defaultValue } : {}),
|
| 9436 |
}).then((made) => {
|
| 9437 |
const reconcile = (current: Field[]) => {
|
| 9438 |
const without = current.filter((item) => item.key !== field.key && item.key !== made?.key);
|
|
|
|
| 9541 |
const setFieldConfig = useCallback(
|
| 9542 |
(key: string, patch: {
|
| 9543 |
label?: string; link?: unknown; rollup?: unknown; if?: Field["if"]; formula?: string; agg?: string;
|
|
|
|
|
|
|
| 9544 |
/* ⭐ W50-T05 — the display mode rides the DEFINITION door for D-468/D-275's reason: on a
|
| 9545 |
shared column the overlay stratum would fork it, and this one edits it in place. */
|
| 9546 |
showAs?: ShowAs;
|
|
|
|
| 9743 |
...(old.createdBy ? { createdBy: old.createdBy } : {}),
|
| 9744 |
...(old.permissions ? { permissions: old.permissions } : {}),
|
| 9745 |
...(keepFormat ? { format: old.format } : {}),
|
|
|
|
|
|
|
|
|
|
| 9746 |
...((type === "select" || type === "multiselect") && options?.length
|
| 9747 |
? { options }
|
| 9748 |
: {}),
|
|
|
|
| 9757 |
...(type === "multiselect" ? { multi: true } : {}),
|
| 9758 |
...(type === "rating" ? { max: extra?.max ?? 5 } : {}),
|
| 9759 |
};
|
| 9760 |
+
if (isUserTable && !old.custom) {
|
| 9761 |
/* THE DEFINITION DOOR. `patch_field` merges the body through the same `_clean_field` the
|
| 9762 |
create used, so the type, the options, the colours and a rating's max all land in the
|
| 9763 |
one validator — and the SERVER's echo replaces the local field, exactly as the create
|
|
|
|
| 9773 |
...(next.max !== undefined ? { max: next.max } : {}),
|
| 9774 |
...(next.agg ? { agg: next.agg } : {}),
|
| 9775 |
...(next.format ? { format: next.format } : {}),
|
|
|
|
| 9776 |
}).then((made) => {
|
| 9777 |
if (!made) return; // the bridge has already said why
|
| 9778 |
setFields((current) => current.map((f) => (f.key === made.key ? made : f)));
|
| 9779 |
signal(WORKSPACE_STALE_EVENT);
|
| 9780 |
signal(ROWS_STALE_EVENT);
|
| 9781 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9782 |
} else {
|
| 9783 |
saveField(next);
|
| 9784 |
}
|
|
|
|
| 12761 |
every page reachable: `matched` is the server's own count, so this is a view onto the
|
| 12762 |
whole population rather than a cap on it (standing rule 1). Grouped, each open group
|
| 12763 |
pages on its own footer instead. */}
|
| 12764 |
+
<div className="cg-grid-footer">
|
| 12765 |
{!nativeActivity && !rowsLoading && !mirrorUnavailable && <>
|
| 12766 |
{((!config.groupBy && (displayMode === "grid" || (serverWindowed && displayMode === "list")))
|
| 12767 |
|| (serverWindowed && displayMode === "gallery")) && !loading && (
|
|
|
|
| 12783 |
{nativeActivity && activityPage.error && <span role="alert">Activity could not be loaded.</span>}
|
| 12784 |
{!embedded && !isQueryPreview && <GridActivity key={scope}
|
| 12785 |
database={scope === "customer" || scope === "cohort" ? "customer_data" : scope === "product" ? "product_data" : scope} />}
|
| 12786 |
+
</div>
|
| 12787 |
</main>
|
| 12788 |
|
| 12789 |
{embedded && menuField && columnMenu && (
|
web/src/customer-grid/GridActivity.tsx
CHANGED
|
@@ -83,8 +83,8 @@ export function activityPerson(record: ActivityRecord): string {
|
|
| 83 |
return record.via ? `${person} via ${record.via}` : person;
|
| 84 |
}
|
| 85 |
|
| 86 |
-
function ActivityDrawer({ records, failed, now, onClose
|
| 87 |
-
records: ActivityRecord[]; failed: boolean; now: number; onClose: () => void;
|
| 88 |
}) {
|
| 89 |
const panelRef = useRef<HTMLElement>(null);
|
| 90 |
const title = useId();
|
|
@@ -95,8 +95,7 @@ function ActivityDrawer({ records, failed, now, onClose, onRetry }: {
|
|
| 95 |
<h2 id={title}>Activity</h2>
|
| 96 |
<button type="button" className="cg-activity-button" onClick={onClose}>Close</button>
|
| 97 |
</header>
|
| 98 |
-
{failed ? <p role="alert">Activity could not be loaded.
|
| 99 |
-
<button type="button" className="cg-activity-button" onClick={onRetry}>Retry</button></p> : records.length === 0 ?
|
| 100 |
<p>No activity</p> : <ol className="cg-activity-list">
|
| 101 |
{records.map(record => <li key={record.id}>
|
| 102 |
<span>{activityPerson(record)}</span>
|
|
@@ -117,7 +116,6 @@ export function GridActivity({ database }: { database: string }) {
|
|
| 117 |
const [failed, setFailed] = useState(false);
|
| 118 |
const [now, setNow] = useState(Date.now);
|
| 119 |
const activeDatabase = useRef(database);
|
| 120 |
-
const retryRead = useRef<(() => void) | null>(null);
|
| 121 |
const [loadedDatabase, setLoadedDatabase] = useState(database);
|
| 122 |
activeDatabase.current = database;
|
| 123 |
useEffect(() => {
|
|
@@ -165,8 +163,7 @@ export function GridActivity({ database }: { database: string }) {
|
|
| 165 |
setFailed(false);
|
| 166 |
setLoadedDatabase(database);
|
| 167 |
const read = async () => {
|
| 168 |
-
|
| 169 |
-
controller = request;
|
| 170 |
try {
|
| 171 |
let cursor: string | null = null;
|
| 172 |
let answer: ActivityPage;
|
|
@@ -181,25 +178,20 @@ export function GridActivity({ database }: { database: string }) {
|
|
| 181 |
if (!response.ok) throw new Error("activity unavailable");
|
| 182 |
answer = await response.json() as ActivityPage;
|
| 183 |
cursor = answer.next_cursor;
|
| 184 |
-
} while (answer.records.length === 0 && cursor && live
|
| 185 |
-
if (live &&
|
| 186 |
setPage(answer);
|
| 187 |
setFailed(false);
|
| 188 |
setNow(Date.now());
|
| 189 |
}
|
| 190 |
} catch {
|
| 191 |
-
if (live
|
| 192 |
} finally {
|
| 193 |
-
if (live
|
| 194 |
}
|
| 195 |
};
|
| 196 |
-
retryRead.current = () => {
|
| 197 |
-
clearTimeout(timer);
|
| 198 |
-
controller?.abort();
|
| 199 |
-
void read();
|
| 200 |
-
};
|
| 201 |
void read();
|
| 202 |
-
return () => { live = false;
|
| 203 |
}, [database]);
|
| 204 |
const records = loadedDatabase === database ? page?.records ?? [] : [];
|
| 205 |
const last = records[0];
|
|
@@ -216,6 +208,6 @@ export function GridActivity({ database }: { database: string }) {
|
|
| 216 |
</span>
|
| 217 |
) : null}
|
| 218 |
{open && loadedDatabase === database && <ActivityDrawer records={records}
|
| 219 |
-
failed={failed} now={now} onClose={() => setOpen(false)}
|
| 220 |
</>;
|
| 221 |
}
|
|
|
|
| 83 |
return record.via ? `${person} via ${record.via}` : person;
|
| 84 |
}
|
| 85 |
|
| 86 |
+
function ActivityDrawer({ records, failed, now, onClose }: {
|
| 87 |
+
records: ActivityRecord[]; failed: boolean; now: number; onClose: () => void;
|
| 88 |
}) {
|
| 89 |
const panelRef = useRef<HTMLElement>(null);
|
| 90 |
const title = useId();
|
|
|
|
| 95 |
<h2 id={title}>Activity</h2>
|
| 96 |
<button type="button" className="cg-activity-button" onClick={onClose}>Close</button>
|
| 97 |
</header>
|
| 98 |
+
{failed ? <p role="alert">Activity could not be loaded.</p> : records.length === 0 ?
|
|
|
|
| 99 |
<p>No activity</p> : <ol className="cg-activity-list">
|
| 100 |
{records.map(record => <li key={record.id}>
|
| 101 |
<span>{activityPerson(record)}</span>
|
|
|
|
| 116 |
const [failed, setFailed] = useState(false);
|
| 117 |
const [now, setNow] = useState(Date.now);
|
| 118 |
const activeDatabase = useRef(database);
|
|
|
|
| 119 |
const [loadedDatabase, setLoadedDatabase] = useState(database);
|
| 120 |
activeDatabase.current = database;
|
| 121 |
useEffect(() => {
|
|
|
|
| 163 |
setFailed(false);
|
| 164 |
setLoadedDatabase(database);
|
| 165 |
const read = async () => {
|
| 166 |
+
controller = new AbortController();
|
|
|
|
| 167 |
try {
|
| 168 |
let cursor: string | null = null;
|
| 169 |
let answer: ActivityPage;
|
|
|
|
| 178 |
if (!response.ok) throw new Error("activity unavailable");
|
| 179 |
answer = await response.json() as ActivityPage;
|
| 180 |
cursor = answer.next_cursor;
|
| 181 |
+
} while (answer.records.length === 0 && cursor && live);
|
| 182 |
+
if (live && activeDatabase.current === database) {
|
| 183 |
setPage(answer);
|
| 184 |
setFailed(false);
|
| 185 |
setNow(Date.now());
|
| 186 |
}
|
| 187 |
} catch {
|
| 188 |
+
if (live) { setPage(null); setFailed(true); }
|
| 189 |
} finally {
|
| 190 |
+
if (live) timer = setTimeout(read, 5000);
|
| 191 |
}
|
| 192 |
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
void read();
|
| 194 |
+
return () => { live = false; clearTimeout(timer); controller?.abort(); };
|
| 195 |
}, [database]);
|
| 196 |
const records = loadedDatabase === database ? page?.records ?? [] : [];
|
| 197 |
const last = records[0];
|
|
|
|
| 208 |
</span>
|
| 209 |
) : null}
|
| 210 |
{open && loadedDatabase === database && <ActivityDrawer records={records}
|
| 211 |
+
failed={failed} now={now} onClose={() => setOpen(false)} />}
|
| 212 |
</>;
|
| 213 |
}
|
web/src/customer-grid/MapView.tsx
CHANGED
|
@@ -5252,10 +5252,6 @@ export function MapView(props: MapViewProps) {
|
|
| 5252 |
key,
|
| 5253 |
title,
|
| 5254 |
...(fieldMap.image ? { image: String(fieldMap.image) } : {}),
|
| 5255 |
-
...(fieldMap.sku ? { sku: String(fieldMap.sku) } : {}),
|
| 5256 |
-
...(fieldMap.price ? { price: String(fieldMap.price) } : {}),
|
| 5257 |
-
...(fieldMap.category ? { category: String(fieldMap.category) } : {}),
|
| 5258 |
-
...(fieldMap.description ? { description: String(fieldMap.description) } : {}),
|
| 5259 |
},
|
| 5260 |
};
|
| 5261 |
const display = application.config?.display ?? {};
|
|
|
|
| 5252 |
key,
|
| 5253 |
title,
|
| 5254 |
...(fieldMap.image ? { image: String(fieldMap.image) } : {}),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5255 |
},
|
| 5256 |
};
|
| 5257 |
const display = application.config?.display ?? {};
|
web/src/customer-grid/RecordDetail.tsx
CHANGED
|
@@ -67,7 +67,7 @@ import { dropTableRowsCache, fetchLinkTargets, fetchRecordMeasureValues, fetchRe
|
|
| 67 |
fetchRelatedMeasureValues, fetchTableWindow, fetchTopicRows, isRelatedMetricScope,
|
| 68 |
isRelatedProductMetricScope, probeRelatedRead,
|
| 69 |
readThroughTables, usesPinnedRows, WINDOW_ROWS } from "./apiBridge";
|
| 70 |
-
import { API_V1, CREDENTIALS, ROWS_STALE_EVENT, WORKSPACE_STALE_EVENT,
|
| 71 |
|
| 72 |
/**
|
| 73 |
* ⭐⭐ WAVE-34 (owner ruling R13) — whose value sits in this enrichment cell, in words.
|
|
@@ -669,15 +669,6 @@ function RelatedRefusalNote(
|
|
| 669 |
{ code, subject, message, details }:
|
| 670 |
{ code: string; subject: string; message: string; details: string[] },
|
| 671 |
) {
|
| 672 |
-
const denial = code !== "no_related_rows";
|
| 673 |
-
const text = [subject, message, ...details].filter(Boolean).join(" ");
|
| 674 |
-
const announced = useRef<string | null>(null);
|
| 675 |
-
useEffect(() => {
|
| 676 |
-
if (!denial || announced.current === text) return;
|
| 677 |
-
announced.current = text;
|
| 678 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
|
| 679 |
-
}, [denial, text]);
|
| 680 |
-
if (denial) return null;
|
| 681 |
if (details.length === 0) {
|
| 682 |
return (
|
| 683 |
<p
|
|
@@ -3320,7 +3311,7 @@ export default function RecordDetail({
|
|
| 3320 |
`<details>` whose summary is a real disclosure control, and wrapping every one of
|
| 3321 |
them in its own live region would announce the same strip N times. */}
|
| 3322 |
{groupedRefusals.length > 0 && (
|
| 3323 |
-
<>
|
| 3324 |
{groupedRefusals.map((refusal) => (
|
| 3325 |
<RelatedRefusalNote
|
| 3326 |
key={`${refusal.code}:${refusal.message}`}
|
|
@@ -3335,7 +3326,7 @@ export default function RecordDetail({
|
|
| 3335 |
details={refusal.details}
|
| 3336 |
/>
|
| 3337 |
))}
|
| 3338 |
-
</>
|
| 3339 |
)}
|
| 3340 |
</div>
|
| 3341 |
) : (
|
|
|
|
| 67 |
fetchRelatedMeasureValues, fetchTableWindow, fetchTopicRows, isRelatedMetricScope,
|
| 68 |
isRelatedProductMetricScope, probeRelatedRead,
|
| 69 |
readThroughTables, usesPinnedRows, WINDOW_ROWS } from "./apiBridge";
|
| 70 |
+
import { API_V1, CREDENTIALS, ROWS_STALE_EVENT, WORKSPACE_STALE_EVENT, UNAUTHORIZED_EVENT, checkTenant, signal } from "../apiContract";
|
| 71 |
|
| 72 |
/**
|
| 73 |
* ⭐⭐ WAVE-34 (owner ruling R13) — whose value sits in this enrichment cell, in words.
|
|
|
|
| 669 |
{ code, subject, message, details }:
|
| 670 |
{ code: string; subject: string; message: string; details: string[] },
|
| 671 |
) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 672 |
if (details.length === 0) {
|
| 673 |
return (
|
| 674 |
<p
|
|
|
|
| 3311 |
`<details>` whose summary is a real disclosure control, and wrapping every one of
|
| 3312 |
them in its own live region would announce the same strip N times. */}
|
| 3313 |
{groupedRefusals.length > 0 && (
|
| 3314 |
+
<div className="cg-refusal-strip" role="status">
|
| 3315 |
{groupedRefusals.map((refusal) => (
|
| 3316 |
<RelatedRefusalNote
|
| 3317 |
key={`${refusal.code}:${refusal.message}`}
|
|
|
|
| 3326 |
details={refusal.details}
|
| 3327 |
/>
|
| 3328 |
))}
|
| 3329 |
+
</div>
|
| 3330 |
)}
|
| 3331 |
</div>
|
| 3332 |
) : (
|
web/src/customer-grid/apiBridge.ts
CHANGED
|
@@ -1825,27 +1825,20 @@ export function patchCustomer(pid: number, updates: Partial<Row>): Promise<boole
|
|
| 1825 |
* would appear minutes later, which reads as "the button did nothing". Same reason the shell's
|
| 1826 |
* retired Add-record bar cleared it (wave 20 item 4 moved that door here).
|
| 1827 |
*/
|
| 1828 |
-
export interface TableRowAcknowledgement {
|
| 1829 |
-
rid: string | number;
|
| 1830 |
-
pid: number;
|
| 1831 |
-
values?: Record<string, string | number | null>;
|
| 1832 |
-
}
|
| 1833 |
-
|
| 1834 |
export async function addTableRow(
|
| 1835 |
tableKey: string,
|
| 1836 |
values: Record<string, unknown> = {},
|
| 1837 |
-
rid?: string | number
|
| 1838 |
-
|
| 1839 |
-
): Promise<TableRowAcknowledgement | null> {
|
| 1840 |
try {
|
| 1841 |
const res = await fetch(`${API_V1}/tables/${encodeURIComponent(tableKey)}/rows`, {
|
| 1842 |
method: "POST",
|
| 1843 |
credentials: CREDENTIALS,
|
| 1844 |
headers: JSON_HEADERS,
|
| 1845 |
-
body: JSON.stringify(rid === undefined ? { values
|
| 1846 |
});
|
| 1847 |
if (handledSession(res)) return null;
|
| 1848 |
-
const body = (await readJson(res)) as { rid?: string | number; pid?: number;
|
| 1849 |
error?: { message?: string } } | null;
|
| 1850 |
if (!res.ok) {
|
| 1851 |
// The server states WHY (a row cap, a store refusal). Surfacing its sentence beats a
|
|
@@ -1859,15 +1852,7 @@ export async function addTableRow(
|
|
| 1859 |
return null;
|
| 1860 |
}
|
| 1861 |
dropTableRowsCache(tableKey);
|
| 1862 |
-
|
| 1863 |
-
typeof body.values === "object" && !Array.isArray(body.values) ? {} : undefined;
|
| 1864 |
-
if (accepted) for (const [key, value] of Object.entries(body.values as Record<string, unknown>)) {
|
| 1865 |
-
if (key === "pid") continue;
|
| 1866 |
-
if (value === null || typeof value === "string" ||
|
| 1867 |
-
(typeof value === "number" && Number.isFinite(value))) accepted[key] = value;
|
| 1868 |
-
else if (typeof value === "boolean") accepted[key] = value ? "True" : "False";
|
| 1869 |
-
}
|
| 1870 |
-
return { rid: body.rid, pid: body.pid, ...(accepted ? { values: accepted } : {}) };
|
| 1871 |
} catch {
|
| 1872 |
signal(DATA_ERROR_EVENT, "Cannot reach the server.");
|
| 1873 |
return null;
|
|
|
|
| 1825 |
* would appear minutes later, which reads as "the button did nothing". Same reason the shell's
|
| 1826 |
* retired Add-record bar cleared it (wave 20 item 4 moved that door here).
|
| 1827 |
*/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1828 |
export async function addTableRow(
|
| 1829 |
tableKey: string,
|
| 1830 |
values: Record<string, unknown> = {},
|
| 1831 |
+
rid?: string | number
|
| 1832 |
+
): Promise<{ rid: string | number; pid: number } | null> {
|
|
|
|
| 1833 |
try {
|
| 1834 |
const res = await fetch(`${API_V1}/tables/${encodeURIComponent(tableKey)}/rows`, {
|
| 1835 |
method: "POST",
|
| 1836 |
credentials: CREDENTIALS,
|
| 1837 |
headers: JSON_HEADERS,
|
| 1838 |
+
body: JSON.stringify(rid === undefined ? { values } : { rid, values }),
|
| 1839 |
});
|
| 1840 |
if (handledSession(res)) return null;
|
| 1841 |
+
const body = (await readJson(res)) as { rid?: string | number; pid?: number;
|
| 1842 |
error?: { message?: string } } | null;
|
| 1843 |
if (!res.ok) {
|
| 1844 |
// The server states WHY (a row cap, a store refusal). Surfacing its sentence beats a
|
|
|
|
| 1852 |
return null;
|
| 1853 |
}
|
| 1854 |
dropTableRowsCache(tableKey);
|
| 1855 |
+
return { rid: body.rid, pid: body.pid };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1856 |
} catch {
|
| 1857 |
signal(DATA_ERROR_EVENT, "Cannot reach the server.");
|
| 1858 |
return null;
|
web/src/filter-kit/FieldsHidePanel.tsx
CHANGED
|
@@ -15,7 +15,6 @@
|
|
| 15 |
|
| 16 |
import { useEffect, useMemo, useRef, useState } from "react";
|
| 17 |
import { useEscapeClose } from "../ui/useEscapeClose";
|
| 18 |
-
import { TOAST_EVENT } from "../apiContract";
|
| 19 |
import { useOverlayLayer } from "../customer-grid/OverlaySurface";
|
| 20 |
// ⭐⭐ W46-T31 (contract C6) — the lane's own sheet, imported from the COMPONENT and never from
|
| 21 |
// `index.css`. An @imported sheet is inlined at the TOP of the bundle's cascade and loses every
|
|
@@ -788,12 +787,7 @@ export function FieldsHidePanel({
|
|
| 788 |
if (action === "reassign" && onReassignFields && passed.length > 0) onReassignFields(passed);
|
| 789 |
if (action === "share" || action === "reassign") done += passed.length;
|
| 790 |
const text = bulkOutcomeLine(action, done, refused);
|
| 791 |
-
|
| 792 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
|
| 793 |
-
setBulkNote(null);
|
| 794 |
-
} else {
|
| 795 |
-
setBulkNote(text ? { text, refused: false } : null);
|
| 796 |
-
}
|
| 797 |
/**
|
| 798 |
* ⭐ AFTER A DELETE THE SELECTION BECOMES EXACTLY WHAT SURVIVED IT, and that is one
|
| 799 |
* decision doing two jobs: the deleted keys are gone from `fields` and must not linger in a
|
|
@@ -1625,7 +1619,7 @@ export function FieldsHidePanel({
|
|
| 1625 |
`bulkOutcomeLine` and never here, so R6(a)'s refusal has exactly one producer. */}
|
| 1626 |
{bulkNote && (
|
| 1627 |
<div
|
| 1628 |
-
className="cg-fields-bulk-note"
|
| 1629 |
role="status"
|
| 1630 |
>
|
| 1631 |
{bulkNote.text}
|
|
|
|
| 15 |
|
| 16 |
import { useEffect, useMemo, useRef, useState } from "react";
|
| 17 |
import { useEscapeClose } from "../ui/useEscapeClose";
|
|
|
|
| 18 |
import { useOverlayLayer } from "../customer-grid/OverlaySurface";
|
| 19 |
// ⭐⭐ W46-T31 (contract C6) — the lane's own sheet, imported from the COMPONENT and never from
|
| 20 |
// `index.css`. An @imported sheet is inlined at the TOP of the bundle's cascade and loses every
|
|
|
|
| 787 |
if (action === "reassign" && onReassignFields && passed.length > 0) onReassignFields(passed);
|
| 788 |
if (action === "share" || action === "reassign") done += passed.length;
|
| 789 |
const text = bulkOutcomeLine(action, done, refused);
|
| 790 |
+
setBulkNote(text ? { text, refused: refused.length > 0 } : null);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 791 |
/**
|
| 792 |
* ⭐ AFTER A DELETE THE SELECTION BECOMES EXACTLY WHAT SURVIVED IT, and that is one
|
| 793 |
* decision doing two jobs: the deleted keys are gone from `fields` and must not linger in a
|
|
|
|
| 1619 |
`bulkOutcomeLine` and never here, so R6(a)'s refusal has exactly one producer. */}
|
| 1620 |
{bulkNote && (
|
| 1621 |
<div
|
| 1622 |
+
className={"cg-fields-bulk-note" + (bulkNote.refused ? " is-refusal" : "")}
|
| 1623 |
role="status"
|
| 1624 |
>
|
| 1625 |
{bulkNote.text}
|
web/src/index.css
CHANGED
|
@@ -30,7 +30,6 @@
|
|
| 30 |
@import "./styles/wave51/sheet-chrome.css";
|
| 31 |
@import "./styles/wave51/sheet-engine.css";
|
| 32 |
@import "./styles/sdlc74/settings.css";
|
| 33 |
-
@import "./styles/sdlc76/overlays.css";
|
| 34 |
|
| 35 |
@font-face {
|
| 36 |
font-family: "Inter";
|
|
|
|
| 30 |
@import "./styles/wave51/sheet-chrome.css";
|
| 31 |
@import "./styles/wave51/sheet-engine.css";
|
| 32 |
@import "./styles/sdlc74/settings.css";
|
|
|
|
| 33 |
|
| 34 |
@font-face {
|
| 35 |
font-family: "Inter";
|
web/src/intelligence/intelligenceApi.ts
CHANGED
|
@@ -104,8 +104,6 @@ export interface IntelligenceList {
|
|
| 104 |
offset: number;
|
| 105 |
limit: number;
|
| 106 |
folders: string[];
|
| 107 |
-
canManageFolders?: boolean;
|
| 108 |
-
folderRevision?: number;
|
| 109 |
}
|
| 110 |
export interface IntelligenceQuery {
|
| 111 |
q: string;
|
|
@@ -134,10 +132,6 @@ export interface IntelligenceApi {
|
|
| 134 |
history(path: string, version: number, signal?: AbortSignal): Promise<IntelligenceHistory>;
|
| 135 |
restore(path: string, version: number, expectedVersion: number): Promise<IntelligenceFile>;
|
| 136 |
insights(signal?: AbortSignal): Promise<IntelligenceInsights>;
|
| 137 |
-
renameFile?: (path: string, title: string, expectedVersion: number) => Promise<IntelligenceFile>;
|
| 138 |
-
deleteFile?: (path: string, expectedVersion: number) => Promise<{ deleted: string }>;
|
| 139 |
-
renameFolder?: (path: string, name: string, expectedRevision: number) => Promise<{ path: string }>;
|
| 140 |
-
deleteFolder?: (path: string, expectedRevision: number) => Promise<{ deleted: string }>;
|
| 141 |
}
|
| 142 |
|
| 143 |
export class IntelligenceApiError extends Error {
|
|
@@ -163,7 +157,6 @@ function readRow(value: unknown): IntelligenceFileRow {
|
|
| 163 |
if (value.section === "database-notes" && (typeof value.databaseKey !== "string" || !value.databaseKey
|
| 164 |
|| value.databaseKey.includes("/") || value.path !== `database-notes/${value.databaseKey}.md`
|
| 165 |
|| typeof value.canEdit !== "boolean" || value.revisionHistory !== "database-note")) throw new Error("Invalid note.");
|
| 166 |
-
if (value.canEdit != null && typeof value.canEdit !== "boolean") throw new Error("Invalid permission.");
|
| 167 |
return value as unknown as IntelligenceFileRow;
|
| 168 |
}
|
| 169 |
function readFile(value: unknown): IntelligenceFile {
|
|
@@ -196,16 +189,7 @@ function readList(value: unknown): IntelligenceList {
|
|
| 196 |
|| (value.files.length > 0 && value.offset + value.files.length > value.total)) throw new Error("Invalid list.");
|
| 197 |
const files = value.files.map(readRow);
|
| 198 |
if (new Set(files.map((file) => file.path)).size !== files.length) throw new Error("Invalid list.");
|
| 199 |
-
|
| 200 |
-
|| (value.folderRevision != null && !count(value.folderRevision))) throw new Error("Invalid folder permission.");
|
| 201 |
-
return { files, total: value.total, offset: value.offset, limit: value.limit, folders: value.folders as string[],
|
| 202 |
-
...(typeof value.canManageFolders === "boolean" ? { canManageFolders: value.canManageFolders } : {}),
|
| 203 |
-
...(count(value.folderRevision) ? { folderRevision: value.folderRevision } : {}) };
|
| 204 |
-
}
|
| 205 |
-
|
| 206 |
-
function readDeleted(value: unknown, path: string): { deleted: string } {
|
| 207 |
-
if (!object(value) || value.deleted !== path) throw new Error("Invalid deletion.");
|
| 208 |
-
return { deleted: path };
|
| 209 |
}
|
| 210 |
|
| 211 |
function readHistory(value: unknown): IntelligenceHistory {
|
|
@@ -258,8 +242,7 @@ async function request<T>(query: string, init: RequestInit, parse: (value: unkno
|
|
| 258 |
const body: unknown = await response.json().catch(() => null);
|
| 259 |
if (!response.ok) {
|
| 260 |
const refusal = refusalPair(body);
|
| 261 |
-
const message = response.status >= 500 ? (init.method === "
|
| 262 |
-
? "The change could not be confirmed. Reload and try again." : init.method === "PUT"
|
| 263 |
? "The file save could not be confirmed. Reload and try again." : init.method === "POST"
|
| 264 |
? resource === "restore" ? "The restore could not be confirmed. Reload and try again."
|
| 265 |
: "The decision could not be confirmed. Reload and try again." : "Brain files could not be read. Try again.") : refusal.message;
|
|
@@ -288,29 +271,6 @@ export function newFilePayload(input: NewIntelligenceFile): { path: string; body
|
|
| 288 |
}
|
| 289 |
|
| 290 |
export const intelligenceApi: IntelligenceApi = {
|
| 291 |
-
renameFile(path, title, expectedVersion) {
|
| 292 |
-
return request("", { method: "PATCH", headers: { "Content-Type": "application/json" },
|
| 293 |
-
body: JSON.stringify({ path, title, expectedVersion }) }, (value) => {
|
| 294 |
-
const file = readFile(value);
|
| 295 |
-
if (file.path !== path || file.version <= expectedVersion) throw new Error("Invalid rename.");
|
| 296 |
-
return file;
|
| 297 |
-
});
|
| 298 |
-
},
|
| 299 |
-
deleteFile(path, expectedVersion) {
|
| 300 |
-
return request(`?${new URLSearchParams({ path, expectedVersion: String(expectedVersion) })}`,
|
| 301 |
-
{ method: "DELETE" }, (value) => readDeleted(value, path));
|
| 302 |
-
},
|
| 303 |
-
renameFolder(path, name, expectedRevision) {
|
| 304 |
-
return request("", { method: "PATCH", headers: { "Content-Type": "application/json" },
|
| 305 |
-
body: JSON.stringify({ path, name, expectedRevision }) }, (value) => {
|
| 306 |
-
if (!object(value) || typeof value.path !== "string" || !value.path) throw new Error("Invalid folder rename.");
|
| 307 |
-
return { path: value.path };
|
| 308 |
-
}, "folders");
|
| 309 |
-
},
|
| 310 |
-
deleteFolder(path, expectedRevision) {
|
| 311 |
-
return request(`?${new URLSearchParams({ path, expectedRevision: String(expectedRevision) })}`,
|
| 312 |
-
{ method: "DELETE" }, (value) => readDeleted(value, path), "folders");
|
| 313 |
-
},
|
| 314 |
history(path, version, signal) {
|
| 315 |
return request(`?${new URLSearchParams({ path, version: String(version) })}`, { method: "GET", signal }, readHistory, "history");
|
| 316 |
},
|
|
|
|
| 104 |
offset: number;
|
| 105 |
limit: number;
|
| 106 |
folders: string[];
|
|
|
|
|
|
|
| 107 |
}
|
| 108 |
export interface IntelligenceQuery {
|
| 109 |
q: string;
|
|
|
|
| 132 |
history(path: string, version: number, signal?: AbortSignal): Promise<IntelligenceHistory>;
|
| 133 |
restore(path: string, version: number, expectedVersion: number): Promise<IntelligenceFile>;
|
| 134 |
insights(signal?: AbortSignal): Promise<IntelligenceInsights>;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
}
|
| 136 |
|
| 137 |
export class IntelligenceApiError extends Error {
|
|
|
|
| 157 |
if (value.section === "database-notes" && (typeof value.databaseKey !== "string" || !value.databaseKey
|
| 158 |
|| value.databaseKey.includes("/") || value.path !== `database-notes/${value.databaseKey}.md`
|
| 159 |
|| typeof value.canEdit !== "boolean" || value.revisionHistory !== "database-note")) throw new Error("Invalid note.");
|
|
|
|
| 160 |
return value as unknown as IntelligenceFileRow;
|
| 161 |
}
|
| 162 |
function readFile(value: unknown): IntelligenceFile {
|
|
|
|
| 189 |
|| (value.files.length > 0 && value.offset + value.files.length > value.total)) throw new Error("Invalid list.");
|
| 190 |
const files = value.files.map(readRow);
|
| 191 |
if (new Set(files.map((file) => file.path)).size !== files.length) throw new Error("Invalid list.");
|
| 192 |
+
return { files, total: value.total, offset: value.offset, limit: value.limit, folders: value.folders as string[] };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
}
|
| 194 |
|
| 195 |
function readHistory(value: unknown): IntelligenceHistory {
|
|
|
|
| 242 |
const body: unknown = await response.json().catch(() => null);
|
| 243 |
if (!response.ok) {
|
| 244 |
const refusal = refusalPair(body);
|
| 245 |
+
const message = response.status >= 500 ? (init.method === "PUT"
|
|
|
|
| 246 |
? "The file save could not be confirmed. Reload and try again." : init.method === "POST"
|
| 247 |
? resource === "restore" ? "The restore could not be confirmed. Reload and try again."
|
| 248 |
: "The decision could not be confirmed. Reload and try again." : "Brain files could not be read. Try again.") : refusal.message;
|
|
|
|
| 271 |
}
|
| 272 |
|
| 273 |
export const intelligenceApi: IntelligenceApi = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
history(path, version, signal) {
|
| 275 |
return request(`?${new URLSearchParams({ path, version: String(version) })}`, { method: "GET", signal }, readHistory, "history");
|
| 276 |
},
|
web/src/operator/OperatorPage.tsx
CHANGED
|
@@ -1,10 +1,10 @@
|
|
| 1 |
-
import { useEffect,
|
| 2 |
import {
|
| 3 |
AutomationError, createOperatorGrant, getOperatorAudit, getOperatorSetup,
|
| 4 |
getOperatorVoiceSetup, getSystemData, type OperatorAudit, type OperatorGrant,
|
| 5 |
type OperatorSetup, type OperatorSetupField, type OperatorVoiceSetup, type SystemData,
|
| 6 |
} from "../automation/automationApi";
|
| 7 |
-
import { API_V1, CREDENTIALS,
|
| 8 |
import "./operator.css";
|
| 9 |
|
| 10 |
export interface OperatorPageProps { platformAdmin: boolean }
|
|
@@ -13,30 +13,7 @@ const SAFE_SETUP_FIELDS: OperatorSetupField[] = [
|
|
| 13 |
"displayName", "timezone", "voicePurpose", "consentPolicy", "queryEnabled", "providerLabel",
|
| 14 |
];
|
| 15 |
|
| 16 |
-
function useRefusalToast() {
|
| 17 |
-
const [messages, setMessages] = useState<{ id: number; text: string }[]>([]);
|
| 18 |
-
const sequence = useRef(0);
|
| 19 |
-
const delivered = useRef(0);
|
| 20 |
-
useEffect(() => {
|
| 21 |
-
if (!messages.length) return;
|
| 22 |
-
const through = messages[messages.length - 1].id;
|
| 23 |
-
for (const message of messages) {
|
| 24 |
-
if (message.id <= delivered.current) continue;
|
| 25 |
-
delivered.current = message.id;
|
| 26 |
-
const text = message.text;
|
| 27 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
|
| 28 |
-
}
|
| 29 |
-
setMessages((current) => current.filter((message) => message.id > through));
|
| 30 |
-
}, [messages]);
|
| 31 |
-
return (text: string) => {
|
| 32 |
-
if (!text) return;
|
| 33 |
-
const message = { id: ++sequence.current, text };
|
| 34 |
-
setMessages((current) => [...current, message]);
|
| 35 |
-
};
|
| 36 |
-
}
|
| 37 |
-
|
| 38 |
export default function OperatorPage({ platformAdmin }: OperatorPageProps) {
|
| 39 |
-
const refuse = useRefusalToast();
|
| 40 |
const [audit, setAudit] = useState<OperatorAudit[] | null>(null);
|
| 41 |
const [system, setSystem] = useState<SystemData | null>(null);
|
| 42 |
const [tenant, setTenant] = useState("");
|
|
@@ -80,20 +57,13 @@ export default function OperatorPage({ platformAdmin }: OperatorPageProps) {
|
|
| 80 |
const voiceSetup = await getOperatorVoiceSetup(target, granted.token);
|
| 81 |
setSetup(tenantSetup); setVoice(voiceSetup);
|
| 82 |
} catch (error) {
|
| 83 |
-
const refused = error instanceof AutomationError &&
|
| 84 |
-
|
| 85 |
-
+ (error instanceof Error ? error.message : "Tenant setup unavailable.");
|
| 86 |
-
if (refused) refuse(text);
|
| 87 |
-
else setProblem(text);
|
| 88 |
} finally {
|
| 89 |
// Both allowed and refused inspections append an audit result. Refresh after either path so
|
| 90 |
// the visible receipt is the final server outcome, not the preflight list.
|
| 91 |
try { setAudit((await getOperatorAudit()).audit); }
|
| 92 |
-
catch (error) {
|
| 93 |
-
const text = error instanceof Error ? error.message : "Audit refresh unavailable.";
|
| 94 |
-
if (error instanceof AutomationError && [401, 403, 404].includes(error.status)) refuse(text);
|
| 95 |
-
else setLoadError({ sentence: "Could not refresh the audit history.", detail: text });
|
| 96 |
-
}
|
| 97 |
setBusy(false);
|
| 98 |
}
|
| 99 |
}
|
|
|
|
| 1 |
+
import { useEffect, useState } from "react";
|
| 2 |
import {
|
| 3 |
AutomationError, createOperatorGrant, getOperatorAudit, getOperatorSetup,
|
| 4 |
getOperatorVoiceSetup, getSystemData, type OperatorAudit, type OperatorGrant,
|
| 5 |
type OperatorSetup, type OperatorSetupField, type OperatorVoiceSetup, type SystemData,
|
| 6 |
} from "../automation/automationApi";
|
| 7 |
+
import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../apiContract";
|
| 8 |
import "./operator.css";
|
| 9 |
|
| 10 |
export interface OperatorPageProps { platformAdmin: boolean }
|
|
|
|
| 13 |
"displayName", "timezone", "voicePurpose", "consentPolicy", "queryEnabled", "providerLabel",
|
| 14 |
];
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
export default function OperatorPage({ platformAdmin }: OperatorPageProps) {
|
|
|
|
| 17 |
const [audit, setAudit] = useState<OperatorAudit[] | null>(null);
|
| 18 |
const [system, setSystem] = useState<SystemData | null>(null);
|
| 19 |
const [tenant, setTenant] = useState("");
|
|
|
|
| 57 |
const voiceSetup = await getOperatorVoiceSetup(target, granted.token);
|
| 58 |
setSetup(tenantSetup); setVoice(voiceSetup);
|
| 59 |
} catch (error) {
|
| 60 |
+
const refused = error instanceof AutomationError && (error.status === 403 || error.status === 404);
|
| 61 |
+
setProblem((refused ? "That tenant or capability is unavailable. " : "") + (error instanceof Error ? error.message : "Tenant setup unavailable."));
|
|
|
|
|
|
|
|
|
|
| 62 |
} finally {
|
| 63 |
// Both allowed and refused inspections append an audit result. Refresh after either path so
|
| 64 |
// the visible receipt is the final server outcome, not the preflight list.
|
| 65 |
try { setAudit((await getOperatorAudit()).audit); }
|
| 66 |
+
catch (error) { setProblem((current) => current || (error instanceof Error ? error.message : "Audit refresh unavailable.")); }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
setBusy(false);
|
| 68 |
}
|
| 69 |
}
|
web/src/query/queryApi.ts
CHANGED
|
@@ -254,7 +254,7 @@ export interface AssistantArtifact {
|
|
| 254 |
createdAt: string; status: "active" | "paused" | "deleted";
|
| 255 |
toolCall: ArtifactToolCall;
|
| 256 |
file_id?: string; mime?: string; link?: string; frozen_at?: string;
|
| 257 |
-
actions: Array<"open" | "run" | "pause" | "resume" | "
|
| 258 |
}
|
| 259 |
export interface ArtifactIndex { items: AssistantArtifact[]; nextCursor: string | null; }
|
| 260 |
|
|
|
|
| 254 |
createdAt: string; status: "active" | "paused" | "deleted";
|
| 255 |
toolCall: ArtifactToolCall;
|
| 256 |
file_id?: string; mime?: string; link?: string; frozen_at?: string;
|
| 257 |
+
actions: Array<"open" | "run" | "pause" | "resume" | "delete">;
|
| 258 |
}
|
| 259 |
export interface ArtifactIndex { items: AssistantArtifact[]; nextCursor: string | null; }
|
| 260 |
|
web/src/query/queryParts.tsx
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
-
import {
|
| 2 |
import type { ReactNode } from "react";
|
| 3 |
import { useEscapeClose } from "../ui/useEscapeClose";
|
| 4 |
-
import { TOAST_EVENT } from "../apiContract";
|
| 5 |
import { useOverlayLayer } from "../customer-grid/OverlaySurface";
|
| 6 |
|
| 7 |
import { FolderMark } from "../customer-grid/icons";
|
|
@@ -52,28 +51,6 @@ import type { SavedQuery } from "./queryApi";
|
|
| 52 |
import "./query.css";
|
| 53 |
|
| 54 |
/** Which label of which row is being typed into. One at a time, by construction. */
|
| 55 |
-
function useRefusalToast() {
|
| 56 |
-
const [messages, setMessages] = useState<{ id: number; text: string }[]>([]);
|
| 57 |
-
const sequence = useRef(0);
|
| 58 |
-
const delivered = useRef(0);
|
| 59 |
-
useEffect(() => {
|
| 60 |
-
if (!messages.length) return;
|
| 61 |
-
const through = messages[messages.length - 1].id;
|
| 62 |
-
for (const message of messages) {
|
| 63 |
-
if (message.id <= delivered.current) continue;
|
| 64 |
-
delivered.current = message.id;
|
| 65 |
-
const text = message.text;
|
| 66 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
|
| 67 |
-
}
|
| 68 |
-
setMessages((current) => current.filter((message) => message.id > through));
|
| 69 |
-
}, [messages]);
|
| 70 |
-
return (text: string) => {
|
| 71 |
-
if (!text) return;
|
| 72 |
-
const message = { id: ++sequence.current, text };
|
| 73 |
-
setMessages((current) => [...current, message]);
|
| 74 |
-
};
|
| 75 |
-
}
|
| 76 |
-
|
| 77 |
interface Editing { id: string; field: "name" | "description"; value: string; }
|
| 78 |
|
| 79 |
function QueryActionMenu({ anchor, onClose, children }: {
|
|
@@ -219,23 +196,20 @@ export function QueryRail({ groups, activeId, onSelect, onDelete, onChanged }: {
|
|
| 219 |
const [editing, setEditing] = useState<Editing | null>(null);
|
| 220 |
const menuOpenerRef = useRef<HTMLButtonElement | null>(null);
|
| 221 |
const editingFinishedRef = useRef(false);
|
| 222 |
-
const editingSequence = useRef(0);
|
| 223 |
useEscapeClose(editing !== null, () => {
|
| 224 |
-
editingSequence.current += 1;
|
| 225 |
editingFinishedRef.current = true;
|
| 226 |
setEditing(null);
|
| 227 |
menuOpenerRef.current?.focus();
|
| 228 |
});
|
| 229 |
const beginEditing = (next: Editing) => {
|
| 230 |
-
editingSequence.current += 1;
|
| 231 |
editingFinishedRef.current = false;
|
| 232 |
setMenuFor("");
|
| 233 |
setEditing(next);
|
| 234 |
};
|
| 235 |
// âš TWO STATES, NOT ONE. A refusal and a confirmation read differently and are coloured
|
| 236 |
// differently; sharing one slot painted "Saved as ..." in the refusal red.
|
|
|
|
| 237 |
const [notice, setNotice] = useState("");
|
| 238 |
-
const refuse = useRefusalToast();
|
| 239 |
/**
|
| 240 |
* ⭐ C2's star list, read AFTER PAINT and never blocking the rail (E-2: `GET /starred` scans
|
| 241 |
* every visible database's view bucket and was MEASURED at 7,331 ms on a cold container). The
|
|
@@ -245,28 +219,17 @@ export function QueryRail({ groups, activeId, onSelect, onDelete, onChanged }: {
|
|
| 245 |
*/
|
| 246 |
const stars = useStarred();
|
| 247 |
const starred = new Set(stars.starred.queries);
|
| 248 |
-
const said = (message: string) => setNotice(message);
|
| 249 |
-
const failed = (
|
| 250 |
-
setNotice("");
|
| 251 |
-
refuse(text);
|
| 252 |
-
};
|
| 253 |
|
| 254 |
const commit = async () => {
|
| 255 |
if (!editing || editingFinishedRef.current) return;
|
| 256 |
editingFinishedRef.current = true;
|
| 257 |
const current = editing;
|
| 258 |
-
const sequence = editingSequence.current;
|
| 259 |
setEditing(null);
|
| 260 |
const result = await renameQuery(current.id, current.field === "name"
|
| 261 |
? { name: current.value } : { description: current.value });
|
| 262 |
-
if (!result.ok) {
|
| 263 |
-
if (sequence === editingSequence.current) {
|
| 264 |
-
editingFinishedRef.current = false;
|
| 265 |
-
setEditing((next) => next ?? current);
|
| 266 |
-
}
|
| 267 |
-
failed(result.message);
|
| 268 |
-
return;
|
| 269 |
-
}
|
| 270 |
said("");
|
| 271 |
onChanged?.(result.value);
|
| 272 |
};
|
|
@@ -328,6 +291,7 @@ export function QueryRail({ groups, activeId, onSelect, onDelete, onChanged }: {
|
|
| 328 |
<button type="button" className="qy-rail-scrim" aria-label="Close menu"
|
| 329 |
onClick={() => setMenuFor("")} />
|
| 330 |
) : null}
|
|
|
|
| 331 |
{notice ? <p className="qy-rail-notice" role="status">{notice}</p> : null}
|
| 332 |
<div className="qy-rail-scroll">
|
| 333 |
{groups.map((group) => (
|
|
|
|
| 1 |
+
import { useRef, useState } from "react";
|
| 2 |
import type { ReactNode } from "react";
|
| 3 |
import { useEscapeClose } from "../ui/useEscapeClose";
|
|
|
|
| 4 |
import { useOverlayLayer } from "../customer-grid/OverlaySurface";
|
| 5 |
|
| 6 |
import { FolderMark } from "../customer-grid/icons";
|
|
|
|
| 51 |
import "./query.css";
|
| 52 |
|
| 53 |
/** Which label of which row is being typed into. One at a time, by construction. */
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
interface Editing { id: string; field: "name" | "description"; value: string; }
|
| 55 |
|
| 56 |
function QueryActionMenu({ anchor, onClose, children }: {
|
|
|
|
| 196 |
const [editing, setEditing] = useState<Editing | null>(null);
|
| 197 |
const menuOpenerRef = useRef<HTMLButtonElement | null>(null);
|
| 198 |
const editingFinishedRef = useRef(false);
|
|
|
|
| 199 |
useEscapeClose(editing !== null, () => {
|
|
|
|
| 200 |
editingFinishedRef.current = true;
|
| 201 |
setEditing(null);
|
| 202 |
menuOpenerRef.current?.focus();
|
| 203 |
});
|
| 204 |
const beginEditing = (next: Editing) => {
|
|
|
|
| 205 |
editingFinishedRef.current = false;
|
| 206 |
setMenuFor("");
|
| 207 |
setEditing(next);
|
| 208 |
};
|
| 209 |
// âš TWO STATES, NOT ONE. A refusal and a confirmation read differently and are coloured
|
| 210 |
// differently; sharing one slot painted "Saved as ..." in the refusal red.
|
| 211 |
+
const [problem, setProblem] = useState("");
|
| 212 |
const [notice, setNotice] = useState("");
|
|
|
|
| 213 |
/**
|
| 214 |
* ⭐ C2's star list, read AFTER PAINT and never blocking the rail (E-2: `GET /starred` scans
|
| 215 |
* every visible database's view bucket and was MEASURED at 7,331 ms on a cold container). The
|
|
|
|
| 219 |
*/
|
| 220 |
const stars = useStarred();
|
| 221 |
const starred = new Set(stars.starred.queries);
|
| 222 |
+
const said = (message: string) => { setNotice(message); setProblem(""); };
|
| 223 |
+
const failed = (message: string) => { setProblem(message); setNotice(""); };
|
|
|
|
|
|
|
|
|
|
| 224 |
|
| 225 |
const commit = async () => {
|
| 226 |
if (!editing || editingFinishedRef.current) return;
|
| 227 |
editingFinishedRef.current = true;
|
| 228 |
const current = editing;
|
|
|
|
| 229 |
setEditing(null);
|
| 230 |
const result = await renameQuery(current.id, current.field === "name"
|
| 231 |
? { name: current.value } : { description: current.value });
|
| 232 |
+
if (!result.ok) { failed(result.message); return; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
said("");
|
| 234 |
onChanged?.(result.value);
|
| 235 |
};
|
|
|
|
| 291 |
<button type="button" className="qy-rail-scrim" aria-label="Close menu"
|
| 292 |
onClick={() => setMenuFor("")} />
|
| 293 |
) : null}
|
| 294 |
+
{problem ? <p className="qy-rail-problem" role="status">{problem}</p> : null}
|
| 295 |
{notice ? <p className="qy-rail-notice" role="status">{notice}</p> : null}
|
| 296 |
<div className="qy-rail-scroll">
|
| 297 |
{groups.map((group) => (
|
web/src/settings/SettingsModal.tsx
CHANGED
|
@@ -33,7 +33,7 @@
|
|
| 33 |
// would not open.
|
| 34 |
// ---------------------------------------------------------------------------
|
| 35 |
|
| 36 |
-
import { useCallback, useEffect,
|
| 37 |
// ⭐ W37-T05 — the shared in-flight label; see `ui/Busy.tsx` for why it is a component.
|
| 38 |
import { Busy } from "../ui/Busy";
|
| 39 |
import { useOverlayLayer } from "../customer-grid/OverlaySurface";
|
|
@@ -63,7 +63,7 @@ import type { ConnectorRow, KeyEntry, UnsyncedInfo } from "./settingsApi";
|
|
| 63 |
// `/admin/connectors` row (a credential with a status column) and the directory's row is a CARD.
|
| 64 |
// Two different payloads that happen to share a word, so the second is aliased rather than one of
|
| 65 |
// them renamed under another ticket's file.
|
| 66 |
-
import { API_V1, CREDENTIALS
|
| 67 |
import ConnectorModal from "../connectors/ConnectorModal";
|
| 68 |
import { scopeLabel } from "../connectors/KeychainTab";
|
| 69 |
import { parseDirectory } from "../connectors/ConnectorsPage";
|
|
@@ -351,7 +351,7 @@ function UsersPane() {
|
|
| 351 |
setError("");
|
| 352 |
reload();
|
| 353 |
}}
|
| 354 |
-
onError={
|
| 355 |
/>
|
| 356 |
|
| 357 |
{users.length === 0 && !error ? (
|
|
@@ -476,19 +476,6 @@ function AddUser({
|
|
| 476 |
const [role, setRole] = useState("user");
|
| 477 |
const [password, setPassword_] = useState("");
|
| 478 |
const [busy, setBusy] = useState(false);
|
| 479 |
-
const requestScope = useRef<AbortController | null>(null);
|
| 480 |
-
useLayoutEffect(() => {
|
| 481 |
-
const scope = new AbortController();
|
| 482 |
-
requestScope.current = scope;
|
| 483 |
-
const invalidate = () => scope.abort();
|
| 484 |
-
window.addEventListener(UNAUTHORIZED_EVENT, invalidate);
|
| 485 |
-
window.addEventListener("aios:signed-out", invalidate);
|
| 486 |
-
return () => {
|
| 487 |
-
scope.abort();
|
| 488 |
-
window.removeEventListener(UNAUTHORIZED_EVENT, invalidate);
|
| 489 |
-
window.removeEventListener("aios:signed-out", invalidate);
|
| 490 |
-
};
|
| 491 |
-
}, []);
|
| 492 |
|
| 493 |
if (!open)
|
| 494 |
return (
|
|
@@ -563,8 +550,6 @@ function AddUser({
|
|
| 563 |
className="set-primary"
|
| 564 |
disabled={busy || !valid}
|
| 565 |
onClick={() => {
|
| 566 |
-
const request = requestScope.current?.signal;
|
| 567 |
-
if (!request || request.aborted) return;
|
| 568 |
setBusy(true);
|
| 569 |
void createUser({
|
| 570 |
// D-385: sent as typed. The server folds a slug and keeps an email's spelling.
|
|
@@ -588,7 +573,6 @@ function AddUser({
|
|
| 588 |
modules: "all",
|
| 589 |
password,
|
| 590 |
}).then((r) => {
|
| 591 |
-
if (request.aborted) return;
|
| 592 |
setBusy(false);
|
| 593 |
if (r.ok) {
|
| 594 |
onCreated(`Created ${username.trim()}.`);
|
|
|
|
| 33 |
// would not open.
|
| 34 |
// ---------------------------------------------------------------------------
|
| 35 |
|
| 36 |
+
import { useCallback, useEffect, useRef, useState } from "react";
|
| 37 |
// ⭐ W37-T05 — the shared in-flight label; see `ui/Busy.tsx` for why it is a component.
|
| 38 |
import { Busy } from "../ui/Busy";
|
| 39 |
import { useOverlayLayer } from "../customer-grid/OverlaySurface";
|
|
|
|
| 63 |
// `/admin/connectors` row (a credential with a status column) and the directory's row is a CARD.
|
| 64 |
// Two different payloads that happen to share a word, so the second is aliased rather than one of
|
| 65 |
// them renamed under another ticket's file.
|
| 66 |
+
import { API_V1, CREDENTIALS } from "../apiContract";
|
| 67 |
import ConnectorModal from "../connectors/ConnectorModal";
|
| 68 |
import { scopeLabel } from "../connectors/KeychainTab";
|
| 69 |
import { parseDirectory } from "../connectors/ConnectorsPage";
|
|
|
|
| 351 |
setError("");
|
| 352 |
reload();
|
| 353 |
}}
|
| 354 |
+
onError={setError}
|
| 355 |
/>
|
| 356 |
|
| 357 |
{users.length === 0 && !error ? (
|
|
|
|
| 476 |
const [role, setRole] = useState("user");
|
| 477 |
const [password, setPassword_] = useState("");
|
| 478 |
const [busy, setBusy] = useState(false);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 479 |
|
| 480 |
if (!open)
|
| 481 |
return (
|
|
|
|
| 550 |
className="set-primary"
|
| 551 |
disabled={busy || !valid}
|
| 552 |
onClick={() => {
|
|
|
|
|
|
|
| 553 |
setBusy(true);
|
| 554 |
void createUser({
|
| 555 |
// D-385: sent as typed. The server folds a slug and keeps an email's spelling.
|
|
|
|
| 573 |
modules: "all",
|
| 574 |
password,
|
| 575 |
}).then((r) => {
|
|
|
|
| 576 |
setBusy(false);
|
| 577 |
if (r.ok) {
|
| 578 |
onCreated(`Created ${username.trim()}.`);
|
web/src/sheet/SheetPage.tsx
CHANGED
|
@@ -34,7 +34,6 @@
|
|
| 34 |
|
| 35 |
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
|
| 36 |
import type { PointerEvent as ReactPointerEvent, ReactNode } from "react";
|
| 37 |
-
import { TOAST_EVENT } from "../apiContract";
|
| 38 |
import "../styles/wave49/sheet.css";
|
| 39 |
import "../styles/wave50/sheet.css";
|
| 40 |
import "../styles/wave55/sheet.css";
|
|
@@ -411,28 +410,6 @@ export interface SheetPageProps {
|
|
| 411 |
onNavigate?: (address: { database: string; view?: string }) => void;
|
| 412 |
}
|
| 413 |
|
| 414 |
-
function useRefusalToast() {
|
| 415 |
-
const [messages, setMessages] = useState<{ id: number; text: string }[]>([]);
|
| 416 |
-
const sequence = useRef(0);
|
| 417 |
-
const delivered = useRef(0);
|
| 418 |
-
useEffect(() => {
|
| 419 |
-
if (!messages.length) return;
|
| 420 |
-
const through = messages[messages.length - 1].id;
|
| 421 |
-
for (const message of messages) {
|
| 422 |
-
if (message.id <= delivered.current) continue;
|
| 423 |
-
delivered.current = message.id;
|
| 424 |
-
const text = message.text;
|
| 425 |
-
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
|
| 426 |
-
}
|
| 427 |
-
setMessages((current) => current.filter((message) => message.id > through));
|
| 428 |
-
}, [messages]);
|
| 429 |
-
return (text: string) => {
|
| 430 |
-
if (!text) return;
|
| 431 |
-
const message = { id: ++sequence.current, text };
|
| 432 |
-
setMessages((current) => [...current, message]);
|
| 433 |
-
};
|
| 434 |
-
}
|
| 435 |
-
|
| 436 |
export default function SheetPage({ address: mountAddress, embedded = false, onNavigate }: SheetPageProps = {}) {
|
| 437 |
const instanceId = useId();
|
| 438 |
const storagePrefix = embedded ? `embed:sheet:${instanceId}:` : "";
|
|
@@ -467,14 +444,6 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 467 |
} | null>(null);
|
| 468 |
const [busy, setBusy] = useState(false);
|
| 469 |
const [notice, setNotice] = useState("");
|
| 470 |
-
const showRefusal = useRefusalToast();
|
| 471 |
-
const [readAttempt, setReadAttempt] = useState(0);
|
| 472 |
-
const readRetry = useRef<(() => void) | null>(null);
|
| 473 |
-
const retryOpeningRead = () => {
|
| 474 |
-
setNotice("");
|
| 475 |
-
handledSheetHashRef.current = "";
|
| 476 |
-
setReadAttempt((attempt) => attempt + 1);
|
| 477 |
-
};
|
| 478 |
/** W53-T09: bumped by the ribbon's Import button; `SheetRail` opens its dialog on a change. */
|
| 479 |
const [importRequest, setImportRequest] = useState(0);
|
| 480 |
/**
|
|
@@ -1012,7 +981,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1012 |
setEditAt("");
|
| 1013 |
setDrillAt("");
|
| 1014 |
setUnreadableAddressTab("");
|
| 1015 |
-
|
| 1016 |
acceptedAddressRef.current = null;
|
| 1017 |
handledSheetHashRef.current = currentSheetHash();
|
| 1018 |
return;
|
|
@@ -1123,13 +1092,8 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1123 |
if (!absent || tabRouteRef.current === "yes") {
|
| 1124 |
// ⛔ A TAB THAT WILL NOT LOAD IS NOT AN EMPTY TAB. Painting it as one reads exactly
|
| 1125 |
// like the cells having been deleted, so the reason is said instead.
|
| 1126 |
-
if (!quiet && still === "apply")
|
| 1127 |
-
|
| 1128 |
-
readRetry.current = () => {
|
| 1129 |
-
setNotice("");
|
| 1130 |
-
void ensureTabs(workbookId, [key], false, stillCurrent);
|
| 1131 |
-
};
|
| 1132 |
-
}
|
| 1133 |
return false;
|
| 1134 |
}
|
| 1135 |
tabRouteRef.current = "no";
|
|
@@ -1142,13 +1106,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1142 |
const still = stillCurrent === undefined || stillCurrent() ? "apply" : "discard";
|
| 1143 |
if (!fresh.ok) {
|
| 1144 |
if (discardMissingWorkbook(workbookId, fresh)) return false;
|
| 1145 |
-
if (!quiet && still === "apply")
|
| 1146 |
-
setNotice(fresh.message);
|
| 1147 |
-
readRetry.current = () => {
|
| 1148 |
-
setNotice("");
|
| 1149 |
-
void ensureTabs(workbookId, keys, false, stillCurrent);
|
| 1150 |
-
};
|
| 1151 |
-
}
|
| 1152 |
return false;
|
| 1153 |
}
|
| 1154 |
const live = bookRef.current;
|
|
@@ -1295,7 +1253,6 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1295 |
} catch {
|
| 1296 |
if (stillCurrent()) {
|
| 1297 |
setNotice("That sheet could not be read, so it is not shown.");
|
| 1298 |
-
readRetry.current = () => openTab(id);
|
| 1299 |
setUnreadableAddressTab(id);
|
| 1300 |
}
|
| 1301 |
} finally {
|
|
@@ -1371,7 +1328,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1371 |
if (bookRef.current?.id !== book.id) return;
|
| 1372 |
if (!got.ok) {
|
| 1373 |
if (typeof got.rev_current === "number") applyLocal({ ...bookRef.current, rev: got.rev_current });
|
| 1374 |
-
|
| 1375 |
return;
|
| 1376 |
}
|
| 1377 |
const live = bookRef.current;
|
|
@@ -1434,7 +1391,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1434 |
sheets: live.sheets.map((t) => (t.id === tabKey ? { ...t, ...next } : t)),
|
| 1435 |
});
|
| 1436 |
}
|
| 1437 |
-
if (bookRef.current?.id === workbookId)
|
| 1438 |
}, [applyLocal]);
|
| 1439 |
|
| 1440 |
/**
|
|
@@ -1507,7 +1464,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1507 |
markAllLoaded(fresh.value);
|
| 1508 |
applyLocal(fresh.value);
|
| 1509 |
}
|
| 1510 |
-
if (bookRef.current?.id === current.id)
|
| 1511 |
return "stopped";
|
| 1512 |
}
|
| 1513 |
if (sent.ok) {
|
|
@@ -1549,12 +1506,12 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1549 |
const conflicts = sent.value.conflicts ?? [];
|
| 1550 |
if (conflicts.length > 0) {
|
| 1551 |
const changed = conflicts.map((cell) => `${cell.byName || cell.by} changed ${cell.addr}`).join("; ");
|
| 1552 |
-
|
| 1553 |
}
|
| 1554 |
if (refused.length > 0) {
|
| 1555 |
savedCleanRef.current = false;
|
| 1556 |
const head = refused[0];
|
| 1557 |
-
|
| 1558 |
? (head.sentence || `${head.addr} was not saved.`)
|
| 1559 |
: `${head.sentence || `${head.addr} was not saved.`} `
|
| 1560 |
+ `${refused.length - 1} other cells were refused for the same kind of reason.`);
|
|
@@ -1570,7 +1527,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1570 |
// ⭐ THE SERVER'S OWN SENTENCE, VERBATIM. C3 says it names the count and the cap, and
|
| 1571 |
// it is the server that knows which cap was hit, cells or bytes. Rewriting it here
|
| 1572 |
// would be this client guessing at a number it never measured.
|
| 1573 |
-
|
| 1574 |
return "stopped";
|
| 1575 |
}
|
| 1576 |
if (sent.status === 405 && patchModeRef.current !== "patch") {
|
|
@@ -1585,7 +1542,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1585 |
return "route_absent";
|
| 1586 |
}
|
| 1587 |
for (const addr of Array.from(addrs)) markDirty(tabKey, addr);
|
| 1588 |
-
|
| 1589 |
return "stopped";
|
| 1590 |
}
|
| 1591 |
return "sent";
|
|
@@ -1602,7 +1559,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1602 |
const fresh = await readWorkbook(workbookId);
|
| 1603 |
if (bookRef.current?.id !== workbookId) return;
|
| 1604 |
if (!fresh.ok) {
|
| 1605 |
-
|
| 1606 |
return;
|
| 1607 |
}
|
| 1608 |
historyRef.current = emptyHistory();
|
|
@@ -1613,7 +1570,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1613 |
markAllLoaded(fresh.value);
|
| 1614 |
applyLocal(fresh.value);
|
| 1615 |
workbookConflictRef.current = null;
|
| 1616 |
-
|
| 1617 |
}, [applyLocal, markAllLoaded]);
|
| 1618 |
|
| 1619 |
/**
|
|
@@ -1641,7 +1598,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1641 |
// be sent and the cells that were would describe a grid the server does not have.
|
| 1642 |
structureDirtyRef.current = true;
|
| 1643 |
savedCleanRef.current = false;
|
| 1644 |
-
|
| 1645 |
+ "Reload the page and try again.");
|
| 1646 |
return;
|
| 1647 |
}
|
|
@@ -1666,7 +1623,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1666 |
// structure change is still pending and the next drain must still carry it.
|
| 1667 |
structureDirtyRef.current = true;
|
| 1668 |
savedCleanRef.current = false;
|
| 1669 |
-
|
| 1670 |
return;
|
| 1671 |
}
|
| 1672 |
if (bookRef.current?.id !== current.id) return;
|
|
@@ -1768,7 +1725,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1768 |
]);
|
| 1769 |
if (timer !== null) window.clearTimeout(timer);
|
| 1770 |
if (outcome === "timeout") {
|
| 1771 |
-
|
| 1772 |
workbookTransitionRef.current = false;
|
| 1773 |
return false;
|
| 1774 |
}
|
|
@@ -1973,7 +1930,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1973 |
if (!base) return;
|
| 1974 |
const refusal = structureRefusal(base, target, op);
|
| 1975 |
if (refusal) {
|
| 1976 |
-
|
| 1977 |
return;
|
| 1978 |
}
|
| 1979 |
const bound = boundCellsInBand(base.sheets.find((t) => t.id === target), op);
|
|
@@ -1991,7 +1948,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 1991 |
const base = await structureBase(pending.workbookId, pending.tabId);
|
| 1992 |
if (!base) return;
|
| 1993 |
const refusal = structureRefusal(base, pending.tabId, pending.op);
|
| 1994 |
-
if (refusal) {
|
| 1995 |
commitSheets(applyStructureWorkbook(base, pending.tabId, pending.op));
|
| 1996 |
}, [bandAt, commitSheets, structureBase]);
|
| 1997 |
|
|
@@ -2069,12 +2026,12 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2069 |
if (requested.startsWith("new:")) {
|
| 2070 |
const made = addTab(base);
|
| 2071 |
const refusal = renameTabRefusal({ ...base, sheets: made.sheets }, made.id, requested.slice(4));
|
| 2072 |
-
if (refusal) {
|
| 2073 |
destination = made.id;
|
| 2074 |
sheets = made.sheets.map(t => t.id === destination ? { ...t, name: requested.slice(4) } : t);
|
| 2075 |
}
|
| 2076 |
if (!sheets.some(t => t.id === destination) || !sheets.some(t => t.id === sourceId)) {
|
| 2077 |
-
|
| 2078 |
}
|
| 2079 |
const saved = { ...chart, sheetId: destination, source: { ...chart.source, ranges: chart.source?.ranges ?? [chart.range], sheetId: sourceId } };
|
| 2080 |
commitSheets(sheets.map(t => ({ ...t,
|
|
@@ -2203,7 +2160,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2203 |
if (!still || still.id !== workbookId) return;
|
| 2204 |
if (!result.ok) {
|
| 2205 |
if (result.status === 409) await reloadWholeWorkbookAfterConflict(workbookId);
|
| 2206 |
-
else
|
| 2207 |
return;
|
| 2208 |
}
|
| 2209 |
const saved = result.value;
|
|
@@ -2226,7 +2183,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2226 |
setTabId(added.id);
|
| 2227 |
refreshOpenedWorkbook(workbookId, added.id);
|
| 2228 |
}
|
| 2229 |
-
}).catch(() =>
|
| 2230 |
.finally(() => { tabWritesRef.current.delete(workbookId); });
|
| 2231 |
}, [applyLocal, canEditOutline, flushSave, refreshOpenedWorkbook, reloadWholeWorkbookAfterConflict]);
|
| 2232 |
|
|
@@ -2329,17 +2286,17 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2329 |
}, [mutateTab]);
|
| 2330 |
|
| 2331 |
const onRenameTab = useCallback(() => {
|
| 2332 |
-
if (!canEditOutline) {
|
| 2333 |
const pending = tabRename;
|
| 2334 |
const base = bookRef.current;
|
| 2335 |
if (!pending || !base) return;
|
| 2336 |
if (nameWritesRef.current.has(base.id)) {
|
| 2337 |
-
|
| 2338 |
return;
|
| 2339 |
}
|
| 2340 |
const refusal = renameTabRefusal(base, pending.id, pending.name);
|
| 2341 |
if (refusal) {
|
| 2342 |
-
|
| 2343 |
: pending.name.includes("'") ? "A sheet name cannot contain an apostrophe."
|
| 2344 |
: "Another sheet already has that name.");
|
| 2345 |
return;
|
|
@@ -2377,7 +2334,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2377 |
applyLocal({ ...still, sheets });
|
| 2378 |
}
|
| 2379 |
if (historyRef.current === renameHistory) historyRef.current = priorHistory;
|
| 2380 |
-
|
| 2381 |
};
|
| 2382 |
saveChainRef.current = saveChainRef.current.then(async () => {
|
| 2383 |
const live = bookRef.current;
|
|
@@ -2401,7 +2358,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2401 |
if (!base) return;
|
| 2402 |
const refusal = removeTabRefusal(base, id);
|
| 2403 |
if (refusal) {
|
| 2404 |
-
|
| 2405 |
return;
|
| 2406 |
}
|
| 2407 |
const target = base.sheets.find((t) => t.id === id);
|
|
@@ -2542,7 +2499,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2542 |
// ⚠ A COMPUTE THAT FAILS ON ITS OWN MERITS AFTER A SAVE THAT DID LAND still speaks, and
|
| 2543 |
// this is the case the line was written for: an unreadable database, a scope that cannot
|
| 2544 |
// be compiled, a mirror still syncing. Nothing else has written a sentence about it.
|
| 2545 |
-
|
| 2546 |
return;
|
| 2547 |
}
|
| 2548 |
applyLocal({ ...live, rev: got.value.rev || live.rev });
|
|
@@ -2596,7 +2553,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2596 |
if (!got.ok) {
|
| 2597 |
if (typeof got.rev_current === "number") applyLocal({ ...live, rev: got.rev_current });
|
| 2598 |
if (!spoke) {
|
| 2599 |
-
|
| 2600 |
spoke = true;
|
| 2601 |
}
|
| 2602 |
continue;
|
|
@@ -2679,7 +2636,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2679 |
const onViewRows = useCallback((addr: string, cell: Cell | null) => {
|
| 2680 |
const affordance = drillAffordance(cell);
|
| 2681 |
if (!affordance.enabled) {
|
| 2682 |
-
|
| 2683 |
return;
|
| 2684 |
}
|
| 2685 |
setNotice("");
|
|
@@ -2704,8 +2661,6 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2704 |
const refreshIndex = useCallback(async () => {
|
| 2705 |
const got = await readIndex();
|
| 2706 |
if (got.ok) setIndex(got.value);
|
| 2707 |
-
setNotice(got.ok ? "" : got.message);
|
| 2708 |
-
if (!got.ok) readRetry.current = () => void refreshIndex();
|
| 2709 |
}, []);
|
| 2710 |
|
| 2711 |
/**
|
|
@@ -2792,7 +2747,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2792 |
addressInitializedRef.current = true;
|
| 2793 |
}
|
| 2794 |
if (!current()) return;
|
| 2795 |
-
if (!got.ok) { setNotice(got.message);
|
| 2796 |
// An explicit id never falls through, including when access filtering omitted its row.
|
| 2797 |
if (targetId === null) {
|
| 2798 |
targetId = (got.value.workbooks.find((row) => row.id === lastWorkbookId)
|
|
@@ -2802,7 +2757,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2802 |
void readIndex().then((got) => {
|
| 2803 |
if (addressMountedRef.current) {
|
| 2804 |
if (got.ok) setIndex(got.value);
|
| 2805 |
-
else
|
| 2806 |
}
|
| 2807 |
});
|
| 2808 |
addressInitializedRef.current = true;
|
|
@@ -2841,7 +2796,6 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2841 |
setEditAt("");
|
| 2842 |
setDrillAt("");
|
| 2843 |
setNotice(got.ok ? "That sheet could not be read, so it is not shown." : got.message);
|
| 2844 |
-
readRetry.current = retryOpeningRead;
|
| 2845 |
return;
|
| 2846 |
}
|
| 2847 |
const { openingTab, ...openedWorkbook } = got.value as WorkbookOpening;
|
|
@@ -2885,7 +2839,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2885 |
})();
|
| 2886 |
}, [sheetHash, opening, barAddr, adoptWorkbook, ensureTabs, flushBeforeWorkbookChange,
|
| 2887 |
lastWorkbookId, prepareWorkbookOpen, refreshIndex, refreshOpenedWorkbook, discardMissingWorkbook,
|
| 2888 |
-
rememberOpenWorkbook, currentSheetHash, navigateSheetAddress, mergeTab
|
| 2889 |
|
| 2890 |
// The workbook can open before its index arrives. Enrich only after the open has settled,
|
| 2891 |
// so changing the hash cannot invalidate an in-flight workbook read's address guard.
|
|
@@ -2913,7 +2867,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2913 |
}
|
| 2914 |
const made = await createWorkbook("Untitled workbook");
|
| 2915 |
if (!made.ok) {
|
| 2916 |
-
|
| 2917 |
workbookTransitionRef.current = false;
|
| 2918 |
setOpening(false);
|
| 2919 |
return;
|
|
@@ -2945,14 +2899,14 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2945 |
}
|
| 2946 |
const source = await readWorkbook(id);
|
| 2947 |
if (!source.ok) {
|
| 2948 |
-
|
| 2949 |
workbookTransitionRef.current = false;
|
| 2950 |
setOpening(false);
|
| 2951 |
return;
|
| 2952 |
}
|
| 2953 |
const made = await createWorkbook(`${source.value.name} copy`);
|
| 2954 |
if (!made.ok) {
|
| 2955 |
-
|
| 2956 |
workbookTransitionRef.current = false;
|
| 2957 |
setOpening(false);
|
| 2958 |
return;
|
|
@@ -2961,7 +2915,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2961 |
name: made.value.name, sheets: source.value.sheets, rev: made.value.rev,
|
| 2962 |
});
|
| 2963 |
if (!filled.ok) {
|
| 2964 |
-
|
| 2965 |
workbookTransitionRef.current = false;
|
| 2966 |
setOpening(false);
|
| 2967 |
return;
|
|
@@ -2985,14 +2939,14 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 2985 |
*/
|
| 2986 |
const renameWorkbook = useCallback(async (id: string, name: string) => {
|
| 2987 |
if (workbookTransitionRef.current) return;
|
| 2988 |
-
if (nameWritesRef.current.has(id)) {
|
| 2989 |
setNotice("");
|
| 2990 |
name = name.trim();
|
| 2991 |
const open = bookRef.current?.id === id ? bookRef.current : null;
|
| 2992 |
const rows = railIndexRef.current.workbooks.concat(railIndexRef.current.sharedWithMe ?? []);
|
| 2993 |
const row = rows.find((row) => row.id === id);
|
| 2994 |
const before = open?.name ?? row?.name ?? "";
|
| 2995 |
-
if (!name) {
|
| 2996 |
if (name === before) return;
|
| 2997 |
nameWritesRef.current.add(id);
|
| 2998 |
setRailNames((held) => ({ ...held, [id]: { name, rev: Number.POSITIVE_INFINITY } }));
|
|
@@ -3007,7 +2961,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 3007 |
});
|
| 3008 |
const still = bookRef.current;
|
| 3009 |
if (still?.id === id && still.name === name) applyLocal({ ...still, name: before });
|
| 3010 |
-
|
| 3011 |
};
|
| 3012 |
const send = async (): Promise<void> => {
|
| 3013 |
let rev = bookRef.current?.id === id ? bookRef.current.rev : row?.rev;
|
|
@@ -3052,7 +3006,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 3052 |
setNotice("");
|
| 3053 |
const gone = await deleteWorkbook(id);
|
| 3054 |
if (!gone.ok && !isMissingItem("workbook", gone)) {
|
| 3055 |
-
|
| 3056 |
return;
|
| 3057 |
}
|
| 3058 |
itemDeleted({ kind: "workbook", id });
|
|
@@ -3114,7 +3068,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 3114 |
]);
|
| 3115 |
if (!saved.ok) {
|
| 3116 |
setIndex(previousIndex);
|
| 3117 |
-
|
| 3118 |
clearTimeout(timeout);
|
| 3119 |
const rows = await Promise.race([
|
| 3120 |
readIndex(),
|
|
@@ -3127,10 +3081,10 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 3127 |
}
|
| 3128 |
setIndex(saved.value);
|
| 3129 |
const sentence = repairSentence(saved.value.repairs);
|
| 3130 |
-
if (sentence)
|
| 3131 |
} catch (error) {
|
| 3132 |
setIndex(previousIndex);
|
| 3133 |
-
|
| 3134 |
} finally {
|
| 3135 |
clearTimeout(timeout);
|
| 3136 |
}
|
|
@@ -3214,9 +3168,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 3214 |
|
| 3215 |
if (embedded && !loading && !opening && !book && notice) {
|
| 3216 |
return <div ref={pageRef} className="sheet-page" data-embedded="true">
|
| 3217 |
-
<p className="sheet-
|
| 3218 |
-
<button type="button" className="set-secondary" onClick={() => (readRetry.current ?? retryOpeningRead)()}>Retry</button>
|
| 3219 |
-
</p>
|
| 3220 |
</div>;
|
| 3221 |
}
|
| 3222 |
|
|
@@ -3340,7 +3292,7 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 3340 |
onEvaluateBindings={onEvaluateBindings}
|
| 3341 |
onUndo={onUndo}
|
| 3342 |
onRedo={onRedo}
|
| 3343 |
-
onNotice={
|
| 3344 |
// ⭐ W50-T21's HANDOVER. The bar now mirrors the SELECTED cell; its name box still
|
| 3345 |
// works, because both write the same state. `FormulaBar.tsx` was not touched.
|
| 3346 |
onSelect={(sel) => {
|
|
@@ -3404,19 +3356,19 @@ export default function SheetPage({ address: mountAddress, embedded = false, onN
|
|
| 3404 |
{tabReadError
|
| 3405 |
? tabReadError
|
| 3406 |
: notice
|
| 3407 |
-
?
|
| 3408 |
: "No workbook is open. Use Create new in the rail to start one."}
|
| 3409 |
</p>
|
| 3410 |
-
{notice || tabReadError ? <button type="button" className="set-secondary" onClick={() => {
|
| 3411 |
-
if (tabReadError && selectedTab) openTab(selectedTab.id);
|
| 3412 |
-
else (readRetry.current ?? retryOpeningRead)();
|
| 3413 |
-
}}>Retry</button> : null}
|
| 3414 |
</div>
|
| 3415 |
)}
|
| 3416 |
|
| 3417 |
-
{
|
| 3418 |
-
|
| 3419 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3420 |
|
| 3421 |
{/* ⭐⭐ THE TAB BAR (wave-49 R7), AND IT SITS AT THE BOTTOM OF THE WORKBOOK.
|
| 3422 |
R7 says one rail entry is a WORKBOOK WITH TABS, so the tabs belong INSIDE the workbook
|
|
|
|
| 34 |
|
| 35 |
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
|
| 36 |
import type { PointerEvent as ReactPointerEvent, ReactNode } from "react";
|
|
|
|
| 37 |
import "../styles/wave49/sheet.css";
|
| 38 |
import "../styles/wave50/sheet.css";
|
| 39 |
import "../styles/wave55/sheet.css";
|
|
|
|
| 410 |
onNavigate?: (address: { database: string; view?: string }) => void;
|
| 411 |
}
|
| 412 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
export default function SheetPage({ address: mountAddress, embedded = false, onNavigate }: SheetPageProps = {}) {
|
| 414 |
const instanceId = useId();
|
| 415 |
const storagePrefix = embedded ? `embed:sheet:${instanceId}:` : "";
|
|
|
|
| 444 |
} | null>(null);
|
| 445 |
const [busy, setBusy] = useState(false);
|
| 446 |
const [notice, setNotice] = useState("");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 447 |
/** W53-T09: bumped by the ribbon's Import button; `SheetRail` opens its dialog on a change. */
|
| 448 |
const [importRequest, setImportRequest] = useState(0);
|
| 449 |
/**
|
|
|
|
| 981 |
setEditAt("");
|
| 982 |
setDrillAt("");
|
| 983 |
setUnreadableAddressTab("");
|
| 984 |
+
setNotice(ITEM_NOT_AVAILABLE);
|
| 985 |
acceptedAddressRef.current = null;
|
| 986 |
handledSheetHashRef.current = currentSheetHash();
|
| 987 |
return;
|
|
|
|
| 1092 |
if (!absent || tabRouteRef.current === "yes") {
|
| 1093 |
// ⛔ A TAB THAT WILL NOT LOAD IS NOT AN EMPTY TAB. Painting it as one reads exactly
|
| 1094 |
// like the cells having been deleted, so the reason is said instead.
|
| 1095 |
+
if (!quiet && still === "apply") setNotice(got.ok ? "That sheet could not be read, so it is not shown."
|
| 1096 |
+
: got.message);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1097 |
return false;
|
| 1098 |
}
|
| 1099 |
tabRouteRef.current = "no";
|
|
|
|
| 1106 |
const still = stillCurrent === undefined || stillCurrent() ? "apply" : "discard";
|
| 1107 |
if (!fresh.ok) {
|
| 1108 |
if (discardMissingWorkbook(workbookId, fresh)) return false;
|
| 1109 |
+
if (!quiet && still === "apply") setNotice(fresh.message);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1110 |
return false;
|
| 1111 |
}
|
| 1112 |
const live = bookRef.current;
|
|
|
|
| 1253 |
} catch {
|
| 1254 |
if (stillCurrent()) {
|
| 1255 |
setNotice("That sheet could not be read, so it is not shown.");
|
|
|
|
| 1256 |
setUnreadableAddressTab(id);
|
| 1257 |
}
|
| 1258 |
} finally {
|
|
|
|
| 1328 |
if (bookRef.current?.id !== book.id) return;
|
| 1329 |
if (!got.ok) {
|
| 1330 |
if (typeof got.rev_current === "number") applyLocal({ ...bookRef.current, rev: got.rev_current });
|
| 1331 |
+
setNotice(got.message);
|
| 1332 |
return;
|
| 1333 |
}
|
| 1334 |
const live = bookRef.current;
|
|
|
|
| 1391 |
sheets: live.sheets.map((t) => (t.id === tabKey ? { ...t, ...next } : t)),
|
| 1392 |
});
|
| 1393 |
}
|
| 1394 |
+
if (bookRef.current?.id === workbookId) setNotice(reason);
|
| 1395 |
}, [applyLocal]);
|
| 1396 |
|
| 1397 |
/**
|
|
|
|
| 1464 |
markAllLoaded(fresh.value);
|
| 1465 |
applyLocal(fresh.value);
|
| 1466 |
}
|
| 1467 |
+
if (bookRef.current?.id === current.id) setNotice(sent.message);
|
| 1468 |
return "stopped";
|
| 1469 |
}
|
| 1470 |
if (sent.ok) {
|
|
|
|
| 1506 |
const conflicts = sent.value.conflicts ?? [];
|
| 1507 |
if (conflicts.length > 0) {
|
| 1508 |
const changed = conflicts.map((cell) => `${cell.byName || cell.by} changed ${cell.addr}`).join("; ");
|
| 1509 |
+
setNotice(`${changed}; your ${conflicts.length === 1 ? "value was" : "values were"} kept.`);
|
| 1510 |
}
|
| 1511 |
if (refused.length > 0) {
|
| 1512 |
savedCleanRef.current = false;
|
| 1513 |
const head = refused[0];
|
| 1514 |
+
setNotice(refused.length === 1
|
| 1515 |
? (head.sentence || `${head.addr} was not saved.`)
|
| 1516 |
: `${head.sentence || `${head.addr} was not saved.`} `
|
| 1517 |
+ `${refused.length - 1} other cells were refused for the same kind of reason.`);
|
|
|
|
| 1527 |
// ⭐ THE SERVER'S OWN SENTENCE, VERBATIM. C3 says it names the count and the cap, and
|
| 1528 |
// it is the server that knows which cap was hit, cells or bytes. Rewriting it here
|
| 1529 |
// would be this client guessing at a number it never measured.
|
| 1530 |
+
setNotice(sent.message);
|
| 1531 |
return "stopped";
|
| 1532 |
}
|
| 1533 |
if (sent.status === 405 && patchModeRef.current !== "patch") {
|
|
|
|
| 1542 |
return "route_absent";
|
| 1543 |
}
|
| 1544 |
for (const addr of Array.from(addrs)) markDirty(tabKey, addr);
|
| 1545 |
+
setNotice(sent.message);
|
| 1546 |
return "stopped";
|
| 1547 |
}
|
| 1548 |
return "sent";
|
|
|
|
| 1559 |
const fresh = await readWorkbook(workbookId);
|
| 1560 |
if (bookRef.current?.id !== workbookId) return;
|
| 1561 |
if (!fresh.ok) {
|
| 1562 |
+
setNotice("Your edit was not saved. Reload the workbook before editing again.");
|
| 1563 |
return;
|
| 1564 |
}
|
| 1565 |
historyRef.current = emptyHistory();
|
|
|
|
| 1570 |
markAllLoaded(fresh.value);
|
| 1571 |
applyLocal(fresh.value);
|
| 1572 |
workbookConflictRef.current = null;
|
| 1573 |
+
setNotice("This workbook changed. Your edit was not saved and the workbook was reloaded.");
|
| 1574 |
}, [applyLocal, markAllLoaded]);
|
| 1575 |
|
| 1576 |
/**
|
|
|
|
| 1598 |
// be sent and the cells that were would describe a grid the server does not have.
|
| 1599 |
structureDirtyRef.current = true;
|
| 1600 |
savedCleanRef.current = false;
|
| 1601 |
+
setNotice("Some sheets in this workbook could not be read, so nothing was saved. "
|
| 1602 |
+ "Reload the page and try again.");
|
| 1603 |
return;
|
| 1604 |
}
|
|
|
|
| 1623 |
// structure change is still pending and the next drain must still carry it.
|
| 1624 |
structureDirtyRef.current = true;
|
| 1625 |
savedCleanRef.current = false;
|
| 1626 |
+
setNotice(saved.message);
|
| 1627 |
return;
|
| 1628 |
}
|
| 1629 |
if (bookRef.current?.id !== current.id) return;
|
|
|
|
| 1725 |
]);
|
| 1726 |
if (timer !== null) window.clearTimeout(timer);
|
| 1727 |
if (outcome === "timeout") {
|
| 1728 |
+
setNotice("This workbook is still saving. Wait for it to finish before opening another one.");
|
| 1729 |
workbookTransitionRef.current = false;
|
| 1730 |
return false;
|
| 1731 |
}
|
|
|
|
| 1930 |
if (!base) return;
|
| 1931 |
const refusal = structureRefusal(base, target, op);
|
| 1932 |
if (refusal) {
|
| 1933 |
+
setNotice(refusal);
|
| 1934 |
return;
|
| 1935 |
}
|
| 1936 |
const bound = boundCellsInBand(base.sheets.find((t) => t.id === target), op);
|
|
|
|
| 1948 |
const base = await structureBase(pending.workbookId, pending.tabId);
|
| 1949 |
if (!base) return;
|
| 1950 |
const refusal = structureRefusal(base, pending.tabId, pending.op);
|
| 1951 |
+
if (refusal) { setNotice(refusal); return; }
|
| 1952 |
commitSheets(applyStructureWorkbook(base, pending.tabId, pending.op));
|
| 1953 |
}, [bandAt, commitSheets, structureBase]);
|
| 1954 |
|
|
|
|
| 2026 |
if (requested.startsWith("new:")) {
|
| 2027 |
const made = addTab(base);
|
| 2028 |
const refusal = renameTabRefusal({ ...base, sheets: made.sheets }, made.id, requested.slice(4));
|
| 2029 |
+
if (refusal) { setNotice(refusal); return false; }
|
| 2030 |
destination = made.id;
|
| 2031 |
sheets = made.sheets.map(t => t.id === destination ? { ...t, name: requested.slice(4) } : t);
|
| 2032 |
}
|
| 2033 |
if (!sheets.some(t => t.id === destination) || !sheets.some(t => t.id === sourceId)) {
|
| 2034 |
+
setNotice("The chart's source or destination sheet is unavailable."); return false;
|
| 2035 |
}
|
| 2036 |
const saved = { ...chart, sheetId: destination, source: { ...chart.source, ranges: chart.source?.ranges ?? [chart.range], sheetId: sourceId } };
|
| 2037 |
commitSheets(sheets.map(t => ({ ...t,
|
|
|
|
| 2160 |
if (!still || still.id !== workbookId) return;
|
| 2161 |
if (!result.ok) {
|
| 2162 |
if (result.status === 409) await reloadWholeWorkbookAfterConflict(workbookId);
|
| 2163 |
+
else setNotice(result.message);
|
| 2164 |
return;
|
| 2165 |
}
|
| 2166 |
const saved = result.value;
|
|
|
|
| 2183 |
setTabId(added.id);
|
| 2184 |
refreshOpenedWorkbook(workbookId, added.id);
|
| 2185 |
}
|
| 2186 |
+
}).catch(() => setNotice("The tab change could not be saved."))
|
| 2187 |
.finally(() => { tabWritesRef.current.delete(workbookId); });
|
| 2188 |
}, [applyLocal, canEditOutline, flushSave, refreshOpenedWorkbook, reloadWholeWorkbookAfterConflict]);
|
| 2189 |
|
|
|
|
| 2286 |
}, [mutateTab]);
|
| 2287 |
|
| 2288 |
const onRenameTab = useCallback(() => {
|
| 2289 |
+
if (!canEditOutline) { setNotice("This workbook is read only."); return; }
|
| 2290 |
const pending = tabRename;
|
| 2291 |
const base = bookRef.current;
|
| 2292 |
if (!pending || !base) return;
|
| 2293 |
if (nameWritesRef.current.has(base.id)) {
|
| 2294 |
+
setNotice("The name is still saving.");
|
| 2295 |
return;
|
| 2296 |
}
|
| 2297 |
const refusal = renameTabRefusal(base, pending.id, pending.name);
|
| 2298 |
if (refusal) {
|
| 2299 |
+
setNotice(!pending.name.trim() ? "A sheet needs a name."
|
| 2300 |
: pending.name.includes("'") ? "A sheet name cannot contain an apostrophe."
|
| 2301 |
: "Another sheet already has that name.");
|
| 2302 |
return;
|
|
|
|
| 2334 |
applyLocal({ ...still, sheets });
|
| 2335 |
}
|
| 2336 |
if (historyRef.current === renameHistory) historyRef.current = priorHistory;
|
| 2337 |
+
setNotice(message);
|
| 2338 |
};
|
| 2339 |
saveChainRef.current = saveChainRef.current.then(async () => {
|
| 2340 |
const live = bookRef.current;
|
|
|
|
| 2358 |
if (!base) return;
|
| 2359 |
const refusal = removeTabRefusal(base, id);
|
| 2360 |
if (refusal) {
|
| 2361 |
+
setNotice(refusal);
|
| 2362 |
return;
|
| 2363 |
}
|
| 2364 |
const target = base.sheets.find((t) => t.id === id);
|
|
|
|
| 2499 |
// ⚠ A COMPUTE THAT FAILS ON ITS OWN MERITS AFTER A SAVE THAT DID LAND still speaks, and
|
| 2500 |
// this is the case the line was written for: an unreadable database, a scope that cannot
|
| 2501 |
// be compiled, a mirror still syncing. Nothing else has written a sentence about it.
|
| 2502 |
+
setNotice(got.message);
|
| 2503 |
return;
|
| 2504 |
}
|
| 2505 |
applyLocal({ ...live, rev: got.value.rev || live.rev });
|
|
|
|
| 2553 |
if (!got.ok) {
|
| 2554 |
if (typeof got.rev_current === "number") applyLocal({ ...live, rev: got.rev_current });
|
| 2555 |
if (!spoke) {
|
| 2556 |
+
setNotice(got.message);
|
| 2557 |
spoke = true;
|
| 2558 |
}
|
| 2559 |
continue;
|
|
|
|
| 2636 |
const onViewRows = useCallback((addr: string, cell: Cell | null) => {
|
| 2637 |
const affordance = drillAffordance(cell);
|
| 2638 |
if (!affordance.enabled) {
|
| 2639 |
+
setNotice(affordance.reason);
|
| 2640 |
return;
|
| 2641 |
}
|
| 2642 |
setNotice("");
|
|
|
|
| 2661 |
const refreshIndex = useCallback(async () => {
|
| 2662 |
const got = await readIndex();
|
| 2663 |
if (got.ok) setIndex(got.value);
|
|
|
|
|
|
|
| 2664 |
}, []);
|
| 2665 |
|
| 2666 |
/**
|
|
|
|
| 2747 |
addressInitializedRef.current = true;
|
| 2748 |
}
|
| 2749 |
if (!current()) return;
|
| 2750 |
+
if (!got.ok) { setNotice(got.message); return; }
|
| 2751 |
// An explicit id never falls through, including when access filtering omitted its row.
|
| 2752 |
if (targetId === null) {
|
| 2753 |
targetId = (got.value.workbooks.find((row) => row.id === lastWorkbookId)
|
|
|
|
| 2757 |
void readIndex().then((got) => {
|
| 2758 |
if (addressMountedRef.current) {
|
| 2759 |
if (got.ok) setIndex(got.value);
|
| 2760 |
+
else setNotice(got.message);
|
| 2761 |
}
|
| 2762 |
});
|
| 2763 |
addressInitializedRef.current = true;
|
|
|
|
| 2796 |
setEditAt("");
|
| 2797 |
setDrillAt("");
|
| 2798 |
setNotice(got.ok ? "That sheet could not be read, so it is not shown." : got.message);
|
|
|
|
| 2799 |
return;
|
| 2800 |
}
|
| 2801 |
const { openingTab, ...openedWorkbook } = got.value as WorkbookOpening;
|
|
|
|
| 2839 |
})();
|
| 2840 |
}, [sheetHash, opening, barAddr, adoptWorkbook, ensureTabs, flushBeforeWorkbookChange,
|
| 2841 |
lastWorkbookId, prepareWorkbookOpen, refreshIndex, refreshOpenedWorkbook, discardMissingWorkbook,
|
| 2842 |
+
rememberOpenWorkbook, currentSheetHash, navigateSheetAddress, mergeTab]);
|
| 2843 |
|
| 2844 |
// The workbook can open before its index arrives. Enrich only after the open has settled,
|
| 2845 |
// so changing the hash cannot invalidate an in-flight workbook read's address guard.
|
|
|
|
| 2867 |
}
|
| 2868 |
const made = await createWorkbook("Untitled workbook");
|
| 2869 |
if (!made.ok) {
|
| 2870 |
+
setNotice(made.message);
|
| 2871 |
workbookTransitionRef.current = false;
|
| 2872 |
setOpening(false);
|
| 2873 |
return;
|
|
|
|
| 2899 |
}
|
| 2900 |
const source = await readWorkbook(id);
|
| 2901 |
if (!source.ok) {
|
| 2902 |
+
setNotice(source.message);
|
| 2903 |
workbookTransitionRef.current = false;
|
| 2904 |
setOpening(false);
|
| 2905 |
return;
|
| 2906 |
}
|
| 2907 |
const made = await createWorkbook(`${source.value.name} copy`);
|
| 2908 |
if (!made.ok) {
|
| 2909 |
+
setNotice(made.message);
|
| 2910 |
workbookTransitionRef.current = false;
|
| 2911 |
setOpening(false);
|
| 2912 |
return;
|
|
|
|
| 2915 |
name: made.value.name, sheets: source.value.sheets, rev: made.value.rev,
|
| 2916 |
});
|
| 2917 |
if (!filled.ok) {
|
| 2918 |
+
setNotice(filled.message);
|
| 2919 |
workbookTransitionRef.current = false;
|
| 2920 |
setOpening(false);
|
| 2921 |
return;
|
|
|
|
| 2939 |
*/
|
| 2940 |
const renameWorkbook = useCallback(async (id: string, name: string) => {
|
| 2941 |
if (workbookTransitionRef.current) return;
|
| 2942 |
+
if (nameWritesRef.current.has(id)) { setNotice("The name is still saving."); return; }
|
| 2943 |
setNotice("");
|
| 2944 |
name = name.trim();
|
| 2945 |
const open = bookRef.current?.id === id ? bookRef.current : null;
|
| 2946 |
const rows = railIndexRef.current.workbooks.concat(railIndexRef.current.sharedWithMe ?? []);
|
| 2947 |
const row = rows.find((row) => row.id === id);
|
| 2948 |
const before = open?.name ?? row?.name ?? "";
|
| 2949 |
+
if (!name) { setNotice("A workbook needs a name."); return; }
|
| 2950 |
if (name === before) return;
|
| 2951 |
nameWritesRef.current.add(id);
|
| 2952 |
setRailNames((held) => ({ ...held, [id]: { name, rev: Number.POSITIVE_INFINITY } }));
|
|
|
|
| 2961 |
});
|
| 2962 |
const still = bookRef.current;
|
| 2963 |
if (still?.id === id && still.name === name) applyLocal({ ...still, name: before });
|
| 2964 |
+
setNotice(message);
|
| 2965 |
};
|
| 2966 |
const send = async (): Promise<void> => {
|
| 2967 |
let rev = bookRef.current?.id === id ? bookRef.current.rev : row?.rev;
|
|
|
|
| 3006 |
setNotice("");
|
| 3007 |
const gone = await deleteWorkbook(id);
|
| 3008 |
if (!gone.ok && !isMissingItem("workbook", gone)) {
|
| 3009 |
+
setNotice(gone.message);
|
| 3010 |
return;
|
| 3011 |
}
|
| 3012 |
itemDeleted({ kind: "workbook", id });
|
|
|
|
| 3068 |
]);
|
| 3069 |
if (!saved.ok) {
|
| 3070 |
setIndex(previousIndex);
|
| 3071 |
+
setNotice(saved.message);
|
| 3072 |
clearTimeout(timeout);
|
| 3073 |
const rows = await Promise.race([
|
| 3074 |
readIndex(),
|
|
|
|
| 3081 |
}
|
| 3082 |
setIndex(saved.value);
|
| 3083 |
const sentence = repairSentence(saved.value.repairs);
|
| 3084 |
+
if (sentence) setNotice(sentence);
|
| 3085 |
} catch (error) {
|
| 3086 |
setIndex(previousIndex);
|
| 3087 |
+
setNotice(error instanceof Error ? error.message : "Folders could not be saved. Reload folders to retry.");
|
| 3088 |
} finally {
|
| 3089 |
clearTimeout(timeout);
|
| 3090 |
}
|
|
|
|
| 3168 |
|
| 3169 |
if (embedded && !loading && !opening && !book && notice) {
|
| 3170 |
return <div ref={pageRef} className="sheet-page" data-embedded="true">
|
| 3171 |
+
<p className="sheet-notice" role="status">{notice}</p>
|
|
|
|
|
|
|
| 3172 |
</div>;
|
| 3173 |
}
|
| 3174 |
|
|
|
|
| 3292 |
onEvaluateBindings={onEvaluateBindings}
|
| 3293 |
onUndo={onUndo}
|
| 3294 |
onRedo={onRedo}
|
| 3295 |
+
onNotice={setNotice}
|
| 3296 |
// ⭐ W50-T21's HANDOVER. The bar now mirrors the SELECTED cell; its name box still
|
| 3297 |
// works, because both write the same state. `FormulaBar.tsx` was not touched.
|
| 3298 |
onSelect={(sel) => {
|
|
|
|
| 3356 |
{tabReadError
|
| 3357 |
? tabReadError
|
| 3358 |
: notice
|
| 3359 |
+
? "Use Create new in the rail to try again."
|
| 3360 |
: "No workbook is open. Use Create new in the rail to start one."}
|
| 3361 |
</p>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3362 |
</div>
|
| 3363 |
)}
|
| 3364 |
|
| 3365 |
+
{/* `.sheet-notice` is a transient sentence about a refusal, not chrome.
|
| 3366 |
+
Keep messages above the tab strip so they cannot move the ribbon or the grid's
|
| 3367 |
+
origin (owner instructions 6 and 12). */}
|
| 3368 |
+
<div className="sheet-tab-notices">
|
| 3369 |
+
{/* A tab that could not be read says so once, in the grid area, not again here. */}
|
| 3370 |
+
{tabReadError ? null : <>{notice && <p className="sheet-notice">{notice}</p>}</>}
|
| 3371 |
+
</div>
|
| 3372 |
|
| 3373 |
{/* ⭐⭐ THE TAB BAR (wave-49 R7), AND IT SITS AT THE BOTTOM OF THE WORKBOOK.
|
| 3374 |
R7 says one rail entry is a WORKBOOK WITH TABS, so the tabs belong INSIDE the workbook
|