SLOPSHOPPER

collision-widget

Stops an edit to a file another Claude Code session on this machine changed since this one last read it, and has Claude read it again first

newpanebandspinnerguardcommand
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · collision-widget
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /collision-widget ⎿ collision-widget: Collision on; /widgets places it. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

Claude Code Widgets

Small cards that sit under the Claude Code prompt, or docked beside the transcript in fullscreen. Each widget is its own mod, toggled with a slash command.

It started with a few useful ones (context, usage, file tree) and then got carried away: there are now 95 widgets, from git status and a turn timer to a pixel crab, a dungeon crawl and Tetris.

Try every widget in its own little terminal on the demo page: the real widget code runs in the browser against a simulated session, so you can type its slash commands, run a turn and play the games. It is a static page in docs/, published to GitHub Pages on every push to main that changes it; opening docs/index.html from a checkout works too.

Install

Add the marketplace, then install the layout plugin and whichever widgets you want:

/plugin marketplace add oMaN-Rod/claude-code-widgets
/plugin install widgets@claude-code-widgets
/plugin install context-widget@claude-code-widgets

Every widget needs widgets, the layout plugin that places the cards.

Requires a Claude Code version with mod (function hook) support. The mod API is early access and may change between releases.

Widgets

Layout

Required by every widget.

PluginCommandWhat it shows
widgets`/widgets [side\above\below\close\<columns>\width <widget> <columns\reset>]`Places the cards: below the prompt, above it, or docked beside the transcript in fullscreen

Session

What Claude is doing and what it is costing.

PluginCommandWhat it shows
context-widget`/context-widget [auto\detailed\grid\top\bar\line]`The context window as a stacked bar, one colour per /context category
usage-widget/usage-widgetA bar per rate-limit window, time to reset, session cost
timer-widget`/timer-widget [on\off\clear]`The running turn's elapsed time, plus last, average and longest turn and a sparkline
activity-widget`/activity-widget [on\off\clear]`The latest tool calls with their duration and whether they failed
tasks-widget`/tasks-widget [on\off\clear]`The task list Claude is working through, with a progress bar
checks-widget`/checks-widget [on\off\clear]`The latest test, lint and build runs: pass or fail, duration and how long ago
timeline-widget`/timeline-widget [on\off]`The turn as a chart: one bar per tool call on a time axis, parallel calls stacked
board-widget`/board-widget [on\off\clear]`A status board Claude writes itself through a pin tool: goal, findings and open questions
forecast-widget`/forecast-widget [on\off\clear]`Context growth per turn as a chart, with the turns left before compaction; warns once when three or fewer are left
guard-widget`/guard-widget [on\off\clear]`Permission checks this session: allowed, asked and denied, with what you keep being asked about
stream-widget`/stream-widget [on\off]`A live tokens-per-second gauge and sparkline while Claude is writing (estimated from text length)
sessions-widget/relay <number> <message>, `/sessions-widget [on\off]`Every Claude Code session open on this machine: folder, branch, working or waiting and for how long; /relay 1 <message> sends a line to one
collision-widget`/collision-widget [on\off\clear]`Stops an edit to a file another Claude Code session on this machine changed since this one last read it, and has Claude read it again first
sieve-widget`/sieve-widget [on\off]`A compaction that keeps every word you and Claude said and folds only the old tool traffic, with no summary and no tokens spent
redact-widget`/redact-widget [on\off\clear]`Replaces API keys, tokens, private keys and passwords in command output and file reads before Claude sees them
notebook-widget`/notebook-widget [on\off\show\drop <number>\clear]`Gives Claude a jot tool for writing down what its future self should know about this project, and reads the notes back next session
footnotes-widget`/footnotes-widget [on\off\show\clear]`Checks every file path, cited line and code symbol in Claude's last reply against the working tree, with no model call, and flags the ones that are not there
witness-widget`/witness-widget [on\off\show\clear]`Every line of hidden context the other widgets add to your prompts, word for word, with a running size
queue-widget`/queue-widget [on\off\add <prompt>\until <command\off>\start\drop <number>\report\clear]`A queue of prompts that run back to back while you are away, a gate command each must pass before the next starts, and a report of how each one ended
done-widget`/done-widget [on\off\add <criterion>\drop <number>\show\clear]`A definition of done you write once: Claude ticks each item with evidence through its tick tool, and is pulled up when it says done with items open
trial-widget`/trial-widget [on\off\test <widget>\clear]`A fair test of another widget: sessions alternate with it on and off, and the card compares how many turns end clean
aside-widget`/aside-widget [on\off\ask <question>\clear]`Ask a side question about the conversation, even mid-turn, and get the answer on a card without adding a turn to the transcript
tap-widget`/tap-widget [on\off\list [word]\add <server> <tool> [json] [anyway]\run <n>\show <n>\drop <n>\clear]`One line per tool of your connected MCP servers, called by the widget on a clock with no model: pull requests, errors, the next meeting
margin-widget`/margin-widget [on\off\mark [remark]\drop <n>\send\clear]`Mark passages of Claude's reply with the mouse, write a remark against each, and send them back as one quoted prompt
loupe-widget`/loupe-widget [on\off\look [text]\copy]`Select a hash, path, name, timestamp or colour in the transcript with the mouse and the card says what it is, with no model call
strays-widget`/strays-widget [on\off\stop <port>\forget <port>\clear]`Servers this session started that still hold a port, with age and turn, one verb to stop one, and the survivors shown when the next session opens
premise-widget`/premise-widget [on\off\show\fix <n>\clear]`Quotes thinking-summary sentences that name a gap and a choice made anyway, unless the reply flags it, and starts your correction; no model call; needs "showThinkingSummaries": true in settings.json
earpiece-widget`/earpiece-widget [on\off], /whisper <number> <note>`Every running subagent with the tool it is on and its last sentence, and /whisper slips one of them a note without stopping the turn
pen-widget`/pen-widget [on\off\show\clear]`The file, edit or command Claude is writing right now, drawn line by line as the tool call's arguments stream in, before the tool runs
outage-widget`/outage-widget [on\off\check\clear]`When a push or install fails on the network, checks the provider's status page and says whether GitHub, npm, PyPI or crates.io reports an incident
landmarks-widget`/landmarks-widget [on\off\list\go <n>\clear]`A numbered table of contents for the session, built as it happens from prompts, first edits, checks turning red or green, commits and questions; press a line to scroll the transcript to it
seen-widget`/seen-widget [on\off\show\open [n]\clear]`The pictures Claude looked at this session, image files it read and screenshots that came back from tools, drawn as Claude received them and opened full size with one command
amendments-widget`/amendments-widget [on\off\show [n]\clear]`What changed in the system prompt and the built-in tool descriptions Claude Code gives Claude since the version you last ran, with the before and after one command away
skimmed-widget`/skimmed-widget [on\off\show\clear]`The caveats in Claude's replies that left your screen while Claude was still writing and have not been back, quoted in full; it never claims that what was on screen was read
attic-widget`/attic-widget [on\off\show\keep <tool>\stow <tool>\clear]`Counts which tools Claude calls in this project, puts the unused ones behind ToolSearch, lists the daily ones up front, and reports how many schema tokens each request no longer carries
rehearsal-widget`/rehearsal-widget [on\off\show\forget <n>\clear]`Which of the commands and edits Claude has made in this project would stop for permission or be refused right now, asked of the engine's own permission check without running anything
aim-widget`/aim-widget [on\off\prod <word>\unprod <word>\show\clear]`Where a command lands outside this folder: the kube context, cloud profile, Terraform workspace or database it is aimed at, named in the permission dialog
earshot-widget`/earshot-widget [on\off\last\clear]`Whether Claude has got the message you typed while it was working: how late a request first carried it, and what Claude changed before it heard you

Project and git

The state of the working tree.

PluginCommandWhat it shows
file-tree-widget/file-tree-widgetThe project directory; folders expand on click
git-widget/git-widgetBranch, ahead/behind, staged, changed and untracked counts, and the last commit
changes-widget`/changes-widget [on\off\clear]`Files edited this session, most recent first, with an edit count each
commits-widget/commits-widgetThe commits made since the session started
todos-widget/todos-widgetTODO, FIXME, HACK and XXX comments in tracked files, counted and listed
diff-widget`/diff-widget [on\off\clear]`The last edit as a syntax-highlighted diff
watch-widget`/watch-widget [on\off\run\stop], /watch <command>`/watch bun test reruns the command after every edit: a pass or fail light and the last failing lines
map-widget`/map-widget [on\off\clear]`A pixel map of the tracked files, lit blue where Claude has read and green where it has edited
stakes-widget`/stakes-widget [on\off\clear]`What a yes would lose, measured from git and written under the permission dialog for a destructive command
ledger-widget`/ledger-widget [on\off\scan\show\clear]`What a project has cost across every session, from any folder or worktree in it: measured as each turn ends, and read back from the sessions Claude Code saved
squiggle-widget`/squiggle-widget [on\off\check [text]]`Underlines file names that do not exist, as you type them in the prompt box, and paints the ones that do green
critic-widget`/critic-widget [on\off\review\tell\clear]`A second pair of eyes: a separate model reads the uncommitted diff and lists only real defects, which you can hand to Claude
customs-widget`/customs-widget [on\off\show\trust <name>\clear]`Looks up every package Claude installs on npm or PyPI before the command runs, and holds the install for a yes when the name is missing or under 30 days old. Scoped names and installs that name a registry, or sit beside a project .npmrc that does, are not looked up; user-level and environment registry settings, bunfig.toml, .yarnrc.yml and pip and uv config files are not seen
provenance-widget`/provenance-widget [on\off\scan\look [<path>:<line>]\copy\clear]`The conversation behind a line of code: for lines Claude is about to edit, or a path:line you ask about, the prompt you typed before they were written and the command that resumes that session
green-widget`/green-widget [on\off\tell\clear]`What changed in the working tree since each test, lint or build command last passed, measured against a hidden git snapshot taken at that moment and handed to Claude on request

Time and focus

Clocks, timers and reminders that do not depend on the session.

PluginCommandWhat it shows
pomodoro-widget`/pomodoro-widget [on\off\start\break\stop\<minutes>]`A focus timer with a countdown, a progress bar and a count of finished sessions
countdown-widget`/countdown-widget [on\off\clear], /countdown <HH:MM\<n>m\<n>h> [label]`Time left to a deadline you set, with a progress bar and a toast when it arrives
clocks-widget`/clocks-widget [on\off\add <zone>\remove <zone>\clear]`Your local time beside the time zones you add, such as Asia/Tokyo
notes-widget`/notes-widget [on\off\clear], /note <text\done <n>>`Pinned notes kept across sessions; /note <text> adds one, /note done <n> removes it
coffee-widget`/coffee-widget [on\off\refill\<minutes>]`A cup that empties over 90 minutes and nudges you to take a break

Scenes

Pixel art that reacts to turns, tool calls, checks and context usage.

PluginCommandWhat it shows
pet-widget`/pet-widget [on\off\<mood>]`Clawd, a pixel crab: works during a turn, dizzy when a tool call fails, happy when tests pass. Earns XP and levels up across sessions, wears a hat once badges-widget has awarded a badge, and with two sessions open stays in the one you last prompted. Remembers each project and greets you with how long you were away and whether the checks were red
aquarium-widget`/aquarium-widget [on\off\demo]`A fish for every running tool call and agent
skyline-widget`/skyline-widget [on\off\demo\clear]`One building per turn, one floor per tool call
train-widget`/train-widget [on\off]`A locomotive pulling one wagon per tool call this turn, coloured by tool
garden-widget`/garden-widget [on\off\reset]`A plant: a leaf per tool call, a flower when checks pass, wilting when a call fails
campfire-widget`/campfire-widget [on\off\stoke]`A campfire that burns higher with tool calls and dies down to embers when idle
constellation-widget`/constellation-widget [on\off\clear]`A star per turn, joined into a constellation that gets a name after nine
fireworks-widget`/fireworks-widget [on\off\demo]`A night sky that sets off fireworks when checks pass, and a dud when they fail
invaders-widget`/invaders-widget [on\off\demo\clear]`An invader arrives for every failing check; passing checks shoot them down
weather-widget`/weather-widget [on\off\live\<percent>]`Clear sky when context has room, a storm near compaction
boss-widget`/boss-widget [on\off]`Context usage as a boss health bar; compaction defeats it and starts the next level
sky-widget`/sky-widget [on\off]`The sky at your local time: sun by day, moon by night, more stars the longer the session runs
world-widget`/world-widget [on\off\clear]`One scene for everything: sky by the clock, weather by context, a tower per turn, a train of tool calls and a wandering crab
quest-widget`/quest-widget [on\off\reset]`The session as a dungeon crawl: a room per turn, a monster per tool call, loot when checks pass; the hero is kept across sessions
race-widget`/race-widget [on\off\clear]`Parallel subagents as cars on a track, one stride per tool call, with a podium as they finish
moon-widget`/moon-widget [on\off\north\south]`The real moon right now, drawn for your hemisphere, with a countdown to the next full moon and what it means for your deploy

Visualizers

Abstract pictures driven by tool activity.

PluginCommandWhat it shows
mosaic-widget`/mosaic-widget [on\off\clear]`One tile per tool call, coloured by tool; failures are red
sorting-widget`/sorting-widget [on\off\step]`A bar chart being sorted, one swap per tool call
equalizer-widget`/equalizer-widget [on\off]`Level meters that jump with each tool call and fall back to rest
rain-widget`/rain-widget [on\off]`Falling code rain that speeds up the busier the turn gets
orbit-widget`/orbit-widget [on\off]`A small solar system; the planets speed up while tool calls run
life-widget`/life-widget [on\off\reset]`Conway's Game of Life; every tool call drops a glider
donut-widget`/donut-widget [on\off]`The spinning 3D donut; it spins faster while tool calls run
pipes-widget`/pipes-widget [on\off]`The pipes screensaver; it grows while the session is idle and pauses while Claude works
maze-widget`/maze-widget [on\off\new]`A first-person walk through a maze seeded by the project folder
marquee-widget`/marquee-widget [on\off\clear\<text>]`An LED ticker scrolling session events; any other text posts your own headline

Games

Snake, 2048 and Tetris play themselves until you click the board and take the keys.

PluginCommandWhat it shows
snake-widget`/snake-widget [on\off]`Snake; it plays itself until you take the keys
2048-widget`/2048-widget [on\off]`2048; it plays itself until you take the keys
tetris-widget`/tetris-widget [on\off]`Tetris; it plays itself until you take the keys
minesweeper-widget`/minesweeper-widget [on\off]`Minesweeper: click to reveal, right-click or f to flag, r to restart
breakout-widget`/breakout-widget [on\off\reset]`A self-playing brick breaker; every tool call adds a row of bricks
typer-widget`/typer-widget [on\off]`A typing game: words from your own file names fall, and you type them before they land

Just for fun

PluginCommandWhat it shows
fortune-widget`/fortune-widget [on\off\next]`A one-line fortune that changes with every turn
8ball-widget`/8ball-widget [on\off], /8ball <question>`/8ball <question> gives an answer of doubtful reliability
badges-widget`/badges-widget [on\off\reset]`Achievements earned across sessions, with a toast when one unlocks
sigil-widget`/sigil-widget [on\off\clear]`A pixel emblem generated from this session's activity, beside a gallery of the ones from earlier sessions
sound-widget`/sound-widget [on\off\mute\test]`A note per tool call, a chord when checks pass, a buzz on failure, with a piano roll (audio plays on macOS only)

Placement, which widgets are on, and view modes are saved and restored in every session.

Notes

  • /widgets width pet 60 sets how wide one widget's card may grow (the default is 40 columns); /widgets width pet reset puts it back.
  • /widgets side docks the cards beside the transcript only in the fullscreen layout (/tui fullscreen). In the default layout it falls back to below the prompt.
  • The pixel art is drawn with terminal block characters and shows in the terminal only.
  • sound-widget plays audio on macOS only; elsewhere it stays silent and just draws the piano roll.
  • board-widget registers a pin tool that Claude can call, so its description is part of the context while the board is on.
  • watch-widget runs your command through sh -c, falling back to cmd /c.
  • Taking over a game, and playing Minesweeper at all, needs a mouse click on the board, which the fullscreen layout reports.

Develop

Each plugin under plugins/ is a mod: a manifest, a hooks module and its tests.

claude --plugin-dir plugins            # load every plugin from this checkout
claude plugin validate plugins/<name>  # check a manifest and hooks module
claude plugin test plugins/<name>      # run its tests

Plugin storage ($.store) is read once per session, so a widget that has to see other live sessions keeps a file under its own folder instead ($.plugin.root).

Plugins cannot import from one another, so widgets shares card stacking and the pixel renderer as $.widgets (plugins/widgets/hooks/kit.tsx), which every widget calls.

Demo page

docs/ is the demo page. bun run site/build.ts bundles every widget's hooks module into docs/mods.js and writes docs/catalog.js from the tables above, so a new widget appears on the page once it has a row here. docs/engine.js is a small stand-in for the mod engine (state, store, clock, commands, a made-up project and a scripted turn), and docs/view.js draws the card trees. bun run site/smoke.ts boots every widget in that engine and runs a turn; a widget that needs an engine call the stand-in lacks shows up there. docs/widgets.js holds recordings from the real interface, shown only if a widget fails to start.

The Widget Factory

New widgets are made by the Widget Factory in factory/: a crew of Claude Code agents that takes each widget through ideation, design, build, inspection and shipping, with a different agent inspecting than built it. Clone the repository and you can run your own:

https://github.com/user-attachments/assets/6833eb82-8b2e-4b4c-80ca-4194d48d10e7

bun run --cwd factory setup   # checks what you need and prepares the floor
bun run --cwd factory floor   # the factory floor in your browser
bun run --cwd factory line    # opens a Claude Code session that runs the line

https://github.com/user-attachments/assets/d0953871-4935-4fa9-8ab3-f58b51739a17

factory/README.md explains the stations, the crew, the widget standard and how to contribute a widget.

License

MIT

Source 3 files
hooks/register.tsx 459 lines
1import { atom, read, update } from 'claude-code'
2import type { Elements, EngineInterface, FsEntry, Register, RenderElement, RenderSurface } from 'claude-code'
3import type { WidgetsPlace } from 'widgets'
4
5import type { CollisionHeld, CollisionMeet, CollisionWatch } from '../types'
6import { fit, plural, span } from './lib'
7
8type Tags = Pick<Elements[RenderSurface], 'Box' | 'Text'>
9type Peer = CollisionHeld & { place: string }
10type Peers = Record<string, Peer>
11type Shared = { id: string; cwd: string; files: Record<string, CollisionHeld> }
12
13const PANE = 'widgets'
14const CARD_COLUMNS = 40
15const USAGE = 'Usage: /collision-widget [on|off|clear]'
16const WINDOW_MS = 30 * 60_000
17const STALE_MS = 24 * 3_600_000
18const STARTED_SLACK_MS = 1000
19const OWN_EDIT_MS = 2000
20const FILES = 60
21const MEETS = 6
22const STATS = 40
23const SEEN = 200
24const WRITE_PASSES = 3
25const ROW_COLUMNS = 30
26const PLACE_LETTERS = 8
27const FRAME_COLUMNS = 4
28const GLYPH_COLUMNS = 2
29const NO_PLACE = 'root'
30const EDITS = ['Edit', 'Write', 'NotebookEdit', 'MultiEdit']
31const WORD_BREAKS = /[\s"'`<>|;&()]+/
32const EMPTY = 'No shared files. A file appears here when another session edits one that this session edits.'
33const NO_WRITE = 'Cannot write the shared folder. Others cannot see edits made here.'
34const NO_HOME = 'No home folder found. Cannot watch other sessions.'
35const STATES = [
36  { state: 'stopped', glyph: '✕', color: 'red', legend: 'edit stopped' },
37  { state: 'changed', glyph: '!', color: 'yellow', legend: 'Bash changed' },
38  { state: 're-read', glyph: '✓', color: 'green', legend: 'read again' },
39] as const
40const REST: CollisionWatch = { slot: '', wrote: null, mine: {}, seen: {}, meets: [], others: 0, isBlind: false }
41const site = { plugin: 'widgets', key: 'site' } as const
42const widths = { plugin: 'widgets', key: 'widths' } as const
43const isOn = atom({ plugin: 'collision-widget', key: 'isOn' } as const, false)
44const watch = atom({ plugin: 'collision-widget', key: 'watch' } as const, REST)
45
46const slashed = (path: string): string => path.replaceAll('\\', '/')
47
48const isDrive = (part: string | undefined): boolean => part !== undefined && /^[a-z]:$/i.test(part)
49
50const absolute = (path: string, cwd: string): string => {
51  const base = slashed(cwd)
52  const mounted = /^[a-z]:/i.test(base) ? slashed(path).replace(/^\/([a-z])(?=\/|$)/i, '$1:') : slashed(path)
53  const whole = /^[a-z]:|^\//i.test(mounted) ? mounted : `${base}/${mounted}`
54  const parts: string[] = []
55  for (const part of whole.split('/')) {
56    if (part === '..' && !isDrive(parts[parts.length - 1])) parts.pop()
57    else if (part !== '' && part !== '.' && part !== '..') parts.push(part)
58  }
59
60  return `${whole.startsWith('/') ? '/' : ''}${parts.join('/')}`
61}
62
63const lastOf = (path: string): string => slashed(path).split('/').filter(part => part !== '').pop() ?? ''
64
65const placeOf = (cwd: string): string => {
66  const last = lastOf(cwd)
67
68  return last === '' || isDrive(last) ? NO_PLACE : last
69}
70
71const pathIn = (input: unknown): string | undefined => {
72  if (typeof input !== 'object' || input === null) return undefined
73  const { file_path: file, notebook_path: notebook } = input as { file_path?: unknown; notebook_path?: unknown }
74  const path = file ?? notebook
75
76  return typeof path === 'string' && path !== '' ? path : undefined
77}
78
79const isHeld = (value: unknown): value is CollisionHeld =>
80  typeof value === 'object' &&
81  value !== null &&
82  typeof (value as CollisionHeld).path === 'string' &&
83  typeof (value as CollisionHeld).at === 'number'
84
85const sharedOf = (text: string): Shared | undefined => {
86  try {
87    const value: unknown = JSON.parse(text)
88    if (typeof value !== 'object' || value === null) return undefined
89    const { id, cwd, at, files } = value as Record<string, unknown>
90    if (typeof id !== 'string' || typeof cwd !== 'string' || typeof at !== 'number') return undefined
91    if (typeof files !== 'object' || files === null) return undefined
92
93    return { id, cwd, files: Object.fromEntries(Object.entries(files).filter((entry): entry is [string, CollisionHeld] => isHeld(entry[1]))) }
94  } catch {
95    return undefined
96  }
97}
98
99const evicted = (mine: Record<string, CollisionHeld>, now: number): Record<string, CollisionHeld> =>
100  Object.fromEntries(
101    Object.entries(mine)
102      .filter(([, held]) => now - held.at <= WINDOW_MS)
103      .sort(([, one], [, other]) => other.at - one.at)
104      .slice(0, FILES),
105  )
106
107const capped = (seen: Record<string, number>): Record<string, number> =>
108  Object.fromEntries(
109    Object.entries(seen)
110      .sort(([, one], [, other]) => other - one)
111      .slice(0, SEEN),
112  )
113
114const met = (meets: readonly CollisionMeet[], meet: CollisionMeet): CollisionMeet[] =>
115  [meet, ...meets.filter(old => old.key !== meet.key)].slice(0, MEETS)
116
117const clipped = (name: string, room: number): string =>
118  name.length <= room ? name : `…${name.slice(name.length - Math.max(0, room - 1))}`
119
120const wrapped = (text: string, room: number): string[] =>
121  text.split(' ').filter(word => word !== '').reduce<string[]>((lines, word) => {
122    const last = lines[lines.length - 1]
123
124    return last !== undefined && last.length + 1 + word.length <= room ? [...lines.slice(0, -1), `${last} ${word}`] : [...lines, word]
125  }, [])
126
127const fileOf = (id: string): string => `${id.replace(/[^\w.-]/g, '_')}.json`
128
129const dirOf = async ($: EngineInterface): Promise<string | null> => {
130  const held = (await read($, watch)).dir
131  if (held !== undefined) return held
132
133  const config = await $.env.get('CLAUDE_CONFIG_DIR')
134  const home = config || (await $.env.get('HOME')) || (await $.env.get('USERPROFILE'))
135  const base = slashed(home ?? '').replace(/\/+$/, '')
136  const dir = !home ? null : config ? `${base}/collision-widget` : `${base}/.claude/collision-widget`
137  await update($, watch, kept => ({ ...kept, dir }))
138
139  return dir
140}
141
142const idOf = async ($: EngineInterface): Promise<string | undefined> => {
143  try {
144    return (await $.session.id()) || undefined
145  } catch {
146    return undefined
147  }
148}
149
150const scan = async ($: EngineInterface, dir: string, id: string, now: number): Promise<Peers> => {
151  const { slot, wrote, others } = await read($, watch)
152  const entries = await $.fs.list(dir).catch((): FsEntry[] => [])
153  const peers: Peers = {}
154  const ids = new Set<string>()
155  let isTaken = false
156  for (const entry of entries) {
157    if (entry.kind !== 'file' || !entry.name.endsWith('.json') || !(entry.mtimeMs >= now - WINDOW_MS)) continue
158    const shared = sharedOf(await $.fs.read(`${dir}/${entry.name}`).catch(() => ''))
159    if (shared === undefined || shared.id === id || shared.id === wrote) continue
160
161    ids.add(shared.id)
162    isTaken ||= entry.name === slot
163    const place = placeOf(shared.cwd)
164    for (const [key, held] of Object.entries(shared.files)) {
165      if (now - held.at <= WINDOW_MS && held.at > (peers[key]?.at ?? 0)) peers[key] = { ...held, place }
166    }
167  }
168  if (isTaken || ids.size !== others) {
169    await update($, watch, kept => ({ ...kept, others: ids.size, slot: isTaken && kept.slot === slot ? fileOf(id) : kept.slot }))
170  }
171
172  return peers
173}
174
175const slotOf = async ($: EngineInterface, dir: string, id: string, now: number): Promise<string> => {
176  const entries = await $.fs.list(dir).catch((): FsEntry[] => [])
177  const oldest = entries
178    .filter(entry => entry.kind === 'file' && entry.name.endsWith('.json') && entry.mtimeMs > 0)
179    .sort((one, other) => one.mtimeMs - other.mtimeMs)[0]
180
181  return oldest !== undefined && now - oldest.mtimeMs > STALE_MS ? oldest.name : fileOf(id)
182}
183
184const publish = async ($: EngineInterface, dir: string, id: string, now: number): Promise<void> => {
185  const cwd = await $.session.cwd()
186  const chosen = (await read($, watch)).slot || (await slotOf($, dir, id, now))
187  for (let pass = 0; pass < WRITE_PASSES; pass += 1) {
188    const held = await update($, watch, kept => ({ ...kept, slot: kept.slot || chosen, mine: evicted(kept.mine, now) }))
189    const isWritten = await $.fs.write(`${dir}/${held.slot}`, JSON.stringify({ id, cwd, at: now, files: held.mine })).then(
190      () => true,
191      () => false,
192    )
193    const after = await update($, watch, kept => ({ ...kept, wrote: isWritten ? id : kept.wrote, isBlind: !isWritten }))
194    if (!isWritten || JSON.stringify(after.mine) === JSON.stringify(held.mine)) return
195  }
196}
197
198const touched = async (
199  $: EngineInterface,
200  command: string,
201  cwd: string,
202  started: number,
203  now: number,
204  peers: Peers,
205): Promise<Record<string, CollisionHeld>> => {
206  const named = command
207    .split(WORD_BREAKS)
208    .filter(word => word !== '')
209    .map((word): [string, string] => {
210      const path = absolute(word, cwd)
211
212      return [path.toLowerCase(), path]
213    })
214  const candidates = [...new Map([...Object.entries(peers).map(([key, peer]): [string, string] => [key, peer.path]), ...named])].slice(0, STATS)
215  const found = await Promise.all(
216    candidates.map(async ([key, path]): Promise<[string, CollisionHeld][]> => {
217      const stat = await $.fs.stat(path).catch(() => undefined)
218      if (stat === undefined || stat.kind !== 'file' || stat.mtimeMs < started - STARTED_SLACK_MS) return []
219      const peer = peers[key]
220      if (peer !== undefined && stat.mtimeMs <= peer.at + OWN_EDIT_MS) return []
221
222      return [[key, { path, at: Math.min(stat.mtimeMs, now) }]]
223    }),
224  )
225
226  return Object.fromEntries(found.flat())
227}
228
229const wipe = async ($: EngineInterface): Promise<void> => {
230  await update($, watch, kept => ({ ...kept, mine: {}, seen: {}, meets: [] }))
231  const dir = await dirOf($)
232  const id = dir === null ? undefined : await idOf($)
233  if (dir !== null && id !== undefined) await publish($, dir, id, await $.clock.now())
234}
235
236const show = async (
237  $: EngineInterface,
238  { Box, Text }: Tags,
239  beneath: RenderElement,
240  place: WidgetsPlace,
241  columns: number,
242): Promise<RenderElement> => {
243  if (!(await read($, isOn))) return beneath
244  if ((await $.state.get(site)).value !== place) return beneath
245
246  const width = fit((await $.state.get(widths)).value?.['collision-widget'] ?? CARD_COLUMNS, columns)
247  const { dir, mine, meets, others, isBlind } = await read($, watch)
248  const files = Object.keys(mine).length
249  const error = dir === null ? NO_HOME : isBlind ? NO_WRITE : undefined
250  const isWide = width >= ROW_COLUMNS
251  const isResting = error === undefined && meets.length === 0
252  const isEmpty = isResting && files === 0 && others === 0
253  const hasCounts = isResting && !isEmpty
254  const inner = width - FRAME_COLUMNS
255  const room = inner - GLYPH_COLUMNS
256  const rows = meets.map((meet, at) => {
257    const { glyph, color } = STATES.find(known => known.state === meet.state) ?? STATES[0]
258    const name = lastOf(meet.path)
259    const spot = meet.place.length > PLACE_LETTERS ? `${meet.place.slice(0, PLACE_LETTERS - 1)}…` : meet.place
260    const side = `${spot} · ${meet.state}`
261
262    return (
263      <Box key={`meet-${at}`} justifyContent="space-between" columnGap={1}>
264        <Box columnGap={1}>
265          <Text color={color}>{glyph}</Text>
266          <Text wrap="truncate-start">{clipped(name, isWide ? room - side.length - 1 : room)}</Text>
267        </Box>
268        {isWide ? (
269          <Box columnGap={1}>
270            <Text dimColor wrap="truncate-end">{`${spot} ·`}</Text>
271            <Text color={color} wrap="truncate-end">
272              {meet.state}
273            </Text>
274          </Box>
275        ) : null}
276      </Box>
277    )
278  })
279  const legend = isWide
280    ? []
281    : STATES.filter(known => meets.some(meet => meet.state === known.state)).map(known => (
282        <Box key={`legend-${known.state}`} columnGap={1}>
283          <Text color={known.color}>{known.glyph}</Text>
284          <Text dimColor wrap="truncate-end">
285            {known.legend}
286          </Text>
287        </Box>
288      ))
289
290  return $.widgets.card({
291    beneath,
292    width,
293    title: 'Collision',
294    note: error !== undefined ? 'blind' : meets.length > 0 ? `${meets.length} met` : files > 0 ? 'clear' : 'idle',
295    body: (
296      <Box flexDirection="column">
297        {rows}
298        {legend}
299        {hasCounts ? (
300          <Text key="files" wrap="truncate-end">
301            {files === 0 ? 'No files edited' : `${plural(files, 'file')} edited`}
302          </Text>
303        ) : null}
304        {hasCounts ? (
305          <Text key="others" dimColor wrap="truncate-end">
306            {others === 0 ? 'No others nearby' : `${plural(others, 'other')} nearby`}
307          </Text>
308        ) : null}
309        {wrapped(error ?? (isEmpty ? EMPTY : ''), inner).map((line, at) => (
310          <Text key={`prose-${at}`} color={error === undefined ? undefined : 'red'} dimColor={error === undefined} wrap="truncate-end">
311            {line}
312          </Text>
313        ))}
314      </Box>
315    ),
316  })
317}
318
319export const register: Register = on => {
320  on('session.start', async ($, e, next) => {
321    await $.command.register({
322      name: 'collision-widget',
323      description: 'Toggle the Collision card, or clear what it has recorded',
324      argumentHint: '[on|off|clear]',
325    })
326    if ((await $.store.get('isOn')) === true) await update($, isOn, () => true)
327
328    return next(e)
329  })
330
331  on('command.run', { command: 'collision-widget' }, async ($, e) => {
332    const arg = e.args.trim().toLowerCase()
333    if (arg === 'clear') {
334      if (!(await read($, isOn))) return { text: 'Collision is off.' }
335
336      await wipe($)
337
338      return { text: 'Collision cleared.' }
339    }
340    if (arg !== '' && arg !== 'on' && arg !== 'off') return { text: USAGE }
341
342    const isShown = await update($, isOn, shown => (arg === '' ? !(shown ?? false) : arg === 'on'))
343    await $.store.set('isOn', isShown)
344
345    return { text: isShown ? 'Collision on; /widgets places it.' : 'Collision off.' }
346  })
347
348  on('tool.check', async ($, e, next) => {
349    if (!(await read($, isOn))) return next(e)
350
351    const verdict = await next(e)
352    const path = pathIn(e.input)
353    if (e.tool_use_id === undefined || verdict.decision === 'deny' || !EDITS.includes(e.tool) || path === undefined) return verdict
354
355    const dir = await dirOf($)
356    const id = dir === null ? undefined : await idOf($)
357    if (dir === null || id === undefined) return verdict
358
359    const now = await $.clock.now()
360    const key = absolute(path, await $.session.cwd()).toLowerCase()
361    const peer = (await scan($, dir, id, now))[key]
362    if (peer === undefined || peer.at <= ((await read($, watch)).seen[key] ?? 0)) return verdict
363
364    const name = lastOf(path)
365    await update($, watch, kept => ({ ...kept, meets: met(kept.meets, { key, path, place: peer.place, at: peer.at, state: 'stopped' }) }))
366
367    return {
368      decision: 'deny',
369      reason: `collision-widget: ${name} was edited by another Claude Code session (in ${peer.place}) ${span(now - peer.at)} ago, after this session last read it. Read the file again, then repeat the edit, and tell the user that two sessions are working on this file.`,
370    }
371  })
372
373  on('tool.call', async ($, e, next) => {
374    if (!(await read($, isOn))) return next(e)
375
376    const tool: string = e.tool
377    const started = tool === 'Bash' ? await $.clock.now() : 0
378    const ran = await next(e)
379    if (ran.deny !== undefined || ran.isError === true) return ran
380
381    const path = pathIn(e)
382    const isRead = tool === 'Read' && path !== undefined
383    const isEdit = EDITS.includes(tool) && path !== undefined
384    const command = e.tool === 'Bash' && ran.isReadOnly !== true ? e.command : ''
385    if (!isRead && !isEdit && command === '') return ran
386
387    const dir = await dirOf($)
388    if (dir === null) return ran
389
390    const cwd = await $.session.cwd()
391    if (isRead) {
392      const now = await $.clock.now()
393      const key = absolute(path, cwd).toLowerCase()
394      await update($, watch, kept => ({
395        ...kept,
396        seen: capped({ ...kept.seen, [key]: now }),
397        meets: kept.meets.map(meet => (meet.key === key ? { ...meet, state: 're-read' as const } : meet)),
398      }))
399
400      return ran
401    }
402
403    const id = await idOf($)
404    if (id === undefined) return ran
405
406    const now = await $.clock.now()
407    if (isEdit) {
408      const whole = absolute(path, cwd)
409      const key = whole.toLowerCase()
410      await update($, watch, kept => ({
411        ...kept,
412        mine: { ...kept.mine, [key]: { path: whole, at: now } },
413        seen: capped({ ...kept.seen, [key]: now }),
414      }))
415      await publish($, dir, id, now)
416
417      return ran
418    }
419
420    const peers = await scan($, dir, id, now)
421    const mine = await touched($, command, cwd, started, now, peers)
422    if (Object.keys(mine).length === 0) return ran
423
424    const { seen, meets } = await read($, watch)
425    const fresh = Object.entries(mine).flatMap(([key, held]): CollisionMeet[] => {
426      const peer = peers[key]
427      const known = Math.max(seen[key] ?? 0, meets.find(meet => meet.key === key)?.at ?? 0)
428
429      return peer === undefined || peer.at <= known ? [] : [{ key, path: held.path, place: peer.place, at: peer.at, state: 'changed' }]
430    })
431    await update($, watch, kept => ({ ...kept, mine: { ...kept.mine, ...mine }, meets: fresh.reduce(met, kept.meets) }))
432    await publish($, dir, id, now)
433    if (fresh.length === 0) return ran
434
435    return {
436      ...ran,
437      context: [
438        ...(ran.context ?? []),
439        ...fresh.map(
440          meet =>
441            `collision-widget: this command changed ${lastOf(meet.path)}, which another Claude Code session (in ${meet.place}) edited ${span(now - meet.at)} ago. Read the file again before editing it further, and tell the user.`,
442        ),
443      ],
444    }
445  })
446
447  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e, next) =>
448    show($, $.ui.resolve(e), await next(e), 'side', e.props.bodyColumns),
449  )
450
451  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) =>
452    e.props.hasSurvey ? next(e) : show($, $.ui.resolve(e), await next(e), 'above', e.props.bodyColumns),
453  )
454
455  on('ui.render', { component: 'PromptHint' }, async ($, e, next) =>
456    show($, $.ui.resolve(e), await next(e), 'below', e.viewport?.columns ?? 80),
457  )
458}
459
hooks/lib.ts 45 lines
1const MIN_CARD = 20
2const BARS = '▁▂▃▄▅▆▇█'
3
4export const fit = (wanted: number, columns: number): number => Math.min(wanted, Math.max(MIN_CARD, columns))
5
6export const plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? '' : 's'}`
7
8export const span = (ms: number): string => {
9  const seconds = Math.max(0, Math.round(ms / 1000))
10  if (seconds < 60) return `${seconds}s`
11  const minutes = Math.floor(seconds / 60)
12  if (minutes < 60) return `${minutes}m ${String(seconds % 60).padStart(2, '0')}s`
13  const hours = Math.floor(minutes / 60)
14  if (hours < 24) return `${hours}h ${String(minutes % 60).padStart(2, '0')}m`
15
16  return `${Math.floor(hours / 24)}d ${hours % 24}h`
17}
18
19export const spark = (values: readonly number[], width: number): string => {
20  const shown = width > 0 ? values.slice(-width) : []
21  const top = Math.max(...shown, 0)
22
23  return shown
24    .map(value => (top <= 0 ? BARS[0] : BARS[Math.min(BARS.length - 1, Math.round((Math.max(0, value) / top) * (BARS.length - 1)))]))
25    .join('')
26}
27
28export const hash = (text: string): number => {
29  let held = 2166136261
30  for (const letter of text) held = Math.imul(held ^ (letter.codePointAt(0) ?? 0), 16777619)
31
32  return held >>> 0
33}
34
35export const shade = (color: number, factor: number): number =>
36  (Math.round((color >> 16) * factor) << 16) |
37  (Math.round(((color >> 8) & 255) * factor) << 8) |
38  Math.round((color & 255) * factor)
39
40export const folder = (path: string): string => {
41  const flat = path.replaceAll('\\', '/').replace(/\/+$/, '')
42
43  return /^[a-z]:/i.test(flat) ? flat.toLowerCase() : flat
44}
45
types/index.d.ts 29 lines
1export type CollisionSwitch = boolean
2
3export type CollisionHeld = { path: string; at: number }
4
5export type CollisionMeet = {
6  key: string
7  path: string
8  place: string
9  at: number
10  state: 'stopped' | 'changed' | 're-read'
11}
12
13export type CollisionWatch = {
14  dir?: string | null
15  slot: string
16  wrote: string | null
17  mine: Record<string, CollisionHeld>
18  seen: Record<string, number>
19  meets: CollisionMeet[]
20  others: number
21  isBlind: boolean
22}
23
24declare module 'claude-code' {
25  interface PluginState {
26    'collision-widget': { isOn: CollisionSwitch; watch: CollisionWatch }
27  }
28}
29