agentvibes 4.4.1 → 4.5.7

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