SLOPSHOPPER

pager-view

This session's pager name and new mail above the prompt; its pager conversation and peers in a pane

panebandcommandprocesstimer
★ 1v0.1.0no licenseupdated 2026-10-21iMUngHee/dotfiles/claude/mods/pager-view
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · pager-view
│ ┃ pager ✕ › fix the failing auth test and add an audit log call │ ┃ This session has no pager name yet. │ ┃ ⏺ 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 │ │ › /pager │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · pager
This session has no pager name yet.
README

dotfiles

Personal configuration files managed via ~/.config/ and synced with git.

What's tracked

DirectoryToolKey files
ai/Shared (Claude + Codex)PERSONAL.md, guardrails.md, rules/, memory/, skills/, AGENTS.manifest
claude/Claude CodeCLAUDE.md, DEVGUARD.md, settings.json, hooks/, agents/, commands/, skills/ (Claude-only)
codex/Codex CLIconfig.toml.template, skills/ (Codex-only), scripts/
notifier/Shared AI notifiermacOS Swift app, Linux Go daemon, Go sender, shared icon
ghostty/Ghosttyconfig, shaders/ (cursor animation)
aerospace/AeroSpace (macOS)aerospace.toml (shipped default trimmed to digit workspaces so Option stays free for terminal Meta keys; float rules, Omarchy gaps)
brave/Brave Originvimium-options.json (Vimium export; restore by hand from its Options page when Brave Sync has not carried it over)
nvim/Neoviminit.lua, lua/plugins/
tmux/tmuxtmux.conf, scripts/, status/
zsh/Zsh.zshrc, custom/plugins/
homebrew/Homebrew BundleBrewfile, bootstrap.sh (macOS package set + shell env)
arch/Arch Linux / Omarchypackages.sh (pacman + AUR, the Brewfile mapping), bootstrap.sh (packages + mise + shell env)
lib/Shared bootstrapshell-env.sh (~/.zshenv ZDOTDIR + oh-my-zsh, used by both Unix package layers)
windows/Native Windowsbootstrap.ps1, packages.ps1 (winget), profile.ps1, starship.toml, terminal/, notifier/, Cowork skill packaging
.ideavimrcIdeaVim (JetBrains)Standalone file

AI assistant 3-tier layout

ai/ is the single source of truth for tool-agnostic content (rules, memory, most skills). claude/ and codex/ hold per-tool deploy logic and tool-only files. notifier/ is shared runtime infrastructure for Claude/Codex desktop notifications. The orchestrator at ai/scripts/bootstrap.sh calls each tool's bootstrap. See ai/README.md, claude/README.md, codex/README.md.

Everything else under ~/.config/ is gitignored. See .gitignore for the allowlist.

Machine-local settings

Anything true of one machine and not another stays out of the tracked files. Each config loads an optional private file last, so it overrides without being edited into the shared one:

ConfigHook in the tracked fileMachine-local file
zshsource $ZDOTDIR/private.shzsh/private.sh
ghosttyconfig-file = ?"…/private.conf"ghostty/private.conf
tmuxif-shell '[ -r … ]' 'source-file …'tmux/private.conf
nvimplugins/99_private.lua → require("private.plugins")nvim/lua/private/plugins.lua

All four are absent by default and silent when missing, so a fresh clone works with none of them. On Omarchy they are where the theme wiring lives, which is why macOS keeps Catppuccin while that machine follows the system theme.

One case the seam cannot cover: Omarchy's display text size slider rewrites font-size in ghostty/config at a path it hardcodes, so moving the line out would make the slider silently do nothing. That one line is normalized on its way into the index by the clean filter in lib/git-filter-machine-local.sh (wired in .gitattributes, registered by ai/scripts/bootstrap.sh) — the working tree keeps this monitor's size and git never sees it. When git rewrites the file (a pull that changes it, a reset, git stash), the smudge side of the same filter puts the size back from the slider's record in ~/.config/omarchy/shell.toml, using the px-to-pt formula it reads out of the installed omarchy-display-text-size. If that formula ever changes, the smudge leaves the stored 16 in place and says so, and ai/lib/git-filter-machine-local.test.mjs fails until the filter is updated. The smudge is registered by bootstrap, which the post-merge hook runs after a pull, so the pull that first brings it in still checks files out with the old cat. That only matters if the same pull also changes ghostty/config; then move the slider once. The same filter drops a # >>> machine-local … # <<< machine-local block whole; aerospace/aerospace.toml keeps its work-machine float rules there, since AeroSpace has no include to put them in a private file.

Bootstrap registers the filter as required, with a smudge beside it: required covers checkouts too, and with no smudge to run every checkout of a filtered file aborts with smudge filter machine-local failed. A machine that ran bootstrap after c240add but before 942bb12 has required without the smudge, so the pull that brings the fix can stop there. Run git -C ~/.config config filter.machine-local.smudge cat once, then pull again.

Submodules

PathRepo
zsh/custom/plugins/zsh-autosuggestionszsh-users/zsh-autosuggestions
zsh/custom/plugins/zsh-history-substring-searchzsh-users/zsh-history-substring-search
zsh/custom/plugins/zsh-syntax-highlightingzsh-users/zsh-syntax-highlighting
zsh/custom/plugins/fzf-tabaloxaf/fzf-tab
ghostty/shaderssahaj-b/ghostty-cursor-shaders

Setup

macOS / Linux

git clone --recurse-submodules <repo> ~/.config
~/.config/bootstrap.sh   # packages + shell env, then deploys Claude + Codex config

bootstrap.sh picks the package layer from the machine, then hands off to the same ai/scripts/bootstrap.sh in every case:

MachinePackage layerSource of claude / codex
macOShomebrew/bootstrap.sh → brew bundleHomebrew casks
Arch / Omarchyarch/bootstrap.sh → pacman + AURmise (~/.config/mise/config.toml, machine-local)
Linux with Homebrew, no pacmanhomebrew/bootstrap.shHomebrew

On Omarchy the package step uses omarchy-pkg-add / omarchy-pkg-aur-add when they exist, so packages installed here look the same as ones added through the Omarchy menu. arch/packages.sh --dry-run prints the plan without installing; --skip-optional leaves out desktop apps and AUR.

~/.config is usually not empty on a fresh Omarchy install — ghostty/, nvim/ and tmux/ already exist. The tracked versions here replace them; move the originals aside first if you want them back.

Windows

winget install --id Git.Git --exact
git clone --recurse-submodules <repo> $HOME\.config
pwsh -File $HOME\.config\windows\bootstrap.ps1   # winget packages + shell/terminal, then the SAME ai/scripts/bootstrap.sh under Git Bash

Requires Developer Mode (Settings > System > For developers) so the deploy can create symlinks unelevated. windows/bootstrap.ps1 replaces bootstrap.sh only at the package layer — the Claude/Codex deploy is delegated to ai/scripts/bootstrap.sh verbatim, so there is one implementation of the 3-tier merge, not two. See windows/README.md.

For per-tool details: ai/, claude/, codex/, windows/.

Source 3 files
hooks/register.tsx 758 lines
1// pager-view: this session's pager name and its new mail as one line above the
2// prompt, and a /pager pane: the session's chats, and each chat a room of
3// bubbles. Read-only: it lists and exports; it never sends, marks or delivers.
4//
5// I/O happens in events, handlers and timers only; ui.render reads $.state and nothing else.
6
7import { atom, read, update } from 'claude-code'
8import type { EngineInterface as Engine, On, RenderElement, RenderInput } from 'claude-code'
9
10import type { Entry, PagerState } from '../types'
11import {
12  agoOf,
13  clockOf,
14  conversationOf,
15  dayOf,
16  exportedOf,
17  flatOf,
18  foldOf,
19  inboundOf,
20  isMissing,
21  liveOf,
22  nameOf,
23  newCountOf,
24  newestInOf,
25  newestOf,
26  peersOf,
27  roomsOf,
28  rosterOf,
29  seenOf,
30  unreadOf,
31} from './pager'
32import type { Room, Run } from './pager'
33
34export const PANE = 'pager'
35const POLL_MS = 5_000
36const REFRESH_DEBOUNCE_MS = 300
37// How often the session id is compared, well inside POLL_MS; see watchSession.
38const SESSION_WATCH_MS = 1_000
39const SHOWN_ENTRIES = 200
40/** The newest messages a room draws: the engine refuses a drawing over 100,000 characters. */
41const ROOM_MESSAGES = 60
42/**
43 * The body text a room's bubbles may draw together, leaving the rest of the
44 * 100,000 to the chrome: unfolded bubbles cost their whole bodies, and past it
45 * the oldest give way so the newest and the controls under them stay drawn.
46 */
47const ROOM_TEXT = 80_000
48/** The share of the content width a bubble may take; the rest stays empty on the far side. */
49const BUBBLE_SHARE = 0.8
50
51const EMPTY: PagerState = {
52  sessionId: '',
53  name: null,
54  entries: [],
55  peers: [],
56  newCount: 0,
57  live: 0,
58  lastAgo: null,
59  now: 0,
60  error: null,
61  unread: {},
62}
63
64const pager = atom({ plugin: 'pager-view', key: 'pager' } as const, EMPTY)
65const room = atom({ plugin: 'pager-view', key: 'room' } as const, null)
66const cursor = atom({ plugin: 'pager-view', key: 'cursor' } as const, null)
67const expanded = atom({ plugin: 'pager-view', key: 'expanded' } as const, [])
68
69const baselineKey = (sessionId: string) => `baseline:${sessionId}`
70const seenKey = (sessionId: string) => `seen:${sessionId}`
71
72async function run($: Engine, argv: string[]): Promise<Run> {
73  try {
74    return await $.process.run(argv, { timeoutMs: 10_000 })
75  } catch (error) {
76    return { exitCode: -1, stdout: '', stderr: error instanceof Error ? error.message : String(error) }
77  }
78}
79
80// Module state: a reload starts it over, as it does $.clock timers. `generation`
81// moves when the session id changes under the process (/clear, /resume, /branch);
82// a refresh begun under an older one is dropped. The baseline and the per-room
83// seen map live in $.store, keyed by session id, so a reload keeps them and a new
84// session starts its own.
85//
86// These are module-level, which assumes one hooks-module instance per session.
87// That is what the engine documents -- a folder is loaded "for that session
88// only" and $.session.id() takes no argument -- but it is nowhere stated
89// outright, so it is written down here as the assumption it is. Were one
90// process to share an instance across sessions, `pending?.cancel()` in soon()
91// would drop another session's scheduled refresh, `generation` would void its
92// running one, `isRefreshing` would serialise their I/O, and `sessionSeen`
93// would see the id flip on every watch and wipe each view in turn; the fix
94// then is to key all five by session id.
95//
96// Baselines are never pruned: one `baseline:<uuid>` per session, forever, in a
97// $.store capped at 4 MiB of JSON. At ~55 bytes an entry that is tens of
98// thousands of sessions away, and $.store.keys()/delete are there if it ever
99// matters -- but it is accumulation, not a leak that stops.
100let generation = 0
101let isRefreshing = false
102let isDirty = false
103let pending: { cancel: () => void } | null = null
104// The id watchSession last saw.
105let sessionSeen = ''
106
107async function isPaneOpen($: Engine): Promise<boolean> {
108  return (await $.ui.panes()).some(one => one.id === PANE)
109}
110
111/**
112 * Moves the baseline to `newest` when that is later. Answers the baseline in
113 * force (`next`) and the one before this refresh (`prior`), from which a room
114 * met for the first time starts counting.
115 */
116async function baselineAt(
117  $: Engine,
118  sessionId: string,
119  newest: number,
120  isSeen: boolean,
121): Promise<{ prior: number; next: number }> {
122  const stored = await $.store.get(baselineKey(sessionId))
123  const current = typeof stored === 'number' ? stored : null
124  // No baseline yet: what arrived before this session's first look is not new.
125  const next = current === null || (isSeen && newest > current) ? newest : current
126  if (next !== current) await $.store.set(baselineKey(sessionId), next)
127  return { prior: current ?? newest, next }
128}
129
130function isSeenMap(value: unknown): value is Record<string, number> {
131  return (
132    typeof value === 'object' &&
133    value !== null &&
134    !Array.isArray(value) &&
135    Object.values(value).every(mark => typeof mark === 'number')
136  )
137}
138
139async function storedSeen($: Engine, sessionId: string): Promise<Record<string, number>> {
140  const stored = await $.store.get(seenKey(sessionId))
141  return isSeenMap(stored) ? stored : {}
142}
143
144async function refreshOnce($: Engine): Promise<void> {
145  const started = generation
146  const sessionId = await $.session.id()
147  const isStale = async () => started !== generation || sessionId !== (await $.session.id())
148  const settle = async (next: (prev: PagerState) => PagerState) => {
149    if (await isStale()) return
150    await update($, pager, next)
151  }
152  const failed = (error: string) =>
153    settle(prev => (prev.sessionId === sessionId ? { ...prev, error } : { ...EMPTY, sessionId, error }))
154
155  const whoami = await run($, ['pager', 'whoami', '--session', sessionId])
156  if (isMissing(whoami)) return settle(() => ({ ...EMPTY, sessionId }))
157  const name = nameOf(whoami)
158  if (name !== null && typeof name === 'object') return failed(name.error)
159  if (name === null) return settle(() => ({ ...EMPTY, sessionId }))
160
161  const inbound = inboundOf(await run($, ['pager', 'ls', '--session', sessionId]))
162  if ('error' in inbound) return failed(inbound.error)
163  // `pager export` dumps the whole database and takes no arguments -- it says
164  // so itself, pointing at jq -- so this grows with the message count rather
165  // than with this session's share of it. Measured at ~1.9 KB a message
166  // against $.process.run's 4 MiB stdout cap, which is a ceiling somewhere
167  // near 2,200 messages. Past it `failureOf` answers 'output truncated' every
168  // refresh and the band holds its last good line with a dim `?`, for good:
169  // the database only grows back. The pane spells the reason out (`⚠ pager:
170  // output truncated`), which is the only warning there is. A real fix needs
171  // a filter on `pager export`, not a change here.
172  const rows = exportedOf(await run($, ['pager', 'export']))
173  if ('error' in rows) return failed(rows.error)
174  const isSeen = await isPaneOpen($)
175  // A room on screen reads its mail as it lands.
176  const shownRoom = isSeen ? await read($, room) : null
177  // The band counts live peers too, so `who` runs on every refresh (~13 ms measured).
178  const who = peersOf(await run($, ['pager', 'who']))
179  if ('error' in who) return failed(who.error)
180  const now = await $.clock.now()
181  // Windows: HOME is only set by a shell profile; the desktop app has USERPROFILE alone.
182  const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE')) ?? ''
183  if (await isStale()) return
184
185  const { prior, next: baseline } = await baselineAt($, sessionId, newestOf(inbound), isSeen)
186  const entries = conversationOf(rows, inbound, sessionId).slice(-SHOWN_ENTRIES)
187  const before = await storedSeen($, sessionId)
188  const seen = seenOf(before, entries, prior, shownRoom)
189  if (JSON.stringify(seen) !== JSON.stringify(before)) await $.store.set(seenKey(sessionId), seen)
190  const last = entries.at(-1)
191  await settle(() => ({
192    sessionId,
193    name,
194    entries,
195    peers: rosterOf(who, home),
196    newCount: newCountOf(inbound, baseline),
197    live: liveOf(who, name),
198    lastAgo: last ? agoOf(last.at, now) : null,
199    now,
200    error: null,
201    unread: unreadOf(entries, seen),
202  }))
203}
204
205async function refresh($: Engine): Promise<void> {
206  if (isRefreshing) {
207    isDirty = true
208    return
209  }
210  isRefreshing = true
211  try {
212    do {
213      isDirty = false
214      await refreshOnce($)
215    } while (isDirty)
216  } finally {
217    isRefreshing = false
218  }
219}
220
221function soon($: Engine): void {
222  pending?.cancel()
223  pending = $.clock.after(REFRESH_DEBOUNCE_MS, () => {
224    pending = null
225    void refresh($)
226  })
227}
228
229/** /pager and a click on the band's name: open the pane on the chats, and count the look as seen. */
230async function openPane($: Engine): Promise<void> {
231  // A pane opened anew starts on the chats; one already up stays in its room.
232  if (!(await isPaneOpen($))) await update($, room, () => null)
233  await $.ui.open({ id: PANE, title: 'pager', focus: true })
234  // Clear the badge now; the next refresh moves the stored baseline (the pane is open).
235  const state = await read($, pager)
236  const sessionId = await $.session.id()
237  if (state.sessionId === sessionId && state.newCount > 0) {
238    await update($, pager, prev => ({ ...prev, newCount: 0 }))
239  }
240  soon($)
241}
242
243/** Moves the pane's window; a move the surface refuses changes nothing worth telling. */
244async function scrollTo($: Engine, to: 'start' | 'end'): Promise<void> {
245  await $.ui.scroll({ in: PANE, to }).catch((error: unknown) => ({ deny: String(error) }))
246}
247
248/** A press on a chat (or `o` on the cursor's): show its room at the newest bubble, and read it. */
249async function openRoom($: Engine, name: string): Promise<void> {
250  await update($, room, () => name)
251  await update($, cursor, () => name)
252  const state = await read($, pager)
253  const sessionId = await $.session.id()
254  if (state.sessionId === sessionId) {
255    const newest = newestInOf(state.entries, name)
256    const seen = await storedSeen($, sessionId)
257    if (newest > (seen[name] ?? 0)) await $.store.set(seenKey(sessionId), { ...seen, [name]: newest })
258    if ((state.unread[name] ?? 0) > 0) {
259      const rest = (unread: Record<string, number>) =>
260        Object.fromEntries(Object.entries(unread).filter(([peer]) => peer !== name))
261      await update($, pager, prev => ({ ...prev, unread: rest(prev.unread) }))
262    }
263  }
264  await scrollTo($, 'end')
265}
266
267/** `b` and `‹ chats`: back to the chat list. */
268async function leaveRoom($: Engine): Promise<void> {
269  await update($, room, () => null)
270  await scrollTo($, 'start')
271}
272
273/** `j` and `k`: the cursor bar onto the chat at `at`, held inside the list. */
274async function moveCursor($: Engine, names: readonly string[], at: number): Promise<void> {
275  const name = names[Math.max(0, Math.min(names.length - 1, at))]
276  if (name !== undefined) await update($, cursor, () => name)
277}
278
279/** A bubble's fold control: unfold it past the fold, or fold it back. */
280async function toggleFold($: Engine, id: number): Promise<void> {
281  await update($, expanded, prev => (prev.includes(id) ? prev.filter(one => one !== id) : [...prev, id]))
282}
283
284/** `e`: unfold every folded bubble of the room; when none is folded, fold them all again. */
285async function toggleFolds($: Engine, ids: readonly number[]): Promise<void> {
286  await update($, expanded, prev =>
287    ids.every(id => prev.includes(id)) ? prev.filter(id => !ids.includes(id)) : [...new Set([...prev, ...ids])],
288  )
289}
290
291async function switched($: Engine): Promise<void> {
292  generation += 1
293  await update($, pager, () => EMPTY)
294  await update($, room, () => null)
295  await update($, cursor, () => null)
296  await update($, expanded, () => [])
297}
298
299// /clear, /resume and /branch change the id under the process. classic.SessionStart
300// said so for all three, but on a machine with managed settings (and in Team and
301// Enterprise organizations) the built-in cc-plugin-sec-default runs outermost and
302// sends every classic.* event past the plugins a person installs
303// (next.to(e, "append")): a classic hook here never runs, and the engine reports
304// it as skipped. session.end still fires for /clear and resume, but before the id
305// changes and never for /branch. So the id is compared on a timer.
306async function watchSession($: Engine): Promise<void> {
307  const sessionId = await $.session.id()
308  if (sessionId === sessionSeen) return
309  sessionSeen = sessionId
310  await switched($)
311  soon($)
312}
313
314export function register(on: On): void {
315  on('session.start', async ($, e, next) => {
316    await $.command.register({
317      name: PANE,
318      description: "Show this session's pager chats",
319      immediate: true,
320    })
321    const result = await next(e)
322    sessionSeen = await $.session.id()
323    $.clock.every(POLL_MS, () => void refresh($))
324    $.clock.every(SESSION_WATCH_MS, () => void watchSession($))
325    soon($)
326    return result
327  })
328
329  // If it fails, .catch hands back what next settled to (or runs it once when it
330  // had not run), so a failure never blocks or repeats work.
331  on('command.run', { command: PANE }, async $ => {
332    await openPane($)
333    return {}
334  }).catch(($, e, next) => next(e))
335
336  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
337    if (e.props.hasSurvey) return next(e)
338    const state = await read($, pager)
339    const below = await next(e)
340    const line = bandLine($, e, state)
341    if (line === null) return below
342    const { Box } = $.ui.resolve(e)
343    return (
344      <Box flexDirection="column">
345        {line}
346        {below}
347      </Box>
348    )
349  })
350
351  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
352    const state = await read($, pager)
353    const shown = await read($, room)
354    const at = await read($, cursor)
355    const open = await read($, expanded)
356    return paneOf($, e, { state, shown, at, open })
357  })
358}
359
360const PREVIEW_CHARS = 60
361
362const previewOf = (body: string) => {
363  const flat = flatOf(body)
364  return flat.length > PREVIEW_CHARS ? `${flat.slice(0, PREVIEW_CHARS - 1)}…` : flat
365}
366
367/** A root cut from its start: the end is the folder that tells two sessions apart. */
368const startCut = (text: string, cells: number) =>
369  text.length > cells ? `…${text.slice(text.length - Math.max(1, cells - 1))}` : text
370
371/** The band line: the way into /pager, new mail, the last message; live peers at the right edge. */
372function bandLine($: Engine, e: RenderInput<'AbovePrompt'>, state: PagerState): RenderElement | null {
373  if (state.name === null) return null
374  const { Box, Text, Button } = $.ui.resolve(e)
375  const last = state.entries.at(-1)
376  return (
377    <Box flexDirection="row">
378      <Box flexDirection="row" flexShrink={1}>
379        {/* The name is the way into /pager: a click (or ctrl+x tab, Enter) opens it. */}
380        <Button key="open-pager" label={`✉ ${state.name}`} plain onPress={() => openPane($)} />
381        <Text wrap="truncate-end">
382          {state.newCount > 0 ? (
383            <Text>
384              {'  '}
385              <Text backgroundColor="warning" color="inverseText" bold>{` ${state.newCount} new `}</Text>
386            </Text>
387          ) : (
388            ''
389          )}
390          {last ? (
391            <Text>
392              {'  '}
393              <Text bold color={last.direction === 'out' ? 'claude' : undefined}>
394                {last.direction === 'in' ? '←' : '→'} {last.peer}
395              </Text>
396              <Text dimColor>
397                {state.lastAgo !== null ? ` ${state.lastAgo}` : ''}
398                {'  '}
399                {previewOf(last.body)}
400              </Text>
401            </Text>
402          ) : (
403            ''
404          )}
405          {state.error !== null ? <Text dimColor> ?</Text> : ''}
406        </Text>
407      </Box>
408      <Box flexGrow={1} />
409      {state.live > 0 ? (
410        <Box flexShrink={0} marginLeft={2}>
411          <Text>
412            <Text color="success">●</Text>
413            <Text dimColor> {state.live} live</Text>
414          </Text>
415        </Box>
416      ) : (
417        ''
418      )}
419    </Box>
420  )
421}
422
423type View = { state: PagerState; shown: string | null; at: string | null; open: number[] }
424
425function paneOf($: Engine, e: RenderInput<'Pane'>, view: View): RenderElement {
426  const { Box, Text } = $.ui.resolve(e)
427  const { state } = view
428  // The pane frame is the engine's; the content keeps a column clear on each side.
429  const width = Math.max(20, e.props.bodyColumns - 2)
430  const status = state.error !== null ? <Text dimColor wrap="truncate-end">⚠ pager: {state.error}</Text> : ''
431  if (state.name === null) {
432    return (
433      <Box flexDirection="column" paddingX={1}>
434        <Text dimColor>This session has no pager name yet.</Text>
435        {status}
436      </Box>
437    )
438  }
439  return (
440    <Box flexDirection="column" paddingX={1}>
441      {view.shown === null ? chatsBody($, e, view, state.name, width) : roomBody($, e, view, view.shown, width)}
442      {status}
443    </Box>
444  )
445}
446
447/** The chats: this session's name over one two-line row per room, the cursor's marked. */
448function chatsBody($: Engine, e: RenderInput<'Pane'>, view: View, self: string, width: number): RenderElement {
449  const { Box, Text, Button } = $.ui.resolve(e)
450  const { state } = view
451  const rooms = roomsOf(state.entries, state.peers, self)
452  const total = Object.values(state.unread).reduce((sum, count) => sum + count, 0)
453  const header = (
454    <Text wrap="truncate-end">
455      <Text backgroundColor="claude" color="inverseText" bold>{` ${self} `}</Text>
456      {state.live > 0 ? (
457        <Text>
458          {'  '}
459          <Text color="success">●</Text>
460          <Text dimColor> {state.live} live</Text>
461        </Text>
462      ) : (
463        ''
464      )}
465      {total > 0 ? <Text color="warning">{` · ${total} unread`}</Text> : ''}
466    </Text>
467  )
468  if (rooms.length === 0) {
469    return (
470      <Box flexDirection="column">
471        {header}
472        <Text> </Text>
473        <Text dimColor>No messages to or from {self} yet.</Text>
474      </Box>
475    )
476  }
477  const names = rooms.map(one => one.name)
478  const at = Math.max(0, view.at === null ? 0 : names.indexOf(view.at))
479  const isTerminal = e.surface === 'terminal'
480  return (
481    <Box flexDirection="column">
482      {header}
483      <Text> </Text>
484      {rooms.map((one, index) => {
485        const row = chatRow($, e, state, one, index === at, width)
486        // The peers without messages follow the conversations under their own label.
487        const isFirstQuiet = one.last === null && index > 0 && rooms[index - 1]!.last !== null
488        return isFirstQuiet ? (
489          <Box flexDirection="column" marginTop={1}>
490            <Text dimColor bold>
491              PEERS
492            </Text>
493            {row}
494          </Box>
495        ) : (
496          row
497        )
498      })}
499      <Text> </Text>
500      {isTerminal ? (
501        <Box flexDirection="row" columnGap={2}>
502          <Button key="down" label="down" hotkey="j" plain onPress={() => moveCursor($, names, at + 1)} />
503          <Button key="up" label="up" hotkey="k" plain onPress={() => moveCursor($, names, at - 1)} />
504          <Button key="open" label="open" hotkey="o" plain onPress={() => openRoom($, names[at]!)} />
505          <Text dimColor wrap="truncate-end">
506            · click a name
507          </Text>
508        </Box>
509      ) : (
510        <Text dimColor>click a name to open its chat</Text>
511      )}
512    </Box>
513  )
514}
515
516/** One chat: presence, name and tool, the age and unread pinned right; the preview under them. */
517function chatRow(
518  $: Engine,
519  e: RenderInput<'Pane'>,
520  state: PagerState,
521  one: Room,
522  isCursor: boolean,
523  width: number,
524): RenderElement {
525  const { Box, Text, Button } = $.ui.resolve(e)
526  const isLive = one.peer?.host === 'live'
527  const unread = state.unread[one.name] ?? 0
528  const age = one.last ? agoOf(one.last.at, state.now) : null
529  const bar = (
530    <Box width={2} flexShrink={0}>
531      <Text color="claude">{isCursor ? '▌' : ' '}</Text>
532    </Box>
533  )
534  const preview = one.last ? (
535    <Text dimColor wrap="truncate-end">
536      {one.last.direction === 'out' ? 'you: ' : ''}
537      {one.last.isHuman ? <Text color="suggestion">(human) </Text> : ''}
538      {previewOf(one.last.body)}
539    </Text>
540  ) : (
541    <Text dimColor wrap="truncate-end">
542      no messages yet{one.peer ? ` · ${startCut(one.peer.root, Math.max(8, width - 22))}` : ''}
543    </Text>
544  )
545  return (
546    <Box flexDirection="column">
547      <Box flexDirection="row">
548        {bar}
549        <Box width={2} flexShrink={0}>
550          <Text color={isLive ? 'success' : undefined} dimColor={!isLive}>
551            {isLive ? '●' : '○'}
552          </Text>
553        </Box>
554        <Box flexShrink={1}>
555          <Button
556            key={`chat-${one.name}`}
557            label={one.name}
558            plain
559            dimColor={!isLive && one.last === null}
560            onPress={() => openRoom($, one.name)}
561          />
562        </Box>
563        {one.peer ? (
564          <Box flexShrink={1} marginLeft={1}>
565            <Text dimColor wrap="truncate-end">
566              {one.peer.tool}
567            </Text>
568          </Box>
569        ) : (
570          ''
571        )}
572        <Box flexGrow={1} />
573        {age !== null ? (
574          <Box flexShrink={0} marginLeft={1}>
575            <Text dimColor>{age}</Text>
576          </Box>
577        ) : (
578          ''
579        )}
580        {unread > 0 ? (
581          <Box flexShrink={0} marginLeft={1}>
582            <Text backgroundColor="warning" color="inverseText" bold>{` ${unread} `}</Text>
583          </Box>
584        ) : (
585          ''
586        )}
587      </Box>
588      <Box flexDirection="row">
589        {bar}
590        <Box flexShrink={1} paddingLeft={2}>
591          {preview}
592        </Box>
593      </Box>
594    </Box>
595  )
596}
597
598/** A room: who it is with, then the conversation as bubbles, the newest at the bottom. */
599function roomBody($: Engine, e: RenderInput<'Pane'>, view: View, name: string, width: number): RenderElement {
600  const { Box, Text, Button } = $.ui.resolve(e)
601  const { state } = view
602  const peer = state.peers.find(one => one.name === name) ?? null
603  const isLive = peer?.host === 'live'
604  const all = state.entries.filter(entry => entry.peer === name)
605  const recent = all.slice(-ROOM_MESSAGES)
606  const isTerminal = e.surface === 'terminal'
607  // The text a full-width bubble wraps at: its share, less the border and padding.
608  const inner = Math.max(8, Math.floor(width * BUBBLE_SHARE) - 4)
609  // Newest first while the text budget lasts; the newest is always drawn.
610  const shown: Entry[] = []
611  let left = ROOM_TEXT
612  for (let at = recent.length - 1; at >= 0; at--) {
613    const entry = recent[at]!
614    const cost = drawnOf(entry, view.open.includes(entry.id), inner).text.length
615    if (shown.length > 0 && cost > left) break
616    left -= cost
617    shown.unshift(entry)
618  }
619  const items: RenderElement[] = []
620  if (all.length > shown.length) {
621    items.push(
622      <Box justifyContent="center">
623        <Text dimColor>{`${all.length - shown.length} earlier messages not shown`}</Text>
624      </Box>,
625    )
626  }
627  let day = ''
628  for (const entry of shown) {
629    const today = dayOf(entry.at)
630    if (today !== day) {
631      items.push(
632        <Box justifyContent="center">
633          <Text dimColor>{`── ${today} ──`}</Text>
634        </Box>,
635      )
636      day = today
637    }
638    items.push(bubbleOf($, e, entry, view.open.includes(entry.id), inner))
639  }
640  // The bubbles past the fold, which `e` unfolds together (Tab reaches `‹ chats` first).
641  // Over every recent one, not just those the budget let in: folding them all must
642  // leave none unfolded out of sight.
643  const foldable = recent.filter(entry => drawnOf(entry, false, inner).hidden > 0).map(entry => entry.id)
644  const isAllOpen = foldable.every(id => view.open.includes(id))
645  return (
646    <Box flexDirection="column">
647      <Box flexDirection="row">
648        <Box flexShrink={0}>
649          <Button key="back" label="‹ chats" hotkey="b" plain onPress={() => leaveRoom($)} />
650        </Box>
651        <Box flexShrink={1} marginLeft={2}>
652          <Text wrap="truncate-end">
653            <Text bold>{name}</Text>
654            {'  '}
655            <Text color={isLive ? 'success' : undefined} dimColor={!isLive}>
656              {isLive ? '● live' : '○ gone'}
657            </Text>
658            {peer ? (
659              <Text dimColor>{` · ${peer.tool} · ${startCut(peer.root, Math.max(8, width - 26 - name.length - peer.tool.length))}`}</Text>
660            ) : (
661              ''
662            )}
663          </Text>
664        </Box>
665      </Box>
666      <Text color="subtle" wrap="truncate-end">
667        {'─'.repeat(width)}
668      </Text>
669      {shown.length === 0 ? <Text dimColor>No messages with {name} yet.</Text> : items}
670      <Text> </Text>
671      <Box flexDirection="row" columnGap={2}>
672        {foldable.length > 0 ? (
673          <Button
674            key="fold-all"
675            label={isAllOpen ? 'fold all' : 'unfold all'}
676            hotkey="e"
677            plain
678            onPress={() => toggleFolds($, foldable)}
679          />
680        ) : (
681          ''
682        )}
683        <Text dimColor wrap="truncate-end">
684          {isTerminal ? '↑↓ scroll' : 'click ▾ to unfold a message'}
685        </Text>
686      </Box>
687    </Box>
688  )
689}
690
691/**
692 * One message as a bubble hugging its side: received on the left in `subtle`,
693 * sent on the right in the accent, a fifth of the width left empty opposite.
694 */
695/** What a bubble's body draws: folded past FOLD_LINES unless it is open. */
696function drawnOf(entry: Entry, isOpen: boolean, inner: number): { text: string; hidden: number; isFolded: boolean } {
697  const body = entry.body.replace(/\s+$/, '')
698  const fold = foldOf(body, inner)
699  const isFolded = fold.hidden > 0 && !isOpen
700  return { text: isFolded ? fold.text : body, hidden: fold.hidden, isFolded }
701}
702
703function bubbleOf($: Engine, e: RenderInput<'Pane'>, entry: Entry, isOpen: boolean, inner: number): RenderElement {
704  const { Box, Text, Button } = $.ui.resolve(e)
705  const isOut = entry.direction === 'out'
706  const { text, hidden, isFolded } = drawnOf(entry, isOpen, inner)
707  const left = entry.length - entry.body.length
708  const spacer = <Box width={`${Math.round((1 - BUBBLE_SHARE) * 100)}%`} flexShrink={0} />
709  const card = (
710    <Box
711      flexDirection="column"
712      flexShrink={1}
713      borderStyle="round"
714      borderColor={isOut ? 'claude' : 'subtle'}
715      paddingX={1}
716    >
717      {text.split('\n').map(line => (
718        <Text wrap="wrap">{line === '' ? ' ' : line}</Text>
719      ))}
720      {!isFolded && left > 0 ? (
721        <Text dimColor wrap="wrap">
722          … {left.toLocaleString('en-US')} more characters · full text: pager export (#{entry.id})
723        </Text>
724      ) : (
725        ''
726      )}
727      {/* Justified rather than parted by a growing Box: a grower widens the bubble to its
728          most, where justifying leaves it as wide as its longest line. */}
729      <Box flexDirection="row" justifyContent={hidden > 0 ? 'space-between' : 'flex-end'}>
730        {hidden > 0 ? (
731          <Button
732            key={`fold-${entry.id}`}
733            label={isFolded ? `▾ ${hidden} more lines` : '▴ fold'}
734            plain
735            dimColor
736            onPress={() => toggleFold($, entry.id)}
737          />
738        ) : (
739          ''
740        )}
741        <Box flexShrink={0} marginLeft={2}>
742          <Text>
743            {entry.isHuman ? <Text color="suggestion">(human) </Text> : ''}
744            <Text dimColor>{clockOf(entry.at)}</Text>
745          </Text>
746        </Box>
747      </Box>
748    </Box>
749  )
750  return (
751    <Box key={`bubble-${entry.id}`} flexDirection="row" justifyContent={isOut ? 'flex-end' : 'flex-start'}>
752      {isOut ? spacer : ''}
753      {card}
754      {isOut ? '' : spacer}
755    </Box>
756  )
757}
758
hooks/pager.ts 362 lines
1// Pure readers for pager-view: what the pager CLI prints, turned into this
2// session's name, its conversation and its peers. register.tsx does the I/O.
3
4import type { Entry, Peer } from '../types'
5
6export type { Entry, Peer }
7
8/** What one `$.process.run` answered, the fields these readers look at. */
9export type Run = {
10  exitCode: number
11  stdout: string
12  stderr: string
13  isStdoutTruncated?: boolean
14}
15
16export type Failure = { error: string }
17
18/** The run's failure, if it failed: a non-zero exit or output cut short. */
19export function failureOf(run: Run): string | undefined {
20  if (run.isStdoutTruncated) return 'output truncated'
21  if (run.exitCode !== 0) {
22    return run.stderr.trim().split('\n').at(-1) || `exit ${run.exitCode}`
23  }
24  return undefined
25}
26
27/** A run that never started because `pager` is not installed. */
28export function isMissing(run: Run): boolean {
29  return run.exitCode === -1 && /ENOENT|not found|No such file/i.test(run.stderr)
30}
31
32/**
33 * `pager whoami --session <id>`: the `name:` line, or null when it has none.
34 *
35 * Only the first whitespace-separated field is the name, and `none` is not a
36 * name. An unnamed session makes whoami print a sentence, not a blank —
37 * `name:    none — it is assigned once a hook runs with the host detected` —
38 * so taking the rest of the line draws that whole sentence where the name goes
39 * and never reaches the `null` branch the band and pane check for. Both guards
40 * were in the statusline this mod replaced; they are the same two.
41 */
42export function nameOf(run: Run): string | null | Failure {
43  const failure = failureOf(run)
44  if (failure) return { error: failure }
45  const line = run.stdout.split('\n').find(one => /^name:/.test(one))
46  const name = line?.replace(/^name:\s*/, '').trim().split(/\s+/)[0]
47  if (!name || name === 'none') return null
48  return name
49}
50
51/**
52 * `pager ls --session <id>`: the ids of the messages addressed to this session,
53 * under any of its names. Only the ID column (`#<n>`) is read.
54 */
55export function inboundOf(run: Run): Set<number> | Failure {
56  const failure = failureOf(run)
57  if (failure) return { error: failure }
58  const lines = run.stdout.split('\n').filter(line => line.trim() !== '')
59  if (lines.length === 0 || (lines.length === 1 && lines[0]!.trim() === 'nothing here')) {
60    return new Set()
61  }
62  if (!/^ID\s+INBOX\b/.test(lines[0]!)) return { error: 'unexpected ls output' }
63  const ids = new Set<number>()
64  for (const line of lines.slice(1)) {
65    const m = /^#(\d+)\s/.exec(line)
66    if (m) ids.add(Number(m[1]))
67  }
68  return ids
69}
70
71type Exported = {
72  v?: number
73  id?: number
74  created_at?: string
75  alias?: string
76  sender_session?: string | null
77  sender_label?: string | null
78  origin?: string
79  body?: string
80}
81
82/** `pager export` JSONL, the rows of version 1. */
83export function exportedOf(run: Run): Exported[] | Failure {
84  const failure = failureOf(run)
85  if (failure) return { error: failure }
86  const rows: Exported[] = []
87  for (const line of run.stdout.split('\n')) {
88    if (line.trim() === '') continue
89    try {
90      const row = JSON.parse(line) as Exported
91      if (row.v === 1 && typeof row.id === 'number') rows.push(row)
92    } catch {
93      return { error: 'unreadable export line' }
94    }
95  }
96  return rows
97}
98
99/** The most of a body kept and drawn; the rest is named, with the way to read it. */
100export const BODY_CAP = 6_000
101
102/** A body on one line, as the band and the message index show it. */
103export function flatOf(body: string): string {
104  return body.trim().replace(/\s*\n\s*/g, ' ⏎ ')
105}
106
107/** This session's conversation: what it received (by id) and what it sent. */
108export function conversationOf(
109  rows: readonly Exported[],
110  inbound: ReadonlySet<number>,
111  sessionId: string,
112): Entry[] {
113  const entries: Entry[] = []
114  for (const row of rows) {
115    const id = row.id!
116    const isOut = row.sender_session === sessionId
117    const isIn = inbound.has(id)
118    if (!isOut && !isIn) continue
119    entries.push({
120      id,
121      at: row.created_at ?? '',
122      direction: isIn ? 'in' : 'out',
123      peer: isIn ? row.sender_label || 'unknown' : row.alias || 'unknown',
124      body: (row.body ?? '').slice(0, BODY_CAP),
125      length: (row.body ?? '').length,
126      isHuman: row.origin === 'human',
127    })
128  }
129  return entries.sort((a, b) => a.at.localeCompare(b.at) || a.id - b.id)
130}
131
132/** `pager who`: NAME TOOL ROOT HOST LAST, HOST being live, gone or unknown. */
133export function peersOf(run: Run): Peer[] | Failure {
134  const failure = failureOf(run)
135  if (failure) return { error: failure }
136  const lines = run.stdout.split('\n').filter(line => line.trim() !== '')
137  if (lines.length === 0) return []
138  if (!/^NAME\s+TOOL\b/.test(lines[0]!)) return { error: 'unexpected who output' }
139  const peers: Peer[] = []
140  for (const line of lines.slice(1)) {
141    const m = /^(\S+)\s+(\S+)\s+(.+?)\s+(live|gone|unknown)\s+(.+)$/.exec(line.trim())
142    if (m) peers.push({ name: m[1]!, tool: m[2]!, root: m[3]!, host: m[4]!, last: m[5]!.trim() })
143  }
144  return peers
145}
146
147/**
148 * The peers as the pane lists them: live hosts first, then the order pager gave
149 * (latest activity first), the home folder shown as `~`.
150 */
151export function rosterOf(peers: readonly Peer[], home: string): Peer[] {
152  const tilde = (root: string) =>
153    // `\` too: on Windows pager prints roots as C:\Users\...
154    home !== '' && (root === home || root.startsWith(`${home}/`) || root.startsWith(`${home}\\`))
155      ? `~${root.slice(home.length)}`
156      : root
157  const live = peers.filter(peer => peer.host === 'live')
158  const rest = peers.filter(peer => peer.host !== 'live')
159  return [...live, ...rest].map(peer => ({ ...peer, root: tilde(peer.root) }))
160}
161
162/** The highest inbound id, the baseline a look at the pane moves to. */
163export function newestOf(inbound: ReadonlySet<number>): number {
164  let max = 0
165  for (const id of inbound) if (id > max) max = id
166  return max
167}
168
169export function newCountOf(inbound: ReadonlySet<number>, baseline: number): number {
170  let count = 0
171  for (const id of inbound) if (id > baseline) count += 1
172  return count
173}
174
175const two = (n: number) => String(n).padStart(2, '0')
176
177/** `2026-10-07T05:48:19.655Z` → `14:48` in the host's time zone; `--:--` for a bad time. */
178export function clockOf(iso: string): string {
179  const date = new Date(iso)
180  if (Number.isNaN(date.getTime())) return '--:--'
181  return `${two(date.getHours())}:${two(date.getMinutes())}`
182}
183
184/** `2026-10-07T05:48:19.655Z` → `10-07` in the host's time zone; `--` for a bad time. */
185export function dayOf(iso: string): string {
186  const date = new Date(iso)
187  if (Number.isNaN(date.getTime())) return '--'
188  return `${two(date.getMonth() + 1)}-${two(date.getDate())}`
189}
190
191/** One chat of the /pager list: a peer this session has messages with, or one pager lists. */
192export type Room = {
193  name: string
194  /** pager's roster row for the peer; null once the peer left the roster. */
195  peer: Peer | null
196  /** The newest message with the peer; null when there is none yet. */
197  last: Entry | null
198}
199
200/**
201 * The chats: the conversations by their newest message, newest first, then the
202 * peers without messages in the roster's order (live first). `self` is this
203 * session's name, which is the pane's header and never a room.
204 */
205export function roomsOf(entries: readonly Entry[], peers: readonly Peer[], self: string): Room[] {
206  const lastOf = new Map<string, Entry>()
207  // Oldest first, so the last write per peer is its newest message.
208  for (const entry of entries) if (entry.peer !== self) lastOf.set(entry.peer, entry)
209  const peerOf = new Map(peers.map(peer => [peer.name, peer]))
210  const talked = [...lastOf.values()]
211    .sort((a, b) => b.at.localeCompare(a.at) || b.id - a.id)
212    .map(last => ({ name: last.peer, peer: peerOf.get(last.peer) ?? null, last }))
213  const quiet = peers
214    .filter(peer => peer.name !== self && !lastOf.has(peer.name))
215    .map(peer => ({ name: peer.name, peer, last: null }))
216  return [...talked, ...quiet]
217}
218
219/** The highest id of what `peer` sent this session; 0 when nothing. */
220export function newestInOf(entries: readonly Entry[], peer: string): number {
221  let max = 0
222  for (const entry of entries) if (entry.direction === 'in' && entry.peer === peer && entry.id > max) max = entry.id
223  return max
224}
225
226/**
227 * The per-room seen map after a refresh: the last inbound id counted as read,
228 * per peer. A room met for the first time starts at `prior`, the session's
229 * baseline before this refresh moved it, so mail from before the session's
230 * first look is not unread; the room `open` in the pane moves to its newest.
231 */
232export function seenOf(
233  stored: Readonly<Record<string, number>>,
234  entries: readonly Entry[],
235  prior: number,
236  open: string | null,
237): Record<string, number> {
238  const seen: Record<string, number> = { ...stored }
239  for (const entry of entries) {
240    if (entry.direction === 'in' && seen[entry.peer] === undefined) seen[entry.peer] = prior
241  }
242  if (open !== null) {
243    const newest = newestInOf(entries, open)
244    if (newest > (seen[open] ?? 0)) seen[open] = newest
245  }
246  return seen
247}
248
249/** Unread per room: what each peer sent past its seen id. Rooms with none are left out. */
250export function unreadOf(entries: readonly Entry[], seen: Readonly<Record<string, number>>): Record<string, number> {
251  const unread: Record<string, number> = {}
252  for (const entry of entries) {
253    if (entry.direction !== 'in') continue
254    const mark = seen[entry.peer]
255    if (mark !== undefined && entry.id > mark) unread[entry.peer] = (unread[entry.peer] ?? 0) + 1
256  }
257  return unread
258}
259
260/** Whether a code point takes two terminal cells (East Asian Wide and Fullwidth, emoji). */
261function isWide(code: number): boolean {
262  return (
263    (code >= 0x1100 && code <= 0x115f) ||
264    (code >= 0x2e80 && code <= 0x303e) ||
265    (code >= 0x3041 && code <= 0x33ff) ||
266    (code >= 0x3400 && code <= 0x4dbf) ||
267    (code >= 0x4e00 && code <= 0x9fff) ||
268    (code >= 0xa000 && code <= 0xa4cf) ||
269    (code >= 0xa960 && code <= 0xa97f) ||
270    (code >= 0xac00 && code <= 0xd7a3) ||
271    (code >= 0xf900 && code <= 0xfaff) ||
272    (code >= 0xfe30 && code <= 0xfe4f) ||
273    (code >= 0xff00 && code <= 0xff60) ||
274    (code >= 0xffe0 && code <= 0xffe6) ||
275    (code >= 0x1f300 && code <= 0x1f64f) ||
276    (code >= 0x1f680 && code <= 0x1f6ff) ||
277    (code >= 0x1f900 && code <= 0x1f9ff) ||
278    (code >= 0x1fa70 && code <= 0x1faff) ||
279    (code >= 0x20000 && code <= 0x3fffd)
280  )
281}
282
283/** Combining marks, zero-width spaces and joiners, variation selectors: no cell of their own. */
284function isZeroWidth(code: number): boolean {
285  return (
286    (code >= 0x0300 && code <= 0x036f) ||
287    (code >= 0x200b && code <= 0x200f) ||
288    (code >= 0x20d0 && code <= 0x20ff) ||
289    (code >= 0xfe00 && code <= 0xfe0f)
290  )
291}
292
293const cellOf = (char: string) => {
294  const code = char.codePointAt(0) ?? 0
295  return isZeroWidth(code) ? 0 : isWide(code) ? 2 : 1
296}
297
298/** The terminal cells a string takes: a Hangul syllable two, a Latin letter one. */
299export function cellsOf(text: string): number {
300  let cells = 0
301  for (const char of text) cells += cellOf(char)
302  return cells
303}
304
305/** A bubble folds past this many visual lines. */
306export const FOLD_LINES = 8
307
308/** What a folded bubble draws: `text`, and how many visual lines it leaves out (0 when whole). */
309export type Fold = { text: string; hidden: number }
310
311/**
312 * The first `limit` visual lines of `body` at `width` cells a line. A line of
313 * the body takes ceil(cells / width) rows, one when empty; a line cut at the
314 * fold keeps the cells that fit.
315 */
316export function foldOf(body: string, width: number, limit = FOLD_LINES): Fold {
317  const room = Math.max(1, width)
318  const lines = body.split('\n')
319  const rowsOf = (line: string) => Math.max(1, Math.ceil(cellsOf(line) / room))
320  const total = lines.reduce((sum, line) => sum + rowsOf(line), 0)
321  if (total <= limit) return { text: body, hidden: 0 }
322  const kept: string[] = []
323  let used = 0
324  for (const line of lines) {
325    const rows = rowsOf(line)
326    if (used + rows <= limit) {
327      kept.push(line)
328      used += rows
329      continue
330    }
331    const left = (limit - used) * room
332    if (left > 0) {
333      let cut = ''
334      let cells = 0
335      for (const char of line) {
336        if (cells + cellOf(char) > left) break
337        cut += char
338        cells += cellOf(char)
339      }
340      kept.push(cut)
341    }
342    break
343  }
344  return { text: kept.join('\n'), hidden: total - limit }
345}
346
347/** Peers other than `self` whose host pager judges live. */
348export function liveOf(peers: readonly Peer[], self: string): number {
349  return peers.filter(peer => peer.host === 'live' && peer.name !== self).length
350}
351
352/** How long before `nowMs` an ISO time was: `now`, `12m`, `3h`, `2d`. */
353export function agoOf(iso: string, nowMs: number): string | null {
354  const then = Date.parse(iso)
355  if (Number.isNaN(then)) return null
356  const minutes = Math.floor(Math.max(0, nowMs - then) / 60_000)
357  if (minutes < 1) return 'now'
358  if (minutes < 60) return `${minutes}m`
359  if (minutes < 24 * 60) return `${Math.floor(minutes / 60)}h`
360  return `${Math.floor(minutes / (24 * 60))}d`
361}
362
types/index.d.ts 51 lines
1/** One message of this session's pager conversation, oldest first. */
2export type Entry = {
3  id: number
4  at: string
5  direction: 'in' | 'out'
6  peer: string
7  /** The body as sent, line breaks kept, cut at BODY_CAP characters. */
8  body: string
9  /** The body's full length, so a cut one can say how much is left. */
10  length: number
11  isHuman: boolean
12}
13
14export type Peer = { name: string; tool: string; root: string; host: string; last: string }
15
16/**
17 * What the band and the /pager pane draw, for `sessionId`. `name` null: pager
18 * has no name for this session (or no pager at all), so nothing is drawn.
19 * `error` says the latest refresh failed; the rest is the last good read.
20 */
21export type PagerState = {
22  sessionId: string
23  name: string | null
24  entries: Entry[]
25  peers: Peer[]
26  newCount: number
27  /** Peers other than this session whose host is live. */
28  live: number
29  /** How long ago the last entry was, as of the refresh that read it (`3m`). */
30  lastAgo: string | null
31  /** When that refresh ran (ms since the epoch): the ages the pane draws count from it. */
32  now: number
33  error: string | null
34  /** Per peer, what it sent since its room was last opened; rooms with none are absent. */
35  unread: Record<string, number>
36}
37
38declare module 'claude-code' {
39  interface PluginState {
40    'pager-view': {
41      pager: PagerState
42      /** The room the pane shows, by the peer's name; null shows the chats. */
43      room: string | null
44      /** The chat the cursor bar is on; null (or a name gone from the list) puts it on the first. */
45      cursor: string | null
46      /** The ids of the bubbles unfolded past the fold. */
47      expanded: number[]
48    }
49  }
50}
51