Files
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

345 lines
16 KiB
Python

"""A conversation's look — the colour and the action icon its cards wear.
``meta.look`` holds what was *set*: by the session itself (``conv look`` /
``conv-meta look``) or by the owner (the card's menu). Every key is optional
and a patch merges into what's there (an empty string clears a key):
* ``color`` — a palette name (``TagColor`` in the PWA's ``lib/tagStyles.ts``),
optionally with a shade (``violet-300``);
* ``action`` — what the conversation does (``ACTIONS``), drawn under its tile;
* ``icon`` — a project-icon override: a curated glyph key, or
``sh:<ref>`` for a selfh.st logo.
What the cards show is resolved on top of that (``resolve``):
* the **colour** of a work conversation follows its Linear issue + PR
(``subject``): the issue picks a hue no other recently active issue wears,
each of its PRs a shade of it (``LookColors``), and a conversation keeps the
colour it got first; any other conversation takes its project's colour (in
the PWA, from the tag);
* the **action** is the labeller's (``meta.lookAuto``, written by the
``conversation-labels`` plugin — ``plugins/hubcomplete.py``) unless
one was set.
"""
from __future__ import annotations
import datetime
import hashlib
import json
import os
import pathlib
import re
import threading
# The palette — `TAG_COLORS` keys minus the two theme-following ones (primary,
# slate), which can't tell two conversations apart.
COLORS = ("sky", "blue", "emerald", "amber", "violet", "rose", "cyan", "orange",
"lime", "fuchsia", "teal")
# Accepted when set by hand, never handed out automatically.
SET_ONLY_COLORS = ("primary", "slate")
# The shades a hue's PRs take, in order (the issue alone wears the plain 500):
# light, dark, then the two in between.
SHADES = ("300", "700", "400", "600")
# What a conversation does → its badge glyph (the PWA's `lib/look.tsx` maps
# the key to a lucide icon; keep the lists in step — cli/notify.py and the
# conv-meta skill carry copies).
ACTIONS = {
"feature": 'build, add, implement or change behaviour (the default for "make X do Y", "I want X")',
"fix": "something is broken, erroring or wrong and must be repaired",
"investigate": "find out why / analyse / debug, without a known fix yet",
"review": "review a pull request, read or answer review comments, update a PR after feedback",
"refactor": "restructure or clean code without changing behaviour",
"perf": "make it faster, lighter, use less memory",
"research": "explore options, compare tools, read up, evaluate feasibility",
"design": "UI look, mockups, visuals, icons, layout",
"docs": "write or update documentation or notes",
"test": "write, run or fix tests",
"data": "queries, dashboards, data exports, stats",
"deploy": "ship, release, publish, roll out",
"ops": "machines, services, infra, config, access, setup",
"question": "the user only asks a question, no change expected",
"plan": "produce a plan or a scope before doing the work",
"chore": "dependency updates, git housekeeping (merge, rebase, branches), cleanup",
}
# The labeller's instructions (the conversation-labels plugin reads them off its
# ``hub/labels/pending`` bridge; scripts/look-backfill.py to the Batch API). Tuned on 13 real
# conversations, 2026-10-20.
SYSTEM_PROMPT = (
"You label what a coding-agent conversation is doing, from its title and the "
"user's first message.\n"
'Answer with ONLY a JSON object {"action": "<key>"}, key exactly one of:\n'
+ "".join(f"- {k}: {v}\n" for k, v in ACTIONS.items())
+ 'Judge by what the user asks the agent to DO, not by words in the title ("implement '
'the research" is feature; "check the comments and review the code in <PR>" is review; '
'"update the PR description as per the last review comment" is review; "abort the '
'merge" is chore; "make generation faster" is perf). Linear labels, when given, are a '
'hint ("is : bug" leans fix, "is : improvement" leans feature).'
)
def ask_text(title: str | None, prompt: str | None, labels=()) -> str:
"""The user turn the labeller sends: title, the issue's labels, the ask."""
parts = [f"Title: {title.strip()[:300]}"] if (title or "").strip() else []
if labels:
parts.append("Linear labels: " + ", ".join(str(x)[:60] for x in list(labels)[:12]))
parts.append("First message:\n" + (prompt or "").strip()[:3000])
return "\n\n".join(parts)
_ICON_RE = re.compile(r"^(sh:)?[a-z0-9][a-z0-9-]{0,47}$")
_COLOR_RE = re.compile(r"^([a-z]+)(?:-(\d00))?$")
FIELDS = ("color", "action", "icon")
def valid_color(v: str) -> bool:
m = _COLOR_RE.match(v or "")
if not m or m.group(1) not in COLORS + SET_ONLY_COLORS:
return False
return m.group(2) is None or (m.group(2) in SHADES + ("500",)
and m.group(1) in COLORS)
def clean(look) -> dict:
"""Validate a ``look`` patch; raise ValueError on anything unknown.
Returns the patch with values stripped and lower-cased. ``""`` survives
(it clears that key when merged)."""
if not isinstance(look, dict):
raise ValueError("look must be an object")
unknown = set(look) - set(FIELDS)
if unknown:
raise ValueError(f"unknown look keys: {', '.join(sorted(unknown))}")
out = {}
for k, v in look.items():
if v is None:
continue
if not isinstance(v, str):
raise ValueError(f"look.{k} must be text")
v = v.strip().lower()
if v and k == "color" and not valid_color(v):
raise ValueError(f"unknown colour {v!r} — one of {', '.join(COLORS)} "
f"(optionally -{'/-'.join(SHADES)})")
if v and k == "action" and v not in ACTIONS:
raise ValueError(f"unknown action {v!r} — one of {', '.join(ACTIONS)}")
if v and k == "icon" and not _ICON_RE.match(v):
raise ValueError("look.icon is a glyph key or sh:<selfh.st ref>")
out[k] = v
return out
# ── what the colour stands for ───────────────────────────────────────────────
def subject(resources: list[dict] | None, roles: dict[str, str] | None = None
) -> tuple[str | None, str | None]:
"""``(subject, hue key)`` — what a work conversation's colour stands for,
and the ``kind:id`` of the resource its hue is (whose metadata draws the
work icon).
The subject is the **hue + shade combination** of the resources whose
plugin declares a ``hueRole`` (plugins/resources.py): with the ``linear``
and ``github`` plugins, ``linear:INS-2171+pr:o/r#13497`` — the issue is
the hue, its PRs its shades. The hue is the primary ``hue`` resource,
else the first (the view already cross-linked the issue a PR's or a
branch's name carries); the shade the primary ``shade`` one, else the
first. A hue without a shade is ``linear:INS-2171``; a shade alone is its
own hue (``pr:…``); with neither, the primary resource (a Slack thread,
a link)."""
rs = [r for r in resources or () if r.get("kind") and r.get("id")]
if not rs:
return None, None
roles = roles or {}
rs.sort(key=lambda r: not r.get("primary")) # stable: primary first
hue = next((r for r in rs if roles.get(r["kind"]) == "hue"), None)
shade = next((r for r in rs if roles.get(r["kind"]) == "shade"), None)
key = lambda r: f"{r['kind']}:{r['id']}" # noqa: E731
parts = ([key(hue)] if hue else []) + ([key(shade)] if shade else [])
if parts:
return "+".join(parts), key(hue) if hue else None
return key(rs[0]), None
# ── one colour per subject ───────────────────────────────────────────────────
LOOK_COLORS_PATH = os.environ.get("LOOK_COLORS_PATH", "/data/look-colors.json")
# The palette walked so that neighbours are far apart in hue — the first few
# live issues never get sky + blue, or amber + orange.
_SPREAD = ("violet", "emerald", "amber", "sky", "rose", "lime", "fuchsia", "teal",
"orange", "blue", "cyan")
# Issues active within this many days of each other compete for hues.
WINDOW_DAYS = 7
# `seen` only moves forward in steps this big (a running conversation's
# endedAt changes every turn — not a write per turn).
_SEEN_STEP = datetime.timedelta(hours=1)
_SAVE_DELAY_S = 2.0
def _ts(iso: str | None) -> datetime.datetime | None:
try:
return datetime.datetime.fromisoformat(str(iso).replace("Z", "+00:00"))
except ValueError:
return None
class LookColors:
"""Card colours, handed out once and kept (``/data/look-colors.json``).
* ``hues`` — the hue of an issue (or of a bare PR / Slack thread): the one
the fewest *other* hue keys active within ``WINDOW_DAYS`` of it wear,
ties broken by a hash of its key so a rebuild hands out the same ones;
* ``prs`` — a hue's shade resources (an issue's PRs) in the order first
seen: the first takes the light shade, the second the dark one… (the
hue alone is the plain colour); keyed ``prs`` on disk since it began;
* ``convs`` — the colour each conversation got first: it keeps it even
when it later opens a PR (Gabriel's call, 2026-10-20).
``seen`` is a hue's latest conversation activity, never "now" — rebuilding
old cards mustn't make old issues look live. Writes are debounced: the
first card build after a deploy hands out hundreds at once."""
def __init__(self, path: str = LOOK_COLORS_PATH):
self.path = pathlib.Path(path)
self._lock = threading.RLock()
self._timer: threading.Timer | None = None
self.hues: dict[str, dict] = {}
self.prs: dict[str, list[str]] = {}
self.convs: dict[str, dict] = {}
# Bumped when colours already handed out change (a pin by hand) — the
# list's per-card cache keys on it (conversations/catalog.py).
self.version = 0
try:
raw = json.loads(self.path.read_text(encoding="utf-8"))
self.hues = {k: v for k, v in (raw.get("hues") or {}).items()
if isinstance(v, dict) and v.get("color") in COLORS}
self.prs = {k: list(v) for k, v in (raw.get("prs") or {}).items()
if isinstance(v, list)}
self.convs = {k: v for k, v in (raw.get("convs") or {}).items()
if isinstance(v, dict) and valid_color(v.get("color") or "")}
except (OSError, ValueError, AttributeError):
pass
# ── persistence ─────────────────────────────────────────────────────────
def flush(self) -> None:
with self._lock:
self._timer = None
data = {"hues": self.hues, "prs": self.prs, "convs": self.convs}
try:
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(".json.tmp")
tmp.write_text(json.dumps(data, indent=1, sort_keys=True), encoding="utf-8")
os.replace(tmp, self.path)
except OSError:
pass
def _dirty(self) -> None:
if self._timer is None:
self._timer = threading.Timer(_SAVE_DELAY_S, self.flush)
self._timer.daemon = True
self._timer.start()
# ── hues ────────────────────────────────────────────────────────────────
def _hue(self, key: str, at: datetime.datetime | None, seen: str | None) -> str:
e = self.hues.get(key)
if e:
old = _ts(e.get("seen"))
if at and (old is None or at - old >= _SEEN_STEP):
self.hues[key] = {**e, "seen": seen}
self._dirty()
return e["color"]
used = dict.fromkeys(COLORS, 0)
for v in self.hues.values():
vs = _ts(v.get("seen"))
if at is None or vs is None or abs(vs - at).days < WINDOW_DAYS:
used[v["color"]] = used.get(v["color"], 0) + 1
start = int(hashlib.sha1(key.encode()).hexdigest(), 16) % len(_SPREAD)
order = _SPREAD[start:] + _SPREAD[:start]
color = min(order, key=lambda c: used.get(c, 0)) # min keeps order on ties
self.hues[key] = {"color": color, "seen": seen}
self._dirty()
return color
def color_for(self, subject_key: str, seen: str | None = None) -> str:
"""A subject's colour: its issue's hue, shaded by which of the issue's
PRs it is (``violet``, ``violet-300``, ``violet-700``…)."""
at = _ts(seen)
hue_key, _, pr = subject_key.partition("+")
with self._lock:
hue = self._hue(hue_key, at, seen)
if not pr:
return hue
order = self.prs.setdefault(hue_key, [])
if pr not in order:
order.append(pr)
self._dirty()
return f"{hue}-{SHADES[order.index(pr) % len(SHADES)]}"
def for_conversation(self, sid: str, subject_key: str, seen: str | None = None) -> str:
"""The conversation's colour — the one it got first, for good."""
e = self.convs.get(sid)
if e:
if seen: # keep its issue's hue marked live while it runs
with self._lock:
self._hue(e["subject"].partition("+")[0], _ts(seen), seen)
return e["color"]
color = self.color_for(subject_key, seen)
with self._lock:
self.convs[sid] = {"subject": subject_key, "color": color}
self._dirty()
return color
def subject_of(self, sid: str) -> str | None:
e = self.convs.get(sid)
return e.get("subject") if e else None
def set(self, subject_key: str, color: str) -> int:
"""Pin a subject's colour by hand — every conversation that wears it
follows. Returns how many conversations changed."""
with self._lock:
if "+" not in subject_key and "-" not in color:
self.hues[subject_key] = {**(self.hues.get(subject_key) or {}),
"color": color}
n = 0
for sid, e in self.convs.items():
if e.get("subject") == subject_key and e.get("color") != color:
self.convs[sid] = {**e, "color": color}
n += 1
self.version += 1
self._dirty()
return n
def resolve(stored: dict | None, *, sid: str | None, subject_key: str | None,
seen: str | None, colors: "LookColors | None",
auto: dict | None = None, linear: dict | None = None) -> dict | None:
"""The look a card wears: what was set (``meta.look``) over what derives.
* ``color`` — set, else the conversation's (``LookColors``: its issue's
hue, shaded by its PR; kept from first sight). ``None`` for a
conversation that isn't about an issue / PR / thread: the PWA then takes
its project's tag colour.
* ``subject`` — what the colour stands for (``linear:INS-2171+pr:…``),
the one it was first given.
* ``action`` — set, else Haiku's label (``auto``, ``meta.lookAuto``).
* ``icon`` — a set project-icon override only (the PWA otherwise draws
the Linear label's / project's / team's icon, or the project tag's).
* ``linear`` — the issue's ``{project, labels, team}`` (its work icon).
* ``set`` — which of color / action / icon the session or the owner chose;
``actionSource`` says where the action came from."""
stored = {k: v for k, v in (stored or {}).items() if k in FIELDS and v}
color = stored.get("color")
if colors is not None and sid:
kept = colors.subject_of(sid)
if kept or subject_key:
subject_key = kept or subject_key
derived = colors.for_conversation(sid, subject_key, seen)
color = color or derived
action, source = stored.get("action"), "set"
if not action and (auto or {}).get("action") in ACTIONS:
action, source = auto["action"], "haiku"
if not (color or action or subject_key or stored or linear):
return None
return {"color": color, "subject": subject_key, "action": action,
"actionSource": source if action else None,
"icon": stored.get("icon"), "linear": linear or None,
"set": sorted(stored)}