SLOPSHOPPER

lens

Sorts each of Claude's replies into what's in progress, what needs you and what got done, in a side pane and in place in the transcript

panerowsguardcommandmodeltimer
A shopper browsing a rack in a slop shop
README

lens

Sorts each of Claude's replies into five lists, in progress, needs you, waiting on others, blocked and done, under a one-line headline. You see where the work stands without reading the whole reply. The idea comes from Amelia Wattenberger's fish-eye essay: show the part you're looking at in detail, with the context around it summarised.

What it does

After each main-loop turn, Haiku reads your prompt and Claude's final answer and returns a headline plus up to five items per list:

  • In progress: work started but not finished, or next steps Claude said it would take itself.
  • Needs you: only what you personally have to do: questions Claude asked you, choices it offered, approvals or actions it requested of you.
  • Waiting on others: work waiting on someone other than you or Claude. Each item names who, as specifically as the reply allows (a session, agent, branch, PR, CI run or person). A task handed to another session goes here, even when you're the one relaying it.
  • Blocked: obstacles that are nobody's task: rate or usage limits, failing tools or services, denied permissions, missing access.
  • Done: what this turn finished.

One call covers all five lists, so switching between them never calls the model again. Digests are cached per turn for the session.

Every view is stamped with when Claude finished the original reply (with the date once it isn't today), not when it was summarised.

In the transcript

The inline button cycles three modes. Replace is the default:

  • off: replies draw as usual.
  • callout: a strip under each answer shows the headline, the list counts anything that needs you and anything blocked, plus open in lens ›.
  • replace: each answer becomes one box that starts as the original, with the purpose buttons and open in lens ›. Nothing is sent to Haiku until you click a list (all, in progress, needs you, waiting on others, blocked or done); the box then shows sorting… and swaps in the headline and that list. show original and show lens view flip between the two. The box stays the same size and place whether it is showing the original, sorting or showing the lists, so the transcript doesn't jump. Text Claude wrote between tool calls folds to its first line.

In the side pane

/lens [all|progress|needs|waiting|blocked|done] opens a pane with:

  • Session so far: what's still open after the latest turn, and what got done across the session.
  • The focused turn: the turn in full, with original to swap in Claude's reply.
  • Nearby turns: as headlines, with ✋ n when they're waiting on you and ⛔ n when they're blocked.

Keys while the pane has focus: a/1–5 choose the list, r retries the focused turn's summary, n cycles the inline mode, o toggles the original, and k/j/l move between turns.

When a summary fails

A summary that fails (the model call errors or times out, or its answer can't be read) shows ↻, inline and in the pane, next to the error. Inline replies never retry on their own, so a rate limit isn't hammered; the pane retries what it shows each time it refreshes. A summary still sorting… after 75 seconds was lost (a reload mid-call, say) and gets the button too.

Notes

  • Display only. Replace mode changes what you see, never what Claude reads or what the transcript file stores.
  • Cost. One Haiku call per turn when you first ask to see it sorted: by clicking a list on a reply in replace mode, opening the pane, or showing it in callout mode (callout sorts every reply as it is drawn, at most three at a time). While the pane is open, one more call for the session overview after each new turn.
  • Earlier turns. When the lens loads (a resumed session, or the mod added mid-session), it rebuilds the last 10 turns already in the transcript. Those turns have no timestamp, because the conversation API doesn't expose message times. Older turns, and the reply being streamed, draw as usual.

Limits of the mod API this works around

These come from Claude Code's mod API (2.1.293, early access) and shaped the design. Some may change in later releases.

  • No type size for text. Text and Markdown draw at the app's body size. Markdown ##/### headings use the app's own small heading styles, and Text offers only bold, italic, underline, colour and background. The only way to draw a larger heading is an Svg element, so on the desktop every heading here is an SVG image. That costs three things:
  • SVG headings can't be selected or copied.
  • They wrap lines by estimating character width, so a line can break a little early or late.
  • They pick light or dark colours from the system setting, which can differ from the app's theme.
  • Colours have no light/dark pair outside SVG. Text and Box colours take a theme name or a fixed hex. The lens uses mid-tone hex values that read on both themes, rather than separate shades for each.
  • Rewriting a reply means redrawing it. To add the callout or replace the answer, the mod draws the reply's text itself with Markdown. Spacing, the reply's opening bullet and code styling can look slightly different from replies the app draws.
  • Replies carry no turn id. A reply is drawn with a message id, and the hook that would tie rows to turns (session.append) is declared in the types but refused at load in this build. The mod matches each reply to its turn by text, so two replies that open identically can be matched to the wrong turn.
  • The desktop reports neither scroll position nor selection. In the desktop Code tab, replies are drawn without onScreen, and $.ui.selection() answers undefined. A pane that follows what you're reading is therefore only possible in the fullscreen terminal, so it isn't in this version.
  • Render hooks can't start work. A drawing may read state but not write it or call the model, so replies note which digests they're missing and a timer fetches them, three at a time.
  • Hotkeys only show on plain buttons. Buttons drawn as real buttons hide their hotkey, so the pane's shortcuts work but aren't labelled.

Develop

claude plugin validate mods/lens
claude plugin test mods/lens
Source 7 files
hooks/register.tsx 575 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, ResolveInput, Timer } from 'claude-code'
3
4import type { Digest, InlineMode, Purpose, Turn, View } from '../types'
5import { LENS, headingSvg, mid } from './heading'
6import type { Hue } from './heading'
7import { turnsFrom, withBackfill } from './backfill'
8import { endsAnswer, turnContaining } from './match'
9import { timeOf } from './time'
10import { BUCKETS, PURPOSES, overviewRequest, parseDigest, titleOf, turnRequest } from './digest'
11
12const PANE = 'lens'
13const MODEL = 'haiku'
14const NEAR = 2 // turns this close to the focus show their headline; farther ones fold away
15const TICK_MS = 400 // how often the inline rows' wanted digests are generated
16const REPLY_MAX = 8000 // characters kept per reply block for matching
17const INLINE_MAX = 3 // inline digests generated at once
18const BACKFILL = 10 // earlier turns rebuilt from the transcript when the lens loads
19const TIMEOUT_MS = 60_000 // how long one model call may take
20const STALE_MS = TIMEOUT_MS + 15_000 // a call pending longer was lost (a reload mid-call) and may be retried
21
22const turns = atom({ plugin: 'lens', key: 'turns' } as const, [])
23const purpose = atom({ plugin: 'lens', key: 'purpose' } as const, 'all')
24const focus = atom({ plugin: 'lens', key: 'focus' } as const, null)
25const views = atom({ plugin: 'lens', key: 'views' } as const, {})
26const isOpen = atom({ plugin: 'lens', key: 'isOpen' } as const, false)
27const inline = atom({ plugin: 'lens', key: 'inline' } as const, 'replace')
28const expanded = atom({ plugin: 'lens', key: 'expanded' } as const, [])
29const lensed = atom({ plugin: 'lens', key: 'lensed' } as const, [])
30
31const MODES: InlineMode[] = ['off', 'callout', 'replace']
32// Sessions from before the third mode stored this as a boolean.
33const modeOf = (stored: unknown): InlineMode =>
34  stored === false ? 'off' : stored === true ? 'callout' : MODES.includes(stored as InlineMode) ? (stored as InlineMode) : 'replace'
35
36// v2: digests cached before the five lists had a different shape.
37const viewKey = (turnId: string) => `digest|v2|${turnId}`
38const overviewKey = (lastTurnId: string) => `digest|v2|overview|${lastTurnId}`
39
40const focusIndex = (list: Turn[], id: string | null) => {
41  const found = id === null ? -1 : list.findIndex(t => t.id === id)
42
43  return found === -1 ? list.length - 1 : found
44}
45
46// What a retry button may redo: a failed call, or one pending past its timeout.
47const isRetryable = (view: View | undefined, now: number) =>
48  view?.status === 'error' || (view?.status === 'pending' && now - (view.since ?? 0) > STALE_MS)
49
50// `force` redoes the call whatever is known: the retry buttons.
51async function generate($: EngineInterface, key: string, ask: { system: string; prompt: string; maxTokens: number }, force = false) {
52  const now = await $.clock.now().catch(() => Date.now())
53  const known = (await read($, views))[key]
54  if (!force && known && known.status !== 'error' && !isRetryable(known, now)) return
55
56  const pending: View = { status: 'pending', text: '', since: now }
57  await update($, views, v => ({ ...v, [key]: pending }))
58  // A call that rejects (the engine refusing to send it) ends as an error view
59  // too, never left pending: an error is what the next refresh retries.
60  let view: View
61  try {
62    const result = await $.model.complete({ model: MODEL, effort: 'low', timeoutMs: TIMEOUT_MS, ...ask })
63    const digest = result.isAnswered ? parseDigest(result.text) : undefined
64    view = digest
65      ? { status: 'done', text: digest.headline, digest }
66      : { status: 'error', text: result.isAnswered ? "couldn't read the summary" : `couldn't summarize (${result.reason})` }
67  } catch {
68    view = { status: 'error', text: "couldn't summarize" }
69  }
70  await update($, views, v => ({ ...v, [key]: view }))
71}
72
73// One line per earlier turn, so a digest knows what led up to its turn.
74const contextFor = (list: Turn[], known: Record<string, View>, i: number) =>
75  list.slice(Math.max(0, i - 6), i).map(t => {
76    const view = known[viewKey(t.id)]
77
78    return view?.status === 'done' ? view.text : titleOf(t)
79  })
80
81// Fills what the pane is about to show: the focused turn and its neighbours,
82// and the session overview.
83async function refresh($: EngineInterface) {
84  const list = await read($, turns)
85  if (list.length === 0) return
86
87  const f = focusIndex(list, await read($, focus))
88  const known = await read($, views)
89
90  const jobs: Promise<void>[] = []
91  list.forEach((t, i) => {
92    if (Math.abs(i - f) <= NEAR) jobs.push(generate($, viewKey(t.id), turnRequest(t, contextFor(list, known, i))))
93  })
94  const last = list.at(-1)
95  if (last) jobs.push(generate($, overviewKey(last.id), overviewRequest(list.slice(-20))))
96  await Promise.all(jobs)
97}
98
99async function retryTurn($: EngineInterface, turnId: string) {
100  const list = await read($, turns)
101  const i = list.findIndex(t => t.id === turnId)
102  const turn = list[i]
103  if (turn !== undefined) await generate($, viewKey(turnId), turnRequest(turn, contextFor(list, await read($, views), i)), true)
104}
105
106async function retryOverview($: EngineInterface) {
107  const list = await read($, turns)
108  const last = list.at(-1)
109  if (last) await generate($, overviewKey(last.id), overviewRequest(list.slice(-20)), true)
110}
111
112const shownBuckets = (d: Digest, p: Purpose) => BUCKETS.filter(b => (p === 'all' ? d[b.id].length > 0 : b.id === p))
113
114// A heading at a real size: SVG text where the surface draws SVG (the desktop),
115// else bold coloured text, as the terminal has one type size.
116function heading($: EngineInterface, e: ResolveInput, key: string, text: string, size: number, hue: Hue, columns: number) {
117  // By surface, not by the table: every surface's table answers `in` for Svg.
118  if (e.surface !== 'terminal') {
119    const { Box, Svg } = $.ui.resolve({ ...e, surface: e.surface })
120    const svg = headingSvg(text, size, hue, Math.min(720, Math.max(240, columns * 8)))
121
122    return (
123      <Box key={key}>
124        <Svg source={svg.source} alt={text} width={svg.width} height={svg.height} />
125      </Box>
126    )
127  }
128  const { Text } = $.ui.resolve(e)
129
130  return (
131    <Text key={key} bold color={hue === 'text' ? undefined : mid(hue)}>
132      {text}
133    </Text>
134  )
135}
136
137// The digest's lists, one heading each in the list's own colour, as many as the
138// purpose asks for. `all` skips empty ones.
139function sections($: EngineInterface, e: ResolveInput, d: Digest, p: Purpose, size: number, columns: number) {
140  const { Box, Markdown } = $.ui.resolve(e)
141  const shown = shownBuckets(d, p)
142  if (shown.length === 0) return <Markdown text="_nothing to report_" />
143
144  return (
145    <Box flexDirection="column" rowGap={1}>
146      {shown.map(b => (
147        <Box key={`s-${b.id}`} flexDirection="column">
148          {heading($, e, `h-${b.id}`, `${b.mark} ${b.label}`, size, b.hue, columns)}
149          <Markdown text={d[b.id].length === 0 ? `_${b.empty}_` : d[b.id].map(x => `- ${x}`).join('\n')} />
150        </Box>
151      ))}
152    </Box>
153  )
154}
155
156const tally = (d: Digest) => BUCKETS.map(b => `${b.mark} ${d[b.id].length}`).join('   ')
157
158// A message row carries no turn id; once matched by its text, it keeps its turn.
159const turnOfMessage = new Map<string, string>()
160const turnFor = (list: Turn[], requestId: string, text: string) => {
161  const known = turnOfMessage.get(requestId)
162  if (known) return known
163  const turn = turnContaining(list, text)
164  if (turn) turnOfMessage.set(requestId, turn.id)
165
166  return turn?.id
167}
168
169async function openPane($: EngineInterface) {
170  await update($, isOpen, () => true)
171  await $.ui.open({ id: PANE, title: 'Lens' })
172  await refresh($)
173}
174
175// The inline rows ask for the digests they lack; a render may not start work,
176// so they note the turn here and a timer generates a few at a time.
177const wanted = new Set<string>()
178let inFlight = 0
179let ticker: Timer | undefined
180
181async function fillInline($: EngineInterface) {
182  if (wanted.size === 0 || inFlight >= INLINE_MAX) return
183
184  const list = await read($, turns)
185  const known = await read($, views)
186  const jobs: Promise<void>[] = []
187  for (const turnId of [...wanted].reverse()) {
188    if (inFlight >= INLINE_MAX) break
189    wanted.delete(turnId)
190    const i = list.findIndex(t => t.id === turnId)
191    const turn = list[i]
192    const key = viewKey(turnId)
193    if (turn === undefined || known[key] !== undefined) continue
194    inFlight += 1
195    jobs.push(generate($, key, turnRequest(turn, contextFor(list, known, i))).finally(() => (inFlight -= 1)))
196  }
197  await Promise.all(jobs)
198}
199
200// The inline row's button: show this turn in the pane, opening it if need be.
201async function showTurn($: EngineInterface, id: string) {
202  const list = await read($, turns)
203  await update($, focus, () => (id === list.at(-1)?.id ? null : id))
204  if (await read($, isOpen)) await refresh($)
205  else await openPane($)
206}
207
208// The turns from before the lens loaded (a resumed session, or the mod added
209// mid-session): the last few are rebuilt from the transcript, without times.
210async function backfill($: EngineInterface) {
211  try {
212    const rebuilt = turnsFrom(await $.session.messages())
213    if (rebuilt.length > 0) await update($, turns, known => withBackfill(known, rebuilt, BACKFILL).slice(-50))
214  } catch {
215    // No transcript to read: the lens starts from the next turn.
216  }
217}
218
219const toggleExpanded = ($: EngineInterface, id: string) =>
220  update($, expanded, ids => (ids.includes(id) ? ids.filter(x => x !== id) : [...ids, id].slice(-200)))
221
222// An inline reply draws its original until the person asks for a list; only then is it sorted.
223const setLensed = ($: EngineInterface, id: string, isOn: boolean) =>
224  update($, lensed, ids => (isOn ? (ids.includes(id) ? ids : [...ids, id].slice(-200)) : ids.filter(x => x !== id)))
225
226// A purpose button on a reply: show that list, sorting the reply first if it isn't yet
227// (an error from before is retried).
228async function pickPurpose($: EngineInterface, id: string, u: Purpose) {
229  await update($, purpose, () => u)
230  await setLensed($, id, true)
231  const list = await read($, turns)
232  const i = list.findIndex(t => t.id === id)
233  const turn = list[i]
234  if (turn === undefined) return
235  await generate($, viewKey(id), turnRequest(turn, contextFor(list, await read($, views), i)))
236}
237
238export const register: Register = on => {
239  // The turn in flight; a reload mid-turn loses it, which only drops that turn's file list.
240  let prompt = ''
241  let files: string[] = []
242  let tools = 0
243
244  on('session.start', async ($, e, next) => {
245    ticker?.cancel()
246    ticker = $.clock.every(TICK_MS, () => void fillInline($))
247    await $.command.register({
248      name: 'lens',
249      description: 'Sort this session into in progress, needs you, waiting on others, blocked and done: /lens [all|progress|needs|waiting|blocked|done]',
250      argumentHint: '[purpose]',
251    })
252    await backfill($)
253
254    return next(e)
255  })
256
257  on('command.run', { command: 'lens' }, async ($, e) => {
258    const words: Record<string, Purpose> = {
259      all: 'all',
260      progress: 'progress',
261      needs: 'needs',
262      you: 'needs',
263      waiting: 'waiting',
264      others: 'waiting',
265      blocked: 'blocked',
266      done: 'done',
267    }
268    for (const word of e.args.toLowerCase().split(/\s+/).filter(Boolean)) {
269      const u = words[word]
270      if (u) await update($, purpose, () => u)
271    }
272    if ((await read($, turns)).length === 0) {
273      await update($, isOpen, () => true)
274      await $.ui.open({ id: PANE, title: 'Lens' })
275
276      return { text: 'Lens opened. It fills in after the next answer.' }
277    }
278    await openPane($)
279
280    return { text: 'Lens opened.' }
281  })
282
283  on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
284    const mode = modeOf(await read($, inline))
285    if (e.props.isSummary || mode === 'off') return next(e)
286    const list = await read($, turns)
287    const id = turnFor(list, e.requestId, e.props.text)
288    const turn = list.find(t => t.id === id)
289    if (turn === undefined) return next(e) // still streaming, or from before the lens
290
291    const isEnd = endsAnswer(turn, e.props.text)
292    const isPicked = (await read($, lensed)).includes(turn.id)
293    const p = await read($, purpose)
294    const view = (await read($, views))[viewKey(turn.id)]
295    // Callout sorts every reply as it is drawn; replace waits for the person to pick a list.
296    if (view === undefined && mode === 'callout') wanted.add(turn.id)
297    const d = view?.digest
298    const { Box, Text, Button, Markdown } = $.ui.resolve(e)
299    const label = PURPOSES.find(x => x.id === p)?.label ?? p
300    const columns = e.viewport?.columns ?? 80
301    const when = timeOf(turn.at, await $.clock.now().catch(() => Date.now()))
302
303    const color = mid(LENS)
304    const openButton = <Button key={`lens-${turn.id}`} label="open in lens ›" onPress={() => showTurn($, turn.id)} />
305    const status = view?.status === 'error' ? `${view.text}; showing the original` : 'sorting…'
306    const retryButton = isRetryable(view, await $.clock.now().catch(() => Date.now())) && (
307      <Button key={`retry-${turn.id}`} label="↻" onPress={() => retryTurn($, turn.id)} />
308    )
309
310    // Callout: the original, then a strip with the headline and the purpose's items
311    // (with `all`, the counts and whatever needs the person).
312    if (mode === 'callout') {
313      if (!isEnd) return next(e)
314      // With `all`, what needs a look: the person's asks and what is blocked.
315      const items: { text: string; hue?: Hue }[] =
316        d === undefined
317          ? []
318          : p === 'all'
319            ? BUCKETS.filter(b => b.id === 'needs' || b.id === 'blocked').flatMap(b => d[b.id].map(x => ({ text: `${b.mark} ${x}`, hue: b.hue })))
320            : d[p].map(x => ({ text: `• ${x}` }))
321
322      return (
323        <Box flexDirection="column" rowGap={1}>
324          <Markdown text={e.props.text} />
325          <Box flexDirection="column" borderStyle="round" borderColor={color} paddingX={1}>
326            <Box columnGap={2} alignItems="center">
327              <Text bold color={color}>
328                ◆ Lens
329              </Text>
330              {when !== undefined && <Text dimColor>{when}</Text>}
331              <Box flexShrink={1} flexGrow={1}>
332                <Text dimColor={d === undefined}>{d?.headline ?? status}</Text>
333              </Box>
334              {retryButton}
335              {openButton}
336            </Box>
337            {d !== undefined && p === 'all' && <Text dimColor>{tally(d)}</Text>}
338            {d !== undefined && p !== 'all' && items.length === 0 && <Text dimColor>{BUCKETS.find(b => b.id === p)?.empty}</Text>}
339            {items.map((x, i) => (
340              <Text key={`i-${i}`} color={x.hue === undefined ? undefined : mid(x.hue)}>
341                {x.text}
342              </Text>
343            ))}
344          </Box>
345        </Box>
346      )
347    }
348
349    // Replace: the steps between tool calls fold to one dim line each. The answer
350    // is one box in every state (the original, sorting, the lists), so nothing
351    // around it moves as it fills in or flips; only its body changes. It starts as
352    // the original, and the model is called only once a list is picked.
353    if (!isEnd) {
354      return (
355        <Text dimColor wrap="truncate-end">
356          · {e.props.text.trim().split('\n')[0]}
357        </Text>
358      )
359    }
360    const isLens = isPicked && d !== undefined
361
362    return (
363      <Box flexDirection="column" borderStyle="round" borderColor={color} paddingX={1} rowGap={1}>
364        <Box columnGap={2} alignItems="center">
365          <Text bold color={color}>
366            ◆ Lens · {isLens ? label : 'original'}
367          </Text>
368          {when !== undefined && <Text dimColor>{when}</Text>}
369          <Box flexShrink={1} flexGrow={1}>
370            {isPicked && d === undefined && <Text dimColor>{status}</Text>}
371          </Box>
372          {isPicked && retryButton}
373          {d !== undefined && (
374            <Button key={`orig-${turn.id}`} label={isLens ? 'show original' : 'show lens view'} onPress={() => setLensed($, turn.id, !isLens)} />
375          )}
376          {openButton}
377        </Box>
378        {/* The pane's purpose buttons, here too: they refilter every reply at once. */}
379        <Box flexWrap="wrap" columnGap={1} rowGap={1} alignItems="center">
380          {PURPOSES.map(x => (
381            <Button
382              key={`ru-${turn.id}-${x.id}`}
383              variant={isPicked && x.id === p ? 'primary' : 'secondary'}
384              label={x.label}
385              onPress={() => pickPurpose($, turn.id, x.id)}
386            />
387          ))}
388        </Box>
389        {isLens ? (
390          <Box flexDirection="column" rowGap={1}>
391            {heading($, e, 'headline', d.headline, 20, 'text', columns)}
392            {sections($, e, d, p, 16, columns)}
393          </Box>
394        ) : (
395          <Markdown text={e.props.text} />
396        )}
397      </Box>
398    )
399  })
400
401  on('ui.close', async ($, e, next) => {
402    if (e.id === PANE) await update($, isOpen, () => false)
403
404    return next(e)
405  })
406
407  on('turn.start', ($, e, next) => {
408    prompt = e.text
409    files = []
410    tools = 0
411
412    return next(e)
413  })
414
415  on('tool.call', ($, e, next) => {
416    if (e.agentId === undefined) {
417      tools += 1
418      const input = ('input' in e ? e.input : undefined) as { file_path?: unknown; notebook_path?: unknown } | undefined
419      const path = input?.file_path ?? input?.notebook_path
420      if (typeof path === 'string' && !files.includes(path)) files.push(path)
421    }
422
423    return next(e)
424  })
425
426  on('turn.complete', async ($, e, next) => {
427    if (e.agentId === undefined && e.reason === 'answer' && e.answer.trim() !== '') {
428      // The turn's assistant text blocks: every row after the last prompt the person typed.
429      // Missing them only costs matching on the turn's earlier blocks, never the turn.
430      let replies: string[] = []
431      try {
432        const rows = await $.session.messages()
433        const start = rows.findLastIndex(r => r.role === 'user' && (r.toolResults ?? []).length === 0)
434        replies = rows
435          .slice(start + 1)
436          .filter(r => r.role === 'assistant' && r.text.trim() !== '' && r.text !== e.answer)
437          .map(r => r.text.slice(0, REPLY_MAX))
438      } catch {
439        replies = []
440      }
441      // The reply's own time, which every view stamps; a clock that fails costs the stamp, not the turn.
442      const at = await $.clock.now().catch(() => undefined)
443      const turn: Turn = { id: e.turnId, prompt, answer: e.answer, files: [...files], tools, replies, at }
444      await update($, turns, list => [...list, turn].slice(-50))
445      if (await read($, isOpen)) $.clock.after(50, () => void refresh($))
446    }
447
448    return next(e)
449  })
450
451  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
452    const { Box, Text, Button, Markdown } = $.ui.resolve(e)
453    const list = await read($, turns)
454    const p = await read($, purpose)
455    const known = await read($, views)
456    const mode = modeOf(await read($, inline))
457    const columns = e.props.bodyColumns
458    const color = mid(LENS)
459
460    const sortBy = (u: Purpose) => () => update($, purpose, () => u)
461    const goTo = (id: string | null) => async () => {
462      await update($, focus, () => id)
463      await refresh($)
464    }
465    const cycleInline = () => update($, inline, () => MODES[(MODES.indexOf(mode) + 1) % MODES.length] ?? 'replace')
466
467    const header = (
468      <Box flexDirection="column">
469        <Box flexWrap="wrap" columnGap={1} rowGap={1} alignItems="center">
470          {PURPOSES.map(x => (
471            <Button key={`u-${x.id}`} hotkey={x.hotkey} variant={x.id === p ? 'primary' : 'secondary'} label={x.label} onPress={sortBy(x.id)} />
472          ))}
473          <Text dimColor> │ </Text>
474          <Button key="inline" hotkey="n" label={`inline: ${mode}`} onPress={cycleInline} />
475        </Box>
476      </Box>
477    )
478
479    if (list.length === 0) {
480      return (
481        <Box flexDirection="column" gap={1}>
482          {header}
483          <Text dimColor>No answers yet. The lens fills in after Claude's next reply.</Text>
484        </Box>
485      )
486    }
487
488    const f = focusIndex(list, await read($, focus))
489    const now = await $.clock.now().catch(() => Date.now())
490    const shownOriginal = await read($, expanded)
491    const body = (v: View | undefined, key: string, retry: () => Promise<void>) =>
492      v?.digest !== undefined ? (
493        <Box flexDirection="column" rowGap={1}>
494          <Text bold>{v.digest.headline}</Text>
495          {sections($, e, v.digest, p, 15, columns)}
496        </Box>
497      ) : (
498        <Box columnGap={2} alignItems="center">
499          <Text dimColor>{v?.status === 'error' ? v.text : 'sorting…'}</Text>
500          {isRetryable(v, now) && <Button key={key} hotkey={key === 'retry-turn' ? 'r' : undefined} label="↻" onPress={retry} />}
501        </Box>
502      )
503    const overview = known[overviewKey(list.at(-1)?.id ?? '')]
504
505    const rows = list.map((t, i) => {
506      const d = Math.abs(i - f)
507      const view = known[viewKey(t.id)]
508      if (d === 0) {
509        const isOriginal = shownOriginal.includes(t.id)
510
511        return (
512          <Box key={`t-${t.id}`} flexDirection="column" borderStyle="round" borderColor={color} paddingX={1} rowGap={1}>
513            <Box columnGap={2} alignItems="center">
514              <Box flexShrink={1} flexGrow={1}>
515                {heading($, e, 'title', `${i + 1}. ${titleOf(t)}`, 18, 'text', columns - 14)}
516              </Box>
517              <Button key="pane-orig" hotkey="o" label={isOriginal ? 'lens view' : 'original'} onPress={() => toggleExpanded($, t.id)} />
518            </Box>
519            {(t.at !== undefined || t.files.length > 0) && (
520              <Text dimColor wrap="truncate-end">
521                {[timeOf(t.at, now), ...t.files].filter(Boolean).join('  ·  ')}
522              </Text>
523            )}
524            {isOriginal ? <Markdown text={t.answer} /> : body(view, 'retry-turn', () => retryTurn($, t.id))}
525          </Box>
526        )
527      }
528      if (d <= NEAR) {
529        const flags = BUCKETS.filter(b => (b.id === 'needs' || b.id === 'blocked') && (view?.digest?.[b.id].length ?? 0) > 0)
530          .map(b => `   ${b.mark} ${view?.digest?.[b.id].length}`)
531          .join('')
532        const when = timeOf(t.at, now)
533
534        return (
535          <Button
536            key={`t-${t.id}`}
537            plain
538            dimColor
539            label={`${i + 1}  ${when !== undefined ? `${when}  ` : ''}${view?.status === 'done' ? view.text : titleOf(t)}${flags}`}
540            onPress={goTo(i === list.length - 1 ? null : t.id)}
541          />
542        )
543      }
544
545      return null
546    })
547
548    const older = Math.max(0, f - NEAR)
549    const newer = Math.max(0, list.length - 1 - f - NEAR)
550
551    return (
552      <Box flexDirection="column" gap={1}>
553        {header}
554        <Box flexDirection="column" rowGap={1}>
555          {heading($, e, 'session', 'Session so far', 20, LENS, columns)}
556          {list.at(-1)?.at !== undefined && <Text dimColor>as of {timeOf(list.at(-1)?.at, now)}</Text>}
557          {body(overview, 'retry-overview', () => retryOverview($))}
558        </Box>
559        <Box flexDirection="column">
560          {older > 0 && <Text dimColor>… {older} earlier</Text>}
561          {rows}
562          {newer > 0 && <Text dimColor>… {newer} later</Text>}
563        </Box>
564        <Box columnGap={1}>
565          {f > 0 && <Button key="prev" hotkey="k" label="‹ older" onPress={goTo(list[f - 1]?.id ?? null)} />}
566          {f < list.length - 1 && (
567            <Button key="next" hotkey="j" label="newer ›" onPress={goTo(f + 1 === list.length - 1 ? null : (list[f + 1]?.id ?? null))} />
568          )}
569          {f < list.length - 1 && <Button key="latest" hotkey="l" label="latest »" onPress={goTo(null)} />}
570        </Box>
571      </Box>
572    )
573  })
574}
575
hooks/heading.ts 67 lines
1// Headings drawn as SVG text, the one way a plugin sets a type size on the
2// desktop: its Text and Markdown take the app's body size and its small
3// heading styles. The SVG is drawn as an image, so it carries its own colours
4// for light and dark and wraps its own lines.
5
6// Six hues, none shared: one per list, whose colour means the same everywhere,
7// and the lens's own for its frames. `mid` reads on either theme and colours
8// borders and text; `light` and `dark` are the headings' shades.
9export const PALETTE = {
10  text: { mid: '#8a8780', light: '#1f1e1d', dark: '#f0eee6' },
11  // the lists
12  blue: { mid: '#3b82f6', light: '#1d4ed8', dark: '#93b4fd' },
13  amber: { mid: '#f59e0b', light: '#b45309', dark: '#fcd34d' },
14  teal: { mid: '#14b8a6', light: '#0f766e', dark: '#5eead4' },
15  red: { mid: '#ef4444', light: '#b91c1c', dark: '#fca5a5' },
16  green: { mid: '#22c55e', light: '#15803d', dark: '#86efac' },
17  // the lens
18  violet: { mid: '#a855f7', light: '#7e22ce', dark: '#d8b4fe' },
19} as const
20
21export type Hue = keyof typeof PALETTE
22
23export const LENS: Hue = 'violet'
24
25export const mid = (hue: Hue) => PALETTE[hue].mid
26
27const escape = (text: string) =>
28  text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
29
30// Greedy word wrap on an estimate of the glyph width: system-ui runs about
31// 0.55em per character at these weights.
32function wrap(text: string, perLine: number) {
33  const lines: string[] = []
34  let line = ''
35  for (const word of text.split(/\s+/).filter(Boolean)) {
36    if (line !== '' && line.length + 1 + word.length > perLine) {
37      lines.push(line)
38      line = word
39    } else {
40      line = line === '' ? word : `${line} ${word}`
41    }
42  }
43  if (line !== '') lines.push(line)
44
45  return lines.length ? lines : ['']
46}
47
48export function headingSvg(text: string, size: number, hue: Hue, maxWidth: number) {
49  const perLine = Math.max(8, Math.floor(maxWidth / (size * 0.55)))
50  const lines = wrap(text, perLine)
51  const lineHeight = Math.round(size * 1.3)
52  const width = Math.min(maxWidth, Math.ceil(Math.max(...lines.map(l => l.length)) * size * 0.58) + 4)
53  const height = lines.length * lineHeight + Math.round(size * 0.35)
54  const { light, dark } = PALETTE[hue]
55  const spans = lines.map((l, i) => `<tspan x="0" y="${Math.round(size + i * lineHeight)}">${escape(l)}</tspan>`).join('')
56
57  return {
58    width,
59    height,
60    source:
61      `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
62      `<style>text{fill:${light};font:600 ${size}px system-ui,-apple-system,"Segoe UI",sans-serif}` +
63      `@media (prefers-color-scheme:dark){text{fill:${dark}}}</style>` +
64      `<text>${spans}</text></svg>`,
65  }
66}
67
hooks/backfill.ts 89 lines
1import type { SessionMessage } from 'claude-code'
2
3import type { Turn } from '../types'
4
5const REPLY_MAX = 8000 // characters kept per reply block for matching
6
7// A prompt the person typed: a user row with text and no tool results, and not
8// one of the rows the engine writes in their name (command records, reminders).
9const isPrompt = (row: SessionMessage) =>
10  row.role === 'user' &&
11  (row.toolResults ?? []).length === 0 &&
12  row.text.trim() !== '' &&
13  !/^\s*<(local-command|command-|system-reminder|task-notification)/.test(row.text)
14
15// A stable id from the turn's text, so a turn rebuilt twice is the same turn.
16const hash = (text: string) => {
17  let h = 5381
18  for (let i = 0; i < text.length; i++) h = ((h << 5) + h + text.charCodeAt(i)) | 0
19
20  return (h >>> 0).toString(36)
21}
22
23/**
24 * The turns a transcript holds, rebuilt from its rows: each typed prompt and
25 * the assistant text that followed it, the last block being the answer. Rows
26 * carry no times, so a rebuilt turn has none.
27 */
28export function turnsFrom(rows: readonly SessionMessage[]): Turn[] {
29  const turns: Turn[] = []
30  let open: { prompt: string; texts: string[]; files: string[]; tools: number } | undefined
31  const close = () => {
32    const answer = open?.texts.at(-1)
33    if (open === undefined || answer === undefined) return
34    turns.push({
35      id: `backfill:${hash(`${open.prompt}\n${answer.slice(0, 500)}`)}`,
36      prompt: open.prompt,
37      answer,
38      files: open.files,
39      tools: open.tools,
40      replies: open.texts.slice(0, -1).map(t => t.slice(0, REPLY_MAX)),
41    })
42  }
43
44  for (const row of rows) {
45    if (isPrompt(row)) {
46      close()
47      open = { prompt: row.text, texts: [], files: [], tools: 0 }
48      continue
49    }
50    if (open === undefined || row.role !== 'assistant') continue
51    if (row.text.trim() !== '') open.texts.push(row.text)
52    for (const use of row.toolUses) {
53      if (use.agentId !== undefined) continue
54      open.tools += 1
55      const path = use.input.file_path ?? use.input.notebook_path
56      if (typeof path === 'string' && !open.files.includes(path)) open.files.push(path)
57    }
58  }
59  close()
60
61  return turns
62}
63
64/**
65 * The turns the lens already knows, with up to `limit` of the transcript's
66 * earlier ones filled in around them, in transcript order. A known turn keeps
67 * its id, time and files; it is recognised by its answer.
68 */
69export function withBackfill(known: Turn[], rebuilt: Turn[], limit: number): Turn[] {
70  const byAnswer = new Map(known.map(t => [t.answer.trim(), t]))
71  const missing = rebuilt.filter(t => !byAnswer.has(t.answer.trim()))
72  const added = new Set(limit > 0 ? missing.slice(-limit) : [])
73
74  const merged: Turn[] = []
75  for (const t of rebuilt) {
76    const kept = byAnswer.get(t.answer.trim())
77    if (kept !== undefined) {
78      merged.push(kept)
79      byAnswer.delete(t.answer.trim())
80    } else if (added.has(t)) {
81      merged.push(t)
82    }
83  }
84
85  // Known turns the transcript no longer shows were compacted away, so they are
86  // older than anything it holds: they stay, ahead of it.
87  return [...byAnswer.values(), ...merged]
88}
89
hooks/match.ts 23 lines
1import type { Turn } from '../types'
2
3// Drawn text and markdown source differ in punctuation and spacing, so both
4// sides are reduced to lowercase words before matching.
5export const words = (text: string) => text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim()
6
7// A message row carries no turn id, so find the turn whose text
8// holds its opening; the latest wins, as a repeated phrase most likely means it.
9export const turnContaining = (list: Turn[], text: string) => {
10  const probe = words(text).slice(0, 120).trim()
11  if (probe.length < 8) return undefined
12
13  // Turns kept before `replies` existed lack it and match on their answer alone.
14  return list.findLast(t => [...(t.replies ?? []), t.answer].some(r => words(r).includes(probe)))
15}
16
17// True for the block that ends the turn's answer: the one a summary row goes under.
18export const endsAnswer = (turn: Turn, text: string) => {
19  const tail = words(text).slice(-120)
20
21  return tail.length > 0 && words(turn.answer).endsWith(tail)
22}
23
hooks/time.ts 10 lines
1// When the original reply was written, in the person's local time, with the
2// day once it is not today. Absent for turns kept before times were recorded.
3export const timeOf = (at: number | undefined, now: number) => {
4  if (at === undefined) return undefined
5  const d = new Date(at)
6  const time = d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })
7
8  return new Date(now).toDateString() === d.toDateString() ? time : `${d.toLocaleDateString([], { month: 'short', day: 'numeric' })}, ${time}`
9}
10
hooks/digest.ts 105 lines
1import type { Bucket, Digest, Purpose, Turn } from '../types'
2import type { Hue } from './heading'
3
4export const PURPOSES: { id: Purpose; label: string; hotkey: string }[] = [
5  { id: 'all', label: 'all', hotkey: 'a' },
6  { id: 'progress', label: 'in progress', hotkey: '1' },
7  { id: 'needs', label: 'needs you', hotkey: '2' },
8  { id: 'waiting', label: 'waiting on others', hotkey: '3' },
9  { id: 'blocked', label: 'blocked', hotkey: '4' },
10  { id: 'done', label: 'done', hotkey: '5' },
11]
12
13export const BUCKETS: { id: Bucket; label: string; mark: string; hue: Hue; empty: string }[] = [
14  { id: 'progress', label: 'In progress', mark: '◐', hue: 'blue', empty: 'nothing in progress' },
15  { id: 'needs', label: 'Needs you', mark: '✋', hue: 'amber', empty: 'nothing waiting on you' },
16  { id: 'waiting', label: 'Waiting on others', mark: '⏳', hue: 'teal', empty: 'not waiting on anyone' },
17  { id: 'blocked', label: 'Blocked', mark: '⛔', hue: 'red', empty: 'nothing blocked' },
18  { id: 'done', label: 'Done', mark: '✓', hue: 'green', empty: 'nothing finished' },
19]
20
21// Who every digest is written for: someone following along, not doing the work.
22const READER =
23  'someone following the work who wants to know where it stands: what is underway, what needs their input, and what got finished'
24
25// Keeps the head and the tail: an answer's asks of the person usually close it.
26const clip = (text: string, max: number) =>
27  text.length > max ? `${text.slice(0, max * 0.6)}\n…[middle cut]…\n${text.slice(-max * 0.4)}` : text
28
29const SYSTEM =
30  `You sort an AI coding assistant's work for one reader: ${READER}. ` +
31  'Use only facts present in the material; never invent progress, asks or results.'
32
33const FORMAT =
34  'Reply with JSON only, no code fence: ' +
35  '{"headline": string, "progress": string[], "needs": string[], "waiting": string[], "blocked": string[], "done": string[]}\n' +
36  '- headline: at most 15 words, what this means for the reader.\n' +
37  '- progress: work started but not finished, or next steps the assistant said it would take itself.\n' +
38  '- needs: only what the reader personally must do before the work can go on: questions put to them, ' +
39  'choices offered to them, approvals or actions requested of them. A task handed to another session or agent is not this, ' +
40  'even when the reader relays it.\n' +
41  '- waiting: work waiting on anyone other than the reader or the assistant. Each item names who or what, as specifically as ' +
42  'the material allows (the session, agent, branch, PR, CI run, task or person), as "<who>: <what>".\n' +
43  '- blocked: obstacles that are nobody\'s task: rate or usage limits hit, tools or services failing, permissions denied, ' +
44  'missing access, errors the assistant could not get past. Name the obstacle.\n' +
45  '- done: things completed: changes made, checks run, questions answered.\n' +
46  'Put each item in one list only. Each item at most 15 words, written for this reader, most important first; at most 5 per list. ' +
47  'Leave out what this reader would not care about; empty lists are fine.'
48
49export function turnRequest(turn: Turn, context: string[]) {
50  const before = context.length ? `Earlier in the session (oldest first):\n${context.map(c => `- ${c}`).join('\n')}\n\n` : ''
51  const files = turn.files.length ? `Files touched: ${turn.files.join(', ')}\n` : ''
52
53  return {
54    system: SYSTEM,
55    maxTokens: 700,
56    prompt:
57      `${before}The user asked:\n<ask>\n${clip(turn.prompt, 4000)}\n</ask>\n\n` +
58      `${files}Tool calls: ${turn.tools}\n\n` +
59      `The assistant answered:\n<answer>\n${clip(turn.answer, 12000)}\n</answer>\n\n` +
60      `Sort this one turn. "done" is only what this turn completed.\n${FORMAT}`,
61  }
62}
63
64export function overviewRequest(turns: Turn[]) {
65  const lines = turns.map((t, i) => `${i + 1}. Asked: ${clip(t.prompt, 300)}\n   Answered: ${clip(t.answer, 900)}`)
66
67  return {
68    system: SYSTEM,
69    maxTokens: 700,
70    prompt:
71      `The session so far, turn by turn:\n${lines.join('\n')}\n\n` +
72      'Sort where the session stands now. "progress", "needs", "waiting" and "blocked" are what is still open after the latest turn: ' +
73      `drop anything a later turn finished or the user answered. "done" is what was finished across the session.\n${FORMAT}`,
74  }
75}
76
77const strings = (v: unknown) =>
78  Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string' && x.trim() !== '').slice(0, 5) : []
79
80export function parseDigest(text: string): Digest | undefined {
81  const body = text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)
82  try {
83    const raw = JSON.parse(body) as Record<string, unknown>
84    const headline = typeof raw.headline === 'string' ? raw.headline.trim() : ''
85    if (headline === '') return undefined
86
87    return {
88      headline,
89      progress: strings(raw.progress),
90      needs: strings(raw.needs),
91      waiting: strings(raw.waiting),
92      blocked: strings(raw.blocked),
93      done: strings(raw.done),
94    }
95  } catch {
96    return undefined
97  }
98}
99
100export const titleOf = (turn: Turn) => {
101  const line = turn.prompt.split('\n').find(l => l.trim()) ?? '(no prompt)'
102
103  return line.length > 80 ? `${line.slice(0, 79)}…` : line
104}
105
types/index.d.ts 40 lines
1export type Bucket = 'progress' | 'needs' | 'waiting' | 'blocked' | 'done'
2
3export type Purpose = 'all' | Bucket
4
5export type InlineMode = 'off' | 'callout' | 'replace'
6
7export type Turn = {
8  id: string
9  prompt: string
10  answer: string
11  files: string[]
12  tools: number
13  /** Each assistant text block of this turn, to find the turn a transcript message belongs to. */
14  replies: string[]
15  /** When Claude finished the reply, in ms since the epoch; absent on turns kept before it was recorded. */
16  at?: number
17}
18
19/** A turn (or the session) sorted: a headline and what is in progress, needs the person, waits on others, is blocked, or got done. */
20export type Digest = { headline: string } & Record<Bucket, string[]>
21
22/** `since`: when a pending call started, so one lost to a reload can be retried. */
23export type View = { status: 'pending' | 'done' | 'error'; text: string; digest?: Digest; since?: number }
24
25declare module 'claude-code' {
26  interface PluginState {
27    lens: {
28      turns: Turn[]
29      purpose: Purpose
30      focus: string | null
31      views: Record<string, View>
32      isOpen: boolean
33      inline: InlineMode
34      expanded: string[]
35      /** Turns whose inline reply the person asked to see sorted. */
36      lensed: string[]
37    }
38  }
39}
40