SLOPSHOPPER

awareness

A Claude Code pane showing the model, thinking level, context, usage limits, git state, PR, running agents and your last three prompts.

paneguardcommandtoastpromptmodel
v?MITupdated 2026-10-20hatton/awareness
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · awareness
│ ┃ awareness ✕ › fix the failing auth test and add an audit log call │ ┃ Worktree: open-folder open-vscode │ ┃ Branch: (detached) Parent: a1b2c3d4e5f6a… ⏺ Read(src/auth.ts) │ ┃ 2 files uncommitted ⎿ Read 6 lines │ ┃ Branch not pushed (no upstream) ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ PR: None ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ │ ┃ Recent Prompts ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ┃ fix the failing auth test and add an au… ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ Opus 5.5 | context: 49% › /awareness │ ┃ usage: 5-hour 31% ⎿ awareness: Awareness is off, in this session and the ones after │ ┃ │ ┃ Awareness Mod │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · awareness
Worktree: open-folder open-vscode Branch: (detached) Parent: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c… 2 files uncommitted Branch not pushed (no upstream) PR: None Recent Prompts fix the failing auth test and add an audit log call Opus 5.5 | context: 49% usage: 5-hour 31% Awareness Mod
README

Awareness

A Claude Code mod that keeps a pane open beside the conversation, showing:

  • the model, its thinking level, and how full the context window is (red above 50%)
  • your 5-hour and weekly usage (red above 80%)
  • the workspace: the YouTrack issue named by a BL- branch with its summary and state (read with the YOUTRACK_BOT token), the branch and its parent (the pull request's base, else the repository's default branch), the folder with buttons that open it in Explorer or VS Code, and the branch's pull request with the branch it merges into, its status and a link to its Reviewable page
  • a stack of pull requests, when the branch's pull request is in one: each pull request in merge order, with its status (a draft's highlighted) and a link to the worktree on this machine that has its branch checked out, which brings Orca's window to that worktree; an open one checked out nowhere offers to create one
  • a warning when the pull request is merged or closed, or when the folder is named for a different branch than the one checked out
  • uncommitted files and unpushed commits (orange when there are any)
  • a "Working on:" line naming the skill and the task in progress
  • subagents still running
  • your last three prompts, each on one line, the newest highlighted

The pane docks beside the transcript in Claude Code's fullscreen layout when the terminal is at least 110 columns wide; otherwise it sits above the prompt. It opens itself when a session starts on a terminal at least 144 columns wide.

Type /awareness to turn the mod off: the pane closes, and the mod stops reading git, gh, YouTrack and usage, and stops labelling the Orca tab. It stays off in later sessions until you type /awareness again. If the mod is on but you closed its pane, /awareness opens the pane again at any width.

In Orca, it also keeps the session's terminal tab labelled with a two- or three-word summary of what the conversation is working on, asked for again every few prompts. Until the first summary, the words of the card's branch name stand in (BL-15958-crop-marks reads crop marks). Turn this off with the "Label the Orca tab" row in /config.

The pull request comes from the GitHub CLI (gh), so gh must be installed and signed in for that part to show.

Install

In a Claude Code terminal session:

/plugin install awareness --marketplace hatton/awareness

Answer y to add the marketplace, then choose the user scope so it loads in every session.

Keep it up to date

Claude Code does not update plugins from a marketplace like this one unless you ask it to. To get each new version on its own, run /plugin, open Marketplaces, select awareness, and choose Enable auto-update. Claude Code then checks for a new version a few minutes into each session and loads it the next time you start Claude Code, or straight away after /reload-plugins.

To update right now instead:

claude plugin update awareness@awareness

Develop

claude --plugin-dir <path to this folder>
claude plugin validate <path to this folder>
claude plugin test <path to this folder>

License

MIT

Source 2 files
hooks/register.tsx 1215 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { Card, CheckedOut, Header, PullRequest, Recent, Repo, RunningAgent, Stack, StackEntry, WorkingOn } from '../types'
5
6const SHOWN = 3
7const PANE = 'awareness'
8const TITLE = 'Awareness'
9// Docked, the pane asks for a third of the terminal's columns, within these bounds.
10const DOCK_MIN_COLUMNS = 40
11const DOCK_MAX_COLUMNS = 70
12// Above this share of the context window, the figure turns red.
13const CONTEXT_WARNING_PERCENT = 50
14// Above this share of a usage window, the figure turns red.
15const LIMIT_WARNING_PERCENT = 80
16// How often git, agents and usage are read again, for changes made outside a turn.
17const REFRESH_MS = 10_000
18// The pull request is read over the network, so less often.
19const PULL_REQUEST_REFRESH_MS = 60_000
20const YOUTRACK_ISSUE_URL = 'https://issues.bloomlibrary.org/youtrack/issue/'
21const YOUTRACK_API_URL = 'https://issues.bloomlibrary.org/youtrack/api/issues/'
22// How many prompts pass before the task summary in an Orca tab's label is asked for again.
23const TAB_SUMMARY_EVERY_TURNS = 5
24const TAB_SUMMARY_PROMPT =
25  'In two or three words, name the task this conversation is working on now, as a label for a terminal tab ' +
26  '(for example "Contentful sponsors" or "Devin fixes"). Reply with only those words.'
27
28// Oldest first, newest last; at most SHOWN entries.
29const recent = atom({ plugin: 'awareness', key: 'recent' } as const, [] as Recent)
30const header = atom({ plugin: 'awareness', key: 'header' } as const, {
31  model: null,
32  effort: null,
33  contextPercent: null,
34  limits: [],
35} as Header)
36const repo = atom({ plugin: 'awareness', key: 'repo' } as const, null as Repo)
37const pullRequest = atom({ plugin: 'awareness', key: 'pullRequest' } as const, null as PullRequest)
38const card = atom({ plugin: 'awareness', key: 'card' } as const, null as Card)
39const stack = atom({ plugin: 'awareness', key: 'stack' } as const, [] as Stack)
40const checkedOut = atom({ plugin: 'awareness', key: 'checkedOut' } as const, [] as readonly CheckedOut[])
41// The branches a worktree is being made for, so their rows say so until it exists.
42const creating = atom({ plugin: 'awareness', key: 'creating' } as const, [] as readonly string[])
43const agents = atom({ plugin: 'awareness', key: 'agents' } as const, [] as readonly RunningAgent[])
44const NOTHING_YET: WorkingOn = { skill: null, tasks: {}, todo: null }
45const workingOn = atom({ plugin: 'awareness', key: 'workingOn' } as const, NOTHING_YET)
46
47/** Collapses a prompt's whitespace so blank lines in it don't stretch the pane. */
48const oneLine = (text: string) => text.replace(/\s+/g, ' ').trim()
49
50/**
51 * Turns a skill's name into a title: `preflight` reads `Preflight`,
52 * `youtrack-fix` `Youtrack fix`, and a plugin's `vercel:deploy` `Deploy`.
53 */
54export const skillTitle = (name: string) => {
55  const words = (name.split(':').pop() ?? name).replace(/[-_]+/g, ' ').trim()
56  return words.charAt(0).toUpperCase() + words.slice(1)
57}
58
59/**
60 * Lowers the first letter of a step phrase so it reads after a comma
61 * (`Fixing Devin bugs` reads `fixing Devin bugs`), but leaves a word in
62 * capitals alone (`CI`, `PR`).
63 */
64const lowerFirst = (phrase: string) =>
65  /^[A-Z][a-z]/.test(phrase) ? phrase.charAt(0).toLowerCase() + phrase.slice(1) : phrase
66
67/**
68 * Builds the "Working on:" line: the skill, then the step in progress; null
69 * when neither is known. The step is the in-progress task's phrase, else the
70 * in-progress item of the last `TodoWrite` list.
71 */
72export const workingOnText = (state: WorkingOn) => {
73  const task = Object.values(state.tasks).find(t => t.status === 'in_progress')
74  const step = task?.doing ?? state.todo
75  if (state.skill !== null && step !== null) {
76    return `Working on: ${state.skill}, ${lowerFirst(step)}`
77  }
78  if (state.skill !== null) {
79    return `Working on: ${state.skill}`
80  }
81  if (step !== null) {
82    return `Working on: ${step}`
83  }
84  return null
85}
86
87/**
88 * The skill a prompt starts, when it is a slash command: `/preflight thorough`
89 * names `preflight`, as does the `<command-name>/preflight</command-name>`
90 * form the prompt takes once Claude Code expands it.
91 */
92export const typedSkillName = (text: string) =>
93  /<command-name>\/?([\w:.-]+)<\/command-name>/.exec(text)?.[1] ?? /^\/([\w:.-]+)/.exec(text.trim())?.[1]
94
95/**
96 * Turns a model id such as `claude-opus-5-5[1m]` into `Opus 5.5 (1M context)`.
97 * Anything not spelled that way is shown as given.
98 */
99export const friendlyModelName = (model: string) => {
100  const match = /^claude-([a-z]+)-(\d+(?:-\d{1,2})*)(?:-\d{8})?(\[1m\])?$/i.exec(model)
101  if (!match) {
102    return model
103  }
104  const [, family = '', version = '', isLongContext] = match
105  const name = `${family.charAt(0).toUpperCase()}${family.slice(1)} ${version.replace(/-/g, '.')}`
106  return isLongContext ? `${name} (1M context)` : name
107}
108
109/** Names a usage window the way people say it. */
110const limitLabel = (kind: string) => {
111  switch (kind) {
112    case 'five_hour':
113      return '5-hour'
114    case 'seven_day':
115      return 'week'
116    case 'spend_limit':
117      return 'spend'
118    default:
119      return kind
120  }
121}
122
123/**
124 * Reads `git status --porcelain=v2 --branch` output into the repo's state.
125 * A detached HEAD shows as `(detached)`.
126 */
127export const parseGitStatus = (stdout: string, worktree: string, defaultBranch: string | null): NonNullable<Repo> => {
128  let branch = '(detached)'
129  let unpushedCommits: number | null = null
130  let changedFiles = 0
131  for (const line of stdout.split(/\r?\n/)) {
132    if (line.startsWith('# branch.head ')) {
133      branch = line.slice('# branch.head '.length).trim()
134    } else if (line.startsWith('# branch.ab ')) {
135      const ahead = /\+(\d+)/.exec(line)
136      unpushedCommits = ahead ? Number(ahead[1]) : 0
137    } else if (line !== '' && !line.startsWith('#')) {
138      changedFiles += 1
139    }
140  }
141  return { branch, defaultBranch, worktree, changedFiles, unpushedCommits }
142}
143
144/** Turns a folder path such as `D:\work` into a `vscode://file/D:/work` URL that opens it in VS Code. */
145export const vscodeUrl = (path: string) => `vscode://file/${path.replace(/\\/g, '/').replace(/^\/+/, '')}`
146
147/**
148 * Hands a folder or a URL to Windows Explorer: a folder opens in Explorer, a
149 * URL in the app registered for its scheme. A terminal opens only some link
150 * schemes itself, so the pane's folder links go this way instead.
151 */
152const openInExplorer = async ($: EngineInterface, target: string) => {
153  await $.process.run(['explorer.exe', target], { timeoutMs: 10_000 })
154}
155
156/** Describes the uncommitted files for the pane. */
157const uncommittedText = (count: number) => {
158  if (count === 0) {
159    return 'Nothing uncommitted'
160  }
161  return `${count} ${count === 1 ? 'file' : 'files'} uncommitted`
162}
163
164/** Describes the unpushed commits for the pane. */
165const unpushedText = (count: number | null) => {
166  if (count === null) {
167    return 'Branch not pushed (no upstream)'
168  }
169  if (count === 0) {
170    return 'Nothing unpushed'
171  }
172  return `${count} ${count === 1 ? 'commit' : 'commits'} not pushed`
173}
174
175/** Reads the model, the context window's fill and the usage windows into the header. */
176const refreshHeader = async ($: EngineInterface) => {
177  const [model, usage] = await Promise.all([$.session.model(), $.session.usage()])
178  await update($, header, h => ({
179    ...h,
180    model: friendlyModelName(model),
181    contextPercent: usage.context.percent ?? h.contextPercent,
182    limits: usage.rateLimits.map(l => ({ kind: l.kind, percentUsed: l.percentUsed })),
183  }))
184}
185
186/** Reads the thinking level from settings, for before the first request reports it. */
187const readEffortSetting = async ($: EngineInterface) => {
188  const { effortLevel } = await $.settings.read()
189  if (effortLevel === undefined) {
190    return
191  }
192  await update($, header, h => ({ ...h, effort: String(effortLevel) }))
193}
194
195/**
196 * Reads `git rev-parse --abbrev-ref origin/HEAD` output, `origin/master`,
197 * into the default branch's name, `master`.
198 */
199export const parseDefaultBranch = (stdout: string) => stdout.trim().replace(/^origin\//, '') || null
200
201/**
202 * Writes a drive path that git gives with forward slashes, `D:/work`, the
203 * Windows way, `D:\work`, which Explorer needs; any other path as it is.
204 */
205export const windowsPath = (path: string) => (/^[A-Za-z]:\//.test(path) ? path.replace(/\//g, '\\') : path)
206
207/** Reads the worktree's branch, the repository's default branch, uncommitted files and unpushed commits. */
208const refreshRepo = async ($: EngineInterface) => {
209  const [status, originHead, topLevel] = await Promise.all([
210    $.process.run(['git', 'status', '--porcelain=v2', '--branch'], { timeoutMs: 10_000 }),
211    $.process.run(['git', 'rev-parse', '--abbrev-ref', 'origin/HEAD'], { timeoutMs: 10_000 }),
212    $.process.run(['git', 'rev-parse', '--show-toplevel'], { timeoutMs: 10_000 }),
213  ])
214  // The session can move into a subfolder; the worktree is the repository's top folder.
215  const worktree = topLevel.exitCode === 0 ? windowsPath(topLevel.stdout.trim()) : await $.session.cwd()
216  const defaultBranch = originHead.exitCode === 0 ? parseDefaultBranch(originHead.stdout) : null
217  const state: Repo = status.exitCode === 0 ? parseGitStatus(status.stdout, worktree, defaultBranch) : null
218  await update($, repo, () => state)
219}
220
221/**
222 * Turns a GitHub pull request URL such as
223 * `https://github.com/BloomBooks/BloomDesktop/pull/8315` into its Reviewable
224 * page, `https://reviewable.io/reviews/BloomBooks/BloomDesktop/8315`.
225 */
226export const reviewableUrl = (pullRequestUrl: string) =>
227  pullRequestUrl.replace(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+).*$/, 'https://reviewable.io/reviews/$1/$2/$3')
228
229/**
230 * Reads `gh pr view --json number,url,baseRefName,headRefName,state,isDraft` output into
231 * the pull request's state: a draft reads `draft`, otherwise the state in lower case.
232 */
233export const parsePullRequest = (stdout: string): NonNullable<PullRequest> => {
234  const pr = JSON.parse(stdout) as GhPullRequest
235  return { number: pr.number, url: pr.url, base: pr.baseRefName, head: pr.headRefName, status: pullRequestStatus(pr) }
236}
237
238/** A pull request as `gh` gives it with the fields this module asks for. */
239type GhPullRequest = {
240  number: number
241  url: string
242  baseRefName: string
243  headRefName: string
244  state: string
245  isDraft: boolean
246}
247
248/** A draft reads `draft`, otherwise the state in lower case. */
249const pullRequestStatus = (pr: GhPullRequest) => (pr.isDraft && pr.state === 'OPEN' ? 'draft' : pr.state.toLowerCase())
250
251/**
252 * Finds the stack a branch's pull request is in, from `gh pr list --json
253 * number,url,baseRefName,headRefName,state,isDraft` output of the open pull
254 * requests: below it, the one whose branch it merges into, and that one's, and
255 * so on; above it, the one that merges into its branch, while there is exactly
256 * one. Returned in the order they merge; empty when nothing is chained to it.
257 */
258export const stackOf = (stdout: string, head: string): Stack => {
259  const open = JSON.parse(stdout) as GhPullRequest[]
260  const byHead = new Map(open.map(pr => [pr.headRefName, pr]))
261  const current = byHead.get(head)
262  if (current === undefined) {
263    return []
264  }
265  const chain = [current]
266  const seen = new Set([current.headRefName])
267  for (let below = byHead.get(current.baseRefName); below && !seen.has(below.headRefName); below = byHead.get(below.baseRefName)) {
268    chain.unshift(below)
269    seen.add(below.headRefName)
270  }
271  for (let top = current; ; ) {
272    const above = open.filter(pr => pr.baseRefName === top.headRefName)
273    if (above.length !== 1 || seen.has(above[0]!.headRefName)) {
274      break
275    }
276    top = above[0]!
277    chain.push(top)
278    seen.add(top.headRefName)
279  }
280  if (chain.length < 2) {
281    return []
282  }
283  return chain.map((pr): StackEntry => ({ number: pr.number, url: pr.url, head: pr.headRefName, base: pr.baseRefName, status: pullRequestStatus(pr) }))
284}
285
286/**
287 * Reads `git rev-parse --abbrev-ref @{upstream}` output, `origin/canvas-refit`,
288 * into the branch's name on its remote, `canvas-refit`; null when it is empty.
289 */
290export const parseUpstreamBranch = (stdout: string) => stdout.trim().replace(/^[^/]+\//, '') || null
291
292const pullRequestFields = ['--json', 'number,url,baseRefName,headRefName,state,isDraft']
293
294/**
295 * Reads the current branch's pull request through the GitHub CLI. `gh` finds it
296 * by where the branch pushes, and when the local name differs from the remote one
297 * (Orca names a second worktree of `canvas-refit` `canvas-refit-2`) git cannot say
298 * where that is, so `gh` finds nothing. Then we ask again by the name of the
299 * branch it tracks.
300 */
301const refreshPullRequest = async ($: EngineInterface) => {
302  let { exitCode, stdout } = await $.process.run(['gh', 'pr', 'view', ...pullRequestFields], { timeoutMs: 20_000 })
303  if (exitCode !== 0) {
304    const upstream = await $.process.run(['git', 'rev-parse', '--abbrev-ref', '@{upstream}'], { timeoutMs: 10_000 })
305    const remoteBranch = upstream.exitCode === 0 ? parseUpstreamBranch(upstream.stdout) : null
306    if (remoteBranch !== null) {
307      ;({ exitCode, stdout } = await $.process.run(['gh', 'pr', 'view', remoteBranch, ...pullRequestFields], {
308        timeoutMs: 20_000,
309      }))
310    }
311  }
312  const state: PullRequest = exitCode === 0 ? parsePullRequest(stdout) : null
313  await update($, pullRequest, () => state)
314  await refreshStack($, state)
315  await refreshCheckedOut($)
316}
317
318const STACK_QUERY =
319  'query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) { ' +
320  'stack { entries(first: 100) { nodes { position pullRequest { number url headRefName baseRefName state isDraft } } } } } } }'
321
322/**
323 * Reads GitHub's answer to STACK_QUERY into the stack the pull request is in,
324 * merged pull requests included, in the order they merge; null when GitHub
325 * has it in no stack.
326 */
327export const parseGitHubStack = (stdout: string): Stack | null => {
328  const answer = JSON.parse(stdout) as {
329    data: { repository: { pullRequest: { stack: { entries: { nodes: { position: number; pullRequest: GhPullRequest }[] } } | null } } }
330  }
331  const found = answer.data.repository.pullRequest.stack
332  if (found === null) {
333    return null
334  }
335  return [...found.entries.nodes]
336    .sort((a, b) => a.position - b.position)
337    .map(({ pullRequest: pr }): StackEntry => ({ number: pr.number, url: pr.url, head: pr.headRefName, base: pr.baseRefName, status: pullRequestStatus(pr) }))
338}
339
340/**
341 * Keeps the stack the branch's pull request is in. GitHub's own stack comes
342 * first, since it remembers the pull requests already merged. A pull request
343 * GitHub has in no stack may still be chained to others by their branches,
344 * and those are found from the open pull requests.
345 */
346const refreshStack = async ($: EngineInterface, pr: PullRequest) => {
347  if (pr === null) {
348    await update($, stack, () => [])
349    return
350  }
351  const repoMatch = /github\.com\/([^/]+)\/([^/]+)\/pull\//.exec(pr.url)
352  if (repoMatch) {
353    const asked = await $.process.run(
354      ['gh', 'api', 'graphql', '-f', `query=${STACK_QUERY}`, '-F', `owner=${repoMatch[1]}`, '-F', `repo=${repoMatch[2]}`, '-F', `number=${pr.number}`],
355      { timeoutMs: 20_000 },
356    )
357    const fromGitHub = asked.exitCode === 0 ? parseGitHubStack(asked.stdout) : null
358    if (fromGitHub !== null) {
359      await update($, stack, () => fromGitHub)
360      return
361    }
362  }
363  if (pr.status !== 'open' && pr.status !== 'draft') {
364    await update($, stack, () => [])
365    return
366  }
367  const { exitCode, stdout } = await $.process.run(
368    ['gh', 'pr', 'list', '--state', 'open', '--limit', '200', ...pullRequestFields],
369    { timeoutMs: 20_000 },
370  )
371  if (exitCode !== 0) {
372    return
373  }
374  const found = stackOf(stdout, pr.head)
375  await update($, stack, () => found)
376}
377
378/**
379 * What is wrong with keeping this worktree as it is, for the line under it:
380 * its pull request is already merged or closed, so the folder can go, and its
381 * folder is named for something other than its branch. Empty when neither.
382 */
383export const worktreeWarnings = (worktree: string, branch: string, pullRequestStatus: string | null) => {
384  const warnings: string[] = []
385  if (pullRequestStatus === 'merged' || pullRequestStatus === 'closed') {
386    warnings.push(`PR ${pullRequestStatus}; this worktree can be removed`)
387  }
388  const folder = (worktree.split(/[\\/]/).pop() ?? '').toLowerCase()
389  const name = branch.toLowerCase()
390  if (branch !== '(detached)' && !folder.startsWith(name) && !name.startsWith(folder)) {
391    warnings.push(`folder name is not the branch (${branch})`)
392  }
393  return warnings
394}
395
396/** The YouTrack card id a branch named the team's way starts with, such as `BL-15958`; null without one. */
397export const cardId = (branch: string) => /^BL-\d+/i.exec(branch)?.[0].toUpperCase() ?? null
398
399/**
400 * Reads YouTrack's answer to `?fields=summary,customFields(name,value(name))`
401 * into the card: its summary, and the name of its State field's value.
402 */
403export const parseCard = (id: string, text: string): NonNullable<Card> => {
404  const issue = JSON.parse(text) as {
405    summary: string
406    customFields?: { name: string; value: { name?: string } | null }[]
407  }
408  const state = issue.customFields?.find(f => f.name === 'State')?.value?.name ?? null
409  return { id, summary: issue.summary, state }
410}
411
412/**
413 * Reads the summary and state of the card the branch names from YouTrack,
414 * through the team's Bot token in `YOUTRACK_BOT`. It is read again on every
415 * refresh, because the card's state moves while the work goes on.
416 */
417const refreshCard = async ($: EngineInterface) => {
418  const git = await read($, repo)
419  const id = git === null ? null : cardId(git.branch)
420  if (id === null) {
421    return
422  }
423  const token = await $.env.get('YOUTRACK_BOT')
424  if (!token) {
425    return
426  }
427  const response = await $.http.fetch(`${YOUTRACK_API_URL}${id}?fields=summary,customFields(name,value(name))`, {
428    headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
429  })
430  if (!response.ok) {
431    return
432  }
433  const latest = parseCard(id, response.text)
434  await update($, card, () => latest)
435}
436
437/** Reads what lives on the network, the pull request and the card's summary. */
438const refreshRemote = ($: EngineInterface) => Promise.allSettled([refreshPullRequest($), refreshCard($)])
439
440/**
441 * The words after the card id in a branch named the team's way:
442 * `BL-15958-crop-marks` gives `crop marks`; a branch without a card id, none.
443 */
444export const cardWords = (branch: string) => {
445  const words = /^[A-Za-z]+-\d+[-_](.+)$/.exec(branch)?.[1]?.replace(/[-_]+/g, ' ').trim()
446  return words || null
447}
448
449/** Trims a model's reply to a tab label: one line, no quotes or closing period, at most four words. */
450export const tidySummary = (text: string) =>
451  text
452    .split('\n')[0]!
453    .replace(/["'`*.]/g, '')
454    .trim()
455    .split(/\s+/)
456    .slice(0, 4)
457    .join(' ')
458
459/**
460 * The Orca tab's label: the summary of what the conversation is working on.
461 * The worktree's card can be about something else entirely, so its words
462 * stand in only until the first summary; null when there is neither.
463 */
464export const tabLabel = (words: string | null, task: string | null) => task ?? words
465
466// What this module last asked Orca for, so an unchanged label is not sent again.
467let lastLabel: string | null = null
468let task: string | null = null
469let taskAskedAtTurn = -Infinity
470
471/**
472 * Keeps the Orca terminal tab this session runs in labelled with what it is
473 * about. Outside Orca there is no tab handle and it does nothing.
474 */
475const refreshTabLabel = async ($: EngineInterface) => {
476  const handle = await $.env.get('ORCA_TERMINAL_HANDLE')
477  if (!handle) {
478    return
479  }
480  const branch = await $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], { timeoutMs: 10_000 })
481  const words = branch.exitCode === 0 ? cardWords(branch.stdout.trim()) : null
482  const turns = await $.session.turns()
483  if (turns > 0 && turns - taskAskedAtTurn >= TAB_SUMMARY_EVERY_TURNS) {
484    const reply = await $.model.fork({ prompt: TAB_SUMMARY_PROMPT })
485    if (reply.isAnswered && tidySummary(reply.text)) {
486      task = tidySummary(reply.text)
487      taskAskedAtTurn = turns
488    }
489  }
490  const label = tabLabel(words, task)
491  if (label === null || label === lastLabel) {
492    return
493  }
494  const renamed = await $.process.run(['orca', 'terminal', 'rename', '--terminal', handle, '--title', label], {
495    timeoutMs: 10_000,
496  })
497  if (renamed.exitCode === 0) {
498    lastLabel = label
499  }
500}
501
502/** Reads which subagents and teammates are still at work. */
503const refreshAgents = async ($: EngineInterface) => {
504  const list = await $.agent.list()
505  const running = list
506    .filter(a => a.status === 'running' || a.status === 'pending' || a.status === 'waiting')
507    .map(a => ({ id: a.id, description: a.description, type: a.type }))
508  await update($, agents, () => running)
509}
510
511/**
512 * Applies a `TaskUpdate` to the tracked task list: a new status or phrase, or
513 * the task's removal when it is deleted. An id the list never saw (one
514 * created before the list was last cleared) is added only when the update
515 * names what it does; otherwise the list is left as it was.
516 */
517export const updatedTasks = (
518  tasks: WorkingOn['tasks'],
519  change: { taskId: string; status?: string; activeForm?: string; subject?: string },
520): WorkingOn['tasks'] => {
521  if (change.status === 'deleted') {
522    const { [change.taskId]: _removed, ...rest } = tasks
523    return rest
524  }
525  const known = tasks[change.taskId]
526  const named = change.activeForm ?? change.subject
527  if (known === undefined && named === undefined) {
528    return tasks
529  }
530  const before = known ?? { doing: named ?? '', status: 'pending' as const }
531  const status =
532    change.status === 'in_progress' || change.status === 'completed' || change.status === 'pending'
533      ? change.status
534      : before.status
535  return {
536    ...tasks,
537    [change.taskId]: { doing: change.activeForm ?? change.subject ?? before.doing, status },
538  }
539}
540
541/** Takes the activity from a prompt that runs a skill as a slash command. */
542const noteTypedSkill = async ($: EngineInterface, text: string) => {
543  const name = typedSkillName(text)
544  if (name === undefined) {
545    return
546  }
547  const command = (await $.command.list()).find(c => c.name === name)
548  // Built-in commands (/clear, /model) and this mod's own name no activity.
549  if (command === undefined || command.source === 'builtin' || command.plugin === 'awareness') {
550    return
551  }
552  await update($, workingOn, w => ({ ...w, skill: skillTitle(name) }))
553}
554
555/**
556 * The body columns to ask for while docked: a third of the terminal, between
557 * DOCK_MIN_COLUMNS and DOCK_MAX_COLUMNS.
558 */
559export const dockColumns = (terminalColumns: number) =>
560  Math.max(DOCK_MIN_COLUMNS, Math.min(DOCK_MAX_COLUMNS, Math.round(terminalColumns / 3)))
561
562/**
563 * Reads `git worktree list --porcelain` output into each worktree's folder and
564 * the local branch it has checked out; a detached worktree is left out.
565 */
566export const parseWorktrees = (stdout: string) => {
567  const found: { path: string; branch: string }[] = []
568  let path: string | null = null
569  for (const line of stdout.split(/\r?\n/)) {
570    if (line.startsWith('worktree ')) {
571      path = line.slice('worktree '.length).trim()
572    } else if (line.startsWith('branch refs/heads/') && path !== null) {
573      found.push({ path: windowsPath(path), branch: line.slice('branch refs/heads/'.length).trim() })
574    }
575  }
576  return found
577}
578
579/**
580 * Reads `git for-each-ref --format=%(refname:short)%09%(upstream:short)%09%(upstream:track) refs/heads`
581 * output into each local branch's upstream (the name on the remote, without the remote) and
582 * how it stands against it; a branch with no upstream is left out.
583 */
584export const parseTracking = (stdout: string) => {
585  const found = new Map<string, { remoteBranch: string; sync: string }>()
586  for (const line of stdout.split(/\r?\n/)) {
587    const [branch, upstream, track = ''] = line.split('\t')
588    if (!branch || !upstream) {
589      continue
590    }
591    found.set(branch, { remoteBranch: upstream.replace(/^[^/]+\//, ''), sync: syncFromCounts(track) })
592  }
593  return found
594}
595
596/** Turns git's `[ahead 3, behind 5]`, or the same counts written `ahead 3 behind 5`, into one word. */
597const syncFromCounts = (track: string) => {
598  if (track.includes('gone')) {
599    return 'not pushed'
600  }
601  const ahead = Number(/ahead (\d+)/.exec(track)?.[1] ?? 0)
602  const behind = Number(/behind (\d+)/.exec(track)?.[1] ?? 0)
603  if (ahead > 0 && behind > 0) {
604    return 'diverged'
605  }
606  if (ahead > 0) {
607    return 'ahead'
608  }
609  if (behind > 0) {
610    return 'behind'
611  }
612  return 'in sync'
613}
614
615/**
616 * Finds which worktree on this machine has each of the stack's branches
617 * checked out, and how that branch stands against the remote. A branch with
618 * no upstream is compared with the remote branch of the same name.
619 */
620/**
621 * Reads `orca worktree ps --json` output into what the agents in each Orca
622 * worktree are doing, by the worktree's folder in lower case, written the
623 * Windows way: `working` when any agent is, else `waiting` when any waits on
624 * the person. A worktree whose agents are all done is left out.
625 */
626export const parseOrcaAgents = (stdout: string) => {
627  const answer = JSON.parse(stdout) as { result?: { worktrees?: { path: string; agents?: { state: string }[] }[] } }
628  const found = new Map<string, string>()
629  for (const w of answer.result?.worktrees ?? []) {
630    const states = (w.agents ?? []).map(a => a.state)
631    const agent = states.includes('working') ? 'working' : states.find(s => s !== 'done' && s !== 'working') ? 'waiting' : null
632    if (agent !== null) {
633      found.set(windowsPath(w.path).toLowerCase(), agent)
634    }
635  }
636  return found
637}
638
639/** Asks Orca what its agents are doing; empty when Orca is not running or not installed. */
640const readOrcaAgents = async ($: EngineInterface) => {
641  const ps = await $.process.run(['orca', 'worktree', 'ps', '--json', '--limit', '500'], { timeoutMs: 10_000 }).catch(() => null)
642  if (ps === null || ps.exitCode !== 0) {
643    return new Map<string, string>()
644  }
645  try {
646    return parseOrcaAgents(ps.stdout)
647  } catch {
648    return new Map<string, string>()
649  }
650}
651
652const refreshCheckedOut = async ($: EngineInterface) => {
653  const heads = new Set((await read($, stack)).map(s => s.head))
654  if (heads.size === 0) {
655    await update($, checkedOut, () => [])
656    return
657  }
658  const [list, refs, agentsByPath] = await Promise.all([
659    $.process.run(['git', 'worktree', 'list', '--porcelain'], { timeoutMs: 10_000 }),
660    $.process.run(
661      ['git', 'for-each-ref', '--format=%(refname:short)%09%(upstream:short)%09%(upstream:track)', 'refs/heads'],
662      { timeoutMs: 10_000 },
663    ),
664    readOrcaAgents($),
665  ])
666  if (list.exitCode !== 0 || refs.exitCode !== 0) {
667    return
668  }
669  const tracking = parseTracking(refs.stdout)
670  const found: CheckedOut[] = []
671  for (const { path, branch } of parseWorktrees(list.stdout)) {
672    const tracked = tracking.get(branch)
673    const remoteBranch = tracked?.remoteBranch ?? branch
674    if (!heads.has(remoteBranch)) {
675      continue
676    }
677    let sync = tracked?.sync
678    if (sync === undefined) {
679      const counts = await $.process.run(
680        ['git', 'rev-list', '--left-right', '--count', `refs/heads/${branch}...refs/remotes/origin/${branch}`],
681        { timeoutMs: 10_000 },
682      )
683      const [ahead = '0', behind = '0'] = counts.stdout.trim().split(/\s+/)
684      sync = counts.exitCode === 0 ? syncFromCounts(`ahead ${ahead} behind ${behind}`) : 'not pushed'
685    }
686    found.push({ path, remoteBranch, sync, agent: agentsByPath.get(path.toLowerCase()) ?? null })
687  }
688  await update($, checkedOut, () => found)
689}
690
691/**
692 * Reads `orca terminal list --worktree <selector> --json` output into the
693 * handle of the terminal to show for that worktree: the first one an agent
694 * runs in, else the first one; null when the worktree has none.
695 */
696export const parseOrcaTerminal = (stdout: string) => {
697  const answer = JSON.parse(stdout) as { result?: { terminals?: { handle: string; agentIdentity?: string | null }[] } }
698  const terminals = answer.result?.terminals ?? []
699  return (terminals.find(t => t.agentIdentity) ?? terminals[0])?.handle ?? null
700}
701
702/**
703 * Names a folder beside the worktree's top folder: `D:\BL16822-1` with
704 * `BL-1-part-4` gives `D:\BL-1-part-4`. That is where Orca puts the
705 * worktrees it makes.
706 */
707export const siblingFolder = (worktree: string, name: string) => worktree.replace(/[^\\/]+[\\/]*$/, '') + name
708
709/**
710 * Brings Orca's window to a worktree, on the tab of the agent working there
711 * if there is one; a worktree with no terminal gets a new one.
712 */
713const goToWorktree = async ($: EngineInterface, path: string) => {
714  const selector = `path:${path.replace(/\\/g, '/')}`
715  const list = await $.process.run(['orca', 'terminal', 'list', '--worktree', selector, '--json'], { timeoutMs: 10_000 })
716  const handle = list.exitCode === 0 ? parseOrcaTerminal(list.stdout) : null
717  const shown =
718    handle === null
719      ? await $.process.run(['orca', 'terminal', 'create', '--worktree', selector, '--focus', '--json'], { timeoutMs: 20_000 })
720      : await $.process.run(['orca', 'terminal', 'switch', '--terminal', handle, '--json'], { timeoutMs: 10_000 })
721  if (shown.exitCode !== 0) {
722    $.ui.toast(`Orca could not show ${path}: ${(shown.stderr || shown.stdout).trim()}`)
723  }
724}
725
726/**
727 * Checks a stacked pull request's branch out in a new worktree beside this
728 * one, named after the branch, then brings Orca to it. `git worktree add`
729 * checks out the branch itself, tracking the remote one; `orca worktree
730 * create` would make a new branch with a number on the end instead.
731 */
732const createWorktree = async ($: EngineInterface, worktree: string, branch: string) => {
733  await update($, creating, list => [...list, branch])
734  try {
735    await $.process.run(['git', 'fetch', 'origin', branch], { timeoutMs: 120_000 })
736    let path = siblingFolder(worktree, branch)
737    for (let n = 2; await $.fs.exists(path); n += 1) {
738      path = siblingFolder(worktree, `${branch}-${n}`)
739    }
740    const added = await $.process.run(['git', 'worktree', 'add', path, branch], { timeoutMs: 600_000 })
741    if (added.exitCode !== 0) {
742      $.ui.toast(`Could not make a worktree for ${branch}: ${added.stderr.trim()}`)
743      return
744    }
745    await refreshCheckedOut($)
746    await goToWorktree($, path)
747  } finally {
748    await update($, creating, list => list.filter(b => b !== branch))
749  }
750}
751
752/** Reads everything the pane shows that can change outside a turn. */
753const refreshAll = async ($: EngineInterface) => {
754  await Promise.allSettled([refreshHeader($), refreshRepo($), refreshAgents($), refreshCheckedOut($)])
755}
756
757/**
758 * Opens the pane, reads everything and starts the timers that read it again.
759 * Returns those timers.
760 */
761const startWatching = async ($: EngineInterface, labelOrcaTab: boolean) => {
762  void $.ui.open({ id: PANE, title: TITLE })
763  await Promise.allSettled([refreshAll($), readEffortSetting($)])
764  void refreshRemote($)
765  if (labelOrcaTab) {
766    void refreshTabLabel($).catch(() => undefined)
767  }
768  return [
769    $.clock.every(REFRESH_MS, () => refreshAll($)),
770    $.clock.every(PULL_REQUEST_REFRESH_MS, () => refreshRemote($)),
771  ]
772}
773
774// The `$.store` key that holds whether the person turned the mod off with /awareness.
775const OFF_KEY = 'off'
776
777export const register: Register = (on, options) => {
778  const labelOrcaTab = options.labelOrcaTab !== false
779  // Whether the mod is on; read from `$.store` at each session start.
780  let isOn = true
781  // The timers startWatching started.
782  let timers: Timer[] = []
783  // The dock width last asked for, so the pane asks again only when the terminal's width changes it.
784  let askedColumns: number | null = null
785
786  // Claude Code docks the pane beside the transcript in the fullscreen layout
787  // from 110 columns; elsewhere it seats it above the prompt.
788  on('session.start', async ($, e, next) => {
789    await $.command.register({
790      name: 'awareness',
791      description: 'Turn the Awareness mod on or off: its pane, its git and usage polling, and its Orca tab label',
792    })
793    isOn = (await $.store.get(OFF_KEY).catch(() => undefined)) !== true
794    if (isOn) {
795      timers = await startWatching($, labelOrcaTab)
796    }
797
798    return next(e)
799  })
800
801  // /clear starts the conversation over, so the activity starts over too.
802  on('classic.SessionStart', async ($, e, next) => {
803    if (isOn && e.source === 'clear') {
804      await update($, workingOn, () => NOTHING_YET).catch(() => undefined)
805    }
806    return next(e)
807  })
808
809  // A slash command typed at the prompt; noteTypedSkill skips built-ins.
810  on('command.run', async ($, e, next) => {
811    if (isOn && e.command !== 'awareness') {
812      await noteTypedSkill($, `/${e.command}`).catch(() => undefined)
813    }
814    return next(e)
815  })
816
817  // While the mod is on but the person closed its pane, /awareness opens the pane again instead of turning the mod off.
818  on('command.run', { command: 'awareness' }, async $ => {
819    if (!isOn) {
820      isOn = true
821      await $.store.delete(OFF_KEY)
822      timers = await startWatching($, labelOrcaTab)
823      return { text: 'Awareness is on.' }
824    }
825    if (!(await $.ui.panes()).some(pane => pane.id === PANE)) {
826      await $.ui.open({ id: PANE, title: TITLE })
827      return { text: 'Awareness pane opened. Type /awareness again to turn Awareness off.' }
828    }
829    isOn = false
830    await $.store.set(OFF_KEY, true)
831    for (const timer of timers) {
832      timer.cancel()
833    }
834    timers = []
835    await $.ui.close({ id: PANE })
836    return { text: 'Awareness is off, in this session and the ones after it. Type /awareness to turn it back on.' }
837  })
838
839  // Records only what the person typed (here or through Remote Control), not
840  // prompts raised by plugins, schedules, task notifications or other agents.
841  on('prompt.submit', async ($, e, next) => {
842    const text = oneLine(e.text)
843    if (isOn && (e.origin.kind === 'composer' || e.origin.kind === 'bridge') && text) {
844      // A failed write must not hold up the prompt.
845      await update($, recent, list => [...list, text].slice(-SHOWN)).catch(() => undefined)
846      await noteTypedSkill($, e.text).catch(() => undefined)
847    }
848    return next(e)
849  })
850
851  // The model starting a skill names the activity.
852  on('tool.call', { tool: 'Skill' }, async ($, e, next) => {
853    const result = await next(e)
854    if (isOn && e.agentId === undefined && result.deny === undefined && result.isError !== true) {
855      await update($, workingOn, w => ({ ...w, skill: skillTitle(e.skill) })).catch(() => undefined)
856    }
857    return result
858  })
859
860  // The main conversation's task list names the step in progress.
861  on('tool.call', { tool: 'TaskCreate' }, async ($, e, next) => {
862    const result = await next(e)
863    if (isOn && e.agentId === undefined && result.deny === undefined && result.isError !== true) {
864      const doing = e.activeForm ?? e.subject
865      await update($, workingOn, w => ({
866        ...w,
867        tasks: { ...w.tasks, [result.result.task.id]: { doing, status: 'pending' as const } },
868      })).catch(() => undefined)
869    }
870    return result
871  })
872
873  on('tool.call', { tool: 'TaskUpdate' }, async ($, e, next) => {
874    const result = await next(e)
875    if (isOn && e.agentId === undefined && result.deny === undefined && result.isError !== true) {
876      await update($, workingOn, w => ({ ...w, tasks: updatedTasks(w.tasks, e) })).catch(() => undefined)
877    }
878    return result
879  })
880
881  on('tool.call', { tool: 'TodoWrite' }, async ($, e, next) => {
882    const result = await next(e)
883    if (isOn && e.agentId === undefined && result.deny === undefined && result.isError !== true) {
884      const todo = e.todos.find(t => t.status === 'in_progress')?.activeForm ?? null
885      await update($, workingOn, w => ({ ...w, todo })).catch(() => undefined)
886    }
887    return result
888  })
889
890  // Each main-loop request carries the effort it asks for, and its response
891  // moves the context window's fill.
892  on('turn.step', async function* ($, e, next) {
893    if (!isOn || e.agentId !== undefined) {
894      return yield* next(e)
895    }
896    const effort = e.effort === undefined ? null : String(e.effort)
897    await update($, header, h => ({ ...h, effort })).catch(() => undefined)
898    const response = yield* next(e)
899    await refreshHeader($).catch(() => undefined)
900
901    return response
902  })
903
904  // A tool call can commit, push, edit a file or start an agent.
905  on('tool.call', async ($, e, next) => {
906    const result = await next(e)
907    if (isOn) {
908      void Promise.allSettled([refreshRepo($), refreshAgents($)])
909    }
910    return result
911  })
912
913  // The main conversation's turn ending leaves Claude idle, so nothing is being worked on.
914  on('turn.complete', async ($, e, next) => {
915    const result = await next(e)
916    if (!isOn) {
917      return result
918    }
919    if (e.agentId === undefined) {
920      await update($, workingOn, () => NOTHING_YET).catch(() => undefined)
921    }
922    void refreshAll($)
923    void refreshRemote($)
924    if (labelOrcaTab && e.agentId === undefined) {
925      void refreshTabLabel($).catch(() => undefined)
926    }
927    return result
928  })
929
930  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
931    const { Box, Button, Text, Link } = $.ui.resolve(e)
932    // The dock keeps the width it opened with, so each change of the terminal's width asks for a width again.
933    if (e.props.placement === 'dock' && e.viewport !== undefined) {
934      const wanted = dockColumns(e.viewport.columns)
935      if (wanted !== askedColumns) {
936        askedColumns = wanted
937        void $.ui.open({ id: PANE, title: TITLE, columns: wanted }).catch(() => undefined)
938      }
939    }
940    const list = await read($, recent)
941    const top = await read($, header)
942    const git = await read($, repo)
943    const pr = await read($, pullRequest)
944    const chain = await read($, stack)
945    const worktrees = await read($, checkedOut)
946    const beingMade = await read($, creating)
947    const working = await read($, agents)
948    const activity = workingOnText(await read($, workingOn))
949    const newest = list.length - 1
950    const percent = top.contextPercent
951    const id = git === null ? null : cardId(git.branch)
952    const known = await read($, card)
953    const shown = known !== null && known.id === id ? known : null
954    // A pull request names the branch it merges into; without one, the repository's default branch stands in.
955    const parent = pr?.base ?? git?.defaultBranch ?? null
956
957    return (
958      <Box flexDirection="column" gap={1} paddingLeft={2} minHeight={e.props.placement === 'dock' ? e.props.scroll.bodyRows : undefined}>
959        {git !== null && (
960          <Box flexDirection="column">
961            {id !== null && (
962              <Box flexDirection="row" gap={1} marginBottom={1}>
963                {/* Only the summary gives way to a narrow pane; the label and the id keep their width. */}
964                <Box flexShrink={0}>
965                  <Text>Issue:</Text>
966                </Box>
967                <Box flexShrink={0}>
968                  <Link href={`${YOUTRACK_ISSUE_URL}${id}`}>
969                    <Text underline>
970                      {id}
971                    </Text>
972                  </Link>
973                </Box>
974                {/* A long summary gives way so the state after it stays in view. */}
975                {shown !== null && (
976                  <Box flexShrink={1}>
977                    <Text wrap="truncate-end">
978                      {shown.summary}
979                    </Text>
980                  </Box>
981                )}
982                {shown?.state != null && (
983                  <Box flexShrink={0}>
984                    <Text>({shown.state})</Text>
985                  </Box>
986                )}
987              </Box>
988            )}
989            <Box flexDirection="row" gap={1}>
990              {/* Only the path gives way to a narrow pane; the label and VSCode keep their width. */}
991              <Box flexShrink={0}>
992                <Text dimColor>Worktree:</Text>
993              </Box>
994              <Box flexShrink={1}>
995                <Button key="open-folder" plain dimColor onPress={() => openInExplorer($, git.worktree)}>
996                  <Text underline wrap="truncate-middle">
997                    {git.worktree}
998                  </Text>
999                </Button>
1000              </Box>
1001              <Box flexShrink={0}>
1002                <Button key="open-vscode" plain dimColor onPress={() => openInExplorer($, vscodeUrl(git.worktree))}>
1003                  <Text underline>VSCode</Text>
1004                </Button>
1005              </Box>
1006            </Box>
1007            {worktreeWarnings(git.worktree, git.branch, pr?.status ?? null).map(w => (
1008              <Text key={w} color="warning" wrap="truncate-end">
1009                {w}
1010              </Text>
1011            ))}
1012            <Text bold dimColor wrap="truncate-end">
1013              Branch: {git.branch}
1014              {parent === null ? '' : `  Parent: ${parent}`}
1015            </Text>
1016            <Box flexDirection="column" paddingLeft={2}>
1017              <Text color={git.changedFiles > 0 ? 'warning' : undefined} dimColor={git.changedFiles === 0}>
1018                {uncommittedText(git.changedFiles)}
1019              </Text>
1020              <Text
1021                color={git.unpushedCommits !== 0 ? 'warning' : undefined}
1022                dimColor={git.unpushedCommits === 0}
1023              >
1024                {unpushedText(git.unpushedCommits)}
1025              </Text>
1026            </Box>
1027            {/* A stack lists the branch's pull request among the others, so the PR line is left out. */}
1028            {pr === null && (
1029              <Box marginTop={1}>
1030                <Text>PR: None</Text>
1031              </Box>
1032            )}
1033            {pr !== null && chain.length === 0 && (
1034              <Box flexDirection="row" gap={4} marginTop={1}>
1035                <Box flexDirection="row" gap={1}>
1036                  <Link href={pr.url}>
1037                    <Text underline>
1038                      PR #{pr.number}
1039                    </Text>
1040                  </Link>
1041                  <Text>
1042                    into {pr.base} ({pr.status})
1043                  </Text>
1044                </Box>
1045                <Link href={reviewableUrl(pr.url)}>
1046                  <Text underline>
1047                    Reviewable
1048                  </Text>
1049                </Link>
1050              </Box>
1051            )}
1052            {chain.length > 0 && (
1053              <Box flexDirection="column" marginTop={1}>
1054                <Text>PR Stack into {chain[0]!.base}</Text>
1055                {chain.map((s, i) => (
1056                  <Box key={`s${s.number}`} flexDirection="row" gap={1} paddingLeft={2}>
1057                    <Text bold={s.number === pr?.number} color={s.number === pr?.number ? 'suggestion' : undefined}>
1058                      {i + 1}.
1059                    </Text>
1060                    <Link href={s.url}>
1061                      <Text underline bold={s.number === pr?.number} color={s.number === pr?.number ? 'suggestion' : undefined}>
1062                        #{s.number}
1063                      </Text>
1064                    </Link>
1065                    <Box flexShrink={1}>
1066                      <Text
1067                        wrap="truncate-end"
1068                        bold={s.number === pr?.number}
1069                        color={s.number === pr?.number ? 'suggestion' : undefined}
1070                      >
1071                        {cardWords(s.head) ?? s.head}
1072                      </Text>
1073                    </Box>
1074                    {/* The status opens the pull request's Reviewable page. */}
1075                    <Box flexShrink={0}>
1076                      <Link href={reviewableUrl(s.url)}>
1077                        {/* A draft stands out in the same color as the current pull request. */}
1078                        <Text
1079                          underline
1080                          bold={s.number === pr?.number}
1081                          color={s.number === pr?.number || s.status === 'draft' ? 'suggestion' : undefined}
1082                        >
1083                          ({s.status})
1084                        </Text>
1085                      </Link>
1086                    </Box>
1087                    {/*
1088                      Where this machine has the branch checked out, and whether it matches the remote.
1089                      "worktree" brings Orca to it; when the branch has several, each is named by its folder.
1090                    */}
1091                    {worktrees
1092                      .filter(w => w.remoteBranch === s.head)
1093                      .map((w, _, here) => (
1094                        <Box key={`w${w.path}`} flexShrink={0} flexDirection="row" gap={1}>
1095                          {w.path === git.worktree ? (
1096                            <Text bold color="suggestion">
1097                              {'<-- you are here'}
1098                            </Text>
1099                          ) : (
1100                            <Button key={`go${w.path}`} plain onPress={() => goToWorktree($, w.path)}>
1101                              <Text underline>{here.length > 1 ? (w.path.split(/[\\/]/).pop() ?? w.path) : 'worktree'}</Text>
1102                            </Button>
1103                          )}
1104                          {w.sync !== 'in sync' && <Text color="warning">{w.sync}</Text>}
1105                          {w.agent !== null && (
1106                            <Text color={w.agent === 'working' ? 'suggestion' : 'warning'}>
1107                              {w.agent === 'working' ? 'agent working' : 'agent waiting'}
1108                            </Text>
1109                          )}
1110                        </Box>
1111                      ))}
1112                    {/* An open pull request not checked out here can be, beside this worktree. */}
1113                    {(s.status === 'open' || s.status === 'draft') &&
1114                      !worktrees.some(w => w.remoteBranch === s.head) &&
1115                      (beingMade.includes(s.head) ? (
1116                        <Box flexShrink={0}>
1117                          <Text dimColor>making worktree…</Text>
1118                        </Box>
1119                      ) : (
1120                        <Box flexShrink={0}>
1121                          <Button key={`make${s.head}`} plain dimColor onPress={() => createWorktree($, git.worktree, s.head)}>
1122                            <Text underline>create worktree</Text>
1123                          </Button>
1124                        </Box>
1125                      ))}
1126                  </Box>
1127                ))}
1128              </Box>
1129            )}
1130          </Box>
1131        )}
1132
1133        {working.length > 0 && (
1134          <Box flexDirection="column">
1135            <Text bold dimColor>
1136              Running Agents
1137            </Text>
1138            {working.map(a => (
1139              <Box key={a.id} paddingLeft={2}>
1140                <Text dimColor wrap="truncate-end">
1141                  {a.description} ({a.type})
1142                </Text>
1143              </Box>
1144            ))}
1145          </Box>
1146        )}
1147
1148        {activity !== null && (
1149          <Text color="suggestion" wrap="truncate-end">
1150            {activity}
1151          </Text>
1152        )}
1153
1154        {/* Docked, the pane is as tall as its column, and this pushes the prompts and the session's figures to the bottom. */}
1155        <Box flexGrow={1} />
1156
1157        <Box flexDirection="column" gap={1}>
1158          <Text bold dimColor>
1159            Recent Prompts
1160          </Text>
1161          {list.length === 0 && <Text dimColor>No prompts yet.</Text>}
1162          {list.map((text, i) => (
1163            <Box key={`p${i}`} paddingLeft={2}>
1164              {i === newest ? (
1165                <Text bold color="suggestion" wrap="truncate-end">
1166                  {text}
1167                </Text>
1168              ) : (
1169                <Text dimColor wrap="truncate-end">
1170                  {text}
1171                </Text>
1172              )}
1173            </Box>
1174          ))}
1175        </Box>
1176
1177        <Box flexDirection="column">
1178          <Text wrap="truncate-end">
1179            <Text dimColor>
1180              {top.model ?? '…'}
1181              {top.effort === null ? '' : ` (${top.effort})`} | context:{' '}
1182            </Text>
1183            <Text
1184              color={percent !== null && percent > CONTEXT_WARNING_PERCENT ? 'error' : undefined}
1185              dimColor={percent === null || percent <= CONTEXT_WARNING_PERCENT}
1186            >
1187              {percent === null ? '…' : `${percent}%`}
1188            </Text>
1189          </Text>
1190          {top.limits.length > 0 && (
1191            <Text wrap="truncate-end">
1192              <Text dimColor>usage: </Text>
1193              {top.limits.map((l, i) => (
1194                <Text
1195                  key={l.kind}
1196                  color={l.percentUsed > LIMIT_WARNING_PERCENT ? 'error' : undefined}
1197                  dimColor={l.percentUsed <= LIMIT_WARNING_PERCENT}
1198                >
1199                  {i > 0 ? ' · ' : ''}
1200                  {limitLabel(l.kind)} {Math.round(l.percentUsed)}%
types/index.d.ts 129 lines
1/** The person's most recent prompts, oldest first. */
2export type Recent = readonly string[]
3
4/** One subscription usage window, as a share used. */
5export type Limit = {
6  /** `five_hour`, `seven_day`, or a gateway's `spend_limit`. */
7  kind: string
8  percentUsed: number
9}
10
11/** What the pane's top lines show; each part null until it is known. */
12export type Header = {
13  /** The main loop's model, as `/model` shows it. */
14  model: string | null
15  /** The effort the main loop's last request asked for. */
16  effort: string | null
17  /** How full the context window is, as a whole percentage. */
18  contextPercent: number | null
19  /** The subscription usage windows; empty off a subscription. */
20  limits: readonly Limit[]
21}
22
23/** The git state of the session's worktree; null outside a repository. */
24export type Repo = {
25  branch: string
26  /** The repository's default branch, such as `master`; null when `origin/HEAD` is not set. */
27  defaultBranch: string | null
28  /** The session's directory. */
29  worktree: string
30  /** Files with changes not yet committed, untracked ones included. */
31  changedFiles: number
32  /** Commits on the branch not on its upstream; null when it has no upstream. */
33  unpushedCommits: number | null
34} | null
35
36/** The branch's pull request; null when it has none or `gh` cannot say. */
37export type PullRequest = {
38  number: number
39  url: string
40  /** The branch the pull request merges into, such as `master`. */
41  base: string
42  /** The branch the pull request merges, such as `BL-16822-inline-3-model`. */
43  head: string
44  /** The branch it merges into; the first one's is the branch the whole stack goes into. */
45  base: string
46  /** `draft`, `open`, `merged` or `closed`. */
47  status: string
48} | null
49
50/** The YouTrack card the branch names, with its summary and state once read; null until one is read. */
51export type Card = {
52  /** Such as `BL-15958`. */
53  id: string
54  summary: string
55  /** The card's State field, such as `Ready For Code Review`; null when it has none. */
56  state: string | null
57} | null
58
59/** One pull request in the stack the branch's pull request belongs to. */
60export type StackEntry = {
61  number: number
62  url: string
63  head: string
64  /** The branch it merges into; the first one's is the branch the whole stack goes into. */
65  base: string
66  /** `draft`, `open`, `merged` or `closed`. */
67  status: string
68}
69
70/**
71 * The pull requests in the branch's pull request's stack, in the order they
72 * merge, merged ones included; empty when it is in no stack.
73 */
74export type Stack = readonly StackEntry[]
75
76/** A worktree on this machine that has a branch checked out. */
77export type CheckedOut = {
78  /** The worktree's top folder, written the Windows way on Windows. */
79  path: string
80  /** The branch's name on the remote, which is what a pull request names. */
81  remoteBranch: string
82  /** How the local branch stands against the remote one: `in sync`, `ahead`, `behind`, `diverged` or `not pushed`. */
83  sync: string
84  /**
85   * What the agents Orca runs in the worktree are doing: `working` when any is,
86   * else `waiting` when any waits on the person; null when none is, or Orca does
87   * not manage the worktree.
88   */
89  agent: string | null
90}
91
92/** One entry of the main conversation's task list, by its id. */
93export type TrackedTask = {
94  /** The present-continuous phrase shown beside the spinner, else the subject. */
95  doing: string
96  status: 'pending' | 'in_progress' | 'completed'
97}
98
99/** What the "Working on:" line is made from. */
100export type WorkingOn = {
101  /** The skill last started, as the person or the model named it. */
102  skill: string | null
103  /** The `TaskCreate`/`TaskUpdate` task list, by task id. */
104  tasks: Readonly<Record<string, TrackedTask>>
105  /** The in-progress item of the last `TodoWrite` list, if any. */
106  todo: string | null
107}
108
109/** A subagent or teammate still at work. */
110export type RunningAgent = { id: string; description: string; type: string }
111
112declare module 'claude-code' {
113  interface PluginState {
114    awareness: {
115      recent: Recent
116      header: Header
117      repo: Repo
118      pullRequest: PullRequest
119      stack: Stack
120      card: Card
121      workingOn: WorkingOn
122      agents: readonly RunningAgent[]
123      checkedOut: readonly CheckedOut[]
124      /** The branches a worktree is being made for. */
125      creating: readonly string[]
126    }
127  }
128}
129