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

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.
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.
Required by every widget.
| Plugin | Command | What 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 |
What Claude is doing and what it is costing.
| Plugin | Command | What 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-widget | A 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 |
The state of the working tree.
| Plugin | Command | What it shows | |||||
|---|---|---|---|---|---|---|---|
file-tree-widget | /file-tree-widget | The project directory; folders expand on click | |||||
git-widget | /git-widget | Branch, 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-widget | The commits made since the session started | |||||
todos-widget | /todos-widget | TODO, 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 |
Clocks, timers and reminders that do not depend on the session.
| Plugin | Command | What 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 |
Pixel art that reacts to turns, tool calls, checks and context usage.
| Plugin | Command | What 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 |
Abstract pictures driven by tool activity.
| Plugin | Command | What 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 |
Snake, 2048 and Tetris play themselves until you click the board and take the keys.
| Plugin | Command | What 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 |
| Plugin | Command | What 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.
/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.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.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.
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.
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.
MIT
hooks/register.tsx 462 lines1import { atom, read, update } from 'claude-code'
2import type { Elements, EngineInterface, PluginState, Register, RenderElement, RenderSurface, Timer } from 'claude-code'
3import type { WidgetsPlace } from 'widgets'
4
5import { fit, plural, span } from './lib'
6
7type Tags = Pick<Elements[RenderSurface], 'Box' | 'Text'>
8type Report = PluginState['outage-widget']['reports'][number]
9type Incident = NonNullable<Report['incident']>
10type Provider = {
11 key: string
12 name: string
13 short: string
14 page: string
15 hosts: readonly string[]
16 alone: readonly string[]
17 programs: readonly string[]
18 verbs: readonly string[]
19 parts: RegExp
20}
21type Row = { text: string; color?: 'red' | 'yellow'; isDim?: boolean }
22type Drawn = { note?: string; rows: Row[] }
23
24const PANE = 'widgets'
25const CARD_COLUMNS = 40
26const CARD_EDGE = 4
27const WIDE_COLUMNS = 30
28const USAGE = 'Usage: /outage-widget [on|off|check|clear]'
29const OFF = 'Outage is off.'
30const NOTHING = 'Nothing to check yet: no network command has failed.'
31const EMPTY_WIDE = "No network failure yet. When a push or install fails on the network, the provider's status page is checked and its answer shows here."
32const EMPTY_SHORT = "No network failure yet. A failed push or install is checked against the provider's status page."
33const LAG = 'A status page can lag an outage.'
34const FEED = '/api/v2/incidents/unresolved.json'
35const LIMIT_MS = 2000
36const FRESH_MS = 180_000
37const POLL_MS = 60_000
38const MOST_REPORTS = 4
39const MOST_PARTS = 3
40const NAME_CHARS = 80
41const PART_CHARS = 40
42const HOST_CHARS = 60
43const IMPACTS = ['minor', 'major', 'critical'] as const
44const GIT_VERBS = ['push', 'pull', 'fetch', 'clone', 'ls-remote']
45const NODE_VERBS = ['install', 'i', 'ci', 'add', 'update', 'upgrade', 'publish', 'dlx', 'x', 'view', 'info', 'outdated', 'audit']
46const PYTHON_VERBS = ['install', 'download', 'add', 'sync', 'lock', 'update', 'upgrade', 'publish', 'upload', 'pip', 'tool']
47const CARGO_VERBS = ['build', 'check', 'install', 'add', 'update', 'fetch', 'publish', 'search', 'generate-lockfile']
48const PROVIDERS: readonly Provider[] = [
49 {
50 key: 'github',
51 name: 'GitHub',
52 short: 'GitHub',
53 page: 'www.githubstatus.com',
54 hosts: ['github.com', 'githubusercontent.com'],
55 alone: ['gh'],
56 programs: [],
57 verbs: [],
58 parts: /^(?:git operations|api requests)$/i,
59 },
60 {
61 key: 'npm',
62 name: 'npm',
63 short: 'npm',
64 page: 'status.npmjs.org',
65 hosts: ['npmjs.org', 'npmjs.com'],
66 alone: ['npx', 'bunx'],
67 programs: ['npm', 'pnpm', 'yarn', 'bun'],
68 verbs: NODE_VERBS,
69 parts: /^package (?:installation|publishing)$/i,
70 },
71 {
72 key: 'pypi',
73 name: 'PyPI',
74 short: 'PyPI',
75 page: 'status.python.org',
76 hosts: ['pypi.org', 'pythonhosted.org'],
77 alone: [],
78 programs: ['pip', 'pip3', 'pipx', 'uv', 'poetry', 'twine'],
79 verbs: PYTHON_VERBS,
80 parts: /^(?:pypi|files\.pythonhosted\.org)/i,
81 },
82 {
83 key: 'crates',
84 name: 'crates.io',
85 short: 'crates',
86 page: 'status.crates.io',
87 hosts: ['crates.io'],
88 alone: [],
89 programs: ['cargo'],
90 verbs: CARGO_VERBS,
91 parts: /^crates\.io$/i,
92 },
93]
94const NETWORK =
95 /timed out|timeout|ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|ENOTFOUND|ENETUNREACH|socket hang up|connection reset|connection refused|connection closed|could not resolve host|name resolution|network is unreachable|remote end hung up|unexpected disconnect|early EOF|could not read from remote repository|internal server error|bad gateway|service unavailable|(?:error|status|HTTP|returned)[^\n]{0,20}?\b50[0234]\b|\bE50[0234]\b/i
96const VETO = /permission denied|authentication failed|non-fast-forward|fetch first|\[rejected\]|\bE?40[134]\b/i
97const UNSAFE = /[\p{Cc}\p{Zl}\p{Zp}"]/gu
98const site = { plugin: 'widgets', key: 'site' } as const
99const widths = { plugin: 'widgets', key: 'widths' } as const
100const isOn = atom({ plugin: 'outage-widget', key: 'isOn' } as const, false)
101const reports = atom({ plugin: 'outage-widget', key: 'reports' } as const, [])
102
103let timer: Timer | undefined
104
105const fields = (value: unknown): Record<string, unknown> => (typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {})
106
107const clean = (value: unknown, most: number): string =>
108 (typeof value === 'string' ? value : '').replace(UNSAFE, ' ').replace(/\s+/g, ' ').trim().slice(0, most)
109
110const cut = (text: string, room: number): string => (text.length <= room ? text : `${text.slice(0, room - 1)}…`)
111
112const wrapped = (text: string, room: number): string[] =>
113 text.split(' ').reduce<string[]>((rows, word) => {
114 const last = rows.at(-1)
115
116 return last !== undefined && last.length + 1 + word.length <= room ? [...rows.slice(0, -1), `${last} ${word}`] : [...rows, word]
117 }, [])
118
119const squeezed = (host: string, room: number): string => {
120 if (host.length <= room) return host
121 const tail = Math.floor((room - 1) / 2)
122
123 return `${host.slice(0, room - 1 - tail)}…${host.slice(host.length - tail)}`
124}
125
126const known = (key: string): Provider | undefined => PROVIDERS.find(provider => provider.key === key)
127
128const hosted = (host: string): Provider | undefined =>
129 PROVIDERS.find(provider => provider.hosts.some(own => host === own || host.endsWith(`.${own}`)))
130
131const stamp = (value: unknown, now: number): number | undefined => {
132 const at = typeof value === 'string' ? Date.parse(value) : Number.NaN
133
134 return Number.isFinite(at) && at <= now ? at : undefined
135}
136
137const kept = (raw: unknown, provider: Provider, now: number): { incident: Incident; isRelated: boolean } => {
138 const record = fields(raw)
139 const parts = (Array.isArray(record.components) ? record.components : []).map(part => clean(fields(part).name, PART_CHARS)).filter(part => part !== '')
140 const own = parts.filter(part => provider.parts.test(part))
141 const name = clean(record.name, NAME_CHARS) || 'unnamed incident'
142
143 return {
144 isRelated: parts.length === 0 || own.length > 0,
145 incident: {
146 id: clean(record.id, NAME_CHARS) || name,
147 name,
148 impact: IMPACTS.find(impact => impact === record.impact) ?? 'unknown',
149 startedAt: stamp(record.started_at, now) ?? stamp(record.created_at, now) ?? now,
150 components: [...own, ...parts.filter(part => !own.includes(part))].slice(0, MOST_PARTS),
151 },
152 }
153}
154
155const listed = (text: string): unknown[] | undefined => {
156 try {
157 const body: unknown = JSON.parse(text)
158 const incidents = fields(body).incidents
159
160 return Array.isArray(incidents) ? incidents : undefined
161 } catch {
162 return undefined
163 }
164}
165
166const judged = (provider: Provider, list: unknown[] | undefined, now: number): Report => {
167 const base = { key: provider.key, name: provider.name, checkedAt: now, toldId: null }
168 if (list === undefined) return { ...base, verdict: 'unread', incident: null }
169
170 const found = list.map(raw => kept(raw, provider, now))
171 const related = found.find(each => each.isRelated)
172 if (related !== undefined) return { ...base, verdict: 'incident', incident: related.incident }
173
174 return found[0] === undefined ? { ...base, verdict: 'clear', incident: null } : { ...base, verdict: 'elsewhere', incident: found[0].incident }
175}
176
177const checked = async ($: EngineInterface, provider: Provider, signal?: AbortSignal): Promise<Report> => {
178 const answer = await Promise.race([
179 $.http.fetch(`https://${provider.page}${FEED}`).catch(() => undefined),
180 $.clock.sleep(LIMIT_MS, signal === undefined ? {} : { signal }).then(
181 () => undefined,
182 () => undefined,
183 ),
184 ])
185
186 return judged(provider, answer?.ok === true ? listed(answer.text) : undefined, await $.clock.now())
187}
188
189const again = async ($: EngineInterface, held: readonly Report[]): Promise<Report[]> =>
190 Promise.all(
191 held.flatMap(report => {
192 const provider = report.verdict === 'stranger' ? undefined : known(report.key)
193
194 return provider === undefined ? [] : [checked($, provider)]
195 }),
196 )
197
198const taken = (old: Report | undefined, fresh: Report): Report =>
199 old === undefined ? fresh : fresh.verdict === 'unread' && old.verdict === 'incident' ? old : { ...fresh, toldId: old.toldId }
200
201const newest = (held: readonly Report[]): Report[] => [...held].sort((first, second) => second.checkedAt - first.checkedAt).slice(0, MOST_REPORTS)
202
203const merged = (held: readonly Report[], found: readonly Report[]): Report[] =>
204 newest([
205 ...found.map(fresh => taken(held.find(report => report.key === fresh.key), fresh)),
206 ...held.filter(report => !found.some(fresh => fresh.key === report.key)),
207 ])
208
209const refreshed = (held: readonly Report[], found: readonly Report[]): Report[] =>
210 newest(
211 held.map(report => {
212 const fresh = found.find(each => each.key === report.key)
213
214 return fresh === undefined ? report : taken(report, fresh)
215 }),
216 )
217
218const told = (held: readonly Report[], keys: readonly string[]): Report[] =>
219 held.map(report => (report.verdict === 'incident' && report.incident !== null && keys.includes(report.key) ? { ...report, toldId: report.incident.id } : report))
220
221const ordered = (held: readonly Report[]): Report[] => [
222 ...held.filter(report => report.verdict === 'incident'),
223 ...held.filter(report => report.verdict !== 'incident'),
224]
225
226const age = (report: Report, incident: Incident): string => span(report.checkedAt - incident.startedAt)
227
228const sentence = (provider: Provider, report: Report, incident: Incident): string => {
229 const on = incident.components.length === 0 ? '' : `, on ${incident.components.join(', ')}`
230
231 return `[outage-widget] ${provider.name}'s status page (https://${provider.page}) reports an open incident: "${incident.name}", impact ${incident.impact}${on}, open ${age(report, incident)}. The words in quotes are the provider's.`
232}
233
234const line = (report: Report): string => {
235 if (report.verdict === 'stranger') return `No status page known for ${report.name}.`
236 if (report.verdict === 'unread') return `Could not check ${report.name}'s status.`
237 if (report.incident === null || report.verdict === 'clear') return `${report.name} reports no incident.`
238 if (report.verdict === 'elsewhere') return `${report.name}: an incident on another part, "${report.incident.name}".`
239
240 return `${report.name}: "${report.incident.name}", ${report.incident.impact}, open ${age(report, report.incident)}.`
241}
242
243const remotes = (stdout: string): string[] =>
244 stdout.split('\n').flatMap(row => {
245 const url = row.trim().split(/\s+/)[1] ?? ''
246 const authority = /^[a-z][a-z0-9+.-]*:\/\/([^/]*)/i.exec(url)?.[1]
247 const host = authority === undefined ? /^(?:[^@/:]+@)?([^@/:]+):/.exec(url)?.[1] : authority.slice(authority.lastIndexOf('@') + 1).replace(/:\d*$/, '')
248
249 return host !== undefined && /^[a-z0-9.-]{2,}$/i.test(host) ? [host.toLowerCase().slice(0, HOST_CHARS)] : []
250 })
251
252const named = async ($: EngineInterface, command: string, text: string): Promise<{ providers: Provider[]; stranger?: string }> => {
253 const both = `${command}\n${text}`.toLowerCase()
254 const parts = command.split(/[;&|()\n]+/).map(part => part.trim().toLowerCase().split(/\s+/))
255 const byHost = PROVIDERS.filter(provider => provider.hosts.some(host => both.includes(host)))
256 const byWord = PROVIDERS.filter(provider =>
257 parts.some(words =>
258 words.some((word, at) => provider.alone.includes(word) || (provider.programs.includes(word) && provider.verbs.includes(words.slice(at + 1).find(next => !next.startsWith('-')) ?? ''))),
259 ),
260 )
261 const isGit = parts.some(words => words.includes('git') && words.slice(words.indexOf('git') + 1).some(word => GIT_VERBS.includes(word)))
262 if (!isGit || byHost.length > 0) return { providers: PROVIDERS.filter(provider => byHost.includes(provider) || byWord.includes(provider)) }
263
264 const listing = await $.process.run(['git', 'remote', '-v'], { timeoutMs: LIMIT_MS }).catch(() => undefined)
265 const hosts = listing?.exitCode === 0 ? remotes(listing.stdout) : []
266 const byRemote = hosts.flatMap(host => hosted(host) ?? [])
267 const providers = PROVIDERS.filter(provider => byWord.includes(provider) || byRemote.includes(provider))
268
269 return byRemote.length > 0 || hosts[0] === undefined ? { providers } : { providers, stranger: hosts[0] }
270}
271
272// A hook that has waited reads the switch as it was when the hook began; update answers with the switch as it is now.
273const lit = async ($: EngineInterface): Promise<boolean> => update($, isOn, shown => shown)
274
275const sync = async ($: EngineInterface): Promise<void> => {
276 const isWanted = (await read($, isOn)) && (await read($, reports)).some(report => report.verdict === 'incident')
277 if (isWanted && timer === undefined) {
278 timer = $.clock.every(POLL_MS, () => {
279 void poll($)
280 })
281 }
282 if (!isWanted && timer !== undefined) {
283 timer.cancel()
284 timer = undefined
285 }
286}
287
288const poll = async ($: EngineInterface): Promise<void> => {
289 const open = (await read($, reports)).filter(report => report.verdict === 'incident')
290 const found = (await again($, open)).filter(fresh => fresh.verdict !== 'unread')
291 if (!(await lit($))) return
292
293 const after = await update($, reports, held => refreshed(held, found))
294 for (const fresh of found) {
295 const isShown = after.some(report => report.key === fresh.key && report.verdict === fresh.verdict && report.checkedAt === fresh.checkedAt)
296 if (isShown && fresh.verdict === 'clear') $.ui.toast(`${fresh.name} reports the incident resolved.`)
297 if (isShown && fresh.verdict === 'elsewhere') $.ui.toast(`${fresh.name} reports the incident resolved; another is open elsewhere.`)
298 }
299 await sync($)
300}
301
302const strange = (host: string, inner: number): string => {
303 const wide = `No status page known: ${host}`
304 if (inner >= WIDE_COLUMNS && wide.length <= inner) return wide
305 const short = `no page: ${host}`
306
307 return short.length <= inner ? short : `${squeezed(host, inner - 6)}: none`
308}
309
310const drawn = (report: Report, inner: number): Row[] => {
311 const isWide = inner >= WIDE_COLUMNS
312 const short = known(report.key)?.short ?? report.name
313 const who = isWide ? report.name : short
314 const settled = (wide: string, narrow: string): string => (isWide && wide.length <= inner ? wide : cut(narrow, inner))
315
316 if (report.verdict === 'stranger') return [{ text: strange(report.name, inner), isDim: true }]
317 if (report.verdict === 'unread') return [{ text: settled(`Could not check ${report.name}'s status`, `${short}: unread`), color: 'yellow' }]
318 if (report.incident === null || report.verdict === 'clear') return [{ text: settled(`${report.name} reports no incident`, `${short}: quiet`) }]
319 if (report.verdict === 'elsewhere') {
320 return [{ text: cut(isWide ? `${who}: other incident (${report.incident.components[0] ?? report.incident.name})` : `${who}: other`, inner) }]
321 }
322
323 const open = `open ${age(report, report.incident)}`
324 const part = report.incident.components[0]
325
326 return [
327 { text: cut(`${who}: ${report.incident.name}`, inner), color: 'red' },
328 { text: cut(isWide ? `${report.incident.impact}, ${open}${part === undefined ? '' : `, ${part}`}` : open, inner), isDim: true },
329 ]
330}
331
332const draw = (held: readonly Report[], inner: number): Drawn => {
333 const isWide = inner >= WIDE_COLUMNS
334 if (held.length === 0) return { rows: wrapped(isWide ? EMPTY_WIDE : EMPTY_SHORT, inner).map(text => ({ text })) }
335
336 const open = held.filter(report => report.verdict === 'incident').length
337 const hasLag = isWide && open === 0 && held.some(report => report.verdict !== 'stranger')
338
339 return {
340 ...(open === 0 ? {} : { note: isWide ? plural(open, 'incident') : `${open} open` }),
341 rows: [...ordered(held).flatMap(report => drawn(report, inner)), ...(hasLag ? [{ text: LAG, isDim: true }] : [])],
342 }
343}
344
345const show = async (
346 $: EngineInterface,
347 { Box, Text }: Tags,
348 beneath: RenderElement,
349 place: WidgetsPlace,
350 columns: number,
351): Promise<RenderElement> => {
352 if (!(await read($, isOn))) return beneath
353 if ((await $.state.get(site)).value !== place) return beneath
354
355 const width = fit((await $.state.get(widths)).value?.['outage-widget'] ?? CARD_COLUMNS, columns)
356 const { note, rows } = draw(await read($, reports), width - CARD_EDGE)
357
358 return $.widgets.card({
359 beneath,
360 width,
361 title: 'Outage',
362 note,
363 body: (
364 <Box flexDirection="column">
365 {rows.map(row => (
366 <Text color={row.color} dimColor={row.isDim === true} wrap="truncate-end">
367 {row.text}
368 </Text>
369 ))}
370 </Box>
371 ),
372 })
373}
374
375export const register: Register = on => {
376 on('session.start', async ($, e, next) => {
377 await $.command.register({
378 name: 'outage-widget',
379 description: 'Toggle the Outage card, check the status pages on it again, or clear it',
380 argumentHint: '[on|off|check|clear]',
381 })
382 if ((await $.store.get('isOn')) === true) await update($, isOn, () => true)
383 await sync($)
384
385 return next(e)
386 })
387
388 on('command.run', { command: 'outage-widget' }, async ($, e) => {
389 const arg = e.args.trim().toLowerCase()
390 if (arg === 'check' || arg === 'clear') {
391 if (!(await read($, isOn))) return { text: OFF }
392 if (arg === 'clear') {
393 await update($, reports, () => [])
394 await sync($)
395
396 return { text: 'Outage cleared.' }
397 }
398
399 const held = await read($, reports)
400 if (held.length === 0) return { text: NOTHING }
401
402 const found = await again($, held)
403 if (!(await lit($))) return { text: OFF }
404 const after = await update($, reports, was => refreshed(was, found))
405 await sync($)
406
407 return { text: after.length === 0 ? NOTHING : ordered(after).map(line).join('\n') }
408 }
409 if (arg !== '' && arg !== 'on' && arg !== 'off') return { text: USAGE }
410
411 const isShown = await update($, isOn, shown => (arg === '' ? !(shown ?? false) : arg === 'on'))
412 await $.store.set('isOn', isShown)
413 if (!isShown) await update($, reports, () => [])
414 await sync($)
415
416 return { text: isShown ? 'Outage on; /widgets places it.' : 'Outage off.' }
417 })
418
419 on('tool.call', async ($, e, next) => {
420 if (!(await read($, isOn))) return next(e)
421 if (e.tool !== 'Bash' && e.tool !== 'PowerShell') return next(e)
422
423 const ran = await next(e)
424 if (ran.isError !== true || typeof ran.text !== 'string' || !NETWORK.test(ran.text) || VETO.test(ran.text)) return ran
425 if (!(await lit($))) return ran
426
427 const { providers, stranger } = await named($, e.command, ran.text)
428 if (providers.length === 0 && stranger === undefined) return ran
429
430 const now = await $.clock.now()
431 const held = await read($, reports)
432 const stale = providers.filter(provider => !held.some(report => report.key === provider.key && report.verdict !== 'unread' && now - report.checkedAt < FRESH_MS))
433 const found = await Promise.all(stale.map(provider => checked($, provider, next.signal)))
434 if (!(await lit($))) return ran
435
436 const unknown: Report[] = stranger === undefined ? [] : [{ key: stranger, name: stranger, verdict: 'stranger', checkedAt: now, incident: null, toldId: null }]
437 const after = await update($, reports, was => merged(was, [...found, ...unknown]))
438 const sentences = providers.flatMap(provider => {
439 const report = after.find(each => each.key === provider.key)
440
441 return report?.verdict === 'incident' && report.incident !== null && report.incident.id !== report.toldId ? [sentence(provider, report, report.incident)] : []
442 })
443 const keys = providers.map(provider => provider.key)
444 if (sentences.length > 0) await update($, reports, was => told(was, keys))
445 await sync($)
446
447 return sentences.length === 0 ? ran : { deny: `${ran.text}\n\n${sentences.join('\n')}` }
448 })
449
450 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e, next) =>
451 show($, $.ui.resolve(e), await next(e), 'side', e.props.bodyColumns),
452 )
453
454 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) =>
455 e.props.hasSurvey ? next(e) : show($, $.ui.resolve(e), await next(e), 'above', e.props.bodyColumns),
456 )
457
458 on('ui.render', { component: 'PromptHint' }, async ($, e, next) =>
459 show($, $.ui.resolve(e), await next(e), 'below', e.viewport?.columns ?? 80),
460 )
461}
462hooks/lib.ts 45 lines1const 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}
45types/index.d.ts 24 lines1export type OutageSwitch = boolean
2
3declare module 'claude-code' {
4 interface PluginState {
5 'outage-widget': {
6 isOn: OutageSwitch
7 reports: {
8 key: string
9 name: string
10 verdict: 'incident' | 'elsewhere' | 'clear' | 'unread' | 'stranger'
11 checkedAt: number
12 incident: {
13 id: string
14 name: string
15 impact: 'minor' | 'major' | 'critical' | 'unknown'
16 startedAt: number
17 components: string[]
18 } | null
19 toldId: string | null
20 }[]
21 }
22 }
23}
24