agentvibes 4.6.8 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/.agentvibes/bmad-voice-map.json +104 -0
  2. package/.agentvibes/config.json +13 -12
  3. package/.agentvibes/copilot-sessions.log +4 -0
  4. package/.claude/audio/tracks/README.md +51 -52
  5. package/.claude/config/audio-effects-bmad.cfg +50 -0
  6. package/.claude/config/audio-effects.cfg +4 -4
  7. package/.claude/config/background-music-enabled.txt +1 -0
  8. package/.claude/config/personality.txt +1 -0
  9. package/.claude/hooks/play-tts-piper.sh +3 -1
  10. package/.claude/hooks/play-tts.sh +373 -301
  11. package/.claude/hooks/session-start-tts.sh +81 -81
  12. package/.claude/hooks-windows/audio-processor.ps1 +181 -0
  13. package/.claude/hooks-windows/play-tts-piper.ps1 +259 -245
  14. package/.claude/hooks-windows/play-tts.ps1 +101 -9
  15. package/.claude/hooks-windows/session-start-tts.ps1 +114 -114
  16. package/README.md +98 -6
  17. package/RELEASE_NOTES.md +35 -0
  18. package/bin/bmad-speak.js +16 -8
  19. package/mcp-server/server.py +15 -8
  20. package/package.json +1 -1
  21. package/src/console/app.js +899 -897
  22. package/src/console/footer-config.js +50 -50
  23. package/src/console/navigation.js +65 -65
  24. package/src/console/tabs/agents-tab.js +1896 -1886
  25. package/src/console/tabs/music-tab.js +1046 -1039
  26. package/src/console/tabs/placeholder-tab.js +81 -80
  27. package/src/console/tabs/settings-tab.js +939 -3988
  28. package/src/console/tabs/setup-tab.js +1811 -0
  29. package/src/console/tabs/voices-tab.js +1720 -1714
  30. package/src/installer.js +6147 -6092
  31. package/src/services/llm-provider-service.js +407 -0
  32. package/src/services/navigation-service.js +123 -123
  33. package/src/services/tts-engine-service.js +69 -0
  34. package/.claude/audio/tracks/dreamy_house_loop.mp3 +0 -0
  35. package/src/console/tabs/install-tab.js +0 -1081
@@ -1,1039 +1,1046 @@
1
- /**
2
- * AgentVibes TUI Console — Music Tab
3
- * Epic 9: Stories 9.1-9.3
4
- *
5
- * Implements the Tab Component Contract:
6
- * createMusicTab(screen, services) → { box, show, hide, onFocus, onBlur, getFooterText, getFooterColor }
7
- *
8
- * Features: dynamic track library from .claude/audio/tracks/, favorites (★), active track (▶),
9
- * toggle music on/off, favorites filter, preview playback on Enter/Space (toggle).
10
- */
11
-
12
- import fs from 'node:fs';
13
- import path from 'node:path';
14
- import os from 'node:os';
15
- import { fileURLToPath } from 'node:url';
16
- import { spawn } from 'node:child_process';
17
- import { buildAudioEnv, detectMp3Player } from '../audio-env.js';
18
- import { t } from '../../i18n/strings.js';
19
-
20
- // Package-relative tracks dir — used as fallback when cwd has no .claude/audio/tracks/
21
- const _PKG_TRACKS_DIR = path.resolve(
22
- path.dirname(fileURLToPath(import.meta.url)),
23
- '..', '..', '..', '.claude', 'audio', 'tracks'
24
- );
25
-
26
- const IS_TEST = process.env.AGENTVIBES_TEST_MODE === 'true';
27
-
28
- let blessed;
29
- if (!IS_TEST) {
30
- const { default: b } = await import('blessed');
31
- blessed = b;
32
- }
33
-
34
- // ---------------------------------------------------------------------------
35
-
36
- const COLORS = {
37
- contentBg: '#0a0e1a',
38
- sectionHdr: '#f06292', // Light magenta — section headers for Music tab
39
- labelFg: '#e3f2fd',
40
- valueFg: '#f06292', // Light magenta — brand color
41
- activeFg: '#69f0ae', // Green — active/playing track
42
- favoriteFg: '#ffff00', // Yellow — favorite star
43
- btnDefault: '#880e4f', // Dark magenta — Music tab buttons
44
- btnFocus: '#2e7d32', // Green — focused/selected
45
- btnFocusFg: '#ffffff',
46
- btnPress: '#ff00ff',
47
- borderFg: '#f06292', // Light magenta — border
48
- footerBg: '#880e4f', // Dark magenta — Music tab footer
49
- noticeFg: '#90a4ae',
50
- dimFg: '#455a64',
51
- playingFg: 'bright-cyan', // Cyan — currently previewing track indicator
52
- };
53
-
54
- const FOOTER_TEXT = '[↑↓/jk] Navigate [Space] Preview [Enter] Select [M] Toggle [*] Favorite [F] Filter [Q] Quit';
55
-
56
- // ---------------------------------------------------------------------------
57
- // Static catalog — correct real filenames; Soft Flamenco kept first for compat.
58
- // At runtime the UI scans .claude/audio/tracks/ dynamically so new tracks appear.
59
-
60
- // Full display names per track — emoji + label. Single-codepoint emoji only (no \uFE0F
61
- // variation selectors) so blessed renders them cleanly in list widgets.
62
- const TRACK_DISPLAY = Object.freeze({
63
- 'agentvibes_soft_flamenco_loop.mp3': '🎻 Soft Flamenco',
64
- 'agent_vibes_arabic_v2_loop.mp3': '🎵 Arabic Oud',
65
- 'agent_vibes_bachata_v1_loop.mp3': '🎺 Bachata',
66
- 'agent_vibes_bossa_nova_v2_loop.mp3': '🌸 Bossa Nova',
67
- 'agent_vibes_celtic_harp_v1_loop.mp3': '🎶 Celtic Harp',
68
- 'agent_vibes_chillwave_v2_loop.mp3': '🌊 Chillwave',
69
- 'agent_vibes_cumbia_v1_loop.mp3': '🎸 Cumbia',
70
- 'agent_vibes_dark_chill_step_loop.mp3': '🌙 Dark Chill Step',
71
- 'agent_vibes_ganawa_ambient_v2_loop.mp3': '🪘 Gnawa Ambient',
72
- 'agent_vibes_goa_trance_v2_loop.mp3': '🌀 Goa Trance',
73
- 'agent_vibes_harpsichord_v2_loop.mp3': '🎼 Harpsichord',
74
- 'agent_vibes_hawaiian_slack_key_guitar_v2_loop.mp3': '🌺 Hawaiian Slack Key Guitar',
75
- 'agent_vibes_japanese_city_pop_v1_loop.mp3': '🌆 Japanese City Pop',
76
- 'agent_vibes_salsa_v2_loop.mp3': '💃 Salsa',
77
- 'agent_vibes_tabla_dream_pop_v1_loop.mp3': '🥁 Tabla Dream Pop',
78
- });
79
-
80
- const BUILT_IN_TRACK_CATALOG = Object.freeze([
81
- { id: 'agentvibes_soft_flamenco_loop.mp3', label: '🎻 Soft Flamenco' },
82
- { id: 'agent_vibes_arabic_v2_loop.mp3', label: '🎵 Arabic Oud' },
83
- { id: 'agent_vibes_bachata_v1_loop.mp3', label: '🎺 Bachata' },
84
- { id: 'agent_vibes_bossa_nova_v2_loop.mp3', label: '🌸 Bossa Nova' },
85
- { id: 'agent_vibes_celtic_harp_v1_loop.mp3', label: '🎶 Celtic Harp' },
86
- { id: 'agent_vibes_chillwave_v2_loop.mp3', label: '🌊 Chillwave' },
87
- { id: 'agent_vibes_cumbia_v1_loop.mp3', label: '🎸 Cumbia' },
88
- { id: 'agent_vibes_dark_chill_step_loop.mp3', label: '🌙 Dark Chill Step' },
89
- { id: 'agent_vibes_ganawa_ambient_v2_loop.mp3', label: '🪘 Gnawa Ambient' },
90
- { id: 'agent_vibes_goa_trance_v2_loop.mp3', label: '🌀 Goa Trance' },
91
- { id: 'agent_vibes_harpsichord_v2_loop.mp3', label: '🎼 Harpsichord' },
92
- { id: 'agent_vibes_hawaiian_slack_key_guitar_v2_loop.mp3', label: '🌺 Hawaiian Slack Key Guitar' },
93
- { id: 'agent_vibes_japanese_city_pop_v1_loop.mp3', label: '🌆 Japanese City Pop' },
94
- { id: 'agent_vibes_salsa_v2_loop.mp3', label: '💃 Salsa' },
95
- { id: 'agent_vibes_tabla_dream_pop_v1_loop.mp3', label: '🥁 Tabla Dream Pop' },
96
- ]);
97
-
98
- // ---------------------------------------------------------------------------
99
- // Exported pure helpers (testable without blessed)
100
-
101
- /**
102
- * Return the built-in track catalog (static, predictable for tests).
103
- * @returns {{ id: string, label: string }[]}
104
- */
105
- export function getBuiltInTracks() {
106
- return [...BUILT_IN_TRACK_CATALOG];
107
- }
108
-
109
- /**
110
- * Generate a pretty label from a track filename.
111
- * Returns the canonical display name (with emoji) for known tracks.
112
- * For unknown tracks, strips agent_vibes_/agentvibes_ prefix and _loop/_vN suffixes,
113
- * then title-cases the result.
114
- *
115
- * @param {string} filename
116
- * @returns {string}
117
- */
118
- export function formatTrackLabel(filename) {
119
- if (TRACK_DISPLAY[filename]) return TRACK_DISPLAY[filename];
120
- const label = filename
121
- .replace(/\.mp3$/i, '')
122
- .replace(/^agent_vibes_/i, '')
123
- .replace(/^agentvibes_/i, '')
124
- .replace(/_loop$/i, '')
125
- .replace(/_v\d+$/i, '')
126
- .replace(/_/g, ' ')
127
- .replace(/\b\w/g, c => c.toUpperCase())
128
- .trim();
129
- return label || filename;
130
- }
131
-
132
- /**
133
- * Format music enabled state as readable string.
134
- * @param {boolean|undefined} enabled
135
- * @returns {string}
136
- */
137
- export function formatMusicStatus(enabled) {
138
- return enabled ? 'Enabled' : 'Disabled';
139
- }
140
-
141
- // ---------------------------------------------------------------------------
142
- // Test stub
143
-
144
- function createTestStub() {
145
- return {
146
- box: {},
147
- show: () => {},
148
- hide: () => {},
149
- onFocus: () => {},
150
- onBlur: () => {},
151
- getFooterText: () => FOOTER_TEXT,
152
- getFooterColor: () => COLORS.footerBg,
153
- };
154
- }
155
-
156
- // ---------------------------------------------------------------------------
157
- // Helpers (used inside createMusicTab)
158
-
159
- /**
160
- * Resolve the tracks directory for the running project.
161
- * Uses process.cwd() because the TUI always runs from the project root
162
- * and this function is called both internally and from exported helpers
163
- * that lack configService context.
164
- * @returns {string}
165
- */
166
- function _getTracksDir() {
167
- const cwdTracks = path.join(process.cwd(), '.claude', 'audio', 'tracks');
168
- // Fall back to package-bundled tracks if cwd doesn't have any
169
- return fs.existsSync(cwdTracks) ? cwdTracks : _PKG_TRACKS_DIR;
170
- }
171
-
172
- /**
173
- * Scan .claude/audio/tracks/ for .mp3 files.
174
- * Falls back to the static catalog if the directory is absent.
175
- *
176
- * @returns {{ id: string, label: string, isBuiltIn: boolean }[]}
177
- */
178
- export function scanTracks() {
179
- const tracksDir = _getTracksDir();
180
- try {
181
- const files = fs.readdirSync(tracksDir);
182
- const builtInIds = new Set(BUILT_IN_TRACK_CATALOG.map(t => t.id));
183
- return files
184
- .filter(f => /\.mp3$/i.test(f))
185
- .sort()
186
- .map(f => ({ id: f, label: formatTrackLabel(f), isBuiltIn: builtInIds.has(f) }));
187
- } catch {
188
- // Directory not found or unreadable — use the static catalog
189
- return BUILT_IN_TRACK_CATALOG.map(t => ({ ...t, isBuiltIn: true }));
190
- }
191
- }
192
-
193
- /**
194
- * Get music config from configService.
195
- */
196
- function _getMusic(configService) {
197
- const cfg = configService.getConfig();
198
- // Use backgroundMusic (matches settings-tab); fall back to legacy 'music' key
199
- const music = cfg.backgroundMusic ?? cfg.music ?? {};
200
- return {
201
- enabled: music.enabled ?? false,
202
- track: music.track ?? BUILT_IN_TRACK_CATALOG[0].id,
203
- volume: music.volume ?? 20,
204
- };
205
- }
206
-
207
- /**
208
- * Update music config (merge, never overwrite).
209
- * Writes to 'backgroundMusic' key (shared with settings-tab).
210
- */
211
- function _setMusic(configService, update) {
212
- const current = _getMusic(configService);
213
- configService.set('backgroundMusic', { ...current, ...update });
214
- }
215
-
216
- /**
217
- * Patch the 'default' entry in audio-effects.cfg to use the given track.
218
- * play-tts-piper.sh reads the track from audio-effects.cfg (not from config.json),
219
- * so any track change must be reflected here to take effect at runtime.
220
- * Safe to call with invalid/missing tracks — non-fatal on failure.
221
- * @param {string} track - Filename like "agent_vibes_salsa_v2_loop.mp3"
222
- */
223
- export function applyTrackToAudioEffects(track) {
224
- if (!track || /[|/\\]/.test(track)) return;
225
- const cfgFile = path.join(process.cwd(), '.claude', 'config', 'audio-effects.cfg');
226
- try {
227
- let content = fs.readFileSync(cfgFile, 'utf-8');
228
- content = content.replace(
229
- /^default\|([^|]*)\|([^|]*)\|(.*)$/m,
230
- (match, g1, g2, g3) => `default|${g1}|${track}|${g3}`,
231
- );
232
- fs.writeFileSync(cfgFile, content, 'utf-8');
233
- } catch { /* file may not exist — non-fatal */ }
234
- }
235
-
236
- /**
237
- * Get favorites array from config.musicFavorites.
238
- */
239
- export function getMusicFavorites(configService) {
240
- const favs = configService.getConfig().musicFavorites;
241
- return Array.isArray(favs) ? favs : [];
242
- }
243
-
244
- /**
245
- * Toggle a track in the favorites list.
246
- */
247
- export function toggleMusicFavorite(configService, trackId) {
248
- const favs = getMusicFavorites(configService);
249
- const idx = favs.indexOf(trackId);
250
- if (idx >= 0) {
251
- favs.splice(idx, 1);
252
- } else {
253
- favs.push(trackId);
254
- }
255
- configService.set('musicFavorites', favs);
256
- }
257
-
258
- /**
259
- * Get custom tracks from config.
260
- */
261
- function _getCustomTracks(configService) {
262
- const custom = configService.getConfig().customTracks;
263
- return Array.isArray(custom) ? custom : [];
264
- }
265
-
266
- // ---------------------------------------------------------------------------
267
-
268
- /**
269
- * Create the Music tab component.
270
- *
271
- * @param {object} screen - Blessed screen instance (or test stub)
272
- * @param {object} services
273
- * @param {import('../../services/config-service.js').ConfigService} services.configService
274
- * @returns {{ box, show, hide, onFocus, onBlur, getFooterText, getFooterColor }}
275
- */
276
- export function createMusicTab(screen, services) {
277
- if (IS_TEST) return createTestStub();
278
-
279
- const { configService, focusMainTabBar, updateHeaderStatus, languageService } = services;
280
- const _tl = (key) => languageService ? languageService.t(key) : t('en', key);
281
-
282
- // -------------------------------------------------------------------------
283
- // Container
284
-
285
- const box = blessed.box({
286
- parent: screen,
287
- top: 5,
288
- left: 0,
289
- width: '100%',
290
- bottom: 2,
291
- hidden: true,
292
- style: { fg: COLORS.labelFg, bg: COLORS.contentBg },
293
- border: { type: 'line' },
294
- borderStyle: { fg: COLORS.borderFg },
295
- });
296
-
297
- // -------------------------------------------------------------------------
298
- // Section headers
299
-
300
- const builtInHdr = blessed.text({
301
- parent: box,
302
- top: 1,
303
- left: 2,
304
- content: `{${COLORS.sectionHdr}-fg}${_tl('musicBuiltInHeader')}${'─'.repeat(48)}{/${COLORS.sectionHdr}-fg}`,
305
- tags: true,
306
- style: { bg: COLORS.contentBg },
307
- });
308
-
309
- // Currently selected track indicator (updated by refreshDisplay)
310
- const activeTrackText = blessed.text({
311
- parent: box,
312
- top: 1,
313
- right: 4,
314
- shrink: true,
315
- tags: true,
316
- content: '',
317
- style: { bg: COLORS.contentBg },
318
- });
319
-
320
- // -------------------------------------------------------------------------
321
- // Track list
322
-
323
- const trackList = blessed.list({
324
- parent: box,
325
- top: 3,
326
- left: 2,
327
- width: '96%',
328
- height: '55%',
329
- keys: true,
330
- vi: true,
331
- mouse: true,
332
- tags: true,
333
- border: { type: 'line' },
334
- scrollbar: { ch: '│', style: { fg: COLORS.sectionHdr } },
335
- style: {
336
- fg: COLORS.labelFg,
337
- bg: COLORS.contentBg,
338
- border: { fg: COLORS.borderFg },
339
- selected: { bg: '#3e2000', fg: COLORS.activeFg, bold: true },
340
- item: { fg: COLORS.labelFg },
341
- },
342
- });
343
-
344
- // -------------------------------------------------------------------------
345
- // Status panel
346
-
347
- const musicStatusHdr = blessed.text({
348
- parent: box,
349
- top: '64%',
350
- left: 2,
351
- content: `{${COLORS.sectionHdr}-fg}${_tl('musicStatusHeader')}${'─'.repeat(52)}{/${COLORS.sectionHdr}-fg}`,
352
- tags: true,
353
- style: { bg: COLORS.contentBg },
354
- });
355
-
356
- const statusLine = blessed.text({
357
- parent: box,
358
- top: '69%',
359
- left: 2,
360
- tags: true,
361
- content: '',
362
- style: { fg: COLORS.labelFg, bg: COLORS.contentBg },
363
- });
364
-
365
- const previewLine = blessed.text({
366
- parent: box,
367
- top: '74%',
368
- left: 2,
369
- tags: true,
370
- content: '',
371
- style: { fg: COLORS.playingFg, bg: COLORS.contentBg },
372
- });
373
-
374
- // -------------------------------------------------------------------------
375
- // Buttons
376
-
377
- function _createBtn(label, onClick) {
378
- const btn = blessed.button({
379
- parent: box,
380
- content: label,
381
- mouse: true,
382
- keys: true,
383
- shrink: true,
384
- padding: { left: 1, right: 1 },
385
- style: {
386
- bg: COLORS.btnDefault,
387
- fg: 'white',
388
- focus: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
389
- hover: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
390
- },
391
- });
392
- btn.on('focus', () => {
393
- btn.style.bg = COLORS.btnFocus;
394
- btn.style.fg = COLORS.btnFocusFg;
395
- const raw = btn.content.replace(/[►◄]/g, '').trim();
396
- btn.setContent(`►${raw}◄`);
397
- screen.render();
398
- });
399
- btn.on('blur', () => {
400
- btn.style.bg = COLORS.btnDefault;
401
- btn.style.fg = 'white';
402
- const raw = btn.content.replace(/[►◄]/g, '').trim();
403
- btn.setContent(raw);
404
- screen.render();
405
- });
406
- btn.key(['enter', 'space'], () => {
407
- btn.style.bg = COLORS.btnPress;
408
- screen.render();
409
- setTimeout(() => {
410
- btn.style.bg = COLORS.btnDefault;
411
- screen.render();
412
- onClick();
413
- }, 150);
414
- });
415
- btn.on('click', () => btn.press());
416
- btn.on('mouseover', () => btn.focus());
417
- return btn;
418
- }
419
-
420
- const toggleBtn = _createBtn(_tl('musicToggleBtn'), () => {
421
- const { enabled } = _getMusic(configService);
422
- _setMusic(configService, { enabled: !enabled });
423
- refreshDisplay();
424
- });
425
- toggleBtn.bottom = 4;
426
- toggleBtn.left = 4;
427
-
428
- const addCustomTrackBtn = _createBtn(_tl('musicAddCustomBtn'), () => {
429
- const modal = blessed.box({
430
- parent: screen,
431
- top: 'center',
432
- left: 'center',
433
- width: 66,
434
- height: 11,
435
- border: { type: 'line' },
436
- tags: true,
437
- label: ` {${COLORS.activeFg}-fg}Add Custom Background Track{/${COLORS.activeFg}-fg} `,
438
- style: { border: { fg: COLORS.borderFg }, bg: COLORS.contentBg },
439
- content: [
440
- '',
441
- ` {${COLORS.labelFg}-fg}To add a custom track:{/${COLORS.labelFg}-fg}`,
442
- '',
443
- ` {${COLORS.valueFg}-fg}1.{/${COLORS.valueFg}-fg} Place an MP3/OGG/WAV file in:`,
444
- ` {${COLORS.noticeFg}-fg}.claude/audio/tracks/{/${COLORS.noticeFg}-fg}`,
445
- '',
446
- ` {${COLORS.valueFg}-fg}2.{/${COLORS.valueFg}-fg} Or run: {${COLORS.noticeFg}-fg}/agent-vibes:background-music{/${COLORS.noticeFg}-fg}`,
447
- '',
448
- ` {${COLORS.dimFg}-fg}[Esc / Enter] Close{/${COLORS.dimFg}-fg}`,
449
- ].join('\n'),
450
- });
451
- modal.key(['escape', 'enter', 'q'], () => { modal.destroy(); trackList.focus(); screen.render(); });
452
- modal.setFront();
453
- modal.focus();
454
- screen.render();
455
- });
456
- addCustomTrackBtn.bottom = 4;
457
- addCustomTrackBtn.left = 26;
458
-
459
- // -------------------------------------------------------------------------
460
- // Hint text shown in previewLine when the list has focus and nothing is playing.
461
- // Getter functions so they re-translate when language changes.
462
- const _hintText = () => `{${COLORS.dimFg}-fg}${_tl('musicHintText')}{/${COLORS.dimFg}-fg}`;
463
- const _rowHint = () => ` {bright-black-fg}${_tl('musicRowHint')}{/bright-black-fg}`;
464
- let _listFocused = false;
465
-
466
- // Inline selection hint appended to the currently highlighted track row.
467
- // _hintBase stores the item's clean content (no hint, no █) so we never need
468
- // a sentinel character — PUA chars like U+E000 render as Nerd Font icons.
469
- let _hintIdx = -1;
470
- let _hintBase = ''; // content of items[_hintIdx] before hint was appended
471
- let _refreshing = false;
472
-
473
- // Known limitation: _updateHint and _tlTick (blink) can interleave,
474
- // causing brief visual glitches. The _refreshing guard prevents the worst
475
- // cases but is not a complete fix. Acceptable for a TUI animation.
476
- function _updateHint(idx) {
477
- const items = trackList.items;
478
- // Restore previously hinted row using its saved base content
479
- if (_hintIdx >= 0 && _hintIdx !== idx && items[_hintIdx]) {
480
- const hadBlink = (items[_hintIdx].content ?? '').endsWith(' █');
481
- items[_hintIdx].setContent(hadBlink ? _hintBase + ' █' : _hintBase);
482
- }
483
- // Add hint to the new row, saving its clean base first
484
- if (idx >= 0 && items[idx]) {
485
- let c = items[idx].content ?? '';
486
- const hasBlink = c.endsWith(' ');
487
- if (hasBlink) c = c.slice(0, -2);
488
- _hintBase = c;
489
- items[idx].setContent(c + _rowHint() + (hasBlink ? ' █' : ''));
490
- } else {
491
- _hintBase = '';
492
- }
493
- _hintIdx = idx;
494
- }
495
-
496
- // -------------------------------------------------------------------------
497
- // Playback state
498
-
499
- let _playingProcess = null;
500
- let _playingTrackId = null;
501
-
502
- // Kill the entire process group so child audio processes (ffplay, play, mpg123) all die
503
- function _killPlayingProcess() {
504
- if (_playingProcess) {
505
- const _isWin = process.platform === 'win32' && !process.env.WSL_DISTRO_NAME;
506
- try {
507
- if (_isWin) {
508
- // Windows: kill the process tree via taskkill (process group kill doesn't work)
509
- spawn('taskkill', ['/F', '/T', '/PID', String(_playingProcess.pid)], {
510
- stdio: 'ignore', windowsHide: true,
511
- });
512
- } else {
513
- process.kill(-_playingProcess.pid, 'SIGTERM');
514
- }
515
- } catch (e) {
516
- if (e.code !== 'ESRCH') { /* ignore */ }
517
- }
518
- _playingProcess = null;
519
- }
520
- }
521
-
522
- const _spawnEnv = buildAudioEnv();
523
- const _detectedPlayer = detectMp3Player(_spawnEnv);
524
-
525
- process.on('exit', () => { _killPlayingProcess(); });
526
-
527
- /**
528
- * Preview a track by spawning an audio player.
529
- * Second call with the same trackId stops playback (toggle).
530
- */
531
- function _playTrack(trackId) {
532
- const tracksDir = _getTracksDir();
533
- const trackPath = path.resolve(tracksDir, trackId);
534
-
535
- // Guard: path must stay inside tracksDir
536
- const safeBase = path.resolve(tracksDir);
537
- if (!trackPath.startsWith(safeBase + path.sep) && trackPath !== safeBase) {
538
- return;
539
- }
540
-
541
- // Toggle: second press on the same track → stop
542
- if (_playingTrackId === trackId) {
543
- _killPlayingProcess();
544
- _playingTrackId = null;
545
- previewLine.setContent(_listFocused ? _hintText() : '');
546
- screen.render();
547
- return;
548
- }
549
-
550
- // Kill any previously playing track
551
- _killPlayingProcess();
552
- _playingTrackId = null;
553
-
554
- if (!_detectedPlayer) {
555
- const installHint = process.platform === 'win32'
556
- ? 'No MP3 player found. Install ffmpeg: winget install ffmpeg'
557
- : 'No MP3 player found. Install ffmpeg: sudo apt install ffmpeg';
558
- previewLine.setContent(`{red-fg}${installHint}{/red-fg}`);
559
- screen.render();
560
- setTimeout(() => { previewLine.setContent(_listFocused ? _hintText() : ''); screen.render(); }, 5000);
561
- return;
562
- }
563
-
564
- const _isWin = process.platform === 'win32' && !process.env.WSL_DISTRO_NAME;
565
- // Spawn the detected player directly (no sh -c chain — avoids VLC/cvlc stderr issues)
566
- _playingProcess = spawn(_detectedPlayer.bin, _detectedPlayer.args(trackPath), {
567
- stdio: 'ignore', detached: !_isWin, windowsHide: true, env: _spawnEnv,
568
- });
569
- _playingTrackId = trackId;
570
-
571
- const label = _allTracks.find(t => t.id === trackId)?.label ?? formatTrackLabel(trackId);
572
- previewLine.setContent(`{${COLORS.playingFg}-fg}♪ Previewing: ${label} (Space again to stop){/${COLORS.playingFg}-fg}`);
573
- screen.render();
574
-
575
- _playingProcess.on('exit', () => {
576
- if (_playingTrackId === trackId) {
577
- _playingTrackId = null;
578
- _playingProcess = null;
579
- previewLine.setContent(_listFocused ? _hintText() : '');
580
- refreshDisplay(); // clears (playing) label
581
- }
582
- });
583
-
584
- _playingProcess.on('error', () => {
585
- if (_playingTrackId === trackId) {
586
- _killPlayingProcess();
587
- _playingTrackId = null;
588
- _playingProcess = null;
589
- previewLine.setContent(_listFocused ? _hintText() : '');
590
- }
591
- });
592
- }
593
-
594
- // -------------------------------------------------------------------------
595
- // Display state
596
-
597
- let _showFavoritesOnly = false;
598
- let _allTracks = [];
599
-
600
- function _buildAllTracks() {
601
- const scanned = scanTracks();
602
- const scannedIds = new Set(scanned.map(t => t.id));
603
- // Append custom tracks not already present from disk scan
604
- const custom = _getCustomTracks(configService)
605
- .filter(id => !scannedIds.has(id))
606
- .map(id => ({ id, label: formatTrackLabel(id), isBuiltIn: false }));
607
- return [...scanned, ...custom];
608
- }
609
-
610
- function _getVisibleTracks() {
611
- if (!_showFavoritesOnly) return _allTracks;
612
- const favs = getMusicFavorites(configService);
613
- return _allTracks.filter(t => favs.includes(t.id));
614
- }
615
-
616
- function _getSelectedTrackId() {
617
- const visible = _getVisibleTracks();
618
- const entry = visible[trackList.selected];
619
- return entry ? entry.id : null;
620
- }
621
-
622
- function _buildListItems(tracks, activeTrackId, favorites) {
623
- return tracks.map(t => {
624
- const isFav = favorites.includes(t.id);
625
- const isActive = t.id === activeTrackId;
626
- const isPrev = t.id === _playingTrackId;
627
- const star = isFav ? '★' : ' ';
628
- const dot = isPrev ? '' : (isActive ? '{green-fg}✓{/green-fg}' : ' ');
629
- const tag = t.isBuiltIn ? '' : ' [custom]';
630
- return ` ${star}${dot} ${t.label}${tag}${isPrev ? ' (playing)' : ''}`;
631
- });
632
- }
633
-
634
- function refreshDisplay() {
635
- _refreshing = true;
636
- const savedIdx = trackList.selected ?? 0;
637
-
638
- _allTracks = _buildAllTracks();
639
- const { enabled, track: activeTrackId } = _getMusic(configService);
640
- const favorites = getMusicFavorites(configService);
641
- const visible = _getVisibleTracks();
642
- const items = _buildListItems(visible, activeTrackId, favorites);
643
-
644
- const activeTrack = _allTracks.find(t => t.id === activeTrackId);
645
- const activeLabel = (activeTrack?.label ?? formatTrackLabel(activeTrackId ?? '')) || 'None';
646
-
647
- trackList.setItems(items.length > 0 ? items : [' (no tracks match filter)']);
648
- // Restore selection (setItems resets to 0)
649
- const maxIdx = Math.max(0, (items.length > 0 ? items.length : 1) - 1);
650
- trackList.select(Math.min(savedIdx, maxIdx));
651
-
652
- // Re-apply inline hint if list is focused
653
- if (_listFocused) {
654
- _hintIdx = -1;
655
- _hintBase = '';
656
- _updateHint(trackList.selected ?? 0);
657
- }
658
-
659
- statusLine.setContent(
660
- ` ${_tl('musicStatusLabel')} ${formatMusicStatus(enabled)} | ${_tl('musicActiveTrack')} ${activeLabel} | ${_tl('musicFilterLabel')} ${_showFavoritesOnly ? _tl('musicFilterFavs') : _tl('musicFilterAll')}`
661
- );
662
-
663
- // Update "Currently Selected" header
664
- activeTrackText.setContent(`{${COLORS.activeFg}-fg}✓ ${activeLabel}{/${COLORS.activeFg}-fg}`);
665
-
666
- _refreshing = false;
667
- if (typeof updateHeaderStatus === 'function') updateHeaderStatus();
668
- screen.render();
669
- }
670
-
671
- // -------------------------------------------------------------------------
672
- // Key bindings on trackList
673
-
674
- // [Enter] → open save modal for selected track
675
- trackList.key(['enter'], () => {
676
- const trackId = _getSelectedTrackId();
677
- if (!trackId) return;
678
- const label = _allTracks.find(t => t.id === trackId)?.label ?? formatTrackLabel(trackId);
679
- _openSaveModal(trackId, label);
680
- });
681
-
682
- /**
683
- * Save-track modal: Save Locally | Save Globally & Locally | Cancel | Preview
684
- */
685
- function _openSaveModal(trackId, displayName) {
686
- const modal = blessed.box({
687
- parent: screen,
688
- top: 'center',
689
- left: 'center',
690
- width: 72,
691
- height: 8,
692
- border: { type: 'line' },
693
- tags: true,
694
- label: ` {${COLORS.activeFg}-fg}Set Background Track{/${COLORS.activeFg}-fg} `,
695
- style: { border: { fg: COLORS.btnFocus }, bg: COLORS.contentBg },
696
- });
697
-
698
- blessed.text({
699
- parent: modal,
700
- top: 1,
701
- left: 2,
702
- right: 2,
703
- content: `Set {${COLORS.valueFg}-fg}${displayName}{/${COLORS.valueFg}-fg} as your background track?`,
704
- tags: true,
705
- style: { bg: COLORS.contentBg },
706
- });
707
-
708
- const modalStatus = blessed.text({
709
- parent: modal,
710
- top: 3,
711
- left: 2,
712
- right: 2,
713
- tags: true,
714
- content: `{${COLORS.dimFg}-fg}Press Preview to audition this track{/${COLORS.dimFg}-fg}`,
715
- style: { bg: COLORS.contentBg },
716
- });
717
-
718
- function _close() {
719
- _killPlayingProcess();
720
- _playingTrackId = null;
721
- previewLine.setContent(_listFocused ? _hintText() : '');
722
- modal.destroy();
723
- trackList.focus();
724
- screen.render();
725
- }
726
-
727
- function _makeBtn(lbl, bg, left, top, onClick) {
728
- const btn = blessed.button({
729
- parent: modal,
730
- content: lbl,
731
- top,
732
- left,
733
- mouse: true,
734
- keys: true,
735
- shrink: true,
736
- padding: { left: 1, right: 1 },
737
- style: {
738
- bg,
739
- fg: 'white',
740
- focus: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
741
- hover: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
742
- },
743
- });
744
- btn.key(['enter', 'space'], () => { _close(); onClick(); });
745
- btn.on('click', () => btn.press());
746
- return btn;
747
- }
748
-
749
- function _saveLocally() {
750
- _setMusic(configService, { track: trackId });
751
- applyTrackToAudioEffects(trackId);
752
- refreshDisplay();
753
- _showTrackChangedNotice(displayName);
754
- }
755
-
756
- function _saveGlobally() {
757
- configService.setGlobal('backgroundMusic', { track: trackId });
758
- }
759
-
760
- const okLocalBtn = _makeBtn('Save Locally', COLORS.btnDefault, 2, 5, () => {
761
- _saveLocally();
762
- });
763
- const okGlobalBtn = _makeBtn('Save Globally & Locally', '#1565c0', 18, 5, () => {
764
- _saveLocally();
765
- _saveGlobally();
766
- });
767
- const cancelBtn = _makeBtn('Cancel', '#546e7a', 46, 5, () => {});
768
-
769
- // Preview button — does NOT close the modal; plays/stops the track inline
770
- const previewBtn = blessed.button({
771
- parent: modal,
772
- content: 'Preview',
773
- top: 5,
774
- left: 58,
775
- mouse: true,
776
- keys: true,
777
- shrink: true,
778
- padding: { left: 1, right: 1 },
779
- style: {
780
- bg: '#e65100',
781
- fg: 'white',
782
- focus: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
783
- hover: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
784
- },
785
- });
786
- previewBtn.key(['enter', 'space'], () => {
787
- const isPlaying = _playingTrackId === trackId;
788
- _playTrack(trackId);
789
- modalStatus.setContent(isPlaying
790
- ? `{${COLORS.dimFg}-fg}Stopped.{/${COLORS.dimFg}-fg}`
791
- : `{${COLORS.playingFg}-fg}♪ Playing: ${displayName}…{/${COLORS.playingFg}-fg}`
792
- );
793
- screen.render();
794
- });
795
- previewBtn.on('click', () => previewBtn.press());
796
-
797
- // Tab/arrow navigation: SaveLocal → SaveGlobal → Cancel → Preview → SaveLocal
798
- okLocalBtn.key(['tab', 'right'], () => { okGlobalBtn.focus(); screen.render(); });
799
- okGlobalBtn.key(['tab', 'right'], () => { cancelBtn.focus(); screen.render(); });
800
- cancelBtn.key(['tab', 'right'], () => { previewBtn.focus(); screen.render(); });
801
- previewBtn.key(['tab', 'right'], () => { okLocalBtn.focus(); screen.render(); });
802
- previewBtn.key(['left'], () => { cancelBtn.focus(); screen.render(); });
803
- cancelBtn.key(['left'], () => { okGlobalBtn.focus(); screen.render(); });
804
- okGlobalBtn.key(['left'], () => { okLocalBtn.focus(); screen.render(); });
805
- okLocalBtn.key(['left'], () => { previewBtn.focus(); screen.render(); });
806
-
807
- modal.key(['escape', 'q'], _close);
808
-
809
- modal.setFront();
810
- okLocalBtn.focus();
811
- screen.render();
812
- }
813
-
814
- function _showTrackChangedNotice(displayName) {
815
- const notice = blessed.box({
816
- parent: screen,
817
- top: 'center',
818
- left: 'center',
819
- width: 50,
820
- height: 5,
821
- border: { type: 'line' },
822
- tags: true,
823
- label: ` {${COLORS.activeFg}-fg}Done{/${COLORS.activeFg}-fg} `,
824
- style: { border: { fg: COLORS.btnFocus }, bg: COLORS.contentBg },
825
- content: `\n {${COLORS.activeFg}-fg}✓ Track set: ${displayName}{/${COLORS.activeFg}-fg}`,
826
- });
827
- notice.setFront();
828
- screen.render();
829
- let noticeDestroyed = false;
830
- setTimeout(() => { if (!noticeDestroyed) { notice.destroy(); noticeDestroyed = true; screen.render(); } }, 2000);
831
- }
832
-
833
- // [Space] → preview/stop track (toggle)
834
- trackList.key(['space'], () => {
835
- const trackId = _getSelectedTrackId();
836
- if (trackId) {
837
- _playTrack(trackId);
838
- refreshDisplay();
839
- }
840
- });
841
-
842
- // [m/M] → toggle music enabled in config
843
- trackList.key(['m', 'M'], () => {
844
- const { enabled } = _getMusic(configService);
845
- _setMusic(configService, { enabled: !enabled });
846
- refreshDisplay();
847
- });
848
-
849
- // [*] → toggle favorite
850
- trackList.key(['*'], () => {
851
- const trackId = _getSelectedTrackId();
852
- if (trackId) {
853
- toggleMusicFavorite(configService, trackId);
854
- refreshDisplay();
855
- }
856
- });
857
-
858
- // [f/F] → toggle favorites filter
859
- trackList.key(['f', 'F'], () => {
860
- _showFavoritesOnly = !_showFavoritesOnly;
861
- refreshDisplay();
862
- });
863
-
864
- // [↑] at top of list → jump to main header tab bar
865
- trackList.key(['up'], () => {
866
- if (trackList.selected === 0 && typeof focusMainTabBar === 'function') {
867
- focusMainTabBar();
868
- setTimeout(() => { trackList.select(0); screen.render(); }, 0);
869
- }
870
- });
871
-
872
- // Escape at the list level → return to header tab bar
873
- trackList.key(['escape'], () => {
874
- if (typeof focusMainTabBar === 'function') { focusMainTabBar(); screen.render(); }
875
- });
876
-
877
- // ↓ at the last item → descend into the button row (Toggle Music gets focus first)
878
- // Note: Tab is NOT used here — navigation.js registers screen.key(['tab']) to cycle tabs,
879
- // so element.key(['tab']) + screen.key(['tab']) both fire, causing a simultaneous tab-cycle.
880
- trackList.key(['down'], () => {
881
- const visible = _getVisibleTracks();
882
- if (trackList.selected >= visible.length - 1) {
883
- toggleBtn.focus();
884
- screen.render();
885
- }
886
- });
887
-
888
- // ←/→ navigate between the two buttons
889
- toggleBtn.key(['right'], () => { addCustomTrackBtn.focus(); screen.render(); });
890
- addCustomTrackBtn.key(['right'], () => { toggleBtn.focus(); screen.render(); });
891
- toggleBtn.key(['left'], () => { addCustomTrackBtn.focus(); screen.render(); });
892
- addCustomTrackBtn.key(['left'], () => { toggleBtn.focus(); screen.render(); });
893
-
894
- // ↑ or Escape from any button → back to track list
895
- toggleBtn.key(['up', 'escape'], () => { trackList.focus(); screen.render(); });
896
- addCustomTrackBtn.key(['up', 'escape'], () => { trackList.focus(); screen.render(); });
897
-
898
- // Blinking on selected row while list is focused
899
- let _tlBlink = { interval: null, on: false, sel: -1 };
900
- process.on('exit', () => { if (_tlBlink.interval) clearInterval(_tlBlink.interval); });
901
- function _tlTick() {
902
- _tlBlink.on = !_tlBlink.on;
903
- const items = trackList.items;
904
- const cur = trackList.selected ?? 0;
905
- if (_tlBlink.sel !== cur && _tlBlink.sel >= 0 && items[_tlBlink.sel]) {
906
- items[_tlBlink.sel].setContent((items[_tlBlink.sel].content ?? '').replace(/ █$/, ''));
907
- }
908
- _tlBlink.sel = cur;
909
- if (items[cur]) {
910
- const base = (items[cur].content ?? '').replace(/ █$/, '');
911
- items[cur].setContent(_tlBlink.on ? `${base} █` : base);
912
- }
913
- screen.render();
914
- }
915
- trackList.on('focus', () => {
916
- _listFocused = true;
917
- _tlBlink.on = true;
918
- _tlBlink.sel = trackList.selected ?? 0;
919
- _hintIdx = -1;
920
- _hintBase = '';
921
- _updateHint(_tlBlink.sel);
922
- const items = trackList.items;
923
- if (items[_tlBlink.sel]) items[_tlBlink.sel].setContent((items[_tlBlink.sel].content ?? '') + ' █');
924
- if (!_playingTrackId) previewLine.setContent(_hintText());
925
- screen.render();
926
- _tlBlink.interval = setInterval(_tlTick, 500);
927
- });
928
- trackList.on('blur', () => {
929
- _listFocused = false;
930
- if (!_playingTrackId) previewLine.setContent('');
931
- if (_tlBlink.interval) { clearInterval(_tlBlink.interval); _tlBlink.interval = null; }
932
- const items = trackList.items;
933
- const sel = trackList.selected ?? 0;
934
- if (items[sel]) {
935
- // Restore the hinted item to its clean base; for non-hinted items just strip █
936
- items[sel].setContent(sel === _hintIdx ? _hintBase : (items[sel].content ?? '').replace(/ █$/, ''));
937
- }
938
- if (_hintIdx >= 0 && _hintIdx !== sel && items[_hintIdx]) {
939
- items[_hintIdx].setContent(_hintBase);
940
- }
941
- _hintIdx = -1;
942
- _hintBase = '';
943
- screen.render();
944
- });
945
-
946
- // Refresh status text on cursor movement
947
- trackList.on('select item', () => {
948
- if (_refreshing) return;
949
- _updateHint(trackList.selected ?? 0);
950
- if (_tlBlink.interval) _tlTick(); // move █ to newly selected row
951
- const { enabled, track: activeTrackId } = _getMusic(configService);
952
- const activeTrack = _allTracks.find(t => t.id === activeTrackId);
953
- const activeLabel = (activeTrack?.label ?? formatTrackLabel(activeTrackId ?? '')) || 'None';
954
- statusLine.setContent(
955
- ` ${_tl('musicStatusLabel')} ${formatMusicStatus(enabled)} | ${_tl('musicActiveTrack')} ${activeLabel} | ${_tl('musicFilterLabel')} ${_showFavoritesOnly ? _tl('musicFilterFavs') : _tl('musicFilterAll')}`
956
- );
957
- screen.render();
958
- });
959
-
960
- // Type-to-jump: press a letter to jump to first track whose label starts with it
961
- const _trackJumpBlocked = new Set(['j', 'k', 'g', 'h', 'l', 'd', 'u', 'm', 'f']);
962
- trackList.on('keypress', (ch, key) => {
963
- if (!ch || key.ctrl || key.meta) return;
964
- const lower = ch.toLowerCase();
965
- if (!/^[a-z]$/.test(lower)) return;
966
- if (_trackJumpBlocked.has(lower)) return;
967
- const tracks = _getVisibleTracks();
968
- const count = tracks.length;
969
- if (count === 0) return;
970
- const start = trackList.selected ?? 0;
971
- for (let i = 1; i <= count; i++) {
972
- const idx = (start + i) % count;
973
- // Strip leading emoji/symbols to get first letter of track name
974
- const firstLetter = tracks[idx].label.replace(/^[^a-zA-Z]*/, '')[0]?.toLowerCase() ?? '';
975
- if (firstLetter === lower) {
976
- trackList.select(idx);
977
- screen.render();
978
- break;
979
- }
980
- }
981
- });
982
-
983
- // -------------------------------------------------------------------------
984
- // -------------------------------------------------------------------------
985
- // Language refresh
986
-
987
- function refreshMusicLabels() {
988
- builtInHdr.setContent(`{${COLORS.sectionHdr}-fg}${_tl('musicBuiltInHeader')}${'─'.repeat(48)}{/${COLORS.sectionHdr}-fg}`);
989
- musicStatusHdr.setContent(`{${COLORS.sectionHdr}-fg}${_tl('musicStatusHeader')}${'─'.repeat(52)}{/${COLORS.sectionHdr}-fg}`);
990
- toggleBtn.setContent(_tl('musicToggleBtn'));
991
- addCustomTrackBtn.setContent(_tl('musicAddCustomBtn'));
992
- refreshDisplay();
993
- }
994
-
995
- if (languageService) {
996
- languageService.onChange(() => { refreshMusicLabels(); screen.render(); });
997
- }
998
-
999
- // Tab Component Contract
1000
-
1001
- return {
1002
- box,
1003
-
1004
- show() {
1005
- box.show();
1006
- refreshDisplay();
1007
- screen.render();
1008
- },
1009
-
1010
- hide() {
1011
- // Stop any preview when leaving the tab
1012
- _killPlayingProcess();
1013
- _playingTrackId = null;
1014
- previewLine.setContent('');
1015
- box.hide();
1016
- screen.render();
1017
- },
1018
-
1019
- onFocus() {
1020
- trackList.focus();
1021
- screen.render();
1022
- },
1023
-
1024
- onBlur() {
1025
- // Stop preview when focus leaves Music tab
1026
- _killPlayingProcess();
1027
- _playingTrackId = null;
1028
- },
1029
-
1030
- getFooterText() {
1031
- return _tl('musicFooter');
1032
- },
1033
-
1034
- getFooterColor() {
1035
- return COLORS.footerBg;
1036
- },
1037
- };
1038
-
1039
- }
1
+ /**
2
+ * AgentVibes TUI Console — Music Tab
3
+ * Epic 9: Stories 9.1-9.3
4
+ *
5
+ * Implements the Tab Component Contract:
6
+ * createMusicTab(screen, services) → { box, show, hide, onFocus, onBlur, getFooterText, getFooterColor }
7
+ *
8
+ * Features: dynamic track library from .claude/audio/tracks/, favorites (★), active track (▶),
9
+ * toggle music on/off, favorites filter, preview playback on Enter/Space (toggle).
10
+ */
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import os from 'node:os';
15
+ import { fileURLToPath } from 'node:url';
16
+ import { spawn } from 'node:child_process';
17
+ import { buildAudioEnv, detectMp3Player } from '../audio-env.js';
18
+ import { t } from '../../i18n/strings.js';
19
+
20
+ // Package-relative tracks dir — used as fallback when cwd has no .claude/audio/tracks/
21
+ const _PKG_TRACKS_DIR = path.resolve(
22
+ path.dirname(fileURLToPath(import.meta.url)),
23
+ '..', '..', '..', '.claude', 'audio', 'tracks'
24
+ );
25
+
26
+ const IS_TEST = process.env.AGENTVIBES_TEST_MODE === 'true';
27
+
28
+ let blessed;
29
+ if (!IS_TEST) {
30
+ const { default: b } = await import('blessed');
31
+ blessed = b;
32
+ }
33
+
34
+ // ---------------------------------------------------------------------------
35
+
36
+ const COLORS = {
37
+ contentBg: '#0a0e1a',
38
+ sectionHdr: '#f06292', // Light magenta — section headers for Music tab
39
+ labelFg: '#e3f2fd',
40
+ valueFg: '#f06292', // Light magenta — brand color
41
+ activeFg: '#69f0ae', // Green — active/playing track
42
+ favoriteFg: '#ffff00', // Yellow — favorite star
43
+ btnDefault: '#880e4f', // Dark magenta — Music tab buttons
44
+ btnFocus: '#2e7d32', // Green — focused/selected
45
+ btnFocusFg: '#ffffff',
46
+ btnPress: '#ff00ff',
47
+ borderFg: '#f06292', // Light magenta — border
48
+ footerBg: '#880e4f', // Dark magenta — Music tab footer
49
+ noticeFg: '#90a4ae',
50
+ dimFg: '#455a64',
51
+ playingFg: 'bright-cyan', // Cyan — currently previewing track indicator
52
+ };
53
+
54
+ const FOOTER_TEXT = '[↑↓/jk] Navigate [Space] Preview [Enter] Select [M] Toggle [*] Favorite [F] Filter [Q] Quit';
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // Static catalog — correct real filenames; Soft Flamenco kept first for compat.
58
+ // At runtime the UI scans .claude/audio/tracks/ dynamically so new tracks appear.
59
+
60
+ // Full display names per track — emoji + label. Single-codepoint emoji only (no \uFE0F
61
+ // variation selectors) so blessed renders them cleanly in list widgets.
62
+ const TRACK_DISPLAY = Object.freeze({
63
+ 'agentvibes_soft_flamenco_loop.mp3': '🎻 Soft Flamenco',
64
+ 'agent_vibes_arabic_v2_loop.mp3': '🎵 Arabic Oud',
65
+ 'agent_vibes_bachata_v1_loop.mp3': '🎺 Bachata',
66
+ 'agent_vibes_bossa_nova_v2_loop.mp3': '🌸 Bossa Nova',
67
+ 'agent_vibes_celtic_harp_v1_loop.mp3': '🎶 Celtic Harp',
68
+ 'agent_vibes_chillwave_v2_loop.mp3': '🌊 Chillwave',
69
+ 'agent_vibes_cumbia_v1_loop.mp3': '🎸 Cumbia',
70
+ 'agent_vibes_dark_chill_step_loop.mp3': '🌙 Dark Chill Step',
71
+ 'agent_vibes_ganawa_ambient_v2_loop.mp3': '🪘 Gnawa Ambient',
72
+ 'agent_vibes_goa_trance_v2_loop.mp3': '🌀 Goa Trance',
73
+ 'agent_vibes_harpsichord_v2_loop.mp3': '🎼 Harpsichord',
74
+ 'agent_vibes_hawaiian_slack_key_guitar_v2_loop.mp3': '🌺 Hawaiian Slack Key Guitar',
75
+ 'agent_vibes_japanese_city_pop_v1_loop.mp3': '🌆 Japanese City Pop',
76
+ 'agent_vibes_salsa_v2_loop.mp3': '💃 Salsa',
77
+ 'agent_vibes_tabla_dream_pop_v1_loop.mp3': '🥁 Tabla Dream Pop',
78
+ });
79
+
80
+ const BUILT_IN_TRACK_CATALOG = Object.freeze([
81
+ { id: 'agentvibes_soft_flamenco_loop.mp3', label: '🎻 Soft Flamenco' },
82
+ { id: 'agent_vibes_arabic_v2_loop.mp3', label: '🎵 Arabic Oud' },
83
+ { id: 'agent_vibes_bachata_v1_loop.mp3', label: '🎺 Bachata' },
84
+ { id: 'agent_vibes_bossa_nova_v2_loop.mp3', label: '🌸 Bossa Nova' },
85
+ { id: 'agent_vibes_celtic_harp_v1_loop.mp3', label: '🎶 Celtic Harp' },
86
+ { id: 'agent_vibes_chillwave_v2_loop.mp3', label: '🌊 Chillwave' },
87
+ { id: 'agent_vibes_cumbia_v1_loop.mp3', label: '🎸 Cumbia' },
88
+ { id: 'agent_vibes_dark_chill_step_loop.mp3', label: '🌙 Dark Chill Step' },
89
+ { id: 'agent_vibes_ganawa_ambient_v2_loop.mp3', label: '🪘 Gnawa Ambient' },
90
+ { id: 'agent_vibes_goa_trance_v2_loop.mp3', label: '🌀 Goa Trance' },
91
+ { id: 'agent_vibes_harpsichord_v2_loop.mp3', label: '🎼 Harpsichord' },
92
+ { id: 'agent_vibes_hawaiian_slack_key_guitar_v2_loop.mp3', label: '🌺 Hawaiian Slack Key Guitar' },
93
+ { id: 'agent_vibes_japanese_city_pop_v1_loop.mp3', label: '🌆 Japanese City Pop' },
94
+ { id: 'agent_vibes_salsa_v2_loop.mp3', label: '💃 Salsa' },
95
+ { id: 'agent_vibes_tabla_dream_pop_v1_loop.mp3', label: '🥁 Tabla Dream Pop' },
96
+ ]);
97
+
98
+ // ---------------------------------------------------------------------------
99
+ // Exported pure helpers (testable without blessed)
100
+
101
+ /**
102
+ * Return the built-in track catalog (static, predictable for tests).
103
+ * @returns {{ id: string, label: string }[]}
104
+ */
105
+ export function getBuiltInTracks() {
106
+ return [...BUILT_IN_TRACK_CATALOG];
107
+ }
108
+
109
+ /**
110
+ * Generate a pretty label from a track filename.
111
+ * Returns the canonical display name (with emoji) for known tracks.
112
+ * For unknown tracks, strips agent_vibes_/agentvibes_ prefix and _loop/_vN suffixes,
113
+ * then title-cases the result.
114
+ *
115
+ * @param {string} filename
116
+ * @returns {string}
117
+ */
118
+ export function formatTrackLabel(filename) {
119
+ if (TRACK_DISPLAY[filename]) return TRACK_DISPLAY[filename];
120
+ const label = filename
121
+ .replace(/\.mp3$/i, '')
122
+ .replace(/^agent_vibes_/i, '')
123
+ .replace(/^agentvibes_/i, '')
124
+ .replace(/_loop$/i, '')
125
+ .replace(/_v\d+$/i, '')
126
+ .replace(/_/g, ' ')
127
+ .replace(/\b\w/g, c => c.toUpperCase())
128
+ .trim();
129
+ return label || filename;
130
+ }
131
+
132
+ /**
133
+ * Format music enabled state as readable string.
134
+ * @param {boolean|undefined} enabled
135
+ * @returns {string}
136
+ */
137
+ export function formatMusicStatus(enabled) {
138
+ return enabled ? 'Enabled' : 'Disabled';
139
+ }
140
+
141
+ // ---------------------------------------------------------------------------
142
+ // Test stub
143
+
144
+ function createTestStub() {
145
+ return {
146
+ box: {},
147
+ show: () => {},
148
+ hide: () => {},
149
+ onFocus: () => {},
150
+ onBlur: () => {},
151
+ getFooterText: () => FOOTER_TEXT,
152
+ getFooterColor: () => COLORS.footerBg,
153
+ };
154
+ }
155
+
156
+ // ---------------------------------------------------------------------------
157
+ // Helpers (used inside createMusicTab)
158
+
159
+ /**
160
+ * Resolve the tracks directory for the running project.
161
+ * Uses process.cwd() because the TUI always runs from the project root
162
+ * and this function is called both internally and from exported helpers
163
+ * that lack configService context.
164
+ * @returns {string}
165
+ */
166
+ function _getTracksDir() {
167
+ const cwdTracks = path.join(process.cwd(), '.claude', 'audio', 'tracks');
168
+ // Fall back to package-bundled tracks if cwd doesn't have any
169
+ return fs.existsSync(cwdTracks) ? cwdTracks : _PKG_TRACKS_DIR;
170
+ }
171
+
172
+ /**
173
+ * Scan .claude/audio/tracks/ for .mp3 files.
174
+ * Falls back to the static catalog if the directory is absent.
175
+ *
176
+ * @returns {{ id: string, label: string, isBuiltIn: boolean }[]}
177
+ */
178
+ export function scanTracks() {
179
+ const tracksDir = _getTracksDir();
180
+ try {
181
+ const files = fs.readdirSync(tracksDir);
182
+ const builtInIds = new Set(BUILT_IN_TRACK_CATALOG.map(t => t.id));
183
+ return files
184
+ .filter(f => /\.mp3$/i.test(f))
185
+ .sort()
186
+ .map(f => ({ id: f, label: formatTrackLabel(f), isBuiltIn: builtInIds.has(f) }));
187
+ } catch {
188
+ // Directory not found or unreadable — use the static catalog
189
+ return BUILT_IN_TRACK_CATALOG.map(t => ({ ...t, isBuiltIn: true }));
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Get music config from configService.
195
+ */
196
+ function _getMusic(configService) {
197
+ const cfg = configService.getConfig();
198
+ // Use backgroundMusic (matches settings-tab); fall back to legacy 'music' key
199
+ const music = cfg.backgroundMusic ?? cfg.music ?? {};
200
+ return {
201
+ enabled: music.enabled ?? false,
202
+ track: music.track ?? BUILT_IN_TRACK_CATALOG[0].id,
203
+ volume: music.volume ?? 20,
204
+ };
205
+ }
206
+
207
+ /**
208
+ * Update music config (merge, never overwrite).
209
+ * Writes to 'backgroundMusic' key (shared with settings-tab).
210
+ */
211
+ function _setMusic(configService, update) {
212
+ const current = _getMusic(configService);
213
+ configService.set('backgroundMusic', { ...current, ...update });
214
+ }
215
+
216
+ /**
217
+ * Patch the 'default' entry in audio-effects.cfg to use the given track.
218
+ * play-tts-piper.sh reads the track from audio-effects.cfg (not from config.json),
219
+ * so any track change must be reflected here to take effect at runtime.
220
+ * Safe to call with invalid/missing tracks — non-fatal on failure.
221
+ * @param {string} track - Filename like "agent_vibes_salsa_v2_loop.mp3"
222
+ */
223
+ export function applyTrackToAudioEffects(track) {
224
+ if (!track || /[|/\\]/.test(track)) return;
225
+ const cfgFile = path.join(process.cwd(), '.claude', 'config', 'audio-effects.cfg');
226
+ try {
227
+ let content = fs.readFileSync(cfgFile, 'utf-8');
228
+ content = content.replace(
229
+ /^default\|([^|]*)\|([^|]*)\|(.*)$/m,
230
+ (match, g1, g2, g3) => `default|${g1}|${track}|${g3}`,
231
+ );
232
+ fs.writeFileSync(cfgFile, content, 'utf-8');
233
+ } catch { /* file may not exist — non-fatal */ }
234
+ }
235
+
236
+ /**
237
+ * Get favorites array from config.musicFavorites.
238
+ */
239
+ export function getMusicFavorites(configService) {
240
+ const favs = configService.getConfig().musicFavorites;
241
+ return Array.isArray(favs) ? favs : [];
242
+ }
243
+
244
+ /**
245
+ * Toggle a track in the favorites list.
246
+ */
247
+ export function toggleMusicFavorite(configService, trackId) {
248
+ const favs = getMusicFavorites(configService);
249
+ const idx = favs.indexOf(trackId);
250
+ if (idx >= 0) {
251
+ favs.splice(idx, 1);
252
+ } else {
253
+ favs.push(trackId);
254
+ }
255
+ configService.set('musicFavorites', favs);
256
+ }
257
+
258
+ /**
259
+ * Get custom tracks from config.
260
+ */
261
+ function _getCustomTracks(configService) {
262
+ const custom = configService.getConfig().customTracks;
263
+ return Array.isArray(custom) ? custom : [];
264
+ }
265
+
266
+ // ---------------------------------------------------------------------------
267
+
268
+ /**
269
+ * Create the Music tab component.
270
+ *
271
+ * @param {object} screen - Blessed screen instance (or test stub)
272
+ * @param {object} services
273
+ * @param {import('../../services/config-service.js').ConfigService} services.configService
274
+ * @returns {{ box, show, hide, onFocus, onBlur, getFooterText, getFooterColor }}
275
+ */
276
+ export function createMusicTab(screen, services) {
277
+ if (IS_TEST) return createTestStub();
278
+
279
+ const { configService, focusMainTabBar, updateHeaderStatus, languageService } = services;
280
+ const _tl = (key) => languageService ? languageService.t(key) : t('en', key);
281
+
282
+ // -------------------------------------------------------------------------
283
+ // Container
284
+
285
+ const box = blessed.box({
286
+ parent: screen,
287
+ top: 5,
288
+ left: 0,
289
+ width: '100%',
290
+ bottom: 2,
291
+ hidden: true,
292
+ style: { fg: COLORS.labelFg, bg: COLORS.contentBg },
293
+ border: { type: 'line' },
294
+ borderStyle: { fg: COLORS.borderFg },
295
+ });
296
+
297
+ // -------------------------------------------------------------------------
298
+ // Section headers
299
+
300
+ const builtInHdr = blessed.text({
301
+ parent: box,
302
+ top: 1,
303
+ left: 2,
304
+ content: `{${COLORS.sectionHdr}-fg}${_tl('musicBuiltInHeader')}${'─'.repeat(48)}{/${COLORS.sectionHdr}-fg}`,
305
+ tags: true,
306
+ style: { bg: COLORS.contentBg },
307
+ });
308
+
309
+ // Currently selected track indicator (updated by refreshDisplay)
310
+ const activeTrackText = blessed.text({
311
+ parent: box,
312
+ top: 1,
313
+ right: 4,
314
+ shrink: true,
315
+ tags: true,
316
+ content: '',
317
+ style: { bg: COLORS.contentBg },
318
+ });
319
+
320
+ // -------------------------------------------------------------------------
321
+ // Track list
322
+
323
+ const trackList = blessed.list({
324
+ parent: box,
325
+ top: 3,
326
+ left: 2,
327
+ width: '96%',
328
+ height: '55%',
329
+ keys: true,
330
+ vi: true,
331
+ mouse: true,
332
+ tags: true,
333
+ border: { type: 'line' },
334
+ scrollbar: { ch: '│', style: { fg: COLORS.sectionHdr } },
335
+ style: {
336
+ fg: COLORS.labelFg,
337
+ bg: COLORS.contentBg,
338
+ border: { fg: COLORS.borderFg },
339
+ selected: { bg: '#3e2000', fg: COLORS.activeFg, bold: true },
340
+ item: { fg: COLORS.labelFg },
341
+ },
342
+ });
343
+
344
+ // -------------------------------------------------------------------------
345
+ // Status panel
346
+
347
+ const musicStatusHdr = blessed.text({
348
+ parent: box,
349
+ top: '64%',
350
+ left: 2,
351
+ content: `{${COLORS.sectionHdr}-fg}${_tl('musicStatusHeader')}${'─'.repeat(52)}{/${COLORS.sectionHdr}-fg}`,
352
+ tags: true,
353
+ style: { bg: COLORS.contentBg },
354
+ });
355
+
356
+ const statusLine = blessed.text({
357
+ parent: box,
358
+ top: '69%',
359
+ left: 2,
360
+ tags: true,
361
+ content: '',
362
+ style: { fg: COLORS.labelFg, bg: COLORS.contentBg },
363
+ });
364
+
365
+ const previewLine = blessed.text({
366
+ parent: box,
367
+ top: '74%',
368
+ left: 2,
369
+ tags: true,
370
+ content: '',
371
+ style: { fg: COLORS.playingFg, bg: COLORS.contentBg },
372
+ });
373
+
374
+ // -------------------------------------------------------------------------
375
+ // Buttons
376
+
377
+ function _createBtn(label, onClick) {
378
+ const btn = blessed.button({
379
+ parent: box,
380
+ content: label,
381
+ mouse: true,
382
+ keys: true,
383
+ shrink: true,
384
+ padding: { left: 1, right: 1 },
385
+ style: {
386
+ bg: COLORS.btnDefault,
387
+ fg: 'white',
388
+ focus: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
389
+ hover: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
390
+ },
391
+ });
392
+ btn.on('focus', () => {
393
+ btn.style.bg = COLORS.btnFocus;
394
+ btn.style.fg = COLORS.btnFocusFg;
395
+ const raw = btn.content.replace(/[►◄]/g, '').trim();
396
+ btn.setContent(`►${raw}◄`);
397
+ screen.render();
398
+ });
399
+ btn.on('blur', () => {
400
+ btn.style.bg = COLORS.btnDefault;
401
+ btn.style.fg = 'white';
402
+ const raw = btn.content.replace(/[►◄]/g, '').trim();
403
+ btn.setContent(raw);
404
+ screen.render();
405
+ });
406
+ btn.key(['enter', 'space'], () => {
407
+ btn.style.bg = COLORS.btnPress;
408
+ screen.render();
409
+ setTimeout(() => {
410
+ btn.style.bg = COLORS.btnDefault;
411
+ screen.render();
412
+ onClick();
413
+ }, 150);
414
+ });
415
+ btn.on('click', () => btn.press());
416
+ btn.on('mouseover', () => btn.focus());
417
+ return btn;
418
+ }
419
+
420
+ const toggleBtn = _createBtn(_tl('musicToggleBtn'), () => {
421
+ const { enabled } = _getMusic(configService);
422
+ _setMusic(configService, { enabled: !enabled });
423
+ refreshDisplay();
424
+ });
425
+ toggleBtn.bottom = 4;
426
+ toggleBtn.left = 4;
427
+
428
+ const addCustomTrackBtn = _createBtn(_tl('musicAddCustomBtn'), () => {
429
+ const modal = blessed.box({
430
+ parent: screen,
431
+ top: 'center',
432
+ left: 'center',
433
+ width: 66,
434
+ height: 11,
435
+ border: { type: 'line' },
436
+ tags: true,
437
+ label: ` {${COLORS.activeFg}-fg}Add Custom Background Track{/${COLORS.activeFg}-fg} `,
438
+ style: { border: { fg: COLORS.borderFg }, bg: COLORS.contentBg },
439
+ content: [
440
+ '',
441
+ ` {${COLORS.labelFg}-fg}To add a custom track:{/${COLORS.labelFg}-fg}`,
442
+ '',
443
+ ` {${COLORS.valueFg}-fg}1.{/${COLORS.valueFg}-fg} Place an MP3/OGG/WAV file in:`,
444
+ ` {${COLORS.noticeFg}-fg}.claude/audio/tracks/{/${COLORS.noticeFg}-fg}`,
445
+ '',
446
+ ` {${COLORS.valueFg}-fg}2.{/${COLORS.valueFg}-fg} Or run: {${COLORS.noticeFg}-fg}/agent-vibes:background-music{/${COLORS.noticeFg}-fg}`,
447
+ '',
448
+ ` {${COLORS.dimFg}-fg}[Esc / Enter] Close{/${COLORS.dimFg}-fg}`,
449
+ ].join('\n'),
450
+ });
451
+ modal.key(['escape', 'enter', 'q'], () => { modal.destroy(); trackList.focus(); screen.render(); });
452
+ modal.setFront();
453
+ modal.focus();
454
+ screen.render();
455
+ });
456
+ addCustomTrackBtn.bottom = 4;
457
+ addCustomTrackBtn.left = 26;
458
+
459
+ // -------------------------------------------------------------------------
460
+ // Hint text shown in previewLine when the list has focus and nothing is playing.
461
+ // Getter functions so they re-translate when language changes.
462
+ const _hintText = () => `{${COLORS.dimFg}-fg}${_tl('musicHintText')}{/${COLORS.dimFg}-fg}`;
463
+ const _rowHint = () => ` {bright-black-fg}${_tl('musicRowHint')}{/bright-black-fg}`;
464
+ let _listFocused = false;
465
+
466
+ // Inline selection hint appended to the currently highlighted track row.
467
+ // _hintBase stores the item's clean content (no hint, no █) so we never need
468
+ // a sentinel character — PUA chars like U+E000 render as Nerd Font icons.
469
+ let _hintIdx = -1;
470
+ let _hintBase = ''; // content of items[_hintIdx] before hint was appended
471
+ let _refreshing = false;
472
+
473
+ // Known limitation: _updateHint and _tlTick (blink) can interleave,
474
+ // causing brief visual glitches. The _refreshing guard prevents the worst
475
+ // cases but is not a complete fix. Acceptable for a TUI animation.
476
+ function _updateHint(idx) {
477
+ const items = trackList.items;
478
+ // Restore previously hinted row pad with spaces to overwrite ghost hint text
479
+ const _pad = ' '.repeat(60);
480
+ if (_hintIdx >= 0 && _hintIdx !== idx && items[_hintIdx]) {
481
+ const hadBlink = (items[_hintIdx].content ?? '').endsWith(' █');
482
+ items[_hintIdx].setContent((hadBlink ? _hintBase + ' █' : _hintBase) + _pad);
483
+ }
484
+ // Add hint to the new row, saving its clean base first
485
+ if (idx >= 0 && items[idx]) {
486
+ let c = items[idx].content ?? '';
487
+ const hasBlink = c.endsWith(' █');
488
+ if (hasBlink) c = c.slice(0, -2);
489
+ _hintBase = c;
490
+ items[idx].setContent(c + _rowHint() + (hasBlink ? ' █' : ''));
491
+ } else {
492
+ _hintBase = '';
493
+ }
494
+ _hintIdx = idx;
495
+ }
496
+
497
+ // -------------------------------------------------------------------------
498
+ // Playback state
499
+
500
+ let _playingProcess = null;
501
+ let _playingTrackId = null;
502
+
503
+ // Kill the entire process group so child audio processes (ffplay, play, mpg123) all die
504
+ function _killPlayingProcess() {
505
+ if (_playingProcess) {
506
+ const _isWin = process.platform === 'win32' && !process.env.WSL_DISTRO_NAME;
507
+ try {
508
+ if (_isWin) {
509
+ // Windows: kill the process tree via taskkill (process group kill doesn't work)
510
+ spawn('taskkill', ['/F', '/T', '/PID', String(_playingProcess.pid)], {
511
+ stdio: 'ignore', windowsHide: true,
512
+ });
513
+ } else {
514
+ process.kill(-_playingProcess.pid, 'SIGTERM');
515
+ }
516
+ } catch (e) {
517
+ if (e.code !== 'ESRCH') { /* ignore */ }
518
+ }
519
+ _playingProcess = null;
520
+ }
521
+ }
522
+
523
+ const _spawnEnv = buildAudioEnv();
524
+ const _detectedPlayer = detectMp3Player(_spawnEnv);
525
+
526
+ process.on('exit', () => { _killPlayingProcess(); });
527
+
528
+ /**
529
+ * Preview a track by spawning an audio player.
530
+ * Second call with the same trackId stops playback (toggle).
531
+ */
532
+ function _playTrack(trackId) {
533
+ const tracksDir = _getTracksDir();
534
+ const trackPath = path.resolve(tracksDir, trackId);
535
+
536
+ // Guard: path must stay inside tracksDir
537
+ const safeBase = path.resolve(tracksDir);
538
+ if (!trackPath.startsWith(safeBase + path.sep) && trackPath !== safeBase) {
539
+ return;
540
+ }
541
+
542
+ // Toggle: second press on the same track → stop
543
+ if (_playingTrackId === trackId) {
544
+ _killPlayingProcess();
545
+ _playingTrackId = null;
546
+ previewLine.setContent(_listFocused ? _hintText() : '');
547
+ screen.render();
548
+ return;
549
+ }
550
+
551
+ // Kill any previously playing track
552
+ _killPlayingProcess();
553
+ _playingTrackId = null;
554
+
555
+ if (!_detectedPlayer) {
556
+ const installHint = process.platform === 'win32'
557
+ ? 'No MP3 player found. Install ffmpeg: winget install ffmpeg'
558
+ : 'No MP3 player found. Install ffmpeg: sudo apt install ffmpeg';
559
+ previewLine.setContent(`{red-fg}${installHint}{/red-fg}`);
560
+ screen.render();
561
+ setTimeout(() => { previewLine.setContent(_listFocused ? _hintText() : ''); screen.render(); }, 5000);
562
+ return;
563
+ }
564
+
565
+ const _isWin = process.platform === 'win32' && !process.env.WSL_DISTRO_NAME;
566
+ // Spawn the detected player directly (no sh -c chain — avoids VLC/cvlc stderr issues)
567
+ _playingProcess = spawn(_detectedPlayer.bin, _detectedPlayer.args(trackPath), {
568
+ stdio: 'ignore', detached: !_isWin, windowsHide: true, env: _spawnEnv,
569
+ });
570
+ _playingTrackId = trackId;
571
+
572
+ const label = _allTracks.find(t => t.id === trackId)?.label ?? formatTrackLabel(trackId);
573
+ previewLine.setContent(`{${COLORS.playingFg}-fg}♪ Previewing: ${label} (Space again to stop){/${COLORS.playingFg}-fg}`);
574
+ screen.render();
575
+
576
+ _playingProcess.on('exit', () => {
577
+ if (_playingTrackId === trackId) {
578
+ _playingTrackId = null;
579
+ _playingProcess = null;
580
+ previewLine.setContent(_listFocused ? _hintText() : '');
581
+ refreshDisplay(); // clears (playing) label
582
+ }
583
+ });
584
+
585
+ _playingProcess.on('error', () => {
586
+ if (_playingTrackId === trackId) {
587
+ _killPlayingProcess();
588
+ _playingTrackId = null;
589
+ _playingProcess = null;
590
+ previewLine.setContent(_listFocused ? _hintText() : '');
591
+ }
592
+ });
593
+ }
594
+
595
+ // -------------------------------------------------------------------------
596
+ // Display state
597
+
598
+ let _showFavoritesOnly = false;
599
+ let _allTracks = [];
600
+
601
+ function _buildAllTracks() {
602
+ const scanned = scanTracks();
603
+ const scannedIds = new Set(scanned.map(t => t.id));
604
+ // Append custom tracks not already present from disk scan
605
+ const custom = _getCustomTracks(configService)
606
+ .filter(id => !scannedIds.has(id))
607
+ .map(id => ({ id, label: formatTrackLabel(id), isBuiltIn: false }));
608
+ return [...scanned, ...custom];
609
+ }
610
+
611
+ function _getVisibleTracks() {
612
+ if (!_showFavoritesOnly) return _allTracks;
613
+ const favs = getMusicFavorites(configService);
614
+ return _allTracks.filter(t => favs.includes(t.id));
615
+ }
616
+
617
+ function _getSelectedTrackId() {
618
+ const visible = _getVisibleTracks();
619
+ const entry = visible[trackList.selected];
620
+ return entry ? entry.id : null;
621
+ }
622
+
623
+ function _buildListItems(tracks, activeTrackId, favorites) {
624
+ return tracks.map(t => {
625
+ const isFav = favorites.includes(t.id);
626
+ const isActive = t.id === activeTrackId;
627
+ const isPrev = t.id === _playingTrackId;
628
+ const star = isFav ? '' : ' ';
629
+ const dot = isPrev ? '' : (isActive ? '{green-fg}✓{/green-fg}' : ' ');
630
+ const tag = t.isBuiltIn ? '' : ' [custom]';
631
+ return ` ${star}${dot} ${t.label}${tag}${isPrev ? ' (playing)' : ''}`;
632
+ });
633
+ }
634
+
635
+ function refreshDisplay() {
636
+ _refreshing = true;
637
+ const savedIdx = trackList.selected ?? 0;
638
+
639
+ _allTracks = _buildAllTracks();
640
+ const { enabled, track: activeTrackId } = _getMusic(configService);
641
+ const favorites = getMusicFavorites(configService);
642
+ const visible = _getVisibleTracks();
643
+ const items = _buildListItems(visible, activeTrackId, favorites);
644
+
645
+ const activeTrack = _allTracks.find(t => t.id === activeTrackId);
646
+ const activeLabel = (activeTrack?.label ?? formatTrackLabel(activeTrackId ?? '')) || 'None';
647
+
648
+ trackList.setItems(items.length > 0 ? items : [' (no tracks match filter)']);
649
+ // Restore selection (setItems resets to 0)
650
+ const maxIdx = Math.max(0, (items.length > 0 ? items.length : 1) - 1);
651
+ trackList.select(Math.min(savedIdx, maxIdx));
652
+
653
+ // Re-apply inline hint if list is focused
654
+ if (_listFocused) {
655
+ _hintIdx = -1;
656
+ _hintBase = '';
657
+ _updateHint(trackList.selected ?? 0);
658
+ }
659
+
660
+ statusLine.setContent(
661
+ ` ${_tl('musicStatusLabel')} ${formatMusicStatus(enabled)} | ${_tl('musicActiveTrack')} ${activeLabel} | ${_tl('musicFilterLabel')} ${_showFavoritesOnly ? _tl('musicFilterFavs') : _tl('musicFilterAll')}`
662
+ );
663
+
664
+ // Update "Currently Selected" header
665
+ activeTrackText.setContent(`{${COLORS.activeFg}-fg}✓ ${activeLabel}{/${COLORS.activeFg}-fg}`);
666
+
667
+ _refreshing = false;
668
+ if (typeof updateHeaderStatus === 'function') updateHeaderStatus();
669
+ screen.render();
670
+ }
671
+
672
+ // -------------------------------------------------------------------------
673
+ // Key bindings on trackList
674
+
675
+ // [Enter] open save modal for selected track
676
+ trackList.key(['enter'], () => {
677
+ const trackId = _getSelectedTrackId();
678
+ if (!trackId) return;
679
+ const label = _allTracks.find(t => t.id === trackId)?.label ?? formatTrackLabel(trackId);
680
+ _openSaveModal(trackId, label);
681
+ });
682
+
683
+ /**
684
+ * Save-track modal: Save Locally | Save Globally & Locally | Cancel | Preview
685
+ */
686
+ function _openSaveModal(trackId, displayName) {
687
+ const modal = blessed.box({
688
+ parent: screen,
689
+ top: 'center',
690
+ left: 'center',
691
+ width: 72,
692
+ height: 8,
693
+ border: { type: 'line' },
694
+ tags: true,
695
+ label: ` {${COLORS.activeFg}-fg}Set Background Track{/${COLORS.activeFg}-fg} `,
696
+ style: { border: { fg: COLORS.btnFocus }, bg: COLORS.contentBg },
697
+ });
698
+
699
+ blessed.text({
700
+ parent: modal,
701
+ top: 1,
702
+ left: 2,
703
+ right: 2,
704
+ content: `Set {${COLORS.valueFg}-fg}${displayName}{/${COLORS.valueFg}-fg} as your background track?`,
705
+ tags: true,
706
+ style: { bg: COLORS.contentBg },
707
+ });
708
+
709
+ const modalStatus = blessed.text({
710
+ parent: modal,
711
+ top: 3,
712
+ left: 2,
713
+ right: 2,
714
+ tags: true,
715
+ content: `{${COLORS.dimFg}-fg}Press Preview to audition this track{/${COLORS.dimFg}-fg}`,
716
+ style: { bg: COLORS.contentBg },
717
+ });
718
+
719
+ function _close() {
720
+ _killPlayingProcess();
721
+ _playingTrackId = null;
722
+ previewLine.setContent(_listFocused ? _hintText() : '');
723
+ modal.destroy();
724
+ trackList.focus();
725
+ screen.render();
726
+ }
727
+
728
+ function _makeBtn(lbl, bg, left, top, onClick) {
729
+ const btn = blessed.button({
730
+ parent: modal,
731
+ content: lbl,
732
+ top,
733
+ left,
734
+ mouse: true,
735
+ keys: true,
736
+ shrink: true,
737
+ padding: { left: 1, right: 1 },
738
+ style: {
739
+ bg,
740
+ fg: 'white',
741
+ focus: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
742
+ hover: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
743
+ },
744
+ });
745
+ btn.key(['enter', 'space'], () => { _close(); onClick(); });
746
+ btn.on('click', () => btn.press());
747
+ return btn;
748
+ }
749
+
750
+ function _saveLocally() {
751
+ _setMusic(configService, { track: trackId });
752
+ applyTrackToAudioEffects(trackId);
753
+ refreshDisplay();
754
+ _showTrackChangedNotice(displayName);
755
+ }
756
+
757
+ function _saveGlobally() {
758
+ configService.setGlobal('backgroundMusic', { track: trackId });
759
+ }
760
+
761
+ const okLocalBtn = _makeBtn('Save Locally', COLORS.btnDefault, 2, 5, () => {
762
+ _saveLocally();
763
+ });
764
+ const okGlobalBtn = _makeBtn('Save Globally & Locally', '#1565c0', 18, 5, () => {
765
+ _saveLocally();
766
+ _saveGlobally();
767
+ });
768
+ const cancelBtn = _makeBtn('Cancel', '#546e7a', 46, 5, () => {});
769
+
770
+ // Preview button — does NOT close the modal; plays/stops the track inline
771
+ const previewBtn = blessed.button({
772
+ parent: modal,
773
+ content: 'Preview',
774
+ top: 5,
775
+ left: 58,
776
+ mouse: true,
777
+ keys: true,
778
+ shrink: true,
779
+ padding: { left: 1, right: 1 },
780
+ style: {
781
+ bg: '#e65100',
782
+ fg: 'white',
783
+ focus: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
784
+ hover: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
785
+ },
786
+ });
787
+ previewBtn.key(['enter', 'space'], () => {
788
+ const isPlaying = _playingTrackId === trackId;
789
+ _playTrack(trackId);
790
+ modalStatus.setContent(isPlaying
791
+ ? `{${COLORS.dimFg}-fg}Stopped.{/${COLORS.dimFg}-fg}`
792
+ : `{${COLORS.playingFg}-fg}♪ Playing: ${displayName}…{/${COLORS.playingFg}-fg}`
793
+ );
794
+ screen.render();
795
+ });
796
+ previewBtn.on('click', () => previewBtn.press());
797
+
798
+ // Tab/arrow navigation: SaveLocal SaveGlobal → Cancel → Preview → SaveLocal
799
+ okLocalBtn.key(['tab', 'right'], () => { okGlobalBtn.focus(); screen.render(); });
800
+ okGlobalBtn.key(['tab', 'right'], () => { cancelBtn.focus(); screen.render(); });
801
+ cancelBtn.key(['tab', 'right'], () => { previewBtn.focus(); screen.render(); });
802
+ previewBtn.key(['tab', 'right'], () => { okLocalBtn.focus(); screen.render(); });
803
+ previewBtn.key(['left'], () => { cancelBtn.focus(); screen.render(); });
804
+ cancelBtn.key(['left'], () => { okGlobalBtn.focus(); screen.render(); });
805
+ okGlobalBtn.key(['left'], () => { okLocalBtn.focus(); screen.render(); });
806
+ okLocalBtn.key(['left'], () => { previewBtn.focus(); screen.render(); });
807
+
808
+ modal.key(['escape', 'q'], _close);
809
+
810
+ modal.setFront();
811
+ okLocalBtn.focus();
812
+ screen.render();
813
+ }
814
+
815
+ function _showTrackChangedNotice(displayName) {
816
+ const notice = blessed.box({
817
+ parent: screen,
818
+ top: 'center',
819
+ left: 'center',
820
+ width: 50,
821
+ height: 5,
822
+ border: { type: 'line' },
823
+ tags: true,
824
+ label: ` {${COLORS.activeFg}-fg}Done{/${COLORS.activeFg}-fg} `,
825
+ style: { border: { fg: COLORS.btnFocus }, bg: COLORS.contentBg },
826
+ content: `\n {${COLORS.activeFg}-fg}✓ Track set: ${displayName}{/${COLORS.activeFg}-fg}`,
827
+ });
828
+ notice.setFront();
829
+ screen.render();
830
+ let noticeDestroyed = false;
831
+ setTimeout(() => { if (!noticeDestroyed) { notice.destroy(); noticeDestroyed = true; screen.render(); } }, 2000);
832
+ }
833
+
834
+ // [Space] → preview/stop track (toggle)
835
+ trackList.key(['space'], () => {
836
+ const trackId = _getSelectedTrackId();
837
+ if (trackId) {
838
+ _playTrack(trackId);
839
+ refreshDisplay();
840
+ }
841
+ });
842
+
843
+ // [m/M] toggle music enabled in config
844
+ trackList.key(['m', 'M'], () => {
845
+ const { enabled } = _getMusic(configService);
846
+ _setMusic(configService, { enabled: !enabled });
847
+ refreshDisplay();
848
+ });
849
+
850
+ // [*] toggle favorite
851
+ trackList.key(['*'], () => {
852
+ const trackId = _getSelectedTrackId();
853
+ if (trackId) {
854
+ toggleMusicFavorite(configService, trackId);
855
+ refreshDisplay();
856
+ }
857
+ });
858
+
859
+ // [f/F] toggle favorites filter
860
+ trackList.key(['f', 'F'], () => {
861
+ _showFavoritesOnly = !_showFavoritesOnly;
862
+ refreshDisplay();
863
+ });
864
+
865
+ // [] at top of list → jump to main header tab bar (second press)
866
+ let _prevTrackSel = -1;
867
+ trackList.key(['up'], () => {
868
+ const cur = trackList.selected ?? 0;
869
+ if (cur === 0 && _prevTrackSel === 0 && typeof focusMainTabBar === 'function') {
870
+ focusMainTabBar();
871
+ setTimeout(() => { trackList.select(0); screen.render(); }, 0);
872
+ }
873
+ _prevTrackSel = cur;
874
+ });
875
+
876
+ // Escape at the list level → return to header tab bar
877
+ trackList.key(['escape'], () => {
878
+ if (typeof focusMainTabBar === 'function') { focusMainTabBar(); screen.render(); }
879
+ });
880
+
881
+ // at the last item → descend into the button row (Toggle Music gets focus first)
882
+ // Track previous selection so arriving at last item doesn't immediately jump
883
+ let _prevTrackSelDown = -1;
884
+ trackList.key(['down'], () => {
885
+ const visible = _getVisibleTracks();
886
+ const cur = trackList.selected ?? 0;
887
+ const lastIdx = visible.length - 1;
888
+ if (cur >= lastIdx && _prevTrackSelDown >= lastIdx) {
889
+ toggleBtn.focus();
890
+ screen.render();
891
+ }
892
+ _prevTrackSelDown = cur;
893
+ });
894
+
895
+ // ←/→ navigate between the two buttons
896
+ toggleBtn.key(['right'], () => { addCustomTrackBtn.focus(); screen.render(); });
897
+ addCustomTrackBtn.key(['right'], () => { toggleBtn.focus(); screen.render(); });
898
+ toggleBtn.key(['left'], () => { addCustomTrackBtn.focus(); screen.render(); });
899
+ addCustomTrackBtn.key(['left'], () => { toggleBtn.focus(); screen.render(); });
900
+
901
+ // or Escape from any button → back to track list
902
+ toggleBtn.key(['up', 'escape'], () => { trackList.focus(); screen.render(); });
903
+ addCustomTrackBtn.key(['up', 'escape'], () => { trackList.focus(); screen.render(); });
904
+
905
+ // Blinking on selected row while list is focused
906
+ let _tlBlink = { interval: null, on: false, sel: -1 };
907
+ process.on('exit', () => { if (_tlBlink.interval) clearInterval(_tlBlink.interval); });
908
+ function _tlTick() {
909
+ _tlBlink.on = !_tlBlink.on;
910
+ const items = trackList.items;
911
+ const cur = trackList.selected ?? 0;
912
+ if (_tlBlink.sel !== cur && _tlBlink.sel >= 0 && items[_tlBlink.sel]) {
913
+ items[_tlBlink.sel].setContent((items[_tlBlink.sel].content ?? '').replace(/ █$/, ''));
914
+ }
915
+ _tlBlink.sel = cur;
916
+ if (items[cur]) {
917
+ const base = (items[cur].content ?? '').replace(/ █$/, '');
918
+ items[cur].setContent(_tlBlink.on ? `${base} █` : base);
919
+ }
920
+ screen.render();
921
+ }
922
+ trackList.on('focus', () => {
923
+ _listFocused = true;
924
+ _tlBlink.on = true;
925
+ _tlBlink.sel = trackList.selected ?? 0;
926
+ _hintIdx = -1;
927
+ _hintBase = '';
928
+ _updateHint(_tlBlink.sel);
929
+ const items = trackList.items;
930
+ if (items[_tlBlink.sel]) items[_tlBlink.sel].setContent((items[_tlBlink.sel].content ?? '') + ' █');
931
+ if (!_playingTrackId) previewLine.setContent(_hintText());
932
+ screen.render();
933
+ _tlBlink.interval = setInterval(_tlTick, 500);
934
+ });
935
+ trackList.on('blur', () => {
936
+ _listFocused = false;
937
+ if (!_playingTrackId) previewLine.setContent('');
938
+ if (_tlBlink.interval) { clearInterval(_tlBlink.interval); _tlBlink.interval = null; }
939
+ const items = trackList.items;
940
+ const sel = trackList.selected ?? 0;
941
+ if (items[sel]) {
942
+ // Restore the hinted item to its clean base; for non-hinted items just strip █
943
+ items[sel].setContent(sel === _hintIdx ? _hintBase : (items[sel].content ?? '').replace(/ █$/, ''));
944
+ }
945
+ if (_hintIdx >= 0 && _hintIdx !== sel && items[_hintIdx]) {
946
+ items[_hintIdx].setContent(_hintBase);
947
+ }
948
+ _hintIdx = -1;
949
+ _hintBase = '';
950
+ screen.render();
951
+ });
952
+
953
+ // Refresh status text on cursor movement
954
+ trackList.on('select item', () => {
955
+ if (_refreshing) return;
956
+ _updateHint(trackList.selected ?? 0);
957
+ if (_tlBlink.interval) _tlTick(); // move █ to newly selected row
958
+ const { enabled, track: activeTrackId } = _getMusic(configService);
959
+ const activeTrack = _allTracks.find(t => t.id === activeTrackId);
960
+ const activeLabel = (activeTrack?.label ?? formatTrackLabel(activeTrackId ?? '')) || 'None';
961
+ statusLine.setContent(
962
+ ` ${_tl('musicStatusLabel')} ${formatMusicStatus(enabled)} | ${_tl('musicActiveTrack')} ${activeLabel} | ${_tl('musicFilterLabel')} ${_showFavoritesOnly ? _tl('musicFilterFavs') : _tl('musicFilterAll')}`
963
+ );
964
+ screen.render();
965
+ });
966
+
967
+ // Type-to-jump: press a letter to jump to first track whose label starts with it
968
+ const _trackJumpBlocked = new Set(['j', 'k', 'g', 'h', 'l', 'd', 'u', 'm', 'f']);
969
+ trackList.on('keypress', (ch, key) => {
970
+ if (!ch || key.ctrl || key.meta) return;
971
+ const lower = ch.toLowerCase();
972
+ if (!/^[a-z]$/.test(lower)) return;
973
+ if (_trackJumpBlocked.has(lower)) return;
974
+ const tracks = _getVisibleTracks();
975
+ const count = tracks.length;
976
+ if (count === 0) return;
977
+ const start = trackList.selected ?? 0;
978
+ for (let i = 1; i <= count; i++) {
979
+ const idx = (start + i) % count;
980
+ // Strip leading emoji/symbols to get first letter of track name
981
+ const firstLetter = tracks[idx].label.replace(/^[^a-zA-Z]*/, '')[0]?.toLowerCase() ?? '';
982
+ if (firstLetter === lower) {
983
+ trackList.select(idx);
984
+ screen.render();
985
+ break;
986
+ }
987
+ }
988
+ });
989
+
990
+ // -------------------------------------------------------------------------
991
+ // -------------------------------------------------------------------------
992
+ // Language refresh
993
+
994
+ function refreshMusicLabels() {
995
+ builtInHdr.setContent(`{${COLORS.sectionHdr}-fg}${_tl('musicBuiltInHeader')}${'─'.repeat(48)}{/${COLORS.sectionHdr}-fg}`);
996
+ musicStatusHdr.setContent(`{${COLORS.sectionHdr}-fg}${_tl('musicStatusHeader')}${'─'.repeat(52)}{/${COLORS.sectionHdr}-fg}`);
997
+ toggleBtn.setContent(_tl('musicToggleBtn'));
998
+ addCustomTrackBtn.setContent(_tl('musicAddCustomBtn'));
999
+ refreshDisplay();
1000
+ }
1001
+
1002
+ if (languageService) {
1003
+ languageService.onChange(() => { refreshMusicLabels(); screen.render(); });
1004
+ }
1005
+
1006
+ // Tab Component Contract
1007
+
1008
+ return {
1009
+ box,
1010
+
1011
+ show() {
1012
+ box.show();
1013
+ refreshDisplay();
1014
+ screen.render();
1015
+ },
1016
+
1017
+ hide() {
1018
+ // Stop any preview when leaving the tab
1019
+ _killPlayingProcess();
1020
+ _playingTrackId = null;
1021
+ previewLine.setContent('');
1022
+ box.hide();
1023
+ screen.render();
1024
+ },
1025
+
1026
+ onFocus() {
1027
+ trackList.focus();
1028
+ screen.render();
1029
+ },
1030
+
1031
+ onBlur() {
1032
+ // Stop preview when focus leaves Music tab
1033
+ _killPlayingProcess();
1034
+ _playingTrackId = null;
1035
+ },
1036
+
1037
+ getFooterText() {
1038
+ return _tl('musicFooter');
1039
+ },
1040
+
1041
+ getFooterColor() {
1042
+ return COLORS.footerBg;
1043
+ },
1044
+ };
1045
+
1046
+ }