A quiet side pane: what this session is doing now, its plan, its agents as a tree, and every other Claude Code session with theirs

<h1> <img alt="glimt" src="docs/logo-light.svg" height="56"> </h1>
A quiet side pane for Claude Code: what this session is doing, its plan, its agents, and every other session.
glimt is Danish for a glimpse, a brief flash of light. Say it like glimpse without the -pse: GLIMT, with a short i.
Its icon says what it does: a calm board of everything at a glance; one lamp lights when something needs you.

/plugin install glimt --marketplace mmedum/glimt
Needs Claude Code 2.1.289 or later in a terminal (2.1.295 for desktop notifications); tested with 2.1.295. Mods don't draw in the VS Code panel or with -p.
The pane opens by itself when the terminal is at least 144 columns wide. /glimt opens it at any width, with the keyboard; with the pane open, behind another tab or with the keyboard in the prompt box, it gives the pane the keyboard again, on the row you left. q closes it. A pane you close stays closed, also after /clear, until you open it.
Third-party marketplaces don't update on their own. To update, run claude plugin update glimt@glimt and restart Claude Code. To remove glimt, run claude plugin uninstall glimt@glimt.
The keys work while the pane holds the keyboard: open it with /glimt, click it, or press ctrl+x tab. j and k move down and up the rows, while ↑ ↓ and Tab also stop on the keys, the way back and the fields; l goes in and h back out; Enter opens or closes the row (a step's description, an agent's task, a session's agents); Esc gives the keyboard back to the prompt; q closes the pane. The key row shows only what the selected row allows; i lists every key. While the keyboard is at the prompt or in one of glimt's forms, the row you left stays marked by a quiet band across the pane, as in a Neovim side panel: by default the theme's userMessageBackground, or the Cursor band color option. Closing the pane forgets the row, and it opens again on the overview.
| Key | Does |
|---|---|
j | the next row; from a key or the way back, the first |
k | the row before; from a key or the way back, the last |
l | go into an agent or a session: its task, model, branch and live activity |
h | back out, one level at a time, from the line that names where it goes |
n | new agent here |
s | new background session (claude --bg), from the i list |
r | rename this session, or another session running glimt |
c | clear this conversation, after asking |
m | write to the agent or session you are in |
a | copy a background session's claude attach command |
x | stop a background session or agent, after asking |
i | all keys |
q | close the pane |
A spinner marks whatever is working right now: a running agent, a working session, the step in progress while Claude is on it. The rest keep still marks: ◉ waiting for you, ○ idle, ✓ done, ✗ failed, ■ stopped.
Under this session's name, a status row speaks up only when something is out of the ordinary: bypass permissions in amber while the main conversation runs in that mode; a plan limit from 80% used, at full weight from 95%, the fullest first with when it resets, as in 5h limit 95% · resets in 1h12m; and same folder when another session runs in this session's folder. Otherwise it isn't there. Open the row for the folder, the model and its effort.
A waiting session says what it wants: approve for a permission prompt, answer for a question. A background session that ended says done, failed or stopped. Each other session shows how long it has been in its state, counted from when glimt saw that state begin, and its name turns bold when it stops or ends, until you react to it: open it in glimt (in any session's pane), type or send a prompt in its own terminal, or press in its glimt pane there. Stopping it with x counts too. Sessions are listed waiting first, then working, then failed or stopped, then done or idle, each group by when the sessions started, so a row moves only when its state changes. Short of room, idle sessions you have seen fold into one line (○ 2 idle), and +N more gives up working rows and rows you have seen before one that waits or is in bold. A session you never renamed goes by the title Claude Code gave it, as in its resume list. A row says same folder when another session runs in the same folder. Where another session runs glimt, its row also shows how far its plan has come, as in 3/7, bypass in amber while it runs in bypass permissions, and its context from 80% full. Going into a session names its permission mode.
glimt has five options. Set them in /config (type glimt to find them) or with /plugin configure glimt@glimt, then restart Claude Code.
inactive by default, Claude Code's own color for hints and timestamps): hints, counts, times, finished rows and the tree's lines.inactive by default): the ☐ of a step to do and the ○ of another session that is idle or done, or of one of its agents gone quiet, also on the lines that fold them (☐ 3 more, ○ 2 idle). The other marks keep their status colors.userMessageBackground by default, the background behind your messages): the band across the row you left while the keyboard is at the prompt or in one of glimt's forms. Otherwise the row's name is inverse.By default the quiet text, the marks and the band follow /theme, light or dark. A color option takes another role, such as claude or success, or a color: #7aa2f7, rgb(122,162,247), ansi256(110) or ansi:cyan. A value glimt can't read leaves the default. To restyle quiet text all over Claude Code, override inactive in a custom theme instead; a hex or rgb() color doesn't follow light or dark themes, while color names, ansi: names and ansi256() from 0 to 15 follow your terminal's own palette. The keys and the way back (← Overview) stay inactive whatever you set: they are buttons, and Claude Code gives a mod's buttons no color of their own.
An agent with a call waiting for your approval shows ◉ and approve with the tool and what it runs, as in approve Bash · git push. Claude Code tells a mod when a call is put to you, not when you answer, so the mark stays until that call ends.
Mods run with your permissions, so here is everything glimt touches. claude plugin validate lists the same. glimt itself makes no network requests; an agent or a session you start with it talks to Claude like any other.
$.agent.list), every 5 seconds while glimt shows one as running, so an agent whose end it missed doesn't stay running.claude agents --json, every 5 seconds while the pane is drawn.~/.claude/projects/, for the title Claude Code gave it: once, whether the session was ever renamed, and while it never was, the transcript's last 64 KiB every 30 seconds while the pane is drawn.~/.claude/projects/ (or $CLAUDE_CONFIG_DIR/projects/), for a session you open: its subagents' file names and .meta.json files every 5 seconds, its transcript's last 128 KiB every 2 seconds while you are inside it, and an agent's first line when you open that agent.HOME and CLAUDE_CONFIG_DIR, only to find that folder and to write paths as ~. It reads no credentials./config or with /plugin configure glimt@glimt: Notifications and the four colors.claude agents --json; tail -c 131072 <transcript> and head -n 1 <agent transcript> for the reads above; grep -m 1 -F '"type":"custom-title"' <transcript> and tail -c 65536 <transcript> for a session's title; claude --bg <task>, in this session's folder, when you press s and type a task; claude stop <id> when you press x on a background session and answer y; git -C <folder> rev-parse --abbrev-ref HEAD for a session you are inside, at most every 30 seconds, to show its branch.TaskList once at session start, so a resumed session shows its plan, and TaskGet when you open a step, for its description, which only read; and TaskStop when you press x on an agent that runs in the background and answer y, which stops that agent./rename <name> when you rename this session with r, or when another session's glimt asks it to take a name; /clear when you press c and answer y.general-purpose agent when you press n. Its prompt is the task you type, and nothing else.m, as typed, to the agent or session you are inside, through Claude Code.$.ui.notify, Claude Code's own call (2.1.295), and your notification setting; a toast where your terminal shows none; nothing if you turned notifications off in Claude Code or glimt's Notifications option is off. A session in a terminal of its own notifies from there when it waits.claude attach <id> to your clipboard when you press a.metadata.parent)./glimt, its own command, opens the pane or gives it the keyboard.Its hook on Claude Code's permission request only notes which agent is being asked and about which call (the tool, and the command, path or address it is on), and hands the request on unchanged: glimt never answers a permission. Its other hooks (tool calls, turns, agents, prompts, the hook events that carry the permission mode, usage measurements, session start and end, focus) only read what passes, to keep the pane current, and pass it on unchanged.
The plan comes from Claude's task list. Claude Code offers that list by default only on some models, and on every model in background sessions (agent view, or claude --bg); see task tool availability. To have it in a terminal session on other models, start Claude Code with CLAUDE_CODE_ENABLE_TODO_TOOLS=1. Without it, the plan says so and everything else works the same.
It can't switch this terminal to another session: Claude Code offers mods no way to do that (#100519). In an attached background session, ← on an empty prompt returns to agent view.
glimt collects no data about you and sends nothing anywhere. It runs only on your machine, makes no network requests, and has no service or telemetry of its own. It writes no files.
What it reads, it reads to draw the pane, as listed under How it works. What it keeps between sessions sits in Claude Code's plugin store on your machine: each session's running agents, with up to 400 characters of each agent's task and the tool one waits on you to allow, how far its plan has come, its permission mode and how full its context is, when you last reacted to each listed session (a time, never what you typed), and names one session asks another to take. A session's entry is deleted when the session ends or stops running, an entry not refreshed for a minute is ignored, and a name is deleted once taken.
An agent or a session you start from glimt, and a message you send with m, goes to Claude through Claude Code like anything you type yourself, under Anthropic's privacy policy.
Questions and bugs: open an issue. For a pull request, open an issue first. CONTRIBUTING.md says how to run, test and release glimt. To report a security problem, see SECURITY.md.
Apache-2.0 © 2026 Mark Medum Bundgaard
hooks/register.tsx 1771 lines1// glimt's hooks, and everything that talks to the engine: the engine follows
2// $ only into functions of this file, and reads state only through atoms
3// declared here, so all of that lives here. The other modules are pure: what
4// the pane computes and draws.
5
6import { atom, read, update } from 'claude-code'
7import type { EngineInterface, PromptOrigin, Register } from 'claude-code'
8import type {
9 Activity,
10 Agent,
11 AgentState,
12 Composer,
13 Feed,
14 Opened,
15 Plan,
16 RemoteAgent,
17 RemoteList,
18 RunningCall,
19 Session,
20 Shared,
21 SharedAgent,
22 Step,
23} from '../types'
24import { agentSection, askCall, askingOf, contextTokens, isStoppable, isTurnRunning, mainAgent, settled, withCalls } from './agents'
25import type { Spawned } from './agents'
26import { FEED_KEPT, TAIL_BYTES, callLine, drillSection, isShownText, lastModel, parseTranscript, titleOf } from './drill'
27import { FORM_ROWS, composerSection, helpSection, keySection, landingOf, selfSection } from './keys'
28import { colorOf } from './paint'
29import { applyUpdate, nowSection, parentFrom, planLines, planSection, planTitle, planUnits, rowCount } from './plan'
30import type { StepUpdate } from './plan'
31import {
32 HEARTBEAT_MS,
33 POLL_MS,
34 REMOTE_KEPT,
35 SHARED_TASK,
36 STALE_MS,
37 isReachable,
38 isSessionBusy,
39 endingOf,
40 isNotifier,
41 isShared,
42 nextPhases,
43 nextSeen,
44 sharedFolders,
45 parseSessions,
46 sessionSection,
47 sortSessions,
48 waitingNote,
49} from './sessions'
50import { PANE, runtime } from './state'
51import { FRAME_MS, describeCall, firstLine, fit, isRecord, spin, wrap } from './text'
52import type { Colors, View } from './view'
53
54// Who counts as asking: the person, typing or through Remote Control or the
55// SDK. A task notification, a peer or a plugin is not a new request.
56const PERSON: ReadonlySet<PromptOrigin['kind']> = new Set(['composer', 'bridge', 'sdk'])
57
58// The shares of a docked pane's rows the agents and the other sessions may
59// take from the plan, which gets the rest.
60const AGENT_SHARE = 0.35
61const SESSION_SHARE = 0.25
62
63// The person's doings in this session count as one reaction a second at
64// most: typing raises an edit with nearly every key.
65const TOUCH_MS = 1000
66
67// Drilled into another session, its transcript is read again this often,
68// from its last TAIL_BYTES; an agent of this session is read as it acts.
69// The newest FEED_KEPT items are kept.
70const FEED_MS = 2000
71// Rows the chat leaves out while the pane shows them.
72const PLAN_TOOLS: ReadonlySet<string> = new Set(['TaskCreate', 'TaskUpdate', 'TaskList', 'TaskGet', 'TodoWrite'])
73
74// One line in the system prompt, sent while the task tools are on offer, so
75// Claude files a sub-step under its step.
76const SUB_STEP_NOTE = "When a task you create with TaskCreate is a sub-step of another task, set metadata.parent to that task's id."
77
78const focus = atom({ plugin: 'glimt', key: 'focus' } as const, null)
79const plan = atom({ plugin: 'glimt', key: 'plan' } as const, null)
80const steps = atom({ plugin: 'glimt', key: 'steps' } as const, [])
81const agents = atom({ plugin: 'glimt', key: 'agents' } as const, [])
82const now = atom({ plugin: 'glimt', key: 'now' } as const, 0)
83const isShown = atom({ plugin: 'glimt', key: 'isShown' } as const, false)
84const expanded = atom({ plugin: 'glimt', key: 'expanded' } as const, [])
85const cursor = atom({ plugin: 'glimt', key: 'cursor' } as const, null)
86const sessions = atom({ plugin: 'glimt', key: 'sessions' } as const, null)
87const sessionsError = atom({ plugin: 'glimt', key: 'sessionsError' } as const, null)
88const phases = atom({ plugin: 'glimt', key: 'phases' } as const, {})
89const seen = atom({ plugin: 'glimt', key: 'seen' } as const, {})
90const hasTaskList = atom({ plugin: 'glimt', key: 'hasTaskList' } as const, null)
91const mode = atom({ plugin: 'glimt', key: 'mode' } as const, null)
92const limits = atom({ plugin: 'glimt', key: 'limits' } as const, [])
93const engine = atom({ plugin: 'glimt', key: 'engine' } as const, null)
94const titles = atom({ plugin: 'glimt', key: 'titles' } as const, {})
95const stopping = atom({ plugin: 'glimt', key: 'stopping' } as const, null)
96const self = atom({ plugin: 'glimt', key: 'self' } as const, null)
97const shared = atom({ plugin: 'glimt', key: 'shared' } as const, {})
98const composer = atom({ plugin: 'glimt', key: 'composer' } as const, null)
99const clearing = atom({ plugin: 'glimt', key: 'clearing' } as const, false)
100const opened = atom({ plugin: 'glimt', key: 'opened' } as const, [])
101const feed = atom({ plugin: 'glimt', key: 'feed' } as const, null)
102const remote = atom({ plugin: 'glimt', key: 'remote' } as const, {})
103const remoteTasks = atom({ plugin: 'glimt', key: 'remoteTasks' } as const, {})
104const help = atom({ plugin: 'glimt', key: 'help' } as const, false)
105
106const transcripts = new Map<string, string>()
107
108// Claude Code's own titles: whether each session was renamed (then its name
109// stays), and when its title was last read; read again after TITLE_MS, from
110// the transcript's last TITLE_BYTES.
111const TITLE_MS = 30_000
112const TITLE_BYTES = 65_536
113const titleReads = new Map<string, { isRenamed: boolean; at: number }>()
114
115// Each folder's git branch as last read, and when: read again after BRANCH_MS.
116const BRANCH_MS = 30_000
117const branches = new Map<string, { branch: string | undefined; at: number }>()
118
119// Each subagent's type and description, by its meta file: they never change.
120const metas = new Map<string, { type: string; description: string }>()
121
122export const register: Register = (on, options) => {
123 runtime.notifies = options.notifications !== false
124 // The color options, read once here for the pane and the chat alike. A
125 // Heading color unset or unreadable leaves the headings without a color:
126 // bold in the terminal's own text color.
127 const colors: Colors = {
128 quiet: colorOf(options.quietColor, 'inactive'),
129 mark: colorOf(options.markColor, 'inactive'),
130 heading: colorOf(options.headingColor, undefined),
131 band: colorOf(options.bandColor, 'userMessageBackground'),
132 }
133
134 // The command last: a refused registration then leaves the pane and its clock running.
135 on('session.start', async ($, e, next) => {
136 $.clock.every(FRAME_MS, () => void tick($))
137 $.clock.every(POLL_MS, () => void readSessions($, false).catch(() => undefined))
138 $.clock.every(POLL_MS, () => void settleAgents($).catch(() => undefined))
139 $.clock.every(POLL_MS, () => void share($).catch(() => undefined))
140 $.clock.every(FEED_MS, () => void readFeed($, true).catch(() => undefined))
141 $.clock.every(POLL_MS, () => void readRemote($).catch(() => undefined))
142 void openPane($).catch(() => undefined)
143 runtime.home = (await $.env.get('HOME').catch(() => undefined)) ?? ''
144 const configured = await $.env.get('CLAUDE_CONFIG_DIR').catch(() => undefined)
145 runtime.configDir = configured !== undefined && configured !== '' ? configured : `${runtime.home}/.claude`
146 await learnSelf($)
147 void readSessions($, true).catch(() => undefined)
148 await seedSteps($).catch(() => undefined)
149 await $.command.register({
150 name: 'glimt',
151 description: 'Open the glimt pane: what is in progress, the plan, the agents, and the other sessions',
152 })
153
154 return next(e)
155 })
156
157 // /clear, /resume and /branch put every $.state value back to its default
158 // and raise no session.start: learn the session's id again, and whether
159 // the pane is drawn.
160 on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
161 await learnSelf($)
162 void openPane($).catch(() => undefined)
163 void readSessions($, true).catch(() => undefined)
164
165 return next(e)
166 })
167
168 // /glimt gives the pane the keyboard: it opens it, brings it to the front
169 // of the dock, or takes the keyboard back from the prompt, the ring where
170 // the person left off (see landingOf). q closes the pane.
171 on('command.run', { command: 'glimt' }, async $ => {
172 await openPane($, true)
173 const to = landingOf({
174 hasForm: (await read($, composer)) !== null,
175 hasKeyList: await read($, help),
176 cursor: await read($, cursor),
177 rows: runtime.toggles.map(one => one.key),
178 isInside: (await read($, opened)).length > 0,
179 })
180 if (to !== null) {
181 await ringOn($, to.key, to.isRow)
182 }
183
184 return {}
185 })
186
187 // Unless a hook refused the close, the pane forgets (see forgetPane). A
188 // hook that keeps glimt's pane open by answering without next, rather than
189 // with a deny, can't be told apart: a rare case, accepted.
190 on('ui.close', async ($, e, next) => {
191 const answered = await next(e)
192 if (e.id === PANE && answered.deny === undefined) {
193 await forgetPane($)
194 }
195
196 return answered
197 })
198
199 // Tab and the arrows move Claude Code's focus ring; the cursor follows it
200 // onto a toggle. Leaving the form's field that way, or by a click, closes
201 // the form.
202 on('ui.focus', async ($, e, next) => {
203 const key = e.element
204 if (e.requestId === PANE && e.origin.kind === 'person') {
205 await touch($)
206 }
207 if (e.requestId === PANE && key !== undefined) {
208 runtime.isOffRows = !runtime.toggles.some(one => one.key === key)
209 if (!runtime.isOffRows) {
210 await update($, cursor, () => key)
211 }
212 }
213 const isLeavingForm = e.requestId === PANE && e.origin.kind === 'person' && key !== 'composer-field' && (await read($, composer)) !== null
214 if (isLeavingForm) {
215 await update($, composer, () => null)
216 }
217
218 const answered = await next(e)
219 // Tab onto the form's own cancel: the button goes with the form.
220 if (isLeavingForm && key === 'composer-cancel') {
221 await ringBack($)
222 }
223 return answered
224 })
225
226 // Whether Claude has a task list depends on the model; the plan says so
227 // while it is empty.
228 on('prompt.compose', async ($, e, next) => {
229 const composed = await next(e)
230 const isOffered = e.tools.includes('TaskCreate') || e.tools.includes('TodoWrite')
231 await update($, hasTaskList, was => was === true || isOffered)
232 if (!e.tools.includes('TaskCreate')) {
233 return composed
234 }
235
236 return { sections: [...composed.sections, { id: 'glimt:sub-steps', text: SUB_STEP_NOTE, scope: 'session' as const }] }
237 })
238
239 // While the pane is drawn the chat leaves out the plan's rows and squeezes a
240 // running agent to one line; an errored call still shows.
241 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
242 const isPlanRow = PLAN_TOOLS.has(e.props.tool)
243 const isLiveAgent = e.props.tool === 'Agent' && e.props.isRunning
244 if ((!isPlanRow && !isLiveAgent) || e.props.isErrored || !(await read($, isShown))) {
245 return next(e)
246 }
247
248 const { Box, Text } = $.ui.resolve(e)
249 if (isPlanRow) {
250 return <Box />
251 }
252
253 const input = isRecord(e.props.input) ? e.props.input : {}
254 const type = typeof input.subagent_type === 'string' ? input.subagent_type : 'Agent'
255 const description = typeof input.description === 'string' ? input.description : ''
256
257 return (
258 <Text color={colors.quiet} wrap="truncate-end">
259 {spin(await read($, now))} {type} · {description}
260 </Text>
261 )
262 })
263
264 // A /clear starts a new conversation: nothing on show belongs to it.
265 on('session.end', async ($, e, next) => {
266 // The session's share goes with it; after a /clear the next is under a new id.
267 const id = await read($, self)
268 if (id !== null) {
269 await $.store.delete(`agents:${id}`).catch(() => undefined)
270 }
271 runtime.lastShared = ''
272 if (e.reason === 'clear') {
273 await update($, focus, () => null)
274 await update($, plan, () => null)
275 await update($, steps, () => [])
276 await update($, agents, () => [])
277 await update($, expanded, () => [])
278 await update($, cursor, () => null)
279 await update($, stopping, () => null)
280 await update($, opened, () => [])
281 await update($, feed, () => null)
282 await update($, help, () => false)
283 }
284
285 return next(e)
286 })
287
288 // Whatever the person sends here is a reaction to this session; a new
289 // request also clears the agents that finished before it.
290 on('prompt.submit', async ($, e, next) => {
291 if (PERSON.has(e.origin.kind)) {
292 await touch($)
293 }
294 if (PERSON.has(e.origin.kind) && !e.text.startsWith('/')) {
295 await update($, agents, list => list.filter(a => a.state === 'running'))
296 }
297
298 return next(e)
299 })
300
301 // Typing in the prompt box is a reaction to this session too. Only when
302 // it happens counts: what is typed is never read. The key goes on at once,
303 // so typing never waits on glimt.
304 on('prompt.edit', async ($, e, next) => {
305 void touch($).catch(() => undefined)
306
307 return next(e)
308 })
309
310 // So is a press in this session's pane.
311 on('ui.press', async ($, e, next) => {
312 if (e.requestId === PANE) {
313 await touch($)
314 }
315
316 return next(e)
317 })
318
319 // The main loop's turns: a subagent's run raises no turn.start.
320 on('turn.start', async ($, e, next) => {
321 runtime.isBusy = true
322 const at = await $.clock.now()
323 await update($, focus, () => ({ startedAt: at, tools: 0 }))
324 await update($, now, () => at)
325
326 return next(e)
327 })
328
329 on('turn.complete', async ($, e, next) => {
330 const at = await $.clock.now()
331 const agentId = e.agentId
332 const state: AgentState = e.reason === 'answer' ? 'done' : e.reason === 'aborted' ? 'stopped' : 'failed'
333 if (agentId === undefined) {
334 await update($, focus, f => (f === null ? f : withCalls({ ...f, endedAt: at, outcome: state }, [])))
335 } else {
336 await update($, agents, list => list.map(a => (a.agentId === agentId ? withCalls({ ...a, state, endedAt: at }, []) : a)))
337 await readAgentFeed($, agentId).catch(() => undefined)
338 }
339 await update($, now, () => at)
340
341 return next(e)
342 })
343
344 // An agent's own tasks nest under the plan step in progress when it
345 // started; one spawned by another agent nests where that agent does.
346 on('agent.spawn', async ($, e, next) => {
347 const started = await next(e)
348 if (started.deny !== undefined) {
349 return started
350 }
351
352 await recordAgent($, {
353 agentId: started.agentId,
354 fallbackId: e.tool_use_id,
355 parentId: e.parentAgentId,
356 type: e.subagentType,
357 description: e.description,
358 task: e.prompt,
359 model: started.model,
360 isBackground: e.background,
361 })
362
363 return started
364 })
365
366 // Each model request of any loop: the size of that loop's context, and for
367 // the main conversation how full its window is. A request starts once the
368 // loop's calls have ended, so any still listed (one that never told its
369 // end) go as it starts.
370 on('turn.step', async function* ($, e, next) {
371 const loopId = e.agentId
372 if (loopId === undefined) {
373 const use = { model: e.model, effort: typeof e.effort === 'string' ? e.effort : undefined }
374 await update($, engine, () => use)
375 await update($, focus, f => (f === null || (f.calls ?? []).length === 0 ? f : withCalls(f, [])))
376 } else {
377 await update($, agents, list => list.map(a => (a.agentId === loopId && (a.calls ?? []).length > 0 ? withCalls(a, []) : a)))
378 }
379 const result = yield* next(e)
380 if (result.usage !== null) {
381 const tokens = contextTokens(result.usage)
382 const agentId = e.agentId
383 if (agentId === undefined) {
384 const percent = (await $.session.usage().catch(() => undefined))?.context.percent
385 await update($, focus, f => (f === null ? f : { ...f, tokens, percent }))
386 } else {
387 await update($, agents, list => list.map(a => (a.agentId === agentId ? { ...a, tokens } : a)))
388 }
389 }
390 if (e.agentId !== undefined) {
391 await readAgentFeed($, e.agentId).catch(() => undefined)
392 }
393
394 return result
395 })
396
397 // Each loop's calls: the ones it runs now and how many it has made; each
398 // call goes from its loop's list as it ends, whichever ends first. The
399 // pane's own calls (TaskList, TaskGet) never pass its own hooks.
400 on('tool.call', async ($, e, next) => {
401 const agentId = e.agentId
402 runtime.calls += 1
403 const call: RunningCall = { id: String(runtime.calls), tool: e.tool, on: describeCall(e) }
404 const end = <T extends { calls?: RunningCall[] | undefined }>(item: T) =>
405 withCalls(
406 item,
407 (item.calls ?? []).filter(one => one.id !== call.id),
408 )
409 if (agentId === undefined) {
410 await update($, focus, f => (f === null || !isTurnRunning(f) ? f : withCalls({ ...f, tools: (f.tools ?? 0) + 1 }, [...(f.calls ?? []), call])))
411 try {
412 return await next(e)
413 } finally {
414 await update($, focus, f => (f === null ? f : end(f)))
415 }
416 }
417
418 runtime.isBusy = true
419 await update($, agents, list =>
420 list.map(a =>
421 a.agentId === agentId ? withCalls({ ...a, state: 'running', endedAt: undefined, tools: a.tools + 1 }, [...(a.calls ?? []), call]) : a,
422 ),
423 )
424 await readAgentFeed($, agentId).catch(() => undefined)
425 try {
426 return await next(e)
427 } finally {
428 await update($, agents, list => list.map(a => (a.agentId === agentId ? end(a) : a)))
429 await readAgentFeed($, agentId).catch(() => undefined)
430 }
431 })
432
433 // Claude Code is about to ask the person about a subagent's call: that
434 // call waits from now until it ends. Claude Code says when it asks, not
435 // when the person answers, so an allowed call shows as waiting while it
436 // runs; and a settings hook beneath that answers the request itself goes
437 // unseen. The hook decides nothing: it hands the request on as it came,
438 // and leaves the answer to the person.
439 on('classic.PermissionRequest', async ($, e, next) => {
440 const agentId = e.agent_id
441 if (agentId !== undefined) {
442 const at = await $.clock.now()
443 const subject = describeCall(e.tool_input)
444 await update($, agents, list =>
445 list.some(a => a.agentId === agentId)
446 ? list.map(a => (a.agentId === agentId ? withCalls(a, askCall(a.calls ?? [], e.tool_name, subject, at)) : a))
447 : list,
448 )
449 }
450
451 return next(e)
452 })
453
454 // This session's permission mode, as these events carry it: read only, the
455 // events handed on as they came. A mode changed with shift+tab shows by the
456 // next prompt, tool call or turn's end; Claude Code's own footer says it
457 // first. Permission events are left alone for this.
458 on('classic.UserPromptSubmit', async ($, e, next) => {
459 await noteMode($, e.permission_mode, e.agent_id)
460 return next(e)
461 })
462 on('classic.PostToolUse', async ($, e, next) => {
463 await noteMode($, e.permission_mode, e.agent_id)
464 return next(e)
465 })
466 on('classic.Stop', async ($, e, next) => {
467 await noteMode($, e.permission_mode, e.agent_id)
468 return next(e)
469 })
470
471 // The plan's limit windows, as Claude Code measures them after a response.
472 on('session.measure', async ($, e, next) => {
473 const windows = e.rateLimits.map(limit => ({ kind: limit.kind, percentUsed: limit.percentUsed, resetsAt: limit.resetsAt }))
474 await update($, limits, () => windows)
475 return next(e)
476 })
477
478 // The plan is the main loop's task list: TaskCreate and TaskUpdate, or
479 // TodoWrite where a build still uses it. A subagent's own tasks join it as
480 // sub-steps (see ownerOf).
481 on('tool.call', { tool: 'TaskCreate' }, async ($, e, next) => {
482 const ran = await next(e)
483 const owner = await ownerOf($, e.agentId)
484 if (ran.deny !== undefined || ran.isError || owner === null) {
485 return ran
486 }
487
488 const { id, subject } = ran.result.task
489 const parent = parentFrom(e.metadata)
490 const step: Step = {
491 id: owner.prefix + id,
492 subject,
493 description: e.description,
494 activeForm: e.activeForm,
495 status: 'pending',
496 parentId: typeof parent === 'string' ? owner.prefix + parent : owner.stepId,
497 }
498 await update($, steps, list => [...list, step])
499
500 return ran
501 })
502
503 on('tool.call', { tool: 'TaskUpdate' }, async ($, e, next) => {
504 const ran = await next(e)
505 const owner = await ownerOf($, e.agentId)
506 if (ran.deny !== undefined || ran.isError || !ran.result.success || owner === null) {
507 return ran
508 }
509
510 const parent = parentFrom(e.metadata)
511 const change: StepUpdate = {
512 taskId: owner.prefix + e.taskId,
513 subject: e.subject,
514 description: e.description,
515 activeForm: e.activeForm,
516 status: e.status,
517 parent: typeof parent === 'string' ? owner.prefix + parent : parent,
518 }
519 const at = await $.clock.now()
520 // A subagent's task the pane never saw made is none of the plan's.
521 await update($, steps, list => (owner.prefix !== '' && !list.some(step => step.id === change.taskId) ? list : applyUpdate(list, change, at)))
522
523 return ran
524 })
525
526 on('tool.call', { tool: 'TodoWrite' }, async ($, e, next) => {
527 const ran = await next(e)
528 if (e.agentId === undefined && ran.deny === undefined && !ran.isError) {
529 const todos = ran.result.newTodos
530 const at = await $.clock.now()
531 // TodoWrite sends the whole list each time: a todo still in progress
532 // under the same words keeps the time it started.
533 await update($, steps, list =>
534 todos.map((todo, i) => {
535 const before = list.find(step => step.subject === todo.content && step.status === 'in_progress')
536 return {
537 id: String(i + 1),
538 subject: todo.content,
539 description: '',
540 activeForm: todo.activeForm,
541 status: todo.status,
542 startedAt: todo.status === 'in_progress' ? (before?.startedAt ?? at) : undefined,
543 }
544 }),
545 )
546 }
547
548 return ran
549 })
550
551 on('tool.call', { tool: 'ExitPlanMode' }, async ($, e, next) => {
552 const ran = await next(e)
553 if (e.agentId !== undefined || ran.deny !== undefined || ran.isError) {
554 return ran
555 }
556
557 const text = ran.result.plan
558 if (text !== null && text !== '') {
559 const approved: Plan = { title: planTitle(text), path: ran.result.filePath }
560 await update($, plan, () => approved)
561 }
562
563 return ran
564 })
565
566 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
567 const ui = $.ui.resolve(e)
568 const { Box, Text } = ui
569 const request = await read($, focus)
570 const approved = await read($, plan)
571 const list = await read($, steps)
572 const team = await read($, agents)
573 const open = await read($, expanded)
574 // Esc hands the keyboard back to the prompt and raises nothing else:
575 // drawn without the keyboard, a form shows no more, and the clock's next
576 // frame closes it (a drawing may not write); drawn with the keyboard
577 // again before that frame, it stays. Only the terminal holds the
578 // keyboard: another surface drawing the pane says nothing about it.
579 if (e.surface === 'terminal') {
580 if (e.props.isFocused) {
581 runtime.hasLostKeyboard = false
582 } else if (runtime.isFocused) {
583 runtime.hasLostKeyboard = true
584 }
585 runtime.isFocused = e.props.isFocused
586 }
587 const form = e.props.isFocused ? await read($, composer) : null
588 // The rows hold the keyboard while the pane does and no form of glimt's
589 // is open; the cursor's row, the keys and h follow it. Claude Code can't
590 // say reliably where its focus ring is, so typing in the message field
591 // inside an agent or a session leaves the row inverse, as before 0.6.2.
592 const holdsRows = e.props.isFocused && form === null
593 const view: View = {
594 ui,
595 Input: 'Input' in ui ? ui.Input : undefined,
596 columns: Math.max(12, e.props.bodyColumns),
597 at: await read($, now),
598 isTurnRunning: isTurnRunning(request),
599 cursor: await read($, cursor),
600 isFocused: holdsRows,
601 toggle: key => void toggle($, key),
602 colors,
603 }
604
605 // This session at the top; the other sessions on the machine, and what
606 // their glimts share, at the bottom.
607 const listed = named(await read($, sessions), await read($, titles))
608 const selfId = await read($, self)
609 const others = listed === null ? null : sortSessions(listed.filter(s => s.sessionId !== selfId))
610 const sharedBy = await read($, shared)
611 const pointed = others?.find(s => view.cursor === `toggle-session-${s.sessionId}`)
612 const pointedAgent = team.find(a => view.cursor === `toggle-agent-${a.id}`)
613 const isOnSelf = view.cursor === 'toggle-self'
614 const renameTarget = isOnSelf ? selfId : pointed !== undefined && sharedBy[pointed.sessionId] !== undefined ? pointed.sessionId : null
615 const keys = holdsRows
616 ? keySection(
617 view,
618 {
619 canInto: /^toggle-(agent|session|remote)-/.test(view.cursor ?? ''),
620 canClear: isOnSelf,
621 canRename: renameTarget !== null,
622 canReach: pointed !== undefined && isReachable(pointed),
623 canStop: pointedAgent !== undefined && isStoppable(pointedAgent),
624 },
625 {
626 into: () => void goInto($),
627 spawn: () => void openComposer($, { kind: 'spawn', where: 'here' }),
628 help: () => void update($, help, () => true),
629 rename: () => void (renameTarget === null ? undefined : openComposer($, { kind: 'rename', sessionId: renameTarget })),
630 clear: () => void update($, clearing, () => true),
631 attach: () => void attachSession($),
632 stop: () => void askStop($),
633 down: () => void moveBy($, 1),
634 up: () => void moveBy($, -1),
635 close: () => void closePane($),
636 },
637 )
638 : undefined
639
640 const folders = sharedFolders(listed ?? [])
641 const selfSession = listed?.find(s => s.sessionId === selfId)
642 const header = selfSection(view, {
643 session: selfSession,
644 isOpen: open.includes('self'),
645 isClearing: await read($, clearing),
646 answer: isYes => void answerClear($, isYes),
647 mode: await read($, mode),
648 limits: await read($, limits),
649 isSameFolder: selfSession !== undefined && folders.has(selfSession.cwd),
650 engine: await read($, engine),
651 })
652 const formRows = form === null ? 0 : FORM_ROWS
653 const formNode =
654 form === null
655 ? undefined
656 : composerSection(view, form, listed ?? [], {
657 spawn: (task, where) => void spawnAgent($, task, where),
658 rename: (sessionId, name) => void renameSession($, sessionId, name),
659 cancel: () => void update($, composer, () => null).then(() => ringBack($)),
660 })
661
662 // The sections stack from the top, each in a place that never moves: this
663 // session, any open form, what is in progress, the plan, the agents, the
664 // other sessions, and the keys while the pane holds the keyboard. Docked,
665 // the pane's height is a budget: the agents and the sessions take up to
666 // their shares and the plan, the longest list, gets what is left and
667 // folds to fit. Inline, nothing is cut.
668 const rows = e.props.placement === 'dock' ? e.props.scroll.bodyRows : undefined
669
670 // i: the key list takes the pane until i again, or a key it lists.
671 if (await read($, help)) {
672 runtime.toggles = []
673 const leave = async (then: () => Promise<unknown>) => {
674 await update($, help, () => false)
675 await then()
676 }
677 return (
678 <Box flexDirection="column" width={view.columns}>
679 {helpSection(view, {
680 spawn: () => void leave(() => openComposer($, { kind: 'spawn', where: 'here' })),
681 session: () => void leave(() => openComposer($, { kind: 'spawn', where: 'session' })),
682 close: () => void closePane($),
683 back: () => void update($, help, () => false),
684 })}
685 </Box>
686 )
687 }
688
689 // Gone into an agent or a session, it takes the pane: the arrows walk a
690 // session's agents, and h steps back out to where it was.
691 const into = (await read($, opened)).at(-1)
692 const remoteBy = await read($, remote)
693 const tasks = await read($, remoteTasks)
694 if (into !== undefined) {
695 const sessionId = into.kind === 'agent' ? undefined : into.sessionId
696 // h goes back to the session the pane went into first, else to the overview.
697 const below = (await read($, opened)).at(-2)
698 const parent = below?.kind === 'session' ? listed?.find(s => s.sessionId === below.sessionId) : undefined
699 const drill = drillSection(view, {
700 into,
701 backTo: below === undefined ? 'Overview' : (parent?.name ?? 'back'),
702 agent: into.kind === 'agent' ? team.find(a => a.id === into.id) : undefined,
703 session: sessionId === undefined ? undefined : listed?.find(s => s.sessionId === sessionId),
704 phase: into.kind === 'session' ? (await read($, phases))[into.sessionId] : undefined,
705 mode: sessionId === undefined ? undefined : sharedBy[sessionId]?.mode,
706 remoteAgent: into.kind === 'remote' ? remoteBy[into.sessionId]?.agents.find(a => a.id === into.agentId) : undefined,
707 remote: sessionId === undefined ? undefined : remoteBy[sessionId],
708 shared: sessionId === undefined ? [] : (sharedBy[sessionId]?.agents ?? []),
709 isSharing: sessionId !== undefined && sharedBy[sessionId] !== undefined,
710 tasks,
711 open,
712 feed: await read($, feed),
713 asked: await read($, stopping),
714 isFocused: holdsRows,
715 room: rows === undefined ? undefined : rows - formRows,
716 act: {
717 back: () => void goBack($),
718 into: () => void goInto($),
719 message: () => void ringOn($, 'message-field', false),
720 send: (to, name, text) => void sendFromField($, to, name, text),
721 rename: () => void (into.kind === 'session' ? openComposer($, { kind: 'rename', sessionId: into.sessionId }) : undefined),
722 attach: () => void attachSession($),
723 stop: () => void askStop($),
724 answer: isYes => void answerStop($, isYes),
725 help: () => void update($, help, () => true),
726 down: () => void moveBy($, 1),
727 up: () => void moveBy($, -1),
728 close: () => void closePane($),
729 },
730 })
731 runtime.toggles = drill.toggles
732 return (
733 <Box flexDirection="column" width={view.columns}>
734 {drill.node}
735 {formNode !== undefined && (
736 <Box flexDirection="column" marginTop={1}>
737 {formNode}
738 </Box>
739 )}
740 </Box>
741 )
742 }
743
744 // Before anything has happened, one quiet line says what will show here.
745 const isEmpty =
746 list.length === 0 && team.length === 0 && request?.startedAt === undefined && others?.length === 0 && (await read($, sessionsError)) === null
747 if (isEmpty) {
748 runtime.toggles = [{ key: 'toggle-self', target: 'self' }]
749 const footer = formNode ?? keys?.node
750 return (
751 <Box flexDirection="column" width={view.columns} {...(rows === undefined ? {} : { height: rows })}>
752 {header.node}
753 <Box key="empty" flexDirection="column" marginTop={1}>
754 {wrap('glimt · the plan, agents and other sessions show here as they start', view.columns).map(text => (
755 <Text color={view.colors.quiet}>{text}</Text>
756 ))}
757 </Box>
758 <Box key="gap" flexGrow={1} />
759 {footer !== undefined && (
760 <Box flexDirection="column" marginTop={1}>
761 {footer}
762 </Box>
763 )}
764 </Box>
765 )
766 }
767
768 const shareOf = (part: number) => (rows === undefined ? Infinity : Math.max(3, Math.floor(rows * part)))
769 const current = nowSection(view, list)
770 const units = planUnits(list, open, view.columns)
771 // The footer: the form while one is open, else the keys while they show.
772 const footerRows = formNode !== undefined ? formRows : keys === undefined ? 0 : 1 + keys.rows
773 // Rows the plan does not need go to the agents, then the sessions, before
774 // either folds: the pane less this session's rows, the plan's heading and
775 // its lines unfolded, both shares, a blank row above each section, and
776 // the footer.
777 const spare =
778 rows === undefined
779 ? 0
780 : Math.max(
781 0,
782 rows -
783 header.rows -
784 current.rows -
785 1 -
786 Math.max(1, rowCount(units.flat())) -
787 shareOf(AGENT_SHARE) -
788 shareOf(SESSION_SHARE) -
789 4 -
790 footerRows,
791 )
792 const crew = agentSection(view, mainAgent(request), team, open, shareOf(AGENT_SHARE) + spare, {
793 asked: await read($, stopping),
794 answer: isYes => void answerStop($, isYes),
795 })
796 const listing = sessionSection(
797 view,
798 {
799 list: others,
800 error: await read($, sessionsError),
801 shared: sharedBy,
802 remote: remoteBy,
803 tasks,
804 open,
805 asked: await read($, stopping),
806 answer: isYes => void answerStop($, isYes),
807 phases: await read($, phases),
808 seen: await read($, seen),
809 folders,
810 },
811 shareOf(SESSION_SHARE) + spare - Math.max(0, crew.rows - shareOf(AGENT_SHARE)),
812 )
813 // Left for the plan: less this session's rows, its own heading, the blank
814 // row above each section, and the footer.
815 const planRoom = rows === undefined ? Infinity : Math.max(1, rows - header.rows - 1 - current.rows - crew.rows - listing.rows - 4 - footerRows)
816 const lines = planLines(units, planRoom)
817 runtime.toggles = [
818 { key: 'toggle-self', target: 'self' },
819 ...lines.flatMap(line => (line.kind === 'step' ? [{ key: `toggle-${line.step.id}`, target: line.step.id }] : [])),
820 ...crew.toggles,
821 ...listing.toggles,
822 ]
823
824 // Docked, the sessions and the footer keep to the bottom: agents coming
825 // and going change the gap above them, never where they stand.
826 const footer = formNode ?? keys?.node
827 return (
828 <Box flexDirection="column" width={view.columns} {...(rows === undefined ? {} : { height: rows })}>
829 {header.node}
830 <Box flexDirection="column" marginTop={1}>
831 {current.node}
832 </Box>
833 <Box flexDirection="column" marginTop={1}>
834 {planSection(view, approved, list, lines, await read($, hasTaskList))}
835 </Box>
836 <Box flexDirection="column" marginTop={1}>
837 {crew.node}
838 </Box>
839 <Box key="gap" flexGrow={1} />
840 <Box flexDirection="column" marginTop={1}>
841 {listing.node}
842 </Box>
843 {footer !== undefined && (
844 <Box flexDirection="column" marginTop={1}>
845 {footer}
846 </Box>
847 )}
848 </Box>
849 )
850 })
851}
852
853// Opened unasked, at session start, the pane waits for a wide terminal and
854// leaves the keyboard alone; opened by /glimt it takes the keyboard.
855// Opening it unasked (at start, after /clear) leaves a pane the person
856// closed closed; asked, it opens and stays open from then on.
857async function openPane($: EngineInterface, isAsked = false) {
858 if (!isAsked && runtime.isClosed) {
859 return
860 }
861
862 runtime.isClosed = false
863 const pane = { id: PANE, title: 'glimt' }
864 const shown = await $.ui.open(isAsked ? { ...pane, focus: true as const } : pane)
865 await update($, isShown, () => shown.isPlaced)
866}
867
868// q closes the pane with glimt's own close, which passes no
869// ui.close hook of glimt's; refused, the pane stays as it was, the key list
870// too.
871async function closePane($: EngineInterface) {
872 await $.ui.close({ id: PANE }).then(
873 () => forgetPane($),
874 () => undefined,
875 )
876}
877
878// The pane closed, by its close mark, ctrl+x x or q: it stays closed
879// until the person opens it again, the chat shows all of itself again, and
880// the pane forgets its cursor, the agent or session it was in, a form left
881// open, the key list, and a clear or a stop waiting for y or n. Opened again,
882// it starts on the overview, as Claude Code's focus ring starts afresh, and
883// a band left on a row from before would mark nothing.
884async function forgetPane($: EngineInterface) {
885 runtime.isClosed = true
886 runtime.isFocused = false
887 runtime.hasLostKeyboard = false
888 await update($, isShown, () => false)
889 await update($, cursor, () => null)
890 await update($, opened, () => [])
891 await update($, feed, () => null)
892 await update($, composer, () => null)
893 await update($, help, () => false)
894 await update($, clearing, () => false)
895 await update($, stopping, () => null)
896}
897
898// A resumed session already holds a task list: read it once, so the plan
899// shows before it next changes.
900async function seedSteps($: EngineInterface) {
901 const listed = await $.tool.call({ tool: 'TaskList' })
902 if (listed.deny !== undefined || listed.isError) {
903 return
904 }
905
906 const tasks = listed.result.tasks
907 await update($, steps, list => (list.length > 0 ? list : tasks.map(task => ({ id: task.id, subject: task.subject, status: task.status }))))
908}
909
910// Whose task list a call changes. The main loop's is the plan itself. A
911// subagent's joins it under the step its run belongs to, its ids led by the
912// agent's so they never meet the main list's; a subagent started while no
913// step was in progress keeps its tasks to itself (null).
914async function ownerOf($: EngineInterface, agentId: string | undefined): Promise<{ prefix: string; stepId?: string } | null> {
915 if (agentId === undefined) {
916 return { prefix: '' }
917 }
918
919 const agent = (await read($, agents)).find(a => a.agentId === agentId)
920
921 return agent?.stepId === undefined ? null : { prefix: `${agentId}/`, stepId: agent.stepId }
922}
923
924// Opens or closes a step (keyed by its task id) or an agent ("agent:" and its
925// id). A step seeded from TaskList has no description yet: the first
926// opening reads it with TaskGet.
927async function toggle($: EngineInterface, id: string) {
928 const open = await update($, expanded, ids => (ids.includes(id) ? ids.filter(other => other !== id) : [...ids, id]))
929 // Another session shows its agents as it opens; one of them, its task.
930 const [kind = '', sessionId = '', agentId = ''] = id.split(':')
931 if (open.includes(id) && kind === 'session') {
932 await markSeen($, sessionId)
933 await readRemote($, [sessionId]).catch(() => undefined)
934 }
935 if (open.includes(id) && kind === 'remote') {
936 await loadRemoteTask($, sessionId, agentId).catch(() => undefined)
937 }
938 const step = (await read($, steps)).find(one => one.id === id)
939 if (!open.includes(id) || step === undefined || step.description !== undefined) {
940 return
941 }
942
943 const got = await $.tool.call({ tool: 'TaskGet', taskId: id }).catch(() => undefined)
944 const task = got === undefined || got.deny !== undefined || got.isError ? null : got.result.task
945 const description = task?.description ?? ''
946 await update($, steps, list => list.map(one => (one.id === id ? { ...one, description } : one)))
947}
948
949// l: one step in, as Claude Code's agent view goes into a session: from the
950// overview into one of this session's agents, another session or one of its
951// agents; from a session, into one of its agents. The pane shows it alone,
952// its activity read at once.
953async function goInto($: EngineInterface) {
954 const key = await read($, cursor)
955 const target = runtime.toggles.find(one => one.key === key)?.target
956 if (target === undefined) {
957 return
958 }
959
960 const [kind = '', id = '', agentId = ''] = target.split(':')
961 const from = key ?? undefined
962 const step: Opened | null =
963 kind === 'agent'
964 ? { kind: 'agent', id: target.slice('agent:'.length), from }
965 : kind === 'session'
966 ? { kind: 'session', sessionId: id, from }
967 : kind === 'remote'
968 ? { kind: 'remote', sessionId: id, agentId, from }
969 : null
970 if (step === null) {
971 return
972 }
973
974 await update($, feed, () => null)
975 await update($, opened, trail => [...trail, step])
976 // When what the pane draws changes, Claude Code keeps its focus ring at
977 // the same place among the pane's elements, which can be the message field:
978 // the keys the key row shows would be typed there. The ring goes onto the
979 // way back instead, as h puts it back on the row it came from.
980 await ringOn($, 'back', false)
981 if (step.kind === 'session') {
982 await markSeen($, step.sessionId)
983 await readRemote($, [step.sessionId]).catch(() => undefined)
984 }
985 if (step.kind === 'remote') {
986 await loadRemoteTask($, step.sessionId, step.agentId).catch(() => undefined)
987 }
988 await readFeed($).catch(() => undefined)
989}
990
991// j and k: the cursor to the next or the previous row, over the rows alone;
992// it stays at the first and the last. From off the rows (the way back, a
993// key, a field) or with no row under it yet, j goes to the first row and k
994// to the last.
995async function moveBy($: EngineInterface, by: 1 | -1) {
996 const keys = runtime.toggles.map(one => one.key)
997 const at = runtime.isOffRows ? -1 : keys.indexOf((await read($, cursor)) ?? '')
998 const to = at < 0 ? (by > 0 ? keys[0] : keys.at(-1)) : keys[at + by]
999 if (to === undefined) {
1000 return
1001 }
1002
1003 // glimt's own move passes no ui.focus hook of glimt's: the cursor moves here.
1004 await update($, cursor, () => to)
1005 await ringOn($, to, true)
1006}
1007
1008// A form closed under Claude Code's focus ring: the ring goes back to the
1009// cursor's row, the way back inside an agent or a session, or this
1010// session's row. Left on the form's own button, which goes with it, the
1011// next key would reach nothing.
1012async function ringBack($: EngineInterface) {
1013 const to = landingOf({
1014 hasForm: false,
1015 hasKeyList: false,
1016 cursor: await read($, cursor),
1017 rows: runtime.toggles.map(one => one.key),
1018 isInside: (await read($, opened)).length > 0,
1019 })
1020 await ringOn($, to?.key ?? 'toggle-self', to?.isRow ?? true)
1021}
1022
1023// Puts Claude Code's focus ring on one of the pane's elements. glimt's own
1024// move passes no ui.focus hook of glimt's, so it notes here whether the ring
1025// is on a row, for j and k.
1026async function ringOn($: EngineInterface, key: string, isRow: boolean) {
1027 runtime.isOffRows = !isRow
1028 await $.ui.focus({ requestId: PANE, key }).catch(() => undefined)
1029}
1030
1031// h: one step back out, the cursor on the row it went in from.
1032async function goBack($: EngineInterface) {
1033 const last = (await read($, opened)).at(-1)
1034 if (last !== undefined) {
1035 await update($, opened, trail => trail.slice(0, -1))
1036 await update($, feed, () => null)
1037 await update($, cursor, () => last.from ?? null)
1038 if (last.from !== undefined) {
1039 await ringOn($, last.from, true)
1040 }
1041 await readFeed($).catch(() => undefined)
1042 }
1043}
1044
1045// The activity of the step the pane shows: one of this session's agents'
1046// messages as the session holds them, another session's or its agent's
1047// from the tail of its transcript. The timer reads only those on disk. A
1048// read that a move overtook is dropped.
1049async function readFeed($: EngineInterface, isTimer = false) {
1050 const top = (await read($, opened)).at(-1)
1051 if (top === undefined || (isTimer && top.kind === 'agent')) {
1052 return
1053 }
1054
1055 const reading =
1056 top.kind === 'agent' ? agentFeed($, top.id) : top.kind === 'session' ? sessionFeed($, top.sessionId) : remoteFeed($, top.sessionId, top.agentId)
1057 const got = await reading.catch((error: unknown): Feed => ({ items: [], error: error instanceof Error ? error.message : String(error) }))
1058 const still = (await read($, opened)).at(-1)
1059 if (still !== undefined && JSON.stringify(still) === JSON.stringify(top)) {
1060 await update($, feed, () => ({ ...got, items: got.items.slice(-FEED_KEPT) }))
1061 }
1062}
1063
1064// After an agent of this session acts: its activity again, when the pane
1065// shows it.
1066async function readAgentFeed($: EngineInterface, agentId: string) {
1067 const top = (await read($, opened)).at(-1)
1068 if (top?.kind !== 'agent') {
1069 return
1070 }
1071
1072 const agent = (await read($, agents)).find(a => a.id === top.id)
1073 if (agent?.agentId === agentId) {
1074 await readFeed($)
1075 }
1076}
1077
1078async function agentFeed($: EngineInterface, id: string): Promise<Feed> {
1079 const agent = (await read($, agents)).find(a => a.id === id)
1080 if (agent?.agentId === undefined) {
1081 return { items: [], error: 'This agent has no transcript to read.' }
1082 }
1083
1084 const found = await $.session.messages({ agentId: agent.agentId })
1085 if ('deny' in found) {
1086 return { items: [], error: found.deny }
1087 }
1088
1089 // Its first message is the task, drawn above the activity already.
1090 return {
1091 items: found.flatMap((message): Activity[] => [
1092 ...(isShownText(message.text) && !(message.role === 'user' && message.text.trim() === agent.task.trim())
1093 ? [{ kind: message.role === 'user' ? ('asked' as const) : ('said' as const), text: message.text.trim() }]
1094 : []),
1095 ...message.toolUses.map(use => ({ kind: 'call' as const, text: callLine(use.tool, use.input) })),
1096 ]),
1097 }
1098}
1099
1100async function sessionFeed($: EngineInterface, sessionId: string): Promise<Feed> {
1101 const s = (await read($, sessions))?.find(one => one.sessionId === sessionId)
1102 const path = s === undefined ? null : await transcriptOf($, s)
1103 if (s === undefined || path === null) {
1104 return { items: [], error: 'No transcript found for this session.' }
1105 }
1106
1107 return { ...(await tailFeed($, path, false)), branch: await branchOf($, s.cwd) }
1108}
1109
1110// The git branch a folder is on: undefined outside a repository and on a
1111// detached HEAD.
1112async function branchOf($: EngineInterface, cwd: string): Promise<string | undefined> {
1113 const at = await $.clock.now()
1114 const known = branches.get(cwd)
1115 if (known !== undefined && at - known.at < BRANCH_MS) {
1116 return known.branch
1117 }
1118
1119 const ran = await $.process.run(['git', '-C', cwd, 'rev-parse', '--abbrev-ref', 'HEAD'], { timeoutMs: 5000 }).catch(() => undefined)
1120 const name = ran?.exitCode === 0 ? ran.stdout.trim() : ''
1121 const branch = name === '' || name === 'HEAD' ? undefined : name
1122 branches.set(cwd, { branch, at })
1123 return branch
1124}
1125
1126// Another session's agent: the tail of its own transcript, less its task.
1127async function remoteFeed($: EngineInterface, sessionId: string, agentId: string): Promise<Feed> {
1128 const s = (await read($, sessions))?.find(one => one.sessionId === sessionId)
1129 const dir = s === undefined ? null : await subagentsDir($, s)
1130 if (dir === null) {
1131 return { items: [], error: 'No transcript found for this agent.' }
1132 }
1133
1134 const got = await tailFeed($, `${dir}/agent-${agentId}.jsonl`, true)
1135 const task = (await read($, remoteTasks))[`${sessionId}:${agentId}`]
1136 return { ...got, items: got.items.filter(item => !(item.kind === 'asked' && item.text === task)) }
1137}
1138
1139async function tailFeed($: EngineInterface, path: string, isSubagent: boolean): Promise<Feed> {
1140 const ran = await $.process.run(['tail', '-c', String(TAIL_BYTES), path], { timeoutMs: 5000 })
1141 if (ran.exitCode !== 0) {
1142 return { items: [], error: firstLine(ran.stderr) ?? 'Could not read the transcript.' }
1143 }
1144
1145 return { items: parseTranscript(ran.stdout, isSubagent), model: lastModel(ran.stdout, isSubagent) }
1146}
1147
1148// The subagents of the sessions opened in the list or drilled into: every
1149// POLL_MS while the pane is drawn, and at once when one opens.
1150async function readRemote($: EngineInterface, only?: string[]) {
1151 if (only === undefined && !(await read($, isShown))) {
1152 return
1153 }
1154
1155 const listed = (await read($, sessions)) ?? []
1156 const open = await read($, expanded)
1157 const trail = await read($, opened)
1158 const ids = only ?? [
1159 ...new Set([
1160 ...open.flatMap(key => (key.startsWith('session:') ? [key.slice('session:'.length)] : [])),
1161 ...trail.flatMap(step => (step.kind === 'agent' ? [] : [step.sessionId])),
1162 ]),
1163 ]
1164 for (const id of ids) {
1165 const s = listed.find(one => one.sessionId === id)
1166 if (s !== undefined) {
1167 const list = await remoteAgentsOf($, s)
1168 await update($, remote, all => ({ ...all, [id]: list }))
1169 }
1170 }
1171}
1172
1173// A session's subagents, from the folder beside its transcript: the newest
1174// written first, each with the type and description of its meta file.
1175async function remoteAgentsOf($: EngineInterface, s: Session): Promise<RemoteList> {
1176 const dir = await subagentsDir($, s)
1177 if (dir === null) {
1178 return { agents: [], total: 0 }
1179 }
1180
1181 const files = (await $.fs.list(dir).catch(() => [])).flatMap(entry => {
1182 const id = /^agent-(.+)\.jsonl$/.exec(entry.name)?.[1]
1183 return entry.kind === 'file' && id !== undefined ? [{ id, writtenAt: entry.mtimeMs }] : []
1184 })
1185 const found: RemoteAgent[] = []
1186 for (const file of files.toSorted((a, b) => b.writtenAt - a.writtenAt).slice(0, REMOTE_KEPT)) {
1187 found.push({ ...file, ...(await metaOf($, `${dir}/agent-${file.id}.meta.json`)) })
1188 }
1189
1190 return { agents: found, total: files.length }
1191}
1192
1193async function subagentsDir($: EngineInterface, s: Session): Promise<string | null> {
1194 const path = await transcriptOf($, s)
1195
1196 return path === null ? null : `${path.slice(0, -'.jsonl'.length)}/subagents`
1197}
1198
1199async function metaOf($: EngineInterface, path: string): Promise<{ type: string; description: string }> {
1200 const known = metas.get(path)hooks/agents.tsx 415 lines1// This session's agents: the main conversation and its subagents as a tree.
2
3import type { AgentInfo, ModelUsage } from 'claude-code'
4import type { Agent, AgentState, Focus, RunningCall } from '../types'
5import { cells, clip, duration, fit, fitStart, minutes, spin, tokenNumber, toolName, wrap } from './text'
6import { cursorStyle, heading } from './view'
7import type { View } from './view'
8
9// Finished agents stay on show below the running ones until a new request,
10// the newest this many, as room allows.
11export const FINISHED_SHOWN = 6
12
13// Below this many columns an agent's time and tools take a line of their own.
14export const NARROW = 50
15
16// A row's title keeps at least this many cells: a count in words that would
17// leave less is shortened.
18export const MIN_TITLE = 12
19
20export type Spawned = {
21 agentId?: string | undefined
22 fallbackId: string
23 parentId?: string | undefined
24 type: string
25 description: string
26 task: string
27 model?: string | undefined
28 isBackground?: boolean | undefined
29}
30
31export function isTurnRunning(request: Focus | null): boolean {
32 return request?.startedAt !== undefined && request.endedAt === undefined
33}
34
35// The main conversation drawn as the first agent, once a turn has started.
36export function mainAgent(request: Focus | null): Agent | undefined {
37 if (request?.startedAt === undefined) {
38 return undefined
39 }
40
41 return {
42 id: 'main',
43 type: 'Claude',
44 description: 'main conversation',
45 task: '',
46 state: isTurnRunning(request) ? 'running' : (request.outcome ?? 'done'),
47 startedAt: request.startedAt,
48 endedAt: request.endedAt,
49 tools: request.tools ?? 0,
50 tool: request.tool,
51 doing: request.doing,
52 tokens: request.tokens,
53 percent: request.percent,
54 }
55}
56
57export function contextTokens(usage: ModelUsage): number {
58 return usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens + usage.output_tokens
59}
60
61// What runs spins; a finished agent keeps a still mark: ✓ done, and a failed
62// or stopped one a shape of its own, so each reads without its color.
63export function runningMark(at: number) {
64 return { mark: spin(at), color: 'claude' }
65}
66
67// x stops an agent that runs in the background, as a plugin's own always
68// does; Claude Code stops no other kind from a plugin.
69export function isStoppable(agent: Agent): boolean {
70 return agent.state === 'running' && agent.isBackground === true && agent.agentId !== undefined
71}
72
73// A call put to the agent's person shows as waiting once it has waited this
74// long, so a call the mode decides at once never flashes.
75export const ASK_SHOWN_MS = 1000
76
77// A loop's calls after one starts or ends: the latest names its tool and
78// what it is on.
79// The agents glimt holds as running, set right by Claude Code's own list of
80// the session's agents: one it lists as ended, or no longer lists (it drops
81// a subagent's task a while after the end), ended. glimt learns an end from
82// the agent's turn.complete, which a reload of the mod in between loses; an
83// agent with no id of its own, or still running, waiting or idle, is kept.
84// Nothing ended, the same list.
85export function settled(list: Agent[], listed: AgentInfo[], at: number): Agent[] {
86 const ends: Partial<Record<AgentInfo['status'], AgentState>> = { completed: 'done', failed: 'failed', killed: 'stopped' }
87 const statuses = new Map(listed.map(info => [info.id, info.status]))
88 const after = list.map(a => {
89 if (a.state !== 'running' || a.agentId === undefined) {
90 return a
91 }
92 const status = statuses.get(a.agentId)
93 const state = status === undefined ? 'done' : ends[status]
94 return state === undefined ? a : withCalls({ ...a, state, endedAt: at }, [])
95 })
96
97 return after.every((a, i) => a === list[i]) ? list : after
98}
99
100export function withCalls<T extends { calls?: RunningCall[] | undefined; tool?: string | undefined; doing?: string | undefined }>(
101 item: T,
102 calls: RunningCall[],
103): T {
104 const latest = calls.at(-1)
105 return { ...item, calls, tool: latest?.tool, doing: latest?.on }
106}
107
108// The call Claude Code is about to ask the person about: of that tool, the
109// one on the same thing, else the latest not asked yet (a hook may have
110// rewritten what it is on), now waiting since `at`.
111export function askCall(calls: RunningCall[], tool: string, on: string | undefined, at: number): RunningCall[] {
112 const open = calls.filter(call => call.tool === tool && call.askedAt === undefined)
113 const asked = open.find(call => call.on === on) ?? open.at(-1)
114 return asked === undefined ? calls : calls.map(call => (call === asked ? { ...call, askedAt: at } : call))
115}
116
117// The call a running agent has waited on its person for the longest, once
118// that has lasted ASK_SHOWN_MS by `at`.
119export function askingOf(at: number, agent: Agent): RunningCall | undefined {
120 if (agent.state !== 'running') {
121 return undefined
122 }
123
124 return (agent.calls ?? []).find(call => call.askedAt !== undefined && at - call.askedAt >= ASK_SHOWN_MS)
125}
126
127// An agent's mark: ◉ while it waits on its person, the spinner while it
128// runs, a still mark once it has finished.
129export function agentMark(view: View, agent: Agent): { mark: string; color: string } {
130 if (agent.state !== 'running') {
131 return AGENT_MARK[agent.state]
132 }
133
134 return askingOf(view.at, agent) === undefined ? runningMark(view.at) : { mark: '◉', color: 'warning' }
135}
136
137// After ⎿: the call that waits on its person, "approve Bash · npm test", or
138// else the latest running call and what it is on.
139export function callOf(agent: Agent, asking: RunningCall | undefined, room: number): string | undefined {
140 if (agent.state !== 'running') {
141 return undefined
142 }
143
144 const call = asking ?? (agent.tool === undefined ? undefined : { tool: agent.tool, on: agent.doing })
145 if (call === undefined) {
146 return undefined
147 }
148
149 const tool = `${asking === undefined ? '' : 'approve '}${toolName(call.tool)}`
150 const space = room - cells(tool) - 5
151 const on = call.on === undefined ? '' : /^[/~]/.test(call.on) ? fitStart(call.on, space) : fit(call.on, space)
152 return on === '' ? `⎿ ${tool}` : `⎿ ${tool} · ${on}`
153}
154
155export const AGENT_MARK: Record<Exclude<AgentState, 'running'>, { mark: string; color: string }> = {
156 done: { mark: '✓', color: 'success' },
157 failed: { mark: '✗', color: 'error' },
158 stopped: { mark: '■', color: 'warning' },
159}
160
161// The most lines an opened agent's task takes.
162export const TASK_LINES = 12
163
164// One agent as the tree draws it: `branch` leads its row, `stem` leads the
165// rows of its children, and the lines under it continue the stem.
166export type AgentNode = { agent: Agent; branch: string; stem: string; isMain: boolean; hasChildren: boolean }
167
168// The running agents, the newest finished, and every agent above one of
169// those, so no row hangs without the agent that spawned it.
170export function shownAgents(team: Agent[]): Agent[] {
171 const byAgentId = new Map<string, Agent>()
172 for (const agent of team) {
173 if (agent.agentId !== undefined) {
174 byAgentId.set(agent.agentId, agent)
175 }
176 }
177
178 const wanted = [...team.filter(a => a.state === 'running'), ...team.filter(a => a.state !== 'running').slice(-FINISHED_SHOWN)]
179 const keep = new Set<string>()
180 for (const agent of wanted) {
181 let at: Agent | undefined = agent
182 while (at !== undefined && !keep.has(at.id)) {
183 keep.add(at.id)
184 at = at.parentId === undefined ? undefined : byAgentId.get(at.parentId)
185 }
186 }
187
188 return team.filter(a => keep.has(a.id))
189}
190
191// The tree in spawn order: the main conversation at the root, each agent
192// under the one that spawned it; one whose parent is not on show hangs from
193// the root.
194export function agentTree(main: Agent | undefined, shown: Agent[]): AgentNode[] {
195 const ids = new Set(shown.flatMap(a => (a.agentId === undefined ? [] : [a.agentId])))
196 const parentOf = (a: Agent) => (a.parentId !== undefined && ids.has(a.parentId) ? a.parentId : undefined)
197 const childrenOf = (parent: string | undefined) => shown.filter(a => parentOf(a) === parent)
198 const nodes: AgentNode[] = []
199
200 const grow = (parent: string | undefined, stem: string, isBranched: boolean) => {
201 const children = childrenOf(parent)
202 children.forEach((agent, i) => {
203 const isLast = i === children.length - 1
204 const branch = isBranched ? `${stem}${isLast ? '└─ ' : '├─ '}` : stem
205 const below = isBranched ? `${stem}${isLast ? ' ' : '│ '}` : stem
206 const hasChildren = agent.agentId !== undefined && childrenOf(agent.agentId).length > 0
207 nodes.push({ agent, branch, stem: below, isMain: false, hasChildren })
208 if (agent.agentId !== undefined) {
209 grow(agent.agentId, below, true)
210 }
211 })
212 }
213
214 if (main !== undefined) {
215 nodes.push({ agent: main, branch: '', stem: '', isMain: true, hasChildren: childrenOf(undefined).length > 0 })
216 }
217 grow(undefined, '', main !== undefined)
218
219 return nodes
220}
221
222// The lines an agent's row carries under it, each led by the stem: its time
223// and tools on a narrow pane, what its running call is on (after ⎿, as
224// Claude Code nests a call's lines), its opened task.
225export function agentLines(view: View, node: AgentNode, open: readonly string[], isTight = false) {
226 const { agent } = node
227 const under = underOf(node)
228 const width = view.columns - cells(under)
229 const lines: string[] = []
230
231 if (view.columns < NARROW) {
232 lines.push(fit(tallyOf(view, node), width))
233 }
234 // Short of room, the ⎿ lines go, so more running agents fit; one that
235 // waits on its person keeps its line.
236 const asking = askingOf(view.at, agent)
237 const call = callOf(agent, asking, width)
238 if (call !== undefined && (!isTight || asking !== undefined)) {
239 lines.push(call)
240 }
241 const isOpen = !node.isMain && open.includes(`agent:${agent.id}`)
242 const task = isOpen
243 ? clip(
244 agent.task.split('\n').flatMap(paragraph => wrap(paragraph, width)),
245 TASK_LINES,
246 )
247 : []
248
249 return { under, status: lines, task: isOpen && task.length === 0 ? ['No task text.'] : task }
250}
251
252// What leads the lines under an agent's row: its stem, carrying on down to
253// its children when it has any.
254export function underOf(node: AgentNode): string {
255 return `${node.stem}${node.hasChildren ? '│ ' : ' '}`
256}
257
258// What comes before an agent's title: its branch, its toggle, its mark.
259export function leadOf(node: AgentNode): number {
260 return cells(node.branch) + (node.isMain ? 0 : 2) + 2
261}
262
263// Its time, its tool calls and its context: "45k tokens", and for the main
264// conversation "74% context", while there is room for the words beside a
265// title of MIN_TITLE cells (or on a line of its own on a narrow pane);
266// "45k tok" and "74%" when there isn't.
267export function tallyOf(view: View, node: AgentNode): string {
268 const words = agentTally(view, node.agent, true)
269 const room = view.columns < NARROW ? view.columns - cells(underOf(node)) : view.columns - leadOf(node) - MIN_TITLE - 1
270
271 return cells(words) <= room ? words : agentTally(view, node.agent, false)
272}
273
274export function agentTally(view: View, agent: Agent, isInWords: boolean): string {
275 const time = agent.endedAt === undefined ? minutes(view.at - agent.startedAt) : duration(agent.endedAt - agent.startedAt)
276 const parts = [time, `${agent.tools} ${agent.tools === 1 ? 'tool' : 'tools'}`]
277 if (agent.tokens !== undefined) {
278 parts.push(`${tokenNumber(agent.tokens)} ${isInWords ? 'tokens' : 'tok'}`)
279 }
280 if (agent.percent !== undefined) {
281 parts.push(isInWords ? `${Math.round(agent.percent)}% context` : `${Math.round(agent.percent)}%`)
282 }
283
284 return parts.join(' · ')
285}
286
287export function nodeRows(view: View, node: AgentNode, open: readonly string[], isTight: boolean): number {
288 const { status, task } = agentLines(view, node, open, isTight)
289
290 return 1 + status.length + task.length
291}
292
293// The agents in `room` rows. Past the room, finished agents with nothing
294// under them go first, oldest first; then the rest are counted on one line.
295// After x on an agent, the question whether to stop it, under its row.
296export type AgentStop = { asked: string | null; answer: (isYes: boolean) => void }
297
298export function agentSection(view: View, main: Agent | undefined, team: Agent[], open: readonly string[], room: number, stop: AgentStop) {
299 const { Box, Button, Text } = view.ui
300 const { quiet } = view.colors
301 const isNarrow = view.columns < NARROW
302 let shown = shownAgents(team)
303 let nodes = agentTree(main, shown)
304 let isTight = false
305 const isAsked = (a: Agent) => stop.asked === `agent:${a.id}`
306 const rowsOf = (all: AgentNode[]) => all.reduce((sum, node) => sum + nodeRows(view, node, open, isTight) + (isAsked(node.agent) ? 1 : 0), 0)
307 // The rows for `count` agents of the `total` on show: the heading takes
308 // one, and once an agent is left out, so does "+N more".
309 const total = nodes.length
310 const limit = (count: number) => room - 1 - (count < total ? 1 : 0)
311
312 // Short of room: finished agents with nothing under them go first, oldest
313 // first; then the ⎿ lines; only then running agents.
314 while (rowsOf(nodes) > limit(nodes.length)) {
315 const leaves = nodes.filter(node => !node.isMain && node.agent.state !== 'running' && !node.hasChildren)
316 const oldest = leaves.toSorted((a, b) => (a.agent.endedAt ?? 0) - (b.agent.endedAt ?? 0))[0]
317 if (oldest === undefined) {
318 break
319 }
320 shown = shown.filter(a => a.id !== oldest.agent.id)
321 nodes = agentTree(main, shown)
322 }
323 isTight = rowsOf(nodes) > limit(nodes.length)
324
325 let kept = nodes
326 if (rowsOf(kept) > limit(kept.length)) {
327 kept = []
328 for (const node of nodes) {
329 if (rowsOf([...kept, node]) > limit(kept.length + 1)) {
330 break
331 }
332 kept.push(node)
333 }
334 }
335 const hidden = total - kept.length
336 const running = (main?.state === 'running' ? 1 : 0) + team.filter(a => a.state === 'running').length
337 const waiting = team.filter(a => askingOf(view.at, a) !== undefined).length
338 const count = [running > 0 ? `${running} running` : '', waiting > 0 ? `${waiting} waiting` : ''].filter(part => part !== '').join(' · ')
339
340 return {
341 rows: 1 + Math.max(1, rowsOf(kept) + (hidden > 0 ? 1 : 0)),
342 toggles: kept.flatMap(node => (node.isMain ? [] : [{ key: `toggle-agent-${node.agent.id}`, target: `agent:${node.agent.id}` }])),
343 node: (
344 <Box flexDirection="column">
345 {heading(view, 'agents-heading', 'Agents', count)}
346 {kept.length === 0 && hidden === 0 && (
347 <Box key="no-agents">
348 <Text color={quiet}>No agents running.</Text>
349 </Box>
350 )}
351 {kept.map(node => {
352 const { agent: a, branch, isMain } = node
353 const { under, status, task } = agentLines(view, node, open, isTight)
354 const isRunning = a.state === 'running'
355 const { mark, color } = agentMark(view, a)
356 const tally = tallyOf(view, node)
357 const title = fit(`${a.type} ${a.description}`, view.columns - leadOf(node) - (isNarrow ? 0 : cells(tally) + 1))
358 const type = title.startsWith(a.type) ? a.type : title
359 const cursor = cursorStyle(view, `toggle-agent-${a.id}`)
360
361 return (
362 <Box key={`agent-${a.id}`} flexDirection="column">
363 <Box flexDirection="row" {...cursor.row}>
364 {branch !== '' && <Text color={quiet}>{branch}</Text>}
365 {!isMain && (
366 <Button key={`toggle-agent-${a.id}`} plain label={task.length > 0 ? '▾' : '▸'} onPress={() => view.toggle(`agent:${a.id}`)} />
367 )}
368 {!isMain && <Text> </Text>}
369 <Box flexGrow={1}>
370 <Text {...(isRunning ? {} : { color: quiet })}>
371 <Text color={color}>{mark}</Text>{' '}
372 <Text {...cursor.name}>
373 <Text bold>{type}</Text>
374 {title.slice(type.length)}
375 </Text>
376 </Text>
377 </Box>
378 {!isNarrow && <Text color={quiet}> {tally}</Text>}
379 </Box>
380 {isAsked(a) && (
381 <Box key={`stop-agent-${a.id}`} flexDirection="row" columnGap={2} paddingLeft={4}>
382 <Text color="warning">{fit(`Stop ${a.type} ${a.description}?`, view.columns - 20)}</Text>
383 <Button key="stop-yes" plain hotkey="y" label="yes" onPress={() => stop.answer(true)} />
384 <Button key="stop-no" plain hotkey="n" label="no" onPress={() => stop.answer(false)} />
385 </Box>
386 )}
387 {status.map(line => (
388 <Text color={quiet}>
389 {under}
390 {line}
391 </Text>
392 ))}
393 {task.length > 0 && (
394 <Box key={`task-${a.id}`} flexDirection="column">
395 {task.map(line => (
396 <Text color={quiet}>
397 {under}
398 {line}
399 </Text>
400 ))}
401 </Box>
402 )}
403 </Box>
404 )
405 })}
406 {hidden > 0 && (
407 <Box key="more-agents">
408 <Text color={quiet}>+{hidden} more</Text>
409 </Box>
410 )}
411 </Box>
412 ),
413 }
414}
415hooks/drill.tsx 417 lines1// Going into an agent or a session with l: what it is doing, read from its
2// transcript, drawn alone in the pane with a field to write to it.
3
4import type { Activity, Agent, Feed, Opened, Phase, RemoteAgent, RemoteList, Session, SharedAgent } from '../types'
5import { agentMark, agentTally, askingOf, callOf, isStoppable } from './agents'
6import { isReachable, modeWords, placeOf, remoteMark, remoteSection, remoteTally, sessionMark, stateText } from './sessions'
7import { clip, describeCall, fit, fitStart, isRecord, modelName, toolName, wrap } from './text'
8import { heading, keyButton, keyWidth, wrappedRows } from './view'
9import type { View } from './view'
10
11export const TAIL_BYTES = 131_072
12export const FEED_KEPT = 200
13
14// The most lines a drilled-into agent's task takes above its activity.
15export const TASK_SHOWN = 4
16
17// The items in a transcript's lines: the person's prompts (or a subagent's
18// task), Claude's text and its calls. A line cut by the tail, a line Claude
19// Code added itself, text it wrapped in a tag (a command, a reminder, a
20// notification) and, in a session's own transcript, a subagent's line are
21// left out.
22export function parseTranscript(text: string, isSubagent = false): Activity[] {
23 return text.split('\n').flatMap(line => {
24 let entry: unknown
25 try {
26 entry = JSON.parse(line)
27 } catch {
28 return []
29 }
30 if (!isRecord(entry)) {
31 return []
32 }
33
34 const { type, message, isSidechain, isMeta } = entry
35 if ((isSidechain === true && !isSubagent) || isMeta === true || (type !== 'user' && type !== 'assistant')) {
36 return []
37 }
38 const content = isRecord(message) ? message.content : undefined
39 const blocks: unknown[] = typeof content === 'string' ? [{ type: 'text', text: content }] : Array.isArray(content) ? content : []
40
41 return blocks.flatMap((block): Activity[] => {
42 const fields = isRecord(block) ? block : {}
43 if (fields.type === 'text' && typeof fields.text === 'string' && isShownText(fields.text)) {
44 return [{ kind: type === 'user' ? 'asked' : 'said', text: fields.text.trim() }]
45 }
46 if (type === 'assistant' && fields.type === 'tool_use' && typeof fields.name === 'string') {
47 return [{ kind: 'call', text: callLine(fields.name, fields.input) }]
48 }
49 return []
50 })
51 })
52}
53
54// The model the latest reply in a transcript's lines came from; in a
55// session's own transcript, a subagent's replies are left out.
56export function lastModel(text: string, isSubagent = false): string | undefined {
57 let model: string | undefined
58 for (const line of text.split('\n')) {
59 let entry: unknown
60 try {
61 entry = JSON.parse(line)
62 } catch {
63 continue
64 }
65 const message = isRecord(entry) ? entry.message : undefined
66 if (
67 isRecord(entry) &&
68 entry.type === 'assistant' &&
69 (isSubagent || entry.isSidechain !== true) &&
70 isRecord(message) &&
71 typeof message.model === 'string'
72 ) {
73 model = message.model
74 }
75 }
76
77 return model
78}
79
80// What a transcript's lines say of its session's name: whether it was
81// renamed (a custom title), and the latest title Claude Code generated.
82export function titleOf(text: string): { isRenamed: boolean; generated?: string | undefined } {
83 let isRenamed = false
84 let generated: string | undefined
85 for (const line of text.split('\n')) {
86 if (!line.includes('title')) {
87 continue
88 }
89 let entry: unknown
90 try {
91 entry = JSON.parse(line)
92 } catch {
93 continue
94 }
95 if (isRecord(entry) && entry.type === 'custom-title') {
96 isRenamed = true
97 }
98 if (isRecord(entry) && entry.type === 'ai-title' && typeof entry.aiTitle === 'string' && entry.aiTitle.trim() !== '') {
99 generated = entry.aiTitle.trim()
100 }
101 }
102
103 return { isRenamed, generated }
104}
105
106export function isShownText(text: string): boolean {
107 const trimmed = text.trim()
108
109 return trimmed !== '' && !trimmed.startsWith('<')
110}
111
112// "Read · /a/b.ts": the tool, and what the call is on when it says.
113export function callLine(tool: string, input: unknown): string {
114 const on = describeCall(input)
115
116 return on === undefined ? toolName(tool) : `${toolName(tool)} · ${on}`
117}
118
119export type Drill = {
120 into: Opened
121 // Where h goes: the overview, or the session the pane went into first.
122 backTo: string
123 // What the pane is in, each undefined once it is gone: one of this
124 // session's agents, another session (also the one of an agent of it), or
125 // another session's agent.
126 agent: Agent | undefined
127 session: Session | undefined
128 // The session's state as glimt watched it, and its permission mode as its
129 // glimt shares it.
130 phase: Phase | undefined
131 mode: string | undefined
132 remoteAgent: RemoteAgent | undefined
133 // The session's agents as read, what its glimt shares, and whether it
134 // runs one at all (to take a new name).
135 remote: RemoteList | undefined
136 shared: SharedAgent[]
137 isSharing: boolean
138 tasks: Record<string, string>
139 open: readonly string[]
140 feed: Feed | null
141 asked: string | null
142 isFocused: boolean
143 // The rows docked; undefined inline, where nothing is cut.
144 room: number | undefined
145 act: {
146 back: () => void
147 into: () => void
148 message: () => void
149 send: (to: { sessionId: string } | { agentId: string }, name: string, text: string) => void
150 rename: () => void
151 attach: () => void
152 stop: () => void
153 answer: (isYes: boolean) => void
154 help: () => void
155 down: () => void
156 up: () => void
157 close: () => void
158 }
159}
160
161// The most activity items drawn inline, where the pane has no height to fill.
162export const FEED_INLINE = 20
163
164// What l went into, alone in the pane as Claude Code's agent view shows a
165// session: the way back, the agent or the session with what it does now, a
166// session's agents (j, k, Enter and l work on them), an agent's task, its latest
167// activity (newest last, as much as the rows left hold), a field for a
168// message to it, and the keys while the pane holds the keyboard.
169export function drillSection(view: View, drill: Drill) {
170 const { Box, Button, Text } = view.ui
171 const { Input } = view
172 const { quiet } = view.colors
173 const { into, agent, session, remoteAgent, shared, feed: got, asked, act } = drill
174 const width = view.columns
175 const isGone = into.kind === 'agent' ? agent === undefined : into.kind === 'session' ? session === undefined : remoteAgent === undefined
176
177 // The title, and the quiet lines under it: what it does now, and where.
178 let title: { mark: string; color: string; name: string } | undefined
179 let facts: string[] = []
180 let taskText: string | undefined
181 // The model a reply came from, after the time: "4m · 3 tools · Haiku 5.5".
182 const withModel = (line: string, model: string | undefined) => (model === undefined ? line : `${line} · ${modelName(model)}`)
183 if (into.kind === 'agent' && agent !== undefined) {
184 title = { ...agentMark(view, agent), name: `${agent.type} ${agent.description}` }
185 facts = [withModel(agentTally(view, agent, true), agent.model)]
186 const call = callOf(agent, askingOf(view.at, agent), width - 2)
187 if (call !== undefined) {
188 facts.push(call)
189 }
190 taskText = agent.task
191 } else if (into.kind === 'session' && session !== undefined) {
192 const { mark, color, word } = sessionMark(view, session)
193 title = { mark, color, name: session.name }
194 const mode = drill.mode === undefined ? '' : ` · ${modeWords(drill.mode)}`
195 facts = [`${withModel(stateText(word, drill.phase, view.at), got?.model)}${mode}`, fitStart(`⎿ ${placeOf(session, got?.branch)}`, width - 2)]
196 } else if (into.kind === 'remote' && remoteAgent !== undefined) {
197 const share = shared.find(one => one.id === remoteAgent.id)
198 title = { ...remoteMark(view, remoteAgent, share), name: `${remoteAgent.type} ${remoteAgent.description}` }
199 facts = [withModel(remoteTally(view, remoteAgent, share), got?.model), fit(`⎿ in ${session?.name ?? 'another session'}`, width - 2)]
200 taskText = drill.tasks[`${into.sessionId}:${remoteAgent.id}`] ?? share?.task
201 }
202 const task =
203 into.kind === 'session' || isGone
204 ? []
205 : taskText === undefined
206 ? ['Loading…']
207 : clip(
208 taskText.split('\n').flatMap(paragraph => wrap(paragraph, width - 2)),
209 TASK_SHOWN,
210 )
211 const crew =
212 into.kind === 'session' && session !== undefined
213 ? remoteSection(view, session, { list: drill.remote, shared, tasks: drill.tasks, open: drill.open })
214 : undefined
215 // After x, what y would stop: the session, or the agent, the pane is in.
216 const stopping =
217 into.kind === 'session' && session !== undefined && asked === session.sessionId
218 ? { key: `stop-${session.sessionId}`, name: session.name }
219 : into.kind === 'agent' && agent !== undefined && asked === `agent:${agent.id}`
220 ? { key: `stop-agent-${agent.id}`, name: `${agent.type} ${agent.description}` }
221 : undefined
222 const isAsking = stopping !== undefined
223
224 const canMessage =
225 Input !== undefined &&
226 !isGone &&
227 (into.kind === 'session' || (into.kind === 'agent' && agent?.state === 'running' && agent.agentId !== undefined))
228 const canInto = crew?.toggles.some(toggle => toggle.key === view.cursor) === true
229 const canReach = into.kind === 'session' && session !== undefined && isReachable(session)
230 const canStopAgent = into.kind === 'agent' && agent !== undefined && isStoppable(agent)
231 const canRename = into.kind === 'session' && session !== undefined && drill.isSharing
232 // The keys, as the overview binds them: l on one of a session's agents,
233 // then what the pane is in allows, j and k while there are agents to move
234 // over, and q; h sits on the way back above. Each with the cells it
235 // takes, to count the rows the row wraps to.
236 const keyItems = drill.isFocused
237 ? [
238 ...(canInto ? [{ width: keyWidth('into'), node: keyButton(view, 'into', 'l', 'into', act.into) }] : []),
239 ...(canMessage ? [{ width: keyWidth('message'), node: keyButton(view, 'message', 'm', 'message', act.message) }] : []),
240 ...(canRename ? [{ width: keyWidth('rename'), node: keyButton(view, 'rename', 'r', 'rename', act.rename) }] : []),
241 ...(canReach
242 ? [
243 { width: keyWidth('attach'), node: keyButton(view, 'attach', 'a', 'attach', act.attach) },
244 { width: keyWidth('stop'), node: keyButton(view, 'stop', 'x', 'stop', act.stop) },
245 ]
246 : []),
247 ...(canStopAgent ? [{ width: keyWidth('stop'), node: keyButton(view, 'stop', 'x', 'stop', act.stop) }] : []),
248 { width: keyWidth('keys'), node: keyButton(view, 'help', 'i', 'keys', act.help) },
249 ...((crew?.toggles.length ?? 0) > 0
250 ? [
251 { width: keyWidth('down'), node: keyButton(view, 'down', 'j', 'down', act.down) },
252 { width: keyWidth('up'), node: keyButton(view, 'up', 'k', 'up', act.up) },
253 ]
254 : []),
255 { width: keyWidth('close'), node: keyButton(view, 'close', 'q', 'close', act.close) },
256 ]
257 : undefined
258 const keyRows =
259 keyItems === undefined
260 ? 0
261 : 1 +
262 wrappedRows(
263 keyItems.map(item => item.width),
264 width,
265 3,
266 )
267
268 // The activity takes the rows the rest leaves: the way back and a blank,
269 // the title and its lines, a session's agents or an agent's task under a
270 // heading, the activity's heading, the field and the keys, each with a
271 // blank above.
272 const fixed =
273 2 +
274 (isGone ? 1 : 1 + facts.length + (isAsking ? 1 : 0)) +
275 (crew === undefined ? 0 : 2 + crew.rows) +
276 (task.length === 0 ? 0 : 2 + task.length) +
277 2 +
278 (canMessage ? 2 : 0) +
279 keyRows
280 const room = drill.room === undefined ? Infinity : Math.max(3, drill.room - fixed)
281 const items = got === null ? [] : drill.room === undefined ? got.items.slice(-FEED_INLINE) : got.items
282 const shown = lastItems(items, width, room)
283
284 return {
285 toggles: crew?.toggles ?? [],
286 node: (
287 <Box key="drill" flexDirection="column">
288 <Button
289 key="back"
290 plain
291 dimColor
292 {...(drill.isFocused ? { hotkey: 'h' } : {})}
293 label={fit(`← ${drill.backTo}`, drill.isFocused ? width - 3 : width)}
294 onPress={act.back}
295 />
296 <Box key="drill-title" flexDirection="column" marginTop={1}>
297 {title === undefined ? (
298 <Text color={quiet}>{into.kind === 'session' ? 'This session is no longer listed.' : 'This agent is no longer listed.'}</Text>
299 ) : (
300 <Text>
301 <Text color={title.color}>{title.mark}</Text> <Text bold>{fit(title.name, width - 2)}</Text>
302 </Text>
303 )}
304 {facts.map(line => (
305 <Text color={quiet}>
306 {' '}
307 {line}
308 </Text>
309 ))}
310 {stopping !== undefined && (
311 <Box key={stopping.key} flexDirection="row" columnGap={2} paddingLeft={2}>
312 <Text color="warning">{fit(`Stop ${stopping.name}?`, width - 20)}</Text>
313 <Button key="stop-yes" plain hotkey="y" label="yes" onPress={() => act.answer(true)} />
314 <Button key="stop-no" plain hotkey="n" label="no" onPress={() => act.answer(false)} />
315 </Box>
316 )}
317 </Box>
318 {crew !== undefined && (
319 <Box key="drill-agents" flexDirection="column" marginTop={1}>
320 {heading(
321 view,
322 'drill-agents-heading',
323 'Agents',
324 drill.remote === undefined || drill.remote.total === 0 ? '' : String(drill.remote.total),
325 )}
326 {crew.node}
327 </Box>
328 )}
329 {task.length > 0 && (
330 <Box key="drill-task" flexDirection="column" marginTop={1}>
331 {heading(view, 'task-heading', 'Task', '')}
332 {task.map(line => (
333 <Text color={quiet}>
334 {' '}
335 {line}
336 </Text>
337 ))}
338 </Box>
339 )}
340 <Box flexDirection="column" marginTop={1}>
341 {heading(view, 'activity-heading', 'Activity', '')}
342 <Box key="activity" flexDirection="column">
343 {got === null ? (
344 <Text color={quiet}>Reading…</Text>
345 ) : got.error !== undefined ? (
346 <Text color="error">{fit(got.error, width)}</Text>
347 ) : shown.length === 0 ? (
348 <Text color={quiet}>Nothing yet.</Text>
349 ) : (
350 shown.flatMap(({ item, lines }) =>
351 lines.map(line => (
352 <Text bold={item.kind === 'asked'} {...(item.kind === 'call' ? { color: quiet } : {})}>
353 {line}
354 </Text>
355 )),
356 )
357 )}
358 </Box>
359 </Box>
360 {canMessage && Input !== undefined && (
361 <Box marginTop={1}>
362 <Input
363 key="message-field"
364 label="Message"
365 placeholder="Type and press Enter"
366 value=""
367 submitLabel="send"
368 onSubmit={text =>
369 agent?.agentId !== undefined
370 ? act.send({ agentId: agent.agentId }, `${agent.type} ${agent.description}`, text)
371 : session !== undefined && act.send({ sessionId: session.sessionId }, session.name, text)
372 }
373 />
374 </Box>
375 )}
376 {keyItems !== undefined && (
377 <Box key="keys" flexDirection="row" flexWrap="wrap" columnGap={3} marginTop={1}>
378 {keyItems.map(item => item.node)}
379 </Box>
380 )}
381 </Box>
382 ),
383 }
384}
385
386// An activity item's lines: a call on one, quiet, under ⎿ as Claude Code nests
387// a call; what was asked (›) on up to two and what Claude said (●) on up to
388// three, wrapped.
389export function itemLines(item: Activity, width: number): string[] {
390 if (item.kind === 'call') {
391 return [fit(` ⎿ ${item.text}`, width)]
392 }
393
394 const lead = item.kind === 'asked' ? '› ' : '● '
395 return wrap(item.text, width - 2, item.kind === 'asked' ? 2 : 3).map((line, i) => `${i === 0 ? lead : ' '}${line}`)
396}
397
398// The newest items that fit in `room` rows, oldest first; the newest alone
399// cut to the room when even it does not fit.
400export function lastItems(items: Activity[], width: number, room: number): { item: Activity; lines: string[] }[] {
401 const shown: { item: Activity; lines: string[] }[] = []
402 let used = 0
403 for (const item of items.toReversed()) {
404 const lines = itemLines(item, width)
405 if (used + lines.length > room) {
406 if (shown.length === 0) {
407 shown.push({ item, lines: lines.slice(0, room) })
408 }
409 break
410 }
411 shown.unshift({ item, lines })
412 used += lines.length
413 }
414
415 return shown
416}
417hooks/keys.tsx 253 lines1// The keys and the forms: the key row, the key list i opens, this session's
2// row, and the form n, s and r open.
3
4import type { Composer, Limit, ModelUse, Session } from '../types'
5import { runtime } from './state'
6import { LIMIT_LOUD, LIMIT_SHOWN, limitText } from './sessions'
7import { cells, fit, fitParts, fitStart, minutes, modelName, tildePath } from './text'
8import type { Part } from './text'
9import { cursorStyle, keyButton, keyWidth, partsNode, wrappedRows } from './view'
10import type { View } from './view'
11
12export type Keys = Record<'into' | 'spawn' | 'help' | 'rename' | 'clear' | 'attach' | 'stop' | 'down' | 'up' | 'close', () => void>
13
14// What the cursor is on allows: l on an agent or a session, c on this
15// session, r on this session or one whose glimt shares, a and x on a
16// background session, x on an agent of this session that runs in the
17// background.
18export type KeyContext = { canInto: boolean; canClear: boolean; canRename: boolean; canReach: boolean; canStop: boolean }
19
20// The keys while the pane holds the keyboard: glimt's own actions, those
21// the cursor's row allows, then n and i, then j and k to move and q to
22// close, as every pane of the series binds them. Claude Code's own keys
23// work too: Up, Down and Tab move, Enter opens or closes the row, Esc hands
24// the keyboard back. A key works only while drawn, so s lives in the list.
25export function keySection(view: View, can: KeyContext, keys: Keys) {
26 const { Box } = view.ui
27 const key = (name: string, hotkey: string, label: string, press: () => void) => keyButton(view, name, hotkey, label, press)
28 const labels = [
29 can.canInto && 'into',
30 can.canRename && 'rename',
31 can.canClear && 'clear',
32 can.canReach && 'attach',
33 (can.canReach || can.canStop) && 'stop',
34 'new',
35 'keys',
36 'down',
37 'up',
38 'close',
39 ].filter((label): label is string => label !== false)
40
41 return {
42 rows: wrappedRows(labels.map(keyWidth), view.columns, 3),
43 node: (
44 <Box key="keys" flexDirection="row" flexWrap="wrap" columnGap={3}>
45 {can.canInto && key('into', 'l', 'into', keys.into)}
46 {can.canRename && key('rename', 'r', 'rename', keys.rename)}
47 {can.canClear && key('clear', 'c', 'clear', keys.clear)}
48 {can.canReach && key('attach', 'a', 'attach', keys.attach)}
49 {(can.canReach || can.canStop) && key('stop', 'x', 'stop', keys.stop)}
50 {key('spawn', 'n', 'new', keys.spawn)}
51 {key('help', 'i', 'keys', keys.help)}
52 {key('down', 'j', 'down', keys.down)}
53 {key('up', 'k', 'up', keys.up)}
54 {key('close', 'q', 'close', keys.close)}
55 </Box>
56 ),
57 }
58}
59
60// Where /glimt puts Claude Code's focus ring as it gives the pane the
61// keyboard: in a form's field left open, on the key list's way back while
62// it shows, on the row the cursor was on while that row is drawn, or inside
63// an agent or a session on the way back, as l puts it; never on the message
64// field. None leaves the ring where opening the pane put it.
65export type Landing = { hasForm: boolean; hasKeyList: boolean; cursor: string | null; rows: readonly string[]; isInside: boolean }
66
67export function landingOf(at: Landing): { key: string; isRow: boolean } | null {
68 if (at.hasForm) {
69 return { key: 'composer-field', isRow: false }
70 }
71 if (at.hasKeyList) {
72 return { key: 'key-help', isRow: false }
73 }
74 if (at.cursor !== null && at.rows.includes(at.cursor)) {
75 return { key: at.cursor, isRow: true }
76 }
77 return at.isInside ? { key: 'back', isRow: false } : null
78}
79
80// What each key does, for the list i opens; the keys that start something or
81// close the pane are pressable there.
82export const KEY_LIST: readonly (readonly [string, string])[] = [
83 ['↑ ↓', 'move between rows, as Tab does'],
84 ['j k', 'down and up the rows alone; from a key, the first or last row'],
85 ['Enter', 'open or close the row'],
86 ['l', 'go into an agent or a session'],
87 ['h', 'back out'],
88 ['r', 'rename this session, or one running glimt'],
89 ['c', 'clear this conversation'],
90 ['m', 'write to the agent or session you are in'],
91 ['a', "copy a background session's attach command"],
92 ['x', 'stop a background session or agent'],
93 ['Esc', 'give the keyboard back to the prompt'],
94]
95
96export type HelpActions = { spawn: () => void; session: () => void; close: () => void; back: () => void }
97
98// i: every key and what it does, under the name and where it lives, in
99// place of the pane's body; n, s and q work from here, i goes back.
100export function helpSection(view: View, act: HelpActions) {
101 const { Box, Button, Text } = view.ui
102 const line = (keys: string, what: string) => (
103 <Text>
104 <Text color="claude">{keys}</Text>
105 {fit(`: ${what}`, view.columns - cells(keys))}
106 </Text>
107 )
108
109 return (
110 <Box key="help" flexDirection="column">
111 <Text color={view.colors.quiet}>{fit('glimt · github.com/mmedum/glimt', view.columns)}</Text>
112 <Box key="help-keys" flexDirection="column" marginTop={1}>
113 {KEY_LIST.map(([keys, what]) => line(keys, what))}
114 <Button key="help-spawn" plain hotkey="n" label="new agent here" onPress={act.spawn} />
115 <Button key="help-session" plain hotkey="s" label="new background session" onPress={act.session} />
116 <Button key="help-close" plain hotkey="q" label="close the pane" onPress={act.close} />
117 </Box>
118 <Box key="keys" marginTop={1}>
119 {keyButton(view, 'help', 'i', 'back', act.back)}
120 </Box>
121 </Box>
122 )
123}
124
125// What this session's rows say beside its name: the permission mode as last
126// seen, the plan's limits, whether another session runs in its folder, and
127// the main conversation's model and effort.
128export type SelfState = {
129 session: Session | undefined
130 isOpen: boolean
131 isClearing: boolean
132 answer: (isYes: boolean) => void
133 mode: string | null
134 limits: Limit[]
135 isSameFolder: boolean
136 engine: ModelUse | null
137}
138
139// The status row under this session's name, empty while all is usual:
140// bypass permissions in amber, each limit window from LIMIT_SHOWN (the
141// fullest first, with when it resets), another session in the same folder.
142// Short of room, when it resets goes first, then the other windows, then
143// the folder.
144export function selfStatus(view: View, state: SelfState): Part[] {
145 const shown = state.limits.filter(limit => limit.percentUsed >= LIMIT_SHOWN).toSorted((a, b) => b.percentUsed - a.percentUsed)
146 const resets = shown[0]?.resetsAt === undefined ? Number.NaN : Date.parse(shown[0].resetsAt)
147 const parts: Part[] = [
148 ...(state.mode === 'bypassPermissions' ? [{ text: view.columns < 36 ? 'bypass' : 'bypass permissions', color: 'warning', rank: 9 }] : []),
149 ...shown.flatMap((limit, i) => [
150 { text: limitText(limit), isBold: limit.percentUsed >= LIMIT_LOUD, rank: i === 0 ? 8 : 6 - i },
151 ...(i === 0 && !Number.isNaN(resets) ? [{ text: `resets in ${minutes(resets - view.at)}`, rank: 1 }] : []),
152 ]),
153 ...(state.isSameFolder ? [{ text: 'same folder', rank: 7 }] : []),
154 ]
155
156 return fitParts(parts, view.columns - 2)
157}
158
159// This session at the top: its name, under it the status row while it has
160// something to say, opened its folder, model, effort and id, and after c the
161// question whether to clear the conversation.
162export function selfSection(view: View, state: SelfState) {
163 const { Box, Button, Text } = view.ui
164 const { session, isOpen, isClearing, engine } = state
165 // Until the session list names it, the row just says what it is.
166 const name = session?.name
167 const where = session === undefined ? '' : tildePath(session.cwd, runtime.home)
168 const status = selfStatus(view, state)
169 const use = engine === null ? '' : ` · ${modelName(engine.model)}${engine.effort === undefined ? '' : ` · ${engine.effort} effort`}`
170 const cursor = cursorStyle(view, 'toggle-self')
171
172 return {
173 rows: 1 + (status.length > 0 ? 1 : 0) + (isOpen && session !== undefined ? 1 : 0) + (isClearing ? 1 : 0),
174 node: (
175 <Box key="self" flexDirection="column">
176 <Box flexDirection="row" {...cursor.row}>
177 <Button key="toggle-self" plain label={isOpen ? '▾' : '▸'} onPress={() => view.toggle('self')} />
178 <Text>
179 {' '}
180 <Text bold {...cursor.name}>
181 {fit(name ?? 'this session', view.columns - 16)}
182 </Text>
183 {name !== undefined && <Text color={view.colors.quiet}>{' this session'}</Text>}
184 </Text>
185 </Box>
186 {status.length > 0 && (
187 <Box key="self-status" paddingLeft={2}>
188 {partsNode(view, status)}
189 </Box>
190 )}
191 {isOpen && session !== undefined && (
192 <Text color={view.colors.quiet}>
193 {' ⎿ '}
194 {fitStart(`${where}${use} · ${session.id ?? session.sessionId}`, view.columns - 4)}
195 </Text>
196 )}
197 {isClearing && (
198 <Box key="clear-ask" flexDirection="row" columnGap={2} paddingLeft={2}>
199 <Text color="warning">Clear this conversation?</Text>
200 <Button key="clear-yes" plain hotkey="y" label="yes" onPress={() => state.answer(true)} />
201 <Button key="clear-no" plain hotkey="n" label="no" onPress={() => state.answer(false)} />
202 </Box>
203 )}
204 </Box>
205 ),
206 }
207}
208
209export type ComposerActions = {
210 spawn: (task: string, where: 'here' | 'session') => void
211 rename: (sessionId: string, name: string) => void
212 cancel: () => void
213}
214
215// The rows the form takes, the blank above it included.
216export const FORM_ROWS = 3
217
218// The form n, s or r opens, where the keys were, so nothing else moves: a
219// task for a new agent here (n) or in a new background session (s), or a new
220// name for a session (r). Its label says which, so nothing is left to choose.
221// Its field holds the keyboard: Enter starts, Enter on an empty field or
222// leaving it (Tab, or a click on cancel) closes it. The Enter hint is quiet
223// text: by default as dim as its cancel key, so the two read as one row of
224// keys.
225export function composerSection(view: View, form: Composer, list: Session[], act: ComposerActions) {
226 const { Box, Button, Text } = view.ui
227 const { Input } = view
228 if (Input === undefined) {
229 return <Text color={view.colors.quiet}>Typing here needs the terminal or the desktop app.</Text>
230 }
231
232 const isSpawn = form.kind === 'spawn'
233 const name = isSpawn ? '' : (list.find(s => s.sessionId === form.sessionId)?.name ?? 'the session')
234 const verb = isSpawn ? 'start' : 'rename'
235 return (
236 <Box key="composer" flexDirection="column">
237 <Input
238 key="composer-field"
239 label={isSpawn ? (form.where === 'here' ? 'New agent' : 'New session') : `Rename ${fit(name, 24)}`}
240 placeholder={isSpawn ? 'What should it do?' : 'New name'}
241 value=""
242 submitLabel={verb}
243 autoFocus
244 onSubmit={text => (isSpawn ? act.spawn(text, form.where) : act.rename(form.sessionId, text))}
245 />
246 <Box flexDirection="row" columnGap={3}>
247 <Text color={view.colors.quiet}>{`↵ ${verb}`}</Text>
248 <Button key="composer-cancel" plain dimColor label="tab cancel" onPress={act.cancel} />
249 </Box>
250 </Box>
251 )
252}
253hooks/paint.ts 111 lines1// A color option, as Claude Code's custom themes spell a color, turned into
2// one a Text paints: a theme role by name, hex, or one of the terminal's 256
3// colors by number.
4
5// Claude Code's theme roles, which follow the person's theme: every token its
6// custom theme reference lists.
7const ROLES = new Set([
8 'text',
9 'inverseText',
10 'inactive',
11 'subtle',
12 'suggestion',
13 'remember',
14 'success',
15 'error',
16 'warning',
17 'merged',
18 'claude',
19 'permission',
20 'planMode',
21 'autoAccept',
22 'promptBorder',
23 'bashBorder',
24 'ide',
25 'diffAdded',
26 'diffRemoved',
27 'diffAddedDimmed',
28 'diffRemovedDimmed',
29 'diffAddedWord',
30 'diffRemovedWord',
31 'fastMode',
32 'effortUltra',
33 'userMessageBackground',
34 'userMessageBackgroundHover',
35 'bashMessageBackgroundColor',
36 'memoryBackgroundColor',
37 'selectionBg',
38 'rate_limit_fill',
39 'rate_limit_empty',
40 'briefLabelYou',
41 'briefLabelClaude',
42 ...['claude', 'warning', 'permission', 'promptBorder', 'inactive', 'fastMode'].map(role => `${role}Shimmer`),
43 ...['red', 'blue', 'green', 'yellow', 'purple', 'orange', 'pink', 'cyan'].map(color => `${color}_FOR_SUBAGENTS_ONLY`),
44 ...['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'].flatMap(color => [`rainbow_${color}`, `rainbow_${color}_shimmer`]),
45])
46
47// The terminal's sixteen colors as Text names them, in ANSI order, which
48// numbers them for `ansi256(n)`; gray, in either spelling, is blackBright.
49const ANSI = [
50 'black',
51 'red',
52 'green',
53 'yellow',
54 'blue',
55 'magenta',
56 'cyan',
57 'white',
58 'blackBright',
59 'redBright',
60 'greenBright',
61 'yellowBright',
62 'blueBright',
63 'magentaBright',
64 'cyanBright',
65 'whiteBright',
66]
67const NUMBERS = new Map<string, number>([...ANSI.map((name, n) => [name, n] as const), ['gray', 8], ['grey', 8]])
68
69const hex = (...channels: number[]) => `#${channels.map(channel => channel.toString(16).padStart(2, '0')).join('')}`
70
71// The option's color, or `fallback` for one it can't read (undefined for no
72// color at all): a theme role, a color name, `#rgb` or `#rrggbb`,
73// `rgb(r, g, b)`, `ansi256(n)` or `ansi:<name>`, as a custom theme takes
74// them. A color name, bare or after `ansi:`, comes back by its number as
75// `ansi256(n)`, which Claude Code draws in the terminal's own palette: it
76// draws a bare name as a fixed hex, and refuses a colon in a Text color. Hex,
77// short or not, and `rgb()` come back as `#rrggbb`, so nothing rests on how
78// Claude Code reads `#rgb`.
79export function colorOf<T>(value: unknown, fallback: T): string | T {
80 if (typeof value !== 'string') {
81 return fallback
82 }
83 const color = value.trim()
84 if (ROLES.has(color)) {
85 return color
86 }
87 const named = NUMBERS.get(color.startsWith('ansi:') ? color.slice('ansi:'.length) : color)
88 if (named !== undefined) {
89 return `ansi256(${named})`
90 }
91 if (/^#[0-9a-f]{6}$/i.test(color)) {
92 return color.toLowerCase()
93 }
94 const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(color)
95 if (short !== null) {
96 return hex(...short.slice(1).map(digit => Number.parseInt(digit.repeat(2), 16)))
97 }
98 const rgb = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/.exec(color)
99 if (rgb !== null) {
100 const channels = rgb.slice(1).map(Number)
101 return channels.every(channel => channel <= 255) ? hex(...channels) : fallback
102 }
103 const indexed = /^ansi256\(\s*(\d{1,3})\s*\)$/.exec(color)
104 if (indexed !== null) {
105 const n = Number(indexed[1])
106 return n <= 255 ? `ansi256(${n})` : fallback
107 }
108
109 return fallback
110}
111hooks/plan.tsx 290 lines1// The plan: Claude's task list as steps and sub-steps, and what is in
2// progress now.
3
4import type { Plan, Step, StepStatus } from '../types'
5import { clip, duration, fit, spin, wrap } from './text'
6import { cursorStyle, heading } from './view'
7import type { View } from './view'
8
9// How far a sub-step is indented under its step, per level.
10export const INDENT = 2
11
12export type StepUpdate = {
13 taskId: string
14 subject?: string | undefined
15 description?: string | undefined
16 activeForm?: string | undefined
17 status?: StepStatus | 'deleted' | undefined
18 // A new parent, or null to make it a step of its own.
19 parent?: string | null | undefined
20}
21
22// A line of the plan as drawn: a step at its depth under the top level, with
23// its description when opened, or a line standing for steps folded or cut.
24export type StepLine = { kind: 'step'; step: Step; depth: number; detail: string[] }
25export type PlanLine = StepLine | { kind: 'done'; count: number } | { kind: 'more'; count: number }
26
27// The task a sub-step belongs to, from its metadata.parent; null when the
28// update clears it, undefined when the call does not say.
29export function parentFrom(metadata: unknown): string | null | undefined {
30 if (typeof metadata !== 'object' || metadata === null || !('parent' in metadata)) {
31 return undefined
32 }
33
34 const parent: unknown = metadata.parent
35 if (parent === null) {
36 return null
37 }
38
39 return typeof parent === 'string' || typeof parent === 'number' ? String(parent) : undefined
40}
41
42// A step's time in progress starts when it goes in progress, at `at`, and
43// is dropped when it leaves.
44export function applyUpdate(list: Step[], change: StepUpdate, at: number): Step[] {
45 if (change.status === 'deleted') {
46 return list.filter(step => step.id !== change.taskId)
47 }
48
49 const status = change.status
50 const known = list.some(step => step.id === change.taskId)
51 const updated = list.map(step => {
52 if (step.id !== change.taskId) {
53 return step
54 }
55
56 const next = status ?? step.status
57 return {
58 ...step,
59 subject: change.subject ?? step.subject,
60 description: change.description ?? step.description,
61 activeForm: change.activeForm ?? step.activeForm,
62 status: next,
63 startedAt: next !== 'in_progress' ? undefined : step.status === 'in_progress' ? step.startedAt : at,
64 parentId: change.parent === undefined ? step.parentId : (change.parent ?? undefined),
65 }
66 })
67
68 // A task made before this pane was watching: show it under what is known.
69 return known
70 ? updated
71 : [
72 ...updated,
73 {
74 id: change.taskId,
75 subject: change.subject ?? `Task ${change.taskId}`,
76 description: change.description,
77 activeForm: change.activeForm,
78 status: status ?? 'pending',
79 startedAt: status === 'in_progress' ? at : undefined,
80 parentId: change.parent ?? undefined,
81 },
82 ]
83}
84
85// The plan as units to draw: each top-level step with the steps under it,
86// depth first. A step whose parent is gone, or whose parents loop back to
87// it, stands at the top level.
88export function planUnits(list: Step[], open: readonly string[], columns: number): StepLine[][] {
89 const ids = new Set(list.map(step => step.id))
90 const parentOf = (step: Step) => (step.parentId !== undefined && ids.has(step.parentId) ? step.parentId : undefined)
91 const seen = new Set<string>()
92 const lineOf = (step: Step, depth: number): StepLine => ({
93 kind: 'step',
94 step,
95 depth,
96 detail: open.includes(step.id) ? detailLines(step, columns - 4 - depth * INDENT) : [],
97 })
98 const under = (parent: string, depth: number): StepLine[] =>
99 list
100 .filter(step => parentOf(step) === parent && !seen.has(step.id))
101 .flatMap(step => {
102 seen.add(step.id)
103 return [lineOf(step, depth), ...under(step.id, depth + 1)]
104 })
105 const unitOf = (step: Step): StepLine[] => {
106 seen.add(step.id)
107 return [lineOf(step, 0), ...under(step.id, 1)]
108 }
109
110 const units = list.filter(step => parentOf(step) === undefined).map(unitOf)
111 for (const step of list) {
112 if (!seen.has(step.id)) {
113 units.push(unitOf(step))
114 }
115 }
116
117 return units
118}
119
120// The plan's lines in `room` rows. A step and its sub-steps move together:
121// finished ones fold into one line, oldest first, until the rest fits; then
122// the tail is cut and its steps counted, so the step in progress stays in view.
123export function planLines(units: StepLine[][], room: number): PlanLine[] {
124 const all = units.flat()
125 if (rowCount(all) <= room) {
126 return all
127 }
128
129 const finished = units.filter(unit => unit.every(line => line.step.status === 'completed'))
130 let rest = units
131 let shown: PlanLine[] = all
132 for (let folded = 1; folded <= finished.length && rowCount(shown) > room; folded += 1) {
133 const hidden = new Set(finished.slice(0, folded))
134 rest = units.filter(unit => !hidden.has(unit))
135 shown = [{ kind: 'done', count: finished.slice(0, folded).flat().length }, ...rest.flat()]
136 }
137 if (rowCount(shown) <= room) {
138 return shown
139 }
140
141 const head = shown.filter(line => line.kind === 'done')
142 for (let kept = rest.length - 1; kept >= 1; kept -= 1) {
143 const cut: PlanLine[] = [...head, ...rest.slice(0, kept).flat(), { kind: 'more', count: rest.slice(kept).flat().length }]
144 if (rowCount(cut) <= room) {
145 return cut
146 }
147 }
148
149 // Room for less than the first step and its sub-steps: its lines from the
150 // top, the last one's description cut to fit.
151 const budget = room - head.length - 1
152 const taken: StepLine[] = []
153 for (const line of rest[0] ?? []) {
154 const used = rowCount(taken)
155 if (used + 1 > budget) {
156 break
157 }
158 taken.push({ ...line, detail: clip(line.detail, budget - used - 1) })
159 }
160 const left = rest.flat().length - taken.length
161
162 return [...head, ...taken, ...(left > 0 ? [{ kind: 'more' as const, count: left }] : [])]
163}
164
165export function rowCount(lines: readonly PlanLine[]): number {
166 return lines.reduce((sum, line) => sum + 1 + (line.kind === 'step' ? line.detail.length : 0), 0)
167}
168
169export function detailLines(step: Step, width: number): string[] {
170 if (step.description === undefined) {
171 return ['Loading…']
172 }
173
174 const lines = step.description.split('\n').flatMap(paragraph => wrap(paragraph, width))
175
176 return lines.length === 0 ? ['No description.'] : lines
177}
178
179// The plan's first heading, or its first line when it has none.
180export function planTitle(text: string): string {
181 const lines = text
182 .split('\n')
183 .map(line => line.trim())
184 .filter(line => line !== '')
185 const title = lines.find(line => line.startsWith('#')) ?? lines[0] ?? 'Plan'
186
187 return title.replace(/^#+\s*/, '')
188}
189
190// Claude Code's checklist marks: ☒ done, ☐ to do; ◐ for the step in progress.
191// A step to do carries no status, so its mark takes the mark color.
192const STEP_MARK: Record<StepStatus, string> = { completed: '☒', in_progress: '◐', pending: '☐' }
193const STATUS_COLOR: Record<Exclude<StepStatus, 'pending'>, string> = { completed: 'success', in_progress: 'claude' }
194
195// The steps in progress, and how long the first has been: a step left in
196// progress while nothing runs shows its age here.
197export function nowSection(view: View, list: Step[]) {
198 const { Box, Text } = view.ui
199 const active = list.filter(step => step.status === 'in_progress')
200 const since = active[0]?.startedAt
201 const mark = view.isTurnRunning ? spin(view.at) : STEP_MARK.in_progress
202
203 return {
204 rows: 1 + Math.max(1, active.length),
205 node: (
206 <Box flexDirection="column">
207 {heading(view, 'now-heading', 'Now', since === undefined ? '' : duration(view.at - since))}
208 <Box key="now" flexDirection="column">
209 {active.length === 0 ? (
210 <Text color={view.colors.quiet}>No step in progress.</Text>
211 ) : (
212 active.map(step => <Text color="claude">{fit(`${mark} ${step.activeForm ?? step.subject}`, view.columns)}</Text>)
213 )}
214 </Box>
215 </Box>
216 ),
217 }
218}
219
220export function stepMark(view: View, status: StepStatus): { mark: string; color: string } {
221 return { mark: STEP_MARK[status], color: status === 'pending' ? view.colors.mark : STATUS_COLOR[status] }
222}
223
224// Empty, the plan says why where it knows: Claude has no task list here,
225// which depends on the model.
226export function planSection(view: View, approved: Plan | null, list: Step[], lines: PlanLine[], hasTaskList: boolean | null) {
227 const { Box, Button, Text } = view.ui
228 const { quiet } = view.colors
229 const done = list.filter(step => step.status === 'completed').length
230
231 return (
232 <Box flexDirection="column">
233 {heading(view, 'plan-heading', approved === null ? 'Plan' : `Plan · ${approved.title}`, list.length === 0 ? '' : `${done}/${list.length}`)}
234 {list.length === 0 && (
235 <Box key="no-steps">
236 <Text color={quiet}>{hasTaskList === false ? 'No task list in this session.' : 'No steps yet.'}</Text>
237 </Box>
238 )}
239 {lines.map(line => {
240 if (line.kind === 'done') {
241 return (
242 <Box key="folded">
243 <Text color={quiet}>
244 {' '}
245 <Text color={STATUS_COLOR.completed}>{STEP_MARK.completed}</Text> {line.count} done
246 </Text>
247 </Box>
248 )
249 }
250 if (line.kind === 'more') {
251 return (
252 <Box key="more">
253 <Text color={quiet}>
254 {' '}
255 <Text color={view.colors.mark}>{STEP_MARK.pending}</Text> {line.count} more
256 </Text>
257 </Box>
258 )
259 }
260
261 const { step, detail, depth } = line
262 const indent = ' '.repeat(depth * INDENT)
263 const isOpen = detail.length > 0
264 const { mark, color } = stepMark(view, step.status)
265 const cursor = cursorStyle(view, `toggle-${step.id}`)
266
267 return (
268 <Box key={`step-${step.id}`} flexDirection="column">
269 <Box flexDirection="row" {...cursor.row}>
270 {indent !== '' && <Text>{indent}</Text>}
271 <Button key={`toggle-${step.id}`} plain label={isOpen ? '▾' : '▸'} onPress={() => view.toggle(step.id)} />
272 <Text {...(step.status === 'completed' ? { color: quiet } : {})} bold={step.status === 'in_progress'}>
273 {' '}
274 <Text color={color}>{mark}</Text> <Text {...cursor.name}>{fit(step.subject, view.columns - 4 - indent.length)}</Text>
275 </Text>
276 </Box>
277 {isOpen && (
278 <Box key={`detail-${step.id}`} flexDirection="column" paddingLeft={4 + indent.length}>
279 {detail.map(text => (
280 <Text color={quiet}>{text}</Text>
281 ))}
282 </Box>
283 )}
284 </Box>
285 )
286 })}
287 </Box>
288 )
289}
290hooks/sessions.tsx 577 lines1// The other Claude Code sessions on the machine, and their agents: how they
2// are listed, sorted and drawn.
3
4import type { Limit, Phase, RemoteAgent, RemoteList, Session, SessionState, Shared, SharedAgent } from '../types'
5import { TASK_LINES } from './agents'
6import { runtime } from './state'
7import { cells, clip, fit, fitParts, fitStart, isRecord, minutes, partsText, spin, tildePath, toolName, wrap } from './text'
8import type { Part } from './text'
9import { cursorStyle, heading, partsNode } from './view'
10import type { View } from './view'
11
12// How often the session list is read again while the pane is drawn, and how
13// often a session shares its running agents (when they changed) and looks
14// for a name another session's glimt asked it to take.
15export const POLL_MS = 5000
16
17// Shared agents are written again this often unchanged, so a reader can tell
18// a quiet session from one whose glimt has gone: older than STALE_MS, a
19// share is not shown.
20export const HEARTBEAT_MS = 30_000
21export const STALE_MS = 60_000
22
23// The most of an agent's task another session is shown.
24export const SHARED_TASK = 400
25
26// Another session's subagents: the newest REMOTE_KEPT are read, REMOTE_SHOWN
27// drawn; one whose transcript was written within ACTIVE_MS counts as at
28// work, unless its session's glimt says which run.
29export const REMOTE_KEPT = 20
30export const REMOTE_SHOWN = 6
31export const ACTIVE_MS = 60_000
32
33// A limit window shows once this much of it is used, and at full weight
34// from LIMIT_LOUD; another session's context shows once this full.
35export const LIMIT_SHOWN = 80
36export const LIMIT_LOUD = 95
37export const CONTEXT_SHOWN = 80
38
39// Claude Code's permission modes in its own words, without its glyphs.
40const MODE_WORDS: Record<string, string> = {
41 default: 'manual mode',
42 plan: 'plan mode',
43 acceptEdits: 'accept edits',
44 auto: 'auto mode',
45 dontAsk: "don't ask",
46 bypassPermissions: 'bypass permissions',
47}
48
49export function modeWords(mode: string): string {
50 return MODE_WORDS[mode] ?? mode
51}
52
53// A limit window by its length: "5h limit 84%".
54const LIMIT_NAMES: Record<string, string> = { five_hour: '5h limit', seven_day: '7d limit', spend_limit: 'spend limit' }
55
56export function limitText(limit: Limit): string {
57 return `${LIMIT_NAMES[limit.kind] ?? limit.kind} ${Math.round(limit.percentUsed)}%`
58}
59
60// The folders more than one live session runs in.
61export function sharedFolders(list: Session[]): ReadonlySet<string> {
62 const seen = new Set<string>()
63 const twice = new Set<string>()
64 for (const s of list) {
65 if (seen.has(s.cwd)) {
66 twice.add(s.cwd)
67 }
68 seen.add(s.cwd)
69 }
70
71 return twice
72}
73
74export function isShared(value: unknown): value is Shared {
75 if (typeof value !== 'object' || value === null) {
76 return false
77 }
78
79 const share = value as { at?: unknown; agents?: unknown }
80 return typeof share.at === 'number' && Array.isArray(share.agents)
81}
82
83// Waiting for its person first, then working, then failed or stopped, then
84// done or idle; by when they started within each, so a row moves only when
85// its state changes. Being in bold moves nothing: short of room,
86// sessionSection gives up the quiet rows first instead.
87export function sortSessions(list: Session[]): Session[] {
88 const rank: Record<SessionState, number> = { waiting: 0, working: 1, failed: 2, stopped: 2, done: 3, idle: 3 }
89
90 return list.toSorted((a, b) => rank[sessionState(a)] - rank[sessionState(b)] || a.startedAt - b.startedAt)
91}
92
93// Whether a session's name is drawn bold: its state, other than work, began
94// after the person last reacted to it. glimt sees a state begin at the read
95// after it did, up to POLL_MS late, so a reaction that close before counts.
96// A state glimt never saw begin is no news.
97export function isUnseen(phase: Phase | undefined, seenAt: number | undefined): boolean {
98 return phase?.since !== undefined && phase.state !== 'working' && (seenAt === undefined || seenAt + POLL_MS < phase.since)
99}
100
101// What this glimt knows of the person's reactions after a read: its own and
102// every share's, the latest of each, for the sessions in `ids` alone. What
103// another glimt knew is kept, so it outlasts that glimt. The same record
104// when nothing is new.
105export function nextSeen(own: Record<string, number>, shared: Record<string, Shared>, ids: ReadonlySet<string>): Record<string, number> {
106 const next: Record<string, number> = {}
107 for (const known of [own, ...Object.values(shared).map(share => (isRecord(share.seen) ? share.seen : {}))]) {
108 for (const [id, at] of Object.entries(known)) {
109 if (ids.has(id) && typeof at === 'number' && at > (next[id] ?? -Infinity)) {
110 next[id] = at
111 }
112 }
113 }
114 const isSame = Object.keys(next).length === Object.keys(own).length && Object.entries(next).every(([id, at]) => own[id] === at)
115
116 return isSame ? own : next
117}
118
119// The sessions in what `claude agents --json` printed; an entry with no
120// sessionId is left out.
121export function parseSessions(value: unknown): Session[] {
122 if (!Array.isArray(value)) {
123 throw new Error('not a list')
124 }
125
126 const text = (field: unknown) => (typeof field === 'string' ? field : undefined)
127 return value.flatMap((item: unknown) => {
128 const fields = isRecord(item) ? item : {}
129 const sessionId = text(fields.sessionId)
130 if (sessionId === undefined) {
131 return []
132 }
133
134 return [
135 {
136 sessionId,
137 id: text(fields.id),
138 name: text(fields.name) ?? sessionId.slice(0, 8),
139 cwd: text(fields.cwd) ?? '',
140 kind: text(fields.kind) ?? 'session',
141 status: text(fields.status),
142 state: text(fields.state),
143 waitingFor: text(fields.waitingFor),
144 pid: typeof fields.pid === 'number' ? fields.pid : undefined,
145 startedAt: typeof fields.startedAt === 'number' ? fields.startedAt : 0,
146 },
147 ]
148 })
149}
150
151// A background session can be attached to and stopped from here; one in a
152// terminal of its own is reached in that terminal. The footer offers a and x
153// for the first kind only.
154export function isReachable(s: Session): s is Session & { id: string } {
155 return s.kind === 'background' && s.id !== undefined
156}
157
158export type Listing = {
159 // The other sessions, sorted; null before the first read.
160 list: Session[] | null
161 error: string | null
162 // What their glimts share, by session id.
163 shared: Record<string, Shared>
164 // Their subagents as read, by session id, and the tasks of those opened.
165 remote: Record<string, RemoteList>
166 tasks: Record<string, string>
167 open: readonly string[]
168 asked: string | null
169 answer: (isYes: boolean) => void
170 phases: Record<string, Phase>
171 // When the person last reacted to each session, by id.
172 seen: Record<string, number>
173 // The folders more than one live session runs in.
174 folders: ReadonlySet<string>
175}
176
177// A session's name keeps at least this many cells before its facts give way.
178const MIN_NAME = 8
179
180// What another session's row says after its name, in this order: its state,
181// bypass permissions (amber), a context window from CONTEXT_SHOWN, another
182// session in its folder, how long it has been in its state, its plan's
183// progress and its running agents. Short of room the last go first; the
184// state, bypass and the folder go last.
185export function sessionParts(view: View, word: string, phase: Phase | undefined, share: Shared | undefined, isSameFolder: boolean): Part[] {
186 const context = share?.context
187 const running = share?.agents.length ?? 0
188 const percent = context === undefined ? '' : `${Math.round(context)}%`
189
190 return [
191 { text: word, rank: 10 },
192 ...(share?.mode === 'bypassPermissions' ? [{ text: 'bypass', color: 'warning', rank: 9 }] : []),
193 ...(context !== undefined && context >= CONTEXT_SHOWN ? [{ text: view.columns < 50 ? percent : `${percent} context`, rank: 6 }] : []),
194 ...(isSameFolder ? [{ text: 'same folder', rank: 8 }] : []),
195 ...(phase?.since === undefined ? [] : [{ text: minutes(view.at - phase.since), rank: 5 }]),
196 ...(share?.plan === undefined ? [] : [{ text: `${share.plan.done}/${share.plan.total}`, rank: 4 }]),
197 ...(running === 0 ? [] : [{ text: `${running} ${running === 1 ? 'agent' : 'agents'}`, rank: 3 }]),
198 ]
199}
200
201// The other Claude Code sessions on the machine in `room` rows, one line
202// each, in sortSessions' order, with how long they have been in that state
203// and how many agents their glimt says run; a name in bold changed state
204// since the person last reacted to it (see isUnseen). Opened, a session
205// shows where it runs and its id, then its agents (l goes into the session,
206// or into one of them); after x, it asks whether to stop it. Past the room,
207// the idle ones not in bold fold into one line, then rows are counted from
208// the end: the quiet ones first, those that neither wait nor are in bold,
209// and the rest only when those alone don't fit. A session that ended is not
210// idle: it keeps its row, which says how it ended.
211export function sessionSection(view: View, listing: Listing, room: number) {
212 const { Box, Button, Text } = view.ui
213 const { quiet } = view.colors
214 const { list, error, open, asked } = listing
215 const all = list ?? []
216 const waiting = all.filter(isSessionWaiting).length
217 const working = all.filter(isSessionBusy).length
218 const count = [waiting > 0 ? `${waiting} waiting` : '', working > 0 ? `${working} working` : ''].filter(part => part !== '').join(' · ')
219
220 const sharedOf = (s: Session) => listing.shared[s.sessionId]?.agents ?? []
221 const crews = new Map(
222 all.map(s => [
223 s.sessionId,
224 open.includes(`session:${s.sessionId}`)
225 ? remoteSection(view, s, { list: listing.remote[s.sessionId], shared: sharedOf(s), tasks: listing.tasks, open })
226 : undefined,
227 ]),
228 )
229 const rowsOf = (s: Session) => {
230 const crew = crews.get(s.sessionId)
231 return 1 + (crew === undefined ? 0 : 1 + crew.rows) + (asked === s.sessionId ? 1 : 0)
232 }
233 const total = (shown: Session[]) => shown.reduce((sum, s) => sum + rowsOf(s), 0)
234 const budget = room - 1 - (error === null ? 0 : 1)
235 const bold = new Set(all.filter(s => isUnseen(listing.phases[s.sessionId], listing.seen[s.sessionId])).map(s => s.sessionId))
236 const isBold = (s: Session) => bold.has(s.sessionId)
237 // An opened session stays on show, whatever else folds.
238 const isOpen = (s: Session) => crews.get(s.sessionId) !== undefined
239 const isQuiet = (s: Session) => !isOpen(s) && !isBold(s) && sessionState(s) !== 'waiting'
240 let shown = all
241 let idle = 0
242 if (total(shown) > budget) {
243 shown = all.filter(s => sessionState(s) !== 'idle' || isOpen(s) || isBold(s))
244 idle = all.length - shown.length
245 }
246 let hidden = 0
247 const extra = () => (idle > 0 ? 1 : 0) + (hidden > 0 ? 1 : 0)
248 while (total(shown) + extra() > budget) {
249 const lastQuiet = shown.map(isQuiet).lastIndexOf(true)
250 const last = lastQuiet === -1 ? shown.map(isOpen).lastIndexOf(false) : lastQuiet
251 if (last === -1) {
252 break
253 }
254 shown = shown.filter((_, i) => i !== last)
255 hidden += 1
256 }
257 const notes = (error === null ? 0 : 1) + (list === null && error === null ? 1 : 0) + (list !== null && list.length === 0 ? 1 : 0)
258
259 return {
260 rows: 1 + Math.max(1, notes + total(shown) + extra()),
261 toggles: shown.flatMap(s => [
262 { key: `toggle-session-${s.sessionId}`, target: `session:${s.sessionId}` },
263 ...(crews.get(s.sessionId)?.toggles ?? []),
264 ]),
265 node: (
266 <Box flexDirection="column">
267 {heading(view, 'sessions-heading', 'Sessions', count)}
268 {error !== null && (
269 <Box key="sessions-error">
270 <Text color="error">{fit(error, view.columns)}</Text>
271 </Box>
272 )}
273 {list === null && error === null && (
274 <Box key="no-sessions">
275 <Text color={quiet}>Reading the sessions…</Text>
276 </Box>
277 )}
278 {list !== null && list.length === 0 && (
279 <Box key="no-sessions">
280 <Text color={quiet}>No other sessions.</Text>
281 </Box>
282 )}
283 {shown.map(s => {
284 const crew = crews.get(s.sessionId)
285 const { mark, color, word } = sessionMark(view, s)
286 const phase = listing.phases[s.sessionId]
287 const parts = fitParts(
288 sessionParts(view, word, phase, listing.shared[s.sessionId], listing.folders.has(s.cwd)),
289 view.columns - 4 - MIN_NAME - 1,
290 )
291 const tally = partsText(parts)
292 const cursor = cursorStyle(view, `toggle-session-${s.sessionId}`)
293
294 return (
295 <Box key={`session-${s.sessionId}`} flexDirection="column">
296 <Box flexDirection="row" {...cursor.row}>
297 <Button
298 key={`toggle-session-${s.sessionId}`}
299 plain
300 label={crew === undefined ? '▸' : '▾'}
301 onPress={() => view.toggle(`session:${s.sessionId}`)}
302 />
303 <Box flexGrow={1}>
304 <Text {...(word === 'idle' && !isBold(s) ? { color: quiet } : {})}>
305 {' '}
306 <Text color={color}>{mark}</Text>{' '}
307 <Text bold={isBold(s)} {...cursor.name}>
308 {fit(s.name, view.columns - 4 - cells(tally) - 1)}
309 </Text>
310 </Text>
311 </Box>
312 <Text> </Text>
313 {partsNode(view, parts)}
314 </Box>
315 {asked === s.sessionId && (
316 <Box key={`stop-${s.sessionId}`} flexDirection="row" columnGap={2} paddingLeft={4}>
317 <Text color="warning">{fit(`Stop ${s.name}?`, view.columns - 20)}</Text>
318 <Button key="stop-yes" plain hotkey="y" label="yes" onPress={() => listing.answer(true)} />
319 <Button key="stop-no" plain hotkey="n" label="no" onPress={() => listing.answer(false)} />
320 </Box>
321 )}
322 {crew !== undefined && (
323 <Box key={`session-detail-${s.sessionId}`} flexDirection="column">
324 <Text color={quiet}>
325 {' ⎿ '}
326 {fitStart(placeOf(s), view.columns - 4)}
327 </Text>
328 {crew.node}
329 </Box>
330 )}
331 </Box>
332 )
333 })}
334 {idle > 0 && (
335 <Box key="sessions-idle">
336 <Text color={quiet}>
337 {' '}
338 <Text color={view.colors.mark}>○</Text> {idle} idle
339 </Text>
340 </Box>
341 )}
342 {hidden > 0 && (
343 <Box key="sessions-more">
344 <Text color={quiet}>+{hidden} more</Text>
345 </Box>
346 )}
347 </Box>
348 ),
349 }
350}
351
352// Where a session runs, on which git branch where known, what kind it is and
353// its id: "~/code on main · background · a1b2c3d4".
354export function placeOf(s: Session, branch?: string): string {
355 const where = tildePath(s.cwd, runtime.home)
356 const on = branch === undefined ? '' : ` on ${branch}`
357
358 return `${where}${on} · ${s.kind === 'background' ? 'background' : 'terminal'} · ${s.id ?? s.sessionId}`
359}
360
361export type RemoteState = { list: RemoteList | undefined; shared: SharedAgent[]; tasks: Record<string, string>; open: readonly string[] }
362
363// Another session's subagents, under it: the newest REMOTE_SHOWN written,
364// then how many are older. One at work spins: its session's glimt says it
365// runs, or its transcript changed within ACTIVE_MS; the rest say when they
366// last wrote. Opened, an agent shows its task.
367export function remoteSection(view: View, s: Session, state: RemoteState) {
368 const { Box, Button, Text } = view.ui
369 const { quiet } = view.colors
370 const { list, shared, tasks, open } = state
371 const sid = s.sessionId
372 if (list === undefined || list.total === 0) {
373 return {
374 rows: 1,
375 toggles: [],
376 node: (
377 <Box key={`remote-${sid}`}>
378 <Text color={quiet}>{list === undefined ? ' └─ Reading its agents…' : ' └─ No agents.'}</Text>
379 </Box>
380 ),
381 }
382 }
383
384 const shown = list.agents.slice(0, REMOTE_SHOWN)
385 const older = list.total - shown.length
386 const lines = shown.map((a, i) => {
387 const share = shared.find(one => one.id === a.id)
388 const target = `remote:${sid}:${a.id}`
389 const text = tasks[`${sid}:${a.id}`] ?? share?.task
390 const task = !open.includes(target)
391 ? []
392 : text === undefined
393 ? ['Loading…']
394 : text === ''
395 ? ['No task text.']
396 : clip(wrap(text, view.columns - 7), TASK_LINES)
397 const key = `toggle-remote-${sid}-${a.id}`
398 return {
399 a,
400 target,
401 task,
402 key,
403 cursor: cursorStyle(view, key),
404 isActive: isRemoteActive(view, a, share),
405 mark: remoteMark(view, a, share),
406 tally: remoteTally(view, a, share),
407 branch: i === shown.length - 1 && older === 0 ? ' └─ ' : ' ├─ ',
408 }
409 })
410
411 return {
412 rows: lines.reduce((sum, line) => sum + 1 + line.task.length, 0) + (older > 0 ? 1 : 0),
413 toggles: lines.map(line => ({ key: line.key, target: line.target })),
414 node: (
415 <Box key={`remote-${sid}`} flexDirection="column">
416 {lines.map(line => (
417 <Box key={`remote-${sid}-${line.a.id}`} flexDirection="column">
418 <Box flexDirection="row" {...line.cursor.row}>
419 <Text color={quiet}>{line.branch}</Text>
420 <Button key={line.key} plain label={line.task.length > 0 ? '▾' : '▸'} onPress={() => view.toggle(line.target)} />
421 <Box flexGrow={1}>
422 <Text {...(line.isActive ? {} : { color: quiet })}>
423 {' '}
424 <Text color={line.mark.color}>{line.mark.mark}</Text>{' '}
425 <Text {...line.cursor.name}>{fit(`${line.a.type} ${line.a.description}`, view.columns - 9 - cells(line.tally) - 1)}</Text>
426 </Text>
427 </Box>
428 <Text color={quiet}> {line.tally}</Text>
429 </Box>
430 {line.task.map(text => (
431 <Text color={quiet}>
432 {' '}
433 {text}
434 </Text>
435 ))}
436 </Box>
437 ))}
438 {older > 0 && (
439 <Box key={`remote-older-${sid}`}>
440 <Text color={quiet}>{` └─ +${older} older`}</Text>
441 </Box>
442 )}
443 </Box>
444 ),
445 }
446}
447
448export function isRemoteActive(view: View, a: RemoteAgent, share: SharedAgent | undefined): boolean {
449 return share !== undefined || view.at - a.writtenAt <= ACTIVE_MS
450}
451
452// Another session's agent: ◉ while its glimt says it waits on its person,
453// the spinner while it works, ○ in the mark color once it is quiet.
454export function remoteMark(view: View, a: RemoteAgent, share: SharedAgent | undefined): { mark: string; color: string } {
455 if (share?.asking !== undefined) {
456 return { mark: '◉', color: 'warning' }
457 }
458
459 return isRemoteActive(view, a, share) ? { mark: spin(view.at), color: 'claude' } : { mark: '○', color: view.colors.mark }
460}
461
462// A running agent its glimt shares: its time and what it runs, or the tool it
463// waits on its person to allow; any other, when its transcript was last
464// written.
465export function remoteTally(view: View, a: RemoteAgent, share: SharedAgent | undefined): string {
466 if (share === undefined) {
467 return `${minutes(view.at - a.writtenAt)} ago`
468 }
469
470 const doing =
471 share.asking !== undefined
472 ? `approve ${toolName(share.asking)}`
473 : share.tool === undefined
474 ? `${share.tools} ${share.tools === 1 ? 'tool' : 'tools'}`
475 : toolName(share.tool)
476 return `${minutes(view.at - share.startedAt)} · ${doing}`
477}
478
479// Waiting for its person: a background session says so as its state, any
480// session as its status.
481export function isSessionWaiting(s: Session): boolean {
482 return s.state === 'blocked' || s.status === 'waiting'
483}
484
485export function isSessionBusy(s: Session): boolean {
486 return !isSessionWaiting(s) && (s.status === 'busy' || s.state === 'working')
487}
488
489// What a session is doing. A background session that ended is not idle: it
490// says how it ended, and ending starts a phase of its own.
491export function sessionState(s: Session): SessionState {
492 if (isSessionWaiting(s)) {
493 return 'waiting'
494 }
495 if (isSessionBusy(s)) {
496 return 'working'
497 }
498
499 return s.state === 'failed' || s.state === 'stopped' || s.state === 'done' ? s.state : 'idle'
500}
501
502// What a waiting session wants of its person, by why it waits: a
503// permission prompt or a sandbox request an approval, a question an answer.
504const WANTS: Record<string, 'approve' | 'answer'> = { 'permission prompt': 'approve', 'sandbox request': 'approve', 'input needed': 'answer' }
505
506// A session's mark and word: the spinner while it works, ◉ while it waits
507// for its person, ○ while it idles, in the mark color; a background session
508// that ended keeps the agents' marks, ✗ failed and ■ stopped, and one done
509// says so. The word says it again without color, and a waiting session's
510// says what it wants, where it says why it waits.
511export function sessionMark(view: View, s: Session): { mark: string; color: string; word: string } {
512 const state = sessionState(s)
513 switch (state) {
514 case 'waiting':
515 return { mark: '◉', color: 'warning', word: WANTS[s.waitingFor ?? ''] ?? 'waiting' }
516 case 'working':
517 return { mark: spin(view.at), color: 'claude', word: 'working' }
518 case 'failed':
519 return { mark: '✗', color: 'error', word: 'failed' }
520 case 'stopped':
521 return { mark: '■', color: 'warning', word: 'stopped' }
522 }
523
524 // Done or idle.
525 return { mark: '○', color: view.colors.mark, word: state }
526}
527
528// The word, and how long the session has been in its state when glimt saw
529// that state begin: "idle · 4m", or "idle".
530export function stateText(word: string, phase: Phase | undefined, at: number): string {
531 return phase?.since === undefined ? word : `${word} · ${minutes(at - phase.since)}`
532}
533
534// The sessions' phases after a read at `at`. A session glimt meets for the
535// first time is in a phase of unknown age; one whose state changed, ending
536// included, starts a phase now; a session no longer listed is dropped.
537export function nextPhases(before: Record<string, Phase>, list: Session[], at: number): Record<string, Phase> {
538 return Object.fromEntries(
539 list.map(s => {
540 const state = sessionState(s)
541 const was = before[s.sessionId]
542 const phase: Phase = was === undefined ? { state } : was.state === state ? was : { state, since: at }
543 return [s.sessionId, phase]
544 }),
545 )
546}
547
548// Whether this session's glimt is the one on the machine to tell of
549// `subject`: of the panes drawn, the one whose session id sorts first, the
550// subject's own left out. Every glimt reaches the same answer from the
551// shares, so one notification goes out, not one per pane.
552export function isNotifier(selfId: string | null, subject: string, shared: Record<string, Shared>): boolean {
553 return Object.entries(shared).every(([id, share]) => share.watching !== true || id === subject || id > (selfId ?? ''))
554}
555
556// What a background session's change of state since the last read is worth
557// a notification for: it finished or failed. One already ended at the first
558// read is left alone.
559export function endingOf(was: Session | undefined, s: Session): 'finished' | 'failed' | undefined {
560 if (was === undefined || s.kind !== 'background' || was.state === s.state) {
561 return undefined
562 }
563
564 return s.state === 'done' ? 'finished' : s.state === 'failed' ? 'failed' : undefined
565}
566
567// What a notification says of a session that started waiting.
568export function waitingNote(s: Session): string {
569 const wants = WANTS[s.waitingFor ?? '']
570
571 return wants === 'approve'
572 ? `${s.name} needs your approval`
573 : wants === 'answer'
574 ? `${s.name} has a question for you`
575 : `${s.name} is waiting for you`
576}
577hooks/state.ts 34 lines1// What glimt's modules share: the pane's id, and the few values they share
2// as they run. The values drawing reads stay in register.tsx.
3
4export const PANE = 'glimt'
5
6// A toggle drawn in the pane and what it opens, in the order j and k walk.
7export type Toggle = { key: string; target: string }
8
9// The values glimt's modules share as they run: the toggles in the order
10// last drawn (for j and k) and whether Claude Code's focus ring is off
11// them, on the way back, a key or a field, whether the pane held the keyboard when last
12// drawn and whether it gave it up since the clock last looked, the home
13// folder and Claude Code's own folder,
14// whether anything runs (so the clock knows to move) and how many frames
15// have passed, what this session last shared, and when, how many calls it
16// has seen start (each running call's id), whether its notifications are on
17// (the `notifications` option), and whether the person closed the pane,
18// which then stays closed, /clear included, until they open it again.
19export const runtime = {
20 toggles: [] as Toggle[],
21 isOffRows: false,
22 isFocused: false,
23 hasLostKeyboard: false,
24 home: '',
25 configDir: '',
26 isBusy: false,
27 ticks: 0,
28 lastShared: '',
29 lastSharedAt: 0,
30 calls: 0,
31 notifies: true,
32 isClosed: false,
33}
34hooks/text.ts 203 lines1// Text as the pane draws it: measured in cells, fitted, wrapped, and
2// times and counts written short.
3
4// The pane measures text in code points (see cells), so spreading a string
5// into its code points is how it is measured and cut here.
6/* oxlint-disable typescript/no-misused-spread */
7
8// The braille spinner the skins mod's spinner turns too, a frame every
9// FRAME_MS while something runs; the clock stands still when nothing does.
10// It turns only on what is working right now: a running agent, a working
11// session, the step in progress while a turn runs. What waits, idles or is
12// done keeps a still mark.
13export const FRAME_MS = 100
14export const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
15
16// 950, 9.5k, 45k, 1.2M: a decimal only where a count has two digits or
17// fewer, and none that would round up to the next unit.
18export function tokenNumber(tokens: number): string {
19 if (tokens < 1000) {
20 return String(tokens)
21 }
22 if (tokens < 9_950) {
23 return `${(tokens / 1000).toFixed(1)}k`
24 }
25
26 return tokens < 999_500 ? `${Math.round(tokens / 1000)}k` : `${(tokens / 1_000_000).toFixed(1)}M`
27}
28
29// The fields that say what a call is on, in the order they are looked for:
30// a command, a file, a pattern, an address, a query, a task.
31export const CALL_FIELDS = ['command', 'file_path', 'notebook_path', 'path', 'pattern', 'url', 'query', 'description', 'subject', 'prompt']
32
33// What a call is on, from the first of those fields it has: its first line.
34export function describeCall(input: unknown): string | undefined {
35 const fields = isRecord(input) ? input : {}
36 for (const name of CALL_FIELDS) {
37 const value = fields[name]
38 if (typeof value === 'string' && value.trim() !== '') {
39 return value.trim().split('\n')[0]
40 }
41 }
42
43 return undefined
44}
45
46// Text is measured in code points, one cell each for the glyphs this pane
47// draws; a wide character in a prompt can overrun by a cell.
48export function cells(text: string): number {
49 return [...text].length
50}
51
52// Cut to `width` cells, an ellipsis marking the cut.
53export function fit(text: string, width: number): string {
54 const chars = [...text]
55 if (chars.length <= width) {
56 return text
57 }
58
59 return width <= 0 ? '' : `${chars.slice(0, width - 1).join('')}…`
60}
61
62// Cut from the start, for a path: its end is what tells files apart.
63export function fitStart(text: string, width: number): string {
64 const chars = [...text]
65 if (chars.length <= width) {
66 return text
67 }
68
69 return width <= 0 ? '' : `…${chars.slice(chars.length - width + 1).join('')}`
70}
71
72// Word-wrapped to `width`, at most `limit` lines, the last ending in an
73// ellipsis when there was more. A word longer than a line is split.
74export function wrap(text: string, width: number, limit = Infinity): string[] {
75 const lines: string[] = []
76 let line = ''
77 for (const word of text.split(/\s+/).filter(part => part !== '')) {
78 const joined = line === '' ? word : `${line} ${word}`
79 if (cells(joined) <= width) {
80 line = joined
81 continue
82 }
83 if (line !== '') {
84 lines.push(line)
85 }
86 let rest = [...word]
87 while (rest.length > width) {
88 lines.push(rest.slice(0, width).join(''))
89 rest = rest.slice(width)
90 }
91 line = rest.join('')
92 }
93 if (line !== '') {
94 lines.push(line)
95 }
96 if (lines.length <= limit) {
97 return lines
98 }
99
100 const kept = lines.slice(0, limit)
101 const last = kept[limit - 1] ?? ''
102 kept[limit - 1] = cells(last) < width ? `${last}…` : fit(last, width)
103
104 return kept
105}
106
107export function clip(lines: string[], count: number): string[] {
108 if (lines.length <= count) {
109 return lines
110 }
111
112 return count <= 0 ? [] : [...lines.slice(0, count - 1), '…']
113}
114
115export function spin(at: number): string {
116 return SPINNER[Math.floor(at / FRAME_MS) % SPINNER.length] ?? '◐'
117}
118
119export function duration(ms: number): string {
120 const seconds = Math.max(0, Math.floor(ms / 1000))
121 if (seconds < 60) {
122 return `${seconds}s`
123 }
124
125 const wholeMinutes = Math.floor(seconds / 60)
126 if (wholeMinutes < 60) {
127 return `${wholeMinutes}m${String(seconds % 60).padStart(2, '0')}s`
128 }
129
130 return `${Math.floor(wholeMinutes / 60)}h${String(wholeMinutes % 60).padStart(2, '0')}m`
131}
132
133// A running time on a row, by the minute, so the row stands still: <1m, 4m,
134// 1h05m. A finished one keeps its seconds (duration), as it no longer moves.
135export function minutes(ms: number): string {
136 const total = Math.max(0, Math.floor(ms / 60_000))
137 if (total < 1) {
138 return '<1m'
139 }
140
141 return total < 60 ? `${total}m` : `${Math.floor(total / 60)}h${String(total % 60).padStart(2, '0')}m`
142}
143
144// A model id as people say it: "claude-haiku-5-5" is "Haiku 5.5"; any other
145// id stays as it is.
146export function modelName(id: string): string {
147 const [, family = '', major = '', minor] = /^claude-([a-z]+)-(\d{1,2})(?:-(\d{1,2}))?(?=-|$)/.exec(id) ?? []
148 if (family === '') {
149 return id
150 }
151
152 return `${family.charAt(0).toUpperCase()}${family.slice(1)} ${major}${minor === undefined ? '' : `.${minor}`}`
153}
154
155// A folder under the home folder from ~: "/home/demo/code" is "~/code", while
156// "/home/demox" stays as it is.
157export function tildePath(path: string, home: string): string {
158 if (home === '' || (path !== home && !path.startsWith(`${home}/`))) {
159 return path
160 }
161
162 return `~${path.slice(home.length)}`
163}
164
165// One word or phrase of a row of facts: what it says, how it is drawn, and
166// how long it keeps its place when room runs short (higher stays longer).
167export type Part = { text: string; color?: string | undefined; isBold?: boolean | undefined; rank: number }
168
169// The parts that fit in `room` cells joined by " · ", in their order: the
170// lowest ranked go first until the rest fit.
171export function fitParts(parts: Part[], room: number): Part[] {
172 let kept = parts
173 const width = (some: Part[]) => some.reduce((sum, part, i) => sum + cells(part.text) + (i === 0 ? 0 : 3), 0)
174 while (kept.length > 0 && width(kept) > room) {
175 const lowest = Math.min(...kept.map(part => part.rank))
176 const at = kept.findLastIndex(part => part.rank === lowest)
177 kept = kept.filter((_, i) => i !== at)
178 }
179
180 return kept
181}
182
183export function partsText(parts: Part[]): string {
184 return parts.map(part => part.text).join(' · ')
185}
186
187// mcp__server__tool reads as tool.
188export function toolName(tool: string): string {
189 return tool.startsWith('mcp__') ? tool.split('__').slice(2).join('__') : tool
190}
191
192// A parsed JSON value's fields, when it is an object.
193export function isRecord(value: unknown): value is Record<string, unknown> {
194 return typeof value === 'object' && value !== null
195}
196
197// The first line of what a process printed, or undefined when it printed none.
198export function firstLine(text: string | undefined): string | undefined {
199 const line = text?.trim().split('\n')[0]
200
201 return line === undefined || line === '' ? undefined : line
202}
203hooks/view.tsx 111 lines1// What drawing needs beside the state, and the pieces every section draws.
2
3import type { ElementTable } from 'claude-code'
4import { cells, fit } from './text'
5import type { Part } from './text'
6
7export type Ui = Pick<ElementTable, 'Box' | 'Text' | 'Button'>
8export type InputElement = ElementTable<'terminal' | 'desktop'>['Input']
9
10// The color options, each a theme role or a color (see paint.ts): the quiet
11// text, the marks that carry no status (a step to do, another session idle
12// or done, or one of its agents gone quiet), the headings, without one bold
13// in the terminal's own text color, and the band behind the cursor's row
14// while the pane doesn't hold the keyboard; the status marks keep the
15// theme's colors. Quiet text goes without dimColor, which would win over its
16// color. A Button takes no color, so the keys stay dimColor: the theme's
17// inactive.
18export type Colors = { quiet: string; mark: string; heading: string | undefined; band: string }
19
20// What drawing needs beside the state: the elements (an Input where the
21// surface has one), the width, the time, the toggle the cursor is on,
22// whether the pane's rows hold the keyboard (the pane does, and no form of
23// glimt's is open), what pressing a toggle does, and the colors.
24export type View = {
25 ui: Ui
26 Input?: InputElement | undefined
27 columns: number
28 at: number
29 isTurnRunning: boolean
30 cursor: string | null
31 isFocused: boolean
32 toggle: (id: string) => void
33 colors: Colors
34}
35
36// The row whose toggle is `key`, while the cursor is on it: its name inverse
37// while the rows hold the keyboard. Without it, the row you left keeps a
38// quiet band across the pane in the Cursor band color, by default the
39// theme's background behind your messages, as Neovim keeps a side panel's
40// cursor line and lazygit its inactive selection, so it doesn't compete with
41// the prompt or the form you type in. `row` goes on the row's Box, `name` on
42// the Text of its name.
43export function cursorStyle({ cursor, isFocused, colors }: View, key: string): { row: { backgroundColor?: string }; name: { inverse?: boolean } } {
44 const isOn = cursor === key
45
46 return { row: isOn && !isFocused ? { backgroundColor: colors.band } : {}, name: isOn && isFocused ? { inverse: true } : {} }
47}
48
49// A section's heading: its label, bold, in the Heading color where one is
50// set, and what the section counts right beside it, quiet. Nearness ties the
51// count to its label; the blank row above each section sets the sections
52// apart.
53export function heading({ ui: { Box, Text }, columns, colors }: View, key: string, label: string, count: string) {
54 const shown = fit(label, count === '' ? columns : Math.max(1, columns - cells(count) - 2))
55
56 return (
57 <Box key={key} flexDirection="row">
58 <Text bold {...(colors.heading === undefined ? {} : { color: colors.heading })}>
59 {shown}
60 </Text>
61 {count !== '' && <Text color={colors.quiet}>{fit(` ${count}`, columns - cells(shown))}</Text>}
62 </Box>
63 )
64}
65
66// A row of facts joined by quiet " · ": each quiet, or in its own color
67// (amber for a risk) or at full weight (a limit nearly reached).
68export function partsNode({ ui: { Text }, colors }: View, parts: Part[]) {
69 return (
70 <Text>
71 {parts.map((part, i) => {
72 const color = part.color ?? (part.isBold === true ? undefined : colors.quiet)
73 return (
74 <Text>
75 {i > 0 && <Text color={colors.quiet}> · </Text>}
76 <Text {...(color === undefined ? {} : { color })} bold={part.isBold === true}>
77 {part.text}
78 </Text>
79 </Text>
80 )
81 })}
82 </Text>
83 )
84}
85
86// The cells a key takes on its row: the hotkey, a colon and a space, the label.
87export function keyWidth(label: string): number {
88 return 3 + cells(label)
89}
90
91// How many rows a row of items `widths` wide takes once it wraps at
92// `columns`, `gap` cells apart.
93export function wrappedRows(widths: readonly number[], columns: number, gap: number): number {
94 let rows = 1
95 let used = 0
96 for (const width of widths) {
97 if (used > 0 && used + gap + width > columns) {
98 rows += 1
99 used = width
100 } else {
101 used = used === 0 ? width : used + gap + width
102 }
103 }
104
105 return rows
106}
107
108export function keyButton({ ui: { Button } }: View, name: string, hotkey: string, label: string, press: () => void) {
109 return <Button key={`key-${name}`} plain dimColor hotkey={hotkey} label={label} onPress={press} />
110}
111types/index.d.ts 232 lines1export type StepStatus = 'pending' | 'in_progress' | 'completed'
2
3// One step of the plan, as Claude's task list (or TodoWrite) holds it.
4// `description` is undefined until known: a task seeded from TaskList is
5// read with TaskGet the first time it is opened. `startedAt` is when it went
6// in progress, while it is; unknown for one seeded already in progress.
7// `parentId` is the step it is a sub-step of. A subagent's own tasks join the
8// plan with ids led by the agent's ("<agentId>/<taskId>").
9export type Step = {
10 id: string
11 subject: string
12 description?: string | undefined
13 activeForm?: string | undefined
14 status: StepStatus
15 startedAt?: number | undefined
16 parentId?: string | undefined
17}
18
19export type AgentState = 'running' | 'done' | 'failed' | 'stopped'
20
21// One subagent, from its spawn to the end of its run. `parentId` is the
22// agentId of the agent that spawned it, undefined when the main conversation
23// did; `stepId` is the plan step in progress when it started, which its own
24// tasks nest under; `task` is the prompt it was given; `tool` and `doing` say
25// what its running call is and what that call is on; `tokens` is the size of
26// its context: what its latest model request carried, and the reply;
27// `model` is what it runs on; `isBackground` says it runs in the background,
28// so it can be stopped from here; `calls` are the calls it runs now, the
29// latest the one `tool` and `doing` name.
30export type Agent = {
31 id: string
32 agentId?: string | undefined
33 parentId?: string | undefined
34 stepId?: string | undefined
35 type: string
36 description: string
37 task: string
38 state: AgentState
39 startedAt: number
40 endedAt?: number | undefined
41 tools: number
42 tool?: string | undefined
43 doing?: string | undefined
44 tokens?: number | undefined
45 // How full its context window is, in percent: known for the main
46 // conversation alone.
47 percent?: number | undefined
48 model?: string | undefined
49 isBackground?: boolean | undefined
50 calls?: RunningCall[] | undefined
51}
52
53// A call a loop runs now: an id of glimt's own, the tool, what it is on, and
54// since when it has waited on its person, while it has.
55export type RunningCall = { id: string; tool: string; on?: string | undefined; askedAt?: number | undefined }
56
57// The main conversation's latest turn: when it started and ended, how it
58// ended, the calls it runs now (the latest named by `tool` and `doing`), how
59// many calls it has made and its context.
60export type Focus = {
61 startedAt?: number | undefined
62 endedAt?: number | undefined
63 outcome?: AgentState | undefined
64 tools?: number | undefined
65 tool?: string | undefined
66 doing?: string | undefined
67 calls?: RunningCall[] | undefined
68 tokens?: number | undefined
69 percent?: number | undefined
70}
71
72// A plan approved in plan mode.
73export type Plan = { title: string; path?: string | undefined }
74
75// One Claude Code session on this machine, as `claude agents --json` lists
76// it. `id` is a background session's short id, what `claude attach` and
77// `claude stop` take; `status` is busy, waiting or idle for every session,
78// `state` working, blocked (waiting for the person) and the like for a
79// background one; `waitingFor` says why it waits ("permission prompt",
80// "input needed", ...).
81export type Session = {
82 sessionId: string
83 id?: string | undefined
84 name: string
85 cwd: string
86 kind: string
87 status?: string | undefined
88 state?: string | undefined
89 waitingFor?: string | undefined
90 pid?: number | undefined
91 startedAt: number
92}
93
94// What a session is doing, as its mark says it; a background session that
95// ended says how.
96export type SessionState = 'waiting' | 'working' | 'failed' | 'stopped' | 'done' | 'idle'
97
98// Another session's state as glimt has watched it: since when, undefined
99// while glimt has not seen it begin.
100export type Phase = { state: SessionState; since?: number | undefined }
101
102// A running agent of another session, as that session's glimt shares it
103// through the store every session on the machine reads; `asking` is the tool
104// a call of its waits on its person to allow.
105export type SharedAgent = {
106 id: string
107 type: string
108 description: string
109 task: string
110 startedAt: number
111 tools: number
112 tool?: string | undefined
113 asking?: string | undefined
114}
115
116// What a session's glimt shares: when it last did, its running agents, how
117// far its plan has come, whether its pane is drawn (so it reads the session
118// list, and may be the one to notify), its permission mode as last seen,
119// how full its context window is, in percent, and when the person last
120// reacted to each session, as far as it knows.
121export type Shared = {
122 at: number
123 agents: SharedAgent[]
124 plan?: { done: number; total: number } | undefined
125 watching?: boolean | undefined
126 mode?: string | undefined
127 context?: number | undefined
128 seen?: Record<string, number> | undefined
129}
130
131// One of the plan's limit windows as Claude Code reports it: `five_hour`,
132// `seven_day` or a gateway's `spend_limit`, how much of it is used, and when
133// it resets (ISO 8601).
134export type Limit = { kind: string; percentUsed: number; resetsAt?: string | undefined }
135
136// The main conversation's model and effort, as its latest model request
137// named them.
138export type ModelUse = { model: string; effort?: string | undefined }
139
140// The form open at the top of the pane: a new agent, here or as a new
141// background session, or a new name for a session.
142export type Composer = { kind: 'spawn'; where: 'here' | 'session' } | { kind: 'rename'; sessionId: string }
143
144// One step of the way l drilled in, in place of the overview: one of this
145// session's agents (by its Agent id), another session, or one of another
146// session's agents. `from` is the toggle the cursor was on, where h puts it
147// back.
148export type Opened = (
149 | { kind: 'agent'; id: string }
150 | { kind: 'session'; sessionId: string }
151 | { kind: 'remote'; sessionId: string; agentId: string }
152) & { from?: string | undefined }
153
154// One subagent of another session, as that session's transcript folder lists
155// it: its type and description from the agent's meta file, and when its
156// transcript was last written.
157export type RemoteAgent = { id: string; type: string; description: string; writtenAt: number }
158
159// Another session's subagents, the newest written first, as many as are
160// read; `total` counts every one in the folder.
161export type RemoteList = { agents: RemoteAgent[]; total: number }
162
163// One item of an agent's or a session's latest activity: what it was asked,
164// what Claude said, or a call it made ("Read · /a/b.ts").
165export type Activity = { kind: 'asked' | 'said' | 'call'; text: string }
166
167// The activity last read for what the pane is drilled into, oldest first, or
168// why it could not be read.
169// `model` is the one its latest reply came from, and `branch` the git branch
170// of the session's folder, where known.
171export type Feed = { items: Activity[]; error?: string | undefined; model?: string | undefined; branch?: string | undefined }
172
173declare module 'claude-code' {
174 interface PluginState {
175 glimt: {
176 focus: Focus | null
177 plan: Plan | null
178 steps: Step[]
179 agents: Agent[]
180 now: number
181 // Whether the pane is drawn, so the chat can leave out what it shows.
182 isShown: boolean
183 // The steps, and the agents ("agent:" and the id), opened to show more.
184 expanded: string[]
185 // The toggle j, k and o act on, drawn highlighted.
186 cursor: string | null
187 // Every session, as last read; null before the first read.
188 sessions: Session[] | null
189 // Why the last read failed, until one succeeds.
190 sessionsError: string | null
191 // The other sessions' states as glimt watched them, by session id.
192 phases: Record<string, Phase>
193 // When the person last reacted to each session, by id, as far as this
194 // glimt knows: opened it in any glimt, or typed, sent a prompt or
195 // pressed in its own terminal. Shared with the other glimts.
196 seen: Record<string, number>
197 // Whether this session's requests offer Claude a task list; null
198 // before the first. Once one does, it stays true.
199 hasTaskList: boolean | null
200 // This session's permission mode as the last event that carries it
201 // said; null before one has.
202 mode: string | null
203 // The plan's limit windows as last measured.
204 limits: Limit[]
205 // The main conversation's model and effort; null before its first request.
206 engine: ModelUse | null
207 // Claude Code's own titles for sessions never renamed, by session id.
208 titles: Record<string, string>
209 // What `x` asked to stop, waiting for y or n: a session by its id, or
210 // one of this session's agents as "agent:" and its id.
211 stopping: string | null
212 // This session's id, to leave it out of the list: the pane is about it.
213 self: string | null
214 // What the other sessions' glimts share, by session id, fresh ones only.
215 shared: Record<string, Shared>
216 composer: Composer | null
217 // Whether c asked to clear this conversation, waiting for y or n.
218 clearing: boolean
219 // The way l drilled in, the last step on show; empty for the overview.
220 opened: Opened[]
221 // The last step's latest activity; null until the first read.
222 feed: Feed | null
223 // The subagents of the sessions opened or drilled into, by session id.
224 remote: Record<string, RemoteList>
225 // Another session's agents' tasks as read, by "<sessionId>:<agentId>".
226 remoteTasks: Record<string, string>
227 // Whether i opened the key list in place of the pane's body.
228 help: boolean
229 }
230 }
231}
232