SLOPSHOPPER

session-handoff-button

A Session Hand-off button above the prompt, colored by context usage; reads Context clean and cannot be pressed while green. From orange on, one press writes…

bandtoastprompttimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · session-handoff-button
› 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 [ session-handoff ] ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
[ session-handoff ] ⟨Claude Code's own drawing⟩
README

session-handoff-button

A Session Hand-off button above the prompt that shows how full the context window is (green under 45%, orange 45–64%, red from 65%). While green it reads Context clean and cannot be pressed; from orange on it reads Session Hand-off and one press hands the work to a fresh session: it writes a session handoff, saves it to a temp .md, runs /clear, and continues in the fresh session with a short message while the handoff rides along as hidden context. Past 65% it also stops your next prompt once and recommends the button.

Requires Claude Code 2.1.287 or later. Built on 2.1.295; the live run below was on 2.1.299.

● 30% Context clean            <- green: plain text, nothing to press
[ ● 52% Session Hand-off ]      <- orange/red: the button
> _

What one press does

  1. Runs your handoff skill as a slash command (/session-handoff by default). If no command of that name is installed, it sends a built-in handoff prompt instead.
  2. When that turn ends with an answer, the mod saves the answer to <TMPDIR>/session-handoff/handoff-<timestamp>.md.
  3. It runs /clear, then adds the handoff to the fresh session as a user-role row you do not see as typed, and sends one short message: Session Hand-off: continuing from the previous session (handoff saved at <path>). The model reads the full handoff; you never see it pasted. If autoSend is off, the short message goes into the prompt box and you press Enter.

If the hidden row is refused, the full handoff text is sent as the message instead, so nothing is lost. If the file cannot be written, the path is left out of the message. When the handoff turn is interrupted, errors, is refused or returns no text, the mod does not run /clear; a toast says why. Presses while a handoff is running are ignored. /resume brings back the old session at any time.

The 65% guard

From 65% on, the first prompt you send is stopped once with this message, and nothing reaches the model:

Session Hand-off: context is at 72%, past the point where answers get worse. Press the Session Hand-off button above the prompt to continue in a fresh session without losing the thread. This message shows once; send yours again to carry on here anyway.

Press Enter again and the same prompt goes through (the mod puts your draft back if the box was emptied). It warns once per crossing: if the context drops under 65% (a new session, a compaction) and rises again, it warns again. Slash commands (/compact, /clear, …), prompts from plugins and everything while a handoff is running are never stopped. If the guard itself breaks, your prompt goes through.

Where the button is

Claude Code's status line (the statusLine setting) is a shell command's output. Mods cannot draw into it, so the button sits in the band directly above the prompt, the closest place that accepts a pressable button. Click it, or focus the band (a click or ctrl+x tab) and press h.

The percentage is the same figure the status line reads as context_window.used_percentage. It shows – in a fresh session until the first response.

What it can reach

❯ ./register.tsx hooks: session.start, session.measure, prompt.submit, turn.start, turn.complete, ui.render{component=AbovePrompt} ❯ ./register.tsx calls: $.clock.after, $.clock.now (via saveHandoff), $.command.list (via startHandoff), $.command.run (via startHandoff, switchSession), $.env.get (via saveHandoff), $.fs.write (via saveHandoff), $.prompt.fill (via restoreDraft, switchSession), $.prompt.read (via restoreDraft), $.prompt.submit (via startHandoff, switchSession), $.session.append (via switchSession), $.session.usage, $.state.get, $.state.set, $.ui.resolve, $.ui.toast ❯ ./register.tsx env reads: TEMP, TMPDIR ❯ ./register.tsx state keys: session-handoff-button.percent, session-handoff-button.phase, session-handoff-button.warned

Reach L2 writes or runs or drives Claude (drives Claude, writes one file, writes a session row and the prompt box, persists state, draws).

Threat model for session-handoff-button (reach L2, writes or runs or drives Claude)
1. Reads:    context usage figures ($.session.usage, session.measure); the final answer text of main-loop turns, used only for the turn the mod started; typed prompts (prompt.submit, text read only to decide on the 65% stop and to restore a draft); the slash command list; env names TMPDIR and TEMP; state keys session-handoff-button.percent, .phase and .warned
2. Runs:     no processes; it drives Claude: one skill turn (or the built-in prompt) per press, /clear, one session row and one prompt in the fresh session
3. Sends:    nothing leaves the machine beyond the normal model requests of those turns
4. Persists: the handoff as one .md file per press under TMPDIR (default /tmp); three $.state keys for this session only; nothing in $.store
5. Hostile input: the handoff text is the model's answer, which can carry text from files or tool results it read; the mod gives it to the fresh session as a user-role row and a message sent as your own words (asUser), so injected instructions in it reach the new session with your authority, exactly as a manual paste would; set autoSend to false to read the short message first, and read the .md at the path it names; the skill name option only reaches $.command.run as a command name, never a shell; the saved file takes the default permissions (on macOS TMPDIR is private to your user; on Linux /tmp is shared, so the file may be readable by other local users)

Install

One session: claude --plugin-dir ./session-handoff-button. To keep it, install it from a marketplace, then run /reload-plugins in an open session. Installed copies are cached by version: bump version before reinstalling.

Options

  • skill: the slash command that writes the handoff, without the slash. Default session-handoff. If it is not installed, the built-in handoff prompt is used.
  • autoSend: send the short continue message to the fresh session automatically. Default true. Off: the message goes into the prompt box and waits for Enter; the handoff is already in the session either way.

Stored under pluginConfigs in settings; a change reloads the mod.

Proof

  • 16 unit tests on the official kit pass (claude plugin test); the guard and the flow-order tests were seen failing against a deliberately broken copy.
  • claude plugin validate passes.
  • Live, in a real terminal session on 2.1.299 (a pseudo-terminal driving claude --plugin-dir, with the thresholds lowered in a scratch copy so 5% context was enough): the button press ran the handoff, /clear ran, the fresh session showed only the short message with the temp file path, the model then answered a question about something said only in the old session, and the handoff text did not appear on screen. In a second run the first prompt over the mark was stopped with the warning and the same prompt went through on Enter.
  • Not checked: the Desktop Code tab, a reload mid-handoff, and a real 45% / 65% session (the live runs used lowered thresholds).

Limitations

  • The button is in the band above the prompt, not inside the status line (see above).
  • Draws only in the terminal and the Desktop app's Code tab. In claude -p, the Agent SDK, the VS Code chat panel and cloud sessions nothing is drawn, so there is no button.
  • The fresh session's transcript line for the short message is labelled with the plugin's name (Prompt from the session-handoff-button plugin), as Claude Code does for any prompt a plugin sends.
  • If you queue another prompt yourself between the press and the start of the handoff turn, the mod can pick up that turn as the handoff. Press when the session is idle.
  • Reloading the mod (/reload-plugins, saving a file in development) while a handoff runs cancels it; nothing is cleared.
  • The colors are fixed hex values (#22c55e, #f97316, #ef4444) and do not follow your theme.
  • The temp .md files are not deleted by the mod; the operating system clears its temp folder on its own schedule.

Uninstall

Disable it in /plugin. It leaves no $.store keys; the handoff .md files it wrote stay in the temp folder until the operating system removes them.

Source 2 files
hooks/register.tsx 196 lines
1import type { EngineInterface, Register } from 'claude-code'
2import { atom, read, update } from 'claude-code'
3
4type Phase = { step: 'idle' | 'requested' | 'generating' | 'switching'; turnId: string | null }
5type Config = { skill: string; autoSend: boolean }
6
7const IDLE: Phase = { step: 'idle', turnId: null }
8const percent = atom({ plugin: 'session-handoff-button', key: 'percent' } as const, null as number | null)
9const phase = atom({ plugin: 'session-handoff-button', key: 'phase' } as const, IDLE as Phase)
10const warned = atom({ plugin: 'session-handoff-button', key: 'warned' } as const, false)
11
12export const GREEN = '#22c55e'
13export const ORANGE = '#f97316'
14export const RED = '#ef4444'
15export const CLEAN_LABEL = 'Context clean'
16export const WARN_AT = 65
17
18// Sent only when the configured skill is not installed, so the mod also works for people without it.
19export const FALLBACK_PROMPT = [
20  'Write a session handoff so a fresh session can continue this work without repeating discovery.',
21  'Reply in the language of this conversation, as one message that is itself the continuation prompt, with these sections:',
22  'Goal and immediate next action; User constraints and decisions; Completed work and current state',
23  '(implemented / verified / pending / blocked, with evidence); Essential artifacts (absolute paths, why each matters);',
24  'Open questions and risks; First step for the next session.',
25  'Keep literal paths, commands and error messages. No secrets. Do not start new implementation work.',
26].join(' ')
27
28export function colorFor(value: number): string {
29  if (value >= WARN_AT) return RED
30  if (value >= 45) return ORANGE
31  return GREEN
32}
33
34export function warnMessage(value: number): string {
35  return `Session Hand-off: context is at ${value}%, past the point where answers get worse. `
36    + 'Press the Session Hand-off button above the prompt to continue in a fresh session without losing the thread. '
37    + 'This message shows once; send yours again to carry on here anyway.'
38}
39
40export function continueMessage(path: string | null): string {
41  return `Session Hand-off: continuing from the previous session${path ? ` (handoff saved at ${path})` : ''}.`
42}
43
44export function handoffContext(text: string, path: string | null): string {
45  return [
46    'The previous session was cleared by the Session Hand-off button. Its handoff follows; treat it as the person\'s briefing,',
47    `continue from its first step and do not repeat discovery.${path ? ` A copy is saved at ${path}.` : ''}`,
48    '<session-handoff>',
49    text,
50    '</session-handoff>',
51  ].join('\n')
52}
53
54function labelFor(step: Phase['step']): string {
55  if (step === 'switching') return 'Opening fresh session…'
56  if (step === 'idle') return 'Session Hand-off'
57  return 'Writing handoff…'
58}
59
60async function startHandoff($: EngineInterface, config: Config): Promise<void> {
61  const current = await read($, phase)
62  if (current.step !== 'idle') {
63    $.ui.toast('Session Hand-off is already running')
64    return
65  }
66  await update($, phase, () => ({ step: 'requested', turnId: null }))
67  const names = (await $.command.list()).map(c => c.name)
68  const started = names.includes(config.skill)
69    ? $.command.run({ command: config.skill })
70    : $.prompt.submit({ text: FALLBACK_PROMPT, asUser: true })
71  $.ui.toast(names.includes(config.skill) ? `Handing off: running /${config.skill}…` : 'Handing off: writing the handoff with the built-in prompt…')
72  started.catch(async () => {
73    await update($, phase, () => IDLE)
74    $.ui.toast('Session Hand-off: could not start the handoff turn')
75  })
76}
77
78// A temp file, so the handoff outlives the session it came from; null when it cannot be written.
79async function saveHandoff($: EngineInterface, text: string): Promise<string | null> {
80  try {
81    const base = (await $.env.get('TMPDIR')) ?? (await $.env.get('TEMP')) ?? '/tmp'
82    const stamp = new Date(await $.clock.now()).toISOString().replace(/[:.]/g, '-')
83    const path = `${base.replace(/[\\/]+$/, '')}/session-handoff/handoff-${stamp}.md`
84    await $.fs.write(path, text.endsWith('\n') ? text : `${text}\n`)
85    return path
86  } catch {
87    return null
88  }
89}
90
91async function switchSession($: EngineInterface, text: string, config: Config): Promise<void> {
92  const path = await saveHandoff($, text)
93  try {
94    await $.command.run({ command: 'clear' })
95  } catch {
96    await update($, phase, () => IDLE)
97    $.ui.toast(`Session Hand-off: /clear failed; the handoff is ${path ? `saved at ${path}` : 'in the transcript above'}`)
98    return
99  }
100  await update($, phase, () => IDLE)
101  // The handoff goes in as a user-role row the person does not see as typed; the visible message stays short.
102  // If the row is refused the full text is the message, so nothing is lost.
103  const row = await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: handoffContext(text, path) }] } }).catch(() => null)
104  const message = row && !row.deny ? continueMessage(path) : text
105  if (config.autoSend) void $.prompt.submit({ text: message, asUser: true })
106  else await $.prompt.fill({ text: message, mode: 'replace' })
107}
108
109// A dropped prompt may leave the box empty; put the draft back so the warning costs nothing.
110async function restoreDraft($: EngineInterface, draft: string): Promise<void> {
111  const box = await $.prompt.read()
112  if (!box.text) await $.prompt.fill({ text: draft, mode: 'replace' })
113}
114
115export const register: Register = (on, options) => {
116  const config: Config = {
117    skill: typeof options.skill === 'string' && options.skill.trim() ? options.skill.trim().replace(/^\//, '') : 'session-handoff',
118    autoSend: options.autoSend !== false,
119  }
120
121  on('session.start', async ($, e, next) => {
122    const started = await next(e)
123    await update($, phase, () => IDLE)
124    await update($, warned, () => false)
125    const usage = await $.session.usage()
126    await update($, percent, () => usage.context.percent ?? null)
127    return started
128  })
129
130  on('session.measure', async ($, e, next) => {
131    await update($, percent, () => e.context.percent ?? null)
132    if ((e.context.percent ?? 100) < WARN_AT) await update($, warned, () => false)
133    return next(e)
134  })
135
136  on('prompt.submit', async ($, e, next) => {
137    const fromPerson = e.origin.kind === 'composer' || e.origin.kind === 'bridge'
138    // Once per crossing of the red mark, stop the person's next prompt and point at the button.
139    const value = await read($, percent)
140    const idle = (await read($, phase)).step === 'idle'
141    if (fromPerson && idle && value !== null && value >= WARN_AT && !(await read($, warned)) && !e.text.trim().startsWith('/')) {
142      await update($, warned, () => true)
143      const draft = e.text
144      $.clock.after(150, () => { void restoreDraft($, draft) })
145      return { drop: warnMessage(value) }
146    }
147    return next(e)
148  })
149
150  on('turn.start', async ($, e, next) => {
151    const current = await read($, phase)
152    if (current.step === 'requested') await update($, phase, () => ({ step: 'generating', turnId: e.turnId }))
153    return next(e)
154  })
155
156  on('turn.complete', async ($, e, next) => {
157    const done = await next(e)
158    if (e.agentId) return done
159    const current = await read($, phase)
160    if (current.step !== 'generating' || current.turnId !== e.turnId) return done
161    const text = e.answer.trim()
162    if (e.reason !== 'answer' || e.isAborted || !text) {
163      await update($, phase, () => IDLE)
164      $.ui.toast(`Session Hand-off stopped: the handoff turn ended with ${e.isAborted ? 'aborted' : e.reason}${text ? '' : ', no text'}; nothing was cleared`)
165      return done
166    }
167    await update($, phase, () => ({ step: 'switching', turnId: e.turnId }))
168    // command.run rejects inside a hook the turn waits on, so /clear starts from a timer.
169    $.clock.after(250, () => { void switchSession($, text, config) })
170    return done
171  })
172
173  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
174    if (e.props.hasSurvey) return next(e)
175    const { Box, Button, Text } = $.ui.resolve(e)
176    const value = await read($, percent)
177    const current = await read($, phase)
178    const beneath = await next(e)
179    const chip = <Text color={value === null ? 'inactive' : colorFor(value)} bold>● {value === null ? '–' : `${value}%`}</Text>
180    // Button has no disabled prop, so a clean context draws plain text: nothing to press, no hotkey.
181    const clean = current.step === 'idle' && value !== null && colorFor(value) === GREEN
182    return (
183      <Box flexDirection="column">
184        <Box flexDirection="row">
185          {clean
186            ? <Text>{chip} <Text dimColor>{CLEAN_LABEL}</Text></Text>
187            : <Button key="session-handoff" hotkey="h" onPress={() => { void startHandoff($, config) }}>
188                {chip} {labelFor(current.step)}
189              </Button>}
190        </Box>
191        {beneath}
192      </Box>
193    )
194  })
195}
196
types/index.d.ts 10 lines
1declare module 'claude-code' {
2  interface PluginState {
3    'session-handoff-button': {
4      percent: number | null
5      warned: boolean
6      phase: { step: 'idle' | 'requested' | 'generating' | 'switching'; turnId: string | null }
7    }
8  }
9}
10