Files

662 lines
32 KiB
Python

#!/usr/bin/env python3
"""Unit tests for the Linear resource plugin — pure data, no code of its own:
its ``plugin.json`` validated by the hub's own ``plugins/manifest.py``, its
``resources[]`` compiled by ``plugins/resources.py`` and run through the
transcript miner and the card view the way the hub does (Linear links and
their slug titles, team-gated bare keys, branch / PR cross-links, the
``get_issue`` extractor, the card's hue, scope settings), plus the art.
Needs the ai-agent source (``~/projects/ai-agent/backend``, or
``AI_AGENT_BACKEND``); skipped without it.
python3 -m unittest discover -s plugins/linear/tests -p "test_*.py"
"""
from __future__ import annotations
import copy
import json
import os
import pathlib
import re
import subprocess
import sys
import tempfile
import types
import unittest
sys.dont_write_bytecode = True
PLUGIN = pathlib.Path(__file__).resolve().parents[1]
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 look
from conversations import resource_view as rv
from conversations.parse import parse_conversation
from plugins import resources as plugin_resources
from plugins.manifest import ManifestError, capability_fingerprint, validate_manifest
needs_backend = unittest.skipUnless(HAVE_BACKEND, f"no ai-agent backend at {BACKEND}")
WORKSPACE = "acme"
SETTINGS = {"linearWorkspace": WORKSPACE}
ACME = "/Users/alice/work/acme/acme"
ISSUE = "https://linear.app/acme/issue/"
PR = "https://github.com/acme-corp/acme-monorepo/pull/"
# A minimal stand-in for the github plugin's PR kind — only what the hue /
# shade and the xref paths need (``hueRole: "shade"``); the real github
# fixture is used where its ``gh pr view`` extractor matters.
PR_KIND = {"id": "pr", "label": "Pull request",
"urlRegex": "^https://github\\.com/(?P<repo>[\\w.-]+/[\\w.-]+)/pull/(?P<num>\\d{1,7})",
"idRegex": "^(?P<repo>[\\w.-]+/[\\w.-]+)#(?P<num>\\d{1,7})$",
"idTemplate": "{repo}#{num}", "priority": 20, "hueRole": "shade"}
# ── helpers ──────────────────────────────────────────────────────────────────
_MF: dict = {}
def manifest() -> dict:
if "m" not in _MF:
_MF["m"] = validate_manifest(PLUGIN)
return copy.deepcopy(_MF["m"])
def raw() -> dict:
return json.loads((PLUGIN / "plugin.json").read_text())
def res() -> dict:
return raw()["resources"][0]
def project_res() -> dict:
return raw()["resources"][1]
class Store:
"""What ``plugins.resources.registry`` reads of a ``PluginStore``: its
``version`` and the owner's active ``(id, manifest, settings)``."""
def __init__(self, settings=None, extra=()):
self.version = 1
self.rows = [("linear", manifest(), dict(SETTINGS if settings is None else settings))]
self.rows += list(extra)
def active_manifests(self, uid):
return [(p, copy.deepcopy(m), dict(c)) for p, m, c in self.rows]
def deps(store) -> types.SimpleNamespace:
return types.SimpleNamespace(plugin_store=store)
def registry(settings=None, extra=()):
return plugin_resources.registry(deps(Store(settings, extra)))
def pr_plugin(settings=None):
return ("prs", {"resources": [copy.deepcopy(PR_KIND)], "settings": {"fields": []}},
dict(settings or {}))
def github_fixture():
"""The hub's reference github manifest (its ``gh pr view`` extractor)."""
p = BACKEND / "fixtures" / "resource_plugins" / "github"
return ("github", validate_manifest(p), {"githubRepo": "acme-corp/acme-monorepo"}) \
if (p / "plugin.json").is_file() else None
class T:
"""A tiny transcript builder (the shape of a Claude Code JSONL)."""
def __init__(self):
self.recs, self.n = [], 0
def _ts(self):
self.n += 1
return f"2026-11-26T10:{self.n // 60:02d}:{self.n % 60:02d}.000Z"
def user(self, text, cwd=ACME, branch="main"):
self.recs.append({"type": "user", "timestamp": self._ts(), "cwd": cwd,
"gitBranch": branch, "sessionId": "s",
"message": {"role": "user", "content": text}})
return self
def tool(self, name, inp, result, cwd=ACME, branch="main"):
tid = f"toolu_{self.n}"
self.recs.append({"type": "assistant", "timestamp": self._ts(), "cwd": cwd,
"gitBranch": branch, "sessionId": "s",
"message": {"id": f"m{self.n}", "role": "assistant",
"model": "claude-opus-5-5", "content": [
{"type": "tool_use", "id": tid, "name": name,
"input": inp}]}})
self.recs.append({"type": "user", "timestamp": self._ts(), "cwd": cwd,
"gitBranch": branch, "sessionId": "s",
"message": {"role": "user", "content": [
{"type": "tool_result", "tool_use_id": tid, "content": result}]}})
return self
def parse(self, store=None):
prev = plugin_resources._bound
plugin_resources.bind(deps(store or Store()))
try:
with tempfile.TemporaryDirectory() as d:
p = pathlib.Path(d) / "11111111-2222-3333-4444-555555555555.jsonl"
p.write_text("\n".join(json.dumps(r) for r in self.recs) + "\n")
return parse_conversation(p)
finally:
plugin_resources._bound = prev
def keys(s) -> list[str]:
return [f"{r['kind']}:{r['id']}" for r in s["resourcesAuto"]]
def view(s, reg=None, archive_teams=(), scoped=None):
"""What a card shows of one summary — the teams this transcript saw in
real links plus ``archive_teams`` (what the rest of the archive saw)."""
reg = reg or registry()
teams, *rest = rv._derive(reg, s)
teams = {k: set(v) for k, v in teams.items()}
teams.setdefault("linear", set()).update(archive_teams)
ctx = rv.Context(reg, teams, *rest)
return rv.merge(s["resourcesAuto"], [], [], ctx, reg.kinds if scoped is None else scoped, True)
def by_key(rs) -> dict:
return {f"{r['kind']}:{r['id']}": r for r in rs}
# ── the manifest ─────────────────────────────────────────────────────────────
@needs_backend
class TestManifest(unittest.TestCase):
def test_validates_with_the_hubs_validator(self):
m = manifest()
self.assertEqual((m["schema"], m["id"], m["name"], m["version"], m["author"]),
(1, "linear", "Linear", "1.1.0", "gabrielvidal"))
self.assertEqual([r["id"] for r in m["resources"]], ["linear", "linear-project"])
def test_owner_only_and_declarative(self):
m, r = manifest(), raw()
# No guest edition, no code, no secrets, nothing scheduled, nothing reached.
for k in ("managed", "skill", "proxy", "handlers", "ui", "jobs", "agents"):
self.assertNotIn(k, r, k)
self.assertEqual((m["secrets"], m["actions"], m["schedules"], m["webhooks"],
m["capabilities"]), ([], {}, [], [], []))
self.assertFalse(any(p.suffix in (".py", ".sh", ".js") for p in PLUGIN.iterdir()))
def test_matches_the_hubs_reference_fixture(self):
ref = BACKEND / "fixtures" / "resource_plugins" / "linear" / "plugin.json"
if not ref.is_file():
self.skipTest("no reference fixture")
self.assertEqual(raw()["resources"], json.loads(ref.read_text())["resources"])
mine = {f["key"]: f["type"] for f in raw()["settings"]["fields"]}
theirs = {f["key"]: f["type"] for f in json.loads(ref.read_text())["settings"]["fields"]}
self.assertEqual(mine, theirs)
def test_resource_shape(self):
r = manifest()["resources"][0]
self.assertEqual((r["label"], r["icon"], r["color"], r["clickAction"], r["priority"],
r["hueRole"], r["bareKeyTeamGroup"], r["slugTitleGroup"]),
("Linear issue", "linear", "indigo", "open", 10, "hue", "team", "slug"))
for k in ("urlRegex", "idRegex", "bareKeyRegex", "branchKeyPattern"):
re.compile(r[k])
(ex,) = r["toolExtractors"]
self.assertEqual(ex["tool"], "mcp__*__get_issue")
self.assertEqual(ex["metaFields"], {"labels": "labels[].name", "project": "project.name",
"team": "team.name"})
self.assertEqual(r["groupBy"], "project")
def test_project_shape(self):
r = manifest()["resources"][1]
self.assertEqual((r["label"], r["icon"], r["clickAction"], r["priority"], r["hueRole"],
r["slugTitleGroup"]),
("Linear project", "folder-kanban", "open", 40, "group", "slug"))
get, lst = r["toolExtractors"]
self.assertEqual((get["tool"], lst["tool"], lst["itemsPath"]),
("mcp__*__get_project", "mcp__*__list_projects", "projects[]"))
for ex in (get, lst):
self.assertEqual(ex["metaFields"], {"icon": "icon", "color": "color"})
def test_scope_settings(self):
fields = {f["key"]: f for f in manifest()["settings"]["fields"]}
self.assertEqual({k: f["type"] for k, f in fields.items()},
{"linearWorkspace": "text", "workers": "list", "cwdGlobs": "list",
"notifPills": "checkbox", "cardColour": "select", "iconOrder": "select",
"groupPills": "checkbox", "groupLooks": "checkbox"})
self.assertIs(fields["notifPills"]["default"], False)
self.assertEqual((fields["cardColour"]["default"], fields["iconOrder"]["default"],
fields["groupPills"]["default"], fields["groupLooks"]["default"]),
("group", "group", True, True))
for k in ("cardColour", "iconOrder"):
self.assertEqual([o["value"] for o in fields[k]["options"]],
["group", "hue" if k == "cardColour" else "label"])
for f in fields.values():
self.assertTrue(f["label"] and f["help"], f["key"])
self.assertFalse(f["required"], f["key"])
self.assertIn("linear.app/<workspace>", fields["linearWorkspace"]["help"])
self.assertIn("local", fields["workers"]["help"])
self.assertIn("empty", fields["cwdGlobs"]["help"])
def test_fingerprint_reads_id_and_url_regex_only(self):
m = manifest()
fp = capability_fingerprint(m)
m["resources"][0]["toolExtractors"] = []
m["resources"][0]["bareKeyRegex"] = "x"
self.assertEqual(capability_fingerprint(m), fp)
m["resources"][0]["urlRegex"] = "^https://linear\\.app/x"
self.assertNotEqual(capability_fingerprint(m), fp)
def test_an_ungated_bare_key_would_be_refused(self):
r = raw()
del r["resources"][0]["bareKeyTeamGroup"]
with tempfile.TemporaryDirectory() as d:
(pathlib.Path(d) / "plugin.json").write_text(json.dumps(r))
with self.assertRaises(ManifestError):
validate_manifest(pathlib.Path(d))
# ── links, ids, templates ────────────────────────────────────────────────────
@needs_backend
class TestUrls(unittest.TestCase):
def setUp(self):
self.reg = registry()
def test_issue_link_with_slug_title(self):
r = self.reg.resolve_url(ISSUE + "APP-123/add-dark-mode-toggle")
self.assertEqual((r["kind"], r["id"], r["label"], r["team"], r["slugTitle"]),
("linear", "APP-123", "APP-123", "APP", "Add dark mode toggle"))
self.assertEqual(r["url"], ISSUE + "APP-123")
def test_link_without_slug_and_lowercase_key(self):
r = self.reg.resolve_url("https://linear.app/acme-co/issue/eng-42")
self.assertEqual((r["id"], r["url"], r["team"]),
("ENG-42", "https://linear.app/acme-co/issue/ENG-42", "ENG"))
self.assertNotIn("slugTitle", r)
def test_query_and_fragment_are_not_the_slug(self):
r = self.reg.resolve_url(ISSUE + "APP-7/fix-login?foo=1#comment-3")
self.assertEqual((r["id"], r["slugTitle"]), ("APP-7", "Fix login"))
def test_the_links_workspace_wins_over_the_setting(self):
r = self.reg.resolve_url("https://linear.app/other/issue/OPS-3")
self.assertEqual(r["url"], "https://linear.app/other/issue/OPS-3")
def test_not_issue_links(self):
for u in ("https://linear.app/acme/project/session-123",
"https://linear.app/acme/view/abc", "https://linear.app/acme/issue/123",
"http://linear.app/acme/issue/APP-1", "https://evil.io/linear.app/acme/issue/APP-1",
"https://linear.app/acme/issue/TOOLONGTEAM-1"):
self.assertIsNone(self.reg.resolve_url(u), u)
def test_key_alone_gets_the_settings_workspace(self):
r = self.reg.parse_ref("app-123")
self.assertEqual((r["kind"], r["id"], r["url"]), ("linear", "APP-123", ISSUE + "APP-123"))
self.assertEqual(self.reg.parse_ref("APP-123", kind="linear")["id"], "APP-123")
self.assertEqual(self.reg.parse_ref(ISSUE + "APP-9/x")["id"], "APP-9")
def test_key_alone_without_a_workspace_has_no_link(self):
r = registry(settings={}).parse_ref("APP-123")
self.assertEqual(r["id"], "APP-123")
self.assertIsNone(r["url"])
def test_token_and_needles(self):
d = self.reg.by_kind["linear"]
r = d.from_id("APP-123")
self.assertEqual(d.token(r), "APP-123")
self.assertEqual(d.needle_list(r), ["APP-123"])
def test_descriptor_for_the_ui(self):
dsc, pdsc = self.reg.descriptors()
self.assertEqual(dsc, {"id": "linear", "label": "Linear issue", "icon": "linear",
"color": "indigo", "stateTones": {}, "clickAction": "open",
"priority": 10, "hueRole": "hue", "pluginId": "linear"})
self.assertEqual((pdsc["id"], pdsc["hueRole"], pdsc["priority"]),
("linear-project", "group", 40))
# ── bare keys typed in prose ─────────────────────────────────────────────────
@needs_backend
class TestBareKeys(unittest.TestCase):
def setUp(self):
self.reg = registry()
def found(self, text):
return [r["id"] for _, r in self.reg.bare_keys(text)]
def test_keys_in_prose(self):
self.assertEqual(self.found("fix APP-2175 then (ENG-4), and OPS-12."),
["APP-2175", "ENG-4", "OPS-12"])
(_, r), = self.reg.bare_keys("see APP-2175")
self.assertTrue(r["bare"])
self.assertEqual((r["team"], r["url"]), ("APP", ISSUE + "APP-2175"))
def test_not_keys(self):
for t in ("path/APP-1", "#APP-1", "v1.APP-1", "APP-1-foo", "APP-12x", "app-12",
"a-APP-1", "APP-1234567", "TOOLONGT-1"):
self.assertEqual(self.found(t), [], t)
def test_spans_of_links_are_skipped(self):
text = f"{ISSUE}APP-1/x and APP-2"
start = text.index("https")
self.assertEqual([r["id"] for _, r in self.reg.bare_keys(text, [(start, start + 40)])],
["APP-2"])
def test_utf8_and_iso8601_never_become_issues(self):
text = (f"fix APP-2175 — the body is UTF-8, dates are ISO-8601, see {ISSUE}APP-1/x "
"and SHA-256 / X-1 for the rest")
s = T().user(text).parse()
# The miner keeps every key-shaped word, flagged bare…
stored = sorted(k for k in keys(s) if k.startswith("linear:"))
self.assertIn("linear:UTF-8", stored)
self.assertIn("linear:ISO-8601", stored)
# …the card keeps only teams a real link named.
self.assertEqual(sorted(by_key(view(s))), ["linear:APP-1", "linear:APP-2175"])
def test_a_team_seen_elsewhere_in_the_archive_counts(self):
s = T().user("ship ENG-77 today").parse()
self.assertEqual(list(by_key(view(s))), [])
self.assertEqual(list(by_key(view(s, archive_teams=("ENG",)))), ["linear:ENG-77"])
def test_without_the_plugin_no_keys_are_read(self):
store = Store()
store.rows = []
s = T().user(f"fix APP-2175 {ISSUE}APP-1/x").parse(store)
self.assertEqual([r["kind"] for r in s["resourcesAuto"]], ["url"])
# Installed later: the same stored summary lights up (no re-parse).
self.assertEqual(sorted(by_key(view(s))), ["linear:APP-1"])
# ── branches and PRs ─────────────────────────────────────────────────────────
@needs_backend
class TestCrossLinks(unittest.TestCase):
def setUp(self):
self.reg = registry()
def linked(self, text):
return [(r["id"], r.get("slugTitle")) for r in self.reg.cross_links(text)]
def test_branch_names(self):
self.assertEqual(self.linked("app-123-add-dark-mode-toggle"),
[("APP-123", "Add dark mode toggle")])
self.assertEqual(self.linked("alice/app-2007-login-page-crash"),
[("APP-2007", "Login page crash")])
self.assertEqual(self.linked("worktree-eng-4"), [("ENG-4", None)])
self.assertEqual(self.linked("feature/worktree-OPS-12-x"), [("OPS-12", "X")])
(r,) = self.reg.cross_links("app-123-x")
self.assertTrue(r["bare"])
self.assertEqual(r["url"], ISSUE + "APP-123")
def test_not_branch_keys(self):
for b in ("main", "dev-checks-panel", "release/2026-11", "a/b/app-1-x", "plugin-linear",
"", " "):
self.assertEqual(self.linked(b), [], b)
def test_skip_own_kind(self):
self.assertEqual(self.reg.cross_links("app-1-x", skip="linear"), [])
def test_pr_head_and_body_without_the_github_plugin(self):
# What the hub does with a PR's headRefName and what its body closes:
# plain strings through linear's branchKeyPattern — no github import.
body = "Closes APP-123.\r\n\r\nAlso fixes ENG-7, resolves https://x.io/y"
self.assertEqual(plugin_resources.closes(body), ["APP-123", "ENG-7", "https://x.io/y"])
got = [r["id"] for x in ["app-123-add-dark-mode", *plugin_resources.closes(body)]
for r in self.reg.cross_links(x)]
self.assertEqual(got, ["APP-123", "APP-123", "ENG-7"])
def test_git_branch_in_a_transcript(self):
s = (T().user(f"go {ISSUE}APP-1")
.tool("Bash", {"command": "git checkout -q -b app-2165-password-reset origin/main"}, "")
.parse())
self.assertIn("branch:app-2165-password-reset", keys(s))
v = by_key(view(s))
self.assertIn("linear:APP-2165", v)
self.assertEqual((v["linear:APP-2165"]["via"], v["linear:APP-2165"]["title"]),
("branch", "Password reset")) # the branch slug titles it
def test_gh_pr_view_head_and_body_link_the_issue(self):
gh = github_fixture()
if gh is None:
self.skipTest("no github reference fixture")
out = json.dumps({"body": "closes APP-123\r\n\r\n## Release message",
"headRefName": "app-123-add-dark-mode-toggle",
"state": "OPEN", "title": "feat(mrp): separate tenant",
"url": PR + "13722"})
store = Store(extra=[gh])
s = (T().user(f"review {PR}13722 {ISSUE}APP-1")
.tool("Bash", {"command": "gh pr view 13722 --json title,body,headRefName,state,url"},
out).parse(store))
info = s["resourceInfo"]["pr:acme-corp/acme-monorepo#13722"]
self.assertEqual(info["xref"], ["app-123-add-dark-mode-toggle", "APP-123"])
v = by_key(view(s, plugin_resources.registry(deps(store))))
self.assertEqual(v["linear:APP-123"]["via"], "xref")
self.assertTrue(v["linear:APP-123"]["firstTurn"])
# ── get_issue lookups ────────────────────────────────────────────────────────
@needs_backend
class TestGetIssue(unittest.TestCase):
RESULT = {"id": "APP-2007", "title": "TypeError: login page crash",
"url": ISSUE + "APP-2007/typeerror-login-page-crash",
"status": "In Progress",
"labels": [{"name": "Bug"}, {"name": "Backend"}],
"project": {"name": "Session"}, "team": {"name": "Insurance"}}
def test_extracts_title_status_labels_project_team(self):
s = (T().user(f"look at {ISSUE}APP-1")
.tool("mcp__linear__get_issue", {"id": "APP-2007"}, json.dumps(self.RESULT)).parse())
info = s["resourceInfo"]["linear:APP-2007"]
self.assertEqual(info["title"], "TypeError: login page crash")
self.assertEqual({k: info[k] for k in ("labels", "project", "team")},
{"labels": ["Bug", "Backend"], "project": "Session", "team": "Insurance"})
v = by_key(view(s))["linear:APP-2007"]
self.assertEqual((v["title"], v["state"]),
("TypeError: login page crash", "In Progress"))
self.assertEqual(v["url"], ISSUE + "APP-2007")
def test_any_linear_mcp_server_and_issueId_input(self):
res = dict(self.RESULT, id="c0ffee-uuid", identifier="ENG-9",
url="https://linear.app/acme/issue/ENG-9/x")
s = (T().user("go").tool("mcp__claude_ai_Linear__get_issue", {"issueId": "ENG-9"},
[{"type": "text", "text": json.dumps(res)}]).parse())
self.assertIn("linear:ENG-9", by_key(view(s)))
self.assertEqual(s["resourceInfo"]["linear:ENG-9"]["project"], "Session")
def test_moved_issue_titles_the_asked_key(self):
s = (T().user("TECH-1234 please")
.tool("mcp__linear__get_issue", {"id": "TECH-1234"}, json.dumps(self.RESULT)).parse())
self.assertEqual(s["resourceInfo"]["linear:TECH-1234"]["title"],
"TypeError: login page crash")
v = by_key(view(s))
self.assertIn("linear:APP-2007", v)
self.assertNotIn("linear:TECH-1234", v) # TECH: no real link named that team
def test_other_tools_are_not_linear_lookups(self):
s = (T().user("go").tool("mcp__linear__list_issues", {"query": "x"},
json.dumps({"id": "APP-3", "title": "nope"})).parse())
self.assertNotIn("linear:APP-3", s.get("resourceInfo") or {})
ex = registry().by_kind["linear"].extractors[0]
self.assertTrue(ex.matches("mcp__linear__get_issue"))
self.assertTrue(ex.matches("mcp__claude_ai_Linear__get_issue"))
self.assertFalse(ex.matches("mcp__linear__get_issue_comments"))
self.assertFalse(ex.matches("shell"))
# ── the card's colour ────────────────────────────────────────────────────────
@needs_backend
class TestHue(unittest.TestCase):
def test_issue_is_the_hue_its_prs_the_shades(self):
reg = registry(extra=[pr_plugin()])
self.assertEqual(reg.roles, {"linear": "hue", "pr": "shade", "linear-project": "group"})
self.assertEqual([d.kind for d in reg.defs], ["linear", "pr", "linear-project"])
rs = [{"kind": "pr", "id": "o/r#13497"}, {"kind": "linear", "id": "APP-2171"}]
self.assertEqual(look.subject(rs, reg.roles),
("linear:APP-2171+pr:o/r#13497", "linear:APP-2171"))
self.assertEqual(look.subject(rs[1:], reg.roles), ("linear:APP-2171", "linear:APP-2171"))
def test_the_issue_is_listed_first(self):
reg = registry(extra=[pr_plugin()])
s = T().user(f"review {PR}13722 for {ISSUE}APP-123/x").parse()
self.assertEqual([r["kind"] for r in view(s, reg)][:1], ["linear"])
# ── scope settings ───────────────────────────────────────────────────────────
KINDS = frozenset({"linear", "linear-project"})
@needs_backend
class TestScope(unittest.TestCase):
def test_empty_scope_is_everywhere(self):
reg = registry()
self.assertEqual(reg.scoped_kinds(None, "/anywhere"), KINDS)
self.assertEqual(reg.scoped_kinds("mac-acme", None), KINDS)
self.assertFalse(reg.notif_pills(None, "/"))
def test_workers_and_cwd_globs(self):
reg = registry(settings={**SETTINGS, "workers": "mac-acme\nlocal",
"cwdGlobs": ["/Users/alice/work/acme/acme*"],
"notifPills": True})
self.assertEqual(reg.scoped_kinds("mac-acme", ACME + "/.claude/worktrees/app-1"),
KINDS)
self.assertEqual(reg.scoped_kinds(None, ACME), KINDS) # None = local
self.assertEqual(reg.scoped_kinds("devbox", ACME), frozenset())
self.assertEqual(reg.scoped_kinds("mac-acme", "/home/x/homelab"), frozenset())
self.assertTrue(reg.notif_pills("mac-acme", ACME))
self.assertFalse(reg.notif_pills("mac-acme", "/tmp"))
def test_home_glob_expands(self):
home = pathlib.Path.home()
reg = registry(settings={"cwdGlobs": "~/work/acme*"})
self.assertEqual(reg.scoped_kinds(None, f"{home}/work/acme-api"), KINDS)
self.assertEqual(reg.scoped_kinds(None, f"{home}/work/other"), frozenset())
def test_out_of_scope_cards_drop_the_pills(self):
s = T().user(f"{ISSUE}APP-1/x and APP-2").parse()
self.assertEqual(sorted(by_key(view(s))), ["linear:APP-1", "linear:APP-2"])
self.assertEqual(list(by_key(view(s, scoped=frozenset()))), [])
def test_unsaved_notif_pills_reads_its_default(self):
self.assertFalse(registry(settings={}).notif_pills(None, "/"))
# ── projects ─────────────────────────────────────────────────────────────────
PROJECT = "https://linear.app/acme/project/checkout-revamp-4f81c6823b68"
LISTING = json.dumps({"projects": [
{"name": "Checkout revamp", "icon": "Rocket", "color": "#4CB782", "url": PROJECT},
{"name": "Docs", "icon": ":books:", "color": "#bec2c8",
"url": "https://linear.app/acme/project/docs-0123456789ab"}]})
def issue_in(key, project="Checkout revamp"):
return json.dumps({"id": key, "title": f"Issue {key}", "url": ISSUE + key,
"project": project, "team": "App"})
@needs_backend
class TestProjects(unittest.TestCase):
def test_project_link(self):
r = registry().resolve_url(PROJECT + "/overview")
self.assertEqual((r["kind"], r["id"], r["label"], r["url"]),
("linear-project", "checkout-revamp-4f81c6823b68", "Checkout revamp",
PROJECT))
self.assertIsNone(registry().resolve_url("https://linear.app/acme/projects/all"))
def test_get_project_and_list_projects_teach_the_look(self):
s = (T().user("projects?").tool("mcp__linear__list_projects", {}, LISTING)
.tool("mcp__linear__get_project", {"query": "x"}, json.dumps(
{"name": "Checkout revamp", "icon": "Rocket", "color": "#4cb782",
"url": PROJECT, "status": {"name": "Started"}})).parse())
info = s["resourceInfo"]["linear-project:checkout-revamp-4f81c6823b68"]
self.assertEqual((info["title"], info["icon"], info["color"], info["state"]),
("Checkout revamp", "Rocket", "#4cb782", "Started"))
self.assertEqual(s["resourceInfo"]["linear-project:docs-0123456789ab"]["icon"], ":books:")
# only the project looked up is what the conversation is about
self.assertEqual([k for k in keys(s) if k.startswith("linear-project")],
["linear-project:checkout-revamp-4f81c6823b68"])
def test_the_issues_project_pill_wears_linears_look(self):
s = (T().user(f"fix {ISSUE}APP-7").tool("mcp__linear__list_projects", {}, LISTING)
.tool("mcp__linear__get_issue", {"id": "APP-7"}, issue_in("APP-7")).parse())
rs = view(s)
self.assertEqual([r["kind"] for r in rs], ["linear", "linear-project"])
self.assertEqual((rs[1]["label"], rs[1]["icon"], rs[1]["color"], rs[1]["url"]),
("Checkout revamp", "rocket", "#4cb782", PROJECT))
off = registry(settings={**SETTINGS, "groupPills": False})
self.assertEqual([r["kind"] for r in view(s, off)], ["linear"])
def test_the_card_wears_the_projects_colour(self):
s = (T().user(f"fix {ISSUE}APP-7").tool("mcp__linear__list_projects", {}, LISTING)
.tool("mcp__linear__get_issue", {"id": "APP-7"}, issue_in("APP-7")).parse())
reg = registry()
teams, *rest = rv._derive(reg, s)
ctx = rv.Context(reg, teams, *rest)
rs = rv.merge(s["resourcesAuto"], [], [], ctx, reg.kinds, True)
subject, hue = look.subject(rs, reg.roles)
g = rv.group_look(ctx, hue, subject)
self.assertEqual(g, {"name": "Checkout revamp", "icon": "rocket", "color": "#4cb782"})
with tempfile.TemporaryDirectory() as d:
colors = look.LookColors(str(pathlib.Path(d) / "c.json"))
out = look.resolve(None, sid="s", subject_key=subject, seen=None, colors=colors,
group=g, hue_key=hue, prefs=reg.look)
self.assertEqual((out["color"], out["colorGroup"], out["linear"]["projectIcon"],
out["linear"]["iconOrder"]), ("#4cb782", "Checkout revamp", "rocket", "group"))
# ── art and the info page ────────────────────────────────────────────────────
class TestArt(unittest.TestCase):
def test_icon_svg(self):
svg = (PLUGIN / "icon.svg").read_text()
self.assertLess(len(svg.encode()), 32 * 1024)
for tok in ('viewBox="0 0 24 24"', 'width="24"', 'height="24"', 'fill="none"',
'stroke="currentColor"', 'stroke-width="1.75"', 'stroke-linecap="round"',
'stroke-linejoin="round"'):
self.assertIn(tok, svg)
for bad in ("<script", "foreignObject", "href", "data:", "http://", " on", "<image",
"<style", "<text"):
self.assertNotIn(bad, svg.replace("http://www.w3.org/2000/svg", ""), bad)
# Monochrome: currentColor only.
self.assertEqual(set(re.findall(r'(?:fill|stroke)="([^"]+)"', svg)) - {"none"},
{"currentColor"})
def test_illustration_webp(self):
p = PLUGIN / "illustration.webp"
b = p.read_bytes()
self.assertEqual((b[:4], b[8:12]), (b"RIFF", b"WEBP"))
self.assertLess(len(b), 60 * 1024)
try:
out = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "stream=width,height",
"-of", "csv=p=0", str(p)], capture_output=True, text=True,
timeout=20).stdout.strip()
except (OSError, subprocess.TimeoutExpired):
self.skipTest("no ffprobe")
w, h = map(int, out.split(","))
self.assertEqual(w, 960)
self.assertAlmostEqual(w / h, 16 / 9, delta=0.05)
def test_tile_colour_is_a_hex(self):
self.assertRegex(raw()["color"], r"^#[0-9a-f]{6}$")
def test_readme(self):
lines = [ln for ln in (PLUGIN / "README.md").read_text().splitlines() if ln.strip()]
self.assertTrue(6 <= len(lines) <= 12, len(lines))
text = "\n".join(lines)
for tok in ("linear.app", "UTF-8", "branch", "hue", "runners", "folders"):
self.assertIn(tok, text)
@needs_backend
def test_hub_picks_the_art_up(self):
m = manifest()
self.assertEqual((m["iconSvg"], m["illustration"], m["readme"], m["color"]),
("icon.svg", "illustration.webp", "README.md", raw()["color"]))
self.assertTrue(m["artVersion"])
if __name__ == "__main__":
unittest.main()