SLOPSHOPPER

lofi-radio

Claude FM player: a pane drawn like the stream with the current track, /lofi, volume, a mini video window; audio via yt-dlp + ffplay

panebandguardcommandtoolprocess
v0.3.0MITupdated 2026-10-09alkanalperen/lofi-radio
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · lofi-radio
│ ┃ Claude FM ✕ › fix the failing auth test and add an audit log call │ ┃ ♫ Claude FM │ ┃ music for thinking and building ⏺ Read(src/auth.ts) │ ┃ .:. .::. .:. ⎿ Read 6 lines │ ┃ .:::::. .:::::::::. .:. .:::::. ⏺ Update(src/auth.ts) │ ┃ ~ ~ ~ ~ ~ ~ ~ \__/ ~ ~ ~ ~ ~ ~ ~ ~ ⎿ Added 2 lines, removed 1 line │ ┃ ● TUNING IN… · vol ▮▮▮▮▮▮▯▯▯▯ ⏺ Bash(bun test) │ ┃ [ ■ Cancel ] [ − ] [ + ] [ ▣ Mini window ] Y ⎿ 3 pass, 1 fail │ ┃ unofficial, not affiliated with Anthropic │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /lofi │ ⎿ lofi-radio: Claude FM tuning in… │ │ ♪ Claude FM tuning in… [ Cancel ] ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
♪ Claude FM tuning in… [ Cancel ] ⟨Claude Code's own drawing⟩
Pane · Claude FM
♫ Claude FM music for thinking and building .:. .::. .:. .:::::. .:::::::::. .:. .:::::. ~ ~ ~ ~ ~ ~ ~ \__/ ~ ~ ~ ~ ~ ~ ~ ~ ● TUNING IN… · vol ▮▮▮▮▮▮▯▯▯▯ [ ■ Cancel ] [ − ] [ + ] [ ▣ Mini window ] YouTube ↗ https:/ unofficial, not affiliated with Anthropic
README

lofi-radio

Claude FM, Anthropic's 24/7 lo-fi stream, inside Claude Code.

The player: it wakes up, tunes in, names the track and lands a fish

A Claude Code mod (a plugin of function hooks) that adds:

  • a button above the prompt that starts the radio,
  • a player pane drawn like the stream: dotted mountains, a pine line, drifting water and Clawd fishing from his boat,
  • the current track, read off the stream itself,
  • a listening timer and a small catch: one fish for every Claude turn that finishes while the radio plays,
  • volume control and a small always-on-top video window,
  • /lofi to open the player and play, /lofi stop to stop.

By default it plays audio only, so there is no browser tab.

Unofficial, fan-made mod. Not affiliated with or endorsed by Anthropic.

Requirements

  • macOS (it uses Homebrew's paths, pkill, and macOS Vision for the track name)
  • brew install yt-dlp ffmpeg deno (yt-dlp needs a JavaScript runtime such as Deno for full YouTube support)
  • Keep yt-dlp current with brew upgrade yt-dlp. YouTube changes often break older versions.
  • For the track name: the Xcode Command Line Tools (xcode-select --install). Without them the radio still plays and the pane shows the stream's tagline instead.
  • Claude Code with plugin hooks (mods)

Install

In a claude session in the terminal:

/plugin install lofi-radio --marketplace alkanalperen/lofi-radio

Or from the shell:

claude plugin marketplace add alkanalperen/lofi-radio
claude plugin install lofi-radio@lofi-radio

If the button above the prompt does not show up, restart Claude Code.

Use

  1. Click ♪ Play Claude FM above the prompt, or run /lofi.
  2. In the pane: ▶ Play / ■ Stop (p), − / + for volume (j / k), ▣ Mini window (m) for the video, and a link to the stream on YouTube.
  3. Run /lofi stop to stop.

You can also just ask Claude: "put on some lofi", "turn it down", "what's playing?". The mod gives Claude a lofi tool with the same controls.

The player follows Claude Code's language setting, then the system locale. Set the plugin's language option to en or tr to choose.

How it works

yt-dlp resolves https://clau.de/radio (the address /radio opens) to the live HLS stream. The stream has no audio-only format, so it picks 360p, the smallest format with AAC-LC audio, and ffplay plays it with -nodisp. A resolved address goes stale within minutes, so every start resolves a fresh one, and a stream that stops getting segments is resolved again by itself. Changing the volume or the window restarts ffplay; the old player keeps going until the new one is ready.

The track name exists only in the video. While the radio plays, a small macOS Vision helper (compiled once into ~/.cache/lofi-radio) reads the stream's now-playing box: one frame every 90 seconds to notice a change, and a 28-second read to stitch the scrolling name when it does. That costs about 20 MB an hour.

Credits

The pixel Clawd sprite comes from johnnyvizz's savvy-progress (claude-kit, MIT) by way of the agent-deck mod. Claude, Claude FM and the Clawd character belong to Anthropic.

The music on Claude FM is made by independent artists. The pane names the track; earwitness.fyi also reads the ticker and credits the artists.

License

MIT for the code. See LICENSE and NOTICE.

Türkçe

Claude FM'i Claude Code'un içinde çalan bir mod. Prompt'un üstündeki ♪ Claude FM çal butonuna bas veya /lofi yaz. Panelde çalan şarkı, çal/durdur, ses ve mini pencere var. Arayüz Claude Code'un dil ayarını izler; eklentinin language ayarıyla tr seçebilirsin. Kurulum için önce brew install yt-dlp ffmpeg deno, sonra yukarıdaki /plugin install satırı. Resmi değil, Anthropic ile bağı yok.

Source 2 files
hooks/register.tsx 955 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, HookStream, ProcessSpawnChunk, ProcessSpawnResult, Register, Timer } from 'claude-code'
3
4import type { Pond, Radio } from '../types'
5
6// The address /radio opens; it redirects to whatever the current YouTube live id is.
7export const STREAM_URL = 'https://clau.de/radio'
8// The stream has no audio-only format; 360p is the smallest one with AAC-LC audio.
9const FORMAT = 'worst[height>=360]/worst'
10// 720p for reading the now-playing box: lower resolutions misread it.
11const OCR_FORMAT = '95/best'
12const TITLE = 'Claude FM'
13// pkill -f matches the joined argv, so ffplay's window title marks our player.
14// No leading dash, or pkill would read the pattern as a flag.
15const MARK = `window_title ${TITLE}`
16// The desktop app's PATH may miss Homebrew, so each tool is tried there too.
17const BIN_DIRS = ['', '/opt/homebrew/bin/', '/usr/local/bin/']
18const PANE = 'claude-fm'
19const TOOL = 'mcp__lofi-radio__lofi'
20const CHECK_MS = 90_000
21const BACKOFF_MS = 300_000
22// A resolved HLS address goes stale within minutes and ffplay then retries its 403s
23// forever, so a stalled stream is resolved afresh this many times before giving up.
24const MAX_RESTARTS = 2
25const HEALTHY_MS = 120_000
26// ffplay logs this when it gives up on a segment. A lone 403 is routine (keepalive
27// retries recover); a run of skipped segments means no sound and a stale address.
28const SKIP = /failed too many times, skipping/g
29const STALL_SKIPS = 3
30const STALL_WINDOW_MS = 30_000
31// ffplay traps SIGINT and SIGTERM and exits 123, so another session's pkill is a stop, not a failure.
32const FFPLAY_KILLED = 123
33const NP_SOURCE = 'bin/nowplaying.swift'
34const NP_VERSION = 1
35// The Command Line Tools' own compiler; /usr/bin/swiftc is a shim that offers to install them.
36const CLT_SWIFTC = '/Library/Developer/CommandLineTools/usr/bin/swiftc'
37
38// --- language: the `language` option, else Claude Code's `language` setting, else the
39// process locale; English unless one of them says Turkish.
40
41type Lang = 'en' | 'tr'
42
43const EN = {
44  live: 'LIVE',
45  tuning: 'TUNING IN…',
46  off: 'OFF',
47  error: 'NO SIGNAL',
48  boxTuning: 'tuning in…',
49  boxOff: 'Claude FM · off',
50  boxError: 'no signal',
51  tagline: 'music for thinking and building',
52  minutes: (m: number) => (m >= 60 ? `${Math.floor(m / 60)} h ${m % 60} min` : `${m} min`),
53  volume: (v: number) => `vol ${v}%`,
54  volumeShort: 'vol',
55  fishToday: (n: number) => `${n} fish today`,
56  play: '▶ Play',
57  stop: '■ Stop',
58  cancel: '■ Cancel',
59  retry: '↻ Retry',
60  mini: '▣ Mini window',
61  closeMini: '▣ Close window',
62  unofficial: 'unofficial, not affiliated with Anthropic',
63  bandPlay: '♪ Play Claude FM',
64  bandTuning: '♪ Claude FM tuning in…',
65  bandCancel: 'Cancel',
66  bandRetry: 'Retry',
67  player: 'Player',
68  stopped: 'Claude FM stopped.',
69  playing: 'Claude FM is playing.',
70  starting: 'Claude FM tuning in…',
71  missing: (tool: string) => `${tool} missing: brew install ${tool}`,
72  notFound: 'stream not found',
73  ffplayStopped: 'ffplay stopped',
74  stalled: 'stream address expired',
75  command: 'Open the Claude FM player and play (/lofi stop to stop)',
76}
77type Strings = typeof EN
78
79const TR: Strings = {
80  live: 'CANLI',
81  tuning: 'AÇILIYOR…',
82  off: 'KAPALI',
83  error: 'BAĞLANAMADI',
84  boxTuning: 'ayar çekiliyor…',
85  boxOff: 'Claude FM · kapalı',
86  boxError: 'bağlanamadı',
87  tagline: 'music for thinking and building',
88  minutes: m => (m >= 60 ? `${Math.floor(m / 60)} sa ${m % 60} dk` : `${m} dk`),
89  volume: v => `ses %${v}`,
90  volumeShort: 'ses',
91  fishToday: n => `bugün ${n} balık`,
92  play: '▶ Çal',
93  stop: '■ Durdur',
94  cancel: '■ İptal',
95  retry: '↻ Tekrar dene',
96  mini: '▣ Mini pencere',
97  closeMini: '▣ Pencereyi kapat',
98  unofficial: 'resmi değil, Anthropic ile bağı yok',
99  bandPlay: '♪ Claude FM çal',
100  bandTuning: '♪ Claude FM açılıyor…',
101  bandCancel: 'İptal',
102  bandRetry: 'Tekrar dene',
103  player: 'Çalar',
104  stopped: 'Claude FM durdu.',
105  playing: 'Claude FM çalıyor.',
106  starting: 'Claude FM açılıyor…',
107  missing: tool => `${tool} yok: brew install ${tool}`,
108  notFound: 'yayın bulunamadı',
109  ffplayStopped: 'ffplay durdu',
110  stalled: 'yayın adresi eskidi',
111  command: 'Claude FM çaları aç ve çal (/lofi stop durdurur)',
112}
113
114export const STRINGS: Record<Lang, Strings> = { en: EN, tr: TR }
115
116// Module scope is fine: session.start sets it again on every (re)load.
117let lang: Lang = 'en'
118const t = () => STRINGS[lang]
119
120const isTurkish = (v: unknown) => typeof v === 'string' && /^(tr([-_.]|$)|turk|türk)/i.test(v.trim())
121
122async function detectLang($: EngineInterface, option: unknown): Promise<Lang> {
123  if (option === 'en' || option === 'tr') return option
124  try {
125    const settings = (await $.settings.read()) as Record<string, unknown>
126    if (typeof settings.language === 'string' && settings.language.trim()) return isTurkish(settings.language) ? 'tr' : 'en'
127  } catch {
128    // No settings: fall through to the locale.
129  }
130  const locale = (await $.env.get('LC_ALL')) || (await $.env.get('LC_MESSAGES')) || (await $.env.get('LANG'))
131  return isTurkish(locale) ? 'tr' : 'en'
132}
133
134// --- state
135
136const OFF: Radio = { status: 'off', note: null, volume: 60, isWindow: false, track: null, onSince: null, minute: 0 }
137const radio = atom({ plugin: 'lofi-radio', key: 'radio' } as const, OFF as Radio)
138const EMPTY_POND: Pond = { day: '', gold: [], lastAt: 0 }
139const pond = atom({ plugin: 'lofi-radio', key: 'pond' } as const, EMPTY_POND as Pond)
140
141// Merging over OFF fills fields a value saved by an older version lacks.
142const patch = ($: EngineInterface, change: Partial<Radio>) =>
143  update($, radio, (prev): Radio => ({ ...OFF, ...prev, ...change }))
144const current = async ($: EngineInterface): Promise<Radio> => ({ ...OFF, ...(await read($, radio)) })
145const isLive = (s: Radio) => s.status === 'on' || s.status === 'tuning'
146const clampVolume = (v: number) => Math.max(10, Math.min(100, v))
147
148const pad = (n: number) => String(n).padStart(2, '0')
149export const dayOf = (ms: number) => {
150  const d = new Date(ms)
151  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
152}
153const todaysFish = async ($: EngineInterface): Promise<Pond> => {
154  const p = { ...EMPTY_POND, ...(await read($, pond)) }
155  const day = dayOf(await $.clock.now())
156  return p.day === day ? p : { ...EMPTY_POND, day }
157}
158
159// Volume and window outlive the session; so does today's catch.
160async function savePrefs($: EngineInterface) {
161  const { volume, isWindow } = await current($)
162  await $.store.set('prefs', { volume, isWindow }).catch(() => undefined)
163}
164
165async function restoreSaved($: EngineInterface) {
166  const prefs = (await $.store.get('prefs').catch(() => undefined)) as Partial<Radio> | undefined
167  if (prefs && typeof prefs.volume === 'number') {
168    await patch($, { volume: clampVolume(prefs.volume), isWindow: prefs.isWindow === true })
169  }
170  const saved = (await $.store.get('pond').catch(() => undefined)) as Pond | undefined
171  if (saved && Array.isArray(saved.gold) && saved.day === dayOf(await $.clock.now())) {
172    await update($, pond, (): Pond => ({ ...EMPTY_POND, ...saved, lastAt: 0 }))
173  }
174}
175
176// --- the player
177
178const found = new Map<string, string>()
179let player: HookStream<ProcessSpawnChunk, ProcessSpawnResult> | null = null
180// Bumped on every play, restart and stop: a player loop whose number is old writes nothing.
181let generation = 0
182// One listen runs from play to stop and survives quiet restarts. Its timers and
183// now-playing reads carry its number and stop as soon as it changes.
184let listen = 0
185let minuteTimer: Timer | null = null
186let firstRead: Timer | null = null
187let readTimer: Timer | null = null
188
189async function bin($: EngineInterface, name: string, versionFlag: string) {
190  const known = found.get(name)
191  if (known) return known
192  for (const dir of BIN_DIRS) {
193    const path = dir + name
194    const ok = await $.process.run([path, versionFlag], { timeoutMs: 10_000 }).then(
195      r => r.exitCode === 0,
196      () => false,
197    )
198    if (ok) {
199      found.set(name, path)
200      return path
201    }
202  }
203  return null
204}
205
206// Last non-empty stderr line, short enough for the band.
207export function lastLine(text: string): string {
208  const lines = text.split('\n').map(l => l.trim()).filter(Boolean)
209  return (lines.at(-1) ?? '').slice(0, 80)
210}
211
212// Always a fresh address: one resolved a few minutes ago already answers 403.
213async function resolveUrl($: EngineInterface, ytdlp: string, format: string): Promise<{ url: string } | { error: string }> {
214  const r = await $.process
215    .run([ytdlp, '--no-update', '--no-warnings', '--no-playlist', '-f', format, '-g', STREAM_URL], { timeoutMs: 30_000 })
216    .catch(() => null)
217  const url = r?.exitCode === 0 ? (r.stdout.trim().split('\n')[0] ?? '') : ''
218  return url ? { url } : { error: lastLine(r?.stderr ?? '') || t().notFound }
219}
220
221async function killPlayers($: EngineInterface) {
222  await $.process.run(['pkill', '-f', MARK]).catch(() => undefined)
223}
224
225function stopTimers() {
226  minuteTimer?.cancel()
227  firstRead?.cancel()
228  readTimer?.cancel()
229  minuteTimer = firstRead = readTimer = null
230  failures = 0
231  isSlow = false
232}
233
234async function play($: EngineInterface) {
235  const id = ++generation
236  const l = ++listen
237  stopTimers()
238  rawTrack = null
239  await patch($, { status: 'tuning', note: null, track: null })
240
241  const ytdlp = await bin($, 'yt-dlp', '--version')
242  const ffplay = await bin($, 'ffplay', '-version')
243  if (id !== generation) return
244  if (!ytdlp || !ffplay) {
245    await patch($, { status: 'error', note: t().missing(!ytdlp ? 'yt-dlp' : 'ffmpeg') })
246    return
247  }
248
249  const stream = await resolveUrl($, ytdlp, FORMAT)
250  if (id !== generation) return
251  if ('error' in stream) {
252    await patch($, { status: 'error', note: stream.error })
253    return
254  }
255  await runPlayer($, id, l, ffplay, stream.url, false, 0)
256}
257
258// Volume and window are ffplay flags. A playing stream restarts with them quietly: the old
259// player keeps going while the new address resolves, then hands over within a second.
260async function restart($: EngineInterface) {
261  const s = await current($)
262  if (s.status === 'tuning') return void play($)
263  if (s.status !== 'on') return
264  const ytdlp = found.get('yt-dlp')
265  const ffplay = found.get('ffplay')
266  if (!ytdlp || !ffplay) return void play($)
267  const id = ++generation
268  const stream = await resolveUrl($, ytdlp, FORMAT)
269  if (id !== generation) return
270  const old = player
271  player = null
272  void old?.return({ code: null, signal: 'SIGTERM' })
273  if ('error' in stream) {
274    await killPlayers($)
275    return void play($)
276  }
277  await runPlayer($, id, listen, ffplay, stream.url, true, 0)
278}
279
280async function runPlayer($: EngineInterface, id: number, l: number, ffplay: string, url: string, isRestart: boolean, restarts: number) {
281  const s = await current($)
282  const view = s.isWindow ? ['-x', '480', '-y', '270', '-alwaysontop'] : ['-nodisp', '-vn']
283  // One stream at a time, also across sessions.
284  await killPlayers($)
285  if (id !== generation) return
286  const child = $.process.spawn({
287    argv: [ffplay, ...view, '-loglevel', 'warning', '-volume', String(s.volume), '-window_title', TITLE, url],
288  })
289  player = child
290  const spawnedAt = await $.clock.now()
291
292  if (!isRestart) {
293    const startedAt = spawnedAt
294    if (id !== generation) return
295    // Checked inside the updater too: a retried write must not put "on" back over a stop's "off".
296    await update($, radio, (prev): Radio =>
297      id === generation ? { ...OFF, ...prev, status: 'on', note: null, onSince: startedAt, minute: 0 } : { ...OFF, ...prev })
298    if (id !== generation) return
299    startTimers($, l)
300  }
301
302  let stderr = ''
303  let end: ProcessSpawnResult | null = null
304  let isStalled = false
305  let skips: number[] = []
306  try {
307    let step = await child.next()
308    while (!step.done) {
309      if (step.value.stream === 'stderr') {
310        stderr = (stderr + step.value.text).slice(-4_000)
311        const skipped = step.value.text.match(SKIP)?.length ?? 0
312        if (skipped) {
313          const now = await $.clock.now()
314          skips = [...skips, ...Array<number>(skipped).fill(now)].filter(at => now - at < STALL_WINDOW_MS)
315          if (skips.length >= STALL_SKIPS) {
316            isStalled = true
317            void child.return({ code: null, signal: 'SIGTERM' })
318            break
319          }
320        }
321      }
322      step = await child.next()
323    }
324    if (step.done) end = step.value
325  } catch (error) {
326    stderr += String(error)
327  }
328  if (id !== generation) return
329  player = null
330
331  if (isStalled) {
332    // ffplay would retry the dead address forever: make sure it is gone, then resolve afresh.
333    await killPlayers($)
334    const ytdlp = found.get('yt-dlp')
335    // A stream that played for a while before stalling gets a fresh budget.
336    const budget = (await $.clock.now()) - spawnedAt > HEALTHY_MS ? 0 : restarts
337    if (budget < MAX_RESTARTS && ytdlp) {
338      const stream = await resolveUrl($, ytdlp, FORMAT)
339      if (id !== generation) return
340      if (!('error' in stream)) return runPlayer($, id, l, ffplay, stream.url, true, budget + 1)
341    }
342  }
343
344  const wasKilled = end !== null && (end.signal !== null || end.code === FFPLAY_KILLED)
345  const failed = isStalled || (!wasKilled && (end === null || end.code !== 0))
346  // The listen is over: its timers and any read still running stop here.
347  listen++
348  stopTimers()
349  await patch($, failed
350    ? { status: 'error', note: isStalled ? t().stalled : lastLine(stderr) || t().ffplayStopped, onSince: null, minute: 0 }
351    : { status: 'off', note: null, track: null, onSince: null, minute: 0 })
352}
353
354async function stop($: EngineInterface) {
355  generation++
356  listen++
357  stopTimers()
358  rawTrack = null
359  const child = player
360  player = null
361  void child?.return({ code: null, signal: 'SIGTERM' })
362  await killPlayers($)
363  await patch($, { status: 'off', note: null, track: null, onSince: null, minute: 0 })
364}
365
366async function toggle($: EngineInterface) {
367  if (isLive(await current($))) return stop($)
368  void play($)
369}
370
371// Read and write in one update, so two quick presses both count.
372async function stepVolume($: EngineInterface, delta: number) {
373  let changed = false
374  await update($, radio, (prev): Radio => {
375    const s = { ...OFF, ...prev }
376    const volume = clampVolume(s.volume + delta)
377    changed = volume !== s.volume
378    return { ...s, volume }
379  })
380  if (!changed) return
381  await savePrefs($)
382  await restart($)
383}
384
385async function toggleWindow($: EngineInterface) {
386  const next = await update($, radio, (prev): Radio => {
387    const s = { ...OFF, ...prev }
388    return { ...s, isWindow: !s.isWindow }
389  })
390  await savePrefs($)
391  if (isLive({ ...OFF, ...next })) await restart($)
392  else void play($)
393}
394
395const openPlayer = ($: EngineInterface) => void $.ui.open({ id: PANE, title: TITLE }).catch(() => undefined)
396
397// --- now playing: the track name exists only burned into the video's top-right box.
398// A compiled macOS Vision helper reads a 28 s burst of that crop and stitches the marquee.
399
400const CROP = 'crop=iw*0.2219:ih*0.0611:iw*0.7438:ih*0.0347,scale=852:132:flags=lanczos,format=gray'
401// perl alarm + exec is a hard wall clock around ffmpeg, which otherwise retries a 403 forever.
402const FULL_SH = `/usr/bin/perl -e 'alarm 30; exec @ARGV' "$3" -nostdin -loglevel error -live_start_index -14 -i "$1" -an -t 28 -vf 'fps=2,${CROP}' -f rawvideo -pix_fmt gray - 2>/dev/null | "$2" --raw 852 132`
403const CHECK_SH = `/usr/bin/perl -e 'alarm 15; exec @ARGV' "$3" -nostdin -loglevel error -i "$1" -an -frames:v 1 -vf '${CROP}' -f rawvideo -pix_fmt gray - 2>/dev/null | "$2" --raw 852 132 --debug`
404// Compiles to a temporary name first, so a timed-out build never passes for a finished one.
405const COMPILE_SH = 'mkdir -p "$4" && "$1" -O "$2" -o "$3.$$.tmp" && mv "$3.$$.tmp" "$3"'
406
407let helper: Promise<string | null> | null = null
408// The marquee's own text ("Artist — 01 - Title"), which one-frame checks are matched against.
409let rawTrack: string | null = null
410// The listen whose read is running, so a stale read never blocks or is blamed on a new one.
411let readingListen: number | null = null
412let failures = 0
413let isSlow = false
414
415// A real compiler only: never the /usr/bin shim, which would open an install dialog.
416async function findSwiftc($: EngineInterface) {
417  if (await $.fs.exists(CLT_SWIFTC).catch(() => false)) return CLT_SWIFTC
418  const r = await $.process.run(['/usr/bin/xcode-select', '-p'], { timeoutMs: 5_000 }).catch(() => null)
419  const dev = r?.exitCode === 0 ? r.stdout.trim() : ''
420  if (!dev) return null
421  for (const path of [`${dev}/usr/bin/swiftc`, `${dev}/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc`]) {
422    if (await $.fs.exists(path).catch(() => false)) return path
423  }
424  return null
425}
426
427// Compiled once per machine into ~/.cache; without a compiler the feature stays off.
428function nowPlayingHelper($: EngineInterface) {
429  helper ??= (async () => {
430    const home = await $.env.get('HOME')
431    if (!home) return null
432    const dir = `${home}/.cache/lofi-radio`
433    const out = `${dir}/nowplaying-v${NP_VERSION}`
434    if (await $.fs.exists(out).catch(() => false)) return out
435    const swiftc = await findSwiftc($)
436    if (!swiftc) return null
437    const r = await $.process
438      .run(['/bin/sh', '-c', COMPILE_SH, 'sh', swiftc, `${$.plugin.root}/${NP_SOURCE}`, out, dir], { timeoutMs: 180_000 })
439      .catch(() => null)
440    return r?.exitCode === 0 ? out : null
441  })()
442  return helper
443}
444
445const norm = (s: string) => s.toLowerCase().replace(/[—–]/g, '-').replace(/\s+/g, ' ').trim()
446
447// "Kyle Preston — 01 - We Made It" shows as "Kyle Preston — We Made It".
448export function cleanTrack(artist: string, title: string): string {
449  const t = title.replace(/^\d{1,2}\s*-\s*/, '').trim()
450  return artist ? `${artist.trim()} — ${t}` : t
451}
452
453// True when a one-frame fragment still fits inside the known track's looping marquee.
454export function stillPlaying(track: string, fragment: string): boolean {
455  const f = norm(fragment)
456  const inner = f.length > 8 ? f.slice(1, -1) : f
457  return inner.length >= 4 && norm(`${track} ${track}`).includes(inner)
458}
459
460type HelperOut = { track?: string; artist?: string; title?: string; complete?: boolean; fragments?: string[] }
461function parseHelper(stdout: string | undefined): HelperOut | null {
462  try {
463    return stdout ? (JSON.parse(stdout.trim().split('\n').at(-1) ?? '') as HelperOut) : null
464  } catch {
465    return null
466  }
467}
468
469async function readTrack($: EngineInterface, l: number, full: boolean) {
470  if (l !== listen || readingListen === l) return
471  readingListen = l
472  try {
473    const [helperPath, ytdlp, ffmpeg] = await Promise.all([
474      nowPlayingHelper($),
475      bin($, 'yt-dlp', '--version'),
476      bin($, 'ffmpeg', '-version'),
477    ])
478    // Missing tools turn the feature off; that is not a miss.
479    if (l !== listen || !helperPath || !ytdlp || !ffmpeg) return
480    const ocr = await resolveUrl($, ytdlp, OCR_FORMAT)
481    if (l !== listen) return
482    if ('error' in ocr) return fail($, l)
483
484    const known = (await current($)).track
485    if (!full && known && rawTrack) {
486      const r = await $.process.run(['/bin/sh', '-c', CHECK_SH, 'sh', ocr.url, helperPath, ffmpeg], { timeoutMs: 25_000 }).catch(() => null)
487      if (l !== listen) return
488      const fragment = parseHelper(r?.stdout)?.fragments?.[0] ?? ''
489      if (!fragment) return fail($, l)
490      if (stillPlaying(rawTrack, fragment)) return recovered($, l)
491    }
492
493    const r = await $.process.run(['/bin/sh', '-c', FULL_SH, 'sh', ocr.url, helperPath, ffmpeg], { timeoutMs: 45_000 }).catch(() => null)
494    if (l !== listen) return
495    const out = parseHelper(r?.stdout)
496    if (!out?.complete) return fail($, l)
497    recovered($, l)
498    rawTrack = out.track ?? null
499    const track = cleanTrack(out.artist ?? '', out.title ?? '')
500    await update($, radio, (prev): Radio => (l === listen ? { ...OFF, ...prev, track } : { ...OFF, ...prev }))
501  } finally {
502    if (readingListen === l) readingListen = null
503  }
504}
505
506function setCadence($: EngineInterface, l: number, ms: number) {
507  readTimer?.cancel()
508  readTimer = $.clock.every(ms, () => void readTrack($, l, false))
509}
510
511// Three misses in a row slow the checks to every five minutes; the last known track stays shown.
512function fail($: EngineInterface, l: number) {
513  if (l !== listen || !readTimer) return
514  failures++
515  if (failures >= 3 && !isSlow) {
516    isSlow = true
517    setCadence($, l, BACKOFF_MS)
518  }
519}
520
521function recovered($: EngineInterface, l: number) {
522  failures = 0
523  if (isSlow && l === listen && readTimer) {
524    isSlow = false
525    setCadence($, l, CHECK_MS)
526  }
527}
528
529function startTimers($: EngineInterface, l: number) {
530  stopTimers()
531  minuteTimer = $.clock.every(60_000, () => {
532    void (async () => {
533      if (l !== listen) return
534      const s = await current($)
535      if (s.status === 'on' && s.onSince !== null) {
536        const minute = Math.floor(((await $.clock.now()) - s.onSince) / 60_000)
537        if (l === listen) await patch($, { minute })
538      }
539    })()
540  })
541  firstRead = $.clock.after(5_000, () => void readTrack($, l, true))
542  setCadence($, l, CHECK_MS)
543}
544
545// --- the player scene: a small window onto the stream. Dot-matrix sky, ranges and
546// treeline, drifting water and Clawd fishing from a boat, drawn as one SVG. At most
547// three slow loops move (water drift, boat bob, status dot) and only while playing.
548
549const CLAY = '#D97757'
550const INK = '#1E1E1E'
551const MONO = "ui-monospace,'SF Mono',Menlo,monospace"
552
553type Px = [number, number, number, number, string]
554const px = (list: Px[]) => list.map(([x, y, w, h, c]) => `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="${c}"/>`).join('')
555
556// Pixel Clawd after johnnyvizz's savvy-progress (MIT, see LICENSE) by way of agent-deck,
557// posed for the stream: rod in the left claw, the hull hiding his legs. The character is Anthropic's.
558const BODY: Px[] = [[7, 10, 16, 12, CLAY], [3, 14, 4, 4, CLAY], [23, 14, 4, 4, CLAY]]
559const EYES: Record<Radio['status'], Px[]> = {
560  on: [[9, 12, 2, 2, INK], [19, 12, 2, 2, INK]],
561  tuning: [[9, 12, 2, 2, INK], [19, 12, 2, 2, INK]],
562  off: [[9, 13, 2, 1, INK], [19, 13, 2, 1, INK]],
563  error: [
564    [8, 11, 1, 1, INK], [10, 11, 1, 1, INK], [9, 12, 1, 1, INK], [8, 13, 1, 1, INK], [10, 13, 1, 1, INK],
565    [18, 11, 1, 1, INK], [20, 11, 1, 1, INK], [19, 12, 1, 1, INK], [18, 13, 1, 1, INK], [20, 13, 1, 1, INK],
566  ],
567}
568const SLEEP_Z: Px[] = [[24, 4, 3, 1, '#8A8A8A'], [25, 5, 1, 1, '#8A8A8A'], [24, 6, 3, 1, '#8A8A8A']]
569const ROD: Px[] = [[4, 4, 1, 10, '#9390B9'], [3, 3, 2, 1, '#E8E8E8']]
570const HULL: Px[] = [
571  [-3, 18, 3, 1, '#B07A45'], [30, 18, 3, 1, '#B07A45'],
572  [-2, 19, 34, 1, '#B07A45'], [-1, 20, 32, 1, '#8B6123'], [0, 21, 30, 1, '#8B6123'], [1, 22, 28, 1, '#6D4119'], [3, 23, 24, 1, '#6D4119'],
573]
574// 5×3, facing left; gold for a turn of ten minutes or more.
575const fishPx = (x: number, y: number, gold: boolean): Px[] => {
576  const body = gold ? '#F0A27F' : '#6699D4'
577  const tail = gold ? '#D9825F' : '#4D7FBF'
578  return [[x + 1, y, 2, 1, body], [x, y + 1, 4, 1, body], [x + 1, y + 2, 2, 1, body], [x + 4, y, 1, 3, tail], [x + 1, y + 1, 1, 1, INK]]
579}
580const FISH_SPOTS = [[28, 16], [33, 16], [30.5, 13], [35.5, 13]] as const
581// A 9×9 pixel ♫.
582const NOTE: Px[] = [[2, 0, 7, 2, CLAY], [2, 2, 1, 5, CLAY], [8, 2, 1, 4, CLAY], [0, 6, 3, 3, CLAY], [6, 5, 3, 3, CLAY]]
583
584const ridge = (x: number, W: number, base: number, amp: number, seed: number) => {
585  const t = (x / W) * Math.PI * 2
586  return base - amp * (0.5 * Math.sin(t * 1.1 + seed) + 0.3 * Math.sin(t * 2.7 + seed * 1.9) + 0.2 * Math.sin(t * 6.3 + seed * 3.1))
587}
588// Deterministic 0..1 noise, so the same size always draws the same scene.
589const noise = (i: number, seed: number) => {
590  const s = Math.sin(i * 127.1 + seed * 311.7) * 43758.5453
591  return s - Math.floor(s)
592}
593const f1 = (n: number) => Math.round(n * 10) / 10
594
595export const fit = (s: string, max: number) => (s.length > max ? s.slice(0, Math.max(1, max - 1)) + '…' : s)
596const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c] ?? c)
597
598export const elapsed = (minute: number, ts: Strings = t()) => ts.minutes(minute)
599const statusLabel = (status: Radio['status'], ts: Strings) => ({ on: ts.live, tuning: ts.tuning, off: ts.off, error: ts.error })[status]
600const ROOT_CLASS: Record<Radio['status'], string> = { on: 'on', tuning: 'tune', off: 'off', error: 'err' }
601
602export function altText(s: Radio, fishCount: number, ts: Strings = t()): string {
603  const parts = [`Claude FM: ${statusLabel(s.status, ts)}`]
604  if (s.status === 'on' && s.track) parts.push(s.track)
605  if (s.status === 'on') parts.push(elapsed(s.minute, ts))
606  parts.push(ts.volume(s.volume))
607  if (fishCount > 0) parts.push(ts.fishToday(fishCount))
608  if (s.status === 'error' && s.note) parts.push(s.note)
609  return parts.join(' · ')
610}
611
612export function scene(W: number, H: number, s: Radio, gold: boolean[], now: number, popFish = false, ts: Strings = t()): string {
613  const k = W / 480
614  const p = Math.max(3, Math.round(3.3 * k))
615  const S = Math.max(2, Math.round(H / 95))
616  const wy = Math.round(H * 0.74)
617  const phase = (period: number) => `animation-delay:-${((now % period) / 1000).toFixed(2)}s`
618
619  const css = `<style>
620.on .w{animation:drift 24s linear infinite}.on .wr{animation:drift 24s linear infinite reverse}
621@keyframes drift{to{stroke-dashoffset:-24}}
622.on .bob{animation:bob 6s infinite}@keyframes bob{0%,49.9%{transform:translateY(0)}50%,100%{transform:translateY(1px)}}
623.on .dot{animation:breathe 4s ease-in-out infinite}.tune .dot{animation:breathe 1.2s ease-in-out infinite}
624@keyframes breathe{50%{opacity:.5}}
625.tune .seg{animation:slide 1.6s ease-in-out infinite alternate}@keyframes slide{to{transform:translateX(${f1((W - 24) * 0.7)}px)}}
626.pop{transform-box:fill-box;transform-origin:center;animation:pop .6s ease-out both}@keyframes pop{from{transform:scale(.6)}}
627@media (prefers-color-scheme: light){.card{stroke:rgba(0,0,0,.10)}}
628@media (prefers-reduced-motion: reduce){*{animation:none!important}}
629</style>`
630
631  const defs = `<defs>
632<pattern id="p0" width="${2 * p}" height="${2 * p}" patternUnits="userSpaceOnUse"><rect x="${p}" y="${p}" width="1" height="1" fill="#5C5C5C"/></pattern>
633<pattern id="p1" width="${p}" height="${p}" patternUnits="userSpaceOnUse"><rect x="1" y="1" width="1" height="1" fill="#8B8B8B"/></pattern>
634<pattern id="p2" width="${2 * p}" height="${2 * p}" patternUnits="userSpaceOnUse"><rect y="1" width="${2 * p}" height="${f1(0.4 * p)}" fill="#B8B8B8"/><rect x="1" y="${p + 1}" width="1" height="1" fill="#8B8B8B"/><rect x="${p + 1}" y="${p + 1}" width="1" height="1" fill="#8B8B8B"/></pattern>
635<pattern id="p3" width="${2 * p}" height="${2 * p}" patternUnits="userSpaceOnUse"><rect y="1" width="${f1(1.6 * p)}" height="${f1(0.45 * p)}" fill="#D0D0D0"/></pattern>
636<linearGradient id="fade" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#fff"/><stop offset=".6" stop-color="#000"/></linearGradient>
637<mask id="mfade" maskContentUnits="objectBoundingBox"><rect width="1" height="1" fill="url(#fade)"/></mask>
638<linearGradient id="scrim" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#000" stop-opacity="0"/><stop offset="1" stop-color="#000" stop-opacity=".55"/></linearGradient>
639<clipPath id="card"><rect width="${W}" height="${H}" rx="10"/></clipPath>
640</defs>`
641
642  // Each shape is laid opaque first, so nearer layers hide farther ones.
643  const layer = (d: string, fill: string, bright?: string) =>
644    `<path d="${d}" fill="${INK}"/><path d="${d}" fill="url(#${fill})"/>${bright ? `<path d="${d}" fill="url(#${bright})" mask="url(#mfade)"/>` : ''}`
645
646  const stars: string[] = []
647  for (let i = 0; i < 18; i++) {
648    const x = Math.round(noise(i, 1) * W)
649    const y = Math.round(noise(i, 2) * H * 0.28)
650    stars.push(`<rect x="${x}" y="${y}" width="1" height="1" fill="#8B8B8B"/>`)
651  }
652
653  // The stream's big bright cloud bank hangs from the top left.
654  const cw = W * 0.55
655  const ch = H * 0.3
656  let cloud = `M0 0H${f1(cw)}`
657  for (let x = cw; x >= 0; x -= 6) {
658    const env = 1 - (x / cw) ** 2
659    cloud += `L${f1(x)} ${f1(ch * env * (0.8 + 0.2 * Math.sin(x * 0.025 + 1.3)))}`
660  }
661  cloud += 'Z'
662
663  let far = `M0 ${wy}`
664  for (let x = 0; x <= W; x += 4) far += `L${x} ${f1(ridge(x, W, H * 0.45, H * 0.2, 1.3))}`
665  far += `L${W} ${wy}Z`
666
667  // Pines: seeded spikes along 0.66H.
668  const base = H * 0.66
669  let trees = `M0 ${wy}L0 ${f1(base)}`
670  for (let x = 0, i = 0; x < W; i++) {
671    const step = (5 + noise(i, 3) * 7) * k
672    const h = (6 + noise(i, 4) * 16) * k
673    trees += `L${f1(x + step / 2)} ${f1(base - h)}L${f1(x + step)} ${f1(base)}`
674    x += step
675  }
676  trees += `L${W} ${wy}Z`
677
678  const water: string[] = []
679  const rows = 12
680  const gap = (H - 30 - (wy + 4)) / (rows - 1)
681  for (let i = 0; i < rows; i++) {
682    const y = f1(wy + 4 + i * gap)
683    const opacity = (0.14 + (0.24 * i) / (rows - 1)).toFixed(2)
684    water.push(
685      `<path class="${i % 2 ? 'wr' : 'w'}" style="${phase(24_000)}" d="M0 ${y}H${W}" stroke="#D6D6D6" stroke-width="1.2" stroke-dasharray="${1 + (i % 3)} ${4 + ((i * 7) % 9)}" stroke-dashoffset="${(i * 13) % 17}" opacity="${opacity}" fill="none"/>`,
686    )
687  }
688
689  // Clawd's grid scaled by S: hull centred on x 0.5W, its bottom row on 0.85H.
690  const bx = Math.round(W * 0.5 - 15 * S)
691  const by = Math.round(H * 0.85 - 24 * S)
692  const shown = gold.slice(-4)
693  const fish = shown.flatMap((g, i) => fishPx(FISH_SPOTS[i]![0], FISH_SPOTS[i]![1], g))
694  const lastFish = shown.length ? fishPx(FISH_SPOTS[shown.length - 1]![0], FISH_SPOTS[shown.length - 1]![1], shown.at(-1)!) : []
695  const fishSvg = popFish && shown.length
696    ? px(fish.slice(0, -lastFish.length)) + `<g class="pop">${px(lastFish)}</g>`
697    : px(fish)
698  const more = gold.length > 4
699    ? `<text x="${bx + 41.5 * S}" y="${by + 15.5 * S}" font-family="${MONO}" font-size="10" fill="#8B8B8B">+${gold.length - 4}</text>`
700    : ''
701  const line = `<path d="M3.5 3.5L-1.5 3.5V${f1((wy - by) / S + 1)}" stroke="#E8E8E8" stroke-width=".3" opacity=".6" fill="none"/>`
702  const boat = `<g class="bob" style="${phase(6_000)}"><g transform="translate(${bx},${by}) scale(${S})" shape-rendering="crispEdges">
703${line}${px(ROD)}${px(BODY)}${px(EYES[s.status])}${s.status === 'off' ? px(SLEEP_Z) : ''}${px(HULL)}${fishSvg}
704</g>${more}</g>`
705
706  // Now-playing box, top right.
707  const label =
708    s.status === 'on' && s.track ? { text: s.track, color: '#D6D6D6' }
709    : s.status === 'on' ? { text: `Claude FM — ${ts.tagline}`, color: '#8F8F8F' }
710    : s.status === 'tuning' ? { text: ts.boxTuning, color: '#E0B44C' }
711    : s.status === 'error' ? { text: s.note ?? ts.boxError, color: '#FF8A80' }
712    : { text: ts.boxOff, color: '#7A7A7A' }
713  const maxChars = Math.floor((W * 0.62 - 38) / 7.2)
714  const text = fit(label.text, maxChars)
715  const bw = Math.round(Math.min(W * 0.62, text.length * 7.2 + 38))
716  const boxX = W - 12 - bw
717  const boxStroke = s.status === 'error' ? 'stroke="#FF4E45" stroke-opacity=".6"' : 'stroke="#FFFFFF" stroke-opacity=".08"'
718  const box = `<rect x="${boxX}" y="12" width="${bw}" height="26" rx="3" fill="#131313" fill-opacity=".92" ${boxStroke}/>
719<g transform="translate(${boxX + 10},20.5)" shape-rendering="crispEdges">${px(NOTE)}</g>
720<text x="${boxX + 26}" y="29.5" font-family="${MONO}" font-size="12" fill="${label.color}">${esc(text)}</text>`
721
722  // YouTube-style live bar.
723  const barW = W - 24
724  const bar =
725    s.status === 'on' ? `<rect x="12" y="${H - 24}" width="${barW}" height="3" rx="1.5" fill="#FF0033"/><circle cx="${W - 12}" cy="${H - 22.5}" r="5" fill="#FF0033"/>`
726    : s.status === 'tuning' ? `<rect x="12" y="${H - 24}" width="${barW}" height="3" rx="1.5" fill="#FFFFFF" fill-opacity=".15"/><rect class="seg" x="12" y="${H - 24}" width="${f1(barW * 0.3)}" height="3" rx="1.5" fill="#E0B44C"/>`
727    : s.status === 'error' ? `<line x1="12" y1="${H - 22.5}" x2="${W - 12}" y2="${H - 22.5}" stroke="#7A2A26" stroke-width="3" stroke-dasharray="6 4"/>`
728    : `<rect x="12" y="${H - 24}" width="${barW}" height="3" rx="1.5" fill="#FFFFFF" fill-opacity=".12"/>`
729
730  // Info row: status and listening time left, catch and volume right.
731  const dotColor = s.status === 'on' ? '#FF4E45' : s.status === 'tuning' ? '#E0B44C' : s.status === 'error' ? '#FF4E45' : '#8A8A8A'
732  const statusText = s.status === 'on' ? `${ts.live} · ${elapsed(s.minute, ts)}` : statusLabel(s.status, ts)
733  const meterRight = W - 12 - 20
734  const meter: string[] = []
735  for (let i = 0; i < 10; i++) {
736    const h = 3 + (i * 5) / 9
737    const x = meterRight - 38 + i * 4
738    meter.push(`<rect x="${x}" y="${f1(H - 8 - h)}" width="2" height="${f1(h)}" fill="#FFFFFF" fill-opacity="${i < s.volume / 10 ? 1 : 0.18}"/>`)
739  }
740  const catchText = gold.length > 0 && s.status !== 'off' && W >= 360
741    ? `<text x="${meterRight - 46}" y="${H - 8}" text-anchor="end" font-family="${MONO}" font-size="10" fill="#8B8B8B">&gt;&lt;&gt; ×${gold.length}</text>`
742    : ''
743  const info = `<circle class="dot" style="${phase(s.status === 'tuning' ? 1_200 : 4_000)}" cx="18" cy="${H - 12}" r="3.5" fill="${dotColor}"/>
744<text x="28" y="${H - 8}" font-family="${MONO}" font-size="11" fill="#E8E8E8">${statusText}</text>
745${catchText}${meter.join('')}
746<text x="${W - 12}" y="${H - 8}" text-anchor="end" font-family="${MONO}" font-size="10" fill="#8B8B8B">${s.volume}</text>`
747
748  const sceneOpacity = { on: 1, tuning: 0.6, off: 0.55, error: 0.45 }[s.status]
749
750  return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">${css}${defs}
751<rect class="card" width="${W}" height="${H}" rx="10" fill="${INK}" stroke="none"/>
752<g class="${ROOT_CLASS[s.status]}" clip-path="url(#card)">
753<g opacity="${sceneOpacity}">
754${stars.join('')}
755${layer(cloud, 'p1', 'p3')}
756${layer(far, 'p1', 'p3')}
757<g opacity=".75">${layer(trees, 'p2')}</g>
758${water.join('')}
759${boat}
760</g>
761<rect y="${H - 44}" width="${W}" height="44" fill="url(#scrim)"/>
762${box}
763${bar}
764${info}
765</g>
766</svg>`
767}
768
769export const register: Register = (on, options) => {
770  on('session.start', async ($, e, n) => {
771    lang = await detectLang($, options.language)
772    await $.command.register({ name: 'lofi', description: t().command })
773    await $.tool.register({
774      name: 'lofi',
775      description:
776        'Control the Claude FM lo-fi radio player in this session: play, stop, set the volume, toggle the mini video window, or read its status (state, current track, listening minutes). Use it only when the user asks for music or the radio.',
777      inputSchema: {
778        type: 'object',
779        properties: {
780          action: { type: 'string', enum: ['play', 'stop', 'status', 'volume', 'window'] },
781          volume: { type: 'integer', minimum: 10, maximum: 100, description: 'For action "volume": the new volume, in steps of 10.' },
782        },
783        required: ['action'],
784      },
785    })
786    // A reload killed the old module's player; the shared state must not claim it still plays.
787    if (!player) await patch($, { status: 'off', note: null, track: null, onSince: null, minute: 0 })
788    await restoreSaved($)
789
790    return n(e)
791  })
792
793  // One fish per finished main-loop turn while the radio plays. The store is the
794  // count of record, so sessions on the same day add to one catch.
795  on('turn.complete', async ($, e, n) => {
796    if (!e.agentId && e.reason === 'answer' && (await current($)).status === 'on') {
797      const now = await $.clock.now()
798      const day = dayOf(now)
799      const saved = (await $.store.get('pond').catch(() => undefined)) as Pond | undefined
800      const base = saved && saved.day === day && Array.isArray(saved.gold) ? saved.gold : []
801      const next: Pond = { day, gold: [...base, e.durationMs >= 600_000].slice(-500), lastAt: now }
802      await $.store.set('pond', next).catch(() => undefined)
803      await update($, pond, (): Pond => next)
804    }
805
806    return n(e)
807  })
808
809  // The same controls for the model, so "put on some lofi" works and the player can be checked.
810  on('tool.call', { tool: TOOL }, async ($, e) => {
811    const input = e as unknown as { action?: string; volume?: number }
812    const s = await current($)
813    if (input.action === 'play') {
814      openPlayer($)
815      if (!isLive(s)) void play($)
816    } else if (input.action === 'stop') {
817      await stop($)
818    } else if (input.action === 'volume' && typeof input.volume === 'number') {
819      // A restart runs for as long as the new player plays, so the call answers without it.
820      void stepVolume($, clampVolume(Math.round(input.volume / 10) * 10) - s.volume)
821    } else if (input.action === 'window') {
822      void toggleWindow($)
823    }
824    const now = await current($)
825    const players = await $.process.run(['pgrep', '-f', MARK]).then(r => r.stdout.trim().split('\n').filter(Boolean).length, () => 0)
826    const { gold } = await todaysFish($)
827    const { status, track, minute, volume, isWindow, note } = now
828    return { result: JSON.stringify({ status, track, minutes: minute, volume, isWindow, note, players, fishToday: gold.length }) }
829  }).catch(() => ({ result: JSON.stringify({ error: 'lofi-radio could not run that' }) }))
830
831  on('command.run', { command: 'lofi' }, async ($, e) => {
832    if (e.args.trim() === 'stop') {
833      await stop($)
834      return { text: t().stopped }
835    }
836    openPlayer($)
837    if (isLive(await current($))) return { text: t().playing }
838    void play($)
839    return { text: t().starting }
840  })
841
842  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
843    const s = await current($)
844    const fish = await todaysFish($)
845    const now = await $.clock.now()
846    const ts = t()
847    const ui = $.ui.resolve(e)
848    const { Box, Button, Link, Text } = ui
849    const W = Math.max(300, Math.min(720, (e.props.bodyColumns || 60) * 8 - 8))
850
851    const main = { on: ts.stop, tuning: ts.cancel, off: ts.play, error: ts.retry }[s.status]
852    const controls = (
853      <Box key="fm-controls" flexDirection="row" alignItems="center" gap={1} flexWrap="wrap">
854        <Button key="fm-main" variant="primary" hotkey="p" label={main} onPress={() => void toggle($)} />
855        <Button key="fm-down" hotkey="j" label="−" dimColor={s.volume <= 10} onPress={() => void stepVolume($, -10)} />
856        <Button key="fm-up" hotkey="k" label="+" dimColor={s.volume >= 100} onPress={() => void stepVolume($, 10)} />
857        <Button
858          key="fm-window"
859          hotkey="m"
860          label={W < 420 ? '▣' : s.isWindow ? ts.closeMini : ts.mini}
861          onPress={() => void toggleWindow($)}
862        />
863        <Link key="fm-yt" href={STREAM_URL} label="YouTube ↗" />
864      </Box>
865    )
866    const note = s.status === 'error' && s.note ? <Text key="fm-note" color="error">{s.note}</Text> : null
867    const foot = <Text key="fm-foot" dimColor>{ts.unofficial}</Text>
868
869    // The terminal's table may still name Svg; only the remote surfaces draw it.
870    if (e.surface !== 'terminal' && 'Svg' in ui) {
871      const { Svg } = ui
872      const H = Math.round(Math.max(190, Math.min(320, W * 0.5625)))
873      const isNewFish = now - fish.lastAt < 2_000
874      return (
875        <Box flexDirection="column" gap={1}>
876          <Svg key="fm-scene" source={scene(W, H, s, fish.gold, now, isNewFish, ts)} alt={altText(s, fish.gold.length, ts)} width={W} height={H} />
877          {controls}
878          {note}
879          {foot}
880        </Box>
881      )
882    }
883
884    const meter = '▮'.repeat(s.volume / 10) + '▯'.repeat(10 - s.volume / 10)
885    const status = [s.status === 'on' ? `${ts.live} · ${elapsed(s.minute, ts)}` : statusLabel(s.status, ts), `${ts.volumeShort} ${meter}`]
886    if (fish.gold.length) status.push(`><> ×${fish.gold.length}`)
887    return (
888      <Box flexDirection="column">
889        <Text color="claude" bold>
890          ♫ Claude FM
891        </Text>
892        {s.status === 'on' && s.track ? <Text>♪ {s.track}</Text> : <Text dimColor>{ts.tagline}</Text>}
893        <Text dimColor>{'    .:.        .::.            .:.'}</Text>
894        <Text dimColor>{'  .:::::.  .:::::::::.   .:. .:::::.'}</Text>
895        <Text dimColor>{' ~ ~ ~ ~ ~ ~ ~ \\__/ ~ ~ ~ ~ ~ ~ ~ ~'}</Text>
896        <Text color={s.status === 'on' ? 'claude' : undefined} dimColor={s.status !== 'on'}>
897          ● {status.join(' · ')}
898        </Text>
899        {controls}
900        {note}
901        {foot}
902      </Box>
903    )
904  })
905
906  on('ui.render', { component: 'AbovePrompt' }, async ($, e, n) => {
907    if (e.props.hasSurvey) return n(e)
908
909    const s = await current($)
910    const ts = t()
911    const rest = await n(e)
912    const { Box, Button, Text } = $.ui.resolve(e)
913
914    const row =
915      s.status === 'on' ? (
916        <Box key="fm" gap={1}>
917          <Text color="claude">♪ {fit(s.track ?? 'Claude FM', Math.max(12, (e.props.bodyColumns || 80) - 28))}</Text>
918          <Text dimColor>· {elapsed(s.minute, ts)}</Text>
919          <Button key="fm-open" label={ts.player} plain dimColor onPress={() => openPlayer($)} />
920          <Button key="fm-stop" label="■" plain dimColor onPress={() => void stop($)} />
921        </Box>
922      ) : s.status === 'tuning' ? (
923        <Box key="fm" gap={1}>
924          <Text dimColor>{ts.bandTuning}</Text>
925          <Button key="fm-stop" label={ts.bandCancel} dimColor onPress={() => void stop($)} />
926        </Box>
927      ) : s.status === 'error' ? (
928        <Box key="fm" gap={1}>
929          <Text dimColor>♪ Claude FM: {s.note}</Text>
930          <Button key="fm-play" label={ts.bandRetry} dimColor onPress={() => void play($)} />
931        </Box>
932      ) : (
933        <Box key="fm">
934          <Button
935            key="fm-play"
936            label={ts.bandPlay}
937            dimColor
938            plain
939            onPress={() => {
940              void play($)
941              openPlayer($)
942            }}
943          />
944        </Box>
945      )
946
947    return (
948      <Box flexDirection="column">
949        {row}
950        {rest}
951      </Box>
952    )
953  })
954}
955
types/index.d.ts 24 lines
1export type Radio = {
2  status: 'off' | 'tuning' | 'on' | 'error'
3  note: string | null
4  // ffplay's -volume, 10 to 100.
5  volume: number
6  // Video in a small always-on-top ffplay window instead of audio only.
7  isWindow: boolean
8  // "Artist — Title" read from the stream's now-playing box; null until read.
9  track: string | null
10  // When the current listen started (ms); null while not playing.
11  onSince: number | null
12  // Whole minutes since onSince, ticked once a minute so the pane redraws rarely.
13  minute: number
14}
15
16// One fish per finished Claude turn while the radio plays, counted per local day.
17export type Pond = { day: string; gold: boolean[]; lastAt: number }
18
19declare module 'claude-code' {
20  interface PluginState {
21    'lofi-radio': { radio: Radio; pond: Pond }
22  }
23}
24