SLOPSHOPPER

ghostty

Ghostty integration: a 4-word summary as the tab title (/title for a new one now), a tab progress bar, ❓ when Claude waits on you (the notify mod sends the…

paneguardcommandtoastpromptmodel
v0.4.0no licenseupdated 2026-10-22whilestevego/claude-mods/ghostty
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · ghostty
│ ┃ claude-goto ✕ › fix the failing auth test and add an audit log call │ ┃ ❓ waiting on you · ⏳ working · number or │ ┃ Enter to jump · Esc to close ⏺ 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 │ │ › /title │ ⎿ ghostty: Tab title: OK │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · claude-goto
❓ waiting on you · ⏳ working · number or Enter to jump · Esc to close
Pane · claude-workspaces
No saved workspaces. /workspace save remembers this window.
README

claude-mods

Mods for Claude Code: small plugins that add to its screen and behavior. Each folder is one mod. Turn on the ones you want (see Setup) and change their settings in /config, under the mod's name.

Each mod works on its own, and a few work better together. notify tells you when something happens; with say it can tell you out loud, with tldr its turn summaries reuse tldr's line instead of writing their own, and with ghostty it stays quiet while you're looking at the session. In Ghostty, clicking its notification brings you back to the session's tab.

The mods

context-bar

Shows how full Claude's context window is, as a colored bar above the prompt.

  • Point at the bar to see what's using the space (system prompt, messages, tools…).
  • /context-bar hides or shows it for this session.

rate-limits

Shows how much of your 5-hour and weekly usage limits you've used, as two small meters under the context bar. They turn yellow at 70% and red at 90%, and you get a warning inside Claude once a limit passes 90%. (notify also warns, as a desktop notification or out loud, at a threshold you set.)

  • Nothing to do: it appears on its own when you're on a subscription plan.

session-id

Shows this session's ID in the bottom-right corner of the screen.

  • Click it to copy the ID.
  • Ctrl-click it to copy the full claude --resume <id> command.

turn-receipt

Adds a receipt to the line that closes each turn ("✻ Baked for 42s"): how many tools ran, which files were edited, the tokens used and what the turn cost.

  • Nothing to do: it appears after every turn.

tldr

Adds a one-sentence summary under Claude's longer replies, written by Claude Haiku.

  • Nothing to do. TL;DR: long reply in /config sets how long a reply must be (600 characters by default).
  • With notify on, the same line is its summary when a long turn finishes, at no extra cost.

notify

Tells you when something happens in a session: as a desktop notification, out loud through say, or both. With the ghostty mod on, it only tells you when you're away from the session (another app or tab in front), so it never interrupts you while you're watching. Without it, nothing can tell whether you're looking, so it always tells you.

  • What it tells you about: Claude needs your permission or has a question, or a turn stopped on an API error (like a lost connection); a long turn finished, with a one-line summary of what it did; you're close to a usage limit; a background task finished; and every few minutes, how a long turn is going.
  • Where each one goes: each event has its own setting in /config under notify: both, banner (the desktop notification), voice (spoken by say) or off. By default the first three are both, and background tasks and check-ins are voice.
  • Clicking a notification in Ghostty brings you to the tab of the session that sent it. Each one is titled with the session's folder, so you can tell sessions apart.
  • Without say, voice alerts are skipped and the banners still go out.
CommandWhat it does
/notify testSends a desktop notification right away. macOS can't tell a mod whether your terminal may show notifications, so this is how to check. The first time notify starts, it reminds you once.
/notify settingsOpens the switch in System Settings: Ghostty's own entry in Ghostty, the Notifications list elsewhere.

say

Gives Claude a voice, through murmur. The notify mod decides what gets said and when; say is the voice it speaks in.

  • A soft chime plays before it speaks, so a voice never starts out of nowhere. Turn it off with Chime in /config.
  • Each open session gets its own voice: the best one no other session has, by Kokoro's grades (Heart, then Bella, Nicole, Emma…). Pick one fixed voice, or your own list, in /config under say.

Everything else is one command, /say:

CommandWhat it does
/sayNames this session's voice and plays a short sample of it.
/say pickLists every voice with its grade and switches this session to the one you pick, with a sample in it. The choice sticks to the conversation, so resuming it keeps the voice.
/say pick <name>Switches directly, like /say pick emma. Part of the name is enough.
/say pick randomSwitches to a random voice, other than the current one. Better-graded voices come up more often.
/say readReads Claude's last reply aloud.
/say tldrA spoken 2–3 sentence summary of the session so far.
/say hushMutes this session; run it again to unmute.
/say helpLists these.

ghostty

Ties Claude into the Ghostty terminal. All its settings start with "Ghostty" in /config.

  • Tab title: a 4-word summary of what the session is about, from your last 10 messages and Claude's latest reply, updated every few minutes as it goes. /title gets a new one right away. A resumed session gets its old title back.
  • Tab progress bar: shows while Claude works, and turns red when a command fails.
  • ❓ waiting on you: a ❓ in the tab title when Claude needs a permission or an answer. The notify mod sends the notification.
  • /workspace saves and reopens whole windows of sessions: see Workspaces.
  • /goto lists your open Claude sessions, the ones waiting on you first, and jumps to the one you pick. /goto next jumps straight to the one waiting longest; /goto <words> jumps to the one whose title matches.
  • /keybind add <keys> <text> makes a Ghostty key type something into Claude, like /keybind add super+ctrl+h /say hush for ⌘⌃H. /keybind lists them, and /keybind remove <keys> removes one. For ⌘⌃G to open /goto, run /keybind add super+ctrl+g /goto, or turn on Ghostty: install Claude keybinds in /config. The mod changes your Ghostty config only when you do one of these: it adds one line that loads its own claude-keybinds file.
Workspaces

A workspace is a Ghostty window of Claude sessions you can put away and bring back later. It remembers every tab and split: each Claude session with its conversation, and each shell with its folder. Reopening it brings back the whole window, with every conversation picking up where it left off.

CommandWhat it does
/workspace save [name]Saves this window. With no name, it keeps the name the window already had, or Claude Haiku picks one from the tabs.
/workspace close [name]Saves this window, then exits every Claude session in it and closes their tabs. Your current tab stays open at the shell, and shell tabs stay open. If another session is still working or waiting on you, it closes nothing and names them; /workspace close --force closes them anyway.
/workspace listShows your saved workspaces, newest first. Press a number or Enter to reopen one, or Tab to ✕ delete to remove it.
/workspace open <name>Reopens a saved workspace in a new window. Part of the name is enough.
  • Reopening puts each tab back in its folder. Claude tabs run claude --resume, so they continue their own conversation, with the tab title they had when you saved. A tab saved without a title gets a new one from its conversation. Shell tabs open at the prompt.
  • Put away a project for the day: /workspace close. Pick it up tomorrow: /workspace list, then press its number.
  • What doesn't come back: programs that were running (a dev server, a test watcher), and the exact split layout. Splits reopen side by side.
  • Where they're kept: ~/.claude/workspaces/, one JSON file per workspace. Saving never overwrites a different workspace that happens to have the same name: the new one gets a file of its own.

Setup

Install the mods you want, one line each, at the prompt of a Claude Code session:

/plugin install context-bar --marketplace whilestevego/claude-mods

Answer y to add the marketplace, then pick a scope. The mods are context-bar, rate-limits, session-id, turn-receipt, tldr, notify, say and ghostty.

From a clone, while working on them

  1. Clone this repo.
  2. List the mods you want in CLAUDE_CODE_PLUGIN_DIRS, separated by :, in the env block of ~/.claude/settings.json:
   "env": {
     "CLAUDE_CODE_PLUGIN_DIRS": "/path/to/claude-mods/context-bar:/path/to/claude-mods/say"
   }
  1. Start a new Claude session.

To try one mod for a single session: claude --plugin-dir /path/to/claude-mods/tldr.

Requirements

  • ghostty needs Ghostty 1.3 or newer on macOS. Set CLAUDE_CODE_DISABLE_TERMINAL_TITLE=1 in the same env block, so Claude Code doesn't overwrite the tab title.
  • say needs murmur installed, which runs on Apple Silicon Macs.
  • notify's desktop notifications need notifications allowed for your terminal, in System Settings → Notifications (Ghostty, say). /notify test checks; /notify settings opens the page.
  • session-id's pointing-hand cursor works in Ghostty, Kitty and foot.

The first time a mod controls Ghostty, macOS asks for permission. Allow it.

Development

Editing a mod's files reloads it in running sessions. A mod newly added to CLAUDE_CODE_PLUGIN_DIRS loads only in sessions started after that.

claude plugin validate context-bar   # check a mod the way Claude Code will load it
claude plugin test context-bar       # run its tests

Mods can call each other through nouns on $: say adds $.voice.say({ text }), which notify speaks through, and ghostty adds $.ghostty.isFocused(), which notify asks before alerting. Their types are in each mod's types/index.d.ts.

IDEAS.md has ideas for more mods.

Source 7 files
hooks/register.tsx 659 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PluginOptions, Register } from 'claude-code'
3
4import type { WorkspaceRow } from '../types'
5
6import {
7  claudeSessions, matchSessions, progress, Progress, runningBar, shortFolder, tabTitle, titleAction,
8} from './term'
9import type { Session } from './term'
10import { DEFAULTS, parseAdd, parseBindings, prettyKeys, renderFile, upsert, withInclude } from './keybinds'
11import type { Binding } from './keybinds'
12import { asksPermission, badge, nextWaiting, parseEntry, rank } from './registry'
13import type { Entry, Ranked, Status } from './registry'
14import { ask, bare, clean, context } from './title'
15import {
16  claudePidsFrom, cleanName, closable, conversationOf, fromWindow, namePrompt, openScript, parseWorkspace, sameWorkspace, slug,
17  summary as describe,
18} from './workspace'
19import type { Workspace } from './workspace'
20
21type Config = {
22  tabTitle: boolean
23  titleMinutes: number
24  tabProgress: boolean
25  waitingBadge: boolean
26  keybinds: boolean
27}
28
29function config(o: PluginOptions): Config {
30  return {
31    tabTitle: o.tabTitle !== false,
32    titleMinutes: typeof o.titleMinutes === 'number' && o.titleMinutes > 0 ? o.titleMinutes : 3,
33    tabProgress: o.tabProgress !== false,
34    waitingBadge: o.waitingBadge !== false,
35    keybinds: o.keybinds === true,
36  }
37}
38
39// The module's own session state; a reload starts it over.
40let cfg: Config
41let tty = ''
42/** Claude's own process: a session is alive while it is. */
43let pid = ''
44let summary = ''
45let titledAt = 0
46let hasFailed = false
47let isRunning = false
48let isWaiting = false
49/** Calls the permission check put to you, until they run or are refused. */
50const asking = new Set<string>()
51/** The calls waiting on you right now (a dialog that's up, a question): ❓ until the last of them is answered. */
52const waitingOn = new Set<string>()
53let home = ''
54/** The sessions the /goto picker shows. */
55let picks: Ranked[] = []
56let status: Status = 'idle'
57let statusSince = 0
58
59const workspaceRows = atom({ plugin: 'ghostty', key: 'workspaces' } as const, [])
60const WORKSPACES = 'claude-workspaces'
61
62const GOTO = 'claude-goto'
63
64// "<tty> <pid>" of Claude itself: the nearest ancestor named claude (the mods' own host process, between it and
65// this shell, owns the tty too). Without one, the nearest ancestor owning a tty. No API names Claude's tty or pid.
66const FIND_TTY = `p=$$
67first=
68while [ "$p" -gt 1 ]; do
69  t=$(ps -o tty= -p "$p" | tr -d ' ')
70  case "$t" in ''|'?'|'??') ;; *) [ -z "$first" ] && first="/dev/$t $p"
71    c=$(ps -o comm= -p "$p"); [ "\${c##*/}" = claude ] && { echo "/dev/$t $p"; exit; } ;;
72  esac
73  p=$(ps -o ppid= -p "$p" | tr -d ' ')
74done
75echo "$first"`
76
77async function locate($: EngineInterface) {
78  home = (await $.env.get('HOME')) ?? ''
79  ;[tty = '', pid = ''] = (await $.process.run(['sh', '-c', FIND_TTY])).stdout.trim().split(' ')
80}
81
82// Every Ghostty terminal as "id<TAB>tty<TAB>title<TAB>folder"; plus the ttys running Claude.
83const LIST_TERMINALS = `tell application "Ghostty"
84  set out to ""
85  repeat with t in terminals
86    set out to out & (id of t) & (character id 9) & (tty of t) & (character id 9) & (name of t) & (character id 9) & (working directory of t) & linefeed
87  end repeat
88  return out
89end tell`
90// A string pattern with [/]: no backslash for the template literal to eat.
91const CLAUDE_TTYS = `ps -ax -o tty=,comm= | awk 'match($2, "(^|[/])claude$") { print "/dev/" $1 }'`
92const FOCUS = `on run argv
93  tell application "Ghostty" to focus (first terminal whose id is (item 1 of argv))
94end run`
95
96async function listSessions($: EngineInterface): Promise<Session[]> {
97  const [terms, ttys] = await Promise.all([
98    $.process.run(['osascript', '-e', LIST_TERMINALS]),
99    $.process.run(['sh', '-c', CLAUDE_TTYS]),
100  ])
101  // A failing command must say so: an empty list would read as "no other sessions".
102  for (const [what, r] of [['Ghostty', terms], ['ps', ttys]] as const) {
103    if (r.exitCode !== 0) throw new Error(`${what} query failed: ${r.stderr.trim().slice(0, 160) || `exit ${r.exitCode}`}`)
104  }
105  return claudeSessions(terms.stdout, new Set(ttys.stdout.split('\n').filter(Boolean)), tty)
106}
107
108// The tty of the terminal Ghostty has focused, or nothing when Ghostty isn't the frontmost app.
109const FOCUSED_TTY = `tell application "Ghostty"
110  if frontmost then return tty of focused terminal of selected tab of front window
111  return ""
112end tell`
113
114/** This session's terminal is the one in front of you. Unsure (no tty, AppleScript failed) reads as not. */
115async function isFocused($: EngineInterface): Promise<boolean> {
116  if (!tty) return false
117  const r = await $.process.run(['osascript', '-e', FOCUSED_TTY])
118  return r.exitCode === 0 && r.stdout.trim() === tty
119}
120
121async function goTo($: EngineInterface, s: Session) {
122  await $.process.run(['osascript', '-e', FOCUS, s.id])
123}
124
125// A mod can't print to the screen, so escape sequences go straight to Claude's tty. Bytes written there can land
126// inside a frame Claude is drawing and garble it, so only the progress bar (no other way to set it) goes this way.
127async function send($: EngineInterface, bytes: string) {
128  if (!tty || !bytes) return
129  await $.process.run(['sh', '-c', 'printf "%s" "$1" > "$2"', 'sh', bytes, tty]).catch(() => null)
130}
131
132const SET_TITLE = `on run argv
133tell application "Ghostty" to perform action (item 2 of argv) on (first terminal whose tty is (item 1 of argv))
134end run`
135
136async function drawTitle($: EngineInterface) {
137  if (!tty) return
138  if (cfg.tabTitle || (cfg.waitingBadge && isWaiting) || summary) {
139    await $.process.run(['osascript', '-e', SET_TITLE, tty, titleAction(tabTitle(summary, cfg.waitingBadge && isWaiting))]).catch(() => null)
140  }
141}
142
143let wantedBar = ''
144let sentBar = ''
145
146async function drawBar($: EngineInterface) {
147  if (!cfg.tabProgress) return
148  wantedBar = isWaiting ? progress(Progress.paused) : isRunning ? runningBar(hasFailed) : progress(Progress.hide)
149  // Let the redraw that came with this change (a submitted prompt, a finished turn) finish first; the last call wins.
150  // ponytail: a fixed delay only dodges that redraw, a spinner frame can still collide; no way to sync with Claude's renderer.
151  await $.clock.sleep(150)
152  if (wantedBar === sentBar) return
153  sentBar = wantedBar
154  await send($, sentBar)
155}
156
157async function waitOnYou($: EngineInterface, id: string) {
158  waitingOn.add(id)
159  isWaiting = true
160  void setStatus($, 'waiting').catch(() => {})
161  await Promise.all([drawTitle($), drawBar($)])
162}
163
164/**
165 * A call that asks waits in Claude Code's dialog, or in auto mode its checker. Only the dialog marks the session
166 * record waiting, so watch it while the call is pending. Mods hear neither classic.PermissionRequest nor
167 * classic.Notification while a dialog is up (checked on 2.1.301), so this file is the only sign.
168 */
169async function watchForDialog($: EngineInterface, id: string) {
170  asking.add(id)
171  // ponytail: polls every half second, 10 minutes at most; an event for the dialog would replace it.
172  for (let i = 0; i < 1200; i++) {
173    await $.clock.sleep(500)
174    if (!asking.has(id)) return
175    if (asksPermission(await $.fs.read(`${home}/.claude/sessions/${pid}.json`).catch(() => ''))) return waitOnYou($, id)
176  }
177}
178
179/** `id` was answered; the ❓ goes once nothing else waits on you. */
180async function answered($: EngineInterface, id: string) {
181  if (!waitingOn.delete(id) || waitingOn.size > 0) return
182  isWaiting = false
183  void setStatus($, isRunning ? 'working' : 'idle').catch(() => {})
184  await Promise.all([drawTitle($), drawBar($)])
185}
186
187/**
188 * A new title from the transcript (so a resumed session has its history), remembered for its conversation.
189 * `answer`: the reply that just ended, which the transcript may not hold yet. '' when there's nothing to summarize.
190 */
191async function retitle($: EngineInterface, answer?: string): Promise<string> {
192  const c = context(await $.session.messages())
193  if (c.prompts.length === 0) return ''
194  const r = await $.model.complete({ model: 'haiku', prompt: ask(c.prompts, answer ?? c.answer), maxTokens: 24 })
195  const words = r.isAnswered ? clean(r.text) : ''
196  if (!words) return ''
197  summary = words
198  await drawTitle($)
199  const file = titleFile(await $.session.id())
200  if (file) await $.process.run(['mkdir', '-p', titleDir()]).then(() => $.fs.write(file, words)).catch(() => {})
201  return words
202}
203
204// Each conversation's title, so resuming it (or reopening its workspace) puts the title back.
205const titleDir = () => `${home}/Library/Caches/claude-ghostty/titles`
206const titleFile = (sessionId?: string) => (home && sessionId && /^[0-9a-f-]{8,64}$/i.test(sessionId) ? `${titleDir()}/${sessionId}` : undefined)
207
208/** The title this conversation had, or a new one when it has history but no title yet. */
209async function restoreTitle($: EngineInterface) {
210  const file = titleFile(await $.session.id())
211  const saved = file ? clean(await $.fs.read(file).catch(() => '')) : ''
212  titledAt = Date.now()
213  if (!saved) return void (await retitle($))
214  summary = saved
215  await drawTitle($)
216}
217
218// ─── Session status (for /goto and /workspace) ─────────────────────────────
219
220const statusDir = () => `${home}/Library/Caches/claude-ghostty/sessions`
221
222/** This session's status file: only this session writes it, so sessions never race. */
223async function setStatus($: EngineInterface, next: Status) {
224  if (!home || !tty) return
225  if (next !== status || !statusSince) statusSince = Date.now()
226  status = next
227  const entry: Entry = { tty, pid, sessionId: await $.session.id(), cwd: await $.session.cwd(), status, since: statusSince }
228  await $.process.run(['mkdir', '-p', statusDir()])
229  await $.fs.write(`${statusDir()}/${tty.replace(/\W/g, '_')}.json`, JSON.stringify(entry))
230}
231
232async function readEntries($: EngineInterface): Promise<Map<string, Entry>> {
233  const files = await $.fs.list(statusDir()).catch(() => [])
234  const entries = await Promise.all(
235    files.filter(f => f.name.endsWith('.json')).map(f => $.fs.read(`${statusDir()}/${f.name}`).then(parseEntry, () => undefined)),
236  )
237  return new Map(entries.filter(e => e !== undefined).map(e => [e.tty, e]))
238}
239
240async function rankedSessions($: EngineInterface): Promise<Ranked[]> {
241  const [sessions, entries] = await Promise.all([listSessions($), readEntries($)])
242  return rank(sessions, entries)
243}
244
245// ─── Workspaces ──────────────────────────────────────────────────────────────
246
247const workspaceDir = () => `${home}/.claude/workspaces`
248
249// The window holding this session, as "tab index<TAB>tty<TAB>folder<TAB>title<TAB>terminal id" lines in order.
250const LIST_WINDOW = `on run argv
251  set myTty to item 1 of argv
252  set sep to character id 9
253  tell application "Ghostty"
254    repeat with w in windows
255      set hit to false
256      repeat with t in terminals of w
257        if tty of t is myTty then set hit to true
258      end repeat
259      if hit then
260        set out to ""
261        repeat with tb in tabs of w
262          repeat with t in terminals of tb
263            set out to out & (index of tb) & sep & (tty of t) & sep & (working directory of t) & sep & (name of t) & sep & (id of t) & linefeed
264          end repeat
265        end repeat
266        return out
267      end if
268    end repeat
269  end tell
270  return ""
271end run`
272
273// Every Claude process with its tty: "/dev/ttys004 36583" lines.
274const CLAUDE_PIDS = `ps -ax -o tty=,pid=,comm= | awk 'match($3, "(^|[/])claude$") { print "/dev/" $1, $2 }'`
275
276/** Claude Code's records of running sessions: process ID → conversation ID. */
277async function conversations($: EngineInterface, pids: Iterable<string>): Promise<Map<string, string>> {
278  const pairs = await Promise.all(
279    [...pids].map(async pid => [pid, conversationOf(await $.fs.read(`${home}/.claude/sessions/${pid}.json`).catch(() => ''))] as const),
280  )
281  return new Map(pairs.filter((p): p is readonly [string, string] => p[1] !== undefined))
282}
283
284type Saved = { text: string; window?: string; claudePids?: Map<string, string> }
285
286/** Every saved workspace, read in full. */
287async function savedWorkspaces($: EngineInterface): Promise<Array<Workspace & { file: string }>> {
288  const files = await $.fs.list(workspaceDir()).catch(() => [])
289  const all = await Promise.all(
290    files.filter(f => f.name.endsWith('.json')).map(async f => {
291      const file = `${workspaceDir()}/${f.name}`
292      const ws = parseWorkspace(await $.fs.read(file).catch(() => ''))
293      return ws ? { ...ws, file } : undefined
294    }),
295  )
296  return all.filter(w => w !== undefined)
297}
298
299async function saveWorkspace($: EngineInterface, given: string): Promise<Saved> {
300  const [window, ps] = await Promise.all([$.process.run(['osascript', '-e', LIST_WINDOW, tty]), $.process.run(['sh', '-c', CLAUDE_PIDS])])
301  if (window.exitCode !== 0) return { text: `Couldn't read this Ghostty window: ${window.stderr.trim().slice(0, 160)}` }
302  const claudePids = claudePidsFrom(ps.stdout)
303  const tabs = fromWindow(window.stdout, claudePids, await conversations($, claudePids.values()))
304  if (tabs.length === 0) return { text: "Couldn't find this session's Ghostty window." }
305  // No name: the saved workspace this window was opened from keeps its name and file, else Haiku names it.
306  const all = await savedWorkspaces($)
307  const same = given.trim() ? undefined : sameWorkspace(tabs, all)
308  let name = given.trim() || same?.name || ''
309  if (!name) {
310    const r = await $.model.complete({ model: 'haiku', prompt: namePrompt(tabs), maxTokens: 20, timeoutMs: 8000 })
311    name = (r.isAnswered && cleanName(r.text)) || `Workspace ${new Date().toISOString().slice(0, 10)}`
312  }
313  const file = same?.file ?? fileFor(name, all, given.trim() !== '')
314  const existed = all.some(w => w.file === file)
315  const ws: Workspace = { name, savedAt: Date.now(), tabs }
316  await $.process.run(['mkdir', '-p', workspaceDir()])
317  await $.fs.write(file, JSON.stringify(ws, null, 2))
318  const unknown = tabs.flat().filter(p => p.kind === 'claude' && !p.sessionId)
319  const text = `${existed ? 'Updated' : 'Saved'} workspace "${name}": ${describe(ws)}.` +
320    (unknown.length ? ` Couldn't find the conversation for ${unknown.map(p => `"${p.title}"`).join(', ')}: ${unknown.length === 1 ? 'it' : 'they'} will reopen as a new session.` : '')
321  return { text, window: window.stdout, claudePids }
322}
323
324/**
325 * Where `name` is saved: its slug's file, unless that holds a different workspace (another name, or one
326 * Haiku's name happened to land on), which is never overwritten: then the first free `-2`, `-3`, …
327 */
328function fileFor(name: string, all: ReadonlyArray<{ file: string; name: string }>, isNamedByYou: boolean): string {
329  const at = (suffix: string) => `${workspaceDir()}/${slug(name)}${suffix}.json`
330  const held = all.find(w => w.file === at(''))
331  if (!held || (isNamedByYou && held.name.toLowerCase() === name.toLowerCase())) return at('')
332  for (let n = 2; ; n++) if (!all.some(w => w.file === at(`-${n}`))) return at(`-${n}`)
333}
334
335/**
336 * Saves the window, exits every other Claude session in it and closes their panes, then exits this
337 * session too, leaving its tab open at the shell. Shell panes stay open. Sessions still working or waiting on
338 * you are not stopped unless `force`.
339 */
340async function closeWorkspace($: EngineInterface, given: string, force: boolean): Promise<string> {
341  const saved = await saveWorkspace($, given)
342  if (!saved.window || !saved.claudePids) return saved.text
343  const targets = closable(saved.window, saved.claudePids, tty)
344  if (targets.length === 0) return exitThisSession($, `${saved.text} Exiting this session.`)
345  if (!force) {
346    const entries = await readEntries($)
347    const busy = targets.filter(t => entries.get(t.tty)?.status === 'working' || entries.get(t.tty)?.status === 'waiting')
348    if (busy.length) {
349      const names = busy.map(t => `"${t.title || t.tty}"`).join(', ')
350      return `${saved.text} Closed nothing: ${names} ${busy.length === 1 ? 'is' : 'are'} still working or waiting on you. ` +
351        'Let them finish, or /workspace close --force.'
352    }
353  }
354  // A polite exit, as quitting from outside does; Claude has written each conversation to disk as it went.
355  await $.process.run(['kill', '-TERM', ...targets.map(t => t.pid)])
356  let alive = targets
357  for (let waited = 0; alive.length && waited < 5000; waited += 250) {
358    await $.clock.sleep(250)
359    const r = await $.process.run(['sh', '-c', 'for p; do kill -0 "$p" 2>/dev/null && echo "$p"; done', 'sh', ...alive.map(t => t.pid)])
360    const running = new Set(r.stdout.split('\n').filter(Boolean))
361    alive = alive.filter(t => running.has(t.pid))
362  }
363  const exited = targets.filter(t => !alive.includes(t))
364  for (const t of exited) await $.process.run(['osascript', '-e', CLOSE_TERMINAL, t.id])
365  return exitThisSession(
366    $,
367    `${saved.text} Closed ${exited.length} other Claude session${exited.length === 1 ? '' : 's'}.` +
368      (alive.length ? ` ${alive.length} didn't exit within 5 seconds and ${alive.length === 1 ? 'is' : 'are'} still open.` : '') +
369      ' Exiting this session.',
370  )
371}
372
373/** Quits this session the way typing /exit does, just after `message` has printed: the tab stays, at the shell. */
374function exitThisSession($: EngineInterface, message: string): string {
375  $.clock.after(300, () => void $.command.run({ command: 'exit', args: '' }).catch(() => {}))
376  return message
377}
378
379const CLOSE_TERMINAL = `on run argv
380  tell application "Ghostty" to close (first terminal whose id is (item 1 of argv))
381end run`
382
383async function loadWorkspaces($: EngineInterface): Promise<WorkspaceRow[]> {
384  const all = await savedWorkspaces($)
385  return all.map(ws => ({ file: ws.file, name: ws.name, summary: describe(ws), savedAt: ws.savedAt })).sort((a, b) => b.savedAt - a.savedAt)
386}
387
388async function openWorkspace($: EngineInterface, file: string): Promise<string> {
389  const ws = parseWorkspace(await $.fs.read(file).catch(() => ''))
390  if (!ws) return "That workspace couldn't be read."
391  // Each Claude tab's saved title, for its session to pick up when it resumes; a title the session saved itself wins.
392  await $.process.run(['mkdir', '-p', titleDir()])
393  for (const p of ws.tabs.flat()) {
394    const file = p.kind === 'claude' ? titleFile(p.sessionId) : undefined
395    if (file && bare(p.title) && !(await $.fs.stat(file).then(() => true, () => false))) await $.fs.write(file, clean(bare(p.title)))
396  }
397  const r = await $.process.run(['osascript', '-e', openScript(ws)])
398  return r.exitCode === 0 ? `Opened "${ws.name}": ${describe(ws)}.` : `Ghostty couldn't open it: ${r.stderr.trim().slice(0, 160)}`
399}
400
401async function deleteWorkspace($: EngineInterface, file: string) {
402  await $.process.run(['rm', '-f', file])
403  await update($, workspaceRows, rows => rows.filter(r => r.file !== file))
404}
405
406// ─── Keybinds ────────────────────────────────────────────────────────────────
407
408// Where Ghostty reads its config: ~/.config/ghostty when that's in use, else the macOS app folder.
409async function configDir($: EngineInterface): Promise<string> {
410  const xdg = `${home}/.config/ghostty`
411  const app = `${home}/Library/Application Support/com.mitchellh.ghostty`
412  const r = await $.process.run(['sh', '-c', '[ -f "$1/config" ] && echo "$1" || echo "$2"', 'sh', xdg, app])
413  return r.stdout.trim() || app
414}
415
416async function readBindings($: EngineInterface): Promise<{ dir: string; file: string; text: string | null }> {
417  const dir = await configDir($)
418  const file = `${dir}/claude-keybinds`
419  const text = await $.fs.read(file).catch(() => null)
420  return { dir, file, text }
421}
422
423/** Writes the bindings, makes the main config load them, and lets Ghostty check and reload. Undoes a rejected change. */
424async function saveBindings($: EngineInterface, bindings: readonly Binding[]): Promise<string | undefined> {
425  const { dir, file, text } = await readBindings($)
426  const previous = text ?? ''
427  await $.process.run(['mkdir', '-p', dir])
428  await $.fs.write(file, renderFile(previous, bindings))
429  const main = `${dir}/config`
430  const config = await $.fs.read(main).catch(() => '')
431  if (withInclude(config) !== config) await $.fs.write(main, withInclude(config))
432  const check = await $.process.run(['sh', '-c', '"$GHOSTTY_BIN_DIR/ghostty" +validate-config 2>&1'])
433  if (check.exitCode !== 0) {
434    await $.fs.write(file, previous)
435    return check.stdout.trim().split('\n')[0] || 'Ghostty rejected the change'
436  }
437  await $.process.run(['osascript', '-e', 'tell application "Ghostty" to perform action "reload_config" on (first terminal)'])
438  return undefined
439}
440
441function listing(bindings: readonly Binding[]): string {
442  if (bindings.length === 0) return 'No Claude keybinds yet. /keybind add <keys> <text>, e.g. /keybind add super+ctrl+h /say hush'
443  return bindings.map(b => `${prettyKeys(b.keys).padEnd(6)} ${b.text}`).join('\n')
444}
445
446export const register: Register = (on, options) => {
447  // $.ghostty.isFocused: other mods (notify) ask whether you're looking at this session. The noun's own method holds
448  // no `$`, so it only answers when nothing else does; the hook below, which has one, does the asking.
449  on('engine.create', async (_$, e, next) => ({ ...(await next(e)), ghostty: { isFocused: async () => false } }))
450
451  on('ghostty.isFocused', async $ => ({ value: await isFocused($) }))
452
453  cfg = config(options)
454  // Hooks that gate a prompt or a tool call pass it on untouched if they fail: the tab must never block work.
455
456  on('session.start', async ($, e, next) => {
457    await locate($)
458    void setStatus($, 'idle').catch(() => {})
459    if (cfg.tabTitle) void restoreTitle($).catch(() => {})
460    await $.command.register({ name: 'title', description: 'A new 4-word tab title for this session, now' })
461    await $.command.register({ name: 'keybind', description: 'Ghostty keys that type into Claude: /keybind, /keybind add <keys> <text>, /keybind remove <keys>' })
462    // First start: install the default keys once (a later /keybind remove sticks, since the file then exists).
463    if (cfg.keybinds && (await readBindings($).catch(() => null))?.text === null) void saveBindings($, DEFAULTS).catch(() => {})
464    await $.command.register({ name: 'goto', description: 'Jump to another Claude session in Ghostty (waiting ones first): /goto, /goto next, or /goto <number or words>' })
465    await $.command.register({ name: 'workspace', description: 'Save this Ghostty window of sessions, or reopen one: /workspace save [name], /workspace close [name] (save, then exit the other sessions), /workspace list, /workspace open <name>' })
466    return next(e)
467  })
468
469  // Claude exits: clear the bar. /clear ends the conversation but not Claude, and no session.start follows:
470  // drop the old topic from the tab and let the next finished turn title the new one.
471  on('session.end', async ($, e, next) => {
472    if (cfg.tabProgress) await send($, progress(Progress.hide))
473    if (e.reason === 'clear') {
474      summary = ''
475      titledAt = 0
476      await drawTitle($)
477    }
478    return next(e)
479  })
480
481  on('command.run', { command: 'title' }, async $ => {
482    titledAt = Date.now()
483    const words = await retitle($).catch(() => '')
484    return { text: words ? `Tab title: ${words}` : 'Nothing to summarize yet: send a message first.' }
485  })
486
487  on('command.run', { command: 'goto' }, async ($, e) => {
488    const ranked = await rankedSessions($).catch((err: Error) => err)
489    if (ranked instanceof Error) return { text: `/goto couldn't list sessions: ${ranked.message}` }
490    const others = ranked.filter(s => !s.isMe)
491    if (others.length === 0) return { text: 'No other Claude sessions are running in Ghostty.' }
492    const query = e.args.trim()
493    if (query === 'next') {
494      const waiting = nextWaiting(ranked)
495      if (!waiting) return { text: 'No session is waiting on you.' }
496      await goTo($, waiting)
497      return { text: `→ ${waiting.title} (${badge(waiting, Date.now())})` }
498    }
499    if (query) {
500      const hits = matchSessions(ranked, query).filter(s => !s.isMe)
501      if (hits.length === 1) {
502        await goTo($, hits[0]!)
503        return { text: `→ ${hits[0]!.title}` }
504      }
505      if (hits.length === 0) return { text: `No Claude session matches "${query}". /goto lists them.` }
506    }
507    picks = ranked
508    await $.ui.open({ id: GOTO, title: 'Claude sessions', focus: true, closeOnEscape: true, rows: ranked.length + 1 })
509    const waiting = others.filter(s => s.status === 'waiting').length
510    return { text: `${others.length} other Claude session${others.length === 1 ? '' : 's'}${waiting ? `, ${waiting} waiting on you` : ''}: pick one above.` }
511  })
512
513  on('command.run', { command: 'workspace' }, async ($, e) => {
514    const [verb = 'list', ...rest] = e.args.trim().split(/\s+/).filter(Boolean)
515    const arg = rest.join(' ')
516    if (verb === 'save') return { text: (await saveWorkspace($, arg)).text }
517    if (verb === 'close') return { text: await closeWorkspace($, rest.filter(w => w !== '--force').join(' '), rest.includes('--force')) }
518    const rows = await loadWorkspaces($)
519    if (verb === 'open' && arg) {
520      const hit = rows.find(r => r.name.toLowerCase() === arg.toLowerCase()) ?? rows.find(r => r.name.toLowerCase().includes(arg.toLowerCase()))
521      return { text: hit ? await openWorkspace($, hit.file) : `No workspace called "${arg}". /workspace list shows them.` }
522    }
523    if (verb !== 'list' && verb !== 'open') return { text: 'Usage: /workspace save [name], /workspace close [name], /workspace list, /workspace open <name>' }
524    if (rows.length === 0) return { text: 'No saved workspaces yet. /workspace save remembers this window.' }
525    await update($, workspaceRows, () => rows)
526    await $.ui.open({ id: WORKSPACES, title: 'Workspaces', focus: true, closeOnEscape: true, rows: rows.length + 1 })
527    return { text: `${rows.length} saved workspace${rows.length === 1 ? '' : 's'}: pick one above.` }
528  })
529
530  on('command.run', { command: 'keybind' }, async ($, e) => {
531    const [verb, ...rest] = e.args.trim().split(/\s+/)
532    const current = parseBindings((await readBindings($)).text ?? '')
533    if (!verb || verb === 'list') return { text: listing(current) }
534    if (verb === 'add') {
535      const b = parseAdd(rest.join(' '))
536      if (typeof b === 'string') return { text: b }
537      const error = await saveBindings($, upsert(current, b))
538      return { text: error ? `Ghostty didn't accept that: ${error}` : `${prettyKeys(b.keys)} now types ${b.text} ⏎` }
539    }
540    if (verb === 'remove') {
541      const keys = (rest[0] ?? '').toLowerCase()
542      if (!current.some(b => b.keys === keys)) return { text: `No Claude keybind on ${keys || '(no keys given)'}.\n${listing(current)}` }
543      const error = await saveBindings($, current.filter(b => b.keys !== keys))
544      return { text: error ? `Ghostty didn't accept that: ${error}` : `Removed ${prettyKeys(keys)}.` }
545    }
546    return { text: 'Usage: /keybind, /keybind add <keys> <text>, /keybind remove <keys>' }
547  })
548
549  on('ui.render', { component: 'Pane', requestId: GOTO }, async ($, e) => {
550    const { Box, Button, Text } = $.ui.resolve(e)
551    const now = Date.now()
552    const label = (s: Ranked) => `${badge(s, now).padEnd(6)} ${s.title} · ${shortFolder(s.folder, home)}`
553    const first = picks.findIndex(p => !p.isMe)
554    return (
555      <Box flexDirection="column">
556        {picks.map((s, i) =>
557          s.isMe ? (
558            <Text dimColor>
559              {'   '}
560              {label(s)} (this session)
561            </Text>
562          ) : (
563            <Button
564              key={`goto-${i}`}
565              plain
566              hotkey={i < 9 ? String(i + 1) : undefined}
567              label={label(s)}
568              autoFocus={first === i ? true : undefined}
569              onPress={async () => {
570                await $.ui.close({ id: GOTO })
571                await goTo($, s)
572              }}
573            />
574          ),
575        )}
576        <Text dimColor>❓ waiting on you · ⏳ working · number or Enter to jump · Esc to close</Text>
577      </Box>
578    )
579  })
580
581  on('ui.render', { component: 'Pane', requestId: WORKSPACES }, async ($, e) => {
582    const { Box, Button, Text } = $.ui.resolve(e)
583    const rows = await read($, workspaceRows)
584    if (rows.length === 0) return <Text dimColor>No saved workspaces. /workspace save remembers this window.</Text>
585    return (
586      <Box flexDirection="column">
587        {rows.map((r, i) => (
588          <Box flexDirection="row">
589            <Button
590              key={`ws-open-${i}`}
591              plain
592              hotkey={i < 9 ? String(i + 1) : undefined}
593              label={`${r.name} · ${r.summary} · ${new Date(r.savedAt).toLocaleDateString()}`}
594              autoFocus={i === 0 ? true : undefined}
595              onPress={async () => {
596                await $.ui.close({ id: WORKSPACES })
597                const text = await openWorkspace($, r.file)
598                $.ui.toast(text)
599              }}
600            />
601            <Text> </Text>
602            <Button key={`ws-del-${i}`} plain dimColor label="✕ delete" onPress={() => deleteWorkspace($, r.file)} />
603          </Box>
604        ))}
605        <Text dimColor>number or Enter to open · Tab to ✕ delete · Esc to close</Text>
606      </Box>
607    )
608  })
609
610  on('prompt.submit', async ($, e, next) => {
611    hasFailed = false
612    isRunning = true
613    isWaiting = false
614    waitingOn.clear()
615    void Promise.all([drawTitle($), drawBar($), setStatus($, 'working').catch(() => {})])
616    return next(e)
617  }).catch(($, e, next) => next(e))
618
619  on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
620    if (e.tool_use_id) void waitOnYou($, e.tool_use_id)
621    return next(e)
622  }).catch(($, e, next) => next(e))
623
624  // Every tool call: a permission prompt or a question waits inside next(); its return means you answered that one.
625  // Other calls finishing meanwhile (parallel reads, subagents) leave the ❓ alone.
626  on('tool.call', async ($, e, next) => {
627    const ran = await next(e)
628    const id = e.tool_use_id ?? ''
629    asking.delete(id)
630    const failed = ran.deny === undefined && ran.isError === true
631    if (!e.agentId && failed !== hasFailed) {
632      hasFailed = failed
633      void drawBar($)
634    }
635    void answered($, id)
636    return ran
637  }).catch(($, e, next) => next(e))
638
639  on('tool.check', async ($, e, next) => {
640    const r = await next(e)
641    if (r.decision === 'ask' && e.tool_use_id) void watchForDialog($, e.tool_use_id).catch(() => {})
642    return r
643  }).catch(($, e, next) => next(e))
644
645  on('turn.complete', async ($, e, next) => {
646    if (e.agentId) return next(e)
647    isRunning = false
648    isWaiting = false
649    waitingOn.clear()
650    void Promise.all([drawTitle($), drawBar($), setStatus($, 'idle').catch(() => {})])
651    const now = Date.now()
652    if (cfg.tabTitle && now - titledAt >= cfg.titleMinutes * 60_000) {
653      titledAt = now
654      void retitle($, e.answer).catch(() => {})
655    }
656    return next(e)
657  })
658}
659
hooks/term.ts 62 lines
1// Ghostty's escape sequences and actions, and the small decisions around them. Pure: register.ts sends them.
2
3const ESC = '\x1b'
4const BEL = '\x07'
5
6/** Strips control characters, so text from the model or a tool can't smuggle in escape sequences. */
7export function safe(text: string): string {
8  return text.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ').replace(/\s+/g, ' ').trim()
9}
10
11/** Ghostty's set_surface_title action, sent over AppleScript so no bytes race Claude's own drawing on the tty. */
12export const titleAction = (text: string) => `set_surface_title:${safe(text)}`
13
14/** OSC 9;4 states, as Ghostty draws them on the tab. */
15export const Progress = { hide: 0, value: 1, error: 2, busy: 3, paused: 4 } as const
16
17/** OSC 9;4: the tab's progress bar. `percent` matters for `value` (and colors `error`/`paused` when given). */
18export function progress(state: number, percent?: number): string {
19  const p = percent === undefined ? '' : `;${Math.max(0, Math.min(100, Math.round(percent)))}`
20  return `${ESC}]9;4;${state}${p}${BEL}`
21}
22
23/** The tab title: the session's summary, with ❓ in front while Claude waits on you. */
24export function tabTitle(summary: string, isWaiting: boolean): string {
25  return `${isWaiting ? '❓' : '✳'} ${summary || 'Claude Code'}`
26}
27
28/** The bar for a running turn: red after a failed tool call, else busy. */
29export function runningBar(hasFailed: boolean): string {
30  return hasFailed ? progress(Progress.error, 100) : progress(Progress.busy)
31}
32
33// ─── /goto ───────────────────────────────────────────────────────────────────
34
35export type Session = { id: string; tty: string; title: string; folder: string; isMe: boolean }
36
37/**
38 * Ghostty's terminals ("id\ttty\ttitle\tfolder" lines) that run Claude (by tty, from `ps`).
39 * Splits of one tab running Claude are separate sessions; a tab without Claude isn't one.
40 */
41export function claudeSessions(terminals: string, claudeTtys: ReadonlySet<string>, myTty: string): Session[] {
42  return terminals
43    .split('\n')
44    .map(line => line.split('\t'))
45    .filter(f => f.length >= 4 && claudeTtys.has(f[1]!))
46    .map(([id, tty, title, folder]) => ({ id: id!, tty: tty!, title: safe(title!), folder: folder!, isMe: tty === myTty }))
47}
48
49/** The sessions `/goto <query>` means: a number from the list, or text in the title or folder. */
50export function matchSessions(sessions: readonly Session[], query: string): Session[] {
51  const q = query.trim().toLowerCase()
52  if (!q) return []
53  const n = Number(q)
54  if (Number.isInteger(n) && n >= 1 && n <= sessions.length) return [sessions[n - 1]!]
55  return sessions.filter(s => s.title.toLowerCase().includes(q) || s.folder.toLowerCase().includes(q))
56}
57
58/** "~/work/brilliant" for display. */
59export function shortFolder(folder: string, home: string): string {
60  return home && folder.startsWith(home) ? `~${folder.slice(home.length)}` : folder
61}
62
hooks/keybinds.ts 63 lines
1// Ghostty keybinds that type into Claude, kept in their own file the main Ghostty config includes.
2
3export type Binding = { keys: string; text: string }
4
5export const HEADER = [
6  '# Ghostty keys that type into Claude Code, managed with /keybind (the ghostty Claude mod).',
7  '# Loaded by `config-file = ?claude-keybinds` in your Ghostty config. Edits by hand are kept.',
8]
9
10/** The line that makes the main config load this file; `?` means a missing file is fine. */
11export const INCLUDE = 'config-file = ?claude-keybinds'
12
13/** What every new install starts with. */
14export const DEFAULTS: Binding[] = [{ keys: 'super+ctrl+g', text: '/goto' }]
15
16/** Ghostty's `text:` action takes a Zig string literal: backslashes doubled, then Enter as \r. */
17export function bindingLine(b: Binding): string {
18  return `keybind = ${b.keys}=text:${b.text.replace(/\\/g, '\\\\')}\\r`
19}
20
21/** The bindings a keybinds file holds (only `text:` ones ending in Enter are this mod's shape). */
22export function parseBindings(file: string): Binding[] {
23  const out: Binding[] = []
24  for (const line of file.split('\n')) {
25    const m = /^\s*keybind\s*=\s*([^=\s]+)=text:(.*)\\r\s*$/.exec(line)
26    if (m) out.push({ keys: m[1]!, text: m[2]!.replace(/\\\\/g, '\\') })
27  }
28  return out
29}
30
31/** The whole file for `bindings`, keeping any other lines you wrote by hand. */
32export function renderFile(previous: string, bindings: readonly Binding[]): string {
33  const mine = previous.split('\n').filter(l => l.trim() && !HEADER.includes(l) && !/^\s*keybind\s*=\s*[^=\s]+=text:.*\\r\s*$/.test(l))
34  return [...HEADER, ...mine, ...bindings.map(bindingLine)].join('\n') + '\n'
35}
36
37/** Adds or replaces the binding for `keys`. */
38export function upsert(bindings: readonly Binding[], b: Binding): Binding[] {
39  return [...bindings.filter(x => x.keys !== b.keys), b]
40}
41
42/** `super+ctrl+g` → `⌘⌃G`, for display. */
43export function prettyKeys(keys: string): string {
44  const sym: Record<string, string> = { super: '⌘', cmd: '⌘', ctrl: '⌃', alt: '⌥', opt: '⌥', shift: '⇧' }
45  return keys.split('+').map(k => sym[k] ?? k.toUpperCase()).join('')
46}
47
48/** `/keybind add <keys> <text…>` → a binding, or why not. */
49export function parseAdd(args: string): Binding | string {
50  const [keys, ...rest] = args.trim().split(/\s+/)
51  const text = rest.join(' ')
52  if (!keys || !text) return 'Usage: /keybind add <keys> <text>, e.g. /keybind add super+ctrl+h /say hush'
53  if (!/^[a-z0-9_+.,;'\[\]\/`-]+$/i.test(keys)) return `"${keys}" isn't a Ghostty key combination (like super+ctrl+g)`
54  if (/[\u0000-\u001f\u007f]/.test(text)) return 'The text can\'t contain control characters'
55  return { keys: keys.toLowerCase(), text }
56}
57
58/** The main Ghostty config with the include line added once. */
59export function withInclude(config: string): string {
60  if (config.split('\n').some(l => l.trim() === INCLUDE)) return config
61  return `${config.replace(/\n*$/, '\n')}\n# Claude Code keybinds (/keybind)\n${INCLUDE}\n`
62}
63
hooks/registry.ts 64 lines
1// Each Claude session's status in its own small file, so /goto can rank sessions and /workspace can resume them.
2
3import type { Session } from './term'
4
5export type Status = 'idle' | 'working' | 'waiting'
6
7/** One session's file: `<dir>/<tty name>.json`, written only by that session. */
8export type Entry = { tty: string; pid: string; sessionId: string; cwd: string; status: Status; since: number }
9
10export function parseEntry(text: string): Entry | undefined {
11  try {
12    const e = JSON.parse(text) as Partial<Entry>
13    return typeof e.tty === 'string' && typeof e.status === 'string' ? (e as Entry) : undefined
14  } catch {
15    return undefined
16  }
17}
18
19/**
20 * Claude Code's own record of a running session (~/.claude/sessions/<pid>.json) says a permission dialog is up.
21 * Only the dialog sets it: auto mode's checker approves a call that asks without one.
22 */
23export function asksPermission(record: string): boolean {
24  try {
25    const r = JSON.parse(record) as { status?: unknown; waitingFor?: unknown }
26    return r.status === 'waiting' && typeof r.waitingFor === 'string' && /permission/i.test(r.waitingFor)
27  } catch {
28    return false
29  }
30}
31
32export type Ranked = Session & { status: Status; since?: number }
33
34const ORDER: Record<Status, number> = { waiting: 0, working: 1, idle: 2 }
35
36/** Waiting on you first (longest wait first), then working, then idle; this session last. */
37export function rank(sessions: readonly Session[], entries: ReadonlyMap<string, Entry>): Ranked[] {
38  return sessions
39    .map(s => {
40      const e = entries.get(s.tty)
41      return { ...s, status: e?.status ?? 'idle', since: e?.since }
42    })
43    .sort((a, b) => Number(a.isMe) - Number(b.isMe) || ORDER[a.status] - ORDER[b.status] || (a.since ?? 0) - (b.since ?? 0))
44}
45
46/** "45s", "4m", "1h 5m". */
47export function ago(ms: number): string {
48  const s = Math.max(0, Math.round(ms / 1000))
49  if (s < 60) return `${s}s`
50  const m = Math.floor(s / 60)
51  return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${m % 60}m`
52}
53
54/** The picker row's lead: ❓ and the wait, ⏳ while working, nothing when idle. */
55export function badge(r: Ranked, now: number): string {
56  if (r.status === 'waiting') return `❓ ${r.since ? ago(now - r.since) : ''}`.trim()
57  return r.status === 'working' ? '⏳' : ''
58}
59
60/** The other session waiting on you longest, for `/goto next`. */
61export function nextWaiting(ranked: readonly Ranked[]): Ranked | undefined {
62  return ranked.find(r => !r.isMe && r.status === 'waiting')
63}
64
hooks/title.ts 38 lines
1// The model's reply as a safe tab title: no control characters (no escape-sequence injection), 4 words, 48 chars.
2export function clean(reply: string): string {
3  return reply
4    .replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ')
5    .replace(/["'`*_#.]/g, '')
6    .split(/\s+/)
7    .filter(Boolean)
8    .slice(0, 4)
9    .join(' ')
10    .slice(0, 48)
11}
12
13/** Your last 10 requests and Claude's latest reply, from the transcript; markup-only messages (commands, notices) are skipped. */
14export function context(messages: ReadonlyArray<{ role: string; text: string }>): { prompts: string[]; answer: string } {
15  const said = messages.filter(m => m.text.trim() && !m.text.trimStart().startsWith('<'))
16  return {
17    prompts: said.filter(m => m.role === 'user').map(m => m.text).slice(-10),
18    answer: [...said].reverse().find(m => m.role === 'assistant')?.text ?? '',
19  }
20}
21
22export function ask(prompts: readonly string[], answer: string): string {
23  return [
24    'Recent requests in a coding session, oldest first:',
25    ...prompts.map(p => `- ${p.slice(0, 300)}`),
26    '',
27    `Latest reply (start): ${answer.slice(0, 600)}`,
28    '',
29    'Summarize what this session is about in exactly 4 words, Title Case. Reply with the 4 words only.',
30  ].join('\n')
31}
32
33/** A tab's title without the ✳ or ❓ this mod puts in front; '' for the default "Claude Code". */
34export function bare(tabName: string): string {
35  const words = tabName.replace(/^[✳❓]️?\s*/u, '').trim()
36  return words === 'Claude Code' ? '' : words
37}
38
hooks/workspace.ts 163 lines
1// Workspaces: a Ghostty window's tabs of Claude sessions and shells, saved and reopened.
2
3import { safe } from './term'
4import { bare } from './title'
5
6/** A Claude tab resumes its conversation (or the folder's latest, without a known ID); a shell just opens there. */
7export type Pane = { kind: 'claude'; cwd: string; title: string; sessionId?: string } | { kind: 'shell'; cwd: string; title: string }
8
9/** Each tab's panes in order: the first is the tab, the rest its splits. */
10export type Workspace = { name: string; savedAt: number; tabs: Pane[][] }
11
12/**
13 * The window's terminals ("tab index<TAB>tty<TAB>folder<TAB>title" lines, in order) as tabs of panes.
14 * A pane is Claude when Claude runs on its tty (`claudePids`: tty → Claude's process ID); its conversation
15 * is the one Claude Code records for that process (`conversations`: pid → session ID).
16 */
17export function fromWindow(
18  lines: string,
19  claudePids: ReadonlyMap<string, string>,
20  conversations: ReadonlyMap<string, string>,
21): Pane[][] {
22  const tabs = new Map<string, Pane[]>()
23  for (const line of lines.split('\n')) {
24    const [tab, tty, cwd, title] = line.split('\t')
25    if (!tab || !tty || cwd === undefined) continue
26    const name = bare(safe(title ?? ''))
27    const pid = claudePids.get(tty)
28    const pane: Pane = pid
29      ? { kind: 'claude', cwd, title: name, sessionId: conversations.get(pid) }
30      : { kind: 'shell', cwd, title: name }
31    tabs.set(tab, [...(tabs.get(tab) ?? []), pane])
32  }
33  return [...tabs.values()]
34}
35
36/** `ps` lines ("/dev/ttys004 36583") → tty → Claude's process ID. */
37export function claudePidsFrom(ps: string): Map<string, string> {
38  return new Map(ps.split('\n').map(l => l.trim().split(/\s+/)).filter(f => f.length === 2).map(([tty, pid]) => [tty!, pid!]))
39}
40
41/** Claude Code's own record of a running session (~/.claude/sessions/<pid>.json) → its conversation ID. */
42export function conversationOf(record: string): string | undefined {
43  try {
44    const id = (JSON.parse(record) as { sessionId?: unknown }).sessionId
45    return typeof id === 'string' ? id : undefined
46  } catch {
47    return undefined
48  }
49}
50
51/** The conversations a workspace resumes. */
52export function conversationsIn(ws: Pick<Workspace, 'tabs'>): Set<string> {
53  return new Set(ws.tabs.flat().flatMap(p => (p.kind === 'claude' && p.sessionId ? [p.sessionId] : [])))
54}
55
56/**
57 * The saved workspace this window is (at least half the same conversations), so saving it again,
58 * or closing it, updates that one instead of making a near-duplicate under a new name.
59 */
60export function sameWorkspace<T extends Pick<Workspace, 'tabs'>>(tabs: Pane[][], saved: readonly T[]): T | undefined {
61  const mine = conversationsIn({ tabs })
62  if (mine.size === 0) return undefined
63  let best: T | undefined
64  let bestShare = 0.5
65  for (const ws of saved) {
66    const theirs = conversationsIn(ws)
67    const shared = [...mine].filter(id => theirs.has(id)).length
68    const share = shared / Math.max(mine.size, theirs.size)
69    if (share >= bestShare) [best, bestShare] = [ws, share]
70  }
71  return best
72}
73
74/** The terminals `/workspace close` exits and closes: every Claude pane but this session's own. */
75export function closable(
76  lines: string,
77  claudePids: ReadonlyMap<string, string>,
78  myTty: string,
79): Array<{ id: string; tty: string; pid: string; title: string }> {
80  return lines
81    .split('\n')
82    .map(l => l.split('\t'))
83    .filter(f => f.length >= 5 && f[1] !== myTty && claudePids.has(f[1]!))
84    .map(f => ({ id: f[4]!, tty: f[1]!, pid: claudePids.get(f[1]!)!, title: bare(safe(f[3]!)) }))
85}
86
87/** "Brilliant Admin Work" → "brilliant-admin-work": the file name. */
88export function slug(name: string): string {
89  return name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'workspace'
90}
91
92export function namePrompt(tabs: readonly Pane[][]): string {
93  const rows = tabs.flat().map(p => `- ${p.title || '(untitled)'} in ${p.cwd}`)
94  return [
95    'These terminal tabs are being saved as a workspace. Name it in 2 to 4 words, Title Case,',
96    'after the work they share (a project or a task). Reply with the name only.',
97    '',
98    ...rows.slice(0, 30),
99  ].join('\n')
100}
101
102/** The model's reply as a name; empty when unusable. */
103export function cleanName(reply: string): string {
104  const name = safe(reply).replace(/["'`*_#.:]/g, '').trim()
105  return name.length >= 2 && name.length <= 48 ? name : ''
106}
107
108/** An AppleScript string literal. */
109const str = (s: string) => `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
110
111/** The command a pane starts with: resume its conversation, or a new session when it isn't known. */
112export function startCommand(p: Pane): string | undefined {
113  if (p.kind === 'shell') return undefined
114  return p.sessionId && /^[0-9a-f-]{8,64}$/i.test(p.sessionId) ? `claude --resume ${p.sessionId}` : 'claude'
115}
116
117/**
118 * AppleScript that recreates the workspace in a new window. Commands are typed into each pane's shell
119 * (initial input), so they run with your normal PATH and environment.
120 */
121export function openScript(ws: Workspace): string {
122  const out = ['tell application "Ghostty"']
123  let n = 0
124  const config = (p: Pane) => {
125    const c = `c${++n}`
126    out.push(`  set ${c} to new surface configuration`)
127    out.push(`  set initial working directory of ${c} to ${str(p.cwd)}`)
128    const cmd = startCommand(p)
129    if (cmd) out.push(`  set initial input of ${c} to ${str(cmd)} & linefeed`)
130    return c
131  }
132  ws.tabs.forEach((panes, i) => {
133    const [first, ...splits] = panes
134    if (!first) return
135    const c = config(first)
136    if (i === 0) {
137      out.push(`  set w to new window with configuration ${c}`)
138      out.push('  set t to focused terminal of selected tab of w')
139    } else {
140      out.push(`  set tb to new tab in w with configuration ${c}`)
141      out.push('  set t to focused terminal of tb')
142    }
143    for (const p of splits) out.push(`  set t to split t direction right with configuration ${config(p)}`)
144  })
145  out.push('  activate window w', 'end tell')
146  return out.join('\n')
147}
148
149/** "3 tabs · 2 Claude" for the picker. */
150export function summary(ws: Workspace): string {
151  const claude = ws.tabs.flat().filter(p => p.kind === 'claude').length
152  return `${ws.tabs.length} tab${ws.tabs.length === 1 ? '' : 's'} · ${claude} Claude`
153}
154
155export function parseWorkspace(text: string): Workspace | undefined {
156  try {
157    const w = JSON.parse(text) as Workspace
158    return typeof w.name === 'string' && Array.isArray(w.tabs) ? w : undefined
159  } catch {
160    return undefined
161  }
162}
163
types/index.d.ts 19 lines
1
2/** One saved workspace as the /workspace picker lists it. */
3export type WorkspaceRow = { file: string; name: string; summary: string; savedAt: number }
4
5/** The ghostty mod's answers about Ghostty, for other mods (notify). */
6export type Ghostty = {
7  /** This session's terminal is the one in front of you: Ghostty is the frontmost app and has it focused. */
8  isFocused: () => Promise<boolean>
9}
10
11declare module 'claude-code' {
12  interface EngineInterface {
13    ghostty: Ghostty
14  }
15  interface PluginState {
16    ghostty: { workspaces: WorkspaceRow[] }
17  }
18}
19