Deploy AIOS web (React glide grid + FastAPI slice)
Browse files- RELEASES.json +1 -1
- VERSION +1 -1
- api/agent_runtime.py +7 -0
- api/assistant_worklists.py +17 -1
- api/external_openapi.py +9 -0
- api/loopy_worklist_tools.py +7 -1
- api/main.py +101 -19
- api/routes_query.py +6 -0
- api/routes_sheet.py +96 -8
- api/whatsapp_door.py +18 -7
- web/public/AIOS_DEPLOY_RECEIPT +1 -1
- web/src/assistant/AssistantPage.tsx +13 -11
- web/src/assistant/AssistantPanel.tsx +4 -5
- web/src/assistant/dockClient.ts +2 -0
- web/src/assistant/streamClient.ts +11 -10
- web/src/query/queryApi.ts +1 -1
RELEASES.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
{
|
| 2 |
-
"current": "
|
| 3 |
"releases": []
|
| 4 |
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"current": "1bcc071da",
|
| 3 |
"releases": []
|
| 4 |
}
|
VERSION
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
|
|
|
|
| 1 |
+
1bcc071da
|
api/agent_runtime.py
CHANGED
|
@@ -375,6 +375,13 @@ def _after_dispatch(session, door, name, args, result, call, turn, effect):
|
|
| 375 |
owned = getattr(files, "owned_metadata", None)
|
| 376 |
metadata = owned(session.runtime, session.uname, file_id) if owned else None
|
| 377 |
artifact_id = metadata.get("artifactId") if metadata else None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
if not artifact_id and effect == "write":
|
| 379 |
artifact_id = _record_artifact(session, door, name, args, result, sources=_turn_sources(turn))
|
| 380 |
if artifact_id:
|
|
|
|
| 375 |
owned = getattr(files, "owned_metadata", None)
|
| 376 |
metadata = owned(session.runtime, session.uname, file_id) if owned else None
|
| 377 |
artifact_id = metadata.get("artifactId") if metadata else None
|
| 378 |
+
if not artifact_id and name in {"build_chase_list", "build_contact_worklist"} and isinstance(result, dict):
|
| 379 |
+
worklists = _optional_module("assistant_worklists")
|
| 380 |
+
artifacts = _optional_module("assistant_artifacts")
|
| 381 |
+
row = artifacts.get(session.runtime, session.uname, result.get("artifactId")) if artifacts else None
|
| 382 |
+
metadata = worklists.owned_artifact(session.runtime, session.uname, row) if worklists else None
|
| 383 |
+
if metadata and metadata["id"] == result.get("worklistId"):
|
| 384 |
+
artifact_id = metadata["artifactId"]
|
| 385 |
if not artifact_id and effect == "write":
|
| 386 |
artifact_id = _record_artifact(session, door, name, args, result, sources=_turn_sources(turn))
|
| 387 |
if artifact_id:
|
api/assistant_worklists.py
CHANGED
|
@@ -160,13 +160,29 @@ def save(session, title, columns, rows, validation, resolve, *, tool_call=None,
|
|
| 160 |
item = {"version": 1, "id": worklist_id, "owner": username, "ownerHash": h,
|
| 161 |
"tenant": session.tenant, "total": len(rows), "size": len(data), "builtAt": built_at}
|
| 162 |
rt.upload_bytes(_path(item), data, message="Save assistant worklist")
|
|
|
|
|
|
|
| 163 |
item["artifactId"] = assistant_artifacts.record(rt, username, {
|
| 164 |
"kind": "report", "ref": worklist_id, "title": title, "door": door,
|
| 165 |
-
"toolCall": call, "createdAt": built_at})
|
| 166 |
rt.update(_key(worklist_id), lambda _raw: copy.deepcopy(item), flush="sync")
|
| 167 |
return {"id": worklist_id, "link": _https(links.artifact_link(item["artifactId"]))}
|
| 168 |
|
| 169 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
def metadata(rt, worklist_id):
|
| 171 |
"""Read tenant metadata without granting the caller ownership."""
|
| 172 |
if not isinstance(worklist_id, str) or not _WORKLIST_ID.fullmatch(worklist_id):
|
|
|
|
| 160 |
item = {"version": 1, "id": worklist_id, "owner": username, "ownerHash": h,
|
| 161 |
"tenant": session.tenant, "total": len(rows), "size": len(data), "builtAt": built_at}
|
| 162 |
rt.upload_bytes(_path(item), data, message="Save assistant worklist")
|
| 163 |
+
import agent_runtime
|
| 164 |
+
sources = agent_runtime.producing_turn_sources(session)
|
| 165 |
item["artifactId"] = assistant_artifacts.record(rt, username, {
|
| 166 |
"kind": "report", "ref": worklist_id, "title": title, "door": door,
|
| 167 |
+
"toolCall": call, "createdAt": built_at, "frozen_at": built_at, "sources": sources})
|
| 168 |
rt.update(_key(worklist_id), lambda _raw: copy.deepcopy(item), flush="sync")
|
| 169 |
return {"id": worklist_id, "link": _https(links.artifact_link(item["artifactId"]))}
|
| 170 |
|
| 171 |
|
| 172 |
+
def owned_artifact(rt, username, row):
|
| 173 |
+
"""Validate an active report against its immutable owner-bound worklist metadata."""
|
| 174 |
+
if (not isinstance(row, dict) or row.get("kind") != "report" or row.get("status") != "active"
|
| 175 |
+
or (row.get("toolCall") or {}).get("name") not in {"build_chase_list", "build_contact_worklist"}):
|
| 176 |
+
return None
|
| 177 |
+
item = metadata(rt, row.get("ref"))
|
| 178 |
+
if (item is None or item["owner"] != username
|
| 179 |
+
or item["ownerHash"] != assistant_log._hash(rt, username)
|
| 180 |
+
or item["artifactId"] != row.get("id") or item["builtAt"] != row.get("createdAt")
|
| 181 |
+
or row.get("frozen_at", item["builtAt"]) != item["builtAt"]):
|
| 182 |
+
return None
|
| 183 |
+
return item
|
| 184 |
+
|
| 185 |
+
|
| 186 |
def metadata(rt, worklist_id):
|
| 187 |
"""Read tenant metadata without granting the caller ownership."""
|
| 188 |
if not isinstance(worklist_id, str) or not _WORKLIST_ID.fullmatch(worklist_id):
|
api/external_openapi.py
CHANGED
|
@@ -3,6 +3,7 @@
|
|
| 3 |
import hashlib
|
| 4 |
import json
|
| 5 |
import re
|
|
|
|
| 6 |
|
| 7 |
|
| 8 |
# Checkbox, structured and linked cells use the grid's string wire representation.
|
|
@@ -155,6 +156,14 @@ def _operation(operation_id, response, *, query=False, database=False):
|
|
| 155 |
def build(session, base_url, *, cookie_auth=False):
|
| 156 |
"""Describe permitted reads without copying tenant metadata or credential claims."""
|
| 157 |
import routes_external
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
auth_name = "BearerAuth"
|
| 160 |
auth_scheme = {"type": "http", "scheme": "bearer"}
|
|
|
|
| 3 |
import hashlib
|
| 4 |
import json
|
| 5 |
import re
|
| 6 |
+
from copy import copy
|
| 7 |
|
| 8 |
|
| 9 |
# Checkbox, structured and linked cells use the grid's string wire representation.
|
|
|
|
| 156 |
def build(session, base_url, *, cookie_auth=False):
|
| 157 |
"""Describe permitted reads without copying tenant metadata or credential claims."""
|
| 158 |
import routes_external
|
| 159 |
+
from core import user_tables
|
| 160 |
+
|
| 161 |
+
# One description owns one rows-free definition/grant snapshot. The real scope
|
| 162 |
+
# resolver still decides every database and field; lending its reads avoids
|
| 163 |
+
# copying the entire registry again for each database. Never retain this handle
|
| 164 |
+
# on the authenticated session: the next build must see revocations and edits.
|
| 165 |
+
session = copy(session)
|
| 166 |
+
session.runtime = user_tables.lend(session.runtime)
|
| 167 |
|
| 168 |
auth_name = "BearerAuth"
|
| 169 |
auth_scheme = {"type": "http", "scheme": "bearer"}
|
api/loopy_worklist_tools.py
CHANGED
|
@@ -22,7 +22,13 @@ def _save(session, original_args, name, build):
|
|
| 22 |
"No contacts match that filter."}
|
| 23 |
saved = assistant_worklists.save(session, **worklist, resolve=resolve, door=door,
|
| 24 |
tool_call={"name": name, "args": original_args})
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
"title": worklist["title"], "total": len(worklist["rows"])}
|
| 27 |
|
| 28 |
|
|
|
|
| 22 |
"No contacts match that filter."}
|
| 23 |
saved = assistant_worklists.save(session, **worklist, resolve=resolve, door=door,
|
| 24 |
tool_call={"name": name, "args": original_args})
|
| 25 |
+
import assistant_artifacts
|
| 26 |
+
item = assistant_worklists.metadata(session.runtime, saved["id"])
|
| 27 |
+
artifact = assistant_artifacts.get(session.runtime, session.uname, item["artifactId"])
|
| 28 |
+
if assistant_worklists.owned_artifact(session.runtime, session.uname, artifact) is None:
|
| 29 |
+
raise ValueError("This worklist could not be read.")
|
| 30 |
+
return {"ok": True, "worklistId": saved["id"], "artifactId": item["artifactId"],
|
| 31 |
+
"link": _secure_link(saved["link"]), "sources": artifact["sources"],
|
| 32 |
"title": worklist["title"], "total": len(worklist["rows"])}
|
| 33 |
|
| 34 |
|
api/main.py
CHANGED
|
@@ -706,13 +706,17 @@ def _seed_and_sync_store():
|
|
| 706 |
t0 = _t.time()
|
| 707 |
try:
|
| 708 |
from harness import datastore as _ds
|
|
|
|
|
|
|
|
|
|
| 709 |
if _ds.ensure_seed():
|
| 710 |
print(f"[aios-api] datastore seeded in {_t.time() - t0:.1f}s")
|
|
|
|
| 711 |
# DEDICATED Odoo connection for this thread (the W6 postmortem rule): the sync's
|
| 712 |
# search_reads must never interleave on the shared client's xmlrpc transport.
|
| 713 |
import core.odoo as _odoo
|
| 714 |
try:
|
| 715 |
-
_odoo._tlocal.client = _odoo.OdooClient
|
| 716 |
except Exception:
|
| 717 |
pass
|
| 718 |
selected_entities = _configured_mirror_entities()
|
|
@@ -857,6 +861,11 @@ def _pull_amazon(why, vendor=True):
|
|
| 857 |
# projection on that same tenant; never fall back to an operator's environment credential.
|
| 858 |
tenant_key = "royal-imports"
|
| 859 |
rt = _runtime.get_runtime(tenant_key)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 860 |
if not _amazon.credential(tenant_key, rt=rt):
|
| 861 |
print(f"[aios-api] amazon sync skipped ({why}): no stored amazon_sp credential "
|
| 862 |
"for royal-imports; the connector is idle, not broken")
|
|
@@ -921,20 +930,85 @@ def _restore_amazon_mirror_once(why):
|
|
| 921 |
import routes_odoo_tables as _rot
|
| 922 |
tenant_key = "royal-imports"
|
| 923 |
rt = _runtime.get_runtime(tenant_key)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 924 |
if not _amazon.credential(tenant_key, rt=rt):
|
| 925 |
return False
|
| 926 |
started = _t.time()
|
| 927 |
result = _amazon.restore_mirror(tenant_key, rt)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 928 |
_rot.invalidate_sources()
|
| 929 |
_rot._sources()
|
| 930 |
print(f"[aios-api] amazon mirror {result.get('state')} ({why}) in "
|
| 931 |
f"{_t.time() - started:.0f}s, before the Odoo catch-up")
|
| 932 |
return True
|
| 933 |
except Exception as exc: # noqa: BLE001
|
|
|
|
| 934 |
print(f"[aios-api] amazon mirror restore FAILED ({why}): {type(exc).__name__}: {exc}")
|
| 935 |
return False
|
| 936 |
|
| 937 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 938 |
class _SyncNowRefused(Exception):
|
| 939 |
"""An application-authored, credential-free sentence for a Sync now receipt."""
|
| 940 |
|
|
@@ -1028,7 +1102,7 @@ def _sync_now_detail(provider, tenant, *, ok, detail="", cause=None):
|
|
| 1028 |
return sentence + suffix
|
| 1029 |
|
| 1030 |
|
| 1031 |
-
def _run_sync_requests(outcome=None):
|
| 1032 |
"""Drain Sync now intents on the resident resync thread, the mirror's single writer.
|
| 1033 |
|
| 1034 |
D-29 / intake F6: HTTP handlers only queue intents. Provider calls stay here, before the
|
|
@@ -1038,7 +1112,16 @@ def _run_sync_requests(outcome=None):
|
|
| 1038 |
"""
|
| 1039 |
from core import connector_sync
|
| 1040 |
odoo_requested = False
|
| 1041 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1042 |
provider, tenant = receipt["provider"], receipt["tenant"]
|
| 1043 |
ok, detail = False, ""
|
| 1044 |
first_load_progress, continuing = None, False
|
|
@@ -1048,9 +1131,8 @@ def _run_sync_requests(outcome=None):
|
|
| 1048 |
rt = runtime.get_runtime(tenant)
|
| 1049 |
if rt.key != tenant:
|
| 1050 |
raise _SyncNowRefused("The sync runtime does not match the requesting tenant.")
|
| 1051 |
-
#
|
| 1052 |
-
|
| 1053 |
-
if provider in ("odoo", "meta_ads") and (
|
| 1054 |
rt.datastore_path.resolve() != datastore.DB_PATH.resolve() or
|
| 1055 |
datastore.path_for(tenant).resolve() != datastore.DB_PATH.resolve()):
|
| 1056 |
raise _SyncNowRefused(
|
|
@@ -1086,7 +1168,8 @@ def _run_sync_requests(outcome=None):
|
|
| 1086 |
try:
|
| 1087 |
# Raw mirror pulls use the resolved tenant credential and a dedicated
|
| 1088 |
# transport. Do not borrow a request's cached XML-RPC client.
|
| 1089 |
-
odoo._tlocal.client =
|
|
|
|
| 1090 |
odoo._tlocal.tenant_ctx = None
|
| 1091 |
from connector_onboarding import selected_mirror_entities
|
| 1092 |
selected_entities = selected_mirror_entities(rt)
|
|
@@ -1159,6 +1242,8 @@ def _run_sync_requests(outcome=None):
|
|
| 1159 |
connector_sync.finish_sync_request(provider, tenant, ok=ok, detail=detail)
|
| 1160 |
if outcome is not None:
|
| 1161 |
outcome[provider] = "continuing" if (continuing and ok) else ("done" if ok else "failed")
|
|
|
|
|
|
|
| 1162 |
if continuing and ok and floor_wait:
|
| 1163 |
# ⛔ HOTFIX 2026-09-29: NOT every 30 seconds. A pass that landed nothing can only defer
|
| 1164 |
# again until Amazon's next report floor opens, and each of those passes republished
|
|
@@ -1960,7 +2045,7 @@ def _resync_mirror_pass(manual, passes, entities=None):
|
|
| 1960 |
# DEDICATED Odoo connection for this thread (the W6 postmortem rule): the sync's
|
| 1961 |
# search_reads must never interleave on the shared client's xmlrpc transport.
|
| 1962 |
try:
|
| 1963 |
-
_odoo._tlocal.client = _odoo.OdooClient
|
| 1964 |
except Exception:
|
| 1965 |
pass
|
| 1966 |
# ⚠ A PLAIN BRANCH, NOT AN EARLY EXIT AND NOT AN EXCEPTION. A `raise` here would be
|
|
@@ -2157,6 +2242,13 @@ def _store_resync_loop():
|
|
| 2157 |
return
|
| 2158 |
import time as _t
|
| 2159 |
from core import connector_sync
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2160 |
passes = 0
|
| 2161 |
# ⛔⛔ HOTFIX 2026-09-29 — A RESTART NO LONGER FORGETS. These lived in memory only, so every
|
| 2162 |
# deploy began with `no-fingerprint` and rebuilt every Odoo table whole (live 2026-09-29
|
|
@@ -2263,16 +2355,6 @@ def _store_resync_loop():
|
|
| 2263 |
# the disposable DuckDB mirror up (Odoo reads, no store; the dashboards read it, W58) and
|
| 2264 |
# restores Amazon's saved mirror. The store-touching half (Meta and Amazon vendor pulls,
|
| 2265 |
# the relational rebuild) waits for the pass that is actually due.
|
| 2266 |
-
if not passes:
|
| 2267 |
-
try:
|
| 2268 |
-
import amazon_relational as _ar
|
| 2269 |
-
_ar.RESTORE_PENDING["since"] = _t.time()
|
| 2270 |
-
except Exception: # noqa: BLE001
|
| 2271 |
-
pass
|
| 2272 |
-
_await_boot_seed()
|
| 2273 |
-
# Amazon's saved mirror first: minutes of store reads, where the Odoo catch-up below
|
| 2274 |
-
# runs about an hour after a restart and Amazon answered nothing until it ended.
|
| 2275 |
-
_restore_amazon_mirror("boot")
|
| 2276 |
_boot_catch_up = ((not passes or catch_up_retries)
|
| 2277 |
and _resync_boot_recent(last_good_pass_at, _t.time(), _every))
|
| 2278 |
# ⛔⛔ HOTFIX 2026-09-24 — A DESK WAKE IS NOT A SCHEDULED PASS.
|
|
@@ -2509,7 +2591,7 @@ def _prewarm():
|
|
| 2509 |
# The Odoo seed/sync can run for minutes and is separate from the finite cache warm below.
|
| 2510 |
# Keep it opt-in: Live Pg serves its seeded analytical mirror at boot and lets explicit
|
| 2511 |
# workers perform real sync work, so a routine restart can still scale Neon back to zero.
|
| 2512 |
-
if os.environ.get("AIOS_BOOT_SYNC") == "1":
|
| 2513 |
import threading as _th
|
| 2514 |
_th.Thread(target=_seed_and_sync_store, daemon=True, name="store-seed-sync").start()
|
| 2515 |
try:
|
|
|
|
| 706 |
t0 = _t.time()
|
| 707 |
try:
|
| 708 |
from harness import datastore as _ds
|
| 709 |
+
_await_boot_seed()
|
| 710 |
+
while globals().get("_SEED_THREAD") is not None and _SEED_THREAD.is_alive():
|
| 711 |
+
_await_boot_seed()
|
| 712 |
if _ds.ensure_seed():
|
| 713 |
print(f"[aios-api] datastore seeded in {_t.time() - t0:.1f}s")
|
| 714 |
+
_restore_amazon_mirror("boot")
|
| 715 |
# DEDICATED Odoo connection for this thread (the W6 postmortem rule): the sync's
|
| 716 |
# search_reads must never interleave on the shared client's xmlrpc transport.
|
| 717 |
import core.odoo as _odoo
|
| 718 |
try:
|
| 719 |
+
_odoo._tlocal.client = _DeskAwareOdooClient(_odoo.OdooClient)
|
| 720 |
except Exception:
|
| 721 |
pass
|
| 722 |
selected_entities = _configured_mirror_entities()
|
|
|
|
| 861 |
# projection on that same tenant; never fall back to an operator's environment credential.
|
| 862 |
tenant_key = "royal-imports"
|
| 863 |
rt = _runtime.get_runtime(tenant_key)
|
| 864 |
+
from harness import datastore as _ds
|
| 865 |
+
if (rt.key != tenant_key or
|
| 866 |
+
rt.datastore_path.resolve() != _ds.DB_PATH.resolve() or
|
| 867 |
+
_ds.path_for(tenant_key).resolve() != _ds.DB_PATH.resolve()):
|
| 868 |
+
raise RuntimeError("Amazon sync requires the requesting tenant's resident mirror.")
|
| 869 |
if not _amazon.credential(tenant_key, rt=rt):
|
| 870 |
print(f"[aios-api] amazon sync skipped ({why}): no stored amazon_sp credential "
|
| 871 |
"for royal-imports; the connector is idle, not broken")
|
|
|
|
| 930 |
import routes_odoo_tables as _rot
|
| 931 |
tenant_key = "royal-imports"
|
| 932 |
rt = _runtime.get_runtime(tenant_key)
|
| 933 |
+
from harness import datastore as _ds
|
| 934 |
+
if (rt.key != tenant_key or
|
| 935 |
+
rt.datastore_path.resolve() != _ds.DB_PATH.resolve() or
|
| 936 |
+
_ds.path_for(tenant_key).resolve() != _ds.DB_PATH.resolve()):
|
| 937 |
+
raise RuntimeError("Amazon restore requires the requesting tenant's resident mirror.")
|
| 938 |
if not _amazon.credential(tenant_key, rt=rt):
|
| 939 |
return False
|
| 940 |
started = _t.time()
|
| 941 |
result = _amazon.restore_mirror(tenant_key, rt)
|
| 942 |
+
if result.get("state") == "refused":
|
| 943 |
+
raise RuntimeError("; ".join(result.get("problems") or ["Amazon mirror restore refused."]))
|
| 944 |
+
# Publish measured definitions before any Odoo read can block the resident writer.
|
| 945 |
+
if result.get("state") != "absent":
|
| 946 |
+
state = _rebuild_amazon_relational(why, rt)
|
| 947 |
+
if state.get("changed") and not state.get("applied") and not state.get("known"):
|
| 948 |
+
raise RuntimeError("Amazon mirror restored but relational rebuild failed.")
|
| 949 |
+
if result.get("problems"):
|
| 950 |
+
RESYNC_STATE["amazonRestoreError"] = {
|
| 951 |
+
"type": "PartialRestore", "message": "; ".join(result["problems"])}
|
| 952 |
+
else:
|
| 953 |
+
RESYNC_STATE.pop("amazonRestoreError", None)
|
| 954 |
_rot.invalidate_sources()
|
| 955 |
_rot._sources()
|
| 956 |
print(f"[aios-api] amazon mirror {result.get('state')} ({why}) in "
|
| 957 |
f"{_t.time() - started:.0f}s, before the Odoo catch-up")
|
| 958 |
return True
|
| 959 |
except Exception as exc: # noqa: BLE001
|
| 960 |
+
RESYNC_STATE["amazonRestoreError"] = {"type": type(exc).__name__, "message": str(exc)}
|
| 961 |
print(f"[aios-api] amazon mirror restore FAILED ({why}): {type(exc).__name__}: {exc}")
|
| 962 |
return False
|
| 963 |
|
| 964 |
|
| 965 |
+
class _DeskAwareOdooClient:
|
| 966 |
+
"""Leave mirror writes on the resident thread while an Odoo transport read waits."""
|
| 967 |
+
|
| 968 |
+
READ_ONLY = True
|
| 969 |
+
|
| 970 |
+
def __init__(self, factory):
|
| 971 |
+
self._factory = factory
|
| 972 |
+
self._client = None
|
| 973 |
+
self._next_desk = 0.0
|
| 974 |
+
|
| 975 |
+
def __getattr__(self, name):
|
| 976 |
+
if name not in {"search_read", "search_count", "read_group", "fields_get"}:
|
| 977 |
+
raise AttributeError(name)
|
| 978 |
+
|
| 979 |
+
def read(*args, **kwargs):
|
| 980 |
+
import threading
|
| 981 |
+
import time
|
| 982 |
+
result, finished = {}, threading.Event()
|
| 983 |
+
|
| 984 |
+
def serve_desk():
|
| 985 |
+
if time.monotonic() >= self._next_desk:
|
| 986 |
+
outcome = {}
|
| 987 |
+
_run_sync_requests(outcome, during_odoo=True)
|
| 988 |
+
self._next_desk = time.monotonic() + (30 if "continuing" in outcome.values() else 0.25)
|
| 989 |
+
|
| 990 |
+
def transport():
|
| 991 |
+
try:
|
| 992 |
+
if self._client is None:
|
| 993 |
+
self._client = self._factory()
|
| 994 |
+
result["value"] = getattr(self._client, name)(*args, **kwargs)
|
| 995 |
+
except BaseException as exc:
|
| 996 |
+
result["error"] = exc
|
| 997 |
+
finally:
|
| 998 |
+
finished.set()
|
| 999 |
+
|
| 1000 |
+
serve_desk()
|
| 1001 |
+
threading.Thread(target=transport, daemon=True, name="odoo-resident-read").start()
|
| 1002 |
+
while not finished.wait(0.25):
|
| 1003 |
+
serve_desk()
|
| 1004 |
+
if "error" in result:
|
| 1005 |
+
raise result["error"]
|
| 1006 |
+
serve_desk()
|
| 1007 |
+
return result["value"]
|
| 1008 |
+
|
| 1009 |
+
return read
|
| 1010 |
+
|
| 1011 |
+
|
| 1012 |
class _SyncNowRefused(Exception):
|
| 1013 |
"""An application-authored, credential-free sentence for a Sync now receipt."""
|
| 1014 |
|
|
|
|
| 1102 |
return sentence + suffix
|
| 1103 |
|
| 1104 |
|
| 1105 |
+
def _run_sync_requests(outcome=None, *, during_odoo=False):
|
| 1106 |
"""Drain Sync now intents on the resident resync thread, the mirror's single writer.
|
| 1107 |
|
| 1108 |
D-29 / intake F6: HTTP handlers only queue intents. Provider calls stay here, before the
|
|
|
|
| 1112 |
"""
|
| 1113 |
from core import connector_sync
|
| 1114 |
odoo_requested = False
|
| 1115 |
+
pending = globals().setdefault("_SYNC_CLAIMED", [])
|
| 1116 |
+
pending.extend(connector_sync.take_sync_requests())
|
| 1117 |
+
while True:
|
| 1118 |
+
receipt = next((row for row in pending
|
| 1119 |
+
if not during_odoo or row["provider"] != "odoo"), None)
|
| 1120 |
+
if receipt is None:
|
| 1121 |
+
if pending:
|
| 1122 |
+
connector_sync.sync_wake_event().set()
|
| 1123 |
+
break
|
| 1124 |
+
pending.remove(receipt)
|
| 1125 |
provider, tenant = receipt["provider"], receipt["tenant"]
|
| 1126 |
ok, detail = False, ""
|
| 1127 |
first_load_progress, continuing = None, False
|
|
|
|
| 1131 |
rt = runtime.get_runtime(tenant)
|
| 1132 |
if rt.key != tenant:
|
| 1133 |
raise _SyncNowRefused("The sync runtime does not match the requesting tenant.")
|
| 1134 |
+
# Every resident loader uses the process-global instance. Never repoint it under readers.
|
| 1135 |
+
if provider in ("odoo", "meta_ads", "amazon_sp") and (
|
|
|
|
| 1136 |
rt.datastore_path.resolve() != datastore.DB_PATH.resolve() or
|
| 1137 |
datastore.path_for(tenant).resolve() != datastore.DB_PATH.resolve()):
|
| 1138 |
raise _SyncNowRefused(
|
|
|
|
| 1168 |
try:
|
| 1169 |
# Raw mirror pulls use the resolved tenant credential and a dedicated
|
| 1170 |
# transport. Do not borrow a request's cached XML-RPC client.
|
| 1171 |
+
odoo._tlocal.client = _DeskAwareOdooClient(
|
| 1172 |
+
lambda: odoo.OdooClient(creds=source._creds))
|
| 1173 |
odoo._tlocal.tenant_ctx = None
|
| 1174 |
from connector_onboarding import selected_mirror_entities
|
| 1175 |
selected_entities = selected_mirror_entities(rt)
|
|
|
|
| 1242 |
connector_sync.finish_sync_request(provider, tenant, ok=ok, detail=detail)
|
| 1243 |
if outcome is not None:
|
| 1244 |
outcome[provider] = "continuing" if (continuing and ok) else ("done" if ok else "failed")
|
| 1245 |
+
if during_odoo and ok and not continuing:
|
| 1246 |
+
_project_desk({provider: "done"}, tenant)
|
| 1247 |
if continuing and ok and floor_wait:
|
| 1248 |
# ⛔ HOTFIX 2026-09-29: NOT every 30 seconds. A pass that landed nothing can only defer
|
| 1249 |
# again until Amazon's next report floor opens, and each of those passes republished
|
|
|
|
| 2045 |
# DEDICATED Odoo connection for this thread (the W6 postmortem rule): the sync's
|
| 2046 |
# search_reads must never interleave on the shared client's xmlrpc transport.
|
| 2047 |
try:
|
| 2048 |
+
_odoo._tlocal.client = _DeskAwareOdooClient(_odoo.OdooClient)
|
| 2049 |
except Exception:
|
| 2050 |
pass
|
| 2051 |
# ⚠ A PLAIN BRANCH, NOT AN EARLY EXIT AND NOT AN EXCEPTION. A `raise` here would be
|
|
|
|
| 2242 |
return
|
| 2243 |
import time as _t
|
| 2244 |
from core import connector_sync
|
| 2245 |
+
# Restore/rebuild precedes cadence/source hydration as well as the Odoo backfill.
|
| 2246 |
+
import amazon_relational as _ar_boot
|
| 2247 |
+
_ar_boot.RESTORE_PENDING["since"] = _t.time()
|
| 2248 |
+
_await_boot_seed()
|
| 2249 |
+
while globals().get("_SEED_THREAD") is not None and _SEED_THREAD.is_alive():
|
| 2250 |
+
_await_boot_seed()
|
| 2251 |
+
_restore_amazon_mirror("boot")
|
| 2252 |
passes = 0
|
| 2253 |
# ⛔⛔ HOTFIX 2026-09-29 — A RESTART NO LONGER FORGETS. These lived in memory only, so every
|
| 2254 |
# deploy began with `no-fingerprint` and rebuilt every Odoo table whole (live 2026-09-29
|
|
|
|
| 2355 |
# the disposable DuckDB mirror up (Odoo reads, no store; the dashboards read it, W58) and
|
| 2356 |
# restores Amazon's saved mirror. The store-touching half (Meta and Amazon vendor pulls,
|
| 2357 |
# the relational rebuild) waits for the pass that is actually due.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2358 |
_boot_catch_up = ((not passes or catch_up_retries)
|
| 2359 |
and _resync_boot_recent(last_good_pass_at, _t.time(), _every))
|
| 2360 |
# ⛔⛔ HOTFIX 2026-09-24 — A DESK WAKE IS NOT A SCHEDULED PASS.
|
|
|
|
| 2591 |
# The Odoo seed/sync can run for minutes and is separate from the finite cache warm below.
|
| 2592 |
# Keep it opt-in: Live Pg serves its seeded analytical mirror at boot and lets explicit
|
| 2593 |
# workers perform real sync work, so a routine restart can still scale Neon back to zero.
|
| 2594 |
+
if os.environ.get("AIOS_BOOT_SYNC") == "1" and os.environ.get("AIOS_STORE_RESYNC") != "1":
|
| 2595 |
import threading as _th
|
| 2596 |
_th.Thread(target=_seed_and_sync_store, daemon=True, name="store-seed-sync").start()
|
| 2597 |
try:
|
api/routes_query.py
CHANGED
|
@@ -3208,6 +3208,12 @@ def governed_query(body: dict = Body(default=None),
|
|
| 3208 |
raise err(400, "bad_request", "a prompt is required")
|
| 3209 |
if len(question) > MAX_QUESTION:
|
| 3210 |
raise err(400, "question_too_long", f"a prompt must be under {MAX_QUESTION} characters")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3211 |
routed = _route(session, question) if not database else {
|
| 3212 |
"database": database, "label": "", "reason": "", "auto": False, "alternatives": []}
|
| 3213 |
database = routed["database"]
|
|
|
|
| 3208 |
raise err(400, "bad_request", "a prompt is required")
|
| 3209 |
if len(question) > MAX_QUESTION:
|
| 3210 |
raise err(400, "question_too_long", f"a prompt must be under {MAX_QUESTION} characters")
|
| 3211 |
+
if not database:
|
| 3212 |
+
import agent_tools
|
| 3213 |
+
if agent_tools.admitted_tools(question):
|
| 3214 |
+
# Preflight executes nothing. Chat derives admission again from its own question.
|
| 3215 |
+
return {"status": "continue_chat", "routedTo": {
|
| 3216 |
+
"database": "", "label": "", "reason": "", "auto": False, "alternatives": []}}
|
| 3217 |
routed = _route(session, question) if not database else {
|
| 3218 |
"database": database, "label": "", "reason": "", "auto": False, "alternatives": []}
|
| 3219 |
database = routed["database"]
|
api/routes_sheet.py
CHANGED
|
@@ -160,6 +160,8 @@ def _mirror(session: Session):
|
|
| 160 |
if fields is None and not is_registry_grid and not is_shipments:
|
| 161 |
connector_defn = _connector_definition(session, table_key)
|
| 162 |
if connector_defn is None:
|
|
|
|
|
|
|
| 163 |
raise err(404, "not_connected", f"{table_key} is not a connected Odoo database.")
|
| 164 |
fields = list(connector_defn.get("fields") or [])
|
| 165 |
if not fields:
|
|
@@ -291,12 +293,53 @@ def _mirror(session: Session):
|
|
| 291 |
return _drill_for
|
| 292 |
|
| 293 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
def _connector_definition(session: Session, table_key: str):
|
| 295 |
"""The stored stub of a read-through CONNECTOR grid (S66-T43), or None when it is not one.
|
| 296 |
|
| 297 |
Only a key the read-through registry serves qualifies (`routes_odoo_tables._sources()`), or an
|
| 298 |
-
Amazon table the connector declares (`amazon_relational.SOURCE`, stored or read-through)
|
| 299 |
-
|
| 300 |
`_mirror` memoises: `resolve_bindings` asks once per CELL and the Session dies with the request.
|
| 301 |
⚠ `scope_applied=True` because every Sheet read compiles the row wall into its own SQL.
|
| 302 |
"""
|
|
@@ -733,13 +776,17 @@ def distinct_values(database: str, field: str = Query(...),
|
|
| 733 |
import odoo_relational as rel
|
| 734 |
import routes_odoo_tables as rot
|
| 735 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 736 |
known = set(rel._REGISTRY_GRID_FIELDS) | {key for _bucket, key, _label, _fields in rel.TABLES}
|
| 737 |
known.add(rel.SHIPMENTS_KEY)
|
| 738 |
known.update(rot._sources())
|
| 739 |
if database.startswith("ut_amzn_"):
|
| 740 |
import amazon_relational
|
| 741 |
known.update(amazon_relational.SOURCE)
|
| 742 |
-
if database not in known:
|
| 743 |
raise err(404, "not_connected", f"{database} is not a connected database.")
|
| 744 |
database = _require_database(session, database)
|
| 745 |
_refuse_unapplied_audience(session, database)
|
|
@@ -748,6 +795,8 @@ def distinct_values(database: str, field: str = Query(...),
|
|
| 748 |
wall_nodes, wall_conj = _fe_parts(wall)
|
| 749 |
needed = sheet_mod.filter_columns_named(wall_nodes) | {field}
|
| 750 |
cur, spec, columns = _mirror(session)(database, needed=needed)
|
|
|
|
|
|
|
| 751 |
fields = spec.get("fields") or []
|
| 752 |
if field in perm_scope.hidden_keys(session.user, database, fields, st=session.runtime):
|
| 753 |
raise err(403, "field_unreadable", f"You cannot read field {field} in {database}.")
|
|
@@ -3257,7 +3306,8 @@ def _sheet_request_scope(session):
|
|
| 3257 |
previous = getattr(session, "_sheet_read_memo", None)
|
| 3258 |
previous_assemblies = getattr(session, "_sheet_assemblies", None)
|
| 3259 |
previous_context = getattr(session, "_sheet_scope_context", None)
|
| 3260 |
-
|
|
|
|
| 3261 |
"stats": {"engines": 0, "resolves": 0, "input_hits": 0}}
|
| 3262 |
try:
|
| 3263 |
session._sheet_read_memo = memo
|
|
@@ -3269,9 +3319,12 @@ def _sheet_request_scope(session):
|
|
| 3269 |
try:
|
| 3270 |
yield memo
|
| 3271 |
finally:
|
| 3272 |
-
|
| 3273 |
-
|
| 3274 |
-
|
|
|
|
|
|
|
|
|
|
| 3275 |
|
| 3276 |
|
| 3277 |
def _request_scoped(route):
|
|
@@ -3286,6 +3339,8 @@ def _request_scoped(route):
|
|
| 3286 |
session = signature.bind_partial(*args, **kwargs).arguments.get("session")
|
| 3287 |
if session is None:
|
| 3288 |
return route(*args, **kwargs)
|
|
|
|
|
|
|
| 3289 |
with _sheet_request_scope(session):
|
| 3290 |
return route(*args, **kwargs)
|
| 3291 |
return scoped
|
|
@@ -3912,6 +3967,7 @@ def _binding_filter_nodes(session, database, binding, *, memo=None):
|
|
| 3912 |
return _rewrite_related_filters(session, database, nodes), conj
|
| 3913 |
|
| 3914 |
|
|
|
|
| 3915 |
def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=None,
|
| 3916 |
book=None, tab=None, ending_seen=(), _pivot=None):
|
| 3917 |
"""Evaluate ONE C2 binding and return `{value, limits, sql_columns}`.
|
|
@@ -3975,6 +4031,15 @@ def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=Non
|
|
| 3975 |
related_bags = _related_leaf_bags(session, database, scope_nodes, needed)
|
| 3976 |
cur, spec, cols = _mirror(session)(database, metric_window=window, needed=needed)
|
| 3977 |
cols = dict(cols)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3978 |
# Authored filters need field access; trusted defaults and permanent walls keep the full map.
|
| 3979 |
hidden = perm_scope.hidden_keys(session.user, database, spec.get("fields") or [], st=session.runtime)
|
| 3980 |
unreadable = sorted(sheet_mod.filter_columns_named(scope_nodes) & hidden)
|
|
@@ -4054,6 +4119,8 @@ def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=Non
|
|
| 4054 |
"live connection, so the number is not being shown rather than shown wider "
|
| 4055 |
"than you asked for. Edit the cell's scope and try again.")
|
| 4056 |
|
|
|
|
|
|
|
| 4057 |
if _pivot is not None:
|
| 4058 |
pivot_limits = list(limits) + [item for field, item in (spec.get("unbounded") or {}).items()
|
| 4059 |
if field in needed]
|
|
@@ -4072,7 +4139,7 @@ def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=Non
|
|
| 4072 |
depends = set(sheet_mod.filter_columns_named(scope_nodes))
|
| 4073 |
if binding["aggregate"].get("field"):
|
| 4074 |
depends.add(str(binding["aggregate"]["field"]))
|
| 4075 |
-
limits = (list(limits)
|
| 4076 |
+ [row for key, row in (spec.get("unbounded") or {}).items() if key in depends]
|
| 4077 |
+ sheet_mod.period_limits(binding.get("period"), binding["aggregate"], bound_field,
|
| 4078 |
spec.get("bounded") or (), depends))
|
|
@@ -4357,6 +4424,7 @@ def _compute_cell_scoped(workbook_id: str, addr: str, body, session: Session):
|
|
| 4357 |
|
| 4358 |
|
| 4359 |
@router.post("/sheets/{workbook_id}/view-rows")
|
|
|
|
| 4360 |
def view_rows(workbook_id: str, body: object = Body(default=None),
|
| 4361 |
session: Session = Depends(require_session)):
|
| 4362 |
"""W62 C2 / R29: read the live rows of a placed view under this caller's walls."""
|
|
@@ -4405,6 +4473,8 @@ def view_rows(workbook_id: str, body: object = Body(default=None),
|
|
| 4405 |
related_bags = _related_leaf_bags(session, database, scope_nodes, needed)
|
| 4406 |
cur, spec, cols = _mirror(session)(database, metric_window=window, needed=needed)
|
| 4407 |
cols = dict(cols)
|
|
|
|
|
|
|
| 4408 |
related = related_bags(cur, spec, cols, window=window)
|
| 4409 |
for key in dict.fromkeys([*requested, *sorted(sorted_keys | sheet_mod.filter_columns_named(scope_nodes))]):
|
| 4410 |
if key.startswith(sheet_mod.RELATED_FILTER_PREFIX):
|
|
@@ -4481,6 +4551,11 @@ def _drill_mirror(session, database, window, needed, databases):
|
|
| 4481 |
from core import sheet_binding, perm_scope
|
| 4482 |
import datetime
|
| 4483 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4484 |
sources = _drill_tokens(session, databases)
|
| 4485 |
token = sheet_binding.fingerprint(sources) if all(sources.values()) else None
|
| 4486 |
# C1 also fingerprints derived wall sources, which can change without the primary table.
|
|
@@ -4711,6 +4786,16 @@ def drill_cell(workbook_id: str, addr: str, tab: str | None = None,
|
|
| 4711 |
cols = dict(cols)
|
| 4712 |
# Apply the aggregate's field wall before compiling either the count or the IDs.
|
| 4713 |
hidden = perm_scope.hidden_keys(session.user, database, spec.get("fields") or [], st=session.runtime)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4714 |
unreadable = sorted(sheet_mod.filter_columns_named(scope_nodes) & hidden)
|
| 4715 |
if unreadable:
|
| 4716 |
raise err(403, "field_unreadable", f"You cannot filter on field {unreadable[0]} in {database}.")
|
|
@@ -4728,6 +4813,8 @@ def drill_cell(workbook_id: str, addr: str, tab: str | None = None,
|
|
| 4728 |
raise err(409, "scope_not_applicable",
|
| 4729 |
"This cell's scope uses a restriction that cannot be applied on its live "
|
| 4730 |
"connection. Edit the scope or ask an administrator to update the restriction.")
|
|
|
|
|
|
|
| 4731 |
total = (cur.execute(count_sql, count_params).fetchone() or [0])[0]
|
| 4732 |
|
| 4733 |
# S66-T48: preserve the existing mutable-table cap and every legacy answer key.
|
|
@@ -4739,6 +4826,7 @@ def drill_cell(workbook_id: str, addr: str, tab: str | None = None,
|
|
| 4739 |
ids_sql = f"{ids_sql} LIMIT {int(id_limit)}"
|
| 4740 |
record_ids = [int(r[0]) for r in cur.execute(ids_sql, ids_params).fetchall() if r and r[0]]
|
| 4741 |
|
|
|
|
| 4742 |
out = {"database": database, "record_ids": record_ids, "count": int(total or 0),
|
| 4743 |
"id_limit": id_limit, "limits": limits}
|
| 4744 |
if scope.get("view_id"):
|
|
|
|
| 160 |
if fields is None and not is_registry_grid and not is_shipments:
|
| 161 |
connector_defn = _connector_definition(session, table_key)
|
| 162 |
if connector_defn is None:
|
| 163 |
+
if _native_table_definition(session, table_key) is not None:
|
| 164 |
+
return _native_table_mirror(session, table_key)
|
| 165 |
raise err(404, "not_connected", f"{table_key} is not a connected Odoo database.")
|
| 166 |
fields = list(connector_defn.get("fields") or [])
|
| 167 |
if not fields:
|
|
|
|
| 293 |
return _drill_for
|
| 294 |
|
| 295 |
|
| 296 |
+
def _native_table_definition(session, table_key):
|
| 297 |
+
"""A real stored, non-connector database; a ut_ prefix alone admits nothing."""
|
| 298 |
+
from core import user_tables
|
| 299 |
+
import odoo_relational as rel
|
| 300 |
+
import routes_odoo_tables as rot
|
| 301 |
+
key = str(table_key or "")
|
| 302 |
+
# Amazon owns its stored snapshots as well as its read-through tables.
|
| 303 |
+
if not key.startswith("ut_") or key.startswith("ut_amzn_"):
|
| 304 |
+
return None
|
| 305 |
+
if (key == rel.SHIPMENTS_KEY or key in rot._sources()
|
| 306 |
+
or any(key == declared for _bucket, declared, _label, _fields in rel.TABLES)):
|
| 307 |
+
return None
|
| 308 |
+
reader = _sheet_permission_reader(session)
|
| 309 |
+
defn = (user_tables.all_defs(st=reader) or {}).get(key)
|
| 310 |
+
if not defn or not user_tables.materialises(key, st=reader, defn=defn):
|
| 311 |
+
return None
|
| 312 |
+
if user_tables.is_connected(key, st=user_tables.lend(reader, user_tables={key: defn})):
|
| 313 |
+
return None
|
| 314 |
+
return defn
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def _native_table_mirror(session, table_key):
|
| 318 |
+
"""Reuse Data's scoped grid/spec reader, with a cursor owned by this Sheet request.
|
| 319 |
+
|
| 320 |
+
The payload has already applied permanent predicates, allowed IDs and field/BU walls.
|
| 321 |
+
Authored Sheet filters still compile below, against only the visible column vocabulary.
|
| 322 |
+
"""
|
| 323 |
+
import routes_odoo_tables as rot
|
| 324 |
+
memo = getattr(session, "_sheet_read_memo", None)
|
| 325 |
+
if not isinstance(memo, dict) or "sources" not in memo:
|
| 326 |
+
raise RuntimeError("A native Sheet source needs a request scope.")
|
| 327 |
+
slot = ("native_source", table_key)
|
| 328 |
+
if slot not in memo:
|
| 329 |
+
read = memo["sources"].enter_context(rot._materialised_read(
|
| 330 |
+
table_key, session, {"filters": [], "filterConj": "and", "search": ""}, None))
|
| 331 |
+
spec = {**read["spec"], "fields": read["payload"]["fields"],
|
| 332 |
+
"scope_applied": True, "limits": list(read["limits"])}
|
| 333 |
+
memo[slot] = (read["cur"], spec, read["cols"])
|
| 334 |
+
return memo[slot]
|
| 335 |
+
|
| 336 |
+
|
| 337 |
def _connector_definition(session: Session, table_key: str):
|
| 338 |
"""The stored stub of a read-through CONNECTOR grid (S66-T43), or None when it is not one.
|
| 339 |
|
| 340 |
Only a key the read-through registry serves qualifies (`routes_odoo_tables._sources()`), or an
|
| 341 |
+
Amazon table the connector declares (`amazon_relational.SOURCE`, stored or read-through).
|
| 342 |
+
Native typed databases use Data's separate scoped reader. Memoised on the Session for the reason
|
| 343 |
`_mirror` memoises: `resolve_bindings` asks once per CELL and the Session dies with the request.
|
| 344 |
⚠ `scope_applied=True` because every Sheet read compiles the row wall into its own SQL.
|
| 345 |
"""
|
|
|
|
| 776 |
import odoo_relational as rel
|
| 777 |
import routes_odoo_tables as rot
|
| 778 |
|
| 779 |
+
if (_native_table_definition(session, database) is not None
|
| 780 |
+
and not isinstance(getattr(session, "_sheet_read_memo", None), dict)):
|
| 781 |
+
with _sheet_request_scope(session):
|
| 782 |
+
return distinct_values(database, field, offset, limit, search, session)
|
| 783 |
known = set(rel._REGISTRY_GRID_FIELDS) | {key for _bucket, key, _label, _fields in rel.TABLES}
|
| 784 |
known.add(rel.SHIPMENTS_KEY)
|
| 785 |
known.update(rot._sources())
|
| 786 |
if database.startswith("ut_amzn_"):
|
| 787 |
import amazon_relational
|
| 788 |
known.update(amazon_relational.SOURCE)
|
| 789 |
+
if database not in known and _native_table_definition(session, database) is None:
|
| 790 |
raise err(404, "not_connected", f"{database} is not a connected database.")
|
| 791 |
database = _require_database(session, database)
|
| 792 |
_refuse_unapplied_audience(session, database)
|
|
|
|
| 795 |
wall_nodes, wall_conj = _fe_parts(wall)
|
| 796 |
needed = sheet_mod.filter_columns_named(wall_nodes) | {field}
|
| 797 |
cur, spec, columns = _mirror(session)(database, needed=needed)
|
| 798 |
+
if spec.get("scope_applied"):
|
| 799 |
+
wall_nodes, wall_conj = [], "and"
|
| 800 |
fields = spec.get("fields") or []
|
| 801 |
if field in perm_scope.hidden_keys(session.user, database, fields, st=session.runtime):
|
| 802 |
raise err(403, "field_unreadable", f"You cannot read field {field} in {database}.")
|
|
|
|
| 3306 |
previous = getattr(session, "_sheet_read_memo", None)
|
| 3307 |
previous_assemblies = getattr(session, "_sheet_assemblies", None)
|
| 3308 |
previous_context = getattr(session, "_sheet_scope_context", None)
|
| 3309 |
+
sources = contextlib.ExitStack()
|
| 3310 |
+
memo = {"today": _sheet_today(session), "sources": sources,
|
| 3311 |
"stats": {"engines": 0, "resolves": 0, "input_hits": 0}}
|
| 3312 |
try:
|
| 3313 |
session._sheet_read_memo = memo
|
|
|
|
| 3319 |
try:
|
| 3320 |
yield memo
|
| 3321 |
finally:
|
| 3322 |
+
try:
|
| 3323 |
+
sources.close()
|
| 3324 |
+
finally:
|
| 3325 |
+
session._sheet_read_memo = previous
|
| 3326 |
+
session._sheet_assemblies = previous_assemblies
|
| 3327 |
+
session._sheet_scope_context = previous_context
|
| 3328 |
|
| 3329 |
|
| 3330 |
def _request_scoped(route):
|
|
|
|
| 3339 |
session = signature.bind_partial(*args, **kwargs).arguments.get("session")
|
| 3340 |
if session is None:
|
| 3341 |
return route(*args, **kwargs)
|
| 3342 |
+
if isinstance(getattr(session, "_sheet_read_memo", None), dict):
|
| 3343 |
+
return route(*args, **kwargs)
|
| 3344 |
with _sheet_request_scope(session):
|
| 3345 |
return route(*args, **kwargs)
|
| 3346 |
return scoped
|
|
|
|
| 3967 |
return _rewrite_related_filters(session, database, nodes), conj
|
| 3968 |
|
| 3969 |
|
| 3970 |
+
@_request_scoped
|
| 3971 |
def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=None,
|
| 3972 |
book=None, tab=None, ending_seen=(), _pivot=None):
|
| 3973 |
"""Evaluate ONE C2 binding and return `{value, limits, sql_columns}`.
|
|
|
|
| 4031 |
related_bags = _related_leaf_bags(session, database, scope_nodes, needed)
|
| 4032 |
cur, spec, cols = _mirror(session)(database, metric_window=window, needed=needed)
|
| 4033 |
cols = dict(cols)
|
| 4034 |
+
if spec.get("scope_applied"):
|
| 4035 |
+
wall_nodes, wall_conj = [], "and"
|
| 4036 |
+
unreadable = (sheet_mod.filter_columns_named(scope_nodes) - set(cols)
|
| 4037 |
+
- sheet_mod.related_filter_ids(scope_nodes))
|
| 4038 |
+
field = binding["aggregate"].get("field")
|
| 4039 |
+
if field and field not in cols:
|
| 4040 |
+
unreadable.add(field)
|
| 4041 |
+
if unreadable:
|
| 4042 |
+
raise err(403, "field_unreadable", f"You cannot read field {sorted(unreadable)[0]} in {database}.")
|
| 4043 |
# Authored filters need field access; trusted defaults and permanent walls keep the full map.
|
| 4044 |
hidden = perm_scope.hidden_keys(session.user, database, spec.get("fields") or [], st=session.runtime)
|
| 4045 |
unreadable = sorted(sheet_mod.filter_columns_named(scope_nodes) & hidden)
|
|
|
|
| 4119 |
"live connection, so the number is not being shown rather than shown wider "
|
| 4120 |
"than you asked for. Edit the cell's scope and try again.")
|
| 4121 |
|
| 4122 |
+
if spec.get("scope_applied") and limits:
|
| 4123 |
+
raise err(409, "scope_not_applicable", "This cell's filter cannot be applied to this database.")
|
| 4124 |
if _pivot is not None:
|
| 4125 |
pivot_limits = list(limits) + [item for field, item in (spec.get("unbounded") or {}).items()
|
| 4126 |
if field in needed]
|
|
|
|
| 4139 |
depends = set(sheet_mod.filter_columns_named(scope_nodes))
|
| 4140 |
if binding["aggregate"].get("field"):
|
| 4141 |
depends.add(str(binding["aggregate"]["field"]))
|
| 4142 |
+
limits = (list(limits) + list(spec.get("limits") or [])
|
| 4143 |
+ [row for key, row in (spec.get("unbounded") or {}).items() if key in depends]
|
| 4144 |
+ sheet_mod.period_limits(binding.get("period"), binding["aggregate"], bound_field,
|
| 4145 |
spec.get("bounded") or (), depends))
|
|
|
|
| 4424 |
|
| 4425 |
|
| 4426 |
@router.post("/sheets/{workbook_id}/view-rows")
|
| 4427 |
+
@_request_scoped
|
| 4428 |
def view_rows(workbook_id: str, body: object = Body(default=None),
|
| 4429 |
session: Session = Depends(require_session)):
|
| 4430 |
"""W62 C2 / R29: read the live rows of a placed view under this caller's walls."""
|
|
|
|
| 4473 |
related_bags = _related_leaf_bags(session, database, scope_nodes, needed)
|
| 4474 |
cur, spec, cols = _mirror(session)(database, metric_window=window, needed=needed)
|
| 4475 |
cols = dict(cols)
|
| 4476 |
+
if spec.get("scope_applied"):
|
| 4477 |
+
wall_nodes, wall_conj = [], "and"
|
| 4478 |
related = related_bags(cur, spec, cols, window=window)
|
| 4479 |
for key in dict.fromkeys([*requested, *sorted(sorted_keys | sheet_mod.filter_columns_named(scope_nodes))]):
|
| 4480 |
if key.startswith(sheet_mod.RELATED_FILTER_PREFIX):
|
|
|
|
| 4551 |
from core import sheet_binding, perm_scope
|
| 4552 |
import datetime
|
| 4553 |
|
| 4554 |
+
if _native_table_definition(session, database) is not None:
|
| 4555 |
+
# Native rows are a fresh scoped Data payload. Never cache their cursor/permissions
|
| 4556 |
+
# across requests; the request's ExitStack closes it after the page is produced.
|
| 4557 |
+
yield _mirror(session)(database, metric_window=window, needed=needed), None
|
| 4558 |
+
return
|
| 4559 |
sources = _drill_tokens(session, databases)
|
| 4560 |
token = sheet_binding.fingerprint(sources) if all(sources.values()) else None
|
| 4561 |
# C1 also fingerprints derived wall sources, which can change without the primary table.
|
|
|
|
| 4786 |
cols = dict(cols)
|
| 4787 |
# Apply the aggregate's field wall before compiling either the count or the IDs.
|
| 4788 |
hidden = perm_scope.hidden_keys(session.user, database, spec.get("fields") or [], st=session.runtime)
|
| 4789 |
+
if spec.get("scope_applied"):
|
| 4790 |
+
wall_nodes, wall_conj = [], "and"
|
| 4791 |
+
unavailable = (sheet_mod.filter_columns_named(scope_nodes) - set(cols)
|
| 4792 |
+
- sheet_mod.related_filter_ids(scope_nodes))
|
| 4793 |
+
if unavailable:
|
| 4794 |
+
raise err(403, "field_unreadable",
|
| 4795 |
+
f"You cannot filter on field {sorted(unavailable)[0]} in {database}.")
|
| 4796 |
+
field = binding["aggregate"].get("field")
|
| 4797 |
+
if field and (field in hidden or field not in cols):
|
| 4798 |
+
raise err(403, "field_unreadable", f"You cannot read field {field} in {database}.")
|
| 4799 |
unreadable = sorted(sheet_mod.filter_columns_named(scope_nodes) & hidden)
|
| 4800 |
if unreadable:
|
| 4801 |
raise err(403, "field_unreadable", f"You cannot filter on field {unreadable[0]} in {database}.")
|
|
|
|
| 4813 |
raise err(409, "scope_not_applicable",
|
| 4814 |
"This cell's scope uses a restriction that cannot be applied on its live "
|
| 4815 |
"connection. Edit the scope or ask an administrator to update the restriction.")
|
| 4816 |
+
if spec.get("scope_applied") and limits:
|
| 4817 |
+
raise err(409, "scope_not_applicable", "This cell's filter cannot be applied to this database.")
|
| 4818 |
total = (cur.execute(count_sql, count_params).fetchone() or [0])[0]
|
| 4819 |
|
| 4820 |
# S66-T48: preserve the existing mutable-table cap and every legacy answer key.
|
|
|
|
| 4826 |
ids_sql = f"{ids_sql} LIMIT {int(id_limit)}"
|
| 4827 |
record_ids = [int(r[0]) for r in cur.execute(ids_sql, ids_params).fetchall() if r and r[0]]
|
| 4828 |
|
| 4829 |
+
limits = list(limits) + list(spec.get("limits") or [])
|
| 4830 |
out = {"database": database, "record_ids": record_ids, "count": int(total or 0),
|
| 4831 |
"id_limit": id_limit, "limits": limits}
|
| 4832 |
if scope.get("view_id"):
|
api/whatsapp_door.py
CHANGED
|
@@ -69,7 +69,7 @@ def _file_route(item):
|
|
| 69 |
|
| 70 |
|
| 71 |
def _artifact_links(rt, username, phone, files, made, *, now, mint):
|
| 72 |
-
"""Resolve
|
| 73 |
try:
|
| 74 |
artifacts = import_module("assistant_artifacts")
|
| 75 |
except ImportError:
|
|
@@ -88,9 +88,20 @@ def _artifact_links(rt, username, phone, files, made, *, now, mint):
|
|
| 88 |
except Exception:
|
| 89 |
continue
|
| 90 |
if (not isinstance(row, dict) or row.get("id") != artifact_id
|
| 91 |
-
or row.get("status") != "active"
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
continue
|
| 95 |
link = loopy_links.artifact_link(artifact_id)
|
| 96 |
if share is not None and not share.needs_sign_in(row):
|
|
@@ -431,8 +442,6 @@ def process(message, *, run_turn=None, append=None, now=None):
|
|
| 431 |
original_reply = str(reply or "")
|
| 432 |
reply = re.sub(r"(?:https?://[^\s<>]*?)?#/artifacts(?:\?[^\s<>]*)?"
|
| 433 |
r"|(?:https?://[^\s<>]*?)?/a/[^\s<>]+", "", str(reply or "")).strip()
|
| 434 |
-
if not reply and original_reply.strip():
|
| 435 |
-
reply = "Open Loopable to view this item."
|
| 436 |
reply = loopy_links.absolutize_text(reply)
|
| 437 |
reply = _omit_unconfigured_links(reply, tenant=tenant, username=username)
|
| 438 |
reply = clean_reply(reply)
|
|
@@ -445,10 +454,12 @@ def process(message, *, run_turn=None, append=None, now=None):
|
|
| 445 |
if "too_large" in routes:
|
| 446 |
reply = FILE_TOO_LARGE + ("\n" + reply if reply else "")
|
| 447 |
link = "\n".join(links) or None
|
|
|
|
|
|
|
| 448 |
if link:
|
| 449 |
reply = reply.rstrip()
|
| 450 |
if not reply.endswith(link):
|
| 451 |
-
reply
|
| 452 |
if callable(log):
|
| 453 |
if not runtime_owned:
|
| 454 |
log(rt, username, {"role": "user", "door": "whatsapp", "kind": "text",
|
|
|
|
| 69 |
|
| 70 |
|
| 71 |
def _artifact_links(rt, username, phone, files, made, *, now, mint):
|
| 72 |
+
"""Resolve frozen files or owned worklists, which always require sign-in."""
|
| 73 |
try:
|
| 74 |
artifacts = import_module("assistant_artifacts")
|
| 75 |
except ImportError:
|
|
|
|
| 88 |
except Exception:
|
| 89 |
continue
|
| 90 |
if (not isinstance(row, dict) or row.get("id") != artifact_id
|
| 91 |
+
or row.get("status") != "active"):
|
| 92 |
+
continue
|
| 93 |
+
if row.get("kind") == "report":
|
| 94 |
+
try:
|
| 95 |
+
worklist = import_module("assistant_worklists").owned_artifact(rt, username, row)
|
| 96 |
+
except Exception:
|
| 97 |
+
continue
|
| 98 |
+
if worklist is None:
|
| 99 |
+
continue
|
| 100 |
+
link = loopy_links.artifact_link(artifact_id)
|
| 101 |
+
if link and link not in links:
|
| 102 |
+
links.append(link)
|
| 103 |
+
continue
|
| 104 |
+
if row.get("kind") not in {"snapshot", "pdf", "xlsx", "image"} or not row.get("frozen_at"):
|
| 105 |
continue
|
| 106 |
link = loopy_links.artifact_link(artifact_id)
|
| 107 |
if share is not None and not share.needs_sign_in(row):
|
|
|
|
| 442 |
original_reply = str(reply or "")
|
| 443 |
reply = re.sub(r"(?:https?://[^\s<>]*?)?#/artifacts(?:\?[^\s<>]*)?"
|
| 444 |
r"|(?:https?://[^\s<>]*?)?/a/[^\s<>]+", "", str(reply or "")).strip()
|
|
|
|
|
|
|
| 445 |
reply = loopy_links.absolutize_text(reply)
|
| 446 |
reply = _omit_unconfigured_links(reply, tenant=tenant, username=username)
|
| 447 |
reply = clean_reply(reply)
|
|
|
|
| 454 |
if "too_large" in routes:
|
| 455 |
reply = FILE_TOO_LARGE + ("\n" + reply if reply else "")
|
| 456 |
link = "\n".join(links) or None
|
| 457 |
+
if not reply and original_reply.strip() and not link:
|
| 458 |
+
reply = "Open Loopable to view this item."
|
| 459 |
if link:
|
| 460 |
reply = reply.rstrip()
|
| 461 |
if not reply.endswith(link):
|
| 462 |
+
reply = (reply + "\n" if reply else "") + link
|
| 463 |
if callable(log):
|
| 464 |
if not runtime_owned:
|
| 465 |
log(rt, username, {"role": "user", "door": "whatsapp", "kind": "text",
|
web/public/AIOS_DEPLOY_RECEIPT
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
|
|
|
|
| 1 |
+
a94337c60d57ce6ace7f1c563aed15e988a84cde8590862ee4126a3f8807adad
|
web/src/assistant/AssistantPage.tsx
CHANGED
|
@@ -118,7 +118,10 @@ type SemanticDraft = {
|
|
| 118 |
fields: Array<{ field: string; label: string; why: string; role: string; dataType: string;
|
| 119 |
sensitivity: string; sample: { redacted: boolean; values: string[]; sample: string[] } }>;
|
| 120 |
};
|
| 121 |
-
type
|
|
|
|
|
|
|
|
|
|
| 122 |
status: "refused"; wording: string; speakable: string; artifacts: null; code?: string;
|
| 123 |
}) & { routedTo?: RoutedTo; draft?: SemanticDraft };
|
| 124 |
|
|
@@ -809,8 +812,8 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
|
|
| 809 |
|
| 810 |
useEffect(() => { void reload(); }, [reload]);
|
| 811 |
useEffect(() => () => openCancel.current?.(), []);
|
| 812 |
-
// Keep
|
| 813 |
-
//
|
| 814 |
useEffect(() => {
|
| 815 |
const permitted = databases.map((entry) => entry.key);
|
| 816 |
setTarget((current) => permitted.includes(current) ? current : databases[0]?.key ?? "");
|
|
@@ -849,7 +852,7 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
|
|
| 849 |
const text = override?.prompt ?? (replay ? replay.prompt : question.trim());
|
| 850 |
const selectedTarget = approvedFields && alignment ? alignment.database : target;
|
| 851 |
const database = override?.database ?? (replay ? (approvedFields ? selectedTarget : replay.database) : "");
|
| 852 |
-
if (!text || !
|
| 853 |
|| (requestInFlight.current && !activeChat.current)) return;
|
| 854 |
const primary = !activeChat.current;
|
| 855 |
if (primary) {
|
|
@@ -1009,8 +1012,7 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
|
|
| 1009 |
if (error instanceof ChatStreamFailure && error.admitted) {
|
| 1010 |
await loadConversation();
|
| 1011 |
}
|
| 1012 |
-
keepAsked(
|
| 1013 |
-
: error instanceof Error ? error.message : "This question could not be answered.");
|
| 1014 |
return;
|
| 1015 |
}
|
| 1016 |
}
|
|
@@ -1088,10 +1090,10 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
|
|
| 1088 |
};
|
| 1089 |
|
| 1090 |
useEffect(() => {
|
| 1091 |
-
if (!conversationLoaded ||
|
| 1092 |
const prompt = takePendingAsk();
|
| 1093 |
if (prompt) void ask(undefined, { database: "", prompt });
|
| 1094 |
-
}, [ask, busy, conversationLoaded
|
| 1095 |
|
| 1096 |
const submitDraft = async () => {
|
| 1097 |
if (!alignment?.draft || !alignmentFields.length || busy || draftBusy || requestInFlight.current) return;
|
|
@@ -1192,7 +1194,7 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
|
|
| 1192 |
className="as-prompt"
|
| 1193 |
value={question}
|
| 1194 |
rows={1}
|
| 1195 |
-
placeholder="Ask
|
| 1196 |
aria-label="Ask the assistant"
|
| 1197 |
onChange={(event) => setQuestion(event.currentTarget.value)}
|
| 1198 |
onKeyDown={(event) => {
|
|
@@ -1208,7 +1210,7 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
|
|
| 1208 |
onClick={() => void stop()}>Stop</button> : null}
|
| 1209 |
{/* R116: no model or database picker. The server routes the question and picks the model. */}
|
| 1210 |
<button type="button" className="as-send" aria-label="Send"
|
| 1211 |
-
disabled={stopping || draftBusy || !conversationLoaded || !question.trim()
|
| 1212 |
<svg viewBox="0 0 16 16" aria-hidden="true" width="15" height="15">
|
| 1213 |
<path d="M8 13V3.6M4 7.4 8 3.4l4 4" />
|
| 1214 |
</svg>
|
|
@@ -1242,7 +1244,7 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
|
|
| 1242 |
{empty ? <div className="as-opening"><AssistantGreeting loaded={conversationLoaded}
|
| 1243 |
turnCount={turns.length} />
|
| 1244 |
<SuggestionChips granted={granted} loaded={conversationLoaded} turnCount={turns.length}
|
| 1245 |
-
busy={busy
|
| 1246 |
</div> : null}
|
| 1247 |
{turns.map((turn) => {
|
| 1248 |
const message = turnMessage(turn);
|
|
|
|
| 118 |
fields: Array<{ field: string; label: string; why: string; role: string; dataType: string;
|
| 119 |
sensitivity: string; sample: { redacted: boolean; values: string[]; sample: string[] } }>;
|
| 120 |
};
|
| 121 |
+
type AssistantChatContinuation = {
|
| 122 |
+
status: "continue_chat"; routedTo: RoutedTo & { database: ""; auto: false };
|
| 123 |
+
};
|
| 124 |
+
type RoutedQueryResult = (Awaited<ReturnType<typeof runQueryTool>> | AssistantChatContinuation | {
|
| 125 |
status: "refused"; wording: string; speakable: string; artifacts: null; code?: string;
|
| 126 |
}) & { routedTo?: RoutedTo; draft?: SemanticDraft };
|
| 127 |
|
|
|
|
| 812 |
|
| 813 |
useEffect(() => { void reload(); }, [reload]);
|
| 814 |
useEffect(() => () => openCancel.current?.(), []);
|
| 815 |
+
// Keep source selection within the grant for clarification replays. A fresh question needs
|
| 816 |
+
// no target: the server preflight decides whether to route Data or continue guarded chat.
|
| 817 |
useEffect(() => {
|
| 818 |
const permitted = databases.map((entry) => entry.key);
|
| 819 |
setTarget((current) => permitted.includes(current) ? current : databases[0]?.key ?? "");
|
|
|
|
| 852 |
const text = override?.prompt ?? (replay ? replay.prompt : question.trim());
|
| 853 |
const selectedTarget = approvedFields && alignment ? alignment.database : target;
|
| 854 |
const database = override?.database ?? (replay ? (approvedFields ? selectedTarget : replay.database) : "");
|
| 855 |
+
if (!text || !conversationLoaded || draftBusy || stopInFlight.current
|
| 856 |
|| (requestInFlight.current && !activeChat.current)) return;
|
| 857 |
const primary = !activeChat.current;
|
| 858 |
if (primary) {
|
|
|
|
| 1012 |
if (error instanceof ChatStreamFailure && error.admitted) {
|
| 1013 |
await loadConversation();
|
| 1014 |
}
|
| 1015 |
+
keepAsked(refusalSentence(failureCode(error)));
|
|
|
|
| 1016 |
return;
|
| 1017 |
}
|
| 1018 |
}
|
|
|
|
| 1090 |
};
|
| 1091 |
|
| 1092 |
useEffect(() => {
|
| 1093 |
+
if (!conversationLoaded || busy || requestInFlight.current) return;
|
| 1094 |
const prompt = takePendingAsk();
|
| 1095 |
if (prompt) void ask(undefined, { database: "", prompt });
|
| 1096 |
+
}, [ask, busy, conversationLoaded]);
|
| 1097 |
|
| 1098 |
const submitDraft = async () => {
|
| 1099 |
if (!alignment?.draft || !alignmentFields.length || busy || draftBusy || requestInFlight.current) return;
|
|
|
|
| 1194 |
className="as-prompt"
|
| 1195 |
value={question}
|
| 1196 |
rows={1}
|
| 1197 |
+
placeholder="Ask the assistant…"
|
| 1198 |
aria-label="Ask the assistant"
|
| 1199 |
onChange={(event) => setQuestion(event.currentTarget.value)}
|
| 1200 |
onKeyDown={(event) => {
|
|
|
|
| 1210 |
onClick={() => void stop()}>Stop</button> : null}
|
| 1211 |
{/* R116: no model or database picker. The server routes the question and picks the model. */}
|
| 1212 |
<button type="button" className="as-send" aria-label="Send"
|
| 1213 |
+
disabled={busy || stopping || draftBusy || !conversationLoaded || !question.trim()} onClick={() => void ask()}>
|
| 1214 |
<svg viewBox="0 0 16 16" aria-hidden="true" width="15" height="15">
|
| 1215 |
<path d="M8 13V3.6M4 7.4 8 3.4l4 4" />
|
| 1216 |
</svg>
|
|
|
|
| 1244 |
{empty ? <div className="as-opening"><AssistantGreeting loaded={conversationLoaded}
|
| 1245 |
turnCount={turns.length} />
|
| 1246 |
<SuggestionChips granted={granted} loaded={conversationLoaded} turnCount={turns.length}
|
| 1247 |
+
busy={busy} onAsk={(database, prompt) => void ask(undefined, { database, prompt })} />
|
| 1248 |
</div> : null}
|
| 1249 |
{turns.map((turn) => {
|
| 1250 |
const message = turnMessage(turn);
|
web/src/assistant/AssistantPanel.tsx
CHANGED
|
@@ -5,7 +5,7 @@ import type { SuggestionChips } from "./SuggestionChips";
|
|
| 5 |
import type { TypingIndicator } from "./TypingIndicator";
|
| 6 |
import type { NavEntry } from "../shell/nav";
|
| 7 |
import type { QueryCitation, QueryMessage, Result, SavedQuery } from "../query/queryApi";
|
| 8 |
-
import { dockClient } from "./dockClient";
|
| 9 |
import type { DockClient, DockContext } from "./dockClient";
|
| 10 |
import "./assistantPanel.css";
|
| 11 |
|
|
@@ -53,10 +53,9 @@ function unlogged(messages: QueryMessage[], turns: AssistantLogTurn[]): QueryMes
|
|
| 53 |
const ids = new Set(turns.flatMap((turn) => [turn.id, turn.payload?.id]));
|
| 54 |
return messages.filter((message) => !ids.has(message.id));
|
| 55 |
}
|
| 56 |
-
/** C2:
|
| 57 |
-
* Two pre-C2 lines stay, pinned by assistantPanel.test: no response at all, and the uncoded 403 wall. */
|
| 58 |
export function dockFailureLine(result: Extract<Result<unknown>, { ok: false }>): string {
|
| 59 |
-
return
|
| 60 |
}
|
| 61 |
/** The dock's databases as nav entries, for the suggestion chips and the link pop-up. */
|
| 62 |
export function dockSources(database?: string, databases?: string[], label?: string): NavEntry[] {
|
|
@@ -171,7 +170,7 @@ export default function AssistantPanel({ open, onClose, surface = "data", databa
|
|
| 171 |
], value.turns), citations: [...value.citations, ...response.citations], view: response.view }));
|
| 172 |
} catch {
|
| 173 |
if (mounted.current) setState((value) => ({ ...value, draft, retry: { id, question },
|
| 174 |
-
problem:
|
| 175 |
} finally {
|
| 176 |
inFlight.current = false;
|
| 177 |
if (mounted.current) setState((value) => ({ ...value, busy: false }));
|
|
|
|
| 5 |
import type { TypingIndicator } from "./TypingIndicator";
|
| 6 |
import type { NavEntry } from "../shell/nav";
|
| 7 |
import type { QueryCitation, QueryMessage, Result, SavedQuery } from "../query/queryApi";
|
| 8 |
+
import { dockClient, refusalSentence } from "./dockClient";
|
| 9 |
import type { DockClient, DockContext } from "./dockClient";
|
| 10 |
import "./assistantPanel.css";
|
| 11 |
|
|
|
|
| 53 |
const ids = new Set(turns.flatMap((turn) => [turn.id, turn.payload?.id]));
|
| 54 |
return messages.filter((message) => !ids.has(message.id));
|
| 55 |
}
|
| 56 |
+
/** C2: failed turns use the shared mapper even without a response or a recognized code. */
|
|
|
|
| 57 |
export function dockFailureLine(result: Extract<Result<unknown>, { ok: false }>): string {
|
| 58 |
+
return refusalSentence(result.code);
|
| 59 |
}
|
| 60 |
/** The dock's databases as nav entries, for the suggestion chips and the link pop-up. */
|
| 61 |
export function dockSources(database?: string, databases?: string[], label?: string): NavEntry[] {
|
|
|
|
| 170 |
], value.turns), citations: [...value.citations, ...response.citations], view: response.view }));
|
| 171 |
} catch {
|
| 172 |
if (mounted.current) setState((value) => ({ ...value, draft, retry: { id, question },
|
| 173 |
+
problem: refusalSentence() }));
|
| 174 |
} finally {
|
| 175 |
inFlight.current = false;
|
| 176 |
if (mounted.current) setState((value) => ({ ...value, busy: false }));
|
web/src/assistant/dockClient.ts
CHANGED
|
@@ -2,6 +2,8 @@ import { call as queryRequest } from "../query/queryApi";
|
|
| 2 |
import type { ChatResult, Result } from "../query/queryApi";
|
| 3 |
import type { AssistantLogTurn } from "./AssistantPage";
|
| 4 |
|
|
|
|
|
|
|
| 5 |
export type DockSurface = "data" | "sheet" | "automation" | "field";
|
| 6 |
export interface DockContext {
|
| 7 |
surface: DockSurface;
|
|
|
|
| 2 |
import type { ChatResult, Result } from "../query/queryApi";
|
| 3 |
import type { AssistantLogTurn } from "./AssistantPage";
|
| 4 |
|
| 5 |
+
export { refusalSentence } from "../query/queryApi";
|
| 6 |
+
|
| 7 |
export type DockSurface = "data" | "sheet" | "automation" | "field";
|
| 8 |
export interface DockContext {
|
| 9 |
surface: DockSurface;
|
web/src/assistant/streamClient.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
import { API_V1, CREDENTIALS, checkTenant, signal, UNAUTHORIZED_EVENT } from "../apiContract";
|
| 2 |
-
import { refusalPair, type ChatResult } from "../query/queryApi";
|
| 3 |
|
| 4 |
type StreamLine = { message?: string; label?: string; name?: string; [key: string]: unknown };
|
| 5 |
type StreamError = StreamLine & { status?: number; code?: string; retry?: boolean; result?: unknown;
|
|
@@ -57,10 +57,10 @@ export async function streamChat(body: ChatStreamRequest, onEvent: (event: ChatS
|
|
| 57 |
method: "POST", credentials: CREDENTIALS, signal: abortSignal,
|
| 58 |
headers: { "Content-Type": "application/json", Accept: "text/event-stream" }, body: JSON.stringify(body),
|
| 59 |
});
|
| 60 |
-
} catch
|
| 61 |
abortSignal?.throwIfAborted();
|
| 62 |
// Losing the response cannot establish that the server refused admission. Read its log.
|
| 63 |
-
throw new ChatStreamFailure(
|
| 64 |
}
|
| 65 |
abortSignal?.throwIfAborted();
|
| 66 |
if (checkTenant(response)) throw new ChatStreamFailure("The workspace changed. Open this chat again.", false);
|
|
@@ -68,8 +68,8 @@ export async function streamChat(body: ChatStreamRequest, onEvent: (event: ChatS
|
|
| 68 |
if (!response.ok) {
|
| 69 |
const detail = await response.json().catch(() => null) as StreamError | null;
|
| 70 |
const { code } = refusalPair(detail);
|
| 71 |
-
throw new ChatStreamFailure(
|
| 72 |
-
!boundaryFailure(response.status,
|
| 73 |
}
|
| 74 |
if (response.headers.get("Content-Type")?.split(";")[0].trim().toLowerCase() !== "text/event-stream" || !response.body)
|
| 75 |
throw new ChatStreamFailure("The answer stream is unavailable.", true);
|
|
@@ -118,10 +118,11 @@ export async function streamChat(body: ChatStreamRequest, onEvent: (event: ChatS
|
|
| 118 |
}
|
| 119 |
}
|
| 120 |
onEvent(event);
|
| 121 |
-
if (event.type === "error")
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
| 125 |
if (event.type === "done" || event.type === "joined") return event;
|
| 126 |
}
|
| 127 |
if (chunk.done) throw new ChatStreamFailure("The answer stream ended before the answer was saved.", false, true);
|
|
@@ -129,7 +130,7 @@ export async function streamChat(body: ChatStreamRequest, onEvent: (event: ChatS
|
|
| 129 |
} catch (error) {
|
| 130 |
abortSignal?.throwIfAborted();
|
| 131 |
if (error instanceof ChatStreamFailure) throw error;
|
| 132 |
-
throw new ChatStreamFailure(
|
| 133 |
} finally {
|
| 134 |
abortSignal?.removeEventListener("abort", cancel);
|
| 135 |
void reader.cancel().catch(() => {});
|
|
|
|
| 1 |
import { API_V1, CREDENTIALS, checkTenant, signal, UNAUTHORIZED_EVENT } from "../apiContract";
|
| 2 |
+
import { refusalPair, refusalSentence, type ChatResult } from "../query/queryApi";
|
| 3 |
|
| 4 |
type StreamLine = { message?: string; label?: string; name?: string; [key: string]: unknown };
|
| 5 |
type StreamError = StreamLine & { status?: number; code?: string; retry?: boolean; result?: unknown;
|
|
|
|
| 57 |
method: "POST", credentials: CREDENTIALS, signal: abortSignal,
|
| 58 |
headers: { "Content-Type": "application/json", Accept: "text/event-stream" }, body: JSON.stringify(body),
|
| 59 |
});
|
| 60 |
+
} catch {
|
| 61 |
abortSignal?.throwIfAborted();
|
| 62 |
// Losing the response cannot establish that the server refused admission. Read its log.
|
| 63 |
+
throw new ChatStreamFailure(refusalSentence(), false, true);
|
| 64 |
}
|
| 65 |
abortSignal?.throwIfAborted();
|
| 66 |
if (checkTenant(response)) throw new ChatStreamFailure("The workspace changed. Open this chat again.", false);
|
|
|
|
| 68 |
if (!response.ok) {
|
| 69 |
const detail = await response.json().catch(() => null) as StreamError | null;
|
| 70 |
const { code } = refusalPair(detail);
|
| 71 |
+
throw new ChatStreamFailure(refusalSentence(code),
|
| 72 |
+
!boundaryFailure(response.status, code), false, code);
|
| 73 |
}
|
| 74 |
if (response.headers.get("Content-Type")?.split(";")[0].trim().toLowerCase() !== "text/event-stream" || !response.body)
|
| 75 |
throw new ChatStreamFailure("The answer stream is unavailable.", true);
|
|
|
|
| 118 |
}
|
| 119 |
}
|
| 120 |
onEvent(event);
|
| 121 |
+
if (event.type === "error") {
|
| 122 |
+
const { code } = refusalPair(event.data);
|
| 123 |
+
throw new ChatStreamFailure(refusalSentence(code), !admitted && event.data.retry !== false &&
|
| 124 |
+
!boundaryFailure(event.data.status || 0, code), admitted, code);
|
| 125 |
+
}
|
| 126 |
if (event.type === "done" || event.type === "joined") return event;
|
| 127 |
}
|
| 128 |
if (chunk.done) throw new ChatStreamFailure("The answer stream ended before the answer was saved.", false, true);
|
|
|
|
| 130 |
} catch (error) {
|
| 131 |
abortSignal?.throwIfAborted();
|
| 132 |
if (error instanceof ChatStreamFailure) throw error;
|
| 133 |
+
throw new ChatStreamFailure(refusalSentence(), !admitted, admitted);
|
| 134 |
} finally {
|
| 135 |
abortSignal?.removeEventListener("abort", cancel);
|
| 136 |
void reader.cancel().catch(() => {});
|
web/src/query/queryApi.ts
CHANGED
|
@@ -403,7 +403,7 @@ export async function call<T>(path: string, init: RequestInit, read: (body: unkn
|
|
| 403 |
try {
|
| 404 |
res = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS, ...init });
|
| 405 |
} catch {
|
| 406 |
-
return { ok: false, status: 0, message: "Cannot reach the server." };
|
| 407 |
}
|
| 408 |
const body = (await res.json().catch(() => null)) as unknown;
|
| 409 |
if (!res.ok) {
|
|
|
|
| 403 |
try {
|
| 404 |
res = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS, ...init });
|
| 405 |
} catch {
|
| 406 |
+
return { ok: false, status: 0, message: "Cannot reach the server.", sentence: refusalSentence() };
|
| 407 |
}
|
| 408 |
const body = (await res.json().catch(() => null)) as unknown;
|
| 409 |
if (!res.ok) {
|