SLOPSHOPPER

editor-context

Shows the file and lines you have selected in Cursor or VS Code above the Claude Code prompt in the desktop app, and quietly tells Claude what you're looking…

bandrowscommandpromptprocessnetwork
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · editor-context
› 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 › /editor-context-demo ⎿ editor-context: Editor band demo on: every row is shown with sample data. Run again to turn it off. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

editor-context

Claude always knows what you're looking at in your editor.

A mod for the Claude desktop app that shows your current Cursor or VS Code file and selection in a tab above the prompt, and quietly sends it to Claude with every message.

Version License: MIT Claude desktop app

Why

In the terminal, Claude Code already sees your editor selection through /ide. The desktop app doesn't. So you end up pasting code and file paths into every message.

With this mod, you just select the code and ask: "why does this fail?" or "explain this".

Features

🗂️ A tab above the prompt<br> The Editor tab shows the file you're in and its line range. Hover it for a card with everything else. Click the tab to turn sharing on or off. If other mods add tabs to the same row, they line up beside it.

👀 Live file and selection<br> The tab follows your editor as you click around: the file, the selected lines, and a clay dot while it's sharing.

💬 Sent with every message<br> Claude gets the file path and the selected code. It stays out of your chat; a small "Sent with" chip above your message shows what went with it.

⚡ Start with ++<br> Begin a new session's first message with ++, as in ++ why does this jump?, and it goes with your selection, then sharing stays on. The new-session screen has no tab yet, so this is how you turn it on from there. Claude doesn't see the ++, though your message bubble still shows it. Works in sessions opened in a project folder, not in "No folder" sessions (see Good to know).

📌 Pin<br> Pin up to 10 selections, from any files. They're attached to every message until you unpin them. Click a pin to jump back to its lines in your editor.

💾 Unsaved warning<br> Tells you (and Claude) when the file has unsaved changes, with a Save button.

🔌 Connection notices<br> Says when no editor is open or the connection drops.

🎛️ Proper controls<br> The card's buttons are the app's own. The tab and the switch are drawn by the mod itself, styled after the app's own popovers.

Quick start

1. Install the Claude Code extension in your editor. Search for Claude Code by Anthropic in the Extensions view, or run:

cursor --install-extension anthropic.claude-code   # Cursor
code --install-extension anthropic.claude-code     # VS Code

2. Install the mod. In a Claude Code session:

/plugin marketplace add talbarina/claude-editor-context
/plugin install editor-context@talbarina

3. Start a session in the desktop app, in the same folder you have open in your editor, and click the Editor tab above the prompt to turn it on.

To preview every part of the tab and its card with sample data, run /editor-context-demo.

Requirements

  • The Claude desktop app, with Claude Code v2.1.287 or later
  • VS Code or Cursor, open, with the Claude Code extension
  • Node.js 22 or later
  • macOS or Linux

Good to know

  • Off at the start of every session. Click the Editor tab to turn it on, or start the first message with ++. The new-session screen comes before the session exists, so no mod can draw there; the tab appears once the session starts.
  • The card opens on hover. Mods can only float a card on hover, not on click; the click on the tab is the on/off switch.
  • ++ needs a project folder. In a "No folder" session the app starts the session ahead of time, and ++ doesn't turn sharing on there. Click the Editor tab instead.
  • Desktop app only. In terminal sessions the mod stays off, because /ide already does this there.
  • One editor connection. Your editor accepts one connection at a time. All your desktop sessions share it, but a terminal session using /ide on the same editor will take turns with them.
  • Long selections are cut at 20,000 characters.

What Claude sees

Nothing shows in your chat. Claude gets a short note with each message:

The user has lines 12-30 of /path/to/project/src/components/CheckoutForm.tsx
selected in Cursor. "This", "here" or "these lines" likely refers to it:
<the selected code>

If the selection hasn't changed since your last message, Claude gets a one-line reminder instead of the code again.

🔒 Privacy

Everything stays on your machine. The mod is off when a session starts: until you turn it on, it doesn't connect to your editor or send anything. Once on, it reads your editor through the Claude Code extension's local connection and adds it only to messages you send. Turn it off (click the tab, or the switch in its card) whenever you want Claude not to see what's open: it then sends nothing, and keeps the connection so turning it back on is instant.

Troubleshooting

  • Click the Editor tab, or start the session's first message with ++. It's off until you do.
  • Check that the editor is open and the extension is installed: ls ~/.claude/ide should list a .lock file.
  • Run /plugin and check that editor-context is listed as active.
  • Make sure you're in the desktop app, not the terminal.

Another client took the editor's connection, usually a terminal session running /ide. The mod reconnects when the editor is free.

Install Node.js 22 or later, then start a new session.

It picks the window that has your session's folder open. Start the session in that folder, or close the other window.

How it works

The Claude Code extension runs a small local server in your editor and records its port in ~/.claude/ide/. When a desktop session starts, the mod launches a Node helper that connects to that server, listens for selection changes, and checks for unsaved changes every 1.5 seconds.

The editor accepts one client at a time, so the first session's helper holds the connection and the other sessions listen to it over a local socket. When that session closes, another takes over.

The tab sits in a row above the prompt that mods share: each tab's key carries its place in the row, so the order is the same whichever mod loads first. Its card is a hidden box the app shows as a popover while you hover the tab.

The tab and the card's switch are small custom controls (hooks/controls.tsx) that the app runs on its own. A click posts a press back to the mod, which runs that control's action. The card's other buttons are the app's own. The "Sent with" chips are drawn by hooks/chips.tsx.

To see exactly which events the mod handles and what it calls before you install it:

git clone https://github.com/talbarina/claude-editor-context
claude plugin validate claude-editor-context/plugins/editor-context
claude plugin test claude-editor-context/plugins/editor-context

Update or remove

claude plugin marketplace update talbarina          # update
claude plugin uninstall editor-context@talbarina    # remove

Credits

Icons by Tabler Icons (MIT).

License

MIT © 2026 Tal Barina

Source 4 files
hooks/register.tsx 848 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { Attached, EditorSelection } from '../types'
5import { type Chip, sentWith } from './chips'
6
7const selection = atom({ plugin: 'editor-context', key: 'selection' } as const, null)
8const ide = atom({ plugin: 'editor-context', key: 'ide' } as const, null)
9const isPaused = atom({ plugin: 'editor-context', key: 'isPaused' } as const, false)
10const isDirty = atom({ plugin: 'editor-context', key: 'isDirty' } as const, false)
11const pins = atom({ plugin: 'editor-context', key: 'pins' } as const, [])
12const isDemo = atom({ plugin: 'editor-context', key: 'isDemo' } as const, false)
13const notice = atom({ plugin: 'editor-context', key: 'notice' } as const, null)
14const isNoticeHidden = atom({ plugin: 'editor-context', key: 'isNoticeHidden' } as const, false)
15// Sharing is off until the Editor tab (or the switch in its card) turns it on: off, it sends nothing.
16const isShown = atom({ plugin: 'editor-context', key: 'isShown' } as const, false)
17const attached = atom({ plugin: 'editor-context', key: 'attached' } as const, [])
18const MAX_ATTACHED = 30
19
20const MAX_TEXT = 20000
21const MAX_PINS = 10
22const DOT_COLOR = '#D97757'
23const WARN_COLOR = '#E5A50A'
24const DOT_SIZE = 9
25const ICON_SIZE = 14
26const ICON_COLOR = '#8A8A8A'
27const DIVIDER_SVG = '<svg xmlns="http://www.w3.org/2000/svg" width="4000" height="1" viewBox="0 0 4000 1" preserveAspectRatio="none"><rect width="4000" height="1" fill="#8A8A8A" fill-opacity="0.2"/></svg>'
28
29// Tabler outline icons (tabler.io/icons, MIT), the set the desktop app ships.
30const ICONS: Record<string, string> = {
31  save: '<path d="M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2"/><path d="M10 14a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"/><path d="M14 4l0 4l-6 0l0 -4"/>',
32  pin: '<path d="M15 4.5l-4 4l-4 1.5l-1.5 1.5l7 7l1.5 -1.5l1.5 -4l4 -4"/><path d="M9 15l-4.5 4.5"/><path d="M14.5 4l5.5 5.5"/>',
33  unpin: '<path d="M3 3l18 18"/><path d="M15 4.5l-3.249 3.249m-2.57 1.433l-2.181 .818l-1.5 1.5l7 7l1.5 -1.5l.82 -2.186m1.43 -2.563l3.25 -3.251"/><path d="M9 15l-4.5 4.5"/><path d="M14.5 4l5.5 5.5"/>',
34  file: '<path d="M14 3v4a1 1 0 0 0 1 1h4"/><path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z"/>',
35  pause: '<path d="M6 6a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v12a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z"/><path d="M14 6a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v12a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z"/>',
36  resume: '<path d="M7 4v16l13 -8z"/>',
37  close: '<path d="M18 6l-12 12"/><path d="M6 6l12 12"/>',
38}
39
40
41function iconSvg(name: string, color: string) {
42  return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${ICONS[name]}</svg>`
43}
44
45// Runs under node. Connects to the Claude Code extension's MCP websocket in
46// Cursor / VS Code (found through ~/.claude/ide/<port>.lock), prints one JSON
47// line per selection or dirty-state change, and serves POST /call on a Unix
48// socket so the mod can call the editor's tools (save, open file). Sessions
49// share one connection per editor window (see the hub notes inside).
50const BRIDGE = String.raw`
51const fs = require('node:fs'), os = require('node:os'), path = require('node:path'), http = require('node:http'), net = require('node:net')
52const cwd = process.argv[1] || ''
53const dir = path.join(os.homedir(), '.claude', 'ide')
54const out = o => process.stdout.write(JSON.stringify(o) + '\n')
55const alive = pid => { try { process.kill(pid, 0); return true } catch { return false } }
56const parse = r => { try { return JSON.parse(r.content[0].text) } catch { return r } }
57const sleep = ms => new Promise(r => setTimeout(r, ms))
58let hubSocket = null
59
60function pickLock() {
61  let names = []
62  try { names = fs.readdirSync(dir).filter(n => n.endsWith('.lock')) } catch { return null }
63  const locks = names.map(n => {
64    try {
65      const p = path.join(dir, n)
66      return { port: n.slice(0, -5), mtime: fs.statSync(p).mtimeMs, ...JSON.parse(fs.readFileSync(p, 'utf8')) }
67    } catch { return null }
68  }).filter(l => l && (!l.pid || alive(l.pid)))
69  const inWorkspace = l => (l.workspaceFolders || []).some(f => cwd === f || cwd.startsWith(f + '/') || f.startsWith(cwd + '/'))
70  locks.sort((a, b) => (inWorkspace(b) - inWorkspace(a)) || (b.mtime - a.mtime))
71  return locks[0] || null
72}
73
74// The editor's server takes one client at a time and drops the older one, so
75// every Claude Code session shares one connection per editor window: the first
76// helper becomes the hub, the rest subscribe to it over a Unix socket.
77
78// Resolves true once a hub's stream has ended, false when there was no hub.
79function subscribe(sock) {
80  return new Promise(resolve => {
81    let connected = false
82    const req = http.get({ socketPath: sock, path: '/events' }, res => {
83      connected = true
84      out({ type: 'ready', socket: sock })
85      res.setEncoding('utf8')
86      res.on('data', d => process.stdout.write(d))
87      res.on('end', () => resolve(true))
88      res.on('error', () => resolve(true))
89    })
90    req.on('error', () => resolve(connected))
91  })
92}
93
94function canConnect(sock) {
95  return new Promise(resolve => {
96    const c = net.connect(sock)
97    c.on('connect', () => { c.destroy(); resolve(true) })
98    c.on('error', () => resolve(false))
99  })
100}
101
102function listen(server, sock) {
103  return new Promise((resolve, reject) => {
104    server.once('error', reject)
105    server.listen(sock, () => { server.removeListener('error', reject); resolve() })
106  })
107}
108
109// Resolves false when another helper is already the hub; otherwise runs the
110// hub until the editor goes away, then resolves true.
111async function serve(sock, lock) {
112  const subscribers = new Set()
113  const last = {}
114  let ws = null, ready = false, nextId = 100, current = null, lastDirty = null, stopped = false
115  const pending = new Map()
116
117  const broadcast = o => {
118    last[o.type] = o
119    const line = JSON.stringify(o) + '\n'
120    process.stdout.write(line)
121    for (const res of subscribers) res.write(line)
122  }
123
124  const call = (name, args) => new Promise((resolve, reject) => {
125    if (!ws || !ready) return reject(new Error('editor not connected'))
126    const id = ++nextId
127    pending.set(id, { resolve, reject })
128    ws.send(JSON.stringify({ jsonrpc: '2.0', id, method: 'tools/call', params: { name, arguments: args } }))
129    setTimeout(() => { if (pending.delete(id)) reject(new Error('timeout')) }, 5000)
130  })
131
132  const handle = (req, res) => {
133    if (req.method === 'GET' && req.url === '/events') {
134      res.writeHead(200, { 'content-type': 'application/x-ndjson' })
135      for (const o of [last.status, last.selection, last.dirty]) if (o) res.write(JSON.stringify(o) + '\n')
136      subscribers.add(res)
137      req.on('close', () => subscribers.delete(res))
138      return
139    }
140    let body = ''
141    req.on('data', c => { body += c })
142    req.on('end', async () => {
143      try {
144        const { name, arguments: args } = JSON.parse(body || '{}')
145        const r = await call(name, args || {})
146        res.writeHead(200, { 'content-type': 'application/json' })
147        res.end(JSON.stringify(parse(r)))
148      } catch (err) {
149        res.writeHead(502, { 'content-type': 'application/json' })
150        res.end(JSON.stringify({ error: String(err && err.message || err) }))
151      }
152    })
153  }
154
155  let server = http.createServer(handle)
156  try {
157    await listen(server, sock)
158  } catch (err) {
159    if (err.code !== 'EADDRINUSE' || await canConnect(sock)) return false
160    try { fs.unlinkSync(sock) } catch {}
161    server = http.createServer(handle)
162    try { await listen(server, sock) } catch { return false }
163  }
164  hubSocket = sock
165  out({ type: 'ready', socket: sock })
166
167  const checkDirty = () => {
168    if (!current || !ready) return
169    const file = current
170    call('checkDocumentDirty', { filePath: file }).then(r => {
171      const isDirty = !!parse(r).isDirty
172      const key = file + ':' + isDirty
173      if (key !== lastDirty) { lastDirty = key; broadcast({ type: 'dirty', filePath: file, isDirty }) }
174    }).catch(() => {})
175  }
176  const dirtyTimer = setInterval(checkDirty, 1500)
177
178  const emit = s => {
179    if (!s || !s.filePath) return
180    current = s.filePath
181    broadcast({ type: 'selection', ide: lock.ideName, ...s })
182    checkDirty()
183  }
184
185  return new Promise(resolve => {
186    let delay = 3000, openedAt = 0, goneTimer = null
187
188    const stop = () => {
189      if (stopped) return
190      stopped = true
191      clearInterval(dirtyTimer)
192      clearTimeout(goneTimer)
193      for (const res of subscribers) res.end()
194      server.close()
195      try { fs.unlinkSync(sock) } catch {}
196      hubSocket = null
197      resolve(true)
198    }
199
200    const connect = () => {
201      if (stopped) return
202      const now = pickLock()
203      if (!now || now.port !== lock.port) return stop()
204      ws = new WebSocket('ws://127.0.0.1:' + lock.port, {
205        protocols: ['mcp'],
206        headers: { 'x-claude-code-ide-authorization': now.authToken },
207      })
208      ws.onopen = () => ws.send(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'editor-context', version: '1.0.1' } } }))
209      ws.onmessage = m => {
210        let d; try { d = JSON.parse(m.data) } catch { return }
211        if (d.id === 1) {
212          ready = true
213          openedAt = Date.now()
214          clearTimeout(goneTimer)
215          broadcast({ type: 'status', ide: lock.ideName })
216          ws.send(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }))
217          call('getCurrentSelection', {}).then(r => emit(parse(r))).catch(() => {})
218        } else if (d.id && pending.has(d.id)) {
219          const p = pending.get(d.id); pending.delete(d.id)
220          d.error ? p.reject(new Error(d.error.message)) : p.resolve(d.result)
221        } else if (d.method === 'selection_changed') {
222          emit(d.params)
223        }
224      }
225      ws.onclose = () => {
226        ready = false
227        for (const p of pending.values()) p.reject(new Error('editor disconnected'))
228        pending.clear()
229        // Another client (a terminal session's /ide) may have taken the
230        // editor: back off instead of fighting it, and keep the band up
231        // through a short gap.
232        delay = openedAt && Date.now() - openedAt > 10000 ? 3000 : Math.min(delay * 2, 30000)
233        openedAt = 0
234        clearTimeout(goneTimer)
235        goneTimer = setTimeout(() => broadcast({ type: 'status', ide: null, reason: 'disconnected', ideName: lock.ideName }), 8000)
236        setTimeout(connect, delay)
237      }
238      ws.onerror = () => {}
239    }
240    connect()
241  })
242}
243
244async function main() {
245  for (;;) {
246    const lock = pickLock()
247    if (!lock) { out({ type: 'status', ide: null, reason: 'no-editor' }); await sleep(5000); continue }
248    const sock = path.join(os.tmpdir(), 'editor-context-' + lock.port + '.sock')
249    if (await subscribe(sock)) { await sleep(200 + Math.random() * 800); continue }
250    await serve(sock, lock)
251    await sleep(200 + Math.random() * 500)
252  }
253}
254
255const quit = () => { if (hubSocket) { try { fs.unlinkSync(hubSocket) } catch {} } process.exit(0) }
256process.on('SIGTERM', quit)
257process.on('SIGINT', quit)
258setInterval(() => { if (process.ppid === 1) quit() }, 5000)
259main()
260`
261
262function toSelection(raw: any): EditorSelection {
263  const start = raw.selection?.start?.line ?? 0
264  let end = raw.selection?.end?.line ?? start
265  // A whole-line selection ends at column 0 of the next line.
266  if (end > start && raw.selection?.end?.character === 0) end -= 1
267  return {
268    ide: String(raw.ide ?? 'IDE'),
269    filePath: String(raw.filePath),
270    startLine: start + 1,
271    endLine: end + 1,
272    isEmpty: Boolean(raw.selection?.isEmpty ?? !raw.text),
273    text: String(raw.text ?? '').slice(0, MAX_TEXT),
274  }
275}
276
277function fileName(filePath: string) {
278  return filePath.split('/').pop() ?? filePath
279}
280
281function lineCount(s: EditorSelection) {
282  return s.endLine - s.startLine + 1
283}
284
285function rangeLabel(s: EditorSelection) {
286  return s.startLine === s.endLine ? `L${s.startLine}` : `L${s.startLine}–${s.endLine}`
287}
288
289function pinKey(p: EditorSelection) {
290  return `${p.filePath}|${p.startLine}|${p.endLine}`
291}
292
293function codeBlock(text: string) {
294  return '```\n' + text + '\n```'
295}
296
297// The bridge needs Node 22 or later, for its built-in WebSocket.
298const MIN_NODE_MAJOR = 22
299
300async function nodeMajor($: any, node: string): Promise<number> {
301  try {
302    const r = await $.process.run([node, '--version'], { timeoutMs: 5000 })
303    if (r.exitCode !== 0) return 0
304    return Number(/^v(\d+)/.exec(r.stdout.trim())?.[1] ?? 0)
305  } catch {
306    return 0
307  }
308}
309
310async function findNode($: any): Promise<string | null> {
311  // The last session's answer, kept across sessions: probing login shells is
312  // slow, and the first message should not wait on it.
313  const cached = await $.store.get('nodePath')
314  if (typeof cached === 'string' && (await nodeMajor($, cached)) >= MIN_NODE_MAJOR) return cached
315
316  const found = await probeNode($)
317  if (found) await $.store.set('nodePath', found)
318  return found
319}
320
321async function probeNode($: any): Promise<string | null> {
322  for (const candidate of ['node', '/opt/homebrew/bin/node', '/usr/local/bin/node', '/usr/bin/node']) {
323    if ((await nodeMajor($, candidate)) >= MIN_NODE_MAJOR) return candidate
324  }
325  // nvm, fnm, volta and similar live behind the login shell's PATH.
326  for (const shell of ['/bin/zsh', '/bin/bash']) {
327    try {
328      const r = await $.process.run([shell, '-lic', 'command -v node'], { timeoutMs: 10000 })
329      const line = r.stdout.trim().split('\n').pop()
330      if (r.exitCode === 0 && line && line.startsWith('/') && (await nodeMajor($, line)) >= MIN_NODE_MAJOR) return line
331    } catch {}
332  }
333  return null
334}
335
336// The bridge's Unix socket, once it is listening.
337let socketPath: string | null = null
338
339async function ideCall($: any, name: string, args: Record<string, unknown>) {
340  if (!socketPath) return null
341  try {
342    const r = await $.http.fetch('http://bridge/call', {
343      method: 'POST',
344      headers: { 'content-type': 'application/json' },
345      body: JSON.stringify({ name, arguments: args }),
346      socketPath,
347    })
348    return r.ok ? JSON.parse(r.text) : null
349  } catch {
350    return null
351  }
352}
353
354// Settles once the editor's state first arrives (or there is none), so the
355// session's first message, sent while the bridge is still starting, waits
356// for it instead of going out without context.
357let isStarting = false
358let settleStart: () => void = () => {}
359let started: Promise<void> = Promise.resolve()
360const START_WAIT_MS = 4000
361
362// Typed at the start of a session's first message: sends it with the editor's
363// context and turns the mod on for the rest of the session. The app can put
364// notes of its own before the typed text (a session with no folder does), so
365// those are skipped and kept.
366const START_MARKER = /^((?:\s*<system-reminder>[\s\S]*?<\/system-reminder>)*\s*)\+\+(?:\s+|$)/
367
368// A message as its bubble shows it: the desktop draws what was typed, without
369// the app's notes and with the marker, so both are left out when matching.
370function asTyped(text: string) {
371  return text.replace(/^(?:\s*<system-reminder>[\s\S]*?<\/system-reminder>)*\s*/, '').replace(/^\+\+(?:\s+|$)/, '')
372}
373
374// A session the app started ahead of time learns it is on the desktop only
375// once it is claimed, which can come just after its first message.
376async function waitForDesktop($: any) {
377  for (let i = 0; i < 30; i++) {
378    if ((await $.session.surfaces()).some(isDesktop)) return true
379    await $.clock.sleep(100)
380  }
381  return false
382}
383
384// The mod runs in the desktop app only: the terminal CLI already gets the
385// editor's selection through /ide, and the editor accepts one client at a
386// time, so a second connection there would only compete with it.
387let isActive = false
388
389function isDesktop(surface: string | null | undefined) {
390  return surface === 'desktop'
391}
392
393async function showNotice($: any, next: { kind: string; ide?: string } | null) {
394  const current = await read($, notice)
395  if (current?.kind === next?.kind && current?.ide === next?.ide) return
396  await update($, notice, () => next)
397  await update($, isNoticeHidden, () => false)
398}
399
400async function handleLine($: any, msg: any) {
401  if (msg.type === 'ready') {
402    socketPath = msg.socket
403  } else if (msg.type === 'status') {
404    await update($, ide, () => msg.ide ?? null)
405    if (msg.ide) {
406      await showNotice($, null)
407    } else {
408      await update($, selection, () => null)
409      await showNotice($, { kind: msg.reason ?? 'no-editor', ide: msg.ideName })
410      settleStart()
411    }
412  } else if (msg.type === 'selection') {
413    const incoming = toSelection(msg)
414    const prev = await read($, selection)
415    if (prev && prev.filePath !== incoming.filePath) {
416      await update($, isDirty, () => false)
417    }
418    await update($, selection, () => incoming)
419    settleStart()
420  } else if (msg.type === 'dirty') {
421    const s = await read($, selection)
422    if (s && s.filePath === msg.filePath) await update($, isDirty, () => Boolean(msg.isDirty))
423  }
424}
425
426async function startBridge($: any) {
427  if (isActive) return
428  isActive = true
429  isStarting = true
430  started = new Promise<void>(resolve => {
431    settleStart = () => { isStarting = false; resolve() }
432  })
433  const node = await findNode($)
434  if (!node) {
435    await showNotice($, { kind: 'no-node' })
436    settleStart()
437    return
438  }
439  let buffer = ''
440  const bridge = $.process.spawn({ argv: [node, '-e', BRIDGE, await $.session.cwd()] })
441  for await (const piece of bridge) {
442    if (piece.stream !== 'stdout') continue
443    buffer += piece.text
444    let nl
445    while ((nl = buffer.indexOf('\n')) >= 0) {
446      const line = buffer.slice(0, nl)
447      buffer = buffer.slice(nl + 1)
448      let msg: any
449      try { msg = JSON.parse(line) } catch { continue }
450      await handleLine($, msg)
451    }
452  }
453}
454
455// What each context block last sent, so an unchanged selection is not resent.
456const lastSent = new Map<string, string>()
457
458function isFresh(key: string, value: string) {
459  const isSame = lastSent.get(key) === value
460  lastSent.set(key, value)
461  return !isSame
462}
463
464// ---- Band actions ----
465// The app's Buttons call runAction from onPress; the desktop's drawn tab and switch post
466// a press that the `ui.message` hook turns into the same call, by the Client's key.
467
468// Presses whose action has not finished yet: a second press of the same button is ignored.
469const inFlight = new Set<string>()
470
471async function runAction($: any, key: string) {
472  if (inFlight.has(key)) return
473  inFlight.add(key)
474  try {
475    await actionOf($, key)
476  } finally {
477    inFlight.delete(key)
478  }
479}
480
481async function actionOf($: any, key: string) {
482  // The demo's rows are samples: only the band's own toggles act.
483  const demo = await read($, isDemo)
484  const s = await read($, selection)
485  switch (key) {
486    case 'editor-on':
487    case 'editor-off':
488      if ((key === 'editor-on') === (await read($, isShown))) return
489    // falls through: same as the tab
490    case 'editor-switch':
491    case 'launch-tab:editor-context': {
492      // The tab turns it on and off. Off, nothing is sent; on, it connects and sends.
493      // On and off is the one switch: Pause is folded into it.
494      lastSent.clear()
495      await update($, isPaused, () => false)
496      await update($, isShown, v => !v)
497      if (await read($, isShown)) void startBridge($)
498      return
499    }
500    case 'close-notice':
501      await update($, isNoticeHidden, () => true)
502      return
503    case 'pause':
504      await update($, isPaused, v => !v)
505      return
506    case 'save':
507      if (!demo && s) await ideCall($, 'saveDocument', { filePath: s.filePath })
508      return
509    case 'pin':
510      if (!demo && s && !s.isEmpty && s.text) {
511        const pin = s
512        await update($, pins, list => (list.length >= MAX_PINS || list.some(p => pinKey(p) === pinKey(pin)) ? list : [...list, pin]))
513      }
514      return
515  }
516  if (key.startsWith('open-pin:') && !demo) {
517    const target = key.slice('open-pin:'.length)
518    const pin = (await read($, pins)).find(p => pinKey(p) === target)
519    if (pin) {
520      const lines = pin.text.split('\n').filter(l => l.trim() !== '')
521      await ideCall($, 'openFile', { filePath: pin.filePath, startText: lines[0] ?? '', endText: lines[lines.length - 1] ?? '', makeFrontmost: true })
522    }
523    return
524  }
525  if (key.startsWith('unpin:') && !demo) {
526    const target = key.slice('unpin:'.length)
527    await update($, pins, list => list.filter(p => pinKey(p) !== target))
528  }
529}
530
531// ---- Launcher ----
532// On the desktop each mod draws one tab in a shared row above the prompt; its full
533// panel opens in a pane. Each mod's band nests the bands of mods loaded after it, so
534// whichever draws outermost lays the tabs out in one order, then any other bands.
535const PANE = 'editor-context'
536// The floating card's content fills the card. The app sizes the card to its content, caps
537// it at 360px and sets its padding and text size by its density, so a fixed width in ch
538// overflows (and gets cut) when the app uses its larger, comfortable size.
539const POPOVER_WIDTH = '100%'
540// A launcher tab's key carries its place in the row: "launch:<rank>:<name>".
541const launchRank = (key: string) => Number(key.match(/^launch:(\d+):/)?.[1] ?? 9)
542const POWER_ICON = '<path d="M7 6a7.75 7.75 0 1 0 10 0"/><path d="M12 4l0 8"/>'
543const FILE_ICON = '<path d="M14 3v4a1 1 0 0 0 1 1h4"/><path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z"/>'
544const CODE_ICON = '<path d="M7 8l-4 4l4 4"/><path d="M17 8l4 4l-4 4"/><path d="M14 4l-4 16"/>'
545
546function nodeKey(node: any): string {
547  const key = node?.props?.key
548  return typeof key === 'string' ? key : ''
549}
550
551function stackLauncher(Box: any, mine: any, below: any, hasBelow: boolean, divider: (key: string) => any) {
552  let tabs: any[] = []
553  let rest: any[] = []
554  if (hasBelow && nodeKey(below) === 'launcher-stack') {
555    const [row, ...others] = below.children ?? []
556    tabs = row?.children ?? []
557    rest = others.filter((c: any) => !nodeKey(c).startsWith('launcher-divider'))
558  } else if (hasBelow) {
559    rest = [below]
560  }
561  const sorted = [mine, ...tabs]
562    .map((node, i) => ({ node, i, rank: launchRank(nodeKey(node)) }))
563    .sort((x, y) => x.rank - y.rank || x.i - y.i)
564    .map(x => x.node)
565  const children: any[] = [
566    <Box key="launcher-row" flexDirection="row" alignItems="center" columnGap={1} flexWrap="wrap">{sorted}</Box>,
567  ]
568  rest.forEach((node, i) => children.push(divider(`launcher-divider:${i}`), node))
569  return <Box key="launcher-stack" flexDirection="column" width="100%" rowGap={1}>{children}</Box>
570}
571
572export const register: Register = on => {
573  on('command.run', { command: 'editor-context-demo' }, async $ => {
574    await update($, isDemo, v => !v)
575    if (await read($, isDemo)) {
576      await update($, isShown, () => true)
577    }
578    return { text: (await read($, isDemo)) ? 'Editor band demo on: every row is shown with sample data. Run again to turn it off.' : 'Editor band demo off.' }
579  })
580
581  on('session.start', async ($, e, next) => {
582    const result = await next(e)
583    await $.command.register({
584      name: 'editor-context-demo',
585      description: 'Toggle sample data in the editor band to preview every row',
586    })
587    // The app's sessions start with no surface of their own and list it here.
588    const isOnDesktop = isDesktop(e.surface) || (await $.session.surfaces()).some(isDesktop)
589    if (isOnDesktop && (await read($, isShown))) void startBridge($)
590    return result
591  })
592
593  // A desktop session may start without a surface and attach the app after.
594  on('session.attach', async ($, e, next) => {
595    if (isDesktop(e.surface) && (await read($, isShown))) void startBridge($)
596    return next(e)
597  })
598
599  on('prompt.submit', async ($, e, next) => {
600    const origin = e.origin as { kind: string; name?: string }
601    const isTyped = origin.kind === 'composer' || origin.kind === 'bridge'
602    // "++" at the start of a session's first message turns it on, as the tab
603    // does: the new-session screen comes before any mod can draw a tab there.
604    const marker = START_MARKER.exec(e.text)
605    if (marker && isTyped && (await $.session.turns()) === 0) {
606      const typed = e.text.slice(marker[0].length)
607      if (typed) e = { ...e, text: marker[1] + typed }
608      if (!(await read($, isShown)) && (await waitForDesktop($))) {
609        lastSent.clear()
610        await update($, isPaused, () => false)
611        await update($, isShown, () => true)
612      }
613    }
614    if (!(await read($, isShown))) return next(e)
615    if (!isActive && (await $.session.surfaces()).some(isDesktop)) void startBridge($)
616    if (!isActive) return next(e)
617    if (isStarting) await Promise.race([started, $.clock.sleep(START_WAIT_MS)])
618    const s = await read($, selection)
619    const isUser = isTyped || (origin.kind === 'plugin' && origin.name === 'editor-context')
620    if (!s || !isUser || (await read($, isPaused))) return next(e)
621
622    const blocks: string[] = []
623
624    let main = `The user is working in ${s.ide}. Active file: ${s.filePath}, cursor at line ${s.startLine}.`
625    if (!s.isEmpty && s.text) {
626      main = isFresh('selection', `${s.filePath}|${s.startLine}|${s.endLine}|${s.text}`)
627        ? `The user has lines ${s.startLine}-${s.endLine} of ${s.filePath} selected in ${s.ide}. "This", "here" or "these lines" likely refers to it:\n${codeBlock(s.text)}`
628        : `The user still has lines ${s.startLine}-${s.endLine} of ${s.filePath} selected in ${s.ide} (same selection as their previous message).`
629    }
630    if (await read($, isDirty)) {
631      main += ' The file has unsaved changes in the editor, so the version on disk may differ from what the user sees.'
632    }
633    blocks.push(main)
634    const chips: Attached['chips'] = [{ icon: 'file', label: s.isEmpty ? `${fileName(s.filePath)} · L${s.startLine}` : `${fileName(s.filePath)} · ${rangeLabel(s)}` }]
635
636    // Each pin's code goes once; while unchanged, one line names them all.
637    const unchanged: string[] = []
638    for (const pin of await read($, pins)) {
639      if (isFresh(`pin:${pinKey(pin)}`, pin.text)) {
640        blocks.push(`The user pinned lines ${pin.startLine}-${pin.endLine} of ${pin.filePath} as reference for this conversation:\n${codeBlock(pin.text)}`)
641      } else {
642        unchanged.push(`lines ${pin.startLine}-${pin.endLine} of ${pin.filePath}`)
643      }
644    }
645    if (unchanged.length > 0) {
646      blocks.push(`Still pinned, unchanged since they were sent: ${unchanged.join('; ')}.`)
647    }
648    for (const pin of await read($, pins)) chips.push({ icon: 'pin', label: `${fileName(pin.filePath)} · ${rangeLabel(pin)}` })
649    await update($, attached, list => [...list, { text: asTyped(e.text), chips }].slice(-MAX_ATTACHED))
650
651    return next({ ...e, context: [...(e.context ?? []), ...blocks] })
652  })
653
654  // On the desktop, your message shows what went with it: chips above the bubble (chips.tsx).
655  on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
656    if (e.surface !== 'desktop') return next(e)
657    const props = e.props as { text?: string; origin?: { kind: string } }
658    // The desktop marks every message row it draws as 'sdk'; the text finds what went with it.
659    const kind = props.origin?.kind
660    if (kind !== 'sdk' && kind !== 'composer' && kind !== 'bridge' && kind !== 'plugin') return next(e)
661    const shown = asTyped(props.text ?? '')
662    const sent = [...(await read($, attached))].reverse().find(a => a.text === shown)
663    const elements = $.ui.resolve(e) as any
664    if (!sent || !elements.Svg) return next(e)
665    const mine: Chip[] = sent.chips.map((c, i) => ({ key: `0:editor-context:${i}`, icon: ICONS[c.icon] ?? '', label: c.label }))
666    return sentWith(elements, await next(e), mine)
667  })
668
669  // A custom control (controls.tsx) posts { press: true }; its Client's key names the button.
670  on('ui.message', async ($, e, next) => {
671    const data = e.data as { press?: unknown } | null
672    if (e.module.endsWith('controls.tsx') && data !== null && typeof data === 'object' && data.press === true) {
673      await runAction($, e.element)
674    }
675    return next(e)
676  })
677
678  // The pane closed, by its X or the tab: off, nothing more is sent.
679  on('ui.close', async ($, e, next) => {
680    if ((e as { id?: string }).id === PANE) {
681      lastSent.clear()
682      await update($, isShown, () => false)
683    }
684    return next(e)
685  })
686
687  // The launcher tab, in the row above the prompt (desktop).
688  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
689    if (!isDesktop(e.surface) || e.props.hasSurvey) return next(e)
690    const below = await next(e)
691    const hasBelow = below !== null && below !== undefined && (below as { type?: string }).type !== 'engine'
692    const elements = $.ui.resolve(e)
693    const { Box, Text } = elements
694    if (!('Client' in elements)) return below
695    const demo = await read($, isDemo)
696    const shown = demo || (await read($, isShown))
697    const s: EditorSelection | null = demo
698      ? { ide: 'Cursor', filePath: '/demo/src/components/CheckoutForm.tsx', startLine: 12, endLine: 30, isEmpty: false, text: 'demo' }
699      : await read($, selection)
700    const hasIde = demo || Boolean(await read($, ide))
701    // On, the tab is the file and its lines; off, or with no editor, it says so.
702    const name = s ? fileName(s.filePath) : ''
703    const isFileTab = shown && hasIde && s !== null
704    const tabLabel = isFileTab ? name : 'Editor'
705    const note = isFileTab ? (s!.isEmpty ? `L${s!.startLine}` : rangeLabel(s!)) : !shown ? 'off' : 'no editor'
706    // Hovering the tab floats the full panel above it: the desktop lifts a hidden Box
707    // that hover reveals into a popover card (the app's own popover look, up to 360px wide).
708    const panel = await editorPanel($, e)
709    const mine = (
710      <Box key="launch:0:editor-context" flexDirection="row">
711        <elements.Client
712          key="launch-tab:editor-context"
713          module="./controls.tsx"
714          props={{ kind: 'tab', label: tabLabel, icon: isFileTab ? FILE_ICON : CODE_ICON, isOn: isFileTab, note, ...(isFileTab ? { dot: DOT_COLOR } : {}) }}
715        />
716        <Box position="absolute" top={-1} left={0} display="none" hover={{ display: 'flex' }} flexDirection="column">
717          {panel}
718        </Box>
719      </Box>
720    )
721    const divider = (key: string) =>
722      'Svg' in elements ? (
723        <Box key={key} width="100%"><elements.Svg source={DIVIDER_SVG} alt="divider" height={0.5} /></Box>
724      ) : (
725        <Box key={key} width="100%" overflow="hidden"><Text dimColor wrap="truncate-end">{'\u2500'.repeat(400)}</Text></Box>
726      )
727    return stackLauncher(Box, mine, below, hasBelow, divider)
728  })
729
730}
731
732
733// The full panel, in the launcher tab's floating card, using its full width (POPOVER_WIDTH),
734// built like the app's own popovers: a "Share with Claude" switch on top, then the file,
735// its actions as the app's own buttons, and the pins.
736async function editorPanel($: any, e: any): Promise<any> {
737  const elements = $.ui.resolve(e)
738  const { Box, Button, Text } = elements
739  const hasSvg = 'Svg' in elements
740  const muted = (text: string) => <Text dimColor>{text}</Text>
741  const header = (label: string, extra?: any) => (
742    <Box flexDirection="row" alignItems="center" width="100%">
743      {muted(label)}
744      <Box flexGrow={1} />
745      {extra ?? null}
746    </Box>
747  )
748  const icon = (paths: string) => (hasSvg ? <elements.Svg source={`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="${ICON_COLOR}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${paths}</svg>`} alt="pin" width={ICON_SIZE} height={ICON_SIZE} /> : null)
749  const card = (...children: any[]) => (
750    <Box flexDirection="column" width={POPOVER_WIDTH} rowGap={1}>{children}</Box>
751  )
752
753  const demo = await read($, isDemo)
754  const shown = demo || (await read($, isShown))
755  const hasIde = demo || Boolean(await read($, ide))
756  const s: EditorSelection | null = demo
757    ? { ide: 'Cursor', filePath: '/demo/src/components/CheckoutForm.tsx', startLine: 12, endLine: 30, isEmpty: false, text: 'demo' }
758    : await read($, selection)
759  const switchRow = (
760    <elements.Client
761      key="editor-switch"
762      module="./controls.tsx"
763      width="100%"
764      props={{ kind: 'switch', label: 'Share with Claude', icon: CODE_ICON, isOn: shown }}
765    />
766  )
767  if (!shown) {
768    return card(switchRow, muted('Off. Turn on to send your Cursor or VS Code file and the lines you select with every message.'))
769  }
770  if (!isActive) void startBridge($)
771  if (!hasIde) {
772    const n = await read($, notice)
773    const message = !n ? 'Connecting to your editor\u2026'
774      : n.kind === 'no-node' ? `Editor context needs Node.js ${MIN_NODE_MAJOR} or later on this machine.`
775      : n.kind === 'disconnected' ? `Lost connection to ${n.ide ?? 'your editor'}. Reconnecting\u2026`
776      : 'Open VS Code or Cursor with the Claude Code extension installed.'
777    return card(
778      switchRow,
779      divider(elements, 'card-divider-waiting'),
780      <Box flexDirection="row" alignItems="center" columnGap={1}>
781        <Text color={WARN_COLOR}>{'\u25cb'}</Text>
782        <Text>{n?.kind === 'disconnected' ? 'Reconnecting' : 'Waiting for an editor'}</Text>
783      </Box>,
784      muted(message),
785    )
786  }
787
788  const dirty = demo || (await read($, isDirty))
789  const pinList: EditorSelection[] = demo
790    ? [
791        { ide: 'Cursor', filePath: '/demo/src/hooks/useCart.ts', startLine: 36, endLine: 48, isEmpty: false, text: 'demo' },
792        { ide: 'Cursor', filePath: '/demo/src/api/client.ts', startLine: 3, endLine: 13, isEmpty: false, text: 'demo' },
793      ]
794    : await read($, pins)
795  const hasSelection = Boolean(s && !s.isEmpty && s.text)
796  const canPin = hasSelection && pinList.length < MAX_PINS && !pinList.some(p => s && pinKey(p) === pinKey(s))
797  const dotSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 10 10"><circle cx="5" cy="5" r="5" fill="${DOT_COLOR}"/></svg>`
798  const chip = (key: string, label: string) => (
799    <Box key={key} borderStyle="round" borderColor="#FFFFFF0F" backgroundColor="#FFFFFF0F" paddingX={0.75} paddingY={0}>
800      <Text dimColor>{label}</Text>
801    </Box>
802  )
803
804  return card(
805    switchRow,
806    muted(s ? `${s.ide} \u00b7 sent with each message` : 'Sent with each message'),
807    divider(elements, 'card-divider-file'),
808    <Box flexDirection="row" alignItems="center" columnGap={1} width="100%">
809      {hasSvg ? <elements.Svg source={dotSvg} alt="sharing" width={DOT_SIZE} height={DOT_SIZE} /> : null}
810      <Text bold wrap="truncate-middle">{s ? fileName(s.filePath) : 'No file focused'}</Text>
811      <Box flexGrow={1} />
812      {s ? chip('lines', s.isEmpty ? `L${s.startLine}` : rangeLabel(s)) : null}
813    </Box>,
814    s && (canPin || dirty) ? (
815      <Box flexDirection="row" alignItems="center" columnGap={1} width="100%">
816        {dirty ? <Text color={WARN_COLOR}>Unsaved changes</Text> : null}
817        <Box flexGrow={1} />
818        {canPin ? <Button key="pin" label="Pin selection" onPress={() => void runAction($, 'pin')} /> : null}
819        {dirty ? <Button key="save" label="Save file" onPress={() => void runAction($, 'save')} /> : null}
820      </Box>
821    ) : null,
822    pinList.length > 0 ? divider(elements, 'card-divider-pins') : null,
823    pinList.length > 0
824      ? header('Pinned', pinList.length > 1
825          ? <Button key="unpin-all" plain dimColor label="Unpin all" onPress={() => { if (!demo) void update($, pins, () => []) }} />
826          : null)
827      : null,
828    pinList.length > 0 ? (
829      <Box flexDirection="column" width="100%" rowGap={0.5}>
830        {pinList.map(pin => (
831          <Box key={`pin:${pinKey(pin)}`} flexDirection="row" alignItems="center" columnGap={1} width="100%">
832            {icon(ICONS.pin ?? '')}
833            <Button key={`open-pin:${pinKey(pin)}`} plain onPress={() => void runAction($, `open-pin:${pinKey(pin)}`)}>{fileName(pin.filePath)} <Text dimColor>{rangeLabel(pin)}</Text></Button>
834            <Box flexGrow={1} />
835            <Button key={`unpin:${pinKey(pin)}`} plain dimColor label={'\u2715'} onPress={() => void runAction($, `unpin:${pinKey(pin)}`)} />
836          </Box>
837        ))}
838      </Box>
839    ) : null,
840  )
841}
842
843// A hairline across the card.
844function divider(elements: any, key: string) {
845  const { Box } = elements
846  return 'Svg' in elements ? <Box key={key} width="100%"><elements.Svg source={DIVIDER_SVG} alt="divider" height={0.5} /></Box> : null
847}
848
hooks/chips.tsx 82 lines
1// The "Sent with" row above your message on the desktop: what the mods attached to it,
2// as small chips. The same file in every mod that draws chips; keep the copies in sync.
3//
4// Each mod's UserMessage hook wraps the row beneath it. The outer one finds the inner
5// one's row (keyed "sent-with") and lays every chip out in one row, in the order the
6// chips' keys give. Text has no size setting, so the label and chips are SVGs with 11px text.
7
8export type Chip = {
9  /** "<rank>:<plugin>:<n>": the rank is the chip's place in the row, lowest first. */
10  key: string
11  /** Tabler path markup for the chip's icon. */
12  icon: string
13  label: string
14}
15
16export const CHIP_HEIGHT = 18
17const CHIP_FONT = 11
18const CHIP_TEXT = '#8A8A8A'
19const FONT = `font-family="-apple-system,BlinkMacSystemFont,system-ui,sans-serif" font-size="${CHIP_FONT}"`
20
21// About how wide the app's 11px system font draws a label, in px.
22function textWidth(text: string) {
23  let w = 0
24  for (const ch of text) w += /[il.,:·'|1 ]/.test(ch) ? 3.4 : /[A-Z0-9mw–_]/.test(ch) ? 7.2 : 5.7
25  return Math.ceil(w)
26}
27
28const escapeXml = (t: string) => t.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
29
30function labelWidth(text: string) {
31  return textWidth(text) + 2
32}
33
34function labelSvg(text: string) {
35  const w = labelWidth(text)
36  return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${CHIP_HEIGHT}" viewBox="0 0 ${w} ${CHIP_HEIGHT}"><text x="0" y="${CHIP_HEIGHT / 2}" dy="0.35em" ${FONT} fill="#6E6C67">${escapeXml(text)}</text></svg>`
37}
38
39function chipWidth(label: string) {
40  return 7 + 11 + 4 + textWidth(label) + 8
41}
42
43function chipSvg(icon: string, label: string) {
44  const w = chipWidth(label)
45  const glyph = `<g transform="translate(7 3.5) scale(${11 / 24})" fill="none" stroke="${CHIP_TEXT}" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">${icon}</g>`
46  return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${CHIP_HEIGHT}" viewBox="0 0 ${w} ${CHIP_HEIGHT}"><rect width="${w}" height="${CHIP_HEIGHT}" rx="6" fill="#FFFFFF" fill-opacity="0.07"/>${glyph}<text x="22" y="${CHIP_HEIGHT / 2}" dy="0.35em" ${FONT} fill="${CHIP_TEXT}">${escapeXml(label)}</text></svg>`
47}
48
49const keyOf = (node: any): string => (typeof node?.props?.key === 'string' ? node.props.key : '')
50const rankOf = (key: string) => Number(key.match(/^chip:(\d+):/)?.[1] ?? 9)
51
52/** The message row with this mod's chips added to any the mods beneath it drew. */
53export function sentWith(elements: any, below: any, mine: Chip[]) {
54  const { Box, Svg } = elements
55  let chips: any[] = []
56  let row = below
57  if (keyOf(below) === 'sent-with') {
58    const [chipRow, inner] = below.children ?? []
59    chips = (chipRow?.children ?? []).filter((c: any) => keyOf(c).startsWith('chip:'))
60    row = inner
61  }
62  const drawn = mine.map(c => (
63    <Box key={`chip:${c.key}`} flexDirection="row">
64      <Svg source={chipSvg(c.icon, c.label)} alt={c.label} width={chipWidth(c.label)} height={CHIP_HEIGHT} />
65    </Box>
66  ))
67  const all = [...chips, ...drawn]
68    .map((node, i) => ({ node, i, rank: rankOf(keyOf(node)) }))
69    .sort((a, b) => a.rank - b.rank || a.i - b.i)
70    .map(x => x.node)
71  // Above the bubble: under it is the app's own hover bar (time, copy, retry).
72  return (
73    <Box key="sent-with" flexDirection="column" rowGap={0.5}>
74      <Box key="sent-with-chips" flexDirection="row" justifyContent="flex-end" alignItems="center" columnGap={0.5} rowGap={0.5} flexWrap="wrap">
75        <Svg source={labelSvg('Sent with')} alt="Sent with" width={labelWidth('Sent with')} height={CHIP_HEIGHT} />
76        {all}
77      </Box>
78      {row}
79    </Box>
80  )
81}
82
hooks/controls.tsx 121 lines
1// One custom control, drawn by the desktop app: a launcher tab (clay while on), a switch
2// row for a popover (icon, label, hint and an on/off switch at the right end), or the
3// launcher pet, a picture that shows its petted mood while the pointer is on it and is
4// never pressed. Buttons are the app's own (Button); only these three are drawn here.
5// Each control is its own Client, so a click anywhere in it is a press of it: no
6// hit-testing. The module posts { press: true } and the hooks module (register.tsx,
7// `ui.message`) runs the action by the Client's key.
8//
9// Inside a Client one padding row is a full line (--engine-row-unit: 1lh), not half a
10// line as elsewhere in the band: paddingY 0.2 is about 4pt a side, a ~30pt control.
11//
12// Svg is not in surface.elements, but the engine passes an `h('Svg', …)` node
13// through and the desktop draws it (width and height are required there).
14
15type ControlProps = {
16  kind: 'tab' | 'switch' | 'pet'
17  label: string
18  /** Tabler path markup for the icon; drawn in the state's color. */
19  icon?: string
20  /** A whole SVG drawn in the icon's place, for a tab whose icon shows a value (a context ring). */
21  iconSvg?: string
22  /** A tab's status beside its label, or a switch row's hint after its label, drawn quieter. */
23  note?: string
24  /** A tab's small status dot, in this color. */
25  dot?: string
26  /** A switch's state; for a tab, whether it is lit. */
27  isOn?: boolean
28  /** The pet's picture now, the one while petted, and its size in px. */
29  pet?: { svg: string; petted: string; width: number; height: number }
30}
31
32type PointerState = { isHover: boolean; isDown: boolean }
33
34// The Claude app's own dark palette, plus the clay accent.
35const TEXT = '#F0EFEC'
36const MUTED = '#8A8A8A'
37const ACCENT = '#D97757'
38const ACCENT_INK = '#1A0F0A'
39const ACCENT_TEXT = '#F2A98E'
40
41const ICON_PX = 15
42
43function iconSource(paths: string, color: string, strokeWidth = 2) {
44  return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="${color}" stroke-width="${strokeWidth}" stroke-linecap="round" stroke-linejoin="round">${paths}</svg>`
45}
46
47const svg = (source: string, alt: string, size = ICON_PX) => h('Svg', { source, alt, width: size, height: size })
48
49const Control = (props: ControlProps, surface: any) => {
50  const { Box, Text } = surface.elements
51  const state: PointerState = surface.state ?? { isHover: false, isDown: false }
52
53  surface.onPointer((ev: { type: string; x: number; y: number; button?: string }) => {
54    const now: PointerState = surface.state ?? { isHover: false, isDown: false }
55    const isInside = ev.x >= 0 && ev.y >= 0 && ev.x < surface.columns && ev.y < surface.rows
56    if (ev.type === 'enter' || ev.type === 'move') {
57      if (now.isHover !== isInside) surface.setState({ ...now, isHover: isInside })
58    } else if (ev.type === 'leave') {
59      if (now.isHover || now.isDown) surface.setState({ isHover: false, isDown: false })
60    } else if (ev.type === 'down' && ev.button === 'left') {
61      surface.setState({ isHover: true, isDown: true })
62    } else if (ev.type === 'up') {
63      if (now.isDown && isInside && props.kind !== 'pet') surface.post({ press: true })
64      surface.setState({ isHover: isInside, isDown: false })
65    }
66  })
67
68  if (props.kind === 'pet' && props.pet) {
69    const { svg: now, petted, width, height } = props.pet
70    return Box({ flexDirection: 'row', children: [h('Svg', { source: state.isHover ? petted : now, alt: props.label || 'pet', width, height })] })
71  }
72
73  if (props.kind === 'tab') {
74    const isOn = props.isOn === true
75    const bg = isOn ? (state.isDown ? '#36292499' : state.isHover ? '#4A3630' : '#3E2F2A') : state.isDown ? '#2C2C2C' : state.isHover ? '#2A2A2A' : '#212121'
76    return Box({
77      flexDirection: 'row',
78      alignItems: 'center',
79      columnGap: 1,
80      paddingX: 1.25,
81      paddingY: 0.2,
82      flexShrink: 0,
83      borderStyle: 'round',
84      borderColor: isOn ? '#74483A' : '#383838',
85      backgroundColor: bg,
86      children: [
87        ...(props.iconSvg
88          ? [h('Svg', { source: props.iconSvg, alt: props.label, width: ICON_PX, height: ICON_PX })]
89          : props.icon ? [svg(iconSource(props.icon, isOn ? ACCENT : state.isHover ? TEXT : MUTED), props.label)] : []),
90        Text({ color: isOn ? ACCENT_TEXT : TEXT, wrap: 'wrap', children: props.label }),
91        ...(props.dot ? [h('Svg', { source: `<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 10 10"><circle cx="5" cy="5" r="4" fill="${props.dot}"/></svg>`, alt: 'status', width: 7, height: 7 })] : []),
92        ...(props.note ? [Text({ color: isOn ? ACCENT_TEXT : MUTED, dimColor: isOn, wrap: 'wrap', children: props.note })] : []),
93      ],
94    })
95  }
96
97  // A switch row.
98  const isOn = props.isOn === true
99  const bg = state.isDown ? '#262626' : state.isHover ? '#2A2A2A' : '#1F1F1F'
100  const track = `<svg xmlns="http://www.w3.org/2000/svg" width="30" height="18" viewBox="0 0 30 18"><rect width="30" height="18" rx="9" fill="${isOn ? ACCENT : '#4A4A4A'}"/><circle cx="${isOn ? 21 : 9}" cy="9" r="7" fill="${isOn ? ACCENT_INK : '#BDBDBD'}"/></svg>`
101  return Box({
102    flexDirection: 'row',
103    alignItems: 'center',
104    columnGap: 1,
105    paddingX: 1,
106    paddingY: 0.2,
107    borderStyle: 'round',
108    borderColor: bg,
109    backgroundColor: bg,
110    children: [
111      ...(props.icon ? [svg(iconSource(props.icon, isOn ? ACCENT : state.isHover ? TEXT : MUTED), props.label)] : []),
112      Text({ color: isOn ? ACCENT_TEXT : TEXT, children: props.label }),
113      ...(props.note ? [Text({ color: MUTED, wrap: 'truncate-end', children: props.note })] : []),
114      Box({ flexGrow: 1 }),
115      h('Svg', { source: track, alt: isOn ? 'on' : 'off', width: 30, height: 18 }),
116    ],
117  })
118}
119
120export default Control
121
types/index.d.ts 31 lines
1export type EditorSelection = {
2  ide: string
3  filePath: string
4  startLine: number
5  endLine: number
6  isEmpty: boolean
7  text: string
8}
9
10/** What the mod attached to one message, drawn as chips above it on the desktop. */
11export type Attached = { text: string; chips: { icon: 'file' | 'pin'; label: string }[] }
12
13declare module 'claude-code' {
14  interface PluginState {
15    'editor-context': {
16      selection: EditorSelection | null
17      ide: string | null
18      isPaused: boolean
19      isDirty: boolean
20      pins: EditorSelection[]
21      isDemo: boolean
22      notice: { kind: string; ide?: string } | null
23      isNoticeHidden: boolean
24      /** Sharing is on (the Editor tab, or the switch in its card). Off, nothing is sent. */
25      isShown: boolean
26      /** The last messages that went out with editor context, newest last. */
27      attached: Attached[]
28    }
29  }
30}
31