561 lines
26 KiB
Python
561 lines
26 KiB
Python
#!/usr/bin/env python3
|
|
"""Unit tests for the Slack resource plugin — pure data, so everything runs
|
|
through the ai-agent host's own code: the manifest validator
|
|
(``backend/plugins/manifest.py``), the resource registry
|
|
(``backend/plugins/resources.py``), the transcript miner
|
|
(``backend/conversations/resources.py``) and the card view
|
|
(``backend/conversations/resource_view.py``).
|
|
|
|
python3 -m unittest discover -s plugins/slack/tests -p "test_*.py"
|
|
|
|
The ai-agent checkout is ``$AI_AGENT_BACKEND`` (default
|
|
``~/projects/ai-agent/backend``); without it every test is skipped.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import copy
|
|
import datetime
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import struct
|
|
import sys
|
|
import types
|
|
import unittest
|
|
|
|
sys.dont_write_bytecode = True # nothing lands in either checkout
|
|
PLUGIN = pathlib.Path(__file__).resolve().parent.parent
|
|
BACKEND = pathlib.Path(os.environ.get("AI_AGENT_BACKEND")
|
|
or pathlib.Path.home() / "projects/ai-agent/backend")
|
|
HAVE_BACKEND = (BACKEND / "plugins" / "resources.py").is_file()
|
|
if HAVE_BACKEND and str(BACKEND) not in sys.path:
|
|
sys.path.insert(0, str(BACKEND))
|
|
|
|
if HAVE_BACKEND:
|
|
from conversations import resource_view as rv # noqa: E402
|
|
from conversations.resources import ResourceMiner, ru # noqa: E402
|
|
from plugins import manifest as manifest_mod # noqa: E402
|
|
from plugins import resources as pr # noqa: E402
|
|
|
|
skip = unittest.skipUnless(HAVE_BACKEND, f"no ai-agent backend at {BACKEND}")
|
|
|
|
WS = "acme-corp"
|
|
CH = "C0123ABCDEF" # #eng-alerts
|
|
CH2 = "C0456GHIJKL" # #feature-requests
|
|
DM = "D04ABCDEF12"
|
|
GRP = "G01PRIVATE9"
|
|
TS = "1792030252.499889"
|
|
TS2 = "1791878511.818179"
|
|
REPLY_TS = "1792031000.123456"
|
|
|
|
|
|
def link(ch: str, ts: str, ws: str = WS, thread: str | None = None, extra: str = "") -> str:
|
|
u = f"https://{ws}.slack.com/archives/{ch}/p{ts.replace('.', '')}"
|
|
if thread:
|
|
u += f"?{extra}thread_ts={thread}"
|
|
return u
|
|
|
|
|
|
def raw() -> dict:
|
|
return json.loads((PLUGIN / "plugin.json").read_text())
|
|
|
|
|
|
def validated() -> dict:
|
|
return manifest_mod.validate_manifest(PLUGIN)
|
|
|
|
|
|
def reg(**settings):
|
|
"""The registry the hub builds from this plugin, with ``settings`` saved
|
|
(unsaved fields read as their default — ``plugins.resources._entries``)."""
|
|
store = _Store(settings)
|
|
return pr.registry(types.SimpleNamespace(plugin_store=store))
|
|
|
|
|
|
class _Store:
|
|
"""What the registry reads of a ``PluginStore``."""
|
|
|
|
def __init__(self, settings: dict):
|
|
self.version = 1
|
|
self.mf = validated()
|
|
self.cfg = dict(settings)
|
|
|
|
def active_manifests(self, uid):
|
|
return [("slack", copy.deepcopy(self.mf), dict(self.cfg))]
|
|
|
|
|
|
def ctx(r, names=None):
|
|
"""A card view context: names learned from transcripts + the registry's."""
|
|
return rv.Context(r, {}, names or {})
|
|
|
|
|
|
def view(r, auto, names=None, worker=None, cwd=None, recorded=()):
|
|
scoped = r.scoped_kinds(worker, cwd)
|
|
in_scope = bool(scoped)
|
|
return rv.merge(list(auto), list(recorded), [], ctx(r, names), scoped, in_scope)
|
|
|
|
|
|
def url_rec(u: str, first=True, at="2026-11-01T10:00:00Z") -> dict:
|
|
"""What the transcript miner stores for a link: a raw ``url`` record."""
|
|
rec = dict(ru.parse_url(u) or {"kind": "url", "id": u, "url": u, "label": u})
|
|
rec.update({"source": "auto", "via": "prompt", "firstSeen": at})
|
|
if first:
|
|
rec["firstTurn"] = True
|
|
return rec
|
|
|
|
|
|
# ── the manifest ─────────────────────────────────────────────────────────────
|
|
@skip
|
|
class TestManifest(unittest.TestCase):
|
|
def test_validates_with_the_host_validator(self):
|
|
m = validated()
|
|
self.assertEqual((m["id"], m["name"], m["schema"]), ("slack", "Slack", 1))
|
|
self.assertRegex(m["version"], r"^\d+\.\d+\.\d+$")
|
|
self.assertEqual(m["author"], "gabrielvidal")
|
|
|
|
def test_pure_data_owner_only(self):
|
|
"""No code, no secrets, no network, nothing granted to guests: the
|
|
registry reads the owner's manifests only."""
|
|
r, m = raw(), validated()
|
|
for k in ("skill", "secrets", "proxy", "actions", "schedules", "webhooks",
|
|
"ui", "managed", "capabilities", "agents"):
|
|
self.assertFalse(r.get(k), k)
|
|
self.assertEqual(m["capabilities"], [])
|
|
self.assertFalse(manifest_mod.requires_operator(m))
|
|
self.assertFalse((PLUGIN / "handlers").exists())
|
|
self.assertFalse((PLUGIN / "skill").exists())
|
|
|
|
def test_one_resource_kind(self):
|
|
res = validated()["resources"]
|
|
self.assertEqual([x["id"] for x in res], ["slack"])
|
|
s = res[0]
|
|
self.assertEqual(s["label"], "Slack thread")
|
|
self.assertEqual(s["priority"], 30)
|
|
self.assertEqual(s["clickAction"], "open")
|
|
self.assertEqual((s["icon"], s["color"]), ("slack", "fuchsia"))
|
|
self.assertEqual((s["namesGroup"], s["dateGroup"]), ("channel", "tss"))
|
|
for f in ("urlRegex", "idRegex", "ignoreUrlRegex", "urlTemplate"):
|
|
self.assertTrue(s.get(f), f)
|
|
self.assertEqual(s["idTemplate"], ["{channel}/{tss|ptss}.{tsu|ptsu}"])
|
|
self.assertEqual(s["labelTemplate"], [{"match": "^D", "template": "DM"},
|
|
{"template": "#{name}"}])
|
|
|
|
def test_tool_extractors(self):
|
|
ex = validated()["resources"][0]["toolExtractors"]
|
|
self.assertEqual([e["tool"] for e in ex], ["mcp__*slack_read_thread*", "*"])
|
|
self.assertTrue(ex[0]["tagOnCall"])
|
|
self.assertEqual(ex[0]["inputTemplate"], "{channel_id|channel}/{message_ts}")
|
|
self.assertEqual(len(ex[1]["channelMapRegex"]), 2)
|
|
self.assertEqual(ex[1]["textHint"], ["Channel: #", "<#"])
|
|
|
|
def test_same_resources_as_the_hub_reference_fixture(self):
|
|
fx = BACKEND / "fixtures/resource_plugins/slack"
|
|
if not (fx / "plugin.json").is_file():
|
|
self.skipTest("no reference fixture")
|
|
self.assertEqual(validated()["resources"],
|
|
manifest_mod.validate_manifest(fx)["resources"])
|
|
self.assertEqual([f["key"] for f in validated()["settings"]["fields"]],
|
|
[f["key"] for f in manifest_mod.validate_manifest(fx)["settings"]["fields"]])
|
|
|
|
def test_scope_settings(self):
|
|
fields = {f["key"]: f for f in validated()["settings"]["fields"]}
|
|
self.assertEqual(set(fields), {"slackWorkspace", "channelMap", "workers",
|
|
"cwdGlobs", "notifPills"})
|
|
types_ = {k: f["type"] for k, f in fields.items()}
|
|
self.assertEqual(types_, {"slackWorkspace": "text", "channelMap": "textarea",
|
|
"workers": "list", "cwdGlobs": "list",
|
|
"notifPills": "checkbox"})
|
|
self.assertIs(fields["notifPills"]["default"], False)
|
|
for f in fields.values():
|
|
self.assertTrue(f["label"] and len(f["label"]) <= 30, f["key"])
|
|
self.assertTrue(f.get("help") and len(f["help"]) >= 20, f["key"])
|
|
self.assertFalse(f["required"], f["key"])
|
|
self.assertIn("C0123ABCD=name", fields["channelMap"]["help"])
|
|
self.assertIn("local", fields["workers"]["help"])
|
|
self.assertTrue(validated()["settings"]["subtitle"])
|
|
|
|
def test_regexes_compile_and_are_refused_when_unsafe(self):
|
|
s = raw()["resources"][0]
|
|
for f in ("urlRegex", "idRegex", "ignoreUrlRegex"):
|
|
re.compile(s[f])
|
|
# The validator's nested-quantifier guard still bites a broken copy.
|
|
import tempfile
|
|
bad = raw()
|
|
bad["resources"][0]["urlRegex"] = "^(a+)+$"
|
|
with tempfile.TemporaryDirectory() as d:
|
|
(pathlib.Path(d) / "plugin.json").write_text(json.dumps(bad))
|
|
with self.assertRaises(manifest_mod.ManifestError):
|
|
manifest_mod.validate_manifest(pathlib.Path(d))
|
|
|
|
|
|
# ── the art ──────────────────────────────────────────────────────────────────
|
|
def webp_size(data: bytes) -> tuple[int, int]:
|
|
assert data[:4] == b"RIFF" and data[8:12] == b"WEBP", "not a WebP"
|
|
chunk = data[12:16]
|
|
if chunk == b"VP8 ":
|
|
w, h = struct.unpack("<HH", data[26:30])
|
|
return w & 0x3FFF, h & 0x3FFF
|
|
if chunk == b"VP8L":
|
|
b = int.from_bytes(data[21:25], "little")
|
|
return (b & 0x3FFF) + 1, ((b >> 14) & 0x3FFF) + 1
|
|
if chunk == b"VP8X":
|
|
return (int.from_bytes(data[24:27], "little") + 1,
|
|
int.from_bytes(data[27:30], "little") + 1)
|
|
raise AssertionError(f"unknown WebP chunk {chunk!r}")
|
|
|
|
|
|
@skip
|
|
class TestArt(unittest.TestCase):
|
|
def test_picked_up_by_name(self):
|
|
m = validated()
|
|
self.assertEqual((m["iconSvg"], m["illustration"], m["readme"]),
|
|
("icon.svg", "illustration.webp", "README.md"))
|
|
self.assertRegex(m["artVersion"], r"^[0-9a-f]{12}$")
|
|
|
|
def test_icon_is_inert_monochrome_24(self):
|
|
data = (PLUGIN / "icon.svg").read_bytes()
|
|
self.assertIsNone(manifest_mod.svg_problem(data))
|
|
t = data.decode()
|
|
self.assertIn('viewBox="0 0 24 24"', t)
|
|
self.assertIn('stroke="currentColor"', t)
|
|
self.assertIn('fill="none"', t)
|
|
self.assertIn('stroke-width="1.75"', t)
|
|
self.assertIn('stroke-linecap="round"', t)
|
|
self.assertIn('stroke-linejoin="round"', t)
|
|
self.assertNotRegex(t, r"#[0-9a-fA-F]{3,8}\b|<script|\bon\w+=|href=|<image|<foreignObject")
|
|
self.assertLess(len(data), 2048)
|
|
|
|
def test_illustration_is_a_small_16_9_webp(self):
|
|
data = (PLUGIN / "illustration.webp").read_bytes()
|
|
w, h = webp_size(data)
|
|
self.assertEqual(w, 960)
|
|
self.assertAlmostEqual(w / h, 16 / 9, delta=0.03)
|
|
self.assertLess(len(data), 120 * 1024)
|
|
|
|
def test_tile_colour_is_the_darker_plum(self):
|
|
c = validated()["color"]
|
|
self.assertRegex(c, r"^#[0-9a-f]{6}$")
|
|
r, g, b = (int(c[i:i + 2], 16) for i in (1, 3, 5))
|
|
self.assertTrue(r > b > g, c) # plum / aubergine
|
|
self.assertLess(0.299 * r + 0.587 * g + 0.114 * b, 110, c) # white icon reads on it
|
|
|
|
def test_readme_for_people(self):
|
|
lines = [x for x in (PLUGIN / "README.md").read_text().splitlines() if x.strip()]
|
|
body = [x for x in lines if not x.startswith("# ")]
|
|
self.assertTrue(6 <= len(body) <= 12, len(body))
|
|
text = "\n".join(lines)
|
|
for word in ("thread_ts", "DM", "#channel", "C0123ABCD=name", "Runners", "Folders"):
|
|
self.assertIn(word, text)
|
|
|
|
|
|
# ── compiling into the registry ──────────────────────────────────────────────
|
|
@skip
|
|
class TestRegistry(unittest.TestCase):
|
|
def test_compiles(self):
|
|
r = reg(slackWorkspace=WS)
|
|
self.assertTrue(r)
|
|
self.assertEqual(r.kinds, frozenset({"slack"}))
|
|
d = r.by_kind["slack"]
|
|
self.assertEqual(d.plugin, "slack")
|
|
self.assertEqual(len(d.extractors), 2)
|
|
self.assertEqual(len(r.name_extractors), 1)
|
|
self.assertEqual([e.tool for e in r.extractors], ["mcp__*slack_read_thread*"])
|
|
|
|
def test_descriptor(self):
|
|
self.assertEqual(reg().descriptors(), [{
|
|
"id": "slack", "label": "Slack thread", "icon": "slack", "color": "fuchsia",
|
|
"stateTones": {}, "clickAction": "open", "priority": 30, "hueRole": None,
|
|
"pluginId": "slack"}])
|
|
|
|
def test_build_directly(self):
|
|
r = pr.build([("slack", validated()["resources"], {"channelMap": f"{CH}=eng-alerts"})])
|
|
self.assertEqual(r.names, {CH: "eng-alerts"})
|
|
self.assertIn("slack", r.by_kind)
|
|
|
|
def test_priority_after_issue_and_pr_kinds(self):
|
|
other = [{"id": "linear", "label": "Issue", "idRegex": r"^[A-Z]+-\d+$",
|
|
"priority": 10, "toolExtractors": []},
|
|
{"id": "pr", "label": "PR", "idRegex": r"^#\d+$", "priority": 20,
|
|
"toolExtractors": []}]
|
|
r = pr.build([("x", other, {}), ("slack", validated()["resources"], {})])
|
|
self.assertEqual([d.kind for d in r.defs], ["linear", "pr", "slack"])
|
|
|
|
|
|
# ── links → threads ──────────────────────────────────────────────────────────
|
|
@skip
|
|
class TestThreadLinks(unittest.TestCase):
|
|
def setUp(self):
|
|
self.r = reg(slackWorkspace=WS)
|
|
|
|
def test_thread_link(self):
|
|
rec = self.r.resolve_url(link(CH, TS))
|
|
self.assertEqual(rec["kind"], "slack")
|
|
self.assertEqual(rec["id"], f"{CH}/{TS}")
|
|
self.assertEqual(rec["url"], link(CH, TS))
|
|
self.assertEqual(rec["label"], f"#{CH}") # nothing learned yet
|
|
|
|
def test_reply_link_joins_its_thread(self):
|
|
parent = self.r.resolve_url(link(CH, TS))
|
|
reply = self.r.resolve_url(link(CH, REPLY_TS, thread=TS))
|
|
self.assertEqual(reply["id"], parent["id"])
|
|
self.assertEqual(reply["url"], parent["url"]) # the parent's link
|
|
self.assertEqual(ru.key(reply), f"slack:{CH}/{TS}")
|
|
|
|
def test_reply_link_with_other_params(self):
|
|
reply = self.r.resolve_url(link(CH, REPLY_TS, thread=TS, extra="cid=C0X&"))
|
|
self.assertEqual(reply["id"], f"{CH}/{TS}")
|
|
self.assertEqual(reply["url"], link(CH, TS))
|
|
|
|
def test_link_workspace_wins_over_the_setting(self):
|
|
rec = reg(slackWorkspace="other").resolve_url(link(CH, TS, ws="acme-team"))
|
|
self.assertEqual(rec["url"], link(CH, TS, ws="acme-team"))
|
|
|
|
def test_trailing_punctuation(self):
|
|
for tail in (").", ">", ","):
|
|
self.assertEqual(self.r.resolve_url(link(CH, TS) + tail)["id"], f"{CH}/{TS}")
|
|
|
|
def test_dm_and_private_channel(self):
|
|
dm = self.r.resolve_url(link(DM, TS))
|
|
self.assertEqual((dm["id"], dm["label"]), (f"{DM}/{TS}", "DM"))
|
|
self.assertIsNone(self.r.by_kind["slack"].token(dm)) # a DM says nothing in a title
|
|
g = self.r.resolve_url(link(GRP, TS))
|
|
self.assertEqual(g["label"], f"#{GRP}")
|
|
|
|
def test_not_threads(self):
|
|
for u in ("https://github.com/o/r/pull/1",
|
|
f"https://{WS}.slack.com/archives/{CH}",
|
|
f"https://{WS}.slack.com/archives/{CH}/p123",
|
|
f"https://{WS}.slack.com/archives/c0123abcdef/p{TS.replace('.', '')}",
|
|
f"https://{WS}.slack.com/archives/U0123456789/p{TS.replace('.', '')}",
|
|
f"http://{WS}.slack.com/archives/{CH}/p{TS.replace('.', '')}",
|
|
f"https://evil.com/{WS}.slack.com/archives/{CH}/p{TS.replace('.', '')}"):
|
|
self.assertIsNone(self.r.resolve_url(u), u)
|
|
|
|
def test_other_slack_links_are_dropped(self):
|
|
for u in (f"https://{WS}.slack.com/",
|
|
f"https://{WS}.slack.com/archives/{CH}",
|
|
f"https://{WS}.slack.com/team/U0123456",
|
|
f"https://{WS}.slack.com/files/U01/F02/x.png",
|
|
f"https://app.slack.com/client/T01/{CH}"):
|
|
self.assertTrue(self.r.ignored(u), u)
|
|
self.assertIsNone(self.r.normalize(url_rec(u)), u)
|
|
for u in (link(CH, TS), link(CH, REPLY_TS, thread=TS), "https://slack.com/intl/en/",
|
|
"https://example.com/x"):
|
|
self.assertFalse(self.r.ignored(u), u)
|
|
|
|
def test_raw_url_records_become_threads_at_view_time(self):
|
|
n = self.r.normalize(url_rec(link(CH, REPLY_TS, thread=TS)))
|
|
self.assertEqual((n["kind"], n["id"]), ("slack", f"{CH}/{TS}"))
|
|
self.assertTrue(n["firstTurn"])
|
|
self.assertEqual(n["via"], "prompt")
|
|
|
|
def test_ids(self):
|
|
rec = self.r.parse_ref(f"{CH}/{TS}")
|
|
self.assertEqual((rec["kind"], rec["id"], rec["url"]), ("slack", f"{CH}/{TS}", link(CH, TS)))
|
|
self.assertEqual(self.r.parse_ref(f"{CH}/{TS}", kind="slack")["id"], f"{CH}/{TS}")
|
|
self.assertEqual(self.r.parse_ref(link(CH, REPLY_TS, thread=TS))["id"], f"{CH}/{TS}")
|
|
# An id with no workspace anywhere: a pill without a link.
|
|
self.assertIsNone(reg().parse_ref(f"{CH}/{TS}")["url"])
|
|
for bad in (f"{CH}/1792030252", f"c0123abcdef/{TS}", f"{CH}/{TS}x", f"X0123ABCDEF/{TS}"):
|
|
r = self.r.parse_ref(bad, kind="slack")
|
|
self.assertIsNone(r, bad)
|
|
|
|
|
|
# ── labels: DM vs #channel, names learned, channelMap ───────────────────────
|
|
@skip
|
|
class TestLabels(unittest.TestCase):
|
|
def test_learned_name(self):
|
|
r = reg(slackWorkspace=WS)
|
|
out = view(r, [url_rec(link(CH, TS))], names={CH: "eng-alerts"})
|
|
self.assertEqual([x["label"] for x in out], ["#eng-alerts"])
|
|
self.assertEqual(r.by_kind["slack"].token(out[0]), "#eng-alerts")
|
|
|
|
def test_dm_never_takes_a_name(self):
|
|
out = view(reg(), [url_rec(link(DM, TS))], names={DM: "jane"})
|
|
self.assertEqual(out[0]["label"], "DM")
|
|
|
|
def test_channel_map_wins_over_learned(self):
|
|
r = reg(channelMap=f"{CH}=#prod-alerts\n{CH2}: product")
|
|
self.assertEqual(r.names, {CH: "prod-alerts", CH2: "product"})
|
|
out = view(r, [url_rec(link(CH, TS)), url_rec(link(CH2, TS2), first=False)],
|
|
names={CH: "eng-alerts", CH2: "feature-requests"})
|
|
self.assertEqual(sorted(x["label"] for x in out), ["#prod-alerts", "#product"])
|
|
|
|
def test_channel_map_formats(self):
|
|
self.assertEqual(pr.channel_map(f"{CH}=a\n\n bad line \n{CH2} = @b ,{DM}:c"),
|
|
{CH: "a", CH2: "b", DM: "c"})
|
|
self.assertEqual(pr.channel_map({CH: "#x", "": "y", CH2: ""}), {CH: "x"})
|
|
|
|
def test_title_token(self):
|
|
d = reg().by_kind["slack"]
|
|
self.assertEqual(d.token({"id": f"{CH}/{TS}", "label": "#eng-alerts"}), "#eng-alerts")
|
|
self.assertIsNone(d.token({"id": f"{DM}/{TS}", "label": "DM"}))
|
|
self.assertIsNone(d.token({"id": f"{GRP}/{TS}", "label": ""}) or None)
|
|
|
|
|
|
# ── learning channel names from tool results ────────────────────────────────
|
|
SEARCH = ("## Messages (2 results)\n### Result 1 of 2\nChannel: #feature-requests "
|
|
f"(ID: {CH2})\nFrom: x\n… moved to <#{CH}|eng-alerts>\n"
|
|
f"<#{GRP}|team.private-1> and <#{DM}>")
|
|
|
|
|
|
@skip
|
|
class TestChannelLearning(unittest.TestCase):
|
|
def setUp(self):
|
|
self.r = reg(slackWorkspace=WS)
|
|
self.ex = self.r.name_extractors[0]
|
|
|
|
def test_both_formats(self):
|
|
self.assertEqual(self.ex.names(SEARCH), {CH2: "feature-requests", CH: "eng-alerts",
|
|
GRP: "team.private-1"})
|
|
|
|
def test_text_hint_gates_the_scan(self):
|
|
self.assertEqual(self.ex.names("Channel #x (ID: C0123456) — no hint here"), {})
|
|
self.assertEqual(self.ex.names("ID: C0123456 nothing"), {})
|
|
|
|
def test_miner_learns_from_any_tool_and_tags_thread_reads(self):
|
|
m = ResourceMiner(self.r)
|
|
m.feed_events([
|
|
{"t": "tool_call", "tool": "mcp__claude_ai_Slack__slack_search_public_and_private",
|
|
"id": "t1", "input": {"query": "x"}, "at": "2026-11-01T10:00:00Z"},
|
|
{"t": "tool_result", "toolCall": "t1", "text": SEARCH},
|
|
{"t": "tool_call", "tool": "mcp__claude_ai_Slack__slack_read_thread", "id": "t2",
|
|
"input": {"channel_id": CH2, "message_ts": TS2}, "at": "2026-11-01T10:01:00Z"},
|
|
{"t": "tool_result", "toolCall": "t2", "text": "{}"},
|
|
{"t": "tool_call", "tool": "shell", "id": "t3",
|
|
"input": {"command": "echo 'Channel: #ops (ID: C0OPS1234)'"}},
|
|
{"t": "tool_result", "toolCall": "t3", "text": "Channel: #ops (ID: C0OPS1234)"},
|
|
])
|
|
s = m.summary()
|
|
self.assertEqual(s["resourceNames"], {CH2: "feature-requests", CH: "eng-alerts",
|
|
GRP: "team.private-1", "C0OPS1234": "ops"})
|
|
self.assertEqual([ru.key(x) for x in s["resourcesAuto"]], [f"slack:{CH2}/{TS2}"])
|
|
self.assertEqual(s["resourcesAuto"][0]["via"], "tool")
|
|
out = view(self.r, s["resourcesAuto"], names=s["resourceNames"])
|
|
self.assertEqual([(x["label"], x["url"]) for x in out],
|
|
[("#feature-requests", link(CH2, TS2))])
|
|
|
|
def test_thread_read_with_channel_alias(self):
|
|
m = ResourceMiner(self.r)
|
|
m.feed_events([{"t": "tool_call", "tool": "mcp__slack__slack_read_thread", "id": "a",
|
|
"input": {"channel": CH, "message_ts": TS}}])
|
|
self.assertEqual([ru.key(x) for x in m.summary()["resourcesAuto"]], [f"slack:{CH}/{TS}"])
|
|
|
|
def test_other_slack_tools_tag_nothing(self):
|
|
m = ResourceMiner(self.r)
|
|
m.feed_events([
|
|
{"t": "tool_call", "tool": "mcp__claude_ai_Slack__slack_read_channel", "id": "a",
|
|
"input": {"channel_id": CH, "message_ts": TS}},
|
|
{"t": "tool_call", "tool": "mcp__claude_ai_Slack__slack_read_thread", "id": "b",
|
|
"input": {"channel_id": CH}}, # no ts: nothing to tag
|
|
{"t": "tool_call", "tool": "mcp__claude_ai_Slack__slack_read_thread", "id": "c",
|
|
"input": {"channel_id": "nope", "message_ts": TS}},
|
|
])
|
|
self.assertEqual(m.summary()["resourcesAuto"], [])
|
|
|
|
def test_manual_channel_map_beats_learning(self):
|
|
r = reg(slackWorkspace=WS, channelMap=f"{CH2}=requests")
|
|
m = ResourceMiner(r)
|
|
m.feed_events([
|
|
{"t": "tool_call", "tool": "mcp__x__search", "id": "t1", "input": {}},
|
|
{"t": "tool_result", "toolCall": "t1", "text": SEARCH},
|
|
{"t": "tool_call", "tool": "mcp__x__slack_read_thread", "id": "t2",
|
|
"input": {"channel_id": CH2, "message_ts": TS2}},
|
|
])
|
|
s = m.summary()
|
|
self.assertEqual(s["resourceNames"][CH2], "feature-requests") # learned…
|
|
out = view(r, s["resourcesAuto"], names=s["resourceNames"])
|
|
self.assertEqual(out[0]["label"], "#requests") # …but the setting wins
|
|
|
|
|
|
# ── several threads of one channel get their date ───────────────────────────
|
|
def day(ts: str) -> str:
|
|
dt = datetime.datetime.fromtimestamp(float(ts), datetime.timezone.utc)
|
|
return f"{dt.day} {dt.strftime('%b')}"
|
|
|
|
|
|
@skip
|
|
class TestDates(unittest.TestCase):
|
|
def test_same_channel_threads_are_dated(self):
|
|
r = reg(slackWorkspace=WS)
|
|
auto = [url_rec(link(CH, TS)), url_rec(link(CH, TS2), first=False),
|
|
url_rec(link(CH2, TS), first=False)]
|
|
out = view(r, auto, names={CH: "eng-alerts", CH2: "feature-requests"})
|
|
labels = {x["id"]: x["label"] for x in out}
|
|
self.assertNotEqual(day(TS), day(TS2))
|
|
self.assertEqual(labels[f"{CH}/{TS}"], f"#eng-alerts · {day(TS)}")
|
|
self.assertEqual(labels[f"{CH}/{TS2}"], f"#eng-alerts · {day(TS2)}")
|
|
self.assertEqual(labels[f"{CH2}/{TS}"], "#feature-requests") # alone: no date
|
|
|
|
def test_reply_and_parent_are_one_pill_not_dated(self):
|
|
out = view(reg(slackWorkspace=WS),
|
|
[url_rec(link(CH, TS)), url_rec(link(CH, REPLY_TS, thread=TS), first=False)],
|
|
names={CH: "eng-alerts"})
|
|
self.assertEqual([(x["id"], x["label"]) for x in out], [(f"{CH}/{TS}", "#eng-alerts")])
|
|
|
|
def test_two_dms_are_dated(self):
|
|
out = view(reg(), [url_rec(link(DM, TS)), url_rec(link("D09ZZZZZZZZ", TS2), first=False)])
|
|
self.assertEqual(sorted(x["label"] for x in out), sorted([f"DM · {day(TS)}", f"DM · {day(TS2)}"]))
|
|
|
|
def test_date_of(self):
|
|
d = reg().by_kind["slack"]
|
|
dt = d.date_of({"id": f"{CH}/{TS}"})
|
|
self.assertEqual(int(dt.timestamp()), int(float(TS)))
|
|
self.assertIsNone(d.date_of({"id": "garbage"}))
|
|
|
|
|
|
# ── scope: runners, folders, pills on pushes ────────────────────────────────
|
|
@skip
|
|
class TestScope(unittest.TestCase):
|
|
def test_empty_scope_is_everywhere(self):
|
|
r = reg()
|
|
for w, c in ((None, None), ("local", "/home/x"), ("acme-mac", "/Users/g/WORK/x")):
|
|
self.assertEqual(r.scoped_kinds(w, c), frozenset({"slack"}))
|
|
|
|
def test_workers(self):
|
|
r = reg(workers=["acme-mac", "devbox"])
|
|
self.assertEqual(r.scoped_kinds("acme-mac", "/x"), frozenset({"slack"}))
|
|
self.assertEqual(r.scoped_kinds("local", "/x"), frozenset())
|
|
self.assertEqual(r.scoped_kinds(None, "/x"), frozenset()) # None = local
|
|
self.assertEqual(reg(workers="local, devbox").scoped_kinds(None, "/x"),
|
|
frozenset({"slack"}))
|
|
|
|
def test_cwd_globs(self):
|
|
r = reg(cwdGlobs=["/Users/g/work/acme/acme*", "~/work/acme*"])
|
|
self.assertTrue(r.scoped_kinds("w", "/Users/g/work/acme/acme-monorepo"))
|
|
self.assertTrue(r.scoped_kinds("w", os.path.expanduser("~/work/acme-api")))
|
|
self.assertFalse(r.scoped_kinds("w", "/home/alice/homelab"))
|
|
self.assertFalse(r.scoped_kinds("w", None))
|
|
|
|
def test_both_must_match(self):
|
|
r = reg(workers=["acme-mac"], cwdGlobs=["/Users/g/WORK/*"])
|
|
self.assertTrue(r.scoped_kinds("acme-mac", "/Users/g/WORK/x"))
|
|
self.assertFalse(r.scoped_kinds("local", "/Users/g/WORK/x"))
|
|
self.assertFalse(r.scoped_kinds("acme-mac", "/tmp/x"))
|
|
|
|
def test_out_of_scope_hides_auto_pills_but_keeps_recorded(self):
|
|
r = reg(slackWorkspace=WS, workers=["acme-mac"])
|
|
auto = [url_rec(link(CH, TS))]
|
|
self.assertEqual(len(view(r, auto, worker="acme-mac", cwd="/x")), 1)
|
|
self.assertEqual(view(r, auto, worker="local", cwd="/x"), [])
|
|
rec = [{"kind": "slack", "id": f"{CH2}/{TS2}", "source": "agent"}]
|
|
out = view(r, auto, worker="local", cwd="/x", recorded=rec)
|
|
self.assertEqual([x["id"] for x in out], [f"{CH2}/{TS2}"])
|
|
self.assertEqual(out[0]["url"], link(CH2, TS2))
|
|
|
|
def test_notif_pills_default_off(self):
|
|
self.assertFalse(reg().notif_pills(None, None))
|
|
self.assertTrue(reg(notifPills=True).notif_pills(None, None))
|
|
r = reg(notifPills=True, workers=["acme-mac"])
|
|
self.assertTrue(r.notif_pills("acme-mac", "/x"))
|
|
self.assertFalse(r.notif_pills("local", "/x"))
|
|
|
|
def test_primary_when_alone(self):
|
|
out = view(reg(slackWorkspace=WS), [url_rec(link(CH, TS))])
|
|
self.assertTrue(out[0]["primary"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|