SLOPSHOPPER

handily-item-toasts

A toast when a work item changes outside this session, at most one every 30 s.

guardcommandtoastprompttimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · handily-item-toasts
› fix the failing auth test and add an audit log call ● handily-item-toasts: item-toasts: not counting the call as own; workitems has no root yet ● handily-item-toasts: item-toasts: not counting the call as own; workitems has no root yet ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /item-toasts ⎿ handily-item-toasts: item-toasts off for this session. No work item change draws a toast until /item-toasts on. ● handily-item-toasts: item-toasts: not counting the call as own; workitems has no root yet ● handily-item-toasts: item-toasts: not counting the call as own; the command check failed: TypeError: undefined is not an object (evaluating '$.workitems.classify') ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

handily-item-toasts

item-toasts shows a toast when a work item changes outside this session. Another session, a person at a shell or a sync can make that change. A change that a tool call of this session made draws no toast, because quiet-items and the transcript already show it.

handily-ab12 closed: Draw text mocks for the mods
handily-cd34 created: Write the beads reader
handily-cd34 updated: Write the beads reader (open -> in_progress)
3 work items changed: 2 closed, 1 created (handily-ab12, handily-cd34, +1)
Work items unavailable: basicly tracker items exited 2.
Work items are back: basicly · 14 open.

The approved mocks are in docs/mocks.md, section 4.

How it finds a change

The mod reads the work items only through workitems. It keeps the snapshot version up to which it has read the diffs.

  1. Every 2 s, the mod reads the snapshot. When its version moved, the mod calls $.workitems.refresh({ since }). It holds the diff for the next toast.
  2. Before a counted call runs (see "Which calls count"), the mod calls refresh({ since }) the same way. A change from before the call is then a change made elsewhere.
  3. While a counted call runs, the mod reads no diff.
  4. After the last running counted call ends, the mod calls refresh({ since }) and drops the diff. The call made this change, or the change came while the call ran.

When counted calls overlap, the mod drops the diff of every version from the start of the first call to the end of the last call. A change made elsewhere in that time draws no toast.

Which calls count

isTrackerWrite in hooks/match.ts decides which calls the mod treats as this session's own tracker writes. Every other call runs as if the mod were not there, so a change made elsewhere while it runs draws a toast.

ToolCounts when
Bash$.workitems.classify finds a tracker name: a write, an echoed write or an opaque command such as a loop
Write, Edit$.workitems.trackerFile names a tracker file at the workitems root
  • --help, -h and --dry-run make a command a non-write, so it does not count.
  • When the mod cannot decide, it does not count the call, and it logs why. This happens when $.workitems.classify fails for a Bash call, when $.workitems.trackerFile fails for a Write or Edit call, and when workitems has no snapshot root yet for a Write or Edit call. A missed change made elsewhere is worse than a toast for this session's own change.
  • quiet-items uses the same two rules of workitems, so both mods count the same calls. The command cases and their tests are in mods/handily-workitems.

Known limits:

  • A change made elsewhere while a counted call runs draws no toast.
  • A script that writes the tracker without a tracker name in its command, such as bash close.sh, draws a toast for its own change.

A call that runs on in the background

A Bash call with run_in_background, or a call that the person or the engine moves to the background, returns before its command ends. The mod keeps such a call open until one of these events:

  • The task notification of the call arrives (prompt.submit with the origin task-notification). The mod reads the ids in its <tool-use-id> and <task-id> tags and compares them exactly with the tool_use_id of the call and the backgroundTaskId of its result. A notification without these tags closes nothing.
  • A Stop hook lists the background tasks of the session, and the backgroundTaskId of the call is not in the list.
  • 30 minutes pass. The Stop hook may not run, for example when a Team organisation's security plugin bypasses the user-tier settings hooks. This limit keeps the toasts from stopping for good.

Until then, a change made elsewhere draws no toast. A new session start closes every open call. A reload of the mod forgets the open background calls, so a change that such a command makes after the reload draws a toast. A call that ends after its session ended stays closed: the mod counts a generation for each session and ignores a call from an older one.

A change during a failure

While the snapshot is failed, workitems keeps the last good items. When it recovers, its diff holds every change from the whole failure. When a call of this session was open at any time during the failure, the mod drops that recovery diff. A change made elsewhere during that failure then draws no toast either.

The toast

  • One change draws <id> <created|updated|closed>: <title>. An update that moved the status adds (<old status> -> <new status>). The title is cut to 40 characters with ….
  • The mod shows at most one toast every 30 s. A change inside that time waits, and every waiting change goes into the next toast: N work items changed: <counts> (<id>, <id>, +N). The larger count comes first.
  • When an item changes more than once before its toast, created wins over closed, and closed wins over updated, as in workitems. An update shows the status from before the first change.

The snapshot state

StateToast
ok after failedWork items are back: <source> · <N> open., once
failed after okWork items unavailable: <first sentence of the reason>., once
failed that stays failedNone
no-tracker, approval-needed, terminal-only, staleNone. The mod drops the waiting changes
pausedNone. The mod drops the waiting changes
  • A state toast also waits for the 30 s limit. A failure that recovers before its toast shows draws no toast.
  • The mod keeps the state it last toasted (announced) and the time of its last toast (lastToastAt) in $.state, which outlives a reload of the mod. This is meant to keep a reload from repeating the failed toast or starting a new 30 s window. Tests cover it with a second session start only. A live reload is not tested.
  • On desktop, a basicly source is terminal-only, so the mod shows nothing. A beads or beans source works as in a terminal.

Settings and the command

SettingDefaultUse
modeonThe mode when a session starts: on or off
CommandEffect
/item-toasts offStops the toasts for this session, and replies with the new mode
/item-toasts onStarts the toasts again for this session, and replies with the new mode
/item-toastsToggles the mode for this session, and replies with the new mode
  • The mod keeps the mode in the mode key of its $.state, so a change does not reach other sessions, and the mode outlives a reload of the mod.
  • When the session starts and the mode key is unset, the mod writes the mode setting to it. So a session starts with the mode of the setting, and /item-toasts toggles from there. /handily shows the setting beside the mode when the two differ.
  • While the mode is off, no work item change and no snapshot state draws a toast. A change made while the mode was off draws no toast after /item-toasts on either: the mod reads the work items again from that point.
  • /item-toasts with any other argument changes nothing. The reply names the valid forms.

Develop

claude --plugin-dir mods
claude plugin test mods/handily-item-toasts

item-toasts depends on workitems, so load the mods folder. The tests load a fake workitems provider, because claude plugin test loads only the mod under test.

The test kit has no module reload and no permission prompt. A test with a second session start stands in for a reload, and a call that waits before it runs stands in for a prompt. No test covers a live reload or a live permission prompt.

Source 4 files
hooks/register.tsx 267 lines
1import type { EngineInterface, Register, Timer } from 'claude-code'
2import type { ItemToastsMode } from '../types'
3import { isTrackerWrite, type ToolUse, type TrackerRules } from './match'
4import { createToaster, type ToastHost, type Toaster } from './toasts'
5
6const TICK_MS = 2000
7const BACKGROUND_LIMIT_MS = 30 * 60 * 1000
8
9type CallResult = Awaited<ReturnType<EngineInterface['tool']['call']>>
10type BackgroundTask = { taskId: string | null; limit: Timer }
11
12type Toasts = {
13  toaster: Toaster | undefined
14  ticks: Timer | undefined
15  background: Map<string, BackgroundTask>
16  generation: number
17}
18
19const TASK_ID_TAG = /<task-id>([^<]*)<\/task-id>/g
20const TOOL_USE_ID_TAG = /<tool-use-id>([^<]*)<\/tool-use-id>/g
21const NOT_OWN = 'item-toasts: not counting the call as own;'
22const COMMAND = 'item-toasts'
23const MODE = { plugin: 'handily-item-toasts', key: 'mode' } as const
24const ON_TEXT = 'item-toasts on for this session. A work item that changes elsewhere draws a toast.'
25const OFF_TEXT =
26  'item-toasts off for this session. No work item change draws a toast until /item-toasts on.'
27const USAGE_TEXT =
28  '/item-toasts takes on, off or no argument. /item-toasts on and /item-toasts off set this session, and /item-toasts toggles it. Set the default with the plugin\'s "mode" setting.'
29
30function hostOf($: EngineInterface): ToastHost {
31  return {
32    snapshot: async () =>
33      (await $.state.get({ plugin: 'handily-workitems', key: 'snapshot' })).value,
34    refresh: (since) => $.workitems.refresh({ since }),
35    lines: async (snapshot) => $.workitems.lines({ snapshot, now: await $.clock.now() }),
36    now: () => $.clock.now(),
37    toast: (text) => {
38      $.ui.toast(text)
39    },
40    log: (text) => {
41      $.ui.log(text)
42    },
43    announced: async () =>
44      (await $.state.get({ plugin: 'handily-item-toasts', key: 'announced' })).value,
45    announce: async (health) => {
46      await $.state.set({ plugin: 'handily-item-toasts', key: 'announced' }, health)
47    },
48    lastToastAt: async () =>
49      (await $.state.get({ plugin: 'handily-item-toasts', key: 'lastToastAt' })).value,
50    noteToast: async (at) => {
51      await $.state.set({ plugin: 'handily-item-toasts', key: 'lastToastAt' }, at)
52    },
53  }
54}
55
56function stopToasts(toasts: Toasts): void {
57  toasts.generation += 1
58  toasts.ticks?.cancel()
59  toasts.ticks = undefined
60  toasts.toaster = undefined
61  for (const task of toasts.background.values()) task.limit.cancel()
62  toasts.background.clear()
63}
64
65function startToasts($: EngineInterface, toasts: Toasts): Toaster {
66  stopToasts(toasts)
67  const toaster = createToaster(hostOf($))
68  toasts.toaster = toaster
69  toasts.ticks = $.clock.every(TICK_MS, () => {
70    toaster.tick().catch((error: unknown) => {
71      $.ui.log(`item-toasts: the tick failed: ${String(error)}`)
72    })
73  })
74  return toaster
75}
76
77async function isOn($: EngineInterface, defaultMode: ItemToastsMode): Promise<boolean> {
78  const { value: mode = defaultMode } = await $.state.get(MODE)
79  return mode === 'on'
80}
81
82function modeFor(args: string, isCurrentlyOn: boolean): ItemToastsMode | null {
83  const asked = args.trim()
84  if (asked === '') return isCurrentlyOn ? 'off' : 'on'
85  if (asked === 'on' || asked === 'off') return asked
86  return null
87}
88
89async function toasterOf(
90  $: EngineInterface,
91  toasts: Toasts,
92  defaultMode: ItemToastsMode,
93): Promise<Toaster | undefined> {
94  if (toasts.toaster !== undefined) return toasts.toaster
95  return (await isOn($, defaultMode)) ? startToasts($, toasts) : undefined
96}
97
98async function setMode($: EngineInterface, toasts: Toasts, mode: ItemToastsMode): Promise<string> {
99  await $.state.set(MODE, mode)
100  if (mode === 'off') {
101    stopToasts(toasts)
102    return OFF_TEXT
103  }
104  if (toasts.toaster === undefined) await startToasts($, toasts).tick()
105  return ON_TEXT
106}
107
108function rulesOf($: EngineInterface): TrackerRules {
109  return {
110    classify: (command) => $.workitems.classify(command),
111    trackerFile: (args) => $.workitems.trackerFile(args),
112  }
113}
114
115async function isOwnCall($: EngineInterface, use: ToolUse): Promise<boolean> {
116  try {
117    return await isTrackerWrite(rulesOf($), use)
118  } catch (error) {
119    const check = use.tool === 'Bash' ? 'the command check' : 'the tracker file check'
120    $.ui.log(`${NOT_OWN} ${check} failed: ${String(error)}`)
121    return false
122  }
123}
124
125function backgroundTaskIdOf(
126  isLaunchedInBackground: boolean,
127  result: CallResult,
128): { taskId: string | null } | null {
129  const output: unknown = result.result
130  const taskId =
131    typeof output === 'object' &&
132    output !== null &&
133    'backgroundTaskId' in output &&
134    typeof output.backgroundTaskId === 'string'
135      ? output.backgroundTaskId
136      : null
137  if (taskId === null && !isLaunchedInBackground) return null
138  return { taskId }
139}
140
141async function endBackground(
142  toasts: Toasts,
143  hasEnded: (toolUseId: string, task: BackgroundTask) => boolean,
144): Promise<void> {
145  for (const [toolUseId, task] of [...toasts.background]) {
146    if (!hasEnded(toolUseId, task)) continue
147    task.limit.cancel()
148    toasts.background.delete(toolUseId)
149    await toasts.toaster?.leaveCall()
150  }
151}
152
153function keepBackgroundOpen(
154  $: EngineInterface,
155  toasts: Toasts,
156  toolUseId: string,
157  taskId: string | null,
158): void {
159  const limit = $.clock.after(BACKGROUND_LIMIT_MS, () => {
160    endBackground(toasts, (openId) => openId === toolUseId).catch((error: unknown) => {
161      $.ui.log(`item-toasts: closing a background call failed: ${String(error)}`)
162    })
163  })
164  toasts.background.set(toolUseId, { taskId, limit })
165}
166
167function idsIn(text: string, tag: RegExp): ReadonlySet<string> {
168  return new Set(Array.from(text.matchAll(tag), (match) => (match[1] ?? '').trim()))
169}
170
171function isNamedIn(text: string, toolUseId: string, task: BackgroundTask): boolean {
172  if (idsIn(text, TOOL_USE_ID_TAG).has(toolUseId)) return true
173  return task.taskId !== null && idsIn(text, TASK_ID_TAG).has(task.taskId)
174}
175
176export const register: Register = (on, options) => {
177  const defaultMode: ItemToastsMode = options.mode === 'off' ? 'off' : 'on'
178  const toasts: Toasts = {
179    toaster: undefined,
180    ticks: undefined,
181    background: new Map(),
182    generation: 0,
183  }
184
185  on('session.start', async ($, e, next) => {
186    await $.command.register({
187      name: COMMAND,
188      description: 'handily · Set or toggle the toasts for work item changes for this session',
189      argumentHint: '[on|off]',
190    })
191    const started = await next(e)
192    const { value: mode, version } = await $.state.get(MODE)
193    if (mode === undefined) await $.state.set(MODE, defaultMode, { ifVersion: version })
194    if (await isOn($, defaultMode)) await startToasts($, toasts).tick()
195    await $.state.set({ plugin: 'handily-item-toasts', key: 'ready' }, { root: $.plugin.root })
196    return started
197  })
198
199  on('command.run', { command: COMMAND }, async ($, e) => {
200    const mode = modeFor(e.args, await isOn($, defaultMode))
201    if (mode === null) return { text: USAGE_TEXT }
202    return { text: await setMode($, toasts, mode) }
203  })
204
205  on('session.end', (_$, e, next) => {
206    stopToasts(toasts)
207    return next(e)
208  })
209
210  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
211    if (!(await isOwnCall($, { tool: 'Bash', command: e.command }))) return next(e)
212    const toaster = await toasterOf($, toasts, defaultMode)
213    if (toaster === undefined) return next(e)
214    const generation = toasts.generation
215    await toaster.enterCall()
216    let result: CallResult
217    try {
218      result = await next(e)
219    } catch (error) {
220      await toaster.leaveCall()
221      throw error
222    }
223    if (toasts.generation !== generation) return result
224    const background = backgroundTaskIdOf(e.run_in_background === true, result)
225    if (background === null) await toaster.leaveCall()
226    else keepBackgroundOpen($, toasts, e.tool_use_id, background.taskId)
227    return result
228  })
229
230  on('tool.call', { tool: ['Write', 'Edit'] }, async ($, e, next) => {
231    const { value: snapshot } = await $.state.get({ plugin: 'handily-workitems', key: 'snapshot' })
232    if (snapshot === undefined) {
233      $.ui.log(`${NOT_OWN} workitems has no root yet`)
234      return next(e)
235    }
236    const use: ToolUse = { tool: e.tool, filePath: e.file_path, root: snapshot.root }
237    if (!(await isOwnCall($, use))) return next(e)
238    const toaster = await toasterOf($, toasts, defaultMode)
239    if (toaster === undefined) return next(e)
240    await toaster.enterCall()
241    try {
242      return await next(e)
243    } finally {
244      await toaster.leaveCall()
245    }
246  })
247
248  on('prompt.submit', async (_$, e, next) => {
249    if (e.origin.kind === 'task-notification') {
250      await endBackground(toasts, (toolUseId, task) => isNamedIn(e.text, toolUseId, task))
251    }
252    return next(e)
253  })
254
255  on('classic.Stop', async (_$, e, next) => {
256    const running = e.background_tasks
257    if (running !== undefined) {
258      const runningIds = new Set(running.map((task) => task.id))
259      await endBackground(
260        toasts,
261        (_toolUseId, task) => task.taskId !== null && !runningIds.has(task.taskId),
262      )
263    }
264    return next(e)
265  })
266}
267
hooks/match.ts 12 lines
1import type { EngineInterface } from 'claude-code'
2
3export type TrackerRules = Pick<EngineInterface['workitems'], 'classify' | 'trackerFile'>
4
5export type ToolUse =
6  { tool: 'Bash'; command: string } | { tool: 'Write' | 'Edit'; filePath: string; root: string }
7
8export async function isTrackerWrite(rules: TrackerRules, use: ToolUse): Promise<boolean> {
9  if (use.tool === 'Bash') return (await rules.classify(use.command)).kind !== 'none'
10  return (await rules.trackerFile({ path: use.filePath, root: use.root })) !== null
11}
12
hooks/toasts.ts 239 lines
1import type { EngineInterface, PluginState } from 'claude-code'
2import type { ItemToastsHealth as Health } from '../types'
3
4type Snapshot = PluginState['handily-workitems']['snapshot']
5type Refreshed = Awaited<ReturnType<EngineInterface['workitems']['refresh']>>
6type Item = Refreshed['created'][number]
7type Line = Awaited<ReturnType<EngineInterface['workitems']['lines']>>[number]
8type ChangeKind = 'created' | 'updated' | 'closed'
9
10export const TITLE_LENGTH = 40
11export const QUIET_WINDOW_MS = 30_000
12
13const NAMED_IDS = 2
14const KINDS_IN_DIFF_ORDER: readonly ChangeKind[] = ['created', 'updated', 'closed']
15const KINDS_BY_STRENGTH: readonly ChangeKind[] = ['updated', 'closed', 'created']
16const HEADER_AGE_PART = ' \u00b7 read '
17
18export type Change = {
19  kind: ChangeKind
20  id: string
21  title: string
22  from: string | null
23  to: string
24}
25
26export type ToastHost = {
27  snapshot: () => Promise<Snapshot | undefined>
28  refresh: (since: number) => Promise<Refreshed>
29  lines: (snapshot: Snapshot) => Promise<readonly Line[]>
30  now: () => Promise<number>
31  toast: (text: string) => void
32  log: (text: string) => void
33  announced: () => Promise<Health | undefined>
34  announce: (health: Health) => Promise<void>
35  lastToastAt: () => Promise<number | undefined>
36  noteToast: (at: number) => Promise<void>
37}
38
39export type Toaster = {
40  tick: () => Promise<void>
41  enterCall: () => Promise<void>
42  leaveCall: () => Promise<void>
43}
44
45export function cutTitle(title: string, length: number): string {
46  const graphemes = Array.from(new Intl.Segmenter().segment(title), (part) => part.segment)
47  if (graphemes.length <= length) return title
48  return `${graphemes.slice(0, length).join('').trimEnd()}\u2026`
49}
50
51function statusMove(change: Change): string {
52  if (change.kind !== 'updated' || change.from === null || change.from === change.to) return ''
53  return ` (${change.from} -> ${change.to})`
54}
55
56export function changeText(change: Change): string {
57  return `${change.id} ${change.kind}: ${cutTitle(change.title, TITLE_LENGTH)}${statusMove(change)}`
58}
59
60function countsText(changes: readonly Change[]): string {
61  const counts = KINDS_IN_DIFF_ORDER.map((kind) => ({
62    kind,
63    count: changes.filter((change) => change.kind === kind).length,
64  }))
65  return counts
66    .filter(({ count }) => count > 0)
67    .sort((a, b) => b.count - a.count)
68    .map(({ kind, count }) => `${String(count)} ${kind}`)
69    .join(', ')
70}
71
72function idsText(changes: readonly Change[]): string {
73  const named = changes.slice(0, NAMED_IDS).map((change) => change.id)
74  const rest = changes.length - named.length
75  return rest > 0 ? [...named, `+${String(rest)}`].join(', ') : named.join(', ')
76}
77
78export function changesText(changes: readonly Change[]): string {
79  const [only] = changes
80  if (changes.length === 1 && only !== undefined) return changeText(only)
81  return `${String(changes.length)} work items changed: ${countsText(changes)} (${idsText(changes)})`
82}
83
84function healthOf(snapshot: Snapshot): Health | null {
85  if (snapshot.state === 'ok') return 'ok'
86  if (snapshot.state === 'failed') return 'failed'
87  return null
88}
89
90function firstSentence(text: string): string {
91  const [first = text] = text.split('. ')
92  return `${first.replace(/\.$/, '')}.`
93}
94
95export function healthText(lines: readonly Line[], health: Health): string {
96  if (health === 'failed') {
97    const failed = lines.find((line) => line.kind === 'failed')
98    if (!failed) throw new Error('item-toasts: workitems drew no failed line for a failed snapshot')
99    return firstSentence(failed.text)
100  }
101  const header = lines.find((line) => line.kind === 'header')
102  if (!header) throw new Error('item-toasts: workitems drew no header line for an ok snapshot')
103  const [label = header.text] = header.text.split(HEADER_AGE_PART)
104  return `Work items are back: ${label}.`
105}
106
107function strongerKind(held: ChangeKind, next: ChangeKind): ChangeKind {
108  return KINDS_BY_STRENGTH.indexOf(held) > KINDS_BY_STRENGTH.indexOf(next) ? held : next
109}
110
111export function createToaster(host: ToastHost): Toaster {
112  let seen: number | undefined
113  let runningCalls = 0
114  let isFailed = false
115  let hasOwnCallDuringFailure = false
116  const knownStatus = new Map<string, string>()
117  const pending = new Map<string, Change>()
118  let queue: Promise<void> = Promise.resolve()
119
120  function inTurn(step: () => Promise<void>): Promise<void> {
121    const run = queue.then(step).catch((error: unknown) => {
122      host.log(`item-toasts: ${String(error)}`)
123    })
124    queue = run
125    return run
126  }
127
128  function remember(items: readonly Item[]): void {
129    for (const item of items) knownStatus.set(item.key, item.rawStatus)
130  }
131
132  function hold(refreshed: Refreshed): void {
133    for (const kind of KINDS_IN_DIFF_ORDER) {
134      for (const item of refreshed[kind]) {
135        const change: Change = {
136          kind,
137          id: item.id,
138          title: item.title,
139          from: knownStatus.get(item.key) ?? null,
140          to: item.rawStatus,
141        }
142        const held = pending.get(item.key)
143        pending.set(
144          item.key,
145          held ? { ...change, kind: strongerKind(held.kind, kind), from: held.from } : change,
146        )
147      }
148    }
149  }
150
151  function takeBaseline(snapshot: Snapshot): number {
152    isFailed = snapshot.state === 'failed'
153    remember(snapshot.items)
154    return snapshot.version
155  }
156
157  async function catchUp(isElsewhere: boolean, mustRead: boolean): Promise<void> {
158    const snapshot = await host.snapshot()
159    if (snapshot === undefined) return
160    const hasProviderRestarted = seen !== undefined && snapshot.version < seen
161    if (hasProviderRestarted) {
162      seen = takeBaseline(snapshot)
163      return
164    }
165    seen ??= takeBaseline(snapshot)
166    if (!mustRead && snapshot.version === seen) return
167    let refreshed: Refreshed
168    try {
169      refreshed = await host.refresh(seen)
170    } catch (error) {
171      seen = undefined
172      throw error
173    }
174    seen = refreshed.version
175    const wasFailed = isFailed
176    isFailed = (await host.snapshot())?.state === 'failed'
177    const hasRecovered = wasFailed && !isFailed
178    const isOwnRecovery = hasRecovered && hasOwnCallDuringFailure
179    if (hasRecovered) hasOwnCallDuringFailure = false
180    if (isElsewhere && !isOwnRecovery) hold(refreshed)
181    remember([...refreshed.created, ...refreshed.updated, ...refreshed.closed])
182  }
183
184  function noteOwnCall(): void {
185    if (isFailed) hasOwnCallDuringFailure = true
186  }
187
188  async function nextText(snapshot: Snapshot, health: Health): Promise<string | null> {
189    if (health !== ((await host.announced()) ?? 'ok')) {
190      const text = healthText(await host.lines(snapshot), health)
191      await host.announce(health)
192      return text
193    }
194    if (pending.size === 0) return null
195    const text = changesText([...pending.values()])
196    pending.clear()
197    return text
198  }
199
200  async function flush(): Promise<void> {
201    const snapshot = await host.snapshot()
202    if (snapshot === undefined) return
203    const health = healthOf(snapshot)
204    if (health === null) {
205      pending.clear()
206      return
207    }
208    const now = await host.now()
209    const lastToastAt = await host.lastToastAt()
210    if (lastToastAt !== undefined && now - lastToastAt < QUIET_WINDOW_MS) return
211    const text = await nextText(snapshot, health)
212    if (text === null) return
213    host.toast(text)
214    await host.noteToast(now)
215  }
216
217  return {
218    tick: () =>
219      inTurn(async () => {
220        if (runningCalls === 0) await catchUp(true, false)
221        await flush()
222      }),
223    enterCall: () =>
224      inTurn(async () => {
225        runningCalls += 1
226        if (runningCalls > 1) return
227        await catchUp(true, true)
228        await flush()
229      }),
230    leaveCall: () =>
231      inTurn(async () => {
232        runningCalls -= 1
233        if (runningCalls > 0) return
234        await catchUp(false, true)
235        noteOwnCall()
236      }),
237  }
238}
239
types/index.d.ts 15 lines
1export type ItemToastsHealth = 'ok' | 'failed'
2
3export type ItemToastsMode = 'on' | 'off'
4
5declare module 'claude-code' {
6  interface PluginState {
7    'handily-item-toasts': {
8      mode: ItemToastsMode
9      announced: ItemToastsHealth
10      lastToastAt: number
11      ready: { root: string }
12    }
13  }
14}
15