fsanyoto commited on
Commit
382942c
·
verified ·
1 Parent(s): 290a976

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,4 +1,4 @@
1
  {
2
- "current": "052998edf",
3
  "releases": []
4
  }
 
1
  {
2
+ "current": "eb42401d8c",
3
  "releases": []
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- 052998edf
 
1
+ eb42401d8c
api/application_registry.py CHANGED
@@ -234,18 +234,26 @@ class ApplicationRuleError(ApplicationError):
234
  super().__init__(str(refusal))
235
 
236
 
237
- # Legacy exception contract retained for callers that import it.
238
- APP_EXISTS_MESSAGE = "You already have this App."
239
 
240
 
241
  class ApplicationExistsError(ApplicationError):
242
- """Keep the legacy refusal envelope available without restricting template copies."""
 
243
 
244
  def __init__(self, existing=None):
245
  super().__init__(APP_EXISTS_MESSAGE)
246
  self.existing = existing
247
 
248
 
 
 
 
 
 
 
 
 
249
  def template_identity(app):
250
  """Return the grouping key for template copies, including each separate Finance template."""
251
  if not isinstance(app, dict):
@@ -258,25 +266,26 @@ def template_identity(app):
258
  return kind if kind in APPLICATION_WIZARD_TEMPLATE_KINDS + GATED_TEMPLATE_KINDS else None
259
 
260
 
261
- def _own_template_app(applications, user, identity):
262
- """Return the first owned live copy for legacy callers, without limiting creation."""
263
  if not identity:
264
- return None
265
- for app in applications.values():
266
- if (isinstance(app, dict) and app.get("createdBy") == user
267
- and app.get("retired") is not True and template_identity(app) == identity):
268
- return app
269
- return None
 
270
 
271
 
272
- def own_template_apps(runtime, user):
273
- """Return every owned live copy grouped by template identity for the picker."""
274
  owned = {}
275
  apps = sorted((app for app in load(runtime)["applications"].values() if isinstance(app, dict)),
276
  key=lambda app: (str(app.get("createdAt") or ""), str(app.get("id") or "")))
277
  for app in apps:
278
  identity = template_identity(app)
279
- if (identity and app.get("createdBy") == user
280
  and app.get("retired") is not True):
281
  owned.setdefault(identity, []).append(
282
  {"id": app.get("id"), "name": app.get("name"),
@@ -1360,9 +1369,32 @@ def _create_record(runtime, app, user, *, via=None, on_behalf_of=None):
1360
  combined = _clean_doc(legacy)
1361
  for record in records.values():
1362
  combined["applications"].update(record["applications"])
 
 
1363
  refusal = capacity_refusal(combined, user)
1364
  if refusal:
1365
  raise ApplicationError(refusal)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1366
  owner = hashlib.sha256(user.encode("utf-8")).hexdigest()
1367
  prefix = f"{_RECORD_PREFIX}{owner}/"
1368
  occupied = {int(key[len(prefix):]) for key, doc in records.items()
@@ -1399,26 +1431,40 @@ def _create_record(runtime, app, user, *, via=None, on_behalf_of=None):
1399
 
1400
 
1401
  def create(runtime, tenant, user, payload, *, semantic_records=None, field_contracts=None,
1402
- allowed_databases=None, via=None, on_behalf_of=None, origin_door=None):
 
1403
  if getattr(runtime, "key", tenant) != tenant or getattr(getattr(runtime, "tenant", None), "key", tenant) != tenant:
1404
  raise PermissionError("an Application cannot be created for another tenant")
1405
  app = _build_application(
1406
  tenant, user, payload, semantic_records=semantic_records, field_contracts=field_contracts,
1407
  allowed_databases=allowed_databases, origin_door=origin_door, via=via)
1408
  app_id = app["id"]
 
 
 
 
 
1409
  advice = _validate_chart_rules(
1410
  app, semantic_records=semantic_records, field_contracts=field_contracts)
1411
  _validate_catalog_rules(app)
1412
  def apply(raw):
1413
  doc=_clean_doc(raw)
 
1414
  refusal = capacity_refusal(doc, user)
1415
  if refusal: raise ApplicationError(refusal)
1416
- # R216 and R247 allow every template to have several independent copies.
1417
  doc["applications"][app_id]=app; return doc
1418
- if callable(getattr(runtime, "list_keys", None)):
1419
- _create_record(runtime, app, user, via=via, on_behalf_of=on_behalf_of)
1420
- else:
1421
- _update_with_activity(runtime, app_id, user, apply, via=via, on_behalf_of=on_behalf_of)
 
 
 
 
 
 
 
 
1422
  result = _public(app,user,allowed_databases=allowed_databases)
1423
  if app["type"] == "chart":
1424
  result["advice"] = advice
@@ -2060,7 +2106,7 @@ def duplicate(runtime, app_id, tenant, user, is_admin=False, *, semantic_records
2060
  return create(runtime,tenant,user,payload,
2061
  semantic_records=semantic_records, field_contracts=field_contracts,
2062
  allowed_databases=allowed_databases, via=via, on_behalf_of=on_behalf_of,
2063
- origin_door=origin_door)
2064
 
2065
 
2066
  _ANY_NAME = object()
 
234
  super().__init__(str(refusal))
235
 
236
 
237
+ APP_EXISTS_MESSAGE = "This App is already in this workspace. Ask its owner to share it."
 
238
 
239
 
240
  class ApplicationExistsError(ApplicationError):
241
+ """A live copy of this template App is in the tenant and the caller may not read it."""
242
+ code = "template_app_exists"
243
 
244
  def __init__(self, existing=None):
245
  super().__init__(APP_EXISTS_MESSAGE)
246
  self.existing = existing
247
 
248
 
249
+ class _TemplateHeld(Exception):
250
+ """A live copy of the template App holds the tenant's one slot."""
251
+
252
+ def __init__(self, live):
253
+ super().__init__("template App exists")
254
+ self.live = live
255
+
256
+
257
  def template_identity(app):
258
  """Return the grouping key for template copies, including each separate Finance template."""
259
  if not isinstance(app, dict):
 
266
  return kind if kind in APPLICATION_WIZARD_TEMPLATE_KINDS + GATED_TEMPLATE_KINDS else None
267
 
268
 
269
+ def _refuse_template_held(applications, identity):
270
+ """Raise `_TemplateHeld` with every live copy of `identity`, oldest first, when one exists."""
271
  if not identity:
272
+ return
273
+ live = sorted((app for app in applications.values()
274
+ if isinstance(app, dict) and app.get("retired") is not True
275
+ and template_identity(app) == identity),
276
+ key=lambda app: (str(app.get("createdAt") or ""), str(app.get("id") or "")))
277
+ if live:
278
+ raise _TemplateHeld(live)
279
 
280
 
281
+ def own_template_apps(runtime, user, is_admin=False):
282
+ """Return every live template copy the caller may read, grouped by template identity."""
283
  owned = {}
284
  apps = sorted((app for app in load(runtime)["applications"].values() if isinstance(app, dict)),
285
  key=lambda app: (str(app.get("createdAt") or ""), str(app.get("id") or "")))
286
  for app in apps:
287
  identity = template_identity(app)
288
+ if (identity and may_read(app, user, is_admin)
289
  and app.get("retired") is not True):
290
  owned.setdefault(identity, []).append(
291
  {"id": app.get("id"), "name": app.get("name"),
 
1369
  combined = _clean_doc(legacy)
1370
  for record in records.values():
1371
  combined["applications"].update(record["applications"])
1372
+ identity = template_identity(app)
1373
+ _refuse_template_held(combined["applications"], identity)
1374
  refusal = capacity_refusal(combined, user)
1375
  if refusal:
1376
  raise ApplicationError(refusal)
1377
+ if identity:
1378
+ # One tenant-wide key chain per template: racing creates of one template lock the same record.
1379
+ chain = f"{_RECORD_PREFIX}template/{hashlib.sha256(identity.encode('utf-8')).hexdigest()}/"
1380
+ for index in range(_MAX):
1381
+ def claim(raw):
1382
+ doc = _clean_doc(raw)
1383
+ _refuse_template_held(doc["applications"], identity)
1384
+ if doc["applications"]:
1385
+ raise _AppSlotOccupied() # a retired copy keeps this link of the chain
1386
+ doc["applications"] = {app["id"]: app}
1387
+ return doc
1388
+ try:
1389
+ saved = _update_with_activity(runtime, app["id"], user, claim, via=via,
1390
+ on_behalf_of=on_behalf_of,
1391
+ document_key=chain + str(index))
1392
+ except _AppSlotOccupied:
1393
+ continue
1394
+ if saved is False:
1395
+ raise ApplicationError("the App was not saved")
1396
+ return
1397
+ raise ApplicationError("the App was not saved")
1398
  owner = hashlib.sha256(user.encode("utf-8")).hexdigest()
1399
  prefix = f"{_RECORD_PREFIX}{owner}/"
1400
  occupied = {int(key[len(prefix):]) for key, doc in records.items()
 
1431
 
1432
 
1433
  def create(runtime, tenant, user, payload, *, semantic_records=None, field_contracts=None,
1434
+ allowed_databases=None, via=None, on_behalf_of=None, origin_door=None, is_admin=False):
1435
+ """Create one App. A template App is one live copy per tenant: a second add returns the first."""
1436
  if getattr(runtime, "key", tenant) != tenant or getattr(getattr(runtime, "tenant", None), "key", tenant) != tenant:
1437
  raise PermissionError("an Application cannot be created for another tenant")
1438
  app = _build_application(
1439
  tenant, user, payload, semantic_records=semantic_records, field_contracts=field_contracts,
1440
  allowed_databases=allowed_databases, origin_door=origin_door, via=via)
1441
  app_id = app["id"]
1442
+ identity = template_identity(app)
1443
+ if identity and not workspace_share_needs_approval(app, is_admin):
1444
+ # The one template copy is listed for the whole tenant. Source walls still gate its data.
1445
+ # An AI door's non-admin copy stays private until an Administrator approves the share.
1446
+ app["share"] = {"mode": "tenant", "users": []}
1447
  advice = _validate_chart_rules(
1448
  app, semantic_records=semantic_records, field_contracts=field_contracts)
1449
  _validate_catalog_rules(app)
1450
  def apply(raw):
1451
  doc=_clean_doc(raw)
1452
+ _refuse_template_held(doc["applications"], identity)
1453
  refusal = capacity_refusal(doc, user)
1454
  if refusal: raise ApplicationError(refusal)
 
1455
  doc["applications"][app_id]=app; return doc
1456
+ try:
1457
+ if callable(getattr(runtime, "list_keys", None)):
1458
+ _create_record(runtime, app, user, via=via, on_behalf_of=on_behalf_of)
1459
+ else:
1460
+ _update_with_activity(runtime, app_id, user, apply, via=via, on_behalf_of=on_behalf_of)
1461
+ except _TemplateHeld as exc:
1462
+ readable = next((held for held in exc.live if may_read(held, user, is_admin)), None)
1463
+ if readable is None:
1464
+ raise ApplicationExistsError() from None
1465
+ result = _public(readable, user, is_admin, allowed_databases=allowed_databases)
1466
+ result["existing"] = True
1467
+ return result
1468
  result = _public(app,user,allowed_databases=allowed_databases)
1469
  if app["type"] == "chart":
1470
  result["advice"] = advice
 
2106
  return create(runtime,tenant,user,payload,
2107
  semantic_records=semantic_records, field_contracts=field_contracts,
2108
  allowed_databases=allowed_databases, via=via, on_behalf_of=on_behalf_of,
2109
+ origin_door=origin_door, is_admin=is_admin)
2110
 
2111
 
2112
  _ANY_NAME = object()
api/routes_assets.py CHANGED
@@ -32,7 +32,7 @@ import time
32
  import uuid
33
  from pathlib import Path
34
 
35
- from fastapi import Body, Depends
36
  from fastapi import APIRouter
37
  from fastapi.responses import FileResponse, Response
38
 
@@ -50,6 +50,8 @@ def _application_error(exc):
50
  raise err(403, "forbidden", str(exc))
51
  if isinstance(exc, applications.ApplicationRuleError):
52
  raise err(400, exc.code, str(exc))
 
 
53
  message = str(exc)
54
  status = 404 if "does not exist" in message else 400
55
  raise err(status, "application_not_found" if status == 404 else "bad_application", message)
@@ -342,7 +344,8 @@ def application_index(database: str = "", type: str = "", starred: bool | None =
342
 
343
  @router.post("/applications", status_code=201)
344
  def create_application(body: dict = Body(default=None),
345
- session: Session = Depends(require_session)):
 
346
  if not session.runtime.available():
347
  raise err(503, "store_unavailable", "the tenant store is unavailable. Nothing was saved.")
348
  try:
@@ -350,10 +353,17 @@ def create_application(body: dict = Body(default=None),
350
  if (body or {}).get("templateKind") == "catalog" and (body or {}).get("sourceDatabase"):
351
  compatible = [*(compatible or []), body["sourceDatabase"]]
352
  allowed, records = application_access_context(session, compatible, strict=True)
353
- return {"application": applications.create(
354
  session.runtime, session.tenant, session.uname, body,
355
  semantic_records=records, allowed_databases=allowed,
356
- field_contracts=_application_chart_fields(session, allowed, body))}
 
 
 
 
 
 
 
357
  except (applications.ApplicationError, PermissionError) as exc:
358
  _application_error(exc)
359
 
 
32
  import uuid
33
  from pathlib import Path
34
 
35
+ from fastapi import Body, Depends, Response
36
  from fastapi import APIRouter
37
  from fastapi.responses import FileResponse, Response
38
 
 
50
  raise err(403, "forbidden", str(exc))
51
  if isinstance(exc, applications.ApplicationRuleError):
52
  raise err(400, exc.code, str(exc))
53
+ if isinstance(exc, applications.ApplicationExistsError):
54
+ raise err(409, exc.code, str(exc))
55
  message = str(exc)
56
  status = 404 if "does not exist" in message else 400
57
  raise err(status, "application_not_found" if status == 404 else "bad_application", message)
 
344
 
345
  @router.post("/applications", status_code=201)
346
  def create_application(body: dict = Body(default=None),
347
+ session: Session = Depends(require_session),
348
+ response: Response = None):
349
  if not session.runtime.available():
350
  raise err(503, "store_unavailable", "the tenant store is unavailable. Nothing was saved.")
351
  try:
 
353
  if (body or {}).get("templateKind") == "catalog" and (body or {}).get("sourceDatabase"):
354
  compatible = [*(compatible or []), body["sourceDatabase"]]
355
  allowed, records = application_access_context(session, compatible, strict=True)
356
+ application = applications.create(
357
  session.runtime, session.tenant, session.uname, body,
358
  semantic_records=records, allowed_databases=allowed,
359
+ field_contracts=_application_chart_fields(session, allowed, body),
360
+ is_admin=session.admin)
361
+ if application.get("existing") is True:
362
+ # A template App already in this tenant: answer that copy instead of a new one.
363
+ if response is not None:
364
+ response.status_code = 200
365
+ return {"application": application, "existing": True}
366
+ return {"application": application}
367
  except (applications.ApplicationError, PermissionError) as exc:
368
  _application_error(exc)
369
 
api/routes_external.py CHANGED
@@ -3358,10 +3358,16 @@ def _application_upsert(session, args):
3358
  if payload.get("sourceDatabase"):
3359
  databases = [*databases, payload["sourceDatabase"]]
3360
  allowed, records = _application_access(session, databases, strict=True)
3361
- return {"application": applications.create(
3362
  session.runtime, session.tenant, session.uname, payload,
3363
  semantic_records=records, allowed_databases=allowed,
3364
- field_contracts=routes_assets._application_chart_fields(session, allowed, payload), **attribution)}
 
 
 
 
 
 
3365
  current = routes_assets._application_databases(session.runtime, app_id)
3366
  allowed, _ = _application_access(session, current)
3367
  if not current or not allowed:
 
3358
  if payload.get("sourceDatabase"):
3359
  databases = [*databases, payload["sourceDatabase"]]
3360
  allowed, records = _application_access(session, databases, strict=True)
3361
+ application = applications.create(
3362
  session.runtime, session.tenant, session.uname, payload,
3363
  semantic_records=records, allowed_databases=allowed,
3364
+ field_contracts=routes_assets._application_chart_fields(session, allowed, payload),
3365
+ is_admin=session.admin, **attribution)
3366
+ if application.get("existing") is True:
3367
+ # One live copy per template App per tenant: answer that copy, a normal success.
3368
+ return {"application": application, "existing": True,
3369
+ "message": "This App is already in this workspace. Nothing new was added."}
3370
+ return {"application": application}
3371
  current = routes_assets._application_databases(session.runtime, app_id)
3372
  allowed, _ = _application_access(session, current)
3373
  if not current or not allowed:
api/routes_nav.py CHANGED
@@ -15,7 +15,7 @@ import re
15
  import time
16
  from datetime import datetime, timezone
17
 
18
- from fastapi import APIRouter, Body, Depends
19
 
20
  from deps import Session, err, perms, require_session
21
  from core import view_audit
@@ -1540,7 +1540,8 @@ def application_templates(session: Session = Depends(require_session)):
1540
 
1541
  @router.post("/nav/applications", status_code=201)
1542
  def create_nav_application(body: dict = Body(default=None),
1543
- session: Session = Depends(require_session)):
 
1544
  """Create one tenant Application from the caller's permission-filtered database schema.
1545
 
1546
  This is a thin nav/schema adapter over the existing Application registry writer. It does not
@@ -1564,15 +1565,21 @@ def create_nav_application(body: dict = Body(default=None),
1564
  application = application_registry.create(
1565
  session.runtime, session.tenant, session.uname, payload,
1566
  field_contracts={source: fields if isinstance(fields, list) else []} if source else {},
1567
- allowed_databases={source} if source else set())
 
1568
  except PermissionError as exc:
1569
  raise err(403, "forbidden", str(exc))
1570
  except application_registry.ApplicationExistsError as exc:
1571
- raise err(400, "app_exists", str(exc), {"existing": exc.existing})
1572
  except application_registry.ApplicationRuleError as exc:
1573
  raise err(400, exc.code, str(exc))
1574
  except application_registry.ApplicationError as exc:
1575
  raise err(400, "bad_application", str(exc))
1576
  except Exception:
1577
  raise err(503, "store_unavailable", "the Application was not saved.")
 
 
 
 
 
1578
  return {"application": application}
 
15
  import time
16
  from datetime import datetime, timezone
17
 
18
+ from fastapi import APIRouter, Body, Depends, Response
19
 
20
  from deps import Session, err, perms, require_session
21
  from core import view_audit
 
1540
 
1541
  @router.post("/nav/applications", status_code=201)
1542
  def create_nav_application(body: dict = Body(default=None),
1543
+ session: Session = Depends(require_session),
1544
+ response: Response = None):
1545
  """Create one tenant Application from the caller's permission-filtered database schema.
1546
 
1547
  This is a thin nav/schema adapter over the existing Application registry writer. It does not
 
1565
  application = application_registry.create(
1566
  session.runtime, session.tenant, session.uname, payload,
1567
  field_contracts={source: fields if isinstance(fields, list) else []} if source else {},
1568
+ allowed_databases={source} if source else set(),
1569
+ is_admin=bool(getattr(session, "admin", False)))
1570
  except PermissionError as exc:
1571
  raise err(403, "forbidden", str(exc))
1572
  except application_registry.ApplicationExistsError as exc:
1573
+ raise err(409, exc.code, str(exc))
1574
  except application_registry.ApplicationRuleError as exc:
1575
  raise err(400, exc.code, str(exc))
1576
  except application_registry.ApplicationError as exc:
1577
  raise err(400, "bad_application", str(exc))
1578
  except Exception:
1579
  raise err(503, "store_unavailable", "the Application was not saved.")
1580
+ if application.get("existing") is True:
1581
+ # A template App already in this tenant: answer it, so the client opens the one copy.
1582
+ if response is not None:
1583
+ response.status_code = 200
1584
+ return {"application": application, "existing": True}
1585
  return {"application": application}
api/routes_templates.py CHANGED
@@ -42,7 +42,7 @@ _TEMPLATE_CATEGORIES = {
42
  # C1 connector keys for a shipped Sheet descriptor's `source` (F25: Amazon is `amazon_sp` there).
43
  _SHEET_CONNECTORS = {"odoo": "odoo", "amazon_sp": "amazon"}
44
  # C1 fields each App row carries so the client can pick its screen and marks.
45
- _APP_WIRE_KEYS = ("view", "mark", "connector", "process", "purpose", "tags")
46
  _TEMPLATE_PREVIEW_LABELS = {**_TEMPLATE_CATEGORIES, "route": "Routing", "catalog": "Catalog",
47
  "competitor_watch": "Competitor watch"}
48
 
@@ -392,10 +392,11 @@ def _data_template_database(template, definitions):
392
 
393
 
394
  def _own_template_apps(session):
395
- """Return all owned copies per template, leaving every template available for creation."""
396
  import application_registry
397
  try:
398
- return application_registry.own_template_apps(session.runtime, session.uname)
 
399
  except Exception:
400
  return {}
401
 
@@ -522,7 +523,7 @@ def _module_templates(session):
522
  **{key: (app_templates.BY_KIND[row["kind"]] if key == "tags" else row).get(key)
523
  for key in _APP_WIRE_KEYS}}
524
  for row in application_templates(session=session)["templates"]]
525
- # Owned copies are optional links. They never replace the template's create action.
526
  owned = _own_template_apps(session)
527
  for row in app:
528
  row["existing"] = [_existing_app(held) for held in owned.get(row["key"], [])]
@@ -697,13 +698,18 @@ def _create_sourceless_app(payload, session):
697
  try:
698
  application = application_registry.create(
699
  session.runtime, session.tenant, session.uname, payload,
700
- field_contracts={}, allowed_databases=set())
 
701
  except PermissionError as exc:
702
  raise err(403, "forbidden", str(exc))
 
 
703
  except application_registry.ApplicationRuleError as exc:
704
  raise err(400, exc.code, str(exc))
705
  except application_registry.ApplicationError as exc:
706
  raise err(400, "bad_application", str(exc))
707
  except Exception:
708
  raise err(503, "store_unavailable", "the Application was not saved.")
 
 
709
  return {"application": application}
 
42
  # C1 connector keys for a shipped Sheet descriptor's `source` (F25: Amazon is `amazon_sp` there).
43
  _SHEET_CONNECTORS = {"odoo": "odoo", "amazon_sp": "amazon"}
44
  # C1 fields each App row carries so the client can pick its screen and marks.
45
+ _APP_WIRE_KEYS = ("view", "mark", "connector", "connectors", "process", "purpose", "tags")
46
  _TEMPLATE_PREVIEW_LABELS = {**_TEMPLATE_CATEGORIES, "route": "Routing", "catalog": "Catalog",
47
  "competitor_watch": "Competitor watch"}
48
 
 
392
 
393
 
394
  def _own_template_apps(session):
395
+ """Return the tenant's live template copies the caller may read, grouped per template."""
396
  import application_registry
397
  try:
398
+ return application_registry.own_template_apps(session.runtime, session.uname,
399
+ is_admin=bool(getattr(session, "admin", False)))
400
  except Exception:
401
  return {}
402
 
 
523
  **{key: (app_templates.BY_KIND[row["kind"]] if key == "tags" else row).get(key)
524
  for key in _APP_WIRE_KEYS}}
525
  for row in application_templates(session=session)["templates"]]
526
+ # A readable live copy marks the card Added and opens it. A second add answers that copy.
527
  owned = _own_template_apps(session)
528
  for row in app:
529
  row["existing"] = [_existing_app(held) for held in owned.get(row["key"], [])]
 
698
  try:
699
  application = application_registry.create(
700
  session.runtime, session.tenant, session.uname, payload,
701
+ field_contracts={}, allowed_databases=set(),
702
+ is_admin=bool(getattr(session, "admin", False)))
703
  except PermissionError as exc:
704
  raise err(403, "forbidden", str(exc))
705
+ except application_registry.ApplicationExistsError as exc:
706
+ raise err(409, exc.code, str(exc))
707
  except application_registry.ApplicationRuleError as exc:
708
  raise err(400, exc.code, str(exc))
709
  except application_registry.ApplicationError as exc:
710
  raise err(400, "bad_application", str(exc))
711
  except Exception:
712
  raise err(503, "store_unavailable", "the Application was not saved.")
713
+ if application.get("existing") is True:
714
+ return {"application": application, "existing": True}
715
  return {"application": application}
api/tool_groups/apps.py CHANGED
@@ -453,7 +453,12 @@ def apply_template(ctx, args):
453
  result = applications.create(
454
  session.runtime, session.tenant, session.uname, payload,
455
  allowed_databases=allowed, semantic_records=records,
456
- field_contracts=_fields(ctx, allowed), **attribution)
 
 
 
 
 
457
  if share is not None:
458
  result = applications.mutate(
459
  session.runtime, result["id"], session.uname, session.admin, {"share": share},
@@ -521,7 +526,7 @@ def save_code(ctx, args):
521
  allowed, records = _access(ctx, payload["compatibleDatabases"], strict=True)
522
  result = applications.create(
523
  session.runtime, session.tenant, session.uname, payload,
524
- allowed_databases=allowed, semantic_records=records, **attribution)
525
  if share is not None:
526
  result = applications.mutate(
527
  session.runtime, result["id"], session.uname, session.admin, {"share": share},
 
453
  result = applications.create(
454
  session.runtime, session.tenant, session.uname, payload,
455
  allowed_databases=allowed, semantic_records=records,
456
+ field_contracts=_fields(ctx, allowed), is_admin=session.admin, **attribution)
457
+ if result.get("existing") is True:
458
+ # One live copy per template App per tenant: answer that copy and leave its sharing alone.
459
+ answer = _result(result)
460
+ answer.update(existing=True, message="This App is already in this workspace. Nothing new was added.")
461
+ return answer
462
  if share is not None:
463
  result = applications.mutate(
464
  session.runtime, result["id"], session.uname, session.admin, {"share": share},
 
526
  allowed, records = _access(ctx, payload["compatibleDatabases"], strict=True)
527
  result = applications.create(
528
  session.runtime, session.tenant, session.uname, payload,
529
+ allowed_databases=allowed, semantic_records=records, is_admin=session.admin, **attribution)
530
  if share is not None:
531
  result = applications.mutate(
532
  session.runtime, result["id"], session.uname, session.admin, {"share": share},
platform/harness/mirror_store.py CHANGED
@@ -766,7 +766,7 @@ class MirrorStore:
766
  else:
767
  self._heal_published(con, result, log)
768
  with _CATCH_UP_LOCK:
769
- _catch_up_source(rt, self.connector)["pass_pending"] = True
770
  self.cache[cache_key] = result
771
  return result
772
  raw = rt.download_bytes(self.prefix + _MANIFEST_KEY)
@@ -806,10 +806,12 @@ class MirrorStore:
806
  newest = _record_newest(con, self.connector)
807
  with _CATCH_UP_LOCK:
808
  _catch_up_source(rt, self.connector).update(
809
- current=current, pass_pending=not current, newest=newest,
810
  **({"misses": 0, "behind": ""} if current else {}))
811
  except Exception as exc:
812
  result["state"] = "refused"
 
 
813
  message = (f"{self.label} mirror restore refused ({type(exc).__name__}); saved manifest, checksums, "
814
  "row counts and state must agree. Full first load required; check tenant-store access "
815
  "and the saved snapshot.")
@@ -1431,6 +1433,9 @@ def sync_mirror(connector, tenant_key, rt, *, report=None, log=print, before_pub
1431
  previous_pass, current_pass = _begin_snapshot_pass(store, tenant_key, rt) if odoo else (None, None)
1432
  restored = store.restore_mirror(tenant_key, rt, log=log)
1433
  if restored["state"] == "refused":
 
 
 
1434
  raise RuntimeError("The saved mirror could not be restored. Repair store access and restart.")
1435
  published, _path = store._connect(tenant_key, rt)
1436
  candidate = None
 
766
  else:
767
  self._heal_published(con, result, log)
768
  with _CATCH_UP_LOCK:
769
+ _catch_up_source(rt, self.connector).update(pass_pending=True, refused=False)
770
  self.cache[cache_key] = result
771
  return result
772
  raw = rt.download_bytes(self.prefix + _MANIFEST_KEY)
 
806
  newest = _record_newest(con, self.connector)
807
  with _CATCH_UP_LOCK:
808
  _catch_up_source(rt, self.connector).update(
809
+ current=current, pass_pending=not current, newest=newest, refused=False,
810
  **({"misses": 0, "behind": ""} if current else {}))
811
  except Exception as exc:
812
  result["state"] = "refused"
813
+ # A resource or I/O fault proves nothing about the snapshot, so the next sync pass retries.
814
+ result["retry"] = isinstance(exc, (OSError, datastore.duckdb.OperationalError))
815
  message = (f"{self.label} mirror restore refused ({type(exc).__name__}); saved manifest, checksums, "
816
  "row counts and state must agree. Full first load required; check tenant-store access "
817
  "and the saved snapshot.")
 
1433
  previous_pass, current_pass = _begin_snapshot_pass(store, tenant_key, rt) if odoo else (None, None)
1434
  restored = store.restore_mirror(tenant_key, rt, log=log)
1435
  if restored["state"] == "refused":
1436
+ if restored.get("retry"):
1437
+ store.cache.pop(store._mirror_cache_key(tenant_key, rt), None)
1438
+ raise RuntimeError("The saved mirror could not be restored. The next sync pass retries it.")
1439
  raise RuntimeError("The saved mirror could not be restored. Repair store access and restart.")
1440
  published, _path = store._connect(tenant_key, rt)
1441
  candidate = None
platform/harness/summary_tables.py CHANGED
@@ -53,6 +53,45 @@ def invalidate(con, source):
53
  con.execute(f"DELETE FROM {CATALOG} WHERE source=?", [source])
54
 
55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  def rebuild(con, source, manifest, tables):
57
  """Rebuild available declarations using SQL inside the caller's source install transaction."""
58
  invalidate(con, source)
@@ -62,11 +101,7 @@ def rebuild(con, source, manifest, tables):
62
  for table in sorted(tables):
63
  for group, expression, totals in _definitions(con, table):
64
  name = _name(source, table, group)
65
- projection = ", ".join(f"{sql} AS {_quote(slot)}" for sql, slot in totals.items())
66
- con.execute(f"CREATE TABLE {_quote(name)} AS SELECT {expression} AS _key, "
67
- f"GROUPING({expression}) AS _overall, count(*) AS _rows"
68
- f"{', ' + projection if projection else ''} FROM {_quote(table)} "
69
- f"GROUP BY GROUPING SETS (({expression}), ())")
70
  definition = json.dumps({"group": expression, "totals": totals}, sort_keys=True)
71
  con.execute(f"INSERT INTO {CATALOG} VALUES (?,?,?,?,?,?,?)",
72
  [source, table, group, tenant, snapshot, name, definition])
 
53
  con.execute(f"DELETE FROM {CATALOG} WHERE source=?", [source])
54
 
55
 
56
+ def _holistic(sql):
57
+ return bool(re.search(r"\bDISTINCT\b|\bquantile|\bmedian\b|\bmode\s*\(", sql, re.IGNORECASE))
58
+
59
+
60
+ def _build(con, name, table, expression, totals):
61
+ """One summary table: the plain totals in one pass, then each holistic total in its own pass."""
62
+ # Trap: one GROUP BY holding every DISTINCT and quantile state per group exceeds the sync
63
+ # worker's 4GB memory plus 4GB spill on a 3M-group table. Each holistic pass alone fits.
64
+ # Trap: one many-way join of the passes plans a near cross product on _overall inside the
65
+ # install transaction. Each pass joins the accumulated table on its own instead.
66
+ holistic = [(sql, slot) for sql, slot in totals.items() if _holistic(sql)]
67
+
68
+ def grouped(target, part, rows):
69
+ columns = "".join(f", {sql} AS {_quote(slot)}" for sql, slot in part)
70
+ con.execute(f"CREATE TABLE {_quote(target)} AS SELECT {expression} AS _key, "
71
+ f"GROUPING({expression}) AS _overall{', count(*) AS _rows' if rows else ''}"
72
+ f"{columns} FROM {_quote(table)} GROUP BY GROUPING SETS (({expression}), ())")
73
+
74
+ if not holistic:
75
+ grouped(name, totals.items(), True)
76
+ return
77
+ # The caller's transaction rolls these work tables back on failure.
78
+ accumulated = f"{name}_a0"
79
+ grouped(accumulated, [(sql, slot) for sql, slot in totals.items() if not _holistic(sql)], True)
80
+ for index, (sql, slot) in enumerate(holistic, 1):
81
+ part = f"{name}_p{index}"
82
+ grouped(part, [(sql, slot)], False)
83
+ if index == len(holistic):
84
+ target, select = name, "a._key, a._overall, a._rows" + "".join(
85
+ f", {'b' if other == slot else 'a'}.{_quote(other)}" for other in totals.values())
86
+ else:
87
+ target, select = f"{name}_a{index}", f"a.*, b.{_quote(slot)}"
88
+ con.execute(f"CREATE TABLE {_quote(target)} AS SELECT {select} FROM {_quote(accumulated)} a "
89
+ f"JOIN {_quote(part)} b ON b._overall = a._overall AND b._key IS NOT DISTINCT FROM a._key")
90
+ con.execute(f"DROP TABLE {_quote(part)}")
91
+ con.execute(f"DROP TABLE {_quote(accumulated)}")
92
+ accumulated = target
93
+
94
+
95
  def rebuild(con, source, manifest, tables):
96
  """Rebuild available declarations using SQL inside the caller's source install transaction."""
97
  invalidate(con, source)
 
101
  for table in sorted(tables):
102
  for group, expression, totals in _definitions(con, table):
103
  name = _name(source, table, group)
104
+ _build(con, name, table, expression, totals)
 
 
 
 
105
  definition = json.dumps({"group": expression, "totals": totals}, sort_keys=True)
106
  con.execute(f"INSERT INTO {CATALOG} VALUES (?,?,?,?,?,?,?)",
107
  [source, table, group, tenant, snapshot, name, definition])
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- c5fafed5f2c6b8c9cca254a28090ceb2b0ef72e52bfd3d7ef3124534fc3ad712
 
1
+ 705fbaa5d6b1c201070c0b8e88cd5bb1a0a32b369058d03bce150e62f8cfe8bb
web/src/home/HomePage.tsx CHANGED
@@ -1638,13 +1638,18 @@ export function HomeSurface({
1638
  const database = application.openTarget?.database
1639
  ?? application.compatibleDatabases?.[0]
1640
  ?? "";
 
 
1641
  return (
1642
  <ItemTileMenu key={application.id} id={application.id} kind="App" name={application.name}
1643
  canRename={application.capabilities?.edit === true}
1644
  canDelete={application.capabilities?.delete === true && !!onDeleteApplication}
1645
  busy={applicationBusy.has(application.id)}
1646
  onRename={onRenameApplication ? (name) => onRenameApplication(application, name) : undefined}
1647
- deleteConfirmation={onDeleteApplication ? (onCancel) => <AppDeleteDialog application={application}
 
 
 
1648
  onDelete={onDeleteApplication} onCancel={onCancel} /> : undefined}>
1649
  <a
1650
  className={"home-tile" + (mode === "app" ? " cg-view-row" + (selection.isSelected(application.id) ? " is-railsel" : "") : "")}
 
1638
  const database = application.openTarget?.database
1639
  ?? application.compatibleDatabases?.[0]
1640
  ?? "";
1641
+ // A template App is removed, not deleted: one live copy per workspace, re-added from Templates.
1642
+ const templatic = hasTemplateMark(application.templateKind);
1643
  return (
1644
  <ItemTileMenu key={application.id} id={application.id} kind="App" name={application.name}
1645
  canRename={application.capabilities?.edit === true}
1646
  canDelete={application.capabilities?.delete === true && !!onDeleteApplication}
1647
  busy={applicationBusy.has(application.id)}
1648
  onRename={onRenameApplication ? (name) => onRenameApplication(application, name) : undefined}
1649
+ remove={templatic}
1650
+ onDelete={onDeleteApplication && templatic
1651
+ ? () => onDeleteApplication(application, application.name) : undefined}
1652
+ deleteConfirmation={onDeleteApplication && !templatic ? (onCancel) => <AppDeleteDialog application={application}
1653
  onDelete={onDeleteApplication} onCancel={onCancel} /> : undefined}>
1654
  <a
1655
  className={"home-tile" + (mode === "app" ? " cg-view-row" + (selection.isSelected(application.id) ? " is-railsel" : "") : "")}
web/src/home/ItemTileMenu.tsx CHANGED
@@ -118,6 +118,8 @@ export interface ItemTileMenuProps {
118
  deleteBody?: ReactNode;
119
  prepareDelete?: () => Promise<ReactNode>;
120
  deleteConfirmation?: (onCancel: () => void) => ReactNode;
 
 
121
  children: ReactNode;
122
  }
123
 
@@ -163,7 +165,7 @@ function TileNameEditor({ tile, name, busy, onSave, onCancel }: {
163
  /** File rights come from the item's server response, independently of folder administration. */
164
  export default function ItemTileMenu({
165
  id, database, kind, name, canRename = false, canDelete = false, busy = false,
166
- onRename, onDelete, deleteBody, prepareDelete, deleteConfirmation, children,
167
  }: ItemTileMenuProps) {
168
  const tile = useRef<HTMLDivElement>(null);
169
  const trigger = useRef<HTMLButtonElement>(null);
@@ -263,12 +265,17 @@ export default function ItemTileMenu({
263
  <MenuLabel icon="rename" text="Rename" />
264
  </button> : null}
265
  {deleteAllowed ? <button type="button" role="menuitem" className="is-danger" onClick={() => open("delete")}>
266
- <MenuLabel icon="trash" text="Delete" />
267
  </button> : null}
268
  </AnchoredOverlay> : null}
269
  {surface === "rename" && renameAllowed ? <TileNameEditor tile={tile.current} name={name} busy={pending}
270
  onSave={save} onCancel={dismiss} /> : null}
271
- {surface === "delete" && deleteAllowed ? deleteConfirmation ? deleteConfirmation(dismiss) : <ConfirmDialog
 
 
 
 
 
272
  open title={`Delete ${kind}`} body={<><p>Delete “{name}”?</p>{preparedDeleteBody ?? deleteBody}
273
  {deleteError ? <p className="home-item-delete-error" role="alert">{deleteError}</p> : null}</>}
274
  confirmLabel={pending ? "Deleting…" : deleteError ? "Retry delete" : "Delete"}
 
118
  deleteBody?: ReactNode;
119
  prepareDelete?: () => Promise<ReactNode>;
120
  deleteConfirmation?: (onCancel: () => void) => ReactNode;
121
+ /** A template App leaves the workspace by Remove, never Delete: its data stays. */
122
+ remove?: boolean;
123
  children: ReactNode;
124
  }
125
 
 
165
  /** File rights come from the item's server response, independently of folder administration. */
166
  export default function ItemTileMenu({
167
  id, database, kind, name, canRename = false, canDelete = false, busy = false,
168
+ onRename, onDelete, deleteBody, prepareDelete, deleteConfirmation, remove = false, children,
169
  }: ItemTileMenuProps) {
170
  const tile = useRef<HTMLDivElement>(null);
171
  const trigger = useRef<HTMLButtonElement>(null);
 
265
  <MenuLabel icon="rename" text="Rename" />
266
  </button> : null}
267
  {deleteAllowed ? <button type="button" role="menuitem" className="is-danger" onClick={() => open("delete")}>
268
+ <MenuLabel icon="trash" text={remove ? "Remove" : "Delete"} />
269
  </button> : null}
270
  </AnchoredOverlay> : null}
271
  {surface === "rename" && renameAllowed ? <TileNameEditor tile={tile.current} name={name} busy={pending}
272
  onSave={save} onCancel={dismiss} /> : null}
273
+ {surface === "delete" && deleteAllowed && remove ? <ConfirmDialog
274
+ open title={`Remove ${name}?`} body={<><p>Its data stays. Add it again from Templates.</p>
275
+ {deleteError ? <p className="home-item-delete-error" role="alert">{deleteError}</p> : null}</>}
276
+ confirmLabel={pending ? "Removing…" : deleteError ? "Retry remove" : "Remove"}
277
+ tone="destructive" busy={pending} onCancel={dismiss} onConfirm={() => void save()} />
278
+ : surface === "delete" && deleteAllowed ? deleteConfirmation ? deleteConfirmation(dismiss) : <ConfirmDialog
279
  open title={`Delete ${kind}`} body={<><p>Delete “{name}”?</p>{preparedDeleteBody ?? deleteBody}
280
  {deleteError ? <p className="home-item-delete-error" role="alert">{deleteError}</p> : null}</>}
281
  confirmLabel={pending ? "Deleting…" : deleteError ? "Retry delete" : "Delete"}
web/src/home/TemplateGallery.tsx CHANGED
@@ -82,7 +82,8 @@ function ModuleGallery({ module, templates, loading, busy, onCreate, onNavigate,
82
  const { reason, actionLabel } = availability(template);
83
  const reasonId = id + "-reason-" + encodeURIComponent(template.key);
84
  const directoryApp = module === "app" && template.creationMode === "post";
85
- const address = directoryApp ? added?.[template.key] ?? ownedApps(template)[0]?.address ?? "" : "";
 
86
  const actionable = !!address || (template.creatable && (!directoryApp || !!onAdd));
87
  const working = busy === template.key;
88
  const name = plain(template.name);
 
82
  const { reason, actionLabel } = availability(template);
83
  const reasonId = id + "-reason-" + encodeURIComponent(template.key);
84
  const directoryApp = module === "app" && template.creationMode === "post";
85
+ // One live template App per workspace: a readable copy reads Added and opens, wizard kinds too.
86
+ const address = module === "app" ? added?.[template.key] ?? ownedApps(template)[0]?.address ?? "" : "";
87
  const actionable = !!address || (template.creatable && (!directoryApp || !!onAdd));
88
  const working = busy === template.key;
89
  const name = plain(template.name);
web/src/shell/Shell.tsx CHANGED
@@ -606,7 +606,8 @@ function ApplicationWizard({
606
  if (!response.ok || !body?.application?.id) {
607
  throw new Error(applicationRefusal(body));
608
  }
609
- if (shareEntries.length > 0) {
 
610
  try {
611
  // ⛔⛔ FIXED AT THE WAVE-59 COMBINE: this PATCHed `/nav/applications/{id}`, and NO
612
  // SUCH ROUTE EXISTS -- `routes_nav.py` mounts only `POST /nav/applications`. Every
@@ -1584,8 +1585,8 @@ function readNavFold(): NavFold {
1584
  }
1585
  }
1586
 
1587
- function AuthenticatedBell({ modules, frozen, onOpenView }: {
1588
- modules: AlertModule[]; frozen: boolean; onOpenView: (database: string, view: string) => void;
1589
  }) {
1590
  const [inbox, setInbox] = useState<BellInbox>(emptyBellInbox);
1591
  const [alertsOpen, setAlertsOpen] = useState(false);
@@ -1684,7 +1685,8 @@ function AuthenticatedBell({ modules, frozen, onOpenView }: {
1684
  }
1685
  };
1686
  return <>
1687
- <button type="button" className="shell-nav-item shell-bell" aria-label={inbox.unread ? `Alerts, ${inbox.unread} unread` : "Alerts"}
 
1688
  aria-haspopup="dialog" aria-expanded={alertsOpen} aria-controls={alertsOpen ? "shell-alerts" : undefined}
1689
  onClick={(event) => { event.currentTarget.focus(); setAlertsOpen((current) => !current); void load(); }}>
1690
  <Bell {...NAV_GLYPH} weight="regular" /><span className="shell-nav-label">Alerts{inbox.unread ? ` (${inbox.unread})` : ""}</span>
@@ -3720,7 +3722,7 @@ function ShellFrame() {
3720
  </a>
3721
 
3722
  <AuthenticatedBell key={JSON.stringify([session.user.tenant, session.user.username])}
3723
- modules={alertsModules} frozen={freezeNotice.enabled} onOpenView={openViewInDatabase} />
3724
  <div
3725
  className="shell-side-bottom"
3726
  // Collapsed, the 56px strip cannot hold the account POPOVER — so the row's one
 
606
  if (!response.ok || !body?.application?.id) {
607
  throw new Error(applicationRefusal(body));
608
  }
609
+ // An existing template App answers the add: its share belongs to its owner, never this wizard.
610
+ if (shareEntries.length > 0 && !body.existing) {
611
  try {
612
  // ⛔⛔ FIXED AT THE WAVE-59 COMBINE: this PATCHed `/nav/applications/{id}`, and NO
613
  // SUCH ROUTE EXISTS -- `routes_nav.py` mounts only `POST /nav/applications`. Every
 
1585
  }
1586
  }
1587
 
1588
+ function AuthenticatedBell({ modules, frozen, railHidden, onOpenView }: {
1589
+ modules: AlertModule[]; frozen: boolean; railHidden: boolean; onOpenView: (database: string, view: string) => void;
1590
  }) {
1591
  const [inbox, setInbox] = useState<BellInbox>(emptyBellInbox);
1592
  const [alertsOpen, setAlertsOpen] = useState(false);
 
1685
  }
1686
  };
1687
  return <>
1688
+ {/* Hidden with Templates and Connectors while /nav loads, so the rail paints once. */}
1689
+ <button type="button" className="shell-nav-item shell-bell" hidden={railHidden} aria-label={inbox.unread ? `Alerts, ${inbox.unread} unread` : "Alerts"}
1690
  aria-haspopup="dialog" aria-expanded={alertsOpen} aria-controls={alertsOpen ? "shell-alerts" : undefined}
1691
  onClick={(event) => { event.currentTarget.focus(); setAlertsOpen((current) => !current); void load(); }}>
1692
  <Bell {...NAV_GLYPH} weight="regular" /><span className="shell-nav-label">Alerts{inbox.unread ? ` (${inbox.unread})` : ""}</span>
 
3722
  </a>
3723
 
3724
  <AuthenticatedBell key={JSON.stringify([session.user.tenant, session.user.username])}
3725
+ modules={alertsModules} frozen={freezeNotice.enabled} railHidden={railLoading} onOpenView={openViewInDatabase} />
3726
  <div
3727
  className="shell-side-bottom"
3728
  // Collapsed, the 56px strip cannot hold the account POPOVER — so the row's one
web/src/styles/sdlc76/alerts.css CHANGED
@@ -3,6 +3,11 @@
3
  width: calc(100% - 16px);
4
  }
5
 
 
 
 
 
 
6
  .shell-root:has(.cg-agent-panel) .shell-side .shell-bell.shell-nav-item,
7
  .shell-side.is-collapsed .shell-bell.shell-nav-item {
8
  margin: 0 6px 2px;
 
3
  width: calc(100% - 16px);
4
  }
5
 
6
+ /* The rail paints once: the bell waits with Templates and Connectors while /nav loads. */
7
+ .shell-bell.shell-nav-item[hidden] {
8
+ display: none;
9
+ }
10
+
11
  .shell-root:has(.cg-agent-panel) .shell-side .shell-bell.shell-nav-item,
12
  .shell-side.is-collapsed .shell-bell.shell-nav-item {
13
  margin: 0 6px 2px;
web/src/styles/wave58/app-data.css CHANGED
@@ -57,6 +57,8 @@
57
  .home-app-delete-body {
58
  display: grid;
59
  gap: 8px;
 
 
60
  }
61
 
62
  .home-app-delete-body p {
@@ -71,6 +73,7 @@
71
  .home-app-delete-input {
72
  box-sizing: border-box;
73
  width: 100%;
 
74
  min-width: 0;
75
  min-height: 30px;
76
  border: 1px solid var(--lp-line);
 
57
  .home-app-delete-body {
58
  display: grid;
59
  gap: 8px;
60
+ /* The body fills the one dialog box (R36): rows pack at the top instead of stretching. */
61
+ align-content: start;
62
  }
63
 
64
  .home-app-delete-body p {
 
73
  .home-app-delete-input {
74
  box-sizing: border-box;
75
  width: 100%;
76
+ max-width: 420px;
77
  min-width: 0;
78
  min-height: 30px;
79
  border: 1px solid var(--lp-line);