SLOPSHOPPER

archon-panel

An Archon pane in the side panel: this project's workflow runs, their graphs and logs, and the approvals that wait on you.

panecommandtoaststatusprocessnetwork
★ 2v0.3.0no licenseupdated 2026-10-11seanrobertwright/claude-mods/mods/archon-panel
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · archon-panel
│ ┃ Archon ✕ › fix the failing auth test and add an audit log call │ ┃ 1: Runs 2: Graph 3: Log 4: Archon's log │ ┃ The Archon pane needs the Archon CLI, v0.11. ⏺ Read(src/auth.ts) │ ┃ Install it from https://archon.diy, or set i ⎿ Read 6 lines │ ┃ the mod settings, then press r. ⏺ 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 │ │ › /archon │ ⎿ archon-panel: Archon pane opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Archon
1: Runs 2: Graph 3: Log 4: Archon's log r: ↻ The Archon pane needs the Archon CLI, v0.11.0 or later. Install it from https://archon.diy, or set its path in the mod settings, then press r.
README

🧩 claude-mods

Small TypeScript mods that live inside Claude Code: a pane that knows your next step, one-click replies, a rate-limit countdown that resumes for you, your repo's pull requests and issues beside the conversation, a shelf of paths you use every day, presets that switch the model and the effort with one press, a chime when a long turn ends, a guard for the Office file you left open, a question before a commit or push on the default branch, a question before Claude reads a .env or key file, a list of the files this session made, a list of the ones it read, a check that keeps banned claims out of a pull request, a gate that runs your checks and hands back only the failures, a nudge to fetch fresh tab IDs when a browser tab is gone, a name for the session from its first prompt, your project's dev servers in a pane that fills a crash's error into the prompt, and one dialog for every mod's settings.

Claude Code 2.1.289+ 21 mods TypeScript strict Checks: tsc, ESLint, validate, test

claude-mods is one developer's personal toolbox of Claude Code mods, shared as a plugin marketplace so anyone can install them. The mods are built for the author's own workflow first, and you are a welcome guest: install one, install all twenty-one, or read the source and write your own.

What is a mod?

A mod is a plugin of function hooks: TypeScript that runs inside Claude Code and changes what it shows (a pane in the side panel, a band of buttons above the prompt, the status line) or what it does between turns. The mod's own code decides when to act, even when what it does is send the model a prompt.

Runs asWho decides when it acts
ModTypeScript function hooks inside Claude CodeThe mod's own code
SkillInstructions the model readsThe model
Plain pluginCommands, agents or shell hooksYou, or a shell script

The mods

ModWhere it showsWhat it does
🧭 whats-nextPane in the side panelLists the next steps of your workflow, each with a prompt ready to paste
⚡ quick-replyBand above the promptOne-click replies, including the options Claude just offered, Pass, Fail and Skip for a verdict, and the next wayfinder ticket
⏳ auto-resumeBand and status lineCounts down to a rate limit's reset, then sends "continue"
🐙 github-panelPane in the side panelThe repo's open pull requests and issues, one click from the browser or from /implement and /wayfinder in the prompt; the issue a /wayfinder run works on, pinned with its next ticket; a toast when your branch's checks turn green or red
🏛️ archon-panelPane in the side panelThis project's Archon workflow runs, their graphs and logs, and the approvals that wait on you, answered from the pane
📚 shelfBand above the promptNamed folders and files; one click drops a path into what you are typing
🔔 turn-chimeSound and toastTells you when a long turn ends or Claude stops to ask you something
🔒 open-file-guardQuestion dialogAsks you to close a Word, Excel or PowerPoint file before Claude uses it
🌿 branch-guardQuestion dialogAsks you before Claude commits or pushes on the default branch
🔑 env-guardQuestion dialogAsks you before Claude reads a .env or key file, and refuses when no one is there to answer
🩹 bash-quoting-rescueRefused tool callStops a shell command that does not parse, such as an unclosed quote, before any of it runs
📂 outputsPane in the side panelThe files this session made or changed, newest first; click one to open it
🔎 sourcesPane in the side panelThe files Claude read, grouped by where they came from, with a lock to the project folder
📊 hudTwo lines under the promptModel, effort, context window, rate limits, turn timer, tool calls, agents, git state, worktree, cost, session length and folder, each named and in colour
🧹 post-merge-cleanupQuestion dialog and toastAfter a PR merges, /cleanup switches to the default branch, pulls and deletes the branch
🧾 pre-pr-claims-checkRefusal Claude readsRefuses gh pr create and gh pr edit while the pull request cites a file and line, holds a placeholder, or spells out a count
🚦 lint-test-gateBand above the promptRuns your checks on a press and before Claude's git commit, and hands back only the failures
🔄 chrome-tab-self-healNote after a browser tool's errorWhen a Claude in Chrome tab is gone, tells Claude to fetch the current tab IDs before it tries again
🏷 session-auto-namerBand above the promptSuggests a name for the session from its first prompt; one press renames it
🧠 model-effort-presetsBand above the promptPlan and execute presets: one press switches the model and the effort together
🖥 dev-server-managerPane in the side panel, status line and toastStarts, restarts and watches the project's dev servers; a crash toasts, restarts and fills its error into the prompt
⚙ mod-settingsGear on each pane; a dialogChange and save any mod's settings without leaving the session

When more than one mod has a pane open, Claude Code shows them as tabs in the side panel.

🧭 whats-next

A pane listing the next steps of your workflow for the project folder, kept between sessions. A skill of your choosing answers "what's next" in a headless run beside your session, and the mod turns the answer into steps.

What's next                        refresh
updated 3 min ago

Fix the failing parse test
working on it  done
The check is red, so nothing else can merge.

Open a pull request for the fix
Review comes before the next feature starts.

Triage the two new issues
They arrived while you were heads-down.
flowchart LR
    A[Skill answers<br/>what's next] --> B[Steps in the pane]
    B --> C[You read a step's prompt<br/>and send it yourself]
    C --> D[Step glows:<br/>working on it]
    D --> E{Laya, Jev or Haiku:<br/>is the step finished?}
    E -- not yet --> D
    E -- yes --> F[Step leaves the list]
  • You stay in charge. A step's prompt reaches the model only when you read it and send it yourself. Click a step to see its prompt, then paste it, paste it into a fresh session (after your prime command, if you name one), or copy it.
  • It notices when you are done. After each answered turn, a System One model is asked whether the step is finished, as your System One models setting allows, and Haiku when none answers surely enough. A finished step leaves the list. Press d to drop it yourself.
  • The run that asks is read-only. By default it gets only read commands of git and gh plus Read, Glob and Grep. git push, git config, git -c, gh api and --output are always denied.
Command or keyWhat it does
/whats-nextBring the pane to the front
/whats-next refreshAsk the skill again
rRefresh
1 to 9Show that step's prompt in the pane
p, n, cPaste the shown prompt, paste it after /clear (and the prime command, once its turn ends), or copy it
bBack to the list
dMark the active step done
SettingKeyDefaultMeaning
Skillskill/ask-seanThe skill that answers "what's next", written as you would run it: / followed by letters, digits, _, :, . or -
Most stepsmaxSteps5How many steps to ask for (1-9)
Refresh on startrefreshOnStartonAsk for a fresh list when a session starts in a git repository
Tools the headless run may useallowedToolsempty: the read-only setComma-separated permission rules for the headless run
Modelmodelempty: your defaultModel for the headless run, as an alias (haiku) or a full id
Prime commandprimeCommandempty: noneA slash command, with any arguments, run after /clear and before the paste (/lril:prime); the prompt is filled once the turn it starts ends, finished or not. A value that is not one slash command on one line is never run, and the step view says so
System One modelsmodelChoicelocal onlyWhich System One model judges whether a turn finished the active step: local only (Laya on this machine, or Haiku as before), local first (Laya, and TypeSafe's hosted Jev while Laya is unavailable) or hosted first (Jev, and Laya while Jev is unavailable)
Jev API keyjevApiKeyemptyYour key for Jev, from console.typesafe.ai, kept in secure storage. Sent only to https://api.typesafe.ai, and only while System One models allows Jev
Laya portlayaPort8000The port your laya-serve listens on at 127.0.0.1 (1-65535)

/ask-sean is the author's own skill, so point the Skill setting at a skill of yours that answers "what should I do next?" (how to set it):

echo '{"skill": "/next-steps", "maxSteps": "3", "model": "haiku"}' | claude plugin configure whats-next@claude-mods --values-stdin

The read-only set, used while Tools is empty, is Bash(git status:*), Bash(git log:*), Bash(git diff:*), Bash(git show:*), Bash(git rev-parse:*), Bash(git branch --show-current), Bash(git branch -vv), Bash(git remote -v), Bash(gh issue list:*), Bash(gh issue view:*), Bash(gh pr list:*), Bash(gh pr view:*), Bash(gh pr checks:*), Bash(gh run list:*), Read, Glob and Grep.

  • A list you write replaces that set; it does not add to it. To widen the set, write all of it plus your additions.
  • Each rule is a tool name, optionally followed by (...). One rule that is not, such as one starting with -, discards your whole list and the read-only set is used.
  • The run can always call Skill, so a skill that calls another still works. MCP servers load only when a rule names an mcp__ tool.

What the judge sends to a System One model, once after each answered turn while a step is active:

  • To Jev, only while System One models allows it and the folder is not marked local-only: the active step's title, reason and prompt and the last 8,000 characters of Claude's answer. Never the contents of a file the mod read itself.
  • To Laya, which keeps it on this machine: the same, fitted to Laya's small window. The step's prompt is dropped first, then the start of the answer, so the end of the answer, where Claude says whether the work is done, is kept.
  • Sure answers only. "Done" counts at a probability of 0.9 or more and "not done" at 0.1 or less. Anything between, a model that is busy or fails, or no answer within 5 s leaves the step to Haiku, as before.
  • A key it cannot use is named. While System One models allows Jev, a missing key, one that is not a key, or one TypeSafe rejects is named on a line in the pane, and the list stays. A rejected key stays off until the mod reloads.
  • A changed key takes effect once the mod reloads. The settings dialog does not list the key, so set it with /plugin configure whats-next@claude-mods. That saves it without reloading the mod: run /reload-plugins, or wait for the next start of Claude Code.

Needs: the claude CLI on the PATH, and the skill named in the Skill setting. Laya and a Jev key are optional: with neither, the judge is Haiku, as before.

⚡ quick-reply

One row of buttons above the prompt after each answer. When Claude ends on a question, the band offers the choices Claude asked you to pick from, then your replies to a question. After any other answer it offers your other replies. You set both lists in the settings below.

Reply:  [a: Keep the copies]  [b: Add a sync script]  [Yes]  [Go with your recommendation]  [No]
  • A choice's button sends its marker with its label, so the model cannot misread it.
  • A numbered report before a yes-or-no question ("Shall I commit?") is not offered as choices.
  • When the answer recommends something, the "recommend" reply is the highlighted one. Advice against something does not count.
  • The band stays out of the way while Claude is working, and after a subagent's turn.
  • A model can read the ending too. After each answered turn, a System One model is asked how the answer ends, as your System One models setting allows: whether it asks you something, whether its numbered items are choices, and which one it recommends. The band shows its own reading at once, and a sure answer that arrives within 2 s takes its place, so a numbered report closed by "push now or wait?" is not offered as choices.

Verdicts. When Claude asks for a pass/fail verdict on a test or a check, as a UAT or /gsd:verify-work step does ("Pass or fail?", "Did it pass?", "Type pass or describe what's wrong"), the band offers a verdict in place of your replies:

Reply:  [Pass]  [Fail…]  [Skip]

Pass sends "pass" and Skip sends "skip", as your own message. Fail… sends nothing: it puts "Fail: " in the prompt, where you say what went wrong and can paste a screenshot. A test's numbered steps are not offered as choices, and a question that only mentions passing ("Shall I make the tests pass?") gets your usual replies.

Next ticket. When you work a map with the wayfinder skill, the band leads with the next ticket after each turn that closes one or charts the map:

Reply:  [Next ticket: /wayfinder 135]  [Continue]  [Commit and push]

One press runs /clear and then /wayfinder 135, the loop you would otherwise type. It is offered only in a session that ran the wayfinder skill, after a turn whose gh issue close worked; after charting it names the map the turn created. A close made some other way (gh api, the web) is not seen, so no button shows, and once a turn closes the map itself the loop ends.

SettingKeyDefaultMeaning
Replies to a questionquestionReplies`Yes\Go with your recommendation\No`Shown after Claude asks something, separated by `\`; empty shows only the choices Claude offered
Replies otherwiseidleReplies`Continue\Commit and push`Shown after any other answer; empty hides the band then, except for Next ticket
Offer the next wayfinder ticketwayfinderNexttrueAfter a wayfinder turn closes a ticket or charts a map, offer Next ticket
System One modelsmodelChoicelocal onlyWhich System One model reads how each answer ends: local only (Laya on this machine, or the band's own reading as before), local first (Laya, and TypeSafe's hosted Jev while Laya is unavailable) or hosted first (Jev, and Laya while Jev is unavailable)
Jev API keyjevApiKeyemptyYour key for Jev, from console.typesafe.ai, kept in secure storage. Sent only to https://api.typesafe.ai, and only while System One models allows Jev
Laya portlayaPort8000The port your laya-serve listens on at 127.0.0.1 (1-65535)

Each list holds up to six replies. A reply longer than 120 characters is cut short, and a repeat is dropped. For example, to answer questions with your own three replies and hide the band after other answers (how to set it):

echo '{"questionReplies": "Yes|No|Explain that first", "idleReplies": ""}' | claude plugin configure quick-reply@claude-mods --values-stdin

What the band sends to a System One model, once after each answered turn:

  • To Jev, only while System One models allows it and the folder is not marked local-only: the last 8,000 characters of Claude's answer and the labels of the choices found in it. Never the contents of a file the mod read itself.
  • To Laya, which keeps it on this machine: the answer's closing lines that fit Laya's small window, where the question is, and at most 9 labels of at most 40 characters.
  • Sure answers only. Each part of the reading counts only when the model is sure of it, at 0.9 or more (0.1 or less for "these are not choices"). Anything less, a model that is busy or fails, a reading Laya reports as cut, or no answer within 2 s leaves the band's own reading. So does a reading that arrives after your next prompt.
  • A key it cannot use is named. While System One models allows Jev, a missing key, one that is not a key, or one TypeSafe rejects is named on a dim line under the replies, until your next prompt. A rejected key stays off until the mod reloads.

Laya and a Jev key are optional: with neither, the band reads each answer as before.

⏳ auto-resume

When a turn dies on a rate limit or an overloaded API, auto-resume counts down to the reset and sends "continue" for you. Go to lunch, and come back to finished work.

⏳ rate limited:  sending "continue" in 1 h 12 min  [Resume now]  [Cancel]
  • The countdown shows above the prompt and in the status line.
  • Send a prompt of your own and it steps aside: you took over.
  • It gives up after too many resumes in a row without a successful answer.
CommandWhat it does
/auto-resumeSay what is waiting, if anything
/auto-resume nowSend the resume now
/auto-resume cancelCancel the wait
/auto-resume in <minutes>Schedule a resume yourself (1 to 1440)
SettingKeyDefaultMeaning
Resume prompttextcontinueWhat is sent when the wait is over; empty sends continue
Grace after reset (s)graceSeconds60Extra seconds to wait past the limit's reset time (0-900)
Retry overloaded/server errorsretryOverloadedonAlso resume after an overloaded or server error, backing off from one minute
Most retries in a rowmaxRetries5Give up after this many resumes without a successful answer (1-20)

For example, to send a longer prompt and wait two minutes past the reset (how to set it):

echo '{"text": "continue where you left off", "graceSeconds": "120"}' | claude plugin configure auto-resume@claude-mods --values-stdin

🐙 github-panel

A GitHub pane beside What's next listing the repo's open pull requests and issues. Click one to open it in the browser. Under each issue, implement and wayfinder put /implement or /wayfinder and the issue's URL in the prompt. Nothing is sent. While a /wayfinder effort is under way, its issue is pinned at the top, with the next ticket to take.

octocat/hello-world                refresh
updated just now

Decide how shared code is copied unpin
3 done · 1 takeable · 1 claimed · 2 blocked
next: Pick the drift check decision
work next

Pull requests 2                        all
#41 Add a drift check for copied guards
  draft · @octocat
#40 Bring the asked pane to the front
  ✗ checks failing · @hubot           fix

Issues 2                               all
#39 Share the headless-session check
  blocked by #12 · ready… implement wayfinder
#12 Decide how shared code is copied
  needs-triage · @hubot implement wayfinder
  • An issue blocked by an open issue has a red line under it. Hover it to see what blocks it.
  • In a narrow pane the implement and wayfinder buttons take a line of their own.
  • The lists refresh on a timer, after a turn once they are a minute old, and on r.
  • The pull request of the branch you are on is watched: when its checks turn green or red, a toast says "Checks passed on #40" or "Checks failed on #40". The first refresh, and the first after you switch branch, only notes where the checks stand.
  • While that pull request's checks fail, its row has a fix button. It fills the prompt box with the failed checks' names, the last 40 lines of the failed run's log, and "Fix it." Nothing is sent: you read it and send it yourself. The log is fetched only when you press fix; when gh cannot fetch it, such as while the run is still going, the prompt holds the names alone.
  • Running /wayfinder on an issue of this repo (/wayfinder 12, /wayfinder #12 or the issue's URL) pins that issue and brings the pane to the front. Anything else, such as prose or another repo's issue, pins nothing. The pin is kept for the repo across sessions, one at a time: a run on another issue replaces it. It goes when you press unpin, or once the issue is closed.
  • The pinned issue's sub-issues are its tickets, each counted once: closed ones are done, open ones with an open blocker are blocked, assigned ones are claimed, and the rest are takeable. next is the first takeable ticket in the order the issue lists its sub-issues, with its wayfinder: type label; click it to open it on GitHub. With nothing takeable it says so; an issue with no sub-issues yet says no tickets yet.
  • work next fills /wayfinder and the pinned issue's URL into the prompt, without sending it, so the skill takes the frontier ticket fresh when it runs.
  • The pinned issue is read in the same refresh as the lists. When a refresh fails, the last section stays and the error shows.
Command or keyWhat it does
/githubBring the pane to the front and refresh it
rRefresh
allOpen the whole list on GitHub
implement, wayfinderFill the command and the issue's URL into the prompt, without sending it
fixFill a request to fix the current branch's failing checks into the prompt box
unpinDrop the pinned issue
work nextFill /wayfinder and the pinned issue's URL into the prompt, without sending it
SettingKeyDefaultMeaning
Most items per listlimit30How many open pull requests and issues to list each (1-100)
Refresh every (minutes)refreshMinutes5How often to refresh (0-120); 0 refreshes only on open, after turns and on r
Implement button fillsimplementCommand/implementThe slash command the implement button fills before the issue's URL; empty hides the button
Wayfinder button fillswayfinderCommand/wayfinderThe slash command the wayfinder and work next buttons fill before the issue's URL, and the skill whose runs pin an issue; empty hides the button and turns pinning off

A command must start with / and hold no spaces. Any other value falls back to the default, and a message says so when the session starts. A button is labelled with its command, without the /.

For example, to list fifty of each and stop the timer (how to set it):

echo '{"limit": "50", "refreshMinutes": "0"}' | claude plugin configure github-panel@claude-mods --values-stdin

Needs: the GitHub CLI, logged in, and a folder with a GitHub remote.

🏛️ archon-panel

An Archon pane in the side panel: this project's Archon workflow runs, their graphs and logs, and the approvals that wait on you. A run that needs you comes first, and the pane answers its approval, or resumes or abandons it, without leaving the session.

1: Runs 3 ⏸1  2: Graph  3: Log  4: Archon's log    ↻ ⚙️
+2 live in other projects
⏸ archon-interactive-prd  needs your approval  4m
  Draft the PRD for the 
Source 19 files
hooks/register.tsx 1061 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement, Timer } from 'claude-code'
3
4import type { ArchonActions, ArchonData, ArchonView, Detail, LogWindow, Notice, Pending, Project, Run, Tab } from '../types'
5import { deliver, hasMoved, movedElsewhere, recordLine, REPLY_MS } from './actions'
6import { actionBody, offersResume } from './actions-view'
7import { bodyWindow, lastPosition, pinnedRow, SETTINGS } from './chrome'
8import { candidates, findArchon, requirementLine } from './cli'
9import { readWorkflow } from './graph'
10import { drawNodes, graphBody } from './graph-view'
11import { EMPTY_WINDOW, isUnder, liveOf, splitChunk, take, toolSteps } from './log'
12import { logBody } from './log-view'
13import type { OpenedFile } from './log-view'
14import { claimKey, collapse, isClaimed, isMine, statusText, toastEvents } from './notify'
15import type { Runner } from './cli'
16import { parseConfig } from './config'
17import type { Config } from './config'
18import { hasEnded, liveCount, needsYou, needsYouCount, sortRuns, topRuns, waitNode } from './runs'
19import { runsBody } from './runs-view'
20import { capLines, expandHome, serveLine } from './serve-log'
21import type { Platform } from './scope'
22import { listRuns, readDetail, serverText, signature } from './source'
23import { clockTime, dollars, duration, firstLine } from './text'
24import type { DiskIo } from './source'
25
26const PANE = 'archon'
27const TITLE = 'Archon'
28/** After a main-thread turn, load only when the runs are older than this. */
29const AFTER_TURN_MS = 10_000
30/** How long each beat of a running node's flash lasts in the Graph. */
31const PULSE_MS = 500
32
33const EMPTY_DATA: ArchonData = {
34  status: 'idle',
35  loadId: 0,
36  requirement: { state: 'unchecked', path: '', version: '' },
37  project: null,
38  source: '',
39  loadedAt: 0,
40  error: '',
41  runs: [],
42  others: { live: 0, needsYou: 0 },
43  listed: [],
44  seen: {},
45  details: {},
46  graphs: {},
47}
48
49const EMPTY_VIEW: ArchonView = {
50  tab: 'runs',
51  at: { 'runs': 0, 'graph': 0, 'log': 0, 'archon-log': 0 },
52  run: '',
53  node: '',
54  fold: '',
55  file: '',
56  isFilesOpen: false,
57  fanouts: [],
58  includes: [],
59  loop: '',
60  round: 0,
61}
62
63const data = atom({ plugin: 'archon-panel', key: 'data' } as const, EMPTY_DATA)
64const view = atom({ plugin: 'archon-panel', key: 'view' } as const, EMPTY_VIEW)
65const hasStartedUp = atom({ plugin: 'archon-panel', key: 'hasStartedUp' } as const, false)
66const startedAt = atom({ plugin: 'archon-panel', key: 'startedAt' } as const, 0)
67const logWindow = atom({ plugin: 'archon-panel', key: 'log' } as const, EMPTY_WINDOW)
68const EMPTY_ACTIONS: ArchonActions = { pending: null, text: {}, sending: '', notices: {}, records: {}, checks: {} }
69const actions = atom({ plugin: 'archon-panel', key: 'actions' } as const, EMPTY_ACTIONS)
70const serveLog = atom({ plugin: 'archon-panel', key: 'serveLog' } as const, { lines: [] as string[], size: 0, isMissing: false })
71const pulse = atom({ plugin: 'archon-panel', key: 'pulse' } as const, 0)
72
73// Dies with the module on a reload; session.start or the next attach starts it again.
74let timer: Timer | undefined
75// Counts attaches, so a surfaces check answered before an attach cannot stop
76// the polling that attach kept going.
77let attaches = 0
78// The run log follower: one spawned `archon workflow logs <id> --follow`, for the one live run whose Graph or Log is in front.
79let follower: { runId: string; stream: AsyncGenerator<unknown, unknown> } | undefined
80// The Graph's flash: ticks while the followed run's Graph is in front, each redrawing it on the next beat.
81let flash: Timer | undefined
82// The file open in Log's read view, fetched only when opened.
83let opened: OpenedFile | undefined
84// A line the read view shows under its buttons, such as the prompt box refusing.
85let fileNotice = ''
86// The furthest each sub-tab can scroll, as last drawn; a scroll never goes past it.
87const furthest: Record<Tab, number> = { 'runs': 0, 'graph': 0, 'log': 0, 'archon-log': 0 }
88// Whether each log sits at its end, and so follows its tail as rows arrive.
89const atEnd: Record<'log' | 'archon-log', boolean> = { 'log': true, 'archon-log': true }
90// Whether the pane was in front when a tick or a draw last looked; undefined until one has.
91let wasInFront: boolean | undefined
92
93/**
94 * Whether any surface shows the session right now. Asked before each action
95 * the mod starts on its own and never kept: a reload or a missed attach would
96 * leave a kept flag wrong. Each mod carries its own copy (ADR-0001).
97 */
98async function isShown($: EngineInterface): Promise<boolean> {
99  return (await $.session.surfaces()).length > 0
100}
101
102/** Whether the Archon pane is the one shown, and placed: what "in front" means for polling. */
103async function isInFront($: EngineInterface): Promise<boolean> {
104  return (await $.ui.panes().catch(() => [])).some(pane => pane.id === PANE && pane.isShown && pane.isPlaced)
105}
106
107function report($: EngineInterface): (error: unknown) => void {
108  return error => $.ui.toast(`${error instanceof Error ? error.message : String(error)}`)
109}
110
111function runner($: EngineInterface): Runner {
112  return (argv, timeoutMs) => $.process.run(argv, timeoutMs === undefined ? undefined : { timeoutMs })
113}
114
115function io($: EngineInterface): DiskIo {
116  return {
117    run: runner($),
118    fetch: (url, init) => $.http.fetch(url, init),
119    sleep: ms => $.clock.sleep(ms),
120    exists: path => $.fs.exists(path),
121    list: path => $.fs.list(path),
122  }
123}
124
125async function isWindows($: EngineInterface): Promise<boolean> {
126  return (await $.env.get('OS')) === 'Windows_NT'
127}
128
129async function home($: EngineInterface): Promise<string> {
130  return ((await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? '').replace(/\\/g, '/')
131}
132
133async function platformOf($: EngineInterface): Promise<Platform> {
134  if (await isWindows($)) return 'windows'
135  return ((await $.env.get('HOME')) ?? '').startsWith('/Users/') ? 'mac' : 'linux'
136}
137
138/** The output of a git command in the session's folder; '' when git cannot say. */
139async function git($: EngineInterface, args: readonly string[]): Promise<string> {
140  const run = await $.process.run(['git', ...args]).catch(() => undefined)
141  return run?.exitCode === 0 ? run.stdout.trim() : ''
142}
143
144/**
145 * The session's primary checkout (the parent of Git's common directory) and
146 * top level; the session's folder outside Git. Worked out once per session and
147 * again on r.
148 */
149async function findProject($: EngineInterface): Promise<Project> {
150  const common = await git($, ['rev-parse', '--path-format=absolute', '--git-common-dir'])
151  const top = await git($, ['rev-parse', '--show-toplevel'])
152  if (common === '' || top === '') {
153    const cwd = await $.session.cwd()
154    return { primary: cwd, top: cwd, branch: '', ids: [], from: '' }
155  }
156  const primary = common.replace(/\\/g, '/').replace(/\/+$/, '').replace(/\/[^/]+$/, '')
157  return { primary, top, branch: await git($, ['branch', '--show-current']), ids: [], from: '' }
158}
159
160/** Checks the Requirement and keeps the result in `$.state`. */
161async function checkCli($: EngineInterface, config: Config): Promise<boolean> {
162  const places = candidates(config.archonPath, await home($), await isWindows($))
163  const requirement = await findArchon(runner($), places)
164  await update($, data, current => ({ ...current, requirement }))
165  return requirement.state === 'ok'
166}
167
168/**
169 * How long until the next poll, by what the person can see and which source
170 * answered: in front with a live run here, in front with nothing live, or
171 * behind another tab or closed (the status line and toasts only).
172 */
173function interval(source: ArchonData['source'], isFront: boolean, hasLive: boolean): number {
174  const isServer = source === 'server'
175  if (!isFront) return isServer ? 15_000 : 60_000
176  if (hasLive) return isServer ? 2_000 : 10_000
177  return isServer ? 10_000 : 30_000
178}
179
180function hasLiveRun(current: ArchonData): boolean {
181  return current.runs.some(run => !hasEnded(run))
182}
183
184function stopPolling(): void {
185  timer?.cancel()
186  timer = undefined
187}
188
189/** Polls again after `ms`; a tick that finds no surface stops it until the next attach. */
190function schedule($: EngineInterface, config: Config, ms: number): void {
191  stopPolling()
192  const own = $.clock.after(ms, () => {
193    void (async () => {
194      const seen = attaches
195      if (!(await isShown($))) {
196        if (timer === own && attaches === seen) stopPolling()
197        return
198      }
199      if (timer !== own) return
200      await load($, config)
201    })().catch(report($))
202  })
203  timer = own
204}
205
206/** Arms the next poll at the interval what the person can see now asks for. */
207async function scheduleNext($: EngineInterface, config: Config): Promise<void> {
208  const current = await read($, data)
209  if (current.requirement.state !== 'ok') return stopPolling()
210  const isFront = await isInFront($)
211  wasInFront = isFront
212  schedule($, config, interval(current.source, isFront, hasLiveRun(current)))
213}
214
215/**
216 * Loads at once when a draw finds the pane come forward since a tick or a
217 * draw last looked: no event fires when its tab is brought forward, and the
218 * tick it set while behind could be a minute off. A draw writes nothing, so
219 * the load starts from a timer of its own.
220 */
221async function loadIfForward($: EngineInterface, config: Config): Promise<void> {
222  const isFront = await isInFront($)
223  const was = wasInFront
224  wasInFront = isFront
225  if (was === false && isFront) $.clock.after(0, () => void load($, config).catch(report($)))
226}
227
228/** Whether a changed row's detail is worth reading: it is live, ended while this session watched, or picked. */
229function wantsDetail(run: Run, since: number, picked: string): boolean {
230  return !hasEnded(run) || run.completedAt >= since || run.id === picked
231}
232
233/**
234 * Loads the runs. One load at a time; a load superseded by a reload of the
235 * module is dropped by its load id. With the Requirement not met nothing is
236 * read, and polling stops until r, an attach or a reload.
237 */
238async function load($: EngineInterface, config: Config): Promise<void> {
239  let loadId = 0
240  await update($, data, (current): ArchonData => {
241    if (current.status === 'loading') return current
242    loadId = current.loadId + 1
243    return { ...current, status: 'loading', loadId }
244  })
245  if (loadId === 0) return
246  const finish = (change: (current: ArchonData) => ArchonData) =>
247    update($, data, current => (current.loadId === loadId ? change(current) : current))
248
249  const before = await read($, data)
250  if (before.requirement.state !== 'ok') {
251    stopPolling()
252    await finish(current => ({ ...current, status: 'idle' }))
253    return
254  }
255  try {
256    const project = before.project ?? (await findProject($))
257    const reader = io($)
258    const archon = before.requirement.path
259    const listing = await listRuns(reader, config.port, archon, project, await platformOf($))
260    const isServer = listing.source === 'server'
261    const since = await read($, startedAt)
262    const picked = (await read($, view)).run
263    const runs = new Map(listing.mine.map(run => [run.id, run]))
264    const details: Record<string, Detail> = {}
265    const seen: Record<string, string> = {}
266
267    // A sub-run whose parent is not listed brings the parent in by id, again only when the sub-run's row changes.
268    for (const run of listing.mine) {
269      if (run.parentId === '' || runs.has(run.parentId)) continue
270      const kept = before.runs.find(known => known.id === run.parentId)
271      if (kept !== undefined && before.seen[run.id] === signature(run)) {
272        runs.set(kept.id, kept)
273        continue
274      }
275      const parent = await readDetail(reader, config.port, archon, run.parentId, isServer, kept)
276      if (parent?.run !== undefined) {
277        runs.set(parent.run.id, parent.run)
278        details[parent.run.id] = parent.detail
279        seen[parent.run.id] = signature(parent.run)
280      }
281    }
282
283    for (const run of [...runs.values()]) {
284      const sig = seen[run.id] ?? signature(run)
285      seen[run.id] = sig
286      if (details[run.id] !== undefined) continue
287      const known = before.details[run.id]
288      if (before.seen[run.id] === sig && known !== undefined) {
289        details[run.id] = known
290        continue
291      }
292      if (before.seen[run.id] === sig || !wantsDetail(run, since, picked)) continue
293      const read = await readDetail(reader, config.port, archon, run.id, isServer, run)
294      if (read !== undefined) details[run.id] = read.detail
295    }
296
297    const mine = new Set(runs.keys())
298    const others = listing.all.filter(run => !mine.has(run.id))
299    const loadedAt = await $.clock.now()
300    await finish(current => ({
301      ...current,
302      status: 'idle',
303      error: '',
304      source: listing.source,
305      project: { ...project, ids: listing.ids, from: listing.from },
306      runs: [...runs.values()],
307      others: { live: liveCount(others), needsYou: needsYouCount(others, {}) },
308      listed: listing.all.map(run => run.id),
309      seen,
310      details,
311      loadedAt,
312    }))
313  } catch (error) {
314    const reason = error instanceof Error ? error.message : String(error)
315    await finish(current => ({ ...current, status: 'idle', error: reason }))
316  }
317  if ((await read($, data)).loadId !== loadId) return
318  await scheduleNext($, config)
319  void notify($, config).catch(report($))
320  void syncLog($, config).catch(report($))
321  await settleActions($)
322}
323
324/** A moment for another session's claim on the same toast to land before this one reads its own back. */
325const CLAIM_WAIT_MS = 300
326
327/**
328 * Sets the status line and raises this poll's toasts. Each toast is claimed
329 * in the shared store first, so one event toasts once across sessions, best
330 * effort: a session that is headless or has toasts off never claims.
331 */
332async function notify($: EngineInterface, config: Config): Promise<void> {
333  if (!(await isShown($))) return
334  const current = await read($, data)
335  $.ui.status(config.isStatusLine ? statusText(current.runs, current.details, current.others.needsYou) : undefined)
336  await prune($, current.listed)
337  if (config.toasts === 'off') return
338  const events = toastEvents(current.runs, current.details, await read($, startedAt))
339    .filter(event => config.toasts === 'all' || event.event === 'needs-you')
340  const session = await $.session.id()
341  const claimed = []
342  for (const event of events) {
343    if (isClaimed(event, await $.store.get(claimKey(event)))) continue
344    await $.store.set(claimKey(event), { session, gate: event.gate })
345    claimed.push(event)
346  }
347  if (claimed.length === 0) return
348  await $.clock.sleep(CLAIM_WAIT_MS)
349  const won = []
350  for (const event of claimed) if (isMine(await $.store.get(claimKey(event)), session)) won.push(event)
351  const toast = collapse(won)
352  if (toast !== undefined) $.ui.toast(toast.text, { timeoutMs: toast.timeoutMs })
353}
354
355/** Drops the toast claims of runs no longer among the listed rows. */
356async function prune($: EngineInterface, listed: readonly string[]): Promise<void> {
357  if (listed.length === 0) return
358  const ids = new Set(listed)
359  for (const key of await $.store.keys()) {
360    const [kind, runId] = key.split('/')
361    if (kind === 'toasted' && runId !== undefined && !ids.has(runId)) await $.store.delete(key)
362  }
363}
364
365/** Picks a run: one that needs you opens Log on its gate or wait node; any other opens its Graph. */
366async function pick($: EngineInterface, config: Config, run: Run): Promise<void> {
367  // Picking a run, even the one in front, starts its window afresh, unless it is being followed.
368  if (follower?.runId !== run.id) {
369    stopFollower()
370    await update($, logWindow, () => EMPTY_WINDOW)
371    atEnd.log = true
372  }
373  await update($, actions, (a): ArchonActions => ({ ...a, pending: null, records: Object.fromEntries(Object.entries(a.records).filter(([id]) => id === run.id)) }))
374  const current = await read($, data)
375  const need = needsYou(run, current.runs, current.details)
376  if (need === undefined) {
377    await openGraph($, config, run.id)
378    return
379  }
380  await changeView($, config, (v): ArchonView => ({ ...v, tab: 'log', run: need.holder.id, node: waitNode(need.standing), file: '' }))
381}
382
383/** Reads a run's graph once from its frozen workflow source, which never changes. */
384async function ensureGraph($: EngineInterface, runId: string): Promise<void> {
385  const current = await read($, data)
386  const run = current.runs.find(r => r.id === runId)
387  if (run === undefined || current.graphs[runId] !== undefined) return
388  const nodes = await readWorkflow({ list: path => $.fs.list(path), read: path => $.fs.read(path) }, run.sourceRoot, run.workflow)
389  await update($, data, (d): ArchonData => ({ ...d, graphs: { ...d.graphs, [runId]: nodes } }))
390}
391
392/** Picks a box in the Graph: a node opens Log cut to it; a block, loop or sub-run box opens what it folds. */
393async function pickNode($: EngineInterface, config: Config, runId: string, id: string): Promise<void> {
394  const current = await read($, data)
395  const shown = await read($, view)
396  const run = current.runs.find(r => r.id === runId)
397  const nodes = current.graphs[runId]
398  if (run === undefined) return
399  if (id.includes('.')) {
400    await openNode($, config, run, id)
401    return
402  }
403  const pickOf = nodes === undefined || nodes === null ? undefined : drawNodes(nodes, run, current.runs, current.details, shown).picks.get(id)
404  if (pickOf?.kind === 'block') {
405    const key = `${runId}:${pickOf.id}`
406    await update($, view, (v): ArchonView => ({ ...v, includes: v.includes.includes(key) ? v.includes : [...v.includes, key] }))
407  } else if (pickOf?.kind === 'loop') {
408    const key = `${runId}:${pickOf.id}`
409    await update($, view, (v): ArchonView => ({ ...v, loop: v.loop === key ? '' : key, round: 0 }))
410  } else if (pickOf?.kind === 'workflow' && pickOf.subRuns.length > 0) {
411    const waiting = pickOf.subRuns.find(subRun => needsYou(subRun, current.runs, current.details) !== undefined)
412    if (waiting !== undefined) await pick($, config, waiting)
413    else if (pickOf.subRuns.length > 1) {
414      const key = `${runId}:${pickOf.id}`
415      await update($, view, (v): ArchonView => ({ ...v, fanouts: v.fanouts.includes(key) ? v.fanouts.filter(f => f !== key) : [...v.fanouts, key] }))
416    } else await openGraph($, config, pickOf.subRuns[0]!.id)
417  } else {
418    await openNode($, config, run, id)
419  }
420}
421
422/**
423 * Opens Log cut to a node. A finished run whose window lost that node's rows
424 * off its top refills it with one replay of that node's rows.
425 */
426async function openNode($: EngineInterface, config: Config, run: Run, node: string): Promise<void> {
427  await changeView($, config, (v): ArchonView => ({ ...v, tab: 'log', run: run.id, node, file: '' }))
428  const win = await read($, logWindow)
429  if (hasEnded(run) && win.runId === run.id && win.dropped > 0 && !win.rows.some(row => row.nodes.includes(node))) await replay($, config, run, node)
430}
431
432/** `a`: Log widened to all nodes, back to the run's newest rows. */
433async function showAll($: EngineInterface, config: Config): Promise<void> {
434  await update($, view, (v): ArchonView => ({ ...v, node: '' }))
435  const current = await read($, data)
436  const picked = (await read($, view)).run
437  const run = current.runs.find(r => r.id === picked)
438  const win = await read($, logWindow)
439  if (run !== undefined && win.runId === run.id && win.node !== '') {
440    if (hasEnded(run)) await replay($, config, run)
441    else {
442      stopFollower()
443      await update($, logWindow, () => EMPTY_WINDOW)
444      await syncLog($, config)
445    }
446  }
447}
448
449/** Shows a run's Graph, reading its source the first time. */
450/** Opens a run's Graph, and follows its run log at once while it is live. */
451async function openGraph($: EngineInterface, config: Config, runId: string): Promise<void> {
452  await update($, view, (v): ArchonView => ({ ...v, tab: 'graph', run: runId, node: '' }))
453  await ensureGraph($, runId)
454  await syncLog($, config)
455}
456
457/** Reads one run again by id, keeping its row and detail: before an action, and when its follower ends. */
458async function refreshRun($: EngineInterface, config: Config, runId: string): Promise<{ run: Run; detail: Detail } | undefined> {
459  const current = await read($, data)
460  const known = current.runs.find(r => r.id === runId)
461  const got = await readDetail(io($), config.port, current.requirement.path, runId, current.source !== 'cli', known).catch(() => undefined)
462  if (got?.run === undefined) return undefined
463  const run = got.run
464  await update($, data, (d): ArchonData => ({
465    ...d,
466    runs: d.runs.some(r => r.id === run.id) ? d.runs.map(r => (r.id === run.id ? run : r)) : [...d.runs, run],
467    details: { ...d.details, [run.id]: got.detail },
468  }))
469  return { run, detail: got.detail }
470}
471
472/** A finished run's end line: `✓ completed 37m $4.12`, or how it failed. */
473function endLine(run: Run, detail: Detail | undefined): string {
474  const spent = duration(run.completedAt - run.startedAt)
475  const cost = run.costUsd > 0 ? ` ${dollars(run.costUsd)}` : ''
476  if (run.status === 'completed') return `✓ completed ${spent}${cost}`
477  if (run.status === 'cancelled') return `✗ cancelled ${spent}${cost}`
478  const failed = [...(detail?.events ?? [])].reverse().find(e => e.type === 'node_failed')
479  const error = firstLine(failed?.error ?? '')
480  return `✗ failed ${spent}${cost}${failed === undefined ? '' : ` at ${failed.step}`}${error === '' ? '' : `: ${error}`}`
481}
482
483function stopFollower(): void {
484  const own = follower
485  follower = undefined
486  stopFlash()
487  void own?.stream.return(undefined).catch(() => {})
488}
489
490function stopFlash(): void {
491  flash?.cancel()
492  flash = undefined
493}
494
495/**
496 * Flashes the running nodes of the followed run's Graph: one tick per beat
497 * redraws it, until a tick finds the Graph of that run no longer in front.
498 */
499function startFlash($: EngineInterface): void {
500  if (flash !== undefined) return
501  const own = $.clock.every(PULSE_MS, () => {
502    void (async () => {
503      const shown = await read($, view)
504      if (flash !== own) return
505      if (shown.tab !== 'graph' || follower?.runId !== shown.run || !(await isInFront($))) {
506        if (flash === own) stopFlash()
507        return
508      }
509      await update($, pulse, beat => beat + 1)
510    })().catch(report($))
511  })
512  flash = own
513}
514
515/**
516 * Follows a live run's log with `archon workflow logs <id> --follow`, which
517 * starts at line 1 and exits once the run reaches a final status. A spawn
518 * delivers chunks, not lines, so a partial last line waits for the next. A
519 * restart after a reload replays from line 1, skipping the lines already taken.
520 */
521async function follow($: EngineInterface, config: Config, runId: string): Promise<void> {
522  const archon = (await read($, data)).requirement.path
523  let win = await read($, logWindow)
524  if (win.runId !== runId || win.node !== '') {
525    win = { ...EMPTY_WINDOW, runId }
526    await update($, logWindow, () => win)
527  }
528  const skip = win.taken
529  const stream = $.process.spawn({ argv: [archon, 'workflow', 'logs', runId, '--follow'] })
530  const own = { runId, stream }
531  follower = own
532  let held = ''
533  let lineNo = 0
534  let isOver: boolean
535  let code: number | null = null
536  try {
537    for await (const chunk of stream) {
538      if (follower !== own) break
539      if (chunk.stream !== 'stdout') continue
540      const split = splitChunk(held, chunk.text)
541      held = split.held
542      const from = lineNo
543      lineNo += split.lines.length
544      if (split.lines.length > 0) await update($, logWindow, (w): LogWindow => (w.runId === runId ? take(w, split.lines, from, skip) : w))
545    }
546    isOver = follower === own
547    if (isOver) code = (await stream.result).code
548  } catch {
549    isOver = follower === own
550  } finally {
551    if (follower === own) follower = undefined
552  }
553  if (!isOver) return
554  if (code !== 0 && lineNo === 0) await update($, logWindow, (w): LogWindow => (w.runId === runId ? { ...w, isMissing: true } : w))
555  const got = await refreshRun($, config, runId)
556  if (got !== undefined && hasEnded(got.run)) {
557    await update($, logWindow, (w): LogWindow => (w.runId === runId ? { ...w, end: endLine(got.run, got.detail) } : w))
558  }
559}
560
561/** A finished run's log, in one `archon workflow logs <id>`; with `node`, only that node's rows are kept. */
562async function replay($: EngineInterface, config: Config, run: Run, node = ''): Promise<void> {
563  const archon = (await read($, data)).requirement.path
564  const out = await runner($)([archon, 'workflow', 'logs', run.id]).catch(() => undefined)
565  if ((await read($, data)).details[run.id] === undefined) await refreshRun($, config, run.id)
566  const detail = (await read($, data)).details[run.id]
567  const steps = toolSteps(detail?.events ?? [])
568  let win: LogWindow = { ...EMPTY_WINDOW, runId: run.id, node }
569  if (out?.exitCode === 0) win = take(win, out.stdout.replace(/\n$/, '').split('\n'), 0, 0, row => isUnder(row, node, steps))
570  else win = { ...win, isMissing: true }
571  const latest = (await read($, data)).runs.find(r => r.id === run.id) ?? run
572  if (hasEnded(latest)) win = { ...win, end: endLine(latest, detail) }
573  await update($, logWindow, () => win)
574}
575
576/**
577 * Keeps the run log in step with what the person sees: the follower runs only
578 * while a live run's Graph or Log is in front, one run at a time, and the Graph
579 * flashes while it runs; a finished run's log is replayed once, and its window
580 * kept until another run is picked.
581 */
582async function syncLog($: EngineInterface, config: Config): Promise<void> {
583  const current = await read($, data)
584  const shown = await read($, view)
585  if (shown.tab === 'archon-log' && (await isShown($)) && (await isInFront($))) await readServeLog($, config)
586  const run = current.runs.find(r => r.id === shown.run)
587  const isWanted = run !== undefined && (shown.tab === 'log' || shown.tab === 'graph') && current.requirement.state === 'ok' && (await isShown($)) && (await isInFront($))
588  if (!isWanted || run === undefined) return stopFollower()
589  if (!hasEnded(run)) {
590    if (follower?.runId !== run.id) {
591      stopFollower()
592      void follow($, config, run.id).catch(report($))
593    }
594    if (shown.tab === 'graph') startFlash($)
595    else stopFlash()
596    return
597  }
598  if (follower?.runId === run.id) return
599  stopFollower()
600  if (shown.tab !== 'log') return
601  const win = await read($, logWindow)
602  if (win.runId !== run.id) await replay($, config, run)
603}
604
605/** Reads Archon's log while its sub-tab is in front, keeping the newest lines under 60,000 characters. */
606async function readServeLog($: EngineInterface, config: Config): Promise<void> {
607  const path = expandHome(config.archonLog, await home($))
608  const text = await $.fs.read(path).catch(() => undefined)
609  await update($, serveLog, () => (text === undefined
610    ? { lines: [], size: 0, isMissing: true }
611    : { lines: capLines(text.split(/\r?\n/).filter(line => line !== '')), size: text.length, isMissing: false }))
612}
613
614/** Changes what the person sees, then brings the run log in step. */
615async function changeView($: EngineInterface, config: Config, change: (v: ArchonView) => ArchonView): Promise<void> {
616  const was = await read($, view)
617  await update($, view, change)
618  const now = await read($, view)
619  // A change of run or sub-tab drops the pending action; any typed text stays.
620  if (now.tab !== was.tab || now.run !== was.run) await update($, actions, (a): ArchonActions => (a.pending === null ? a : { ...a, pending: null }))
621  await syncLog($, config)
622}
623
624/** Where a run's file is on disk. */
625function filePath(run: Run, path: string): string {
626  return `${run.outputRoot.replace(/\\/g, '/').replace(/\/+$/, '')}/artifacts/runs/${run.id}/${path}`
627}
628
629/** Opens one of the run's files in Log's read view: from the server while it answers, else from disk. */
630async function openFile($: EngineInterface, config: Config, path: string): Promise<void> {
631  const current = await read($, data)
632  const shown = await read($, view)
633  const run = current.runs.find(r => r.id === shown.run)
634  await update($, view, (v): ArchonView => ({ ...v, tab: 'log', file: path }))
635  fileNotice = ''
636  if (run === undefined) return
637  const listed = current.details[run.id]?.files.find(file => file.path === path)
638  let text: string | undefined
639  if (current.source === 'server') {
640    const got = await serverText(io($), `http://localhost:${config.port}/api/artifacts/${encodeURIComponent(run.id)}/${path.split('/').map(encodeURIComponent).join('/')}`)
641    text = got?.text
642  }
643  if (text === undefined) text = await $.fs.read(filePath(run, path)).catch(() => undefined)
644  opened = { path, text: text ?? '', isBinary: text !== undefined && text.includes('\u0000'), size: listed?.size ?? text?.length ?? 0 }
645  if (text === undefined) fileNotice = "This file can't be read."
646  $.ui.invalidate('ui.render')
647}
648
649/** Opens the file with the platform's opener, in the terminal only; elsewhere, or when no opener starts, its path is copied. */
650async function openOutside($: EngineInterface, surface: string): Promise<void> {
651  const current = await read($, data)
652  const shown = await read($, view)
653  const run = current.runs.find(r => r.id === shown.run)
654  if (run === undefined || shown.file === '') return
655  const path = filePath(run, shown.file)
656  const windows = await isWindows($)
657  const native = windows ? path.replace(/\//g, '\\') : path
658  if (surface === 'terminal') {
659    const root = ((await $.env.get('SystemRoot')) ?? 'C:\\Windows').replace(/\\+$/, '')
660    const openers = windows ? [[`${root}\\explorer.exe`, native]] : [['open', path], ['xdg-open', path]]
661    for (const argv of openers) {
662      const ran = await $.process.run(argv).catch(() => undefined)
663      // explorer.exe can exit 1 when it opened the file, so its exit code is not trusted.
664      if (ran !== undefined && (windows || ran.exitCode === 0)) return
665    }
666  }
667  await $.ui.copy({ text: native }).catch(() => undefined)
668}
669
670/** Adds `@<absolute path>` to the prompt box, wherever a surface has one. */
671async function mention($: EngineInterface): Promise<void> {
672  const current = await read($, data)
673  const shown = await read($, view)
674  const run = current.runs.find(r => r.id === shown.run)
675  if (run === undefined || shown.file === '') return
676  const filled = await $.prompt.fill({ text: `@${filePath(run, shown.file)} `, mode: 'append' }).catch(() => undefined)
677  if (filled?.isFilled !== true) {
678    fileNotice = "can't reach the prompt here"
679    $.ui.invalidate('ui.render')
680  }
681}
682
683function setNotices($: EngineInterface, runId: string, notices: Notice[]): Promise<unknown> {
684  return update($, actions, (a): ArchonActions => ({ ...a, notices: { ...a.notices, [runId]: notices } }))
685}
686
687/**
688 * Sends the confirmed action. Just before, the run is fetched again: one that
689 * no longer needs you gets nothing. The call goes where the run lives, with 30 s
690 * to reply; a refusal shows Archon's own words. Nothing here ever toasts.
691 */
692async function send($: EngineInterface, config: Config): Promise<void> {
693  const before = await read($, actions)
694  const pending = before.pending
695  if (pending === null || before.sending !== '') return
696  const runId = pending.runId
697  const text = before.text[runId] ?? ''
698  const word = pending.kind === 'answer' ? `Sending ${pending.decision}…` : pending.kind === 'resume' ? '… resuming' : '… abandoning'
699  await update($, actions, (a): ArchonActions => ({ ...a, pending: null, sending: runId, notices: { ...a.notices, [runId]: [{ text: word, tone: 'dim' }] } }))
700  try {
701    const got = await refreshRun($, config, runId)
702    const current = await read($, data)
703    const race = movedElsewhere(pending, got?.run, current.runs, got?.detail)
704    if (race !== undefined) {
705      await setNotices($, runId, [{ text: race, tone: 'dim' }])
706      return
707    }
708    const run = got?.run ?? current.runs.find(r => r.id === runId)
709    if (run === undefined) return
710    const reply = await deliver(io($), config.port, current.requirement.path, pending, run, text, current.source === 'server')
711    if (reply.kind === 'silent') {
712      await setNotices($, runId, [{ text: 'No reply from Archon in 30 s; it may still have gone through', tone: 'error' }])
713      return
714    }
715    if (reply.kind === 'refused') {
716      await setNotices($, runId, [{ text: reply.message, tone: 'error' }])
717      return
718    }
719    const now = await $.clock.now()
720    const isChatResume = pending.kind === 'resume' && reply.via === 'server'
721    const record = pending.kind === 'answer'
722      ? recordLine(pending.decision, pending.label, text, now)
723      : pending.kind === 'abandon' ? `✗ abandoned by you ${clockTime(now)}` : isChatResume ? `▶ sent to its chat ${clockTime(now)}` : `▶ resumed by you ${clockTime(now)}`
724    const isChecked = pending.kind !== 'abandon' && (reply.via === 'cli' || isChatResume)
725    await update($, actions, (a): ArchonActions => ({
726      ...a,
727      text: pending.kind === 'answer' ? { ...a.text, [runId]: '' } : a.text,
728      records: { ...a.records, [run.id]: [...(a.records[run.id] ?? []), record] },
729      notices: { ...a.notices, [runId]: reply.message === '' || reply.via === 'cli' ? [] : [{ text: reply.message, tone: 'dim' }] },
730      checks: isChecked ? { ...a.checks, [run.id]: { kind: pending.kind === 'answer' ? 'answer' : 'resume', at: now, polls: 0, log: reply.log, text, isChat: isChatResume } } : a.checks,
731    }))
732    // A --detach answer or resume is checked on once 30 s have passed; a chat resume over the next two polls.
733    if (isChecked && !isChatResume) $.clock.after(REPLY_MS, () => void checkMoved($, config, run.id).catch(report($)))
734  } finally {
735    await update($, actions, (a): ArchonActions => ({ ...a, sending: a.sending === runId ? '' : a.sending }))
736    await refreshRun($, config, runId)
737  }
738}
739
740/** 30 s after a `--detach` answer or resume: a gate still unanswered, or a run still paused, says so, and the buttons come back with the text. */
741async function checkMoved($: EngineInterface, config: Config, runId: string): Promise<void> {
742  const check = (await read($, actions)).checks[runId]
743  if (check === undefined) return
744  const got = await refreshRun($, config, runId)
745  const runs = (await read($, data)).runs
746  const moved = hasMoved(got?.run, runs, got?.detail, check.kind)
747  await update($, actions, (a): ArchonActions => {
748    const { [runId]: _done, ...checks } = a.checks
749    void _done
750    if (moved) return { ...a, checks }
751    const said = check.kind === 'answer' ? "Archon accepted the answer but hasn't recorded it" : "Archon accepted the resume but the run hasn't moved"
752    return {
753      ...a,
754      checks,
755      text: check.text === '' ? a.text : { ...a.text, [runId]: check.text },
756      notices: { ...a.notices, [runId]: [{ text: `${said}${check.log === '' ? '.' : `; its log is ${check.log}`}`, tone: 'error' }] },
757    }
758  })
759}
760
761/**
762 * After each poll: a pending confirmation for a run that no longer needs you
763 * is dropped, its typed text left on screen, dim, to copy; a resume sent to a
764 * chat that is still paused two polls later says to check the chat.
765 */
766async function settleActions($: EngineInterface): Promise<void> {
767  const current = await read($, data)
768  await update($, actions, (a): ArchonActions => {
769    let next = a
770    const pending = a.pending
771    if (pending !== null) {
772      const run = current.runs.find(r => r.id === pending.runId)
773      const race = movedElsewhere(pending, run, current.runs, current.details[pending.runId])
774      if (race !== undefined) {
775        const typed = a.text[pending.runId] ?? ''
776        next = { ...next, pending: null, notices: { ...next.notices, [pending.runId]: [{ text: race, tone: 'dim' }, ...(typed === '' ? [] : [{ text: typed, tone: 'dim' as const }])] } }
777      }
778    }
779    for (const [runId, check] of Object.entries(a.checks)) {
780      if (!check.isChat) continue
781      const run = current.runs.find(r => r.id === runId)
782      const polls = check.polls + 1
783      const { [runId]: _done, ...rest } = next.checks
784      void _done
785      if (run === undefined || run.status !== 'paused') next = { ...next, checks: rest }
786      else if (polls >= 2) next = { ...next, checks: rest, notices: { ...next.notices, [runId]: [{ text: 'still paused: check its chat', tone: 'dim' }] } }
787      else next = { ...next, checks: { ...next.checks, [runId]: { ...check, polls } } }
788    }
789    return next
790  })
791}
792
793/** The run that has needed you longest, a sub-run's gate counted like any other; undefined with none. */
794function longestWaiting(current: ArchonData): Run | undefined {
795  return sortRuns(topRuns(current.runs), current.runs, current.details).find(run => needsYou(run, current.runs, current.details) !== undefined)
796}
797
798/** Whether mod-settings is installed: the gear shows only then. A command list that cannot be read shows none. */
799async function isSettingsInstalled($: EngineInterface): Promise<boolean> {
800  return (await $.command.list().catch(() => [])).some(command => command.name === SETTINGS)
801}
802
803/**
804 * Rechecks the CLI and the project, then loads: at start, on attach, on reload
805 * and on r. A missing Requirement stops polling and takes down a status line
806 * set while the CLI was there.
807 */
808async function reload($: EngineInterface, config: Config): Promise<void> {
809  const project = await findProject($)
810  await update($, data, current => ({ ...current, project }))
811  if (await checkCli($, config)) await load($, config)
812  else {
813    stopPolling()
814    $.ui.status(undefined)
815  }
816}
817
818/** The start-up work: loads, then opens the pane unasked when `isPaneWanted` and this project has a live run. */
819async function startUp($: EngineInterface, config: Config, isPaneWanted: boolean): Promise<void> {
820  await reload($, config)
821  const current = await read($, data)
822  if (isPaneWanted && current.requirement.state === 'ok' && hasLiveRun(current)) await $.ui.open({ id: PANE, title: TITLE })
823}
824
825export const register: Register = (on, options) => {
826  const config = parseConfig(options)
827
828  on('session.start', async ($, e, next) => {
829    await $.command.register({ name: 'archon', description: "Open the Archon pane: this project's workflow runs, their graphs and logs, and the approvals that wait on you" })
830    const now = await $.clock.now()
831    await update($, startedAt, was => (was === 0 ? now : was))
832    // A reload killed any load in flight: drop its loading state and its result.
833    await update($, data, (current): ArchonData => ({
834      ...current,
835      status: 'idle',
836      loadId: current.loadId + 1,
837    }))
838    stopPolling()
839    // The follower died with the old module; the load below starts it again from line 1 if a live run's Graph or Log is in front.
840    stopFollower()
841    for (const tab of Object.keys(furthest) as Tab[]) furthest[tab] = 0
842    // A headless session does nothing until a surface attaches (session.attach).
843    if (await isShown($)) {
844      const isFirst = !(await read($, hasStartedUp))
845      await update($, hasStartedUp, () => true)
846      void (isFirst ? startUp($, config, true) : reload($, config)).catch(report($))
847    }
848    return next(e)
849  })
850
851  on('session.attach', async ($, e, next) => {
852    attaches += 1
853    const done = await next(e)
854    let isFirst = false
855    await update($, hasStartedUp, was => {
856      isFirst = !was
857      return true
858    })
859    // A session that started headless catches up once. The pane opens unasked
860    // only on a surface that docks it beside the conversation; elsewhere, such as
861    // on a phone, it waits for /archon.
862    if (isFirst) void startUp($, config, e.viewport?.isFullscreen === true).catch(report($))
863    else if (timer === undefined) void reload($, config).catch(report($))
864    return done
865  })
866
867  on('session.detach', async ($, e, next) => {
868    const seen = attaches
869    const done = await next(e)
870    if (!(await isShown($)) && attaches === seen) {
871      stopPolling()
872      stopFollower()
873    }
874    return done
875  })
876
877  on('turn.complete', async ($, e, next) => {
878    const done = await next(e)
879    if (e.agentId !== undefined || !(await isShown($))) return done
880    const current = await read($, data)
881    if (current.requirement.state === 'ok' && (await $.clock.now()) - current.loadedAt > AFTER_TURN_MS) void load($, config).catch(report($))
882    return done
883  })
884
885  on('command.run', { command: 'archon' }, async $ => {
886    // Focus brings the pane in front of another mod's tab and gives it the keys.
887    await $.ui.open({ id: PANE, title: TITLE, focus: true })
888    void (async () => {
889      await reload($, config)
890      const longest = longestWaiting(await read($, data))
891      if (longest !== undefined) await pick($, config, longest)
892      else await changeView($, config, (v): ArchonView => ({ ...v, tab: 'runs' }))
893    })().catch(report($))
894    return { text: 'Archon pane opened.' }
895  })
896
897  on('ui.scroll', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
898    // The engine's window stays at 0 so the pinned row never scrolls away; the shown sub-tab moves itself.
899    await update($, view, (v): ArchonView => {
900      const isLog = v.tab === 'log' || v.tab === 'archon-log'
901      const from = isLog && atEnd[v.tab as 'log'] ? furthest[v.tab] : v.at[v.tab]
902      const at = Math.min(Math.max(0, from + e.by), furthest[v.tab])
903      if (isLog) atEnd[v.tab as 'log'] = at >= furthest[v.tab]
904      return at === v.at[v.tab] ? v : { ...v, at: { ...v.at, [v.tab]: at } }
905    })
906    return next({ ...e, offset: 0 })
907  })
908
909  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
910    const ui = $.ui.resolve(e)
911    const { Box, Text } = ui
912    void loadIfForward($, config).catch(report($))
913    const current = await read($, data)
914    const shown = await read($, view)
915    const line = requirementLine(current.requirement)
916    const width = Math.max(16, e.props.bodyColumns)
917    const bodyRows = e.props.scroll.bodyRows
918    const serverLine = `Archon's server isn't answering on port ${config.port}, so runs come from the CLI every ${interval('cli', true, hasLiveRun(current)) / 1000} s. archon serve makes them faster.`
919    let lines: RenderElement[]
920    let isResumeShown = false
921    if (line !== undefined) lines = [<Text wrap="wrap">{line}</Text>]
922    else if (shown.tab === 'runs') {
923      lines = runsBody({
924        ui,
925        data: current,
926        view: shown,
927        now: await $.clock.now(),
928        width,
929        platform: await platformOf($),
930        serverLine,
931        linkBase: current.source === 'server' && e.surface !== 'mobile' ? `http://localhost:${config.port}/console/r/` : '',
932        onPick: run => void pick($, config, run).catch(report($)),
933        onFanout: id => void update($, view, (v): ArchonView => ({ ...v, fanouts: v.fanouts.includes(id) ? v.fanouts.filter(f => f !== id) : [...v.fanouts, id] })).catch(report($)),
934      })
935    } else if (shown.tab === 'graph') {
936      const run = current.runs.find(r => r.id === shown.run)
937      if (run !== undefined && current.graphs[run.id] === undefined) void ensureGraph($, run.id).catch(report($))
938      const win = await read($, logWindow)
939      const isFollowed = run !== undefined && follower?.runId === run.id && win.runId === run.id && win.node === ''
940      lines = graphBody({
941        ui,
942        run,
943        runs: current.runs,
944        details: current.details,
945        nodes: run === undefined ? undefined : current.graphs[run.id],
946        view: shown,
947        live: isFollowed ? liveOf(win) : undefined,
948        pulse: flash === undefined || (await read($, pulse)) % 2 === 0,
949        now: await $.clock.now(),
950        width,
951        link: run !== undefined && current.source === 'server' && e.surface !== 'mobile' ? `http://localhost:${config.port}/console/r/${run.id}` : '',
952        onPick: id => void pickNode($, config, shown.run, id).catch(report($)),
953        onFold: block => void update($, view, (v): ArchonView => ({ ...v, includes: v.includes.filter(entry => entry !== `${shown.run}:${block}`) })).catch(report($)),
954        onRound: round => void update($, view, (v): ArchonView => ({ ...v, round })).catch(report($)),
955        onParent: parent => void openGraph($, config, parent.id).catch(report($)),
956        onSubRun: subRun => void openGraph($, config, subRun.id).catch(report($)),
957      })
958    } else if (shown.tab === 'archon-log') {
959      const served = await read($, serveLog)
960      lines = served.isMissing
961        ? [<Text dimColor wrap="wrap">{`No Archon's log at ${config.archonLog}. Point Archon's log in the mod settings at the file archon serve is redirected to.`}</Text>]
962        : served.lines.map(text => {
963          const drawn = serveLine(text)
964          return <Text wrap="wrap" {...(drawn.tone === undefined ? {} : { color: drawn.tone })}>{drawn.text}</Text>
965        })
966    }
967    else {
968      const run = current.runs.find(r => r.id === shown.run)
969      const acts = await read($, actions)
970      const top = run === undefined ? undefined : topRuns(current.runs).find(t => needsYou(t, current.runs, current.details)?.holder.id === run.id)
971      const need = top === undefined ? undefined : needsYou(top, current.runs, current.details)
972      const link = run !== undefined && current.source === 'server' && e.surface !== 'mobile' ? `http://localhost:${config.port}/console/r/${run.id}` : ''
973      if (run !== undefined && need !== undefined && current.graphs[run.id] === undefined) void ensureGraph($, run.id).catch(report($))
974      const logLines = logBody({
975        ui,
976        run,
977        runs: current.runs,
978        detail: run === undefined ? undefined : current.details[run.id],
979        window: await read($, logWindow),
980        view: shown,
981        width,
982        link: run !== undefined && current.source === 'server' && e.surface !== 'mobile' ? `http://localhost:${config.port}/console/r/${run.id}` : '',
983        filesFolder: run === undefined ? '' : filePath(run, '').replace(/\/$/, ''),
984        file: opened,
985        notice: fileNotice,
986        onFold: key => void update($, view, (v): ArchonView => ({ ...v, fold: v.fold === key ? '' : key })).catch(report($)),
987        onAll: () => void showAll($, config).catch(report($)),
988        onFiles: () => void update($, view, (v): ArchonView => ({ ...v, isFilesOpen: !v.isFilesOpen })).catch(report($)),
989        onFile: path => void openFile($, config, path).catch(report($)),
990        onBack: () => void update($, view, (v): ArchonView => ({ ...v, file: '' })).catch(report($)),
991        onOpen: () => void openOutside($, e.surface).catch(report($)),
992        onMention: () => void mention($).catch(report($)),
993      })
994      const holderId = run?.id ?? ''
995      const notes: RenderElement[] = [
996        ...(acts.records[holderId] ?? []).map(record => <Text {...(record.startsWith('✗') ? { color: 'error' as const } : {})}>{record}</Text>),
997        ...(acts.notices[holderId] ?? []).map(notice => (notice.tone === 'error'
998          ? <Text color="error" wrap="wrap">{notice.text}</Text>
999          : notice.tone === 'dim' ? <Text dimColor wrap="wrap">{notice.text}</Text> : <Text wrap="wrap">{notice.text}</Text>)),
1000      ]
1001      if (run !== undefined && need !== undefined && shown.file === '') {
1002        const set = (change: (a: ArchonActions) => ArchonActions) => void update($, actions, change).catch(report($))
1003        const ask = (kind: Pending['kind'], decision = '', label = '') => set((a): ArchonActions => ({ ...a, pending: { runId: run.id, kind, decision, label } }))
1004        isResumeShown = offersResume({ run: top!, need, detail: current.details[run.id], actions: acts })
1005        const files = (current.details[run.id]?.files ?? []).map(file => (
1006          <ui.Button key={`file-${file.path}`} plain label={`${file.path}  ${Math.round(file.size / 1024) === 0 ? `${file.size} B` : `${Math.round(file.size / 1024)} KB`}`} onPress={() => void openFile($, config, file.path).catch(report($))} />
1007        ))
1008        lines = [
1009          ...actionBody({
1010            ui,
1011            surface: e.surface,
1012            run: top!,
1013            need,
1014            parent: current.runs.find(r => r.id === run.parentId),
1015            detail: current.details[run.id],
1016            graph: current.graphs[run.id],
1017            actions: acts,
1018            now: await $.clock.now(),
1019            width,
1020            isServer: current.source === 'server',
1021            link,
1022            isCut: shown.node !== '',
1023            log: logLines.slice(1),
1024            files,
1025            onDecide: (decision, label) => ask('answer', decision, label),
1026            onResume: () => ask('resume'),
1027            onAbandon: () => ask('abandon'),
1028            onConfirm: () => void send($, config).catch(report($)),
1029            onBack: () => set((a): ArchonActions => ({ ...a, pending: null })),
1030            onText: text => set((a): ArchonActions => ({ ...a, text: { ...a.text, [run.id]: text } })),
1031            onAll: () => void showAll($, config).catch(report($)),
1032          }),
1033          ...notes,
1034        ]
1035      } else lines = [...logLines, ...notes]
1036    }
1037    // The logs follow their tail while at their end.
1038    const last = lastPosition(lines.length, bodyRows)
1039    const isLog = shown.tab === 'log' || shown.tab === 'archon-log'
1040    const at = isLog && atEnd[shown.tab as 'log'] ? last : shown.at[shown.tab]
1041    furthest[shown.tab] = last
1042    return (
1043      <Box flexDirection="column" width={width}>
1044        {pinnedRow({
1045          ui,
1046          width,
1047          shown: shown.tab,
1048          live: liveCount(current.runs),
1049          needsYou: needsYouCount(current.runs, current.details),
1050          hasSettings: await isSettingsInstalled($),
1051          isReloadKey: !isResumeShown,
1052          onTab: tab => void changeView($, config, (v): ArchonView => ({ ...v, tab })).catch(report($)),
1053          onReload: () => void reload($, config).catch(report($)),
1054          onSettings: () => void $.command.run({ command: SETTINGS }).catch(report($)),
1055        })}
1056        {bodyWindow(ui, lines, at, bodyRows)}
1057      </Box>
1058    )
1059  })
1060}
1061
hooks/actions.ts 200 lines
1// Acting on a run that needs you: answering an approval, and resuming or
2// abandoning a run on action needed or left paused by a sub-run that ended.
3// Nothing else is ever done to a run. Each action goes where the run lives
4// (ADR-0006).
5
6import type { Detail, Gate, Pending, Run } from '../types'
7import { hasEnded, standing } from './runs'
8import { isTimedOut, within } from './source'
9import type { Io } from './source'
10import { clockTime, firstLine, lastLine } from './text'
11
12/** Letters an answer never takes: reload, all nodes, back, open, abandon, and approve's and reject's own. */
13const RESERVED = new Set(['r', 'a', 'b', 'o', 'x', 'y', 'n'])
14
15export type AnswerButton = {
16  decision: string
17  letter: string
18  label: string
19  isPrimary: boolean
20}
21
22/**
23 * One button per decision the gate declares, in the workflow's order and
24 * words: approve is `y`, reject is `n`, any other the first free letter of
25 * its label. The labels carry their consequences: what a reject cancels, and
26 * what a bare approve does at a loop gate whose round said it is done.
27 */
28export function answerButtons(gate: Gate, run: Run, parent: Run | undefined, text: string): AnswerButton[] {
29  const used = new Set<string>()
30  const letterOf = (id: string, label: string) => {
31    if (id === 'approve') return 'y'
32    if (id === 'reject') return 'n'
33    const free = Array.from(label.toLowerCase()).find(ch => /[a-z]/.test(ch) && !RESERVED.has(ch) && !used.has(ch))
34    return free ?? ''
35  }
36  return gate.decisions.map(decision => {
37    const letter = letterOf(decision.id, decision.label)
38    used.add(letter)
39    let label = decision.label
40    if (decision.id === 'reject') {
41      if (parent !== undefined) label = `${label} (cancels this sub-run; ${parent.workflow} stays paused)`
42      else if (!gate.hasRework) label = `${label} (cancels the run)`
43    }
44    if (decision.id === 'approve' && gate.type === 'interactive_loop' && gate.isRoundDone) label = text.trim() === '' ? 'Approve and finish' : 'Another round'
45    return { decision: decision.id, letter, label: letter === '' ? label : `${letter}: ${label}`, isPrimary: decision.id === 'approve' }
46  })
47}
48
49/** Where an action goes: the CLI, the server, or nowhere (a chat run's resume). */
50export type Route =
51  | { via: 'cli'; argv: string[] }
52  | { via: 'server'; path: string; body: string }
53  | { via: 'none' }
54
55/** A chat platform's name as the pane says it: `Slack`, `Telegram`, `GitHub`. */
56export function platformName(platform: string): string {
57  return platform === 'github' ? 'GitHub' : platform === '' ? '' : `${platform[0]!.toUpperCase()}${platform.slice(1)}`
58}
59
60/**
61 * Routes an action where the run lives (ADR-0006). A CLI-started run (no
62 * parent conversation) always goes through the CLI, answers and resumes
63 * `--detach`. A run from the web UI or a chat goes through the server while it
64 * answers, else the same CLI call. A chat run is never resumed from the pane,
65 * and abandon, with nothing to route back, goes through the CLI for it.
66 */
67export function route(pending: Pending, run: Run, text: string, isServer: boolean, archon: string): Route {
68  const viaServer = run.hasConversation && isServer
69  const id = run.id
70  if (pending.kind === 'answer') {
71    if (viaServer) {
72      if (pending.decision === 'approve') return { via: 'server', path: `/api/workflows/runs/${id}/approve`, body: JSON.stringify(text === '' ? {} : { comment: text }) }
73      if (pending.decision === 'reject') return { via: 'server', path: `/api/workflows/runs/${id}/reject`, body: JSON.stringify(text === '' ? {} : { reason: text }) }
74      return { via: 'server', path: `/api/workflows/runs/${id}/respond`, body: JSON.stringify(text === '' ? { decision: pending.decision } : { decision: pending.decision, text }) }
75    }
76    const verb = pending.decision === 'approve' || pending.decision === 'reject' ? [pending.decision, id] : ['respond', id, pending.decision]
77    return { via: 'cli', argv: [archon, 'workflow', ...verb, ...(text === '' ? [] : [text]), '--detach', '--json'] }
78  }
79  if (pending.kind === 'resume') {
80    if (run.platform !== '') return { via: 'none' }
81    if (viaServer) return { via: 'server', path: `/api/workflows/runs/${id}/resume`, body: '' }
82    return { via: 'cli', argv: [archon, 'workflow', 'resume', id, '--detach', '--json'] }
83  }
84  if (viaServer && run.platform === '') return { via: 'server', path: `/api/workflows/runs/${id}/abandon`, body: '' }
85  return { via: 'cli', argv: [archon, 'workflow', 'abandon', id, '--json'] }
86}
87
88/** How a sub-run ended, as a stranded parent's view says it. */
89export function strandHead(subRun: Run | undefined): string {
90  const name = subRun?.workflow ?? 'sub-run'
91  if (subRun?.status === 'cancelled') return `! Sub-run ${name} was cancelled${subRun.completedAt > 0 ? ` (rejected ${clockTime(subRun.completedAt)})` : ''}`
92  if (subRun?.status === 'failed') return `! Sub-run ${name} failed`
93  return `! Sub-run ${name} finished`
94}
95
96/** The resume button of a stranded parent, by how its sub-run ended. */
97export function strandResume(subRun: Run | undefined): string {
98  const name = subRun?.workflow ?? 'the sub-run'
99  if (subRun?.status === 'cancelled') return 'r  Resume without it'
100  if (subRun?.status === 'failed') return `r  Resume: run ${name} again, once`
101  return `r  Resume: go on with ${name}'s output`
102}
103
104/** The confirming line of a stranded parent's resume. */
105export function strandConfirm(node: string, subRun: Run | undefined): string {
106  const name = subRun?.workflow ?? 'the sub-run'
107  if (subRun?.status === 'cancelled') return `Resume: node ${node} fails ("Sub-run '${name}' was cancelled") and the run goes on by its rules, which usually fail it.`
108  if (subRun?.status === 'failed') return `Resume: node ${node} runs ${name} again, once.`
109  return `Resume: node ${node} goes on with ${name}'s output.`
110}
111
112export const ABANDON_LINE = "Abandon: ends this run and anything it started. It can't be resumed."
113export const SERVER_DOWN_NOTE = "The server isn't answering, so the rest of this run won't show in its chat."
114
115/** What an answer that landed looks like: `✓ Approved 14:32 · "…"`, `✗ Rejected …`, other decisions by label. */
116export function recordLine(decision: string, label: string, text: string, at: number): string {
117  const said = text === '' ? '' : ` · "${text}"`
118  if (decision === 'reject') return `✗ Rejected ${clockTime(at)}${said}`
119  if (decision === 'approve') return `✓ Approved ${clockTime(at)}${said}`
120  return `✓ ${label.replace(/^[a-z]: /, '')} ${clockTime(at)}${said}`
121}
122
123/** The last answer the run's events record: the decision, when and the text. */
124export function lastAnswer(detail: Detail | undefined): { decision: string; at: number; text: string } | undefined {
125  const received = [...(detail?.events ?? [])].reverse().find(e => e.type === 'approval_received')
126  return received === undefined ? undefined : { decision: received.decision || 'approve', at: received.at, text: received.text }
127}
128
129/** Archon's own words from a CLI reply or a REST body: `{ok:false, error}`, `{error}`, `{message}`, else the last line; a refusal's `childRunId` names the sub-run to answer instead. */
130export function archonMessage(text: string): { ok: boolean | undefined; message: string; subRunId: string; logPath: string } {
131  try {
132    const parsed = JSON.parse(text) as Record<string, unknown>
133    const message = typeof parsed.error === 'string' ? parsed.error : typeof parsed.message === 'string' ? parsed.message : ''
134    return {
135      ok: typeof parsed.ok === 'boolean' ? parsed.ok : typeof parsed.success === 'boolean' ? parsed.success : undefined,
136      message,
137      subRunId: typeof parsed.childRunId === 'string' ? parsed.childRunId : '',
138      logPath: typeof parsed.logPath === 'string' ? parsed.logPath : '',
139    }
140  } catch {
141    return { ok: undefined, message: firstLine(text.split(/\r?\n/).reverse().join('\n')), subRunId: '', logPath: '' }
142  }
143}
144
145/** How long Archon has to reply to an action, and how long after a `--detach` answer or resume the run is checked on. */
146export const REPLY_MS = 30_000
147
148/** Whether a run, as fetched again, still waits on the pending action; else what happened elsewhere. */
149export function movedElsewhere(pending: Pending, run: Run | undefined, runs: readonly Run[], detail: Detail | undefined): string | undefined {
150  if (run === undefined) return undefined
151  if (hasEnded(run)) return 'Ended elsewhere'
152  const found = standing(run, runs, detail)
153  if (pending.kind === 'answer') {
154    if (found.kind === 'approval') return undefined
155    const answer = lastAnswer(detail)
156    return answer === undefined
157      ? 'Answered elsewhere'
158      : `Answered elsewhere · ${recordLine(answer.decision, answer.decision, answer.text, answer.at)}`
159  }
160  if (found.kind === 'action' || found.kind === 'stranded') return undefined
161  return run.status === 'paused' ? 'Answered elsewhere' : 'Resumed elsewhere'
162}
163
164export type Delivered =
165  | { kind: 'done'; via: 'cli' | 'server'; message: string; log: string }
166  | { kind: 'refused'; message: string }
167  | { kind: 'silent' }
168
169/** Makes the call the action routes to, raced against 30 s; a refusal naming a sub-run's id is followed to it once. */
170export async function deliver(io: Io, port: number, archon: string, pending: Pending, run: Run, text: string, isServer: boolean, isFollowed = false): Promise<Delivered> {
171  const routed = route(pending, run, text, isServer, archon)
172  if (routed.via === 'none') return { kind: 'refused', message: `resume it from ${platformName(run.platform)}` }
173  if (routed.via === 'cli') {
174    const out = await within(io, REPLY_MS, io.run(routed.argv, 2 * REPLY_MS)).catch((error: unknown) => (error instanceof Error ? error : new Error(String(error))))
175    if (isTimedOut(out)) return { kind: 'silent' }
176    if (out instanceof Error) return { kind: 'refused', message: out.message }
177    const said = archonMessage(out.stdout)
178    if (out.exitCode !== 0 || said.ok === false) return { kind: 'refused', message: said.message || lastLine(out.stderr) || `archon exited with ${out.exitCode}` }
179    return { kind: 'done', via: 'cli', message: said.message, log: said.logPath }
180  }
181  const reply = await within(io, REPLY_MS, io.fetch(`http://localhost:${port}${routed.path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: routed.body })).catch((error: unknown) => (error instanceof Error ? error : new Error(String(error))))
182  if (isTimedOut(reply)) return { kind: 'silent' }
183  if (reply instanceof Error) return { kind: 'refused', message: reply.message }
184  const said = archonMessage(reply.text)
185  if (!reply.ok) {
186    if (pending.kind === 'answer' && said.subRunId !== '' && !isFollowed) {
187      return deliver(io, port, archon, { ...pending, runId: said.subRunId }, { ...run, id: said.subRunId }, text, isServer, true)
188    }
189    return { kind: 'refused', message: said.message || `Archon answered ${reply.status}` }
190  }
191  return { kind: 'done', via: 'server', message: pending.kind === 'answer' ? said.message : '', log: '' }
192}
193
194/** Whether a run moved on from what a sent action left it waiting at. */
195export function hasMoved(run: Run | undefined, runs: readonly Run[], detail: Detail | undefined, kind: 'answer' | 'resume'): boolean {
196  if (run === undefined || hasEnded(run)) return true
197  const found = standing(run, runs, detail)
198  return kind === 'answer' ? found.kind !== 'approval' : run.status !== 'paused'
199}
200
hooks/actions-view.tsx 179 lines
1// What Log shows for a run that needs you: the approval view and its answer
2// area, or the resume and abandon view, each action through a confirming step.
3
4import type { Elements, RenderElement } from 'claude-code'
5
6import type { ArchonActions, Detail, GraphNode, Run } from '../types'
7import { ABANDON_LINE, answerButtons, platformName, SERVER_DOWN_NOTE, strandConfirm, strandHead, strandResume } from './actions'
8import { waitNode } from './runs'
9import type { NeedsYou } from './runs'
10import { shortId } from './runs-view'
11import { duration } from './text'
12
13/** The most of a node's output "what it asks about" shows: its last lines. */
14const ASKS_LINES = 10
15
16export type ActionProps = {
17  ui: Elements[keyof Elements]
18  surface: string
19  /** The run that needs you, and the run holding the gate (itself, or its sub-run). */
20  run: Run
21  need: NeedsYou
22  parent: Run | undefined
23  detail: Detail | undefined
24  graph: GraphNode[] | null | undefined
25  actions: ArchonActions
26  now: number
27  width: number
28  isServer: boolean
29  /** The run's page in Archon's web UI, or '' when it is not linked. */
30  link: string
31  /** Whether Log is cut to the gate's node; `a` widens what it asks about to the whole run log. */
32  isCut: boolean
33  /** The whole run log, drawn when `a` widened it. */
34  log: RenderElement[]
35  files: RenderElement[]
36  onDecide: (decision: string, label: string) => void
37  onResume: () => void
38  onAbandon: () => void
39  onConfirm: () => void
40  onBack: () => void
41  onText: (text: string) => void
42  onAll: () => void
43}
44
45/** The area under a run that needs you: notices, then the buttons, the confirming step, or what is being sent. */
46function answerArea(props: ActionProps): RenderElement[] {
47  const { ui, run, need, actions } = props
48  const { Box, Text, Button } = ui
49  // The phone draws no Input.
50  const Input = 'Input' in ui ? ui.Input : undefined
51  const holder = need.holder
52  const text = actions.text[holder.id] ?? ''
53  const lines: RenderElement[] = []
54  const pending = actions.pending?.runId === holder.id ? actions.pending : null
55  if (actions.sending === holder.id) return lines
56  const found = need.standing
57
58  if (pending !== null) {
59    let line: string
60    if (pending.kind === 'answer') {
61      line = `${pending.label.replace(/^[a-z]: /, '').replace(/ \(.*\)$/, '')} ${holder.workflow} ${shortId(holder.id)}${text === '' ? '' : ` · "${text}"`}`
62      if (holder.hasConversation && !props.isServer) line = `${line} ${SERVER_DOWN_NOTE}`
63    } else if (pending.kind === 'resume') {
64      line = found.kind === 'stranded' ? strandConfirm(found.gate.nodeId, found.subRun) : `Resume: the run carries on from ${waitNode(found)}.`
65    } else line = ABANDON_LINE
66    const name = pending.kind === 'answer' ? 'Send' : `${pending.kind === 'resume' ? 'Resume' : 'Abandon'} ${holder.workflow}`
67    lines.push(<Text wrap="wrap">{line}</Text>)
68    lines.push(
69      <Box key="confirming" flexDirection="row" columnGap={2}>
70        <Button key="confirm" variant="primary" autoFocus label={name} onPress={props.onConfirm} />
71        <Button key="back" hotkey="b" label="b: Back" onPress={props.onBack} />
72      </Box>,
73    )
74    return lines
75  }
76
77  if (found.kind === 'approval') {
78    const buttons = answerButtons(found.gate, holder, props.parent, text)
79    lines.push(
80      <Box key="answers" flexDirection="row" flexWrap="wrap" columnGap={2}>
81        {buttons.map(button => (button.letter === ''
82          ? <Button key={`decide-${button.decision}`} {...(button.isPrimary ? { variant: 'primary' as const } : {})} label={button.label} onPress={() => props.onDecide(button.decision, button.label)} />
83          : <Button key={`decide-${button.decision}`} hotkey={button.letter} {...(button.isPrimary ? { variant: 'primary' as const } : {})} label={button.label} onPress={() => props.onDecide(button.decision, button.label)} />))}
84      </Box>,
85    )
86    if (Input !== undefined && props.surface !== 'mobile') {
87      lines.push(<Input key="comment" label="Comment or reason (optional)" placeholder="Comment or reason (optional)" value={text} onInput={(value: string) => props.onText(value)} onSubmit={(value: string) => props.onText(value)} />)
88    } else lines.push(<Text dimColor>A comment needs the terminal or the desktop app.</Text>)
89    if (found.gate.type === 'container_writeback' && props.link !== '' && ui.Link !== undefined) {
90      const { Link } = ui
91      lines.push(<Link key="diff-link" href={props.link} label="↗ Archon, for the full diff" />)
92    }
93    return lines
94  }
95
96  if (found.kind === 'action' || found.kind === 'stranded') {
97    const row: RenderElement[] = []
98    if (run.platform !== '' || holder.platform !== '') row.push(<Text dimColor>{`resume it from ${platformName(holder.platform || run.platform)}`}</Text>)
99    else if (!isPathThere(props.detail)) row.push(<Text dimColor>{`can't resume: ${holder.workingPath} is gone`}</Text>)
100    else {
101      const label = found.kind === 'stranded' ? strandResume(found.subRun) : "r  Resume: I've done it"
102      row.push(<Button key="resume" hotkey="r" variant="primary" label={label} onPress={props.onResume} />)
103    }
104    row.push(<Button key="abandon" hotkey="x" label="x  Abandon run" onPress={props.onAbandon} />)
105    lines.push(<Box key="resume-row" flexDirection="row" flexWrap="wrap" columnGap={2}>{row}</Box>)
106  }
107  return lines
108}
109
110/** The node outputs a gate asks about: each node it waits on, its last part, under an `a` that widens it to the whole run log. */
111function asksAbout(props: ActionProps): RenderElement[] {
112  const { Box, Text, Button } = props.ui
113  const node = waitNode(props.need.standing)
114  const deps = props.graph?.find(n => n.id === node)?.deps ?? []
115  const events = props.detail?.events ?? []
116  const lines: RenderElement[] = [
117    <Box key="asks" flexDirection="row" columnGap={1}>
118      <Text dimColor>{`cut to ${node} ·`}</Text>
119      <Button key="asks-all" plain dimColor hotkey="a" label="whole run log" onPress={props.onAll} />
120    </Box>,
121  ]
122  for (const dep of deps) {
123    const output = [...events].reverse().find(e => e.step === dep && e.type === 'node_completed')?.output ?? ''
124    if (output === '') continue
125    lines.push(<Text bold>{dep}</Text>)
126    for (const line of output.replace(/\n+$/, '').split('\n').slice(-ASKS_LINES)) lines.push(<Text dimColor wrap="wrap">{line}</Text>)
127  }
128  const found = props.need.standing
129  if (found.kind === 'approval' && found.gate.type === 'interactive_loop') {
130    lines.push(<Text dimColor wrap="wrap">{found.gate.isRoundDone ? 'A bare approve finishes the loop; with a comment it runs another round.' : 'An approve runs another round, with your comment if you give one.'}</Text>)
131  }
132  return lines
133}
134
135/** The approval view, or the resume and abandon view, top to bottom. */
136const isPathThere = (detail: ActionProps['detail']): boolean => detail?.isWorkingPathThere !== false
137
138/**
139 * Whether the answer area offers Resume, which then holds the `r` key: the
140 * pinned row's reload gives it up (an answer's letter never takes `r`, but
141 * Resume is `r` by name).
142 */
143export function offersResume(props: Pick<ActionProps, 'run' | 'need' | 'detail' | 'actions'>): boolean {
144  const { standing, holder } = props.need
145  if (standing.kind !== 'action' && standing.kind !== 'stranded') return false
146  if (props.actions.pending?.runId === holder.id) return false
147  return props.run.platform === '' && holder.platform === '' && isPathThere(props.detail)
148}
149
150export function actionBody(props: ActionProps): RenderElement[] {
151  const { ui, need, now } = props
152  const { Box, Text, Markdown, Link } = ui
153  const holder = need.holder
154  const found = need.standing
155  const lines: RenderElement[] = []
156  const waited = duration(now - found.since)
157  if (found.kind === 'approval' || found.kind === 'unreadable') {
158    const name = `${props.parent === undefined ? '' : `${props.parent.workflow} › sub-run `}${holder.workflow}`
159    lines.push(
160      <Box key="loghead" flexDirection="row" columnGap={1}>
161        <Text bold wrap="truncate-end">{`${name} · ${shortId(holder.id)} · waited ${waited}`}</Text>
162        {props.link !== '' && <Link key="archon-link" href={props.link} label="↗ Archon" />}
163      </Box>,
164    )
165    if (found.kind === 'approval' && found.gate.message !== '') lines.push(<Markdown key="gate-message" text={found.gate.message} />)
166    if (found.kind === 'unreadable') lines.push(<Text color="warning" wrap="wrap">This gate is one Archon can't read; answer it in Archon.</Text>)
167  } else if (found.kind === 'action') {
168    lines.push(<Text bold color="warning">{`⏸ Action needed · waiting ${waited}`}</Text>)
169    lines.push(<Text wrap="wrap">{found.wait.message}</Text>)
170  } else {
171    lines.push(<Text bold color="warning">{strandHead(found.subRun)}</Text>)
172    lines.push(<Text>{`Node ${found.gate.nodeId} can't go on.`}</Text>)
173  }
174  lines.push(...(props.isCut ? asksAbout(props) : props.log))
175  lines.push(...props.files)
176  lines.push(...answerArea(props))
177  return lines
178}
179
hooks/chrome.tsx 92 lines
1// The pane's chrome: the pinned row of sub-tabs, and the body window under
2// it that the mod scrolls itself, so the row never scrolls away.
3
4import type { Elements, RenderElement } from 'claude-code'
5
6import type { Tab } from '../types'
7
8/** The settings dialog's command and its gear's key (ADR-0007). mod-settings takes the press; the gear's onPress is the fallback. */
9export const SETTINGS = 'mod-settings'
10/** Columns between sub-tabs at full width, and when shortened. */
11const GAP = 2
12const NARROW_GAP = 1
13
14export const TABS: readonly { tab: Tab; hotkey: string; label: string; short: string }[] = [
15  { tab: 'runs', hotkey: '1', label: 'Runs', short: 'Runs' },
16  { tab: 'graph', hotkey: '2', label: 'Graph', short: 'Graph' },
17  { tab: 'log', hotkey: '3', label: 'Log', short: 'Log' },
18  { tab: 'archon-log', hotkey: '4', label: "Archon's log", short: 'Arch' },
19]
20
21export type ChromeProps = {
22  ui: Elements[keyof Elements]
23  width: number
24  shown: Tab
25  /** This project's live runs, and how many need you. */
26  live: number
27  needsYou: number
28  hasSettings: boolean
29  /** False while a Resume button holds `r`. */
30  isReloadKey: boolean
31  onTab: (tab: Tab) => void
32  onReload: () => void
33  onSettings: () => void
34}
35
36/** The columns a button takes: its `k: ` hotkey prefix and its label, wide characters counting two. */
37function buttonWidth(label: string, hotkey: string | undefined): number {
38  const cells = [...label].reduce((sum, char) => sum + (/\p{Extended_Pictographic}/u.test(char) ? 2 : /️/u.test(char) ? 0 : 1), 0)
39  return (hotkey === undefined ? 0 : hotkey.length + 2) + cells
40}
41
42/**
43 * The pinned row: exactly one line, the reload and gear at its right end. The
44 * sub-tab labels shorten when the full row would not fit beside them, and a
45 * column always separates the two, so a cut label never runs into `r: ↻`.
46 */
47export function pinnedRow(props: ChromeProps): RenderElement {
48  const { Box, Button } = props.ui
49  const counted = (tab: Tab) => (tab === 'runs' ? `${props.live > 0 ? ` ${props.live}` : ''}${props.needsYou > 0 ? ` ⏸${props.needsYou}` : ''}` : '')
50  const tabsWidth = TABS.reduce((sum, { tab, hotkey, label }) => sum + buttonWidth(`${label}${counted(tab)}`, hotkey), 0) + GAP * (TABS.length - 1)
51  const actionsWidth = buttonWidth('↻', props.isReloadKey ? 'r' : undefined) + (props.hasSettings ? 1 + buttonWidth('⚙️', undefined) : 0)
52  const isNarrow = props.width < tabsWidth + 1 + actionsWidth
53  return (
54    <Box key="pinned" flexDirection="row" justifyContent="space-between" columnGap={1} height={1} overflow="hidden">
55      <Box flexDirection="row" columnGap={isNarrow ? NARROW_GAP : GAP} flexShrink={1} overflow="hidden">
56        {TABS.map(({ tab, hotkey, label, short }) => (
57          <Button
58            key={`tab-${tab}`}
59            plain
60            hotkey={hotkey}
61            dimColor={tab !== props.shown}
62            label={`${isNarrow ? short : label}${counted(tab)}`}
63            onPress={() => props.onTab(tab)}
64          />
65        ))}
66      </Box>
67      <Box flexDirection="row" columnGap={1} flexShrink={0}>
68        <Button key="reload" plain dimColor {...(props.isReloadKey ? { hotkey: 'r' } : {})} label="↻" onPress={props.onReload} />
69        {props.hasSettings && <Button key={SETTINGS} plain dimColor label="⚙️" onPress={props.onSettings} />}
70      </Box>
71    </Box>
72  )
73}
74
75/** The furthest a sub-tab can scroll: its last rows fill the window. */
76export function lastPosition(count: number, bodyRows: number): number {
77  return Math.max(0, count - Math.max(1, bodyRows - 1))
78}
79
80/**
81 * The rows the window shows: from `at`, sliced to the body's height under the
82 * pinned row, with a `… N more` line counted in that height.
83 */
84export function bodyWindow(ui: ChromeProps['ui'], lines: readonly RenderElement[], at: number, bodyRows: number): RenderElement[] {
85  const { Text } = ui
86  const room = Math.max(1, bodyRows - 1)
87  const from = Math.min(Math.max(0, at), lastPosition(lines.length, bodyRows))
88  if (lines.length - from <= room) return lines.slice(from)
89  const shown = lines.slice(from, from + room - 1)
90  return [...shown, <Text key="more" dimColor>… {lines.length - from - shown.length} more</Text>]
91}
92
hooks/cli.ts 66 lines
1// Finding and calling the Archon CLI, the pane's one Requirement.
2
3import type { Requirement } from '../types'
4
5/** What the CLI calls need from the engine: a run that rejects when the command cannot start. */
6export type Runner = (argv: readonly string[], timeoutMs?: number) => Promise<{ exitCode: number; stdout: string; stderr: string }>
7
8/** The oldest CLI with `workflow logs --follow`. */
9const MINIMUM = [0, 11, 0] as const
10
11export const NEEDS_CLI = 'The Archon pane needs the Archon CLI, v0.11.0 or later. Install it from https://archon.diy, or set its path in the mod settings, then press r.'
12
13export function needsNewer(version: string): string {
14  return `The Archon pane needs Archon v0.11.0 or later; this is ${version}. Update it, then press r.`
15}
16
17/** The line the pane shows for a Requirement not met; undefined when it is met or not yet checked. */
18export function requirementLine(requirement: Requirement): string | undefined {
19  if (requirement.state === 'missing') return NEEDS_CLI
20  if (requirement.state === 'old') return needsNewer(requirement.version)
21  return undefined
22}
23
24/** `v0.11.1` from what `archon --version` prints; '' when it names no version. */
25export function parseVersion(output: string): string {
26  const found = /v?(\d+)\.(\d+)\.(\d+)/.exec(output)
27  return found === null ? '' : `v${found[1]}.${found[2]}.${found[3]}`
28}
29
30function isNewEnough(version: string): boolean {
31  const parts = version.slice(1).split('.').map(Number)
32  for (let i = 0; i < MINIMUM.length; i++) {
33    const have = parts[i] ?? 0
34    if (have !== MINIMUM[i]) return have > MINIMUM[i]!
35  }
36  return true
37}
38
39/**
40 * Where to look for the CLI, in order: the setting, `archon` on Claude Code's
41 * PATH, then `<home>/.archon/bin/archon(.exe)`. The engine expands no `~` and
42 * sees no PATH set in `init.env`, so the last is an absolute path.
43 */
44export function candidates(setting: string, home: string, isWindows: boolean): string[] {
45  if (setting !== '') return [setting]
46  const found = ['archon']
47  if (home !== '') found.push(`${home.replace(/[\\/]+$/, '')}/.archon/bin/archon${isWindows ? '.exe' : ''}`)
48  return found
49}
50
51/** Checks the CLI: the first candidate that starts names the version; older than v0.11.0 counts as missing. */
52export async function findArchon(run: Runner, places: readonly string[]): Promise<Requirement> {
53  for (const path of places) {
54    let output
55    try {
56      output = await run([path, '--version'])
57    } catch {
58      continue
59    }
60    const version = parseVersion(`${output.stdout}\n${output.stderr}`)
61    if (output.exitCode !== 0 || version === '') continue
62    return { state: isNewEnough(version) ? 'ok' : 'old', path, version }
63  }
64  return { state: 'missing', path: '', version: '' }
65}
66
hooks/graph.ts 440 lines
1// A run's graph: its nodes read from its frozen workflow source, and their
2// layout as box-drawing text that gives way one step at a time when it is
3// wider than the pane (#165; the prototype on `prototype/165-graph-width` is
4// the reference for the layering, the lanes and the give-way steps).
5
6import type { GraphNode } from '../types'
7import { fit, glyph } from './text'
8import type { Look } from './text'
9import { parseYaml } from './yaml'
10
11const KINDS = ['command', 'prompt', 'bash', 'script', 'loop', 'loop_group', 'approval', 'cancel', 'wait', 'workflow', 'include']
12
13function isObject(value: unknown): value is Record<string, unknown> {
14  return typeof value === 'object' && value !== null && !Array.isArray(value)
15}
16
17function depsOf(value: unknown): string[] {
18  if (typeof value === 'string' && value !== '') return [value]
19  return Array.isArray(value) ? value.filter((dep): dep is string => typeof dep === 'string' && dep !== '') : []
20}
21
22function rawNodes(source: unknown): Record<string, unknown>[] {
23  return isObject(source) && Array.isArray(source.nodes) ? source.nodes.filter(isObject).filter(node => typeof node.id === 'string') : []
24}
25
26function readNode(node: Record<string, unknown>): GraphNode {
27  const kind = KINDS.find(k => node[k] !== undefined) ?? 'command'
28  const group = isObject(node.loop_group) ? node.loop_group : {}
29  return {
30    id: String(node.id),
31    deps: depsOf(node.depends_on),
32    kind,
33    block: '',
34    workflow: kind === 'workflow' && typeof node.workflow === 'string' ? node.workflow : '',
35    body: rawNodes(group).map(readNode),
36  }
37}
38
39/**
40 * The nodes of a workflow, with every plain `include:` expanded at load time
41 * as Archon does: `<include>__<node>`, the include's own waits attached to the
42 * block's entry nodes, and a node waiting on the include waiting on the
43 * block's end nodes. `find` reads another workflow of the same frozen source
44 * by name; an include it cannot find stays one node.
45 */
46export function workflowNodes(yaml: string, find: (name: string) => string | undefined, depth = 0): GraphNode[] {
47  const nodes = rawNodes(parseYaml(yaml))
48  const out: GraphNode[] = []
49  const ends = new Map<string, string[]>()
50  for (const raw of nodes) {
51    const node = readNode(raw)
52    const target = typeof raw.include === 'string' && raw.fan_out === undefined && depth < 3 ? find(raw.include) : undefined
53    if (target === undefined) {
54      out.push(node)
55      continue
56    }
57    const inner = workflowNodes(target, find, depth + 1)
58    const ids = new Set(inner.map(n => n.id))
59    const waitedOn = new Set(inner.flatMap(n => n.deps))
60    for (const n of inner) {
61      const own = n.deps.filter(dep => ids.has(dep)).map(dep => `${node.id}__${dep}`)
62      out.push({ ...n, id: `${node.id}__${n.id}`, deps: own.length === 0 ? node.deps : own, block: n.block === '' ? node.id : `${node.id}__${n.block}` })
63    }
64    ends.set(node.id, inner.filter(n => !waitedOn.has(n.id)).map(n => `${node.id}__${n.id}`))
65  }
66  return out.map(node => ({ ...node, deps: node.deps.flatMap(dep => ends.get(dep) ?? [dep]) }))
67}
68
69/** What reading a frozen workflow source needs: a folder's entries and a file's text, each of which may throw. */
70export type SourceIo = {
71  list: (path: string) => Promise<readonly { name: string; kind: string }[]>
72  read: (path: string) => Promise<string>
73}
74
75/** The files under `root` whose name ends `.yaml` or `.yml`, a few folders deep. */
76async function yamlFiles(io: SourceIo, root: string, depth = 0): Promise<string[]> {
77  const entries = await io.list(root).catch(() => [])
78  const found: string[] = []
79  for (const entry of entries) {
80    const path = `${root}/${entry.name}`
81    if (entry.kind === 'dir' && depth < 5) found.push(...(await yamlFiles(io, path, depth + 1)))
82    else if (entry.kind === 'file' && /\.ya?ml$/i.test(entry.name)) found.push(path)
83  }
84  return found
85}
86
87/** How a workflow of a frozen source ranks when two share a name: a project's over a global one over a bundled one. */
88function rankOf(path: string): number {
89  return /\/bundled\//.test(path) ? 0 : /\/global\//.test(path) ? 1 : 2
90}
91
92/** `owner/pack:entry`: how Archon names a run of an installed workflow pack's entry point. */
93const PACK_ENTRY = /^([^/\s:]+)\/([^/\s:]+):([^/\s:]+)$/
94
95/**
96 * The file of an installed pack's entry point in a frozen source. Archon freezes
97 * the pack under `installed/<owner>.<pack>/`, and its `archon-plugin.json` maps
98 * each entry point to a workflow file whose own `name:` differs from the run's
99 * workflow name. Undefined for any other name, or when the pack or the entry
100 * point can't be read.
101 */
102async function packEntryFile(io: SourceIo, root: string, workflow: string): Promise<string | undefined> {
103  const match = PACK_ENTRY.exec(workflow)
104  if (match === null) return undefined
105  const dir = `${root}/installed/${match[1]}.${match[2]}`
106  const pack = await io.read(`${dir}/archon-plugin.json`).then(text => JSON.parse(text) as unknown).catch(() => undefined)
107  const entries = isObject(pack) && isObject(pack.entrypoints) ? pack.entrypoints : {}
108  const file = Object.hasOwn(entries, match[3]!) ? entries[match[3]!] : undefined
109  if (typeof file !== 'string') return undefined
110  const relative = file.replace(/\\/g, '/').replace(/^\.\//, '')
111  return relative === '' || relative.startsWith('/') || relative.split('/').includes('..') ? undefined : `${dir}/${relative}`
112}
113
114/** The workflow names a workflow's plain `include:` nodes refer to. */
115function includesOf(yaml: string): string[] {
116  return [...yaml.matchAll(/^\s*(?:-\s+)?include:\s*["']?([^"'\s#]+)/gm)].map(match => match[1]!)
117}
118
119/**
120 * A run's nodes, read from its frozen workflow source
121 * (`metadata.workflow_source.root`), which never changes: the workflow
122 * `manifest.json` names (else `workflow`), and any workflow it includes. A
123 * pack's entry point (`owner/pack:entry`) is read from the file its pack maps
124 * it to. Null when the source has no such workflow or can't be read.
125 */
126export async function readWorkflow(io: SourceIo, sourceRoot: string, workflow: string): Promise<GraphNode[] | null> {
127  const root = sourceRoot.replace(/\\/g, '/').replace(/\/+$/, '')
128  if (root === '') return null
129  const manifest = await io.read(`${root}/manifest.json`).then(text => JSON.parse(text) as { workflow_name?: unknown }).catch(() => undefined)
130  const name = typeof manifest?.workflow_name === 'string' ? manifest.workflow_name : workflow
131  const files = await yamlFiles(io, root)
132  const texts = new Map<string, string>()
133  const textOf = async (path: string) => {
134    if (!texts.has(path)) texts.set(path, await io.read(path).catch(() => ''))
135    return texts.get(path)!
136  }
137  const nameIn = (text: string) => /^name:\s*["']?([^"'\n#]+?)["']?\s*$/m.exec(text)?.[1] ?? ''
138  // A workflow's file is usually named for it; any other file is read only when that misses.
139  const byName = new Map<string, { text: string; rank: number }>()
140  const consider = (path: string, text: string) => {
141    const found = nameIn(text)
142    const known = byName.get(found)
143    if (found !== '' && (known === undefined || rankOf(path) > known.rank)) byName.set(found, { text, rank: rankOf(path) })
144  }
145  const base = (path: string) => path.slice(path.lastIndexOf('/') + 1).replace(/\.ya?ml$/i, '')
146  const entry = await packEntryFile(io, root, name)
147  let main: string | undefined
148  if (entry !== undefined) {
149    const text = await textOf(entry)
150    main = text === '' ? undefined : text
151  } else {
152    for (const path of files) if (base(path) === name || /^archon-/.test(base(path))) consider(path, await textOf(path))
153    if (!byName.has(name)) for (const path of files) consider(path, await textOf(path))
154    main = byName.get(name)?.text
155  }
156  if (main === undefined) return null
157  // Included workflows the files read so far don't name: first a file named for each, then every file.
158  let pending = includesOf(main)
159  for (let depth = 0; depth < 3 && pending.length > 0; depth++) {
160    const missing = pending.filter(wanted => !byName.has(wanted))
161    for (const path of files) if (missing.includes(base(path))) consider(path, await textOf(path))
162    if (missing.some(wanted => !byName.has(wanted))) for (const path of files) consider(path, await textOf(path))
163    pending = pending.flatMap(wanted => includesOf(byName.get(wanted)?.text ?? ''))
164  }
165  const sync = new Map([...byName].map(([key, value]) => [key, value.text]))
166  return workflowNodes(main, wanted => sync.get(wanted))
167}
168
169/** One box of the drawn graph. */
170export type DrawNode = {
171  id: string
172  /** What the box names: the node, or a folded block's, loop's or sub-run's summary. */
173  label: string
174  look: Look
175  deps: string[]
176  /** A gate waiting on the person: drawn with a bold border in `warning`. */
177  isGate: boolean
178  /** The include block it came from, whose prefix step 2 leaves out. */
179  block: string
180}
181
182/** A run of text in one drawn line, with how it looks and what a press on it picks. */
183export type Seg = {
184  text: string
185  tone?: 'success' | 'error' | 'warning'
186  dim?: boolean
187  bold?: boolean
188  /** The node a press on this segment picks. */
189  pick?: string
190}
191
192export type Drawn = {
193  lines: Seg[][]
194  /** The give-way step that fit: 1 whole names, 2 no include prefix, 3 names cut to 10, 4 skip edges as notes, 5 a list. */
195  step: 1 | 2 | 3 | 4 | 5
196}
197
198type Item = { kind: 'node'; id: string; node: DrawNode; name: string } | { kind: 'lane'; id: string }
199
200function toneOf(look: Look): Seg['tone'] {
201  if (look === 'running' || look === 'completed') return 'success'
202  if (look === 'failed') return 'error'
203  if (look === 'approval' || look === 'action' || look === 'unreadable') return 'warning'
204  return undefined
205}
206
207function depthsOf(nodes: readonly DrawNode[]): Map<string, number> {
208  const byId = new Map(nodes.map(node => [node.id, node]))
209  const depth = new Map<string, number>()
210  const of = (id: string, seen: Set<string>): number => {
211    const known = depth.get(id)
212    if (known !== undefined) return known
213    const node = byId.get(id)
214    if (node === undefined || seen.has(id)) return 0
215    seen.add(id)
216    const deps = node.deps.filter(dep => byId.has(dep))
217    const value = deps.length === 0 ? 0 : 1 + Math.max(...deps.map(dep => of(dep, seen)))
218    depth.set(id, value)
219    return value
220  }
221  for (const node of nodes) of(node.id, new Set())
222  return depth
223}
224
225const width = (name: string) => Array.from(name).length
226
227function itemWidth(item: Item): number {
228  return item.kind === 'lane' ? 1 : width(item.name) + 6
229}
230
231function layerWidth(items: readonly Item[]): number {
232  return items.reduce((sum, item, i) => sum + itemWidth(item) + (i === 0 ? 0 : 1), 0)
233}
234
235/** The name a box shows at a give-way step. */
236function nameAt(node: DrawNode, step: number): string {
237  const name = step >= 2 && node.block !== '' && node.label.startsWith(`${node.block}__`) ? node.label.slice(node.block.length + 2) : node.label
238  return step >= 3 ? fit(name, 10) : name
239}
240
241type Plan = { layers: Item[][]; edges: [string, string][]; notes: Map<number, string[]> }
242
243function plan(nodes: readonly DrawNode[], step: number): Plan {
244  const depth = depthsOf(nodes)
245  const ids = new Set(nodes.map(node => node.id))
246  const deepest = Math.max(0, ...depth.values())
247  const layers: Item[][] = Array.from({ length: deepest + 1 }, () => [])
248  for (const node of nodes) layers[depth.get(node.id) ?? 0]!.push({ kind: 'node', id: node.id, node, name: nameAt(node, step) })
249  const edges: [string, string][] = []
250  const notes = new Map<number, string[]>()
251  for (const node of nodes) {
252    for (const dep of node.deps.filter(d => ids.has(d))) {
253      const from = depth.get(dep)!
254      const to = depth.get(node.id)!
255      if (to - from === 1) edges.push([dep, node.id])
256      else if (step <= 3) {
257        // A lane: a one-column stand-in in each layer the edge passes.
258        let previous = dep
259        for (let layer = from + 1; layer < to; layer++) {
260          const id = `~${dep}>${node.id}@${layer}`
261          layers[layer]!.push({ kind: 'lane', id })
262          edges.push([previous, id])
263          previous = id
264        }
265        edges.push([previous, node.id])
266      } else {
267        notes.set(to, [...(notes.get(to) ?? []), `↑ ${node.id} also waits on ${dep}`])
268      }
269    }
270  }
271  // Each layer in the mean order of what it waits on, so edges cross least.
272  for (let layer = 1; layer < layers.length; layer++) {
273    const above = new Map(layers[layer - 1]!.map((item, i) => [item.id, i]))
274    const mean = (item: Item) => {
275      const at = edges.filter(([, to]) => to === item.id).map(([from]) => above.get(from) ?? 0)
276      return at.length === 0 ? 0 : at.reduce((a, b) => a + b, 0) / at.length
277    }
278    layers[layer] = layers[layer]!.map((item, i) => ({ item, m: mean(item), i })).sort((a, b) => a.m - b.m || a.i - b.i).map(entry => entry.item)
279  }
280  return { layers, edges, notes }
281}
282
283const CORNERS: Record<string, string> = {
284  udlr: '┼', udl: '┤', udr: '├', ulr: '┴', dlr: '┬', ud: '│', lr: '─',
285  ul: '┘', ur: '└', dl: '┐', dr: '┌', u: '│', d: '│', l: '─', r: '─', '': ' ',
286}
287
288/** A box's border: a gate's in bold `warning`; a running node's flashes `success`, heavy and bold on one beat, light and dim on the next. */
289function borderOf(node: DrawNode, pulse: boolean): { chars: string[]; seg: Seg; isHeavy: boolean } {
290  const heavy = ['━', '┃', '┏', '┓', '┗', '┛']
291  const light = ['─', '│', '┌', '┐', '└', '┘']
292  if (node.isGate) return { chars: heavy, seg: { text: '', tone: 'warning', bold: true }, isHeavy: true }
293  if (node.look === 'running') return pulse ? { chars: heavy, seg: { text: '', tone: 'success', bold: true }, isHeavy: true } : { chars: light, seg: { text: '', tone: 'success', dim: true }, isHeavy: false }
294  return { chars: light, seg: { text: '' }, isHeavy: false }
295}
296
297function graphLines({ layers, edges, notes }: Plan, pulse: boolean): Seg[][] {
298  const total = Math.max(...layers.map(layerWidth))
299  const centre = new Map<string, number>()
300  const out: Seg[][] = []
301  const hasOut = new Set(edges.map(([from]) => from))
302  const hasIn = new Set(edges.map(([, to]) => to))
303
304  layers.forEach((items, l) => {
305    const own = layerWidth(items)
306    let x = Math.floor((total - own) / 2)
307    if (l > 0) {
308      // Line the layer up under its parents' mean centre.
309      const ids = new Set(items.map(item => item.id))
310      const parents = edges.filter(([from, to]) => ids.has(to) && centre.has(from)).map(([from]) => centre.get(from)!)
311      if (parents.length > 0) {
312        let rx = 0
313        const centres = items.map(item => {
314          const w = itemWidth(item)
315          const c = rx + Math.floor(w / 2)
316          rx += w + 1
317          return c
318        })
319        const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / xs.length
320        x = Math.max(0, Math.min(total - own, Math.round(mean(parents) - mean(centres))))
321      }
322    }
323    const placed = items.map(item => {
324      const w = itemWidth(item)
325      const at = { item, x, w }
326      centre.set(item.id, x + Math.floor(w / 2))
327      x += w + 1
328      return at
329    })
330
331    if (l > 0) {
332      // The connector row: unrelated edge groups get their own spans, and crossings draw ┼.
333      const arms = Array.from({ length: total }, () => ({ u: false, d: false, l: false, r: false }))
334      const above = new Set(layers[l - 1]!.map(item => item.id))
335      const mine = new Set(items.map(item => item.id))
336      const here = edges.filter(([from, to]) => above.has(from) && mine.has(to))
337      const parent = new Map<string, string>()
338      const find = (a: string): string => {
339        const p = parent.get(a) ?? a
340        return p === a ? a : find(p)
341      }
342      for (const [from, to] of here) parent.set(find(to), find(from))
343      const groups = new Map<string, [string, string][]>()
344      for (const edge of here) groups.set(find(edge[0]), [...(groups.get(find(edge[0])) ?? []), edge])
345      for (const group of groups.values()) {
346        const ups = new Set(group.map(([from]) => centre.get(from)!))
347        const downs = new Set(group.map(([, to]) => centre.get(to)!))
348        const xs = [...ups, ...downs]
349        const lo = Math.min(...xs)
350        const hi = Math.max(...xs)
351        for (let i = lo; i <= hi; i++) {
352          const arm = arms[i]!
353          if (ups.has(i)) arm.u = true
354          if (downs.has(i)) arm.d = true
355          if (i > lo) arm.l = true
356          if (i < hi) arm.r = true
357        }
358      }
359      const key = (a: { u: boolean; d: boolean; l: boolean; r: boolean }) => (a.u ? 'u' : '') + (a.d ? 'd' : '') + (a.l ? 'l' : '') + (a.r ? 'r' : '')
360      out.push([{ text: arms.map(arm => CORNERS[key(arm)]!).join('').trimEnd() }])
361    }
362
363    // Three rows of boxes, each row cut into segments so a box takes its state's colour.
364    for (let r = 0; r < 3; r++) {
365      const segs: Seg[] = []
366      let cursor = 0
367      for (const { item, x: bx, w } of placed) {
368        if (bx > cursor) segs.push({ text: ' '.repeat(bx - cursor) })
369        if (item.kind === 'lane') {
370          segs.push({ text: '│' })
371          cursor = bx + 1
372          continue
373        }
374        const node = item.node
375        const mid = Math.floor(w / 2)
376        const { chars, seg: border, isHeavy } = borderOf(node, pulse)
377        const [h, v, tl, tr, bl, br] = chars as [string, string, string, string, string, string]
378        if (r === 0) {
379          const top = [...`${tl}${h.repeat(w - 2)}${tr}`]
380          if (hasIn.has(item.id)) top[mid] = isHeavy ? '┻' : '┴'
381          segs.push({ ...border, text: top.join('') })
382        } else if (r === 2) {
383          const bottom = [...`${bl}${h.repeat(w - 2)}${br}`]
384          if (hasOut.has(item.id)) bottom[mid] = isHeavy ? '┳' : '┬'
385          segs.push({ ...border, text: bottom.join('') })
386        } else {
387          const name = item.name + ' '.repeat(Math.max(0, w - 6 - width(item.name)))
388          const tone = toneOf(node.look)
389          segs.push({ ...border, text: `${v} ` })
390          segs.push({ text: glyph(node.look), ...(tone === undefined ? {} : { tone }), dim: node.look === 'cancelled' || node.look === 'skipped' })
391          segs.push({ text: ` ${name}`, pick: node.id })
392          segs.push({ ...border, text: ` ${v}` })
393        }
394        cursor = bx + w
395      }
396      out.push(segs)
397    }
398    for (const note of notes.get(l) ?? []) out.push([{ text: `  ${note}`, dim: true }])
399  })
400  return out
401}
402
403function listLines({ layers, notes }: Plan, pulse: boolean): Seg[][] {
404  const out: Seg[][] = []
405  layers.forEach((items, l) => {
406    const nodes = items.flatMap(item => (item.kind === 'node' ? [item.node] : []))
407    nodes.forEach((node, i) => {
408      const mark = nodes.length === 1 ? '' : i === nodes.length - 1 ? '└ ' : '├ '
409      const tone = toneOf(node.look)
410      // A running node's mark flashes as its box would: bold on one beat, dim on the next.
411      const flash = node.look === 'running' && !node.isGate ? (pulse ? { bold: true } : { dim: true }) : {}
412      out.push([
413        { text: `${mark}` },
414        { text: glyph(node.look), ...(tone === undefined ? {} : { tone }), ...(node.isGate ? { bold: true } : {}), ...flash },
415        { text: ` ${nameAt(node, 2)}`, pick: node.id },
416      ].filter(seg => seg.text !== ''))
417    })
418    for (const note of notes.get(l) ?? []) out.push([{ text: `  ${note}`, dim: true }])
419  })
420  return out
421}
422
423/**
424 * Lays the nodes out in layers by depth, giving way one step at a time while
425 * the widest layer is wider than `columns`: whole names, names without their
426 * include prefix, names cut to 10 characters, skip edges as notes instead of
427 * lanes, then the whole run as a list. A wide layer is never stacked into one
428 * box, and a skip edge is never dropped. `pulse` is the flash's beat: a running
429 * node is drawn heavy and bold while it is on, light and dim while it is off.
430 * With no flash running it stays on.
431 */
432export function layout(nodes: readonly DrawNode[], columns: number, pulse = true): Drawn {
433  if (nodes.length === 0) return { lines: [], step: 1 }
434  for (const step of [1, 2, 3, 4] as const) {
435    const planned = plan(nodes, step)
436    if (Math.max(...planned.layers.map(layerWidth)) <= columns) return { lines: graphLines(planned, pulse), step }
437  }
438  return { lines: listLines(plan(nodes, 4), pulse), step: 5 }
439}
440
hooks/graph-view.tsx 275 lines
1// The Graph sub-tab: the picked run's nodes as box-drawing text, include
2// blocks, loop groups and sub-runs folded, each box a press that opens Log.
3
4import type { Elements, RenderElement } from 'claude-code'
5
6import type { ArchonView, Detail, GraphNode, Run, RunEvent } from '../types'
7import { layout } from './graph'
8import type { DrawNode, Seg } from './graph'
9import type { Live } from './log'
10import { hasEnded, needsYou, standing, subRunsOf, waitNode } from './runs'
11import type { Look } from './text'
12import { duration, fit } from './text'
13
14/** A node's look from the events naming it: the last of started, completed, failed, skipped. */
15function lookFrom(events: readonly RunEvent[], step: string, iteration?: number): Look {
16  let look: Look = 'pending'
17  for (const e of events) {
18    if (e.step !== step || (iteration !== undefined && e.iteration !== iteration)) continue
19    if (e.type === 'node_started') look = 'running'
20    else if (e.type === 'node_completed') look = 'completed'
21    else if (e.type === 'node_failed') look = 'failed'
22    else if (e.type === 'node_skipped') look = 'skipped'
23    else if (e.type === 'node_suspended') look = 'paused'
24  }
25  return look
26}
27
28/** How a set of looks reads as one: any failure, then any work, then all done, else waiting. */
29function foldLook(looks: readonly Look[]): Look {
30  if (looks.some(look => look === 'failed')) return 'failed'
31  if (looks.some(look => look === 'running' || look === 'paused' || look === 'approval' || look === 'action')) return 'running'
32  if (looks.length > 0 && looks.every(look => look === 'completed' || look === 'skipped')) return 'completed'
33  return 'pending'
34}
35
36const isDone = (look: Look) => look === 'completed' || look === 'skipped'
37
38/** The rounds a loop group has started, from its body's events. */
39export function roundsOf(events: readonly RunEvent[], group: string): number {
40  return Math.max(0, ...events.filter(e => e.step.startsWith(`${group}.`)).map(e => e.iteration))
41}
42
43function subRunLook(subRun: Run, runs: readonly Run[], details: Readonly<Record<string, Detail>>): { look: Look; isGate: boolean } {
44  if (needsYou(subRun, runs, details) !== undefined) return { look: 'approval', isGate: true }
45  return { look: subRun.status === 'paused' ? 'paused' : subRun.status, isGate: false }
46}
47
48/** The sub-runs a `workflow:` node started. */
49export function nodeSubRuns(run: Run, node: GraphNode, runs: readonly Run[], workflowNodes: number): Run[] {
50  return subRunsOf(run, runs).filter(subRun => subRun.parentNodeId === node.id || (subRun.parentNodeId === '' && workflowNodes === 1))
51}
52
53export type Graphed = {
54  draw: DrawNode[]
55  /** What a press on each box picks. */
56  picks: Map<string, { kind: 'node' | 'block' | 'loop' | 'workflow'; id: string; subRuns: Run[] }>
57}
58
59/**
60 * A node's look from the followed run log, where it names the node: a loop
61 * group runs while any of its body runs. Undefined where the log is silent.
62 */
63function liveLook(live: ReadonlyMap<string, Look> | undefined, node: GraphNode): Look | undefined {
64  if (live === undefined) return undefined
65  if (node.kind === 'loop_group' && [...live].some(([id, look]) => id.startsWith(`${node.id}.`) && look === 'running')) return 'running'
66  return live.get(node.id)
67}
68
69/**
70 * The boxes of a run's graph: node states from its events, or from `live`, its
71 * followed run log, where that names them; gates in `warning`, blocks and loops
72 * folded unless opened. A gate's look wins over both.
73 */
74export function drawNodes(nodes: readonly GraphNode[], run: Run, runs: readonly Run[], details: Readonly<Record<string, Detail>>, view: ArchonView, live?: ReadonlyMap<string, Look>): Graphed {
75  const events = details[run.id]?.events ?? []
76  const found = standing(run, runs, details[run.id])
77  const gateNode = waitNode(found)
78  const picks: Graphed['picks'] = new Map()
79  const workflows = nodes.filter(node => node.kind === 'workflow').length
80  const looks = new Map<string, DrawNode>()
81  for (const node of nodes) {
82    let look = lookFrom(events, node.id)
83    let label = node.id
84    let isGate = node.id === gateNode
85    picks.set(node.id, { kind: 'node', id: node.id, subRuns: [] })
86    let isFromSubRuns = false
87    if (node.kind === 'loop_group') {
88      const round = roundsOf(events, node.id)
89      if (round > 0) look = foldLook(node.body.map(body => lookFrom(events, `${node.id}.${body.id}`, round)))
90      label = round > 0 ? `${node.id} ⟳${round}` : node.id
91      picks.set(node.id, { kind: 'loop', id: node.id, subRuns: [] })
92    } else if (node.kind === 'workflow') {
93      const subRuns = nodeSubRuns(run, node, runs, workflows)
94      picks.set(node.id, { kind: 'workflow', id: node.id, subRuns })
95      if (subRuns.length === 1) {
96        const shown = subRunLook(subRuns[0]!, runs, details)
97        look = shown.look
98        isGate = isGate || shown.isGate
99        label = `↳ ${subRuns[0]!.workflow}`
100        isFromSubRuns = true
101      } else if (subRuns.length > 1) {
102        const subLooks = subRuns.map(subRun => subRunLook(subRun, runs, details))
103        look = foldLook(subLooks.map(s => s.look))
104        isGate = isGate || subLooks.some(s => s.isGate)
105        label = `↳ ${subRuns.filter(subRun => hasEnded(subRun)).length}/${subRuns.length}`
106        isFromSubRuns = true
107      } else label = `↳ ${node.workflow || node.id}`
108    }
109    // A sub-run's own status says more than the parent's log about its node.
110    if (!isFromSubRuns) look = liveLook(live, node) ?? look
111    if (node.id === gateNode) look = found.kind === 'approval' ? 'approval' : 'action'
112    looks.set(node.id, { id: node.id, label, look, deps: node.deps, isGate, block: node.block })
113  }
114
115  // Include blocks fold to one box unless opened: `deliver 3/5`.
116  const blockOf = (node: DrawNode) => node.block.split('__')[0] ?? ''
117  const folded = new Set(nodes.map(node => blockOf(looks.get(node.id)!)).filter(block => block !== '' && !view.includes.includes(`${run.id}:${block}`)))
118  const out: DrawNode[] = []
119  const placed = new Set<string>()
120  for (const node of nodes) {
121    const drawn = looks.get(node.id)!
122    const block = blockOf(drawn)
123    if (!folded.has(block)) {
124      out.push(drawn)
125      continue
126    }
127    if (placed.has(block)) continue
128    placed.add(block)
129    const members = [...looks.values()].filter(n => blockOf(n) === block)
130    const ids = new Set(members.map(n => n.id))
131    const done = members.filter(n => isDone(n.look)).length
132    out.push({
133      id: `block:${block}`,
134      label: `${block} ${done}/${members.length}`,
135      look: foldLook(members.map(n => n.look)),
136      deps: [...new Set(members.flatMap(n => n.deps).filter(dep => !ids.has(dep)))],
137      isGate: members.some(n => n.isGate),
138      block: '',
139    })
140    picks.set(`block:${block}`, { kind: 'block', id: block, subRuns: [] })
141  }
142  // Waits on a folded block's nodes wait on the block.
143  const boxOf = (id: string) => {
144    const drawn = looks.get(id)
145    const block = drawn === undefined ? '' : blockOf(drawn)
146    return folded.has(block) ? `block:${block}` : id
147  }
148  return {
149    draw: out.map(node => ({ ...node, deps: [...new Set(node.deps.map(boxOf).filter(dep => dep !== node.id))] })),
150    picks,
151  }
152}
153
154/** A loop group's body as one round drew it: the current one, or an earlier one picked with ‹ ›. `live` speaks only for the current round. */
155export function roundNodes(group: GraphNode, events: readonly RunEvent[], round: number, live?: ReadonlyMap<string, Look>): DrawNode[] {
156  return group.body.map(body => {
157    const id = `${group.id}.${body.id}`
158    return { id, label: body.id, look: live?.get(id) ?? lookFrom(events, id, round), deps: body.deps.map(dep => `${group.id}.${dep}`), isGate: false, block: '' }
159  })
160}
161
162/** When a node's current run started, from its events: the last `node_started` naming it; 0 when none does. */
163function startedAt(events: readonly RunEvent[], step: string): number {
164  return [...events].reverse().find(e => e.type === 'node_started' && e.step === step)?.at ?? 0
165}
166
167/**
168 * The line under a live run's header saying what runs now: the running nodes,
169 * how long the longest has run, and the newest tool call or model text, once
170 * it was written after the newest of them started. Undefined when nothing runs.
171 */
172export function activityLine(live: Live | undefined, events: readonly RunEvent[], now: number): string | undefined {
173  if (live === undefined || live.running.length === 0) return undefined
174  const starts = live.running.map(({ node, since }) => since || startedAt(events, node))
175  const known = starts.filter(at => at > 0)
176  const longest = known.length === 0 ? '' : ` ${duration(now - Math.min(...known))}`
177  const newestStart = Math.max(0, ...known)
178  const latest = live.latest !== undefined && live.latest.text !== '' && live.latest.at >= newestStart ? live.latest : undefined
179  const doing = latest === undefined ? '' : ` · ${latest.text}${latest.at > 0 ? ` · ${duration(now - latest.at)} ago` : ''}`
180  return `${live.running.map(({ node }) => node).join(', ')}${longest}${doing}`
181}
182
183export type GraphProps = {
184  ui: Elements[keyof Elements]
185  run: Run | undefined
186  runs: readonly Run[]
187  details: Readonly<Record<string, Detail>>
188  nodes: GraphNode[] | null | undefined
189  view: ArchonView
190  /** The run's followed run log, while the follower is on this run; undefined otherwise. */
191  live: Live | undefined
192  /** The flash's beat: on for heavy, bold borders on running nodes, off for light, dim ones. */
193  pulse: boolean
194  now: number
195  width: number
196  /** The run's page in Archon's web UI, or '' when it is not linked. */
197  link: string
198  onPick: (id: string) => void
199  onFold: (block: string) => void
200  onRound: (round: number) => void
201  onParent: (parent: Run) => void
202  onSubRun: (subRun: Run) => void
203}
204
205/** The drawn lines of a graph as elements: a box's name is a press that picks it. */
206export function segLines(ui: GraphProps['ui'], lines: readonly Seg[][], onPick: (id: string) => void, prefix = 'node'): RenderElement[] {
207  const { Box, Text, Button } = ui
208  return lines.map(line => (
209    <Box flexDirection="row">
210      {line.map(seg => (seg.pick !== undefined
211        ? <Button key={`${prefix}-${seg.pick}`} plain label={seg.text} onPress={() => onPick(seg.pick!)} />
212        : <Text {...(seg.tone === undefined ? {} : { color: seg.tone })} {...(seg.bold === true ? { bold: true } : {})} {...(seg.dim === true ? { dimColor: true } : {})}>{seg.text}</Text>))}
213    </Box>
214  ))
215}
216
217export function graphBody(props: GraphProps): RenderElement[] {
218  const { ui, run, view, width } = props
219  const { Box, Text, Button, Link } = ui
220  if (run === undefined) return [<Text dimColor>Pick a run in Runs to see its graph.</Text>]
221  const parent = props.runs.find(other => other.id === run.parentId)
222  const lines: RenderElement[] = []
223  const status = `${run.status}  ${duration((hasEnded(run) ? run.completedAt : props.now) - run.startedAt)}`
224  lines.push(
225    <Box flexDirection="row" columnGap={1}>
226      {parent !== undefined && <Button key="graph-parent" plain dimColor hotkey="b" label={`‹ ${parent.workflow}`} onPress={() => props.onParent(parent)} />}
227      <Text bold wrap="truncate-end">{fit(`${parent === undefined ? '' : `${parent.workflow} › `}${run.workflow}  ${status}`, Math.max(8, width - 12))}</Text>
228      {props.link !== '' && <Link key="archon-link" href={props.link} label="↗ Archon" />}
229    </Box>,
230  )
231  const events = props.details[run.id]?.events ?? []
232  const doing = hasEnded(run) ? undefined : activityLine(props.live, events, props.now)
233  if (doing !== undefined) {
234    lines.push(
235      <Box flexDirection="row">
236        <Text color="success" {...(props.pulse ? { bold: true } : { dimColor: true })}>●</Text>
237        <Text wrap="truncate-end">{` ${fit(doing, Math.max(8, width - 2))}`}</Text>
238      </Box>,
239    )
240  }
241  if (props.nodes === undefined) return [...lines, <Text dimColor>Reading the run's workflow…</Text>]
242  if (props.nodes === null || props.nodes.length === 0) return [...lines, <Text dimColor>This run's workflow source can't be read.</Text>]
243
244  const graphed = drawNodes(props.nodes, run, props.runs, props.details, view, props.live?.looks)
245  for (const block of view.includes.filter(entry => entry.startsWith(`${run.id}:`)).map(entry => entry.slice(run.id.length + 1))) {
246    lines.push(<Button key={`fold-${block}`} plain dimColor label={`▾ ${block}`} onPress={() => props.onFold(block)} />)
247  }
248  lines.push(...segLines(ui, layout(graphed.draw, width, props.pulse).lines, props.onPick))
249
250  // A picked loop group: its round's body as a small graph, stepping through earlier rounds.
251  const group = view.loop.startsWith(`${run.id}:`) ? props.nodes.find(node => node.id === view.loop.slice(run.id.length + 1)) : undefined
252  if (group !== undefined) {
253    const current = roundsOf(events, group.id)
254    const round = view.round > 0 && view.round <= current ? view.round : current
255    lines.push(
256      <Box flexDirection="row">
257        <Text>{`round ${round} · `}</Text>
258        <Button key="round-back" plain label="‹" onPress={() => props.onRound(Math.max(1, round - 1))} />
259        <Text> </Text>
260        <Button key="round-on" plain label="›" onPress={() => props.onRound(Math.min(current, round + 1))} />
261      </Box>,
262    )
263    lines.push(...segLines(ui, layout(roundNodes(group, events, round, round === current ? props.live?.looks : undefined), width, props.pulse).lines, props.onPick, 'body'))
264  }
265
266  // A fan-out's sub-runs, listed once its box is picked.
267  for (const node of props.nodes.filter(n => n.kind === 'workflow' && view.fanouts.includes(`${run.id}:${n.id}`))) {
268    const pick = graphed.picks.get(node.id)
269    for (const subRun of pick?.subRuns ?? []) {
270      lines.push(<Button key={`sub-run-${subRun.id}`} plain label={fit(`↳ ${subRun.workflow}  ${subRun.status}`, width - 2)} onPress={() => props.onSubRun(subRun)} />)
271    }
272  }
273  return lines
274}
275
hooks/log.ts 189 lines
1// A run's run log: transcript lines as rows, each row's node, and the window
2// of the newest 60,000 drawn characters the pane keeps.
3
4import type { LogRow, LogWindow, RunEvent } from '../types'
5import { dollars, duration, firstLine, fit, msOf, size } from './text'
6import type { Look } from './text'
7
8/** The most drawn characters the window keeps, and a file's read view shows. */
9export const WINDOW_CHARS = 60_000
10/** The most an opened fold draws. */
11export const FOLD_CHARS = 4_000
12/** The lines of a bash node's printout shown. */
13const EXEC_LINES = 20
14
15export const EMPTY_WINDOW: LogWindow = { runId: '', rows: [], dropped: 0, taken: 0, open: [], tools: 0, end: '', isMissing: false, node: '' }
16
17function isObject(value: unknown): value is Record<string, unknown> {
18  return typeof value === 'object' && value !== null && !Array.isArray(value)
19}
20
21function str(value: unknown): string {
22  return typeof value === 'string' ? value : ''
23}
24
25/** Whole lines out of a spawn's chunks: what came before plus this chunk, with a partial last line held for the next. */
26export function splitChunk(held: string, chunk: string): { lines: string[]; held: string } {
27  const text = held + chunk
28  const at = text.lastIndexOf('\n')
29  if (at < 0) return { lines: [], held: text }
30  return { lines: text.slice(0, at).split('\n').map(line => line.replace(/\r$/, '')), held: text.slice(at + 1) }
31}
32
33/** The argument a tool row names: a command, a path, a pattern, or the input's first text. */
34function mainArgument(input: Record<string, unknown>): { key: string; text: string } {
35  for (const key of ['command', 'pattern', 'file_path', 'path', 'url', 'query', 'description', 'prompt']) {
36    if (str(input[key]) !== '') return { key, text: str(input[key]) }
37  }
38  const first = Object.entries(input).find(([, value]) => typeof value === 'string')
39  return first === undefined ? { key: '', text: '' } : { key: first[0], text: first[1] as string }
40}
41
42/** A tool row: the tool and its main argument on one line, the full input behind `▸` when there is more of it. */
43function toolRow(name: string, input: Record<string, unknown>): { text: string; full: string } {
44  const main = mainArgument(input)
45  const content = str(input.content)
46  const sized = name === 'Write' && content !== '' ? ` (${size(content.length)})` : ''
47  const line = `${name} ${fit(main.text.split('\n')[0] ?? '', 200)}${sized}`.trim()
48  const whole = Object.entries(input).map(([key, value]) => `${key}: ${typeof value === 'string' ? value : JSON.stringify(value)}`).join('\n')
49  // The full input is folded behind ▸ only when it says much more than the line does.
50  const isMore = whole.length > line.length + 40 || (name === 'Write' && content !== '') || Object.values(input).some(value => typeof value === 'string' && value.includes('\n'))
51  return { text: isMore ? `${line} ▸` : line, full: isMore ? whole : '' }
52}
53
54/** The tail of a printout: its last `count` lines. */
55function tail(text: string, count: number): string[] {
56  const lines = text.replace(/\n+$/, '').split('\n').filter(line => line !== '')
57  return lines.slice(-count)
58}
59
60/**
61 * The rows one transcript line makes. Transcript rows do not name their node:
62 * a tool row is counted so the events can name it, and any other row belongs
63 * to the nodes open when it was written. A node marker names its node by its
64 * path (`fix-cycle.fix` for a loop's body node), as the run's events do.
65 */
66export function rowsOf(text: string, lineNo: number, window: LogWindow): { rows: LogRow[]; window: LogWindow } {
67  let entry: unknown
68  try {
69    entry = JSON.parse(text)
70  } catch {
71    return { rows: [], window }
72  }
73  if (!isObject(entry)) return { rows: [], window }
74  const execution = isObject(entry.execution) ? entry.execution : {}
75  const node = str(execution.path) || str(entry.step) || (isObject(execution.node) ? str(execution.node.id) : '')
76  const key = `l${lineNo}`
77  const written = msOf(entry.ts)
78  const at = (row: Omit<LogRow, 'key' | 'nodes' | 'tool' | 'full' | 'at'> & Partial<LogRow>): LogRow => ({ key, nodes: window.open, tool: -1, full: '', at: written, ...row })
79  switch (entry.type) {
80    case 'node_start':
81      return { rows: [at({ kind: 'start', text: `▶ ${node}`, nodes: [node] })], window: { ...window, open: window.open.includes(node) ? window.open : [...window.open, node] } }
82    case 'node_complete': {
83      const spent = [typeof entry.duration_ms === 'number' ? duration(entry.duration_ms) : '', typeof entry.cost_usd === 'number' ? dollars(entry.cost_usd) : ''].filter(part => part !== '')
84      return { rows: [at({ kind: 'end', text: `✓ ${node}${spent.length === 0 ? '' : ` ${spent.join(' ')}`}`, nodes: [node] })], window: { ...window, open: window.open.filter(open => open !== node) } }
85    }
86    case 'node_error':
87    case 'node_failed':
88      return { rows: [at({ kind: 'error', text: `✗ ${node}: ${str(entry.error) || str(entry.message)}`, nodes: [node] })], window: { ...window, open: window.open.filter(open => open !== node) } }
89    case 'node_skipped':
90      return { rows: [at({ kind: 'skip', text: `– ${node} skipped${str(entry.reason) === '' ? '' : `: ${str(entry.reason)}`}`, nodes: [node] })], window }
91    case 'assistant':
92      return { rows: [at({ kind: 'text', text: str(entry.content) })], window }
93    case 'tool': {
94      const drawn = toolRow(str(entry.tool_name) || 'tool', isObject(entry.tool_input) ? entry.tool_input : {})
95      return { rows: [at({ kind: 'tool', text: drawn.text, full: drawn.full, tool: window.tools })], window: { ...window, tools: window.tools + 1 } }
96    }
97    case 'exec_output': {
98      const out = [...tail(str(entry.stdout_tail), EXEC_LINES), ...tail(str(entry.stderr_tail), EXEC_LINES)]
99      return { rows: out.length === 0 ? [] : [at({ kind: 'exec', text: out.join('\n') })], window }
100    }
101    default:
102      // Heartbeats (watchdog_reset), workflow_start and workflow_complete draw nothing.
103      return { rows: [], window }
104  }
105}
106
107/** The characters a row draws in the window. */
108export function rowChars(row: LogRow): number {
109  return row.text.length
110}
111
112/** Keeps the newest rows that fit in 60,000 drawn characters; older rows drop first. */
113export function capWindow(window: LogWindow): LogWindow {
114  let total = window.rows.reduce((sum, row) => sum + rowChars(row), 0)
115  let cut = 0
116  while (total > WINDOW_CHARS && cut < window.rows.length) {
117    total -= rowChars(window.rows[cut]!)
118    cut++
119  }
120  return cut === 0 ? window : { ...window, rows: window.rows.slice(cut), dropped: window.dropped + cut }
121}
122
123/** Takes whole transcript lines into the window, numbering them from `from + 1`; lines up to `skip` were taken already, and only rows `keep` passes stay. */
124export function take(window: LogWindow, lines: readonly string[], from: number, skip: number, keep: (row: LogRow) => boolean = () => true): LogWindow {
125  let next = window
126  let lineNo = from
127  const rows: LogRow[] = []
128  for (const text of lines) {
129    lineNo++
130    if (lineNo <= skip) continue
131    const made = rowsOf(text, lineNo, next)
132    next = made.window
133    rows.push(...made.rows.filter(keep))
134  }
135  return capWindow({ ...next, rows: [...next.rows, ...rows], taken: Math.max(next.taken, lineNo) })
136}
137
138/** The steps of the run's tool calls in order: the nth names the node of the transcript's nth tool row. */
139export function toolSteps(events: readonly RunEvent[]): string[] {
140  return events.filter(e => e.type === 'tool_called').map(e => e.step)
141}
142
143/** The nodes a row belongs to: a tool row's from the events, any other row's from the nodes open when it was written. */
144export function nodesOf(row: LogRow, steps: readonly string[]): string[] {
145  if (row.kind === 'tool') {
146    const step = steps[row.tool]
147    if (step !== undefined && step !== '') return [step]
148  }
149  return row.nodes
150}
151
152/** Whether a row shows under `node`: all rows with no node picked. */
153export function isUnder(row: LogRow, node: string, steps: readonly string[]): boolean {
154  return node === '' || nodesOf(row, steps).includes(node)
155}
156
157/** What a followed run log says now, read from its window. */
158export type Live = {
159  /** Each node the window names, by its last marker row; nodes open at its newest line are running. */
160  looks: ReadonlyMap<string, Look>
161  /**
162   * The nodes open at the newest line, innermost only (a loop's body, not the
163   * loop too), with when each started; 0 when its start row dropped off the window.
164   */
165  running: readonly { node: string; since: number }[]
166  /** The newest tool call or model text and when it was written; undefined before any. */
167  latest: { text: string; at: number } | undefined
168}
169
170export function liveOf(window: LogWindow): Live {
171  const looks = new Map<string, Look>()
172  const started = new Map<string, number>()
173  let latest: Live['latest']
174  for (const row of window.rows) {
175    const node = row.nodes[0] ?? ''
176    if (row.kind === 'start') {
177      looks.set(node, 'running')
178      started.set(node, row.at || 0)
179    } else if (row.kind === 'end') looks.set(node, 'completed')
180    else if (row.kind === 'error') looks.set(node, 'failed')
181    else if (row.kind === 'skip') looks.set(node, 'skipped')
182    // A tool row's ▸ opens its fold in Log; here it opens nothing.
183    else if (row.kind === 'tool' || row.kind === 'text') latest = { text: firstLine(row.text).replace(/ ▸$/, ''), at: row.at || 0 }
184  }
185  for (const node of window.open) looks.set(node, 'running')
186  const innermost = window.open.filter(node => !window.open.some(other => other.startsWith(`${node}.`)))
187  return { looks, running: innermost.map(node => ({ node, since: started.get(node) ?? 0 })), latest }
188}
189
hooks/log-view.tsx 209 lines
1// The Log sub-tab: the picked run's run log, cut to the picked node, with the
2// files the run kept and a read view for one of them.
3
4import type { Elements, RenderElement } from 'claude-code'
5
6import type { ArchonView, Detail, LogRow, LogWindow, Run, RunFile } from '../types'
7import { FOLD_CHARS, isUnder, nodesOf, toolSteps, WINDOW_CHARS } from './log'
8import { shortId } from './runs-view'
9import { size } from './text'
10
11/** The most wrapped lines a node's output or error shows before the rest folds. */
12const OUTPUT_LINES = 10
13
14/** A file of the run, as opened in the read view. */
15export type OpenedFile = {
16  path: string
17  text: string
18  isBinary: boolean
19  size: number
20}
21
22export type LogProps = {
23  ui: Elements[keyof Elements]
24  run: Run | undefined
25  runs: readonly Run[]
26  detail: Detail | undefined
27  window: LogWindow
28  view: ArchonView
29  width: number
30  /** The run's page in Archon's web UI, or '' when it is not linked. */
31  link: string
32  /** The run's files folder on disk, to tell a Write row of a file it kept. */
33  filesFolder: string
34  file: OpenedFile | undefined
35  notice: string
36  onFold: (key: string) => void
37  onAll: () => void
38  onFiles: () => void
39  onFile: (path: string) => void
40  onBack: () => void
41  onOpen: () => void
42  onMention: () => void
43}
44
45/** A run log's file path relative to the run's files folder; '' when it is outside it. */
46export function keptPath(path: string, folder: string): string {
47  const slashed = path.replace(/\\/g, '/')
48  const base = folder.replace(/\\/g, '/').replace(/\/+$/, '')
49  if (base === '') return ''
50  return slashed.toLowerCase().startsWith(`${base.toLowerCase()}/`) ? slashed.slice(base.length + 1) : ''
51}
52
53/** Lines of `text` cut at `count` wrapped lines at `width`, and how many lines were left out. */
54function cutLines(text: string, count: number, width: number): { shown: string[]; more: number } {
55  const lines = text.replace(/\n+$/, '').split('\n')
56  const shown: string[] = []
57  let used = 0
58  for (const line of lines) {
59    const rows = Math.max(1, Math.ceil(Array.from(line).length / Math.max(8, width)))
60    if (used + rows > count) break
61    shown.push(line)
62    used += rows
63  }
64  return { shown, more: lines.length - shown.length }
65}
66
67function header(props: LogProps, run: Run): RenderElement {
68  const { Box, Text, Link } = props.ui
69  const parent = props.runs.find(other => other.id === run.parentId)
70  const name = `${parent === undefined ? '' : `${parent.workflow} › `}${run.workflow}`
71  return (
72    <Box key="loghead" flexDirection="row" columnGap={1}>
73      <Text bold wrap="truncate-end">{`${name} · ${shortId(run.id)} · ${run.status}`}</Text>
74      {props.link !== '' && <Link key="archon-link" href={props.link} label="↗ Archon" />}
75    </Box>
76  )
77}
78
79function filesLines(props: LogProps, files: readonly RunFile[]): RenderElement[] {
80  const { Box, Button } = props.ui
81  if (files.length === 0) return []
82  const count = `${files.length} file${files.length === 1 ? '' : 's'}`
83  const names = files.map(file => file.path.slice(file.path.lastIndexOf('/') + 1)).join(' · ')
84  if (!props.view.isFilesOpen) return [<Button key="files" plain label={`▸ ${count}: ${names}`} onPress={props.onFiles} />]
85  return [
86    <Button key="files" plain label={`▾ ${count}`} onPress={props.onFiles} />,
87    ...files.map(file => (
88      <Box key={`filerow-${file.path}`} flexDirection="row">
89        <Box flexShrink={0}><Button key={`file-${file.path}`} plain label={`${file.path}  ${size(file.size)}`} onPress={() => props.onFile(file.path)} /></Box>
90      </Box>
91    )),
92  ]
93}
94
95/** The read view of one file the run kept: Markdown for `.md`, Code for anything else, capped at 60,000 characters. */
96function readView(props: LogProps): RenderElement[] {
97  const { Box, Text, Button, Markdown, Code } = props.ui
98  const lines: RenderElement[] = [
99    <Box key="filehead" flexDirection="row" columnGap={2}>
100      <Button key="file-back" plain hotkey="b" label="back" onPress={props.onBack} />
101      <Button key="file-open" plain hotkey="o" label="open" onPress={props.onOpen} />
102      <Button key="file-mention" plain dimColor label="@ prompt" onPress={props.onMention} />
103    </Box>,
104    <Text bold wrap="truncate-end">{props.view.file}</Text>,
105  ]
106  if (props.notice !== '') lines.push(<Text dimColor>{props.notice}</Text>)
107  const file = props.file
108  if (file === undefined || file.path !== props.view.file) return [...lines, <Text dimColor>Reading…</Text>]
109  if (file.isBinary) return [...lines, <Text dimColor>{`A binary file, ${size(file.size)}.`}</Text>]
110  const shown = file.text.slice(0, WINDOW_CHARS)
111  lines.push(file.path.toLowerCase().endsWith('.md') ? <Markdown key="filetext" text={shown} /> : <Code key="filetext" source={shown} />)
112  if (file.text.length > WINDOW_CHARS) lines.push(<Text dimColor>{`… ${size(file.text.length - WINDOW_CHARS)} more: open it outside`}</Text>)
113  return lines
114}
115
116export function logBody(props: LogProps): RenderElement[] {
117  const { ui, run, view, width } = props
118  const { Box, Text, Button } = ui
119  if (run === undefined) return [<Text dimColor>Pick a run in Runs to see its log.</Text>]
120  if (view.file !== '') return [header(props, run), ...readView(props)]
121  const events = props.detail?.events ?? []
122  const steps = toolSteps(events)
123  const window = props.window.runId === run.id ? props.window : undefined
124  const lines: RenderElement[] = [header(props, run)]
125  if (view.node !== '') {
126    lines.push(
127      <Box key="logcut" flexDirection="row" columnGap={1}>
128        <Text dimColor>{`cut to ${view.node} ·`}</Text>
129        <Button key="log-all" plain dimColor hotkey="a" label="all nodes" onPress={props.onAll} />
130      </Box>,
131    )
132  }
133  lines.push(...filesLines(props, props.detail?.files ?? []))
134  if (window === undefined) return [...lines, <Text dimColor>Reading the run log…</Text>]
135
136  if (window.dropped > 0) lines.push(<Box key="log-dropped"><Text dimColor>{`… ${window.dropped} earlier rows not kept`}</Text></Box>)
137  if (window.isMissing) lines.push(<Box key="log-missing"><Text dimColor>This run's transcript is missing; node output and errors still show from its events.</Text></Box>)
138
139  const outputOf = (node: string, key: string) => {
140    for (const e of events.filter(ev => ev.step === node && ((ev.type === 'node_completed' && ev.output !== '') || (ev.type === 'node_failed' && ev.error !== '')))) {
141      const isError = e.type === 'node_failed'
142      const foldKey = `out-${key}-${isError ? 'error' : 'output'}`
143      const isOpen = view.fold === foldKey
144      const full = isError ? e.error : e.output
145      const cut = cutLines(isOpen ? full.slice(0, FOLD_CHARS) : full, isOpen ? Number.MAX_SAFE_INTEGER : OUTPUT_LINES, width)
146      cut.shown.forEach((text, i) => lines.push(
147        <Box key={`log-${foldKey}-${i}`}>{isError ? <Text color="error" wrap="wrap">{text}</Text> : <Text dimColor wrap="wrap">{text}</Text>}</Box>,
148      ))
149      if (isOpen && full.length > FOLD_CHARS) lines.push(<Box key={`log-${foldKey}-rest`}><Text dimColor>{`… ${size(full.length - FOLD_CHARS)} more not shown`}</Text></Box>)
150      if (cut.more > 0) lines.push(<Box key={`log-${foldKey}-more`}><Button key={foldKey} plain dimColor label={`▸ ${cut.more} more lines`} onPress={() => props.onFold(foldKey)} /></Box>)
151    }
152  }
153
154  const ended = new Set<string>()
155  for (const row of window.rows) {
156    if (!isUnder(row, view.node, steps)) continue
157    const nodes = nodesOf(row, steps)
158    const isBody = row.kind === 'text' || row.kind === 'tool' || row.kind === 'exec'
159    const tag = !isBody ? '' : view.node === '' ? (nodes.length === 0 ? '' : `${nodes.join(' ∥ ')} · `) : nodes.length > 1 ? '∥ ' : ''
160    const tagText = tag === '' ? null : <Text dimColor>{tag}</Text>
161    if (row.kind === 'tool' && row.full !== '') {
162      lines.push(
163        <Box key={`log-${row.key}`} flexDirection="row">
164          {tagText}
165          <Button key={`fold-${row.key}`} plain label={row.text} onPress={() => props.onFold(row.key)} />
166        </Box>,
167      )
168      if (view.fold === row.key) lines.push(...foldLines(props, row))
169      continue
170    }
171    const tone = row.kind === 'error' ? { color: 'error' as const } : row.kind === 'skip' ? { dimColor: true } : {}
172    row.text.split('\n').forEach((text, i) => lines.push(
173      <Box key={`log-${row.key}${i === 0 ? '' : `-${i}`}`} flexDirection="row">
174        {i === 0 ? tagText : null}
175        <Text {...tone} wrap="wrap">{text}</Text>
176      </Box>,
177    ))
178    if (row.kind === 'end' || row.kind === 'error') {
179      const node = nodes[0] ?? ''
180      if (!ended.has(node)) {
181        ended.add(node)
182        outputOf(node, row.key)
183      }
184    }
185  }
186  // A skipped node never starts, so the transcript has no row for it: the events give it, with its cause.
187  for (const skipped of events.filter(e => e.type === 'node_skipped' && (view.node === '' || view.node === e.step))) {
188    lines.push(<Box key={`log-skip-${skipped.step}`}><Text dimColor wrap="wrap">{`– ${skipped.step} skipped${skipped.reason === '' ? '' : `: ${skipped.reason}`}`}</Text></Box>)
189  }
190  // Output and errors of nodes whose end marker is not in the window, as with a missing transcript.
191  const seen = new Set(events.filter(e => e.type === 'node_completed' || e.type === 'node_failed').map(e => e.step))
192  for (const node of seen) if (!ended.has(node) && (view.node === '' || view.node === node)) outputOf(node, `ev-${node}`)
193  if (window.end !== '') lines.push(<Box key="log-end"><Text {...(window.end.startsWith('✗') ? { color: 'error' as const } : {})}>{window.end}</Text></Box>)
194  return lines
195}
196
197function foldLines(props: LogProps, row: LogRow): RenderElement[] {
198  const { Box, Text, Button } = props.ui
199  const shown = row.full.slice(0, FOLD_CHARS)
200  const lines: RenderElement[] = shown.split('\n').map((text, i) => (
201    <Box key={`log-${row.key}-fold-${i}`}><Text dimColor wrap="wrap">{text}</Text></Box>
202  ))
203  if (row.full.length > FOLD_CHARS) lines.push(<Box key={`log-${row.key}-fold-more`}><Text dimColor>{`… ${size(row.full.length - FOLD_CHARS)} more not shown`}</Text></Box>)
204  const path = /^file_path: (.*)$/m.exec(row.full)?.[1] ?? ''
205  const kept = row.text.startsWith('Write ') ? keptPath(path, props.filesFolder) : ''
206  if (kept !== '') lines.push(<Box key={`log-${row.key}-fold-open`}><Button key={`write-open-${row.key}`} plain label={`open ${kept}`} onPress={() => props.onFile(kept)} /></Box>)
207  return lines
208}
209
hooks/notify.ts 145 lines
1// What reaches the person outside the pane: the status line, and toasts when
2// this project's runs need you, fail or finish, one per event across sessions.
3
4import type { Detail, Run } from '../types'
5import { hasEnded, needsYou, subRunsOf, topRuns, waitNode } from './runs'
6import type { NeedsYou } from './runs'
7import { duration, firstLine } from './text'
8
9/** The status line's length, about; parts are dropped to fit it. */
10const STATUS_ROOM = 60
11
12/** How a run is named outside the pane: its workflow, and the start of its id when another run here has the same workflow. */
13export function nameOf(run: Run, runs: readonly Run[]): string {
14  const isShared = topRuns(runs).some(other => other.id !== run.id && other.workflow === run.workflow)
15  return isShared ? `${run.workflow} ${run.id.slice(0, 6)}` : run.workflow
16}
17
18function needing(runs: readonly Run[], details: Readonly<Record<string, Detail>>): { run: Run; need: NeedsYou }[] {
19  return topRuns(runs).flatMap(run => {
20    const need = needsYou(run, runs, details)
21    return need === undefined ? [] : [{ run, need }]
22  })
23}
24
25/**
26 * The status line: `Archon`, then what needs you, what runs here, and what
27 * needs you elsewhere, each left out at zero; undefined with none of them.
28 * Cut to about 60 characters by dropping elsewhere, then running, then
29 * naming no run. A parent and its sub-runs count as one.
30 */
31export function statusText(runs: readonly Run[], details: Readonly<Record<string, Detail>>, elsewhere: number): string | undefined {
32  const needs = needing(runs, details)
33  const needIds = new Set(needs.map(entry => entry.run.id))
34  const running = topRuns(runs).filter(run => !needIds.has(run.id) && isFamilyLive(run, runs)).length
35  if (needs.length === 0 && running === 0 && elsewhere === 0) return undefined
36  if (needs.length === 0 && running === 0) return `Archon · ⏸ ${elsewhere} elsewhere`
37
38  const first = needs[0]
39  const counted = needs.length === 1 ? '⏸ 1 needs you' : `⏸ ${needs.length} need you`
40  const named = first === undefined || needs.length > 1
41    ? counted
42    : `⏸ ${nameOf(first.run, runs)} ${first.need.standing.kind === 'approval' ? 'needs approval' : 'needs you'}`
43  const parts = (need: string, isRunning: boolean, isElsewhere: boolean) =>
44    ['Archon', ...(needs.length > 0 ? [need] : []), ...(isRunning && running > 0 ? [`${running} running`] : []), ...(isElsewhere && elsewhere > 0 ? [`⏸ ${elsewhere} elsewhere`] : [])].join(' · ')
45  for (const text of [parts(named, true, true), parts(named, true, false), parts(named, false, false)]) {
46    if (Array.from(text).length <= STATUS_ROOM) return text
47  }
48  return parts(counted, false, false)
49}
50
51function isFamilyLive(run: Run, runs: readonly Run[], depth = 0): boolean {
52  if (!hasEnded(run)) return true
53  return depth < 10 && subRunsOf(run, runs).some(subRun => isFamilyLive(subRun, runs, depth + 1))
54}
55
56export type ToastEvent = {
57  runId: string
58  event: 'needs-you' | 'failed' | 'completed'
59  /** Which gate a needs-you toast was for, so a later gate on the same run toasts again. */
60  gate: string
61  text: string
62  timeoutMs: number
63}
64
65const STAYS = { 'needs-you': 15_000, 'failed': 8_000, 'completed': 4_000 } as const
66
67/** What a run that needs you is waiting on, as its toast says it. */
68function needText(run: Run, need: NeedsYou, runs: readonly Run[]): string {
69  const name = nameOf(run, runs)
70  const found = need.standing
71  if (found.kind === 'approval') {
72    const inSub = need.holder.id === run.id ? '' : ` (in sub-run ${need.holder.workflow})`
73    return `⏸ ${name} needs approval: ${firstLine(found.gate.message)}${inSub}`
74  }
75  if (found.kind === 'action') return `⏸ ${name} needs you: ${firstLine(found.wait.message)}`
76  if (found.kind === 'stranded') {
77    const subRun = found.subRun
78    const ending = subRun === undefined ? 'ended' : subRun.status === 'completed' ? 'done' : subRun.status
79    return `⏸ ${name} needs you: sub-run ${subRun?.workflow ?? 'sub-run'} was ${ending}`
80  }
81  return `⏸ ${name} needs you`
82}
83
84/**
85 * The toast-worthy events among this project's runs as they stand: each run
86 * on an approval, action needed or stranded (an unreadable gate is counted but
87 * never toasts), and each failure and finish after `since`. Sub-runs never
88 * toast for themselves: a sub-run's approval is raised for its parent.
89 */
90export function toastEvents(runs: readonly Run[], details: Readonly<Record<string, Detail>>, since: number): ToastEvent[] {
91  const events: ToastEvent[] = []
92  for (const { run, need } of needing(runs, details)) {
93    if (need.standing.kind === 'unreadable') continue
94    const gate = `${need.holder.id}:${need.standing.kind}:${waitNode(need.standing)}:${need.standing.since}`
95    events.push({ runId: run.id, event: 'needs-you', gate, text: needText(run, need, runs), timeoutMs: STAYS['needs-you'] })
96  }
97  for (const run of topRuns(runs)) {
98    if (run.completedAt <= since) continue
99    if (run.status === 'failed') {
100      const failed = [...(details[run.id]?.events ?? [])].reverse().find(e => e.type === 'node_failed' || (e.type === 'workflow_failed' && e.error !== ''))
101      const node = failed?.type === 'node_failed' ? failed.step : ''
102      const error = firstLine(failed?.error ?? '')
103      const text = `✗ ${nameOf(run, runs)} failed${node === '' ? '' : ` at ${node}`}${error === '' ? '' : `: ${error}`}`
104      events.push({ runId: run.id, event: 'failed', gate: '', text, timeoutMs: STAYS.failed })
105    } else if (run.status === 'completed') {
106      const subFailed = subRunsOf(run, runs).filter(subRun => subRun.status === 'failed').length
107      const tail = subFailed === 0 ? '' : `, ${subFailed} sub-run${subFailed === 1 ? '' : 's'} failed`
108      events.push({ runId: run.id, event: 'completed', gate: '', text: `✓ ${nameOf(run, runs)} finished in ${duration(run.completedAt - run.startedAt)}${tail}`, timeoutMs: STAYS.completed })
109    }
110  }
111  return events
112}
113
114/** One toast for the events of one poll: the one event's own, or the counts in order, staying the longest part's time. */
115export function collapse(events: readonly ToastEvent[]): { text: string; timeoutMs: number } | undefined {
116  if (events.length === 0) return undefined
117  if (events.length === 1) return { text: events[0]!.text, timeoutMs: events[0]!.timeoutMs }
118  const count = (event: ToastEvent['event']) => events.filter(e => e.event === event).length
119  const needs = count('needs-you')
120  const parts = [
121    needs > 0 ? `⏸ ${needs} ${needs === 1 ? 'needs' : 'need'} you` : '',
122    count('failed') > 0 ? `✗ ${count('failed')} failed` : '',
123    count('completed') > 0 ? `✓ ${count('completed')} finished` : '',
124  ].filter(part => part !== '')
125  return { text: parts.join(' · '), timeoutMs: Math.max(...events.map(e => e.timeoutMs)) }
126}
127
128/** The store key of a toast claim. */
129export function claimKey(event: ToastEvent): string {
130  return `toasted/${event.runId}/${event.event}`
131}
132
133/** Whether a claim already in the store covers this event: the same gate for a needs-you, any claim for a failure or finish. */
134export function isClaimed(event: ToastEvent, value: unknown): boolean {
135  if (value === undefined || value === null) return false
136  if (event.event !== 'needs-you') return true
137  return typeof value === 'object' && (value as { gate?: unknown }).gate === event.gate
138}
139
140/** Whether a claim read back is this session's. */
141export function isMine(value: unknown, session: string): boolean {
142  if (typeof value === 'string') return value === session
143  return typeof value === 'object' && value !== null && (value as { session?: unknown }).session === session
144}
145
hooks/config.ts 35 lines
1// The mod's settings, parsed once at the boundary.
2
3export type Toasts = 'all' | 'needs you' | 'off'
4
5export type Config = {
6  /** The Archon CLI the person named; '' finds it on the PATH or in `~/.archon/bin`. */
7  archonPath: string
8  /** Where `archon serve` answers. */
9  port: number
10  /** Archon's log file, `~` not yet expanded. */
11  archonLog: string
12  toasts: Toasts
13  isStatusLine: boolean
14}
15
16export const DEFAULT_PORT = 3090
17export const DEFAULT_LOG = '~/.archon/logs/serve.log'
18
19const TOASTS: readonly Toasts[] = ['all', 'needs you', 'off']
20
21/** Reads the settings: a blank path means find it, a port outside 1-65535 or not whole reads 3090, an unknown `toasts` reads `all`. */
22export function parseConfig(options: Readonly<Record<string, unknown>>): Config {
23  const path = typeof options.archonPath === 'string' ? options.archonPath.trim() : ''
24  const port = options.archonPort
25  const log = typeof options.archonLog === 'string' && options.archonLog.trim() !== '' ? options.archonLog.trim() : DEFAULT_LOG
26  const toasts = TOASTS.find(value => value === options.toasts) ?? 'all'
27  return {
28    archonPath: path,
29    port: typeof port === 'number' && Number.isInteger(port) && port >= 1 && port <= 65535 ? port : DEFAULT_PORT,
30    archonLog: log,
31    toasts,
32    isStatusLine: options.statusLine !== false,
33  }
34}
35
hooks/runs.ts 230 lines
1// Reading Archon's run rows at the boundary, and what state each run is in.
2
3import type { Decision, Detail, Gate, Run, Status, Wait } from '../types'
4import { msOf, oneLine } from './text'
5
6const STATUSES: readonly Status[] = ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled']
7const CHAT_PLATFORMS = ['slack', 'telegram', 'github', 'discord']
8
9function isObject(value: unknown): value is Record<string, unknown> {
10  return typeof value === 'object' && value !== null && !Array.isArray(value)
11}
12
13function text(value: unknown): string {
14  return typeof value === 'string' ? value : ''
15}
16
17function label(id: string): string {
18  return id === '' ? id : `${id[0]!.toUpperCase()}${id.slice(1).replace(/[-_]/g, ' ')}`
19}
20
21function decisions(value: unknown): Decision[] {
22  if (!Array.isArray(value)) return []
23  return value.flatMap((entry): Decision[] => {
24    if (typeof entry === 'string' && entry !== '') return [{ id: entry, label: label(entry) }]
25    if (!isObject(entry)) return []
26    const id = text(entry.id) || text(entry.decision) || text(entry.value)
27    return id === '' ? [] : [{ id, label: text(entry.label) || label(id) }]
28  })
29}
30
31function gate(value: unknown): Gate | null {
32  if (!isObject(value)) return null
33  const nodeId = text(value.nodeId) || text(value.node_id)
34  const type = text(value.type)
35  const declared = decisions(value.decisions)
36  return {
37    nodeId,
38    message: text(value.message),
39    type,
40    decisions: declared.length > 0 ? declared : [{ id: 'approve', label: 'Approve' }, { id: 'reject', label: 'Reject' }],
41    subRunId: text(value.childRunId) || text(value.child_run_id),
42    hasRework: value.onReject !== undefined || value.on_reject !== undefined,
43    isRoundDone: value.roundDone === true || value.isComplete === true || value.complete === true,
44    isReadable: nodeId !== '' && type !== '',
45    since: msOf(value.waitingSince ?? value.requestedAt ?? value.since),
46  }
47}
48
49function wait(value: unknown): Wait | null {
50  if (!isObject(value)) return null
51  return {
52    kind: text(value.kind),
53    nodeId: text(value.nodeId) || text(value.node_id),
54    message: text(value.message),
55    until: text(value.until),
56    event: text(value.event),
57    since: msOf(value.waitingSince ?? value.since),
58  }
59}
60
61/** One run row from either source; undefined when it has no id. Unknown statuses read as `pending`. */
62export function parseRun(value: unknown): Run | undefined {
63  if (!isObject(value) || text(value.id) === '') return undefined
64  const metadata = isObject(value.metadata) ? value.metadata : {}
65  const source = isObject(metadata.workflow_source) ? metadata.workflow_source : {}
66  const status = STATUSES.find(s => s === value.status) ?? 'pending'
67  const platform = [value.platform_type, value.parent_platform_type, metadata.platform_type, metadata.platform]
68    .map(text)
69    .map(name => name.toLowerCase())
70    .find(name => CHAT_PLATFORMS.includes(name)) ?? ''
71  return {
72    id: text(value.id),
73    workflow: text(value.workflow_name) || 'workflow',
74    status,
75    message: oneLine(text(value.user_message)),
76    startedAt: msOf(value.started_at),
77    completedAt: msOf(value.completed_at),
78    lastActivityAt: msOf(value.last_activity_at) || msOf(value.started_at),
79    codebaseId: text(value.codebase_id),
80    workingPath: text(value.working_path),
81    outputRoot: text(value.output_root),
82    parentId: text(value.parent_run_id),
83    parentNodeId: text(metadata.parent_node_id),
84    adoptedFromId: text(value.adopted_from_run_id),
85    origin: text(source.origin),
86    sourceRoot: text(source.root),
87    hasConversation: text(value.parent_conversation_id) !== '',
88    platform,
89    isContainer: metadata.isolation === 'container' || (isObject(metadata.isolation) && metadata.isolation.kind === 'container'),
90    approval: status === 'paused' ? gate(metadata.approval) : null,
91    wait: status === 'paused' ? wait(metadata.wait) : null,
92    costUsd: typeof metadata.total_cost_usd === 'number' ? metadata.total_cost_usd : 0,
93  }
94}
95
96/** The rows of a runs list, either source's body; throws when it is not one. */
97export function parseRuns(body: string): Run[] {
98  const parsed: unknown = JSON.parse(body)
99  if (!isObject(parsed) || !Array.isArray(parsed.runs)) throw new Error('Archon answered without a runs list')
100  return parsed.runs.flatMap(entry => parseRun(entry) ?? [])
101}
102
103/** Whether a run has ended: completed, failed or cancelled. */
104export function hasEnded(run: Run): boolean {
105  return run.status === 'completed' || run.status === 'failed' || run.status === 'cancelled'
106}
107
108/** The run at the top of a run's chain of parents, as far as the rows go; a missing parent stands for itself. */
109export function rootId(run: Run, byId: ReadonlyMap<string, Run>): string {
110  let at = run
111  const seen = new Set<string>()
112  while (at.parentId !== '' && !seen.has(at.id)) {
113    seen.add(at.id)
114    const parent = byId.get(at.parentId)
115    if (parent === undefined) return at.parentId
116    at = parent
117  }
118  return at.id
119}
120
121/** How many live runs: a parent and its sub-runs count as one while any of them has not ended. */
122export function liveCount(runs: readonly Run[]): number {
123  const byId = new Map(runs.map(run => [run.id, run]))
124  return new Set(runs.filter(run => !hasEnded(run)).map(run => rootId(run, byId))).size
125}
126
127/**
128 * Why a run stands where it does, mirroring Archon's `runAttention`
129 * (`packages/workflows/src/schemas/workflow-run.ts` at v0.11.1) from
130 * `metadata.approval` and `metadata.wait`, plus the mod's own check of a
131 * `child_workflow` gate's sub-run, which Archon never reads.
132 */
133export type Standing =
134  | { kind: 'none' }
135  | { kind: 'approval'; gate: Gate; since: number }
136  | { kind: 'action'; wait: Wait; since: number }
137  | { kind: 'stranded'; gate: Gate; subRun: Run | undefined; since: number }
138  | { kind: 'unreadable'; since: number }
139  | { kind: 'blocked'; gate: Gate; subRun: Run | undefined }
140  | { kind: 'waiting'; wait: Wait }
141  | { kind: 'resuming'; gate: Gate }
142
143/** Whether a gate was answered: an `approval_received` after the last `approval_requested`. */
144function isAnswered(detail: Detail | undefined): boolean {
145  const events = detail?.events ?? []
146  const asked = events.map(e => e.type).lastIndexOf('approval_requested')
147  const answered = events.map(e => e.type).lastIndexOf('approval_received')
148  return answered > asked && answered >= 0
149}
150
151/** Where a run stands, its sub-run looked up among `runs`. */
152export function standing(run: Run, runs: readonly Run[], detail: Detail | undefined): Standing {
153  if (run.status !== 'paused') return { kind: 'none' }
154  const since = run.approval?.since || run.wait?.since || run.lastActivityAt
155  if (run.wait !== null) {
156    return run.wait.kind === 'attention' ? { kind: 'action', wait: run.wait, since } : { kind: 'waiting', wait: run.wait }
157  }
158  const gate = run.approval
159  if (gate === null) return { kind: 'unreadable', since }
160  if (gate.type === 'child_workflow') {
161    const subRun = runs.find(other => other.id === gate.subRunId)
162    return subRun !== undefined && hasEnded(subRun) ? { kind: 'stranded', gate, subRun, since } : { kind: 'blocked', gate, subRun }
163  }
164  if (!gate.isReadable) return { kind: 'unreadable', since }
165  return isAnswered(detail) ? { kind: 'resuming', gate } : { kind: 'approval', gate, since }
166}
167
168/** The node a run waits at: an approval's or a stranded parent's gate, or an action-needed wait; '' for any other standing. */
169export function waitNode(found: Standing): string {
170  if (found.kind === 'approval' || found.kind === 'stranded') return found.gate.nodeId
171  if (found.kind === 'action') return found.wait.nodeId
172  return ''
173}
174
175/** What a run that needs you is waiting on: the run that holds it (the parent, or the deepest sub-run on a gate) and why. */
176export type NeedsYou = {
177  holder: Run
178  standing: Extract<Standing, { since: number }>
179}
180
181/**
182 * Whether a run needs you, following a parent blocked on a live sub-run down
183 * the chain to the deepest run on a gate. Waits, answered gates and a sub-run
184 * still working do not.
185 */
186export function needsYou(run: Run, runs: readonly Run[], details: Readonly<Record<string, Detail>>): NeedsYou | undefined {
187  let at = run
188  for (let depth = 0; depth < 10; depth++) {
189    const found = standing(at, runs, details[at.id])
190    if (found.kind === 'approval' || found.kind === 'action' || found.kind === 'stranded' || found.kind === 'unreadable') return { holder: at, standing: found }
191    if (found.kind !== 'blocked' || found.subRun === undefined) return undefined
192    at = found.subRun
193  }
194  return undefined
195}
196
197/** The sub-runs of a run among the rows, oldest first. */
198export function subRunsOf(run: Run, runs: readonly Run[]): Run[] {
199  return runs.filter(other => other.parentId === run.id).sort((a, b) => a.startedAt - b.startedAt)
200}
201
202/** The latest activity of a run or any run below it. */
203export function latestActivity(run: Run, runs: readonly Run[], depth = 0): number {
204  if (depth > 10) return run.lastActivityAt
205  return Math.max(run.lastActivityAt, ...subRunsOf(run, runs).map(subRun => latestActivity(subRun, runs, depth + 1)))
206}
207
208/** The rows the Runs sub-tab lists: runs that are not sub-runs of a listed run. */
209export function topRuns(runs: readonly Run[]): Run[] {
210  const ids = new Set(runs.map(run => run.id))
211  return runs.filter(run => run.parentId === '' || !ids.has(run.parentId))
212}
213
214/** Needs-you runs first, the one that has needed you longest at the top; then the rest by latest activity. */
215export function sortRuns(runs: readonly Run[], all: readonly Run[], details: Readonly<Record<string, Detail>>): Run[] {
216  const keyed = runs.map(run => ({ run, need: needsYou(run, all, details), latest: latestActivity(run, all) }))
217  keyed.sort((a, b) => {
218    if (a.need !== undefined && b.need !== undefined) return a.need.standing.since - b.need.standing.since
219    if (a.need !== undefined) return -1
220    if (b.need !== undefined) return 1
221    return b.latest - a.latest
222  })
223  return keyed.map(entry => entry.run)
224}
225
226/** How many of a run family need you: a parent and its sub-runs count once. */
227export function needsYouCount(runs: readonly Run[], details: Readonly<Record<string, Detail>>): number {
228  return topRuns(runs).filter(run => needsYou(run, runs, details) !== undefined).length
229}
230