SLOPSHOPPER

now-playing

Shows the track playing in Apple Music or Spotify above the prompt, with cover art, play/pause, skip, volume, shuffle and repeat controls, a share-link copy…

panebandspinnerguardcommandtoast
v0.5.0no licenseupdated 2026-10-26benjaminr/nowplaying
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · now-playing
│ ┃ now-playing-queue ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ Up next x: close │ now-playing │ │ ┃ Nothing is playing. Play the Claude Code ⏺ Read(src/auth.ts) │ Now Playing is installed and hidden until │ │ ┃ playlist below, or something in Music. ⎿ Read 6 lines │ asked: /np show reveals the band, /np │ │ ┃ ⏺ Update(src/auth.ts) │ queue opens Up next & playlist, or ask │ │ ┃ Add to the Claude Code playlist ⎿ Added 2 lines, re╰────────────────────────────────────────────╯ │ ┃ Added tracks go in the playlist, not Up ⏺ Bash(bun test) │ ┃ next; "play… ⎿ 3 pass, 1 fail │ ┃ Only songs already in your Music library can │ ┃ be add… ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ Search your library and Apple Music ⏎ search │ ✻ Worked for 42s · done 4:20 PM │ │ › /np │ ⎿ now-playing: Nothing is playing in Music or Spotify. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · now-playing-queue
Up next x: close Nothing is playing. Play the Claude Code playlist below, or something in Music. Add to the Claude Code playlist Added tracks go in the playlist, not Up next; "play… Only songs already in your Music library can be add… Search your library and Apple Music ⏎ search
Pane · now-playing-lyrics
Lyrics x: close Nothing is playing.
README

Now Playing for Claude Code

A Claude Code mod that shows what Apple Music or Spotify is playing in a slim band above the prompt, with controls, cover art, an "Up next" pane, lyrics, a listening history, and tools that let Claude control the player and build playlists from your Music library by mood.

<img width="1794" height="233" alt="compact_bottom_and_band" src="https://github.com/user-attachments/assets/f2ba37be-c97e-484f-8b4b-1ba946252977" />

The band takes its colour from the album cover (red for Music and green for Spotify while a cover has none to give); the cover is the real picture in terminals that draw them (kitty, Ghostty, WezTerm) and a coloured half-block thumbnail elsewhere. In the Claude desktop app the band is drawn in the app's own type, with the real cover in front of a record that turns while it plays, the album in italic, a progress line with a round head, a faint wash of the cover's colour, and native buttons, the transport grouped apart from the rest. The compact band, two rows with a small cover, is a setting away and is what a short or narrow terminal gets:

<img width="1794" height="147" alt="large_top_only" src="https://github.com/user-attachments/assets/8c35244b-f542-44ca-a88a-f4142b927b8f" />

Footer placement puts the track among the prompt footer's bottom-right labels instead:

<img width="1797" height="221" alt="bottom_only" src="https://github.com/user-attachments/assets/dc56c1bc-c577-497f-b13f-345119acb114" />

The Up next & playlist pane

/np queue opens a pane in three sections. Up next is what Music will play, read only; the playlist is the mod's own, where every add lands; the add section searches your library and Apple Music:

Up next · OK Computer                                           x: close
  Airbag — Radiohead
▶ Paranoid Android — Radiohead
  Subterranean Homesick Alien — Radiohead
  Exit Music (For a Film) — Radiohead

Claude Code playlist · 10 tracks                       l: play it  clear
  The Journey — Tom Misch                                         remove
  Wander With Me (feat. Carmody) — Tom Misch                      remove
  Falafel — Tom Misch                                             remove
  Beautiful Escape — Tom Misch                                    remove

Add to the Claude Code playlist
Added tracks go in the playlist, not Up next; "play it" makes it Up next.
Only songs already in your Music library can be added; others open in…
┌──────────────────────────────────────────────────────────────────────┐
│ Search your library and Apple Music                           search │
└──────────────────────────────────────────────────────────────────────┘
"so what"                                                          clear
In your library, press one to add it to the playlist:
+ So What — Miles Davis · Kind of Blue
On Apple Music but not in your library, so not addable here.
Press one to open it in Music and add it to your library there:
↗ So What (Live) — Miles Davis · Live in Europe

The lyrics pane

/np lyrics follows the track on:

Lyrics · Everything In Its Right Place — Radiohead              x: close
Everything
Everything
Everything
In its right place

macOS only: it talks to the players through AppleScript.

Features

  • Band above the prompt, framed in the cover's colour, with the title and artist on their own rows, a thin progress line, shaded brighter towards its head, that moves in half-cell steps, the clock, and shuffle/repeat glyphs. Collapses to one row while Claude is working.
  • Controls with hotkeys: prev, play/pause, next, volume, mute (restores the old volume), shuffle, repeat (off, all, one), copy a share link, queue, hide, open the player. Transport is bright, the rest dim until the pointer is over the band, and a shuffle or repeat that is on shows bright with its state. The band keeps the most-used controls when it gets narrow.
  • Cover art beside the band (10 by 5 cells) and beside each row of the queue (6 by 3). Terminals that draw pictures (kitty, Ghostty, WezTerm) get the real cover; the desktop app draws the real cover as SVG (64 px in the band, 32 px in Up next);; every other terminal gets a pixel thumbnail drawn from coloured half-block cells.
  • Footer placement as an alternative: the track as a dim label in the prompt footer's bottom-right corner, where focus and similar labels sit.
  • Up next & playlist pane (/np queue or /np upnext), in three sections: Up next, Music's current playlist around the track on, each entry clickable to jump to it, preloaded in the background as tracks change; the mod's own playlist ("Claude Code" by default), with a play-it button and its last tracks; and Add to the playlist, a search box. See "How the pieces fit" below.
  • Search and add: the search box finds tracks in your Music library and adds them to the mod's playlist, since Music's own Up Next cannot be scripted. With "Search Apple Music too" on (the default), the same search also asks Apple's public catalogue, and each track you don't own gets a row that opens it in Music, where it can be played or added to the library.
  • Ask Claude: "add 10 great jazz tracks", "skip this", "what's this song", "play my 90s hip hop I haven't heard in a year" all work. Claude gets nine tools: now_playing (track, up next, lyrics), control_player, search_library (text search, or filters by genre, year, stars, favourite, play count and days since last play, sorted random, least played and so on), add_tracks (by name or by id), remove_tracks, clear_playlist, listening_history, open_in_music and show_now_playing. For a song you don't own it gives the Apple Music link, which open_in_music (or /np open <link>) opens in the Music app.
  • Lyrics pane (/np lyrics): the lyrics stored with the library track that is on, following the track as it changes. Apple Music's own streamed lyrics are not exposed to scripts, so only tracks whose files carry lyrics show them.
  • Listening history (/np history [n]): every track heard while Claude Code was open, kept across sessions, with the time and the player. Claude can read it to find "that song from earlier" or build a playlist from a day's listening.
  • Instant updates: a small Swift helper listens for Music's and Spotify's own change notifications, so the band updates the moment a track changes and polls only every 15 seconds to keep the clock honest. It needs Xcode's command line tools; without them the band polls every 2 seconds as before. Off in /config if you prefer.
  • Optional: tell Claude what's playing through a system-prompt section (off by default).

Install

Load it for one session:

claude --plugin-dir /path/to/nowplaying

Or for every session, add the folder to CLAUDE_CODE_PLUGIN_DIRS in the env block of ~/.claude/settings.json.

The first time it talks to Music or Spotify, macOS asks whether your terminal may control that app. Allow it; otherwise the band shows a line pointing at System Settings → Privacy & Security → Automation.

How the pieces fit

  • Now playing is the band: the track your player is on.
  • Up next is what Music will play after it: the rest of whatever playlist or album is playing. The pane shows it and lets you jump to a track, but nothing here can add to it, because Music does not let scripts edit Up Next.
  • The playlist ("Claude Code" by default) is the mod's own, and the only place the pane's search and Claude's add_tracks put songs. Press "play it" (or /np playlist) to make it what's playing; from then on it is Up next, and every song added joins the end of the queue. The pane's add section says which of the two is true at the moment. /np clear empties it; the songs stay in your library.
  • Library only. Music lets a script put only tracks you already own into a playlist, so that is all the search box, /np add and Claude can add. A song found on Apple Music that you don't own is shown with an open-in-Music row instead: open it there, add it to your library, and it becomes addable.
  • Spotify is show-and-control only. Spotify's scripting reports the track and takes transport, volume, shuffle and repeat, and nothing else: no queue, no search, no playlists. With Spotify on, the pane's Up next is empty and its add section still adds to the Music playlist.

Commands

/np on its own reports what's on. With an argument:

ArgumentDoes
play, pause, toggle, next, prevTransport
play <name>Music plays the first library track whose name matches
vol <0-100>, vol +, vol -Volume
mute, shuffle, repeatToggle mute, toggle shuffle, cycle repeat
copyCopy the Spotify link, or the track name on Music
openBring the player to the front
queue, upnextOpen or close the Up next & playlist pane
lyricsOpen or close the lyrics pane
history [n]The last n tracks heard (default 10)
search <text>Search the library and Apple Music, results in the pane
add <title — artist>Add the best library match to the playlist
open <link>Open a music.apple.com link in the Music app
playlistPlay the mod's playlist
clearEmpty the mod's playlist (the tracks stay in your library; the pane has clear and per-track remove buttons too)
hide, showHide or show the band (remembered)

play <name>, search, add, playlist, clear, lyrics and the contents of the pane need Apple Music running; see the table under Limits.

The band starts hidden. /np show, or asking Claude to show what's playing, reveals it, and that choice is remembered across sessions; /np hide or the x control hides it again.

Settings

In /config, under the plugin: placement (band, footer, both), band size (large, compact), player (auto, music, spotify), refresh interval, volume step, cover art, covers in Up next, preload Up next, quiet while Claude works, search Apple Music too, instant updates, tell Claude what's playing, and the playlist name.

Limits

  • Only tracks already in your Music library can be added to the playlist: AppleScript cannot add from the catalogue. Catalogue tracks are found through Apple's public search API (no sign-in) and can only be opened in Music, where you add them to the library yourself.
  • What each player's scripting allows:
Apple MusicSpotify
Band: track, progress, cover artyesyes
Play, pause, skip, volume, mute, shuffleyesyes
Repeatoff, all, oneoff, all
Copythe track namea share link
Up next paneyesno queue in its scripting
Play by name, searchlibrary onlyno
Add to the playlist, play the playlist, clear itlibrary tracks onlyno
Open a link in the appmusic.apple.com linksno
Lyricsstored with library tracks onlyno
Filter by genre, year, stars, favourite, play countyes (favourite needs macOS 14 or later)no
Listening historyyesyes
Instant updatesyesyes
  • Full-resolution cover art needs a terminal that speaks the kitty graphics protocol. iTerm2 and Terminal.app do not, so they get the 4×2 cell thumbnail instead.

Development

Checks: claude plugin validate ., tsc -p . (after the plugin has loaded once, which lays the engine's types beside it) and claude plugin test .. The same three run in CI (.github/workflows/ci.yml, on macOS) and as pre-commit hooks alongside hygiene and secret scanning (.pre-commit-config.yaml; install with uvx pre-commit install).

The player-event helper is hooks/player-events.swift, run through swift as a script, so there is nothing to compile or ship.

claude plugin validate .   # what the engine will accept, and what it refuses
claude plugin test .       # the tests in tests/
tsc -p .                   # type-check, once Claude Code has laid .claude-plugin/types/ by loading the mod

The AppleScript is generated in hooks/players.ts. Quirks it works around: offset, names, removed, matched, before and after are reserved words; loved became favorited in macOS 14; properties must be fetched with get before being concatenated or written; and Music's index of a track matches track k of playlist but not a range or every track, so the queue reads tracks one by one.

Source 7 files
hooks/register.tsx 2573 lines
1/**
2 * Now Playing: the track on in Apple Music or Spotify, shown above the prompt
3 * (a band with cover art and controls) or in the prompt footer, with a `/np`
4 * command, an "Up next" pane that searches the library and adds to a playlist
5 * of the mod's own, and tools Claude calls to add songs.
6 */
7import { atom, read, update } from 'claude-code'
8import type { ElementConstructor, Elements, EngineInterface, PluginOptions, Register, RenderInput, RenderSurface, TextProps, Timer } from 'claude-code'
9
10import type { Artwork, HistoryEntry, LibrarySearch, LyricsView, ModPlaylist, NowPlaying, PlayerSource, PlayerStatus, Queue, QueueEntry, SearchResult, Thumbnail } from '../types'
11import { BUTTON_GAP, MS_PER_SECOND, cellWidth, fitControls, formatClock, keepSteadyClock, layoutFor, msUntilNextSecond, plainButtonWidth, positionNow, shadedRuns, thinBar, truncateText } from './format'
12import { bytesFromBase64, decodeBmp, encodeCells, thumbnailCells } from './pixels'
13import { accentFromThumbnail } from './colour'
14import { coverSvg, progressSvg, vinylSvg, vinylWidth } from './svg'
15import {
16  MAX_SEARCH_RESULTS,
17  addTracksScript,
18  clearPlaylistScript,
19  filterLibraryScript,
20  lyricsScript,
21  normalise,
22  parseCount,
23  parseLibraryTracks,
24  parseLyrics,
25  pickTracks,
26  removeFromPlaylistScript,
27  artworkByIdScript,
28  artworkExportScript,
29  clampVolume,
30  classifyFailure,
31  controlScript,
32  describeFailure,
33  displayName,
34  downloadArgv,
35  ensurePlaylistScript,
36  nextRepeatMode,
37  openAppArgv,
38  osascriptArgv,
39  parseAdded,
40  parseCleared,
41  parsePlayed,
42  parseQueue,
43  parseRunningPlayers,
44  parseSearch,
45  parseSearchMany,
46  parsePlaylist,
47  playPlaylistTrackScript,
48  catalogueSearchUrl,
49  musicAppUrl,
50  parseCatalogue,
51  storefrontFrom,
52  withoutLibraryDuplicates,
53  parseStatus,
54  pickBestMatch,
55  pickCurrent,
56  playByNameScript,
57  playPlaylistScript,
58  queueScript,
59  runningPlayersArgv,
60  searchLibraryManyScript,
61  searchLibraryScript,
62  splitTrackQuery,
63  statusScript,
64  toJpegArgv,
65  toPngArgv,
66  toThumbnailArgv,
67  type AddOutcome,
68  type LibraryFilter,
69  type LibrarySort,
70  type LibraryTrack,
71  type PlayerCommand,
72} from './players'
73
74const COMMAND = 'np'
75const QUEUE_PANE = 'now-playing-queue'
76/** Set once the person (or Claude) shows the band; unset, the band stays hidden. */
77const STORE_SHOWN = 'isShown'
78const TOOL_SEARCH = 'mcp__now-playing__search_library'
79const TOOL_ADD = 'mcp__now-playing__add_tracks'
80const TOOL_OPEN = 'mcp__now-playing__open_in_music'
81const TOOL_SHOW = 'mcp__now-playing__show_now_playing'
82const TOOL_CONTROL = 'mcp__now-playing__control_player'
83const TOOL_STATUS = 'mcp__now-playing__now_playing'
84const TOOL_HISTORY = 'mcp__now-playing__listening_history'
85const TOOL_REMOVE = 'mcp__now-playing__remove_tracks'
86const TOOL_CLEAR = 'mcp__now-playing__clear_playlist'
87const LYRICS_PANE = 'now-playing-lyrics'
88/** Set once the first session has been told the band exists and how to show it. */
89const STORE_INTRODUCED = 'isIntroduced'
90/** The tracks heard, oldest first, kept across sessions. */
91const STORE_HISTORY = 'history'
92const HISTORY_KEEP = 500
93const HISTORY_DEFAULT_SHOWN = 10
94const HISTORY_MAX_SHOWN = 100
95/** The same track starting again within this long is one listen, not two. */
96const HISTORY_REPEAT_WINDOW_MS = 30 * 60 * 1000
97const DEFAULT_UP_NEXT_SHOWN = 5
98const MAX_FILTER_RESULTS = 100
99/** While the player-event listener runs, polling only re-syncs the clock. */
100const LISTENER_PLAYING_POLL_MS = 15_000
101const LISTENER_PAUSED_POLL_MS = 60_000
102
103const IDLE_STATUS: PlayerStatus = { current: null, failure: null }
104const status = atom({ plugin: 'now-playing', key: 'status' } as const, IDLE_STATUS)
105const lyrics = atom({ plugin: 'now-playing', key: 'lyrics' } as const, null)
106/**
107 * Whether the band is hidden: the choice made this session, or null before
108 * one, when `readHidden` asks the store what the last session chose. The band
109 * starts hidden; /np show, the x control's opposite, or Claude's tool reveals it.
110 */
111const isHidden = atom({ plugin: 'now-playing', key: 'isHidden' } as const, null)
112const tick = atom({ plugin: 'now-playing', key: 'tick' } as const, 0)
113const artwork = atom({ plugin: 'now-playing', key: 'artwork' } as const, null)
114const queue = atom({ plugin: 'now-playing', key: 'queue' } as const, null)
115const queueCovers = atom({ plugin: 'now-playing', key: 'queueCovers' } as const, {})
116const search = atom({ plugin: 'now-playing', key: 'search' } as const, null)
117const modPlaylist = atom({ plugin: 'now-playing', key: 'modPlaylist' } as const, null)
118const mutedVolume = atom({ plugin: 'now-playing', key: 'mutedVolume' } as const, null)
119
120const SCRIPT_TIMEOUT_MS = 8000
121const SEARCH_TIMEOUT_MS = 15_000
122/** A batch of searches runs in one osascript, so the whole batch gets one longer bound. */
123const BATCH_SEARCH_TIMEOUT_MS = 90_000
124/** How long a player that refused or garbled a read is left alone. */
125const FAILURE_BACKOFF_MS = 30_000
126/** How long a player that was merely slow to answer is left alone. */
127const TIMEOUT_BACKOFF_MS = 5000
128const PAUSED_POLL_MS = 10_000
129const IDLE_POLL_MS = 5000
130const HIDDEN_POLL_MS = 15_000
131const TICK_MS = 1000
132const REFRESH_AFTER_CONTROL_MS = 400
133const MIN_POLL_SECONDS = 1
134const MAX_POLL_SECONDS = 30
135const DEFAULT_POLL_SECONDS = 2
136const DEFAULT_VOLUME_STEP = 10
137const MAX_VOLUME_STEP = 50
138const UNMUTE_FALLBACK_VOLUME = 50
139const MIN_TITLE_WIDTH = 8
140const DEFAULT_PLAYLIST_NAME = 'Claude Code'
141const MAX_TRACKS_PER_ADD = 50
142/** How many catalogue matches are weighed for a request the library lacks. */
143const CATALOGUE_FALLBACK_LIMIT = 5
144/** How many catalogue lookups run at once: Apple's public search throttles a burst. */
145const CATALOGUE_CONCURRENCY = 4
146
147/** A cover's size in cells at one site. */
148type CoverSize = { columns: number; rows: number }
149/** The small cover beside the compact band. */
150const COMPACT_COVER: CoverSize = { columns: 4, rows: 2 }
151/** The cover inside the large band: tall enough for the title, artist, bar and controls beside it. */
152const LARGE_COVER: CoverSize = { columns: 10, rows: 5 }
153/** A cover beside each row of the Up next pane, with the title and artist on two lines. */
154const QUEUE_COVER: CoverSize = { columns: 6, rows: 3 }
155/** The cells a row's `gap={1}` leaves between a cover and the text beside it. */
156const COVER_GAP_COLUMNS = 1
157/** The large band's frame: a border cell and a padding cell at each side. */
158const FRAME_COLUMNS = 4
159const FRAME_ROWS = 2
160/** The rows a large band takes: its cover and the frame; a terminal with fewer gets the compact band. */
161const LARGE_BAND_ROWS = LARGE_COVER.rows + FRAME_ROWS
162/** Narrower than this, the large band's rows would wrap, so the compact one is drawn. */
163const LARGE_BAND_MIN_COLUMNS = 60
164/** A progress bar shorter than this says nothing, so it is dropped. */
165const MIN_BAR_WIDTH = 8
166const BORDER_STYLE = 'round'
167/** The desktop's cover sides, in CSS pixels: beside the large band, the compact or quiet one, and each Up next row. */
168const DESKTOP_COVER_PX = 64
169const DESKTOP_COMPACT_COVER_PX = 40
170const DESKTOP_QUEUE_COVER_PX = 32
171/** The JPEGs made for the desktop are twice the side drawn, so Retina screens draw them sharp. */
172const DESKTOP_COVER_JPEG_PX = DESKTOP_COVER_PX * 2
173const DESKTOP_QUEUE_JPEG_PX = DESKTOP_QUEUE_COVER_PX * 2
174const DESKTOP_BAR_WIDTH_PX = 220
175const DESKTOP_BAR_HEIGHT_PX = 12
176/** How far the record behind the large band's cover turns each second while playing. */
177const VINYL_DEGREES_PER_SECOND = 24
178/** The desktop band's background: its colour as a faint wash, as an alpha appended to the hex. */
179const DESKTOP_TINT_ALPHA = '14'
180/** The transport controls, drawn on the desktop as a group of their own with glyphs for labels. */
181const TRANSPORT_KEYS: ReadonlySet<string> = new Set(['previous', 'playpause', 'next'])
182/** U+FE0E asks for the text form of a glyph, so macOS draws no emoji in its place. */
183const TEXT_PRESENTATION = '︎'
184/** The cover of the track on, as `.src` (downloaded or exported), `.png` and `.bmp` files, named per track. */
185const ARTWORK_FILE_STEM = 'claude-now-playing-cover'
186/** A track without a player ID is named by title, artist and album, cut to keep the file name sane. */
187const MAX_COVER_ID_LENGTH = 80
188const COVERS_DIRECTORY = 'claude-now-playing-covers'
189/** The side of the small square the cover is shrunk to for cell drawing: room for the largest cover's 10 by 10 pixels. */
190const THUMBNAIL_PIXELS = 24
191/** The dim rule drawn between the pane's search results and its queue. */
192
193/** The footer label never grows past this many cells, whatever the width. */
194const MAX_FOOTER_LABEL = 60
195/** Nor past this share of the terminal, so the engine's own labels keep room. */
196const FOOTER_LABEL_SHARE = 0.4
197const DEFAULT_FOOTER_WIDTH = 40
198
199/** How tall the Up next pane opens. */
200const QUEUE_PANE_ROWS = 16
201/** Cells the pane keeps clear at its right edge, so a row never touches the border. */
202const PANE_MARGIN_COLUMNS = 4
203const CLOSE_LABEL = 'close'
204/** The limit behind the whole add section, said where someone might expect to add a song they do not own. */
205const LIBRARY_ONLY_HINT = 'Only songs already in your Music library can be added; others open in Music, where you add them to your library first.'
206/** The header's room for the playlist name: the width less the close button and the gap before it. */
207const PANE_HEADER_RESERVED = plainButtonWidth(CLOSE_LABEL) + BUTTON_GAP
208const REMOVE_LABEL = 'remove'
209const PANE_REMOVE_RESERVED = plainButtonWidth(REMOVE_LABEL) + BUTTON_GAP
210
211const SOURCE_COLOURS: Readonly<Record<PlayerSource, string>> = {
212  spotify: '#1DB954',
213  music: '#FC3C44',
214}
215const PLAYING_GLYPH = '▶'
216const PAUSED_GLYPH = '❚❚'
217const NOTE_GLYPH = '♪'
218const SHUFFLE_GLYPH = '⇄'
219const REPEAT_GLYPH = '↻'
220
221type Placement = 'footer' | 'band' | 'both'
222/** The framed band with a big cover, or the two-row one. */
223type BandSize = 'large' | 'compact'
224
225type Settings = {
226  placement: Placement
227  size: BandSize
228  source: PlayerSource | 'auto'
229  pollMs: number
230  volumeStep: number
231  showArtwork: boolean
232  queueArtwork: boolean
233  quietWhileWorking: boolean
234  tellClaude: boolean
235  /** Whether searches also ask Apple's catalogue, for tracks the library lacks. */
236  catalogue: boolean
237  playlistName: string
238  preloadQueue: boolean
239  /** Whether a helper listens for the players' own change notifications, so the band updates at once. */
240  pushUpdates: boolean
241}
242
243/** What one load of the module carries between its hooks and timers. */
244type Session = {
245  settings: Settings
246  /** True while a refresh is in flight, so timers never stack osascript runs. */
247  isRefreshing: boolean
248  /** Players that failed: why, when each may be asked again, and how long it was held for. */
249  retryAfter: Map<PlayerSource, { until: number; failure: string; backoffMs: number }>
250  pollTimer: Timer | null
251  /** True on the terminal surface, where covers are drawn (as pictures or as cells). */
252  isTerminal: boolean
253  /** True on the desktop app, which draws covers and the progress bar as SVG. */
254  drawsSvg: boolean
255  /** True when the terminal draws pictures (kitty graphics: kitty, Ghostty, WezTerm). */
256  canDrawArtwork: boolean
257  /** True once polling and the clock's tick have started, so a later surface does not start them twice. */
258  isPolling: boolean
259  artworkDirectory: string
260  /** Covers already exported, by persistent ID; null for a track without one. */
261  coverCache: Map<string, Artwork | null>
262  /** Bumped per queue so a cover run for an old queue stops. */
263  coverRun: number
264  /** Bumped per track change, so the cover of a track no longer on never lands. */
265  artworkRun: number
266  /** True while the queue is being read, so track changes never stack reads. */
267  isReadingQueue: boolean
268  /** True while the player-event helper runs and reports changes, so polling can relax. */
269  hasListener: boolean
270  /** A queue owed once the current read ends, for the track on then (null: the player stopped); null with none owed. */
271  pendingQueue: { current: NowPlaying | null } | null
272  /** The Apple Music storefront catalogue searches use (GB, US), from the Mac's locale. */
273  storefront: string
274  /** `$.clock.now()` when this load of the module started, so `/np version` can say how fresh it is. */
275  loadedAt: number
276}
277
278function readSettings(options: PluginOptions): Settings {
279  const placement = options.placement === 'footer' || options.placement === 'both' ? options.placement : 'band'
280  const size: BandSize = options.size === 'compact' ? 'compact' : 'large'
281  const source = options.source === 'music' || options.source === 'spotify' ? options.source : 'auto'
282  const pollSeconds = clamp(Number(options.pollSeconds) || DEFAULT_POLL_SECONDS, MIN_POLL_SECONDS, MAX_POLL_SECONDS)
283  const volumeStep = clamp(Number(options.volumeStep) || DEFAULT_VOLUME_STEP, 1, MAX_VOLUME_STEP)
284  const playlistName = typeof options.playlistName === 'string' && options.playlistName.trim() !== '' ? options.playlistName.trim() : DEFAULT_PLAYLIST_NAME
285  return {
286    placement,
287    size,
288    source,
289    pollMs: pollSeconds * MS_PER_SECOND,
290    volumeStep,
291    showArtwork: options.artwork !== false,
292    queueArtwork: options.queueArtwork !== false,
293    quietWhileWorking: options.quietWhileWorking !== false,
294    tellClaude: options.tellClaude === true,
295    catalogue: options.catalogue !== false,
296    playlistName,
297    preloadQueue: options.preloadQueue !== false,
298    pushUpdates: options.pushUpdates !== false,
299  }
300}
301
302function clamp(value: number, low: number, high: number): number {
303  return Math.min(high, Math.max(low, value))
304}
305
306function errorText(error: unknown): string {
307  return error instanceof Error ? error.message : String(error)
308}
309
310/** The fields a redraw cares about, as one string: equal keys mean nothing visible changed. */
311function statusKey({ current, failure }: PlayerStatus): string {
312  if (current === null) return JSON.stringify({ failure })
313  const { source, state, trackId, title, artist, album, volume, shuffle, repeat } = current
314  return JSON.stringify({
315    failure,
316    source,
317    state,
318    trackId,
319    title,
320    artist,
321    album,
322    volume,
323    shuffle,
324    repeat,
325    position: Math.floor(current.positionSeconds),
326    duration: Math.floor(current.durationSeconds),
327  })
328}
329
330function isSameTrack(a: NowPlaying | null, b: NowPlaying | null): boolean {
331  if (a === null || b === null) return a === b
332  return a.source === b.source && a.trackId === b.trackId
333}
334
335/** The one dim label the footer shows: glyphs, track, and the clock when it fits. */
336function footerLabel(current: NowPlaying, nowMs: number, columns: number | undefined): string {
337  const width = columns === undefined ? DEFAULT_FOOTER_WIDTH : Math.min(MAX_FOOTER_LABEL, Math.floor(columns * FOOTER_LABEL_SHARE))
338  const stateGlyph = current.state === 'playing' ? PLAYING_GLYPH : PAUSED_GLYPH
339  const clock = ` ${formatClock(positionNow(current, nowMs))}/${formatClock(current.durationSeconds)}`
340  const lead = `${NOTE_GLYPH} ${stateGlyph} `
341  const track = trackLine(current)
342
343  const roomWithClock = width - lead.length - clock.length
344  if (roomWithClock >= MIN_TITLE_WIDTH) {
345    return lead + truncateText(track, roomWithClock) + clock
346  }
347  return lead + truncateText(track, Math.max(MIN_TITLE_WIDTH, width - lead.length))
348}
349
350/** `⇄` while shuffling, `↻` or `↻1` while repeating; empty with neither. */
351function modeGlyphs(current: NowPlaying): string {
352  const parts: string[] = []
353  if (current.shuffle) parts.push(SHUFFLE_GLYPH)
354  if (current.repeat === 'all') parts.push(REPEAT_GLYPH)
355  if (current.repeat === 'one') parts.push(`${REPEAT_GLYPH}1`)
356  return parts.join(' ')
357}
358
359function describeTrack(current: NowPlaying, nowMs: number): string {
360  return (
361    `${displayName(current.source)} ${current.state}: ${trackLine(current)}` +
362    ` (${formatClock(positionNow(current, nowMs))} / ${formatClock(current.durationSeconds)}, volume ${current.volume}%)`
363  )
364}
365
366/** The text a copy puts on the clipboard: the share link, or the track's name. */
367function shareText(current: NowPlaying): string {
368  return current.shareUrl ?? trackLine(current)
369}
370
371/** `Title — Artist`, the line every list, toast and label names a track by. */
372function trackLine(track: { title: string; artist: string }): string {
373  return `${track.title} — ${track.artist}`
374}
375
376/** `Title — Artist · Album`, or just `Title — Artist` for a track without an album. */
377function trackLineWithAlbum(track: { title: string; artist: string; album: string }): string {
378  return track.album ? `${trackLine(track)} · ${track.album}` : trackLine(track)
379}
380
381/** A player that could not be read, and the one line saying why. */
382type ReadFailure = { failure: string }
383
384function isReadFailure(reading: NowPlaying | null | ReadFailure): reading is ReadFailure {
385  return reading !== null && 'failure' in reading
386}
387
388/** Runs an AppleScript through osascript, bounded by `timeoutMs`. */
389async function runScript($: EngineInterface, script: string, timeoutMs: number = SCRIPT_TIMEOUT_MS) {
390  return $.process.run(osascriptArgv(script), { timeoutMs })
391}
392
393/** Runs a script and reads its reply with `parse`; null when the script failed. */
394async function readScript<T>(
395  $: EngineInterface,
396  script: string,
397  parse: (stdout: string) => T | null,
398  timeoutMs: number = SCRIPT_TIMEOUT_MS,
399): Promise<T | null> {
400  const ran = await runScript($, script, timeoutMs)
401  return ran.exitCode === 0 ? parse(ran.stdout) : null
402}
403
404async function readPlayer(
405  $: EngineInterface,
406  session: Session,
407  source: PlayerSource,
408  now: number,
409): Promise<NowPlaying | null | ReadFailure> {
410  const held = session.retryAfter.get(source)
411  if (held !== undefined && held.until > now) return { failure: held.failure }
412  try {
413    const ran = await runScript($, statusScript(source))
414    if (ran.exitCode !== 0) {
415      return holdPlayer($, session, source, now, ran.stderr)
416    }
417    session.retryAfter.delete(source)
418    // Stamp the reading when the script answered, not when it was asked, or its run time counts as play time.
419    return parseStatus(source, ran.stdout, await $.clock.now())
420  } catch (error) {
421    return holdPlayer($, session, source, now, errorText(error))
422  }
423}
424
425/** Remembers a failed player so it is not asked again for a while: briefly when it was only slow. */
426function holdPlayer($: EngineInterface, session: Session, source: PlayerSource, now: number, reason: string): ReadFailure {
427  const failure = describeFailure(source, reason)
428  const backoffMs = classifyFailure(reason) === 'timeout' ? TIMEOUT_BACKOFF_MS : FAILURE_BACKOFF_MS
429  session.retryAfter.set(source, { until: now + backoffMs, failure, backoffMs })
430  $.ui.log(`${displayName(source)} status failed: ${reason.trim()}`)
431  return { failure }
432}
433
434/** The players open right now, as pgrep lists them. */
435async function listRunningPlayers($: EngineInterface): Promise<PlayerSource[]> {
436  const ran = await $.process.run(runningPlayersArgv(), { timeoutMs: SCRIPT_TIMEOUT_MS })
437  return parseRunningPlayers(ran.stdout)
438}
439
440/** The running players the band follows, per the `source` setting. */
441async function runningPlayers($: EngineInterface, session: Session): Promise<PlayerSource[]> {
442  const running = await listRunningPlayers($)
443  const wanted = session.settings.source
444  return wanted === 'auto' ? running : running.filter(source => source === wanted)
445}
446
447async function isMusicRunning($: EngineInterface): Promise<boolean> {
448  return (await listRunningPlayers($)).includes('music')
449}
450
451/** Asks the running players what is on and writes the band's status once it changed. */
452async function refresh($: EngineInterface, session: Session): Promise<PlayerStatus> {
453  const previous = await read($, status)
454  if (session.isRefreshing) return previous
455  session.isRefreshing = true
456  try {
457    const now = await $.clock.now()
458    const sources = await runningPlayers($, session)
459    const readings = await Promise.all(sources.map(source => readPlayer($, session, source, now)))
460
461    const found = readings.filter((reading): reading is NowPlaying | null => !isReadFailure(reading))
462    const firstFailure = readings.find(isReadFailure)
463    const picked = pickCurrent(found, previous.current?.source ?? null)
464    const current = keepSteadyClock(previous.current, picked, await $.clock.now())
465    const failure = current === null && firstFailure !== undefined ? firstFailure.failure : null
466    const next: PlayerStatus = { current, failure }
467
468    if (statusKey(previous) !== statusKey(next)) {
469      await update($, status, () => next)
470    }
471    if (!isSameTrack(previous.current, current)) {
472      void refreshArtwork($, session, current)
473      void preloadQueue($, session, current)
474      void refreshLyricsIfOpen($, session, current)
475      if (current !== null) void recordListen($, current)
476    }
477    return next
478  } catch (error) {
479    $.ui.log(`refresh failed: ${errorText(error)}`)
480    return previous
481  } finally {
482    session.isRefreshing = false
483  }
484}
485
486/** How long to wait before the next poll: quick while playing, lazy otherwise. */
487function nextPollDelay(session: Session, result: PlayerStatus, hidden: boolean): number {
488  if (hidden) return HIDDEN_POLL_MS
489  if (session.hasListener) {
490    if (result.current?.state === 'playing') return Math.max(session.settings.pollMs, LISTENER_PLAYING_POLL_MS)
491    if (result.current?.state === 'paused') return LISTENER_PAUSED_POLL_MS
492  }
493  if (result.current?.state === 'playing') return session.settings.pollMs
494  if (result.current?.state === 'paused') return Math.max(session.settings.pollMs, PAUSED_POLL_MS)
495  if (result.failure !== null) return shortestHold(session)
496  return IDLE_POLL_MS
497}
498
499/** How soon a held player is worth asking again: the shortest hold in force. */
500function shortestHold(session: Session): number {
501  const holds = [...session.retryAfter.values()].map(held => held.backoffMs)
502  return holds.length === 0 ? FAILURE_BACKOFF_MS : Math.min(...holds)
503}
504
505function schedulePoll($: EngineInterface, session: Session, delayMs: number): void {
506  session.pollTimer?.cancel()
507  session.pollTimer = $.clock.after(delayMs, () => void pollAndReschedule($, session))
508}
509
510/** Reads the players again shortly, once a command they were sent has taken effect. */
511function refreshSoon($: EngineInterface, session: Session): void {
512  $.clock.after(REFRESH_AFTER_CONTROL_MS, () => void refresh($, session))
513}
514
515async function pollAndReschedule($: EngineInterface, session: Session): Promise<void> {
516  const hidden = await readHidden($)
517  const result = hidden ? await read($, status) : await refresh($, session)
518  schedulePoll($, session, nextPollDelay(session, result, hidden))
519}
520
521/**
522 * Readies `surface` to draw the band: how it draws covers, and, the first
523 * time a surface that draws the band arrives, polling and the clock's tick.
524 * `pluginRoot` is the mod's folder, where the player-events helper lives.
525 */
526async function startDrawing($: EngineInterface, session: Session, surface: RenderSurface, pluginRoot: unknown): Promise<void> {
527  if (surface === 'terminal') {
528    session.isTerminal = true
529    session.canDrawArtwork = await detectArtworkSupport($)
530  } else if (surface === 'desktop') {
531    session.drawsSvg = true
532  } else {
533    return
534  }
535  if (session.isPolling) {
536    // A new surface may draw covers the first poll skipped, so fetch the current one again for it.
537    void read($, status).then(playerStatus => refreshArtwork($, session, playerStatus.current))
538    return
539  }
540  session.isPolling = true
541  const tmpdir = await $.env.get('TMPDIR')
542  session.artworkDirectory = (tmpdir ?? '/tmp').replace(/\/+$/, '')
543  // Only a catalogue search needs the storefront, so startup does not wait for it.
544  void detectStorefront($).then(storefront => {
545    session.storefront = storefront
546  })
547  void pollAndReschedule($, session)
548  void tickProgress($)
549  if (session.settings.pushUpdates && typeof pluginRoot === 'string') void listenForPlayerEvents($, session, pluginRoot)
550  void introduceOnce($)
551}
552
553/**
554 * Just after each whole second of the track while it plays and shows, so its
555 * clock and bar move between polls in step with the music. Otherwise it checks
556 * back once a second.
557 */
558async function tickProgress($: EngineInterface): Promise<void> {
559  // Each tick schedules the next, so one that fails must still schedule it or the clock stops for good.
560  let delayMs = TICK_MS
561  try {
562    const [hidden, playerStatus] = await Promise.all([readHidden($), read($, status)])
563    const { current } = playerStatus
564    const isShowingPlayback = !hidden && current?.state === 'playing'
565    if (isShowingPlayback) {
566      await update($, tick, count => count + 1)
567      delayMs = msUntilNextSecond(current, await $.clock.now())
568    }
569  } catch (error) {
570    $.ui.log(`clock tick failed: ${errorText(error)}`)
571  }
572  $.clock.after(delayMs, () => void tickProgress($))
573}
574
575/** Where a cover's fetched bytes, its PNG, its thumbnail BMP and its desktop JPEG live. */
576type CoverPaths = { source: string; png: string; bmp: string; jpeg: string }
577
578function coverPaths(directory: string, stem: string): CoverPaths {
579  return {
580    source: `${directory}/${stem}.src`,
581    png: `${directory}/${stem}.png`,
582    bmp: `${directory}/${stem}.bmp`,
583    jpeg: `${directory}/${stem}.jpg`,
584  }
585}
586
587/** Shrinks the PNG to a small JPEG for the desktop and reads it as base64; null when sips fails. */
588async function readCoverJpeg($: EngineInterface, paths: CoverPaths, side: number): Promise<string | null> {
589  try {
590    const shrunk = await $.process.run(toJpegArgv(paths.png, paths.jpeg, side), { timeoutMs: SCRIPT_TIMEOUT_MS })
591    if (shrunk.exitCode !== 0) return null
592    const { base64 } = await $.fs.read(paths.jpeg, { as: 'bytes' })
593    return base64
594  } catch (error) {
595    $.ui.log(`cover jpeg failed: ${errorText(error)}`)
596    return null
597  }
598}
599
600/** Shrinks the PNG to a few pixels, for terminals without pictures; each site folds them into its own cells. */
601async function readCoverThumbnail($: EngineInterface, paths: CoverPaths): Promise<Thumbnail | null> {
602  try {
603    const shrunk = await $.process.run(toThumbnailArgv(paths.png, paths.bmp, THUMBNAIL_PIXELS), { timeoutMs: SCRIPT_TIMEOUT_MS })
604    if (shrunk.exitCode !== 0) return null
605    const { base64 } = await $.fs.read(paths.bmp, { as: 'bytes' })
606    return decodeBmp(bytesFromBase64(base64))
607  } catch (error) {
608    $.ui.log(`thumbnail failed: ${errorText(error)}`)
609    return null
610  }
611}
612
613/**
614 * The `Artwork` for the PNG at `paths`: a small picture where the terminal
615 * cannot draw the PNG, a JPEG `jpegSide` pixels a side for the desktop, and
616 * the colour the band takes from it.
617 */
618async function artworkFrom($: EngineInterface, session: Session, trackId: string, paths: CoverPaths, jpegSide: number): Promise<Artwork> {
619  // The thumbnail is always read, since the band's colour is picked from it; it is kept only where it is drawn.
620  const [pixels, jpeg] = await Promise.all([readCoverThumbnail($, paths), session.drawsSvg ? readCoverJpeg($, paths, jpegSide) : null])
621  const generation = Math.floor(await $.clock.now())
622  const thumbnail = session.canDrawArtwork ? null : pixels
623  return { trackId, path: paths.png, generation, thumbnail, jpeg, accent: accentFromThumbnail(pixels) }
624}
625
626/**
627 * Fetches the cover of the track on into a PNG and a thumbnail, or clears it.
628 * Two quick track changes start two fetches; only the latest may publish.
629 */
630async function refreshArtwork($: EngineInterface, session: Session, current: NowPlaying | null): Promise<void> {
631  const run = ++session.artworkRun
632  const cover = await fetchCurrentCover($, session, current)
633  if (run !== session.artworkRun) return
634  await update($, artwork, () => cover)
635}
636
637/** A file name for a track's cover: the stem and its ID, with anything a path cannot hold replaced. */
638function coverFileStem(trackId: string): string {
639  const safeId = trackId.replace(/[^A-Za-z0-9]+/g, '-').slice(0, MAX_COVER_ID_LENGTH)
640  return `${ARTWORK_FILE_STEM}-${safeId}`
641}
642
643/**
644 * Makes sure the PNG at `paths` exists: one already there, from earlier in the
645 * session or before a reload, is kept; otherwise `fetchSource` writes the
646 * `.src` file and says whether it did, and sips converts it.
647 */
648async function ensureCoverPng($: EngineInterface, paths: CoverPaths, fetchSource: () => Promise<boolean>): Promise<boolean> {
649  if (await $.fs.exists(paths.png)) return true
650  if (!(await fetchSource())) return false
651  const converted = await $.process.run(toPngArgv(paths.source, paths.png), { timeoutMs: SCRIPT_TIMEOUT_MS })
652  return converted.exitCode === 0
653}
654
655/** Music exports the current track's cover to `path`; true when it wrote one. */
656async function exportCurrentCover($: EngineInterface, path: string): Promise<boolean> {
657  const exported = await runScript($, artworkExportScript(path))
658  return exported.exitCode === 0 && exported.stdout.trim() !== ''
659}
660
661/** Downloads the cover at `url` to `path`; true when curl did. */
662async function downloadCover($: EngineInterface, url: string, path: string): Promise<boolean> {
663  const downloaded = await $.process.run(downloadArgv(url, path), { timeoutMs: SCRIPT_TIMEOUT_MS })
664  return downloaded.exitCode === 0
665}
666
667/** The cover of the track on: Music exports it, Spotify names a URL to download; null without one. */
668async function fetchCurrentCover($: EngineInterface, session: Session, current: NowPlaying | null): Promise<Artwork | null> {
669  const drawsCovers = session.isTerminal || session.drawsSvg
670  const wantsArtwork = session.settings.showArtwork && drawsCovers && session.settings.placement !== 'footer'
671  if (current === null || !wantsArtwork) return null
672  const paths = coverPaths(session.artworkDirectory, coverFileStem(current.trackId))
673  const { artworkUrl } = current
674  const fetchSource =
675    current.source === 'music'
676      ? () => exportCurrentCover($, paths.source)
677      : artworkUrl === null
678        ? () => Promise.resolve(false)
679        : () => downloadCover($, artworkUrl, paths.source)
680  try {
681    if (!(await ensureCoverPng($, paths, fetchSource))) return null
682    return await artworkFrom($, session, current.trackId, paths, DESKTOP_COVER_JPEG_PX)
683  } catch (error) {
684    $.ui.log(`artwork failed: ${errorText(error)}`)
685    return null
686  }
687}
688
689/** Reads Music's current playlist around the track on, for the queue pane. */
690async function refreshQueue($: EngineInterface, session: Session, current: NowPlaying | null): Promise<Queue | null> {
691  if (current === null) {
692    await update($, queue, () => null)
693    return null
694  }
695  if (current.source !== 'music') {
696    const empty = emptyQueue(session, current, "Spotify's scripting has no queue, so Up next shows nothing. Controls still work; Up next, search and the playlist need Apple Music.")
697    await update($, queue, () => empty)
698    return empty
699  }
700  try {
701    const next = await readMusicQueue($, session, current)
702    await update($, queue, () => next)
703    void fetchQueueCovers($, session, next.entries)
704    return next
705  } catch (error) {
706    $.ui.log(`queue failed: ${errorText(error)}`)
707    return null
708  }
709}
710
711/** A queue with nothing to list and a line saying why. */
712function emptyQueue(session: Session, current: NowPlaying, note: string, playlistName = ''): Queue {
713  return {
714    source: current.source,
715    trackId: current.trackId,
716    currentIndex: 0,
717    playlistName,
718    isModPlaylist: playlistName === session.settings.playlistName,
719    note,
720    entries: [],
721  }
722}
723
724async function readMusicQueue($: EngineInterface, session: Session, current: NowPlaying): Promise<Queue> {
725  const parsed = await readScript($, queueScript(), parseQueue)
726  if (parsed === null) return emptyQueue(session, current, 'Music gave no playlist for this track.')
727  if (parsed.entries.length === 0) return emptyQueue(session, current, 'Music gave no tracks around this one.', parsed.playlistName)
728  // Music's index names the row on, which a song twice in one playlist needs;
729  // the ID is the fallback when the index names no listed row.
730  const byIndex = parsed.entries.find(entry => entry.index === parsed.currentIndex)
731  const byId = parsed.entries.find(entry => entry.id === current.trackId)
732  const currentEntry = byIndex ?? byId
733  return {
734    source: 'music',
735    trackId: currentEntry?.id ?? current.trackId,
736    currentIndex: currentEntry?.index ?? parsed.currentIndex,
737    playlistName: parsed.playlistName,
738    isModPlaylist: parsed.playlistName === session.settings.playlistName,
739    note: null,
740    entries: parsed.entries,
741  }
742}
743
744/** Exports each queue track's cover in turn, publishing them as they land. */
745async function fetchQueueCovers($: EngineInterface, session: Session, entries: readonly QueueEntry[]): Promise<void> {
746  const drawsCovers = session.isTerminal || session.drawsSvg
747  if (!drawsCovers || !session.settings.queueArtwork) return
748  const run = ++session.coverRun
749  const directory = `${session.artworkDirectory}/${COVERS_DIRECTORY}`
750  try {
751    await $.process.run(['mkdir', '-p', directory], { timeoutMs: SCRIPT_TIMEOUT_MS })
752    for (const entry of entries) {
753      if (run !== session.coverRun) return
754      if (entry.id === '') continue
755      let cover = session.coverCache.get(entry.id)
756      if (cover === undefined) {
757        cover = await exportCoverById($, session, entry.id, directory)
758        session.coverCache.set(entry.id, cover)
759      }
760      if (cover !== null) {
761        const found = cover
762        await update($, queueCovers, covers => (covers[entry.id] === undefined ? { ...covers, [entry.id]: found } : covers))
763      }
764    }
765  } catch (error) {
766    $.ui.log(`queue covers failed: ${errorText(error)}`)
767  }
768}
769
770/** The cover of the library track with this persistent ID, exported by Music; null without one. */
771async function exportCoverById($: EngineInterface, session: Session, id: string, directory: string): Promise<Artwork | null> {
772  const paths = coverPaths(directory, id)
773  const fetchSource = async () => {
774    const exported = await runScript($, artworkByIdScript(id, paths.source))
775    return exported.exitCode === 0 && exported.stdout.trim() === 'ok'
776  }
777  if (!(await ensureCoverPng($, paths, fetchSource))) return null
778  return artworkFrom($, session, id, paths, DESKTOP_QUEUE_JPEG_PX)
779}
780
781async function isQueueOpen($: EngineInterface): Promise<boolean> {
782  const panes = await $.ui.panes()
783  return panes.some(pane => pane.id === QUEUE_PANE)
784}
785
786async function refreshQueueIfOpen($: EngineInterface, session: Session, current: NowPlaying | null): Promise<void> {
787  try {
788    if (await isQueueOpen($)) await refreshQueue($, session, current)
789  } catch (error) {
790    $.ui.log(`queue check failed: ${errorText(error)}`)
791  }
792}
793
794/**
795 * Keeps the queue and its covers warm as tracks change, so the pane opens
796 * with everything already fetched. One read runs at a time; a track that
797 * changed meanwhile is read once the current read ends.
798 */
799async function preloadQueue($: EngineInterface, session: Session, current: NowPlaying | null): Promise<void> {
800  if (!session.settings.preloadQueue) {
801    await refreshQueueIfOpen($, session, current)
802    return
803  }
804  if (session.isReadingQueue) {
805    session.pendingQueue = { current }
806    return
807  }
808  session.isReadingQueue = true
809  try {
810    let wanted = current
811    while (true) {
812      await refreshQueue($, session, wanted)
813      const pending = session.pendingQueue
814      session.pendingQueue = null
815      if (pending === null || isSameTrack(pending.current, wanted)) break
816      wanted = pending.current
817    }
818  } finally {
819    session.isReadingQueue = false
820  }
821}
822
823/** True when the queue in state already describes the track on. */
824function isQueueFresh(list: Queue | null, current: NowPlaying | null): boolean {
825  return list !== null && current !== null && list.source === current.source && list.trackId === current.trackId
826}
827
828/** Opens the queue pane, or closes it when it is already open. */
829async function toggleQueue($: EngineInterface, session: Session, current: NowPlaying | null): Promise<string> {
830  if (await isQueueOpen($)) {
831    await closeQueue($)
832    return 'Up next & playlist closed.'
833  }
834  return openQueue($, session, current)
835}
836
837async function openQueue($: EngineInterface, session: Session, current: NowPlaying | null): Promise<string> {
838  // Preloaded data opens at once; anything stale is fetched first, the playlist count in the background.
839  if (!isQueueFresh(await read($, queue), current)) {
840    await refreshQueue($, session, current)
841  }
842  void refreshModPlaylist($, session)
843  const opened = await $.ui.open({ id: QUEUE_PANE, title: 'Up next & playlist', rows: QUEUE_PANE_ROWS })
844  if (!opened.isPlaced) {
845    return 'Up next: widen the terminal to see the queue pane.'
846  }
847  return 'Up next & playlist opened. /np queue, the q control or ctrl+x x closes it.'
848}
849
850async function closeQueue($: EngineInterface): Promise<void> {
851  try {
852    await $.ui.close({ id: QUEUE_PANE })
853  } catch (error) {
854    $.ui.log(`queue close refused: ${errorText(error)}`)
855  }
856}
857
858/** Makes sure the mod's playlist exists and records how many tracks it holds; null with Music off. */
859async function refreshModPlaylist($: EngineInterface, session: Session): Promise<ModPlaylist | null> {
860  try {
861    const parsed = await readScript($, ensurePlaylistScript(session.settings.playlistName), parsePlaylist, SEARCH_TIMEOUT_MS)
862    if (parsed === null) return null
863    const playlist: ModPlaylist = { name: session.settings.playlistName, count: parsed.count, entries: parsed.entries }
864    await update($, modPlaylist, () => playlist)
865    return playlist
866  } catch (error) {
867    $.ui.log(`playlist check failed: ${errorText(error)}`)
868    return null
869  }
870}
871
872type LibraryMatches = { results: SearchResult[]; note: string | null }
873
874/** Music's own ranked search of the library; the caller has seen that Music is running. */
875async function runLibrarySearch($: EngineInterface, query: string, limit: number): Promise<LibraryMatches> {
876  try {
877    const ran = await runScript($, searchLibraryScript(query, limit), SEARCH_TIMEOUT_MS)
878    if (ran.exitCode !== 0) return { results: [], note: describeFailure('music', ran.stderr) }
879    return { results: parseSearch(ran.stdout), note: null }
880  } catch (error) {
881    return { results: [], note: `Music could not search: ${errorText(error)}` }
882  }
883}
884
885/** Searches the Music library alone, saying so when Music is not running. */
886async function searchLibraryOnly($: EngineInterface, query: string, limit: number): Promise<LibraryMatches> {
887  if (!(await isMusicRunning($))) return { results: [], note: 'Music is not running, so the library cannot be searched.' }
888  return runLibrarySearch($, query, limit)
889}
890
891/** Searches the Apple Music catalogue through Apple's public search API. */
892async function searchCatalogue($: EngineInterface, session: Session, query: string, limit: number): Promise<SearchResult[]> {
893  if (!session.settings.catalogue) return []
894  try {
895    const response = await $.http.fetch(catalogueSearchUrl(query, session.storefront, limit))
896    if (!response.ok) {
897      $.ui.log(`catalogue search answered ${response.status}`)
898      return []
899    }
900    return parseCatalogue(response.text)
901  } catch (error) {
902    $.ui.log(`catalogue search failed: ${errorText(error)}`)
903    return []
904  }
905}
906
907type SearchOptions = { limit?: number; withLibrary?: boolean; withCatalogue?: boolean }
908
909/** The line for a search that found nothing, naming where it looked. */
910function nothingFoundNote(query: string, inLibrary: boolean, inCatalogue: boolean): string {
911  if (inLibrary && inCatalogue) return `Nothing matches "${query}" in the library or on Apple Music.`
912  if (inCatalogue) return `Nothing on Apple Music matches "${query}".`
913  return `Nothing in the library matches "${query}".`
914}
915
916/**
917 * Searches the library and the catalogue, either unless told not to, and
918 * keeps the answer for the pane: library tracks to add, and catalogue tracks
919 * the library lacks. A library that could not be searched says so in the
920 * note whatever the catalogue found, so an empty library section is explained.
921 */
922async function searchMusic(
923  $: EngineInterface,
924  session: Session,
925  query: string,
926  { limit = MAX_SEARCH_RESULTS, withLibrary = true, withCatalogue = true }: SearchOptions = {},
927): Promise<LibrarySearch> {
928  const trimmed = query.trim()
929  const finish = async (found: LibrarySearch): Promise<LibrarySearch> => {
930    await update($, search, () => found)
931    return found
932  }
933  if (trimmed === '') return finish({ query: trimmed, results: [], catalogue: [], note: null })
934
935  const asksCatalogue = withCatalogue && session.settings.catalogue
936  const [library, catalogue] = await Promise.all([
937    withLibrary ? searchLibraryOnly($, trimmed, limit) : Promise.resolve<LibraryMatches>({ results: [], note: null }),
938    asksCatalogue ? searchCatalogue($, session, trimmed, limit) : Promise.resolve([]),
939  ])
940  const unowned = withoutLibraryDuplicates(catalogue, library.results)
941  const isEmpty = library.results.length === 0 && unowned.length === 0
942  const note = library.note ?? (isEmpty ? nothingFoundNote(trimmed, withLibrary, asksCatalogue) : null)
943  return finish({ query: trimmed, results: library.results, catalogue: unowned, note })
944}
945
946/** Opens a catalogue track's page in the Music app, where it can be played or added to the library. */
947async function openInMusic($: EngineInterface, url: string): Promise<string> {
948  if (!/^(music|https?):\/\/music\.apple\.com\//.test(url)) return `Not an Apple Music link: ${url}`
949  try {
950    await $.process.run(['open', musicAppUrl(url)], { timeoutMs: SCRIPT_TIMEOUT_MS })
951    return 'Opened in Music. Press play there, or add it to your library and it becomes addable here.'
952  } catch (error) {
953    return `Could not open Music: ${errorText(error)}`
954  }
955}
956
957/** Adds library tracks by ID to the mod's playlist, skipping ones already in it. */
958async function addTracks($: EngineInterface, session: Session, ids: readonly string[]): Promise<AddOutcome | null> {
959  const unique = [...new Set(ids.filter(id => id !== ''))].slice(0, MAX_TRACKS_PER_ADD)
960  if (unique.length === 0) return { added: 0, skipped: 0, count: 0 }
961  try {
962    const outcome = await readScript($, addTracksScript(session.settings.playlistName, unique), parseAdded, SEARCH_TIMEOUT_MS)
963    if (outcome !== null) {
964      // The pane lists the playlist, so it learns of the new tracks at once.
965      await refreshModPlaylist($, session)
966    }
967    return outcome
968  } catch (error) {
969    $.ui.log(`add failed: ${errorText(error)}`)
970    return null
971  }
972}
973
974/** Starts the mod's playlist from one of its tracks, pressed in the pane. */
975async function playPlaylistTrack($: EngineInterface, session: Session, index: number): Promise<void> {
976  try {
977    await runScript($, playPlaylistTrackScript(session.settings.playlistName, index))
978  } catch (error) {
979    $.ui.toast(`Music did not start the track: ${errorText(error)}`)
980  }
981  refreshSoon($, session)
982}
983
984/** Whether the mod's playlist was started, and why not when it was not. */
985type PlaylistStart = { started: true } | { started: false; failure: string | null }
986
987/** Tells Music to play the mod's playlist from its first track; a refusal or error is the failure. */
988async function startPlaylist($: EngineInterface, session: Session): Promise<string | null> {
989  try {
990    const ran = await runScript($, playPlaylistScript(session.settings.playlistName))
991    if (ran.exitCode !== 0) return describeFailure('music', ran.stderr)
992    return null
993  } catch (error) {
994    return `Music did not start the playlist: ${errorText(error)}`
995  } finally {
996    refreshSoon($, session)
997  }
998}
999
1000/** Starts the mod's playlist when nothing is playing, so added tracks are heard. */
1001async function startPlaylistIfIdle($: EngineInterface, session: Session): Promise<PlaylistStart> {
1002  const { current } = await refresh($, session)
1003  if (current !== null && current.state === 'playing') return { started: false, failure: null }
1004  const failure = await startPlaylist($, session)
1005  return failure === null ? { started: true } : { started: false, failure }
1006}
1007
1008async function playModPlaylist($: EngineInterface, session: Session): Promise<string> {
1009  if (!(await isMusicRunning($))) return 'Music is not running.'
1010  const playlist = await refreshModPlaylist($, session)
1011  if (playlist === null) return `Could not read the "${session.settings.playlistName}" playlist.`
1012  if (playlist.count === 0) return `The "${playlist.name}" playlist is empty. Search in the Up next pane, or ask Claude to add songs.`
1013  const failure = await startPlaylist($, session)
1014  if (failure !== null) return failure
1015  return `Playing "${playlist.name}" (${playlist.count} tracks).`
1016}
1017
1018/** Empties the mod's playlist and tells the pane, which lists it. */
1019async function clearModPlaylist($: EngineInterface, session: Session): Promise<string> {
1020  if (!(await isMusicRunning($))) return 'Music is not running.'
1021  const name = session.settings.playlistName
1022  let removed: number | null
1023  try {
1024    removed = await readScript($, clearPlaylistScript(name), parseCleared, SEARCH_TIMEOUT_MS)
1025  } catch (error) {
1026    return `Music could not clear "${name}": ${errorText(error)}`
1027  }
1028  if (removed === null) return `Could not clear the "${name}" playlist.`
1029  // Music keeps the track on but lists the library as its playlist from here,
1030  // and the band's refresh sees the same track, so the queue is read on purpose.
1031  const { current } = await refresh($, session)
1032  await Promise.all([refreshModPlaylist($, session), refreshQueue($, session, current)])
1033  if (removed === 0) return `"${name}" was already empty.`
1034  return `Removed ${removed} ${removed === 1 ? 'track' : 'tracks'} from "${name}". The tracks stay in your library.`
1035}
1036
1037/** The mod's playlist as the pane, toasts and replies name it: "Claude Code playlist", unless its name says so already. */
1038function playlistLabel(session: Session): string {
1039  const name = session.settings.playlistName
1040  return /playlist$/i.test(name) ? name : `${name} playlist`
1041}
1042
1043/** True while Music plays the mod's playlist, so a track added to it is also up next. */
1044async function isModPlaylistPlaying($: EngineInterface): Promise<boolean> {
1045  const list = await read($, queue)
1046  return list !== null && list.note === null && list.isModPlaylist
1047}
1048
1049/** Adds one found track from the pane, and tells the person in a toast where it went. */
1050async function addResult($: EngineInterface, session: Session, result: SearchResult): Promise<void> {
1051  const label = playlistLabel(session)
1052  const outcome = await addTracks($, session, [result.id])
1053  if (outcome === null) {
1054    $.ui.toast(`Could not add ${result.title} to the ${label}.`)
1055    return
1056  }
1057  if (outcome.added === 0) {
1058    $.ui.toast(`Already in the ${label}: ${trackLine(result)}`)
1059    return
1060  }
1061  const start = await startPlaylistIfIdle($, session)
1062  const where = start.started ? ' · playing it now' : (await isModPlaylistPlaying($)) ? ' · up next' : ''
1063  $.ui.toast(`Added to the ${label}: ${trackLine(result)}${where}`)
1064  if (!start.started && start.failure !== null) $.ui.toast(start.failure)
1065  // A start is followed by a refresh that reads the queue anew; otherwise the pane is told now.
1066  if (!start.started) {
1067    const { current } = await read($, status)
1068    await refreshQueue($, session, current)
1069  }
1070}
1071
1072/** Each request's best library match, or the catalogue's nearest offer for one the library lacks. */
1073type FoundRequests = {
1074  matched: { request: string; result: SearchResult }[]
1075  missing: { request: string; onAppleMusic: SearchResult | null }[]
1076}
1077
1078/** Runs `task` over `items` a few at a time, keeping the results in order. */
1079async function inBatches<T, R>(items: readonly T[], size: number, task: (item: T) => Promise<R>): Promise<R[]> {
1080  const results: R[] = []
1081  for (let start = 0; start < items.length; start += size) {
1082    results.push(...(await Promise.all(items.slice(start, start + size).map(task))))
1083  }
1084  return results
1085}
1086
1087/**
1088 * Looks every request up in one library script, then asks the catalogue
1089 * about the misses a few at a time, so a batch of fifty costs one osascript
1090 * launch and a short run of fetches rather than a hundred turns. A library
1091 * that could not be searched is a failure, not fifty tracks nobody owns.
1092 */
1093async function findRequests($: EngineInterface, session: Session, requests: readonly string[]): Promise<FoundRequests | { failure: string }> {
1094  const parts = requests.map(request => ({ request, ...splitTrackQuery(request) }))
1095  // Music's search ranks across fields, so the artist helps it find the track.
1096  const queries = parts.map(({ title, artist }) => (artist === null ? title : `${title} ${artist}`))
1097  const ran = await runScript($, searchLibraryManyScript(queries), BATCH_SEARCH_TIMEOUT_MS)
1098  if (ran.exitCode !== 0) return { failure: describeFailure('music', ran.stderr) }
1099  const results = parseSearchMany(ran.stdout, queries.length)
1100
1101  const matched: FoundRequests['matched'] = []
1102  const unmatched: typeof parts = []
1103  parts.forEach((part, index) => {
1104    const best = pickBestMatch(results[index] ?? [], part.title, part.artist)
1105    if (best === null) unmatched.push(part)
1106    else matched.push({ request: part.request, result: best })
1107  })
1108
1109  const missing = await inBatches(unmatched, CATALOGUE_CONCURRENCY, async ({ request, title, artist }) => {
1110    const offers = await searchCatalogue($, session, request, CATALOGUE_FALLBACK_LIMIT)
1111    return { request, onAppleMusic: pickBestMatch(offers, title, artist) }
1112  })
1113  return { matched, missing }
1114}
1115
1116/**
1117 * What Claude's add_tracks tool does: each request (`Title — Artist` or just
1118 * a title) is searched in the library and its best match added; the summary
1119 * names what landed and what the library lacks.
1120 */
1121async function addByQueries($: EngineInterface, session: Session, queries: readonly string[], play: boolean): Promise<string> {
1122  const requests = queries.map(query => query.trim()).filter(query => query !== '').slice(0, MAX_TRACKS_PER_ADD)
1123  if (requests.length === 0) return 'No tracks were named.'
1124  if (!(await isMusicRunning($))) return 'Music is not running, so nothing could be added. Open Music and try again.'
1125
1126  const found = await findRequests($, session, requests)
1127  if ('failure' in found) return `The library could not be searched, so nothing was added. ${found.failure}`
1128  const { matched, missing } = found
1129
1130  // With no library match there is nothing to add, and no count to misreport.
1131  const outcome = matched.length === 0 ? null : await addTracks($, session, matched.map(match => match.result.id))
1132  const label = playlistLabel(session)
1133  const lines: string[] = []
1134  if (matched.length === 0) {
1135    lines.push(`None of the ${requests.length === 1 ? 'request' : 'requests'} matched a library track, so the ${label} is unchanged.`)
1136  } else if (outcome === null) {
1137    lines.push(`Music refused the additions to the ${label}.`)
1138  } else {
1139    lines.push(`Added ${outcome.added} track${outcome.added === 1 ? '' : 's'} to the ${label} (${outcome.skipped} already there; ${outcome.count} in it now).`)
1140    for (const match of matched) lines.push(`  + ${trackLineWithAlbum(match.result)}`)
1141    const start: PlaylistStart = play && outcome.added > 0 ? await startPlaylistIfIdle($, session) : { started: false, failure: null }
1142    if (start.started) lines.push(`Started playing the ${label}.`)
1143    else if (start.failure !== null) lines.push(`The playlist did not start: ${start.failure}`)
1144    else if (await isModPlaylistPlaying($)) lines.push(`The ${label} is what's playing, so they are up next.`)
1145    else lines.push(`They are in the playlist, not in Up next: /np playlist (or the pane's "play it") plays it.`)
1146  }
1147  if (missing.length > 0) {
1148    lines.push(`Not in the library (${missing.length}); only library tracks can go in a playlist. On Apple Music, each can be opened in Music with open_in_music or /np open <link>, and added to the library there, after which add_tracks or /np add can add it:`)
1149    for (const miss of missing) {
1150      lines.push(
1151        miss.onAppleMusic === null
1152          ? `  - ${miss.request}: not found on Apple Music either`
1153          : `  - ${miss.request}: ${trackLineWithAlbum(miss.onAppleMusic)} → ${miss.onAppleMusic.url ?? ''}`,
1154      )
1155    }
1156  }
1157  const { current } = await read($, status)
1158  void refreshQueueIfOpen($, session, current)
1159  return lines.join('\n')
1160}
1161
1162async function control($: EngineInterface, session: Session, source: PlayerSource, command: PlayerCommand): Promise<void> {
1163  try {
1164    const ran = await runScript($, controlScript(source, command))
1165    if (ran.exitCode !== 0) {
1166      $.ui.toast(describeFailure(source, ran.stderr))
1167    }
1168  } catch (error) {
1169    $.ui.toast(`${displayName(source)} did not take the command: ${errorText(error)}`)
1170  }
1171  refreshSoon($, session)
1172}
1173
1174/** Silences the player, or restores the volume it had before the last mute. */
1175async function toggleMute($: EngineInterface, session: Session, current: NowPlaying): Promise<string> {
1176  const remembered = await read($, mutedVolume)
1177  if (current.volume > 0) {
1178    await update($, mutedVolume, () => current.volume)
1179    await control($, session, current.source, { volume: 0 })
1180    return `${displayName(current.source)}: muted.`
1181  }
1182  const restored = remembered ?? UNMUTE_FALLBACK_VOLUME
1183  await update($, mutedVolume, () => null)
1184  await control($, session, current.source, { volume: restored })
1185  return `${displayName(current.source)}: volume ${restored}%.`
1186}
1187
1188async function cycleRepeat($: EngineInterface, session: Session, current: NowPlaying): Promise<string> {
1189  const mode = nextRepeatMode(current.source, current.repeat)
1190  await control($, session, current.source, { repeat: mode })
1191  return `${displayName(current.source)}: repeat ${mode}.`
1192}
1193
1194async function copyShare($: EngineInterface, current: NowPlaying, surface: RenderSurface | undefined): Promise<string> {
1195  const text = shareText(current)
1196  const copied = await $.ui.copy(surface === undefined ? { text } : { text, surface })
1197  const what = current.shareUrl === null ? 'track name' : 'link'
1198  const message = copied.isCopied ? `Copied the ${what}: ${text}` : `Could not copy (${copied.reason}): ${text}`
1199  $.ui.toast(message)
1200  return message
hooks/format.ts 222 lines
1/**
2 * Pure helpers for the band: clocks, truncation, the progress bar, the
3 * position between polls, and which controls fit the width the band is given.
4 */
5import { rampTo } from './colour'
6import type { NowPlaying } from '../types'
7
8const SECONDS_PER_MINUTE = 60
9const MINUTES_PER_HOUR = 60
10export const MS_PER_SECOND = 1000
11const ELLIPSIS = '…'
12
13const BAR_LINE = '━'
14const BAR_HEAD = '╸'
15const BAR_TRACK = '─'
16const HALVES_PER_CELL = 2
17/** The played line is drawn in this many shades, darkest at its start. */
18const BAR_SHADE_STEPS = 6
19const BAR_SHADE_DEPTH = 0.22
20/** The left-aligned partial blocks, by eighths filled: the bar's head moves in sub-cell steps. */
21
22/** `m:ss`, or `h:mm:ss` past an hour. */
23export function formatClock(totalSeconds: number): string {
24  const whole = Math.max(0, Math.floor(totalSeconds))
25  const seconds = whole % SECONDS_PER_MINUTE
26  const minutes = Math.floor(whole / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR
27  const hours = Math.floor(whole / (SECONDS_PER_MINUTE * MINUTES_PER_HOUR))
28  const paddedSeconds = String(seconds).padStart(2, '0')
29  if (hours > 0) {
30    return `${hours}:${String(minutes).padStart(2, '0')}:${paddedSeconds}`
31  }
32  return `${minutes}:${paddedSeconds}`
33}
34
35/**
36 * The code point ranges a terminal draws two cells wide: the East Asian wide
37 * and fullwidth blocks (Hangul, kana, CJK ideographs and their forms). Emoji
38 * are checked separately, by property.
39 */
40const WIDE_RANGES: readonly (readonly [number, number])[] = [
41  [0x1100, 0x115f],
42  [0x2e80, 0x303e],
43  [0x3041, 0x33ff],
44  [0x3400, 0x4dbf],
45  [0x4e00, 0x9fff],
46  [0xa000, 0xa4cf],
47  [0xac00, 0xd7a3],
48  [0xf900, 0xfaff],
49  [0xfe30, 0xfe4f],
50  [0xff00, 0xff60],
51  [0xffe0, 0xffe6],
52  [0x20000, 0x3fffd],
53]
54/** Pictographs from here on are the colour emoji that take two cells; the older symbols below are one. */
55const FIRST_EMOJI_CODE_POINT = 0x1f000
56const WIDE_CELLS = 2
57const NARROW_CELLS = 1
58
59/**
60 * How many terminal cells one character takes: none for a combining mark or
61 * a zero-width joiner, two for CJK and emoji, one for the rest. An
62 * approximation of wcwidth close enough to keep a title inside its row.
63 */
64function cellsFor(character: string): number {
65  const codePoint = character.codePointAt(0) ?? 0
66  if (/^[\p{M}\u200b-\u200f\ufe0f]$/u.test(character)) return 0
67  if (WIDE_RANGES.some(([first, last]) => codePoint >= first && codePoint <= last)) return WIDE_CELLS
68  if (codePoint >= FIRST_EMOJI_CODE_POINT && /^\p{Extended_Pictographic}$/u.test(character)) return WIDE_CELLS
69  return NARROW_CELLS
70}
71
72/** The terminal cells `text` occupies on one row. */
73export function cellWidth(text: string): number {
74  let cells = 0
75  for (const character of text) cells += cellsFor(character)
76  return cells
77}
78
79/** Cuts `text` to `width` cells, ending with an ellipsis when it was longer. */
80export function truncateText(text: string, width: number): string {
81  if (width <= 0) return ''
82  if (cellWidth(text) <= width) return text
83  if (width === 1) return ELLIPSIS
84  const room = width - cellWidth(ELLIPSIS)
85  let kept = ''
86  let used = 0
87  for (const character of text) {
88    const cells = cellsFor(character)
89    if (used + cells > room) break
90    kept += character
91    used += cells
92  }
93  return kept + ELLIPSIS
94}
95
96/**
97 * A thin bar `width` cells wide: the played cells, a half-cell head that
98 * moves the bar on twice per cell, and the unplayed line after it.
99 */
100export function thinBar(
101  positionSeconds: number,
102  durationSeconds: number,
103  width: number,
104): { playedCells: number; head: string; remaining: string } {
105  if (width <= 0) return { playedCells: 0, head: '', remaining: '' }
106  const fraction = durationSeconds > 0 ? Math.min(1, Math.max(0, positionSeconds / durationSeconds)) : 0
107  const halves = Math.round(fraction * width * HALVES_PER_CELL)
108  const playedCells = Math.floor(halves / HALVES_PER_CELL)
109  const head = halves % HALVES_PER_CELL === 0 ? '' : BAR_HEAD
110  const usedCells = playedCells + (head === '' ? 0 : 1)
111  return { playedCells, head, remaining: BAR_TRACK.repeat(Math.max(0, width - usedCells)) }
112}
113
114/**
115 * The played cells as a few runs of the line, each a step brighter than the
116 * last up to `colour` at the head, so the bar glows towards where it is.
117 */
118export function shadedRuns(playedCells: number, colour: string): { text: string; colour: string }[] {
119  const runCount = Math.min(playedCells, BAR_SHADE_STEPS)
120  const colours = rampTo(colour, runCount, BAR_SHADE_DEPTH)
121  return colours.map((runColour, index) => {
122    const start = Math.round((index * playedCells) / runCount)
123    const end = Math.round(((index + 1) * playedCells) / runCount)
124    return { text: BAR_LINE.repeat(end - start), colour: runColour }
125  })
126}
127
128/**
129 * Where the track is now: the last reading, moved on by the time since it was
130 * taken while playing, and never past the end.
131 */
132export function positionNow(reading: NowPlaying, nowMs: number): number {
133  if (reading.state !== 'playing') return reading.positionSeconds
134  const elapsed = Math.max(0, nowMs - reading.fetchedAt) / MS_PER_SECOND
135  const moved = reading.positionSeconds + elapsed
136  return reading.durationSeconds > 0 ? Math.min(reading.durationSeconds, moved) : moved
137}
138
139/** How far a fresh reading may stray from the running clock before the clock jumps to it. */
140const CLOCK_DRIFT_TOLERANCE_SECONDS = 1
141
142/**
143 * `next`, but keeping `previous`'s anchor while the same track plays on and
144 * the two agree to within a second. Each reading is a fraction of a second off,
145 * so re-anchoring on every poll would nudge the clock and make it skip.
146 */
147export function keepSteadyClock(previous: NowPlaying | null, next: NowPlaying | null, nowMs: number): NowPlaying | null {
148  if (previous === null || next === null) return next
149  const isSamePlayback =
150    previous.source === next.source &&
151    previous.trackId === next.trackId &&
152    previous.state === 'playing' &&
153    next.state === 'playing'
154  if (!isSamePlayback) return next
155  const drift = Math.abs(positionNow(previous, nowMs) - positionNow(next, nowMs))
156  if (drift > CLOCK_DRIFT_TOLERANCE_SECONDS) return next
157  return { ...next, positionSeconds: previous.positionSeconds, fetchedAt: previous.fetchedAt }
158}
159
160/** Lands a tick just after the clock turns over, never on the edge where it might not have yet. */
161const TICK_MARGIN_MS = 30
162
163/** How long until a playing reading's clock reaches its next whole second. */
164export function msUntilNextSecond(reading: NowPlaying, nowMs: number): number {
165  const position = positionNow(reading, nowMs)
166  const fractionPassed = position - Math.floor(position)
167  return Math.ceil((1 - fractionPassed) * MS_PER_SECOND) + TICK_MARGIN_MS
168}
169
170/** Which optional parts of the status row fit a given width. */
171type BandLayout = {
172  showAlbum: boolean
173  showBar: boolean
174  showClock: boolean
175  barWidth: number
176}
177
178const WIDE_COLUMNS = 120
179const ROOMY_COLUMNS = 90
180const NARROW_COLUMNS = 60
181const FULL_BAR_WIDTH = 16
182
183export function layoutFor(bodyColumns: number): BandLayout {
184  if (bodyColumns >= WIDE_COLUMNS) {
185    return { showAlbum: true, showBar: true, showClock: true, barWidth: FULL_BAR_WIDTH }
186  }
187  if (bodyColumns >= ROOMY_COLUMNS) {
188    return { showAlbum: false, showBar: false, showClock: true, barWidth: 0 }
189  }
190  if (bodyColumns >= NARROW_COLUMNS) {
191    return { showAlbum: false, showBar: false, showClock: true, barWidth: 0 }
192  }
193  return { showAlbum: false, showBar: false, showClock: false, barWidth: 0 }
194}
195
196/** A plain Button draws as `b: prev`: the hotkey, a colon, a space, the label. */
197const PLAIN_BUTTON_CHROME = 3
198/** The cells a row's `gap={1}` leaves between two buttons. */
199export const BUTTON_GAP = 1
200
201/** The cells a plain Button with a hotkey takes: `x: label`. */
202export function plainButtonWidth(label: string): number {
203  return cellWidth(label) + PLAIN_BUTTON_CHROME
204}
205
206/**
207 * Keeps, in their given order, the controls that fit `width` when taken by
208 * rising `priority` (lower first): the most-used controls survive a narrow band.
209 */
210export function fitControls<T extends { label: string; priority: number }>(controls: readonly T[], width: number): T[] {
211  const byPriority = [...controls].sort((a, b) => a.priority - b.priority)
212  const kept = new Set<T>()
213  let used = 0
214  for (const control of byPriority) {
215    const cost = plainButtonWidth(control.label) + (kept.size > 0 ? BUTTON_GAP : 0)
216    if (used + cost > width) continue
217    used += cost
218    kept.add(control)
219  }
220  return controls.filter(control => kept.has(control))
221}
222
hooks/pixels.ts 125 lines
1/**
2 * Tiny pictures for terminals without an image protocol: decoding the small
3 * BMP `sips` writes, shrinking it to a grid, and packing that grid into the
4 * half-block cells a `Raster` element draws, two pixels per cell.
5 */
6import type { Thumbnail } from '../types'
7
8const BMP_HEADER_BYTES = 54
9const BITS_PER_BYTE = 8
10const UPPER_HALF_BLOCK = 0x2580
11const BYTES_PER_CELL_WORD = 4
12const WORDS_PER_CELL = 3
13
14/** One terminal cell: its glyph and the two colours, as `0xRRGGBB`. */
15type Cell = { codePoint: number; foreground: number; background: number }
16
17function readU16(bytes: Uint8Array, offset: number): number {
18  return (bytes[offset] ?? 0) | ((bytes[offset + 1] ?? 0) << 8)
19}
20
21function readI32(bytes: Uint8Array, offset: number): number {
22  return ((bytes[offset] ?? 0) | ((bytes[offset + 1] ?? 0) << 8) | ((bytes[offset + 2] ?? 0) << 16) | ((bytes[offset + 3] ?? 0) << 24)) | 0
23}
24
25/**
26 * Reads an uncompressed 24- or 32-bit BMP into `0xRRGGBB` pixels, row-major
27 * from the top. Returns null for anything else.
28 */
29export function decodeBmp(bytes: Uint8Array): Thumbnail | null {
30  if (bytes.length < BMP_HEADER_BYTES || bytes[0] !== 0x42 || bytes[1] !== 0x4d) return null
31  const pixelOffset = readI32(bytes, 10)
32  const width = readI32(bytes, 18)
33  const rawHeight = readI32(bytes, 22)
34  const bitsPerPixel = readU16(bytes, 28)
35  const compression = readI32(bytes, 30)
36  if (width <= 0 || rawHeight === 0 || compression !== 0) return null
37  if (bitsPerPixel !== 24 && bitsPerPixel !== 32) return null
38
39  const height = Math.abs(rawHeight)
40  const isTopDown = rawHeight < 0
41  const bytesPerPixel = bitsPerPixel / BITS_PER_BYTE
42  const stride = Math.ceil((width * bytesPerPixel) / 4) * 4
43  if (pixelOffset + stride * height > bytes.length) return null
44
45  const pixels: number[] = []
46  for (let row = 0; row < height; row++) {
47    const sourceRow = isTopDown ? row : height - 1 - row
48    const rowStart = pixelOffset + sourceRow * stride
49    for (let column = 0; column < width; column++) {
50      const at = rowStart + column * bytesPerPixel
51      const blue = bytes[at] ?? 0
52      const green = bytes[at + 1] ?? 0
53      const red = bytes[at + 2] ?? 0
54      pixels.push((red << 16) | (green << 8) | blue)
55    }
56  }
57  return { width, height, pixels }
58}
59
60/** Shrinks a picture to `width` by `height` by averaging the pixels each cell covers. */
61export function sampleThumbnail(source: Thumbnail, width: number, height: number): Thumbnail {
62  const pixels: number[] = []
63  for (let row = 0; row < height; row++) {
64    const top = Math.floor((row * source.height) / height)
65    const bottom = Math.max(top + 1, Math.floor(((row + 1) * source.height) / height))
66    for (let column = 0; column < width; column++) {
67      const left = Math.floor((column * source.width) / width)
68      const right = Math.max(left + 1, Math.floor(((column + 1) * source.width) / width))
69      let red = 0
70      let green = 0
71      let blue = 0
72      let count = 0
73      for (let y = top; y < bottom; y++) {
74        for (let x = left; x < right; x++) {
75          const pixel = source.pixels[y * source.width + x] ?? 0
76          red += (pixel >> 16) & 0xff
77          green += (pixel >> 8) & 0xff
78          blue += pixel & 0xff
79          count++
80        }
81      }
82      const average = (channel: number) => Math.round(channel / Math.max(1, count))
83      pixels.push((average(red) << 16) | (average(green) << 8) | average(blue))
84    }
85  }
86  return { width, height, pixels }
87}
88
89/**
90 * Folds a picture into `columns` by `rows` half-block cells: each cell shows
91 * two pixels, the upper as the glyph's colour and the lower as its background.
92 */
93export function thumbnailCells(source: Thumbnail, columns: number, rows: number): Cell[] {
94  const grid = sampleThumbnail(source, columns, rows * 2)
95  const cells: Cell[] = []
96  for (let row = 0; row < rows; row++) {
97    for (let column = 0; column < columns; column++) {
98      const upper = grid.pixels[row * 2 * columns + column] ?? 0
99      const lower = grid.pixels[(row * 2 + 1) * columns + column] ?? 0
100      cells.push({ codePoint: UPPER_HALF_BLOCK, foreground: upper, background: lower })
101    }
102  }
103  return cells
104}
105
106/** Packs cells as `Raster` wants them: little-endian u32 triplets, base64. */
107export function encodeCells(cells: readonly Cell[]): string {
108  const bytes = new Uint8Array(cells.length * WORDS_PER_CELL * BYTES_PER_CELL_WORD)
109  let at = 0
110  for (const cell of cells) {
111    for (const word of [cell.codePoint, cell.foreground, cell.background]) {
112      bytes[at++] = word & 0xff
113      bytes[at++] = (word >> 8) & 0xff
114      bytes[at++] = (word >> 16) & 0xff
115      bytes[at++] = (word >> 24) & 0xff
116    }
117  }
118  return btoa(String.fromCharCode(...bytes))
119}
120
121/** The bytes behind the base64 the host hands over, as `$.fs.read(path, { as: 'bytes' })` answers. */
122export function bytesFromBase64(text: string): Uint8Array {
123  return Uint8Array.from(atob(text), character => character.charCodeAt(0))
124}
125
hooks/colour.ts 132 lines
1/**
2 * The band's accent, taken from the cover: the hue that is both common in the
3 * picture and vivid, set to a lightness that reads on light and dark themes.
4 */
5import type { Thumbnail } from '../types'
6
7/** Hues are grouped into this many slices of the colour wheel before one is picked. */
8const HUE_SLICES = 12
9const DEGREES_PER_TURN = 360
10const DEGREES_PER_SECTOR = 60
11const SECTORS = 6
12/** Pixels greyer than this say nothing about the cover's colour. */
13const MIN_SATURATION = 0.2
14/** Near black and near white are left out for the same reason. */
15const MIN_LIGHTNESS = 0.1
16const MAX_LIGHTNESS = 0.92
17/** The accent's lightness and saturation are held in these ranges so it reads on both themes. */
18const ACCENT_LIGHTNESS = { min: 0.5, max: 0.62 }
19const ACCENT_MIN_SATURATION = 0.5
20/** Below this share of vivid pixels the cover is called grey and gives no accent. */
21const MIN_VIVID_SHARE = 0.04
22const CHANNEL_MAX = 255
23const HEX_RADIX = 16
24const HEX_DIGITS = 6
25
26type Hsl = { hue: number; saturation: number; lightness: number }
27
28function channels(pixel: number): [number, number, number] {
29  return [(pixel >> 16) & CHANNEL_MAX, (pixel >> 8) & CHANNEL_MAX, pixel & CHANNEL_MAX]
30}
31
32export function hexToPixel(hex: string): number {
33  return Number.parseInt(hex.replace('#', ''), HEX_RADIX)
34}
35
36export function pixelToHex(pixel: number): string {
37  return `#${pixel.toString(HEX_RADIX).padStart(HEX_DIGITS, '0').toUpperCase()}`
38}
39
40export function pixelToHsl(pixel: number): Hsl {
41  const [red, green, blue] = channels(pixel).map(channel => channel / CHANNEL_MAX) as [number, number, number]
42  const max = Math.max(red, green, blue)
43  const min = Math.min(red, green, blue)
44  const lightness = (max + min) / 2
45  const chroma = max - min
46  if (chroma === 0) return { hue: 0, saturation: 0, lightness }
47  const saturation = chroma / (1 - Math.abs(2 * lightness - 1))
48  let sector: number
49  if (max === red) sector = ((green - blue) / chroma + SECTORS) % SECTORS
50  else if (max === green) sector = (blue - red) / chroma + 2
51  else sector = (red - green) / chroma + 4
52  return { hue: sector * DEGREES_PER_SECTOR, saturation, lightness }
53}
54
55export function hslToPixel({ hue, saturation, lightness }: Hsl): number {
56  const chroma = (1 - Math.abs(2 * lightness - 1)) * saturation
57  const sector = (((hue % DEGREES_PER_TURN) + DEGREES_PER_TURN) % DEGREES_PER_TURN) / DEGREES_PER_SECTOR
58  const second = chroma * (1 - Math.abs((sector % 2) - 1))
59  const [red, green, blue] = rgbForSector(sector, chroma, second)
60  const offset = lightness - chroma / 2
61  const toChannel = (value: number) => Math.round(Math.min(1, Math.max(0, value + offset)) * CHANNEL_MAX)
62  return (toChannel(red) << 16) | (toChannel(green) << 8) | toChannel(blue)
63}
64
65function rgbForSector(sector: number, chroma: number, second: number): [number, number, number] {
66  if (sector < 1) return [chroma, second, 0]
67  if (sector < 2) return [second, chroma, 0]
68  if (sector < 3) return [0, chroma, second]
69  if (sector < 4) return [0, second, chroma]
70  if (sector < 5) return [second, 0, chroma]
71  return [chroma, 0, second]
72}
73
74/**
75 * The cover's accent as `#RRGGBB`, or null for a grey cover or none. Each
76 * vivid pixel votes for its slice of the wheel, weighted by how vivid it is;
77 * the winning slice's pixels are averaged, then made readable.
78 */
79export function accentFromThumbnail(thumbnail: Thumbnail | null): string | null {
80  if (thumbnail === null || thumbnail.pixels.length === 0) return null
81  const slices = Array.from({ length: HUE_SLICES }, () => ({ weight: 0, colours: [] as Hsl[] }))
82  for (const pixel of thumbnail.pixels) {
83    const colour = pixelToHsl(pixel)
84    const isVivid = colour.saturation >= MIN_SATURATION && colour.lightness >= MIN_LIGHTNESS && colour.lightness <= MAX_LIGHTNESS
85    if (!isVivid) continue
86    const slice = slices[Math.floor(colour.hue / (DEGREES_PER_TURN / HUE_SLICES)) % HUE_SLICES]
87    if (slice === undefined) continue
88    slice.weight += colour.saturation
89    slice.colours.push(colour)
90  }
91  const winner = slices.reduce((best, slice) => (slice.weight > best.weight ? slice : best))
92  if (winner.colours.length / thumbnail.pixels.length < MIN_VIVID_SHARE) return null
93  const average = averageHsl(winner.colours)
94  return pixelToHex(
95    hslToPixel({
96      hue: average.hue,
97      saturation: Math.max(ACCENT_MIN_SATURATION, average.saturation),
98      lightness: Math.min(ACCENT_LIGHTNESS.max, Math.max(ACCENT_LIGHTNESS.min, average.lightness)),
99    }),
100  )
101}
102
103/** The mean of colours from one slice of the wheel; their hues are close, so a plain mean is fair. */
104function averageHsl(colours: readonly Hsl[]): Hsl {
105  const total = colours.reduce(
106    (sum, colour) => ({
107      hue: sum.hue + colour.hue,
108      saturation: sum.saturation + colour.saturation,
109      lightness: sum.lightness + colour.lightness,
110    }),
111    { hue: 0, saturation: 0, lightness: 0 },
112  )
113  const count = colours.length
114  return { hue: total.hue / count, saturation: total.saturation / count, lightness: total.lightness / count }
115}
116
117/** `colour` made darker (a negative `shift`) or lighter, in lightness from 0 to 1. */
118export function shadeColour(colour: string, shift: number): string {
119  const hsl = pixelToHsl(hexToPixel(colour))
120  return pixelToHex(hslToPixel({ ...hsl, lightness: Math.min(1, Math.max(0, hsl.lightness + shift)) }))
121}
122
123/**
124 * `count` colours stepping from `colour` darkened by `depth` up to `colour`
125 * itself, for a bar that brightens towards its head.
126 */
127export function rampTo(colour: string, count: number, depth: number): string[] {
128  if (count <= 0) return []
129  if (count === 1) return [colour]
130  return Array.from({ length: count }, (_, step) => shadeColour(colour, -depth * (1 - step / (count - 1))))
131}
132
hooks/svg.ts 159 lines
1/**
2 * Drawings for the surfaces that draw `Svg` (the desktop app): the cover as a
3 * rounded tile, the record behind it and a progress line. The terminal keeps its cells.
4 *
5 * The desktop draws an `Svg` as an image, so each drawing carries everything
6 * it shows: the cover's JPEG goes in as a data URI, over the cover's few
7 * pixels as rectangles, which show should the picture not load.
8 */
9import type { Thumbnail } from '../types'
10
11/** The corner radius of a cover, as a share of its side. */
12const COVER_CORNER_SHARE = 0.12
13/** How strongly the player's colour tints a cover tile still waiting for its picture. */
14const PLACEHOLDER_TINT_OPACITY = 0.18
15/** The note's size on a placeholder tile, as a share of its side. */
16const PLACEHOLDER_NOTE_SHARE = 0.5
17/** The unplayed part of the bar: the player's colour, faint enough for light and dark themes. */
18const TRACK_OPACITY = 0.25
19const HEX_RADIX = 16
20const HEX_DIGITS = 6
21
22/** The cover's pictures, as an `Artwork` holds them. */
23export type CoverPictures = {
24  /** The cover as a small JPEG, base64; null where none was made. */
25  jpeg: string | null
26  thumbnail: Thumbnail | null
27}
28
29function hexColour(pixel: number): string {
30  return `#${pixel.toString(HEX_RADIX).padStart(HEX_DIGITS, '0')}`
31}
32
33/**
34 * The thumbnail's pixels as rectangles, one per run of equal pixels on a row,
35 * in a `width` by `height` viewBox the caller scales.
36 */
37export function thumbnailRects(thumbnail: Thumbnail): string {
38  const rects: string[] = []
39  for (let y = 0; y < thumbnail.height; y += 1) {
40    const rowStart = y * thumbnail.width
41    let runStart = 0
42    for (let x = 1; x <= thumbnail.width; x += 1) {
43      const runColour = thumbnail.pixels[rowStart + runStart] ?? 0
44      const isRunOver = x === thumbnail.width || (thumbnail.pixels[rowStart + x] ?? 0) !== runColour
45      if (!isRunOver) continue
46      rects.push(`<rect x="${runStart}" y="${y}" width="${x - runStart}" height="1" fill="${hexColour(runColour)}"/>`)
47      runStart = x
48    }
49  }
50  return rects.join('')
51}
52
53/**
54 * A rounded cover tile `side` pixels square: the JPEG where there is one, over
55 * the thumbnail's pixels, over a tile tinted in `colour` with a note on it.
56 */
57export function coverSvg(pictures: CoverPictures | null, side: number, colour: string): string {
58  const radius = Math.round(side * COVER_CORNER_SHARE)
59  const layers = [
60    `<rect width="${side}" height="${side}" fill="${colour}" fill-opacity="${PLACEHOLDER_TINT_OPACITY}"/>`,
61    `<text x="50%" y="50%" text-anchor="middle" dominant-baseline="central" font-size="${Math.round(side * PLACEHOLDER_NOTE_SHARE)}" fill="${colour}">♪</text>`,
62  ]
63  const thumbnail = pictures?.thumbnail ?? null
64  if (thumbnail !== null && thumbnail.width > 0 && thumbnail.height > 0) {
65    layers.push(
66      `<svg width="${side}" height="${side}" viewBox="0 0 ${thumbnail.width} ${thumbnail.height}" preserveAspectRatio="none" shape-rendering="crispEdges">` +
67        thumbnailRects(thumbnail) +
68        '</svg>',
69    )
70  }
71  if (pictures?.jpeg) {
72    layers.push(`<image width="${side}" height="${side}" preserveAspectRatio="xMidYMid slice" href="data:image/jpeg;base64,${pictures.jpeg}"/>`)
73  }
74  return (
75    `<svg xmlns="http://www.w3.org/2000/svg" width="${side}" height="${side}" viewBox="0 0 ${side} ${side}">` +
76    `<clipPath id="corner"><rect width="${side}" height="${side}" rx="${radius}"/></clipPath>` +
77    `<g clip-path="url(#corner)">${layers.join('')}</g>` +
78    '</svg>'
79  )
80}
81
82/** The progress line's thickness and its head's radius, in pixels. */
83const LINE_THICKNESS_PX = 4
84const HEAD_RADIUS_PX = 5
85
86/**
87 * A progress line `width` by `height` pixels: a faint rounded track, played in
88 * `colour` up to `fraction` (0 to 1), with a round head where the track is.
89 * The head stays inside the drawing at either end.
90 */
91export function progressSvg(fraction: number, width: number, height: number, colour: string): string {
92  const share = Math.min(1, Math.max(0, fraction))
93  const headX = HEAD_RADIUS_PX + share * (width - 2 * HEAD_RADIUS_PX)
94  const lineY = (height - LINE_THICKNESS_PX) / 2
95  const radius = LINE_THICKNESS_PX / 2
96  return (
97    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
98    `<rect y="${lineY}" width="${width}" height="${LINE_THICKNESS_PX}" rx="${radius}" fill="${colour}" fill-opacity="${TRACK_OPACITY}"/>` +
99    `<rect y="${lineY}" width="${headX.toFixed(1)}" height="${LINE_THICKNESS_PX}" rx="${radius}" fill="${colour}"/>` +
100    `<circle cx="${headX.toFixed(1)}" cy="${height / 2}" r="${HEAD_RADIUS_PX}" fill="${colour}"/>` +
101    '</svg>'
102  )
103}
104
105/** How far the record shows past the cover's right edge, as a share of the cover's side. */
106const VINYL_REVEAL_SHARE = 0.38
107const VINYL_COLOUR = '#1A1A1A'
108/** The grooves, as shares of the record's radius, faint light rings on the black. */
109const GROOVE_SHARES = [0.92, 0.82, 0.72, 0.62]
110const GROOVE_OPACITY = 0.07
111/** The label in the record's centre, in the cover's colour, and the hole in it. */
112const LABEL_SHARE = 0.34
113const SPINDLE_SHARE = 0.05
114/** The light catching the grooves: an arc that turns with the record, so the turn shows. */
115const SHEEN_OPACITY = 0.22
116const SHEEN_SWEEP_DEGREES = 50
117const SHEEN_SHARE = 0.78
118
119/** The width of a `vinylSvg` drawing for a cover `side` pixels square. */
120export function vinylWidth(side: number): number {
121  return Math.round(side * (1 + VINYL_REVEAL_SHARE))
122}
123
124function pointOnCircle(centreX: number, centreY: number, radius: number, degrees: number): string {
125  const radians = (degrees * Math.PI) / 180
126  return `${(centreX + radius * Math.cos(radians)).toFixed(2)} ${(centreY + radius * Math.sin(radians)).toFixed(2)}`
127}
128
129/**
130 * The cover `side` pixels square in front of a record that slides out to its
131 * right: black, grooved, with a label in `colour` and a sheen at `angle`
132 * degrees, so turning the angle each second spins the record.
133 */
134export function vinylSvg(pictures: CoverPictures | null, side: number, colour: string, angle: number): string {
135  const width = vinylWidth(side)
136  const radius = side / 2 - 1
137  const centreX = width - radius - 1
138  const centreY = side / 2
139  const grooves = GROOVE_SHARES.map(
140    share => `<circle cx="${centreX}" cy="${centreY}" r="${(radius * share).toFixed(2)}" fill="none" stroke="#FFFFFF" stroke-opacity="${GROOVE_OPACITY}"/>`,
141  )
142  const sheenRadius = radius * SHEEN_SHARE
143  const sheen =
144    `<path d="M ${pointOnCircle(centreX, centreY, sheenRadius, angle)} A ${sheenRadius.toFixed(2)} ${sheenRadius.toFixed(2)} 0 0 1 ` +
145    `${pointOnCircle(centreX, centreY, sheenRadius, angle + SHEEN_SWEEP_DEGREES)}" fill="none" stroke="#FFFFFF"` +
146    ` stroke-opacity="${SHEEN_OPACITY}" stroke-width="${Math.max(1, radius * 0.06).toFixed(2)}" stroke-linecap="round"/>`
147  return (
148    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${side}" viewBox="0 0 ${width} ${side}">` +
149    `<circle cx="${centreX}" cy="${centreY}" r="${radius}" fill="${VINYL_COLOUR}"/>` +
150    grooves.join('') +
151    sheen +
152    `<circle cx="${centreX}" cy="${centreY}" r="${(radius * LABEL_SHARE).toFixed(2)}" fill="${colour}"/>` +
153    `<circle cx="${centreX}" cy="${centreY}" r="${Math.max(1, radius * SPINDLE_SHARE).toFixed(2)}" fill="#F1EFE8"/>` +
154    // The cover drawn whole on top, as its own nested drawing.
155    coverSvg(pictures, side, colour).replace('<svg ', '<svg x="0" y="0" ') +
156    '</svg>'
157  )
158}
159
hooks/players.ts 980 lines
1/**
2 * Talking to Apple Music and Spotify: the AppleScript each query and control
3 * runs, how a reply is parsed, and which player the band follows.
4 *
5 * Every script is guarded by `is running` so the mod never launches a player,
6 * and every `tell` names the app literally, which AppleScript needs to compile
7 * its vocabulary. A player that is not running is found with pgrep first, so
8 * no script is compiled against an app that may not be installed.
9 */
10import type { NowPlaying, PlaybackState, PlayerSource, QueueEntry, RepeatMode, SearchResult } from '../types'
11
12const SOURCES: readonly PlayerSource[] = ['spotify', 'music']
13
14/** What sets the two players apart: their names, the words their scripting uses, and how repeat cycles. */
15type PlayerProfile = {
16  name: string
17  /** The status fields each player spells differently; `tr` is the current track. */
18  fields: {
19    duration: string
20    trackId: string
21    shuffle: string
22    repeat: string
23    shareUrl: string
24    artworkUrl: string
25  }
26  toggleShuffle: string
27  setRepeat: (mode: RepeatMode) => string
28  /** The repeat modes in the order the repeat control cycles them. */
29  repeatCycle: readonly RepeatMode[]
30}
31
32const PLAYERS: Readonly<Record<PlayerSource, PlayerProfile>> = {
33  spotify: {
34    name: 'Spotify',
35    fields: {
36      // Spotify reports a track's duration in milliseconds, Music in seconds.
37      duration: '((duration of tr) / 1000)',
38      trackId: 'id of tr',
39      shuffle: 'shuffling',
40      repeat: 'repeating',
41      shareUrl: 'spotify url of tr',
42      artworkUrl: 'artwork url of tr',
43    },
44    toggleShuffle: 'set shuffling to not shuffling',
45    setRepeat: mode => `set repeating to ${mode !== 'off'}`,
46    repeatCycle: ['off', 'all'],
47  },
48  music: {
49    name: 'Music',
50    fields: {
51      duration: 'duration of tr',
52      trackId: 'persistent ID of tr',
53      shuffle: 'shuffle enabled',
54      repeat: 'song repeat',
55      shareUrl: '""',
56      artworkUrl: '""',
57    },
58    toggleShuffle: 'set shuffle enabled to not shuffle enabled',
59    setRepeat: mode => `set song repeat to ${mode}`,
60    repeatCycle: ['off', 'all', 'one'],
61  },
62}
63
64/** Separates the fields a status script returns; never appears in a track name. */
65const FIELD_SEPARATOR = '\u001f'
66/** Ends each query's block in a batched search reply. */
67const RECORD_SEPARATOR = '\u001e'
68const STATUS_FIELD_COUNT = 12
69const SCRIPT_TIMEOUT_SECONDS = 3
70/** Listing a playlist or writing a cover takes Music longer than a status read. */
71const LISTING_TIMEOUT_SECONDS = 5
72const SEARCH_TIMEOUT_SECONDS = 10
73/** How long curl may spend fetching one cover. */
74const DOWNLOAD_TIMEOUT_SECONDS = 8
75
76const MIN_VOLUME = 0
77const MAX_VOLUME = 100
78
79/** How many tracks the queue pane lists, the track on included. */
80const QUEUE_LENGTH = 20
81/** How many already-played tracks the queue shows above the one on. */
82const QUEUE_LOOKBACK = 2
83/** How many of the mod's playlist's tracks the pane lists: the last ones added. */
84const PLAYLIST_LIST_LENGTH = 30
85/** How many matches a library search returns at most. */
86export const MAX_SEARCH_RESULTS = 25
87
88export type PlayerCommand =
89  | 'play'
90  | 'pause'
91  | 'playpause'
92  | 'next'
93  | 'previous'
94  | 'toggleShuffle'
95  | { volume: number }
96  | { repeat: RepeatMode }
97  | { playIndex: number }
98
99export function displayName(source: PlayerSource): string {
100  return PLAYERS[source].name
101}
102
103/** `pgrep` arguments that list the players running right now. */
104export function runningPlayersArgv(): readonly string[] {
105  return ['pgrep', '-l', '-x', SOURCES.map(source => PLAYERS[source].name).join('|')]
106}
107
108/** Reads the players `pgrep -l` listed, by their process names. */
109export function parseRunningPlayers(stdout: string): PlayerSource[] {
110  const names = new Set(
111    stdout
112      .split('\n')
113      .map(line => line.trim().split(/\s+/).slice(1).join(' '))
114      .filter(name => name.length > 0),
115  )
116  return SOURCES.filter(source => names.has(PLAYERS[source].name))
117}
118
119export function osascriptArgv(script: string): readonly string[] {
120  return ['osascript', '-e', script]
121}
122
123/** Brings the player's window to the front. */
124export function openAppArgv(source: PlayerSource): readonly string[] {
125  return ['open', '-a', PLAYERS[source].name]
126}
127
128/** Downloads a cover from its URL to `path`. */
129export function downloadArgv(url: string, path: string): readonly string[] {
130  return ['curl', '-fsSL', '--max-time', String(DOWNLOAD_TIMEOUT_SECONDS), '-o', path, url]
131}
132
133/** Converts whatever picture `source` holds into a PNG at `target`. */
134export function toPngArgv(source: string, target: string): readonly string[] {
135  return ['sips', '-s', 'format', 'png', source, '--out', target]
136}
137
138/** Shrinks the picture at `source` to `size` by `size` pixels as a BMP at `target`. */
139export function toThumbnailArgv(source: string, target: string, size: number): readonly string[] {
140  const side = String(Math.max(1, Math.floor(size)))
141  return ['sips', '-z', side, side, '-s', 'format', 'bmp', source, '--out', target]
142}
143
144/** Shrinks the picture at `source` to fit `size` pixels a side as a JPEG at `target`. */
145export function toJpegArgv(source: string, target: string, size: number): readonly string[] {
146  const side = String(Math.max(1, Math.floor(size)))
147  return ['sips', '-Z', side, '-s', 'format', 'jpeg', '-s', 'formatOptions', '80', source, '--out', target]
148}
149
150/** Quotes `text` for use inside an AppleScript string literal. */
151function escapeAppleScript(text: string): string {
152  return text.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/[\r\n]/g, ' ')
153}
154
155/** `set <name> to ""` then a guarded read of `expression`, so one missing field never fails the script. */
156function guardedField(name: string, expression: string): string[] {
157  return [`set ${name} to ""`, 'try', `  set ${name} to (${expression}) as text`, 'end try']
158}
159
160function guarded(source: PlayerSource, timeoutSeconds: number, body: readonly string[]): string {
161  const appName = PLAYERS[source].name
162  return [
163    `if application "${appName}" is not running then return "off"`,
164    'set sep to character id 31',
165    `with timeout of ${timeoutSeconds} seconds`,
166    `  tell application "${appName}"`,
167    ...body.map(line => `    ${line}`),
168    '  end tell',
169    'end timeout',
170  ].join('\n')
171}
172
173/** A one-line script that sends `verb` to the player only while it is running. */
174function tellIfRunning(source: PlayerSource, verb: string): string {
175  const appName = PLAYERS[source].name
176  return `if application "${appName}" is running then tell application "${appName}" to ${verb}`
177}
178
179/**
180 * Inside a `repeat with k from ...` over playlist `pl`: appends track k's
181 * fields to `out` as one line. Only `index` and `track k of playlist` agree on
182 * the order; a range (`tracks i thru j`) and `every track` each follow
183 * another, so tracks are read one at a time.
184 */
185function appendTrackLine(): string[] {
186  return [
187    ...guardedField('trackTitle', 'get name of track k of pl'),
188    ...guardedField('trackArtist', 'get artist of track k of pl'),
189    ...guardedField('trackAlbum', 'get album of track k of pl'),
190    ...guardedField('trackId', 'get persistent ID of track k of pl'),
191    'set out to out & (k as text) & sep & trackTitle & sep & trackArtist & sep & trackAlbum & sep & trackId & linefeed',
192  ]
193}
194
195/**
196 * Writes the bytes in `pictureBytes` to the file at `path`, replacing it.
197 * The handle is closed on a failed write too: one left open stays open in
198 * Music's process, and the next export of that file is refused.
199 */
200function writePictureLines(path: string): string[] {
201  return [
202    `set target to POSIX file "${escapeAppleScript(path)}"`,
203    'set handle to open for access target with write permission',
204    'try',
205    '  set eof handle to 0',
206    '  write pictureBytes to handle',
207    '  close access handle',
208    'on error writeError',
209    '  close access handle',
210    '  error writeError',
211    'end try',
212  ]
213}
214
215/** The AppleScript that reads what `source` is playing, one line of fields. */
216export function statusScript(source: PlayerSource): string {
217  const { fields } = PLAYERS[source]
218  return guarded(source, SCRIPT_TIMEOUT_SECONDS, [
219    'set playerState to (player state as text)',
220    'if playerState is "stopped" then return "stopped"',
221    // Music can say paused with no track on (its playlist changed under it): that is nothing playing.
222    'try',
223    '  set tr to current track',
224    'on error',
225    '  return "stopped"',
226    'end try',
227    ...guardedField('trackName', 'name of tr'),
228    ...guardedField('trackArtist', 'artist of tr'),
229    ...guardedField('trackAlbum', 'album of tr'),
230    ...guardedField('trackDuration', fields.duration),
231    ...guardedField('trackId', fields.trackId),
232    ...guardedField('shuffleText', fields.shuffle),
233    ...guardedField('repeatText', fields.repeat),
234    ...guardedField('shareUrl', fields.shareUrl),
235    ...guardedField('artworkUrl', fields.artworkUrl),
236    'return playerState & sep & trackName & sep & trackArtist & sep & trackAlbum' +
237      ' & sep & (player position as text) & sep & trackDuration & sep & (sound volume as text)' +
238      ' & sep & trackId & sep & shuffleText & sep & repeatText & sep & shareUrl & sep & artworkUrl',
239  ])
240}
241
242/** The AppleScript that sends `command` to `source`. */
243export function controlScript(source: PlayerSource, command: PlayerCommand): string {
244  return tellIfRunning(source, verbFor(source, command))
245}
246
247function verbFor(source: PlayerSource, command: PlayerCommand): string {
248  const player = PLAYERS[source]
249  if (typeof command === 'object') {
250    if ('volume' in command) return `set sound volume to ${clampVolume(command.volume)}`
251    if ('playIndex' in command) return `play track ${Math.max(1, Math.floor(command.playIndex))} of current playlist`
252    return player.setRepeat(command.repeat)
253  }
254  switch (command) {
255    case 'play':
256      return 'play'
257    case 'pause':
258      return 'pause'
259    case 'playpause':
260      return 'playpause'
261    case 'next':
262      return 'next track'
263    case 'previous':
264      return 'previous track'
265    case 'toggleShuffle':
266      return player.toggleShuffle
267  }
268}
269
270/** The repeat mode after this one in the player's cycle: off, all, one (Spotify skips `one`). */
271export function nextRepeatMode(source: PlayerSource, current: RepeatMode): RepeatMode {
272  const cycle = PLAYERS[source].repeatCycle
273  return cycle[(cycle.indexOf(current) + 1) % cycle.length] ?? 'off'
274}
275
276/** Music plays the first library track whose name contains `query`, and says which. */
277export function playByNameScript(query: string): string {
278  return guarded('music', SEARCH_TIMEOUT_SECONDS, [
279    `set found to (first track of library playlist 1 whose name contains "${escapeAppleScript(query)}")`,
280    'play found',
281    'return (name of found) & sep & (artist of found)',
282  ])
283}
284
285/** Reads a `playByNameScript` reply: the track that started, or null. */
286export function parsePlayed(stdout: string): { title: string; artist: string } | null {
287  const line = stdout.trim()
288  if (line === '' || line === 'off') return null
289  const [title = '', artist = ''] = line.split(FIELD_SEPARATOR)
290  return title === '' ? null : { title, artist }
291}
292
293/** Music lists the tracks around the one on in its current playlist. */
294export function queueScript(): string {
295  return guarded('music', LISTING_TIMEOUT_SECONDS, [
296    'if (player state as text) is "stopped" then return ""',
297    'try',
298    '  set pl to current playlist',
299    '  set i to index of current track',
300    'on error',
301    '  return ""',
302    'end try',
303    'set n to count of tracks of pl',
304    `set firstIndex to i - ${QUEUE_LOOKBACK}`,
305    'if firstIndex < 1 then set firstIndex to 1',
306    `set lastIndex to firstIndex + ${QUEUE_LENGTH - 1}`,
307    'if lastIndex > n then set lastIndex to n',
308    'set out to (i as text) & sep & (get name of pl) & linefeed',
309    'repeat with k from firstIndex to lastIndex',
310    ...appendTrackLine(),
311    'end repeat',
312    'return out',
313  ])
314}
315
316type ParsedQueue = { currentIndex: number; playlistName: string; entries: QueueEntry[] }
317
318/** The non-empty lines of a reply, or null when the player was off or said nothing. */
319function replyLines(stdout: string): string[] | null {
320  const lines = stdout.split('\n').filter(line => line.trim() !== '')
321  const first = lines[0]
322  return first === undefined || first === 'off' ? null : lines
323}
324
325/** Reads the lines `appendTrackLine` wrote, one entry per well-formed line. */
326function parseTrackLines(lines: readonly string[]): QueueEntry[] {
327  const entries: QueueEntry[] = []
328  for (const line of lines) {
329    const [indexText = '', title = '', artist = '', album = '', id = ''] = line.split(FIELD_SEPARATOR)
330    const index = Number.parseInt(indexText, 10)
331    if (Number.isFinite(index)) entries.push({ index, title, artist, album, id })
332  }
333  return entries
334}
335
336/** Reads a `queueScript` reply: the track on and its playlist, then the entries. */
337export function parseQueue(stdout: string): ParsedQueue | null {
338  const lines = replyLines(stdout)
339  if (lines === null) return null
340  const [first = '', ...rest] = lines
341  const [indexText = '', playlistName = ''] = first.split(FIELD_SEPARATOR)
342  const currentIndex = Number.parseInt(indexText, 10)
343  if (!Number.isFinite(currentIndex)) return null
344  return { currentIndex, playlistName, entries: parseTrackLines(rest) }
345}
346
347/** Music writes the current track's cover bytes to `path` and says their format. */
348export function artworkExportScript(path: string): string {
349  return guarded('music', LISTING_TIMEOUT_SECONDS, [
350    'if (player state as text) is "stopped" then return ""',
351    'if (count of artworks of current track) is 0 then return ""',
352    'set art to artwork 1 of current track',
353    'set pictureBytes to (get raw data of art)',
354    ...writePictureLines(path),
355    'return (format of art) as text',
356  ])
357}
358
359/** Music writes the cover of the library track with this persistent ID to `path`. */
360export function artworkByIdScript(id: string, path: string): string {
361  return guarded('music', LISTING_TIMEOUT_SECONDS, [
362    `set t to (first track of library playlist 1 whose persistent ID is "${escapeAppleScript(id)}")`,
363    'if (count of artworks of t) is 0 then return ""',
364    'set pictureBytes to (get raw data of artwork 1 of t)',
365    ...writePictureLines(path),
366    'return "ok"',
367  ])
368}
369
370/** `limit` held to 1 through `MAX_SEARCH_RESULTS`. */
371function capResults(limit: number): number {
372  return Math.max(1, Math.min(MAX_SEARCH_RESULTS, Math.floor(limit)))
373}
374
375/**
376 * Inside a script with `out` set: Music searches the library for the text
377 * `needleExpression` names and appends up to `limit` matches to `out`, one
378 * line each.
379 */
380function appendSearchLines(needleExpression: string, limit: number): string[] {
381  return [
382    `set found to (search library playlist 1 for ${needleExpression})`,
383    'set n to count of found',
384    `repeat with k from 1 to ${capResults(limit)}`,
385    '  if k > n then exit repeat',
386    '  set t to item k of found',
387    ...guardedField('trackName', 'name of t'),
388    ...guardedField('trackArtist', 'artist of t'),
389    ...guardedField('trackAlbum', 'album of t'),
390    '  set out to out & (get persistent ID of t) & sep & trackName & sep & trackArtist & sep & trackAlbum & linefeed',
391    'end repeat',
392  ]
393}
394
395/**
396 * Music searches its library the way its own search box does: every word of
397 * `query` matched across title, artist, album and the rest, results ranked.
398 */
399export function searchLibraryScript(query: string, limit: number = MAX_SEARCH_RESULTS): string {
400  const needle = escapeAppleScript(query)
401  return guarded('music', SEARCH_TIMEOUT_SECONDS, ['set out to ""', ...appendSearchLines(`"${needle}"`, limit), 'return out'])
402}
403
404/**
405 * One script that runs every search in `queries` in turn, so a batch of
406 * requests costs one osascript launch rather than one per request. The reply
407 * holds one block per query, in order, each ended by a record separator; a
408 * search that fails leaves its block empty.
409 */
410export function searchLibraryManyScript(queries: readonly string[], limit: number = MAX_SEARCH_RESULTS): string {
411  const list = queries.map(query => `"${escapeAppleScript(query)}"`).join(', ')
412  return guarded('music', SEARCH_TIMEOUT_SECONDS, [
413    'set rs to character id 30',
414    `set queries to {${list}}`,
415    'set out to ""',
416    'repeat with q from 1 to count of queries',
417    '  set needle to item q of queries',
418    '  try',
419    ...appendSearchLines('needle', limit).map(line => `  ${line}`),
420    '  end try',
421    '  set out to out & rs',
422    'end repeat',
423    'return out',
424  ])
425}
426
427/** Reads a `searchLibraryManyScript` reply: one list of results per query, in the order asked. */
428export function parseSearchMany(stdout: string, queryCount: number): SearchResult[][] {
429  if (stdout.trim() === 'off') return Array.from({ length: queryCount }, () => [])
430  const blocks = stdout.split(RECORD_SEPARATOR).map(parseSearch)
431  return Array.from({ length: queryCount }, (_, index) => blocks[index] ?? [])
432}
433
434/** Reads a `searchLibraryScript` reply. */
435export function parseSearch(stdout: string): SearchResult[] {
436  const results: SearchResult[] = []
437  for (const line of stdout.split('\n')) {
438    if (line.trim() === '' || line === 'off') continue
439    const [id = '', title = '', artist = '', album = ''] = line.split(FIELD_SEPARATOR)
440    if (id !== '') results.push({ id, kind: 'library', title, artist, album, url: null })
441  }
442  return results
443}
444
445/** Apple's public catalogue search, no sign-in needed; `country` is the storefront (GB, US). */
446export function catalogueSearchUrl(query: string, country: string, limit: number = MAX_SEARCH_RESULTS): string {
447  const params = new URLSearchParams({
448    term: query,
449    media: 'music',
450    entity: 'song',
451    limit: String(capResults(limit)),
452    country: storefrontFrom(country),
453  })
454  return `https://itunes.apple.com/search?${params.toString()}`
455}
456
457/** The two-letter storefront in a locale (`en_GB` → `GB`); `US` when none is found. */
458export function storefrontFrom(locale: string): string {
459  const match = /[_-]([A-Za-z]{2})\b/.exec(locale.trim())
460  const country = match?.[1] ?? (/^[A-Za-z]{2}$/.test(locale.trim()) ? locale.trim() : 'US')
461  return country.toUpperCase()
462}
463
464/** A web link to a track becomes the `music://` link that opens in the Music app. */
465export function musicAppUrl(webUrl: string): string {
466  return webUrl.replace(/^https?:\/\//, 'music://')
467}
468
469/** Reads the JSON Apple's catalogue search answers. */
470export function parseCatalogue(json: string): SearchResult[] {
471  let parsed: unknown
472  try {
473    parsed = JSON.parse(json)
474  } catch {
475    return []
476  }
477  if (typeof parsed !== 'object' || parsed === null || !Array.isArray((parsed as { results?: unknown }).results)) return []
478  const results: SearchResult[] = []
479  for (const item of (parsed as { results: unknown[] }).results) {
480    if (typeof item !== 'object' || item === null) continue
481    const row = item as Record<string, unknown>
482    const title = typeof row.trackName === 'string' ? row.trackName : ''
483    const artist = typeof row.artistName === 'string' ? row.artistName : ''
484    const album = typeof row.collectionName === 'string' ? row.collectionName : ''
485    const id = typeof row.trackId === 'number' ? String(row.trackId) : ''
486    const webUrl = typeof row.trackViewUrl === 'string' ? row.trackViewUrl : ''
487    if (title === '' || id === '' || webUrl === '') continue
488    results.push({ id, kind: 'catalogue', title, artist, album, url: musicAppUrl(webUrl) })
489  }
490  return results
491}
492
493/** Catalogue results the library already holds are dropped: the library row is the one to add. */
494export function withoutLibraryDuplicates(catalogue: readonly SearchResult[], library: readonly SearchResult[]): SearchResult[] {
495  const owned = new Set(library.map(result => `${normalise(result.title)}|${normalise(result.artist)}`))
496  const seen = new Set<string>()
497  return catalogue.filter(result => {
498    const key = `${normalise(result.title)}|${normalise(result.artist)}`
499    if (owned.has(key) || seen.has(key)) return false
500    seen.add(key)
501    return true
502  })
503}
504
505/** Music makes the mod's playlist when it is missing and lists its last tracks. */
506export function ensurePlaylistScript(name: string): string {
507  const playlist = escapeAppleScript(name)
508  return guarded('music', SEARCH_TIMEOUT_SECONDS, [
509    `if not (exists user playlist "${playlist}") then make new user playlist with properties {name:"${playlist}"}`,
510    `set pl to user playlist "${playlist}"`,
511    'set playlistCount to count of tracks of pl',
512    `set firstIndex to playlistCount - ${PLAYLIST_LIST_LENGTH - 1}`,
513    'if firstIndex < 1 then set firstIndex to 1',
514    'set out to (playlistCount as text) & linefeed',
515    'repeat with k from firstIndex to playlistCount',
516    ...appendTrackLine(),
517    'end repeat',
518    'return out',
519  ])
520}
521
522/** Reads an `ensurePlaylistScript` reply: how many tracks, then the last of them. */
523export function parsePlaylist(stdout: string): { count: number; entries: QueueEntry[] } | null {
524  const lines = replyLines(stdout)
525  if (lines === null) return null
526  const [first = '', ...rest] = lines
527  const count = Number.parseInt(first, 10)
528  if (!Number.isFinite(count)) return null
529  return { count, entries: parseTrackLines(rest) }
530}
531
532/** Music starts the mod's playlist at its `index`th track (from 1). */
533export function playPlaylistTrackScript(name: string, index: number): string {
534  const position = Math.max(1, Math.floor(index))
535  return tellIfRunning('music', `play track ${position} of user playlist "${escapeAppleScript(name)}"`)
536}
537
538/** Music starts the mod's playlist from its first track. */
539export function playPlaylistScript(name: string): string {
540  return tellIfRunning('music', `play user playlist "${escapeAppleScript(name)}"`)
541}
542
543/**
544 * Music adds the library tracks with these persistent IDs to the mod's
545 * playlist, skipping any already in it, and answers `added<sep>skipped<sep>count`.
546 */
547export function addTracksScript(name: string, ids: readonly string[]): string {
548  const playlist = escapeAppleScript(name)
549  const idList = ids.map(id => `"${escapeAppleScript(id)}"`).join(', ')
550  return guarded('music', SEARCH_TIMEOUT_SECONDS, [
551    `if not (exists user playlist "${playlist}") then make new user playlist with properties {name:"${playlist}"}`,
552    `set pl to user playlist "${playlist}"`,
553    `set wanted to {${idList}}`,
554    'set added to 0',
555    'set skipped to 0',
556    'repeat with wantedRef in wanted',
557    // The loop variable is a reference into the list; the string itself is what the filters compare.
558    '  set wantedId to contents of wantedRef',
559    '  set already to (count of (tracks of pl whose persistent ID is wantedId))',
560    '  if already > 0 then',
561    '    set skipped to skipped + 1',
562    '  else',
563    '    try',
564    '      duplicate (first track of library playlist 1 whose persistent ID is wantedId) to pl',
565    '      set added to added + 1',
566    '    on error',
567    '      set skipped to skipped + 1',
568    '    end try',
569    '  end if',
570    'end repeat',
571    'return (added as text) & sep & (skipped as text) & sep & ((count of tracks of pl) as text)',
572  ])
573}
574
575/** What an add did: tracks added, tracks already there, and the playlist's size after. */
576export type AddOutcome = { added: number; skipped: number; count: number }
577
578/** Reads an `addTracksScript` reply. */
579export function parseAdded(stdout: string): AddOutcome | null {
580  const line = stdout.trim()
581  if (line === '' || line === 'off') return null
582  const [added = '', skipped = '', count = ''] = line.split(FIELD_SEPARATOR).map(part => part.trim())
583  const numbers = [added, skipped, count].map(text => Number.parseInt(text, 10))
584  if (numbers.some(value => !Number.isFinite(value))) return null
585  return { added: numbers[0] ?? 0, skipped: numbers[1] ?? 0, count: numbers[2] ?? 0 }
586}
587
588/**
589 * Music removes every track from the mod's playlist, leaving the playlist
590 * itself and the library untouched, and answers how many it removed. A
591 * playlist that does not exist counts as empty.
592 */
593export function clearPlaylistScript(name: string): string {
594  const playlist = escapeAppleScript(name)
595  return guarded('music', SEARCH_TIMEOUT_SECONDS, [
596    `if not (exists user playlist "${playlist}") then return "0"`,
597    `set pl to user playlist "${playlist}"`,
598    // `removed` is a reserved word in Music's dictionary, so the count has a longer name.
599    'set trackTotal to count of tracks of pl',
600    'if trackTotal > 0 then delete every track of pl',
601    'return (trackTotal as text)',
602  ])
603}
604
605/** Reads a `clearPlaylistScript` reply: how many tracks were removed. */
606export function parseCleared(stdout: string): number | null {
607  return parseCount(stdout)
608}
609
610/**
611 * `Title — Artist`, `Title - Artist` or `Title by Artist` into its two parts.
612 * A dash is tried before `by`, and `by` is split at its last occurrence, so
613 * titles such as "Stand by Me — Ben E. King" or "Killed by Death by Motörhead"
614 * keep their `by`. A lone title containing `by` cannot be told from one with
615 * an artist, so Claude is asked to name tracks with a dash.
616 */
617export function splitTrackQuery(query: string): { title: string; artist: string | null } {
618  const trimmed = query.trim()
619  const dash = /^(.+?)\s+(?:—|–|-)\s+(.+)$/.exec(trimmed)
620  if (dash !== null) return trackParts(dash[1] ?? '', dash[2] ?? '')
621  const by = /^(.+)\s+by\s+(.+)$/i.exec(trimmed)
622  if (by !== null) return trackParts(by[1] ?? '', by[2] ?? '')
623  return { title: trimmed, artist: null }
624}
625
626function trackParts(title: string, artist: string): { title: string; artist: string | null } {
627  return { title: title.trim(), artist: artist.trim() || null }
628}
629
630/**
631 * A title or artist as compared: lower case, without accents or apostrophes,
632 * without a "(feat. X)" credit, and with runs of anything else as one space,
633 * so "Damselfly (feat. Tom Misch)" and "damselfly" are the same song and
634 * "Beyoncé" finds "Beyonce".
635 */
636export function normalise(text: string): string {
637  return text
638    .normalize('NFD')
639    .replace(/[\u0300-\u036f]/g, '')
640    .toLowerCase()
641    .replace(/[([][^)\]]*\b(?:feat|ft|featuring)\b[^)\]]*[)\]]/g, ' ')
642    .replace(/\s\b(?:feat|ft|featuring)\b\.?\s.*$/, ' ')
643    .replace(/['’`]/g, '')
644    .replace(/[^\p{L}\p{N}]+/gu, ' ')
645    .trim()
646}
647
648/** Returns a reply that is a single count, or null for off, empty or garbled. */
649export function parseCount(stdout: string): number | null {
650  const line = stdout.trim()
651  if (line === '' || line === 'off') return null
652  const count = Number.parseInt(line, 10)
653  return Number.isFinite(count) ? count : null
654}
655
656/**
657 * What a filtered library search asks for; the fields given are combined with
658 * "and", and none at all means the whole library (for a random pick).
659 */
660export type LibraryFilter = {
661  title?: string
662  artist?: string
663  album?: string
664  genre?: string
665  yearFrom?: number
666  yearTo?: number
667  /** Stars from 1 to 5; Music keeps a rating from 0 to 100 in steps of 20. */
668  minStars?: number
669  /** Music's favourite (the heart; `favorited` since macOS 14). */
670  favourite?: boolean
671  minPlays?: number
672  maxPlays?: number
673  /** Tracks not played for this many days, never-played ones included. */
674  notPlayedForDays?: number
675}
676
677/** A library track with the facts a filter can sort by. */
678export type LibraryTrack = SearchResult & { year: number; genre: string; stars: number; playCount: number }
679
680export type LibrarySort = 'random' | 'leastPlayed' | 'mostPlayed' | 'newest' | 'oldest' | 'topRated' | 'title'
681
682const STARS_TO_RATING = 20
683
684function wholeNumber(value: number | undefined): number | null {
685  return value !== undefined && Number.isFinite(value) ? Math.floor(value) : null
686}
687
688/** The `whose` conditions a filter stands for, as Music's scripting spells them. */
689function filterConditions(filter: LibraryFilter): string[] {
690  const conditions = ['media kind is song']
691  const texts: [string, string | undefined][] = [['name', filter.title], ['artist', filter.artist], ['album', filter.album], ['genre', filter.genre]]
692  for (const [property, value] of texts) {
693    if (value !== undefined && value.trim() !== '') conditions.push(`${property} contains "${escapeAppleScript(value.trim())}"`)
694  }
695  const yearFrom = wholeNumber(filter.yearFrom)
696  const yearTo = wholeNumber(filter.yearTo)
697  const minStars = wholeNumber(filter.minStars)
698  const minPlays = wholeNumber(filter.minPlays)
699  const maxPlays = wholeNumber(filter.maxPlays)
700  if (yearFrom !== null) conditions.push(`year >= ${yearFrom}`)
701  if (yearTo !== null) conditions.push(`year <= ${yearTo}`)
702  if (minStars !== null && minStars > 0) conditions.push(`rating >= ${Math.min(5, minStars) * STARS_TO_RATING}`)
703  if (filter.favourite === true) conditions.push('favorited is true')
704  if (minPlays !== null) conditions.push(`played count >= ${minPlays}`)
705  if (maxPlays !== null) conditions.push(`played count <= ${maxPlays}`)
706  if (wholeNumber(filter.notPlayedForDays) !== null) conditions.push('(played date < staleDate or played count = 0)')
707  return conditions
708}
709
710/**
711 * Music lists every library song a filter matches, as one line per property
712 * (IDs, names, artists, albums, years, genres, ratings, play counts), each a
713 * separated list: eight reads of a filtered reference, which Music answers in
714 * well under a second for hundreds of tracks. The caller sorts and trims.
715 */
716export function filterLibraryScript(filter: LibraryFilter): string {
717  const staleDays = wholeNumber(filter.notPlayedForDays)
718  const lists = ['persistent ID', 'name', 'artist', 'album', 'year', 'genre', 'rating', 'played count']
719  return guarded('music', SEARCH_TIMEOUT_SECONDS, [
720    ...(staleDays === null ? [] : [`set staleDate to (current date) - (${Math.max(0, staleDays)} * days)`]),
721    // `matched` and `removed` are reserved words here; `hits` is not.
722    `set hits to a reference to (every track of library playlist 1 whose ${filterConditions(filter).join(' and ')})`,
723    'set n to count of hits',
724    "set AppleScript's text item delimiters to sep",
725    'set out to (n as text) & linefeed',
726    'if n > 0 then',
727    ...lists.map(property => `  set out to out & ((${property} of hits) as text) & linefeed`),
728    'end if',
729    'return out',
730  ])
731}
732
733/**
734 * Reads a `filterLibraryScript` reply. Null for a player that is off or a
735 * reply whose lists do not line up (a name holding a line break would do it).
736 */
737export function parseLibraryTracks(stdout: string): LibraryTrack[] | null {
738  const lines = stdout.split('\n')
739  const count = Number.parseInt(lines[0]?.trim() ?? '', 10)
740  if (lines[0]?.trim() === 'off' || !Number.isFinite(count)) return null
741  if (count === 0) return []
742  const columns = lines.slice(1, 9).map(line => line.split(FIELD_SEPARATOR))
743  const [ids = [], titles = [], artists = [], albums = [], years = [], genres = [], ratings = [], plays = []] = columns
744  if (ids.length !== count || titles.length !== count) return null
745  return ids.map((id, index) => ({
746    id,
747    kind: 'library' as const,
748    title: titles[index] ?? '',
749    artist: artists[index] ?? '',
750    album: albums[index] ?? '',
751    url: null,
752    year: Number.parseInt(years[index] ?? '', 10) || 0,
753    genre: genres[index] ?? '',
754    stars: Math.round((Number.parseInt(ratings[index] ?? '', 10) || 0) / STARS_TO_RATING),
755    playCount: Number.parseInt(plays[index] ?? '', 10) || 0,
756  }))
757}
758
759/** The first `limit` tracks in the order asked; random is a fair shuffle. */
760export function pickTracks(tracks: readonly LibraryTrack[], sort: LibrarySort, limit: number, random: () => number = Math.random): LibraryTrack[] {
761  const list = [...tracks]
762  if (sort === 'random') {
763    for (let i = list.length - 1; i > 0; i--) {
764      const j = Math.floor(random() * (i + 1))
765      const swap = list[i] as LibraryTrack
766      list[i] = list[j] as LibraryTrack
767      list[j] = swap
768    }
769  } else {
770    const compare: Record<Exclude<LibrarySort, 'random'>, (a: LibraryTrack, b: LibraryTrack) => number> = {
771      leastPlayed: (a, b) => a.playCount - b.playCount,
772      mostPlayed: (a, b) => b.playCount - a.playCount,
773      newest: (a, b) => b.year - a.year,
774      oldest: (a, b) => a.year - b.year,
775      topRated: (a, b) => b.stars - a.stars || b.playCount - a.playCount,
776      title: (a, b) => a.title.localeCompare(b.title),
777    }
778    list.sort(compare[sort])
779  }
780  return list.slice(0, Math.max(0, Math.floor(limit)))
781}
782
783/** Music takes these tracks out of the mod's playlist (the library keeps them) and answers how many remain. */
784export function removeFromPlaylistScript(name: string, ids: readonly string[]): string {
785  const playlist = escapeAppleScript(name)
786  const idList = ids.map(id => `"${escapeAppleScript(id)}"`).join(', ')
787  return guarded('music', SEARCH_TIMEOUT_SECONDS, [
788    `if not (exists user playlist "${playlist}") then return "0"`,
789    `set pl to user playlist "${playlist}"`,
790    `set wanted to {${idList}}`,
791    'repeat with wantedRef in wanted',
792    '  set wantedId to contents of wantedRef',
793    '  try',
794    '    delete (first track of pl whose persistent ID is wantedId)',
795    '  end try',
796    'end repeat',
797    'return ((count of tracks of pl) as text)',
798  ])
799}
800
801/** The lyrics Music holds for the track on, with the track's identity. */
802export type Lyrics = { id: string; title: string; artist: string; text: string }
803
804/** Music gives the track on and its lyrics (empty when it has none); `stopped` gives nothing. */
805export function lyricsScript(): string {
806  return guarded('music', LISTING_TIMEOUT_SECONDS, [
807    'if player state is stopped then return ""',
808    'try',
809    '  set t to current track',
810    'on error',
811    '  return ""',
812    'end try',
813    'set ly to ""',
814    'try',
815    '  set ly to lyrics of t',
816    'end try',
817    'return (get persistent ID of t) & sep & (get name of t) & sep & (get artist of t) & sep & ly',
818  ])
819}
820
821/** Reads a `lyricsScript` reply; null for nothing on or Music off. */
822export function parseLyrics(stdout: string): Lyrics | null {
823  const trimmed = stdout.replace(/\s+$/, '')
824  if (trimmed === '' || trimmed === 'off') return null
825  const [id = '', title = '', artist = '', ...rest] = trimmed.split(FIELD_SEPARATOR)
826  if (id === '') return null
827  return { id, title, artist, text: rest.join(FIELD_SEPARATOR).trim() }
828}
829
830/**
831 * The result that best answers a request: an exact title by the named artist
832 * first, then an exact title, then a title that contains (or is contained in)
833 * the request, by that artist first. The title must match: Music's search
834 * matches any word, so a loose first result could be the wrong song.
835 */
836export function pickBestMatch(results: readonly SearchResult[], title: string, artist: string | null): SearchResult | null {
837  if (results.length === 0) return null
838  const wantedTitle = normalise(title)
839  if (wantedTitle === '') return null
840  const wantedArtist = artist === null ? null : normalise(artist)
841  const hasArtist = (result: SearchResult) => wantedArtist !== null && normalise(result.artist).includes(wantedArtist)
842  const pick = (list: readonly SearchResult[]) => list.find(hasArtist) ?? (wantedArtist === null ? list[0] : undefined)
843
844  const exact = results.filter(result => normalise(result.title) === wantedTitle)
845  const close = results.filter(result => {
846    const found = normalise(result.title)
847    return found !== wantedTitle && (found.includes(wantedTitle) || wantedTitle.includes(found))
848  })
849  return pick(exact) ?? exact[0] ?? pick(close) ?? null
850}
851
852/** A whole number from 0 to 100; 100 for anything that is not a number. */
853export function clampVolume(volume: number): number {
854  if (!Number.isFinite(volume)) return MAX_VOLUME
855  return Math.min(MAX_VOLUME, Math.max(MIN_VOLUME, Math.round(volume)))
856}
857
858/**
859 * Reads a status script's reply. `off` and `stopped` mean nothing to show;
860 * anything malformed is also nothing, rather than a half-filled row.
861 */
862export function parseStatus(source: PlayerSource, stdout: string, fetchedAt: number): NowPlaying | null {
863  const line = stdout.trim()
864  if (line === '' || line === 'off' || line === 'stopped') return null
865
866  const fields = line.split(FIELD_SEPARATOR)
867  if (fields.length !== STATUS_FIELD_COUNT) return null
868
869  const [
870    stateText = '',
871    title = '',
872    artist = '',
873    album = '',
874    positionText = '',
875    durationText = '',
876    volumeText = '',
877    trackId = '',
878    shuffleText = '',
879    repeatText = '',
880    shareUrlText = '',
881    artworkUrlText = '',
882  ] = fields
883  const state = parsePlaybackState(stateText)
884  if (state === null) return null
885
886  return {
887    source,
888    state,
889    trackId: trackId || `${title}|${artist}|${album}`,
890    title,
891    artist,
892    album,
893    positionSeconds: parseAppleScriptNumber(positionText),
894    durationSeconds: parseAppleScriptNumber(durationText),
895    volume: clampVolume(parseAppleScriptNumber(volumeText)),
896    shuffle: shuffleText === 'true',
897    repeat: parseRepeat(repeatText),
898    shareUrl: shareUrlFor(shareUrlText),
899    artworkUrl: artworkUrlText.startsWith('http') ? artworkUrlText : null,
900    fetchedAt,
901  }
902}
903
904function parsePlaybackState(text: string): PlaybackState | null {
905  if (text === 'playing') return 'playing'
906  if (text === 'paused') return 'paused'
907  return null
908}
909
910function parseRepeat(text: string): RepeatMode {
911  if (text === 'one' || text === 'all') return text
912  if (text === 'true') return 'all'
913  return 'off'
914}
915
916/** A Spotify URI (`spotify:track:ID`) becomes the web link anyone can open. */
917export function shareUrlFor(text: string): string | null {
918  const uri = text.trim()
919  if (uri === '') return null
920  if (uri.startsWith('http')) return uri
921  const parts = uri.split(':')
922  if (parts[0] === 'spotify' && parts.length === 3) {
923    return `https://open.spotify.com/${parts[1]}/${parts[2]}`
924  }
925  return null
926}
927
928/** AppleScript writes reals in the system locale, so a comma may be the point. */
929function parseAppleScriptNumber(text: string): number {
930  const value = Number.parseFloat(text.replace(',', '.'))
931  return Number.isFinite(value) ? value : 0
932}
933
934/**
935 * Which reading the band follows when more than one player is open: whatever
936 * is playing wins; between two in the same state the one shown last stays, so
937 * the band does not flicker between players.
938 */
939export function pickCurrent(
940  readings: readonly (NowPlaying | null)[],
941  previousSource: PlayerSource | null,
942): NowPlaying | null {
943  const present = readings.filter((reading): reading is NowPlaying => reading !== null)
944  if (present.length === 0) return null
945
946  const playing = present.filter(reading => reading.state === 'playing')
947  const pool = playing.length > 0 ? playing : present
948  return pool.find(reading => reading.source === previousSource) ?? pool[0] ?? null
949}
950
951/** Why a script failed: a permission to grant, a player too slow to answer, or something else. */
952export type FailureKind = 'permission' | 'timeout' | 'other'
953
954/**
955 * Reads osascript's stderr. `-1743` is macOS refusing the Apple Event because
956 * the terminal is not allowed to control the player; `-1712` is the event
957 * timing out, which a player still launching, scanning a large library or
958 * waiting on the permission prompt also does.
959 */
960export function classifyFailure(stderr: string): FailureKind {
961  if (/not authori[sz]ed|-1743/i.test(stderr)) return 'permission'
962  if (/timed out|-1712/i.test(stderr)) return 'timeout'
963  return 'other'
964}
965
966/** Turns an osascript failure into one line the band can show. */
967export function describeFailure(source: PlayerSource, stderr: string): string {
968  const app = PLAYERS[source].name
969  switch (classifyFailure(stderr)) {
970    case 'permission':
971      return `${app} is not answering. Allow your terminal to control ${app} under System Settings → Privacy & Security → Automation.`
972    case 'timeout':
973      return `${app} is slow to answer (busy, or waiting on a permission prompt); it will be asked again shortly.`
974    case 'other': {
975      const firstLine = stderr.trim().split('\n')[0] ?? ''
976      return `${app} could not be read${firstLine ? `: ${firstLine}` : '.'}`
977    }
978  }
979}
980
types/index.d.ts 199 lines
1/**
2 * The now-playing mod's state contract: what the band, footer and queue pane
3 * draw from.
4 */
5
6/** Which music player a snapshot came from. */
7export type PlayerSource = 'music' | 'spotify'
8
9/** Whether the player is playing or paused; a stopped player has no snapshot. */
10export type PlaybackState = 'playing' | 'paused'
11
12/** Repeat as both players spell it; Spotify has no `one`. */
13export type RepeatMode = 'off' | 'one' | 'all'
14
15/** One reading of a player: the track on, where it is, and the player's knobs. */
16export type NowPlaying = {
17  source: PlayerSource
18  state: PlaybackState
19  /** The player's own id for the track, so a change of track is detected. */
20  trackId: string
21  title: string
22  artist: string
23  album: string
24  positionSeconds: number
25  durationSeconds: number
26  /** 0 to 100. */
27  volume: number
28  shuffle: boolean
29  repeat: RepeatMode
30  /** A link to share (Spotify), or null where the player gives none. */
31  shareUrl: string | null
32  /** Where the cover can be downloaded from (Spotify), or null. */
33  artworkUrl: string | null
34  /** `$.clock.now()` when the reading was taken, in milliseconds. */
35  fetchedAt: number
36}
37
38/** The band's view of the world: the track to show, or why there is none. */
39export type PlayerStatus = {
40  current: NowPlaying | null
41  /** A reason the player could not be read (a permission to grant), or null. */
42  failure: string | null
43}
44
45/** A small picture as `0xRRGGBB` pixels, row-major from the top. */
46export type Thumbnail = {
47  width: number
48  height: number
49  pixels: number[]
50}
51
52/** A cover: a PNG on disk for terminals that draw pictures, and a small picture for the rest. */
53export type Artwork = {
54  trackId: string
55  path: string
56  /** Changes with each file written, so a redraw reads the new picture. */
57  generation: number
58  /**
59   * The cover shrunk to a few pixels, folded into half-block cells at whatever
60   * size a site draws it, where no picture can be drawn; null where one can.
61   */
62  thumbnail: Thumbnail | null
63  /**
64   * The cover as a small JPEG, base64, for surfaces that draw it inside an
65   * `Svg` (the desktop app); null where no such surface is attached.
66   */
67  jpeg: string | null
68  /** The cover's own colour, picked from its pixels, that the band is drawn in; null for a grey cover. */
69  accent: string | null
70}
71
72export type QueueEntry = {
73  /** The track's position in the current playlist, from 1. */
74  index: number
75  title: string
76  artist: string
77  album: string
78  /** Music's persistent ID, matched against the track on and the covers. */
79  id: string
80}
81
82/** What the queue pane lists: Music's current playlist around the track on. */
83export type Queue = {
84  source: PlayerSource
85  trackId: string
86  /** The playlist position of the track on, so a song listed twice marks the right row. */
87  currentIndex: number
88  playlistName: string
89  /** True when the playlist on is the one this mod adds tracks to. */
90  isModPlaylist: boolean
91  /** Why the list is empty when it is, in a line the pane shows; null with entries. */
92  note: string | null
93  entries: QueueEntry[]
94}
95
96/** One track found: in the Music library (addable) or in the Apple Music catalogue (openable). */
97export type SearchResult = {
98  /** Music's persistent ID for a library track; Apple's track id for a catalogue one. */
99  id: string
100  kind: 'library' | 'catalogue'
101  title: string
102  artist: string
103  album: string
104  /** A `music://` link that opens the track in Music; null for a library track. */
105  url: string | null
106}
107
108/** The last search typed into the pane, and what it found in the library and the catalogue. */
109export type LibrarySearch = {
110  query: string
111  /** Tracks in the library, ready to add. */
112  results: SearchResult[]
113  /** Tracks on Apple Music that the library lacks. */
114  catalogue: SearchResult[]
115  /** A line to show instead of results (nothing found, Music off), or null. */
116  note: string | null
117}
118
119/** One listen, as the history keeps it across sessions. */
120export type HistoryEntry = {
121  id: string
122  title: string
123  artist: string
124  album: string
125  source: PlayerSource
126  /** When the track started, in ms since the epoch. */
127  at: number
128}
129
130/** The lyrics pane's content: the track on, its lyrics, or why there are none. */
131export type LyricsView = {
132  id: string
133  title: string
134  artist: string
135  text: string
136  note: string | null
137}
138
139/** The playlist this mod adds tracks to, as last counted. */
140export type ModPlaylist = {
141  name: string
142  count: number
143  /** The last tracks of the playlist, newest at the end; what the pane lists. */
144  entries: QueueEntry[]
145}
146
147declare module 'claude-code' {
148  /** The tools this mod registers for the model, so their calls are typed. */
149  interface McpToolInputs {
150    'mcp__now-playing__search_library': {
151      query?: string
152      limit?: number
153      scope?: 'both' | 'library' | 'catalogue'
154      genre?: string
155      artist?: string
156      album?: string
157      title?: string
158      yearFrom?: number
159      yearTo?: number
160      minStars?: number
161      favourite?: boolean
162      minPlays?: number
163      maxPlays?: number
164      notPlayedForDays?: number
165      sort?: 'random' | 'leastPlayed' | 'mostPlayed' | 'newest' | 'oldest' | 'topRated' | 'title'
166    }
167    'mcp__now-playing__add_tracks': { tracks?: string[]; ids?: string[]; play?: boolean }
168    'mcp__now-playing__remove_tracks': { ids: string[] }
169    'mcp__now-playing__clear_playlist': Record<string, never>
170    'mcp__now-playing__control_player': {
171      action: 'play' | 'pause' | 'toggle' | 'next' | 'previous' | 'volume' | 'mute' | 'shuffle' | 'repeat' | 'playlist'
172      volume?: number
173      nudge?: 'up' | 'down'
174    }
175    'mcp__now-playing__now_playing': { upNext?: number; lyrics?: boolean }
176    'mcp__now-playing__listening_history': { limit?: number }
177    'mcp__now-playing__open_in_music': { url: string }
178    'mcp__now-playing__show_now_playing': { shown?: boolean }
179  }
180
181  interface PluginState {
182    'now-playing': {
183      status: PlayerStatus
184      isHidden: boolean | null
185      /** Counts the seconds while a track plays, so the clocks move between polls. */
186      tick: number
187      artwork: Artwork | null
188      queue: Queue | null
189      /** Covers of the queue's tracks, by persistent ID, as they arrive. */
190      queueCovers: Record<string, Artwork>
191      search: LibrarySearch | null
192      lyrics: LyricsView | null
193      modPlaylist: ModPlaylist | null
194      /** The volume before a mute, to restore on the next; null while not muted. */
195      mutedVolume: number | null
196    }
197  }
198}
199