@cmodjs/core 5.10.0 → 5.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@ import { AbovePrompt, areas, BelowPrompt, TurnEnd, Working } from '../ui/areas.j
3
3
  import { Box, drawWith } from '../ui/elements.js';
4
4
  import { ifMissing } from '../utils/paths.js';
5
5
  import { messageOf } from '../utils/text.js';
6
- import { cmodPluginName, isNotInstalled } from './dependencies.js';
6
+ import { cmodPluginName, isNotInstalled, isStillInstalling } from './dependencies.js';
7
7
  import { partMethods, styledAt, viewportColumns } from './ui.js';
8
8
  export const claudeHint = 'claude/hint';
9
9
  export const claudeModes = 'claude/modes';
@@ -122,7 +122,7 @@ export function serveWidgets({ claude, router, store, report, turnClosedBy, part
122
122
  }
123
123
  catch (error) {
124
124
  declared.delete(mod);
125
- if (!isNotInstalled(mod, error))
125
+ if (!isNotInstalled(mod, error) && !isStillInstalling(mod, error))
126
126
  claude.ui.warn(`widgets:list:${mod}`, `cmod: ${mod} did not list its widgets: ${messageOf(error)}`);
127
127
  }
128
128
  };
package/src/records.ts CHANGED
@@ -272,6 +272,10 @@ export function servicePath(store: string, mod: string, executable: string): str
272
272
  return `${serviceFolder(store, mod)}/${checkedName(executable)}.json`
273
273
  }
274
274
 
275
+ export function serviceLogPath(store: string, mod: string, executable: string): string {
276
+ return `${serviceFolder(store, mod)}/${checkedName(executable)}.log`
277
+ }
278
+
275
279
  export type Links = { readonly marketplaces: Readonly<Record<string, string>>; readonly turnedOff: Readonly<Record<string, readonly string[]>> }
276
280
 
277
281
  export function parseLinks(value: unknown, path: string): Links {
@@ -288,6 +292,28 @@ export function linkedMarketplacesOf(knownMarketplaces: unknown, links: Links):
288
292
  })
289
293
  }
290
294
 
295
+ export type LinkedCheckout = { readonly name: string; readonly marketplace: string; readonly folder: string }
296
+
297
+ export async function linkedCheckoutsOf(read: ReadFile, knownMarketplaces: unknown, links: Links): Promise<LinkedCheckout[]> {
298
+ const checkouts: LinkedCheckout[] = []
299
+ for (const [marketplace, folder] of linkedMarketplacesOf(knownMarketplaces, links)) {
300
+ const path = `${folder}/.claude-plugin/marketplace.json`
301
+ const text = await read(path)
302
+ const manifest: unknown = text === undefined ? undefined : parsedJson(text, path)
303
+ const plugins: unknown[] = isObject(manifest) && Array.isArray(manifest['plugins']) ? manifest['plugins'] : []
304
+ for (const plugin of plugins) if (isObject(plugin) && typeof plugin['name'] === 'string' && typeof plugin['source'] === 'string') checkouts.push({ name: plugin['name'], marketplace, folder: `${folder}/${plugin['source'].replace(/^\.\//, '')}` })
305
+ }
306
+ return checkouts
307
+ }
308
+
309
+ function parsedJson(text: string, path: string): unknown {
310
+ try {
311
+ return JSON.parse(text)
312
+ } catch (error) {
313
+ throw new Error(`${path} is not valid JSON: ${messageOf(error)}`)
314
+ }
315
+ }
316
+
291
317
  export function hasLinkedMods(knownMarketplaces: unknown, links: Links): boolean {
292
318
  return linkedMarketplacesOf(knownMarketplaces, links).length > 0
293
319
  }
@@ -300,12 +326,26 @@ export function preferencesPath(store: string): string {
300
326
  return `${store}/preferences.json`
301
327
  }
302
328
 
303
- export type Preferences = { readonly showsInstalledModErrors: boolean }
329
+ export type Preferences = { readonly showsInstalledModErrors: boolean; readonly servesWebUi: boolean }
330
+
331
+ const preferenceKeys = ['showsInstalledModErrors', 'servesWebUi'] as const satisfies readonly (keyof Preferences)[]
304
332
 
305
333
  export function parsePreferences(value: unknown, path: string): Preferences {
306
- if (value === undefined) return { showsInstalledModErrors: false }
307
- if (!isObject(value) || (value['showsInstalledModErrors'] !== undefined && typeof value['showsInstalledModErrors'] !== 'boolean')) throw new Error(`${path} is not a map of cmod's preferences to true or false. Delete it, and cmod uses its defaults.`)
308
- return { showsInstalledModErrors: value['showsInstalledModErrors'] === true }
334
+ if (value !== undefined && (!isObject(value) || preferenceKeys.some((key) => value[key] !== undefined && typeof value[key] !== 'boolean'))) throw new Error(`${path} is not a map of cmod's preferences to true or false. Delete it, and cmod uses its defaults.`)
335
+ const saved = isObject(value) ? value : {}
336
+ return { showsInstalledModErrors: saved['showsInstalledModErrors'] === true, servesWebUi: saved['servesWebUi'] === true }
337
+ }
338
+
339
+ export function webPath(store: string): string {
340
+ return `${store}/web.json`
341
+ }
342
+
343
+ export type WebUi = { readonly port: number }
344
+
345
+ export function parseWebUi(value: unknown, path: string): WebUi | undefined {
346
+ if (value === undefined) return undefined
347
+ if (!isObject(value) || !Number.isInteger(value['port'])) throw new Error(`${path} is not the web UI's port. Delete it, and cmod web serve writes it again.`)
348
+ return { port: value['port'] as number }
309
349
  }
310
350
 
311
351
  export type Contact = { readonly kind: 'github'; readonly repository: string } | { readonly kind: 'email'; readonly address: string }
@@ -377,7 +417,7 @@ function readHotkeys(hotkeys: unknown): Steps {
377
417
  return { hotkeys: checkHotkeys('package.json "cmod"', hotkeys as Record<string, HotkeyInit>) }
378
418
  }
379
419
 
380
- export const coreVersion = '5.10.0'
420
+ export const coreVersion = '5.12.0'
381
421
 
382
422
  export const oldestCmodVersion = '5.10.0'
383
423
 
@@ -55,3 +55,11 @@ export function notInstalled(name: string): string {
55
55
  export function isNotInstalled(name: string, error: unknown): boolean {
56
56
  return messageOf(error).endsWith(notInstalled(name))
57
57
  }
58
+
59
+ export function stillInstalling(name: string): string {
60
+ return `${name} is installing. Try again when it's ready.`
61
+ }
62
+
63
+ export function isStillInstalling(name: string, error: unknown): boolean {
64
+ return messageOf(error).endsWith(stillInstalling(name))
65
+ }
@@ -2,6 +2,7 @@ import type { HookStream, ProcessSpawnChunk, ProcessSpawnResult } from 'claude-c
2
2
  import type { Claude } from './claude.js'
3
3
  import type { Pages } from './pages.js'
4
4
  import type { Router } from './router.js'
5
+ import type { Subscription } from '../utils/subscription.js'
5
6
  import type { Failure } from './toaster.js'
6
7
  import type { ToolCalls } from './tool-calls.js'
7
8
  import type { Watches } from './watches.js'
@@ -16,6 +17,7 @@ export type Engine = {
16
17
  readonly answerInput: <Answer>(run: () => Promise<Answer>, passOn: () => Promise<unknown>) => Promise<Answer>
17
18
  readonly spawnCmod: (args: readonly string[], env?: Readonly<Record<string, string>>) => HookStream<ProcessSpawnChunk, ProcessSpawnResult>
18
19
  readonly watches: Watches
20
+ readonly onRedraw: (listener: () => void) => Subscription
19
21
  readonly widgets?: Widgets
20
22
  readonly pages?: Pages
21
23
  }
@@ -11,7 +11,7 @@ import { beforeDeadline, settledAfterAbort } from './deadline.js'
11
11
  import { announcementMs, announcementOf } from './announce.js'
12
12
  import { bind } from './bound.js'
13
13
  import type { Conversations } from './conversations.js'
14
- import { answerCall, answeringOwnCalls, cmodPluginName, dependencyCalls, loadedMethod, withBareRefusals } from './dependencies.js'
14
+ import { answerCall, answeringOwnCalls, cmodPluginName, dependencyCalls, isStillInstalling, loadedMethod, stillInstalling, withBareRefusals } from './dependencies.js'
15
15
  import type { Device } from '../session/context/turn/device.js'
16
16
  import { keepEngine } from './engine.js'
17
17
  import { classicFailure, classicHook, userSkillHook, type Hook, type HookFields, type HookListener, type RoutedEvent } from './hooks.js'
@@ -52,6 +52,8 @@ export type Phase = 'starting' | 'installing' | 'waiting' | 'failed' | 'ready' |
52
52
 
53
53
  const listenMethods: readonly string[] = [conversationMethods.subscribe, conversationMethods.watchBefore]
54
54
 
55
+ const answeredAtOnce: readonly string[] = [...listenMethods, partMethods.draw]
56
+
55
57
  export type Lifecycle<State extends object> = {
56
58
  readonly phase: Phase
57
59
  readonly mod: Mod<State> | undefined
@@ -225,6 +227,17 @@ export function createLifecycle<State extends object, Declared extends Options =
225
227
  const heldListens = new Map<string, Frozen<Args<'cmod.call'>> & { readonly caller?: string }>()
226
228
  let settleStart: () => void = () => undefined
227
229
  const startSettled = new Promise<void>((resolve) => (settleStart = resolve))
230
+ let installSettled: Promise<void> | undefined
231
+ let settleInstall: () => void = () => undefined
232
+ const whenInstalled = () =>
233
+ phase === 'installing' || phase === 'waiting'
234
+ ? (installSettled ??= new Promise<void>((resolve) => {
235
+ settleInstall = () => {
236
+ installSettled = undefined
237
+ resolve()
238
+ }
239
+ }))
240
+ : undefined
228
241
 
229
242
  const claude = () => {
230
243
  if (runtime === undefined) throw new Error(`${definition.name}: the lifecycle has not started. registerMod(addHook, mod, options) starts it at session.start.`)
@@ -237,6 +250,7 @@ export function createLifecycle<State extends object, Declared extends Options =
237
250
 
238
251
  const fail = (reason: string, fix: string | undefined, retry?: () => Promise<void>, error?: unknown) => {
239
252
  phase = 'failed'
253
+ settleInstall()
240
254
  failure ??= new Error(`${definition.name}: ${reason}${/[.!?]$/.test(reason) ? '' : '.'}${fix === undefined ? '' : ` ${fix}`}`, { cause: error })
241
255
  const again = retry === undefined ? {} : { retry: () => ((failure = undefined), stopRetrying(), retry().catch(report)) }
242
256
  toastFailure({ id: installId, message: reason, ...(fix === undefined ? {} : { description: fix }), ...(error === undefined ? {} : { error }), ...again, isCritical: true })
@@ -289,6 +303,7 @@ export function createLifecycle<State extends object, Declared extends Options =
289
303
  await programs?.refresh()
290
304
  phase = 'ready'
291
305
  activation ??= new Promise<void>((resolve) => claude().clock.after(0, () => resolve(activate().catch(report))))
306
+ settleInstall()
292
307
  claude().ui.invalidate('ui.render')
293
308
  }
294
309
 
@@ -602,6 +617,8 @@ export function createLifecycle<State extends object, Declared extends Options =
602
617
 
603
618
  const holdUntilStarted = (signal?: AbortSignal): Promise<boolean> => held(startSettled.then(whenActive), signal)
604
619
 
620
+ const holdUntilInstalled = (signal?: AbortSignal): Promise<boolean> => held(startSettled.then(whenInstalled).then(whenActive), signal)
621
+
605
622
  const holdUntilActive = (signal: AbortSignal | undefined): Promise<boolean> => {
606
623
  const activating = whenActive()
607
624
  return activation !== undefined && phase !== 'active' ? held(activating, signal) : activating.then(() => false)
@@ -629,17 +646,19 @@ export function createLifecycle<State extends object, Declared extends Options =
629
646
  const tool = (e as { readonly tool?: unknown }).tool
630
647
  const isCallToThisMod = (event === 'cmod.call' && (e as Frozen<Args<'cmod.call'>>).to === definition.name) || (event === 'tool.call' && typeof tool === 'string' && tool.startsWith(`mcp__${definition.name}__`))
631
648
  if (event === 'cmod.call' && !isCallToThisMod) return next(e)
632
- const isLate = await (event === 'classic.SessionStart' || event === 'session.append' || isCallToThisMod ? holdUntilStarted(signal) : holdUntilActive(signal))
649
+ const isListen = isCallToThisMod && event === 'cmod.call' && listenMethods.includes(asked.method)
650
+ const waitsForInstall = isCallToThisMod && !(event === 'cmod.call' && answeredAtOnce.includes(asked.method))
651
+ const isLate = await (waitsForInstall ? holdUntilInstalled(signal) : event === 'classic.SessionStart' || event === 'session.append' || isCallToThisMod ? holdUntilStarted(signal) : holdUntilActive(signal))
633
652
  if (event === 'classic.SessionStart' && phase !== 'active') {
634
653
  missedSessionStart = e as Frozen<Args<'classic.SessionStart'>>
635
654
  return next(e)
636
655
  }
637
656
  if (isCallToThisMod && phase !== 'active') {
638
- if (event === 'cmod.call' && listenMethods.includes(asked.method)) {
657
+ if (isListen) {
639
658
  heldListens.set(`${asked.caller}\n${asked.method}\n${String((asked.input as { readonly session?: unknown }).session)}`, asked)
640
659
  return { value: null } as EventResult<N>
641
660
  }
642
- return { deny: phase === 'failed' ? notSetUp() : `${definition.name} is installing. Try again when it's ready.` } as EventResult<N>
661
+ return { deny: phase === 'failed' ? notSetUp() : stillInstalling(definition.name) } as EventResult<N>
643
662
  }
644
663
  if (isLate && phase !== 'active') return (startingRouter ?? router).dispatchFailure(event, e, new Error(`it was still starting after ${startHoldMs / 1000} s`), next, false)
645
664
  const call = e as Frozen<Args<'cmod.call'>>
@@ -733,7 +752,13 @@ export function createLifecycle<State extends object, Declared extends Options =
733
752
  async function createMod<State extends object, Declared extends Options>(definition: ModDefinition<State, string, Declared>, runtime: ModRuntime): Promise<ActiveMod<State, Declared>> {
734
753
  const { router, toaster } = runtime
735
754
  const report = (failure: Failure) => void toaster.fail(failure)
736
- const claude = answeringOwnCalls(withBareRefusals(runtime.claude), router)
755
+ const redraws = new Set<() => void>()
756
+ const calling = answeringOwnCalls(withBareRefusals(runtime.claude), router)
757
+ const invalidate: Claude['ui']['invalidate'] = (event) => {
758
+ calling.ui.invalidate(event)
759
+ if (event === 'ui.render') for (const redraw of redraws) redraw()
760
+ }
761
+ const claude: Claude = { ...calling, ui: { ...calling.ui, invalidate } }
737
762
  const added: string[] = []
738
763
  const announce = (feature: string) => {
739
764
  added.push(feature)
@@ -1043,7 +1068,11 @@ async function createMod<State extends object, Declared extends Options>(definit
1043
1068
  pages = served?.pages
1044
1069
  const tellColor = (to: string, told: SessionColor) => {
1045
1070
  if (told.session === '' || to === cmodPluginName) return
1046
- claude.clock.after(0, () => void claude.cmod.call({ to, method: conversationMethods.sessionColor, input: told }).catch((error: unknown) => claude.ui.warn('color:tell', `cmod: ${to} did not hear the session's color: ${messageOf(error)}`)))
1071
+ claude.clock.after(0, () =>
1072
+ void claude.cmod.call({ to, method: conversationMethods.sessionColor, input: told }).catch((error: unknown) => {
1073
+ if (!isStillInstalling(to, error)) claude.ui.warn('color:tell', `cmod: ${to} did not hear the session's color: ${messageOf(error)}`)
1074
+ }),
1075
+ )
1047
1076
  }
1048
1077
  conversations?.onColor((told) => {
1049
1078
  client.recolor(told)
@@ -1090,6 +1119,10 @@ async function createMod<State extends object, Declared extends Options>(definit
1090
1119
  answerInput: area.answerInput,
1091
1120
  spawnCmod: (args, env) => spawnCmod(claude, args, session, env),
1092
1121
  watches,
1122
+ onRedraw(listener) {
1123
+ redraws.add(listener)
1124
+ return { remove: () => void redraws.delete(listener) }
1125
+ },
1093
1126
  ...(widgets === undefined ? {} : { widgets }),
1094
1127
  ...(pages === undefined ? {} : { pages }),
1095
1128
  })
@@ -3,7 +3,7 @@ import { isObject } from '../records.js'
3
3
  import { Text } from '../ui/elements.js'
4
4
  import { messageOf } from '../utils/text.js'
5
5
  import type { Claude } from './claude.js'
6
- import { cmodPluginName, isNotInstalled } from './dependencies.js'
6
+ import { cmodPluginName, isNotInstalled, isStillInstalling } from './dependencies.js'
7
7
  import type { DrawnParts } from './parts.js'
8
8
  import type { Router } from './router.js'
9
9
  import { partMethods, type PageDeclaration, type PageRequest, type PartPress, type PartsUpdate, type ShownPages } from './ui.js'
@@ -93,7 +93,7 @@ export function servePages({
93
93
  .then(
94
94
  (parts) => void declared.set(mod, pagesOf(parts)),
95
95
  (error: unknown) => {
96
- if (!isNotInstalled(mod, error)) claude.ui.warn(`pages:list:${mod}`, `cmod: ${mod} did not list its pages: ${messageOf(error)}`)
96
+ if (!isNotInstalled(mod, error) && !isStillInstalling(mod, error)) claude.ui.warn(`pages:list:${mod}`, `cmod: ${mod} did not list its pages: ${messageOf(error)}`)
97
97
  },
98
98
  )
99
99
  .finally(() => asking.delete(mod))
@@ -108,7 +108,10 @@ export function servePages({
108
108
  const listed = [...stylers]
109
109
  tellStylers(listed)
110
110
  for (const told of declared.keys()) {
111
- if (told !== cmodPluginName) void claude.cmod.call({ to: told, method: partMethods.stylers, input: listed }).catch((error: unknown) => claude.ui.warn(`pages:stylers:${told}`, `cmod: ${told} did not hear which mods style markdown: ${messageOf(error)}`))
111
+ if (told === cmodPluginName) continue
112
+ void claude.cmod.call({ to: told, method: partMethods.stylers, input: listed }).catch((error: unknown) => {
113
+ if (!isStillInstalling(told, error)) claude.ui.warn(`pages:stylers:${told}`, `cmod: ${told} did not hear which mods style markdown: ${messageOf(error)}`)
114
+ })
112
115
  }
113
116
  }
114
117
 
@@ -2,6 +2,7 @@ import type { RenderElement } from 'claude-code'
2
2
  import { elementOf } from '../ui/elements.js'
3
3
  import { messageOf } from '../utils/text.js'
4
4
  import type { Claude } from './claude.js'
5
+ import { isStillInstalling } from './dependencies.js'
5
6
  import { partMethods, type DrawnPart, type PartPress } from './ui.js'
6
7
 
7
8
  export type DrawnParts = {
@@ -41,6 +42,7 @@ export function drawnParts({ claude, report, press }: { readonly claude: Claude;
41
42
  .then(
42
43
  (data) => keep((data ?? null) as DrawnPart | null),
43
44
  (error: unknown) => {
45
+ if (isStillInstalling(mod, error)) return keep(drawn.get(key)?.data ?? null)
44
46
  report(`draw:${mod}`, `${name} drew nothing`, error)
45
47
  keep(drawn.get(key)?.data ?? null, messageOf(error))
46
48
  },
@@ -14,7 +14,7 @@ import { beforeEvents, processEvents, Session, sessionEvents, type BeforeEvent,
14
14
  import { matches, sentMatcher, type Matcher, type SentMatcher } from '../utils/matcher.js'
15
15
  import { beforeAnswerKeys, foldAnswers, foldBefore, methodOf, takenAnswer, type Answers, type Place } from './before.js'
16
16
  import type { Claude } from './claude.js'
17
- import { cmodPluginName } from './dependencies.js'
17
+ import { cmodPluginName, isStillInstalling } from './dependencies.js'
18
18
  import { messageOf } from '../utils/text.js'
19
19
  import { listenerOf, PassedTimeout, withinTime, type ListenOptions, type ListenTime } from './deadline.js'
20
20
  import { callFiles, type HomeFolders, type HookFields } from './hooks.js'
@@ -195,7 +195,10 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
195
195
  if (tree instanceof Map) return isInScope(scope, session, change, isUnderIn(tree))
196
196
  return tree.then(
197
197
  (read) => isInScope(scope, session, change, isUnderIn(read)),
198
- (error: unknown) => (report(`tasks:${session}`, 'Could not read the tasks it listens under', error), false),
198
+ (error: unknown) => {
199
+ if (!isStillInstalling(cmodPluginName, error)) report(`tasks:${session}`, 'Could not read the tasks it listens under', error)
200
+ return false
201
+ },
199
202
  )
200
203
  }
201
204
 
@@ -9,7 +9,7 @@ import { cmodPluginName } from './dependencies.js'
9
9
 
10
10
  export type ShownToast = { readonly type: ToastType; readonly message: string; readonly description?: string }
11
11
 
12
- export type Failure = { readonly id: string; readonly message: string; readonly error?: unknown; readonly description?: string; readonly retry?: () => unknown; readonly isCritical?: boolean }
12
+ export type Failure = { readonly id: string; readonly message: string; readonly error?: unknown; readonly description?: string; readonly retry?: () => unknown; readonly isCritical?: boolean; readonly root?: string }
13
13
 
14
14
  export type LoggedFailure = {
15
15
  readonly mod: string
@@ -47,6 +47,8 @@ type Entry = {
47
47
  readonly options: ToastOptions
48
48
  readonly actions: readonly Action[]
49
49
  readonly hides?: string
50
+ readonly merged: Map<string, string>
51
+ count: number
50
52
  at: Date
51
53
  isOpen: boolean
52
54
  reporting?: Reporting | undefined
@@ -135,7 +137,8 @@ export function createToaster(claude: Claude, name: string, version: () => strin
135
137
  if (id === undefined) sent.clear()
136
138
  else sent.delete(String(id))
137
139
  for (const entry of entries.values()) {
138
- if (id !== undefined && entry.id !== id) continue
140
+ if (id !== undefined && entry.id !== id && !entry.merged.has(String(id))) continue
141
+ for (const merged of entry.merged.keys()) sent.delete(merged)
139
142
  disarm(entry)
140
143
  entries.delete(entry.id)
141
144
  }
@@ -152,7 +155,7 @@ export function createToaster(claude: Claude, name: string, version: () => strin
152
155
  }
153
156
  if (previous !== undefined) disarm(previous)
154
157
  const reporting = hides !== undefined && previous?.hides === hides ? previous.reporting : undefined
155
- const entry: Entry = { id, type, message, options, actions, ...(hides === undefined ? {} : { hides }), at: new Date(), isOpen: previous?.isOpen ?? false, reporting, timer: undefined }
158
+ const entry: Entry = { id, type, message, options, actions, ...(hides === undefined ? {} : { hides }), merged: new Map(), count: 1, at: new Date(), isOpen: previous?.isOpen ?? false, reporting, timer: undefined }
156
159
  if (type === 'error' && previous?.message !== message) claude.ui.log(`${name}: ${message}${typeof options.description === 'string' ? `: ${options.description}` : ''}`, { to: 'debug' })
157
160
  entries.set(id, entry)
158
161
  changed()
@@ -167,7 +170,7 @@ export function createToaster(claude: Claude, name: string, version: () => strin
167
170
  const hide = (entry: Entry) => {
168
171
  dismiss(entry.id)
169
172
  if (entry.hides === undefined) return
170
- hidden.set(String(entry.id), entry.hides)
173
+ for (const [id, hides] of [[String(entry.id), entry.hides] as const, ...entry.merged]) hidden.set(id, hides)
171
174
  void claude.store.set(hiddenKey, Object.fromEntries(hidden)).catch((error: unknown) => warn('hidden:write', `${name}: could not remember the failure you hid: ${messageOf(error)}`))
172
175
  }
173
176
 
@@ -245,7 +248,7 @@ export function createToaster(claude: Claude, name: string, version: () => strin
245
248
  }
246
249
  }
247
250
 
248
- const fail = ({ id, message, error, description = error === undefined || describe(error) === message ? undefined : describe(error), retry, isCritical = false }: Failure): ToastId => {
251
+ const fail = ({ id, message, error, description = error === undefined || describe(error) === message ? undefined : describe(error), retry, isCritical = false, root = claude.plugin.root }: Failure): ToastId => {
249
252
  const hides = `${version() ?? ''}\n${message}\n${error === undefined ? '' : describe(error)}`
250
253
  const at = new Date()
251
254
  const repeat = `${hides}\n${description ?? ''}\n${at.toISOString().slice(0, 16)}`
@@ -256,7 +259,7 @@ export function createToaster(claude: Claude, name: string, version: () => strin
256
259
  const logged = async () => {
257
260
  const contact = await contactOf(claude)
258
261
  const version = await modVersion()
259
- const failure: LoggedFailure = { mod: name, id, message, details: detailsOf(version, at, `${message}${description === undefined ? '' : `\n${description}`}${stack}`), at: at.toISOString(), isCritical, root: claude.plugin.root, ...(contact === undefined ? {} : { contact }), level: 'error', version, core: coreVersion }
262
+ const failure: LoggedFailure = { mod: name, id, message, details: detailsOf(version, at, `${message}${description === undefined ? '' : `\n${description}`}${stack}`), at: at.toISOString(), isCritical, root, ...(contact === undefined ? {} : { contact }), level: 'error', version, core: coreVersion }
260
263
  const shows = await showsToast(failure, isCritical)
261
264
  if (isCritical) return
262
265
  if (shows !== false) return show()
@@ -265,11 +268,19 @@ export function createToaster(claude: Claude, name: string, version: () => strin
265
268
  const show = () => {
266
269
  if (hidden.get(id) === hides) return
267
270
  hidden.delete(id)
268
- const shown = entries.get(id)
269
- if (shown?.hides === hides && shown.trying === undefined && shown.options.description === description) {
270
- const previous = clockTime(shown.at)
271
+ const own = entries.get(id)
272
+ const text = description ?? message
273
+ const shown =
274
+ own === undefined
275
+ ? [...entries.values()].find((entry) => entry.hides !== undefined && entry.trying === undefined && (entry.options.description ?? entry.message) === text)
276
+ : own.hides === hides && own.trying === undefined && own.options.description === description
277
+ ? own
278
+ : undefined
279
+ if (shown !== undefined) {
280
+ if (shown !== own) shown.merged.set(id, hides)
281
+ shown.count += 1
271
282
  shown.at = new Date()
272
- if (clockTime(shown.at) !== previous) changed()
283
+ changed()
273
284
  return
274
285
  }
275
286
  const actions = [...fixes, ...(retry === undefined ? [] : [{ label: 'Retry', onClick: tryAgain }]), { label: 'Report', onClick: startReporting }]
@@ -323,7 +334,7 @@ export function createToaster(claude: Claude, name: string, version: () => strin
323
334
  const fixed = (child: RenderElement) => Box({ flexShrink: 0, children: child })
324
335
  const close = Button({ plain: true, dimColor: true, key: `toast:${entry.id}:close`, label: entry.hides === undefined ? '✕' : 'Hide', onPress: () => hide(entry) })
325
336
  const actions = entry.actions.map((action, index) => Button({ plain: true, key: `toast:${entry.id}:${index === 0 ? 'action' : `action-${index}`}`, label: action.label, onPress: press(entry, action.onClick) }))
326
- const buttons = Box({ gap: 2, flexWrap: 'wrap', children: [...actions, Text({ dimColor: true, children: clockTime(entry.at) })].map(fixed) })
337
+ const buttons = Box({ gap: 2, flexWrap: 'wrap', children: [...actions, Text({ dimColor: true, children: entry.count > 1 ? `${clockTime(entry.at)} · ${entry.count} times` : clockTime(entry.at) })].map(fixed) })
327
338
  const trying = entry.trying === undefined ? undefined : Box({ gap: 1, children: [Text({ dimColor: true, children: 'Trying again:' }), typeof entry.trying === 'string' ? Text({ dimColor: true, wrap: 'truncate-end', children: entry.trying }) : entry.trying] })
328
339
  const text = details === undefined ? [message] : [message, trying ?? details]
329
340
  const under = trying !== undefined && details === undefined ? [trying] : entry.reporting === undefined ? [buttons] : reportChoices(entry, entry.reporting)