The core speaks English only; every other language is a kind: "translation" plugin
(translation-<lang>; the French one is translation-fr in ai-agent-plugins, seeded once at start).
- plugins: kind translation (typed_manifest.parse_translation: lang, name, englishName, flag,
locale, promptLine, ui/backend JSON dictionaries — strict, operator-only, in the fingerprint);
a top-level "languages" field on any plugin (default ["en"]) shown on its page; seeding takes
translation-*; plugins/translations.py reads the enabled ones (first by id wins a code).
- core/i18n: tr / langs / localized / clean_pref / effective_lang read the installed
translations; a pick whose translation is gone reads English and is kept; browserLang records
any base code. core/i18n_fr.py and FRENCH_LINE are gone (language_line = the plugin's promptLine).
- The owner picks a language too (users.json ownerLang, PUT /api/me {lang}; English by default).
- Public GET /api/i18n/languages and /api/i18n/{lang} (ETag/304), guest host and sign-in included.
- Coverage: backend/core/i18n_keys/{ui,backend}.json (kept by the two i18n tests,
UPDATE_I18N_KEYS=1); a translation's page shows translated / missing / stale / placeholder
mismatches.
- Frontend: frontend/src/i18n/fr removed; the dictionary comes from the hub, cached in
localStorage and revalidated in the background (first boot in a language waits <= 4 s, any
failure is English); Lang is a string; number/currency style from the translation's locale;
LanguageSelect lists English + installed translations (hidden when none); Settings → Plugins
has a Translations kind (tab, catalog filter, group) and a Translation section with the
missing-strings count; mock is English only.
- Tests: test_i18n.py rewritten on a made-up translation; i18n_testkit.speaking() for the
tests that need a second language. authz golden, openapi.json + src/generated regenerated;
docs/plugins.md (Translations), CLAUDE.md, i18n README, docs/settings.md.
Changelog
- Added: languages are plugins — Settings → Plugins → Translations; the owner can pick a language.
- Changed: French moved to the translation-fr plugin (seeded at start: nothing changes for guests).
- Removed: the core's built-in French dictionaries.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1082 lines
61 KiB
Python
1082 lines
61 KiB
Python
"""Guests (users/): the login lifecycle, the gate's caller resolution and
|
|
default-deny route table, the per-conversation filters, the server-pinned
|
|
spawn, sharing, per-user ui-state, the SSE filter and the author tag.
|
|
|
|
Imports ``main`` against throwaway paths (no startup event → no threads)."""
|
|
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
|
|
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
|
|
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
|
|
"PROFILES_PATH": TMP / "profiles.json",
|
|
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
|
|
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
|
|
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
|
|
"NOTIF_READ_PATH": TMP / "nr.json",
|
|
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
|
|
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"PROJECTS_DIR": TMP / "projects",
|
|
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
|
|
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ[k] = str(v)
|
|
(TMP / "projects" / "film").mkdir(parents=True)
|
|
(TMP / "projects" / "other").mkdir(parents=True)
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
import conversations.routes as conv_routes # noqa: E402
|
|
import runs.routes as run_routes # noqa: E402
|
|
import users.routes as user_routes # noqa: E402
|
|
from conversations.parse import _split_author # noqa: E402
|
|
from conversations.tree import _conv_id # noqa: E402
|
|
from core.routes import _guest_filter # noqa: E402
|
|
from notifications.service import _flat_notifications # noqa: E402
|
|
from users import access, mailer # noqa: E402
|
|
from users.caller import OWNER, SESSION_COOKIE, guest_from_record # noqa: E402
|
|
from users.runs import author_tag, check_model # noqa: E402
|
|
from users.store import DEFAULT_GUEST_SHORTCUTS, DEFAULT_SHARED_SKILLS # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
OWNER_H = {"X-Internal-Auth": "tok"}
|
|
|
|
|
|
def _card(sid, **meta):
|
|
return {"sessionId": sid, "endedAt": "2026-10-10T00:00:00Z", "cost": 1.0,
|
|
"meta": {"archived": False, **meta}}
|
|
|
|
|
|
class Guests(unittest.TestCase):
|
|
def setUp(self):
|
|
for u in DEPS.users.all():
|
|
DEPS.users.delete(u["id"])
|
|
self.dom = DEPS.users.create("Dom@Example.com", "Dom",
|
|
projects={"film": "chat"},
|
|
models=["sonnet", "haiku"])
|
|
self.claire = DEPS.users.create("claire@example.com", "Claire",
|
|
projects={"film": "view"})
|
|
self.c = TestClient(main.app)
|
|
self.dom_cookie = DEPS.auth.open_session(self.dom["id"])
|
|
DEPS.users.set_defaults({"sharedSkills": list(DEFAULT_SHARED_SKILLS)})
|
|
DEPS.ui_state.delete(f"u.{self.dom['id']}.ai-agent-settings")
|
|
# Sign-in mails leave off the request thread; inline here. And no
|
|
# earlier test's wrong codes, mails or locks carry over.
|
|
self.addCleanup(setattr, user_routes, "_background", user_routes._background)
|
|
user_routes._background = lambda fn, *a: fn(*a)
|
|
user_routes._BAD_CODES = None
|
|
user_routes._link_sent.clear()
|
|
user_routes._link_sent_to.clear()
|
|
with DEPS.auth._lock:
|
|
DEPS.auth._data["links"].clear()
|
|
DEPS.auth._data.pop("codeMisses", None)
|
|
|
|
def mails(self):
|
|
"""Capture the sign-in mails: ``[(url, code)]``."""
|
|
sent = []
|
|
orig_enabled, orig_mail = mailer.enabled, mailer.login_mail
|
|
mailer.enabled = lambda: True
|
|
mailer.login_mail = lambda to, name, url, minutes, lang="en", code="": \
|
|
sent.append((url, code))
|
|
self.addCleanup(setattr, mailer, "enabled", orig_enabled)
|
|
self.addCleanup(setattr, mailer, "login_mail", orig_mail)
|
|
return sent
|
|
|
|
def guest(self, cookie=None, host="claude.example.test"):
|
|
c = TestClient(main.app, base_url=f"https://{host}")
|
|
c.cookies.set(SESSION_COOKIE, cookie or self.dom_cookie)
|
|
return c
|
|
|
|
# ── store + login ────────────────────────────────────────────────────────
|
|
def test_login_link_is_single_use_and_opens_a_session(self):
|
|
token = DEPS.auth.mint_link(self.dom["id"])
|
|
c = TestClient(main.app, base_url="https://claude.example.test")
|
|
r = c.post("/api/auth/login", json={"token": token})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["id"], self.dom["id"])
|
|
self.assertIn(SESSION_COOKIE, r.cookies)
|
|
self.assertEqual(c.get("/api/me").json()["role"], "guest")
|
|
again = TestClient(main.app, base_url="https://claude.example.test")
|
|
self.assertEqual(again.post("/api/auth/login",
|
|
json={"token": token}).status_code, 401)
|
|
|
|
def test_sign_in_code_opens_a_session_once_and_spends_the_link(self):
|
|
token, code = DEPS.auth.mint_login(self.dom["id"])
|
|
self.assertRegex(code, r"^\d{6}$")
|
|
c = TestClient(main.app, base_url="https://claude.example.test")
|
|
spaced = f"{code[:3]} {code[3:]}" # as the mail shows it, or a paste
|
|
r = c.post("/api/auth/login", json={"email": "DOM@example.com", "code": spaced})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(c.get("/api/me").json()["id"], self.dom["id"])
|
|
again = TestClient(main.app, base_url="https://claude.example.test")
|
|
self.assertEqual(again.post("/api/auth/login", json={"email": "dom@example.com",
|
|
"code": code}).status_code, 401)
|
|
self.assertIsNone(DEPS.auth.consume_link(token)) # the link went with it
|
|
|
|
def test_sign_in_code_stops_after_five_wrong_tries(self):
|
|
token, code = DEPS.auth.mint_login(self.dom["id"])
|
|
wrong = f"{(int(code) + 1) % 10 ** 6:06d}"
|
|
c = TestClient(main.app, base_url="https://claude.example.test")
|
|
for _ in range(5):
|
|
r = c.post("/api/auth/login", json={"email": "dom@example.com", "code": wrong})
|
|
self.assertEqual(r.status_code, 401)
|
|
self.assertEqual(r.json()["detail"]["kind"], "code_invalid")
|
|
self.assertEqual(c.post("/api/auth/login", json={"email": "dom@example.com",
|
|
"code": code}).status_code, 401)
|
|
# the link itself is a long secret: it still works
|
|
self.assertEqual(DEPS.auth.consume_link(token), self.dom["id"])
|
|
|
|
def test_wrong_codes_have_a_daily_ceiling_per_address(self):
|
|
"""Five tries per mail were 150 guesses an hour for whoever kept
|
|
asking for mails: ten wrong codes in a day and the address's codes
|
|
stop — refused, and no longer mailed. The link still signs in."""
|
|
from users.store import CODE_MISSES_MAX
|
|
sent = self.mails()
|
|
c = TestClient(main.app, base_url="https://claude.example.test")
|
|
uid = self.dom["id"]
|
|
for n in range(CODE_MISSES_MAX):
|
|
if n % 4 == 0: # a fresh mail, a fresh code
|
|
_, code = DEPS.auth.mint_login(uid)
|
|
self.assertFalse(DEPS.auth.codes_locked(uid))
|
|
wrong = f"{(int(code) + 1) % 10 ** 6:06d}"
|
|
self.assertEqual(c.post("/api/auth/login", json={"email": "dom@example.com",
|
|
"code": wrong}).status_code, 401)
|
|
self.assertTrue(DEPS.auth.codes_locked(uid))
|
|
# the right code of a live mail is refused too…
|
|
r = c.post("/api/auth/login", json={"email": "dom@example.com", "code": code})
|
|
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (401, "code_invalid"))
|
|
# …and the next mail carries the link alone, which works.
|
|
with DEPS.auth._lock:
|
|
DEPS.auth._data["links"].clear() # past the cooldown
|
|
self.assertEqual(c.post("/api/auth/request-link",
|
|
json={"email": "dom@example.com"}).json(), {"ok": True})
|
|
(url, mailed_code), = sent
|
|
self.assertEqual(mailed_code, "")
|
|
r = c.post("/api/auth/login", json={"token": url.split("token=")[1]})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
# Claire's codes are untouched by Dom's misses.
|
|
_, code = DEPS.auth.mint_login(self.claire["id"])
|
|
self.assertEqual(c.post("/api/auth/login", json={"email": "claire@example.com",
|
|
"code": code}).status_code, 200)
|
|
# A day later Dom's codes work again.
|
|
with DEPS.auth._lock:
|
|
DEPS.auth._data["codeMisses"][uid] = [
|
|
t - 25 * 3600 for t in DEPS.auth._data["codeMisses"][uid]]
|
|
self.assertFalse(DEPS.auth.codes_locked(uid))
|
|
self.assertRegex(DEPS.auth.mint_login(uid)[1], r"^\d{6}$")
|
|
|
|
def test_an_address_guessing_codes_is_locked_out(self):
|
|
"""Wrong codes are counted per IP too, whoever's they are: 20 in ten
|
|
minutes and that address gets no further guess for an hour."""
|
|
import workers.guests as wg
|
|
from unittest import mock
|
|
kinds = []
|
|
rec = mock.patch.object(user_routes.security, "record",
|
|
lambda deps, kind, **kw: kinds.append(kind))
|
|
rec.start()
|
|
self.addCleanup(rec.stop)
|
|
c = TestClient(main.app, base_url="https://claude.example.test")
|
|
for n in range(wg.BadTokens.LIMIT):
|
|
self.assertEqual(c.post("/api/auth/login", json={
|
|
"email": f"nobody{n}@example.com", "code": "123456"}).status_code, 401)
|
|
self.assertTrue(user_routes._bad_codes().locked("testclient"))
|
|
_, code = DEPS.auth.mint_login(self.dom["id"])
|
|
r = c.post("/api/auth/login", json={"email": "dom@example.com", "code": code})
|
|
self.assertEqual(r.status_code, 401) # locked: not even looked at
|
|
token = DEPS.auth.mint_link(self.dom["id"]) # the link is not a guess
|
|
self.assertEqual(c.post("/api/auth/login", json={"token": token}).status_code, 200)
|
|
self.assertEqual(kinds.count("ip_locked"), 1)
|
|
self.assertEqual(kinds.count("code_failed"), wg.BadTokens.LIMIT)
|
|
|
|
def test_one_address_cannot_use_up_the_hours_sign_in_mails(self):
|
|
sent = self.mails()
|
|
c = TestClient(main.app, base_url="https://claude.example.test")
|
|
for _ in range(user_routes.LINK_MAILS_PER_USER_HOUR + 3):
|
|
with DEPS.auth._lock:
|
|
DEPS.auth._data["links"].clear() # past the per-address cooldown
|
|
c.post("/api/auth/request-link", json={"email": "dom@example.com"})
|
|
self.assertEqual(len(sent), user_routes.LINK_MAILS_PER_USER_HOUR)
|
|
c.post("/api/auth/request-link", json={"email": "claire@example.com"})
|
|
self.assertEqual(len(sent), user_routes.LINK_MAILS_PER_USER_HOUR + 1)
|
|
|
|
def test_the_sign_in_mail_leaves_off_the_request(self):
|
|
"""How long request-link takes must not tell a guest's address from
|
|
an unknown one: nothing is minted or mailed before it answers."""
|
|
sent = self.mails()
|
|
later = []
|
|
user_routes._background = lambda fn, *a: later.append((fn, a))
|
|
c = TestClient(main.app, base_url="https://claude.example.test")
|
|
self.assertEqual(c.post("/api/auth/request-link",
|
|
json={"email": "dom@example.com"}).json(), {"ok": True})
|
|
self.assertEqual(sent, [])
|
|
self.assertEqual(DEPS.auth.last_link_at(self.dom["id"]), 0.0)
|
|
(fn, a), = later
|
|
fn(*a)
|
|
self.assertEqual(len(sent), 1)
|
|
|
|
def test_sign_in_code_is_bound_to_its_address(self):
|
|
_, code = DEPS.auth.mint_login(self.dom["id"])
|
|
c = TestClient(main.app, base_url="https://claude.example.test")
|
|
for email in ("claire@example.com", "nobody@example.com", ""):
|
|
self.assertEqual(c.post("/api/auth/login", json={"email": email, "code": code})
|
|
.status_code, 401)
|
|
self.assertEqual(c.post("/api/auth/login", json={"email": "dom@example.com",
|
|
"code": code}).status_code, 200)
|
|
|
|
def test_sign_in_mail_carries_the_code_and_lands_on_the_asking_host(self):
|
|
with DEPS.auth._lock: # no earlier test's link holds the cooldown
|
|
DEPS.auth._data["links"].clear()
|
|
sent = []
|
|
orig_enabled, orig_mail = mailer.enabled, mailer.login_mail
|
|
mailer.enabled = lambda: True
|
|
mailer.login_mail = lambda to, name, url, minutes, lang="en", code="": \
|
|
sent.append((url, code))
|
|
self.addCleanup(setattr, mailer, "enabled", orig_enabled)
|
|
self.addCleanup(setattr, mailer, "login_mail", orig_mail)
|
|
c = TestClient(main.app, base_url="https://claude.example.test")
|
|
self.assertEqual(c.post("/api/auth/request-link",
|
|
json={"email": "dom@example.com"}).status_code, 200)
|
|
(url, code), = sent
|
|
self.assertTrue(url.startswith("https://claude.example.test/login?token="), url)
|
|
self.assertRegex(code, r"^\d{6}$")
|
|
self.assertEqual(c.post("/api/auth/login", json={"email": "dom@example.com",
|
|
"code": code}).status_code, 200)
|
|
|
|
def test_owner_can_mail_the_new_address(self):
|
|
sent = []
|
|
orig_enabled, orig_mail = mailer.enabled, mailer.send
|
|
mailer.enabled = lambda: True
|
|
mailer.send = lambda to, subject, text, html=None: sent.append((to, subject, text))
|
|
self.addCleanup(setattr, mailer, "enabled", orig_enabled)
|
|
self.addCleanup(setattr, mailer, "send", orig_mail)
|
|
from i18n_testkit import speaking, wrap
|
|
with speaking("fr"): # Dom reads a language a translation is installed for
|
|
DEPS.users.update(self.dom["id"], {"lang": "fr"})
|
|
r = self.c.post(f"/api/users/{self.dom['id']}/login-link",
|
|
json={"send": True, "mail": "moved"}, headers=OWNER_H)
|
|
DEPS.users.update(self.dom["id"], {"lang": "auto"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertTrue(r.json()["sent"])
|
|
(to, subject, text), = sent
|
|
self.assertEqual(to, "dom@example.com")
|
|
self.assertTrue(subject.startswith("⟦"), subject)
|
|
self.assertIn(r.json()["url"], text)
|
|
self.assertIn(wrap("Hi {name},").format(name="Dom"), text)
|
|
token = r.json()["url"].split("token=")[1]
|
|
self.assertEqual(DEPS.auth.consume_link(token), self.dom["id"])
|
|
|
|
def test_owner_links_are_invitations(self):
|
|
# Copied / mailed by the owner: lives for days, still single-use; the
|
|
# login page's own link stays a quarter-hour one.
|
|
from users.store import INVITE_TTL_S, LINK_TTL_S
|
|
r = self.c.post(f"/api/users/{self.dom['id']}/login-link", json={"send": False},
|
|
headers=OWNER_H)
|
|
self.assertEqual(r.json()["expiresInS"], INVITE_TTL_S)
|
|
self.assertGreater(INVITE_TTL_S, LINK_TTL_S)
|
|
token = r.json()["url"].split("token=")[1]
|
|
self.assertEqual(DEPS.auth.consume_link(token), self.dom["id"])
|
|
self.assertIsNone(DEPS.auth.consume_link(token))
|
|
|
|
def test_signed_in_guest_can_still_use_sign_in_links(self):
|
|
# Dom's first sign-in worked but the page hung; every later attempt
|
|
# carried the live cookie and the gate refused /api/auth/* (403).
|
|
g = self.guest()
|
|
h = {"Origin": "https://claude.example.test"}
|
|
self.assertEqual(g.post("/api/auth/request-link", json={"email": "x@y.z"},
|
|
headers=h).status_code, 200)
|
|
token = DEPS.auth.mint_link(self.dom["id"])
|
|
r = g.post("/api/auth/login", json={"token": token}, headers=h)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
# the old session gave way to the new one
|
|
self.assertIsNone(DEPS.auth.session_user(self.dom_cookie))
|
|
self.assertEqual(g.post("/api/auth/login", json={"token": token},
|
|
headers=h).status_code, 401) # spent
|
|
|
|
def test_disabled_user_loses_the_session(self):
|
|
DEPS.users.update(self.dom["id"], {"disabled": True})
|
|
r = self.guest().get("/api/me")
|
|
self.assertEqual(r.status_code, 401) # guest surface, no valid session
|
|
|
|
def test_auto_fresh_is_on_for_a_guest_until_turned_off(self):
|
|
g = self.guest()
|
|
h = {"Origin": "https://claude.example.test"}
|
|
self.assertIs(g.get("/api/me").json()["autoFresh"], True)
|
|
r = g.put("/api/me", json={"autoFresh": False}, headers=h)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertIs(r.json()["autoFresh"], False)
|
|
self.assertIs(DEPS.users.get(self.dom["id"])["autoFresh"], False)
|
|
# The owner sees it on the guest's page, and can flip it back.
|
|
r = self.c.put(f"/api/users/{self.dom['id']}", json={"autoFresh": True}, headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertIs(r.json()["autoFresh"], True)
|
|
self.assertIs(g.get("/api/me").json()["autoFresh"], True)
|
|
|
|
def test_request_link_never_reveals_who_exists(self):
|
|
c = TestClient(main.app, base_url="https://claude.example.test")
|
|
for e in ("dom@example.com", "nobody@example.com"):
|
|
self.assertEqual(c.post("/api/auth/request-link",
|
|
json={"email": e}).json(), {"ok": True})
|
|
|
|
# ── the gate ─────────────────────────────────────────────────────────────
|
|
def test_owner_paths_unchanged(self):
|
|
r = self.c.get("/api/me", headers=OWNER_H)
|
|
self.assertEqual(r.json()["role"], "owner")
|
|
self.assertEqual(self.c.get("/api/me").status_code, 403) # untrusted ip
|
|
|
|
def test_guest_surface_is_never_owner(self):
|
|
c = TestClient(main.app, base_url="https://claude.example.test")
|
|
r = c.get("/api/me", headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 401)
|
|
self.assertEqual(r.json()["detail"]["kind"], "login_required")
|
|
# …under any spelling Traefik's Host() rule also matches
|
|
for host in ("claude.example.test.", "CLAUDE.example.test..",
|
|
"claude.example.test.:443"):
|
|
r = c.get("/api/me", headers={**OWNER_H, "Host": host})
|
|
self.assertEqual(r.status_code, 401, host)
|
|
|
|
def test_traefik_without_authelia_is_anonymous(self):
|
|
"""Through Traefik, only Authelia's Remote-User makes the owner: a
|
|
request the guest router let through (it strips the header) is never
|
|
the owner, whatever Host it names."""
|
|
from core import auth
|
|
edge = frozenset({"testclient"})
|
|
orig = auth._resolved
|
|
auth._resolved = lambda: (edge, edge)
|
|
self.addCleanup(setattr, auth, "_resolved", orig)
|
|
c = TestClient(main.app, base_url="https://admin.example.test")
|
|
r = c.get("/api/me")
|
|
self.assertEqual(r.status_code, 401)
|
|
self.assertEqual(r.json()["detail"]["kind"], "login_required")
|
|
self.assertEqual(c.post("/api/spawn", json={"prompt": "x"}).status_code, 401)
|
|
r = c.get("/api/me", headers={"Remote-User": "gabrielvidal"})
|
|
self.assertEqual(r.json()["role"], "owner")
|
|
# a guest's session decides on its own on the guest host — and is
|
|
# ignored anywhere else (a cookie planted from a sibling site), unless
|
|
# it is the owner's impersonation; logging in still works
|
|
self.assertEqual(self.guest().get("/api/me").json()["role"], "guest")
|
|
self.assertEqual(self.guest(host="admin.example.test").get("/api/me")
|
|
.status_code, 401)
|
|
imp = DEPS.auth.open_session(self.dom["id"], impersonator="owner")
|
|
self.assertTrue(self.guest(imp, host="admin.example.test").get("/api/me")
|
|
.json()["impersonating"])
|
|
self.assertNotEqual(c.post("/api/auth/request-link",
|
|
json={"email": "x@example.com"}).status_code, 401)
|
|
|
|
def test_guest_default_deny(self):
|
|
g = self.guest()
|
|
for path in ("/api/users", "/api/cron", "/api/accounts",
|
|
"/api/workers", "/api/skills", "/api/plugins/services-index",
|
|
"/api/project-merges", "/api/notifications/unread"):
|
|
self.assertEqual(g.get(path).status_code, 403, path)
|
|
|
|
def test_guest_cross_site_post_refused(self):
|
|
g = self.guest()
|
|
r = g.post("/api/interrupt", json={"sessionId": "x"},
|
|
headers={"Origin": "https://evil.example"})
|
|
self.assertEqual(r.status_code, 403)
|
|
|
|
def test_me_lists_grants(self):
|
|
me = self.guest().get("/api/me").json()
|
|
self.assertEqual(me["projects"], [{"slug": "film", "level": "chat"}])
|
|
self.assertEqual(me["surface"], "guest")
|
|
|
|
# ── filtering ────────────────────────────────────────────────────────────
|
|
def test_conversation_list_is_own_plus_shared(self):
|
|
cards = [_card("a" * 8, owner=self.dom["id"]),
|
|
_card("b" * 8),
|
|
_card("c" * 8, participants=[self.dom["id"]]),
|
|
_card("d" * 8, owner=self.claire["id"])]
|
|
orig = conv_routes._conversation_cards
|
|
conv_routes._conversation_cards = lambda deps, full: cards
|
|
try:
|
|
got = {c["sessionId"] for c in
|
|
self.guest().get("/api/conversations").json()["conversations"]}
|
|
every = self.c.get("/api/conversations", headers=OWNER_H).json()
|
|
finally:
|
|
conv_routes._conversation_cards = orig
|
|
self.assertEqual(got, {"a" * 8, "c" * 8})
|
|
self.assertEqual(every["count"], 4)
|
|
|
|
def test_cards_carry_owner_and_participants(self):
|
|
# The list filter reads the card's meta: _conv_meta must pass both
|
|
# through (it once rebuilt meta from a fixed key list and dropped them).
|
|
from conversations.cards import _conv_meta
|
|
DEPS.meta_store.update("s-card", {"owner": "dom", "participants": ["claire"]})
|
|
m = _conv_meta(DEPS, {"sessionId": "s-card"})
|
|
self.assertEqual((m["owner"], m["participants"]), ("dom", ["claire"]))
|
|
|
|
def test_unseen_conversation_is_404(self):
|
|
DEPS.meta_store.update("s-other", {"owner": self.claire["id"]})
|
|
r = self.guest().get("/api/conversation?id=-x/s-other.jsonl")
|
|
self.assertEqual(r.status_code, 404)
|
|
|
|
def test_every_route_reaches_its_own_handler(self):
|
|
# A route decorator once slipped onto a helper above the real handler,
|
|
# which then shadowed /api/conversation-commits for everyone.
|
|
for r in main.app.routes:
|
|
ep = getattr(r, "endpoint", None)
|
|
if getattr(r, "path", "").startswith("/api/") and ep is not None:
|
|
self.assertFalse(ep.__name__.startswith("_"), r.path)
|
|
r = self.c.get("/api/conversation-commits?id=-x/nope.jsonl", headers=OWNER_H)
|
|
self.assertNotEqual(r.status_code, 422, r.text)
|
|
|
|
def test_projects_scoped_to_grants(self):
|
|
r = self.guest().get("/api/project?slug=other")
|
|
self.assertEqual(r.status_code, 404)
|
|
|
|
def test_guest_ui_state_has_a_size_ceiling(self):
|
|
"""The store is one file, rewritten on every write (the owner's too)
|
|
and backed up daily: a guest's namespace holds only so much."""
|
|
import settings.routes as sr
|
|
g = self.guest()
|
|
self.addCleanup(DEPS.ui_state.delete_prefix, f"u.{self.dom['id']}.")
|
|
ok = "x" * 1000
|
|
self.assertEqual(g.put("/api/ui-state/ai-agent-store", json={"value": ok})
|
|
.status_code, 200)
|
|
big = "x" * (sr.GUEST_VALUE_MAX + 1)
|
|
self.assertEqual(g.put("/api/ui-state/ai-agent-store", json={"value": big})
|
|
.status_code, 413)
|
|
self.assertEqual(DEPS.ui_state.get(f"u.{self.dom['id']}.ai-agent-store"), ok)
|
|
# all their keys together
|
|
half = "x" * (sr.GUEST_TOTAL_MAX // 2 - 100)
|
|
self.assertEqual(g.put("/api/ui-state/a", json={"value": half}).status_code, 200)
|
|
self.assertEqual(g.put("/api/ui-state/b", json={"value": half}).status_code, 413)
|
|
self.assertEqual(g.put("/api/ui-state/a", json={"value": half}).status_code, 200) # a rewrite fits
|
|
# and how many
|
|
DEPS.ui_state.delete_prefix(f"u.{self.dom['id']}.")
|
|
for n in range(sr.GUEST_KEYS_MAX):
|
|
self.assertEqual(g.put(f"/api/ui-state/k{n}", json={"value": "1"}).status_code, 200)
|
|
self.assertEqual(g.put("/api/ui-state/one-more", json={"value": "1"}).status_code, 413)
|
|
self.assertEqual(g.put("/api/ui-state/k0", json={"value": "2"}).status_code, 200)
|
|
# the owner's own keys are not a guest's
|
|
self.addCleanup(DEPS.ui_state.delete, "owner-big")
|
|
self.assertEqual(self.c.put("/api/ui-state/owner-big", headers=OWNER_H,
|
|
json={"value": big}).status_code, 200)
|
|
|
|
def test_ui_state_is_namespaced(self):
|
|
g = self.guest()
|
|
g.put("/api/ui-state/ai-agent-settings", json={"value": "guest"})
|
|
self.assertEqual(DEPS.ui_state.get(f"u.{self.dom['id']}.ai-agent-settings"),
|
|
"guest")
|
|
self.assertIsNone(self.c.get("/api/ui-state/ai-agent-settings",
|
|
headers=OWNER_H).json()["value"])
|
|
|
|
# ── guest settings + shared skills ──────────────────────────────────────
|
|
def _owner_settings(self, shortcuts, version=4, **state):
|
|
import json
|
|
self.addCleanup(DEPS.ui_state.delete, "ai-agent-settings")
|
|
self.c.put("/api/ui-state/ai-agent-settings", headers=OWNER_H, json={
|
|
"value": json.dumps({"state": {"promptShortcuts": shortcuts, **state},
|
|
"version": version})})
|
|
|
|
def test_prompt_shortcuts_left_me_and_ui_state(self):
|
|
# the prompt-shortcuts plugin serves them now (plugins/carryover.py
|
|
# moved them): /api/me carries none and a settings blob comes back
|
|
# as it was stored — nothing seeded, nothing upgraded on read
|
|
import json
|
|
g = self.guest()
|
|
self.assertIsNone(g.get("/api/ui-state/ai-agent-settings").json()["value"])
|
|
self.assertNotIn("sharedShortcuts", g.get("/api/me").json())
|
|
blob = json.dumps({"state": {"promptShortcuts": [{"id": "c", "label": "C"}]},
|
|
"version": 3})
|
|
self._owner_settings([{"id": "c", "label": "C"}], version=3)
|
|
self.assertEqual(self.c.get("/api/ui-state/ai-agent-settings",
|
|
headers=OWNER_H).json()["value"], blob)
|
|
|
|
def test_guests_sweep_on_the_owners_unsend_curve(self):
|
|
curve = {"points": [{"x": 0, "y": 0}, {"x": 0.5, "y": 0.9}, {"x": 1, "y": 1}],
|
|
"easings": [[0.25, 1, 0.5, 1], [0.7, 0, 0.84, 0]]}
|
|
g = self.guest()
|
|
# the default until the owner draws one
|
|
self.assertIsNone(g.get("/api/me").json().get("unsendCurve"))
|
|
self._owner_settings([], unsendCurve=curve)
|
|
self.assertEqual(g.get("/api/me").json()["unsendCurve"], curve)
|
|
self.assertIsNone(self.c.get("/api/me", headers=OWNER_H).json().get("unsendCurve"))
|
|
# a broken one is the default, not a crash in the guest's composer
|
|
self._owner_settings([], unsendCurve={"points": [{"x": 0.2, "y": 0}], "easings": []})
|
|
self.assertIsNone(g.get("/api/me").json().get("unsendCurve"))
|
|
self._owner_settings([], unsendCurve={**curve, "easings": [[1.5, 0, 1, 1], [0, 0, 1, 1]]})
|
|
self.assertIsNone(g.get("/api/me").json().get("unsendCurve"))
|
|
|
|
def test_owner_save_pings_guests_when_the_unsend_curve_changes(self):
|
|
import json
|
|
from unittest import mock
|
|
curve = {"points": [{"x": 0, "y": 0}, {"x": 1, "y": 1}], "easings": [[0, 0, 1, 1]]}
|
|
self._owner_settings([])
|
|
with mock.patch.object(DEPS.hub, "publish") as pub:
|
|
self._owner_settings([], unsendCurve=curve)
|
|
self.assertIn(mock.call({"type": "users"}), pub.call_args_list)
|
|
pub.reset_mock()
|
|
self._owner_settings([], unsendCurve=curve, theme="dark")
|
|
self.assertNotIn(mock.call({"type": "users"}), pub.call_args_list)
|
|
|
|
def test_guest_defaults_are_the_owners(self):
|
|
self.assertEqual(self.guest().get("/api/guest-defaults").status_code, 403)
|
|
r = self.c.put("/api/guest-defaults", headers=OWNER_H, json={
|
|
"sharedSkills": ["ask-form", "../etc", "film/cut", "a/b/c", "ask-form"]})
|
|
self.assertEqual(r.json()["sharedSkills"], ["ask-form", "film/cut"])
|
|
self.assertNotIn("promptShortcuts", r.json())
|
|
# the old starting list stays readable for the carry-over only
|
|
self.assertEqual(DEPS.users.legacy_guest_shortcuts()[0]["id"], "commit")
|
|
|
|
def test_guest_run_scope_carries_the_shared_skills(self):
|
|
calls = self._capture()
|
|
DEPS.users.set_defaults({"sharedSkills": ["ask-form", "film/cut"]})
|
|
self.guest().post("/api/spawn", json={"prompt": "hi", "projects": ["film"]})
|
|
scope = calls[-1][1]["scope"]
|
|
# the CLI is on for a new guest: its skill comes first (ask-approval
|
|
# now comes from the Approvals live plugin, scheduled jobs from the
|
|
# cron-jobs plugin — not core skills)
|
|
self.assertEqual(scope["skills"], ["@ai-agent", "ask-form", "film/cut"])
|
|
self.assertIn("`shared:cut`", scope["systemPrompt"])
|
|
DEPS.users.update(self.dom["id"], {"cli": False})
|
|
self.guest().post("/api/spawn", json={"prompt": "hi", "projects": ["film"]})
|
|
self.assertEqual(calls[-1][1]["scope"]["skills"], ["ask-form", "film/cut"])
|
|
DEPS.users.set_defaults({"sharedSkills": []})
|
|
self.guest().post("/api/spawn", json={"prompt": "hi", "projects": ["film"]})
|
|
self.assertNotIn("skills", calls[-1][1]["scope"])
|
|
self.assertNotIn("shares these skills", calls[-1][1]["scope"]["systemPrompt"])
|
|
|
|
def test_guest_skills_are_shared_plus_granted_projects(self):
|
|
def skill(root, name):
|
|
d = root / ".claude" / "skills" / name
|
|
d.mkdir(parents=True, exist_ok=True)
|
|
(d / "SKILL.md").write_text(f"---\nname: {name}\ndescription: {name} it\n---\n")
|
|
skill(TMP, "ask-form")
|
|
skill(TMP, "kept-home")
|
|
skill(TMP / "projects" / "film", "cut")
|
|
skill(TMP / "projects" / "other", "secret")
|
|
DEPS.users.set_defaults({"sharedSkills": ["ask-form", "missing"]})
|
|
names = {s["name"]: s["source"] for s in
|
|
self.guest().get("/api/guest-skills").json()["skills"]}
|
|
self.assertEqual(names, {"shared:ask-form": "shared", "cut": "film"})
|
|
cards = {s["name"]: s for s in
|
|
self.c.get("/api/skills", headers=OWNER_H).json()["skills"]}
|
|
self.assertTrue(cards["ask-form"]["sharedWithGuests"])
|
|
self.assertFalse(cards["kept-home"]["sharedWithGuests"])
|
|
self.assertEqual(cards["cut"]["shareRef"], "film/cut")
|
|
|
|
def test_sse_filter(self):
|
|
dom = guest_from_record(self.dom)
|
|
DEPS.meta_store.update("mine", {"owner": self.dom["id"]})
|
|
flt = _guest_filter(DEPS, dom)
|
|
ev = flt({"type": "transcript", "ids": ["-p/mine.jsonl", "-p/theirs.jsonl",
|
|
"-p/mine/subagents/agent-1.jsonl"]})
|
|
self.assertEqual(ev["ids"], ["-p/mine.jsonl", "-p/mine/subagents/agent-1.jsonl"])
|
|
self.assertIsNone(flt({"type": "cron"}))
|
|
self.assertIsNone(flt({"type": "meta", "id": "theirs"}))
|
|
|
|
# ── runs ─────────────────────────────────────────────────────────────────
|
|
def _capture(self):
|
|
calls = []
|
|
orig = run_routes._send_message
|
|
run_routes._send_message = lambda deps, prompt, **kw: (
|
|
calls.append((prompt, kw)) or {"sessionId": "new", "pid": 1})
|
|
self.addCleanup(setattr, run_routes, "_send_message", orig)
|
|
return calls
|
|
|
|
def test_guest_spawn_is_pinned_server_side(self):
|
|
calls = self._capture()
|
|
r = self.guest().post("/api/spawn", json={
|
|
"prompt": "hello", "projects": ["film"], "cwd": "/",
|
|
"account": "work", "worker": "mac", "harness": "pi", "model": "sonnet"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
prompt, kw = calls[0]
|
|
self.assertTrue(prompt.startswith('<ai-agent-from user="dom"'))
|
|
self.assertEqual(kw["cwd"], "~/projects/film")
|
|
self.assertEqual((kw["account"], kw["worker"], kw["harness"]),
|
|
("personal", "local", "claude"))
|
|
# origin: where it was started from (telemetry) — the test client is no browser
|
|
self.assertEqual(kw["stamp"], {"owner": "dom", "projects": ["film"], "origin": "script"})
|
|
self.assertIn("~/projects/film", kw["scope"]["writeDirs"])
|
|
self.assertFalse(kw["scope"]["remoteControl"])
|
|
# their commits are authored as them (lower-cased like the stored user)
|
|
self.assertEqual(kw["scope"]["gitAuthor"],
|
|
{"name": "Dom", "email": self.dom["email"]})
|
|
self.assertIn("authored as Dom", kw["scope"]["systemPrompt"])
|
|
# chat level: git pushes nowhere (no token — and never the owner's)
|
|
self.assertEqual(kw["scope"]["git"], {"user": "dom", "email": self.dom["email"],
|
|
"push": []})
|
|
# on the owner's account the run is capped at what's left of the month
|
|
self.assertEqual(kw["scope"]["maxBudgetUsd"], DEPS.users.get("dom")["budgetUsd"])
|
|
|
|
def test_live_runs_cap(self):
|
|
from users import runs as guest_runs
|
|
from runs import sidecar_client
|
|
calls = self._capture()
|
|
live = {f"0000000{i}-0000-0000-0000-000000000000" for i in range(3)}
|
|
for s in live:
|
|
DEPS.meta_store.update(s, {"runAs": "dom"})
|
|
orig = sidecar_client._sidecar_live_sids
|
|
sidecar_client._sidecar_live_sids = lambda deps, w=None: live
|
|
self.addCleanup(setattr, sidecar_client, "_sidecar_live_sids", orig)
|
|
r = self.guest().post("/api/spawn", json={"prompt": "x", "projects": ["film"]})
|
|
self.assertEqual(r.status_code, 429, r.text)
|
|
self.assertEqual(r.json()["detail"]["kind"], "guest_live_runs")
|
|
guest_runs.check_live_runs(DEPS, guest_from_record(DEPS.users.get("dom")),
|
|
sorted(live)[0]) # a turn into one of them is fine
|
|
self.assertEqual(calls, [])
|
|
|
|
def test_guest_spawn_with_extra_projects(self):
|
|
DEPS.users.update(self.dom["id"], {"projects": {"film": "chat", "other": "ship"}})
|
|
calls = self._capture()
|
|
g = self.guest()
|
|
r = g.post("/api/spawn", json={"prompt": "x", "projects": ["other", "film", "other"]})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
_, kw = calls[0]
|
|
self.assertEqual(kw["cwd"], "~/projects/other") # the select's pick runs first
|
|
self.assertEqual(kw["stamp"]["projects"], ["other", "film"])
|
|
self.assertEqual(kw["scope"]["writeDirs"],
|
|
["~/projects/other", "~/projects/film", "/tmp"])
|
|
self.assertIn("project `film`", kw["scope"]["systemPrompt"])
|
|
self.assertEqual(g.post("/api/spawn", json={
|
|
"prompt": "x", "projects": []}).status_code, 400)
|
|
|
|
def test_guest_spawn_refusals(self):
|
|
self._capture()
|
|
g = self.guest()
|
|
self.assertEqual(g.post("/api/spawn", json={
|
|
"prompt": "x", "projects": ["other"]}).status_code, 403)
|
|
self.assertEqual(g.post("/api/spawn", json={ # an extra needs chat too
|
|
"prompt": "x", "projects": ["film", "other"]}).status_code, 403)
|
|
self.assertEqual(g.post("/api/spawn", json={
|
|
"prompt": "x", "projects": ["film"], "model": "opus"}).status_code, 403)
|
|
claire = self.guest(DEPS.auth.open_session(self.claire["id"]))
|
|
self.assertEqual(claire.post("/api/spawn", json={ # view only
|
|
"prompt": "x", "projects": ["film"]}).status_code, 403)
|
|
|
|
def test_guest_without_a_project_runs_in_their_scratch_folder(self):
|
|
calls = self._capture()
|
|
DEPS.users.update(self.dom["id"], {"projects": {}})
|
|
g = self.guest()
|
|
r = g.post("/api/spawn", json={"prompt": "what is a CDN?", "projects": [],
|
|
"cwd": "/", "worker": "mac"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
prompt, kw = calls[0]
|
|
self.assertTrue(prompt.startswith('<ai-agent-from user="dom"'))
|
|
self.assertEqual(kw["cwd"], "~/projects/.guest-scratch/dom")
|
|
self.assertTrue((TMP / "projects" / ".guest-scratch" / "dom").is_dir())
|
|
self.assertEqual((kw["worker"], kw["harness"], kw["projects"]),
|
|
("local", "claude", []))
|
|
self.assertEqual(kw["stamp"], {"owner": "dom", "projects": [], "scratch": True})
|
|
self.assertEqual(kw["scope"]["writeDirs"], ["~/projects/.guest-scratch/dom", "/tmp"])
|
|
self.assertEqual(kw["scope"]["git"]["push"], [])
|
|
self.assertIn("no project", kw["scope"]["systemPrompt"])
|
|
# a view-only grant is still no project to run in
|
|
claire = self.guest(DEPS.auth.open_session(self.claire["id"]))
|
|
self.assertEqual(claire.post("/api/spawn", json={
|
|
"prompt": "x", "projects": []}).status_code, 200)
|
|
self.assertEqual(calls[-1][1]["cwd"], "~/projects/.guest-scratch/claire")
|
|
# …but naming a project they can't chat in is still refused
|
|
self.assertEqual(claire.post("/api/spawn", json={
|
|
"prompt": "x", "projects": ["film"]}).status_code, 403)
|
|
|
|
def test_no_project_bash_is_the_owners_switch_per_guest(self):
|
|
"""A *No project* chat is a run on the lab: on by default, and the
|
|
owner can take its shell away for one guest (``scope.noBash``, which
|
|
the sidecar turns into no Bash and no Monitor)."""
|
|
calls = self._capture()
|
|
DEPS.users.update(self.dom["id"], {"projects": {}})
|
|
g = self.guest()
|
|
users = lambda: {u["id"]: u for u in # noqa: E731
|
|
self.c.get("/api/users", headers=OWNER_H).json()["users"]}
|
|
self.assertIs(users()["dom"]["scratchBash"], True) # the default
|
|
self.assertEqual(g.post("/api/spawn", json={"prompt": "hi"}).status_code, 200)
|
|
scope = calls[-1][1]["scope"]
|
|
self.assertNotIn("noBash", scope)
|
|
self.assertIn("```notify block (the closing push)", scope["systemPrompt"])
|
|
# a guest can't flip it themselves
|
|
g.put("/api/me", json={"scratchBash": False})
|
|
self.assertIs(users()["dom"]["scratchBash"], True)
|
|
self.assertEqual(g.put(f"/api/users/{self.dom['id']}",
|
|
json={"scratchBash": False}).status_code, 403)
|
|
# the owner switches it off for Dom: no shell, and nothing that is a command
|
|
DEPS.users.update(self.dom["id"], {"cli": True})
|
|
r = self.c.put(f"/api/users/{self.dom['id']}", json={"scratchBash": False},
|
|
headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertIs(r.json()["scratchBash"], False)
|
|
self.assertEqual(g.post("/api/spawn", json={"prompt": "hi"}).status_code, 200)
|
|
scope = calls[-1][1]["scope"]
|
|
self.assertIs(scope["noBash"], True)
|
|
self.assertIn("no shell", scope["systemPrompt"])
|
|
self.assertNotIn("`notify ask` — those reach", scope["systemPrompt"])
|
|
self.assertNotIn("skills", scope)
|
|
self.assertNotIn("tools", scope)
|
|
# …and its next turns keep it
|
|
sid = "44444444-2222-3333-4444-555555555555"
|
|
DEPS.meta_store.update(sid, {"owner": self.dom["id"], "projects": [],
|
|
"scratch": True})
|
|
self.assertEqual(g.post("/api/resume", json={"sessionId": sid, "prompt": "and?"})
|
|
.status_code, 200)
|
|
self.assertIs(calls[-1][1]["scope"]["noBash"], True)
|
|
# Claire's is untouched; a project run never carries it
|
|
claire = self.guest(DEPS.auth.open_session(self.claire["id"]))
|
|
self.assertEqual(claire.post("/api/spawn", json={"prompt": "x"}).status_code, 200)
|
|
self.assertNotIn("noBash", calls[-1][1]["scope"])
|
|
DEPS.users.update(self.dom["id"], {"projects": {"film": "chat"}})
|
|
self.assertEqual(g.post("/api/spawn", json={"prompt": "x", "projects": ["film"]})
|
|
.status_code, 200)
|
|
self.assertNotIn("noBash", calls[-1][1]["scope"])
|
|
|
|
def test_guest_no_project_conversation_keeps_its_scope(self):
|
|
calls = self._capture()
|
|
DEPS.users.update(self.dom["id"], {"projects": {}})
|
|
sid = "33333333-2222-3333-4444-555555555555"
|
|
DEPS.meta_store.update(sid, {"owner": self.dom["id"], "projects": [],
|
|
"scratch": True})
|
|
r = self.guest().post("/api/resume", json={"sessionId": sid, "prompt": "and?"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(calls[-1][1]["scope"]["writeDirs"],
|
|
["~/projects/.guest-scratch/dom", "/tmp"])
|
|
# someone else's scratch conversation stays out of reach
|
|
claire = self.guest(DEPS.auth.open_session(self.claire["id"]))
|
|
self.assertEqual(claire.post("/api/resume", json={
|
|
"sessionId": sid, "prompt": "x"}).status_code, 404)
|
|
|
|
def test_resume_needs_access_and_tags_the_author(self):
|
|
calls = self._capture()
|
|
sid = "11111111-2222-3333-4444-555555555555"
|
|
DEPS.meta_store.update(sid, {"owner": self.claire["id"], "projects": ["film"]})
|
|
g = self.guest()
|
|
self.assertEqual(g.post("/api/resume", json={
|
|
"sessionId": sid, "prompt": "hi"}).status_code, 404)
|
|
DEPS.meta_store.update(sid, {"participants": [self.dom["id"]]})
|
|
self.assertEqual(g.post("/api/resume", json={
|
|
"sessionId": sid, "prompt": "hi", "cwd": "/"}).status_code, 200)
|
|
prompt, kw = calls[-1]
|
|
self.assertIn('name="Dom"', prompt)
|
|
# never the client's: the session's own (none here — no transcript),
|
|
# so a guest's turn can't land in the sidecar's default, the lab repo
|
|
self.assertNotEqual(kw.get("cwd"), "/")
|
|
self.assertIsNone(kw.get("cwd"))
|
|
# …and the owner's own turn in that shared thread is tagged too
|
|
self.c.post("/api/resume", json={"sessionId": sid, "prompt": "me"},
|
|
headers=OWNER_H)
|
|
self.assertTrue(calls[-1][0].startswith('<ai-agent-from user="owner"'))
|
|
|
|
def test_share_by_conversation_owner(self):
|
|
sid = "22222222-2222-3333-4444-555555555555"
|
|
DEPS.meta_store.update(sid, {"owner": self.dom["id"], "projects": ["film"]})
|
|
r = self.guest().put("/api/conversation-share",
|
|
json={"id": sid, "participants": [self.claire["id"]]})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(DEPS.meta_store.peek(sid)["participants"], ["claire"])
|
|
self.assertTrue(access.visible(DEPS, guest_from_record(self.claire), sid))
|
|
|
|
# ── per-user notifications ───────────────────────────────────────────────
|
|
def test_audience(self):
|
|
self.assertEqual(access.audience({}), ["owner"])
|
|
self.assertEqual(access.audience({"owner": "dom"}), ["dom"])
|
|
self.assertEqual(access.audience({"owner": "dom", "participants": ["claire"]}),
|
|
["dom", "claire"])
|
|
self.assertEqual(access.audience({"participants": ["dom"]}), ["owner", "dom"])
|
|
# the owner follows a guest's conversation; a guest mutes one
|
|
self.assertEqual(access.audience({"owner": "dom", "follow": {"owner": True}}),
|
|
["dom", "owner"])
|
|
self.assertEqual(access.audience({"owner": "dom", "participants": ["claire"],
|
|
"follow": {"dom": False}}), ["claire"])
|
|
# a guest's "follow" can't add them to a conversation they don't see
|
|
self.assertEqual(access.audience({"follow": {"claire": True}}), ["owner"])
|
|
|
|
def _forwarded(self):
|
|
"""Capture what goes to the owner's channels (the phone)."""
|
|
import notifications.channels as channels
|
|
sent = []
|
|
orig = channels.deliver
|
|
channels.deliver = lambda deps, uid, event, payload: (
|
|
(sent.append(payload) or [{"channel": "ha", "ok": True, "status": 200}])
|
|
if uid == "owner" else [])
|
|
self.addCleanup(setattr, channels, "deliver", orig)
|
|
return sent
|
|
|
|
def test_pushes_reach_the_conversation_audience(self):
|
|
sent = self._forwarded()
|
|
sid = "33333333-2222-3333-4444-555555555555"
|
|
DEPS.meta_store.update(sid, {"owner": self.dom["id"], "projects": ["film"],
|
|
"participants": [self.claire["id"]]})
|
|
r = self.c.post("/api/notify", headers=OWNER_H, json={
|
|
"title": "done", "message": "m", "sessionId": sid}).json()
|
|
self.assertEqual(sent, []) # the owner doesn't follow it
|
|
self.assertEqual({d["user"] for d in r["delivered"]}, {"dom", "claire"})
|
|
self.assertTrue(r["ok"])
|
|
# the owner writes in it → now follows it → their phone hears the next one
|
|
self._capture()
|
|
self.c.post("/api/resume", json={"sessionId": sid, "prompt": "me"}, headers=OWNER_H)
|
|
r = self.c.post("/api/notify", headers=OWNER_H, json={
|
|
"title": "again", "message": "m", "sessionId": sid}).json()
|
|
self.assertEqual(len(sent), 1)
|
|
self.assertEqual({d["user"] for d in r["delivered"]}, {"dom", "claire", "owner"})
|
|
# the owner's own conversation: the phone only
|
|
sent.clear()
|
|
r = self.c.post("/api/notify", headers=OWNER_H, json={
|
|
"title": "mine", "message": "m", "sessionId": "own-session"}).json()
|
|
self.assertEqual(len(sent), 1)
|
|
self.assertEqual({d["user"] for d in r["delivered"]}, {"owner"})
|
|
|
|
def test_asks_reach_the_conversation_audience(self):
|
|
sent = self._forwarded()
|
|
sid = "44444444-2222-3333-4444-555555555555"
|
|
DEPS.meta_store.update(sid, {"participants": [self.dom["id"]]})
|
|
r = self.c.post("/api/ask", headers=OWNER_H, json={
|
|
"question": "go?", "options": ["yes", "no"], "sessionId": sid}).json()
|
|
self.assertEqual(len(sent), 1)
|
|
self.assertEqual({d["user"] for d in r["delivered"]}, {"owner", "dom"})
|
|
self.assertEqual(DEPS.notify_store.ask_status(r["id"])["to"], ["owner", "dom"])
|
|
|
|
def test_feed_and_log_are_per_user(self):
|
|
self._forwarded()
|
|
mine, doms = "own-feed-session", "55555555-2222-3333-4444-555555555555"
|
|
DEPS.meta_store.update(doms, {"owner": self.dom["id"], "projects": ["film"]})
|
|
for sid in (mine, doms):
|
|
self.c.post("/api/notify", headers=OWNER_H, json={
|
|
"title": f"from {sid}", "message": "m", "sessionId": sid})
|
|
orig = DEPS.store.all_summaries
|
|
DEPS.store.all_summaries = lambda: [
|
|
(f"/x/{s}.jsonl", {"sessionId": s, "messages": 1}) for s in (mine, doms)]
|
|
self.addCleanup(setattr, DEPS.store, "all_summaries", orig)
|
|
|
|
def seen(client, headers=None):
|
|
feed = client.get("/api/notifications", headers=headers).json()
|
|
log = client.get("/api/notify-log", headers=headers).json()
|
|
return ({c["id"] for c in feed["conversations"]},
|
|
{e["sessionId"] for e in log["notifications"]
|
|
if e["sessionId"] in (mine, doms)})
|
|
|
|
self.assertEqual(seen(self.c, OWNER_H), ({_conv_id(f"/x/{mine}.jsonl")}, {mine}))
|
|
self.assertEqual(seen(self.guest()), ({_conv_id(f"/x/{doms}.jsonl")}, {doms}))
|
|
flat = {n["convId"] for n in _flat_notifications(DEPS)}
|
|
self.assertNotIn(_conv_id(f"/x/{doms}.jsonl"), flat) # the desk phone's unread
|
|
# the owner follows Dom's conversation from its bell
|
|
r = self.c.put("/api/conversation-follow", headers=OWNER_H,
|
|
json={"id": doms, "on": True})
|
|
self.assertTrue(r.json()["notifying"], r.text)
|
|
self.assertEqual(seen(self.c, OWNER_H)[0], {_conv_id(f"/x/{mine}.jsonl"), _conv_id(f"/x/{doms}.jsonl")})
|
|
# Dom mutes it: still visible to him, no longer in his feed
|
|
r = self.guest().put("/api/conversation-follow", json={"id": doms, "on": False})
|
|
self.assertFalse(r.json()["notifying"])
|
|
self.assertEqual(seen(self.guest()), (set(), set()))
|
|
self.assertEqual(self.guest().get(f"/api/conversation-share?id={doms}").status_code, 200)
|
|
|
|
def test_guest_links_point_at_the_guest_host(self):
|
|
from notifications.service import VIEW_URL
|
|
from users import deliver
|
|
if not deliver.GUEST_PUBLIC_URL:
|
|
deliver.GUEST_PUBLIC_URL = "https://claude.example.test"
|
|
self.addCleanup(setattr, deliver, "GUEST_PUBLIC_URL", "")
|
|
url = f"{VIEW_URL}/conversation/x.jsonl"
|
|
guest_url = deliver.url_for(guest_from_record(self.dom), url, VIEW_URL)
|
|
self.assertEqual(guest_url, "https://claude.example.test/conversation/x.jsonl")
|
|
self.assertEqual(deliver.url_for(OWNER, guest_url, VIEW_URL), url)
|
|
|
|
# ── user admin: spend + impersonation ────────────────────────────────────
|
|
def test_users_list_carries_spend(self):
|
|
cards = [_card("a" * 8, owner=self.dom["id"]),
|
|
_card("b" * 8, owner=self.dom["id"]),
|
|
{**_card("c" * 8, owner=self.dom["id"]), "endedAt": "2020-01-01T00:00:00Z"},
|
|
_card("d" * 8)]
|
|
import datetime
|
|
now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT00:00:00Z")
|
|
for c in cards[:2]:
|
|
c["endedAt"] = now
|
|
import conversations.catalog as catalog
|
|
orig = catalog._conversation_cards
|
|
catalog._conversation_cards = lambda deps, full: cards
|
|
self.addCleanup(setattr, catalog, "_conversation_cards", orig)
|
|
users = {u["id"]: u for u in
|
|
self.c.get("/api/users", headers=OWNER_H).json()["users"]}
|
|
self.assertEqual((users["dom"]["spentUsd"], users["dom"]["totalSpentUsd"],
|
|
users["dom"]["conversations"]), (2.0, 3.0, 3))
|
|
self.assertEqual(users["claire"]["spentUsd"], 0)
|
|
|
|
def test_impersonation(self):
|
|
before = len(DEPS.auth.sessions_of(self.dom["id"]))
|
|
c = TestClient(main.app) # the owner's browser on the admin host
|
|
r = c.post(f"/api/users/{self.dom['id']}/impersonate", headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertTrue(c.cookies.get(SESSION_COOKIE))
|
|
# the owner's credentials — and yet: Dom
|
|
me = c.get("/api/me", headers=OWNER_H).json()
|
|
self.assertEqual((me["id"], me["role"], me["impersonating"]), ("dom", "guest", True))
|
|
self.assertEqual(c.get("/api/users", headers=OWNER_H).status_code, 403)
|
|
# not one of Dom's own sessions, and no "Dom started…" ping on a spawn
|
|
self.assertEqual(len(DEPS.auth.sessions_of(self.dom["id"])), before)
|
|
self.assertIsNone(DEPS.users.get("dom")["lastLoginAt"])
|
|
calls, pings = self._capture(), []
|
|
orig = run_routes.deliver.owner_ping_start
|
|
run_routes.deliver.owner_ping_start = lambda *a: pings.append(a)
|
|
self.addCleanup(setattr, run_routes.deliver, "owner_ping_start", orig)
|
|
c.post("/api/spawn", json={"prompt": "x", "projects": ["film"]}, headers=OWNER_H)
|
|
self.assertEqual((len(calls), pings), (1, []))
|
|
# back to admin
|
|
c.post("/api/auth/logout", headers=OWNER_H)
|
|
self.assertEqual(c.get("/api/me", headers=OWNER_H).json()["role"], "owner")
|
|
# guests can't, and a disabled guest can't be impersonated
|
|
self.assertEqual(self.guest().post(
|
|
f"/api/users/{self.claire['id']}/impersonate").status_code, 403)
|
|
DEPS.users.update(self.claire["id"], {"disabled": True})
|
|
self.assertEqual(self.c.post(f"/api/users/{self.claire['id']}/impersonate",
|
|
headers=OWNER_H).status_code, 404)
|
|
|
|
def test_user_activity(self):
|
|
import datetime
|
|
import conversations.catalog as catalog
|
|
now = datetime.datetime.now(datetime.timezone.utc)
|
|
iso = lambda d: (now - datetime.timedelta(days=d)).strftime("%Y-%m-%dT%H:%M:%SZ") # noqa: E731
|
|
cards = [
|
|
{**_card("a" * 8, owner="dom", state="running", projects=["film"]),
|
|
"id": "p/aaaaaaaa.jsonl", "title": "A", "startedAt": iso(0), "endedAt": iso(0)},
|
|
{**_card("b" * 8, owner="dom", projects=["other"], account="guest-dom"),
|
|
"id": "p/bbbbbbbb.jsonl", "title": "B", "cost": 2.0,
|
|
"startedAt": iso(3), "endedAt": iso(2)},
|
|
{**_card("c" * 8, owner="dom"), "id": "p/cccccccc.jsonl",
|
|
"startedAt": iso(90), "endedAt": iso(90)},
|
|
{**_card("d" * 8, owner="claire"), "id": "p/dddddddd.jsonl", "endedAt": iso(0)},
|
|
]
|
|
DEPS.meta_store.update("a" * 8, {"projects": ["film"]})
|
|
orig = catalog._conversation_cards
|
|
catalog._conversation_cards = lambda deps, full: cards
|
|
self.addCleanup(setattr, catalog, "_conversation_cards", orig)
|
|
r = self.c.get("/api/users/dom/activity", headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
a = r.json()
|
|
days = a["dailySpend"]
|
|
self.assertEqual((len(days), days[-1]["date"]), (30, now.date().isoformat()))
|
|
self.assertEqual((days[-1]["usd"], days[-3]["ownUsd"]), (1.0, 2.0))
|
|
self.assertEqual(sum(d["usd"] + d["ownUsd"] for d in days), 3.0) # c is too old
|
|
self.assertEqual([r["id"] for r in a["recentConversations"]],
|
|
["p/aaaaaaaa.jsonl", "p/bbbbbbbb.jsonl", "p/cccccccc.jsonl"])
|
|
first = a["recentConversations"][0]
|
|
self.assertEqual((first["state"], first["project"], first["own"]),
|
|
("running", "film", False))
|
|
self.assertTrue(a["recentConversations"][1]["own"])
|
|
self.assertEqual((a["conversations"], a["conversationsThisWeek"]), (3, 2))
|
|
if now.day > 2: # b ran two days ago: this month unless the month just turned
|
|
self.assertEqual({p["project"]: p["usd"] + p["ownUsd"] for p in a["spendByProject"]},
|
|
{"film": 1.0, "other": 2.0})
|
|
self.assertEqual(len(self.c.get("/api/users/dom/activity?limit=1",
|
|
headers=OWNER_H).json()["recentConversations"]), 1)
|
|
self.assertEqual(self.c.get("/api/users/nobody/activity",
|
|
headers=OWNER_H).status_code, 404)
|
|
self.assertEqual(self.guest().get("/api/users/dom/activity").status_code, 403)
|
|
|
|
def test_claude_bill_pick(self):
|
|
g = self.guest()
|
|
# nothing connected: nothing to pick between
|
|
self.assertEqual(g.put("/api/me/claude/bill", json={"bill": "host"}).status_code, 409)
|
|
DEPS.users.set_claude("dom", {"account": "guest-dom", "connectedAt": "2026-10-01T00:00:00Z"})
|
|
self.addCleanup(DEPS.users.set_claude, "dom", None)
|
|
self.assertEqual(g.get("/api/me").json()["claude"]["bill"], "own")
|
|
r = g.put("/api/me/claude/bill", json={"bill": "host"})
|
|
self.assertEqual((r.status_code, r.json()["bill"]), (200, "host"), r.text)
|
|
self.assertEqual(g.get("/api/me").json()["claude"]["bill"], "host")
|
|
# a re-login keeps the pick
|
|
DEPS.users.set_claude("dom", {"account": "guest-dom", "connectedAt": "2026-10-02T00:00:00Z"})
|
|
self.assertEqual(DEPS.users.get("dom")["claude"]["bill"], "host")
|
|
self.assertEqual(g.put("/api/me/claude/bill", json={"bill": "both"}).status_code, 400)
|
|
# the owner has no such chip
|
|
self.assertEqual(self.c.put("/api/me/claude/bill", json={"bill": "own"},
|
|
headers=OWNER_H).status_code, 404)
|
|
|
|
def test_delete_user_retires_the_id_and_cleans_up(self):
|
|
from accounts import guest as guest_claude
|
|
signed_out = []
|
|
orig = guest_claude.sign_out_later
|
|
guest_claude.sign_out_later = lambda deps, uid: signed_out.append(uid)
|
|
self.addCleanup(setattr, guest_claude, "sign_out_later", orig)
|
|
self.addCleanup(DEPS.users._data.pop, "deleted", None)
|
|
DEPS.users.set_claude("dom", {"account": "guest-dom", "connectedAt": "2026-10-01T00:00:00Z"})
|
|
DEPS.meta_store.update("del-own", {"owner": "dom"})
|
|
DEPS.meta_store.update("del-shared", {"participants": ["dom", "claire"],
|
|
"follow": {"dom": False, "owner": True}})
|
|
DEPS.ui_state.set("u.dom.ai-agent-settings", "{}")
|
|
DEPS.ui_state.set("u.domino.ai-agent-settings", "{}")
|
|
|
|
self.assertEqual(self.guest().delete("/api/users/claire").status_code, 403)
|
|
r = self.c.delete("/api/users/dom", headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertIsNone(DEPS.users.get("dom"))
|
|
self.assertIsNone(DEPS.auth.session_user(self.dom_cookie))
|
|
self.assertIsNone(DEPS.ui_state.get("u.dom.ai-agent-settings"))
|
|
self.assertEqual(DEPS.ui_state.get("u.domino.ai-agent-settings"), "{}")
|
|
shared = DEPS.meta_store.peek("del-shared")
|
|
self.assertEqual((shared["participants"], shared["follow"]),
|
|
(["claire"], {"owner": True}))
|
|
self.assertEqual(DEPS.meta_store.peek("del-own")["owner"], "dom") # history stays
|
|
self.assertEqual(signed_out, ["dom"])
|
|
# a new Dom is somebody else: never the old id (conversations, Claude dir, Gitea)
|
|
self.assertEqual(DEPS.users.create("dom2@example.com", "Dom")["id"], "dom-2")
|
|
self.assertEqual(self.c.delete("/api/users/dom", headers=OWNER_H).status_code, 404)
|
|
# no own Claude login, nothing to sign out
|
|
self.c.delete("/api/users/claire", headers=OWNER_H)
|
|
self.assertEqual(signed_out, ["dom"])
|
|
|
|
# ── helpers ──────────────────────────────────────────────────────────────
|
|
def test_author_tag_round_trip(self):
|
|
dom = guest_from_record(self.dom)
|
|
author, text = _split_author(f"{author_tag(dom)}\nfix the trailer")
|
|
self.assertEqual(author, {"id": "dom", "name": "Dom", "role": "guest"})
|
|
self.assertEqual(text, "fix the trailer")
|
|
self.assertEqual(_split_author("plain")[0], None)
|
|
|
|
def test_model_families(self):
|
|
dom = guest_from_record(self.dom)
|
|
self.assertEqual(check_model(dom, None), "sonnet")
|
|
self.assertEqual(check_model(dom, "claude-haiku-4-5-20251001"),
|
|
"claude-haiku-4-5-20251001")
|
|
self.assertTrue(OWNER.can("anything", "ship"))
|
|
|
|
|
|
class GuestBranding(unittest.TestCase):
|
|
"""The guest host serves the install manifest and page title under the
|
|
guest name — what a phone puts under the home-screen icon."""
|
|
|
|
def setUp(self):
|
|
self.static = TMP / "static"
|
|
self.static.mkdir(exist_ok=True)
|
|
(self.static / "index.html").write_text(
|
|
'<!doctype html><html lang="en" class="dark"><head>'
|
|
'<meta name="apple-mobile-web-app-title" content="ai-agent" />'
|
|
'<title>Claude Agent — context</title></head><body></body></html>')
|
|
(self.static / "manifest.webmanifest").write_text(
|
|
'{"name":"Claude Agent — context viewer","short_name":"ai-agent",'
|
|
'"description":"Viewer/editor","lang":"en","start_url":"/",'
|
|
'"icons":[{"src":"/icon-512.png","sizes":"512x512"}]}')
|
|
orig = main.STATIC_DIR
|
|
main.STATIC_DIR = self.static
|
|
self.addCleanup(setattr, main, "STATIC_DIR", orig)
|
|
|
|
def test_guest_host_renames_the_app(self):
|
|
from i18n_testkit import speaking
|
|
with speaking("fr"): # a translation for the browser's language is installed
|
|
self._guest_host_renames_the_app()
|
|
|
|
def _guest_host_renames_the_app(self):
|
|
c = TestClient(main.app, base_url="https://claude.example.test",
|
|
headers={"Accept-Language": "fr-FR,fr;q=0.9"})
|
|
m = c.get("/manifest.webmanifest")
|
|
self.assertEqual(m.status_code, 200)
|
|
self.assertIn("manifest+json", m.headers["content-type"])
|
|
j = m.json()
|
|
self.assertEqual(j["short_name"], "ai-agent")
|
|
self.assertNotIn("Claude", j["name"])
|
|
self.assertEqual(j["lang"], "fr")
|
|
self.assertTrue(j["description"].startswith("⟦"), j["description"])
|
|
self.assertEqual(j["icons"], [{"src": "/icon-512.png", "sizes": "512x512"}])
|
|
for path in ("/", "/login", "/index.html"):
|
|
html = c.get(path).text
|
|
self.assertNotIn("Claude", html, path)
|
|
self.assertIn('<html lang="fr"', html)
|
|
|
|
def test_owner_host_keeps_the_build(self):
|
|
c = TestClient(main.app, base_url="https://ai-agent.example.test")
|
|
self.assertIn("Claude Agent", c.get("/manifest.webmanifest").text)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|