SLOPSHOPPER

cache-timer

Claude Code mod that counts down the prompt cache, shows and sets Claude Code's own idle compaction, and can push a reminder to your phone.

bandtoastprocesstimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cache-timer
› fix the failing auth test and add an audit log call ╭────────────────────────────────────────────╮ │ cache-timer │ ⏺ Read(src/auth.ts) │ cache-timer: idle-compaction threshold not │ ⎿ Read 6 lines │ set (TypeError: undefined is not an object │ ⏺ Update(src/auth.ts) │ (evaluating 'result.deny')) │ ⎿ 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 cache — idle n/a notify ⚙ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
cache — idle n/a notify ⚙
README

cache-timer

cache-timer is a Claude Code mod that shows how long the prompt cache of the current conversation stays warm, shows and sets Claude Code's own idle compaction, and can push a reminder to your phone before the cache expires. The mod itself never compacts a conversation.

It runs only in Claude Code, which loads its function hooks (an early-access plugin API). Other agent tools do not load it.

What It Does

  • Countdown band above the prompt: 54:12 ━━━━━━──── 1h · 612k/500k reads as the time left on the cache, a bar of the lifetime left, the cache lifetime, and the tokens the next request re-sends against the idle-compaction threshold (the threshold is left out while idle compaction is off or does not run, and for a 5-minute cache, which it leaves alone). Icons on the right show whether idle compaction and notifications are on; idle n/a means /config offers no Idle compaction row in this session: Claude Code does not run idle compaction there, or a settings file other than your own sets it. The gear opens a row with a switch for idle compaction, a threshold picker (300k, 500k, or 700k), and a switch and lead-time picker (10, 15, or 20 minutes) for notifications. In the terminal, click them or press ctrl+x tab to focus the band. The band shows in the terminal and in sessions the desktop app runs; viewers that attach over Remote Control, including the iOS app, do not draw mod UI.
  • Claude Code's idle compaction: Claude Code itself can compact a long conversation shortly before its 1-hour cache expires (about 54 minutes into an idle period), so your next message does not re-send the whole context. Where your account has it, /config lists an Idle compaction row; the band's switch changes that same setting. The mod gives the session the threshold as CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS, so idle compaction runs only from that many tokens; a value under 100k is raised to 100k. Where the variable cannot be set, the band shows the threshold Claude Code uses. Leave that variable out of your own settings' env, or a change to the settings file sets it back.
  • Notification before expiry: when a 1-hour cache has the notification lead time left, it sends one push notification per idle period with the session's name and the question its last reply asked, for example Mod check / 「Shall I release 0.2.0?」 / — cache expires in 10 min. It goes through Claude Code's own push notification, so it reaches the phone only while the session has Remote Control on and you are not active in it. A 5-minute cache does not notify.
  • Exact cache lifetime: Claude Code gives status-line scripts the lifetime as prompt_cache.ttl, but the function-hook API does not expose it. After each turn the mod reads the tail of the session transcript, where each response records whether its cache write was 1-hour or 5-minute, and uses that. The transcript format is Claude Code's own and may change; when no write is found there, the mod falls back to inference: it starts from 1 hour and, after a gap of 5.5 to 58 minutes on the same model, a cache hit confirms 1 hour and a miss switches to 5 minutes. Pinning cache_ttl overrides both.

Settings

Each field is a row under /config; a change there or in the band reloads the mod, and the countdown carries over the reload. Sessions the desktop app runs have no /config rows for plugins, so a change made in the band there is kept in the mod's own store and applies to later sessions too; a later /config change to the same field replaces it. The idle-compaction switch is Claude Code's own Idle compaction row, not one of these fields.

FieldDefaultMeaning
threshold_k500Idle compaction runs only when the context holds at least this many thousand tokens
notifytrueSend a push notification before a 1-hour cache expires
notify_lead_minutes10Minutes before a 1-hour cache expires to notify
cache_ttlautoauto (transcript, then inference), 1h, or 5m

Layout

.claude-plugin/plugin.json   Name and settings
hooks/hooks.json             Names the hooks module
hooks/register.tsx           Countdown, inference, idle-compaction settings, and the band
hooks/register.test.tsx      Mock-clock tests: claude plugin test plugins/cache-timer
types/index.d.ts             Type of the cache clock the module keeps

License

MIT

Source 2 files
hooks/register.tsx 572 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3import type { CacheClock, CacheTtl } from '../types'
4
5const TTL_MS: Record<CacheTtl, number> = { '5m': 5 * 60_000, '1h': 60 * 60_000 }
6
7// A gap inside this window tells the two lifetimes apart: a 5m cache has
8// lapsed, a 1h cache has not.
9const INFER_MIN_GAP_MS = 5.5 * 60_000
10const INFER_MAX_GAP_MS = 58 * 60_000
11const INFER_MIN_TOKENS = 20_000
12
13const initial: CacheClock = {
14  lastAt: null,
15  tokens: 0,
16  model: null,
17  ttl: '1h',
18  isTtlObserved: false,
19  isTtlExact: false,
20  notifiedAt: null,
21  title: null,
22  question: null,
23}
24
25// The tail of the transcript read after each turn: enough to reach the
26// turn's last response, well under what one host command returns.
27const TRANSCRIPT_TAIL_BYTES = 512 * 1024
28
29/**
30 * The lifetime of the last main-conversation cache write recorded in the
31 * transcript tail, or null when none is found. The transcript format is
32 * Claude Code's own and may change; callers fall back to inference.
33 */
34export function ttlFromTranscriptTail(tail: string): CacheTtl | null {
35  const lines = tail.split('\n')
36
37  for (let i = lines.length - 1; i >= 0; i -= 1) {
38    let entry: unknown
39    try {
40      entry = JSON.parse(lines[i] ?? '')
41    } catch {
42      continue
43    }
44    const row = entry as {
45      type?: string
46      isSidechain?: boolean
47      message?: { usage?: { cache_creation?: { ephemeral_1h_input_tokens?: number; ephemeral_5m_input_tokens?: number } } }
48    }
49    const written = row.type === 'assistant' && row.isSidechain !== true ? row.message?.usage?.cache_creation : undefined
50
51    if ((written?.ephemeral_1h_input_tokens ?? 0) > 0) {
52      return '1h'
53    }
54    if ((written?.ephemeral_5m_input_tokens ?? 0) > 0) {
55      return '5m'
56    }
57  }
58
59  return null
60}
61
62// The session's cache clock. Module state, saved to the plugin's store under
63// the session id on each change, so a reload (a /config change, a press in
64// the band) restores it in session.start instead of starting over.
65let clock: CacheClock = initial
66
67const storeKey = (sessionId: string): string => `clock:${sessionId}`
68
69const update = ($: EngineInterface, fn: (prev: CacheClock) => CacheClock): void => {
70  clock = fn(clock)
71  const saved = clock
72  void (async () => {
73    await $.store.set(storeKey(await $.session.id()), saved)
74  })().catch(() => {
75    // An unsaved clock only costs the countdown after a reload.
76  })
77}
78
79const QUESTION_MAX = 140
80
81/**
82 * The question a reply leaves the user with: its last sentence that ends in a
83 * question mark, or else its last paragraph, without Markdown marks and cut to
84 * fit a push notification. Null for an empty reply.
85 */
86export function questionOf(reply: string): string | null {
87  const plain = reply
88    .replace(/```[\s\S]*?```/g, ' ')
89    .replace(/[*_`#>]/g, '')
90    .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
91  const paragraphs = plain.split(/\n\s*\n/).map(p => p.replace(/\s+/g, ' ').trim()).filter(p => p !== '')
92
93  if (paragraphs.length === 0) {
94    return null
95  }
96
97  // A full stop inside a word (a version, a path) does not end a sentence.
98  const sentences = paragraphs.flatMap(p => p.split(/(?<=[。!?])|(?<=[.!?])\s+/)).map(t => t.trim()).filter(t => t !== '')
99  const asked = [...sentences].reverse().find(t => /[??]$/.test(t))
100  const text = asked ?? paragraphs[paragraphs.length - 1] ?? ''
101
102  return text.length > QUESTION_MAX ? `${text.slice(0, QUESTION_MAX - 1)}…` : text
103}
104
105/** What the band shows, set by the clock's tick. */
106type View = {
107  /** Time left (`54:12`), `expired`, or `—` before a request. */
108  time: string
109  /** Lifetime and tokens against the threshold: `1h · 612k/500k`. */
110  detail: string
111  /** Share of the cache lifetime left, 0 to 1; null when no countdown runs. */
112  left: number | null
113}
114
115let view: View = { time: '—', detail: '', left: null }
116
117// Whether the band shows its settings row; per process, closed after a reload.
118let isExpanded = false
119
120const formatRemaining = (ms: number): string => {
121  const total = Math.max(0, Math.ceil(ms / 1000))
122  const minutes = Math.floor(total / 60)
123  const seconds = String(total % 60).padStart(2, '0')
124
125  return `${minutes}:${seconds}`
126}
127
128const formatK = (tokens: number): string => `${Math.round(tokens / 1000)}k`
129
130const setView = ($: EngineInterface, next: View): void => {
131  if (next.time !== view.time || next.detail !== view.detail || next.left !== view.left) {
132    view = next
133    $.ui.invalidate('ui.render')
134  }
135}
136
137const THRESHOLD_PRESETS_K = [300, 500, 700]
138const NOTIFY_LEAD_PRESETS_MIN = [10, 15, 20]
139
140const BAR_CELLS = 10
141
142// Icons for the desktop band; the terminal draws text instead.
143const ON = '#1D9E75'
144const OFF = '#888780'
145const icon = (paths: string, color: string): string =>
146  `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${paths}</svg>`
147const CLOCK = '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 3"/>'
148const COMPRESS = '<path d="M5 9h4V5M15 5v4h4M5 15h4v4M15 19v-4h4"/>'
149const BELL = '<path d="M10 5a2 2 0 1 1 4 0a7 7 0 0 1 4 6v3a4 4 0 0 0 2 3H4a4 4 0 0 0 2-3v-3a7 7 0 0 1 4-6"/><path d="M9 17v1a3 3 0 0 0 6 0v-1"/>'
150const bar = (left: number): string =>
151  `<svg xmlns="http://www.w3.org/2000/svg" width="80" height="4" viewBox="0 0 80 4"><rect width="80" height="4" rx="2" fill="${OFF}" fill-opacity="0.35"/><rect width="${Math.round(80 * left)}" height="4" rx="2" fill="${left > 0.2 ? ON : '#BA7517'}"/></svg>`
152
153/** The `/config` key of one of this plugin's fields, as the engine names it. */
154async function configKey($: EngineInterface, field: string): Promise<string | undefined> {
155  const rows = await $.config.list()
156
157  return rows.find(row => row.key.startsWith('cache-timer') && row.key.endsWith(`.${field}`))?.key
158}
159
160// Settings changed in the band where `/config` has no rows for them (a session
161// the desktop app runs). Kept in the plugin store across sessions; a `/config`
162// change to the same field drops the entry.
163const OVERRIDES_KEY = 'settings'
164let overrides: Record<string, boolean | number> = {}
165
166const saveOverrides = async ($: EngineInterface): Promise<void> => {
167  try {
168    await $.store.set(OVERRIDES_KEY, overrides)
169  } catch {
170    // Unsaved: the change holds for this process only.
171  }
172}
173
174async function setOption($: EngineInterface, field: string, value: boolean | number): Promise<void> {
175  const key = await configKey($, field)
176
177  if (key === undefined) {
178    overrides = { ...overrides, [field]: value }
179    $.ui.invalidate('ui.render')
180    await saveOverrides($)
181  } else {
182    const result = await $.config.set({ key, value })
183
184    if ('deny' in result && result.deny !== undefined) {
185      $.ui.toast(`cache-timer: ${field} not changed (${result.deny})`)
186
187      return
188    }
189  }
190
191  if (field === 'threshold_k') {
192    await applyThreshold($, Number(value))
193  }
194}
195
196// Claude Code's own idle compaction compacts a long conversation shortly
197// before its 1-hour cache expires. Its /config row exists only where the
198// engine runs it; the row's value is the person's switch.
199type IdleCompaction = 'on' | 'off' | 'unavailable'
200
201const IDLE_ROW = 'idleCompaction'
202
203// Claude Code raises a lower idle-compaction minimum to this floor, and uses
204// its default when the variable is unset or not a positive whole number.
205const IDLE_FLOOR_K = 100
206const IDLE_DEFAULT_K = 200
207
208// The minimum Claude Code reads now, in thousands of tokens: what the band
209// shows, whether or not the mod's own write went through.
210let appliedK = IDLE_DEFAULT_K
211
212let idle: IdleCompaction = 'unavailable'
213
214const setIdleState = ($: EngineInterface, next: IdleCompaction): void => {
215  if (next !== idle) {
216    idle = next
217    $.ui.invalidate('ui.render')
218  }
219}
220
221async function readIdle($: EngineInterface): Promise<void> {
222  try {
223    const row = (await $.config.list()).find(r => r.key === IDLE_ROW)
224    setIdleState($, row === undefined ? 'unavailable' : row.value === false ? 'off' : 'on')
225  } catch {
226    // An unreadable menu leaves the last state shown.
227  }
228}
229
230async function setIdle($: EngineInterface, value: boolean): Promise<void> {
231  try {
232    const result = await $.config.set({ key: IDLE_ROW, value })
233
234    if ('deny' in result && result.deny !== undefined) {
235      $.ui.toast(`cache-timer: idle compaction not changed (${result.deny})`)
236
237      return
238    }
239    setIdleState($, value ? 'on' : 'off')
240  } catch (err) {
241    $.ui.toast(`cache-timer: idle compaction not changed (${String(err)})`)
242  }
243}
244
245async function readThreshold($: EngineInterface): Promise<void> {
246  try {
247    const raw = await $.env.get('CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS')
248    const tokens = raw !== undefined && /^\d+$/.test(raw) && Number(raw) >= 1 ? Number(raw) : IDLE_DEFAULT_K * 1000
249    const next = Math.max(IDLE_FLOOR_K, Math.round(tokens / 1000))
250
251    if (next !== appliedK) {
252      appliedK = next
253      $.ui.invalidate('ui.render')
254    }
255  } catch {
256    // An unreadable environment leaves the last value shown.
257  }
258}
259
260// Claude Code reads its idle-compaction minimum from this process's
261// environment on every check, so setting it takes effect at once.
262async function applyThreshold($: EngineInterface, k: number): Promise<void> {
263  try {
264    const result = await $.env.set('CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS', String(Math.round(Math.max(IDLE_FLOOR_K, k) * 1000)))
265
266    if (result.deny !== undefined) {
267      $.ui.toast(`cache-timer: idle-compaction threshold not set (${result.deny})`)
268    }
269  } catch (err) {
270    $.ui.toast(`cache-timer: idle-compaction threshold not set (${String(err)})`)
271  }
272
273  await readThreshold($)
274}
275
276export const register: Register = (on, options) => {
277  const option = (field: string, fallback: boolean | number) => overrides[field] ?? options[field] ?? fallback
278  const isNotify = () => option('notify', true) !== false
279  const notifyLeadMin = () => Number(option('notify_lead_minutes', 10))
280  const thresholdK = () => Number(option('threshold_k', 500))
281  const ttlMode = String(options.cache_ttl ?? 'auto')
282
283  // Tokens against the idle-compaction threshold where idle compaction can
284  // run: it is on and the cache lasts 1 hour.
285  const tokensOf = (tokens: number, ttl: CacheTtl): string =>
286    idle === 'on' && ttl === '1h' ? `${formatK(tokens)}/${appliedK}k` : formatK(tokens)
287
288  const effectiveTtl = (s: CacheClock): { ttl: CacheTtl; label: string } => {
289    if (ttlMode === '1h' || ttlMode === '5m') {
290      return { ttl: ttlMode, label: ttlMode }
291    }
292
293    return { ttl: s.ttl, label: s.ttl }
294  }
295
296  on('turn.step', async function* ($, e, next) {
297    // The cache entry is refreshed when the request is processed, not when
298    // the response ends, so the countdown starts from the send time.
299    const sentAt = await $.clock.now()
300    const result = yield* next(e)
301    const usage = result.usage
302
303    if (e.agentId !== undefined || usage === null) {
304      return result
305    }
306
307    const tokens =
308      usage.input_tokens +
309      usage.cache_read_input_tokens +
310      usage.cache_creation_input_tokens +
311      usage.output_tokens
312
313    update($, prev => {
314      let { ttl, isTtlObserved } = prev
315      const gap = prev.lastAt === null ? 0 : sentAt - prev.lastAt
316      const isComparable =
317        !prev.isTtlExact &&
318        prev.lastAt !== null &&
319        prev.model === usage.model &&
320        prev.tokens >= INFER_MIN_TOKENS &&
321        gap >= INFER_MIN_GAP_MS &&
322        gap <= INFER_MAX_GAP_MS
323
324      if (isComparable) {
325        if (usage.cache_read_input_tokens >= prev.tokens * 0.5) {
326          ttl = '1h'
327          isTtlObserved = true
328        } else if (usage.cache_read_input_tokens <= prev.tokens * 0.1) {
329          ttl = '5m'
330          isTtlObserved = true
331        }
332      }
333
334      return { ...prev, lastAt: sentAt, tokens, model: usage.model, ttl, isTtlObserved }
335    })
336
337    return result
338  })
339
340  // Any compaction (manual, automatic, idle) replaces the cached prefix.
341  on('session.compact', async ($, e, next) => {
342    const result = await next(e)
343
344    if (e.trigger !== 'precompute' && result.messages !== undefined && e.agentId === undefined) {
345      update($, prev => ({
346        ...prev,
347        lastAt: null,
348        tokens: result.tokensAfter ?? 0,
349      }))
350    }
351
352    return result
353  })
354
355  // The session's name, for the notification.
356  on('classic.UserPromptSubmit', async ($, e, next) => {
357    if (e.session_title !== undefined && e.session_title !== clock.title) {
358      update($, prev => ({ ...prev, title: e.session_title ?? null }))
359    }
360
361    return next(e)
362  })
363
364  // At the end of each main turn, take the exact lifetime from the transcript,
365  // and look again whether idle compaction runs.
366  on('classic.Stop', async ($, e, next) => {
367    const result = await next(e)
368    update($, prev => ({ ...prev, question: questionOf(e.last_assistant_message ?? '') }))
369    await readIdle($)
370
371    try {
372      const ran = await $.process.run(['tail', '-c', String(TRANSCRIPT_TAIL_BYTES), e.transcript_path])
373      const ttl = ran.exitCode === 0 ? ttlFromTranscriptTail(ran.stdout) : null
374
375      if (ttl !== null) {
376        update($, prev => ({ ...prev, ttl, isTtlObserved: true, isTtlExact: true }))
377      }
378    } catch {
379      // No tail command or no transcript: inference keeps the estimate.
380    }
381
382    return result
383  })
384
385  // A /clear or resume starts another conversation in the same process.
386  on('session.end', async ($, e, next) => {
387    try {
388      await $.store.delete(storeKey(e.sessionId))
389    } catch {
390      // A leftover entry is only read back by a session with this id.
391    }
392
393    if (e.reason === 'clear' || e.reason === 'resume') {
394      update($, prev => ({ ...initial, ttl: prev.ttl, isTtlObserved: prev.isTtlObserved, isTtlExact: prev.isTtlExact }))
395    }
396
397    return next(e)
398  })
399
400  // A change made in /config wins over one the band kept in the store; the
401  // idle-compaction switch flipped there shows in the band.
402  on('config.set', async ($, e, next) => {
403    const result = await next(e)
404    const isWritten = !('deny' in result && result.deny !== undefined)
405    const field = e.key.startsWith('cache-timer') ? e.key.slice(e.key.lastIndexOf('.') + 1) : undefined
406
407    if (field !== undefined && field in overrides && isWritten) {
408      const { [field]: _dropped, ...rest } = overrides
409      overrides = rest
410      await saveOverrides($)
411    }
412
413    if (e.key === IDLE_ROW && isWritten) {
414      setIdleState($, e.value === false ? 'off' : 'on')
415    }
416
417    return result
418  })
419
420  on('session.start', async ($, e, next) => {
421    try {
422      const saved = await $.store.get(OVERRIDES_KEY)
423
424      if (saved !== null && typeof saved === 'object') {
425        overrides = saved as Record<string, boolean | number>
426        $.ui.invalidate('ui.render')
427      }
428    } catch {
429      // No saved settings: the manifest's values apply.
430    }
431
432    await applyThreshold($, thresholdK())
433    await readIdle($)
434
435    try {
436      const saved = (await $.store.get(storeKey(await $.session.id()))) as CacheClock | undefined
437
438      if (saved !== undefined) {
439        clock = { ...initial, ...saved }
440      }
441    } catch {
442      // Nothing saved: the next request sets the clock.
443    }
444
445    $.clock.every(1000, async () => {
446      const s = clock
447      const { ttl, label } = effectiveTtl(s)
448
449      if (s.lastAt === null) {
450        setView($, { time: '—', detail: s.tokens > 0 ? tokensOf(s.tokens, ttl) : '', left: null })
451
452        return
453      }
454
455      const remaining = TTL_MS[ttl] - ((await $.clock.now()) - s.lastAt)
456
457      if (remaining <= 0) {
458        setView($, { time: 'expired', detail: `${label} · ${tokensOf(s.tokens, ttl)}`, left: 0 })
459
460        return
461      }
462
463      setView($, { time: formatRemaining(remaining), detail: `${label} · ${tokensOf(s.tokens, ttl)}`, left: remaining / TTL_MS[ttl] })
464
465      // A 1h cache only: a 5m cache would notify after nearly every reply.
466      if (isNotify() && ttl === '1h' && remaining <= notifyLeadMin() * 60_000 && s.notifiedAt !== s.lastAt) {
467        update($, prev => ({ ...prev, notifiedAt: s.lastAt }))
468        const message = [s.title, s.question === null ? null : `「${s.question}」`, `— cache expires in ${Math.ceil(remaining / 60_000)} min`]
469          .filter(line => line !== null && line !== '')
470          .join('\n')
471        void $.tool
472          .call({ tool: 'PushNotification', message, status: 'proactive' } as never)
473          .catch(() => {
474            // No push tool or a refused call: the band still shows the countdown.
475          })
476      }
477    })
478
479    return next(e)
480  })
481
482  // The band above the prompt: the countdown, the idle-compaction and
483  // notification states, and a gear that opens a row with their settings. A
484  // change to one of the mod's fields writes it, which reloads the mod.
485  on('ui.render', { component: 'AbovePrompt' }, ($, e, next) => {
486    // The mobile app has no Select; it has not drawn mod UI so far either.
487    if (e.props.hasSurvey || e.surface === 'mobile') {
488      return next(e)
489    }
490
491    const isDesktop = e.surface === 'desktop'
492    const { Box, Button, Select, Text } = $.ui.resolve(e)
493    const Svg = isDesktop ? $.ui.resolve(e).Svg : undefined
494    const notify = isNotify()
495    const thresholdNow = thresholdK()
496    const leadNow = notifyLeadMin()
497    const thresholds = THRESHOLD_PRESETS_K.includes(thresholdNow) ? THRESHOLD_PRESETS_K : [...THRESHOLD_PRESETS_K, thresholdNow]
498    const leads = NOTIFY_LEAD_PRESETS_MIN.includes(leadNow) ? NOTIFY_LEAD_PRESETS_MIN : [...NOTIFY_LEAD_PRESETS_MIN, leadNow]
499    const filled = view.left === null ? 0 : Math.round(BAR_CELLS * view.left)
500
501    const state = (paths: string, isOn: boolean, word: string, alt: string) =>
502      Svg !== undefined ? (
503        <Svg source={icon(paths, isOn ? ON : OFF)} alt={`${alt} ${isOn ? 'on' : 'off'}`} width={14} height={14} />
504      ) : (
505        <Text color={isOn ? 'success' : 'inactive'}>{word}</Text>
506      )
507
508    const idleState =
509      Svg !== undefined ? (
510        <Box flexDirection="row" alignItems="center" gap={1}>
511          <Svg source={icon(COMPRESS, idle === 'on' ? ON : OFF)} alt={`idle compaction ${idle === 'unavailable' ? 'unavailable' : idle}`} width={14} height={14} />
512          {idle === 'unavailable' ? <Text dimColor>n/a</Text> : null}
513        </Box>
514      ) : idle === 'unavailable' ? (
515        <Text dimColor>idle n/a</Text>
516      ) : (
517        <Text color={idle === 'on' ? 'success' : 'inactive'}>idle</Text>
518      )
519
520    return (
521      <Box flexDirection="column">
522        <Box flexDirection="row" justifyContent="space-between" gap={2}>
523          <Box flexDirection="row" alignItems="center" gap={1}>
524            {Svg !== undefined ? <Svg source={icon(CLOCK, OFF)} alt="cache" width={14} height={14} /> : <Text dimColor>cache</Text>}
525            <Text bold>{view.time}</Text>
526            {view.left === null ? null : Svg !== undefined ? (
527              <Svg source={bar(view.left)} alt={`${Math.round(view.left * 100)}% left`} width={80} height={4} />
528            ) : (
529              <Text>
530                <Text color={view.left > 0.2 ? 'success' : 'warning'}>{'━'.repeat(filled)}</Text>
531                <Text dimColor>{'─'.repeat(BAR_CELLS - filled)}</Text>
532              </Text>
533            )}
534            <Text dimColor>{view.detail}</Text>
535          </Box>
536          <Box flexDirection="row" alignItems="center" gap={1}>
537            {idleState}
538            {state(BELL, notify, 'notify', 'notify')}
539            <Button key="settings" label="⚙" plain dimColor={!isExpanded} onPress={() => {
540              isExpanded = !isExpanded
541              $.ui.invalidate('ui.render')
542            }} />
543          </Box>
544        </Box>
545        {isExpanded ? (
546          <Box flexDirection="row" alignItems="center" gap={1}>
547            {idle === 'unavailable' ? (
548              <Text dimColor>idle compaction n/a</Text>
549            ) : (
550              <Button key="idle" label="idle compaction" variant={idle === 'on' ? 'primary' : 'secondary'} onPress={() => setIdle($, idle !== 'on')} />
551            )}
552            <Select
553              key="threshold"
554              options={thresholds.map(k => ({ value: String(k), label: `≥${k}k` }))}
555              value={String(thresholdNow)}
556              onSelect={(value: string) => setOption($, 'threshold_k', Number(value))}
557            />
558            <Text dimColor>│</Text>
559            <Button key="notify" label="notify" variant={notify ? 'primary' : 'secondary'} onPress={() => setOption($, 'notify', !notify)} />
560            <Select
561              key="notify_lead"
562              options={leads.map(m => ({ value: String(m), label: `${m}m before` }))}
563              value={String(leadNow)}
564              onSelect={(value: string) => setOption($, 'notify_lead_minutes', Number(value))}
565            />
566          </Box>
567        ) : null}
568      </Box>
569    )
570  })
571}
572
types/index.d.ts 23 lines
1export type CacheTtl = '5m' | '1h'
2
3export type CacheClock = {
4  /** When the last main-thread model request was sent (ms since epoch); null after a compaction or before the first response. */
5  lastAt: number | null
6  /** Prompt tokens the next request re-sends. */
7  tokens: number
8  /** Model that answered last; a switch forfeits the cache, so inference skips it. */
9  model: string | null
10  /** Cache lifetime, and whether it is confirmed (by the transcript or a hit or miss) or assumed. */
11  ttl: CacheTtl
12  isTtlObserved: boolean
13  /** True once the transcript reported the lifetime of a cache write; inference then stands aside. */
14  isTtlExact: boolean
15  /** The lastAt value an expiry notification was already sent for. */
16  notifiedAt: number | null
17  /** The session's name, as the last prompt reported it. */
18  title: string | null
19  /** What the last reply asked the user, for the notification. */
20  question: string | null
21}
22
23