Approvals, New project and Plans now build on the ask-form live plugin, so
nothing creates frm_ forms any more. Per Gabriel's call ("retire
completely", no read-only viewer):
- backend: delete forms/ (routes, service, store, secrets), schemas/forms,
the /api/forms* routes and their authz lines, the worker outbox's `form`
kind, the frm_ scan in tree.py and the pending-forms check in auto-archive
- cli: drop notify wait frm_ / cancel / secret (ask-form secret replaces it)
- frontend: delete FormWidget, FormModal, FormPager, FormFields, formDraft,
formGroups, the Forms page (/forms now redirects to the ask-form plugin's
Forms page) and the generated form models; the dock keeps ask-form frames
only; SandboxedHtml stays
- merge fix-ups: a conflict marker left in cli/notify.py's docstring, the
BottomBar test's Files sub-links, an unused French string, and the
FormDock test now warms the lazy AskFormFrame chunk (its cold import
outlasted waitFor once FormModal stopped importing it statically)
- docs: CLAUDE.md and docs/clarifier.md no longer describe frm_ forms
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
281 lines
13 KiB
Python
281 lines
13 KiB
Python
"""The fetch diet: a live thread is parsed incrementally and served as a
|
|
delta, `transcript` events carry the cards they moved, and the SSE stream
|
|
resumes from `Last-Event-ID` instead of making every tab refetch.
|
|
|
|
Imports ``main`` against throwaway paths (no startup event → no threads)."""
|
|
|
|
import datetime
|
|
import json
|
|
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",
|
|
"NEW_PROJECTS_PATH": TMP / "np.json", "PROJECTS_DIR": TMP / "projects",
|
|
"INTERNAL_API_TOKEN": "tok", "SIDECAR_TOKEN": "",
|
|
"PI_TRANSCRIPTS_DIR": "", "RUNNING_WINDOW_SECS": "600"}.items():
|
|
os.environ[k] = str(v)
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from conversations import ids # noqa: E402
|
|
from conversations.card import cards_for # noqa: E402
|
|
from events import Hub # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
PROJ = "-home-x"
|
|
SID = "11111111-2222-3333-4444-555555555555"
|
|
CID = f"{PROJ}/{SID}.jsonl"
|
|
PATH = TMP / "arch" / PROJ / f"{SID}.jsonl"
|
|
|
|
|
|
def ago(secs: float) -> str:
|
|
t = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(seconds=secs)
|
|
return t.isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
|
|
|
|
def rec(kind: str, uid: str, content, secs: float = 10, mid: str = "m") -> dict:
|
|
base = {"sessionId": SID, "type": kind, "uuid": uid, "timestamp": ago(secs)}
|
|
if kind == "user":
|
|
return {**base, "message": {"role": "user", "content": content}}
|
|
return {**base, "message": {"role": "assistant", "id": mid, "model": "claude-opus-5-5",
|
|
"content": content}}
|
|
|
|
|
|
def write(records: list[dict], append: bool = False) -> None:
|
|
PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
with PATH.open("a" if append else "w") as fh:
|
|
fh.write("\n".join(json.dumps(o) for o in records) + "\n")
|
|
DEPS.indexer.scan_transcripts()
|
|
|
|
|
|
class DeltaThread(unittest.TestCase):
|
|
def setUp(self):
|
|
self.c = TestClient(main.app, headers={"x-internal-auth": "tok"})
|
|
write([rec("user", "u1", "hello", 30),
|
|
rec("assistant", "a1", [{"type": "text", "text": "hi"}], 29, "m1"),
|
|
rec("assistant", "a2", [{"type": "tool_use", "id": "t1", "name": "Read",
|
|
"input": {"file_path": "/x"}}], 28, "m2")])
|
|
|
|
def get(self, **params):
|
|
r = self.c.get("/api/conversation", params={"id": CID, **params})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
return r.json()
|
|
|
|
def test_first_fetch_is_whole_and_carries_a_rev(self):
|
|
d = self.get()
|
|
self.assertEqual(d["threadFrom"], 0)
|
|
self.assertTrue(d["rev"])
|
|
self.assertEqual([t["kind"] for t in d["thread"]][:2], ["text", "text"][:0] or
|
|
[t["kind"] for t in d["thread"]][:2])
|
|
self.assertGreaterEqual(len(d["thread"]), 3)
|
|
|
|
def test_unchanged_delta_is_empty(self):
|
|
d = self.get()
|
|
d2 = self.get(since=d["rev"])
|
|
self.assertEqual(d2["rev"], d["rev"])
|
|
self.assertEqual(d2["threadFrom"], len(d["thread"]))
|
|
self.assertEqual(d2["thread"], [])
|
|
|
|
def test_appended_records_come_as_a_delta_that_rebuilds_the_thread(self):
|
|
d = self.get()
|
|
n = len(d["thread"])
|
|
# The tool result lands *on* the pending Read card (an in-place
|
|
# mutation of an existing item), then a new text turn is appended.
|
|
write([rec("user", "u2", [{"type": "tool_result", "tool_use_id": "t1",
|
|
"content": "file body"}], 20),
|
|
rec("assistant", "a3", [{"type": "text", "text": "done"}], 19, "m3")],
|
|
append=True)
|
|
full = self.get()
|
|
delta = self.get(since=d["rev"])
|
|
self.assertNotEqual(delta["rev"], d["rev"])
|
|
self.assertLess(delta["threadFrom"], n, "the mutated Read card is inside the window")
|
|
rebuilt = d["thread"][:delta["threadFrom"]] + delta["thread"]
|
|
self.assertEqual(rebuilt, full["thread"])
|
|
self.assertEqual(delta["usage"], full["usage"])
|
|
|
|
def test_running_agent_cards_come_as_patches_not_a_wider_window(self):
|
|
# A Task card early in the thread whose agent is still running: a
|
|
# later delta re-sends that card by index instead of starting the
|
|
# window at it.
|
|
sub = PATH.parent / SID / "subagents"
|
|
sub.mkdir(parents=True, exist_ok=True)
|
|
write([rec("assistant", "a9", [{"type": "tool_use", "id": "tagent", "name": "Agent",
|
|
"input": {"description": "dig", "prompt": "dig",
|
|
"subagent_type": "Explore",
|
|
"run_in_background": True}}], 8, "m9"),
|
|
rec("user", "u9", [{"type": "tool_result", "tool_use_id": "tagent",
|
|
"content": "Async agent launched successfully.\nagentId: a1"}], 7)],
|
|
append=True)
|
|
(sub / "agent-a1.jsonl").write_text(json.dumps(
|
|
{**rec("user", "s1", "dig", 5), "isSidechain": True, "agentId": "a1"}) + "\n")
|
|
(sub / "agent-a1.meta.json").write_text(json.dumps(
|
|
{"agentType": "Explore", "description": "dig", "toolUseId": "tagent", "spawnDepth": 1}))
|
|
DEPS.indexer.scan_transcripts()
|
|
d = self.get()
|
|
idx = next(i for i, it in enumerate(d["thread"]) if it.get("agentRunning"))
|
|
write([rec("assistant", "a10", [{"type": "text", "text": "later"}], 2, "m10")], append=True)
|
|
delta = self.get(since=d["rev"])
|
|
self.assertGreater(delta["threadFrom"], idx, "the window starts after the running card")
|
|
self.assertIn(str(idx), delta["threadPatch"])
|
|
full = self.get()
|
|
rebuilt = list(d["thread"][:delta["threadFrom"]])
|
|
for k, it in delta["threadPatch"].items():
|
|
rebuilt[int(k)] = it
|
|
rebuilt += delta["thread"]
|
|
self.assertEqual(rebuilt, full["thread"])
|
|
|
|
def test_a_foreign_rev_gets_the_whole_thread(self):
|
|
self.get()
|
|
d = self.get(since="deadbeef:3")
|
|
self.assertEqual(d["threadFrom"], 0)
|
|
self.assertGreaterEqual(len(d["thread"]), 3)
|
|
|
|
def test_a_request_overtaken_mid_way_still_rebuilds_the_thread(self):
|
|
# Two requests for a live thread overlap (two tabs, or a client that
|
|
# cancels and re-asks on every ping): this one takes its snapshot, and
|
|
# while it decorates it another request reads the grown transcript.
|
|
# Its rev and its delta must still describe the thread it sends — a
|
|
# rev from the later snapshot made the next delta start past the end
|
|
# of what the client held, and the viewer kept only that delta: the
|
|
# latest message alone, the rest of the thread gone.
|
|
from conversations import routes
|
|
d = self.get()
|
|
write([rec("assistant", "a3", [{"type": "text", "text": "one"}], 20, "m3")], append=True)
|
|
real = routes.artefacts_mod.list_for_conversation
|
|
state = {"fired": False}
|
|
|
|
def overtaken(*a, **kw):
|
|
if not state["fired"]:
|
|
state["fired"] = True
|
|
write([rec("assistant", "a4", [{"type": "text", "text": "two"}], 19, "m4")],
|
|
append=True)
|
|
routes._parse_full_cached(PATH) # the other request's snapshot
|
|
return real(*a, **kw)
|
|
|
|
routes.artefacts_mod.list_for_conversation = overtaken
|
|
try:
|
|
mid = self.get(since=d["rev"])
|
|
finally:
|
|
routes.artefacts_mod.list_for_conversation = real
|
|
held = d["thread"][:mid["threadFrom"]] + mid["thread"]
|
|
self.assertEqual([t.get("text") for t in held][-1], "one", "this request's own snapshot")
|
|
nxt = self.get(since=mid["rev"])
|
|
self.assertLessEqual(nxt["threadFrom"], len(held), "the next delta starts inside what the client holds")
|
|
self.assertEqual(held[:nxt["threadFrom"]] + nxt["thread"], self.get()["thread"])
|
|
|
|
def test_transcript_event_cards_match_the_summary_endpoint(self):
|
|
cards = cards_for(DEPS, [CID, f"{PROJ}/{SID}/subagents/agent-zz.jsonl"])
|
|
uid = ids.uid_for_rel(CID)
|
|
self.assertEqual(list(cards), [uid])
|
|
summary = self.c.get("/api/conversation-summary", params={"id": uid}).json()
|
|
self.assertEqual(cards[uid], summary)
|
|
|
|
def test_per_conversation_agents_match_the_global_map(self):
|
|
# A subagent transcript with a recorded type, plus a manual agent run
|
|
# stamped on the session: the per-ping lookup (card / thread) must
|
|
# list what the agents catalog's whole-store map lists.
|
|
from conversations.catalog import _agents_by_conversation
|
|
sub = PATH.parent / SID / "subagents"
|
|
sub.mkdir(parents=True, exist_ok=True)
|
|
(sub / "agent-a1.jsonl").write_text(json.dumps(
|
|
{**rec("user", "s1", "dig", 5), "isSidechain": True, "agentId": "a1"}) + "\n")
|
|
(sub / "agent-a1.meta.json").write_text(json.dumps(
|
|
{"agentType": "Explore", "description": "dig", "toolUseId": "t9", "spawnDepth": 1}))
|
|
DEPS.meta_store.update(SID, {"agentRun": {"name": "radar", "at": ago(1)}}) \
|
|
if hasattr(DEPS.meta_store, "update") else None
|
|
DEPS.indexer.scan_transcripts()
|
|
card = cards_for(DEPS, [CID])[ids.uid_for_rel(CID)]
|
|
expected = _agents_by_conversation(DEPS).get(ids.uid_for_rel(CID), [])
|
|
self.assertIn("Explore", card["agentsUsed"])
|
|
self.assertEqual(card["agentsUsed"], expected)
|
|
self.assertEqual(self.get()["agentsUsed"], expected)
|
|
|
|
|
|
class ResumableEvents(unittest.TestCase):
|
|
def test_replay_after_a_known_id(self):
|
|
hub = Hub()
|
|
q = hub.subscribe()
|
|
hub.publish({"type": "meta"})
|
|
hub.publish({"type": "transcript", "ids": ["a"]})
|
|
first_id, _ = q.get_nowait()
|
|
replay = hub.replay_since(first_id)
|
|
self.assertEqual([json.loads(d)["type"] for _, d in replay], ["transcript"])
|
|
self.assertEqual(hub.replay_since(hub.last_id), [])
|
|
|
|
def test_unknown_or_foreign_id_means_resync(self):
|
|
hub = Hub()
|
|
hub.publish({"type": "meta"})
|
|
self.assertIsNone(hub.replay_since("cafe-1")) # another process
|
|
self.assertIsNone(hub.replay_since(f"{hub.epoch}-9")) # from the future
|
|
hub2 = Hub()
|
|
hub2.RING = 2
|
|
hub2._ring = __import__("collections").deque(maxlen=2)
|
|
for _ in range(5):
|
|
hub2.publish({"type": "meta"})
|
|
self.assertIsNone(hub2.replay_since(hub2.event_id(1))) # fell off the ring
|
|
self.assertEqual(len(hub2.replay_since(hub2.event_id(3))), 2)
|
|
|
|
def test_replay_goes_through_the_subscribers_filter(self):
|
|
hub = Hub()
|
|
hub.publish({"type": "transcript", "ids": ["a"], "cards": {"a": {"id": "a"}}})
|
|
hub.publish({"type": "secret"})
|
|
out = hub.replay_since(hub.event_id(0), lambda ev: ev if ev["type"] != "secret" else None)
|
|
self.assertEqual([json.loads(d)["type"] for _, d in out], ["transcript"])
|
|
|
|
def test_the_stream_resumes_with_last_event_id(self):
|
|
# The endpoint's generator, read directly: a TestClient stream would
|
|
# block on the 15-s keepalive and never release the 9-minute loop.
|
|
# The route is async (it subscribes on the running loop), so it is
|
|
# awaited inside the loop that then reads the stream.
|
|
from core.routes import events as events_route
|
|
from users.caller import Caller
|
|
|
|
class Req:
|
|
def __init__(self, last):
|
|
self.headers = {"last-event-id": last} if last else {}
|
|
|
|
owner = Caller(id="owner", role="owner", name="Gabriel")
|
|
|
|
def head(last, n):
|
|
import asyncio
|
|
|
|
async def read():
|
|
resp = await events_route(Req(last), DEPS, owner)
|
|
gen = resp.body_iterator
|
|
out = []
|
|
try:
|
|
async for chunk in gen:
|
|
out.append(chunk if isinstance(chunk, str) else chunk.decode())
|
|
if len(out) >= n:
|
|
break
|
|
finally:
|
|
await gen.aclose()
|
|
return "".join(out)
|
|
return asyncio.run(read())
|
|
|
|
DEPS.hub.publish({"type": "meta"})
|
|
DEPS.hub.publish({"type": "cron"})
|
|
text = head(DEPS.hub.event_id(DEPS.hub._seq - 1), 2)
|
|
self.assertIn("retry:", text)
|
|
self.assertIn('"type": "cron"', text)
|
|
self.assertNotIn('"meta"', text)
|
|
self.assertIn('"resync"', head("dead-1", 2))
|
|
self.assertIn("retry:", head(None, 1))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|