SLOPSHOPPER

sessions

A side pane listing the Claude Code sessions running on this machine, all folders, with each one's status (working or idle), last activity and a Switch button…

panecommandtoastprocesstimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · sessions
│ ┃ Sessions ✕ › fix the failing auth test and add an audit log call │ ┃ 0 running · 0 working [ Refresh ] │ ┃ ⏺ Read(src/auth.ts) │ ┃ No running sessions found. ⎿ 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 │ │ › /sessions │ ⎿ sessions: Sessions pane opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Sessions
0 running · 0 working [ Refresh ] No running sessions found.
README

claude-code-mods

Small mods for Claude Code, built on its function-hooks plugin API.

ModWhat it does
turn-pulseA band above the prompt summarizing the last turn, plus a live status line while Claude works.
notes/note saves chat text to a notes list shared across projects; /notes opens it in a side pane.
sessions/sessions opens a side pane listing the sessions running on this machine and whether each is working or idle.

Early access. The mod API these use is marked EARLY ACCESS and may change between Claude Code releases. Built and tested on Claude Code 2.1.293, on Windows, in the desktop app's Code tab.

Install

In a terminal, add the marketplace once:

claude plugin marketplace add ilya-paskhover/claude-code-mods

Then install one line per mod:

claude plugin install turn-pulse@claude-code-mods
claude plugin install notes@claude-code-mods
claude plugin install sessions@claude-code-mods

This installs in the user scope, so the mod loads in every new session, including sessions the desktop app starts. Inside an interactive claude session, /plugin marketplace add and /plugin install take the same arguments. /plugin is not available inside the desktop app's Code tab, so install from a terminal.

turn-pulse

turn-pulse: the last-turn band above the prompt and the session total in the status line

A band labeled ◆ last turn sits above the prompt after each turn:

  • Duration of the turn, in yellow past 2 minutes.
  • Files edited, in green. An edit outside the session's working folder shows in bold red, with a 15 second toast.
  • Tool results: ✓ N ok, and ✗ N failed (Tool ×n) when something failed.
  • Usage-limit cost of the turn, for example 5h +1% · week +0.3%.

The status line shows ▶ Tool · N ok · ✗ N failed live during a turn, and session: 5h +6% · week +2% between turns. A toast appears when a turn takes 60 seconds or more. /pulse hides or shows the band. In a cloud session /pulse prints the last turn and the session total as text instead, since the Claude app showing the session may not draw the band or the status line.

Limits:

  • Usage numbers are account-wide, so other sessions running at the same time count toward them.
  • Tracking starts when the mod loads, and the handling of a limit window resetting is heuristic.
  • Paths are compared case-insensitively. That is right on Windows but could misjudge an "outside" edit on a case-sensitive Linux file system.

notes

notes: the Notes side pane with an open note

  • /note <text> saves the typed text. With text selected in the transcript, /note <comment> saves the selection with the typed text as its comment.
  • Notes are kept in the mod's own store, shared across all sessions and projects.
  • /notes opens a Notes side pane: notes render as Markdown, long ones fold behind More/Less, and each has a ☐/☑ done toggle, Delete, and Jump (scroll to the message it came from; same session only). Show/Hide done and Clear done act on the whole list.
  • Text pasted into the prompt has its <pasted_content> wrapper stripped.

Limits:

  • In the desktop app the selection is not passed to mods, so /note there needs pasted or typed text, and Jump never appears. Selection is documented to work in the fullscreen terminal; I have not verified that. Tracked in #1.
  • Jump only scrolls within the session the note was taken in; mods can't open another session. Tracked in #4.

sessions

sessions: the Sessions side pane with two running sessions and a Switch button

/sessions opens a Sessions side pane listing every Claude Code session running on this machine, from any folder:

  • A count of running and working sessions, and a Refresh button.
  • One row per session: ● working (yellow) or ○ idle (green), the session's name, how long since its last activity, and "this session" on your own row.
  • A Switch button on each session the desktop app started opens that session in the app. Sessions started in a terminal have no button.
  • Working sessions sort first, then the most recently active.
  • The pane refreshes every 5 seconds while it is open and stops when you close it.
  • The pane opens by itself once per local session: at start in a terminal, or when the desktop app connects. It opens unfocused, so the prompt keeps the keyboard. Close it and it stays closed for that session, through reloads and desktop reconnects.

In a cloud session, where the container holds only that one session, /sessions lists your 10 most recent cloud sessions instead, from the claude-code-remote MCP server every cloud session has:

  • ● working, ◐ needs input with what the session is waiting on, ✗ failed, or ○ idle (finished or ready for review).
  • An Open link on each other session goes to its page on claude.ai.
  • The pane refreshes every 30 seconds, since each refresh is an API call.

Limits:

  • Opened by itself, the pane shows only in a window at least 144 columns wide, or 110 once you have opened it with /sessions. In a narrower one it waits until you run /sessions. Cloud sessions don't open it by themselves, since each refresh there is an API call; /sessions opens it.
  • The list comes from Claude Code's own files in ~/.claude/sessions/ (or $CLAUDE_CONFIG_DIR/sessions/), not from the mod API. That format is undocumented and could change in any release; if no file can be read, the pane says so instead of showing a wrong list.
  • Locally, only sessions running on this machine appear: closed sessions and cloud sessions do not. In a cloud session, only cloud sessions appear, not the ones on your computer.
  • The cloud list is the claude-code-remote server's list_sessions output, which is not a documented format either; if it can't be read, the pane says so. In a live cloud session the plugin loads and /sessions runs, but the pane does not appear; tracked in #14.
  • Switch works only for sessions the desktop app started, through an undocumented claude:// link, not a mod API (tracked in #4).
  • In the desktop app, a click on the pane first gives it focus, so a button may need two clicks: one to focus the pane, one to press. The pane opens focused, so the first click right after /sessions works; after you click elsewhere, click anywhere in the pane (or Refresh) first. Press Esc to give the keyboard back to the prompt.
  • Sessions and Notes open as tabs in the same side pane; mod panes can't be shown side by side. Tracked in #5.
  • A session that crashed can leave its file behind. The session file only changes when the status changes, so a "working" row shows dimmed as "working?" once it has been busy for 30 minutes: either a long turn or a crash. The pane can't tell which.

Developing

Each mod is a plugin folder under plugins/. To run a working copy instead of the installed one, name the folders in the env block of ~/.claude/settings.json (separated by ; on Windows, : elsewhere) and uninstall the marketplace copy so the mod does not load twice:

{
  "env": {
    "CLAUDE_CODE_PLUGIN_DIRS": "/path/to/claude-code-mods/plugins/turn-pulse;/path/to/claude-code-mods/plugins/notes"
  }
}

Interactive sessions watch those folders and reload a mod when its files are saved. Checks, per mod folder:

claude plugin validate plugins/notes
claude plugin test plugins/notes

To try a branch's copy of a mod in a cloud session, add these lines to the cloud environment's setup script, set BRANCH and MOD, then start a new session. They copy the mod into a one-mod marketplace and install it from there:

BRANCH=claude/my-branch
MOD=sessions
git clone --depth 1 -b "$BRANCH" https://github.com/ilya-paskhover/claude-code-mods /tmp/mod-branch
M=/tmp/mod-branch-mkt
mkdir -p $M/.claude-plugin $M/plugins
cp -r /tmp/mod-branch/plugins/$MOD $M/plugins/
cat > $M/.claude-plugin/marketplace.json <<EOF
{"name":"mod-branch","owner":{"name":"Ilya Paskhover"},"plugins":[{"name":"$MOD","source":"./plugins/$MOD"}]}
EOF
claude plugin marketplace add $M && claude plugin install $MOD@mod-branch

In the session, claude plugin list should then show <mod>@mod-branch enabled.

Each mod's tsconfig.json extends the type declarations the engine writes into .claude-plugin/types/ when it loads the mod (gitignored), so tsc -p plugins/notes works once the mod has loaded once.

License

MIT

Source 3 files
hooks/register.tsx 208 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { SessionRow } from '../types'
5import { ago, cloudSessionId, look, parseCloudSessions, parseSession, sortRows, switchLink } from './parse'
6
7// Claude Code writes one <pid>.json per running session into its config
8// folder's sessions/ directory. That file is the engine's own, not mod API.
9// A cloud container holds only its own session, so there the list comes from
10// the claude-code-remote MCP server every cloud session has.
11const PANE = 'sessions'
12const PANE_TITLE = 'Sessions'
13const REFRESH_MS = 5_000
14// Each cloud refresh is an API call, not a folder read.
15const CLOUD_REFRESH_MS = 30_000
16const REMOTE_SERVER = 'claude-code-remote'
17const CLOUD_LIMIT = 10
18
19const rows = atom({ plugin: 'sessions', key: 'rows' } as const, [])
20const sessionId = atom({ plugin: 'sessions', key: 'sessionId' } as const, '')
21const now = atom({ plugin: 'sessions', key: 'now' } as const, 0)
22const error = atom({ plugin: 'sessions', key: 'error' } as const, '')
23// In $.state, not a module variable: a reload fires session.start again and
24// must not reopen a pane the person closed.
25const autoOpened = atom({ plugin: 'sessions', key: 'autoOpened' } as const, false)
26const cloud = atom({ plugin: 'sessions', key: 'cloud' } as const, false)
27
28type Listing = { found: SessionRow[]; problem: string }
29
30async function sessionsDir($: EngineInterface) {
31  const config = await $.env.get('CLAUDE_CONFIG_DIR')
32  if (config !== undefined && config !== '') return `${config.replace(/[\\/]+$/, '')}/sessions`
33  const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME'))
34  return home === undefined ? undefined : `${home.replace(/[\\/]+$/, '')}/.claude/sessions`
35}
36
37async function localRows($: EngineInterface): Promise<Listing> {
38  const dir = await sessionsDir($)
39  const found: SessionRow[] = []
40  let problem = ''
41  try {
42    if (dir === undefined) throw new Error('no home folder')
43    const files = (await $.fs.list(dir)).filter(f => f.kind === 'file' && f.name.endsWith('.json'))
44    for (const file of files) {
45      const row = await $.fs
46        .read(`${dir}/${file.name}`)
47        .then(parseSession)
48        .catch(() => undefined)
49      if (row !== undefined) found.push(row)
50    }
51    if (files.length > 0 && found.length === 0) {
52      problem = "Couldn't read any session file: Claude Code may have changed their format."
53    }
54  } catch {
55    problem = `No session folder found${dir === undefined ? '' : ` at ${dir}`}.`
56  }
57  return { found, problem }
58}
59
60async function cloudRows($: EngineInterface): Promise<Listing> {
61  const result = await $.mcp
62    .call(REMOTE_SERVER, 'list_sessions', { mine: true, limit: CLOUD_LIMIT })
63    .catch(() => undefined)
64  if (result === undefined) return { found: [], problem: `Couldn't reach the ${REMOTE_SERVER} MCP server.` }
65  if (result.isError) return { found: [], problem: 'The cloud session list failed to load.' }
66  const found = parseCloudSessions(result.content.map(block => block.text ?? '').join(''))
67  if (found === undefined) {
68    return { found: [], problem: "Couldn't read the cloud session list: its format may have changed." }
69  }
70  return { found, problem: '' }
71}
72
73async function refresh($: EngineInterface) {
74  const at = await $.clock.now()
75  const { found, problem } = (await read($, cloud)) ? await cloudRows($) : await localRows($)
76  await update($, rows, () => sortRows(found))
77  await update($, error, () => problem)
78  await update($, now, () => at)
79}
80
81// Hands the link to the OS, which passes it to the desktop app.
82async function openLink($: EngineInterface, url: string) {
83  const argv =
84    (await $.env.get('OS')) === 'Windows_NT' ? ['cmd', '/c', 'start', '', url] : ['open', url]
85  const ran = await $.process.run(argv).catch(() => undefined)
86  if (ran === undefined || ran.exitCode !== 0) $.ui.toast("Couldn't open that session in the desktop app.")
87}
88
89// Module variable on purpose: a reload drops timers, and session.start
90// restarts the refresh when the pane is still up.
91let ticking: Timer | undefined
92
93const isPaneUp = async ($: EngineInterface) => (await $.ui.panes()).some(pane => pane.id === PANE)
94
95async function startTicking($: EngineInterface) {
96  const period = (await read($, cloud)) ? CLOUD_REFRESH_MS : REFRESH_MS
97  if (ticking !== undefined) return
98  ticking = $.clock.every(period, async () => {
99    if (!(await isPaneUp($))) {
100      ticking?.cancel()
101      ticking = undefined
102      return
103    }
104    await refresh($)
105  })
106}
107
108// Once per session: the desktop app attaches again on every reconnect. Cloud
109// sessions are skipped: there each refresh is an API call, so the pane waits
110// for /sessions.
111async function autoOpen($: EngineInterface) {
112  if (await read($, cloud)) return
113  if (await read($, autoOpened)) return
114  await update($, autoOpened, () => true)
115  await refresh($)
116  // Unfocused, so the prompt keeps the keyboard. Unasked, the engine draws a
117  // pane only from 144 columns, or 110 once /sessions has opened it; narrower,
118  // it waits for /sessions.
119  await $.ui.open({ id: PANE, title: PANE_TITLE })
120  await startTicking($)
121}
122
123export const register: Register = on => {
124  on('session.start', async ($, e, next) => {
125    await $.command.register({
126      name: 'sessions',
127      description: 'Open the Sessions pane: running sessions and their status',
128      immediate: true,
129    })
130    const isCloud = (await $.env.get('CLAUDE_CODE_REMOTE')) === 'true'
131    await update($, cloud, () => isCloud)
132    const remoteId = await $.env.get('CLAUDE_CODE_REMOTE_SESSION_ID')
133    const id = isCloud && remoteId !== undefined ? cloudSessionId(remoteId) : await $.session.id()
134    await update($, sessionId, () => id)
135    if (await isPaneUp($).catch(() => false)) {
136      await refresh($)
137      await startTicking($)
138    }
139    if (e.surface === 'terminal') await autoOpen($)
140
141    return next(e)
142  })
143
144  // The desktop app runs the session headless: at session.start nothing draws
145  // yet, so its first chance at the pane is when it attaches. Opened after
146  // next, once the app is on the session's roster of surfaces.
147  on('session.attach', async ($, e, next) => {
148    const attached = await next(e)
149    if (e.surface === 'desktop') await autoOpen($)
150    return attached
151  })
152
153  on('command.run', { command: 'sessions' }, async $ => {
154    await refresh($)
155    // Focused on open: unfocused, Switch took two clicks in the desktop app,
156    // likely the first giving the pane focus.
157    await $.ui.open({ id: PANE, title: PANE_TITLE, focus: true })
158    await startTicking($)
159
160    return { text: 'Sessions pane opened.' }
161  })
162
163  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
164    const { Box, Button, Link, Text } = $.ui.resolve(e)
165    const list = await read($, rows)
166    const current = await read($, sessionId)
167    const at = await read($, now)
168    const problem = await read($, error)
169    // Cloud sessions stay listed after they stop: recent ones, not running ones.
170    const kind = (await read($, cloud)) ? 'recent' : 'running'
171    const working = list.filter(row => row.status === 'busy').length
172
173    return (
174      <Box flexDirection="column" gap={1}>
175        <Box flexDirection="row" gap={1}>
176          <Text color="claude" bold>{list.length} {kind}</Text>
177          <Text dimColor>· {working} working</Text>
178          <Button key="refresh" label="Refresh" onPress={() => refresh($)} />
179        </Box>
180        {problem !== '' ? <Text color="error">{problem}</Text> : null}
181        {problem === '' && list.length === 0 ? <Text dimColor>No {kind} sessions found.</Text> : null}
182        {list.map(row => {
183          const { dot, label, color, isDim } = look(row, at)
184          const link = row.id === current ? undefined : switchLink(row)
185          return (
186            <Box key={row.id} flexDirection="column">
187              <Box flexDirection="row" gap={1}>
188                <Text color={color} dimColor={isDim}>{dot}</Text>
189                <Text bold={row.id === current} dimColor={isDim}>{row.name}</Text>
190                {link !== undefined ? (
191                  <Button key={`switch:${row.id}`} label="Switch" onPress={() => openLink($, link)} />
192                ) : null}
193                {row.url !== undefined && row.id !== current ? <Link href={row.url} label="Open" /> : null}
194              </Box>
195              <Box flexDirection="row" gap={1}>
196                <Text color={color} dimColor={isDim}>  {label}</Text>
197                <Text dimColor>· {ago(at - row.updatedAt)}</Text>
198                {row.id === current ? <Text dimColor>· this session</Text> : null}
199              </Box>
200              {row.needs !== undefined ? <Text dimColor>  {row.needs}</Text> : null}
201            </Box>
202          )
203        })}
204      </Box>
205    )
206  })
207}
208
hooks/parse.ts 129 lines
1import type { SessionRow } from '../types'
2
3// A busy session whose file has not changed for this long may have died
4// without cleaning up; it is drawn dimmed with a question mark.
5export const STALE_MS = 30 * 60_000
6
7export const folderName = (path: string) => path.split(/[\\/]/).filter(Boolean).pop() ?? path
8
9const str = (v: unknown) => (typeof v === 'string' && v !== '' ? v : undefined)
10const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined)
11
12// Claude Code's own session file, not part of the mod API: read defensively.
13export const parseSession = (text: string): SessionRow | undefined => {
14  let raw: unknown
15  try {
16    raw = JSON.parse(text)
17  } catch {
18    return undefined
19  }
20  if (typeof raw !== 'object' || raw === null) return undefined
21  const o = raw as Record<string, unknown>
22
23  const id = str(o.sessionId)
24  const pid = num(o.pid)
25  if (id === undefined || pid === undefined) return undefined
26  const cwd = str(o.cwd) ?? ''
27  return {
28    id,
29    pid,
30    cwd,
31    name: str(o.name) ?? (cwd !== '' ? folderName(cwd) : id.slice(0, 8)),
32    status: str(o.status) ?? 'unknown',
33    updatedAt: num(o.updatedAt) ?? num(o.statusUpdatedAt) ?? num(o.startedAt) ?? 0,
34    hostSessionId: str(o.hostSessionId),
35  }
36}
37
38// status_bucket, SESSION_STATUS_BUCKET_WORKING and so on, in look's words.
39const BUCKETS: Record<string, string> = {
40  working: 'busy',
41  blocked: 'blocked',
42  review_ready: 'idle',
43  completed: 'idle',
44  failed: 'failed',
45}
46
47// needs_action sits in external_metadata.post_turn_summary; the top-level
48// post_turn_summary has been seen without it.
49const needsAction = (holder: unknown) => {
50  const summary = (holder as { post_turn_summary?: unknown } | null | undefined)?.post_turn_summary
51  return str((summary as { needs_action?: unknown } | null | undefined)?.needs_action)
52}
53
54const cloudRow = (item: unknown): SessionRow | undefined => {
55  if (typeof item !== 'object' || item === null) return undefined
56  const o = item as Record<string, unknown>
57  const id = str(o.id)
58  if (id === undefined) return undefined
59  const bucket = str(o.status_bucket)?.replace(/^SESSION_STATUS_BUCKET_/, '').toLowerCase() ?? 'unknown'
60  return {
61    id,
62    cwd: '',
63    name: str(o.title) ?? id,
64    status: BUCKETS[bucket] ?? bucket,
65    updatedAt: num(Date.parse(str(o.updated_at) ?? '')) ?? 0,
66    url: `https://claude.ai/code/${encodeURIComponent(id)}`,
67    needs: needsAction(o.external_metadata) ?? needsAction(o),
68  }
69}
70
71// The claude-code-remote server's list_sessions result, not part of the mod
72// API: read defensively. Its JSON can come wrapped in an untrusted-data
73// envelope, so only the span from the first { to the last } is parsed.
74export const parseCloudSessions = (text: string): SessionRow[] | undefined => {
75  let raw: unknown
76  try {
77    raw = JSON.parse(text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1))
78  } catch {
79    return undefined
80  }
81  const o = raw as { ccr?: { data?: unknown }; data?: unknown } | null
82  const list = o?.ccr?.data ?? o?.data
83  if (!Array.isArray(list)) return undefined
84  return list.map(cloudRow).filter((row): row is SessionRow => row !== undefined)
85}
86
87// CLAUDE_CODE_REMOTE_SESSION_ID reads cse_<id> where list_sessions says
88// session_<id>.
89export const cloudSessionId = (remoteId: string) => `session_${remoteId.replace(/^[a-z]+_/, '')}`
90
91// The desktop app opens a session it started from this link: the one its own
92// session tools hand out to open a session from outside the app. Not public API.
93export const switchLink = (row: SessionRow) =>
94  row.hostSessionId === undefined ? undefined : `claude://claude.ai/epitaxy/${encodeURIComponent(row.hostSessionId)}`
95
96// Working sessions first, then the most recently active; one row per session.
97export const sortRows = (rows: readonly SessionRow[]): SessionRow[] => {
98  const newest = new Map<string, SessionRow>()
99  for (const row of rows) {
100    const seen = newest.get(row.id)
101    if (seen === undefined || row.updatedAt > seen.updatedAt) newest.set(row.id, row)
102  }
103  return [...newest.values()].sort((a, b) => {
104    const busy = Number(b.status === 'busy') - Number(a.status === 'busy')
105    return busy !== 0 ? busy : b.updatedAt - a.updatedAt
106  })
107}
108
109export const ago = (ms: number) => {
110  const minutes = Math.floor(Math.max(0, ms) / 60_000)
111  if (minutes < 1) return 'now'
112  if (minutes < 60) return `${minutes}m`
113  const hours = Math.floor(minutes / 60)
114  return hours < 24 ? `${hours}h` : `${Math.floor(hours / 24)}d`
115}
116
117export type Look = { dot: string; label: string; color?: string; isDim: boolean }
118
119export const look = (row: SessionRow, now: number): Look => {
120  if (row.status === 'busy') {
121    const isStale = now - row.updatedAt > STALE_MS
122    return { dot: '●', label: isStale ? 'working?' : 'working', color: 'warning', isDim: isStale }
123  }
124  if (row.status === 'idle') return { dot: '○', label: 'idle', color: 'success', isDim: false }
125  if (row.status === 'blocked') return { dot: '◐', label: 'needs input', color: 'warning', isDim: false }
126  if (row.status === 'failed') return { dot: '✗', label: 'failed', color: 'error', isDim: false }
127  return { dot: '·', label: row.status, isDim: true }
128}
129
types/index.d.ts 31 lines
1// One session, as Claude Code's own ~/.claude/sessions/<pid>.json describes
2// it, or in a cloud session as the claude-code-remote server's list_sessions
3// does (no pid, no folder).
4export type SessionRow = {
5  id: string
6  pid?: number
7  name: string
8  cwd: string
9  status: string
10  updatedAt: number
11  // The desktop app's id for a session it started: what a switch link opens.
12  hostSessionId?: string
13  // A cloud session's page on claude.ai: what Open goes to.
14  url?: string
15  // What a blocked cloud session is waiting on, as that session put it.
16  needs?: string
17}
18
19declare module 'claude-code' {
20  interface PluginState {
21    sessions: {
22      rows: SessionRow[]
23      sessionId: string
24      now: number
25      error: string
26      autoOpened: boolean
27      cloud: boolean
28    }
29  }
30}
31