SLOPSHOPPER

dev-apps

Open, start and stop this project's browser apps from the Git panel

panecommandprocesstimer
★ 1v0.1.6MITupdated 2026-10-23Spardutti/claude-mods/plugins/dev-apps
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · dev-apps
│ ┃ dev-apps ✕ › fix the failing auth test and add an audit log call │ ┃ No browser apps for this project in │ ┃ dev-ports. ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /apps │ ⎿ dev-apps: No browser apps for this project in dev-ports. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · dev-apps
No browser apps for this project in dev-ports.
README

claude-mods

Little mods for Claude Code: panels that keep the stuff you'd normally go check next to the chat, and helpers that do the chores for you.

Claude Code 2.1.287+ mods: 5 License: MIT

Why

You spend all day in Claude Code. But the small stuff keeps pulling you out of it: checking git, rescuing a session that got too long, doing the same cleanup by hand.

These mods put that stuff inside Claude Code. Some draw a live panel next to the chat. Some do a chore for you at the right moment. You keep your eyes on the work.

Each one installs on its own, so you take only what you want.

Get started

Add the marketplace once, then install a mod:

/plugin marketplace add spardutti/claude-mods
/plugin install branch-status@spardutti-mods
/plugin install auto-handoff@spardutti-mods
/plugin install handoff-pickup@spardutti-mods
/plugin install blocked-run@spardutti-mods
/plugin install dev-apps@spardutti-mods

Install any you like. Each one starts working on the next session start.

The mods

Each mod has its own page with the full story.

ModWhat it does
branch-statusA panel with your branch, develop and main as a tiny git-flow graph, so you see what's waiting to ship without running git log.
auto-handoffWhen the context gets too full, it warns you, counts down, then hands the work to a fresh session.
handoff-pickup/pickup picks up your newest handoff, /pickup done deletes it.
blocked-runWhen auto mode blocks a command, it shows above the prompt with a button to run it yourself.
dev-appsUnder the Git panel: this project's apps, a link to open each, and Start and Stop. Stops them when you close Claude.
/plugin marketplace update spardutti-mods
/plugin update branch-status@spardutti-mods
/plugin update auto-handoff@spardutti-mods
/plugin update handoff-pickup@spardutti-mods
/plugin update blocked-run@spardutti-mods
/plugin update dev-apps@spardutti-mods
/reload-plugins
Source 9 files
hooks/register.tsx 166 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Project } from '../types'
5import { COMPOSE_PS, COMPOSE_SERVICES, LISTENING, READ_REGISTRY, checkIn, checkOut, lastError, startCommands, stopCommand } from './commands'
6import { COMPOSE_FILES, launcherFor } from './launch'
7import { drawApps, splitPane } from './panel'
8import type { PaneInput } from './panel'
9import { projectName } from './project'
10import { browserApps } from './registry'
11import { isBusy, listeningPorts, statusOf } from './running'
12import { isAnyUp, serviceNames, servicesOf } from './containers'
13
14const GIT_PANE = 'branch-status'
15// Keys the two mods tag their drawings with, so whichever runs first can stack both.
16const GIT_GRAPH = 'git-graph'
17const APPS_SECTION = 'dev-apps'
18const PANE = 'dev-apps'
19const POLL_MS = 3_000
20const project = atom({ plugin: 'dev-apps', key: 'project' } as const, null as Project | null)
21// Module state survives a /clear, which drops $.state and fires no session.start.
22let loaded: Project | null = null
23
24async function output($: EngineInterface, argv: string[], cwd?: string) {
25  const { exitCode, stdout } = await $.process.run(argv, { cwd }).catch(() => ({ exitCode: 1, stdout: '' }))
26  return exitCode === 0 ? stdout : undefined
27}
28
29const isTagged = (tree: unknown, key: string) => (tree as { props?: { key?: string } } | undefined)?.props?.key === key
30
31const readFile = ($: EngineInterface, path: string) => $.fs.read(path).catch(() => undefined)
32
33async function load($: EngineInterface, cwd: string): Promise<Project | null> {
34  const commonDir = await output($, ['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'], cwd)
35  const root = (await output($, ['git', 'rev-parse', '--show-toplevel'], cwd))?.trim() || cwd
36  const name = projectName(commonDir, cwd)
37  const apps = browserApps((await output($, READ_REGISTRY)) ?? '', name)
38  if (!apps.length) return null
39  const files = (await $.fs.list(root).catch(() => [])).map(entry => entry.name)
40  const composeFile = COMPOSE_FILES.find(file => files.includes(file))
41  const sources = {
42    compose: composeFile ? await readFile($, `${root}/${composeFile}`) : undefined,
43    env: await readFile($, `${root}/.env`),
44    pkg: files.includes('package.json') ? await readFile($, `${root}/package.json`) : undefined,
45    files,
46  }
47  const launcher = launcherFor(sources, apps.map(app => app.port))
48  if (launcher?.kind !== 'docker') return { name, root, apps, launcher, listening: [] }
49  return { name, root, apps, launcher, listening: [], serviceNames: serviceNames(await output($, COMPOSE_SERVICES, root)) }
50}
51
52async function noteFailure($: EngineInterface, shown: Project) {
53  if (!shown.launcher || shown.failure !== undefined || statusOf(false, shown, await $.clock.now()) !== 'failed') return
54  const failure = (await output($, lastError(shown.name, shown.launcher)))?.trim()
55  if (failure) await update($, project, now => now && (now.startedAt === shown.startedAt ? { ...now, failure } : now))
56}
57
58async function poll($: EngineInterface) {
59  if (loaded && !(await read($, project))) await update($, project, () => loaded)
60  const shown = await read($, project)
61  if (!shown) return
62  void $.process.run(checkIn(shown.name, await $.session.id())).catch(() => undefined)
63  const [ss, ps] = await Promise.all([output($, LISTENING), shown.serviceNames && output($, COMPOSE_PS, shown.root)])
64  const listening = listeningPorts(ss ?? '')
65  const services = shown.serviceNames && servicesOf(ps ?? '', shown.serviceNames)
66  const isAllUp = shown.apps.every(app => listening.includes(app.port))
67  const isAllDown = !shown.apps.some(app => listening.includes(app.port)) && !isAnyUp(services)
68  await update($, project, now => now && {
69    ...now,
70    listening,
71    services,
72    startedAt: isAllUp ? undefined : now.startedAt,
73    stoppingAt: isAllDown ? undefined : now.stoppingAt,
74  })
75  if (!isAllUp) await noteFailure($, shown)
76}
77
78async function start($: EngineInterface) {
79  const shown = await read($, project)
80  if (!shown?.launcher) return
81  const startedAt = await $.clock.now()
82  let isClaimed = false
83  // update retries the change on a clash, so the claim is decided again on each try.
84  await update($, project, now => {
85    isClaimed = !!now && !isBusy(now, startedAt)
86    if (!now || !isClaimed) return now
87    return { ...now, startedAt, stoppingAt: undefined, failure: undefined }
88  })
89  if (!isClaimed) return
90  const config = shown.serviceNames && (await output($, COMPOSE_SERVICES, shown.root))
91  if (config) await update($, project, now => now && { ...now, serviceNames: serviceNames(config) })
92  for (const argv of startCommands(shown.name, shown.launcher)) await $.process.run(argv, { cwd: shown.root })
93}
94
95async function stop($: EngineInterface) {
96  const shown = await read($, project)
97  if (!shown?.launcher) return
98  const stoppingAt = await $.clock.now()
99  await update($, project, now => now && { ...now, startedAt: undefined, stoppingAt })
100  await $.process.run(stopCommand(shown.name, shown.launcher), { cwd: shown.root })
101}
102
103async function stopIfLast($: EngineInterface) {
104  const shown = await read($, project)
105  if (!shown?.launcher) return
106  const left = await output($, checkOut(shown.name, await $.session.id()))
107  if (left?.trim() === 'last') await $.process.run(stopCommand(shown.name, shown.launcher), { cwd: shown.root })
108}
109
110async function apps($: EngineInterface, e: PaneInput) {
111  const shown = await read($, project)
112  if (!shown) return undefined
113  const actions = { start: () => void start($), stop: () => void stop($) }
114  return drawApps($, e, { project: shown, now: await $.clock.now(), actions })
115}
116
117async function startSession($: EngineInterface, cwd: string) {
118  await $.command.register({ name: 'apps', description: "Open, start and stop this project's browser apps" })
119  void load($, cwd).then(async found => {
120    loaded = found
121    await update($, project, () => found)
122    await poll($)
123  })
124  $.clock.every(POLL_MS, () => void poll($))
125}
126
127async function openPanel($: EngineInterface) {
128  if (!(await read($, project))) return { text: 'No browser apps for this project in dev-ports.' }
129  await $.ui.open({ id: PANE, title: 'Apps' })
130
131  return { text: 'Apps panel opened.' }
132}
133
134export const register: Register = on => {
135  on('session.start', async ($, e, next) => {
136    await startSession($, e.cwd)
137
138    return next(e)
139  })
140
141  on('command.run', { command: 'apps' }, openPanel)
142
143  // A /clear or a resume keeps Claude running, so the apps stay up.
144  on('session.end', async ($, e, next) => {
145    if (e.reason !== 'clear' && e.reason !== 'resume') await stopIfLast($)
146
147    return next(e)
148  })
149
150  on('ui.render', { component: 'Pane', requestId: GIT_PANE }, async ($, e, next) => {
151    const below = await next(e)
152    const drawn = await apps($, e)
153    if (!drawn) return below
154    if (isTagged(below, GIT_GRAPH)) return splitPane($, e, { top: below, apps: drawn })
155    const { Box } = $.ui.resolve(e)
156
157    return <Box key={APPS_SECTION} flexDirection="column">{drawn}</Box>
158  })
159
160  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
161    const { Text } = $.ui.resolve(e)
162
163    return (await apps($, e)) ?? <Text dimColor>No browser apps for this project in dev-ports.</Text>
164  })
165}
166
hooks/commands.ts 57 lines
1import type { Launcher } from '../types'
2
3// Every script takes the project as $1; its files live in this folder.
4const CACHE = '"$HOME/.cache/dev-apps/$1"'
5
6export const LOG_FOLDER = '~/.cache/dev-apps'
7
8export const READ_REGISTRY = ['sh', '-c', 'cat "${DEV_PORTS_REGISTRY:-$HOME/.config/dev-ports/registry.tsv}"']
9
10export const LISTENING = ['ss', '-ltnH']
11
12export const COMPOSE_SERVICES = ['docker', 'compose', 'config', '--services']
13
14export const COMPOSE_PS = ['docker', 'compose', 'ps', '-a', '--format', 'json']
15
16// setsid -f lets the app outlive Claude; the exec line frees the pipes so the call returns at once.
17const detached = (script: string, ...args: string[]) => ['setsid', '-f', 'sh', '-c', `mkdir -p ${CACHE} && ${script}`, 'sh', ...args]
18
19// Every watch started in this folder, by any session: a pid file loses track once a second watch dies on the lock.
20const KILL_WATCHES = `for p in $(pgrep -f "^docker compose watch"); do [ "$(readlink /proc/$p/cwd)" = "$(pwd -P)" ] || continue; kill -TERM "-$p" 2>/dev/null || kill -TERM "$p"; timeout 10 tail --pid="$p" -f /dev/null; done`
21
22const composeUp = `exec > ${CACHE}/docker.log 2>&1 < /dev/null && exec docker compose up -d`
23
24// The old watch goes before the log is emptied, or its shutdown lines land in the new log.
25const composeWatch = `exec > /dev/null 2>&1 < /dev/null && ${KILL_WATCHES}; exec > ${CACHE}/docker.log 2>&1 && exec docker compose watch`
26
27const composeDown = `exec >> ${CACHE}/docker.log 2>&1 < /dev/null || exit; ${KILL_WATCHES}; exec docker compose down`
28
29const npmRun = `exec > ${CACHE}/"$2".log 2>&1 < /dev/null && echo $$ > ${CACHE}/"$2".pid && exec "$3" run "$2"`
30
31const KILL_STARTED = `for f in ${CACHE}/*.pid; do [ -f "$f" ] && kill -TERM "-$(cat "$f")" 2>/dev/null; rm -f "$f"; done`
32
33export function startCommands(project: string, launcher: Launcher): string[][] {
34  if (launcher.kind === 'docker') return [detached(launcher.watch ? composeWatch : composeUp, project)]
35  return launcher.scripts.map(script => detached(npmRun, project, script, launcher.manager))
36}
37
38export function stopCommand(project: string, launcher: Launcher): string[] {
39  if (launcher.kind === 'docker') return detached(composeDown, project)
40  return ['sh', '-c', KILL_STARTED, 'sh', project]
41}
42
43// -a: compose's progress output makes grep call the log binary; sed drops color codes.
44const ERROR_LINE = `grep -aiE "error|failed|unhealthy|cannot|ENOTFOUND" | tail -n 1 | sed 's/\\x1b\\[[0-9;]*m//g'`
45
46export function lastError(project: string, launcher: Launcher): string[] {
47  const logs = launcher.kind === 'docker' ? ['docker'] : launcher.scripts
48  return ['sh', '-c', `cd ${CACHE} && shift && cat -- "$@" 2>/dev/null | ${ERROR_LINE}`, 'sh', project, ...logs.map(log => `${log}.log`)]
49}
50
51export const checkIn = (project: string, session: string) =>
52  ['sh', '-c', `mkdir -p ${CACHE}/sessions && touch ${CACHE}/sessions/"$2"`, 'sh', project, session]
53
54// Prints "last" when no other session checked in for this project in the last 2 minutes.
55export const checkOut = (project: string, session: string) =>
56  ['sh', '-c', `rm -f ${CACHE}/sessions/"$2"; find ${CACHE}/sessions -type f -mmin -2 | grep -q . || echo last`, 'sh', project, session]
57
hooks/launch.ts 47 lines
1import type { Launcher } from '../types'
2
3export const COMPOSE_FILES = ['compose.yaml', 'compose.yml', 'docker-compose.yaml', 'docker-compose.yml']
4
5const LOCKS: [string, string][] = [['pnpm-lock.yaml', 'pnpm'], ['bun.lock', 'bun'], ['bun.lockb', 'bun'], ['yarn.lock', 'yarn']]
6
7export type Sources = { compose?: string; env?: string; pkg?: string; files: string[] }
8
9export function envOf(text = ''): Record<string, string> {
10  const pairs = text.split('\n').map(line => /^\s*(?:export\s+)?(\w+)=["']?([^"'\r]*)["']?\s*$/.exec(line))
11  return Object.fromEntries(pairs.filter(m => m !== null).map(m => [m[1], m[2]]))
12}
13
14// ${VAR}, ${VAR:-default} and ${VAR-default}, as compose fills them from .env.
15const fill = (text: string, env: Record<string, string>) =>
16  text.replace(/\$\{(\w+)(?::?-([^}]*))?\}/g, (_, name: string, fallback = '') => env[name] ?? fallback)
17
18// "8080:80", "127.0.0.1:8080:80" or "8080:80/tcp": the host port is the one before the container's.
19const HOST_PORT = /^-\s*["']?(?:[\d.]+:)?(\d+):\d+(?:\/\w+)?["']?\s*$/
20
21export function composePorts(yaml: string, env: Record<string, string>): number[] {
22  return fill(yaml, env)
23    .split('\n')
24    .map(line => HOST_PORT.exec(line.trim()))
25    .filter(m => m !== null)
26    .map(m => Number(m[1]))
27}
28
29export function scriptsFor(pkg: string, ports: number[]): string[] {
30  const scripts: Record<string, string> = JSON.parse(pkg).scripts ?? {}
31  const names = Object.keys(scripts).sort((a, b) => Number(b === 'dev') - Number(a === 'dev'))
32  return ports
33    .map(port => names.find(name => new RegExp(`(^|\\D)${port}(\\D|$)`).test(scripts[name] ?? '')))
34    .filter(name => name !== undefined)
35}
36
37const WATCH = /^\s*develop:\s*\n\s*watch:/m
38
39export const managerOf = (files: string[]) => LOCKS.find(([lock]) => files.includes(lock))?.[1] ?? 'npm'
40
41export function launcherFor(sources: Sources, ports: number[]): Launcher | undefined {
42  const { compose, env, pkg, files } = sources
43  if (compose && composePorts(compose, envOf(env)).some(port => ports.includes(port))) return { kind: 'docker', watch: WATCH.test(compose) }
44  const scripts = pkg ? [...new Set(scriptsFor(pkg, ports))] : []
45  return scripts.length ? { kind: 'node', manager: managerOf(files), scripts } : undefined
46}
47
hooks/panel.tsx 87 lines
1import type { EngineInterface, RenderChildren, RenderInputOf, RenderSurface } from 'claude-code'
2
3import type { Project, Service, ServiceState } from '../types'
4import { LOG_FOLDER } from './commands'
5import { isBusy, statusOf } from './running'
6import { isAnyDown, isAnyUp } from './containers'
7import type { Status } from './running'
8
9export type PaneInput = { [S in RenderSurface]: RenderInputOf<'Pane', S> }[RenderSurface]
10
11export type Actions = { start: () => void; stop: () => void }
12
13export type View = { project: Project; now: number; actions: Actions }
14
15const COLOR: Record<Status, string | undefined> = { running: 'green', starting: 'yellow', stopping: 'yellow', failed: 'red', stopped: undefined }
16
17const SERVICE_COLOR: Record<ServiceState, string | undefined> = {
18  running: 'green', starting: 'yellow', unhealthy: 'red', restarting: 'red', crashed: 'red', exited: undefined, stopped: undefined,
19}
20
21const serviceLabel = ({ state, exitCode }: Service) => (state === 'crashed' ? `crashed, code ${exitCode}` : state)
22
23function services($: EngineInterface, e: PaneInput, list: Service[] = []) {
24  const { Box, Text } = $.ui.resolve(e)
25  if (!list.length) return <Text />
26  return (
27    <Box flexDirection="column">
28      <Text bold>Containers</Text>
29      {list.map(service => (
30        <Text>{service.name} <Text color={SERVICE_COLOR[service.state]} dimColor={!SERVICE_COLOR[service.state]}>{serviceLabel(service)}</Text></Text>
31      ))}
32    </Box>
33  )
34}
35
36function controls($: EngineInterface, e: PaneInput, { project, now, actions }: View) {
37  const { Box, Button, Text } = $.ui.resolve(e)
38  if (!project.launcher) return <Text dimColor>No start command found. Open only.</Text>
39  const isUp = project.apps.some(app => project.listening.includes(app.port)) || isAnyUp(project.services)
40  const isDown = project.apps.some(app => !project.listening.includes(app.port)) || isAnyDown(project.services)
41  const isPressed = isBusy(project, now)
42  return (
43    <Box>
44      {isDown && !isPressed ? <Button key="start" label="Start" onPress={actions.start} /> : <Text />}
45      {isUp && isDown && !isPressed ? <Text> </Text> : <Text />}
46      {isUp && !isPressed ? <Button key="stop" label="Stop" onPress={actions.stop} /> : <Text />}
47    </Box>
48  )
49}
50
51export function drawApps($: EngineInterface, e: PaneInput, view: View) {
52  const { project, now } = view
53  const { Box, Link, Text } = $.ui.resolve(e)
54  const rows = project.apps.map(app => ({ ...app, status: statusOf(project.listening.includes(app.port), project, now) }))
55  const isFailed = rows.some(row => row.status === 'failed')
56  return (
57    <Box flexDirection="column">
58      <Text bold>Apps <Text dimColor>{project.name}</Text></Text>
59      {rows.map(({ service, port, status }) => (
60        <Box flexDirection="column">
61          <Text>{service} <Text color={COLOR[status]} dimColor={status === 'stopped'}>{status}</Text></Text>
62          <Text>  <Link href={`http://localhost:${port}`} /></Text>
63        </Box>
64      ))}
65      {isFailed ? <Text color="red">Didn't start in 90s. Log: {LOG_FOLDER}/{project.name}/</Text> : <Text />}
66      {isFailed && project.failure ? <Text color="red">{project.failure.slice(0, e.props.bodyColumns)}</Text> : <Text />}
67      {services($, e, project.services)}
68      {controls($, e, view)}
69    </Box>
70  )
71}
72
73export function splitPane($: EngineInterface, e: PaneInput, { top, apps }: { top: RenderChildren; apps: RenderChildren }) {
74  const { Box, Text } = $.ui.resolve(e)
75  const rows = e.props.scroll.bodyRows
76  const half = Math.floor(rows / 2)
77  return (
78    <Box flexDirection="column" height={rows}>
79      <Box flexDirection="column" height={half} overflow="hidden">{top}</Box>
80      <Box flexDirection="column" height={rows - half}>
81        <Text dimColor>{'─'.repeat(e.props.bodyColumns)}</Text>
82        {apps}
83      </Box>
84    </Box>
85  )
86}
87
hooks/project.ts 8 lines
1const lastPart = (path: string) => path.replace(/\/+$/, '').split('/').pop() ?? ''
2
3export function projectName(commonDir: string | undefined, cwd: string): string {
4  const dir = commonDir?.trim()
5  if (!dir) return lastPart(cwd)
6  return lastPart(dir.endsWith('/.git') ? dir.slice(0, -'/.git'.length) : dir)
7}
8
hooks/registry.ts 13 lines
1import type { Entry } from '../types'
2
3const BROWSER = /^(web|backoffice|admin|storybook.*|docs.*)$/
4
5export function browserApps(tsv: string, project: string): Entry[] {
6  return tsv
7    .split('\n')
8    .filter(line => line.trim() && !line.startsWith('#'))
9    .map(line => line.trim().split('\t'))
10    .filter(([, name, service = '']) => name === project && BROWSER.test(service))
11    .map(([port, , service = '']) => ({ service, port: Number(port) }))
12}
13
hooks/running.ts 26 lines
1export const START_MS = 90_000
2export const STOP_MS = 90_000
3
4export type Status = 'stopped' | 'starting' | 'running' | 'stopping' | 'failed'
5
6export type Pending = { startedAt?: number; stoppingAt?: number }
7
8export function listeningPorts(ss: string): number[] {
9  const ports = ss
10    .split('\n')
11    .map(line => line.trim().split(/\s+/)[3])
12    .map(local => Number(local?.slice(local.lastIndexOf(':') + 1)))
13    .filter(port => port > 0)
14  return [...new Set(ports)]
15}
16
17// True while a press is within its window: a start or stop that outlived it no longer blocks the buttons.
18export const isBusy = ({ startedAt, stoppingAt }: Pending, now: number) =>
19  (startedAt !== undefined && now - startedAt <= START_MS) || (stoppingAt !== undefined && now - stoppingAt <= STOP_MS)
20
21export function statusOf(isListening: boolean, { startedAt, stoppingAt }: Pending, now: number): Status {
22  if (isListening) return stoppingAt !== undefined && now - stoppingAt <= STOP_MS ? 'stopping' : 'running'
23  if (startedAt === undefined) return 'stopped'
24  return now - startedAt <= START_MS ? 'starting' : 'failed'
25}
26
hooks/containers.ts 50 lines
1import type { Service, ServiceState } from '../types'
2
3type Row = { Service: string; State: string; Health?: string; ExitCode?: number; Labels?: string }
4
5// 130, 137 and 143 are what Ctrl-C, a kill and `docker compose stop` leave behind.
6const STOP_CODES = [0, 130, 137, 143]
7
8const UP: ServiceState[] = ['running', 'starting', 'unhealthy', 'restarting']
9
10// A service with no container may be one that is never meant to run, so only a crash counts as down.
11const DOWN: ServiceState[] = ['crashed']
12
13// Compose v2.21+ prints one object per line; older versions print one array on one line.
14function rowsOf(line: string): Row[] {
15  try {
16    const parsed = JSON.parse(line)
17    return Array.isArray(parsed) ? parsed : [parsed]
18  } catch {
19    return []
20  }
21}
22
23const HEALTH: Record<string, ServiceState> = { unhealthy: 'unhealthy', starting: 'starting' }
24
25const exitedState = (code = 0): ServiceState => (STOP_CODES.includes(code) ? 'exited' : 'crashed')
26
27function stateOf(row: Row | undefined): ServiceState {
28  if (row?.State === 'running') return HEALTH[row.Health ?? ''] ?? 'running'
29  if (row?.State === 'restarting') return 'restarting'
30  if (row?.State === 'exited' || row?.State === 'dead') return exitedState(row.ExitCode)
31  return 'stopped'
32}
33
34export function servicesOf(ps: string, names: string[]): Service[] {
35  const rows = ps.split('\n').filter(line => line.trim()).flatMap(rowsOf).filter(row => !row.Labels?.includes('com.docker.compose.oneoff=True'))
36  const all = names.length ? names : [...new Set(rows.map(row => row.Service))]
37  return all.map(name => {
38    const replicas = rows.filter(r => r.Service === name)
39    const row = replicas.find(r => stateOf(r) === 'crashed') ?? replicas[0]
40    const state = stateOf(row)
41    return state === 'crashed' ? { name, state, exitCode: row?.ExitCode } : { name, state }
42  })
43}
44
45export const isAnyUp = (services: Service[] = []) => services.some(service => UP.includes(service.state))
46
47export const isAnyDown = (services: Service[] = []) => services.some(service => DOWN.includes(service.state))
48
49export const serviceNames = (config = '') => config.split('\n').map(line => line.trim()).filter(Boolean)
50
types/index.d.ts 27 lines
1export type Entry = { service: string; port: number }
2
3export type Launcher = { kind: 'docker'; watch: boolean } | { kind: 'node'; manager: string; scripts: string[] }
4
5export type ServiceState = 'running' | 'starting' | 'unhealthy' | 'restarting' | 'crashed' | 'exited' | 'stopped'
6
7export type Service = { name: string; state: ServiceState; exitCode?: number }
8
9export type Project = {
10  name: string
11  root: string
12  apps: Entry[]
13  launcher?: Launcher
14  listening: number[]
15  serviceNames?: string[]
16  services?: Service[]
17  startedAt?: number
18  stoppingAt?: number
19  failure?: string
20}
21
22declare module 'claude-code' {
23  interface PluginState {
24    'dev-apps': { project: Project | null }
25  }
26}
27