Files
ai-agent/backend/test_look.py
gabrielvidalandClaude Opus 5.5 acda5ecc30 refactor: retire core leftovers the plugins replaced
- frontend: drop the dead Conversations dashboard code (costAnalysis,
  DashboardFilters, ConversationsDashboard), the unused analytics /
  footprint / pricing helpers, the orphan api.ts comment and the dead
  mocks (perf dashboard, storage dashboard, telemetry hub/usage,
  usage daily/history/calibration); their French strings
- backend: drop look.parse_action (the conversation-labels plugin has its
  own) and UsersStore.emails() (no caller)
- routes: drop GET /api/usage/daily|history|calibration,
  GET /api/telemetry/usage, GET /api/goals, POST /api/goal-work — the
  plugin bridges call daily_usage, calibrate.history, views.usage,
  goals_list and goal_work directly; authz table + golden matrix updated;
  openapi.json re-dumped, src/generated regenerated
- FALLBACK_ACCOUNTS: one neutral Claude seat instead of a stale copy of
  the providers' profiles (the full list moves to mock/accounts.ts)
- notify CLI: no local PRICES estimate — the line is
  "Claude Code · 78k tokens · 8m" and the hub's restate_cost puts the
  run's exact list price in (an older CLI's $ line is still restated)
- CLAUDE.md / docs / docstrings: scheduled/, templates/, sidecar
  *_usage.py, the clarifier (now the plugin's agents[] + prefs),
  runs/extras.py, sidecar/routes_chrome.py

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 11:53:15 +01:00

235 lines
11 KiB
Python

"""A conversation's look (conversations/look.py): validation, the issue + PR
subject, one colour per subject, the action precedence, the meta merge and
which conversations wait for a label (look_pending.py — the
conversation-labels plugin does the labelling). ``python -m unittest
test_look`` from ``backend/``."""
import pathlib
import tempfile
import types
import unittest
import meta as meta_mod
from conversations import look
from conversations import look_pending
class TestClean(unittest.TestCase):
def test_valid_and_clearing(self):
self.assertEqual(look.clean({"action": " Fix ", "color": "violet", "icon": "sh:gitea"}),
{"action": "fix", "color": "violet", "icon": "sh:gitea"})
self.assertEqual(look.clean({"action": ""}), {"action": ""})
def test_rejects(self):
for bad in ({"action": "fixx"}, {"color": "mauve"}, {"icon": "../x"},
{"shape": "round"}, {"action": 3}, "fix"):
with self.assertRaises(ValueError):
look.clean(bad)
class TestSubject(unittest.TestCase):
"""The colour's subject is generic: hue + shade by the plugins' ``hueRole``
— nothing in look.py knows `linear` or `pr`."""
ROLES = {"linear": "hue", "pr": "shade"}
def test_hue_and_shade_combination(self):
rs = [{"kind": "pr", "id": "o/r#13497"},
{"kind": "linear", "id": "INS-2171", "primary": True}]
self.assertEqual(look.subject(rs, self.ROLES),
("linear:INS-2171+pr:o/r#13497", "linear:INS-2171"))
def test_any_kinds_with_roles(self):
rs = [{"kind": "gitlab-mr", "id": "g/r!4"}, {"kind": "jira", "id": "ABC-1"}]
self.assertEqual(look.subject(rs, {"jira": "hue", "gitlab-mr": "shade"}),
("jira:ABC-1+gitlab-mr:g/r!4", "jira:ABC-1"))
# without roles (no such plugin): the primary resource alone
self.assertEqual(look.subject(rs), ("gitlab-mr:g/r!4", None))
def test_shade_alone_is_its_own_hue(self):
self.assertEqual(look.subject([{"kind": "pr", "id": "o/r#13902"}], self.ROLES),
("pr:o/r#13902", None))
def test_no_role_falls_back_to_the_primary_resource(self):
self.assertEqual(look.subject([{"kind": "branch", "id": "feat-12-x"},
{"kind": "slack", "id": "C1/1.2", "primary": True}],
self.ROLES),
("slack:C1/1.2", None))
def test_hue_alone_and_nothing(self):
self.assertEqual(look.subject([{"kind": "linear", "id": "INS-9"}], self.ROLES),
("linear:INS-9", "linear:INS-9"))
self.assertEqual(look.subject([]), (None, None))
class TestLookColors(unittest.TestCase):
def setUp(self):
self.d = tempfile.TemporaryDirectory()
self.path = str(pathlib.Path(self.d.name) / "c.json")
def tearDown(self):
self.d.cleanup()
def test_live_issues_never_share_and_colours_stick(self):
c = look.LookColors(self.path)
keys = [f"linear:INS-{i}" for i in range(len(look.COLORS))]
got = [c.color_for(k, "2026-10-20T10:00:00Z") for k in keys]
self.assertEqual(len(set(got)), len(look.COLORS))
c.flush()
again = look.LookColors(self.path) # persisted
self.assertEqual(again.color_for(keys[3], "2026-10-21T10:00:00Z"), got[3])
def test_old_issues_free_their_hue(self):
c = look.LookColors(self.path)
old = c.color_for("linear:OLD-1", "2026-01-01T00:00:00Z")
fresh = {c.color_for(f"linear:NEW-{i}", "2026-10-20T00:00:00Z")
for i in range(len(look.COLORS))}
self.assertIn(old, fresh)
def test_hue_per_issue_shade_per_pr(self):
c = look.LookColors(self.path)
hue = c.color_for("linear:INS-2171", "2026-10-20T00:00:00Z")
self.assertEqual(c.color_for("linear:INS-2171+pr:o/r#13497"), f"{hue}-300")
self.assertEqual(c.color_for("linear:INS-2171+pr:o/r#13902"), f"{hue}-700")
self.assertEqual(c.color_for("linear:INS-2171+pr:o/r#13497"), f"{hue}-300")
self.assertNotEqual(c.color_for("linear:INS-2017+pr:o/r#13497").split("-")[0], hue)
def test_a_conversation_keeps_its_first_colour(self):
c = look.LookColors(self.path)
first = c.for_conversation("s1", "linear:INS-9", "2026-10-20T00:00:00Z")
later = c.for_conversation("s1", "linear:INS-9+pr:o/r#1", "2026-10-20T03:00:00Z")
self.assertEqual(first, later)
self.assertEqual(c.subject_of("s1"), "linear:INS-9")
# another conversation on the PR gets the shade
self.assertEqual(c.for_conversation("s2", "linear:INS-9+pr:o/r#1"), f"{first}-300")
def test_pin_moves_every_conversation_on_the_subject(self):
c = look.LookColors(self.path)
c.for_conversation("s1", "linear:INS-1", "2026-10-20T00:00:00Z")
c.for_conversation("s2", "linear:INS-1", "2026-10-20T00:00:00Z")
self.assertEqual(c.set("linear:INS-1", "lime"), 2)
self.assertEqual(c.for_conversation("s1", "linear:INS-1"), "lime")
self.assertEqual(c.color_for("linear:INS-1"), "lime")
class TestResolve(unittest.TestCase):
def test_action_precedence(self):
r = look.resolve({"action": "review"}, sid="s", subject_key=None, seen=None,
colors=None, auto={"action": "fix"})
self.assertEqual((r["action"], r["actionSource"], r["set"]), ("review", "set", ["action"]))
r = look.resolve({}, sid="s", subject_key=None, seen=None, colors=None,
auto={"action": "docs"})
self.assertEqual((r["action"], r["actionSource"]), ("docs", "haiku"))
# Haiku answered nothing usable, nothing set: no action
self.assertIsNone(look.resolve({}, sid="s", subject_key=None, seen=None,
colors=None, auto={"action": None}))
def test_colour_from_subject_unless_set(self):
with tempfile.TemporaryDirectory() as d:
c = look.LookColors(str(pathlib.Path(d) / "c.json"))
r = look.resolve({}, sid="s", subject_key="linear:INS-1", seen=None, colors=c)
self.assertIn(r["color"], look.COLORS)
r2 = look.resolve({"color": "lime"}, sid="s", subject_key="linear:INS-1",
seen=None, colors=c)
self.assertEqual(r2["color"], "lime")
# the subject it was first given sticks
r3 = look.resolve({}, sid="s", subject_key="linear:INS-1+pr:o/r#2", seen=None,
colors=c)
self.assertEqual((r3["subject"], r3["color"]), ("linear:INS-1", r["color"]))
class TestPrompt(unittest.TestCase):
def test_ask_text_and_prompt(self):
t = look.ask_text("INS-1 · X", "y" * 5000, ["is : bug"])
self.assertIn("Linear labels: is : bug", t)
self.assertLess(len(t), 3200)
for a in look.ACTIONS:
self.assertIn(f"- {a}: ", look.SYSTEM_PROMPT)
def test_shaded_colours_validate(self):
self.assertEqual(look.clean({"color": "violet-300"}), {"color": "violet-300"})
with self.assertRaises(ValueError):
look.clean({"color": "violet-900"})
class TestMetaMerge(unittest.TestCase):
def test_key_by_key_and_clear(self):
with tempfile.TemporaryDirectory() as d:
m = meta_mod.MetaStore(str(pathlib.Path(d) / "m.json"))
m.update("s", {"look": {"action": "fix"}})
cur = m.update("s", {"look": {"color": "violet"}})
self.assertEqual(cur["look"], {"action": "fix", "color": "violet"})
cur = m.update("s", {"look": {"action": "", "color": ""}})
self.assertNotIn("look", cur)
class TestPending(unittest.TestCase):
def setUp(self):
self.d = tempfile.TemporaryDirectory()
meta = meta_mod.MetaStore(str(pathlib.Path(self.d.name) / "m.json"))
summaries = [
("a", {"sessionId": "a", "userTurns": 1, "startedAt": "2099-01-02T00:00:00Z",
"firstPrompt": "fix the crash", "title": "Crash"}),
("b", {"sessionId": "b", "userTurns": 1, "startedAt": "2099-01-03T00:00:00Z",
"firstPrompt": "review #3", "title": "PR 3"}),
("old", {"sessionId": "old", "userTurns": 1, "startedAt": "2000-01-01T00:00:00Z",
"firstPrompt": "x"}),
("side", {"sessionId": "side", "userTurns": 1, "isSidechain": True,
"startedAt": "2099-01-01T00:00:00Z", "firstPrompt": "x"}),
]
self.deps = types.SimpleNamespace(
meta_store=meta, store=types.SimpleNamespace(all_summaries=lambda: summaries),
profile_store=None)
self._labels = look_pending.labels_of
look_pending.labels_of = lambda deps, s, m: []
def tearDown(self):
look_pending.labels_of = self._labels
self.d.cleanup()
def sids(self, **kw):
return [sid for sid, _ in look_pending.candidates(self.deps, **kw)]
def test_newest_first_top_level_recent_only(self):
self.assertEqual(self.sids(days=2), ["b", "a"])
self.assertEqual(self.sids(days=365 * 100), ["b", "a", "old"])
self.assertEqual(self.sids(days=2, limit=1), ["b"])
def test_an_answer_even_unusable_is_never_asked_again(self):
self.deps.meta_store.update("a", {"lookAuto": {"action": None}})
self.deps.meta_store.update("b", {"look": {"action": "fix"}})
self.assertEqual(self.sids(days=2), [])
def test_cron_runs_are_skipped(self):
self.deps.meta_store.update("b", {"cron": {"id": "x"}})
self.assertEqual(self.sids(days=2), ["a"])
def test_rows_and_one_conversation_before_it_is_indexed(self):
[b, a] = look_pending.pending(self.deps, days=2)
self.assertEqual((b["sessionId"], b["firstPrompt"], b["account"], b["isolated"]),
("b", "review #3", "personal", False))
[fresh] = look_pending.pending(self.deps, sid="new-session-id")
self.assertEqual((fresh["sessionId"], fresh["firstPrompt"]), ("new-session-id", None))
self.deps.meta_store.update("a", {"lookAuto": {"action": "fix"}})
self.assertEqual(look_pending.pending(self.deps, sid="a"), [])
def test_a_non_claude_account_bills_its_profiles_claude_login(self):
profiles = {"work": {"workers": [{"id": "mac", "accounts": {
"opencode": "chatgpt-work", "claude": "work"}}]}}
self.deps.profile_store = types.SimpleNamespace(
resolve=lambda worker, account, explicit=None: "work",
get=lambda pid: profiles.get(pid))
import accounts as accounts_mod
real = accounts_mod.harness_of
accounts_mod.harness_of = lambda a: "opencode" if a == "chatgpt-work" else "claude"
try:
s = {"sessionId": "x"}
self.assertEqual(look_pending.claude_account(self.deps, s, {"account": "chatgpt-work"}),
"work")
self.assertEqual(look_pending.claude_account(self.deps, s, {"account": "work"}), "work")
finally:
accounts_mod.harness_of = real
if __name__ == "__main__":
unittest.main()