Keeps track of detached services Claude starts and stops them on request

Keeps track of services Claude starts in the background and that keep running after the command returned — a Docker Compose stack, a container, the Colima VM, a Homebrew service — and lets you stop them.
Claude Code already lists its own background shells and subagents. What it does not show is a service that detaches: docker compose up -d returns at once, and the stack keeps running unnoticed. This mod fills that gap and stays out of sight otherwise.
| When | What you see |
|---|---|
| Nothing Claude started is running | nothing |
| Something is running | 🐳 2 in the footer under the prompt; in the desktop app a click on it opens the pane, also while Claude is working |
| You want details | /services opens a pane: name, folder, start time, a Stop button per service, Stop all, Refresh. In the desktop app each service is a card with a pulsing status dot and how long it has been running, its buttons laid over the card's right edge; Refresh and Stop all sit in the header card |
/clear while something runs | a dialog listing the services: Stop all or Keep running |
| A new session starts while services from an earlier one still run | a toast pointing to /services |
No setup needed.
| Started with | Stopped with | Running check |
|---|---|---|
docker compose up -d (also docker-compose) | docker compose down in the same folder, with the same -f, -p and --profile flags | docker compose ps |
docker compose start | docker compose stop, which keeps the containers | docker compose ps |
docker run -d | docker stop <name or id> | docker ps |
docker start <name> | docker stop <name> | docker ps |
colima start [profile] | colima stop [profile] | colima status |
brew services start / run / restart | brew services stop | brew services info --json |
launchctl load | launchctl unload | none — shown with ? and a Forget button |
launchctl bootstrap <domain> <plist> | launchctl bootout <domain> <plist> | none — shown with ? and a Forget button |
Services are matched in chained commands too, including a preceding cd: in cd app && docker compose up -d the stack is tracked in app. A service that was stopped some other way — by you in a terminal, or by Claude running the stop command — drops off the list the next time it is checked.
sudo, nohup, env and similar prefixes and when sent to the background with &. Other programs sent to the background, such as npm run dev &, are not tracked; Claude Code's own background shells list and stop those./services opens at once, also while Claude is working; the desktop app holds a slash command typed mid-turn until the turn ends, so the 🐳 in the footer is the way in there. Nothing of it reaches Claude's context, and a service Claude starts while the pane checks the list is kept.mod-hub loaded, the desktop footer leaves the 🐳 count to its 🧰, whose Services row shows the count and opens the pane.Remove the mod from CLAUDE_CODE_PLUGIN_DIRS. Services it tracked keep running; stop them first with /services if you want them gone.
hooks/register.tsx 396 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement } from 'claude-code'
3
4import type { Service } from '../types'
5import { detectServices, isRunning, mayStopServices } from './detect'
6import type { HubCall, HubEntry } from './hub'
7import { buttonWidthOf, clockTime, headerCard, serviceCard, shortPath } from './look'
8import { ROOMY_WIDTH, cardWidthOf } from './svg'
9
10const PANE = 'service-radar'
11const STORE_KEY = 'services'
12const STOP_ALL = 'Stop all'
13const KEEP = 'Keep running'
14const CHECK_TIMEOUT_MS = 20_000
15const STOP_TIMEOUT_MS = 120_000
16
17const services = atom({ plugin: 'service-radar', key: 'services' } as const, [])
18const isBusy = atom({ plugin: 'service-radar', key: 'isBusy' } as const, false)
19const message = atom({ plugin: 'service-radar', key: 'message' } as const, '')
20const isHubbed = atom({ plugin: 'service-radar', key: 'isHubbed' } as const, false)
21
22let published: string | null = null
23
24// Without mod-hub the call throws, and the mod keeps its own footer count.
25async function publish($: EngineInterface, entry: HubEntry): Promise<void> {
26 const text = JSON.stringify(entry)
27 if (text === published) {
28 return
29 }
30 let isReached = true
31 try {
32 await ($ as unknown as HubCall).hub.set({ id: 'service-radar', ...entry })
33 } catch {
34 isReached = false
35 }
36 published = isReached ? text : null
37 if ((await read($, isHubbed)) !== isReached) {
38 await update($, isHubbed, () => isReached)
39 }
40}
41
42// Services outlive the session that started them, so the list lives in the
43// plugin's store; the state atom only mirrors it for drawing.
44async function loadServices($: EngineInterface): Promise<Service[]> {
45 const stored = await $.store.get(STORE_KEY)
46
47 return Array.isArray(stored) ? (stored as Service[]) : []
48}
49
50async function saveServices($: EngineInterface, list: Service[]): Promise<void> {
51 await $.store.set(STORE_KEY, list)
52 await update($, services, () => list)
53 await report($, list)
54}
55
56async function report($: EngineInterface, list: readonly Service[]): Promise<void> {
57 await publish($, {
58 icon: '🐳',
59 title: 'Services',
60 status: list.length === 0 ? 'Nothing running' : `${list.length} running`,
61 attention: list.length === 0 ? 'none' : 'info',
62 actions: [{ key: 'open', label: 'Open' }],
63 })
64}
65
66// The desktop app starts sessions with launchd's bare PATH, which lacks
67// Homebrew: docker, colima and brew would not be found there.
68const HOMEBREW_PATH = ['/opt/homebrew/bin', '/opt/homebrew/sbin', '/usr/local/bin']
69
70async function searchPath($: EngineInterface): Promise<string[]> {
71 const current = ((await $.env.get('PATH')) ?? '/usr/bin:/bin:/usr/sbin:/sbin').split(':').filter(i => i !== '')
72
73 return [...current, ...HOMEBREW_PATH.filter(i => !current.includes(i))]
74}
75
76// The child's PATH alone may not steer the lookup of argv[0], so the
77// executable is resolved here; on any doubt the bare name is passed on.
78async function resolveExecutable($: EngineInterface, command: string, directories: readonly string[]): Promise<string> {
79 if (command.includes('/')) {
80 return command
81 }
82 for (const directory of directories) {
83 try {
84 if (await $.fs.exists(`${directory}/${command}`)) {
85 return `${directory}/${command}`
86 }
87 } catch {
88 return command
89 }
90 }
91
92 return command
93}
94
95async function runCommand($: EngineInterface, argv: readonly string[], cwd: string, timeoutMs: number) {
96 const directories = await searchPath($)
97 const [command = '', ...args] = argv
98 const executable = await resolveExecutable($, command, directories)
99
100 return $.process.run([executable, ...args], {
101 cwd,
102 timeoutMs,
103 env: { HOMEBREW_NO_AUTO_UPDATE: '1', PATH: directories.join(':') },
104 })
105}
106
107async function stillRunning($: EngineInterface, service: Service): Promise<boolean> {
108 if (service.check === null) {
109 return true
110 }
111 try {
112 const result = await runCommand($, service.check.argv, service.cwd, CHECK_TIMEOUT_MS)
113
114 return isRunning(service.check.rule, result.exitCode, result.stdout)
115 } catch {
116 return false
117 }
118}
119
120// The pane opens on the list as stored; the checks then update it in place.
121async function openServices($: EngineInterface): Promise<void> {
122 await update($, message, () => '')
123 await $.ui.open({ id: PANE, title: 'Services', focus: true })
124 await refresh($)
125}
126
127// /services runs mid-turn, so a service Claude starts while the checks run must
128// survive: only the dead ones are dropped from the list as it is by then.
129async function refresh($: EngineInterface): Promise<Service[]> {
130 const dead = new Set<string>()
131 for (const service of await loadServices($)) {
132 if (!(await stillRunning($, service))) {
133 dead.add(service.id)
134 }
135 }
136 const current = await loadServices($)
137 const alive = current.filter(i => !dead.has(i.id))
138 await saveServices($, alive)
139
140 return alive
141}
142
143async function stopService($: EngineInterface, service: Service): Promise<string> {
144 try {
145 const result = await runCommand($, service.stop, service.cwd, STOP_TIMEOUT_MS)
146 if (result.exitCode !== 0 && (await stillRunning($, service))) {
147 return `${service.label}: stop failed (${result.stderr.trim().split('\n').pop() ?? `exit ${result.exitCode}`})`
148 }
149 } catch (error) {
150 return `${service.label}: stop failed (${error instanceof Error ? error.message : 'unknown error'})`
151 }
152 await saveServices($, (await loadServices($)).filter(i => i.id !== service.id))
153
154 return `${service.label}: stopped`
155}
156
157async function stopAll($: EngineInterface): Promise<string> {
158 const lines: string[] = []
159 for (const service of await loadServices($)) {
160 lines.push(await stopService($, service))
161 }
162
163 return lines.join('\n')
164}
165
166async function busy($: EngineInterface, work: () => Promise<string>): Promise<void> {
167 if (await read($, isBusy)) {
168 return
169 }
170 await update($, isBusy, () => true)
171 try {
172 const text = await work()
173 await update($, message, () => text)
174 } finally {
175 await update($, isBusy, () => false)
176 }
177}
178
179// A press handler runs under Claude Code's 10-second hook budget, and stopping
180// a VM takes longer; the work is handed to a timer, which has no such limit.
181function inBackground($: EngineInterface, work: () => Promise<string>): void {
182 $.clock.after(0, () => {
183 void busy($, work)
184 })
185}
186
187async function forget($: EngineInterface, id: string): Promise<void> {
188 await saveServices($, (await loadServices($)).filter(i => i.id !== id))
189}
190
191export const register: Register = on => {
192 on('session.start', async ($, e, next) => {
193 await $.command.register({ name: 'services', description: 'Show the services Claude started and stop them', immediate: true })
194 // Checking services can take seconds (a slow Docker daemon); startup must not
195 // wait for it. Until then the hub shows the list as stored.
196 await report($, await loadServices($))
197 void refresh($).then(alive => {
198 if (alive.length > 0) {
199 $.ui.toast(`${alive.length} service${alive.length === 1 ? '' : 's'} Claude started earlier still running. /services shows them.`)
200 }
201 })
202
203 return next(e)
204 })
205
206 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
207 const cwd = await $.session.cwd()
208 const result = await next(e)
209 if (result.deny !== undefined || result.isError === true) {
210 return result
211 }
212
213 const output = typeof result.result.stdout === 'string' ? result.result.stdout : ''
214 const home = (await $.env.get('HOME')) ?? ''
215 const detected = detectServices(e.command, cwd, home, output)
216 if (detected.length > 0) {
217 const now = await $.clock.now()
218 const list = await loadServices($)
219 const added = detected
220 .filter(found => !list.some(known => known.label === found.label && known.cwd === found.cwd))
221 .map((found, index) => ({ ...found, id: `${now}-${index}`, startedAt: now }))
222 await saveServices($, [...list, ...added])
223 } else if (mayStopServices(e.command) && (await loadServices($)).length > 0) {
224 void refresh($)
225 }
226
227 return result
228 })
229
230 on('command.run', { command: 'services' }, async $ => {
231 await openServices($)
232
233 return {}
234 })
235
236 on('ui.press', { plugin: 'mod-hub', element: 'service-radar:open' }, async ($, e, next) => {
237 void openServices($)
238
239 return next(e)
240 })
241
242 // A /clear is the last moment to ask: on exit Claude Code allows no dialog,
243 // and the list is kept in the store for the next session instead.
244 on('command.run', { command: 'clear' }, async ($, e, next) => {
245 const alive = await refresh($)
246 if (alive.length === 0) {
247 return next(e)
248 }
249 const names = alive.slice(0, 5).map(i => `- ${i.label}`).join('\n')
250 const more = alive.length > 5 ? `\n- and ${alive.length - 5} more` : ''
251 let answer = KEEP
252 try {
253 answer = await $.ui.ask(`Services Claude started are still running:\n${names}${more}\n\nStop them before clearing?`, {
254 options: [STOP_ALL, KEEP],
255 header: 'Services',
256 })
257 } catch {
258 answer = KEEP
259 }
260 if (answer === STOP_ALL) {
261 $.ui.toast(await stopAll($))
262 }
263
264 return next(e)
265 })
266
267 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
268 const { Box, Text, Button } = $.ui.resolve(e)
269 const list = await read($, services)
270 const running = await read($, isBusy)
271 const text = await read($, message)
272 const home = await $.env.get('HOME')
273 if (e.surface !== 'terminal') {
274 const { Svg } = $.ui.resolve(e)
275 const width = cardWidthOf(e.props.bodyColumns)
276 const now = await $.clock.now()
277 const isRoomy = width >= ROOMY_WIDTH
278 const headerLabels = list.length > 1 ? ['↻ Refresh', '■ Stop all'] : ['↻ Refresh']
279 const header = headerCard({
280 width,
281 eyebrow: '🐳 SERVICES',
282 title: list.length === 0 ? 'Nothing running' : `${list.length} running`,
283 counter: running ? 'working…' : 'started by Claude',
284 reserve: isRoomy ? buttonWidthOf(headerLabels) : 0,
285 })
286 const headerButtons = [
287 <Button key="refresh" dimColor label="↻ Refresh" onPress={() => inBackground($, async () => `${(await refresh($)).length} running`)} />,
288 ...(list.length > 1
289 ? [<Button key="stop-all" hover={{ scope: 'stop-all', color: 'error' }} label="■ Stop all" onPress={() => inBackground($, () => stopAll($))} />]
290 : []),
291 ]
292 const overlay = (children: RenderElement[]) => (
293 <Box position="absolute" top={0} bottom={0} right={2} flexDirection="row" alignItems="center" columnGap={1}>
294 {children}
295 </Box>
296 )
297
298 // The buttons lie over the cards, centered on their height: the pictures
299 // take no presses. A narrow pane keeps the header's beneath it.
300 return (
301 <Box flexDirection="column" rowGap={1}>
302 <Box key="header" flexDirection="column">
303 <Svg source={header.source} alt={header.alt} width={width} height={header.height} />
304 {isRoomy && overlay(headerButtons)}
305 </Box>
306 {!isRoomy && (
307 <Box flexDirection="row" columnGap={1}>
308 {headerButtons}
309 </Box>
310 )}
311 {list.map(service => {
312 const labels = service.check === null ? ['Forget', '■ Stop'] : ['■ Stop']
313 const card = serviceCard(width, service, { home, now, reserve: buttonWidthOf(labels) })
314
315 return (
316 <Box key={`card-${service.id}`} flexDirection="column">
317 <Svg source={card.source} alt={card.alt} width={width} height={card.height} />
318 {overlay([
319 ...(service.check === null ? [<Button key={`forget-${service.id}`} dimColor label="Forget" onPress={() => forget($, service.id)} />] : []),
320 <Button key={`stop-${service.id}`} hover={{ color: 'error' }} label="■ Stop" onPress={() => inBackground($, () => stopService($, service))} />,
321 ])}
322 </Box>
323 )
324 })}
325 {!running && text.length > 0 && <Text color="claude">{text}</Text>}
326 </Box>
327 )
328 }
329
330 return (
331 <Box flexDirection="column">
332 {list.length === 0 && <Text dimColor>No services started by Claude are running.</Text>}
333 {list.map(service => (
334 <Box key={`row-${service.id}`}>
335 <Text>
336 {service.check === null ? '?' : '●'} {service.label}
337 </Text>
338 <Text dimColor>
339 {' '}
340 {shortPath(service.cwd, home)} · since {clockTime(service.startedAt)}
341 {' '}
342 </Text>
343 <Button key={`stop-${service.id}`} label="Stop" onPress={() => inBackground($, () => stopService($, service))} />
344 {service.check === null && (
345 <Button key={`forget-${service.id}`} dimColor label="Forget" onPress={() => forget($, service.id)} />
346 )}
347 </Box>
348 ))}
349
350 {running && <Text dimColor>Working…</Text>}
351 {!running && text.length > 0 && (
352 <Box marginTop={1}>
353 <Text>{text}</Text>
354 </Box>
355 )}
356
357 <Box marginTop={1}>
358 {list.length > 1 && <Button key="stop-all" label="Stop all" onPress={() => inBackground($, () => stopAll($))} />}
359 <Button key="refresh" dimColor label="Refresh" onPress={() => inBackground($, async () => `${(await refresh($)).length} running`)} />
360 <Button key="close" role="dismiss" dimColor label="Close" onPress={() => $.ui.close({ id: PANE })} />
361 </Box>
362 </Box>
363 )
364 })
365
366 // The terminal draws the mode labels itself, so the label joins them there.
367 // On the desktop, status-band draws the footer from the labels it was handed,
368 // whichever order the mods load in; only a drawn tree survives that.
369 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
370 const count = (await read($, services)).length
371 if (count === 0) {
372 return next(e)
373 }
374 const label = `🐳 ${count}`
375 if (e.surface === 'terminal') {
376 return next({ ...e, props: { ...e.props, modes: [...e.props.modes, label] } })
377 }
378 if (await read($, isHubbed)) {
379 return next(e)
380 }
381 const below = await next(e)
382 const { Box, Button, Text } = $.ui.resolve(e)
383 const rest = below.type !== 'engine' ? below : e.props.modes.length === 0 ? null : <Text dimColor>{e.props.modes.join(' & ')}</Text>
384
385 // A press reaches the mod at once; /services typed mid-turn waits in the
386 // desktop app until the turn ends. The desktop draws a footer's buttons
387 // ahead of its text, so the button takes no separator.
388 return (
389 <Box flexDirection="row" alignItems="center">
390 <Button key="open-services" plain dimColor label={label} onPress={() => openServices($)} />
391 {rest}
392 </Box>
393 )
394 })
395}
396hooks/detect.ts 252 lines1import type { ServiceCheck } from '../types'
2
3export type Detected = { label: string; cwd: string; stop: string[]; check: ServiceCheck | null }
4
5const COMPOSE_GLOBAL_FLAGS = new Set(['-f', '--file', '-p', '--project-name', '--profile', '--env-file', '--project-directory'])
6
7const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'fish', 'ssh', 'sudo', 'xargs', 'eval', 'source', '.'])
8
9// A heredoc body is data for the program it is fed to; only a shell turns it
10// back into commands. Bodies fed to anything else (python3, cat, tee) are left
11// out of the check, so writing documentation that mentions commands is not
12// mistaken for running them.
13export function stripHeredocs(command: string): string {
14 const lines = command.split('\n')
15 const kept: string[] = []
16 let index = 0
17 while (index < lines.length) {
18 const line = lines[index] ?? ''
19 kept.push(line)
20 index += 1
21 const marker = /<<(-?)\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\2/.exec(line)
22 if (marker === null) {
23 continue
24 }
25 const segment = line.slice(0, marker.index).split(/&&|\|\||[;|]/).pop() ?? ''
26 const program = segment.trim().split(/\s+/).find(i => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(i)) ?? ''
27 const pipesIntoShell = /\|\s*(sudo\s+)?(ba|z|da)?sh\b/.test(line.slice(marker.index))
28 if (SHELLS.has(program.split('/').pop() ?? '') || pipesIntoShell) {
29 continue
30 }
31 const delimiter = marker[3]
32 const stripsTabs = marker[1] === '-'
33 while (index < lines.length) {
34 const body = lines[index] ?? ''
35 index += 1
36 if ((stripsTabs ? body.replace(/^\t+/, '') : body) === delimiter) {
37 kept.push(body)
38 break
39 }
40 }
41 }
42
43 return kept.join('\n')
44}
45
46// Prefixes that run the next word as the actual program.
47const WRAPPERS = new Set(['sudo', 'nohup', 'command', 'exec', 'time', 'env', 'setsid', 'caffeinate'])
48
49function splitSegments(command: string): string[] {
50 return command
51 .split(/&&|\|\||[;|\n]/)
52 .map(i => i.trim())
53 .filter(i => i.length > 0)
54}
55
56function tokenize(segment: string): string[] {
57 const raw = (segment.match(/"[^"]*"|'[^']*'|\S+/g) ?? []).map(i => i.replace(/^(["'])(.*)\1$/, '$2'))
58 // Redirections (`2>&1`, `> log`, `2>/dev/null`) and a trailing `&` belong to
59 // the shell, not to the program; read as arguments they would turn into a
60 // bogus Colima profile or container name.
61 const tokens: string[] = []
62 for (let index = 0; index < raw.length; index += 1) {
63 const token = raw[index] ?? ''
64 if (token === '&') {
65 continue
66 }
67 if (/^(\d*|&)(>>?|<)$/.test(token)) {
68 index += 1
69 continue
70 }
71 if (/^(\d*|&)(>>?|<)\S/.test(token)) {
72 continue
73 }
74 tokens.push(token)
75 }
76 let start = 0
77 while (start < tokens.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[start] ?? '') || WRAPPERS.has(tokens[start] ?? ''))) {
78 start += 1
79 }
80
81 return tokens.slice(start)
82}
83
84export function resolvePath(base: string, target: string, home: string): string {
85 if (target === '~' || target.startsWith('~/')) {
86 return `${home}${target.slice(1)}`
87 }
88 if (target.startsWith('/')) {
89 return target
90 }
91 const parts = base.split('/')
92 for (const part of target.split('/')) {
93 if (part === '..') {
94 parts.pop()
95 } else if (part !== '.' && part !== '') {
96 parts.push(part)
97 }
98 }
99
100 return parts.join('/') || '/'
101}
102
103function folderName(path: string): string {
104 return path.split('/').filter(i => i.length > 0).pop() ?? path
105}
106
107function detectCompose(args: readonly string[], cwd: string): Detected | null {
108 const globalFlags: string[] = []
109 let index = 0
110 while (index < args.length && args[index]?.startsWith('-')) {
111 const flag = args[index] ?? ''
112 globalFlags.push(flag)
113 if (COMPOSE_GLOBAL_FLAGS.has(flag) && args[index + 1] !== undefined) {
114 globalFlags.push(args[index + 1] ?? '')
115 index += 1
116 }
117 index += 1
118 }
119 const verb = args[index]
120 const verbArgs = args.slice(index + 1)
121 const isDetachedUp = verb === 'up' && verbArgs.some(i => i === '-d' || i === '--detach' || /^-[a-z]*d[a-z]*$/.test(i))
122 if (!isDetachedUp && verb !== 'start') {
123 return null
124 }
125 const projectIndex = globalFlags.findIndex(i => i === '-p' || i === '--project-name')
126 const project = projectIndex === -1 ? folderName(cwd) : globalFlags[projectIndex + 1] ?? folderName(cwd)
127
128 return {
129 label: `docker compose: ${project}`,
130 cwd,
131 // `up` created the containers, so `down` removes them again; `start` only
132 // resumed existing ones, which `stop` leaves in place.
133 stop: ['docker', 'compose', ...globalFlags, verb === 'start' ? 'stop' : 'down'],
134 check: { argv: ['docker', 'compose', ...globalFlags, 'ps', '--status', 'running', '-q'], rule: 'output' },
135 }
136}
137
138function detectDockerRun(args: readonly string[], cwd: string, output: string): Detected | null {
139 if (!args.some(i => i === '-d' || i === '--detach' || /^-[a-z]*d[a-z]*$/.test(i))) {
140 return null
141 }
142 const nameIndex = args.findIndex(i => i === '--name')
143 const inlineName = args.find(i => i.startsWith('--name='))?.slice('--name='.length)
144 const name = inlineName ?? (nameIndex === -1 ? undefined : args[nameIndex + 1])
145 const containerId = /^([0-9a-f]{12,64})\s*$/m.exec(output)?.[1]
146 const reference = name ?? containerId?.slice(0, 12)
147 if (reference === undefined) {
148 return null
149 }
150
151 return {
152 label: `docker container: ${reference}`,
153 cwd,
154 stop: ['docker', 'stop', reference],
155 check: { argv: ['docker', 'ps', '-q', '--filter', name === undefined ? `id=${reference}` : `name=^${name}$`], rule: 'output' },
156 }
157}
158
159export function detectServices(command: string, startCwd: string, home: string, output: string): Detected[] {
160 const found: Detected[] = []
161 let cwd = startCwd
162
163 for (const segment of splitSegments(stripHeredocs(command))) {
164 const [tool, ...args] = tokenize(segment)
165 if (tool === undefined) {
166 continue
167 }
168 if (tool === 'cd') {
169 cwd = resolvePath(cwd, args[0] ?? '~', home)
170 continue
171 }
172
173 if (tool === 'docker' && args[0] === 'start') {
174 for (const name of args.slice(1).filter(i => !i.startsWith('-'))) {
175 found.push({
176 label: `docker container: ${name}`,
177 cwd,
178 stop: ['docker', 'stop', name],
179 check: { argv: ['docker', 'ps', '-q', '--filter', `name=^${name}$`], rule: 'output' },
180 })
181 }
182 continue
183 }
184
185 let detected: Detected | null = null
186 if (tool === 'docker' && args[0] === 'compose') {
187 detected = detectCompose(args.slice(1), cwd)
188 } else if (tool === 'docker-compose') {
189 detected = detectCompose(args, cwd)
190 } else if (tool === 'docker' && args[0] === 'run') {
191 detected = detectDockerRun(args.slice(1), cwd, output)
192 } else if (tool === 'colima' && args[0] === 'start') {
193 const profileIndex = args.findIndex(i => i === '-p' || i === '--profile')
194 const profile = profileIndex === -1 ? args.slice(1).find(i => !i.startsWith('-')) : args[profileIndex + 1]
195 const profileArgs = profile === undefined ? [] : [profile]
196 detected = {
197 label: profile === undefined ? 'colima' : `colima: ${profile}`,
198 cwd,
199 stop: ['colima', 'stop', ...profileArgs],
200 check: { argv: ['colima', 'status', ...profileArgs], rule: 'exit-zero' },
201 }
202 } else if (tool === 'brew' && args[0] === 'services' && ['start', 'run', 'restart'].includes(args[1] ?? '')) {
203 const formula = args.slice(2).find(i => !i.startsWith('-'))
204 if (formula !== undefined) {
205 detected = {
206 label: `brew service: ${formula}`,
207 cwd,
208 stop: ['brew', 'services', 'stop', formula],
209 check: { argv: ['brew', 'services', 'info', formula, '--json'], rule: 'brew' },
210 }
211 }
212 } else if (tool === 'launchctl' && args[0] === 'bootstrap' && args[1] !== undefined && args[2] !== undefined) {
213 const absolute = resolvePath(cwd, args[2], home)
214 detected = { label: `launch agent: ${folderName(absolute)}`, cwd, stop: ['launchctl', 'bootout', args[1], absolute], check: null }
215 } else if (tool === 'launchctl' && args[0] === 'load') {
216 const path = args.slice(1).find(i => !i.startsWith('-'))
217 if (path !== undefined) {
218 const absolute = resolvePath(cwd, path, home)
219 detected = { label: `launch agent: ${folderName(absolute)}`, cwd, stop: ['launchctl', 'unload', absolute], check: null }
220 }
221 }
222
223 if (detected !== null) {
224 found.push(detected)
225 }
226 }
227
228 return found
229}
230
231export function isRunning(rule: ServiceCheck['rule'], exitCode: number, stdout: string): boolean {
232 switch (rule) {
233 case 'exit-zero':
234 return exitCode === 0
235 case 'output':
236 return exitCode === 0 && stdout.trim().length > 0
237 case 'brew':
238 try {
239 const parsed = JSON.parse(stdout) as Array<{ running?: boolean }>
240
241 return parsed.some(i => i.running === true)
242 } catch {
243 return false
244 }
245 }
246}
247
248// Commands that may end a tracked service; after one of them every service is checked again.
249export function mayStopServices(command: string): boolean {
250 return /\b(down|stop|kill|unload|bootout|rm|prune)\b/.test(command)
251}
252hooks/hub.ts 12 lines1// mod-hub's contract, restated: listed under dependencies, it would keep this
2// mod from loading where mod-hub is not installed.
3export type HubEntry = {
4 icon: string
5 title: string
6 status: string
7 attention: 'none' | 'info' | 'warning'
8 actions: { key: string; label: string }[]
9}
10
11export type HubCall = { hub: { set: (entry: HubEntry & { id: string }) => Promise<void> } }
12hooks/look.ts 61 lines1import type { Service } from '../types'
2import { PAD, escape, fitText, frame, svgDocument } from './svg'
3import type { Card } from './svg'
4
5export { buttonWidthOf, headerCard } from './svg'
6export type { Card } from './svg'
7
8const HEIGHT = 66
9
10export function shortPath(path: string, home: string | undefined): string {
11 return home !== undefined && path.startsWith(home) ? `~${path.slice(home.length)}` : path
12}
13
14export function clockTime(timestamp: number): string {
15 const date = new Date(timestamp)
16
17 return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
18}
19
20export function durationOf(milliseconds: number): string {
21 const minutes = Math.max(0, Math.floor(milliseconds / 60_000))
22 if (minutes < 1) {
23 return 'just started'
24 }
25 if (minutes < 60) {
26 return `${minutes} min`
27 }
28 const hours = Math.floor(minutes / 60)
29
30 return hours < 24 ? `${hours} h ${minutes % 60} min` : `${Math.floor(hours / 24)} d ${hours % 24} h`
31}
32
33// `reserve` keeps the text clear of the native buttons laid over the card's
34// right edge, which the picture cannot know of.
35export function serviceCard(width: number, service: Service, context: { home: string | undefined; now: number; reserve: number }): Card {
36 const isKnown = service.check !== null
37 const textX = PAD + 30
38 const maxWidth = width - textX - PAD - context.reserve
39 const meta = [
40 shortPath(service.cwd, context.home),
41 `since ${clockTime(service.startedAt)}`,
42 isKnown ? durationOf(context.now - service.startedAt) : 'not checkable',
43 ].join(' · ')
44 const dotX = PAD + 8
45 const dotY = HEIGHT / 2
46 const tone = isKnown ? 'success' : 'warning'
47 const body = [
48 frame(width, HEIGHT, 'card'),
49 isKnown ? `<circle class="${tone} ripple" cx="${dotX}" cy="${dotY}" r="5"/>` : '',
50 `<circle class="${tone}" cx="${dotX}" cy="${dotY}" r="5"/>`,
51 `<text class="t" x="${textX}" y="${dotY - 4}" font-size="14" font-weight="650">${escape(fitText(service.label, maxWidth, 14, true))}</text>`,
52 `<text class="muted" x="${textX}" y="${dotY + 15}" font-size="12.5">${escape(fitText(meta, maxWidth, 12.5))}</text>`,
53 ]
54
55 return {
56 height: HEIGHT,
57 alt: `${service.label}: ${isKnown ? 'running' : 'state unknown'}, ${meta}`,
58 source: svgDocument(width, HEIGHT, body.join('')),
59 }
60}
61hooks/svg.ts 603 lines1// An SVG drawn as an image cannot lay out text: no wrapping, no Markdown, no
2// measuring. This module does that by estimate and stacks the result into
3// cards. Every mod with desktop cards carries the same copy of this file.
4
5export type Run = { text: string; isBold?: boolean; isItalic?: boolean; isCode?: boolean; isLink?: boolean }
6
7export type Block =
8 | { kind: 'paragraph'; runs: Run[] }
9 | { kind: 'heading'; runs: Run[] }
10 | { kind: 'quote'; runs: Run[] }
11 | { kind: 'item'; marker: string; runs: Run[] }
12 | { kind: 'code'; lines: string[] }
13
14export const SANS = '-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif'
15export const MONO = 'ui-monospace,SFMono-Regular,Menlo,monospace'
16
17// Classes rather than colors: drawn as an image the SVG follows the light or
18// dark color scheme by itself, which a color handed in from the hook could not.
19export const STYLE = `<style>
20text{font-family:${SANS};white-space:pre}.mono{font-family:${MONO}}
21.card{fill:#f7f6f3;stroke:#e5e3de}.card-accent{fill:#fbf1ec;stroke:#e7b49c}.card-success{fill:#f1f8f3;stroke:#a9d6b8}
22.card-warning{fill:#fcf6e6;stroke:#e6cf8a}.card-error{fill:#fcefee;stroke:#e8aaa6}
23.tile{fill:#ffffff;stroke:#e5e3de}.tile-accent{fill:#ffffff;stroke:#d97757}.tile-success{fill:#ffffff;stroke:#2e9e5b}
24.t{fill:#1f1e1d}.muted{fill:#77756f}.eyebrow{fill:#c9643f}.code{fill:#a2482a}.link{fill:#c9643f}
25.success{fill:#2e9e5b}.warning{fill:#a87a06}.error{fill:#c0392b}.accent{fill:#d97757}.on-accent{fill:#ffffff}
26.badge{fill:#ecebe7}.badge-t{fill:#4a4844}.codebg{fill:#efede8}.rule{fill:#dad7d0}.pill{fill:#f6e1d7}.pill-success{fill:#dcefe2}
27.open{fill:#e4e2dc}.answered{fill:#2e9e5b}.skipped{fill:#d4a017}.current{fill:#d97757}
28.current,.pulse{animation:pulse 1.8s ease-in-out infinite}@keyframes pulse{50%{opacity:.5}}
29.ripple{transform-box:fill-box;transform-origin:center;animation:ripple 2.4s ease-out infinite}@keyframes ripple{0%{transform:scale(1);opacity:.45}100%{transform:scale(2.8);opacity:0}}
30.spin{transform-box:fill-box;transform-origin:center;animation:spin .9s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}
31.dot{animation:dot 1.2s ease-in-out infinite}.dot2{animation-delay:.2s}.dot3{animation-delay:.4s}@keyframes dot{0%,80%,100%{opacity:.25}40%{opacity:1}}
32@media (prefers-color-scheme: dark){
33.card{fill:#262625;stroke:#363632}.card-accent{fill:#2e2420;stroke:#7a4a36}.card-success{fill:#1f2a23;stroke:#2f5a3d}
34.card-warning{fill:#2c2717;stroke:#6a5a24}.card-error{fill:#2e1f1e;stroke:#6e3430}
35.tile{fill:#1e1e1d;stroke:#3a3a36}.tile-accent{fill:#1e1e1d;stroke:#e08a6a}.tile-success{fill:#1e1e1d;stroke:#3fb36b}
36.t{fill:#ecebe8}.muted{fill:#a5a39d}.eyebrow{fill:#e8916f}.code{fill:#f0a283}.link{fill:#e8916f}
37.success{fill:#4cc27a}.warning{fill:#e2b33c}.error{fill:#e8746a}.accent{fill:#e08a6a}.on-accent{fill:#1f1e1d}
38.badge{fill:#34342f}.badge-t{fill:#d6d4cf}.codebg{fill:#1c1c1b}.rule{fill:#45443f}.pill{fill:#4a3328}.pill-success{fill:#24432f}
39.open{fill:#3a3a37}.answered{fill:#3fb36b}.skipped{fill:#d4a017}.current{fill:#e08a6a}}
40@media (prefers-reduced-motion: reduce){.current,.pulse,.dot,.ripple,.spin{animation:none}}
41</style>`
42
43// Widths are estimated from the font size, on the wide side: a line then ends
44// a little early rather than past the card's edge.
45export function textWidth(text: string, size: number, isBold = false, isMono = false): number {
46 if (isMono) {
47 return Array.from(text).length * size * 0.62
48 }
49 let units = 0
50 for (const char of text) {
51 if (/[\s.,:;'|!ijlI]/u.test(char)) {
52 units += 0.3
53 } else if (/[A-Z@%&MWmw]/u.test(char)) {
54 units += 0.74
55 } else if (/\p{Extended_Pictographic}/u.test(char)) {
56 units += 1.15
57 } else {
58 units += 0.53
59 }
60 }
61
62 return units * size * (isBold ? 1.04 : 1)
63}
64
65function runWidth(run: Run, size: number): number {
66 return textWidth(run.text, size, run.isBold === true, run.isCode === true)
67}
68
69export function fitText(text: string, maxWidth: number, size: number, isBold = false): string {
70 if (textWidth(text, size, isBold) <= maxWidth) {
71 return text
72 }
73 const chars = Array.from(text)
74 while (chars.length > 0 && textWidth(`${chars.join('')}…`, size, isBold) > maxWidth) {
75 chars.pop()
76 }
77
78 return `${chars.join('').trimEnd()}…`
79}
80
81export function escape(text: string): string {
82 return text.replace(/&/gu, '&').replace(/</gu, '<').replace(/>/gu, '>').replace(/"/gu, '"')
83}
84
85const INLINE = /(\*\*[^*]+?\*\*|__[^_]+?__|`[^`]+`|\[[^\]]+\]\([^)\s]+\)|(?<![\w*])\*(?!\s)[^*]+?(?<!\s)\*(?!\w))/gu
86
87export function parseInline(text: string): Run[] {
88 const runs: Run[] = []
89 let last = 0
90 for (const match of text.matchAll(INLINE)) {
91 const [token] = match
92 if (match.index > last) {
93 runs.push({ text: text.slice(last, match.index) })
94 }
95 if (token.startsWith('**') || token.startsWith('__')) {
96 runs.push(...parseInline(token.slice(2, -2)).map(i => ({ ...i, isBold: true })))
97 } else if (token.startsWith('`')) {
98 runs.push({ text: token.slice(1, -1), isCode: true })
99 } else if (token.startsWith('[')) {
100 runs.push({ text: token.slice(1, token.indexOf('](')), isLink: true })
101 } else {
102 runs.push(...parseInline(token.slice(1, -1)).map(i => ({ ...i, isItalic: true })))
103 }
104 last = match.index + token.length
105 }
106 if (last < text.length) {
107 runs.push({ text: text.slice(last) })
108 }
109
110 return runs.filter(i => i.text.length > 0)
111}
112
113export function plainOf(text: string): string {
114 return parseInline(text)
115 .map(i => i.text)
116 .join('')
117}
118
119const ITEM = /^\s*([-*•+]|\d{1,3}[.)])\s+(.*)$/u
120const HEADING = /^\s{0,3}#{1,6}\s+(.*)$/u
121const QUOTE = /^\s*>\s?(.*)$/u
122const FENCE = /^\s*(```|~~~)/u
123
124// Single line breaks join a paragraph, as Markdown reads them; a list item,
125// heading, quote or code fence starts a block of its own.
126export function parseBlocks(markdown: string): Block[] {
127 const blocks: Block[] = []
128 let paragraph: string[] = []
129 let item: { marker: string; text: string[] } | null = null
130 let quote: string[] = []
131 const flush = () => {
132 if (paragraph.length > 0) {
133 blocks.push({ kind: 'paragraph', runs: parseInline(paragraph.join(' ')) })
134 }
135 if (item !== null) {
136 blocks.push({ kind: 'item', marker: item.marker, runs: parseInline(item.text.join(' ')) })
137 }
138 if (quote.length > 0) {
139 blocks.push({ kind: 'quote', runs: parseInline(quote.join(' ')) })
140 }
141 paragraph = []
142 item = null
143 quote = []
144 }
145 const lines = markdown.replace(/\r\n?/gu, '\n').split('\n')
146 for (let index = 0; index < lines.length; index++) {
147 const line = lines[index] ?? ''
148 if (FENCE.test(line)) {
149 flush()
150 const code: string[] = []
151 index += 1
152 while (index < lines.length && !FENCE.test(lines[index] ?? '')) {
153 code.push(lines[index] ?? '')
154 index += 1
155 }
156 blocks.push({ kind: 'code', lines: code })
157 continue
158 }
159 if (line.trim().length === 0) {
160 flush()
161 continue
162 }
163 const heading = HEADING.exec(line)
164 if (heading !== null) {
165 flush()
166 blocks.push({ kind: 'heading', runs: parseInline(heading[1] ?? '') })
167 continue
168 }
169 const listed = ITEM.exec(line)
170 if (listed !== null) {
171 flush()
172 const marker = listed[1] ?? '-'
173 item = { marker: /\d/u.test(marker) ? marker : '•', text: [listed[2] ?? ''] }
174 continue
175 }
176 const quoted = QUOTE.exec(line)
177 if (quoted !== null) {
178 if (quote.length === 0) {
179 flush()
180 }
181 quote.push(quoted[1] ?? '')
182 continue
183 }
184 if (item !== null && /^\s+\S/u.test(line)) {
185 item.text.push(line.trim())
186 continue
187 }
188 if (item !== null || quote.length > 0) {
189 flush()
190 }
191 paragraph.push(line.trim())
192 }
193 flush()
194
195 return blocks
196}
197
198type Word = Run & { hasSpace: boolean }
199
200function wordsOf(runs: readonly Run[]): Word[] {
201 const words: Word[] = []
202 for (const run of runs) {
203 for (const piece of run.text.split(/(\s+)/u)) {
204 if (piece.length === 0) {
205 continue
206 }
207 if (/^\s+$/u.test(piece)) {
208 const previous = words.at(-1)
209 if (previous !== undefined) {
210 previous.hasSpace = true
211 }
212 continue
213 }
214 words.push({ ...run, text: piece, hasSpace: false })
215 }
216 }
217
218 return words
219}
220
221function sameStyle(first: Run, second: Run): boolean {
222 return first.isBold === second.isBold && first.isItalic === second.isItalic && first.isCode === second.isCode && first.isLink === second.isLink
223}
224
225function breakWord(word: Word, maxWidth: number, size: number): Word[] {
226 const pieces: Word[] = []
227 let current = ''
228 for (const char of word.text) {
229 if (current.length > 0 && runWidth({ ...word, text: current + char }, size) > maxWidth) {
230 pieces.push({ ...word, text: current, hasSpace: false })
231 current = ''
232 }
233 current += char
234 }
235 pieces.push({ ...word, text: current })
236
237 return pieces
238}
239
240// Greedy, word by word; a word wider than the line is broken by characters.
241// `firstWidth` keeps the first line clear of a badge drawn at its end.
242export function wrapRuns(runs: readonly Run[], maxWidth: number, size: number, firstWidth = maxWidth): Run[][] {
243 const lines: Word[][] = []
244 let line: Word[] = []
245 let width = 0
246 const space = textWidth(' ', size)
247 const words = wordsOf(runs).flatMap(i => (runWidth(i, size) > maxWidth ? breakWord(i, maxWidth, size) : [i]))
248 for (const word of words) {
249 const previous = line.at(-1)
250 const gap = previous?.hasSpace === true ? space : 0
251 const wordWidth = runWidth(word, size)
252 if (line.length > 0 && width + gap + wordWidth > (lines.length === 0 ? firstWidth : maxWidth)) {
253 lines.push(line)
254 line = []
255 width = 0
256 }
257 width += (line.length > 0 ? gap : 0) + wordWidth
258 line.push(word)
259 }
260 if (line.length > 0) {
261 lines.push(line)
262 }
263
264 // The space after a code span is drawn in the text's font, not the code's
265 // wider one.
266 return lines.map(words => {
267 const merged: Run[] = []
268 const append = (run: Run) => {
269 const previous = merged.at(-1)
270 if (previous !== undefined && sameStyle(previous, run)) {
271 previous.text += run.text
272 } else {
273 merged.push({ ...run })
274 }
275 }
276 words.forEach((word, index) => {
277 const { hasSpace, ...run } = word
278 const hasGap = hasSpace && index < words.length - 1
279 if (run.isCode === true) {
280 append(run)
281 if (hasGap) {
282 append({ text: ' ' })
283 }
284 } else {
285 append({ ...run, text: run.text + (hasGap ? ' ' : '') })
286 }
287 })
288
289 return merged
290 })
291}
292
293// Cuts wrapped lines to `maxLines`, the last one ending in an ellipsis.
294export function clampLines(lines: Run[][], maxLines: number, maxWidth: number, size: number): Run[][] {
295 if (lines.length <= maxLines) {
296 return lines
297 }
298 const kept = lines.slice(0, maxLines)
299 const last = kept[maxLines - 1] ?? []
300 const text = last.map(i => i.text).join('')
301 kept[maxLines - 1] = [{ ...(last[0] ?? { text: '' }), text: fitText(`${text}…`, maxWidth, size, last[0]?.isBold === true) }]
302
303 return kept
304}
305
306export function lineSvg(runs: readonly Run[], x: number, y: number, size: number, tone = 't', weight?: number): string {
307 const spans = runs.map(run => {
308 const classes = run.isCode ? 'code' : run.isLink ? 'link' : tone
309 const attributes = [
310 `class="${classes}"`,
311 run.isBold === true || weight !== undefined ? `font-weight="${run.isBold === true ? 650 : weight}"` : '',
312 run.isItalic === true ? 'font-style="italic"' : '',
313 run.isCode === true ? `font-family="${MONO}" font-size="${(size * 0.92).toFixed(1)}"` : '',
314 run.isLink === true ? 'text-decoration="underline"' : '',
315 ].filter(i => i.length > 0)
316
317 return `<tspan ${attributes.join(' ')}>${escape(run.text)}</tspan>`
318 })
319
320 return `<text x="${x}" y="${y.toFixed(1)}" font-size="${size}">${spans.join('')}</text>`
321}
322
323// A pane reports its width in columns only; about 8 CSS pixels each, as
324// savvy-progress measures it, minus the pane's own inset.
325export function cardWidthOf(columns: number): number {
326 return Math.max(240, Math.min(900, (columns || 40) * 8 - 8))
327}
328
329// The columns a native control laid over a card is pushed in by to clear
330// `pixels` of the card, at the same 8 pixels per column.
331export function columnsOf(pixels: number): number {
332 return Math.ceil(pixels / 8)
333}
334
335// About how wide the desktop draws a row of native buttons with these labels,
336// for text that has to keep clear of buttons laid over a card.
337export function buttonWidthOf(labels: readonly string[]): number {
338 return labels.reduce((sum, label) => sum + textWidth(label, 13) + 30, 0) + Math.max(0, labels.length - 1) * 8
339}
340
341export function svgDocument(width: number, height: number, body: string): string {
342 return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">${STYLE}${body}</svg>`
343}
344
345export type Segment = 'answered' | 'skipped' | 'current' | 'open'
346
347export type Card = { source: string; height: number; alt: string }
348
349export type Variant = 'card' | 'card-accent' | 'card-success' | 'card-warning' | 'card-error'
350
351export type Section = { height: number; draw: (y: number) => string }
352
353export const PAD = 18
354export const SIZE = 14
355export const LINE = 21
356export const EYEBROW = 11
357export const RADIUS = 14
358
359// The engine refuses an Svg taller than 4096 pixels; a longer card is cut
360// between sections into several cards of the same look.
361export const MAX_HEIGHT = 4000
362
363export function baseline(y: number, line: number, lineHeight = LINE): number {
364 return y + line * lineHeight + lineHeight * 0.72
365}
366
367export function frame(width: number, height: number, variant: Variant): string {
368 return `<rect class="${variant}" x="0.5" y="0.5" width="${width - 1}" height="${height - 1}" rx="${RADIUS}"/>`
369}
370
371export function eyebrowSvg(text: string, x: number, y: number, tone = 'eyebrow', anchor = 'start'): string {
372 return `<text class="${tone}" x="${x}" y="${y}" font-size="${EYEBROW}" font-weight="700" letter-spacing="1.1" text-anchor="${anchor}">${escape(text)}</text>`
373}
374
375export function eyebrowWidth(text: string): number {
376 return textWidth(text, EYEBROW, true) + text.length * 1.1
377}
378
379export function textSection(
380 runs: readonly Run[],
381 x: number,
382 maxWidth: number,
383 options: { tone?: string; size?: number; maxLines?: number; weight?: number; firstWidth?: number } = {},
384): Section {
385 const size = options.size ?? SIZE
386 const lineHeight = Math.round(size * 1.5)
387 const wrapped = wrapRuns(runs, maxWidth, size, options.firstWidth)
388 const lines = options.maxLines === undefined ? wrapped : clampLines(wrapped, options.maxLines, maxWidth, size)
389
390 return {
391 height: lines.length * lineHeight,
392 draw: y => lines.map((line, index) => lineSvg(line, x, baseline(y, index, lineHeight), size, options.tone, options.weight)).join(''),
393 }
394}
395
396export function codeSection(lines: readonly string[], x: number, maxWidth: number): Section {
397 const size = 12.5
398 const lineHeight = 18
399 const perLine = Math.max(8, Math.floor((maxWidth - 24) / (size * 0.62)))
400 const rows = lines.flatMap(line => {
401 const chars = Array.from(line)
402 const pieces: string[] = []
403 for (let index = 0; index < Math.max(1, chars.length); index += perLine) {
404 pieces.push(chars.slice(index, index + perLine).join(''))
405 }
406
407 return pieces
408 })
409
410 return {
411 height: rows.length * lineHeight + 20,
412 draw: y =>
413 `<rect class="codebg" x="${x}" y="${y}" width="${maxWidth}" height="${rows.length * lineHeight + 20}" rx="8"/>` +
414 rows.map((row, index) => lineSvg([{ text: row, isCode: true }], x + 12, baseline(y + 10, index, lineHeight), size / 0.92)).join(''),
415 }
416}
417
418export function blockSection(block: Block, x: number, maxWidth: number): Section {
419 switch (block.kind) {
420 case 'code':
421 return codeSection(block.lines, x, maxWidth)
422 case 'heading':
423 return textSection(block.runs, x, maxWidth, { size: SIZE + 1.5, weight: 650 })
424 case 'quote': {
425 const text = textSection(block.runs, x + 14, maxWidth - 14, { tone: 'muted' })
426
427 return { height: text.height, draw: y => `<rect class="rule" x="${x}" y="${y + 2}" width="3" height="${text.height - 4}" rx="1.5"/>${text.draw(y)}` }
428 }
429 case 'item': {
430 const indent = block.marker === '•' ? 16 : textWidth(block.marker, SIZE) + 8
431 const text = textSection(block.runs, x + indent, maxWidth - indent)
432
433 return {
434 height: text.height,
435 draw: y => `<text class="muted" x="${x + (block.marker === '•' ? 3 : 0)}" y="${baseline(y, 0).toFixed(1)}" font-size="${SIZE}">${escape(block.marker)}</text>${text.draw(y)}`,
436 }
437 }
438 default:
439 return textSection(block.runs, x, maxWidth)
440 }
441}
442
443// Paragraphs sit further apart than the items of one list.
444export function blockSections(blocks: readonly Block[], x: number, maxWidth: number): Section[] {
445 return blocks.map((block, index) => {
446 const section = blockSection(block, x, maxWidth)
447 const previous = blocks[index - 1]
448 const spacing = index === 0 ? 0 : previous?.kind === 'item' && block.kind === 'item' ? 4 : 10
449
450 return { height: section.height + spacing, draw: y => section.draw(y + spacing) }
451 })
452}
453
454// Stacks sections inside one frame; past MAX_HEIGHT the rest go on in a next one.
455// `minHeight` keeps a short card tall enough for native controls laid over it.
456export function cards(width: number, variant: Variant, sections: readonly Section[], alt: string, decoration = '', minHeight = 0): Card[] {
457 const result: Card[] = []
458 let pending: Section[] = []
459 let used = 2 * PAD
460 const close = () => {
461 if (pending.length === 0) {
462 return
463 }
464 let y = PAD
465 const body = pending.map(section => {
466 const drawn = section.draw(y)
467 y += section.height
468
469 return drawn
470 })
471 const natural = Math.ceil(y + PAD)
472 const height = result.length === 0 ? Math.max(natural, minHeight) : natural
473 result.push({ height, alt, source: svgDocument(width, height, frame(width, height, variant) + (result.length === 0 ? decoration : '') + body.join('')) })
474 pending = []
475 used = 2 * PAD
476 }
477 for (const section of sections) {
478 if (pending.length > 0 && used + section.height > MAX_HEIGHT) {
479 close()
480 }
481 pending.push(section)
482 used += section.height
483 }
484 close()
485
486 return result
487}
488
489export const GLOW =
490 '<defs><linearGradient id="glow" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#d97757" stop-opacity="0.14"/><stop offset="0.55" stop-color="#d97757" stop-opacity="0"/></linearGradient></defs>'
491
492// The card heading a pane: an eyebrow, a count at the right, a title of up
493// to two lines and, given segments, a bar with one segment per step.
494// `reserve` keeps the title clear of native buttons laid over the right side;
495// a card without a bar is too low for them beside the count at its top right,
496// so the count then goes beneath the title.
497export function headerCard(card: { width: number; eyebrow: string; title: string; counter: string; segments?: readonly Segment[]; reserve?: number }): Card {
498 const { width } = card
499 const segments = card.segments ?? []
500 const inner = width - 2 * PAD
501 const reserve = card.reserve ?? 0
502 const isCountBelow = reserve > 0 && segments.length === 0
503 const counterWidth = isCountBelow ? 0 : textWidth(card.counter, 12)
504 const eyebrow = fitText(card.eyebrow, inner - counterWidth - 16 - (isCountBelow ? reserve : 0), EYEBROW, true)
505 const title = textSection(parseInline(card.title).map(i => ({ ...i, isBold: true })), PAD, inner - reserve, { size: 17, maxLines: 2 })
506 const titleTop = PAD + EYEBROW + 8
507 const countY = titleTop + title.height + 14
508 const barY = titleTop + title.height + 12
509 const height = isCountBelow ? countY + PAD - 2 : segments.length === 0 ? titleTop + title.height + PAD - 4 : barY + 6 + PAD
510 const count = Math.max(1, segments.length)
511 const segmentWidth = (inner - 4 * (count - 1)) / count
512 const bars = segments.map(
513 (segment, index) => `<rect class="${segment}" x="${(PAD + index * (segmentWidth + 4)).toFixed(1)}" y="${barY}" width="${segmentWidth.toFixed(1)}" height="6" rx="3"/>`,
514 )
515 const body = [
516 frame(width, height, 'card'),
517 GLOW,
518 `<rect x="0.5" y="0.5" width="${width - 1}" height="${height - 1}" rx="${RADIUS}" fill="url(#glow)"/>`,
519 eyebrowSvg(eyebrow, PAD, PAD + EYEBROW),
520 isCountBelow
521 ? `<text class="muted" x="${PAD}" y="${countY}" font-size="12.5">${escape(fitText(card.counter, inner - reserve, 12.5))}</text>`
522 : `<text class="muted" x="${width - PAD}" y="${PAD + EYEBROW}" font-size="12" text-anchor="end">${escape(card.counter)}</text>`,
523 title.draw(titleTop),
524 ...bars,
525 ]
526
527 return { height, alt: `${card.eyebrow}: ${plainOf(card.title)}, ${card.counter}`, source: svgDocument(width, height, body.join('')) }
528}
529
530export function noticeCard(width: number, variant: 'card-warning' | 'card-error', title: string, text: string, reserve = 0): Card[] {
531 const inner = width - 2 * PAD - reserve
532 const body = textSection([{ text }], PAD, inner, { tone: 'muted' })
533 const sections = [textSection([{ text: title, isBold: true }], PAD, inner, { size: 15 }), { height: body.height + 6, draw: (y: number) => body.draw(y + 6) }]
534
535 return cards(width, variant, sections, `${title} ${text}`, '', reserve > 0 ? 72 : 0)
536}
537
538const FIELD_HEIGHT = 72
539
540// A card holding a native text field: its label and a hint in a column at the
541// left, the rest left free for the field laid over it. `labelWidth` is that
542// column's width; the field starts past it.
543export function fieldCard(width: number, label: string, hint: string, labelWidth: number): Card {
544 const maxWidth = labelWidth - PAD - 12
545 const hints = wrapRuns([{ text: hint }], maxWidth, 12).slice(0, 2)
546 const top = FIELD_HEIGHT / 2 - (hints.length * 16 + EYEBROW + 6) / 2 + EYEBROW
547 const body = [
548 frame(width, FIELD_HEIGHT, 'card'),
549 eyebrowSvg(fitText(label, maxWidth, EYEBROW, true), PAD, top),
550 ...hints.map((line, index) => lineSvg(line, PAD, top + 18 + index * 16, 12, 'muted')),
551 `<rect class="rule" x="${labelWidth - 6}" y="16" width="1" height="${FIELD_HEIGHT - 32}"/>`,
552 ]
553
554 return { height: FIELD_HEIGHT, alt: `${label}: ${hint}`, source: svgDocument(width, FIELD_HEIGHT, body.join('')) }
555}
556
557// Below this width a card leaves too little room beside native controls, so
558// they go beneath it instead of over it.
559export const ROOMY_WIDTH = 420
560
561// A slim card for a row of native buttons laid over it; given a label, that
562// heads the bar at its left, as a section title with its actions beside it.
563export function barCard(width: number, alt: string, label = '', variant: Variant = 'card', reserve = 0): Card {
564 const height = 56
565 const text = label.length === 0 ? '' : eyebrowSvg(fitText(label, width - 2 * PAD - reserve - 12, EYEBROW, true), PAD, height / 2 + EYEBROW / 2 - 1)
566
567 return { height, alt, source: svgDocument(width, height, frame(width, height, variant) + text) }
568}
569
570// A diff or a list of changes in the code font: added lines green, removed
571// ones red, hunk heads in the accent color. Long lines are cut, not wrapped,
572// so the columns stay aligned.
573export function diffCards(width: number, text: string, alt: string): Card[] {
574 const size = 12
575 const lineHeight = 17
576 const maxWidth = width - 2 * PAD
577 const rows = text.replace(/\s+$/u, '').split('\n')
578 const toneOf = (row: string) =>
579 /^\+(?!\+\+)/u.test(row) ? 'success' : /^-(?!--)/u.test(row) ? 'error' : /^@@/u.test(row) ? 'accent' : /^(diff |index |\+\+\+|---)/u.test(row) ? 'muted' : 't'
580 const sections: Section[] = rows.map(row => ({
581 height: lineHeight,
582 draw: y =>
583 `<text class="${toneOf(row)} mono" x="${PAD}" y="${(y + lineHeight * 0.75).toFixed(1)}" font-size="${size}">${escape(fitMono(row, maxWidth, size))}</text>`,
584 }))
585
586 return cards(width, 'card', sections, alt)
587}
588
589function fitMono(text: string, maxWidth: number, size: number): string {
590 const chars = Array.from(text.replace(/\t/gu, ' '))
591 const fits = Math.floor(maxWidth / (size * 0.62))
592
593 return chars.length <= fits ? chars.join('') : `${chars.slice(0, Math.max(1, fits - 1)).join('')}…`
594}
595
596// An eyebrow line heading a card, with an optional second one at its right.
597export function eyebrowSection(left: string, right: string | null, rightTone: string, width: number): Section {
598 return {
599 height: EYEBROW + 10,
600 draw: y => eyebrowSvg(left, PAD, y + EYEBROW) + (right === null ? '' : eyebrowSvg(right, width - PAD, y + EYEBROW, rightTone, 'end')),
601 }
602}
603types/index.d.ts 27 lines1export type ServiceCheck = {
2 argv: string[]
3 // exit-zero: running when the check exits 0; output: running when it prints anything;
4 // brew: running when `brew services info --json` reports it so.
5 rule: 'exit-zero' | 'output' | 'brew'
6}
7
8export type Service = {
9 id: string
10 label: string
11 cwd: string
12 startedAt: number
13 stop: string[]
14 check: ServiceCheck | null
15}
16
17declare module 'claude-code' {
18 interface PluginState {
19 'service-radar': {
20 services: Service[]
21 isBusy: boolean
22 message: string
23 isHubbed: boolean
24 }
25 }
26}
27