SLOPSHOPPER

Project Panel

A side pane for any repo with a plan: sections, items and what blocks the next one. Providers: AI-DLC v2, and a task ledger (WORKPLAN.md) read against its pull…

panebandguardcommandmodelprocess
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · project-panel
│ ┃ panel ✕ › fix the failing auth test and add an audit log call │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ Project [ ↻ Refresh ] │ ⏺ Read(src/auth.ts) │ ┃ │ No plan found for this session yet. │ ⎿ Read 6 lines │ ┃ ╰──────────────────────────────────────────╯ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · panel
╭──────────────────────────────────────────────────────────╮ │ Project [ ↻ Refresh ] │ │ No plan found for this session yet. │ ╰──────────────────────────────────────────────────────────╯
README

project-panel

A side pane for any repo with a plan: sections, items, and what blocks the next one. Which plan it reads is a provider: AI-DLC v2 (awslabs/aidlc-workflows) and a plain task ledger (WORKPLAN.md) read against the repository's pull or merge requests (GitHub through gh, GitLab through glab, self-hosted included). AI-DLC wins when both exist.

SHOP-MVP-RESTART          checked 12s ago [ ↻ Refresh ]

╭──────────────────────────────────────────────────────────╮
│ Now  Inception, 5 of 8                                   │
│ ○ domain-design                                  up next │
│ main: refined-mockups in review, PR #33                  │
│                                                          │
│ Next /aidlc                            [ Put in prompt ] │
│ Execute Domain Design                                    │
╰──────────────────────────────────────────────────────────╯

Needs attention (2)
‖ PR #33 not merged         Inception, after refined-mockups
‖ Parked at domain-design   Inception, after refined-mockups

◑  Plan  45% done, 10 of 22
▸ Initialization                                     ● 3/3 ✓
▸ Ideation                                           ● 4/4 ✓
▾ Inception                                            ◑ 3/8
    – reverse-engineering                          skipped
    ✓ practices-discovery [#27]
    ✓ requirements-analysis [#30]
    ✓ user-stories [#32]
    ◐ refined-mockups [#33]                      in review
    ╭──────────────────────────────────────────────────────╮
    │ ‖ PR #33 not merged                                  │
    │ domain-design can't start on main until it lands.    │
    ╰──────────────────────────────────────────────────────╯
    ╭──────────────────────────────────────────────────────╮
    │ ‖ Parked at domain-design                            │
    │ Waiting on PR #33 to merge; parked 2026-10-11 06:32. │
    │ Resume with /aidlc once it lands.                    │
    ╰──────────────────────────────────────────────────────╯
  › ○ domain-design                                up next
    ○ units-generation
    ○ contract-design
    ○ delivery-planning
▸ Construction                                         ○ 0/7
▸ Operation                                          skipped

Top to bottom the pane answers, in order: where am I (the header), what am I on and what is next (the Now card, with the Next command and a Put in prompt button), what blocks (Needs attention), and how far along the plan is (Plan, with its sections). The pane sizes to its content, so it follows the width the surface gives it, in three steps:

ColumnsLayout
under 48narrowone column. The header is the title and a lone ↻; the badge and the "checked" stamp move to a second row. Next stacks its button under the command. Attention rows are two lines (title, then where). Items show their first chip and a dim +N, and no status word except local only, reopened, stale and a PR's review state (cut, down to 8 columns, before the title is). Done-folding after 6 items, at most 8 open items; no status strip
48 to 79mediumone column. ↻ Refresh, the badge and the stamp share the title's row, and the title is what gets cut (…). Every chip and the status words show. Done-folding after 10 items, at most 12 open items; a collapsed section of 10+ items gets a status strip (64 px wide, or 10 cells on the terminal)
80 and upwidewith sections, two columns: the Now card, actions and attention on the left (40%), the plan on the right. The left column lays out for its own width (40% less the gap), so it uses the narrow layouts (stacked Next, two-line Attention rows) until the pane is 125 columns wide. Done-folding after 16 items, at most 20 open items; the strip is 96 px wide

Glyphs. Items: ✓ done (for AI-DLC: merged on the default branch), ◐ in progress, partial, in review (an open PR) or pushed and not merged, ◌ local only (this worktree, no PR), ○ planned, ✕ failed, – skipped, ↻ revising, ? awaiting a person, ↺ reopened (was done, being redone), an amber ✓ stale (done, but after a reopened item); › marks the current one. An item whose PR is open says where the review stands in its status word (see Pull request review): in draft, awaiting dev-b, changes requested, approved, approved with comments, no reviewer. Attention and gates: ⊘ blocks, ‖ parked or only a warning (also changes requested, and your PR not sent for review), ? waits on an answer or an approval, or on your review, ✓ your PR is approved (with or without comments) and waits on you to merge, ! the check itself failed, ≠ the plan and the repo disagree. Several stages sharing one PR carry a fold gutter on the right: ┐, │ between, ┘. Rings: ○ ◔ ◑ ◕ ● for 0, 1-37, 38-62, 63-99 and 100 percent.

Done-folding. A section with more items than the cap for its width (6, 10, 16) hides its done items behind one row, ✓ 6 done, show, at the top of the list. It never hides the current item, any item with a fold chip, or one with a gate after it. Pressing the row shows them all (and a Hide done row, in the same place at the top, puts them back). If the fold row's text is empty, nothing is hidden.

The open-items cap. A big ledger (one section may hold about a hundred open items) is not drawn as a wall. After done-folding, an expanded section shows at most 8 items on a narrow pane, 12 on a medium one and 20 on a wide one (the current item stays, in its place), then a row Show 32 more that shows the rest; Show fewer at the foot puts them back. The two are independent, so both rows can appear (done on top, more at the bottom). A gate after an item that is left out is not drawn in the list, but it stays under Needs attention. Fold gutters are computed over the items drawn. An empty label hides nothing.

The strip. A collapsed section of 10 or more items shows how its items stand, next to the ring: done in green, in progress and partial in the accent, failed in red, the rest in the track tone (a 6 px bar of rounded segments on the desktop, a 10-cell █▓▒░ bar on the terminal; any group that exists keeps at least one cell).

Small things. Next's reason and the Attention titles (drift labels included) wrap, since their tails carry the meaning; only the where is cut. The header's subtitle is a dim line under the title row (under row 2 on a narrow pane) that wraps, and is left out when the Now card already names the current item, because the card's place says the same. The plan heading's summary wraps beside its ring too, so a long label breaks onto a second line instead of being cut. On the terminal the big ring is the glyph alone (the summary carries the percent). A section at 100% or built has no strip, and every section's count column has one width (the widest, such as 18/18 ✓) so the rings line up. A chip of 8 characters or fewer never shrinks; a longer one is cut first, down to 6 columns, then the title. Proposed sections (a ledger's suggested products) sit under one dim "Proposed" divider, each as a dim card without a tag of its own. A section with no items and nothing counted has no ring and a dim title. A linked title is a Link around a truncating Text, in a clipping, shrinking wrapper.

Version mark (0.14.0). The pane's last line, dim and on the right, is project-panel 0.14.0: the version in the plugin.json the engine loaded the mod from ($.plugin.root), read once when the pane first draws. It says which build is drawing the pane, so a look can be told from an older one after an update. When the manifest cannot be read there is no mark, and the next draw asks again.

Freshness. renderPane takes an optional clock ({ now, checkedAt }). With one the stamp reads checked 12s ago; without it, read 12:03, the time the plan was read. The pane's render never reads $.clock itself (0.14.1): a render that reads the clock is redrawn by it, and each redraw retires the drawn buttons' press handles, so a click landing across one was lost and a fold took a second click. Its now is the refresh engine's latest clock reading (now()), which every poll tick moves; the engine redraws the pane only when the stamp's text would change, also while a read keeps failing (the stamp then ages: checked 30s ago).

Presses (0.18.0). A press on the pane is taken by a ui.press hook, from the button's key and the state now (src/render/press.ts), not left to the drawing's onPress closure: a pane hidden and shown again repaints its last drawing, whose closures the surface had let go, and the first press on it was lost. A key the pane does not draw now goes on to the closure.

Steady press handles (0.21.0). The hook alone did not stop the lost first press: <Button> mints a fresh press handle on every call, the host retires a drawing's handles when the next drawing arrives, and the host checks the handle before any ui.press hook runs. A press from a drawing the surface had not replaced yet (a poll's redraw, a pane shown again) named a retired handle and was dropped (ui_press not handled in the desktop app's log); the second press, on the new drawing, worked. Every button now keeps the handle its key was first drawn with (src/render/steady.ts, applied in both render hooks), and the host keeps a handle the plugin draws again, so a press lands on whichever drawing is on screen. The clock and the error line below come from the refresh engine (src/refresh.ts), which fills freshness on the model; hooks/register.tsx passes the clock. When the latest re-read or remote check failed, a red line under the header says so, the same text is the first Attention row, and the panel keeps the last good model.

On the desktop, vscode and mobile surfaces the rings are real donuts (an Svg): 40 px with the percent drawn inside for the plan, 16 px per section, and each Attention row a bordered card in its tone. The terminal has no Svg, so it draws the glyph rings and plain Attention lines above.

Phase views (0.12.0). On those same surfaces a plan of a handful of phases (2 to 7 sections, proposed ones not counted) gets two more views. A one-column pane (under 80 columns) draws the phase stepper between the header and the Now card: one Svg row of numbered nodes joined by a line, each over its title (cut with … to the room between nodes). A built phase is a green check, the current one (holding the current item, else the first active) an accent ring with its percent as the arc and its title bold in the accent, skipped and uncounted phases (no items, or not included yet) dashed; the line after a built phase is green. The Svg has no size of its own and fits its slot; its alt names every phase and where it stands. The wide pane's plan column draws phase cards instead of the section headings: one bordered card per phase (the open ones in the accent, any under the pointer too) with a 20 px ring, the count (skipped, or not included yet in amber), the numbered title and a strip (86 px). The title is the heading's button under the same key (section:<id>), so a press opens or closes that phase as before and the fold carries over between widths; every open phase draws its items under the cards, under its title, with the same done-folding, cap and gates. A closed card carries the ‖/⊘ of a gate it holds. More than 7 phases, and the terminal, keep the list.

The desktop look (0.13.0). The surfaces that draw Svg (desktop, vscode, mobile) get the card-and-pill look of the design canvas; the terminal keeps its glyphs. Tints are translucent 8-digit hex fills of a tone's mid-tone, so they read on a light and a dark theme alike.

  • Header: the title, the badge as a pill beside it, Refresh at the end; the stamp and the subtitle dim under it.
  • Cards: the stepper and the Now card sit on a faint neutral fill under a faint line (a side job keeps its warning edge). Card labels are set in capitals (NOW, NEXT, THIS SESSION).
  • Next: the label, the command as a grey pill and the reason on one wrapping line, the button under them.
  • Needs attention: the heading with its count as a pill; each card tinted in its tone, the title in the text colour, the where, and the gate's caption under it. The cards stand two lines apart. The rows about pull requests (the rows that link to a PR) are one card, Pull requests (3), where the first of them stood, in the worst of their tones, with one line per PR (0.24.0): the glyph of its worst row, the PR as a link (PR #66, MR !66), everything its rows say in a word or two, worst first (conflicts · not merged · changes requested), and the first command they offer as a small button named by the command (address-review). A review asked of you on someone else's PR outside the plan adds its title and author. No where or caption: the plan's own gate lines say where. The count still counts every row. The terminal draws no cards and keeps every row in place.
  • Plan: Plan bold over a dim summary. A section row is the chevron, its ring (a dashed one where nothing is counted or it is skipped), the numbered title, the count on the right.
  • Items: the status as a 14 px icon (its alt the status word), chips as grey pills without brackets, the status word as a pill in its tone, and the current row tinted in the accent instead of the ›. A gate inside the plan is one line in its tone; its card, with the caption, is under Needs attention.

It is a mod: a TypeScript function-hooks module (hooks/register.tsx) the engine draws on the desktop app's and the terminal's pane surfaces.

Install

/plugin install project-panel --marketplace maksymskuibida/mskuibida-ai-tools

The command is /panel. Where a provider finds a plan the desktop app opens the pane on session start (panel: auto); anywhere, run /panel. Where none does, the mod stays silent — no pane, no command.

It is /panel, not /aidlc: every AI-DLC workspace already ships its own /aidlc skill (the workflow's entry point), and the two would collide. There are no aliases.

Function hooks without CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1: unverified. claude plugin test and validate do not prove it for a live session. The only evidence is that the name appears in the claude 2.1.296 binary solely in lists of environment-variable names, never as a read that gates anything.

Providers

A provider turns one kind of plan into the same neutral PanelModel (types/index.d.ts); the renderer draws any model the same way. src/detect.ts tries the providers in order and the first hit wins; a provider that throws counts as a miss.

ProviderReadsStatus
aidlcan AI-DLC v2 workspace (aidlc/spaces/)shipped
ledgera task ledger (WORKPLAN.md and kin) read against its pull requestsshipped (0.4.0)

A provider is { id, detect(ctx), load(ctx, detection), act?(ctx, detection, actionId) }. ctx hands it file reads (fsx), the host (run a command, complete with a model, mcp to call one of the session's MCP servers, write a file, a persistent store; anything that would spawn goes through it), the session and the options.

The model is sections (with an optional ring), an overall percent with an optional overall.label (display text that replaces the plan heading's own "45% done, 10 of 22", e.g. "74% of effort · 189/287 tasks"), items (status, chips, links), gates between items (parked, awaiting approval, later PR-not-merged...), drift flags, a Next command, and optional action buttons. Text in it is display text the provider resolved through src/strings/en.ts; an empty string hides that element.

The ledger provider

For a repository that keeps its plan in a task ledger: a WORKPLAN.md-style file of tasks with ids. It shows how far the repository has got, task by task, by reading the ledger against the pull requests.

What it detects

In a git repository, the first of these that parses as a ledger (at least 3 items with ids, or at least 5 checkboxes), looking only at git-tracked files:

  1. the path named by task-ledger: in the front matter of docs/DELIVERY.md;
  2. a root WORKPLAN.md, ROADMAP.md, PLAN.md, TODO.md (any case), in that order;
  3. the same names under docs/;
  4. docs/**/plan*.md.

Ledgers may be tables whose first cell starts with a bold id (| T04 | Act | T01a, T03 | M |), headings (#### T04 — Act, a Done first line marks it done), or checkboxes (- [x] API-3 Rate limiting). Phases are the ## headings. A fenced "order of play" (done T02 …, open T16 …, then T04 …) sets the status of items the ledger does not otherwise declare.

How status is derived

EvidenceStatus
a merged PR for the taskdone
an open PRin progress, with a #N chip
the PR carries the qa:failed labelfailed
only sub-slice PRs (T06a, T06b for a task T06)partial if one merged, in progress if only open ones
nothing, or only closed PRswhat the ledger declares (Done, [x], (implemented), an order-of-play line), else planned

How a PR is matched to a task: the id must appear in the PR title or branch with word boundaries (T04 never matches T04a; T1 never matches T10), in any case (qa/t04a-preprod). The strongest tier decides: a delivery branch (feat/T04-…), then a follow-up branch (fix/, hotfix/, qa/), then a loose mention, which counts only when the PR title names the id as its subject (feat(T04):, T04 —, [T04], a trailing (T04)); any other mention is just a chip. Fix PRs on a delivered task stay follow-up chips. A PR naming a longer id (fix-T04a-backdate-picker) belongs to that id only, not to T04a. Reverts never count; they show as chips. Progress is weighted by size: XS 0.5, S 1, M 2, L 3, XL 5 (unknown 1); done counts 1, partial 0.5.

The header shows idle when nothing is in flight, stage when the session's branch names a task, and inferred otherwise. Next is the first planned task with no open PR whose ledger dependencies are done, unless the session's task has an open PR that asks something of you (see Pull request review). The Attention block lists the rows tied to you first, then disagreements: the ledger says not done but a PR merged, the ledger says done but a PR is still open, qa:failed. A task in progress shows its PR's review state as its status word, and a Slack thread chip when the PR has one.

What it runs

All through the host, no shell, from the repository root: git rev-parse --show-toplevel, git ls-files -s -z, git show HEAD:<path>, git fetch --quiet origin <default branch>, git show origin/<default branch>:<path>, git ls-tree -r -z origin/<default branch>, git rev-parse --abbrev-ref HEAD, git symbolic-ref, git remote get-url origin, and the forge's reads (see Forges): on GitHub gh repo view and gh pr list --state all --limit 1000, on GitLab glab api projects/<path> and glab mr list --all, paged. The repository facts, the request list and the branch lookup run together. On GitHub the list also carries each pull request's review (isDraft,reviewDecision,reviewRequests,latestReviews,body,author; one call, the review rides on it). When a pull request is open: gh api user --hostname <host> (once an hour per repository), gh api user/teams?per_page=100 --hostname <host> (only when an open pull request asks a team; once an hour) and git show HEAD:.claude/settings.json (when tracked). The ledger is read from the default branch (after a fetch) so the pane shows what is merged; if the fetch fails but the branch is there the header says the ledger may be behind origin, and if the branch cannot be read it falls back to the committed local copy and says so. When the pull or merge requests cannot be read (no CLI, not logged in, offline, no origin remote) progress comes from the ledger alone and the header says why. It never writes to the repository or the forge: git fetch only updates remote-tracking refs, and every gh/glab call is a read.

Forges: GitHub and GitLab

The origin remote (git remote get-url origin) says where the requests live. src/forge/ parses it (scp-like git@host:group/sub/repo.git, ssh:// with a port, https:// with or without credentials and a port, git://; nested groups of any depth; credentials are never kept, even a password containing @; an ssh port is not the web port; a port above 65535 is no remote; ssh.github.com is github.com; an ssh-config alias such as Host work is not resolved, so set the forge option for such a remote) and picks the forge in this order, with no list of known hosts:

  1. the forge option is none: no forge, no requests, no complaint;
  2. no readable origin: no forge, and the header says so;
  3. the forge option is github or gitlab: that forge for the origin's host, no probe;
  4. the host is github.com: GitHub;
  5. glab auth status --hostname <host> succeeds: GitLab;
  6. gh auth status --hostname <host> succeeds: GitHub Enterprise;
  7. otherwise GitLab anyway (a self-hosted host that is not GitHub is far more often GitLab), whose calls then report the real problem.

A found forge's kind is remembered per repository and origin until the mod reloads (the forge itself is rebuilt from the current host on each call); the fallback in 7 is remembered for 60 seconds only, so a host with no login does not pay the two 5-second probes on every load and poll, and logging in is picked up within a minute.

GitHub (gh)GitLab (glab)
a change ispull request, #33merge request, !275
repositorygh repo view --json url,defaultBranchRefglab api --hostname <host> projects/<url-encoded path>
listgh pr list --state all --limit 1000 --json ...glab mr list -R <web address> --all -F json -P 100 -p <page>, until a short page, at most 10 pages
list, one state (AI-DLC)--state open, merged or closed, and a --limitno flag for open (glab's default), --merged or --closed
status (open only)in the same list: review decision, merge state, check rollupat most 20 open merge requests, five calls at a time: glab mr view <n> -R ... -F json (pipeline) and .../merge_requests/<n>/approvals; a failed lookup leaves its field empty without probing
files of a changegh pr view <n> --json files.../merge_requests/<n>/diffs?per_page=100 (paged), else .../changes on a GitLab without /diffs
remote fingerprintgh pr list ... --json number,state,mergedAt,headRefOidglab mr list ... -P 30 -o updated_at -S desc
AI-DLC remote fingerprintthe same lists as a loadthe lists plus one pipeline lookup per open merge request, no approvals (a load asks for those)
line links<web>/blob/<branch>/<path>#L<n><web>/-/blob/<branch>/<path>#L<n>

Every GitLab merge-request command gets -R <web address> (a full URL, which glab accepts for any host, so GITLAB_HOST is not needed); glab api gets --hostname. Chips, drift lines and links spell a change the way its forge does (!275, not #275).

When a call fails the header (and the Attention line of the live refresh) names the cause:

CauseMeantShown as
missingthe CLI does not start (and <cli> --version does not either)glab missing
not logged inthe call failed and <cli> auth status --hostname <host> failsglab not logged in to gitlab.example.test
unreachablethe call timed out, or failed with a network-looking errorcould not reach gitlab.example.test
failedanything elseglab failed

| no origin

Source 62 files
hooks/register.tsx 436 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Fsx, FsxEntry, ProviderContext, ProviderHost } from '../types'
5import { buildModel, fingerprintOf, runAction } from '../src/model'
6import { createRefreshEngine } from '../src/refresh'
7import type { RefreshEngine, RefreshPorts, Snapshot } from '../src/refresh'
8import { renderPane } from '../src/render'
9import type { Handlers } from '../src/render'
10import { pressAction } from '../src/render/press'
11import { steadyPresses } from '../src/render/steady'
12import { manifestPath, versionOfManifest } from '../src/version'
13import { t } from '../src/strings/en'
14import type { PanelModel, PanelOptions } from '../types'
15
16const PANE = 'panel'
17
18const modelAtom = atom({ plugin: 'project-panel', key: 'model' } as const, null)
19const expandedAtom = atom({ plugin: 'project-panel', key: 'expanded' } as const, {})
20const closedAtom = atom({ plugin: 'project-panel', key: 'isClosed' } as const, false)
21
22// What a missing path looks like when `$.fs` rejects (it says ENOENT); anything else is a real failure.
23const MISSING = /ENOENT|ENOTDIR|EISDIR|no such file|not found|not a directory|is a directory/i
24
25/** Counts the `$.fs` rejections that were not a plain missing path, so a read can tell "nothing there" from "could not look". */
26type FsTally = { failures: number }
27
28function tallied<T>(tally: FsTally, fallback: T): (error: unknown) => T {
29  return error => {
30    if (!MISSING.test(error instanceof Error ? error.message : String(error))) tally.failures++
31    return fallback
32  }
33}
34
35// `$.fs` as the Fsx port, adapted here: the engine follows `$`
36// only into functions of this file, never across an import. The port answers rather than rejects;
37// `tally` remembers the rejections that were not "missing".
38function fsxOf($: EngineInterface, tally: FsTally = { failures: 0 }): Fsx {
39  return {
40    read: path => $.fs.read(path).catch(tallied<string | null>(tally, null)),
41    exists: path => $.fs.exists(path).catch(tallied(tally, false)),
42    list: path =>
43      $.fs
44        .list(path)
45        .then(entries => entries.map(({ name, kind }) => ({ name, kind })))
46        .catch(tallied<FsxEntry[]>(tally, [])),
47    mtime: path =>
48      $.fs
49        .stat(path)
50        .then(stat => stat.mtimeMs)
51        .catch(tallied<number | null>(tally, null)),
52  }
53}
54
55// `$.process`, `$.model`, `$.mcp`, `$.fs.write` and `$.store` as the ProviderHost port.
56function hostOf($: EngineInterface): ProviderHost {
57  return {
58    run: (argv, init) =>
59      $.process.run(argv, init).then(({ exitCode, stdout, stderr }) => ({ exitCode, stdout, stderr })),
60    complete: req =>
61      $.model
62        .complete(req)
63        .then(reply => (reply.isAnswered ? { isAnswered: true, text: reply.text } : { isAnswered: false, text: '' }))
64        .catch(() => ({ isAnswered: false, text: '' })),
65    mcp: (server, tool, args) =>
66      $.mcp.call(server, tool, args).then(result => ({
67        isError: result.isError,
68        text: result.content.map(block => (typeof block.text === 'string' ? block.text : '')).join('\n'),
69      })),
70    write: (path, text) => $.fs.write(path, text),
71    store: {
72      get: key => $.store.get(key),
73      set: (key, value) => $.store.set(key, value),
74    },
75  }
76}
77
78type Settings = PanelOptions & {
79  /** auto: open by itself on a desktop; command: only /panel; off: never. */
80  panel: 'auto' | 'command' | 'off'
81  /** Seconds between mtime polls; 0 = off. */
82  fsPollSeconds: number
83  /** Seconds between remote-fingerprint polls; 0 = off. */
84  prPollSeconds: number
85  /** Which forge pull or merge requests are read from. */
86  forge: 'auto' | 'github' | 'gitlab' | 'none'
87}
88
89const DEFAULT_FS_POLL = 10
90const DEFAULT_PR_POLL = 180
91const MIN_FS_POLL = 2
92const MIN_PR_POLL = 30
93
94/** A poll interval option: unset or garbled = the default, 0 = off, anything else at least `min`. */
95function pollSeconds(value: unknown, fallback: number, min: number): number {
96  if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return fallback
97  return value === 0 ? 0 : Math.max(min, value)
98}
99
100async function contextOf($: EngineInterface, settings: Settings, tally?: FsTally): Promise<ProviderContext> {
101  const [startDir, sessionId, now] = await Promise.all([$.session.root(), $.session.id(), $.clock.now()])
102  return {
103    fsx: fsxOf($, tally),
104    host: hostOf($),
105    startDir,
106    sessionId,
107    now,
108    options: {
109      stageBranchPattern: settings.stageBranchPattern,
110      foldSeparator: settings.foldSeparator,
111      forge: settings.forge,
112      reviewCommands: settings.reviewCommands,
113      slackDomain: settings.slackDomain,
114    },
115  }
116}
117
118/**
119 * detect + load. A disk that fails (not a path that is merely missing) throws: the providers turn a failed
120 * read into "nothing there", which must not be taken for "no plan".
121 */
122async function build($: EngineInterface, settings: Settings): Promise<PanelModel | null> {
123  const tally: FsTally = { failures: 0 }
124  const model = await buildModel(await contextOf($, settings, tally))
125  if (tally.failures > 0) throw new Error('the plan could not be read')
126  return model
127}
128
129// The refresh engine's ports (src/refresh.ts), adapted from `$` here: the engine follows `$`
130// only into functions of this file, and src/ stays `$`-free.
131function refreshPortsOf($: EngineInterface, settings: Settings): RefreshPorts {
132  return {
133    now: () => $.clock.now(),
134    after: (ms, fn) => $.clock.after(ms, fn),
135    every: (ms, fn) => $.clock.every(ms, fn),
136    load: () => build($, settings),
137    fingerprint: async () => fingerprintOf(await contextOf($, settings)),
138    mtime: path =>
139      $.fs
140        .stat(path)
141        .then(stat => stat.mtimeMs)
142        .catch(() => null),
143    run: (argv, init) => $.process.run(argv, init).then(({ exitCode, stdout }) => ({ exitCode, stdout })),
144    publish: async model => {
145      await update($, modelAtom, () => model)
146    },
147    invalidate: async () => {
148      $.ui.invalidate('ui.render')
149    },
150    isVisible: async () => {
151      // The pane list only holds open panes (a person's close removes it), so a closed flag is no veto here.
152      if (settings.panel === 'off') return false
153      const panes = await $.ui.panes()
154      return panes.some(pane => pane.id === PANE && pane.isPlaced)
155    },
156  }
157}
158
159/**
160 * Where the register closure keeps its refresh engine, and the plugin's own version once its manifest has been read
161 * (for the pane's foot); the helpers below take it as a plain argument. `presses` keeps each drawing's press handle
162 * per button key (src/render/steady.ts), so a press on a drawing the surface has not replaced yet still lands.
163 */
164type EngineSlot = { engine: RefreshEngine | null; version?: Promise<string>; presses: { pane: Map<string, number>; bar: Map<string, number> } }
165
166function bindEngine($: EngineInterface, settings: Settings, slot: EngineSlot, startDir: string): RefreshEngine {
167  slot.engine?.stop()
168  slot.engine = createRefreshEngine(refreshPortsOf($, settings), {
169    startDir,
170    isEnabled: settings.panel !== 'off',
171    fsPollSeconds: settings.fsPollSeconds,
172    prPollSeconds: settings.prPollSeconds,
173  })
174  return slot.engine
175}
176
177async function engineOf($: EngineInterface, settings: Settings, slot: EngineSlot): Promise<RefreshEngine> {
178  return slot.engine ?? bindEngine($, settings, slot, await $.session.root().catch(() => ''))
179}
180
181// What the pane's buttons do: the drawing's closures and the press hook both run these.
182function handlersOf($: EngineInterface, settings: Settings, slot: EngineSlot): Handlers {
183  return {
184    onRefresh: async () => {
185      await (await engineOf($, settings, slot)).readNow({ manual: true })
186    },
187    onToggle: async (sectionId, isOpen) => {
188      await update($, expandedAtom, folds => ({ ...folds, [sectionId]: isOpen }))
189    },
190    onAction: async actionId => {
191      // The provider that owns the plan answers; its model replaces the drawn one.
192      const running = await engineOf($, settings, slot)
193      const before = await running.snapshot().catch(() => undefined)
194      const acted = await runAction(await contextOf($, settings), actionId)
195      if (acted === null) return
196      // The engine adopts the provider's answer (a read still in flight drops its result), so the next poll does not re-publish it.
197      const adopted = await running.seed(acted, before)
198      await update($, modelAtom, () => adopted)
199    },
200    onFillNext: async command => {
201      await $.prompt.fill({ text: command, mode: 'replace' })
202    },
203  }
204}
205
206/** Opens the pane once for a desktop that attached after session start (`panel: auto`, a plan, not closed, not open). */
207async function openForDesktop($: EngineInterface, settings: Settings): Promise<void> {
208  if (settings.panel !== 'auto') return
209  if ((await read($, modelAtom)) === null) return
210  if (await read($, closedAtom)) return
211  if ((await $.ui.panes()).some(pane => pane.id === PANE)) return
212  await $.ui.open({ id: PANE, title: t('pane.title') })
213}
214
215/** Opens the pane on the person's ask (`/panel` or the reopen bar): clears the closed flag, opens, wakes the engine. */
216async function openAsked($: EngineInterface, running: RefreshEngine): Promise<boolean> {
217  await update($, closedAtom, () => false)
218  const opened = await $.ui.open({ id: PANE, title: t('pane.title') })
219  await running.wake().catch(() => undefined)
220  return opened.isPlaced
221}
222
223export const register: Register = (on, options) => {
224  const panel = options.panel
225  const reviewCommands = options.reviewCommands
226  const settings: Settings = {
227    stageBranchPattern: String(options.stageBranchPattern ?? ''),
228    foldSeparator: String(options.foldSeparator ?? ''),
229    reviewCommands: reviewCommands === 'on' || reviewCommands === 'off' ? reviewCommands : 'auto',
230    slackDomain: String(options.slackDomain ?? '').trim(),
231    panel: panel === 'command' || panel === 'off' ? panel : 'auto',
232    fsPollSeconds: pollSeconds(options.fsPollSeconds, DEFAULT_FS_POLL, MIN_FS_POLL),
233    prPollSeconds: pollSeconds(options.prPollSeconds, DEFAULT_PR_POLL, MIN_PR_POLL),
234    forge: options.forge === 'github' || options.forge === 'gitlab' || options.forge === 'none' ? options.forge : 'auto',
235  }
236
237  // The refresh engine, bound at session.start. A module reload re-runs session.start, which stops this one.
238  const slot: EngineSlot = { engine: null, presses: { pane: new Map(), bar: new Map() } }
239
240  on('session.start', async ($, e, next) => {
241    const started = await next(e)
242
243    // Bind the engine afresh (a reload re-runs this hook); the old one's timers stop.
244    let bound: RefreshEngine | null = null
245    let before: Snapshot | undefined
246    try {
247      bound = bindEngine($, settings, slot, await $.session.root().catch(() => e.cwd))
248    } catch {
249      bound = null
250    }
251
252    // A plan that can't be read must never break session start.
253    let model: PanelModel | null = null
254    try {
255      // Baselines first, so a write during the read is seen by the next poll.
256      before = bound === null ? undefined : await bound.snapshot().catch(() => undefined)
257      model = await build($, settings)
258    } catch {
259      model = null
260    }
261    try {
262      // The engine adopts this read (hash, mtimes, HEAD), so its first poll does not re-publish it.
263      const seeded = bound === null ? model : await bound.seed(model, before).catch(() => model)
264      await update($, modelAtom, () => seeded)
265    } catch {
266      return started
267    }
268    // Silent without a plan: no command, no pane.
269    if (model === null) return started
270
271    try {
272      await $.command.register({ name: 'panel', description: t('command.description') })
273    } catch {
274      // The pane can still open by itself.
275    }
276    try {
277      if (settings.panel === 'auto' && !(await read($, closedAtom))) {
278        // Unasked panes are only placed from 144 columns, so only a desktop is opened by itself.
279        const isDesktop = e.surface === 'desktop' || (await $.session.surfaces()).includes('desktop')
280        if (isDesktop) await $.ui.open({ id: PANE, title: t('pane.title') })
281      }
282    } catch {
283      // The command still opens it.
284    }
285    // Polls run only while the pane is on screen; the engine checks that itself.
286    try {
287      await bound?.start()
288    } catch {
289      // The pane works without live refresh.
290    }
291    return started
292  })
293
294  on('command.run', { command: 'panel' }, async $ => {
295    if (settings.panel === 'off') return { text: t('command.disabled') }
296
297    let model: PanelModel | null
298    let running: RefreshEngine
299    try {
300      running = await engineOf($, settings, slot)
301      const outcome = await running.readNow()
302      if (!outcome.ok) return { text: t('command.readFailed') }
303      model = outcome.model
304    } catch {
305      return { text: t('command.readFailed') }
306    }
307    if (model === null) {
308      const root = await $.session.root().catch(() => '')
309      return { text: t('command.noPlan', { root }) || t('command.readFailed') }
310    }
311
312    try {
313      return { text: (await openAsked($, running)) ? t('command.opened') : t('command.notPlaced') }
314    } catch {
315      return { text: t('command.openFailed') }
316    }
317  })
318
319  // A person closing the pane: remembered, so `auto` does not reopen it this session.
320  on('ui.close', { id: PANE }, async ($, e, next) => {
321    const closed = await next(e)
322    if (e.origin.kind === 'person') await update($, closedAtom, () => true).catch(() => undefined)
323    // The pane is gone, whoever closed it: nothing to keep fresh.
324    slot.engine?.stop()
325    return closed
326  }).catch(() => undefined)
327
328  // A tool call that wrote the plan, or ran aidlc/git/gh, re-reads. The result is never altered or delayed.
329  on('tool.call', async ($, e, next) => {
330    const result = await next(e)
331    try {
332      slot.engine?.toolCall(String(e.tool), e as unknown as Record<string, unknown>)
333    } catch {
334      // A classification failure never reaches the model.
335    }
336    return result
337  }).catch(($, e, next) => next(e))
338
339  // The turn ending: the model probably touched the plan. Does not hold the turn.
340  on('turn.complete', async ($, e, next) => {
341    try {
342      slot.engine?.request('turn')
343    } catch {
344      // Never breaks the turn.
345    }
346    return next(e)
347  })
348
349  // A surface joined. The desktop app attaches after session start, so `panel: auto` opens the pane here;
350  // then the engine wakes, checks the remote and asks for a read.
351  on('session.attach', async ($, e, next) => {
352    const attached = await next(e)
353    if (e.surface === 'desktop') {
354      try {
355        await openForDesktop($, settings)
356      } catch {
357        // /panel still opens it.
358      }
359    }
360    try {
361      await slot.engine?.attach()
362    } catch {
363      // Polls resume on the next render.
364    }
365    return attached
366  })
367
368  // A pane the person closed leaves a slim bar above the prompt with a button to bring it back, so reopening
369  // needs no /panel. Gone again once the pane is open (openAsked clears the flag, which redraws the bar).
370  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
371    if (settings.panel === 'off' || e.props.hasSurvey) return next(e)
372    const [model, isClosed] = await Promise.all([read($, modelAtom), read($, closedAtom)])
373    if (model === null || !isClosed) return next(e)
374
375    const { Box, Button, Text } = $.ui.resolve(e)
376    return steadyPresses(
377      <Box>
378        <Text dimColor>{t('reopen.hint')} </Text>
379        <Button
380          key="reopen"
381          label={t('reopen.button')}
382          onPress={async () => {
383            await openAsked($, await engineOf($, settings, slot)).catch(() => undefined)
384          }}
385        />
386      </Box>,
387      slot.presses.bar,
388    )
389  })
390
391  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
392    // The manifest is read once, the first time the pane draws; a failed read is asked again on the next draw.
393    slot.version ??= $.fs
394      .read(manifestPath($.plugin.root))
395      .then(versionOfManifest, () => {
396        slot.version = undefined
397        return ''
398      })
399    const [model, expanded, version] = await Promise.all([read($, modelAtom), read($, expandedAtom), slot.version])
400    // No clock read here: a render that reads the clock is invalidated by it, and redraws for nothing. The stamp's
401    // "now" is the engine's latest clock reading, which its polls move; it redraws the pane when the text would change.
402    const now = slot.engine?.now() || model?.readAt || 0
403    // A pane being drawn is a pane on screen: let a stopped engine notice (no state is written here).
404    slot.engine?.noteRendered(now)
405    void slot.engine?.wake().catch(() => undefined)
406
407    const tree = renderPane($.ui.resolve(e), e.surface, e.props.bodyColumns, model, expanded, handlersOf($, settings, slot),
408    // M2 hook point data: the clock the header's "checked {ago}" reads.
409    { now, checkedAt: slot.engine?.checkedAt() ?? 0 },
410    version)
411    // Every button keeps the handle its key was first drawn with: a redraw no longer retires the handles of the
412    // drawing on screen, so a press that lands across one (a pane hidden and shown, a poll's redraw) still runs.
413    return steadyPresses(tree, slot.presses.pane)
414  })
415
416  // A press on the pane is taken here, from its key and the state now, not left to the drawing's closure, so it acts
417  // on the state now whichever drawing it came from. (A press the host no longer holds a handle for never reaches this
418  // hook; the steady handles above keep that from happening.) A key the pane does not draw now goes on to the closure.
419  on('ui.press', async ($, e, next) => {
420    if (e.plugin !== $.plugin.name || e.component !== 'Pane' || e.requestId !== PANE) return next(e)
421    const [model, expanded] = await Promise.all([read($, modelAtom), read($, expandedAtom)])
422    const action = pressAction(model, expanded, e.element)
423    if (action === null) return next(e)
424    const handlers = handlersOf($, settings, slot)
425    try {
426      if (action.kind === 'refresh') await handlers.onRefresh()
427      else if (action.kind === 'toggle') await handlers.onToggle(action.key, action.isOpen)
428      else if (action.kind === 'fill') await handlers.onFillNext(action.command)
429      else await handlers.onAction(action.id)
430    } catch {
431      // A failed press changes nothing on screen, as a closure's would.
432    }
433    return { element: e.element }
434  })
435}
436
src/model.ts 31 lines
1// The model for this session: detect a plan, let its provider load it.
2import { detectPlan } from './detect'
3import type { PanelModel, Provider, ProviderContext } from '../types'
4
5/** null when no provider finds a plan. A provider's `load` may throw; the caller decides what that means. */
6export async function buildModel(ctx: ProviderContext, providers?: readonly Provider[]): Promise<PanelModel | null> {
7  const found = await detectPlan(ctx, providers)
8  return found ? found.provider.load(ctx, found.detection) : null
9}
10
11/** Runs a provider action the person pressed, against a fresh detection. */
12export async function runAction(
13  ctx: ProviderContext,
14  actionId: string,
15  providers?: readonly Provider[],
16): Promise<PanelModel | null> {
17  const found = await detectPlan(ctx, providers)
18  if (!found?.provider.act) return null
19  return found.provider.act(ctx, found.detection, actionId)
20}
21
22/**
23 * The detected provider's remote fingerprint (src/refresh.ts compares it between polls), or null when no
24 * plan is detected or the provider has none. A provider's `fingerprint` may throw; the caller decides what that means.
25 */
26export async function fingerprintOf(ctx: ProviderContext, providers?: readonly Provider[]): Promise<string | null> {
27  const found = await detectPlan(ctx, providers)
28  if (!found?.provider.fingerprint) return null
29  return found.provider.fingerprint(ctx, found.detection)
30}
31
src/refresh.ts 815 lines
1// The refresh engine: keeps the published PanelModel true to the plan and the repo.
2//
3// Provider-neutral and `$`-free: everything outside (clock, timers, the provider's
4// load and fingerprint, stats, commands, the state write, "is the pane on screen")
5// is a port that hooks/register.tsx adapts from `$`. So it is unit-testable with
6// fake ports and a fake clock.
7//
8// What it does
9//  - Triggers: session start, tool calls that touched the plan, the turn ending, a surface
10//    attaching, an mtime poll of the model's `watch` paths plus the git HEAD, a poll of the
11//    provider's remote `fingerprint`, and the Refresh button.
12//  - Coalesces: a read already scheduled absorbs later requests (it is never pushed out, so a burst
13//    cannot starve it); a read already running queues exactly one follow-up.
14//  - Publishes only a change: the model is hashed without `readAt` and `freshness`; an identical
15//    re-read writes nothing and redraws nothing. `checkedAt()` still moves, for the header stamp.
16//  - Never breaks the pane: a failed read or remote check keeps the last model and publishes it
17//    with `freshness.error`; the next success clears it.
18//  - Runs only while the pane is on screen: stop() cancels every timer, start() resumes with a
19//    catch-up read.
20import { agoText } from './freshness'
21import { t } from './strings/en'
22import type { PanelModel } from '../types'
23
24export type Timer = { cancel(): void }
25
26export type RefreshPorts = {
27  now(): Promise<number>
28  after(ms: number, fn: () => void): Timer
29  every(ms: number, fn: () => void): Timer
30  /** detect + provider.load; null = no plan; throws on failure. */
31  load(): Promise<PanelModel | null>
32  /** The detected provider's remote fingerprint; null = it has none; throws on failure. */
33  fingerprint(): Promise<string | null>
34  /** Last modification of a file or directory, null when missing. Never rejects. */
35  mtime(path: string): Promise<number | null>
36  run(
37    argv: readonly string[],
38    init?: { cwd?: string; timeoutMs?: number },
39  ): Promise<{ exitCode: number; stdout: string }>
40  /** Writes the model to state (null = no plan): readers redraw. */
41  publish(model: PanelModel | null): Promise<void>
42  /** A redraw without a model change (the manual refresh's "checked …"). */
43  invalidate(): Promise<void>
44  /** `panel` is not off and the surface lists the pane as open and placed. A person's close removes it from that list. */
45  isVisible(): Promise<boolean>
46}
47
48export type RefreshConfig = {
49  /** The session root: where `git` runs, and what relative tool paths resolve against. */
50  startDir: string
51  /** `panel: off` is false here: nothing ever runs. */
52  isEnabled: boolean
53  /** 0 disables the poll. */
54  fsPollSeconds: number
55  /** 0 disables the poll. */
56  prPollSeconds: number
57  debounceMs?: number
58}
59
60export type ReadOutcome = {
61  /** false when the read failed (the last model stays, with an error line). */
62  ok: boolean
63  /** The model after the read: the new one, or the last good one when it failed. */
64  model: PanelModel | null
65}
66
67export type RefreshEngine = {
68  /** The watched mtimes and git HEAD now: take it BEFORE a read and hand it to `seed`, so a write during the read is not swallowed. */
69  snapshot(): Promise<Snapshot>
70  /**
71   * Adopts a model read elsewhere (session start, a provider action): hash and baselines, and any read in
72   * flight drops its result. Returns it with `freshness`, to publish.
73   */
74  seed(model: PanelModel | null, before?: Snapshot): Promise<PanelModel | null>
75  /** The pane drew at `now`: the engine remembers the "checked ..." text on screen. */
76  noteRendered(now: number): void
77  /** A trigger: debounced. Ignored (beyond re-evaluating visibility) while stopped. */
78  request(reason: string): void
79  /** An immediate, single-flight read: /panel, the Refresh button. `manual` also redraws. */
80  readNow(options?: { manual?: boolean }): Promise<ReadOutcome>
81  /** A tool call finished: re-reads when it touched the plan or ran aidlc/git/gh/glab. */
82  toolCall(tool: string, input: Record<string, unknown>): void
83  /** A surface attached: wake, check the remote, request a read. */
84  attach(): Promise<void>
85  /** Re-evaluates visibility; resumes when the pane is on screen. Cheap when running. */
86  wake(): Promise<void>
87  start(): Promise<void>
88  /** Cancels every timer and pending debounce. */
89  stop(): void
90  isRunning(): boolean
91  /** Epoch ms of the latest successful check, changed or not; 0 before any. */
92  checkedAt(): number
93  /**
94   * Epoch ms of the latest time the engine read the clock (every poll tick, check and read); 0 before any. The
95   * pane's "now" for its stamp: a render that read the clock itself would be redrawn by it, endlessly.
96   */
97  now(): number
98}
99
100export const DEBOUNCE_MS = 500
101/**
102 * A remote check that takes longer than this (a hung gh) counts as failed. Nothing waits on it (attach does
103 * `void` it), so it is generous: the ledger's fingerprint is two 12 s commands in a row at worst.
104 */
105export const REMOTE_TIMEOUT_MS = 30_000
106const GIT_TIMEOUT_MS = 5000
107
108// ── hashing ──────────────────────────────────────────────────────────────────
109
110/** JSON with sorted keys and no `undefined`: equal values, equal text. */
111export function stableStringify(value: unknown): string {
112  if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'
113  if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
114  const record = value as Record<string, unknown>
115  const parts: string[] = []
116  for (const key of Object.keys(record).sort()) {
117    if (record[key] !== undefined) parts.push(`${JSON.stringify(key)}:${stableStringify(record[key])}`)
118  }
119  return `{${parts.join(',')}}`
120}
121
122/** cyrb53: a 53-bit string hash, as base-36 text. */
123export function hashText(text: string, seed = 0): string {
124  let h1 = 0xdeadbeef ^ seed
125  let h2 = 0x41c6ce57 ^ seed
126  for (let i = 0; i < text.length; i++) {
127    const code = text.charCodeAt(i)
128    h1 = Math.imul(h1 ^ code, 2654435761)
129    h2 = Math.imul(h2 ^ code, 1597334677)
130  }
131  h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
132  h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
133  return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36)
134}
135
136/** The model's identity for "did anything change": everything but `readAt` and `freshness`. */
137export function modelHash(model: PanelModel): string {
138  const { readAt: _readAt, freshness: _freshness, ...rest } = model
139  return hashText(stableStringify(rest))
140}
141
142// ── tool-call classification ─────────────────────────────────────────────────
143
144/** An absolute, normalised POSIX path: relative paths resolve against `base`, `.` and `..` fold. */
145export function normalizePath(path: string, base: string): string {
146  const full = path.startsWith('/') ? path : `${base}/${path}`
147  const out: string[] = []
148  for (const part of full.split('/')) {
149    if (part === '' || part === '.') continue
150    if (part === '..') out.pop()
151    else out.push(part)
152  }
153  return `/${out.join('/')}`
154}
155
156const FILE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])
157const COMMANDS = ['aidlc', 'git', 'gh', 'glab']
158const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash'])
159const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/
160const SHELL_C = /^-[a-zA-Z]*c[a-zA-Z]*$/
161
162/** A command that runs another: the flags that take a value, and how many plain words it takes first. */
163type Wrapper = { withValue: readonly string[]; positional?: number }
164const NO_FLAGS: Wrapper = { withValue: [] }
165const WRAPPERS: Record<string, Wrapper> = {
166  env: { withValue: ['-u', '-C', '-S', '--unset', '--chdir'] },
167  sudo: { withValue: ['-u', '-g', '-h', '-p', '-C', '-D', '-R', '-T', '-U', '--user', '--group'] },
168  nice: { withValue: ['-n', '--adjustment'] },
169  timeout: { withValue: ['-k', '-s', '--kill-after', '--signal'], positional: 1 },
170  xargs: { withValue: ['-n', '-I', '-L', '-P', '-s', '-d', '-E', '-a', '-J', '--max-args', '--replace', '--delimiter'] },
171  stdbuf: NO_FLAGS,
172  nohup: NO_FLAGS,
173  command: NO_FLAGS,
174  builtin: NO_FLAGS,
175  exec: NO_FLAGS,
176  time: NO_FLAGS,
177  npx: { withValue: ['-p', '--package'] },
178  bunx: { withValue: ['-p', '--package'] },
179  // Shell keywords that stand before a command.
180  if: NO_FLAGS,
181  then: NO_FLAGS,
182  else: NO_FLAGS,
183  elif: NO_FLAGS,
184  do: NO_FLAGS,
185  while: NO_FLAGS,
186  until: NO_FLAGS,
187  '!': NO_FLAGS,
188}
189// Package managers: `npm exec x`, `pnpm dlx x`, `npm run x`, `yarn x`, `bun x`: the word after is what runs.
190const RUNNERS = new Set(['npm', 'pnpm', 'yarn', 'bun'])
191const RUNNER_VERBS = new Set(['exec', 'dlx', 'run', 'run-script', 'x'])
192
193/** Past flags (and their values) and a bare `--`. */
194function skipFlags(words: string[], from: number, withValue: readonly string[]): number {
195  let i = from
196  while (i < words.length) {
197    const word = words[i] ?? ''
198    if (word === '--') return i + 1
199    if (!word.startsWith('-') || word === '-') return i
200    i += withValue.includes(word) ? 2 : 1
201  }
202  return i
203}
204
205/** The command word of a simple command: past env assignments, wrappers and package runners. */
206function commandWordOf(words: string[]): { word: string; rest: string[] } | null {
207  let i = 0
208  while (i < words.length) {
209    const word = words[i] ?? ''
210    if (ASSIGNMENT.test(word)) {
211      i++
212      continue
213    }
214    const base = word.split('/').pop() ?? word
215    const wrapper = Object.hasOwn(WRAPPERS, base) ? WRAPPERS[base] : undefined
216    if (wrapper !== undefined) {
217      i = skipFlags(words, i + 1, wrapper.withValue) + (wrapper.positional ?? 0)
218      continue
219    }
220    if (RUNNERS.has(base)) {
221      i = skipFlags(words, i + 1, [])
222      if (RUNNER_VERBS.has(words[i] ?? '')) i = skipFlags(words, i + 1, [])
223      continue
224    }
225    return { word: base, rest: words.slice(i + 1) }
226  }
227  return null
228}
229
230/** The index of the `)` closing the `(` at `open`, or the end of the text. */
231function closingParen(text: string, open: number): number {
232  let depth = 0
233  for (let i = open; i < text.length; i++) {
234    if (text[i] === '(') depth++
235    else if (text[i] === ')' && --depth === 0) return i
236  }
237  return text.length
238}
239
240/**
241 * Every command word a shell line runs: the first word of each simple command, after
242 * `&&`, `||`, `;`, `|`, `&`, `(`, `$(`, backticks and newlines, past env assignments and wrappers
243 * (`FOO=1 env git`, `sudo -u bob git`, `timeout 30 git`, `xargs -n1 git`, `npx aidlc`, `pnpm exec gh`,
244 * `npm run git`), inside `bash -c '...'` / `bash -lc ...`, and inside `$(...)` even in double quotes.
245 * Quotes and comments are respected, so `echo "a && git b"` and `curl github.com` run neither.
246 */
247export function commandWordsOf(command: string, depth = 0): string[] {
248  const found: string[] = []
249  let words: string[] = []
250  let word = ''
251  let hasWord = false
252  let quote: '"' | "'" | null = null
253
254  const endWord = () => {
255    if (hasWord) words.push(word)
256    word = ''
257    hasWord = false
258  }
259  const endCommand = () => {
260    endWord()
261    const head = commandWordOf(words)
262    words = []
263    if (head === null) return
264    found.push(head.word)
265    if (SHELLS.has(head.word) && depth < 4) {
266      const at = head.rest.findIndex(flag => SHELL_C.test(flag))
267      const script = at >= 0 ? head.rest[at + 1] : undefined
268      if (script !== undefined) found.push(...commandWordsOf(script, depth + 1))
269    }
270  }
271
272  for (let i = 0; i < command.length; i++) {
273    const c = command[i] ?? ''
274    if (quote === "'") {
275      if (c === "'") quote = null
276      else word += c
277    } else if (quote === '"') {
278      if (c === '\\' && i + 1 < command.length) word += command[++i] ?? ''
279      else if (c === '"') quote = null
280      else if (c === '$' && command[i + 1] === '(' && depth < 4) {
281        const close = closingParen(command, i + 1)
282        found.push(...commandWordsOf(command.slice(i + 2, close), depth + 1))
283        i = close
284      } else if (c === '`' && depth < 4) {
285        const close = command.indexOf('`', i + 1)
286        const end = close < 0 ? command.length : close
287        found.push(...commandWordsOf(command.slice(i + 1, end), depth + 1))
288        i = end
289      } else word += c
290    } else if (c === '\\') {
291      if (i + 1 < command.length) {
292        word += command[++i] ?? ''
293        hasWord = true
294      }
295    } else if (c === "'" || c === '"') {
296      quote = c
297      hasWord = true
298    } else if (c === '#' && !hasWord) {
299      while (i + 1 < command.length && command[i + 1] !== '\n') i++
300    } else if (c === '$' && command[i + 1] === '(') {
301      endCommand()
302      i++
303    } else if (c === ' ' || c === '\t') {
304      endWord()
305    } else if (c === ';' || c === '|' || c === '&' || c === '(' || c === ')' || c === '`' || c === '\n') {
306      endCommand()
307    } else {
308      word += c
309      hasWord = true
310    }
311  }
312  endCommand()
313  return found
314}
315
316/** True when a shell line runs `aidlc`, `git`, `gh` or `glab` as a command. */
317export function runsPlanCommand(command: string): boolean {
318  return commandWordsOf(command).some(word => COMMANDS.includes(word))
319}
320
321/**
322 * Whether a finished tool call is worth a re-read: a file tool that wrote a watched path
323 * (or anything under a watched directory), or a shell line that ran aidlc, git, gh or glab.
324 * `input` is the tool's arguments (`file_path`, `notebook_path`, `command`).
325 */
326export function isRelevantToolCall(
327  tool: string,
328  input: Record<string, unknown>,
329  watch: readonly string[],
330  startDir: string,
331): boolean {
332  if (tool === 'Bash') return typeof input['command'] === 'string' && runsPlanCommand(input['command'])
333  if (!FILE_TOOLS.has(tool)) return false
334  const raw = tool === 'NotebookEdit' ? input['notebook_path'] : input['file_path']
335  if (typeof raw !== 'string' || raw === '') return false
336  const path = normalizePath(raw, startDir)
337  return watch.some(entry => {
338    if (entry === '') return false
339    const target = normalizePath(entry, startDir)
340    return path === target || path.startsWith(target === '/' ? '/' : `${target}/`)
341  })
342}
343
344// ── the engine ───────────────────────────────────────────────────────────────
345
346/** mtimes of the watched paths and the git HEAD signature, as of one moment. */
347export type Snapshot = { mtimes: Map<string, number | null>; head: string }
348
349export function createRefreshEngine(ports: RefreshPorts, config: RefreshConfig): RefreshEngine {
350  const debounceMs = config.debounceMs ?? DEBOUNCE_MS
351  const fsMs = config.fsPollSeconds > 0 ? config.fsPollSeconds * 1000 : 0
352  const prMs = config.prPollSeconds > 0 ? config.prPollSeconds * 1000 : 0
353  const noop = () => undefined
354
355  // What is published, and what it was read from.
356  let last: PanelModel | null = null
357  let lastHash: string | null = null
358  let publishedError: string | undefined
359  let lastCheckedAt = 0
360  /** The latest clock reading, for the pane's stamp (see `now()`). */
361  let lastNowAt = 0
362  let isPlanFailing = false
363  let isRemoteFailing = false
364  /** The failed remote check's own line (a forge error carries one); '' = the generic one. */
365  let remoteErrorText = ''
366  /** The last non-empty watch list: a plan that went away is polled for its return. */
367  let knownWatch: string[] = []
368  /** The "checked ..." text on screen, so a tick redraws only when it would change. */
369  let drawnText = ''
370
371  // Baselines taken around every successful read.
372  let watchBase = new Map<string, number | null>()
373  let headBase = ''
374  let fingerprintBase: string | undefined
375  /** A fingerprint seen to differ: adopted as the baseline only once a read that started after it succeeds. */
376  let pendingFingerprint: { value: string; afterSeq: number } | null = null
377  /** false once the provider answered "no fingerprint": no remote timer until a read re-detects one. */
378  let hasFingerprint = true
379
380  // Lifecycle. `generation` moves on seed, stop and adopt: work that started before drops its results.
381  let generation = 0
382  let startedReads = 0
383  let isRunning = false
384  let isStarting = false
385  let isStale = true
386  let isTicking = false
387  let isCheckingRemote = false
388  let remoteToken = 0
389  let fsTimer: Timer | null = null
390  let remoteTimer: Timer | null = null
391  let remoteKick: Timer | null = null
392  let debounceTimer: Timer | null = null
393
394  // Single flight.
395  let current: Promise<void> | null = null
396  let isQueued = false
397  let queuedGeneration = 0
398  let outcome: ReadOutcome = { ok: true, model: null }
399
400  const safe = async <T>(run: () => Promise<T>, fallback: T): Promise<T> => {
401    try {
402      return await run()
403    } catch {
404      return fallback
405    }
406  }
407
408  const watchList = (): string[] => (last !== null && last.watch.length > 0 ? last.watch : knownWatch)
409
410  function currentError(): string | undefined {
411    const text = isPlanFailing ? t('refresh.failed') : isRemoteFailing ? remoteErrorText || t('refresh.remoteFailed') : ''
412    return text === '' ? undefined : text
413  }
414
415  const withFreshness = (model: PanelModel, checkedAt: number, error: string | undefined): PanelModel => ({
416    ...model,
417    freshness: error === undefined ? { checkedAt } : { checkedAt, error },
418  })
419
420  // ── baselines ──
421
422  async function statAll(paths: readonly string[]): Promise<Map<string, number | null>> {
423    const entries = await Promise.all(paths.map(async path => [path, await safe(() => ports.mtime(path), null)] as const))
424    return new Map(entries)
425  }
426
427  /** The git HEAD signature: sha and branch; '' when there is no git (a normal case, never an error). */
428  async function headSignature(): Promise<string> {
429    const ask = (argv: readonly string[]) =>
430      safe(async () => {
431        const ran = await ports.run(argv, { cwd: config.startDir, timeoutMs: GIT_TIMEOUT_MS })
432        return ran.exitCode === 0 ? ran.stdout.trim() : ''
433      }, '')
434    const [sha, branch] = await Promise.all([ask(['git', 'rev-parse', 'HEAD']), ask(['git', 'branch', '--show-current'])])
435    return sha === '' && branch === '' ? '' : `${sha}|${branch}`
436  }
437
438  async function snapshot(): Promise<Snapshot> {
439    if (!config.isEnabled) return { mtimes: new Map(), head: '' }
440    const [mtimes, head] = await Promise.all([statAll(watchList()), headSignature()])
441    return { mtimes, head }
442  }
443
444  /** Baselines for `paths`: the snapshot's mtimes where it has them, a stat now for the rest. */
445  async function baseline(paths: readonly string[], before: Snapshot): Promise<void> {
446    const extra = await statAll(paths.filter(path => !before.mtimes.has(path)))
447    watchBase = new Map(paths.map(path => [path, before.mtimes.has(path) ? (before.mtimes.get(path) ?? null) : (extra.get(path) ?? null)]))
448    headBase = before.head
449  }
450
451  async function hasFsChanged(): Promise<boolean> {
452    const now = await snapshot()
453    if (now.head !== headBase) return true
454    if (now.mtimes.size !== watchBase.size) return true
455    for (const [path, mtime] of now.mtimes) if (watchBase.get(path) !== mtime) return true
456    return false
457  }
458
459  // ── publishing ──
460
461  /** The error line changed without a new model (a failed read, a recovered remote): republish the last one. */
462  async function syncError(): Promise<void> {
463    const error = currentError()
464    if (last === null || error === publishedError) return
465    const next = withFreshness(last, last.freshness?.checkedAt ?? lastCheckedAt, error)
466    try {
467      await ports.publish(next)
468      last = next
469      publishedError = error
470    } catch {
471      // Not written: the next change tries again.
472    }
473  }
474
475  /** Reads the clock (`fallback` when it fails) and remembers the reading for the pane's stamp. */
476  async function clockNow(fallback: number): Promise<number> {
477    const now = await safe(() => ports.now(), fallback)
478    lastNowAt = Math.max(lastNowAt, now)
479    return now
480  }
481
482  /**
483   * A check that found nothing to do still counts: the stamp moves, and the pane redraws only if its text would.
484   * While the plan fails to read nothing is checked, but the time still moves: the stamp ages ("checked 30s ago").
485   */
486  async function markChecked(): Promise<void> {
487    const now = await clockNow(lastCheckedAt)
488    if (!isPlanFailing) lastCheckedAt = now
489    const text = agoText(now, lastCheckedAt)
490    if (text === drawnText) return
491    drawnText = text
492    await safe(() => ports.invalidate(), undefined)
493  }
494
495  async function doRead(): Promise<void> {
496    const gen = generation
497    const seq = ++startedReads
498    // Baselines first: a write that lands during the load is then seen by the next poll, not swallowed.
499    const before = await snapshot()
500
501    let model: PanelModel | null
502    try {
503      model = await ports.load()
504    } catch {
505      if (gen !== generation) return
506      isPlanFailing = true
507      await syncError()
508      outcome = { ok: false, model: last }
509      return
510    }
511    if (gen !== generation) return
512
513    const paths = model !== null && model.watch.length > 0 ? model.watch : knownWatch
514    await baseline(paths, before)
515    if (gen !== generation) return
516
517    isPlanFailing = false
518    // A read just took fresh baselines: a resume right after it has nothing to catch up on.
519    isStale = false
520    if (model !== null && model.watch.length > 0) knownWatch = model.watch
521    const now = await clockNow(model?.readAt ?? lastCheckedAt)
522    lastCheckedAt = now
523    if (pendingFingerprint !== null && seq > pendingFingerprint.afterSeq) {
524      fingerprintBase = pendingFingerprint.value
525      pendingFingerprint = null
526    }
527    if (!hasFingerprint && isRunning) {
528      // A fresh read may have found a provider with a remote.
529      hasFingerprint = true
530      kickRemote()
531    }
532
533    const hash = model === null ? '' : modelHash(model)
534    const error = model === null ? undefined : currentError()
535    if (hash !== lastHash || error !== publishedError) {
536      const next = model === null ? null : withFreshness(model, now, error)
537      try {
538        await ports.publish(next)
539        last = next
540        lastHash = hash
541        publishedError = error
542      } catch {
543        // Not written: the next read tries again.
544      }
545    }
546    outcome = { ok: true, model: last }
547  }
548
549  // ── single flight ──
550
551  async function pump(): Promise<void> {
552    try {
553      do {
554        isQueued = false
555        await doRead()
556        // A follow-up queued before a stop or a seed belongs to a world that is gone.
557      } while (isQueued && queuedGeneration === generation)
558    } finally {
559      current = null
560    }
561  }
562
563  /** Runs a read, or queues exactly one follow-up behind the one running. Resolves with the last read's outcome. */
564  async function schedule(): Promise<ReadOutcome> {
565    if (current !== null) {
566      isQueued = true
567      queuedGeneration = generation
568    } else current = pump()
569    await current
570    return outcome
571  }
572
573  function cancelDebounce(): void {
574    debounceTimer?.cancel()
575    debounceTimer = null
576  }
577
578  // ── polls ──
579
580  async function visible(): Promise<boolean> {
581    // A failing visibility check does not stop a running engine.
582    return safe(() => ports.isVisible(), true)
583  }
584
585  async function fsTick(): Promise<void> {
586    if (!isRunning || isTicking) return
587    isTicking = true
588    const gen = generation
589    try {
590      if (!(await visible())) {
591        engine.stop()
592        return
593      }
594      if (!isRunning || gen !== generation) return
595      if (await hasFsChanged()) engine.request('fs')
596      else await markChecked()
597    } finally {
598      isTicking = false
599    }
600  }
601
602  /** A fingerprint that outlasts REMOTE_TIMEOUT_MS (a hung gh) counts as a failure. */
603  function guarded<T>(work: Promise<T>): Promise<T> {
604    return new Promise<T>((resolve, reject) => {
605      const timer = ports.after(REMOTE_TIMEOUT_MS, () => reject(new Error('remote check timed out')))
606      work.then(
607        value => {
608          timer.cancel()
609          resolve(value)
610        },
611        error => {
612          timer.cancel()
613          reject(error)
614        },
615      )
616    })
617  }
618
619  function ensureRemoteTimer(): void {
620    if (!isRunning || prMs === 0 || remoteTimer !== null) return
621    try {
622      remoteTimer = ports.every(prMs, () => void remoteTick().catch(noop))
623    } catch {
624      remoteTimer = null
625    }
626  }
627
628  /** Runs the remote check on the next turn of the clock, never inside whatever dispatch woke the engine. */
629  function kickRemote(): void {
630    remoteKick?.cancel()
631    try {
632      remoteKick = ports.after(0, () => {
633        remoteKick = null
634        void checkRemote().catch(noop)
635      })
636    } catch {
637      remoteKick = null
638    }
639  }
640
641  /** Resolves true when the check itself worked (whatever it found). */
642  async function checkRemote(): Promise<boolean> {
643    if (isCheckingRemote) return false
644    isCheckingRemote = true
645    const token = ++remoteToken
646    const gen = generation
647    try {
648      let fingerprint: string | null
649      try {
650        fingerprint = await guarded(ports.fingerprint())
651      } catch (error) {
652        if (gen !== generation) return false
653        isRemoteFailing = true
654        // A provider's error may carry the finished line (the forge layer names the cause); anything else gets the generic one.
655        const display = (error as { display?: unknown } | null)?.display
656        remoteErrorText = typeof display === 'string' ? display : ''
657        hasFingerprint = true
658        ensureRemoteTimer()
659        await syncError()
660        return false
661      }
662      if (gen !== generation) return false
663      isRemoteFailing = false
664      remoteErrorText = ''
665      if (fingerprint === null) {
666        // No remote state: nothing to poll until a read finds a provider that has some.
667        hasFingerprint = false
668        remoteTimer?.cancel()
669        remoteTimer = null
670        await syncError()
671        return true
672      }
673      hasFingerprint = true
674      ensureRemoteTimer()
675      const before = fingerprintBase
676      if (before === undefined && last !== null) fingerprintBase = fingerprint
677      else if (before !== fingerprint) {
678        // Adopted as the baseline only when a read that starts now has succeeded.
679        pendingFingerprint = { value: fingerprint, afterSeq: startedReads }
680        engine.request('remote')
681        return true
682      }
683      await syncError()
684      return true
685    } finally {
686      if (token === remoteToken) isCheckingRemote = false
687    }
688  }
689
690  async function remoteTick(): Promise<void> {
691    if (!isRunning) return
692    if (!(await visible())) {
693      engine.stop()
694      return
695    }
696    if (isRunning && (await checkRemote())) await markChecked()
697  }
698
699  // ── the engine ──
700
701  const engine: RefreshEngine = {
702    snapshot,
703
704    async seed(model, before) {
705      if (!config.isEnabled) return model
706      generation++
707      const now = await clockNow(model?.readAt ?? 0)
708      lastCheckedAt = now
709      last = model === null ? null : withFreshness(model, now, undefined)
710      lastHash = model === null ? '' : modelHash(model)
711      publishedError = undefined
712      if (model !== null && model.watch.length > 0) knownWatch = model.watch
713      await baseline(model !== null && model.watch.length > 0 ? model.watch : knownWatch, before ?? (await snapshot()))
714      isStale = false
715      return last
716    },
717
718    request(_reason) {
719      if (!config.isEnabled) return
720      if (!isRunning) {
721        void engine.wake().catch(noop)
722        return
723      }
724      // A read is already due and will see everything written so far; pushing it out would starve it under a burst.
725      if (debounceTimer !== null) return
726      debounceTimer = ports.after(debounceMs, () => {
727        debounceTimer = null
728        if (isRunning) void schedule().catch(noop)
729      })
730    },
731
732    async readNow(options) {
733      if (!config.isEnabled) return { ok: true, model: last }
734      cancelDebounce()
735      const result = await schedule()
736      if (options?.manual === true) await safe(() => ports.invalidate(), undefined)
737      return result
738    },
739
740    toolCall(tool, input) {
741      if (!config.isEnabled) return
742      if (isRelevantToolCall(tool, input, watchList(), config.startDir)) engine.request('tool')
743    },
744
745    noteRendered(now) {
746      drawnText = agoText(now, lastCheckedAt)
747    },
748
749    async attach() {
750      if (!config.isEnabled) return
751      await engine.wake()
752      if (!isRunning) return
753      // A hung gh must not hold the attach.
754      void checkRemote().catch(noop)
755      engine.request('attach')
756    },
757
758    async wake() {
759      if (!config.isEnabled || isRunning) return
760      await engine.start()
761    },
762
763    async start() {
764      if (!config.isEnabled || isRunning || isStarting) return
765      isStarting = true
766      const gen = generation
767      let isShown = false
768      try {
769        isShown = await safe(() => ports.isVisible(), false)
770      } finally {
771        isStarting = false
772      }
773      // A stop (or a seed) that came while the pane was being looked at wins.
774      if (gen !== generation || isRunning) return
775      if (!isShown) {
776        isStale = true
777        return
778      }
779      try {
780        if (fsMs > 0) fsTimer = ports.every(fsMs, () => void fsTick().catch(noop))
781      } catch {
782        fsTimer = null
783        return
784      }
785      isRunning = true
786      if (isStale) {
787        isStale = false
788        engine.request('resume')
789      }
790      if (prMs > 0 && hasFingerprint) kickRemote()
791    },
792
793    stop() {
794      isRunning = false
795      isStale = true
796      isQueued = false
797      generation++
798      remoteToken++
799      isCheckingRemote = false
800      fsTimer?.cancel()
801      remoteTimer?.cancel()
802      remoteKick?.cancel()
803      fsTimer = null
804      remoteTimer = null
805      remoteKick = null
806      cancelDebounce()
807    },
808
809    isRunning: () => isRunning,
810    checkedAt: () => lastCheckedAt,
811    now: () => lastNowAt,
812  }
813  return engine
814}
815
src/render.tsx 113 lines
1// The panel's tree: any PanelModel, drawn the same way. Deterministic and
2// I/O-free: model + folds + clock in, elements out. Box, Text, Button and Link
3// are in every surface's table; Svg (rings, the status strip) is in all but the
4// terminal's, which draws glyphs and block cells instead.
5//
6// Top to bottom: header (where am I), the Now card with Next (what am I on,
7// what is next), the actions, Needs attention (what blocks), Plan (overall
8// progress and sections). From 80 columns, with sections, the Now card, actions
9// and attention sit in a left column and the plan in a right one.
10//
11// On the Svg surfaces a plan of a handful of phases (2 to 7) gets two more
12// views: in one column, the phase stepper under the header; in two, phase cards
13// over the open phases' items in place of the section headings.
14//
15// Copy comes from `t()` or from the model (display text a provider resolved).
16// A string that is '' hides its element; nothing is substituted. Glyphs are
17// not copy. The pieces live in ./render/.
18import type { RenderSurface } from 'claude-code'
19import type { Clock } from './freshness'
20import { t } from './strings/en'
21import type { PanelModel } from '../types'
22import { attention, rowsOf } from './render/attention'
23import { header } from './render/header'
24import { breakpoint } from './render/kit'
25import type { Ctx, El, Handlers, Kit } from './render/kit'
26import { actionsRow, nowCard } from './render/now'
27import { orphanGates, plan } from './render/plan'
28import { isPhased, stepper } from './render/stepper'
29
30export type { Handlers, Kit } from './render/kit'
31
32const LEFT_SHARE = 0.4
33const COLUMN_GAP = 2
34
35/**
36 * `surface` decides the ring, not the table's keys: the terminal's table answers
37 * an `Svg` constructor at run time though its type has none, and draws nothing from it.
38 * `clock` (the engine's `now`, its last check) turns the stamp into "checked 12s ago";
39 * without it the stamp is the model's "read 12:03". `version`, the plugin's own, is the dim
40 * mark at the foot ('' draws none).
41 */
42export function renderPane(
43  table: Kit,
44  surface: RenderSurface,
45  columns: number,
46  model: PanelModel | null,
47  expanded: Record<string, boolean>,
48  handlers: Handlers,
49  clock?: Clock,
50  version = '',
51): El {
52  const kit: Kit = surface === 'terminal' ? { ...table, Svg: undefined } : table
53  const width = Number.isFinite(columns) ? columns : 60
54  const ctx: Ctx = { kit, surface, bp: breakpoint(width), columns: width, handlers }
55  const { Box, Text } = kit
56  // The build drawing the pane, dim at its foot, so a look can be told from an older one ('' hides it).
57  const mark = t('pane.version', { version })
58  const footer = mark !== '' && (
59    <Box justifyContent="flex-end">
60      <Text dimColor wrap="truncate-end">
61        {mark}
62      </Text>
63    </Box>
64  )
65
66  if (model === null) {
67    const empty = t('pane.empty')
68    return (
69      <Box flexDirection="column" borderStyle="round" borderColor="subtle" paddingX={1}>
70        {header(ctx, null, clock)}
71        {empty !== '' && (
72          <Text dimColor wrap="wrap">
73            {empty}
74          </Text>
75        )}
76        {footer}
77      </Box>
78    )
79  }
80
81  const hasPlan = model.sections.length > 0 || orphanGates(model).length > 0
82  const isTwoColumn = ctx.bp === 'L' && hasPlan
83  // The left column is 40% of the pane, less the gap: it lays out for its own width, not the pane's.
84  const leftWidth = Math.floor(width * LEFT_SHARE) - COLUMN_GAP
85  const leftCtx: Ctx = isTwoColumn ? { ...ctx, bp: breakpoint(leftWidth), columns: leftWidth } : ctx
86  const left = [nowCard(leftCtx, model), actionsRow(leftCtx, model), rowsOf(model).length > 0 && attention(leftCtx, model)]
87  const isPhaseView = kit.Svg !== undefined && isPhased(model)
88  const right = hasPlan && plan(ctx, model, expanded, isTwoColumn && isPhaseView)
89
90  return (
91    <Box flexDirection="column" gap={1}>
92      {header(ctx, model, clock)}
93      {isTwoColumn ? (
94        <Box gap={COLUMN_GAP}>
95          <Box flexDirection="column" gap={1} width="40%">
96            {left}
97          </Box>
98          <Box flexDirection="column" flexGrow={1} flexShrink={1} minWidth={0}>
99            {right}
100          </Box>
101        </Box>
102      ) : (
103        <Box flexDirection="column" gap={1}>
104          {isPhaseView && stepper(ctx, model)}
105          {left}
106          {right}
107        </Box>
108      )}
109      {footer}
110    </Box>
111  )
112}
113
src/render/press.ts 71 lines
1// What a press on one of the pane's buttons does, from its key and the state now: the same as the button's own
2// `onPress` closure, worked out without the drawing. A `ui.press` hook (hooks/register.tsx) runs it and takes the
3// press, so a press still lands when the surface shows a drawing whose closures it already let go (a pane hidden and
4// shown again repaints its last drawing, and the first press on it found no closure to run).
5import type { PanelModel } from '../../types'
6import { rowsOf } from './attention'
7import { uniqueIds } from './kit'
8import { PLAN_KEY } from './plan'
9
10export type PressAction =
11  | { kind: 'refresh' }
12  /** Fold state: `key` should be `isOpen` after the press. */
13  | { kind: 'toggle'; key: string; isOpen: boolean }
14  /** Put a command in the prompt. */
15  | { kind: 'fill'; command: string }
16  /** A provider action. */
17  | { kind: 'action'; id: string }
18
19/** The action a press on `element` (a Button's key) means; null for a key the pane does not draw now. */
20export function pressAction(model: PanelModel | null, expanded: Record<string, boolean>, element: string): PressAction | null {
21  if (element === 'refresh') return { kind: 'refresh' }
22  if (model === null) return null
23
24  if (element === 'next:fill') {
25    const command = model.next?.command ?? ''
26    return command === '' ? null : { kind: 'fill', command }
27  }
28  const after = (prefix: string): string | null => (element.startsWith(prefix) ? element.slice(prefix.length) : null)
29
30  const row = after('attention:fill:')
31  if (row !== null) {
32    const rows = rowsOf(model)
33    const command = rows[uniqueIds(rows.map(one => one.id)).indexOf(row)]?.command ?? ''
34    return command === '' ? null : { kind: 'fill', command }
35  }
36
37  const action = after('action:')
38  if (action !== null) {
39    const actions = (model.actions ?? []).filter(one => one.label !== '')
40    const found = actions[uniqueIds(actions.map(one => one.id)).indexOf(action)]
41    return found ? { kind: 'action', id: found.id } : null
42  }
43
44  if (element === 'plan:fold') {
45    const isFoldable = model.isPlanCollapsed !== undefined
46    const isOpen = !isFoldable || (expanded[PLAN_KEY] ?? !model.isPlanCollapsed)
47    return { kind: 'toggle', key: PLAN_KEY, isOpen: !isOpen }
48  }
49
50  const section = after('section:')
51  if (section !== null) {
52    const ids = uniqueIds(model.sections.map(one => one.id))
53    const found = model.sections[ids.indexOf(section)]
54    if (!found) return null
55    const isOpen = expanded[section] ?? !found.isCollapsed
56    return { kind: 'toggle', key: section, isOpen: !isOpen }
57  }
58
59  const folds: [string, string, boolean][] = [
60    ['more:', '#all', true],
61    ['less:', '#all', false],
62    ['restless:', '#rest', false],
63    ['rest:', '#rest', true],
64  ]
65  for (const [prefix, suffix, isOpen] of folds) {
66    const id = after(prefix)
67    if (id !== null) return { kind: 'toggle', key: `${id}${suffix}`, isOpen }
68  }
69  return null
70}
71
src/render/steady.ts 41 lines
1// One press handle per button key, for as long as the pane lives. `<Button>` mints a fresh handle on every call, and the
2// host retires a drawing's old handles when the next drawing arrives; a surface still showing the older drawing (a
3// redraw it has not taken yet, a pane hidden and shown again) then sends a handle the host no longer holds, and the
4// press is lost ("ui_press not handled" in the desktop log; the second press, on the new drawing, works). The host
5// keeps a button's handle across drawings when the plugin draws it under the same handle again, so each key keeps the
6// first handle it was drawn with. The closure under it is the latest drawing's, as before.
7
8type Press = { plugin: string; handle: number }
9type Node = { props?: { key?: unknown }; press?: Press; children?: unknown }
10
11const isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null
12
13const pressOf = (node: Node): Press | null => {
14  const { press } = node
15  return isObject(press) && press.plugin === '' && typeof press.handle === 'number' ? press : null
16}
17
18/**
19 * `tree` with every pressable element this plugin drew under the handle its key had before (`held`, which it fills
20 * with the keys drawn for the first time). A key drawn twice in one tree keeps its fresh handle the second time, so
21 * no two elements share one.
22 */
23export function steadyPresses<T>(tree: T, held: Map<string, number>): T {
24  const drawn = new Set<string>()
25  const walk = (value: unknown): unknown => {
26    if (Array.isArray(value)) return value.map(walk)
27    if (!isObject(value)) return value
28    const node = value as Node
29    const children = node.children === undefined ? undefined : walk(node.children)
30    const withChildren = children === undefined ? node : { ...node, children }
31    const press = pressOf(node)
32    const key = node.props?.key
33    if (press === null || typeof key !== 'string' || drawn.has(key)) return withChildren
34    drawn.add(key)
35    const handle = held.get(key) ?? press.handle
36    held.set(key, handle)
37    return handle === press.handle ? withChildren : { ...withChildren, press: { ...press, handle } }
38  }
39  return walk(tree) as T
40}
41
src/version.ts 19 lines
1// The plugin's own version, for the dim mark at the foot of the pane: read from the manifest the engine loaded the
2// mod from, so the pane says which build is drawing it. Pure: the caller hands in the read.
3
4/** The `version` of a plugin.json's text; '' when it is missing, not a string, or the text is no JSON object. */
5export function versionOfManifest(text: string | null): string {
6  if (text === null) return ''
7  try {
8    const manifest: unknown = JSON.parse(text)
9    if (typeof manifest !== 'object' || manifest === null) return ''
10    const version = (manifest as { version?: unknown }).version
11    return typeof version === 'string' ? version.trim() : ''
12  } catch {
13    return ''
14  }
15}
16
17/** Where a plugin's manifest stands under its root. */
18export const manifestPath = (root: string): string => `${root.replace(/\/+$/, '')}/.claude-plugin/plugin.json`
19
src/strings/en.ts 331 lines
1// The single source of every user-facing string the panel draws.
2//
3// A mod may import only code files (.ts/.tsx/...), so the table is a module, not
4// en.json (`import x from './en.json'` is refused by the engine). Keys are
5// stable; a missing key resolves to '' and the renderer hides the element
6// rather than substituting text (see `t` below). Placeholders are `{name}`.
7//
8// Generic chrome (pane, command, header, ring, section, item) is drawn by the
9// renderer and the entry point. Keys under `forge.` are the forge layer's causes
10// (src/forge/problem.ts). Keys under `aidlc.` and `ledger.` belong to the
11// AI-DLC and ledger providers, which resolve them through `t()` while building their
12// PanelModel; the model then carries display text, and '' means "hide".
13
14export const en = {
15  // ── chrome ────────────────────────────────────────────────────────────────
16  'pane.title': 'Project',
17  'pane.empty': 'No plan found for this session yet.',
18  'pane.version': 'project-panel {version}',
19
20  'command.description': 'Open the project panel: sections, items and what blocks the next one',
21  'command.opened': 'Project panel opened.',
22  'command.notPlaced': 'Project panel is open but not shown yet: widen the window or press ctrl+x tab.',
23  'command.noPlan': 'No plan found above {root}.',
24  'command.readFailed': 'Could not read the plan; the panel keeps what it had.',
25  'command.disabled': 'The project panel is turned off (the panel option is set to off).',
26  'command.openFailed': 'Could not open the project panel.',
27
28  'reopen.hint': 'Project panel is closed.',
29  'reopen.button': 'Open panel',
30
31  'header.refresh': 'Refresh',
32  'header.checked': 'checked {ago}',
33  'ago.now': 'just now',
34  'ago.seconds': '{n}s ago',
35  'ago.minutes': '{n}m ago',
36  'ago.hours': '{n}h ago',
37  'header.readAt': 'read {time}',
38  'header.badge.sideJob': 'Side job',
39  'header.badge.idle': 'Idle',
40
41  'now.label': 'Now',
42  'now.where': '{section}, {index} of {total}',
43  'now.nextUp': 'Next up',
44  'now.sideJob.label': 'This session',
45  'now.sideJob.headline': 'Side job, not a stage of this plan',
46  'now.idle.label': 'Workspace',
47  'now.idle.headline': 'Nothing in flight',
48  'now.landing.local': 'local only, this worktree',
49
50  'next.label': 'Next',
51  'next.fill': 'Put in prompt',
52
53  'attention.title': 'Needs attention ({count})',
54  'attention.heading': 'Needs attention',
55  'attention.prs': 'Pull requests ({count})',
56  'attention.pr.ref': 'PR #{number}',
57  'attention.pr.ref.gitlab': 'MR !{number}',
58  'attention.pr.separator': ' · ',
59  'attention.pr.word.pr-not-merged': 'not merged',
60  'attention.pr.word.ci-failing': 'CI failing',
61  'attention.pr.word.changes-requested': 'changes requested',
62  'attention.pr.word.conflicts': 'conflicts',
63  'attention.pr.word.behind-main': 'behind',
64  'attention.pr.word.review-requested': 'your review requested',
65  'attention.pr.word.review-commented': 'commented',
66  'attention.pr.word.approval-stale': 'changed since approval',
67  'attention.pr.word.approved-comments': 'approved with comments',
68  'attention.pr.word.approved': 'approved',
69  'attention.pr.word.draft-not-requested': 'draft, not sent for review',
70  'attention.pr.word.review-not-requested': 'not sent for review',
71  'attention.whereAfter': '{section}, after {item}',
72  'attention.whereOn': '{section}, {item}',
73
74  'plan.title': 'Plan',
75  'plan.summary': '{percent}% done, {done} of {total}',
76  'plan.foldedHint': 'folded, show',
77
78  'ring.alt': '{percent}% done',
79  'strip.alt': '{done} of {total} done',
80  'icon.alt.done': 'done',
81  'icon.alt.stale': 'stale',
82  'icon.alt.live': 'in progress',
83  'icon.alt.local': 'local only',
84  'icon.alt.current': 'current',
85  'icon.alt.planned': 'planned',
86  'icon.alt.skipped': 'skipped',
87  'icon.alt.failed': 'failed',
88  'icon.alt.mark': 'needs a look',
89  'stepper.alt': 'Phases: {phases}',
90  'stepper.alt.done': '{title} done',
91  'stepper.alt.skipped': '{title} skipped',
92  'stepper.alt.empty': '{title} not included yet',
93  'stepper.alt.current': '{title} {percent}% done, current',
94  'stepper.alt.open': '{title} {percent}% done',
95
96  'section.count': '{done}/{total}',
97  'section.skipped': 'skipped',
98  'section.notIncluded': 'not included yet',
99  'section.proposedHeading': 'Proposed',
100  'section.doneFold': '{count} done, show',
101  'section.doneHide': 'Hide done',
102  'section.moreItems': 'Show {count} more',
103  'section.fewerItems': 'Show fewer',
104
105  'item.status.open': 'in progress',
106  'item.status.awaiting': 'awaiting',
107  'item.status.revising': 'revising',
108  'item.status.reopened': 'reopened',
109  'item.status.stale': 'stale',
110  'item.status.skipped': 'skipped',
111  'item.status.failed': 'failed',
112  'item.status.partial': 'partial',
113
114  // ── AI-DLC provider ───────────────────────────────────────────────────────
115  'aidlc.name': 'AI-DLC',
116
117  'aidlc.phase.INITIALIZATION': 'Initialization',
118  'aidlc.phase.IDEATION': 'Ideation',
119  'aidlc.phase.INCEPTION': 'Inception',
120  'aidlc.phase.CONSTRUCTION': 'Construction',
121  'aidlc.phase.OPERATION': 'Operation',
122  'aidlc.phase.perUnit': 'per unit: {units}',
123
124  'aidlc.header.unit': 'unit {unit}',
125
126  // Construction drawn as Units of work (providers/aidlc/units.ts, points.ts): the section's caption, a Unit's points
127  // chip, its status word ({stage} a per-unit stage slug, {units} the Unit IDs it waits on), the plan heading when
128  // Construction counts by points, and the rows about the points file ({file}; {units} the Unit IDs it repeats).
129  'aidlc.units.caption': '{units} of {count} units done, {done} of {total} story points',
130  'aidlc.units.count': '{done}/{total} pt',
131  'aidlc.stage.points': '{points} pt',
132  'aidlc.units.done': '{done}/{total} units',
133  'aidlc.section.units': 'Units',
134  'aidlc.unit.claimed': '{unit}, {points} pt: claimed at this checkout',
135  'aidlc.chip.points': '{points} pt',
136  'aidlc.chip.pointsDefault': '{points} pt, default',
137  'aidlc.unit.atStage': '{stage}',
138  'aidlc.unit.awaitingAt': '{stage} awaits approval',
139  'aidlc.unit.revisingAt': 'revising {stage}',
140  'aidlc.unit.paused': 'paused',
141  'aidlc.unit.pausedAt': 'paused at {stage}',
142  'aidlc.unit.stageDone': '{stage} done',
143  'aidlc.unit.waitsOn': 'waits on {units}',
144  'aidlc.overall.points': '{percent}% done by story points, {done} of {total} pt',
145  'aidlc.gate.stagePoints.title': '{file} has lines that count nothing',
146  'aidlc.gate.stagePoints.unknown': 'No stage of this plan: {stages}.',
147  'aidlc.gate.stagePoints.unreadable': 'Not read, not <stage>: <points>: line {lines}.',
148  'aidlc.gate.pointsUncommitted.title': '{file} not committed',
149  'aidlc.gate.pointsRepeated.title': '{file} lists a unit more than once',
150  'aidlc.gate.pointsRepeated.caption': '{units}: the last row counts. Remove the rows that are out of date.',
151  'aidlc.gate.pointsUncommitted.caption': 'It has story points not committed yet, possibly added from Jira. Commit it with this branch.',
152
153  'aidlc.sideJob.caption':
154    'This session is not bound to a stage of {intent}. Progress below is the intent the workspace points at.',
155
156  // A side job folds the intent's plan under its own context, so "below" is not where the progress is.
157  'aidlc.sideJob.captionFolded': 'This session is not bound to a stage of {intent}. The intent\'s progress is folded under Plan.',
158
159  // What the panel knows about the side-job session itself ({ref} as the forge spells it; `.gitlab` says merge request).
160  'aidlc.session.branch': 'on {branch}',
161  'aidlc.session.aheadBehind': '{ahead} ahead, {behind} behind {base}',
162  'aidlc.session.ahead': '{ahead} ahead of {base}',
163  'aidlc.session.behind': '{behind} behind {base}',
164  'aidlc.session.pr': 'PR {ref}, {state}',
165  'aidlc.session.pr.gitlab': 'MR {ref}, {state}',
166  'aidlc.session.pr.open': 'open',
167
168  'aidlc.idle.noneInFlight': 'This workspace has no intent in flight. Start one with /aidlc.',
169  'aidlc.idle.noCursor': 'This workspace has more than one live intent and none is selected. Pick one with /aidlc.',
170  'aidlc.idle.archived': 'This session was bound to an intent that has since been archived, so it shows no workflow.',
171
172  'aidlc.gate.parked.title': 'Parked at {stage}',
173  'aidlc.gate.parked.titleNoStage': 'Parked',
174  'aidlc.gate.parked.caption': 'The workflow was parked {since}. Resume it with /aidlc.',
175  // In a side job the workflow is not this session's to resume: the same facts, no command.
176  'aidlc.gate.parked.captionSideJob': 'The workflow was parked {since}.',
177  'aidlc.gate.awaiting-approval.title': '{stage} awaits your approval',
178  'aidlc.gate.awaiting-approval.caption': 'The gate is open: approve or request changes to move on.',
179
180  // Two truths (M3): the working tree against the default branch on origin, and the PRs between.
181  // {ref} is the forge's own reference text ("#33", "!275"), never spelled here; {base} the default branch. Keys that
182  // name a pull request have a `.gitlab` twin that says merge request (see `wording` in providers/aidlc/truths.ts).
183  'aidlc.word.inPr': 'in review',
184  'aidlc.word.inDraftPr': 'in draft',
185  'aidlc.word.local': 'local only',
186  'aidlc.word.unmerged': 'not merged',
187  'aidlc.word.noPr': 'pushed, no PR',
188  'aidlc.word.noPr.gitlab': 'pushed, no MR',
189  'aidlc.word.upNext': 'up next',
190
191  'aidlc.chip.pr': '{ref}',
192  'aidlc.chip.prDraft': '{ref} draft',
193  'aidlc.chip.ciFailing': 'CI failing',
194  'aidlc.chip.reopened': '↺ reopened in {ref}',
195
196  'aidlc.base.inPr': '{base}: {stage} in review, PR {ref}',
197  'aidlc.base.inPr.gitlab': '{base}: {stage} in review, MR {ref}',
198  'aidlc.base.inPrReview': '{base}: {stage} {review}, PR {ref}',
199  'aidlc.base.inPrReview.gitlab': '{base}: {stage} {review}, MR {ref}',
200  'aidlc.base.unmerged': '{base}: {stage} not merged yet',
201  'aidlc.base.merged': '{base}: {stage} merged',
202  'aidlc.base.running': '{base}: {stage} in progress',
203  'aidlc.base.parked': '{base}: parked at {stage}',
204  'aidlc.base.notStarted': '{base}: {stage} not started',
205  'aidlc.base.absent': 'This intent is not on {base} yet',
206
207  'aidlc.gate.pr-not-merged.title': 'PR {ref} not merged',
208  'aidlc.gate.pr-not-merged.title.gitlab': 'MR {ref} not merged',
209  'aidlc.gate.pr-not-merged.caption': "{next} can't start on {base} until it lands.",
210  'aidlc.gate.ci-failing.title': 'CI failing on PR {ref}',
211  'aidlc.gate.ci-failing.title.gitlab': 'CI failing on MR {ref}',
212  'aidlc.gate.ci-failing.caption': 'Failing: {checks}',
213  'aidlc.gate.changes-requested.title': 'Changes requested on PR {ref}',
214  'aidlc.gate.changes-requested.title.gitlab': 'Changes requested on MR {ref}',
215  'aidlc.gate.changes-requested.caption': 'Address the review before it can merge.',
216  'aidlc.gate.behind-main.title': '{branch} is behind {base}',
217  'aidlc.gate.behind-main.caption': '{count} new commits on {base}; merge or rebase before it can land.',
218  'aidlc.gate.behind-main.captionPr': 'PR {ref} is out of date with {base}; update the branch.',
219  'aidlc.gate.behind-main.captionPr.gitlab': 'MR {ref} is out of date with {base}; update the branch.',
220  'aidlc.gate.conflicts.title': 'PR {ref} has conflicts with {base}',
221  'aidlc.gate.conflicts.title.gitlab': 'MR {ref} has conflicts with {base}',
222  'aidlc.gate.conflicts.caption': 'Resolve them before it can merge.',
223  'aidlc.gate.parked.captionPr': 'Waiting on PR {ref} to merge; parked {since}. Resume with /aidlc once it lands.',
224  'aidlc.gate.parked.captionPr.gitlab': 'Waiting on MR {ref} to merge; parked {since}. Resume with /aidlc once it lands.',
225  'aidlc.gate.parked.captionPrSideJob': 'Waiting on PR {ref} to merge; parked {since}.',
226  'aidlc.gate.parked.captionPrSideJob.gitlab': 'Waiting on MR {ref} to merge; parked {since}.',
227
228  // ── ledger provider ───────────────────────────────────────────────────────
229  'ledger.subtitle': '{path} · {done}/{total} done',
230
231  'ledger.caption.localOnly': 'Showing the local copy of the ledger: the default branch could not be read.',
232  'ledger.caption.noChanges.github': 'Pull requests could not be read ({cause}), so progress comes from the ledger alone.',
233  'ledger.caption.noChanges.gitlab': 'Merge requests could not be read ({cause}), so progress comes from the ledger alone.',
234  'ledger.caption.noRemote': 'No origin remote, so progress comes from the ledger alone.',
235  'ledger.caption.proposal': 'Proposed product sections below — pin them to group tasks by product.',
236  'ledger.caption.aiFailed': 'Grouping by product is unavailable right now; showing the last result.',
237  'ledger.caption.aiUnavailable': 'Product grouping needs a model reply; showing phases.',
238  'ledger.caption.stale': 'Could not fetch; the ledger may be behind origin.',
239
240  'ledger.section.unassigned': 'Unassigned',
241  'ledger.section.tasks': 'Tasks',
242
243  'ledger.chip.more': '+{count} more',
244  'ledger.chip.revert': 'revert {ref}',
245
246  'ledger.next.command': 'start {id} — {title}',
247  'ledger.next.commandNoTitle': 'start {id}',
248  'ledger.next.reasonDeps': 'depends on {deps}, all done',
249  'ledger.next.reasonFree': 'no unfinished dependencies',
250
251  'ledger.drift.declared-open-but-merged': '{id}: the ledger says not done, but {ref} merged',
252  'ledger.drift.declared-done-but-open': '{id}: the ledger says done, but {ref} is still open',
253  'ledger.drift.declared-done-no-pr-open-pr': '{id}: the ledger says done, but {ref} (a slice of it) is still open',
254  'ledger.drift.qa-failed': '{id}: QA failed on {ref}',
255  'ledger.drift.note': '{id}: {note}',
256
257  'ledger.action.propose': 'Propose product sections',
258  'ledger.action.pin': 'Pin sections',
259  'ledger.action.rebuild': 'Propose again',
260
261  // ── pull request review (both providers) ──────────────────────────────────
262  // {ref} is the forge's own reference ("#33"), {number} the bare number a command takes, {who} the logins
263  // asked to review (the viewer reads as review.who.you).
264  'review.word.draft': 'in draft',
265  'review.word.awaiting': 'awaiting {who}',
266  'review.word.changes': 'changes requested',
267  'review.word.commented': 'commented',
268  'review.word.stale': 'approved, new commits',
269  'review.word.approved': 'approved',
270  'review.word.approvedComments': 'approved with comments',
271  'review.word.unreviewed': 'no reviewer',
272  'review.who.you': 'you',
273  'review.who.separator': ', ',
274
275  'review.chip.slack': 'Slack thread',
276
277  'review.row.review-requested.title': 'Your review is requested on PR {ref}',
278  'review.row.review-requested.caption': '{title} — by {author}',
279  'review.row.changes-requested.title': 'Changes requested on your PR {ref}',
280  'review.row.changes-requested.caption': 'Answer the review before it can merge.',
281  'review.row.review-commented.title': 'Comments on your PR {ref}',
282  'review.row.review-commented.caption': 'A review left comments without a verdict.',
283  'review.row.approval-stale.title': 'PR {ref} changed since its approval',
284  'review.row.approval-stale.caption': 'Merging needs an approval of the latest commit.',
285  'review.row.approved-comments.title': 'PR {ref} approved with comments',
286  'review.row.approved-comments.caption': 'Take what you want from the comments, then merge.',
287  'review.row.approved.title': 'PR {ref} approved',
288  'review.row.approved.caption': 'Ready to merge.',
289  'review.row.draft-not-requested.title': 'Your draft PR {ref} is not sent for review',
290  'review.row.draft-not-requested.caption': 'Sending it for review marks it ready.',
291  'review.row.review-not-requested.title': 'PR {ref} is not sent for review',
292  'review.row.review-not-requested.caption': 'Nobody is asked to review it yet.',
293
294  // The pr-review plugin's commands, put in the prompt from a row or from Next.
295  'review.command.review': '/pr-review:review-pr {number}',
296  'review.command.address': '/pr-review:address-review {number}',
297  'review.command.merge': '/pr-review:address-review {number}',
298  'review.command.request': '/pr-review:request-review {number}',
299
300  // ── refresh engine (M2) ───────────────────────────────────────────────────
301  'refresh.failed': 'Could not re-read the plan; showing the last good read.',
302  'refresh.remoteFailed': 'Could not check the remote; changes may be stale.',
303  'refresh.remoteFailed.github': 'Could not check pull requests ({cause}); they may be stale.',
304  'refresh.remoteFailed.gitlab': 'Could not check merge requests ({cause}); they may be stale.',
305
306  // ── forge layer (src/forge/): why a gh / glab call did not work ───────────
307  'forge.cause.missing': '{cli} missing',
308  'forge.cause.notLoggedIn': '{cli} not logged in to {host}',
309  'forge.cause.unreachable': 'could not reach {host}',
310  'forge.cause.failed': '{cli} failed',
311  'forge.cause.noRemote': 'no origin remote',
312} as const
313
314export type StringKey = keyof typeof en
315
316/**
317 * Resolves `key` with `{param}` placeholders filled. Unknown key → ''. A
318 * placeholder whose param is missing or empty makes the whole string '' so a
319 * half-filled sentence is never drawn.
320 */
321export function t(key: string, params: Record<string, string> = {}): string {
322  const template = (en as Record<string, string>)[key] ?? ''
323  let isComplete = true
324  const out = template.replace(/\{(\w+)\}/g, (_, name: string) => {
325    const value = params[name]
326    if (value === undefined || value === '') isComplete = false
327    return value ?? ''
328  })
329  return isComplete ? out : ''
330}
331
src/detect.ts 24 lines
1// Which provider's plan this repo has: the providers are tried in order and the
2// first hit wins (AI-DLC keeps priority over the ledger). A provider that throws
3// counts as a miss, so one broken provider never hides another's plan.
4import type { Detection, Provider, ProviderContext } from '../types'
5import { aidlc } from './providers/aidlc'
6import { ledger } from './providers/ledger'
7
8export const PROVIDERS: readonly Provider[] = [aidlc, ledger]
9
10export async function detectPlan(
11  ctx: ProviderContext,
12  providers: readonly Provider[] = PROVIDERS,
13): Promise<{ provider: Provider; detection: Detection } | null> {
14  for (const provider of providers) {
15    try {
16      const detection = await provider.detect(ctx)
17      if (detection) return { provider, detection }
18    } catch {
19      // A miss.
20    }
21  }
22  return null
23}
24
src/freshness.ts 29 lines
1// How long ago the panel last looked, as display text. Pure: the caller hands in
2// `now`, so the renderer stays deterministic and the redesign can call it freely.
3import { t } from './strings/en'
4import type { PanelModel } from '../types'
5
6const SECOND = 1000
7const MINUTE = 60 * SECOND
8const HOUR = 60 * MINUTE
9
10/** "just now" under 5 s, then "12s ago", "3m ago", "2h ago"; '' for a bad or absent time. */
11export function agoText(now: number, then: number): string {
12  if (!Number.isFinite(now) || !Number.isFinite(then)) return ''
13  const elapsed = Math.max(0, now - then)
14  if (elapsed < 5 * SECOND) return t('ago.now')
15  if (elapsed < MINUTE) return t('ago.seconds', { n: String(Math.floor(elapsed / SECOND)) })
16  if (elapsed < HOUR) return t('ago.minutes', { n: String(Math.floor(elapsed / MINUTE)) })
17  return t('ago.hours', { n: String(Math.floor(elapsed / HOUR)) })
18}
19
20/** The clock the header stamp reads: the engine's `now`, and the engine's last check. */
21export type Clock = { now: number; checkedAt?: number }
22
23/** "checked 12s ago": the freshest of the engine's last check, the model's own check and its read. '' hides the stamp. */
24export function checkedText(model: PanelModel, clock: Clock): string {
25  const at = Math.max(clock.checkedAt ?? 0, model.freshness?.checkedAt ?? 0, model.readAt)
26  const ago = agoText(clock.now, at)
27  return ago === '' ? '' : t('header.checked', { ago })
28}
29
src/render/attention.tsx 301 lines
1// Needs attention: what blocks, and what waits on the viewer. The freshness error, then the gates (a provider
2// puts the rows tied to the viewer first: a review asked of them, their approved PR), then the drift flags. A
3// row with a command offers it as a button that puts it in the prompt. On a desktop the rows about pull requests (the
4// ones that link to a PR) are one card together, where the first of them stands, one line per PR with everything said
5// about it; every other row is a card of its own.
6import { t } from '../strings/en'
7import type { Gate, PanelModel } from '../../types'
8import { gateColor, gateGlyph, isRich, safely, tint, toneColor, uniqueIds } from './kit'
9import { pill } from './look'
10import type { Ctx, El } from './kit'
11
12type Row = { id: string; glyph: string; color: string | undefined; title: string; where: string; isBold: boolean; kind?: string; about?: string; href?: string; command?: string; caption?: string }
13
14/**
15 * The gate's section, or "Section, after item" when it holds after an item of it. A row about the viewer is
16 * about the item itself ("Section, item"), not what comes after it; one about a PR outside the plan says what
17 * the PR is (its caption: title and author).
18 */
19function whereOf(model: PanelModel, gate: Gate): string {
20  const section = model.sections.find(one => one.id === gate.sectionId)
21  if (section === undefined) return gate.isAttentionOnly === true ? (gate.caption ?? '') : ''
22  const after = section.items.find(one => one.id === gate.afterItemId)
23  if (after !== undefined) return t(gate.isAttentionOnly === true ? 'attention.whereOn' : 'attention.whereAfter', { section: section.title, item: after.title })
24  return section.title
25}
26
27export function rowsOf(model: PanelModel): Row[] {
28  const rows: Row[] = []
29  const error = model.freshness?.error ?? ''
30  if (error !== '') rows.push({ id: 'error', glyph: '!', color: 'error', title: error, where: '', isBold: true })
31  for (const gate of model.gates) {
32    if (gate.title === '') continue
33    rows.push({
34      id: 'gate:' + gate.id,
35      glyph: gateGlyph(gate),
36      color: gateColor(gate),
37      title: gate.title,
38      where: whereOf(model, gate),
39      isBold: true,
40      kind: gate.kind,
41      // Someone else's PR outside the plan is known by its title and author, which a review asked of you says.
42      ...(gate.kind === 'review-requested' && !model.sections.some(one => one.id === gate.sectionId) && (gate.caption ?? '') !== '' ? { about: gate.caption } : {}),
43      ...(gate.href !== undefined && gate.href !== '' ? { href: gate.href } : {}),
44      ...(gate.command !== undefined && gate.command !== '' ? { command: gate.command } : {}),
45      ...(gate.caption !== undefined && gate.caption !== '' && gate.isAttentionOnly !== true ? { caption: gate.caption } : {}),
46    })
47  }
48  for (const flag of model.drift) {
49    if (flag.label === '') continue
50    rows.push({ id: 'drift:' + flag.id, glyph: '≠', color: toneColor(flag.tone), title: flag.label, where: '', isBold: false })
51  }
52  return rows
53}
54
55/** The row's command as a button that puts it in the prompt, under the title. */
56function commandEl(ctx: Ctx, row: Row, key: string): El | false {
57  const { Box, Button } = ctx.kit
58  const command = row.command ?? ''
59  if (command === '') return false
60  return (
61    <Box paddingLeft={2} flexShrink={1}>
62      <Button key={'attention:fill:' + key} variant="secondary" onPress={safely(() => ctx.handlers.onFillNext(command))}>
63        {command}
64      </Button>
65    </Box>
66  )
67}
68
69/** A row's lines, without a card: its glyph, title and where, then its caption and command. */
70function rowBody(ctx: Ctx, row: Row, key: string): El {
71  const { Box, Text, Link } = ctx.kit
72  const glyph = (
73    <Box width={1} flexShrink={0}>
74      <Text bold color={row.color}>
75        {row.glyph}
76      </Text>
77    </Box>
78  )
79  const titleText = (
80    <Text bold={row.isBold} color={isRich(ctx) ? undefined : row.color} wrap="wrap">
81      {row.title}
82    </Text>
83  )
84  // The title wins: it keeps up to 24 columns (its own length when shorter) and the where gives way first.
85  const title = (
86    <Box flexShrink={1} minWidth={ctx.bp === 'S' ? undefined : Math.min(Array.from(row.title).length, 24)}>
87      {row.href !== undefined ? (
88        <Link href={row.href} label={row.title}>
89          {titleText}
90        </Link>
91      ) : (
92        titleText
93      )}
94    </Box>
95  )
96  // The where may be cut to nothing: with no floor of its own it would hold its full length on the desktop
97  // and run past the card's border (a long PR caption did).
98  const where =
99    row.where !== '' ? (
100      <Box flexShrink={4} minWidth={0} overflow="hidden">
101        <Text dimColor wrap="truncate-end">
102          {row.where}
103        </Text>
104      </Box>
105    ) : (
106      false
107    )
108  const command = commandEl(ctx, row, key)
109  // The desktop's card also says why, as the plan's gate card did: the gate's caption, dim, under the title.
110  const caption =
111    isRich(ctx) && row.caption !== undefined ? (
112      <Box paddingLeft={2} flexShrink={1}>
113        <Text dimColor wrap="wrap">
114          {row.caption}
115        </Text>
116      </Box>
117    ) : (
118      false
119    )
120  const line =
121    ctx.bp === 'S' ? (
122      <Box flexDirection="column" flexShrink={1}>
123        <Box gap={1}>
124          {glyph}
125          {title}
126        </Box>
127        {where !== false && <Box paddingLeft={2}>{where}</Box>}
128      </Box>
129    ) : (
130      <Box gap={1} flexShrink={1} flexGrow={1} minWidth={0}>
131        {glyph}
132        {title}
133        <Box flexGrow={1} />
134        {where}
135      </Box>
136    )
137  return command === false && caption === false ? (
138    line
139  ) : (
140    <Box flexDirection="column" flexShrink={1} flexGrow={1} minWidth={0}>
141      {line}
142      {caption}
143      {command}
144    </Box>
145  )
146}
147
148/** A card in `color`: the desktop fills it with a tint of the tone under a faint line of it; the title is in the text colour. */
149function card(ctx: Ctx, color: string | undefined, body: El): El {
150  const { Box } = ctx.kit
151  const rich = isRich(ctx)
152  return (
153    <Box
154      borderStyle="round"
155      borderColor={rich ? tint(color, '66') : (color ?? 'subtle')}
156      backgroundColor={rich ? tint(color, '17') : undefined}
157      paddingX={1}
158    >
159      {body}
160    </Box>
161  )
162}
163
164/** The worst tone of several rows, for the card that holds them all: an error over a warning over good news. */
165const RANK: Record<string, number> = { error: 3, warning: 2, accent: 1, success: 0 }
166const worstOf = (rows: readonly Row[]): string | undefined =>
167  rows.reduce<string | undefined>((worst, row) => ((RANK[row.color ?? ''] ?? 2) > (RANK[worst ?? ''] ?? -1) ? row.color : worst), undefined)
168
169/** A PR's number and forge from its link: GitHub's `/pull/66`, GitLab's `/merge_requests/66`; null for anything else. */
170function prRefOf(href: string): string {
171  const github = /\/pull\/(\d+)(?:[/?#]|$)/.exec(href)
172  if (github) return t('attention.pr.ref', { number: github[1]! })
173  const gitlab = /\/merge_requests\/(\d+)(?:[/?#]|$)/.exec(href)
174  return gitlab ? t('attention.pr.ref.gitlab', { number: gitlab[1]! }) : ''
175}
176
177/** What a row says about its PR in a word or two (`conflicts`); its own title for a kind with no short word. */
178const wordOf = (row: Row): string => t(`attention.pr.word.${row.kind ?? ''}`) || row.title
179
180/** A command as its name alone, for a button on a PR's line: `/pr-review:address-review 66` is `address-review`. */
181const commandName = (command: string): string => command.replace(/^\//, '').split(/\s/)[0]!.split(':').pop() ?? command
182
183type PrLine = { href: string; ref: string; rows: { row: Row; key: string }[] }
184
185/** The PR rows by the PR they link to, in the order each PR first comes; the rows in theirs, the worst first. */
186function prLinesOf(rows: readonly { row: Row; key: string }[]): PrLine[] {
187  const lines: PrLine[] = []
188  for (const one of rows) {
189    const href = one.row.href ?? ''
190    const line = lines.find(each => each.href === href)
191    if (line) line.rows.push(one)
192    else lines.push({ href, ref: prRefOf(href), rows: [one] })
193  }
194  for (const line of lines) line.rows.sort((a, b) => (RANK[b.row.color ?? ''] ?? 2) - (RANK[a.row.color ?? ''] ?? 2))
195  return lines
196}
197
198/**
199 * One PR on one line: the glyph of its worst row, the PR as a link, everything the rows say about it in a word or two
200 * (`conflicts · changes requested · not merged`), with the title and author of a PR outside the plan, and the first
201 * command one of them offers as a small button named by the command.
202 */
203function prLineEl(ctx: Ctx, line: PrLine): El {
204  const { Box, Text, Link, Button } = ctx.kit
205  const worst = line.rows[0]!.row
206  const about = line.rows.find(one => (one.row.about ?? '') !== '')?.row.about ?? ''
207  const words = [...new Set([...line.rows.map(one => wordOf(one.row)), about].filter(word => word !== ''))]
208  const label = line.ref || worst.title
209  const withCommand = line.rows.find(one => (one.row.command ?? '') !== '')
210  const command = withCommand?.row.command ?? ''
211  return (
212    <Box gap={1} flexShrink={1} flexGrow={1} minWidth={0}>
213      <Box width={1} flexShrink={0}>
214        <Text bold color={worst.color}>
215          {worst.glyph}
216        </Text>
217      </Box>
218      <Box flexShrink={0}>
219        <Link href={line.href} label={label}>
220          <Text bold>{label}</Text>
221        </Link>
222      </Box>
223      <Box flexShrink={1} flexGrow={1} minWidth={0}>
224        <Text dimColor wrap="wrap">
225          {words.join(t('attention.pr.separator'))}
226        </Text>
227      </Box>
228      {withCommand !== undefined && (
229        <Box flexShrink={0}>
230          <Button key={'attention:fill:' + withCommand.key} variant="secondary" onPress={safely(() => ctx.handlers.onFillNext(command))}>
231            {commandName(command)}
232          </Button>
233        </Box>
234      )}
235    </Box>
236  )
237}
238
239/** The rows about pull requests as one card: a dim heading, then one line per PR. */
240function prCard(ctx: Ctx, rows: readonly { row: Row; key: string }[]): El {
241  const { Box, Text } = ctx.kit
242  const lines = prLinesOf(rows)
243  const heading = t('attention.prs', { count: String(lines.length) })
244  return card(
245    ctx,
246    worstOf(rows.map(one => one.row)),
247    <Box flexDirection="column" gap={1} flexShrink={1} flexGrow={1} minWidth={0}>
248      {heading !== '' && (
249        <Text bold dimColor wrap="truncate-end">
250          {heading}
251        </Text>
252      )}
253      {lines.map(line => prLineEl(ctx, line))}
254    </Box>,
255  )
256}
257
258export function attention(ctx: Ctx, model: PanelModel): El | false {
259  const { Box, Text } = ctx.kit
260  const rows = rowsOf(model)
261  if (rows.length === 0) return false
262  const keys = uniqueIds(rows.map(row => row.id))
263  // The desktop: the heading in the text colour with the count as a pill beside it, the cards a little apart.
264  const rich = isRich(ctx)
265  const heading = rich ? t('attention.heading') : t('attention.title', { count: String(rows.length) })
266  const tone = rows.some(row => row.color === 'error') ? 'error' : 'warning'
267  const keyed = rows.map((row, index) => ({ row, key: keys[index]! }))
268  // On a desktop, the rows about pull requests are one card, where the first of them stands, a line per PR; the
269  // terminal draws no cards and keeps every row in its place.
270  const isBoxed = ctx.surface !== 'terminal'
271  const prs = keyed.filter(one => one.row.href !== undefined)
272  const isFolded = isBoxed && prs.length > 0
273  const firstPr = prs[0]?.key
274  const cards = keyed.flatMap(one => {
275    if (isFolded && one.row.href !== undefined) return one.key === firstPr ? [prCard(ctx, prs)] : []
276    const body = rowBody(ctx, one.row, one.key)
277    return [isBoxed ? card(ctx, one.row.color, body) : body]
278  })
279  return (
280    <Box flexDirection="column" gap={rich ? 1 : 0}>
281      {heading !== '' &&
282        (rich ? (
283          <Box gap={1}>
284            <Text bold wrap="truncate-end">
285              {heading}
286            </Text>
287            {pill(ctx, String(rows.length), tone)}
288          </Box>
289        ) : (
290          <Text bold dimColor wrap="truncate-end">
291            {heading}
292          </Text>
293        ))}
294      {/* The cards stand apart, so each reads as its own. */}
295      <Box flexDirection="column" gap={rich ? 2 : 0}>
296        {cards}
297      </Box>
298    </Box>
299  )
300}
301
src/render/header.tsx 177 lines
1// The header: where am I. Title, badge, freshness stamp and the Refresh button,
2// laid out per breakpoint so the title is what gives way and nothing overlaps.
3import { checkedText } from '../freshness'
4import type { Clock } from '../freshness'
5import { t } from '../strings/en'
6import type { PanelModel } from '../../types'
7import { showsCurrentItem } from './now'
8import { clockTime, isRich, safely } from './kit'
9import { pill } from './look'
10import type { Ctx, El } from './kit'
11
12function badgeColor(mode: PanelModel['header']['mode']): string {
13  switch (mode) {
14    case 'side-job':
15      return 'warning'
16    case 'stage':
17      return 'claude'
18    case 'inferred':
19      return 'suggestion'
20    default:
21      return 'subtle'
22  }
23}
24
25function stampOf(model: PanelModel | null, clock: Clock | undefined): string {
26  if (model === null) return ''
27  if (clock !== undefined) return checkedText(model, clock)
28  return t('header.readAt', { time: clockTime(model.readAt) })
29}
30
31/** Row 1: title | (M/L) badge and stamp | Refresh. Row 2 (S only): badge and stamp. Then the error line. */
32export function header(ctx: Ctx, model: PanelModel | null, clock: Clock | undefined): El {
33  const { Box, Text, Button } = ctx.kit
34  const { bp, handlers } = ctx
35  const title = model === null ? t('pane.title') : model.header.title.toUpperCase()
36  const badge = model === null ? '' : model.header.badge
37  const stamp = stampOf(model, clock)
38  const isDimBadge = model?.header.mode === 'idle'
39  const error = model?.freshness?.error ?? ''
40  // The subtitle (where the plan stands) is dropped when the Now card already names the current item.
41  const subtitle = model === null || showsCurrentItem(model) ? '' : model.header.subtitle
42
43  // On M/L the title shrinks first, down to a small floor of its own; the badge and the stamp
44  // then give way (truncated); the Refresh button never shrinks. On S they sit on row 2, alone.
45  const badgeShrink = bp === 'S' ? 0 : 0.25
46  const badgeEl =
47    badge !== '' && model !== null ? (
48      <Box flexShrink={badgeShrink}>
49        <Text bold color={badgeColor(model.header.mode)} dimColor={isDimBadge} wrap="truncate-end">
50          {badge}
51        </Text>
52      </Box>
53    ) : (
54      false
55    )
56  const refresh = bp === 'S' ? '↻' : `↻ ${t('header.refresh')}`.trimEnd()
57  if (isRich(ctx)) return richHeader(ctx, title, badge, model, stamp, subtitle, error, refresh)
58
59  return (
60    <Box flexDirection="column">
61      <Box gap={1}>
62        {title !== '' && (
63          <Box flexShrink={1} minWidth={Math.min(Array.from(title).length, 8)}>
64            <Text bold wrap="truncate-end">
65              {title}
66            </Text>
67          </Box>
68        )}
69        <Box flexGrow={1} />
70        {bp !== 'S' && badgeEl}
71        {bp !== 'S' && stamp !== '' && (
72          <Box flexShrink={0.25}>
73            <Text dimColor wrap="truncate-end">
74              {stamp}
75            </Text>
76          </Box>
77        )}
78        <Box flexShrink={0}>
79          <Button key="refresh" hotkey="r" onPress={safely(handlers.onRefresh)}>
80            {refresh}
81          </Button>
82        </Box>
83      </Box>
84      {bp === 'S' && (badge !== '' || stamp !== '') && (
85        <Box gap={1}>
86          {badgeEl}
87          {stamp !== '' && (
88            <Box flexShrink={1}>
89              <Text dimColor wrap="truncate-end">
90                {stamp}
91              </Text>
92            </Box>
93          )}
94        </Box>
95      )}
96      {subtitle !== '' && (
97        <Text dimColor wrap="wrap">
98          {subtitle}
99        </Text>
100      )}
101      {error !== '' && (
102        <Box gap={1}>
103          <Box flexShrink={0}>
104            <Text bold color="error">
105              !
106            </Text>
107          </Box>
108          <Box flexShrink={1}>
109            <Text color="error" wrap="wrap">
110              {error}
111            </Text>
112          </Box>
113        </Box>
114      )}
115    </Box>
116  )
117}
118
119/**
120 * The desktop's header: the title with the badge as a pill beside it and Refresh at the end; the stamp, the
121 * subtitle and the error line under it, dim. The title is what gives way.
122 */
123function richHeader(
124  ctx: Ctx,
125  title: string,
126  badge: string,
127  model: PanelModel | null,
128  stamp: string,
129  subtitle: string,
130  error: string,
131  refresh: string,
132): El {
133  const { Box, Text, Button } = ctx.kit
134  const below = [stamp, subtitle].filter(part => part !== '')
135  return (
136    <Box flexDirection="column">
137      <Box gap={1} alignItems="center">
138        {title !== '' && (
139          <Box flexShrink={1} minWidth={Math.min(Array.from(title).length, 8)}>
140            <Text bold wrap="truncate-end">
141              {title}
142            </Text>
143          </Box>
144        )}
145        {badge !== '' && model !== null && (
146          <Box flexShrink={0}>{pill(ctx, badge, badgeColor(model.header.mode), model.header.mode === 'idle')}</Box>
147        )}
148        <Box flexGrow={1} />
149        <Box flexShrink={0}>
150          <Button key="refresh" hotkey="r" onPress={safely(ctx.handlers.onRefresh)}>
151            {refresh}
152          </Button>
153        </Box>
154      </Box>
155      {below.map(line => (
156        <Text dimColor wrap="wrap">
157          {line}
158        </Text>
159      ))}
160      {error !== '' && (
161        <Box gap={1}>
162          <Box flexShrink={0}>
163            <Text bold color="error">
164              !
165            </Text>
166          </Box>
167          <Box flexShrink={1}>
168            <Text color="error" wrap="wrap">
169              {error}
170            </Text>
171          </Box>
172        </Box>
173      )}
174    </Box>
175  )
176}
177