Search Claude Code mods, see what each can reach before you install it, and install, toggle, update or remove them with /mods.

A mod manager for Claude Code. Mods are plugins that run code in your session: they can run programs, read the conversation and change what the model sees. Type /mods to search the mods published on GitHub and in your marketplaces, see what each one can reach before you install it, and install, switch off, update or remove mods without leaving the session. Every change is reviewed first, and toggles, installs and removals can be undone.
--plugin-dir, CLAUDE_CODE_PLUGIN_DIRS, your skills folder, folder marketplaces): validate, test, reload, share./mods list, info, doctor, export and the write commands answer as text for scripts and -p runs.
claude CLI (claude plugin list, install, enable, disable, update, uninstall, marketplace add/update, validate, test) for the changes you confirm, and Claude Code's plugin reload. It never writes a settings file and never passes -y; a command a marketplace declares runs only after you confirm that exact command (its sha256).https://raw.githubusercontent.com/: two indexes from ayagmar/claude-modmgr, branch catalog-index (v1.json for catalogue entries, mods-v2.json for community mods, about once a session and at most every 12 hours within one) and, for a catalogue entry, its hooks/hooks.json and .claude-plugin/plugin.json at the entry's pinned commit. These reads are off under CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC or with the detectRemote option off. Update checks (updateCheckHours, default 6, 0 turns them off) ask the CLI to refresh your marketplaces.--debug, its own debug log for failed hooks. It never reads your settings or the CLI's own files.The full threat model is in docs/SECURITY.md.
Needs a session on Claude Code 2.1.284 or newer (the desktop app runs its own pinned one) and the claude CLI on your path at 2.1.292 or newer. MIT licensed. Source, issues and the landing page: github.com/ayagmar/claude-modmgr · ayagmar.github.io/claude-modmgr.
hooks/register.tsx 404 lines1// The only file that spells `$` (the validator refuses `$` passed across an
2// import). It builds ports from `$` in top-level builders, one per noun (a
3// `$`-taking builder inside `register()` is refused), registers each event
4// once (a module may hook an event only once without a matcher), and
5// delegates to services. `.catch` handlers never touch `$`: on re-entry their
6// `$` calls reject, so they pass through or answer plainly.
7
8import {
9 atom,
10 type EngineInterface,
11 type Register,
12 type RenderInput,
13 read,
14 update,
15} from 'claude-code'
16import { parseConfig } from './domain/config.ts'
17import { devOfKey } from './domain/dev.ts'
18import { foundOfKey } from './domain/discover.ts'
19import { healthOfKey } from './domain/health.ts'
20import { INITIAL, type ModmgrState, type StateKey } from './domain/state.ts'
21import { FILTER_KEY, rowOfKey } from './domain/view.ts'
22import type {
23 ClockPort,
24 CommandPort,
25 EnvPort,
26 FsPort,
27 HttpPort,
28 Ports,
29 ProcessPort,
30 SessionPort,
31 StatePort,
32 StorePort,
33 UiPort,
34} from './ports.ts'
35import { type Actions, createActions } from './services/actions.ts'
36import { modsCommand } from './services/commands.ts'
37import { MODS_DESCRIPTION, onSessionStart, onTurnEnd, onTurnStart } from './services/lifecycle.ts'
38import { createRuntime, newOwnerId, type Runtime } from './services/runtime.ts'
39import { drawBand } from './ui/Band.tsx'
40import type { El, ViewPorts } from './ui/kit.tsx'
41import { drawPane, overlayEnd, pageSize } from './ui/Pane.tsx'
42
43// One atom per key, its plugin and key spelled as literals (the validator lists
44// them) and a shape tag that changes with the key's type (domain/state.ts).
45const MODS = atom({ plugin: 'modmgr', key: 'mods' } as const, INITIAL.mods, { shape: 'mods/2' })
46const DETAIL = atom({ plugin: 'modmgr', key: 'detail' } as const, INITIAL.detail, {
47 shape: 'detail/2',
48})
49const CATALOG_PAGE = atom({ plugin: 'modmgr', key: 'catalogPage' } as const, INITIAL.catalogPage, {
50 shape: 'catalogPage/5',
51})
52const DETECT = atom({ plugin: 'modmgr', key: 'detect' } as const, INITIAL.detect, {
53 shape: 'detect/2',
54})
55const QUEUE = atom({ plugin: 'modmgr', key: 'queue' } as const, INITIAL.queue, { shape: 'queue/1' })
56const SYNC = atom({ plugin: 'modmgr', key: 'sync' } as const, INITIAL.sync, { shape: 'sync/2' })
57const VIEW = atom({ plugin: 'modmgr', key: 'view' } as const, INITIAL.view, { shape: 'view/8' })
58const REVIEW = atom({ plugin: 'modmgr', key: 'review' } as const, INITIAL.review, {
59 shape: 'review/4',
60})
61const ATTENTION = atom({ plugin: 'modmgr', key: 'attention' } as const, INITIAL.attention, {
62 shape: 'attention/2',
63})
64const DEGRADED = atom({ plugin: 'modmgr', key: 'degraded' } as const, INITIAL.degraded, {
65 shape: 'degraded/1',
66})
67const DEV = atom({ plugin: 'modmgr', key: 'dev' } as const, INITIAL.dev, { shape: 'dev/2' })
68const HEALTH = atom({ plugin: 'modmgr', key: 'health' } as const, INITIAL.health, {
69 shape: 'health/1',
70})
71
72type Change<K extends StateKey> = (value: ModmgrState[K]) => ModmgrState[K]
73
74function statePorts($: EngineInterface): StatePort {
75 // `read`/`update` take an atom named directly (the validator refuses a computed one).
76 const readers: { [K in StateKey]: () => Promise<ModmgrState[K]> } = {
77 mods: () => read($, MODS),
78 detail: () => read($, DETAIL),
79 catalogPage: () => read($, CATALOG_PAGE),
80 detect: () => read($, DETECT),
81 queue: () => read($, QUEUE),
82 sync: () => read($, SYNC),
83 view: () => read($, VIEW),
84 review: () => read($, REVIEW),
85 attention: () => read($, ATTENTION),
86 degraded: () => read($, DEGRADED),
87 dev: () => read($, DEV),
88 health: () => read($, HEALTH),
89 }
90 const writers: { [K in StateKey]: (change: Change<K>) => Promise<ModmgrState[K]> } = {
91 mods: change => update($, MODS, change),
92 detail: change => update($, DETAIL, change),
93 catalogPage: change => update($, CATALOG_PAGE, change),
94 detect: change => update($, DETECT, change),
95 queue: change => update($, QUEUE, change),
96 sync: change => update($, SYNC, change),
97 view: change => update($, VIEW, change),
98 review: change => update($, REVIEW, change),
99 attention: change => update($, ATTENTION, change),
100 degraded: change => update($, DEGRADED, change),
101 dev: change => update($, DEV, change),
102 health: change => update($, HEALTH, change),
103 }
104 return {
105 read: key => readers[key](),
106 update: <K extends StateKey>(key: K, change: Change<K>) =>
107 (writers[key] as (change: Change<K>) => Promise<ModmgrState[K]>)(change),
108 }
109}
110
111function processPorts($: EngineInterface): ProcessPort {
112 return {
113 run: (argv, init) => $.process.run(argv, init),
114 spawn: (argv, init) => $.process.spawn({ argv, ...init }),
115 }
116}
117
118function storePorts($: EngineInterface): StorePort {
119 return {
120 get: key => $.store.get(key),
121 set: (key, value) => $.store.set(key, value),
122 delete: key => $.store.delete(key),
123 keys: () => $.store.keys(),
124 }
125}
126
127function clockPorts($: EngineInterface): ClockPort {
128 return {
129 now: () => $.clock.now(),
130 after: (ms, fn) => $.clock.after(ms, fn),
131 every: (ms, fn) => $.clock.every(ms, fn),
132 }
133}
134
135function envPorts($: EngineInterface): EnvPort {
136 return {
137 nonessentialTraffic: () => $.env.get('CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC'),
138 configDir: () => $.env.get('CLAUDE_CONFIG_DIR'),
139 home: () => $.env.get('HOME'),
140 indexUrl: () => $.env.get('MODMGR_INDEX_URL'),
141 }
142}
143
144function sessionPorts($: EngineInterface): SessionPort {
145 return {
146 root: () => $.session.root(),
147 ownRoot: async () => $.plugin.root,
148 cwd: () => $.session.cwd(),
149 id: () => $.session.id(),
150 repo: () => $.session.repo(),
151 surfaces: () => $.session.surfaces(),
152 version: () => $.session.version(),
153 }
154}
155
156function commandPorts($: EngineInterface): CommandPort {
157 return {
158 registerMods: async () => {
159 await $.command.register({
160 name: 'mods',
161 description: MODS_DESCRIPTION,
162 argumentHint:
163 '[list | info | install | remove | update | enable | disable | doctor | export | apply]',
164 })
165 },
166 reloadPlugins: async () => (await $.command.run({ command: 'reload-plugins' })).text,
167 list: () => $.command.list(),
168 }
169}
170
171function uiPorts($: EngineInterface): UiPort {
172 return {
173 debug: text => $.ui.log(text, { to: 'debug' }),
174 panes: () => $.ui.panes(),
175 open: args => $.ui.open(args),
176 close: id => $.ui.close({ id }),
177 focus: async (requestId, key) => {
178 const moved = await $.ui.focus({ requestId, key })
179 // The engine doesn't raise modmgr's own `ui.focus` hook for this move.
180 if (moved.deny === undefined) noteRing(key)
181 return moved
182 },
183 copy: (text, surface) => $.ui.copy(surface === undefined ? { text } : { text, surface }),
184 status: text => $.ui.status(text),
185 notify: async text => {
186 try {
187 const sent = await $.ui.notify(text)
188 if (!sent.isSent) $.ui.log(`modmgr: notification not sent: ${sent.reason}`, { to: 'debug' })
189 return sent.isSent
190 } catch (error) {
191 // Claude Code before 2.1.296 has no $.ui.notify.
192 $.ui.log(`modmgr: notification not sent: ${String(error)}`, { to: 'debug' })
193 return false
194 }
195 },
196 }
197}
198
199function httpPorts($: EngineInterface): HttpPort {
200 return {
201 get: async (url, maxBytes) => {
202 const response = await $.http.fetch(url, { headers: { Range: `bytes=0-${maxBytes}` } })
203 // The file's start, whole when it is short; an empty file can't satisfy a range.
204 if (response.status === 206) return { status: 200, text: response.text }
205 if (response.status === 416) return { status: 200, text: '' }
206 return { status: response.status, text: response.text }
207 },
208 }
209}
210
211function fsPorts($: EngineInterface): FsPort {
212 return {
213 read: path => $.fs.read(path),
214 list: async path =>
215 (await $.fs.list(path)).map(entry => ({ name: entry.name, kind: entry.kind })),
216 }
217}
218
219function portsOf($: EngineInterface): Ports {
220 return {
221 process: processPorts($),
222 state: statePorts($),
223 store: storePorts($),
224 clock: clockPorts($),
225 env: envPorts($),
226 session: sessionPorts($),
227 command: commandPorts($),
228 ui: uiPorts($),
229 http: httpPorts($),
230 fs: fsPorts($),
231 }
232}
233
234function actionsOf($: EngineInterface): Actions {
235 return createActions({ state: statePorts($), ui: uiPorts($) }, runtime)
236}
237
238/** What a view draws with: the surface's elements, state reads (which subscribe), the actions. */
239function viewPortsOf($: EngineInterface, e: RenderInput): ViewPorts {
240 const table = $.ui.resolve(e)
241 // Mobile draws no Input or Select (d.ts Elements), though a table may carry
242 // them (the test kit's does, drawing them as nothing): ask the surface first.
243 const el: El =
244 e.surface !== 'mobile' && 'Input' in table
245 ? {
246 Box: table.Box,
247 Text: table.Text,
248 Button: table.Button,
249 Link: table.Link,
250 Input: table.Input,
251 Select: table.Select,
252 }
253 : { Box: table.Box, Text: table.Text, Button: table.Button, Link: table.Link }
254 return {
255 el,
256 surface: e.surface,
257 read: statePorts($).read,
258 act: actionsOf($),
259 ownRoot: $.plugin.root,
260 }
261}
262
263// This module instance's services, built at its first `session.start` and
264// gone with the module (a reload of modmgr builds the next one).
265let runtime: Runtime | undefined
266
267// Whether modmgr's pane held the terminal's keys when last drawn. Esc hands
268// the keys back to the prompt before it raises `ui.close`, so the close
269// hook can't ask `$.ui.panes()` alone; the draw just before it knows, and the
270// pane redraws when the keys leave it. Module memory: a reload of modmgr
271// starts it false, and the first Esc then closes.
272let paneHadKeys = false
273
274// Whether the ring last landed on one of modmgr's keys rather than a row of
275// the list or its field: Esc then brings it back to the list first. Module
276// memory, set by every move the ring makes; one Esc spends it.
277let ringAway = false
278
279function noteRing(element: string | undefined): void {
280 ringAway =
281 element !== undefined &&
282 element !== FILTER_KEY &&
283 [rowOfKey, foundOfKey, devOfKey, healthOfKey].every(keyOf => keyOf(element) === undefined)
284}
285
286export const register: Register = (on, options) => {
287 const config = parseConfig(options)
288
289 on('session.start', async ($, e, next) => {
290 const started = performance.now()
291 runtime ??= createRuntime(portsOf($), config, newOwnerId())
292 await onSessionStart(runtime)
293 runtime.timing('session.start blocking', started)
294 return next(e)
295 }).catch((_$, e, next) => next(e))
296
297 // Observed only: the detector probes while no turn runs.
298 on('turn.start', async (_$, e, next) => {
299 onTurnStart(runtime, e.turnId)
300 return next(e)
301 }).catch((_$, e, next) => next(e))
302
303 on('turn.complete', async (_$, e, next) => {
304 try {
305 return await next(e)
306 } finally {
307 onTurnEnd(runtime, e.turnId, e.agentId)
308 }
309 }).catch((_$, e, next) => next(e))
310
311 on('command.run', { command: 'mods' }, ($, e) =>
312 modsCommand(
313 {
314 state: statePorts($),
315 ui: uiPorts($),
316 fs: fsPorts($),
317 clock: clockPorts($),
318 process: processPorts($),
319 session: sessionPorts($),
320 },
321 runtime,
322 e.args,
323 // Only the fullscreen layout docks the dialog.
324 e.presentation.isFullscreen ? e.presentation.columns : undefined,
325 ),
326 ).catch(() => ({
327 text: 'modmgr failed to answer; run with --debug for the reason.',
328 exitCode: 1,
329 }))
330
331 on('ui.render', { component: 'Pane', requestId: 'modmgr' }, async ($, e) => {
332 // Esc closes from the terminal's keys; another surface's draw says nothing about them.
333 if (e.surface === 'terminal') paneHadKeys = e.props.isFocused
334 const started = performance.now()
335 const tree = await drawPane(viewPortsOf($, e), {
336 bodyColumns: e.props.bodyColumns,
337 bodyRows: e.props.scroll.bodyRows,
338 isFocused: e.props.isFocused,
339 })
340 // The label is built only when timings are on.
341 if (config.debugTimings) {
342 runtime?.timing(`pane draw (${e.surface}, ${e.props.bodyColumns} columns)`, started)
343 }
344 return tree
345 }).catch((_$, e, next) => next(e))
346
347 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
348 const started = performance.now()
349 const band = await drawBand(viewPortsOf($, e), e.props)
350 runtime?.timing('band draw', started)
351 return band ?? next(e)
352 }).catch((_$, e, next) => next(e))
353
354 // Matchers spell the pane id (domain/view.ts PANE_ID) as a literal: the
355 // validator names it, and scripts/validate-plugin.ts allows these two gates
356 // only on modmgr's own pane.
357
358 // The ring landing on a row makes it the selection (the window and the split
359 // follow). Selected as the ring moves, not after it, so the row's mark and the
360 // detail are drawn with the ring instead of a frame behind it.
361 on('ui.focus', { component: 'Pane', requestId: 'modmgr' }, async ($, e, next) => {
362 const id = rowOfKey(e.element)
363 const found = foundOfKey(e.element)
364 const dev = devOfKey(e.element)
365 const item = healthOfKey(e.element)
366 const act = actionsOf($)
367 const selecting =
368 id !== undefined
369 ? act.focusRow(id)
370 : found !== undefined
371 ? act.focusFound(found)
372 : dev !== undefined
373 ? act.focusDev(dev)
374 : item !== undefined
375 ? act.focusHealth(item)
376 : Promise.resolve()
377 const [moved] = await Promise.all([next(e), selecting])
378 if (moved.deny === undefined) noteRing(e.element)
379 return moved
380 }).catch((_$, e, next) => next(e))
381
382 // The person's wheel over the dialog steps the selection, and Page Up and
383 // Page Down move it a page; over a tall overlay they scroll its lines. The pane
384 // windows both itself, so the engine has nothing of its own to scroll.
385 on('ui.scroll', { component: 'Pane', requestId: 'modmgr' }, async ($, e, next) => {
386 if (e.origin.kind !== 'person') return next(e)
387 // A key moving more than a row is a page key: a page of items, not of the body's rows.
388 const page = e.pointer === undefined && Math.abs(e.by) > 1
389 await actionsOf($).scroll(page ? Math.sign(e.by) * pageSize() : e.by, overlayEnd())
390 return {}
391 }).catch((_$, e, next) => next(e))
392
393 // Esc pops an overlay, then brings the ring back to the list, then clears the
394 // filter, then closes.
395 on('ui.close', { id: 'modmgr' }, async ($, e, next) => {
396 const away = ringAway
397 ringAway = false
398 return e.origin.kind !== 'unload' &&
399 (await actionsOf($).closing(e.origin.kind, paneHadKeys, away))
400 ? { value: undefined }
401 : next(e)
402 }).catch((_$, e, next) => next(e))
403}
404hooks/domain/config.ts 47 lines1// modmgr's `userConfig` (plugin.json) read from `register(on, options)`. The
2// engine validates the values against the manifest; this reads them again so a
3// missing or mistyped one falls back to the default instead of reaching a timer.
4
5export type Config = {
6 /** Hours between update checks; 0 turns them off. */
7 readonly updateCheckHours: number
8 readonly detectRemote: boolean
9 /** A notification when a check finds mod updates. */
10 readonly notifyUpdates: boolean
11 readonly debugTimings: boolean
12}
13
14export const DEFAULT_CONFIG: Config = {
15 updateCheckHours: 6,
16 detectRemote: true,
17 notifyUpdates: false,
18 debugTimings: false,
19}
20
21const MAX_HOURS = 168
22
23export const parseConfig = (options: Readonly<Record<string, unknown>>): Config => {
24 const hours = options.updateCheckHours
25 const detect = options.detectRemote
26 const notify = options.notifyUpdates
27 const timings = options.debugTimings
28 return {
29 updateCheckHours:
30 typeof hours === 'number' && Number.isFinite(hours)
31 ? Math.min(MAX_HOURS, Math.max(0, hours))
32 : DEFAULT_CONFIG.updateCheckHours,
33 detectRemote: typeof detect === 'boolean' ? detect : DEFAULT_CONFIG.detectRemote,
34 notifyUpdates: typeof notify === 'boolean' ? notify : DEFAULT_CONFIG.notifyUpdates,
35 debugTimings: typeof timings === 'boolean' ? timings : DEFAULT_CONFIG.debugTimings,
36 }
37}
38
39/**
40 * `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is on when set to anything but
41 * empty, `0` or `false`: when unsure, modmgr stays off the network.
42 */
43export const trafficOff = (value: string | undefined): boolean => {
44 const text = value?.trim().toLowerCase() ?? ''
45 return text !== '' && text !== '0' && text !== 'false'
46}
47hooks/domain/dev.ts 417 lines1// Dev: which mods this session runs from a folder the
2// person works in, how each is loaded, what its last validate and test said,
3// what the session reported while hot-reloading it, and how to share it.
4// services/dev.ts gathers the inputs; every decision lives here.
5
6import type { DevHow, DevRow, Job, JobState, Origin } from '../../types/index.d.ts'
7import type { InstalledEntry } from './cli-results.ts'
8import { safeSegments } from './detector.ts'
9import { isPluginName, splitPluginId } from './ids.ts'
10import { isRecord, parseJson, str } from './json.ts'
11import { hotkeyFor } from './keymap.ts'
12import { originOf, rootOf, runningVersion } from './mods.ts'
13
14/** A Dev row's Button key: what `ui.focus` and `ui.press` name. */
15export const DEV_PREFIX = 'dev:'
16export const devKey = (key: string): string => `${DEV_PREFIX}${key}`
17export const devOfKey = (key: string | undefined): string | undefined =>
18 key?.startsWith(DEV_PREFIX) === true ? key.slice(DEV_PREFIX.length) : undefined
19
20/** The order Dev lists its sections in. */
21export const DEV_SECTIONS: readonly DevHow[] = [
22 'session-folder',
23 'plugin-dir',
24 'env-dir',
25 'skills-dir',
26 'folder-marketplace',
27]
28
29/** A row's few words for how it is loaded (from 60 columns). */
30export const HOW_SHORT: Readonly<Record<DevHow, string>> = {
31 'session-folder': 'session',
32 'plugin-dir': '--plugin-dir',
33 'env-dir': 'env dirs',
34 'skills-dir': 'skills',
35 'folder-marketplace': 'folder mkt',
36}
37
38/** How it is loaded, in the detail. */
39export const SECTION_LABEL: Readonly<Record<DevHow, string>> = {
40 'session-folder': "This session's mods folder",
41 'plugin-dir': 'Loaded with --plugin-dir',
42 'env-dir': 'From CLAUDE_CODE_PLUGIN_DIRS',
43 'skills-dir': 'Your skills folder',
44 'folder-marketplace': 'Folder marketplaces',
45}
46
47/** How an edit to its files reaches this session (every action says when it applies). */
48export const appliesOf = (how: DevHow): string =>
49 how === 'folder-marketplace'
50 ? `Its folder is read again at the next plugin reload (${hotkeyFor('reload', 'dev')}).`
51 : 'Saving a file there reloads it in this session.'
52
53/** How to stop loading it, where the CLI can't; undefined when Installed toggles it. */
54export const stopLoadingOf = (row: DevRow): string | undefined => {
55 switch (row.how) {
56 case 'session-folder':
57 return 'It is loaded for this session only.'
58 case 'plugin-dir':
59 return 'To stop loading it, leave --plugin-dir out of your launch command.'
60 case 'env-dir':
61 return 'To stop loading it, take its folder out of CLAUDE_CODE_PLUGIN_DIRS and restart.'
62 default:
63 return undefined
64 }
65}
66
67const DEV_ORIGINS: ReadonlyMap<Origin, DevHow> = new Map([
68 ['env-dir', 'env-dir'],
69 ['skills-dir', 'skills-dir'],
70 ['folder-marketplace', 'folder-marketplace'],
71])
72
73/** A plugin the CLI lists, and whether validate found a hooks module (undefined: it couldn't read it). */
74export type Listed = { readonly entry: InstalledEntry; readonly mod: boolean | undefined }
75
76/** A plugin folder modmgr found, with what its manifest says. */
77export type Found = { readonly name: string; readonly path: string; readonly version?: string }
78
79export type DevSources = {
80 readonly listed: readonly Listed[]
81 /** The plugins that registered a command (`$.command.list()`), by name or id. */
82 readonly commandPlugins: readonly string[]
83 /** This session's mods folder's plugins. */
84 readonly sessionFolder: readonly Found[]
85 /** The folders found for plugins the CLI doesn't list (`--plugin-dir`), by name. */
86 readonly located: ReadonlyMap<string, Found>
87 /**
88 * modmgr itself, when it runs from a folder other than its installed copy's
89 * (`--plugin-dir` over an installed modmgr: the CLI lists only the install).
90 */
91 readonly own?: Found
92}
93
94/** The name part of a plugin as a command names it (`modmgr`, `spawner@inline`). */
95const bareName = (plugin: string): string => {
96 const at = plugin.indexOf('@')
97 return at < 0 ? plugin : plugin.slice(0, at)
98}
99
100/**
101 * The plugins this session runs that the CLI doesn't list, whose folder to
102 * look for: what `--plugin-dir` loaded (the flag isn't inherited by a
103 * child). A plugin that registered a command, or one the session reported
104 * failing. Built-in plugins register commands too (`cc-plugin-diff`, found
105 * live), so a name becomes a row only once its folder is found.
106 */
107export const unlistedPlugins = (
108 commandPlugins: readonly string[],
109 known: ReadonlySet<string>,
110): string[] =>
111 [...new Set(commandPlugins.map(bareName))]
112 .filter(name => isPluginName(name) && !known.has(name))
113 .sort()
114
115const byPlace = (a: DevRow, b: DevRow): number =>
116 DEV_SECTIONS.indexOf(a.how) - DEV_SECTIONS.indexOf(b.how) ||
117 a.name.localeCompare(b.name) ||
118 a.key.localeCompare(b.key)
119
120/**
121 * Dev's rows, by section then name: listed plugins loaded from a folder the
122 * person edits (not a plain plugin; one validate couldn't read stays, since a
123 * broken mod is what Dev is for), this session's mods folder, and the
124 * `--plugin-dir` plugins whose folder was found (`located`).
125 */
126export const devRowsOf = (sources: DevSources): DevRow[] => {
127 const rows: DevRow[] = []
128 const listedNames = new Set(sources.listed.map(({ entry }) => splitPluginId(entry.id).name))
129 for (const { entry, mod } of sources.listed) {
130 const how = DEV_ORIGINS.get(originOf(entry))
131 const path = rootOf(entry)
132 if (how === undefined || mod === false || path === undefined) continue
133 const version = runningVersion(entry)
134 rows.push({
135 key: path,
136 name: splitPluginId(entry.id).name,
137 how,
138 id: entry.id,
139 path,
140 enabled: entry.enabled,
141 ...(version === undefined ? {} : { version }),
142 })
143 }
144 // A plugin that registered a command is loaded (a session folder's may not be yet).
145 const loaded = new Set(sources.commandPlugins.map(bareName))
146 const sessionNames = new Set(sources.sessionFolder.map(found => found.name))
147 for (const found of sources.sessionFolder) {
148 // A folder the CLI lists under another heading is said once, there.
149 if (rows.some(row => row.path === found.path)) continue
150 rows.push({
151 key: found.path,
152 ...rowOfFound(found),
153 how: 'session-folder',
154 ...(loaded.has(found.name) ? { enabled: true } : {}),
155 })
156 }
157 for (const [name, found] of sources.located) {
158 if (listedNames.has(name) || sessionNames.has(name) || found.name !== name) continue
159 if (rows.some(row => row.path === found.path)) continue
160 rows.push({
161 key: found.path,
162 ...rowOfFound(found),
163 how: 'plugin-dir',
164 ...(loaded.has(name) ? { enabled: true } : {}),
165 })
166 }
167 const own = sources.own
168 if (own !== undefined && !rows.some(row => row.path === own.path)) {
169 rows.push({ key: own.path, ...rowOfFound(own), how: 'plugin-dir', enabled: true })
170 }
171 return rows.sort(byPlace)
172}
173
174const rowOfFound = (found: Found): Pick<DevRow, 'name' | 'path' | 'version'> => ({
175 name: found.name,
176 path: found.path,
177 ...(found.version === undefined ? {} : { version: found.version }),
178})
179
180/** A `plugin.json`'s name and version, when it names a plugin. */
181export const manifestOf = (text: string): { name: string; version?: string } | undefined => {
182 const value = parseJson(text)
183 if (!isRecord(value)) return undefined
184 const name = str(value, 'name')
185 if (name === undefined || !isPluginName(name)) return undefined
186 const version = str(value, 'version')
187 return version === undefined ? { name } : { name, version: version.slice(0, 64) }
188}
189
190/** An https address a link can open: a host, then a path of URL characters (RFC 3986's, but `'`). */
191const LINKABLE =
192 /^https:\/\/[A-Za-z0-9.-]+(?::\d{1,5})?(?:\/[A-Za-z0-9\-._~:/?#[\]@!$&()*+,;=%]*)?$/
193
194/** What a `plugin.json` says of its plugin, for its detail. */
195export type About = { readonly description?: string; readonly link?: string }
196
197/**
198 * What a `plugin.json` says its plugin is, and where it lives: its
199 * `homepage`, else its `repository` (a URL, or `{ url }` as npm writes it),
200 * when that is an https address. A `git+https://….git` repository reads as
201 * its page.
202 */
203export const manifestAboutOf = (text: string): About => {
204 const value = parseJson(text)
205 if (!isRecord(value)) return {}
206 const description = str(value, 'description')?.trim().slice(0, 300)
207 const repository = isRecord(value.repository)
208 ? str(value.repository, 'url')
209 : str(value, 'repository')
210 const link = [str(value, 'homepage'), repository]
211 .map(candidate =>
212 candidate
213 ?.trim()
214 .replace(/^git\+/, '')
215 .replace(/\.git$/, ''),
216 )
217 .find(url => url !== undefined && url.length <= 300 && LINKABLE.test(url))
218 return {
219 ...(description === undefined || description === '' ? {} : { description }),
220 ...(link === undefined ? {} : { link }),
221 }
222}
223
224/**
225 * The folder a `marketplace.json` gives plugin `name`, relative to the
226 * marketplace's root (`''` for the root itself); undefined when it doesn't
227 * list it, or lists it at a path that is absolute or climbs.
228 */
229export const marketplaceFolderOf = (text: string, name: string): string | undefined => {
230 const value = parseJson(text)
231 if (!isRecord(value) || !Array.isArray(value.plugins)) return undefined
232 const entry = value.plugins.find(plugin => isRecord(plugin) && plugin.name === name)
233 if (!isRecord(entry) || typeof entry.source !== 'string') return undefined
234 const segments = safeSegments(entry.source)
235 return segments?.map(decodeURIComponent).join('/')
236}
237
238/** `a/b` joined under `root`, or `root` itself for `''`. */
239export const joinPath = (root: string, relative: string): string => {
240 const head = root.replace(/\/+$/, '')
241 return relative === '' ? head : `${head}/${relative}`
242}
243
244const SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/
245
246/** A session id that is one plain path segment. */
247export const isSessionId = (value: string): boolean => SESSION_ID.test(value)
248
249/**
250 * This session's mods folder: `<config dir>/dev-mods/<session id>`, the config
251 * dir being `CLAUDE_CONFIG_DIR` or `~/.claude`. Undefined when neither is an
252 * absolute path or the session id isn't one plain segment.
253 */
254export const sessionFolderOf = (how: {
255 readonly configDir: string | undefined
256 readonly home: string | undefined
257 readonly sessionId: string
258}): string | undefined => {
259 if (!SESSION_ID.test(how.sessionId)) return undefined
260 const config = configDirOf(how.configDir, how.home)
261 return config === undefined ? undefined : joinPath(config, `dev-mods/${how.sessionId}`)
262}
263
264/** Claude Code's config dir: `CLAUDE_CONFIG_DIR`, else `~/.claude`; undefined unless absolute. */
265export const configDirOf = (
266 configDir: string | undefined,
267 home: string | undefined,
268): string | undefined => {
269 const config =
270 configDir !== undefined && configDir !== ''
271 ? configDir
272 : home === undefined
273 ? undefined
274 : joinPath(home, '.claude')
275 return config?.startsWith('/') === true ? config : undefined
276}
277
278/** The row Dev shows as selected and acts on: the selection when listed, else the first. */
279export const devRowOf = (
280 selected: string | undefined,
281 rows: readonly DevRow[],
282): DevRow | undefined => rows.find(row => row.key === selected) ?? rows[0]
283
284/**
285 * The selection once rows change: the row shown selected before, while it is
286 * still listed, so a row that joins at the top (a failing folder) never takes
287 * the selection from under the focus ring (found live).
288 */
289export const keptSelection = (
290 selected: string | undefined,
291 before: readonly DevRow[],
292 after: readonly DevRow[],
293): string | undefined => {
294 const shown = devRowOf(selected, before)?.key
295 return after.some(row => row.key === shown) ? shown : after[0]?.key
296}
297
298// ---- what ran ----------------------------------------------------------------
299
300export type DevRunKind = 'validate' | 'test'
301
302/** The newest validate or test of `path` in the queue. */
303export const lastRun = (jobs: readonly Job[], kind: DevRunKind, path: string): Job | undefined =>
304 jobs.findLast(job => job.kind === kind && job.args?.path === path)
305
306export type RunMark = { readonly text: string; readonly tone: 'busy' | 'ok' | 'bad' | 'muted' }
307
308const BUSY: ReadonlySet<JobState> = new Set(['queued', 'running'])
309
310/** A row's short mark for its last validate: `✓`, `✓ 2 warnings`, `✗ 3`, `…`, or nothing yet. */
311export const validateMark = (job: Job | undefined): RunMark | undefined => {
312 if (job === undefined) return undefined
313 if (BUSY.has(job.state)) return { text: 'validating…', tone: 'busy' }
314 const report = job.report
315 if (job.state === 'ok') {
316 const warnings = report?.warnings ?? 0
317 return warnings === 0
318 ? { text: '✓ valid', tone: 'ok' }
319 : { text: `✓ ${warnings} ${warnings === 1 ? 'warning' : 'warnings'}`, tone: 'ok' }
320 }
321 if (job.state === 'failed' && report !== undefined) {
322 return { text: `✗ ${report.errors} ${report.errors === 1 ? 'error' : 'errors'}`, tone: 'bad' }
323 }
324 return job.state === 'failed'
325 ? { text: '✗ validate failed', tone: 'bad' }
326 : { text: `validate ${job.state}`, tone: 'muted' }
327}
328
329/** A row's short mark for its last test run. */
330export const testMark = (job: Job | undefined): RunMark | undefined => {
331 if (job === undefined) return undefined
332 if (BUSY.has(job.state)) return { text: 'testing…', tone: 'busy' }
333 if (job.state === 'ok') return { text: '✓ tests', tone: 'ok' }
334 if (job.state === 'failed') return { text: '✗ tests', tone: 'bad' }
335 return { text: `tests ${job.state}`, tone: 'muted' }
336}
337
338// ---- sharing (the engine's reference, §Sharing a mod) --------------------------
339
340/** `owner/repo` of a GitHub remote (https, ssh or scp form), or undefined. */
341export const githubRepoOf = (remote: string | null | undefined): string | undefined => {
342 if (remote === null || remote === undefined) return undefined
343 const match =
344 /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([A-Za-z0-9][A-Za-z0-9-]{0,38})\/([A-Za-z0-9._-]{1,100}?)(?:\.git)?\/?$/.exec(
345 remote.trim(),
346 )
347 const owner = match?.[1]
348 const repo = match?.[2]
349 return owner === undefined || repo === undefined ? undefined : `${owner}/${repo}`
350}
351
352/** Whether `path` is `root` or inside it. */
353export const isInside = (path: string, root: string): boolean => {
354 const head = root.replace(/\/+$/, '')
355 return path === head || path.startsWith(`${head}/`)
356}
357
358export type Share = {
359 /** What another person types: `/plugin install <mod> --marketplace <owner>/<repo>`. */
360 readonly line: string
361 /** Whether `line` names a real repository (else `<owner>/<repo>` stands in it). */
362 readonly complete: boolean
363 /** The marketplace file to write beside `plugin.json`, when none lists the mod. */
364 readonly snippet?: string
365 readonly notes: readonly string[]
366}
367
368/**
369 * How to share a dev mod: the one install line, and what is missing for it to
370 * work (a marketplace file listing the mod, a GitHub repository, a folder kept
371 * outside this session's mods folder).
372 */
373export const shareOf = (
374 row: Pick<DevRow, 'name' | 'how'>,
375 how: {
376 readonly repo: string | undefined
377 readonly listed: boolean
378 /** The mod's folder relative to the repository's root (`./`, `./plugin`). */
379 readonly source: string
380 },
381): Share => {
382 const repo = how.repo ?? '<owner>/<repo>'
383 const notes: string[] = []
384 if (row.how === 'session-folder') {
385 notes.push(
386 "Copy it out of this session's mods folder to a folder you keep, and make that the repository.",
387 )
388 }
389 if (how.repo === undefined) {
390 notes.push('Push its folder to a GitHub repository; <owner>/<repo> is that repository.')
391 }
392 const snippet = how.listed
393 ? undefined
394 : JSON.stringify(
395 {
396 name: row.name,
397 owner: { name: '<your name>' },
398 plugins: [{ name: row.name, source: how.source }],
399 },
400 null,
401 2,
402 )
403 if (snippet !== undefined) {
404 notes.push(
405 how.source === './'
406 ? 'Write this as .claude-plugin/marketplace.json beside its plugin.json:'
407 : "Write this as .claude-plugin/marketplace.json at the repository's root:",
408 )
409 }
410 return {
411 line: `/plugin install ${row.name} --marketplace ${repo}`,
412 complete: how.repo !== undefined,
413 ...(snippet === undefined ? {} : { snippet }),
414 notes,
415 }
416}
417hooks/domain/discover.ts 224 lines1// Discover's logic: what a catalogue row says, the install
2// review, the review that accepts a marketplace-declared command, and
3// adding a marketplace. The catalogue itself lives in services/catalog.ts.
4
5import type {
6 CatalogPage,
7 CatalogRow,
8 Job,
9 ReviewRequest,
10 Scope,
11 View,
12} from '../../types/index.d.ts'
13import { capabilitiesOf, notableText } from './capabilities.ts'
14import { installIdOf, SORTS } from './catalog.ts'
15import type { CommunityMod } from './community.ts'
16import { parseMarketplaceSource } from './ids.ts'
17
18export const INSTALL_SCOPES = ['user', 'project', 'local'] as const
19export type InstallScope = (typeof INSTALL_SCOPES)[number]
20
21export const isInstallScope = (value: unknown): value is InstallScope =>
22 typeof value === 'string' && (INSTALL_SCOPES as readonly string[]).includes(value)
23
24/** What a scope means, for the review's Select. */
25export const SCOPE_LABEL: Readonly<Record<InstallScope, string>> = {
26 user: 'user: every project',
27 project: 'project: this repository, shared',
28 local: 'local: this repository, only you',
29}
30
31/** What modmgr could read about an entry before installing it (a local source's `validate`). */
32export type Inspection = {
33 readonly notable: readonly string[]
34 readonly hasModule: boolean
35 /** Read by the community index at this commit, not by modmgr here. */
36 readonly at?: string
37}
38
39/** A local entry modmgr tried to read and couldn't, and why. */
40export type Unread = { readonly failed: string }
41
42export const isUnread = (value: Inspection | Unread | undefined): value is Unread =>
43 value !== undefined && 'failed' in value
44
45/**
46 * The review of installing `entry` (`i`): the scope (user by default), what it
47 * can do when modmgr could read it, else that it couldn't (a remote source is
48 * read only once installed).
49 */
50export const installReview = (
51 entry: { readonly id: string; readonly name: string; readonly version?: string | undefined },
52 scope: InstallScope,
53 read: Inspection | Unread | undefined,
54): ReviewRequest => {
55 const inspection = isUnread(read) ? undefined : read
56 const review: ReviewRequest = {
57 action: 'install',
58 targets: [
59 {
60 id: entry.id,
61 op: 'install',
62 scope,
63 ...(entry.version === undefined ? {} : { version: entry.version }),
64 },
65 ],
66 // One mod: the heading names it, so its lines don't.
67 notable: (inspection?.notable ?? []).map(notableText),
68 changesRepoFile: scope !== 'user',
69 ...(inspection?.at === undefined ? {} : { indexedAt: inspection.at }),
70 }
71 if (inspection !== undefined) return review
72 return isUnread(read)
73 ? { ...review, uninspected: true, unreadable: read.failed }
74 : { ...review, uninspected: true }
75}
76
77/**
78 * The review of installing a community mod (`i`): from the marketplace at its
79 * repository's root, which the install adds first. What it can do is known
80 * already, from the community index; modmgr reads it again once installed.
81 * Undefined for a mod no marketplace lists (it can't be installed by id).
82 */
83export const communityInstallReview = (
84 mod: CommunityMod,
85 scope: InstallScope,
86): ReviewRequest | undefined => {
87 const id = installIdOf(mod)
88 if (id === undefined) return undefined
89 return {
90 action: 'install',
91 targets: [{ id, op: 'install', scope }],
92 notable: capabilitiesOf(mod).notable.map(notableText),
93 changesRepoFile: scope !== 'user',
94 source: mod.repo,
95 indexedAt: mod.commit,
96 }
97}
98
99/** The same review at another scope (the review's Select). */
100export const withScope = (review: ReviewRequest, scope: Scope): ReviewRequest =>
101 review.action !== 'install' || !isInstallScope(scope)
102 ? review
103 : {
104 ...review,
105 targets: review.targets.map(target => ({ ...target, scope })),
106 changesRepoFile: scope !== 'user',
107 }
108
109/**
110 * The review that accepts what a failed install or update was stopped by:
111 * the command a marketplace declares (or the headers helper that fetches its
112 * archive), verbatim, with its sha256. Confirming passes the sha with
113 * `--accept-command`; the CLI runs it only if the command it would run still
114 * has that sha, and otherwise shows the new one, which this review
115 * shows again. Undefined for a job that wasn't stopped that way.
116 */
117export const acceptReview = (job: Job): ReviewRequest | undefined => {
118 const { shown, target } = job
119 if (shown === undefined || target === undefined) return undefined
120 if (job.kind !== 'install' && job.kind !== 'update') return undefined
121 const scope = job.args?.scope
122 const declared = {
123 text: shown.command,
124 sha256: shown.sha256,
125 ...(shown.truncated === true ? { truncated: true } : {}),
126 }
127 const source = job.args?.source
128 return {
129 action: job.kind,
130 targets: [{ id: target, op: job.kind, ...(scope === undefined ? {} : { scope }) }],
131 notable: [],
132 changesRepoFile: scope === 'project' || scope === 'local',
133 ...(source === undefined ? {} : { source }),
134 ...(shown.kind === 'entry_helper'
135 ? { headersHelper: declared }
136 : { declaredCommand: declared }),
137 }
138}
139
140/**
141 * The newest failed job that waits for its declared command to be reviewed:
142 * none once a later install or update of the same mod was queued or ran.
143 */
144export const awaitingAcceptance = (jobs: readonly Job[]): Job | undefined => {
145 const at = jobs.findLastIndex(job => job.state === 'failed' && job.shown !== undefined)
146 const stopped = jobs[at]
147 if (stopped === undefined) return undefined
148 const settled = jobs
149 .slice(at + 1)
150 .some(job => job.target === stopped.target && (job.kind === 'install' || job.kind === 'update'))
151 return settled ? undefined : stopped
152}
153
154/**
155 * The review of adding a marketplace (`m`), or why the source can't be one.
156 * Adding fetches the catalogue (a clone for a repository) and writes your
157 * settings; it runs no plugin code.
158 */
159export const marketplaceReview = (
160 text: string,
161): { readonly review: ReviewRequest } | { readonly error: string } => {
162 const source = parseMarketplaceSource(text.trim())
163 if (!source.ok) return { error: source.error.message }
164 return {
165 review: {
166 action: 'marketplace',
167 targets: [],
168 notable: [],
169 changesRepoFile: false,
170 source: source.value,
171 },
172 }
173}
174
175/** The notable lines of an inspection, for the detail. */
176export const inspectionLines = (inspection: Inspection): string[] =>
177 inspection.notable.map(notableText)
178
179/** The marketplace field's key. */
180export const MARKETPLACE_KEY = 'marketplace-source'
181
182/** A Discover row's Button key: what `ui.focus` and `ui.press` name. */
183export const FOUND_PREFIX = 'found:'
184export const foundKey = (id: string): string => `${FOUND_PREFIX}${id}`
185export const foundOfKey = (key: string | undefined): string | undefined =>
186 key?.startsWith(FOUND_PREFIX) === true ? key.slice(FOUND_PREFIX.length) : undefined
187
188/** The catalogue row Discover shows as selected and acts on: the selection when drawn, else the first. */
189export const foundRow = (view: View, page: CatalogPage): CatalogRow | undefined =>
190 page.rows.find(row => row.id === view.found) ?? page.rows[0]
191
192/** What the sort key says: installs, then stars for community mods. */
193export const SORT_LABEL: Readonly<Record<View['sort'], string>> = {
194 installs: 'popularity',
195 stars: 'stars',
196 name: 'name',
197 marketplace: 'source',
198}
199
200/** The next sort (`o`): popularity → stars → name → source. */
201export const nextSort = (sort: View['sort']): View['sort'] =>
202 SORTS[(SORTS.indexOf(sort) + 1) % SORTS.length] ?? 'installs'
203
204/**
205 * `74 mods`, `74 mods · 1,804 of 3,544 entries checked`, or while it runs
206 * `12 mods so far · checking 1,804 of 3,544`; undefined before it ran.
207 */
208export const detectLine = (detect: {
209 readonly checked: number
210 readonly total: number
211 readonly found: number
212 readonly running: boolean
213}): string | undefined => {
214 if (detect.total === 0) return undefined
215 const n = (value: number) => value.toLocaleString('en-US')
216 const mods = `${n(detect.found)} ${detect.found === 1 ? 'mod' : 'mods'}`
217 if (detect.running)
218 return detect.checked === 0
219 ? `checking ${n(detect.total)} entries…`
220 : `${mods} so far · checking ${n(detect.checked)} of ${n(detect.total)}`
221 if (detect.checked >= detect.total) return mods
222 return `${mods} · ${n(detect.checked)} of ${n(detect.total)} entries checked`
223}
224hooks/domain/health.ts 407 lines1// Health: what needs the person's attention, grouped by mod,
2// each with a one-press fix where one exists, then modmgr's own state (the
3// installed list's refresh, a reload owed, the detector, the cache, the update
4// checks). Built from `$.state` alone, so it is drawn, never fetched.
5
6import type {
7 Attention,
8 Degraded,
9 DetectProgress,
10 HealthFacts,
11 JobQueue,
12 ModRow,
13 Sync,
14} from '../../types/index.d.ts'
15import { notableVerb } from './capabilities.ts'
16import { isActive } from './jobs.ts'
17import { sanitize } from './sanitize.ts'
18import { bytesLabel, type Window, whyLocked, whyNoUpdate, windowAround } from './view.ts'
19
20/** What pressing an item does. */
21export type HealthFix =
22 | { readonly kind: 'update' | 'open'; readonly id: string }
23 | { readonly kind: 'copy'; readonly text: string }
24 | { readonly kind: 'reload' | 'refresh' | 'clear-cache' | 'check-updates' }
25
26export type HealthTone = 'bad' | 'warn' | 'info'
27
28export type HealthItem = {
29 /** Stable: the Button's key. */
30 readonly key: string
31 /** The mod it concerns, or modmgr's own heading. */
32 readonly group: string
33 readonly tone: HealthTone
34 /** A status row's name (`Updates`), drawn in a column before its text. */
35 readonly label?: string
36 readonly text: string
37 readonly fix?: HealthFix
38 /** What the fix does, in a word or two. */
39 readonly fixLabel?: string
40}
41
42/** modmgr's own heading (apart from an installed mod named modmgr), and the hook-order notes'. */
43export const OWN_GROUP = 'Status'
44export const ORDER_GROUP = 'Hook order'
45
46/** A Health item's Button key: what `ui.focus` and `ui.press` name. */
47export const HEALTH_PREFIX = 'health:'
48export const healthKey = (key: string): string => `${HEALTH_PREFIX}${key}`
49export const healthOfKey = (key: string | undefined): string | undefined =>
50 key?.startsWith(HEALTH_PREFIX) === true ? key.slice(HEALTH_PREFIX.length) : undefined
51
52/** An item as one line: its label, if any, before its text. */
53export const healthText = (item: HealthItem): string =>
54 item.label === undefined ? item.text : `${item.label}: ${item.text}`
55
56const plural = (n: number, one: string, many: string): string => `${n} ${n === 1 ? one : many}`
57
58/** `just now`, `5 min ago`, `3 h ago`, `2 days ago`. */
59export const agoLabel = (ms: number): string => {
60 const minutes = Math.floor(Math.max(0, ms) / 60_000)
61 if (minutes < 1) return 'just now'
62 if (minutes < 60) return `${minutes} min ago`
63 const hours = Math.floor(minutes / 60)
64 if (hours < 48) return `${hours} h ago`
65 return `${Math.floor(hours / 24)} days ago`
66}
67
68export type HealthInput = {
69 readonly mods: readonly ModRow[]
70 readonly attention: Attention
71 readonly degraded: Degraded
72 readonly sync: Sync
73 readonly detect: DetectProgress
74 readonly queue: JobQueue
75 readonly facts: HealthFacts
76}
77
78const TONE_ORDER: Readonly<Record<HealthTone, number>> = { bad: 0, warn: 1, info: 2 }
79
80/** Each mod's items: what is wrong first. */
81const modItems = (input: HealthInput): HealthItem[] => {
82 const items: HealthItem[] = []
83 // Two mods of one name, from two marketplaces, each get their own group.
84 const named = new Map<string, number>()
85 for (const row of input.mods) named.set(row.name, (named.get(row.name) ?? 0) + 1)
86 const groupOf = (row: ModRow): string =>
87 sanitize(
88 (named.get(row.name) ?? 0) > 1
89 ? `${row.name} · ${row.id.slice(row.id.indexOf('@') + 1)}`
90 : row.name,
91 { max: 60 },
92 )
93 for (const row of input.mods) {
94 const group = groupOf(row)
95 if (row.problems > 0) {
96 items.push({
97 key: `${row.id}:validate`,
98 group,
99 tone: 'bad',
100 text: `validate finds ${plural(row.problems, 'error', 'errors')} in it`,
101 fix: { kind: 'open', id: row.id },
102 fixLabel: 'see it',
103 })
104 }
105 if (row.capsNew !== undefined) {
106 const added = row.capsNew.added.map(notableVerb).join(', ')
107 items.push({
108 key: `${row.id}:caps`,
109 group,
110 tone: 'warn',
111 text: `since ${sanitize(row.capsNew.since, { max: 20 })} it can ${added}`,
112 fix: { kind: 'open', id: row.id },
113 fixLabel: 'review it',
114 })
115 }
116 if (row.updateTo !== undefined && whyNoUpdate(row) === undefined) {
117 items.push({
118 key: `${row.id}:update`,
119 group,
120 tone: 'info',
121 text: `${sanitize(row.updateTo, { max: 20 })} is available`,
122 fix: { kind: 'update', id: row.id },
123 fixLabel: 'update',
124 })
125 }
126 }
127 // The hook failures the debug log names.
128 for (const name of Object.keys(input.facts.logged).sort()) {
129 const group = sanitize(name, { max: 40 })
130 const logged = input.facts.logged[name]
131 if (logged !== undefined) {
132 items.push({
133 key: `${name}:logged`,
134 group,
135 tone: 'bad',
136 text: `a hook failed: ${sanitize(logged, { max: 160 })} (debug log)`,
137 })
138 }
139 }
140 // By mod, worst first; the mods in Installed's order, then the rest by name.
141 const order = input.mods.map(groupOf)
142 const rank = (group: string) => {
143 const at = order.indexOf(group)
144 return at < 0 ? order.length : at
145 }
146 const worst = new Map<string, number>()
147 for (const item of items) {
148 worst.set(item.group, Math.min(worst.get(item.group) ?? 9, TONE_ORDER[item.tone]))
149 }
150 return items.sort(
151 (a, b) =>
152 (worst.get(a.group) ?? 9) - (worst.get(b.group) ?? 9) ||
153 rank(a.group) - rank(b.group) ||
154 a.group.localeCompare(b.group) ||
155 TONE_ORDER[a.tone] - TONE_ORDER[b.tone],
156 )
157}
158
159/** modmgr's own state, and the load states in one line. */
160const ownItems = (input: HealthInput): HealthItem[] => {
161 const { attention, degraded, sync, detect, facts, queue } = input
162 const items: HealthItem[] = []
163 const own = (item: Omit<HealthItem, 'group'>) => items.push({ ...item, group: OWN_GROUP })
164 if (degraded.process) {
165 own({
166 key: 'own:process',
167 tone: 'bad',
168 label: 'CLI',
169 text: sanitize(degraded.reason ?? '', { max: 300 }),
170 })
171 }
172 if (sync.error !== undefined) {
173 own({
174 key: 'own:sync',
175 tone: 'bad',
176 label: 'Installed',
177 text: `couldn't read the list: ${sanitize(sync.error.message, { max: 160 })}`,
178 fix: { kind: 'refresh' },
179 fixLabel: 'try again',
180 })
181 } else if (sync.skipped > 0) {
182 own({
183 key: 'own:unread',
184 tone: 'warn',
185 label: 'Installed',
186 text: `couldn't read ${plural(sync.skipped, 'installed plugin', 'installed plugins')}, so ${sync.skipped === 1 ? 'it is' : 'they are'} not listed`,
187 fix: { kind: 'refresh' },
188 fixLabel: 'read again',
189 })
190 }
191 const reloadQueued = queue.jobs.some(job => job.kind === 'reload' && isActive(job))
192 if (attention.reloadPending && !reloadQueued) {
193 own(
194 attention.reloadByHand === true
195 ? {
196 key: 'own:reload',
197 tone: 'warn',
198 label: 'Reload',
199 text: 'changes wait for you to run /reload-plugins',
200 fix: { kind: 'copy', text: '/reload-plugins' },
201 fixLabel: 'copy command',
202 }
203 : {
204 key: 'own:reload',
205 tone: 'warn',
206 label: 'Reload',
207 text: 'changes wait for a plugin reload',
208 fix: { kind: 'reload' },
209 fixLabel: 'reload',
210 },
211 )
212 }
213 if (facts.cache.full) {
214 own({
215 key: 'own:cache',
216 tone: 'bad',
217 label: 'Cache',
218 text: "full: what modmgr learns isn't saved",
219 fix: { kind: 'clear-cache' },
220 fixLabel: 'clear cache',
221 })
222 }
223 if (degraded.acceptCommand) {
224 own({
225 key: 'own:accept',
226 tone: 'info',
227 label: 'Commands',
228 text: "Claude Code won't accept a declared install command from this session; accept it in a terminal",
229 })
230 }
231 const counts = loadStates(input.mods)
232 if (counts !== undefined) own({ key: 'own:load', tone: 'info', label: 'Mods', text: counts })
233 const updates = facts.updates
234 // Said once the facts are in (the first frame has none, and would say "every 0 hours").
235 if (facts.at !== undefined)
236 own({
237 key: 'own:updates',
238 tone: 'info',
239 label: 'Updates',
240 text:
241 updates.off !== undefined
242 ? `checks are off: ${updates.off}`
243 : `${updates.at === undefined || facts.at === undefined ? 'never checked' : `checked ${agoLabel(facts.at - updates.at)}`} · every ${updates.every} h`,
244 ...(updates.off === undefined
245 ? { fix: { kind: 'check-updates' as const }, fixLabel: 'check now' }
246 : {}),
247 })
248 const left = Math.max(0, facts.detector.budget - facts.detector.spent)
249 // Where Discover's kinds came from: the catalogue index (and how old it is), then checks here.
250 const index =
251 detect.indexAt === undefined || facts.at === undefined
252 ? ''
253 : ` · index ${agoLabel(facts.at - detect.indexAt).replace(' ago', ' old')}`
254 // How far checking got, said only while it hasn't finished.
255 const checking =
256 detect.checked < detect.total
257 ? ` · ${detect.checked.toLocaleString('en-US')} of ${detect.total.toLocaleString('en-US')} checked, ${left} lookups left`
258 : ''
259 own({
260 key: 'own:detector',
261 tone: 'info',
262 label: 'Discover',
263 text:
264 detect.total === 0
265 ? 'finds mods when Discover first opens'
266 : facts.detector.remote
267 ? `${plural(detect.found, 'mod', 'mods')} found in your marketplaces${index}${checking}`
268 : `${plural(detect.found, 'mod', 'mods')} found in your marketplaces' local catalogues (${facts.detector.why ?? 'remote checks are off'})`,
269 })
270 if (!facts.cache.full) {
271 own({
272 key: 'own:cache',
273 tone: 'info',
274 label: 'Cache',
275 text: bytesLabel(facts.cache.bytes),
276 fix: { kind: 'clear-cache' },
277 fixLabel: 'clear',
278 })
279 }
280 const log = facts.debugLog
281 if (log.state === 'too-big' && log.path !== undefined) {
282 own({
283 key: 'own:debug',
284 tone: 'warn',
285 label: 'Hook errors',
286 // The engine's read refuses past 4 MiB, but also on a permission error: which, it doesn't say.
287 text: "this session's debug log couldn't be read here (over 4 MiB, or not readable)",
288 fix: { kind: 'copy', text: `grep 'hook failed closed' ${log.path}` },
289 fixLabel: 'copy a search',
290 })
291 }
292 if (log.state === 'none') {
293 own({
294 key: 'own:debug',
295 tone: 'info',
296 label: 'Hook errors',
297 text: 'seen only in a session started with --debug',
298 fix: { kind: 'copy', text: 'claude --debug' },
299 fixLabel: 'copy command',
300 })
301 }
302 return items
303}
304
305/** `4 enabled · 1 disabled · 1 managed · 2 from the launch command`, or nothing with no mods. */
306export const loadStates = (mods: readonly ModRow[]): string | undefined => {
307 if (mods.length === 0) return undefined
308 const managed = mods.filter(row => row.scope === 'managed').length
309 const launched = mods.filter(
310 row => row.origin === 'env-dir' || row.origin === 'plugin-dir',
311 ).length
312 const other = mods.filter(row => whyLocked(row) === undefined)
313 const enabled = other.filter(row => row.enabled).length
314 const disabled = other.length - enabled
315 return [
316 `${enabled} enabled`,
317 disabled === 0 ? '' : `${disabled} disabled`,
318 managed === 0 ? '' : `${managed} managed`,
319 launched === 0 ? '' : `${launched} from the launch command`,
320 ]
321 .filter(part => part !== '')
322 .join(' · ')
323}
324
325/** Every item Health draws: the mods', the hook-order notes, then modmgr's own. */
326export const healthItemsOf = (input: HealthInput): HealthItem[] => [
327 ...modItems(input),
328 ...input.facts.chain.map(
329 (note): HealthItem => ({
330 key: `order:${note.event}`,
331 group: ORDER_GROUP,
332 tone: 'info',
333 text: sanitize(note.text, { max: 300 }),
334 }),
335 ),
336 ...ownItems(input),
337]
338
339/** How many items say something is wrong (the tab's `▲n`). */
340export const problemCount = (items: readonly HealthItem[]): number =>
341 items.filter(item => item.tone === 'bad').length
342
343/**
344 * The last `hook failed closed: <plugin>: errorKind=… (<event>; …)` line per
345 * plugin in a debug log (the engine logs the error's length, not its text).
346 */
347export const loggedFailures = (log: string): Record<string, string> => {
348 const found: Record<string, string> = {}
349 const line =
350 /hook failed closed: ([a-z0-9][a-z0-9._-]{0,63})(?:@[a-z0-9._-]+)?: errorKind=(\w+)[^(]*\(([\w.]+)/g
351 for (const match of log.matchAll(line)) {
352 const [, name, kind, event] = match
353 if (name !== undefined && kind !== undefined && event !== undefined) {
354 found[name] = `${event} (${kind})`
355 }
356 }
357 return found
358}
359
360/** A row of Health's list: a group's name, or one of its items. */
361export type HealthLine =
362 | { readonly kind: 'group'; readonly group: string }
363 | { readonly kind: 'item'; readonly item: HealthItem }
364
365/**
366 * The rows of Health's list that fit in `rows` around `items[at]`: each
367 * group's name on a row of its own above its items, again at the top when the
368 * window starts inside a group. `items` is the window over the items, for
369 * the pager.
370 */
371export const healthLines = (
372 items: readonly HealthItem[],
373 at: number,
374 rows: number,
375): { readonly lines: HealthLine[]; readonly items: Window } => {
376 const all: HealthLine[] = []
377 items.forEach((item, index) => {
378 if (index === 0 || items[index - 1]?.group !== item.group)
379 all.push({ kind: 'group', group: item.group })
380 all.push({ kind: 'item', item })
381 })
382 const size = Math.max(2, rows)
383 const selected = items[at]
384 const focus = all.findIndex(line => line.kind === 'item' && line.item === selected)
385 const window = windowAround(all.length, focus, size)
386 let lines = all.slice(window.start, window.end)
387 const first = lines[0]
388 if (first?.kind === 'item') {
389 lines = [{ kind: 'group', group: first.item.group }, ...lines]
390 // Over by the name: cut the end, or the top item when that would take the
391 // selection or the row under it (the arrows' way down).
392 const near = lines.slice(-2).some(line => line.kind === 'item' && line.item === selected)
393 if (near && lines[1] !== undefined && !(lines[1].kind === 'item' && lines[1].item === selected))
394 lines.splice(1, 1)
395 else lines.pop()
396 // A top item cut away leaves the next group's name right under this one.
397 if (lines[1]?.kind === 'group') lines.shift()
398 }
399 // A group's name with none of its items under it.
400 if (lines.at(-1)?.kind === 'group') lines.pop()
401 const shown = lines.flatMap(line => (line.kind === 'item' ? [items.indexOf(line.item)] : []))
402 return {
403 lines,
404 items: { start: shown[0] ?? 0, end: (shown.at(-1) ?? -1) + 1 },
405 }
406}
407hooks/domain/state.ts 83 lines1// What each `$.state` key reads before anything is written, and the shape tag
2// its atom is kept under. Bump a key's tag whenever its type in
3// types/index.d.ts changes: the new module then reads the old value as absent.
4
5import type {
6 Attention,
7 CatalogPage,
8 Degraded,
9 DetectProgress,
10 DevState,
11 HealthFacts,
12 JobQueue,
13 ModDetail,
14 ModRow,
15 ReviewRequest,
16 Sync,
17 View,
18} from '../../types/index.d.ts'
19
20/** `PluginState['modmgr']` with each `Shaped<T>` read as its `T`. */
21export type ModmgrState = {
22 mods: ModRow[]
23 detail: ModDetail | null
24 catalogPage: CatalogPage
25 detect: DetectProgress
26 queue: JobQueue
27 sync: Sync
28 view: View
29 review: ReviewRequest | null
30 attention: Attention
31 degraded: Degraded
32 dev: DevState
33 health: HealthFacts
34}
35
36export type StateKey = keyof ModmgrState
37
38export const SHAPES: Readonly<Record<StateKey, string>> = {
39 mods: 'mods/2',
40 detail: 'detail/2',
41 catalogPage: 'catalogPage/5',
42 detect: 'detect/2',
43 queue: 'queue/1',
44 sync: 'sync/2',
45 view: 'view/8',
46 review: 'review/4',
47 attention: 'attention/2',
48 degraded: 'degraded/1',
49 dev: 'dev/2',
50 health: 'health/1',
51}
52
53export const INITIAL_VIEW: View = {
54 tab: 'installed',
55 stack: [],
56 query: '',
57 search: '',
58 sort: 'installs',
59 staged: {},
60}
61
62export const INITIAL: Readonly<ModmgrState> = {
63 mods: [],
64 detail: null,
65 catalogPage: { rows: [], total: 0, community: 0, matched: 0, offset: 0, loading: false },
66 detect: { checked: 0, total: 0, found: 0, running: false },
67 queue: { owner: '', jobs: [] },
68 sync: { refreshing: false, skipped: 0 },
69 view: INITIAL_VIEW,
70 review: null,
71 attention: { updates: 0, problems: 0, reloadPending: false, capsChanged: 0 },
72 degraded: { process: false, network: false, acceptCommand: false },
73 dev: { rows: [], loading: false },
74 health: {
75 chain: [],
76 logged: {},
77 debugLog: { state: 'none' },
78 detector: { spent: 0, budget: 0, remote: false },
79 cache: { bytes: 0, full: false },
80 updates: { every: 0 },
81 },
82}
83hooks/domain/view.ts 881 lines1// The pane's logic as pure functions: which rows show, the staged
2// toggles and the review they become, the Esc cascade, the band's line and
3// the status line. services/actions.ts applies them to `$.state`; ui/ draws
4// what they return.
5
6import type {
7 Attention,
8 Job,
9 JobQueue,
10 ModRow,
11 Overlay,
12 ReviewOp,
13 ReviewRequest,
14 ReviewTarget,
15 Scope,
16 View,
17} from '../../types/index.d.ts'
18import { argvOf, commandOfJob } from './argv.ts'
19import { notableText } from './capabilities.ts'
20import { capsLine } from './caps-history.ts'
21import { isActive, type JobSpec, NEEDS_RELOAD, type UndoStep } from './jobs.ts'
22import { sanitize } from './sanitize.ts'
23
24/** The name part of a plugin id (`turn-band` of `turn-band@fixtures`). */
25export const nameOf = (id: string): string => {
26 const at = id.indexOf('@')
27 return at < 0 ? id : id.slice(0, at)
28}
29
30/** The one pane modmgr opens. */
31export const PANE_ID = 'modmgr'
32export const PANE_TITLE = 'mods'
33
34/** From this many body columns the list and the detail sit side by side. */
35export const SPLIT_MIN_COLUMNS = 80
36
37export type Layout = 'stacked' | 'split'
38
39/** The filter field's key. */
40export const FILTER_KEY = 'filter'
41
42/** A row's Button key: what `ui.focus` and `ui.press` name. */
43export const ROW_PREFIX = 'row:'
44export const rowKey = (id: string): string => `${ROW_PREFIX}${id}`
45/** The mod id a focused element names, when it is a row. */
46export const rowOfKey = (key: string | undefined): string | undefined =>
47 key?.startsWith(ROW_PREFIX) === true ? key.slice(ROW_PREFIX.length) : undefined
48
49export const layoutFor = (bodyColumns: number): Layout =>
50 bodyColumns >= SPLIT_MIN_COLUMNS ? 'split' : 'stacked'
51
52/** The list's columns beside the detail: about two fifths, never cramped or sprawling. */
53export const listColumnsFor = (bodyColumns: number): number =>
54 Math.max(28, Math.min(46, Math.floor(bodyColumns * 0.4)))
55
56/** How a dialog open asks: `holdToasts` only while nothing streams. */
57export type PaneOpen = {
58 readonly id: string
59 readonly title: string
60 readonly closeOnEscape: true
61 readonly focus?: true
62 readonly holdToasts?: true
63 readonly rows?: number
64 readonly columns?: number
65}
66
67/**
68 * Rows a dialog asks for inline: the list plus its chrome, at least 14 (a
69 * detail or a review is taller than a short list), never more than 24.
70 */
71export const rowsFor = (mods: number): number => Math.min(24, Math.max(14, mods + 6))
72
73/** Columns a docked dialog asks for: room for the list and the detail side by side. */
74export const DOCK_COLUMNS = 96
75/** The fewest columns the dock asks for: the list and detail stack below SPLIT_MIN_COLUMNS. */
76const DOCK_MIN_COLUMNS = 48
77/** The columns the dock leaves the transcript beside it, where the terminal has them. */
78const TRANSCRIPT_COLUMNS = 72
79
80/**
81 * Columns the dock asks for in a terminal `columns` wide: DOCK_COLUMNS, less
82 * what the transcript would then lose below TRANSCRIPT_COLUMNS, never under
83 * DOCK_MIN_COLUMNS.
84 */
85export const dockColumnsFor = (columns: number): number =>
86 Math.min(DOCK_COLUMNS, Math.max(DOCK_MIN_COLUMNS, columns - TRANSCRIPT_COLUMNS))
87
88export const paneOpen = (how: {
89 readonly focus: boolean
90 readonly hold: boolean
91 readonly mods: number
92 readonly title?: string
93 /** The dock's columns: the view's `dock`, which `/mods` sets. */
94 readonly dock: number | undefined
95}): PaneOpen => ({
96 id: PANE_ID,
97 title: how.title ?? PANE_TITLE,
98 closeOnEscape: true,
99 rows: rowsFor(how.mods),
100 columns: how.dock ?? DOCK_COLUMNS,
101 ...(how.focus ? { focus: true as const } : {}),
102 ...(how.hold ? { holdToasts: true as const } : {}),
103})
104
105/**
106 * Whether an open of the dialog holds other plugins' toasts: only while
107 * nothing runs or waits and the job log isn't on top, since a pane that stays
108 * open must not silence them for long.
109 */
110export const holdsToasts = (queue: JobQueue, view: View): boolean =>
111 !queue.jobs.some(isActive) && view.stack.at(-1) !== 'jobs'
112
113// ---- rows -------------------------------------------------------------------
114
115/** Installed rows matching the filter: by name or id, case-insensitive. */
116export const filterRows = (rows: readonly ModRow[], query: string): ModRow[] => {
117 const needle = query.trim().toLowerCase()
118 if (needle === '') return [...rows]
119 return rows.filter(
120 row => row.name.toLowerCase().includes(needle) || row.id.toLowerCase().includes(needle),
121 )
122}
123
124/** The rows `[start, end)` a window of `size` shows. */
125export type Window = { readonly start: number; readonly end: number }
126
127/**
128 * A window of `size` rows over `count`, centred on `index` where the list
129 * allows, so the rows on either side of the focused one are always drawn and
130 * the arrows walk onto them (the ring moves only between drawn elements).
131 */
132export const windowAround = (count: number, index: number, size: number): Window => {
133 const rows = Math.max(1, Math.floor(size))
134 if (count <= rows) return { start: 0, end: Math.max(0, count) }
135 const at = Math.min(Math.max(0, index), count - 1)
136 const start = Math.min(Math.max(0, at - Math.floor((rows - 1) / 2)), count - rows)
137 return { start, end: start + rows }
138}
139
140/**
141 * A window of `size` rows over `count` that stays where it was (`previous`, its
142 * first row) while `index` moves inside it, and shifts only as far as needed
143 * when `index` reaches its edge, keeping one row beyond the selection drawn. So
144 * the highlight moves down a still list, as in any list, instead of the list
145 * moving under it at every key. An `index` past the window turns a page: it
146 * leads the window going down, ends it going up. With no previous window it
147 * centres on `index`.
148 */
149export const windowFollowing = (
150 previous: number | undefined,
151 count: number,
152 index: number,
153 size: number,
154): Window => {
155 const rows = Math.max(1, Math.floor(size))
156 if (count <= rows) return { start: 0, end: Math.max(0, count) }
157 if (previous === undefined) return windowAround(count, index, rows)
158 const at = Math.min(Math.max(0, index), count - 1)
159 const margin = rows >= 4 ? 1 : 0
160 let start = Math.min(Math.max(0, previous), count - rows)
161 // A jump past the window (a page key, the next page) turns the page: the
162 // selection opens the new window, as a reader's page turns, not at its far edge.
163 if (at >= start + rows) start = at - margin
164 else if (at < start) start = at - (rows - 1 - margin)
165 else if (at < start + margin) start = at - margin
166 else if (at > start + rows - 1 - margin) start = at - (rows - 1 - margin)
167 start = Math.min(Math.max(0, start), count - rows)
168 return { start, end: start + rows }
169}
170
171/** `6–15 of 40`, or undefined when every row shows. */
172export const pagerLabel = (window: Window, count: number): string | undefined =>
173 window.start === 0 && window.end >= count
174 ? undefined
175 : `${(window.start + 1).toLocaleString('en-US')}–${window.end.toLocaleString('en-US')} of ${count.toLocaleString('en-US')}`
176
177/** The row the selection moves to when `id` goes: the next one shown, else the one before. */
178export const neighbourOf = (
179 view: View,
180 mods: readonly ModRow[],
181 id: string,
182): ModRow | undefined => {
183 const rows = filterRows(mods, view.query)
184 const at = rows.findIndex(row => row.id === id)
185 if (at < 0) return undefined
186 return rows[at + 1] ?? rows[at - 1]
187}
188
189/** The selected row's index among `rows`, 0 when it isn't there. */
190export const selectedIndex = (rows: readonly ModRow[], selected: string | undefined): number => {
191 const index = rows.findIndex(row => row.id === selected)
192 return index < 0 ? 0 : index
193}
194
195/**
196 * The row the pane shows as selected and every action acts on: the selection
197 * when the filter shows it, else the first row shown.
198 * One resolver, so the drawing and a press never disagree.
199 */
200export const selectedRow = (view: View, mods: readonly ModRow[]): ModRow | undefined => {
201 const rows = filterRows(mods, view.query)
202 return rows.find(row => row.id === view.selected) ?? rows[0]
203}
204
205// ---- staging ----------------------------------------------------------------
206
207/**
208 * Stages a toggle of `row`: flips what it will be after apply. Staging it
209 * back to its current state un-stages it. A row the CLI can't toggle is
210 * left alone.
211 */
212export const stageToggle = (view: View, row: ModRow): View => {
213 if (!row.toggleable) return view
214 const { [row.id]: current, ...rest } = view.staged
215 const target = !(current ?? row.enabled)
216 return { ...view, staged: target === row.enabled ? rest : { ...rest, [row.id]: target } }
217}
218
219export type Change = { readonly row: ModRow; readonly enable: boolean }
220
221/** The staged toggles that still change something, in row order. */
222export const stagedChanges = (view: View, rows: readonly ModRow[]): Change[] =>
223 rows.flatMap(row => {
224 const enable = view.staged[row.id]
225 return enable === undefined || enable === row.enabled || !row.toggleable
226 ? []
227 : [{ row, enable }]
228 })
229
230/** The ids whose staged entry still changes something: what rows and the detail mark as staged. */
231export const stagedIds = (view: View, rows: readonly ModRow[]): ReadonlySet<string> =>
232 new Set(stagedChanges(view, rows).map(change => change.row.id))
233
234/** Drops staged entries that no longer change anything (a refresh moved under them). */
235export const pruneStaged = (view: View, rows: readonly ModRow[]): View => {
236 const kept = Object.fromEntries(stagedChanges(view, rows).map(c => [c.row.id, c.enable]))
237 return Object.keys(kept).length === Object.keys(view.staged).length
238 ? view
239 : { ...view, staged: kept }
240}
241
242/** Why a row can't be toggled from here, in the person's terms; undefined when it can. */
243export const whyLocked = (row: ModRow): string | undefined => {
244 if (row.toggleable) return undefined
245 if (row.scope === 'managed') return "managed by your organisation; it can't be turned off here"
246 if (row.origin === 'env-dir')
247 return 'loaded from CLAUDE_CODE_PLUGIN_DIRS; take it out of that variable and restart to stop loading it'
248 if (row.origin === 'plugin-dir')
249 return 'loaded with --plugin-dir; leave the flag out of your launch command to stop loading it'
250 return "this session loaded it from its launch command; it can't be toggled here"
251}
252
253const cliScope = (scope: Scope | undefined): 'user' | 'project' | 'local' | undefined =>
254 scope === 'user' || scope === 'project' || scope === 'local' ? scope : undefined
255
256/** Why the CLI can't update a row, in the person's terms; undefined when it can. */
257export const whyNoUpdate = (row: ModRow): string | undefined => {
258 if (row.scope === 'managed') return 'managed by your organisation; it updates with their settings'
259 if (row.origin === 'folder-marketplace') return 'runs from its marketplace folder: no updates'
260 if (row.origin === 'skills-dir')
261 return 'lives in your skills folder; it changes when its files do'
262 return whyLocked(row)
263}
264
265/** Why the CLI can't remove a row; undefined when it can. */
266export const whyNoRemove = (row: ModRow): string | undefined => {
267 if (row.scope === 'managed') return "managed by your organisation; it can't be removed here"
268 if (row.origin === 'skills-dir') return 'lives in your skills folder; delete its folder there'
269 return whyLocked(row)
270}
271
272/** What a review needs to know about one mod beyond its row. */
273export type ReviewFacts = {
274 readonly notable: readonly string[]
275 readonly parts?: { readonly skills: number; readonly agents: number; readonly mcp: number }
276 /** Its data folder's size, when it has one. */
277 readonly dataBytes?: number
278}
279
280type Parts = { skills: number; agents: number; mcp: number }
281
282const addParts = (into: Parts, parts: ReviewFacts['parts']): void => {
283 if (parts === undefined) return
284 into.skills += parts.skills
285 into.agents += parts.agents
286 into.mcp += parts.mcp
287}
288
289const withParts = (review: ReviewRequest, parts: Parts): ReviewRequest =>
290 parts.skills + parts.agents + parts.mcp > 0 ? { ...review, parts } : review
291
292const targetOf = (row: ModRow, op: ReviewOp): ReviewTarget => {
293 const scope = cliScope(row.scope)
294 return {
295 id: row.id,
296 op,
297 ...(scope === undefined ? {} : { scope }),
298 ...(row.version === undefined ? {} : { version: row.version }),
299 }
300}
301
302const touchesRepo = (scope: Scope | undefined): boolean => scope === 'project' || scope === 'local'
303
304/** The review a batch of toggles opens: one confirm for the whole batch. */
305export const toggleReview = (
306 changes: readonly Change[],
307 facts: (id: string) => ReviewFacts | undefined,
308): ReviewRequest => {
309 const notable: string[] = []
310 const parts = { skills: 0, agents: 0, mcp: 0 }
311 for (const { row, enable } of changes) {
312 const known = facts(row.id)
313 if (enable) {
314 for (const id of known?.notable ?? []) notable.push(`${row.name}: ${notableText(id)}`)
315 } else {
316 addParts(parts, known?.parts)
317 }
318 }
319 return withParts(
320 {
321 action: 'toggle',
322 targets: changes.map(({ row, enable }) => targetOf(row, enable ? 'enable' : 'disable')),
323 notable,
324 changesRepoFile: changes.some(({ row }) => touchesRepo(row.scope)),
325 },
326 parts,
327 )
328}
329
330/** The marketplace a plugin id names. */
331export const marketplaceOf = (id: string): string => id.slice(id.indexOf('@') + 1)
332
333/**
334 * The review of updating `rows` (`u` one, `a` all): each marketplace is
335 * refreshed first, then each mod updated, then one reload. It runs new code,
336 * so it is always reviewed; it can't be undone.
337 */
338export const updateReview = (rows: readonly ModRow[]): ReviewRequest => {
339 const marketplaces = [...new Set(rows.map(row => marketplaceOf(row.id)))].sort()
340 return {
341 action: 'update',
342 targets: rows.map(row => targetOf(row, 'update')),
343 notable: [],
344 changesRepoFile: false,
345 marketplaces,
346 }
347}
348
349/**
350 * The review of removing `row` (`x`): what goes, from which scope, its other
351 * parts and its data, which is kept unless the person asks otherwise.
352 */
353export const removeReview = (row: ModRow, facts: ReviewFacts | undefined): ReviewRequest => {
354 const parts = { skills: 0, agents: 0, mcp: 0 }
355 addParts(parts, facts?.parts)
356 const review: ReviewRequest = {
357 action: 'remove',
358 targets: [targetOf(row, 'remove')],
359 notable: [],
360 changesRepoFile: touchesRepo(row.scope),
361 keepData: true,
362 }
363 return withParts(
364 facts?.dataBytes === undefined ? review : { ...review, dataBytes: facts.dataBytes },
365 parts,
366 )
367}
368
369const UNDO_OP: Readonly<Partial<Record<JobSpec['kind'], ReviewOp>>> = {
370 enable: 'enable',
371 disable: 'disable',
372 install: 'install',
373 remove: 'remove',
374}
375
376/**
377 * The review of an undo that reinstalls (the inverse of a remove): what comes
378 * back, what it can do, and that a declared install command stops it.
379 */
380export const undoReview = (
381 plan: { readonly batch: string; readonly steps: readonly UndoStep[] },
382 rows: readonly ModRow[],
383 facts: (id: string) => ReviewFacts | undefined,
384): ReviewRequest => {
385 const { steps } = plan
386 const notable: string[] = []
387 const parts = { skills: 0, agents: 0, mcp: 0 }
388 const targets = steps.flatMap(({ spec, undoes }): ReviewTarget[] => {
389 const op = UNDO_OP[spec.kind]
390 if (op === undefined || spec.target === undefined) return []
391 // A queue job's target is checked only when it runs: drawn, it is sanitised.
392 const name = sanitize(rows.find(row => row.id === spec.target)?.name ?? nameOf(spec.target), {
393 max: 40,
394 })
395 const known = facts(spec.target)
396 if (op === 'install' || op === 'enable') {
397 for (const id of known?.notable ?? []) notable.push(`${name}: ${notableText(id)}`)
398 } else {
399 addParts(parts, known?.parts)
400 }
401 const scope = cliScope(spec.args?.scope)
402 return [
403 {
404 id: spec.target,
405 op,
406 ...(scope === undefined ? {} : { scope }),
407 // What the CLI said it did with the data, not what modmgr asked.
408 ...(op === 'install' && undoes.keptData !== undefined ? { keptData: undoes.keptData } : {}),
409 },
410 ]
411 })
412 return withParts(
413 {
414 action: 'undo',
415 targets,
416 notable,
417 changesRepoFile: targets.some(target => touchesRepo(target.scope)),
418 undoes: plan.batch,
419 },
420 parts,
421 )
422}
423
424/** What each step of an undo does to its mod, said after the mod's name. */
425const UNDO_WORDS: Readonly<Partial<Record<JobSpec['kind'], (name: string) => string>>> = {
426 enable: name => `turn ${name} back on`,
427 disable: name => `turn ${name} back off`,
428 install: name => `reinstall ${name}`,
429 remove: name => `remove ${name}`,
430}
431
432/** What an undo does, in a few words: its one step by name, or how many it takes. */
433export const undoWords = (steps: readonly UndoStep[], rows: readonly ModRow[]): string => {
434 const [only] = steps
435 const words = only?.spec.target === undefined ? undefined : UNDO_WORDS[only.spec.kind]
436 if (steps.length !== 1 || only?.spec.target === undefined || words === undefined)
437 return `undo ${plural(steps.length, 'change', 'changes')}`
438 const { target } = only.spec
439 // A queue job's target is checked only when it runs: drawn, it is sanitised.
440 return words(sanitize(rows.find(row => row.id === target)?.name ?? nameOf(target), { max: 24 }))
441}
442
443/** The jobs a confirmed review queues (the batch's reload is added by `enqueue`). */
444export const specsOf = (review: ReviewRequest): JobSpec[] => {
445 if (review.action === 'marketplace') {
446 return review.source === undefined
447 ? []
448 : [{ kind: 'marketplace-add', args: { source: review.source } }]
449 }
450 const refresh: JobSpec[] = (review.marketplaces ?? []).map(name => ({
451 kind: 'marketplace-update',
452 target: name,
453 }))
454 // The sha of the command shown: the CLI runs it only while it still matches.
455 const accepted = (review.declaredCommand ?? review.headersHelper)?.sha256
456 const ops = review.targets.map((target): JobSpec => {
457 const scope = cliScope(target.scope)
458 const scoped = scope === undefined ? {} : { scope }
459 const kind = target.op
460 // An install from a marketplace not added yet names its source.
461 const from =
462 review.action === 'install' && kind === 'install' && review.source !== undefined
463 ? { source: review.source }
464 : {}
465 const args: Job['args'] =
466 kind === 'remove'
467 ? { ...scoped, keepData: review.keepData !== false }
468 : (kind === 'install' || kind === 'update') && accepted !== undefined
469 ? { ...scoped, ...from, acceptSha: accepted }
470 : { ...scoped, ...from }
471 return Object.keys(args).length === 0
472 ? { kind, target: target.id }
473 : { kind, target: target.id, args }
474 })
475 return [...refresh, ...ops]
476}
477
478/** The CLI line a job runs, for the review's "Runs" lines; undefined when it can't be built. */
479export const commandLine = (spec: JobSpec): string | undefined => {
480 const job: Job = { id: 'review', kind: spec.kind, state: 'queued', tail: [] }
481 const command = commandOfJob({
482 ...job,
483 ...(spec.target === undefined ? {} : { target: spec.target }),
484 ...(spec.args === undefined ? {} : { args: spec.args }),
485 })
486 return command.ok ? argvOf(command.value).join(' ') : undefined
487}
488
489/** `2 skills, 1 MCP server`; empty when there is nothing. */
490export const partsLabel = (parts: {
491 readonly skills: number
492 readonly agents: number
493 readonly mcp: number
494}): string => {
495 const say = (n: number, one: string, many: string) =>
496 n === 0 ? [] : [`${n} ${n === 1 ? one : many}`]
497 return [
498 ...say(parts.skills, 'skill', 'skills'),
499 ...say(parts.agents, 'agent', 'agents'),
500 ...say(parts.mcp, 'MCP server', 'MCP servers'),
501 ].join(', ')
502}
503
504/** `12 KB`: a data folder's size, rounded. */
505export const bytesLabel = (n: number): string =>
506 n < 1024
507 ? `${n} B`
508 : n < 1024 * 1024
509 ? `${Math.round(n / 1024)} KB`
510 : `${(n / 1048576).toFixed(1)} MB`
511
512/**
513 * The lines `[start, end)` a window of `rows` shows from line `at`, each line
514 * `heights[i]` rows tall. `last` is the furthest start that still fills the
515 * window, and `at` is held to it; one line always shows, however tall.
516 */
517export const lineWindow = (
518 heights: readonly number[],
519 rows: number,
520 at: number,
521): { start: number; end: number; last: number } => {
522 let last = heights.length
523 let tail = 0
524 while (last > 0 && tail + (heights[last - 1] ?? 0) <= rows) {
525 last -= 1
526 tail += heights[last] ?? 0
527 }
528 last = Math.min(last, Math.max(0, heights.length - 1))
529 const start = Math.max(0, Math.min(at, last))
530 let end = start
531 let used = 0
532 while (end < heights.length && (end === start || used + (heights[end] ?? 0) <= rows)) {
533 used += heights[end] ?? 0
534 end += 1
535 }
536 return { start, end, last }
537}
538
539/**
540 * `text` in rows of `width` characters, every one kept and in order: a command
541 * read row by row, where a wrapped Text would move whole words and a window
542 * could only show the line whole or not at all.
543 */
544export const cellRows = (text: string, width: number): string[] => {
545 const chars = [...text]
546 if (chars.length === 0) return ['']
547 const rows: string[] = []
548 for (let at = 0; at < chars.length; at += width) rows.push(chars.slice(at, at + width).join(''))
549 return rows
550}
551
552/**
553 * Rows `texts` wrap to at `columns`, each at least one (a wrapped Text's
554 * height): words move whole to the next row, as the terminal wraps them, and
555 * a word longer than the row is cut across rows.
556 */
557export const wrappedRows = (texts: readonly string[], columns: number): number => {
558 const width = Math.max(1, columns)
559 const rowsOf = (text: string): number => {
560 let rows = 1
561 let used = 0
562 for (const word of text.split(' ')) {
563 const length = [...word].length
564 const need = used === 0 ? length : used + 1 + length
565 if (need <= width) {
566 used = need
567 continue
568 }
569 if (used > 0) rows += 1
570 rows += Math.max(0, Math.ceil(length / width) - 1)
571 used = length % width === 0 && length > 0 ? width : length % width
572 }
573 return rows
574 }
575 return texts.reduce((sum, text) => sum + rowsOf(text), 0)
576}
577
578/**
579 * Rows a wrapping row of items takes at `columns` (the footer's keys, laid
580 * out with `columnGap`): each line fills until the next item would overflow.
581 */
582export const footerRowsFor = (widths: readonly number[], columns: number, gap = 2): number => {
583 const line = Math.max(1, columns)
584 let rows = 1
585 let used = 0
586 for (const width of widths) {
587 const need = used === 0 ? width : used + gap + width
588 if (used > 0 && need > line) {
589 rows += 1
590 used = width
591 } else {
592 used = need
593 }
594 // An item wider than the line wraps inside itself; the next starts on a new line.
595 if (used > line) {
596 rows += Math.ceil(used / line) - 1
597 used = line
598 }
599 }
600 return rows
601}
602
603// ---- overlays and Esc -------------------------------------------------------
604
605export const topOverlay = (view: View): Overlay | undefined => view.stack.at(-1)
606
607/** How far `overlay` is scrolled: its first line in view below what it keeps. */
608export const scrolledAt = (view: View, overlay: Overlay | undefined): number =>
609 view.overlayAt !== undefined && view.overlayAt.overlay === overlay ? view.overlayAt.at : 0
610
611/**
612 * Pushes an overlay, scrolled to its start; one already on the stack moves to
613 * the top instead of repeating.
614 */
615export const pushOverlay = ({ overlayAt: _scrolled, ...view }: View, overlay: Overlay): View => ({
616 ...view,
617 stack: [...view.stack.filter(item => item !== overlay), overlay],
618})
619
620export const popOverlay = (view: View): View =>
621 view.stack.length === 0 ? view : { ...view, stack: view.stack.slice(0, -1) }
622
623/** Opens an overlay, or closes it when it is already on top (the help and jobs keys). */
624export const toggleOverlay = (view: View, overlay: Overlay): View =>
625 topOverlay(view) === overlay ? popOverlay(view) : pushOverlay(view, overlay)
626
627export type Escape =
628 | { readonly kind: 'pop'; readonly view: View }
629 | { readonly kind: 'to-list' }
630 | { readonly kind: 'clear-query'; readonly view: View }
631 | { readonly kind: 'close' }
632
633/**
634 * What an Esc does: while the pane holds the keys it
635 * pops the top overlay, then brings the ring back to the list from a key
636 * (`ringAway`: beside the list, in the footer), then clears the filter, then
637 * closes. An Esc at the prompt (the pane not focused) always closes: the
638 * person can't see what a cascade would pop.
639 */
640export const escapeStep = (view: View, paneFocused: boolean, ringAway = false): Escape => {
641 if (!paneFocused) return { kind: 'close' }
642 if (view.stack.length > 0) return { kind: 'pop', view: popOverlay(view) }
643 if (ringAway) return { kind: 'to-list' }
644 // The field of the tab shown: Installed's filter, or Discover's search.
645 if (view.tab === 'discover' && view.search !== '')
646 return { kind: 'clear-query', view: { ...view, search: '' } }
647 if (view.tab === 'installed' && view.query !== '')
648 return { kind: 'clear-query', view: { ...view, query: '' } }
649 return { kind: 'close' }
650}
651
652/** The view a closed pane leaves: no overlays, no review half-done; staged toggles stay. */
653export const closedView = (view: View): View => {
654 const { notice: _notice, ...rest } = view
655 return { ...rest, stack: [] }
656}
657
658// ---- jobs: the batch line, the band, the status line and the title ------------
659
660const describeJob = (job: Job): string => {
661 const what =
662 job.kind === 'reload'
663 ? 'reload plugins'
664 : job.kind === 'marketplace-update'
665 ? 'refresh marketplace'
666 : job.kind
667 return job.target === undefined ? what : `${what} ${sanitize(job.target, { max: 60 })}`
668}
669
670/** The jobs of the newest batch, oldest first. */
671export const latestBatch = (jobs: readonly Job[]): Job[] => {
672 const batch = jobs.findLast(job => job.batch !== undefined)?.batch
673 return batch === undefined ? [] : jobs.filter(job => job.batch === batch)
674}
675
676export type Status = {
677 readonly tone: 'busy' | 'ok' | 'error'
678 readonly text: string
679}
680
681const plural = (n: number, one: string, many: string): string => `${n} ${n === 1 ? one : many}`
682
683/** How a finished batch's work reads: what changed, and what was unchanged. */
684export const doneText = (work: readonly Job[]): string => {
685 const changed = work.filter(job => job.state === 'ok' && job.unchanged !== true)
686 const same = work.length - changed.length
687 const updates = work.every(job => job.kind === 'update')
688 if (updates) {
689 if (changed.length === 0) return same === 1 ? 'already up to date' : 'all already up to date'
690 return same === 0
691 ? `${changed.length} updated`
692 : `${changed.length} updated, ${same} already up to date`
693 }
694 if (changed.length === 0) return 'nothing needed changing'
695 const [only] = changed
696 if (changed.length === 1 && same === 0 && only?.target !== undefined) {
697 const name = sanitize(nameOf(only.target), { max: 40 })
698 if (only.kind === 'remove') return `${name} removed`
699 if (only.kind === 'install') return `${name} installed`
700 }
701 const applied = plural(changed.length, 'change', 'changes')
702 return same === 0 ? `${applied} applied` : `${applied} applied, ${same} unchanged`
703}
704
705/**
706 * The jobs a batch counts as its work: not the reload, and not a marketplace
707 * refresh (a step of an update). The pane's batch line and the summary share
708 * it, so they count a batch alike.
709 */
710export const isWork = (job: Job): boolean =>
711 job.kind !== 'reload' && job.kind !== 'marketplace-update'
712
713/**
714 * One line about the newest batch, in the pane: what runs now, or how it
715 * ended. A failure stays until the next batch; a success shows only while
716 * `showDone` (the band's echo, which the runner clears after a while: that
717 * write is what redraws the pane). A batch that changed
718 * nothing gets the same echo, though its reload never ran.
719 */
720export const batchLineOf = (queue: JobQueue, showDone: boolean): Status | undefined => {
721 const jobs = latestBatch(queue.jobs)
722 if (jobs.length === 0) return undefined
723 const running = jobs.find(job => job.state === 'running')
724 const work = jobs.filter(isWork)
725 const done = work.filter(job => job.state !== 'queued' && job.state !== 'running').length
726 if (running !== undefined) {
727 if (running.kind === 'reload') return { tone: 'busy', text: 'reloading plugins…' }
728 if (running.kind === 'marketplace-update')
729 return { tone: 'busy', text: `${describeJob(running)}…` }
730 return { tone: 'busy', text: `${describeJob(running)} (${done + 1} of ${work.length})…` }
731 }
732 if (jobs.some(job => job.state === 'queued')) {
733 return work.every(job => job.state !== 'queued')
734 ? { tone: 'busy', text: 'reload waits for the settings to settle…' }
735 : { tone: 'busy', text: `${plural(work.length, 'change', 'changes')} queued…` }
736 }
737 const failed = jobs.filter(job => job.state === 'failed' || job.state === 'interrupted')
738 if (failed.length > 0) {
739 const first = failed[0]
740 const why = first?.error?.message === undefined ? '' : `: ${first.error.message}`
741 return {
742 tone: 'error',
743 text: `${failed.length} of ${jobs.length} failed (${describeJob(first as Job)}${why})`,
744 }
745 }
746 if (!showDone) return undefined
747 const reload = jobs.find(job => job.kind === 'reload')
748 if (work.length === 0) return { tone: 'ok', text: 'plugins reloaded' }
749 const text = doneText(work)
750 return { tone: 'ok', text: reload?.state === 'ok' ? `${text}, plugins reloaded` : text }
751}
752
753/**
754 * What modmgr has to say outside the dialog, in one value: the band,
755 * the status line and the pane title are each drawn from it, so they never
756 * disagree.
757 */
758export type Summary = {
759 /** The job running now, not the reload (a refresh, a change, a test). */
760 readonly running?: Job
761 /** Changes (jobs that need a reload) queued or running: what "applying" counts. */
762 readonly pending: number
763 /** The batch's reload is running (or waiting for the turn to end). */
764 readonly reloading: boolean
765 /** A reload is owed and none is queued: the band offers its reload key. */
766 readonly reloadOwed: boolean
767 /** The session lets only the person reload: they run /reload-plugins. */
768 readonly reloadByHand: boolean
769 readonly updates: number
770 /** Mods whose update added notable capabilities not yet seen. */
771 readonly capsCount: number
772 /** "turn-band can now run programs", when something is new. */
773 readonly caps?: string
774 /**
775 * The person dismissed the band line that said this news (updates, what an
776 * update added): the status line and the title leave it out too, until it
777 * changes. What is under way or owed is never quieted.
778 */
779 readonly newsDismissed: boolean
780 /** The CLI's answer to the last reload, or how a batch that needed none ended. */
781 readonly echo?: string
782}
783
784const reloadOwedText = (summary: Summary): string =>
785 summary.reloadByHand ? 'run /reload-plugins to apply' : 'reload to apply'
786
787const updatesText = (n: number): string | undefined =>
788 n > 0 ? plural(n, 'update', 'updates') : undefined
789
790export const summaryOf = (input: {
791 readonly attention: Attention
792 readonly queue: JobQueue
793 readonly mods: readonly ModRow[]
794}): Summary => {
795 const { attention, queue, mods } = input
796 const reloadJob = queue.jobs.find(job => job.kind === 'reload' && isActive(job))
797 const running = queue.jobs.find(job => job.kind !== 'reload' && job.state === 'running')
798 const caps = capsLine(mods)
799 const news = [updatesText(attention.updates), caps].filter(
800 (part): part is string => part !== undefined,
801 )
802 const said = new Set(attention.dismissed?.split(' · ') ?? [])
803 return {
804 ...(running === undefined ? {} : { running }),
805 pending: queue.jobs.filter(job => NEEDS_RELOAD.has(job.kind) && isActive(job)).length,
806 reloading: reloadJob?.state === 'running',
807 reloadOwed: attention.reloadPending && reloadJob === undefined,
808 reloadByHand: attention.reloadByHand === true,
809 updates: attention.updates,
810 capsCount: mods.filter(row => row.capsNew !== undefined).length,
811 ...(caps === undefined ? {} : { caps }),
812 newsDismissed: news.length > 0 && news.every(part => said.has(part)),
813 ...(attention.lastReload === undefined ? {} : { echo: attention.lastReload }),
814 }
815}
816
817export type Band = {
818 /** What was said: a dismissal hides the band until this changes. */
819 readonly key: string
820 readonly text: string
821 /** Offer the reload key: a reload is owed and none is queued. */
822 readonly reload: boolean
823}
824
825/**
826 * The band's one line: shown only when something is
827 * actionable and that very thing wasn't dismissed. `isWorking` is the band's
828 * `e.props.isWorking`: a reload asked mid-turn waits for the turn to end.
829 */
830export const bandOf = (
831 summary: Summary,
832 how: { readonly dismissed?: string | undefined; readonly isWorking: boolean },
833): Band | undefined => {
834 const parts: string[] = []
835 if (summary.running !== undefined) parts.push(`${describeJob(summary.running)}…`)
836 if (summary.reloading) {
837 parts.push(how.isWorking ? 'reload queued, runs when the turn ends' : 'reloading plugins…')
838 }
839 const updates = updatesText(summary.updates)
840 if (updates !== undefined) parts.push(updates)
841 if (summary.caps !== undefined) parts.push(summary.caps)
842 if (summary.reloadOwed) parts.push(reloadOwedText(summary))
843 if (parts.length === 0) {
844 if (summary.echo === undefined) return undefined
845 parts.push(summary.echo)
846 }
847 const text = `mods · ${parts.join(' · ')}`
848 if (how.dismissed === text) return undefined
849 return { key: text, text, reload: summary.reloadOwed && !summary.reloadByHand }
850}
851
852/**
853 * The status line under the prompt (`$.ui.status`, one per plugin, drawn
854 * `modmgr: <text>`): one clause, the most important, since it sits under
855 * every prompt. What is under way, then what is owed, then news the person
856 * hasn't dismissed (what an update added before how many updates wait);
857 * nothing when idle (undefined clears it). The band says the rest.
858 */
859export const statusLineOf = (summary: Summary): string | undefined => {
860 const { running } = summary
861 if (running?.kind === 'marketplace-update') return `${describeJob(running)}…`
862 if (summary.pending > 0) return `applying ${summary.pending}…`
863 if (running !== undefined) return `${describeJob(running)}…`
864 if (summary.reloading) return 'reloading plugins…'
865 if (summary.reloadOwed) return reloadOwedText(summary)
866 if (summary.newsDismissed) return undefined
867 // The engine names the plugin before it (`modmgr: …`).
868 return summary.caps ?? updatesText(summary.updates)
869}
870
871/** The pane's title: `mods`, with news not dismissed (a retitle is an open). */
872export const titleOf = (summary: Summary): string => {
873 const parts = [PANE_TITLE]
874 if (!summary.newsDismissed) {
875 const updates = updatesText(summary.updates)
876 if (updates !== undefined) parts.push(updates)
877 if (summary.capsCount > 0) parts.push(`${summary.capsCount} can do more`)
878 }
879 return parts.join(' · ')
880}
881hooks/ports.ts 150 lines1// The ports services and views take in place of `$`. Types only: every
2// builder lives in register.tsx, the one file that spells `$`. Each noun
3// is its own interface, so a service asks for `Pick<Ports, 'process' | 'state'>`
4// and a test fakes only those nouns.
5
6import type {
7 CommandInfo,
8 ProcessRunResult,
9 ProcessSpawnChunk,
10 ProcessSpawnResult,
11 RenderSurface,
12 SessionRepo,
13 SessionVersion,
14 Timer,
15 UiCopyResult,
16 UiFocusResult,
17 UiOpenResult,
18 UiPane,
19} from 'claude-code'
20import type { ModmgrState, StateKey } from './domain/state.ts'
21import type { PaneOpen } from './domain/view.ts'
22
23export type { ModmgrState, StateKey }
24
25/**
26 * How a child runs. There is deliberately no `env`: children inherit the
27 * session's environment untouched (never strip `CLAUDECODE` to slip past a refusal).
28 */
29export type RunInit = { readonly cwd?: string; readonly timeoutMs?: number }
30
31export interface ProcessPort {
32 run(argv: readonly string[], init?: RunInit): Promise<ProcessRunResult>
33 /** Streams a child; leaving the loop (or `return()`) kills it. */
34 spawn(
35 argv: readonly string[],
36 init?: Pick<RunInit, 'cwd'>,
37 ): AsyncGenerator<ProcessSpawnChunk, ProcessSpawnResult>
38}
39
40/** modmgr's own `$.state` keys, read and written through shaped atoms. */
41export interface StatePort {
42 read<K extends StateKey>(key: K): Promise<ModmgrState[K]>
43 /** Compare-and-set with retry (`update` from claude-code): concurrent writers both land. */
44 update<K extends StateKey>(
45 key: K,
46 change: (value: ModmgrState[K]) => ModmgrState[K],
47 ): Promise<ModmgrState[K]>
48}
49
50export interface StorePort {
51 get(key: string): Promise<unknown>
52 /** Rejects past 4 MiB of JSON in all. */
53 set(key: string, value: unknown): Promise<void>
54 delete(key: string): Promise<void>
55 keys(): Promise<string[]>
56}
57
58export interface ClockPort {
59 now(): Promise<number>
60 after(ms: number, fn: () => void): Timer
61 every(ms: number, fn: () => void): Timer
62}
63
64/** The variables modmgr reads, one method each (`$.env.get` takes literals only). */
65export interface EnvPort {
66 /** `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`: any non-empty value turns modmgr's network use off. */
67 nonessentialTraffic(): Promise<string | undefined>
68 /** `CLAUDE_CONFIG_DIR` and `HOME`: where this session's mods folder is (Dev). */
69 configDir(): Promise<string | undefined>
70 home(): Promise<string | undefined>
71 /** `MODMGR_INDEX_URL`: where to read the catalogue index instead, to try one before it is published. */
72 indexUrl(): Promise<string | undefined>
73}
74
75export interface SessionPort {
76 root(): Promise<string>
77 /** modmgr's own folder, the one holding its plugin.json, as this session loaded it. */
78 ownRoot(): Promise<string>
79 cwd(): Promise<string>
80 id(): Promise<string>
81 /** The git repository the session runs in (its `origin` remote), or null. */
82 repo(): Promise<SessionRepo | null>
83 surfaces(): Promise<readonly RenderSurface[]>
84 version(): Promise<SessionVersion>
85}
86
87export interface CommandPort {
88 /**
89 * Registers `/mods`. Spelled in register.tsx with a literal name, which keeps
90 * the `/mods` hook "answering its own command" rather than a gate.
91 */
92 registerMods(): Promise<void>
93 /** `/reload-plugins`; rejects inside a hook the turn waits on. Resolves the CLI's line. */
94 reloadPlugins(): Promise<string | undefined>
95 list(): Promise<readonly CommandInfo[]>
96}
97
98export interface UiPort {
99 /** One line to the debug log (`--debug`), never the transcript. */
100 debug(text: string): void
101 panes(): Promise<readonly UiPane[]>
102 /** Opens modmgr's pane, or retitles it and sets its manners anew when open. */
103 open(args: PaneOpen): Promise<UiOpenResult>
104 close(id: string): Promise<void>
105 /** Moves the pane's focus ring onto an element it drew (rejects or denies when it can't). */
106 focus(requestId: string, key: string): Promise<UiFocusResult>
107 copy(text: string, surface?: RenderSurface): Promise<UiCopyResult>
108 /** modmgr's one status line under the prompt; undefined clears it. */
109 status(text: string | undefined): void
110 /** A notification through the person's own channel: whether it was sent (a debug line when not). */
111 notify(text: string): Promise<boolean>
112}
113
114/** The network, through the host. Used only for raw.githubusercontent.com: the catalogue index and the detector's probes. */
115export interface HttpPort {
116 /**
117 * A GET of `url` for at most `maxBytes + 1` bytes: a Range request, so a
118 * server that honours it never sends more, and a longer body is known to be
119 * too long without reading it whole. A range answered (206) reads as 200.
120 */
121 get(url: string, maxBytes: number): Promise<{ readonly status: number; readonly text: string }>
122}
123
124/** The plugin's names of a directory's entries (`$.fs.list`). */
125export type DirEntry = { readonly name: string; readonly kind: 'file' | 'dir' | 'other' }
126
127/**
128 * Reads plugin manifests and lists plugin folders: local catalogue sources
129 * (Discover) and folders of mods under development (Dev). Never writes.
130 */
131export interface FsPort {
132 /** A file's text; rejects when missing or over 4 MiB. */
133 read(path: string): Promise<string>
134 /** A directory's entries; rejects when it is missing. */
135 list(path: string): Promise<readonly DirEntry[]>
136}
137
138export type Ports = {
139 process: ProcessPort
140 state: StatePort
141 store: StorePort
142 clock: ClockPort
143 env: EnvPort
144 session: SessionPort
145 command: CommandPort
146 ui: UiPort
147 http: HttpPort
148 fs: FsPort
149}
150hooks/services/actions.ts 932 lines1// What the pane's Buttons, its Input, the band and the focus ring do:
2// each reads and writes `$.state` through the dispatch's own ports, then asks
3// the module's runtime to run what it queued (`kick`). No job ever runs here.
4// Every action catches its own failure: a press must never throw into the host.
5
6import type { RenderSurface } from 'claude-code'
7import type { DevRow, ReviewRequest, Tab, View } from '../../types/index.d.ts'
8import { type DevRunKind, devKey, devRowOf, lastRun } from '../domain/dev.ts'
9import {
10 acceptReview,
11 awaitingAcceptance,
12 communityInstallReview,
13 foundKey,
14 foundRow,
15 installReview,
16 isInstallScope,
17 MARKETPLACE_KEY,
18 marketplaceReview,
19 nextSort,
20 withScope,
21} from '../domain/discover.ts'
22import { type HealthItem, healthItemsOf, healthKey } from '../domain/health.ts'
23import {
24 enqueueReload,
25 isActive,
26 prune,
27 stillUndoes,
28 undoNeedsReview,
29 undoPlan,
30} from '../domain/jobs.ts'
31import {
32 closedView,
33 escapeStep,
34 FILTER_KEY,
35 filterRows,
36 holdsToasts,
37 neighbourOf,
38 PANE_ID,
39 paneOpen,
40 popOverlay,
41 pruneStaged,
42 pushOverlay,
43 removeReview,
44 rowKey,
45 scrolledAt,
46 selectedRow,
47 specsOf,
48 stagedChanges,
49 stageToggle,
50 summaryOf,
51 titleOf,
52 toggleOverlay,
53 toggleReview,
54 topOverlay,
55 undoReview,
56 undoWords,
57 updateReview,
58 whyLocked,
59 whyNoRemove,
60 whyNoUpdate,
61} from '../domain/view.ts'
62import type { Ports } from '../ports.ts'
63import { enqueue } from './job-runner.ts'
64import type { Runtime } from './runtime.ts'
65
66export type ActionPorts = Pick<Ports, 'state' | 'ui'>
67
68/** The parts of the module's runtime an action reaches; absent before the first `session.start`. */
69export type ActionRuntime = Pick<
70 Runtime,
71 | 'registry'
72 | 'showTab'
73 | 'runner'
74 | 'newJobId'
75 | 'chrome'
76 | 'catalog'
77 | 'detector'
78 | 'dev'
79 | 'health'
80 | 'updater'
81 | 'store'
82>
83
84/** What Health's "check now" says, by what the scheduler did. */
85const CHECK_SAID: Readonly<Record<'queued' | 'busy' | 'off' | 'nothing', string>> = {
86 queued: 'Checking the marketplaces for updates…',
87 busy: 'Busy now (a turn or a reload); try again in a moment',
88 off: 'Update checks are off',
89 nothing: 'No installed mod comes from a marketplace that updates',
90}
91
92export type Actions = {
93 tab(tab: Tab): Promise<void>
94 /** The focus ring landed on a row: it becomes the selection (the split's detail follows). */
95 focusRow(id: string): Promise<void>
96 /** Enter on a row: its detail, in full (beside the list, over it). */
97 open(id: string): Promise<void>
98 /** Pops the top overlay (a review popped is a review cancelled). */
99 back(): Promise<void>
100 /** Stages a toggle of the selected mod, or of `id`. */
101 toggle(id?: string): Promise<void>
102 /** `u`: reviews updating the selected mod, or `id`. */
103 update(id?: string): Promise<void>
104 /** `a`: reviews updating every mod the CLI can update. */
105 updateAll(): Promise<void>
106 /** `x`: reviews removing the selected mod, or `id`. */
107 remove(id?: string): Promise<void>
108 /** `d` on a remove's review: keep the mod's data (the default) or delete it too. */
109 keepData(): Promise<void>
110 /** Opens the review of what is staged. */
111 apply(): Promise<void>
112 /** `y` on the review: queues the batch and its reload. */
113 confirm(): Promise<void>
114 /** `n` on the review. */
115 cancel(): Promise<void>
116 /** Queues the inverse of the last batch; one that reinstalls is reviewed first. */
117 undo(): Promise<void>
118 refresh(): Promise<void>
119 /** Queues a reload on its own (the band's reload key). */
120 reload(): Promise<void>
121 overlay(which: 'help' | 'jobs'): Promise<void>
122 filter(text: string): Promise<void>
123 /** Enter in the field: the filter, then the ring onto the row it leaves selected. */
124 submitFilter(text: string): Promise<void>
125 /** `f`: the ring onto the filter field. */
126 focusFilter(): Promise<void>
127 /** Moves the selection to the first or last row the filter shows, and the ring with it. */
128 edge(which: 'first' | 'last'): Promise<void>
129 /**
130 * The wheel, j and k, the page keys: moves the selection `by` rows (negative: up),
131 * the ring with it; over a review, its lines, no further than `last`.
132 */
133 scroll(by: number, last?: number): Promise<void>
134 copy(text: string, surface?: RenderSurface): Promise<void>
135 /** Opens the dialog from the band. */
136 openPane(): Promise<void>
137 /** The ring landed on a Discover row: it becomes the selection (the window follows). */
138 focusFound(id: string): Promise<void>
139 /** Enter on a Discover row: its detail (a local entry is read with `validate` first). */
140 openFound(id: string): Promise<void>
141 /** `i`: reviews installing the selected catalogue entry, or `id`. */
142 install(id?: string): Promise<void>
143 /** The install review's scope Select. */
144 scope(value: string): Promise<void>
145 /** `o`: the next sort. */
146 cycleSort(): Promise<void>
147 /** `k`: Discover lists only your marketplaces' entries, or everything again. */
148 toggleMine(): Promise<void>
149 /** `v`: reviews the declared command a stopped install or update showed. */
150 acceptShown(): Promise<void>
151 /** `m`: asks for a marketplace to add. */
152 addMarketplace(): Promise<void>
153 /** The marketplace field's Enter: reviews adding it, or says why it can't be one. */
154 submitMarketplace(text: string): Promise<void>
155 /** The footer's close: the same `ui.close` as Esc, origin `plugin`. */
156 close(): Promise<void>
157 /** Hides the band's current line. */
158 dismiss(line: string): Promise<void>
159 cancelJob(id: string): Promise<void>
160 /** The ring landed on a Dev row: it becomes Dev's selection (the split's detail follows). */
161 focusDev(key: string): Promise<void>
162 /** Enter on a Dev row: its detail. */
163 openDev(key: string): Promise<void>
164 /** `v` / `t` on Dev: validates (`--strict`) or tests the selected dev mod, or `key`. */
165 devRun(kind: DevRunKind, key?: string): Promise<void>
166 /** `p` on Dev: how to share the selected dev mod, or `key`. */
167 share(key?: string): Promise<void>
168 /** The ring landed on a Health item: it becomes Health's selection. */
169 focusHealth(key: string): Promise<void>
170 /** A Health item's fix: its button in the detail. */
171 fix(key: string): Promise<void>
172 /** Enter on a Health item, stacked: the item whole (its row is clipped), its fix a button. */
173 openHealth(key: string): Promise<void>
174 /**
175 * Esc and the close mark (`ui.close`, origin `person`): true keeps the pane
176 * open. `hadKeys` is whether the pane held the keys when it was last drawn
177 * on the terminal. Esc hands the keys back to the prompt before the hook runs
178 * is raised, so the cascade answers only when the pane had them then and has them
179 * no more; the close mark and ctrl+x x leave them with the pane and
180 * close. A kept pane re-takes the keys. `ringAway`: the ring was on a key
181 * rather than the list or its field, so this Esc brings it back to the list.
182 */
183 closing(
184 origin: 'person' | 'plugin' | 'unload',
185 hadKeys: boolean,
186 ringAway?: boolean,
187 ): Promise<boolean>
188}
189
190export const createActions = (
191 ports: ActionPorts,
192 rt: ActionRuntime | undefined,
193 debug: (text: string) => void = text => ports.ui.debug(text),
194): Actions => {
195 const { state, ui } = ports
196 const setView = (change: (view: View) => View) => state.update('view', change)
197 const notice = (text: string) => setView(view => ({ ...view, notice: text }))
198 const quiet = (view: View): View => {
199 if (view.notice === undefined) return view
200 const { notice: _gone, ...rest } = view
201 return rest
202 }
203
204 /** Runs an action, logging (never throwing) what fails. */
205 const safely =
206 <A extends unknown[]>(name: string, fn: (...args: A) => Promise<void>) =>
207 async (...args: A): Promise<void> => {
208 try {
209 await fn(...args)
210 } catch (error) {
211 debug(`modmgr: ${name} failed: ${String(error)}`)
212 }
213 }
214
215 const select = async (id: string | undefined): Promise<void> => {
216 await rt?.registry.select(id)
217 }
218
219 /**
220 * Opens (or re-opens) the dialog with its manners and the current title: a
221 * re-open sets both anew, so every open says them. Toasts are held
222 * only while nothing runs.
223 */
224 const openDialog = async (how: { focus: boolean; idle?: boolean }): Promise<void> => {
225 const [attention, queue, mods, view] = await Promise.all([
226 state.read('attention'),
227 state.read('queue'),
228 state.read('mods'),
229 state.read('view'),
230 ])
231 const idle = how.idle ?? holdsToasts(queue, view)
232 const title = titleOf(summaryOf({ attention, queue, mods }))
233 await ui.open(
234 paneOpen({ focus: how.focus, hold: idle, mods: mods.length, title, dock: view.dock }),
235 )
236 }
237
238 /** Queues a batch and its reload; `when` guards it against a queue that moved since it was read. */
239 const queueBatch = async (
240 specs: Parameters<typeof enqueue>[1]['specs'],
241 when?: Parameters<typeof enqueue>[3],
242 ): Promise<'queued' | 'stale' | 'starting'> => {
243 if (rt === undefined) {
244 await notice('modmgr is still starting; try again in a moment')
245 return 'starting'
246 }
247 const queued = await enqueue(
248 ports,
249 { id: rt.newJobId(), specs, reload: true },
250 () => rt.newJobId(),
251 when,
252 )
253 if (!queued) return 'stale'
254 // These are the dispatch's writes, not the runtime's: say so to the status line.
255 rt.chrome.schedule()
256 // A pane left open while jobs run must not hold other plugins' toasts.
257 if ((await ui.panes()).some(pane => pane.id === PANE_ID)) {
258 await openDialog({ focus: false, idle: false })
259 }
260 rt.runner.kick()
261 return 'queued'
262 }
263
264 /** Re-takes the keys after an Esc the cascade answered (the selected row's autoFocus takes the ring). */
265 const retake = (): Promise<void> => openDialog({ focus: true })
266
267 /**
268 * Puts the ring on the first of `keys` the pane draws (a ring whose
269 * Button a redraw removed goes nowhere). `$.ui.focus` awaits an element the
270 * redraw is about to draw; a denial or a refusal tries the next key.
271 */
272 const ringTo = async (...keys: readonly string[]): Promise<void> => {
273 for (const key of keys) {
274 const moved = await ui.focus(PANE_ID, key).catch(() => ({ deny: 'refused' }))
275 if (!('deny' in moved) || moved.deny === undefined) return
276 }
277 }
278
279 /** The ring back on the selected row once no overlay is on top. */
280 const ringToSelection = async (): Promise<void> => {
281 const [view, mods, page] = await Promise.all([
282 state.read('view'),
283 state.read('mods'),
284 state.read('catalogPage'),
285 ])
286 if (view.stack.length > 0) return
287 if (view.tab === 'discover') {
288 const found = foundRow(view, page)
289 if (found !== undefined) await ringTo(foundKey(found.id))
290 return
291 }
292 if (view.tab === 'dev') {
293 const row = devRowOf(view.dev, (await state.read('dev')).rows)
294 if (row !== undefined) await ringTo(devKey(row.key))
295 return
296 }
297 if (view.tab === 'health') {
298 const items = await healthItems()
299 const item = items.find(each => each.key === view.health) ?? items[0]
300 if (item !== undefined) await ringTo(healthKey(item.key))
301 return
302 }
303 const row = selectedRow(view, mods)
304 if (row !== undefined) await ringTo(rowKey(row.id))
305 }
306
307 /**
308 * Discover's window follows its search and selection. The catalogue is module
309 * memory: a reloaded modmgr starts without it, so it is read on demand (once).
310 */
311 const showCatalog = async (): Promise<void> => {
312 if (rt === undefined) return
313 await rt.catalog.load()
314 await rt.catalog.show()
315 }
316
317 /**
318 * Moves the selection to the row `choose` picks, given how many rows the tab
319 * lists and the selected one's index (held to the ends), and the ring with it.
320 * Health's few items have no rows to page through.
321 */
322 const moveSelection = async (choose: (count: number, at: number) => number): Promise<void> => {
323 const pick = (count: number, at: number) => Math.max(0, Math.min(count - 1, choose(count, at)))
324 const view = await state.read('view')
325 if (view.tab === 'health') {
326 const items = await healthItems()
327 const current = items.findIndex(each => each.key === view.health)
328 const item = items[pick(items.length, Math.max(0, current))]
329 if (item === undefined || item === items[current]) return
330 await setView(shown => ({ ...quiet(shown), health: item.key }))
331 await ui.focus(PANE_ID, healthKey(item.key)).catch(() => undefined)
332 return
333 }
334 if (view.tab === 'dev') {
335 const { rows } = await state.read('dev')
336 const current = devRowOf(view.dev, rows)
337 const row = rows[pick(rows.length, current === undefined ? 0 : rows.indexOf(current))]
338 if (row === undefined || row === current) return
339 await setView(shown => ({ ...quiet(shown), dev: row.key }))
340 await ui.focus(PANE_ID, devKey(row.key)).catch(() => undefined)
341 return
342 }
343 if (view.tab === 'discover') {
344 await rt?.catalog.load()
345 const id = rt?.catalog.pick(view.found, pick)
346 if (id === undefined || id === view.found) return
347 await setView(shown => ({ ...quiet(shown), found: id }))
348 await showCatalog()
349 await ui.focus(PANE_ID, foundKey(id)).catch(() => undefined)
350 return
351 }
352 const mods = await state.read('mods')
353 const rows = filterRows(mods, view.query)
354 const current = selectedRow(view, mods)
355 const row = rows[pick(rows.length, current === undefined ? 0 : rows.indexOf(current))]
356 if (row === undefined || row === current) return
357 await setView(shown => ({ ...quiet(shown), selected: row.id }))
358 await select(row.id)
359 // The row may be drawn only after the redraw this write causes; focus awaits it.
360 await ui.focus(PANE_ID, rowKey(row.id)).catch(() => undefined)
361 }
362
363 /** The ring onto what an overlay offers first: its safe default (review: cancel). */
364 const ringToOverlay = async (): Promise<void> => {
365 const view = await state.read('view')
366 const top = topOverlay(view)
367 if (top === undefined) return ringToSelection()
368 if (top === 'review') return ringTo('act:cancel')
369 if (top === 'marketplace') return ringTo(MARKETPLACE_KEY)
370 if (top === 'detail' && view.tab === 'discover') return ringTo('act:install', 'act:copy')
371 if (top === 'detail' && view.tab === 'dev') return ringTo('act:validate', 'act:copy')
372 if (top === 'detail' && view.tab === 'health') return ringTo('act:fix', 'act:back')
373 if (top === 'share') return ringTo('act:copy')
374 if (top === 'welcome') return ringTo('act:start')
375 if (top === 'detail') return ringTo('act:toggle', 'act:copy')
376 return ringTo(top === 'help' ? 'act:help' : 'act:jobs')
377 }
378
379 const dropReview = async (): Promise<void> => {
380 await state.update('review', () => null)
381 }
382
383 /** Puts a review on top, the ring on its safe default (cancel). */
384 const openReview = async (review: ReviewRequest): Promise<void> => {
385 await state.update('review', () => review)
386 // A new review starts at its top.
387 await setView(current => pushOverlay(quiet(current), 'review'))
388 await ringToOverlay()
389 }
390
391 /** Health's items as the pane draws them. */
392 const healthItems = async (): Promise<HealthItem[]> => {
393 const [mods, attention, degraded, sync, detect, queue, facts] = await Promise.all([
394 state.read('mods'),
395 state.read('attention'),
396 state.read('degraded'),
397 state.read('sync'),
398 state.read('detect'),
399 state.read('queue'),
400 state.read('health'),
401 ])
402 return healthItemsOf({ mods, attention, degraded, sync, detect, queue, facts })
403 }
404
405 /** The welcome on the stack is being left: it isn't said again. */
406 const seenWelcome = (view: View): void => {
407 if (!view.stack.includes('welcome')) return
408 rt?.store.update('prefs', prefs =>
409 prefs.firstRunDone ? prefs : { ...prefs, firstRunDone: true },
410 )
411 }
412
413 /** The tab and sort a next session opens with (the store's prefs, written in a batch). */
414 const remember = (view: View): void => {
415 rt?.store.update('prefs', prefs =>
416 prefs.tab === view.tab && prefs.sort === view.sort
417 ? prefs
418 : { ...prefs, tab: view.tab, sort: view.sort },
419 )
420 }
421
422 /** The Dev row an action names, or the selected one. */
423 const devRowFor = async (key: string | undefined): Promise<DevRow | undefined> => {
424 const [view, dev] = await Promise.all([state.read('view'), state.read('dev')])
425 return key === undefined ? devRowOf(view.dev, dev.rows) : dev.rows.find(row => row.key === key)
426 }
427
428 /** The row an action names, or the selected one. */
429 const rowFor = async (id: string | undefined) => {
430 const [view, mods] = await Promise.all([state.read('view'), state.read('mods')])
431 return id === undefined ? selectedRow(view, mods) : mods.find(item => item.id === id)
432 }
433
434 const actions: Actions = {
435 tab: safely('tab', async tab => {
436 // A review on the stack and in state go together.
437 await dropReview()
438 const view = await setView(current => ({ ...quiet(current), tab, stack: [] }))
439 remember(view)
440 await rt?.showTab(tab)
441 await ringToSelection()
442 }),
443
444 focusRow: safely('focus', async id => {
445 const view = await state.read('view')
446 if (view.selected === id) return
447 await setView(current => ({ ...quiet(current), selected: id }))
448 await select(id)
449 }),
450
451 open: safely('open', async id => {
452 await setView(view => pushOverlay({ ...quiet(view), selected: id }, 'detail'))
453 await select(id)
454 await ringToOverlay()
455 // Opening the detail is seeing what its update added.
456 await rt?.registry.acknowledge(id)
457 }),
458
459 back: safely('back', async () => {
460 const view = await state.read('view')
461 if (topOverlay(view) === 'review') await dropReview()
462 seenWelcome(view)
463 await setView(current => popOverlay(quiet(current)))
464 await ringToOverlay()
465 }),
466
467 toggle: safely('toggle', async id => {
468 const row = await rowFor(id)
469 if (row === undefined) return
470 const locked = whyLocked(row)
471 if (locked !== undefined) {
472 await notice(`${row.name}: ${locked}`)
473 return
474 }
475 await setView(current => stageToggle(quiet(current), row))
476 }),
477
478 update: safely('update', async id => {
479 const row = await rowFor(id)
480 if (row === undefined) return
481 const why = whyNoUpdate(row)
482 if (why !== undefined) {
483 await notice(`${row.name}: ${why}`)
484 return
485 }
486 await openReview(updateReview([row]))
487 }),
488
489 updateAll: safely('update all', async () => {
490 const mods = await state.read('mods')
491 const rows = mods.filter(row => whyNoUpdate(row) === undefined)
492 if (rows.length === 0) {
493 await notice(
494 mods.length === 0 ? 'No mods installed' : 'None of these mods updates through the CLI',
495 )
496 return
497 }
498 await openReview(updateReview(rows))
499 }),
500
501 remove: safely('remove', async id => {
502 const row = await rowFor(id)
503 if (row === undefined) return
504 const why = whyNoRemove(row)
505 if (why !== undefined) {
506 await notice(`${row.name}: ${why}`)
507 return
508 }
509 await openReview(removeReview(row, rt?.registry.facts(row.id)))
510 }),
511
512 keepData: safely('keep data', async () => {
513 await state.update('review', review =>
514 review?.action === 'remove' ? { ...review, keepData: review.keepData === false } : review,
515 )
516 }),
517
518 apply: safely('apply', async () => {
519 const [view, mods] = await Promise.all([state.read('view'), state.read('mods')])
520 const changes = stagedChanges(view, mods)
521 if (changes.length === 0) {
522 await setView(current => pruneStaged({ ...current, notice: 'Nothing is staged' }, mods))
523 return
524 }
525 await openReview(toggleReview(changes, id => rt?.registry.facts(id)))
526 }),
527
528 confirm: safely('confirm', async () => {
529 // Taken by compare-and-set: of two presses before the redraw (a hotkey and
530 // an Enter), one gets the review and the other finds none.
531 let taken: ReviewRequest | null = null
532 await state.update('review', review => {
533 taken = review
534 return null
535 })
536 const review = taken as ReviewRequest | null
537 if (review === null) return
538 // An undo reviewed is queued only while its batch is still the one to undo.
539 const { undoes } = review
540 const queued = await queueBatch(
541 specsOf(review),
542 undoes === undefined ? undefined : queue => stillUndoes(queue.jobs, undoes),
543 )
544 if (queued === 'starting') {
545 await state.update('review', current => current ?? review)
546 return
547 }
548 const ids = new Set(review.targets.map(target => target.id))
549 // A removed mod's detail goes with it, and the selection moves on, or the
550 // ring would land on a row the refresh is about to take away.
551 const gone = review.targets.find(target => target.op === 'remove')?.id
552 // An entry installed leaves the catalogue: its Discover detail goes too.
553 const installed = review.action === 'install' && (await state.read('view')).tab === 'discover'
554 const mods = await state.read('mods')
555 await setView(view => {
556 const staged = Object.fromEntries(
557 Object.entries(view.staged).filter(([id]) => !ids.has(id)),
558 )
559 const stack = view.stack.filter(
560 overlay =>
561 overlay !== 'review' && !((gone !== undefined || installed) && overlay === 'detail'),
562 )
563 const next = gone === undefined ? undefined : neighbourOf(view, mods, gone)
564 const moved = next === undefined ? {} : { selected: next.id }
565 const said =
566 queued === 'stale'
567 ? { notice: 'The last batch changed since this undo was shown; nothing was queued' }
568 : {}
569 return { ...quiet(view), staged, stack, ...moved, ...said }
570 })
571 if (gone !== undefined) await select((await state.read('view')).selected)
572 await ringToOverlay()
573 }),
574
575 cancel: safely('cancel', async () => {
576 await dropReview()
577 await setView(view => ({
578 ...quiet(view),
579 stack: view.stack.filter(overlay => overlay !== 'review'),
580 }))
581 await ringToOverlay()
582 }),
583
584 undo: safely('undo', async () => {
585 const [queue, mods] = await Promise.all([state.read('queue'), state.read('mods')])
586 const plan = undoPlan(queue.jobs)
587 if (plan.kind === 'none') {
588 await notice(plan.reason)
589 return
590 }
591 // A reinstall runs the mod's code again: reviewed, as an install is.
592 if (undoNeedsReview(plan)) {
593 await openReview(undoReview(plan, mods, id => rt?.registry.facts(id)))
594 return
595 }
596 // Two presses read one queue: only the first still finds this batch to undo.
597 const queued = await queueBatch(
598 plan.steps.map(step => step.spec),
599 current => stillUndoes(current.jobs, plan.batch),
600 )
601 if (queued === 'queued') await notice(`Queued: ${undoWords(plan.steps, mods)}`)
602 }),
603
604 refresh: safely('refresh', async () => {
605 if (rt === undefined) return
606 const { tab } = await state.read('view')
607 if (tab === 'dev' || tab === 'health') {
608 await rt.registry.refresh()
609 await rt.showTab(tab)
610 return
611 }
612 if (tab === 'discover') {
613 await rt.catalog.load({ force: true, retry: true })
614 rt.detector.start()
615 return
616 }
617 await rt.registry.refresh()
618 // A row the refresh flipped under a staged entry no longer changes.
619 const mods = await state.read('mods')
620 await setView(view => pruneStaged(view, mods))
621 }),
622
623 reload: safely('reload', async () => {
624 if (rt === undefined) return
625 const batch = rt.newJobId()
626 const id = rt.newJobId()
627 await state.update('queue', queue => ({
628 ...queue,
629 jobs: prune(enqueueReload(queue.jobs, id, batch)),
630 }))
631 rt.chrome.schedule()
632 rt.runner.kick()
633 }),
634
635 overlay: safely('overlay', async which => {
636 await setView(view => toggleOverlay(quiet(view), which))
637 await ringToOverlay()
638 }),
639
640 filter: safely('filter', async text => {
641 if ((await state.read('view')).tab === 'discover') {
642 await setView(current => ({ ...quiet(current), search: text.slice(0, 100) }))
643 await showCatalog()
644 return
645 }
646 const view = await setView(current => ({ ...quiet(current), query: text.slice(0, 100) }))
647 // The split's detail follows the row the filter leaves selected.
648 await select(selectedRow(view, await state.read('mods'))?.id)
649 }),
650
651 submitFilter: safely('submit filter', async text => {
652 await actions.filter(text)
653 await ringToSelection()
654 }),
655
656 focusFilter: safely('focus filter', async () => {
657 await ui.focus(PANE_ID, FILTER_KEY).catch(() => undefined)
658 }),
659
660 edge: safely('edge', async which => {
661 await moveSelection(count => (which === 'first' ? 0 : count - 1))
662 }),
663
664 scroll: safely('scroll', async (by, last = 0) => {
665 const view = await state.read('view')
666 const top = topOverlay(view)
667 // Over an overlay the wheel scrolls it, as far as its last line; the list isn't under it.
668 if (top !== undefined) {
669 const from = scrolledAt(view, top)
670 const at = Math.max(0, Math.min(last, from + by))
671 if (at !== from) await setView(current => ({ ...current, overlayAt: { overlay: top, at } }))
672 return
673 }
674 await moveSelection((_count, at) => at + by)
675 }),
676
677 copy: safely('copy', async (text, surface) => {
678 const copied = await ui.copy(text, surface)
679 await notice(copied.isCopied ? `Copied ${text}` : `Couldn't copy: ${copied.reason}`)
680 }),
681
682 openPane: safely('open pane', async () => {
683 await openDialog({ focus: true })
684 // A restored tab is read when the dialog shows it.
685 void rt
686 ?.showTab((await state.read('view')).tab)
687 .catch(error => debug(`modmgr: reading the tab failed: ${String(error)}`))
688 }),
689
690 focusFound: safely('focus found', async id => {
691 const view = await state.read('view')
692 if (view.found === id) return
693 const { offset } = await state.read('catalogPage')
694 await setView(current => ({ ...quiet(current), found: id }))
695 await showCatalog()
696 // The window around the selection moved: the engine keeps the ring at its
697 // place among the rows, now another row's, so it goes back onto this one.
698 // Not awaited: this runs inside the ring's own move.
699 if ((await state.read('catalogPage')).offset !== offset) {
700 void ui.focus(PANE_ID, foundKey(id)).catch(() => undefined)
701 }
702 // A local entry beside the list (the split) says what it can do too: read in
703 // the background, never on the ring's path; the redraw follows.
704 void rt?.catalog
705 .inspect(id)
706 .catch(error => debug(`modmgr: reading ${id} failed: ${String(error)}`))
707 }),
708
709 openFound: safely('open found', async id => {
710 await setView(view => pushOverlay({ ...quiet(view), found: id }, 'detail'))
711 await showCatalog()
712 await ringToOverlay()
713 // A local entry is read now: the detail redraws when it lands.
714 void rt?.catalog
715 .inspect(id)
716 .catch(error => debug(`modmgr: reading ${id} failed: ${String(error)}`))
717 }),
718
719 install: safely('install', async id => {
720 if (rt === undefined) return
721 await rt.catalog.load()
722 const [view, page] = await Promise.all([state.read('view'), state.read('catalogPage')])
723 const found = id ?? foundRow(view, page)?.id
724 const mod = found === undefined ? undefined : rt.catalog.mod(found)
725 if (mod !== undefined) {
726 const review = communityInstallReview(mod, 'user')
727 if (review === undefined) {
728 await notice(`No marketplace lists ${mod.name}: c copies its link`)
729 return
730 }
731 await openReview(review)
732 return
733 }
734 const entry = found === undefined ? undefined : rt.catalog.entry(found)
735 if (entry === undefined) {
736 await notice(
737 found === undefined ? 'Select an entry to install' : `${found} is no longer listed`,
738 )
739 return
740 }
741 const inspection = await rt.catalog.inspect(entry.id)
742 await openReview(installReview(entry, 'user', inspection))
743 }),
744
745 scope: safely('scope', async value => {
746 if (!isInstallScope(value)) return
747 await state.update('review', review => (review === null ? null : withScope(review, value)))
748 }),
749
750 cycleSort: safely('sort', async () => {
751 remember(await setView(view => ({ ...quiet(view), sort: nextSort(view.sort) })))
752 await showCatalog()
753 }),
754
755 toggleMine: safely('mine', async () => {
756 await setView(view => ({ ...quiet(view), mine: view.mine !== true }))
757 await showCatalog()
758 }),
759
760 acceptShown: safely('accept', async () => {
761 const queue = await state.read('queue')
762 const stopped = awaitingAcceptance(queue.jobs)
763 const review = stopped === undefined ? undefined : acceptReview(stopped)
764 if (review === undefined) {
765 await notice('Nothing waits for a command to be reviewed')
766 return
767 }
768 await openReview(review)
769 }),
770
771 addMarketplace: safely('add marketplace', async () => {
772 await setView(view => pushOverlay(quiet(view), 'marketplace'))
773 await ringToOverlay()
774 }),
775
776 submitMarketplace: safely('submit marketplace', async text => {
777 const asked = marketplaceReview(text)
778 if ('error' in asked) {
779 await notice(asked.error)
780 return
781 }
782 await setView(view => ({
783 ...view,
784 stack: view.stack.filter(overlay => overlay !== 'marketplace'),
785 }))
786 await openReview(asked.review)
787 }),
788
789 close: safely('close', async () => {
790 await ui.close(PANE_ID)
791 }),
792
793 dismiss: safely('dismiss', async line => {
794 await state.update('attention', attention => ({ ...attention, dismissed: line }))
795 // A dismissal quiets the status line and the title too.
796 rt?.chrome.schedule()
797 }),
798
799 cancelJob: safely('cancel job', async id => {
800 await rt?.runner.cancel(id)
801 }),
802
803 focusDev: safely('focus dev', async key => {
804 const view = await state.read('view')
805 if (view.dev === key) return
806 await setView(current => ({ ...quiet(current), dev: key }))
807 }),
808
809 openDev: safely('open dev', async key => {
810 await setView(view => pushOverlay({ ...quiet(view), dev: key }, 'detail'))
811 await ringToOverlay()
812 }),
813
814 devRun: safely('dev run', async (kind, key) => {
815 const row = await devRowFor(key)
816 if (row === undefined) return
817 const { path } = row
818 // One validate (or test) of a folder at a time: a second press says so.
819 const running = lastRun((await state.read('queue')).jobs, kind, path)
820 if (running !== undefined && isActive(running)) {
821 await notice(
822 `${row.name}: ${kind === 'test' ? 'its tests are' : 'it is being validated'} already`,
823 )
824 return
825 }
826 await queueBatch(
827 [{ kind, target: row.id ?? row.name, args: { path } }],
828 queue =>
829 !queue.jobs.some(job => isActive(job) && job.kind === kind && job.args?.path === path),
830 )
831 }),
832
833 share: safely('share', async key => {
834 const row = await devRowFor(key)
835 if (row === undefined || rt === undefined) return
836 if ((await rt.dev.share(row.key)) === undefined) return
837 await setView(view => pushOverlay({ ...quiet(view), dev: row.key }, 'share'))
838 await ringToOverlay()
839 }),
840
841 openHealth: safely('open health', async key => {
842 await setView(view => pushOverlay({ ...quiet(view), health: key }, 'detail'))
843 await ringToOverlay()
844 }),
845
846 focusHealth: safely('focus health', async key => {
847 const view = await state.read('view')
848 if (view.health === key) return
849 await setView(current => ({ ...quiet(current), health: key }))
850 }),
851
852 fix: safely('fix', async key => {
853 const item = (await healthItems()).find(each => each.key === key)
854 const fix = item?.fix
855 if (fix === undefined || rt === undefined) return
856 // The item's detail, when it was open, has done its job.
857 await setView(current => ({
858 ...quiet(current),
859 health: key,
860 stack: current.stack.filter(overlay => overlay !== 'detail'),
861 }))
862 switch (fix.kind) {
863 case 'open':
864 // What a mod can do, and its errors, are in its Installed detail.
865 await setView(view => ({ ...view, tab: 'installed', stack: [] }))
866 await actions.open(fix.id)
867 return
868 case 'update':
869 await actions.update(fix.id)
870 return
871 case 'copy':
872 await actions.copy(fix.text)
873 return
874 case 'reload':
875 await actions.reload()
876 return
877 case 'refresh':
878 await actions.refresh()
879 return
880 case 'clear-cache': {
881 const cleared = await rt.store.clearCaches()
882 await notice(
883 cleared.ok ? 'Cache cleared' : `Couldn't clear the cache: ${cleared.error.message}`,
884 )
885 await rt.health.refresh()
886 return
887 }
888 case 'check-updates': {
889 const outcome = await rt.updater.run()
890 await notice(CHECK_SAID[outcome])
891 await rt.health.refresh()
892 return
893 }
894 }
895 }),
896
897 async closing(origin, hadKeys, ringAway = false) {
898 try {
899 const stillHasKeys =
900 (await ui.panes()).find(pane => pane.id === PANE_ID)?.isFocused === true
901 debug(`modmgr: close from ${origin}, keys at last draw ${hadKeys}, now ${stillHasKeys}`)
902 const before = await state.read('view')
903 // Closed or popped, the welcome was on screen: seen.
904 seenWelcome(before)
905 if (origin === 'person' && hadKeys && !stillHasKeys) {
906 const view = before
907 const step = escapeStep(view, true, ringAway)
908 if (step.kind !== 'close') {
909 if (step.kind === 'pop' && topOverlay(view) === 'review') await dropReview()
910 if (step.kind !== 'to-list') {
911 await setView(current => {
912 const now = escapeStep(current, true, ringAway)
913 return now.kind === 'pop' || now.kind === 'clear-query' ? quiet(now.view) : current
914 })
915 }
916 if (step.kind === 'clear-query') await showCatalog()
917 await retake()
918 await ringToOverlay()
919 return true
920 }
921 }
922 await dropReview()
923 await setView(view => closedView(view))
924 } catch (error) {
925 debug(`modmgr: close failed: ${String(error)}`)
926 }
927 return false
928 },
929 }
930 return actions
931}
932hooks/services/commands.ts 366 lines1// `/mods`: the bare command opens the dialog; the
2// subcommands answer as text, for a script, a `-p` run or a session that
3// places no panes. A write asks for `--yes`, then runs its jobs here, on this
4// hook's own ports, through the runner's own `runJob` (the same checks and
5// declared-command handling), and records them on the queue and in the history.
6// It never reloads (a reload asked from a command hook rejects); it ends
7// with how to apply what changed.
8
9import type { Job, ModRow } from '../../types/index.d.ts'
10import { type ModRef, parseModsArgs, USAGE } from '../domain/command-args.ts'
11import {
12 type ApplyStep,
13 applyPlan,
14 doctorText,
15 exportOf,
16 infoText,
17 jobsText,
18 listText,
19 whyNot,
20} from '../domain/command-text.ts'
21import { healthItemsOf } from '../domain/health.ts'
22import {
23 appendTail,
24 finish,
25 isActive,
26 type JobSpec,
27 NEEDS_RELOAD,
28 prune,
29 start,
30} from '../domain/jobs.ts'
31import { hotkeyFor } from '../domain/keymap.ts'
32import { sanitize } from '../domain/sanitize.ts'
33import {
34 commandLine,
35 dockColumnsFor,
36 paneOpen,
37 removeReview,
38 specsOf,
39 summaryOf,
40 titleOf,
41 toggleReview,
42 updateReview,
43} from '../domain/view.ts'
44import type { Ports } from '../ports.ts'
45import { failed, historyOf, type Outcome, runJob } from './job-runner.ts'
46import type { Runtime } from './runtime.ts'
47
48export type CommandAnswer = { text?: string; exitCode?: number }
49
50export type CommandPorts = Pick<Ports, 'state' | 'ui' | 'fs' | 'clock' | 'process' | 'session'>
51
52/** The parts of the runtime a subcommand reaches; absent before the first `session.start`. */
53export type CommandRuntime = Pick<
54 Runtime,
55 | 'registry'
56 | 'newJobId'
57 | 'health'
58 | 'dev'
59 | 'chrome'
60 | 'store'
61 | 'jobFinished'
62 | 'runner'
63 | 'owner'
64 | 'showTab'
65>
66
67export { USAGE }
68
69export const modsCommand = async (
70 ports: CommandPorts,
71 rt: CommandRuntime | undefined,
72 args: string,
73 /** The terminal's width as the command runs (`e.presentation.columns`). */
74 columns?: number,
75): Promise<CommandAnswer> => {
76 const parsed = parseModsArgs(args)
77 if (!parsed.ok) return { text: `${parsed.error.message}\n\n${USAGE}`, exitCode: 2 }
78 const command = parsed.value
79 if (command.kind === 'help') return { text: USAGE }
80 if (command.kind === 'open' && (await openDialog(ports, columns))) {
81 // A restored tab is read when the dialog shows it; not awaited (waiting on
82 // anything but its own `$` calls runs down the hook's 10 s budget).
83 if (rt !== undefined) {
84 void rt
85 .showTab((await ports.state.read('view')).tab)
86 .catch(error => ports.ui.debug(`modmgr: reading the tab failed: ${String(error)}`))
87 }
88 return {}
89 }
90 if (rt === undefined)
91 return { text: 'modmgr is still starting; try again in a moment.', exitCode: 1 }
92 // Read when start-up hasn't yet, its CLI on this hook's own ports (their `$`
93 // calls don't run down the hook's 10 s budget).
94 if (!rt.registry.isLoaded()) await rt.registry.refresh(ports)
95 const [mods, sync, degraded] = await Promise.all([
96 ports.state.read('mods'),
97 ports.state.read('sync'),
98 ports.state.read('degraded'),
99 ])
100 // Said first only when it matters to every answer: the CLI is missing (not the network note).
101 const said =
102 degraded.process && degraded.reason !== undefined
103 ? [sanitize(degraded.reason, { max: 300 })]
104 : []
105 const answer = (text: string, exitCode = 0): CommandAnswer =>
106 exitCode === 0
107 ? { text: [...said, text].join('\n') }
108 : { text: [...said, text].join('\n'), exitCode }
109 // The installed mod a ref names: its id, or a name exactly one installed mod has.
110 const rowOf = (ref: ModRef): ModRow | string => {
111 const byId = mods.find(row => row.id === ref)
112 if (byId !== undefined) return byId
113 const shown = sanitize(ref, { max: 130 })
114 if (ref.includes('@')) return `${shown} is not an installed mod.`
115 const named = mods.filter(row => row.name === ref)
116 if (named.length === 1 && named[0] !== undefined) return named[0]
117 if (named.length === 0) return `No installed mod is named ${shown}; /mods list shows their ids.`
118 return `${named.length} installed mods are named ${shown}: give one of ${named.map(row => row.id).join(', ')}.`
119 }
120 if (!rt.registry.isLoaded()) {
121 const why = sync.error?.message ?? 'the claude CLI did not answer'
122 return answer(`Couldn't read your plugins: ${sanitize(why, { max: 300 })}`, 1)
123 }
124
125 switch (command.kind) {
126 case 'open':
127 case 'list':
128 return answer(listText(mods, { skipped: sync.skipped }))
129 case 'info': {
130 const row = rowOf(command.id)
131 if (typeof row === 'string') return answer(row, 1)
132 const detail = await rt.registry.detail(row.id)
133 if (detail === undefined) return answer(`${row.id} is not an installed mod.`, 1)
134 return answer(
135 infoText(row.updateTo === undefined ? detail : { ...detail, updateTo: row.updateTo }),
136 )
137 }
138 case 'doctor': {
139 // Health's facts are local reads (a few ms).
140 await rt.health.refresh()
141 const [attention, detect, queue, facts] = await Promise.all([
142 ports.state.read('attention'),
143 ports.state.read('detect'),
144 ports.state.read('queue'),
145 ports.state.read('health'),
146 ])
147 const items = healthItemsOf({ mods, attention, degraded, sync, detect, queue, facts })
148 const problems = items.some(item => item.tone === 'bad')
149 return { text: doctorText(items, command.json), ...(problems ? { exitCode: 1 } : {}) }
150 }
151 case 'export':
152 return { text: JSON.stringify(exportOf(mods), null, 2) }
153 }
154
155 // The rest change something: they need the CLI, and `--yes`.
156 if (degraded.process) return answer('Changing mods needs the claude CLI.', 1)
157 let specs: JobSpec[]
158 switch (command.kind) {
159 case 'install':
160 specs = [
161 {
162 kind: 'install',
163 target: command.id,
164 args: {
165 scope: command.scope,
166 ...(command.acceptSha === undefined ? {} : { acceptSha: command.acceptSha }),
167 },
168 },
169 ]
170 break
171 case 'remove':
172 case 'enable':
173 case 'disable': {
174 const row = rowOf(command.id)
175 if (typeof row === 'string') return answer(row, 1)
176 const why = whyNot(command.kind, row)
177 if (why !== undefined) return answer(`${sanitize(row.name, { max: 40 })}: ${why}`, 1)
178 if (command.kind === 'remove') {
179 const review = removeReview(row, rt.registry.facts(row.id))
180 specs = specsOf({ ...review, keepData: !command.wipe })
181 break
182 }
183 const enable = command.kind === 'enable'
184 if (row.enabled === enable)
185 return answer(`${sanitize(row.name, { max: 40 })} is already ${enable ? 'on' : 'off'}.`)
186 specs = specsOf(toggleReview([{ row, enable }], id => rt.registry.facts(id)))
187 break
188 }
189 case 'update': {
190 const rows =
191 command.id === undefined ? mods.filter(row => whyNot('update', row) === undefined) : []
192 if (command.id !== undefined) {
193 const row = rowOf(command.id)
194 if (typeof row === 'string') return answer(row, 1)
195 const why = whyNot('update', row)
196 if (why !== undefined) return answer(`${sanitize(row.name, { max: 40 })}: ${why}`, 1)
197 rows.push(row)
198 }
199 if (rows.length === 0)
200 return answer(
201 mods.length === 0 ? 'No mods installed.' : 'None of these mods updates through the CLI.',
202 )
203 specs = specsOf(updateReview(rows))
204 break
205 }
206 case 'apply': {
207 const text = await ports.fs.read(command.file).catch((error: unknown) => {
208 return { error: error instanceof Error ? error.message : String(error) }
209 })
210 if (typeof text !== 'string') {
211 return answer(
212 `Couldn't read ${sanitize(command.file, { max: 200 })}: ${sanitize(text.error, { max: 200 })}`,
213 1,
214 )
215 }
216 const plan = applyPlan(text, mods)
217 // A file it can't use is a refused run, not a usage error.
218 if (plan.errors.length > 0) return answer(plan.errors.join('\n'), 1)
219 if (plan.steps.length === 0)
220 return answer(
221 `Nothing to do: ${plan.already === 1 ? 'its mod is' : `its ${plan.already} mods are`} already as the file says.`,
222 )
223 specs = plan.steps.map(stepSpec)
224 break
225 }
226 }
227 if (!command.yes) {
228 const lines = specs.map(spec => ` ${commandLine(spec) ?? `${spec.kind} ${spec.target ?? ''}`}`)
229 return answer(['This would run:', ...lines, 'Add --yes to run it.'].join('\n'), 1)
230 }
231 const jobs = await runWrites(ports, rt, specs)
232 if (jobs === 'busy') {
233 return answer(
234 `A job is running (the job log, ${hotkeyFor('jobs', 'pane')} in /mods, shows it); try again when it ends.`,
235 1,
236 )
237 }
238 if (jobs === 'moved') return answer('modmgr was reloaded meanwhile; run the command again.', 1)
239 const outcome = jobsText(jobs)
240 return answer(outcome.text, outcome.failed ? 1 : 0)
241}
242
243const stepSpec = (step: ApplyStep): JobSpec =>
244 step.kind === 'install'
245 ? { kind: 'install', target: step.id, args: { scope: step.scope } }
246 : step.scope === undefined
247 ? { kind: 'enable', target: step.id }
248 : { kind: 'enable', target: step.id, args: { scope: step.scope } }
249
250/**
251 * Runs `specs` as one batch on the queue, like the dialog's: refused while a
252 * job is queued or running or another module owns the queue; otherwise each
253 * job is `running` on the queue while it runs (the runner sees it and waits, a
254 * queued reload waits behind it), finished and the next started
255 * in one write. The CLI runs on this command hook's own ports, whose `$` calls
256 * its 10 s budget doesn't run through. No reload (it would reject in a command hook).
257 */
258const runWrites = async (
259 ports: CommandPorts,
260 rt: CommandRuntime,
261 specs: readonly JobSpec[],
262): Promise<Job[] | 'busy' | 'moved'> => {
263 const batch = rt.newJobId()
264 const planned: Job[] = specs.map(spec => ({
265 id: rt.newJobId(),
266 batch,
267 kind: spec.kind,
268 state: 'queued',
269 tail: [],
270 ...(spec.target === undefined ? {} : { target: spec.target }),
271 ...(spec.args === undefined ? {} : { args: spec.args }),
272 }))
273 const ids = new Set(planned.map(job => job.id))
274 const startedAt = await ports.clock.now()
275 let refused: 'busy' | 'moved' | undefined
276 await ports.state.update('queue', queue => {
277 refused = queue.owner !== rt.owner ? 'moved' : queue.jobs.some(isActive) ? 'busy' : undefined
278 if (refused !== undefined) return queue
279 const jobs = [...queue.jobs, ...planned]
280 const first = planned[0]
281 return { ...queue, jobs: prune(first === undefined ? jobs : start(jobs, first.id, startedAt)) }
282 })
283 if (refused !== undefined) return refused
284 rt.chrome.schedule()
285 for (const [index, job] of planned.entries()) {
286 const next = planned[index + 1]
287 // Cancelled from the job log while it waited: skipped, and the next one starts.
288 const cancelled =
289 (await ports.state.read('queue')).jobs.find(queued => queued.id === job.id)?.state ===
290 'cancelled'
291 let outcome: Outcome | undefined
292 if (!cancelled) {
293 try {
294 outcome = await runJob(ports, job, async id => rt.registry.entry(id) !== undefined)
295 } catch (error) {
296 // Never left running: a job stuck there makes every later write answer "busy".
297 outcome = failed({ kind: 'unavailable', message: String(error) })
298 }
299 }
300 const endedAt = await ports.clock.now()
301 let owned = false
302 await ports.state.update('queue', queue => {
303 owned = queue.owner === rt.owner
304 // A newer module took the queue over mid-write: it has settled this batch.
305 if (!owned) return queue
306 const finished =
307 outcome === undefined
308 ? queue.jobs
309 : finish(appendTail(queue.jobs, job.id, outcome.tail), job.id, endedAt, outcome.finish)
310 return {
311 ...queue,
312 jobs: prune(next === undefined ? finished : start(finished, next.id, endedAt)),
313 }
314 })
315 if (!owned) break
316 if (outcome !== undefined) {
317 const done = outcome
318 rt.store.update('history', history => [...history, historyOf(job, endedAt, done)])
319 }
320 }
321 const jobs = (await ports.state.read('queue')).jobs.filter(job => ids.has(job.id))
322 if (
323 jobs.some(job => NEEDS_RELOAD.has(job.kind) && job.state === 'ok' && job.unchanged !== true)
324 ) {
325 await ports.state.update('attention', attention => ({ ...attention, reloadPending: true }))
326 }
327 // A -p run exits with the answer: the history is written before it.
328 await rt.store.flush()
329 for (const job of jobs) rt.jobFinished(job)
330 rt.chrome.schedule()
331 void rt.registry.refresh()
332 // A reload that waited behind the batch goes on.
333 rt.runner.kick()
334 return jobs
335}
336
337/**
338 * Opens the dialog, docked as wide as a terminal `columns` wide leaves the
339 * transcript room for (kept for every later open); false when this session
340 * places no panes (a `-p` run, an older host).
341 */
342const openDialog = async (
343 ports: Pick<Ports, 'state' | 'ui'>,
344 columns: number | undefined,
345): Promise<boolean> => {
346 try {
347 const [mods, queue, attention, view] = await Promise.all([
348 ports.state.read('mods'),
349 ports.state.read('queue'),
350 ports.state.read('attention'),
351 ports.state.read('view'),
352 ])
353 const dock = columns === undefined ? view.dock : dockColumnsFor(columns)
354 if (dock !== undefined && dock !== view.dock)
355 await ports.state.update('view', next => ({ ...next, dock }))
356 const busy = queue.jobs.some(isActive)
357 const title = titleOf(summaryOf({ attention, queue, mods }))
358 const opened = await ports.ui.open(
359 paneOpen({ focus: true, hold: !busy, mods: mods.length, title, dock }),
360 )
361 return opened.isPlaced
362 } catch {
363 return false
364 }
365}
366hooks/services/lifecycle.ts 125 lines1// The ordered fan-out for events modmgr hooks once (a module may hook an event
2// only once without a matcher). Sequencing
3// lives here, not in register.tsx, so it is tested.
4//
5// `session.start` must stay under 5 ms of blocking work: it registers
6// `/mods` and takes the job queue over, then hands everything else to a clock
7// timer. It runs again when modmgr's own module reloads, so every step is
8// idempotent.
9
10import { RELOADED_WITH_MODMGR, takeOver, tookOverReload } from '../domain/jobs.ts'
11import { readPrefs } from '../domain/store-schema.ts'
12import { PANE_ID } from '../domain/view.ts'
13import { probeAndRecord } from './capability-probe.ts'
14import { echoLine } from './job-runner.ts'
15import type { Runtime } from './runtime.ts'
16
17export const MODS_DESCRIPTION = 'Discover, inspect, toggle and update mods'
18
19export const onSessionStart = async (rt: Runtime): Promise<void> => {
20 const { ports } = rt
21 let fresh = false
22 let reloaded = false
23 // Side by side: each is a host round trip, and session.start blocks the session.
24 const takeQueue = async (): Promise<void> => {
25 const now = await ports.clock.now()
26 await ports.state.update('queue', queue => {
27 fresh = queue.owner === ''
28 const next = takeOver(queue, rt.owner, now)
29 reloaded = tookOverReload(queue, next)
30 return next
31 })
32 }
33 await Promise.all([ports.command.registerMods(), takeQueue()])
34 // A module started again in the same session by modmgr's own reload, or by the
35 // person's /reload-plugins where only they can reload, came with the session's
36 // plugins: what was owed is applied. Any other restart (a worker respawn, an
37 // options change, its folder's hot reload) was modmgr's alone: it is still owed.
38 if (!fresh) {
39 await ports.state.update('attention', attention => {
40 if (!reloaded && attention.reloadByHand !== true) return attention
41 const { reloadByHand: _, ...rest } = attention
42 return { ...rest, reloadPending: false }
43 })
44 }
45 if (reloaded) {
46 // Said for a while, as the runner's own echo is.
47 await echoLine(ports, RELOADED_WITH_MODMGR)
48 }
49 ports.clock.after(0, () => {
50 void background(rt, { fresh })
51 })
52}
53
54/**
55 * The rest of start-up, off the blocking path: the store, preferences (first
56 * start of the session only; a reloaded module keeps the view it finds), the
57 * capability probe, the installed list, and any queued jobs.
58 */
59export const background = async (rt: Runtime, how: { fresh: boolean }): Promise<void> => {
60 const { ports } = rt
61 try {
62 await rt.store.load()
63 if (how.fresh) {
64 const prefs = readPrefs(rt.store.get('prefs'))
65 // Until it has been seen, a session that draws opens on a word of welcome;
66 // leaving it marks it seen. A `-p` run draws nothing.
67 const draws = (await ports.session.surfaces().catch(() => [])).length > 0
68 const welcome = draws && !prefs.firstRunDone
69 await ports.state.update('view', view => ({
70 ...view,
71 tab: prefs.tab,
72 sort: prefs.sort,
73 ...(welcome ? { stack: ['welcome' as const] } : {}),
74 }))
75 }
76 // A reloaded module says again what the last one left on the status line.
77 await rt.chrome.sync()
78 const probe = await probeAndRecord(ports)
79 if (!probe.process) {
80 await rt.registry.refresh()
81 rt.runner.kick()
82 // Re-armed by every module from the stored time: a reload loses timers.
83 await rt.updater.arm()
84 // A reloaded modmgr with a tab showing reads what it needs again (module memory). A
85 // fresh session only restores the tab: it is read when the dialog opens, or now
86 // when `/mods` opened it before this module was ready to read it.
87 const shown = (await ports.ui.panes().catch(() => [])).some(
88 pane => pane.id === PANE_ID && pane.isPlaced,
89 )
90 if (!how.fresh || shown) await rt.showTab((await ports.state.read('view')).tab)
91 await rt.chrome.retakeKeys()
92 } else {
93 // Without a CLI it can run, the list is never read: say so rather than "Reading…".
94 await ports.state.update('sync', sync => ({
95 ...sync,
96 error: { kind: 'unavailable', message: "modmgr can't run the claude CLI it needs" },
97 }))
98 }
99 } catch (error) {
100 ports.ui.debug(`modmgr: start-up failed: ${String(error)}`)
101 }
102}
103
104/**
105 * The turns running now, by id: a subagent's run raises no
106 * `turn.start` and its `turn.complete` carries `agentId` (d.ts TurnCompleteFields),
107 * so only the main loop's own start and end count. The detector probes, and
108 * the update scheduler fetches, only while none runs.
109 */
110export const onTurnStart = (rt: Runtime | undefined, turnId: string): void => {
111 if (rt === undefined) return
112 rt.turns.add(turnId)
113 rt.detector.setBusy(true)
114}
115
116export const onTurnEnd = (
117 rt: Runtime | undefined,
118 turnId: string,
119 agentId: string | undefined,
120): void => {
121 if (rt === undefined || agentId !== undefined) return
122 rt.turns.delete(turnId)
123 rt.detector.setBusy(rt.turns.size > 0)
124}
125hooks/services/runtime.ts 232 lines1// The long-lived services of one module instance: built once
2// at its first `session.start`, on that dispatch's ports, and kept in
3// register.tsx's module scope. A reload of modmgr builds a new one; the old
4// one's in-flight work finishes on its own and then stops (it no longer owns
5// the queue).
6
7import type { Job, Tab } from '../../types/index.d.ts'
8import { type Config, trafficOff } from '../domain/config.ts'
9import type { StateKey } from '../domain/state.ts'
10import { PANE_ID } from '../domain/view.ts'
11import type { Ports, StatePort } from '../ports.ts'
12import { type Catalog, createCatalog } from './catalog.ts'
13import { createIndexSync } from './catalog-index.ts'
14import { type Chrome, createChrome } from './chrome.ts'
15import { createCommunity } from './community.ts'
16import { createDetector, DETECT_BUDGET, type Detector } from './detector.ts'
17import { createDev, type Dev } from './dev.ts'
18import { createHealth, type Health } from './health.ts'
19import { createRunner, type Runner } from './job-runner.ts'
20import { createRegistry, type Registry } from './registry.ts'
21import { createStore, type StoreService } from './store.ts'
22import { type Timing, timingOf } from './timing.ts'
23import { createUpdater, type Updater } from './updates.ts'
24
25export type Runtime = {
26 /** This module's queue owner id. */
27 readonly owner: string
28 readonly ports: Ports
29 readonly config: Config
30 readonly store: StoreService
31 readonly registry: Registry
32 readonly runner: Runner
33 /** The status line and the pane title. */
34 readonly chrome: Chrome
35 /** Discover's catalogue (module memory). */
36 readonly catalog: Catalog
37 /** Finds which catalogue entries are mods, while no turn runs. */
38 readonly detector: Detector
39 /** Dev's mods under development and their failures. */
40 readonly dev: Dev
41 /** Checks for updates every `updateCheckHours`, while idle. */
42 readonly updater: Updater
43 /** Health's facts beyond the other keys. */
44 readonly health: Health
45 /** Says how long a step took, with `debugTimings` on (`docs/PERF.md`). */
46 readonly timing: Timing
47 /** After a job ends (the runner's, or a text write's): catalogue, analyses, updates. */
48 jobFinished(job: Job): void
49 /**
50 * What a tab needs read when it is shown (a press, an open, a reloaded module
51 * with it showing): Discover's catalogue and the detector, Dev's folders,
52 * Health's facts. Never at a fresh start.
53 */
54 showTab(tab: Tab): Promise<void>
55 /** The main loop's turns running now, by id (lifecycle `onTurnStart`/`onTurnEnd`). */
56 readonly turns: Set<string>
57 /** Job ids unique across modules: the owner, then a counter. */
58 newJobId(): string
59 dispose(): void
60}
61
62/** The keys the status line and the title are drawn from (domain/view.ts `summaryOf`). */
63const SUMMARY_KEYS: ReadonlySet<StateKey> = new Set(['attention', 'queue', 'mods'])
64
65/** A state port that calls `written` after each successful write of `keys`. */
66export const observedState = (
67 state: StatePort,
68 keys: ReadonlySet<StateKey>,
69 written: () => void,
70): StatePort => ({
71 read: key => state.read(key),
72 async update(key, change) {
73 const value = await state.update(key, change)
74 if (keys.has(key)) written()
75 return value
76 },
77})
78
79export const createRuntime = (base: Ports, config: Config, owner: string): Runtime => {
80 const debug = (text: string): void => base.ui.debug(text)
81 const timing = timingOf(config.debugTimings, debug)
82 const chrome = createChrome(base, debug)
83 // The runtime's own writes (the runner's, the registry's) keep the status line current.
84 const ports: Ports = {
85 ...base,
86 state: observedState(base.state, SUMMARY_KEYS, () => chrome.schedule()),
87 }
88 const store = createStore(ports, { debug })
89 const registry = createRegistry(ports, store, debug, timing)
90 const trafficIsOff = async (): Promise<boolean> =>
91 trafficOff(await ports.env.nonessentialTraffic().catch(() => undefined))
92 const remoteAllowed = async (): Promise<boolean> => config.detectRemote && !(await trafficIsOff())
93 const community = createCommunity(ports, { allowed: remoteAllowed, debug })
94 const catalog = createCatalog(ports, store, debug, timing, community)
95 const detector = createDetector(ports, {
96 store,
97 catalog,
98 index: createIndexSync(ports, { store, debug }),
99 debug,
100 remoteAllowed,
101 })
102 let catalogWarmed = false
103 /** A marketplace or an install changes what the catalogue lists. */
104 const recatalog = (): void => {
105 if (!catalog.isLoaded()) return
106 void catalog
107 .load({ force: true })
108 .then(() => detector.start())
109 .catch(error => debug(`modmgr: catalogue read after a job failed: ${String(error)}`))
110 }
111 /** After a job ends, the runner's or a text write's: what it changed is read again. */
112 const jobFinished = (job: Job): void => {
113 const lists = ['install', 'remove', 'marketplace-add', 'marketplace-update']
114 if (job.state === 'ok' && lists.includes(job.kind)) recatalog()
115 // A folder validated anew: Installed reads what it can do again (it may have changed
116 // without a new version).
117 const path = job.args?.path
118 if (job.kind === 'validate' && path !== undefined && registry.forget(path)) {
119 void registry.refresh()
120 }
121 // A refreshed marketplace says what can update.
122 if (job.kind === 'marketplace-update' && job.state === 'ok') void updater.check()
123 // The CLI found it current: what a check guessed goes, before the refresh that follows.
124 if (job.kind === 'update' && job.unchanged === true && job.target !== undefined) {
125 updater.forget(job.target)
126 }
127 // A reload that left this module running (or failed) gives the keys back here.
128 if (job.kind === 'reload') void chrome.retakeKeys()
129 }
130 const runner = createRunner(ports, {
131 owner,
132 store,
133 isInstalled: async id => {
134 if (!registry.isLoaded()) await registry.refresh()
135 return registry.entry(id) !== undefined
136 },
137 onSettled: () => registry.refresh(),
138 onFinished: job => jobFinished(job),
139 debug,
140 })
141 const dev = createDev(ports, registry, debug, timing)
142 let counter = 0
143 const newJobId = (): string => {
144 counter += 1
145 return `${owner}-${counter}`
146 }
147 const turns = new Set<string>()
148 const updater = createUpdater(ports, {
149 store,
150 registry,
151 hours: config.updateCheckHours,
152 turns,
153 trafficOff: trafficIsOff,
154 newJobId,
155 kick: () => runner.kick(),
156 ...(config.notifyUpdates
157 ? {
158 notify: async (text: string) => {
159 // A person holding the dialog's keys sees the arrows already: said, in effect.
160 const panes = await ports.ui.panes()
161 if (panes.some(pane => pane.id === PANE_ID && pane.isFocused)) return true
162 return ports.ui.notify(text)
163 },
164 }
165 : {}),
166 debug,
167 })
168 const health = createHealth(ports, {
169 registry,
170 store,
171 detector,
172 budget: DETECT_BUDGET,
173 config,
174 trafficOff: trafficIsOff,
175 debug,
176 timing,
177 })
178 return {
179 owner,
180 ports,
181 config,
182 store,
183 registry,
184 runner,
185 chrome,
186 catalog,
187 detector,
188 dev,
189 updater,
190 health,
191 timing,
192 jobFinished,
193 async showTab(tab) {
194 if (tab === 'discover') {
195 // Read at the first visit, then at most every few hours.
196 await catalog.load()
197 await catalog.show()
198 detector.start()
199 } else if (
200 !catalogWarmed &&
201 (await base.ui.panes().catch(() => [])).some(pane => pane.id === PANE_ID && pane.isPlaced)
202 ) {
203 // The catalogue is the slowest read (about a second): begun when the
204 // dialog first shows another tab, Discover opens on it. Once a module,
205 // and never for a closed dialog (a reload shows its tab unseen); a
206 // failed read waits for Discover to try again.
207 catalogWarmed = true
208 void catalog
209 .load()
210 .catch(error => debug(`modmgr: catalogue read ahead failed: ${String(error)}`))
211 }
212 // What a session loads from folders changes with its commands and reloads: read on each visit.
213 if (tab === 'dev' || tab === 'health') await dev.refresh()
214 if (tab === 'health') await health.refresh()
215 },
216 turns,
217 newJobId,
218 dispose() {
219 runner.dispose()
220 detector.dispose()
221 updater.dispose()
222 void store.flush()
223 },
224 }
225}
226
227/** A short random id for a module instance. */
228export const newOwnerId = (random: () => number = Math.random): string =>
229 Math.floor(random() * 36 ** 8)
230 .toString(36)
231 .padStart(8, '0')
232