Files
ai-agent/backend/test_closing_notify.py
gabrielvidalandClaude Opus 5.5 9a9c7733df feat(notifications): the closing push is a ```notify block ending the final message
The parser cuts a trailing ```notify JSON block out of a main-thread
assistant message (closing_notify.split) and keeps it on the thread item
(notify) and the summary (closingNotify); the indexer hands it to
notifications/closing.maybe_push, which pushes it once — id from the
block's time and words, skipped when already logged or older than 15 min —
with final: true and the CLI's cost line rebuilt from the summary.

The push now leaves once the message it announces is in the transcript,
instead of ~11 s (p90 24 s) before it, and the closing tool call (one
full-context request) is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 22:39:59 +01:00

170 lines
6.9 KiB
Python

"""The closing push block: a run ends its final message on a ```notify block,
the parser cuts it out of the text, the indexer hands it to
notifications/closing.py, which pushes it once."""
import datetime
import json
import pathlib
import tempfile
import threading
import unittest
from unittest import mock
import conversations as c
from conversations import closing_notify
from notifications import closing
SID = "11111111-2222-3333-4444-555555555555"
BLOCK = '```notify\n{"title": "Deployed", "message": "all green", "type": "deploy"}\n```'
def now_iso(ago: float = 0) -> str:
t = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(seconds=ago)
return t.isoformat(timespec="milliseconds").replace("+00:00", "Z")
def user(text, ts="2026-11-23T10:00:00.000Z"):
return {"type": "user", "sessionId": SID, "timestamp": ts, "uuid": "u0",
"message": {"role": "user", "content": text}}
def assistant(text, ts="2026-11-23T10:00:05.000Z", uuid="a1", **kw):
return {"type": "assistant", "sessionId": SID, "timestamp": ts, "uuid": uuid,
"message": {"role": "assistant", "id": uuid, "model": "claude-opus-5-5",
"content": [{"type": "text", "text": text}],
"usage": {"input_tokens": 1, "output_tokens": 1}}, **kw}
class SplitTest(unittest.TestCase):
def test_a_trailing_block_is_cut_out(self):
text, block = closing_notify.split("Shipped it.\n\n" + BLOCK)
self.assertEqual(text, "Shipped it.")
self.assertEqual(block, {"title": "Deployed", "message": "all green", "type": "deploy"})
def test_trailing_whitespace_after_the_fence_is_fine(self):
self.assertIsNotNone(closing_notify.split("x\n" + BLOCK + "\n\n ")[1])
def test_a_block_mid_message_stays_text(self):
src = "Example:\n" + BLOCK + "\nand more words after it."
self.assertEqual(closing_notify.split(src), (src, None))
def test_only_the_last_block_counts(self):
src = "Quoted:\n" + BLOCK.replace("Deployed", "Example") + "\nDone.\n" + BLOCK
text, block = closing_notify.split(src)
self.assertEqual(block["title"], "Deployed")
self.assertTrue(text.endswith("Done."))
self.assertIn("Example", text)
def test_bad_json_stays_visible(self):
src = 'x\n```notify\n{"title": "oops",}\n```'
self.assertEqual(closing_notify.split(src), (src, None))
def test_needs_a_title_or_a_message(self):
src = 'x\n```notify\n{"type": "code"}\n```'
self.assertIsNone(closing_notify.split(src)[1])
def test_body_is_read_as_message_and_unknown_keys_dropped(self):
_, block = closing_notify.split('```notify\n{"title": "T", "body": "B", "x": 1}\n```')
self.assertEqual(block, {"title": "T", "message": "B"})
def test_a_message_that_is_only_the_block(self):
self.assertEqual(closing_notify.split(BLOCK)[0], "")
def test_other_fences_are_not_blocks(self):
src = "x\n```json\n{\"title\": \"T\"}\n```"
self.assertEqual(closing_notify.split(src), (src, None))
class ParserTest(unittest.TestCase):
def parse(self, recs, full=True):
with tempfile.TemporaryDirectory() as d:
p = pathlib.Path(d) / f"{SID}.jsonl"
p.write_text("".join(json.dumps(r) + "\n" for r in recs))
return c.parse_conversation(p, full=full)
def test_the_item_loses_the_block_and_carries_the_push(self):
s = self.parse([user("go"), assistant("Done.\n\n" + BLOCK)])
item = [i for i in s["thread"] if i["role"] == "assistant" and i["kind"] == "text"][-1]
self.assertEqual(item["text"], "Done.")
self.assertEqual(item["notify"]["title"], "Deployed")
self.assertEqual(s["closingNotify"]["uuid"], "a1")
self.assertEqual(s["closingNotify"]["at"], "2026-11-23T10:00:05.000Z")
def test_the_summary_keeps_the_latest_block(self):
s = self.parse([user("go"), assistant("one\n" + BLOCK),
user("again", ts="2026-11-23T10:01:00.000Z"),
assistant("two\n" + BLOCK.replace("Deployed", "Again"),
ts="2026-11-23T10:01:05.000Z", uuid="a2")], full=False)
self.assertEqual(s["closingNotify"]["title"], "Again")
def test_no_block_no_push(self):
self.assertIsNone(self.parse([user("go"), assistant("Done.")], full=False)["closingNotify"])
def test_a_sidechain_block_is_not_the_runs_push(self):
s = self.parse([user("go"), assistant("sub\n" + BLOCK, isSidechain=True)], full=False)
self.assertIsNone(s["closingNotify"])
class FakeStore:
def __init__(self, known=()):
self.known = set(known)
def get(self, nid):
return {"id": nid} if nid in self.known else None
class PushTest(unittest.TestCase):
def setUp(self):
closing._seen.clear()
self.deps = mock.Mock(notify_store=FakeStore())
self.sent: list[dict] = []
self.done = threading.Event()
def fake_create(deps, d):
self.sent.append(d)
self.done.set()
p = mock.patch("notifications.service._create_notify", fake_create)
p.start()
self.addCleanup(p.stop)
def summary(self, **kw):
return {"sessionId": SID, "harness": None, "cost": 1.234, "tokens": 78_000,
"startedAt": now_iso(518), **kw}
def block(self, ago=2, **kw):
return {"title": "Deployed", "message": "all green", "type": "deploy",
"uuid": "a1", "at": now_iso(ago), **kw}
def test_pushes_once_with_the_cost_line_and_final(self):
b = self.block()
nid = closing.maybe_push(self.deps, self.summary(), b)
self.assertTrue(nid and nid.startswith("ntf_") and len(nid) == 16)
self.assertTrue(self.done.wait(5))
d = self.sent[0]
self.assertEqual((d["id"], d["sessionId"], d["final"], d["title"], d["type"]),
(nid, SID, True, "Deployed", "deploy"))
self.assertTrue(d["message"].startswith("all green\nClaude Code · $1.23 · 78k tokens · 8m"))
self.assertNotIn("uuid", d)
# every later re-parse hands the same block again
self.assertIsNone(closing.maybe_push(self.deps, self.summary(), dict(b)))
self.assertEqual(len(self.sent), 1)
def test_an_old_block_is_never_pushed(self):
self.assertIsNone(closing.maybe_push(self.deps, self.summary(), self.block(ago=3600)))
def test_a_block_already_in_the_log_is_skipped(self):
b = self.block()
self.deps.notify_store = FakeStore([closing.push_id(b)])
self.assertIsNone(closing.maybe_push(self.deps, self.summary(), b))
def test_the_same_block_in_a_forked_copy_has_the_same_id(self):
b = self.block()
self.assertEqual(closing.push_id(b), closing.push_id({**b, "uuid": "other"}))
def test_harness_label(self):
self.assertTrue(closing.cost_line({"harness": "opencode", "cost": 0}, "").startswith("OpenCode · $0.00"))
if __name__ == "__main__":
unittest.main()