SLOPSHOPPER

session-relaunch

/relaunch restarts this Claude Code session in a new terminal tab with --resume <id>, so MCP servers added since it started are loaded.

guardcommandtoastprocesstimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · session-relaunch
› fix the failing auth test and add an audit log call ⏺ 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 › /relaunch ⎿ session-relaunch: Relaunch cancelled. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

session-relaunch

/relaunch restarts the current Claude Code session in a new terminal tab, so MCP servers you added since it started get loaded. It resumes this exact session by id, so it works even with several sessions open.

Works on Windows, macOS and Linux. Needs Claude Code 2.1.287 or later.

Install

/plugin marketplace add lperezmo/session-relaunch
/plugin install session-relaunch@session-relaunch

Usage

/relaunch                 asks: relaunch now, compact first, or open the tab and stay
/relaunch now [note]      reopen this session in a new tab and exit this one
/relaunch compact [note]  compact first (the note steers the summary), then relaunch
/relaunch stay [note]     open the new tab; it starts once you /exit here
/relaunch help            show this

The note is typed into the new session's prompt box. When a tool call adds or removes an MCP server, the mod prints a one-line reminder to /relaunch.

One catch: if you started the session with a prompt (claude "do X"), that prompt is part of the command line and gets sent again on relaunch.

What it does on your machine

  • Commands it runs: /exit after opening the new tab (and /compact with compact).
  • Programs it starts: powershell.exe with hooks/relaunch.ps1 on Windows, bash with hooks/relaunch.sh elsewhere. Each opens a terminal tab (Windows Terminal, tmux, iTerm, Terminal.app, GNOME Terminal and others) running claude --resume <session id> with your original flags. Along the way they may call wt.exe, tmux, osascript (macOS asks permission once), ps or python3 (macOS, to read the flags).
  • Hooks: the /relaunch command, and after Bash, PowerShell, Write and Edit tool calls a check for MCP config changes. It never changes a call or its result.
  • What it reads: the session id, starting folder, model, your note, tool calls that change MCP config, and the parent claude process's command line (to reuse its flags; they are shown in /relaunch's reply). No credentials.
  • What it stores: the session id and note, locally, until the new session reads them.
  • What it sends: nothing. No network calls.

License

MIT

Source 3 files
hooks/register.ts 392 lines
1/**
2 * session-relaunch: `/relaunch` restarts this session in a new terminal tab
3 * with `claude --resume <id>`, so MCP servers added since it started load.
4 *
5 * Steps: optionally compact, have relaunch.ps1 (Windows) or relaunch.sh open
6 * a tab that waits for this claude to exit and then resumes the same session
7 * id with the same flags
8 * (plus the current model when /model changed it), leave a record in the
9 * store for the new process to welcome itself back with, then exit this one.
10 * Resuming by id rather than `--continue` picks the right session when
11 * several are open at once.
12 *
13 * Also nudges the person (never the model) when a tool call changes the MCP
14 * configuration, since that is exactly when a relaunch is needed.
15 *
16 * Every `$.noun.verb(...)` is written literally here; the loader inventories
17 * them statically. The helpers in parse.ts and mcp-change.ts take no `$`.
18 */
19
20import type { EngineInterface, On } from 'claude-code'
21
22import { mcpChange } from './mcp-change'
23import {
24  asPending,
25  commandLine,
26  isFresh,
27  isModelFlag,
28  isWaiting,
29  isWindowsPath,
30  parseArgs,
31  parseLaunch,
32  PENDING_PREFIX,
33  PENDING_STAY_TTL_MS,
34  PENDING_TTL_MS,
35  type Mode,
36  type PendingRecord,
37} from './parse'
38
39const COMMAND_NAME = 'relaunch'
40
41export const USAGE = [
42  'Usage: /relaunch [now|compact|stay] [note...]',
43  '  /relaunch                 ask: relaunch now, compact first, or open the tab and stay',
44  '  /relaunch now [note]      reopen this session in a new tab and exit this one',
45  '  /relaunch compact [note]  compact first (the note also steers the summary), then relaunch',
46  '  /relaunch stay [note]     open the new tab but leave this session running (it starts once you /exit)',
47  '  /relaunch <note>          text without a keyword is a note; it still asks first',
48  "The note is put in the new session's prompt box. /relaunch help shows this.",
49].join('\n')
50
51/** The confirm dialog's labels and the mode each one picks. */
52const CHOICES: Record<string, Exclude<Mode, 'ask' | 'help'>> = {
53  'Relaunch now': 'now',
54  'Compact, then relaunch': 'compact',
55  'Open tab, stay here': 'stay',
56}
57
58const CANCEL = 'Cancel'
59
60/** How long a relaunch waits for this process to exit before giving up. */
61const WAIT_SECONDS = 120
62
63/**
64 * How long relaunch.ps1/relaunch.sh may take to open the tab: long enough to
65 * answer a macOS Automation prompt for Terminal.app or iTerm.
66 */
67const LAUNCH_TIMEOUT_MS = 120_000
68
69const ALREADY_WAITING =
70  'A tab from an earlier /relaunch is still waiting on this session. Type /exit here and it takes over.'
71
72/**
73 * `$.command.run` from inside a `command.run` hook is refused (it would wait
74 * on the turn the hook holds), so `/exit` runs from a timer just after
75 * /relaunch has answered.
76 */
77const EXIT_DELAY_MS = 300
78
79/**
80 * The welcome waits for the REPL to mount, or for a startup dialog such as a
81 * new .mcp.json server's approval: first try, retries (about a minute), spacing.
82 */
83const WELCOME_DELAY_MS = 1000
84const WELCOME_RETRIES = 120
85const WELCOME_RETRY_MS = 500
86
87/**
88 * Runs `/exit` once the current command has returned, saying so in the
89 * transcript if it is refused.
90 *
91 * @param $ the engine interface
92 * @param opened the line /relaunch answered with, repeated in the fallback
93 */
94function exitSoon($: EngineInterface, opened: string) {
95  $.clock.after(EXIT_DELAY_MS, () => {
96    $.command.run({ command: 'exit' }).catch((error: unknown) => {
97      const reason = error instanceof Error ? error.message : String(error)
98
99      $.ui.log(opened)
100      $.ui.log(`Could not exit this session automatically (${reason}); type /exit and the new tab takes over.`)
101    })
102  })
103}
104
105type Launched = { ok: true; opened: string } | { ok: false; text: string }
106
107/**
108 * Opens the new tab through relaunch.ps1 or relaunch.sh and leaves the welcome-back record.
109 *
110 * @param $ the engine interface
111 * @param stay whether the new tab waits for this session without a time limit
112 * @param note the note for the new session's prompt box, possibly empty
113 * @param startModel the model the session started on, so only a change is carried
114 */
115async function launch(
116  $: EngineInterface,
117  stay: boolean,
118  note: string,
119  startModel: string | undefined,
120): Promise<Launched> {
121  const sessionId = await $.session.id()
122  // The project root, not the current directory: a shell `cd` during the
123  // session moves the latter, and the new tab should open where it started.
124  const cwd = await $.session.root()
125  const model = await $.session.model()
126  const root = $.plugin.root
127  const wait = String(stay ? 0 : WAIT_SECONDS)
128  const windows = isWindowsPath(root)
129
130  const argv = windows
131    ? [
132        'powershell.exe',
133        '-NoProfile',
134        '-ExecutionPolicy',
135        'Bypass',
136        '-File',
137        `${root}\\hooks\\relaunch.ps1`,
138        '-SessionId',
139        sessionId,
140        '-Cwd',
141        cwd,
142        '-WaitSeconds',
143        wait,
144      ]
145    : ['bash', `${root}/hooks/relaunch.sh`, '--session-id', sessionId, '--cwd', cwd, '--wait-seconds', wait]
146
147  if (isModelFlag(model) && model !== startModel) {
148    argv.push(windows ? '-Model' : '--model', model)
149  }
150
151  const run = await $.process.run(argv, { timeoutMs: LAUNCH_TIMEOUT_MS })
152  const result = parseLaunch(run.stdout, run.stderr)
153
154  if (!result.ok) {
155    return { ok: false, text: `/relaunch could not open the new tab: ${result.error}` }
156  }
157
158  const record: PendingRecord = {
159    id: sessionId,
160    at: await $.clock.now(),
161    note,
162    ttlMs: stay ? PENDING_STAY_TTL_MS : PENDING_TTL_MS,
163    waitMs: stay ? 0 : WAIT_SECONDS * 1000,
164  }
165
166  await $.store.set(`${PENDING_PREFIX}${sessionId}`, record)
167
168  const dropped = result.dropped_flags ? ' (its original flags could not be read, so it starts without them)' : ''
169
170  return {
171    ok: true,
172    opened: `Opened a new tab (${result.title}) running: ${commandLine(result.exe, result.args)}${dropped}`,
173  }
174}
175
176/**
177 * Whether a tab from an earlier /relaunch may still be waiting on this
178 * session; a second one would leave two tabs resuming the same id.
179 *
180 * @param $ the engine interface
181 */
182async function tabWaiting($: EngineInterface): Promise<boolean> {
183  const sessionId = await $.session.id()
184
185  return isWaiting(asPending(await $.store.get(`${PENDING_PREFIX}${sessionId}`)), await $.clock.now())
186}
187
188/**
189 * Compacts, then relaunches, once /relaunch has answered: the host refuses
190 * `$.session.compact` from inside a `command.run` hook (it would compact under
191 * the turn the hook holds). Progress goes to the transcript as `ui.log` lines,
192 * one call per line since a log line does not break on `\n`.
193 * The note doubles as the compaction instructions, like `/compact <text>`.
194 *
195 * @param $ the engine interface
196 * @param note the summary instructions and the new prompt box text, possibly empty
197 * @param startModel the model the session started on
198 */
199async function compactThenRelaunch($: EngineInterface, note: string, startModel: string | undefined) {
200  try {
201    const { skip } = await $.session.compact(note ? { instructions: note } : undefined)
202
203    if (skip) {
204      $.ui.log('Compaction was vetoed by a hook, so nothing was relaunched.')
205
206      return
207    }
208
209    const launched = await launch($, false, note, startModel)
210
211    if (!launched.ok) {
212      $.ui.log(launched.text)
213
214      return
215    }
216
217    $.ui.log(launched.opened)
218    $.ui.log('Exiting this session...')
219    exitSoon($, launched.opened)
220  } catch (error) {
221    const reason = error instanceof Error ? error.message : String(error)
222
223    $.ui.log(`/relaunch compact failed (${reason}). Run /compact, then /relaunch now.`)
224  }
225}
226
227/**
228 * Shows the welcome-back toast and puts the note in the prompt box, retrying
229 * while the REPL is still mounting or a dialog holds the keys.
230 *
231 * @param $ the engine interface
232 * @param note the note left by /relaunch, possibly empty
233 * @param attempt how many tries came before this one
234 */
235async function welcome($: EngineInterface, note: string, attempt: number) {
236  try {
237    const surfaces = await $.session.surfaces()
238    const filled = note && surfaces.includes('terminal') ? await $.prompt.fill({ text: note }) : null
239    const ready = surfaces.includes('terminal') && (!filled || filled.isFilled || !filled.refusal)
240
241    if (!ready && attempt < WELCOME_RETRIES) {
242      $.clock.after(WELCOME_RETRY_MS, () => void welcome($, note, attempt + 1))
243
244      return
245    }
246
247    if (!ready && note) {
248      $.ui.log(`Your /relaunch note (it could not go in the prompt box): ${note}`)
249    }
250
251    $.ui.toast('Resumed via /relaunch')
252  } catch (error) {
253    $.ui.log(`session-relaunch welcome failed: ${String(error)}`, { to: 'debug' })
254  }
255}
256
257/**
258 * Registers the command, the welcome back and the MCP-change nudge.
259 *
260 * @param on the engine's registrar
261 */
262export function register(on: On) {
263  // The model the session started on, so only a mid-session /model change
264  // is carried to the new process; its own flags already cover the rest.
265  let startModel: string | undefined
266
267  on('session.start', async ($, e, next) => {
268    await $.command.register({
269      name: COMMAND_NAME,
270      description: 'Restart this session in a new tab (--resume) so new MCP servers load',
271      argumentHint: '[now|compact|stay] [note]',
272    })
273
274    startModel = await $.session.model()
275
276    // A headless resume of the same id leaves the record for the real one.
277    if (!e.isInteractive) {
278      return next(e)
279    }
280
281    const id = await $.session.id()
282    const now = await $.clock.now()
283    let mine: PendingRecord | null = null
284
285    for (const key of await $.store.keys()) {
286      if (!key.startsWith(PENDING_PREFIX)) {
287        continue
288      }
289
290      const record = asPending(await $.store.get(key))
291      const isMine = record?.id === id && key === `${PENDING_PREFIX}${id}`
292
293      if (isMine && record && isFresh(record, now)) {
294        mine = record
295      }
296
297      if (isMine || !record || !isFresh(record, now)) {
298        await $.store.delete(key)
299      }
300    }
301
302    if (mine) {
303      const note = mine.note
304
305      $.clock.after(WELCOME_DELAY_MS, () => void welcome($, note, 0))
306    }
307
308    return next(e)
309  })
310
311  on('command.run', { command: COMMAND_NAME }, async ($, e, _next) => {
312    const parsed = parseArgs(e.args)
313
314    if (parsed.mode === 'help') {
315      return { text: USAGE }
316    }
317
318    const surfaces = await $.session.surfaces()
319
320    if (!surfaces.includes('terminal')) {
321      return { text: '/relaunch needs a local terminal; this session has none.' }
322    }
323
324    let mode = parsed.mode
325
326    if (mode === 'ask') {
327      let answer: string
328
329      try {
330        answer = await $.ui.ask('Relaunch this session in a new tab?', {
331          header: 'Relaunch',
332          options: [...Object.keys(CHOICES), CANCEL],
333        })
334      } catch {
335        return { text: USAGE }
336      }
337
338      const picked = CHOICES[answer]
339
340      if (!picked) {
341        return { text: 'Relaunch cancelled.' }
342      }
343
344      mode = picked
345    }
346
347    if (await tabWaiting($)) {
348      return { text: ALREADY_WAITING }
349    }
350
351    if (mode === 'compact') {
352      $.clock.after(EXIT_DELAY_MS, () => void compactThenRelaunch($, parsed.note, startModel))
353
354      return { text: 'Compacting, then relaunching in a new tab...' }
355    }
356
357    const stay = mode === 'stay'
358    const launched = await launch($, stay, parsed.note, startModel)
359
360    if (!launched.ok) {
361      return { text: launched.text }
362    }
363
364    const opened = launched.opened
365
366    if (stay) {
367      return { text: `${opened}\nIt starts once you /exit here, however long that takes.` }
368    }
369
370    $.ui.toast('Relaunching in a new tab...')
371    exitSoon($, opened)
372
373    return { text: `${opened}\nExiting this session...` }
374  }).catch(($, e, next) => (next.called ? next(e) : { text: `/relaunch failed: ${next.error.message}` }))
375
376  // MCP-change nudge: after the call, a transcript line for the person
377  // (`ui.log` is never sent to the model); the result goes back untouched.
378  on('tool.call', { tool: ['Bash', 'PowerShell', 'Write', 'Edit'] }, async ($, e, next) => {
379    const result = await next(e)
380
381    if (!result.deny && !result.isError) {
382      const change = mcpChange(e.tool, e)
383
384      if (change) {
385        $.ui.log(`MCP config changed (${change}); /relaunch to load it`)
386      }
387    }
388
389    return result
390  }).catch(($, e, next) => next(e))
391}
392
hooks/mcp-change.ts 44 lines
1/**
2 * Spots a tool call that changed this machine's MCP configuration, so the
3 * mod can tell the person a /relaunch would load it. Pure: it reads the tool
4 * name and input and returns a short description, or null.
5 */
6
7/**
8 * `claude mcp <verb>` with a verb that changes the configured servers, the
9 * executable bare, as `claude.exe`/`claude.cmd`, or at the end of a path.
10 */
11const MCP_CLI_RE =
12  /(?:^|[\s;&|(`'"\\/])claude(?:\.exe|\.cmd)?\s+mcp\s+(add-from-claude-desktop|add-json|add|remove)(?=\s|$|[;&|)`'"])/i
13
14/** The basename of a Windows or POSIX path. */
15function basename(path: string): string {
16  return path.split(/[\\/]/).at(-1) ?? path
17}
18
19/**
20 * Describes the MCP change a tool call made, or returns null.
21 *
22 * Covers `claude mcp add|add-json|add-from-claude-desktop|remove` in a Bash
23 * or PowerShell command, and a Write or Edit of a `.mcp.json`.
24 *
25 * @param tool the tool's name (`e.tool`)
26 * @param input the call's input (`e` itself works)
27 */
28export function mcpChange(tool: string, input: { command?: unknown; file_path?: unknown }): string | null {
29  if (tool === 'Bash' || tool === 'PowerShell') {
30    const command = typeof input.command === 'string' ? input.command : ''
31    const match = MCP_CLI_RE.exec(command)
32
33    return match ? `claude mcp ${match[1].toLowerCase()}` : null
34  }
35
36  if (tool === 'Write' || tool === 'Edit') {
37    const path = typeof input.file_path === 'string' ? input.file_path : ''
38
39    return basename(path).toLowerCase() === '.mcp.json' ? `${tool.toLowerCase()} of ${basename(path)}` : null
40  }
41
42  return null
43}
44
hooks/parse.ts 147 lines
1/**
2 * Pure helpers for /relaunch: the argument parser, the helper script's JSON
3 * line, the model check and the welcome-back record. No `$` here, so the
4 * tests import them directly.
5 */
6
7/** What the first word of `/relaunch ...` picks; `ask` when it is none. */
8export type Mode = 'ask' | 'now' | 'compact' | 'stay' | 'help'
9
10export type RelaunchArgs = { mode: Mode; note: string }
11
12const KEYWORDS: readonly Mode[] = ['now', 'compact', 'stay', 'help']
13
14/**
15 * Splits `/relaunch` arguments into an optional leading keyword and a note.
16 *
17 * Only the first word is a keyword (any case); everything after it is the
18 * note, verbatim. Text that does not start with a keyword is all note and
19 * leaves the mode at `ask`, so a typo like `/relaunch stya` still goes
20 * through the confirm dialog instead of relaunching on the spot.
21 *
22 * @param raw everything after `/relaunch`
23 */
24export function parseArgs(raw: string): RelaunchArgs {
25  const text = raw.trim()
26  const match = /^(\S+)\s*([\s\S]*)$/.exec(text)
27
28  if (!match) {
29    return { mode: 'ask', note: '' }
30  }
31
32  const first = match[1].toLowerCase()
33
34  if (first === '?' || first === '-h' || first === '--help') {
35    return { mode: 'help', note: '' }
36  }
37
38  if ((KEYWORDS as readonly string[]).includes(first)) {
39    return { mode: first as Mode, note: match[2].trim() }
40  }
41
42  return { mode: 'ask', note: text }
43}
44
45export type LaunchResult =
46  | { ok: true; pid: number; terminal: string; exe: string; args: string[]; title: string; dropped_flags?: boolean }
47  | { ok: false; error: string }
48
49/** The helper's one JSON line, or a failure naming what it printed instead. */
50export function parseLaunch(stdout: string, stderr: string): LaunchResult {
51  const line = stdout.trim().split(/\r?\n/).at(-1) ?? ''
52
53  try {
54    const parsed = JSON.parse(line) as Partial<LaunchResult> & { ok?: unknown }
55
56    if (parsed.ok === true || parsed.ok === false) {
57      return parsed as LaunchResult
58    }
59  } catch {
60    // Fall through to the failure below.
61  }
62
63  return { ok: false, error: (stderr || stdout || 'the relaunch helper printed nothing').trim() }
64}
65
66/**
67 * Whether the plugin lives at a Windows path (`C:\...`, `C:/...` or a UNC
68 * share), which picks relaunch.ps1 over relaunch.sh.
69 *
70 * @param path the plugin root
71 */
72export function isWindowsPath(path: string): boolean {
73  return /^[A-Za-z]:[\\/]|^\\\\/.test(path)
74}
75
76/** `exe args...` as one line, quoting the parts that hold spaces. */
77export function commandLine(exe: string, args: readonly string[]): string {
78  return [exe, ...args].map((part) => (/\s/.test(part) || part === '' ? `"${part}"` : part)).join(' ')
79}
80
81/**
82 * Whether `$.session.model()`'s answer can go to `--model` as is.
83 *
84 * Probed on 2.1.288 it is the model id (`claude-opus-5-5`); an alias
85 * (`opus`), a provider id (`us.anthropic.claude-...`) or a `[1m]` suffix also
86 * pass. A display name (`Opus 5.5`, anything with spaces or brackets other
87 * than the suffix) does not, so the new session keeps its original flags.
88 *
89 * @param model what `$.session.model()` returned
90 */
91export function isModelFlag(model: string | undefined | null): model is string {
92  return typeof model === 'string' && /^[A-Za-z0-9][\w.:/@-]*(\[1m\])?$/.test(model) && model.length <= 200
93}
94
95/**
96 * What /relaunch leaves in the store for the session it reopens. `waitMs` is
97 * how long the new tab waits for this session to exit, 0 for no limit.
98 */
99export type PendingRecord = { id: string; at: number; note: string; ttlMs: number; waitMs: number }
100
101/** How long a record stays good after `/relaunch` and `/relaunch compact`. */
102export const PENDING_TTL_MS = 10 * 60 * 1000
103
104/** `/relaunch stay` waits for the person to /exit, which can take hours. */
105export const PENDING_STAY_TTL_MS = 12 * 60 * 60 * 1000
106
107/** The store key of one session's record. */
108export const PENDING_PREFIX = 'pending.'
109
110/** Narrows a store value to a record; anything else reads as none. */
111export function asPending(value: unknown): PendingRecord | null {
112  if (!value || typeof value !== 'object') {
113    return null
114  }
115
116  const record = value as Record<string, unknown>
117
118  if (typeof record.id !== 'string' || typeof record.at !== 'number') {
119    return null
120  }
121
122  return {
123    id: record.id,
124    at: record.at,
125    note: typeof record.note === 'string' ? record.note : '',
126    ttlMs: typeof record.ttlMs === 'number' ? record.ttlMs : PENDING_TTL_MS,
127    waitMs: typeof record.waitMs === 'number' ? record.waitMs : 0,
128  }
129}
130
131/** Whether a record is still within its time to live at `now`. */
132export function isFresh(record: PendingRecord, now: number): boolean {
133  return now >= record.at && now - record.at <= record.ttlMs
134}
135
136/**
137 * Whether the tab an earlier /relaunch opened may still be waiting on this
138 * session at `now`, so a second one would leave two tabs resuming one id.
139 */
140export function isWaiting(record: PendingRecord | null, now: number): boolean {
141  if (!record || !isFresh(record, now)) {
142    return false
143  }
144
145  return record.waitMs === 0 || now - record.at < record.waitMs
146}
147