739 lines
37 KiB
Python
739 lines
37 KiB
Python
"""Fresh context moved out of the core (2026-12-01) into the ``fresh-context``
|
|
live plugin. What the core keeps and gained, generic all of it:
|
|
|
|
* ``provider.cache`` on provider plugins (typed_manifest), served on each
|
|
vendor of ``/api/providers`` and ``hub/providers``, ``cache_for(model)``;
|
|
* ``hub/providers`` (``models.read``) — owner **and** guests;
|
|
* ``hub/conversations/{sid}/feed`` (``conversations.read``) — timestamps,
|
|
never text; a guest's own conversations only;
|
|
* ``provides: composer.beforeSend`` / ``runs.compact`` and
|
|
``POST /api/plugins/composer/before-send`` (plugins/composer_bridge.py);
|
|
* ``composer.send`` slots' ``contexts`` / ``guestAllowed`` /
|
|
``requiresHarnessCap`` / ``directAction``;
|
|
* ``/api/resume`` ``compact`` / ``fresh`` → the sidecar's compaction;
|
|
* ``carryover.fresh_context``;
|
|
* the parser: cache clock and the compaction divider, with no saving math.
|
|
|
|
Imports ``main`` against throwaway paths (no startup event → no threads)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import shutil
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
BACKEND = pathlib.Path(__file__).resolve().parent
|
|
if str(BACKEND) not in sys.path:
|
|
sys.path.insert(0, str(BACKEND))
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
FIX = BACKEND / "fixtures" / "typed_plugins"
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
|
|
"WORKSPACE": TMP / "ws", "REPO_DIR": TMP / "ws", "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",
|
|
"ASKFORM_PATH": TMP / "af.json", "FRESH_CONTEXT_PATH": TMP / "fc.json",
|
|
"UI_STATE_PATH": TMP / "ui.json", "DRAFTS_PATH": TMP / "dr.json",
|
|
"NOTIF_READ_PATH": TMP / "nr.json",
|
|
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"PROJECTS_DIR": TMP / "projects", "PLUGINS_DIR": TMP / "plugins",
|
|
"PLUGINS_SEED_DIR": FIX, "TOOLS_TOKEN_KEY": TMP / "tools.key",
|
|
"OPENROUTER_CACHE_PATH": TMP / "or.json",
|
|
"INTERNAL_API_TOKEN": "tok", "SIDECAR_TOKEN": "",
|
|
"PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ[k] = str(v)
|
|
os.environ["PROVIDERS_DISCOVERY"] = "0"
|
|
|
|
from fastapi import HTTPException # noqa: E402
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from conversations import ids # noqa: E402
|
|
from conversations.parse import parse_conversation # noqa: E402
|
|
from plugins import carryover, composer_bridge, providers, typed_manifest # noqa: E402
|
|
from plugins.manifest import ManifestError, capability_fingerprint, validate_manifest # noqa: E402
|
|
from plugins.store import OWNER_UID, PluginStore # noqa: E402
|
|
from runs import service as run_service # noqa: E402
|
|
from toolproxy import access as tp_access # noqa: E402
|
|
from users.caller import OWNER, SESSION_COOKIE, guest_from_record # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
OWNER_H = {"X-Internal-Auth": "tok"}
|
|
SID = "11111111-2222-4333-8444-aaaaaaaaaaaa"
|
|
GSID = "11111111-2222-4333-8444-bbbbbbbbbbbb"
|
|
REL = f"-home-x-projects-demo/{SID}.jsonl"
|
|
GREL = f"-home-x-projects-film/{GSID}.jsonl"
|
|
|
|
|
|
# ── helpers ─────────────────────────────────────────────────────────────────
|
|
class T:
|
|
"""A tiny transcript builder."""
|
|
|
|
def __init__(self, sid=SID):
|
|
self.sid, self.recs, self.n = sid, [], 0
|
|
|
|
def _ts(self):
|
|
self.n += 1
|
|
at = datetime.datetime(2026, 10, 30, 10, tzinfo=datetime.timezone.utc) \
|
|
+ datetime.timedelta(seconds=self.n)
|
|
return at.strftime("%Y-%m-%dT%H:%M:%S.000Z")
|
|
|
|
def idle(self, seconds):
|
|
self.n += seconds
|
|
return self
|
|
|
|
def user(self, text, **extra):
|
|
self.recs.append({"type": "user", "timestamp": self._ts(), "sessionId": self.sid,
|
|
"message": {"role": "user", "content": text}, **extra})
|
|
return self
|
|
|
|
def reply(self, text, ctx, *, model="claude-opus-5-5", w1h=0, w5m=0):
|
|
write = w1h + w5m
|
|
self.recs.append({
|
|
"type": "assistant", "timestamp": self._ts(), "sessionId": self.sid,
|
|
"requestId": f"r{self.n}",
|
|
"message": {"id": f"m{self.n}", "role": "assistant", "model": model,
|
|
"content": [{"type": "text", "text": text}],
|
|
"usage": {"input_tokens": 10, "output_tokens": 100,
|
|
"cache_read_input_tokens": ctx - write - 10,
|
|
"cache_creation_input_tokens": write,
|
|
"cache_creation": {"ephemeral_1h_input_tokens": w1h,
|
|
"ephemeral_5m_input_tokens": w5m}}}})
|
|
return self
|
|
|
|
def cost_state(self, **models):
|
|
self.recs.append({"type": "cost-state", "sessionId": self.sid, "modelUsage": {
|
|
m: {"inputTokens": u[0], "outputTokens": u[1], "cacheReadInputTokens": 0,
|
|
"cacheCreationInputTokens": 0, "cacheCreationEphemeral5mInputTokens": 0,
|
|
"cacheCreationEphemeral1hInputTokens": 0}
|
|
for m, u in models.items()}})
|
|
return self
|
|
|
|
def compact(self, pre, post, summary="1. Primary Request: ship it.", trigger="manual"):
|
|
self.recs.append({"type": "system", "subtype": "compact_boundary",
|
|
"timestamp": self._ts(), "sessionId": self.sid,
|
|
"content": "Conversation compacted",
|
|
"compactMetadata": {"trigger": trigger, "preTokens": pre,
|
|
"postTokens": post, "durationMs": 26544}})
|
|
self.user("This session is being continued from a previous conversation that "
|
|
"ran out of context. The summary below covers the earlier portion "
|
|
"of the conversation.\n\n<system-reminder>\ntools\n</system-reminder>\n"
|
|
f"Summary:\n{summary}", isCompactSummary=True, isVisibleInTranscriptOnly=True)
|
|
self.user("<command-name>/compact</command-name>\n<command-message>compact"
|
|
"</command-message>")
|
|
self.user("<local-command-stdout>Compacted</local-command-stdout>")
|
|
return self
|
|
|
|
def text(self):
|
|
return "\n".join(json.dumps(r) for r in self.recs) + "\n"
|
|
|
|
def parse(self, full=False):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
p = pathlib.Path(d) / f"{self.sid}.jsonl"
|
|
p.write_text(self.text())
|
|
return parse_conversation(p, full=full)
|
|
|
|
|
|
def _copy_fixture(pid: str, dest: pathlib.Path) -> pathlib.Path:
|
|
d = dest / pid
|
|
shutil.copytree(FIX / pid, d)
|
|
return d
|
|
|
|
|
|
# A provider that echoes a verdict chosen by a file in its folder.
|
|
VERDICT = ("import json, os, sys\n"
|
|
"p = json.load(sys.stdin)\n"
|
|
"ctx = json.loads(os.environ['AIA_USER_CONTEXT'])\n"
|
|
"mode = open('mode.txt').read().strip() if os.path.exists('mode.txt') else 'proceed'\n"
|
|
"if mode == 'boom':\n"
|
|
" sys.exit(3)\n"
|
|
"out = {'proceed': {'verdict': 'proceed'},\n"
|
|
" 'modify': {'verdict': 'modify', 'resume': {'compact': {'model': 'haiku',\n"
|
|
" 'instructions': 'keep it all'}}},\n"
|
|
" 'bad-modify': {'verdict': 'modify', 'resume': {'compact': {'model': 'haiku'}}},\n"
|
|
" 'modal': {'verdict': 'modal', 'slot': 'ask', 'init': {'payload': p,\n"
|
|
" 'uid': ctx.get('uid'), 'grant': ctx.get('grant')}},\n"
|
|
" 'bad-slot': {'verdict': 'modal', 'slot': 'nope'},\n"
|
|
" 'big': {'verdict': 'modal', 'slot': 'ask', 'init': {'x': 'y' * 17000}},\n"
|
|
"}[mode]\n"
|
|
"print(json.dumps(out))\n")
|
|
COMPACT = ("import json, sys\n"
|
|
"p = json.load(sys.stdin)\n"
|
|
"print(json.dumps({'model': p.get('ownModel') or 'haiku',\n"
|
|
" 'instructions': 'Summary for ' + p['sessionId']}))\n")
|
|
|
|
|
|
def _fresh_plugin(root: pathlib.Path, pid: str = "fresh-context", *, managed: bool = True,
|
|
caps=("models.read", "conversations.read")) -> pathlib.Path:
|
|
d = root / pid
|
|
(d / "ui").mkdir(parents=True, exist_ok=True)
|
|
(d / "ui" / "m.html").write_text("<p>hi</p>")
|
|
(d / "before.py").write_text(VERDICT)
|
|
(d / "compact.py").write_text(COMPACT)
|
|
(d / "fresh.py").write_text("import json, sys\njson.load(sys.stdin)\n"
|
|
"print(json.dumps({'resume': {'compact': {'model': 'haiku', "
|
|
"'instructions': 'x'}}}))\n")
|
|
mf = {"schema": 1, "id": pid, "name": "Fresh context", "version": "1.0.0",
|
|
"capabilities": list(caps),
|
|
"ui": {"slots": [
|
|
{"id": "ask", "where": "app.modal", "html": "ui/m.html"},
|
|
{"id": "send-fresh", "where": "composer.send", "label": "Send with fresh context",
|
|
"contexts": ["resume"], "guestAllowed": True,
|
|
"requiresHarnessCap": "fresh_context", "directAction": "fresh"}]},
|
|
"actions": {"before": {"script": "before.py", "readOnly": True},
|
|
"compact": {"script": "compact.py", "readOnly": True},
|
|
"fresh": {"script": "fresh.py"}},
|
|
"provides": {"composer.beforeSend": "before", "runs.compact": "compact"}}
|
|
if managed:
|
|
mf["managed"] = {"defaultForGuests": True, "grantFields": [
|
|
{"key": "autoFresh", "label": "Auto fresh", "type": "checkbox", "default": True}]}
|
|
(d / "plugin.json").write_text(json.dumps(mf))
|
|
return d
|
|
|
|
|
|
class _StoreCase(unittest.TestCase):
|
|
"""A fresh plugin store with the reference providers + harnesses in."""
|
|
|
|
PROVIDERS = ("provider-anthropic", "provider-openai", "provider-openrouter", "harness-claude",
|
|
"harness-agy")
|
|
|
|
def setUp(self):
|
|
self.td = tempfile.TemporaryDirectory()
|
|
self.root = pathlib.Path(self.td.name)
|
|
self.orig = DEPS.plugin_store
|
|
self.store = PluginStore(self.root / "plugins-data")
|
|
DEPS.plugin_store = self.store
|
|
src = self.root / "src"
|
|
src.mkdir()
|
|
for pid in self.PROVIDERS:
|
|
self.store.install(OWNER_UID, str(_copy_fixture(pid, src)), is_owner=True, approve=True)
|
|
for u in DEPS.users.all():
|
|
DEPS.users.delete(u["id"])
|
|
self.dom = DEPS.users.create("dom@example.com", "Dom", projects={"film": "chat"})
|
|
self.client = TestClient(main.app)
|
|
|
|
def tearDown(self):
|
|
DEPS.plugin_store = self.orig
|
|
self.td.cleanup()
|
|
|
|
def install_fresh(self, **kw):
|
|
return self.store.install(OWNER_UID, str(_fresh_plugin(self.root, **kw)),
|
|
is_owner=True, approve=True)
|
|
|
|
def mode(self, m: str, pid: str = "fresh-context"):
|
|
(pathlib.Path(self.store.get_raw(OWNER_UID, pid)["dir"]) / "mode.txt").write_text(m)
|
|
|
|
def guest(self):
|
|
return guest_from_record(DEPS.users.get(self.dom["id"]))
|
|
|
|
|
|
# ── 1. provider.cache ───────────────────────────────────────────────────────
|
|
class ProviderCache(unittest.TestCase):
|
|
def test_fixtures_declare_it(self):
|
|
a = validate_manifest(FIX / "provider-anthropic")["provider"]["cache"]
|
|
self.assertEqual(a, {"defaultTtlSeconds": 3600, "expiryMarginSeconds": 120,
|
|
"warmPrefixTokens": 24000,
|
|
"tiers": [{"key": "5m", "ttlSeconds": 300, "writeMult": 1.25},
|
|
{"key": "1h", "ttlSeconds": 3600, "writeMult": 2.0}]})
|
|
o = validate_manifest(FIX / "provider-openai")["provider"]["cache"]
|
|
self.assertEqual((o["defaultTtlSeconds"], o["expiryMarginSeconds"]), (600, 60))
|
|
g = validate_manifest(FIX / "provider-google")["provider"]["cache"]
|
|
self.assertEqual(g["tiers"], [{"key": "default", "ttlSeconds": 300, "writeMult": 1.0}])
|
|
|
|
def test_absent_stays_absent_and_keeps_the_fingerprint(self):
|
|
for pid in ("provider-openrouter", "provider-evox2"):
|
|
self.assertNotIn("cache", validate_manifest(FIX / pid)["provider"])
|
|
with tempfile.TemporaryDirectory() as td:
|
|
d = _copy_fixture("provider-anthropic", pathlib.Path(td))
|
|
raw = json.loads((d / "plugin.json").read_text())
|
|
with_cache = capability_fingerprint(validate_manifest(d))
|
|
raw["provider"].pop("cache")
|
|
(d / "plugin.json").write_text(json.dumps(raw))
|
|
without = validate_manifest(d)
|
|
self.assertNotIn("cache", without["provider"])
|
|
self.assertIsInstance(with_cache, str)
|
|
|
|
def test_defaults(self):
|
|
errs: list[str] = []
|
|
self.assertEqual(typed_manifest._cache({}, errs),
|
|
{"defaultTtlSeconds": None, "tiers": [], "expiryMarginSeconds": 120,
|
|
"warmPrefixTokens": 0})
|
|
self.assertEqual(errs, [])
|
|
|
|
def test_bad_values_are_refused(self):
|
|
cases = [
|
|
("nope", "must be an object"),
|
|
({"defaultTtlSeconds": 0}, "defaultTtlSeconds"),
|
|
({"defaultTtlSeconds": 604_801}, "defaultTtlSeconds"),
|
|
({"defaultTtlSeconds": True}, "defaultTtlSeconds"),
|
|
({"expiryMarginSeconds": 3601}, "expiryMarginSeconds"),
|
|
({"warmPrefixTokens": -1}, "warmPrefixTokens"),
|
|
({"warmPrefixTokens": 10_000_001}, "warmPrefixTokens"),
|
|
({"tiers": "x"}, "tiers must be an array"),
|
|
({"tiers": [{"key": "t", "ttlSeconds": 1}] * 9}, "tiers must be an array"),
|
|
({"tiers": [{"key": "a b", "ttlSeconds": 60}]}, "key must be"),
|
|
({"tiers": [{"key": "a", "ttlSeconds": 60}, {"key": "a", "ttlSeconds": 60}]}, "twice"),
|
|
({"tiers": [{"key": "a"}]}, "ttlSeconds is required"),
|
|
({"tiers": [{"key": "a", "ttlSeconds": 60, "writeMult": 101}]}, "writeMult"),
|
|
({"tiers": [{"key": "a", "ttlSeconds": 60, "extra": 1}]}, "extra"),
|
|
({"ttl": 5}, "ttl"),
|
|
]
|
|
for raw, msg in cases:
|
|
with self.subTest(raw=raw):
|
|
errs: list[str] = []
|
|
typed_manifest._cache(raw, errs)
|
|
self.assertTrue(any(msg in e for e in errs), errs)
|
|
|
|
def test_manifest_with_a_bad_cache_fails(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
d = _copy_fixture("provider-openai", pathlib.Path(td))
|
|
raw = json.loads((d / "plugin.json").read_text())
|
|
raw["provider"]["cache"]["defaultTtlSeconds"] = -5
|
|
(d / "plugin.json").write_text(json.dumps(raw))
|
|
with self.assertRaises(ManifestError) as cm:
|
|
validate_manifest(d)
|
|
self.assertIn("provider.cache.defaultTtlSeconds", str(cm.exception))
|
|
|
|
|
|
class RegistryCache(_StoreCase):
|
|
def test_api_payload_and_cache_for(self):
|
|
reg = providers.registry(self.store)
|
|
vendors = {v["id"]: v for v in reg.api_payload()["vendors"]}
|
|
self.assertEqual(vendors["anthropic"]["cache"]["defaultTtlSeconds"], 3600)
|
|
self.assertEqual(vendors["openai"]["cache"]["defaultTtlSeconds"], 600)
|
|
self.assertIsNone(vendors["openrouter"]["cache"])
|
|
hit = reg.cache_for("claude-opus-5-5")
|
|
self.assertEqual(hit["vendor"], "anthropic")
|
|
self.assertEqual(hit["cache"]["warmPrefixTokens"], 24000)
|
|
self.assertIsNone(reg.cache_for("openai/gpt-oss-20b")) # OpenRouter: none declared
|
|
self.assertIsNone(reg.cache_for("no-such-model"))
|
|
|
|
def test_api_providers_route_carries_it(self):
|
|
r = self.client.get("/api/providers", headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
vendors = {v["id"]: v for v in r.json()["vendors"]}
|
|
self.assertEqual(vendors["anthropic"]["cache"]["tiers"][1]["key"], "1h")
|
|
|
|
|
|
# ── 2. hub/providers ────────────────────────────────────────────────────────
|
|
class HubProviders(_StoreCase):
|
|
def test_owner_and_guest_read_it(self):
|
|
self.install_fresh()
|
|
tok = tp_access.mint_handler(OWNER_UID, "fresh-context", 60)
|
|
r = self.client.get("/proxy/tools/plugins/fresh-context/hub/providers",
|
|
headers={"Authorization": f"Bearer {tok}"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
body = r.json()
|
|
self.assertTrue(body["accounts"])
|
|
self.assertIn("anthropic", {v["id"] for v in body["vendors"]})
|
|
gtok = tp_access.mint_handler(self.dom["id"], "fresh-context", 60)
|
|
r = self.client.get("/proxy/tools/plugins/fresh-context/hub/providers",
|
|
headers={"Authorization": f"Bearer {gtok}"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
g = r.json()
|
|
self.assertEqual(g["accounts"], []) # a guest gets no accounts
|
|
self.assertTrue(all(h.get("guestAllowed") for h in g["harnesses"]))
|
|
self.assertEqual({v["id"]: v["cache"] for v in g["vendors"]}["anthropic"]["defaultTtlSeconds"],
|
|
3600)
|
|
|
|
def test_needs_models_read(self):
|
|
self.install_fresh(caps=("conversations.read",))
|
|
tok = tp_access.mint_handler(OWNER_UID, "fresh-context", 60)
|
|
r = self.client.get("/proxy/tools/plugins/fresh-context/hub/providers",
|
|
headers={"Authorization": f"Bearer {tok}"})
|
|
self.assertEqual(r.status_code, 403)
|
|
|
|
def test_a_guest_without_the_grant_is_refused(self):
|
|
self.install_fresh()
|
|
self.store.set_grant(self.dom["id"], "fresh-context", enabled=False)
|
|
gtok = tp_access.mint_handler(self.dom["id"], "fresh-context", 60)
|
|
r = self.client.get("/proxy/tools/plugins/fresh-context/hub/providers",
|
|
headers={"Authorization": f"Bearer {gtok}"})
|
|
self.assertEqual(r.status_code, 404)
|
|
|
|
|
|
# ── 3. hub/conversations/{sid}/feed ─────────────────────────────────────────
|
|
class HubFeed(_StoreCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
for rel, sid in ((REL, SID), (GREL, GSID)):
|
|
p = TMP / "arch" / rel
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
p.write_text(T(sid).user("go").reply("a", 60_000, w1h=60_000)
|
|
.user("more").reply("b", 61_000).text())
|
|
DEPS.indexer.scan_transcripts()
|
|
|
|
def setUp(self):
|
|
super().setUp()
|
|
self.install_fresh()
|
|
DEPS.meta_store.update(GSID, {"owner": self.dom["id"]})
|
|
DEPS.meta_store.update(SID, {"owner": None})
|
|
self.otok = tp_access.mint_handler(OWNER_UID, "fresh-context", 60)
|
|
self.gtok = tp_access.mint_handler(self.dom["id"], "fresh-context", 60)
|
|
|
|
def feed(self, sid, tok, **params):
|
|
return self.client.get(f"/proxy/tools/plugins/fresh-context/hub/conversations/{sid}/feed",
|
|
params=params, headers={"Authorization": f"Bearer {tok}"})
|
|
|
|
def test_owner_reads_by_session_id(self):
|
|
r = self.feed(SID, self.otok)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
b = r.json()
|
|
self.assertEqual(b["sessionId"], SID)
|
|
self.assertEqual(b["harness"], "claude")
|
|
self.assertEqual(b["model"], "claude-opus-5-5")
|
|
self.assertEqual(b["cacheTtl"], 3600)
|
|
self.assertEqual(b["lastCallAt"], "2026-10-30T10:00:04.000Z")
|
|
self.assertEqual(b["contextTokens"], 61_100)
|
|
self.assertIsNotNone(b["firstContextTokens"])
|
|
self.assertFalse(b["running"])
|
|
self.assertFalse(b["codeMode"])
|
|
roles = [(m["role"], m["kind"]) for m in b["messages"]]
|
|
self.assertEqual(roles, [("user", "text"), ("assistant", "text"),
|
|
("user", "text"), ("assistant", "text")])
|
|
self.assertEqual(set(b["messages"][0]), {"mi", "role", "kind", "ts", "model"})
|
|
self.assertEqual(b["messages"][-1]["model"], "claude-opus-5-5")
|
|
# never the text
|
|
self.assertNotIn("more", json.dumps(b["messages"]))
|
|
|
|
def test_by_conversation_uid_and_tail(self):
|
|
uid = ids.uid_for_path(str(TMP / "arch" / REL))
|
|
r = self.feed(uid, self.otok, tail=2)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["id"], uid)
|
|
self.assertEqual(r.json()["sessionId"], SID)
|
|
self.assertEqual(len(r.json()["messages"]), 2)
|
|
self.assertEqual(len(self.feed(SID, self.otok, tail=0).json()["messages"]), 1)
|
|
self.assertEqual(len(self.feed(SID, self.otok, tail=999).json()["messages"]), 4)
|
|
|
|
def test_guest_reads_only_their_own(self):
|
|
self.assertEqual(self.feed(GSID, self.gtok).status_code, 200)
|
|
self.assertEqual(self.feed(SID, self.gtok).status_code, 404)
|
|
|
|
def test_unknown_and_bad_ids(self):
|
|
self.assertEqual(self.feed("99999999-2222-4333-8444-cccccccccccc", self.otok).status_code, 404)
|
|
self.assertEqual(self.feed("x", self.otok).status_code, 400)
|
|
|
|
def test_needs_conversations_read(self):
|
|
self.store.uninstall(OWNER_UID, "fresh-context", purge=True)
|
|
self.install_fresh(caps=("models.read",))
|
|
self.assertEqual(self.feed(SID, self.otok).status_code, 403)
|
|
|
|
|
|
# ── 4. composer.beforeSend / runs.compact ───────────────────────────────────
|
|
class BeforeSend(_StoreCase):
|
|
def test_manifest_takes_the_two_provides(self):
|
|
mf = validate_manifest(_fresh_plugin(self.root))
|
|
self.assertEqual(mf["provides"], {"composer.beforeSend": "before", "runs.compact": "compact"})
|
|
|
|
def test_no_provider_proceeds(self):
|
|
self.assertEqual(composer_bridge.before_send(DEPS, OWNER, {}), {"verdict": "proceed"})
|
|
r = self.client.post("/api/plugins/composer/before-send", json={"mode": "resume"},
|
|
headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json(), {"verdict": "proceed"})
|
|
|
|
def test_verdicts(self):
|
|
self.install_fresh()
|
|
self.mode("modify")
|
|
self.assertEqual(composer_bridge.before_send(DEPS, OWNER, {"sessionId": SID}),
|
|
{"verdict": "modify", "pluginId": "fresh-context",
|
|
"resume": {"compact": {"model": "haiku", "instructions": "keep it all"}}})
|
|
self.mode("modal")
|
|
out = composer_bridge.before_send(DEPS, OWNER, {"sessionId": SID, "prompt": "secret"})
|
|
self.assertEqual((out["verdict"], out["pluginId"], out["slot"]),
|
|
("modal", "fresh-context", "ask"))
|
|
self.assertEqual(out["init"]["payload"]["trigger"], "composer.beforeSend")
|
|
self.assertEqual(out["init"]["payload"]["sessionId"], SID)
|
|
self.assertNotIn("prompt", out["init"]["payload"])
|
|
self.assertEqual(out["init"]["uid"], OWNER_UID)
|
|
for m in ("proceed", "bad-modify", "bad-slot", "big", "boom"):
|
|
self.mode(m)
|
|
self.assertEqual(composer_bridge.before_send(DEPS, OWNER, {}), {"verdict": "proceed"}, m)
|
|
|
|
def test_route_runs_as_the_guest_with_their_grant(self):
|
|
self.install_fresh()
|
|
self.mode("modal")
|
|
g = TestClient(main.app, base_url="https://claude.example.test")
|
|
g.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(self.dom["id"]))
|
|
r = g.post("/api/plugins/composer/before-send", json={"mode": "resume"},
|
|
headers={"Origin": "https://claude.example.test"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["init"]["uid"], self.dom["id"])
|
|
out = composer_bridge.before_send(DEPS, self.guest(), {"mode": "resume"})
|
|
self.assertEqual(out["init"]["uid"], self.dom["id"])
|
|
self.assertEqual(out["init"]["grant"]["autoFresh"], True)
|
|
self.store.set_grant(self.dom["id"], "fresh-context", enabled=False)
|
|
self.assertEqual(composer_bridge.before_send(DEPS, self.guest(), {}), {"verdict": "proceed"})
|
|
|
|
def test_compact_spec(self):
|
|
self.assertIsNone(composer_bridge.compact_spec(DEPS, None, SID, "claude-opus-5-5"))
|
|
self.install_fresh()
|
|
self.assertEqual(composer_bridge.compact_spec(DEPS, None, SID, "claude-opus-5-5"),
|
|
{"model": "claude-opus-5-5", "instructions": f"Summary for {SID}"})
|
|
self.assertEqual(composer_bridge.compact_spec(DEPS, self.dom["id"], SID, None)["model"],
|
|
"haiku")
|
|
|
|
def test_clean_compact(self):
|
|
c = composer_bridge.clean_compact
|
|
self.assertEqual(c({"model": " sonnet ", "instructions": "x"}), {"model": "sonnet", "instructions": "x"})
|
|
self.assertIsNone(c({"model": "sonnet"}))
|
|
self.assertIsNone(c({"model": "x" * 121, "instructions": "x"}))
|
|
self.assertIsNone(c({"model": "rm -rf /", "instructions": "x"}))
|
|
self.assertIsNone(c({"model": "haiku", "instructions": "x" * 8001}))
|
|
self.assertIsNone(c({"model": "haiku", "instructions": " "}))
|
|
self.assertIsNone(c("haiku"))
|
|
|
|
|
|
# ── 5. composer.send slots ──────────────────────────────────────────────────
|
|
class ComposerSendSlots(_StoreCase):
|
|
def _mf(self, **slot):
|
|
d = _fresh_plugin(self.root, "slotty")
|
|
raw = json.loads((d / "plugin.json").read_text())
|
|
raw["ui"]["slots"][1] = {"id": "s", "where": "composer.send", "html": "ui/m.html", **slot}
|
|
(d / "plugin.json").write_text(json.dumps(raw))
|
|
return validate_manifest(d)
|
|
|
|
def test_new_keys_are_kept_when_set(self):
|
|
sl = self._mf(contexts=["resume", "spawn"], guestAllowed=True,
|
|
requiresHarnessCap="fresh_context", directAction="fresh")["ui"]["slots"][1]
|
|
self.assertEqual(sl["contexts"], ["spawn", "resume"])
|
|
self.assertTrue(sl["guestAllowed"])
|
|
self.assertEqual(sl["requiresHarnessCap"], "fresh_context")
|
|
self.assertEqual(sl["directAction"], "fresh")
|
|
|
|
def test_unset_keys_are_not_written(self):
|
|
sl = self._mf()["ui"]["slots"][1]
|
|
for k in ("contexts", "guestAllowed", "requiresHarnessCap", "directAction"):
|
|
self.assertNotIn(k, sl)
|
|
sl = self._mf(guestAllowed=False)["ui"]["slots"][1]
|
|
self.assertNotIn("guestAllowed", sl)
|
|
|
|
def test_direct_action_needs_no_html(self):
|
|
d = _fresh_plugin(self.root, "nohtml")
|
|
raw = json.loads((d / "plugin.json").read_text())
|
|
raw["ui"]["slots"][1].pop("html", None)
|
|
(d / "plugin.json").write_text(json.dumps(raw))
|
|
self.assertEqual(validate_manifest(d)["ui"]["slots"][1]["directAction"], "fresh")
|
|
|
|
def test_bad_values(self):
|
|
for slot, msg in (({"contexts": ["home"]}, "contexts"),
|
|
({"contexts": []}, "contexts"),
|
|
({"guestAllowed": "yes"}, "guestAllowed"),
|
|
({"requiresHarnessCap": "teleport"}, "requiresHarnessCap"),
|
|
({"directAction": "missing"}, "directAction")):
|
|
with self.subTest(slot=slot), self.assertRaises(ManifestError) as cm:
|
|
self._mf(**slot)
|
|
self.assertIn(msg, str(cm.exception))
|
|
|
|
def test_keys_only_on_composer_send(self):
|
|
d = _fresh_plugin(self.root, "elsewhere")
|
|
raw = json.loads((d / "plugin.json").read_text())
|
|
raw["ui"]["slots"][0]["guestAllowed"] = True
|
|
(d / "plugin.json").write_text(json.dumps(raw))
|
|
with self.assertRaises(ManifestError) as cm:
|
|
validate_manifest(d)
|
|
self.assertIn("is for composer.send slots", str(cm.exception))
|
|
|
|
def test_ui_route_serves_them_and_filters_for_guests(self):
|
|
self.install_fresh()
|
|
d = _fresh_plugin(self.root, "owner-send")
|
|
raw = json.loads((d / "plugin.json").read_text())
|
|
raw["ui"]["slots"][1] = {"id": "later", "where": "composer.send", "html": "ui/m.html"}
|
|
raw.pop("provides")
|
|
(d / "plugin.json").write_text(json.dumps(raw))
|
|
self.store.install(OWNER_UID, str(d), is_owner=True, approve=True)
|
|
r = self.client.get("/api/plugins/ui", headers=OWNER_H)
|
|
sends = {s["id"]: s for s in r.json()["ui"]["slots"] if s["where"] == "composer.send"}
|
|
self.assertEqual(sends["send-fresh"]["directAction"], "fresh")
|
|
self.assertEqual(sends["send-fresh"]["contexts"], ["resume"])
|
|
self.assertIn("later", sends)
|
|
g = TestClient(main.app, base_url="https://claude.example.test")
|
|
g.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(self.dom["id"]))
|
|
r = g.get("/api/plugins/ui")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
gs = [s["id"] for s in r.json()["ui"]["slots"] if s["where"] == "composer.send"]
|
|
self.assertEqual(gs, ["send-fresh"]) # the guest-allowed one only
|
|
self.assertIn("composer.beforeSend", r.json()["provides"])
|
|
|
|
|
|
# ── 6. /api/resume compact / fresh ──────────────────────────────────────────
|
|
class ResumeCompact(_StoreCase):
|
|
def setUp(self):
|
|
super().setUp()
|
|
self.launched: list[dict] = []
|
|
self._orig = (run_service._launch, run_service._sidecar_call)
|
|
|
|
def fake_launch(deps, account, path, payload, worker=None):
|
|
self.launched.append(payload)
|
|
return {"sessionId": payload["sessionId"], "pid": 1}
|
|
|
|
def no_inbox(*a, **k):
|
|
raise HTTPException(404, "no live run")
|
|
run_service._launch = fake_launch
|
|
run_service._sidecar_call = no_inbox
|
|
|
|
def tearDown(self):
|
|
run_service._launch, run_service._sidecar_call = self._orig
|
|
super().tearDown()
|
|
|
|
def send(self, **kw):
|
|
return run_service._send_message(DEPS, "hello", session_id=SID, harness="claude", **kw)
|
|
|
|
def test_explicit_compact_goes_to_the_sidecar(self):
|
|
try:
|
|
self.send(compact={"model": "haiku", "instructions": "keep"})
|
|
except HTTPException as e: # something later in the path the test can't fake
|
|
self.assertNotIn("compact", str(e.detail))
|
|
self.assertTrue(self.launched)
|
|
self.assertEqual(self.launched[0]["compact"], {"model": "haiku", "instructions": "keep"})
|
|
|
|
def test_bad_compact_is_400(self):
|
|
with self.assertRaises(HTTPException) as cm:
|
|
self.send(compact={"model": "haiku"})
|
|
self.assertEqual(cm.exception.status_code, 400)
|
|
|
|
def test_fresh_without_a_provider_is_400(self):
|
|
with self.assertRaises(HTTPException) as cm:
|
|
self.send(fresh=True)
|
|
self.assertEqual(cm.exception.status_code, 400)
|
|
self.assertIn("runs.compact", str(cm.exception.detail))
|
|
|
|
def test_fresh_asks_the_provider(self):
|
|
self.install_fresh()
|
|
try:
|
|
self.send(fresh=True)
|
|
except HTTPException as e:
|
|
self.assertNotIn("compact", str(e.detail))
|
|
self.assertTrue(self.launched)
|
|
self.assertEqual(self.launched[0]["compact"]["instructions"], f"Summary for {SID}")
|
|
|
|
def test_a_harness_without_the_cap_is_400(self):
|
|
with self.assertRaises(HTTPException) as cm:
|
|
run_service._compact_for(DEPS, SID, "agy", {"model": "haiku", "instructions": "x"},
|
|
False, None)
|
|
self.assertEqual(cm.exception.status_code, 400)
|
|
self.assertIsNone(run_service._compact_for(DEPS, SID, "agy", None, False, None))
|
|
|
|
def test_resume_body_takes_compact(self):
|
|
from runs.routes import ResumeBody
|
|
b = ResumeBody(sessionId=SID, prompt="x", compact={"model": "haiku", "instructions": "x"})
|
|
self.assertEqual(b.compact["model"], "haiku")
|
|
self.assertFalse(b.fresh)
|
|
|
|
|
|
# ── 7. the core's old fresh context is gone ─────────────────────────────────
|
|
class Retired(unittest.TestCase):
|
|
def test_routes_and_state(self):
|
|
paths = {getattr(r, "path", "") for r in main.app.routes}
|
|
self.assertNotIn("/api/fresh-context", paths)
|
|
self.assertFalse(hasattr(DEPS, "fresh_store"))
|
|
with self.assertRaises(ImportError):
|
|
__import__("runs.fresh")
|
|
|
|
def test_me_has_no_auto_fresh(self):
|
|
r = TestClient(main.app).get("/api/me", headers=OWNER_H)
|
|
self.assertNotIn("autoFresh", r.json())
|
|
|
|
|
|
# ── 8. carryover.fresh_context ──────────────────────────────────────────────
|
|
class Carryover(_StoreCase):
|
|
def legacy(self, data) -> pathlib.Path:
|
|
p = self.root / "fresh-context.json"
|
|
p.write_text(json.dumps(data))
|
|
return p
|
|
|
|
def test_settings_and_grants(self):
|
|
src = self.legacy({"enabled": True, "minSavingsUsd": 1.0, "autoFresh": True,
|
|
"model": "sonnet", "assumptions": {"x": 1}})
|
|
raw = DEPS.users._data["users"][self.dom["id"]]
|
|
raw["autoFresh"] = False
|
|
eve = DEPS.users.create("eve@example.com", "Eve")
|
|
# Not installed yet: the settings move, the grants wait.
|
|
self.assertTrue(carryover.fresh_context(self.store, DEPS.users, legacy=str(src)))
|
|
dst = self.store.shared_data_dir("fresh-context") / "settings.json"
|
|
self.assertEqual(json.loads(dst.read_text()),
|
|
{"enabled": True, "minSavingsUsd": 1.0, "autoFresh": True, "model": "sonnet"})
|
|
self.assertFalse(src.exists())
|
|
self.assertTrue(src.with_name("fresh-context.json.migrated").exists())
|
|
marker = self.store.shared_data_dir("fresh-context") / ".carried-over"
|
|
self.assertFalse(marker.exists())
|
|
# Installed: the guests' picks land on their grant, once.
|
|
self.install_fresh()
|
|
self.assertTrue(carryover.fresh_context(self.store, DEPS.users, legacy=str(src)))
|
|
self.assertTrue(marker.exists())
|
|
g = self.store.effective_grant(self.dom["id"], "fresh-context")
|
|
self.assertIs(g["config"]["autoFresh"], False)
|
|
self.assertTrue(g["enabled"])
|
|
self.assertTrue(self.store.effective_grant(eve["id"], "fresh-context")["isDefault"])
|
|
self.assertFalse(carryover.fresh_context(self.store, DEPS.users, legacy=str(src)))
|
|
|
|
def test_keeps_an_existing_plugin_settings_file(self):
|
|
dst = self.store.shared_data_dir("fresh-context") / "settings.json"
|
|
dst.write_text('{"mine": 1}')
|
|
src = self.legacy({"enabled": False})
|
|
carryover.fresh_context(self.store, None, legacy=str(src))
|
|
self.assertEqual(json.loads(dst.read_text()), {"mine": 1})
|
|
self.assertTrue((self.store.shared_data_dir("fresh-context") / ".carried-over").exists())
|
|
|
|
def test_nothing_to_carry(self):
|
|
self.assertFalse(carryover.fresh_context(self.store, DEPS.users,
|
|
legacy=str(self.root / "missing.json")))
|
|
self.assertTrue((self.store.shared_data_dir("fresh-context") / ".carried-over").exists())
|
|
|
|
|
|
# ── 9. the parser: cache clock + divider, no saving ─────────────────────────
|
|
class CacheClock(unittest.TestCase):
|
|
def test_last_call_and_the_1h_tier(self):
|
|
s = T().user("go").reply("a", 60_000, w1h=60_000).reply("b", 61_000).parse()
|
|
self.assertEqual(s["lastCallAt"], "2026-10-30T10:00:03.000Z")
|
|
self.assertEqual(s["cacheTtl"], 3600)
|
|
self.assertEqual(s["contextTokens"], 61_100)
|
|
|
|
def test_the_5m_tier(self):
|
|
self.assertEqual(T().user("go").reply("a", 60_000, w5m=60_000).parse()["cacheTtl"], 300)
|
|
|
|
def test_no_write_no_ttl(self):
|
|
self.assertIsNone(T().user("go").reply("a", 60_000).parse()["cacheTtl"])
|
|
|
|
|
|
class Compaction(unittest.TestCase):
|
|
def convo(self, idle=0):
|
|
return (T().user("go").reply("a", 50_000, w1h=50_000).reply("b", 190_000)
|
|
.cost_state(**{"claude-opus-5-5": (20, 200), "claude-haiku-5-5": (1000, 10)})
|
|
.idle(idle).compact(190_000, 16_000)
|
|
.cost_state(**{"claude-opus-5-5": (20, 200),
|
|
"claude-haiku-5-5": (1000 + 190_000, 10 + 8_000)}))
|
|
|
|
def test_divider_with_summary_and_cost(self):
|
|
s = self.convo().parse(full=True)
|
|
[it] = [i for i in s["thread"] if i.get("kind") == "compact"]
|
|
self.assertEqual(it["compact"], {"trigger": "manual", "preTokens": 190_000,
|
|
"postTokens": 16_000, "durationMs": 26544})
|
|
self.assertEqual(it["text"], "1. Primary Request: ship it.")
|
|
self.assertEqual(it["model"], "claude-haiku-5-5")
|
|
self.assertAlmostEqual(it["turnCost"], 0.19 * 0.5 + 0.008 * 2.5, places=6)
|
|
self.assertEqual(s["compactions"], 1)
|
|
self.assertEqual(s["contextTokens"], s["firstContextTokens"] + 16_000)
|
|
|
|
def test_no_saving_is_computed_any_more(self):
|
|
s = (self.convo(idle=2 * 3600).user("next").reply("c", 60_000, w1h=36_000)
|
|
.reply("d", 62_000).parse(full=True))
|
|
it = next(i for i in s["thread"] if i.get("kind") == "compact")
|
|
self.assertNotIn("saved", it["compact"])
|
|
from conversations.parse import usage
|
|
self.assertFalse(hasattr(usage, "FRESH_EXPIRY_MARGIN_MS"))
|
|
self.assertFalse(hasattr(usage.UsageMeter, "gain_prompt"))
|
|
self.assertFalse(hasattr(usage.UsageMeter, "gain_call"))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|