178 lines
9.1 KiB
Python
178 lines
9.1 KiB
Python
"""Past conversations on a subject (conversations/past.py): the hue resource
|
|
(with the fixture ``linear`` plugin, the issue) as the subject — a PR (a
|
|
``shade``) maps to the issue its head branch names — running ones apart,
|
|
primary-then-newest within 30 days, the last message that names the subject,
|
|
and a worker's lookup answered in the outbox ack. ``python -m pytest
|
|
test_past.py`` from ``backend/``."""
|
|
|
|
import datetime as dt
|
|
import types
|
|
import unittest
|
|
from unittest import mock
|
|
|
|
from conversations import catalog, past
|
|
from conversations import related as related_mod
|
|
from conversations import resource_view
|
|
from fixtures.resource_plugins.kit import FakePluginStore, registry
|
|
from test_conv_refs import real_store
|
|
from workers import outbox_mirror
|
|
|
|
NOW = dt.datetime(2026, 11, 3, 12, 0, tzinfo=dt.timezone.utc)
|
|
REPO = "o/r"
|
|
|
|
|
|
def iso(days_ago: float) -> str:
|
|
return (NOW - dt.timedelta(days=days_ago)).strftime("%Y-%m-%dT%H:%M:%S.000Z")
|
|
|
|
|
|
def card(sid, ended_days, *resources, state="finished", started_days=None):
|
|
return {"id": f"p/{sid}.jsonl", "sessionId": sid, "title": sid.upper(),
|
|
"startedAt": iso(started_days if started_days is not None else ended_days + .1),
|
|
"endedAt": iso(ended_days),
|
|
"meta": {"state": state, "resources": list(resources)}}
|
|
|
|
|
|
def res(kind, rid, primary=False):
|
|
return {"kind": kind, "id": rid, "primary": primary}
|
|
|
|
|
|
def msgs(*texts):
|
|
return {"searchMsgs": [{"i": i, "role": role, "text": t}
|
|
for i, (role, t) in enumerate(texts)]}
|
|
|
|
|
|
class Past(unittest.TestCase):
|
|
def setUp(self):
|
|
self.cards = [
|
|
card("a", 1, res("linear", "INS-1", True)), # primary, newest
|
|
card("b", 2, res("linear", "INS-1"), res("linear", "INS-9", True)), # in passing
|
|
card("c", 5, res("linear", "INS-1", True)),
|
|
card("d", 9, res("pr", f"{REPO}#7", True), res("linear", "INS-1")), # PR of INS-1
|
|
card("old", 40, res("linear", "INS-1", True)), # past the window
|
|
card("run", 0, res("linear", "INS-1", True), state="running", started_days=.01),
|
|
card("me", 0, res("linear", "INS-1", True), state="running"),
|
|
card("x", 1, res("linear", "INS-2", True)),
|
|
]
|
|
self.summaries = {
|
|
"p/a.jsonl": msgs(("user", "fix INS-1"), ("assistant", "PR #7 is up for INS-1"),
|
|
("assistant", "Now INS-9: renamed the helper")), # drifted
|
|
"p/c.jsonl": msgs(("assistant", "INS-10 and #70 are other things")),
|
|
# a turn's answer wins over a later mid-turn mention
|
|
"p/d.jsonl": msgs(("assistant", "Merged pull/7, ins-1-fix-thing deleted"), ("user", "ok"),
|
|
("assistant", "I'll start by re-reading INS-1"), ("assistant", "bye")),
|
|
}
|
|
idx = {}
|
|
for c in self.cards:
|
|
for r in c["meta"]["resources"]:
|
|
idx.setdefault(f"{r['kind']}:{r['id']}", []).append(c["id"])
|
|
self.deps = types.SimpleNamespace(
|
|
store=real_store(self.summaries),
|
|
plugin_store=FakePluginStore(settings={"github": {"githubRepo": REPO},
|
|
"linear": {"linearWorkspace": "orus"}}),
|
|
profile_store=types.SimpleNamespace(
|
|
# The Mac is in Work; "c" is a Personal conversation.
|
|
for_runner=lambda r: {"id": "work"},
|
|
of_meta=lambda m, a=None: m.get("profile") or "work"),
|
|
meta_store=types.SimpleNamespace(
|
|
peek=lambda sid: {"profile": "personal"} if sid == "c" else {}),
|
|
worker_store=types.SimpleNamespace(get=lambda wid: {
|
|
"mac": {"id": "mac"}, "guestpc": {"id": "guestpc", "owner": "dom"}}.get(wid)))
|
|
# What the archive learned: PR #7's head branch (a `gh pr view`).
|
|
ctx = resource_view.Context(registry(settings={"github": {"githubRepo": REPO}}),
|
|
xrefs={f"pr:{REPO}#7": ["ins-1-fix-thing"]})
|
|
self.patches = [mock.patch.object(catalog, "_conversation_cards", lambda d, full: self.cards),
|
|
mock.patch.object(resource_view, "context", lambda d: ctx),
|
|
mock.patch.object(related_mod, "index", lambda d: idx),
|
|
mock.patch.object(past, "_conv_id", lambda p: p)]
|
|
for p in self.patches:
|
|
p.start()
|
|
|
|
def tearDown(self):
|
|
for p in self.patches:
|
|
p.stop()
|
|
|
|
def ask(self, *keys, **kw):
|
|
return past.lookup(self.deps, list(keys), session="me", now=NOW, **kw)
|
|
|
|
def test_a_pr_is_looked_up_as_its_issue(self):
|
|
out = self.ask(f"https://github.com/{REPO}/pull/7")
|
|
(s,) = out["subjects"]
|
|
self.assertEqual((s["key"], s["sources"]), ("linear:INS-1", [f"https://github.com/{REPO}/pull/7"]))
|
|
|
|
def test_running_apart_then_primary_first_newest_three(self):
|
|
(s,) = self.ask("INS-1")["subjects"]
|
|
self.assertEqual([r["sessionId"] for r in s["running"]], ["run"]) # never the asker
|
|
# a, c primary (newest first), d's primary is INS-1's PR; b only in passing
|
|
self.assertEqual([p["sessionId"] for p in s["past"]], ["a", "c", "d"])
|
|
self.assertEqual(s["more"], 1) # b; "old" is past 30 days
|
|
self.assertTrue(all(p["primary"] for p in s["past"]))
|
|
|
|
def test_the_excerpt_is_the_last_message_naming_the_subject(self):
|
|
(s,) = self.ask("#7")["subjects"]
|
|
by = {p["sessionId"]: p for p in s["past"]}
|
|
self.assertEqual(by["a"]["excerpt"], "PR #7 is up for INS-1") # not the INS-9 one
|
|
self.assertTrue(by["a"]["excerptUrl"].endswith("/conversation/p/a.jsonl?m=1"))
|
|
self.assertIsNone(by["c"]["excerpt"]) # INS-10 ≠ INS-1
|
|
self.assertIn("pull/7", by["d"]["excerpt"]) # named by its PR
|
|
|
|
def test_visibility_and_what_is_not_looked_up(self):
|
|
out = self.ask("INS-1", "https://x.slack.com/archives/C0123ABC/p1789479945088869",
|
|
visible=lambda cid: cid != "p/a.jsonl")
|
|
self.assertNotIn("a", [p["sessionId"] for p in out["subjects"][0]["past"]])
|
|
self.assertEqual(len(out["skipped"]), 1)
|
|
|
|
def test_a_branch_names_only_an_issue_the_hub_knows(self):
|
|
(s,) = self.ask("ins-1-fix-thing")["subjects"]
|
|
self.assertEqual(s["key"], "linear:INS-1")
|
|
(s,) = self.ask("fix-2-typos")["subjects"]
|
|
self.assertEqual(s["key"], "branch:fix-2-typos")
|
|
|
|
def test_outbox_lookup_owner_answered_guest_refused(self):
|
|
ok = past.outbox_lookup(self.deps, {"worker": "mac", "sessionId": "me", "keys": ["INS-1"]})
|
|
self.assertTrue(ok["ok"])
|
|
self.assertEqual(ok["result"]["subjects"][0]["key"], "linear:INS-1")
|
|
# …within the worker's own profile (workers/bound.py): no Personal "c"
|
|
self.assertNotIn("c", str([p.get("sessionId") for p in ok["result"]["subjects"][0]["past"]]))
|
|
no = past.outbox_lookup(self.deps, {"worker": "guestpc", "sessionId": "s", "keys": ["INS-1"]})
|
|
self.assertTrue(no["failed"])
|
|
|
|
def test_the_mirror_acks_with_the_result(self):
|
|
calls = []
|
|
m = outbox_mirror.OutboxMirror(
|
|
None, create={"lookup": lambda d: {"ok": True, "result": {"subjects": []}}},
|
|
status={}, cancel={})
|
|
m._call = lambda w, path, payload=None, **kw: calls.append((path, payload)) or {}
|
|
m._handle({"id": "mac"}, {"id": "lkp_0123456789ab", "kind": "lookup", "status": "queued",
|
|
"payload": {"keys": ["INS-1"], "sessionId": "me"}})
|
|
self.assertEqual(calls, [("/outbox/lkp_0123456789ab/ack",
|
|
{"hub": {"ok": True, "result": {"subjects": []}}})])
|
|
|
|
def test_route_calls_lookup(self):
|
|
import json
|
|
from conversations import routes as conv_routes
|
|
from users.caller import OWNER
|
|
res = conv_routes.past_conversations(self.deps, OWNER, keys="INS-1", session="me")
|
|
body = json.loads(res.body)
|
|
self.assertEqual([s["key"] for s in body["subjects"]], ["linear:INS-1"])
|
|
|
|
|
|
class PastWithoutPlugins(Past):
|
|
def test_no_hue_plugin_no_issue_subject(self):
|
|
self.deps.plugin_store = FakePluginStore(plugins=("github", "slack"),
|
|
settings={"github": {"githubRepo": REPO}})
|
|
out = past.lookup(self.deps, ["INS-1", "#7", "ins-1-fix-thing"], session="me", now=NOW)
|
|
# Without linear, a key is only a branch name and a PR is its own subject.
|
|
self.assertEqual([s["key"] for s in out["subjects"]],
|
|
["branch:INS-1", f"pr:{REPO}#7", "branch:ins-1-fix-thing"])
|
|
|
|
# The inherited cases need the linear plugin.
|
|
test_a_pr_is_looked_up_as_its_issue = test_running_apart_then_primary_first_newest_three = None
|
|
test_the_excerpt_is_the_last_message_naming_the_subject = None
|
|
test_visibility_and_what_is_not_looked_up = test_a_branch_names_only_an_issue_the_hub_knows = None
|
|
test_outbox_lookup_owner_answered_guest_refused = test_the_mirror_acks_with_the_result = None
|
|
test_route_calls_lookup = None
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|