agentvibes 3.5.9 → 4.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 (71) hide show
  1. package/.agentvibes/bmad/bmad-voices-enabled.flag +0 -0
  2. package/.agentvibes/bmad/bmad-voices.md +69 -0
  3. package/.claude/config/audio-effects.cfg +1 -1
  4. package/.claude/config/background-music-position.txt +1 -27
  5. package/.claude/github-star-reminder.txt +1 -1
  6. package/.claude/hooks/audio-processor.sh +32 -17
  7. package/.claude/hooks/bmad-speak-enhanced.sh +5 -5
  8. package/.claude/hooks/bmad-speak.sh +4 -4
  9. package/.claude/hooks/bmad-voice-manager.sh +8 -8
  10. package/.claude/hooks/clawdbot-receiver-SECURE.sh +23 -25
  11. package/.claude/hooks/clawdbot-receiver.sh +28 -4
  12. package/.claude/hooks/language-manager.sh +1 -1
  13. package/.claude/hooks/path-resolver.sh +60 -0
  14. package/.claude/hooks/play-tts-agentvibes-receiver-for-voiceless-connections.sh +90 -0
  15. package/.claude/hooks/play-tts-piper.sh +82 -24
  16. package/.claude/hooks/play-tts-ssh-remote.sh +13 -15
  17. package/.claude/hooks/play-tts.sh +16 -5
  18. package/.claude/hooks/session-start-tts.sh +26 -56
  19. package/.claude/hooks/soprano-gradio-synth.py +1 -1
  20. package/.claude/hooks/verbosity-manager.sh +10 -4
  21. package/.claude/settings.json +1 -1
  22. package/CLAUDE.md +129 -104
  23. package/README.md +418 -10
  24. package/RELEASE_NOTES.md +60 -1036
  25. package/bin/agentvibes-voice-browser.js +1827 -0
  26. package/bin/agentvibes.js +100 -0
  27. package/mcp-server/server.py +67 -3
  28. package/package.json +11 -2
  29. package/src/console/app.js +806 -0
  30. package/src/console/audio-env.js +123 -0
  31. package/src/console/brand-colors.js +13 -0
  32. package/src/console/footer-config.js +42 -0
  33. package/src/console/modals/.gitkeep +0 -0
  34. package/src/console/modals/modal-overlay.js +247 -0
  35. package/src/console/navigation.js +60 -0
  36. package/src/console/tabs/.gitkeep +0 -0
  37. package/src/console/tabs/agents-tab.js +369 -0
  38. package/src/console/tabs/help-tab.js +261 -0
  39. package/src/console/tabs/install-tab.js +990 -0
  40. package/src/console/tabs/music-tab.js +997 -0
  41. package/src/console/tabs/placeholder-tab.js +45 -0
  42. package/src/console/tabs/readme-tab.js +267 -0
  43. package/src/console/tabs/settings-tab.js +3949 -0
  44. package/src/console/tabs/voices-tab.js +1574 -0
  45. package/src/installer/music-file-input.js +304 -0
  46. package/src/installer.js +1353 -676
  47. package/src/services/.gitkeep +0 -0
  48. package/src/services/agent-voice-store.js +163 -0
  49. package/src/services/config-service.js +240 -0
  50. package/src/services/navigation-service.js +123 -0
  51. package/src/services/provider-service.js +132 -0
  52. package/src/services/verbosity-service.js +157 -0
  53. package/src/utils/audio-duration-validator.js +298 -0
  54. package/src/utils/audio-format-validator.js +277 -0
  55. package/src/utils/dependency-checker.js +3 -3
  56. package/src/utils/file-ownership-verifier.js +358 -0
  57. package/src/utils/music-file-validator.js +275 -0
  58. package/src/utils/preview-list-prompt.js +136 -0
  59. package/src/utils/provider-validator.js +144 -132
  60. package/src/utils/secure-music-storage.js +412 -0
  61. package/templates/agentvibes-receiver.sh +11 -7
  62. package/voice-assignments.json +8245 -0
  63. package/.claude/config/background-music-volume.txt +0 -1
  64. package/.claude/config/background-music.cfg +0 -1
  65. package/.claude/config/background-music.txt +0 -1
  66. package/.claude/config/tts-speech-rate.txt +0 -1
  67. package/.claude/config/tts-verbosity.txt +0 -1
  68. package/.claude/hooks/bmad-party-manager.sh +0 -225
  69. package/.claude/hooks/stop.sh +0 -38
  70. package/.claude/piper-voices-dir.txt +0 -1
  71. package/.mcp.json +0 -34
@@ -0,0 +1,997 @@
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: '#00e5ff', // Cyan — standard focus state
37
+ btnFocusFg: '#000000',
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: '#00e5ff', // Cyan — currently 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
+ try { process.kill(-_playingProcess.pid, 'SIGTERM'); } catch (e) {
494
+ if (e.code !== 'ESRCH') console.error('Kill failed:', e.code);
495
+ }
496
+ _playingProcess = null;
497
+ }
498
+ }
499
+
500
+ const _spawnEnv = buildAudioEnv();
501
+ const _detectedPlayer = detectMp3Player(_spawnEnv);
502
+
503
+ process.on('exit', () => { _killPlayingProcess(); });
504
+
505
+ /**
506
+ * Preview a track by spawning an audio player.
507
+ * Second call with the same trackId stops playback (toggle).
508
+ */
509
+ function _playTrack(trackId) {
510
+ const tracksDir = _getTracksDir();
511
+ const trackPath = path.resolve(tracksDir, trackId);
512
+
513
+ // Guard: path must stay inside tracksDir
514
+ const safeBase = path.resolve(tracksDir);
515
+ if (!trackPath.startsWith(safeBase + path.sep) && trackPath !== safeBase) {
516
+ return;
517
+ }
518
+
519
+ // Toggle: second press on the same track → stop
520
+ if (_playingTrackId === trackId) {
521
+ _killPlayingProcess();
522
+ _playingTrackId = null;
523
+ previewLine.setContent(_listFocused ? HINT_TEXT : '');
524
+ screen.render();
525
+ return;
526
+ }
527
+
528
+ // Kill any previously playing track
529
+ _killPlayingProcess();
530
+ _playingTrackId = null;
531
+
532
+ if (!_detectedPlayer) {
533
+ previewLine.setContent(`{red-fg}No MP3 player found. Install ffmpeg: sudo apt install ffmpeg{/red-fg}`);
534
+ screen.render();
535
+ setTimeout(() => { previewLine.setContent(_listFocused ? HINT_TEXT : ''); screen.render(); }, 5000);
536
+ return;
537
+ }
538
+
539
+ // Spawn the detected player directly (no sh -c chain — avoids VLC/cvlc stderr issues)
540
+ _playingProcess = spawn(_detectedPlayer.bin, _detectedPlayer.args(trackPath), {
541
+ stdio: 'ignore', detached: true, env: _spawnEnv,
542
+ });
543
+ _playingTrackId = trackId;
544
+
545
+ const label = _allTracks.find(t => t.id === trackId)?.label ?? formatTrackLabel(trackId);
546
+ previewLine.setContent(`{${COLORS.playingFg}-fg}♪ Previewing: ${label} (Space again to stop){/${COLORS.playingFg}-fg}`);
547
+ screen.render();
548
+
549
+ _playingProcess.on('exit', () => {
550
+ if (_playingTrackId === trackId) {
551
+ _playingTrackId = null;
552
+ _playingProcess = null;
553
+ previewLine.setContent(_listFocused ? HINT_TEXT : '');
554
+ refreshDisplay(); // clears (playing) label
555
+ }
556
+ });
557
+
558
+ _playingProcess.on('error', () => {
559
+ if (_playingTrackId === trackId) {
560
+ _killPlayingProcess();
561
+ _playingTrackId = null;
562
+ _playingProcess = null;
563
+ previewLine.setContent(_listFocused ? HINT_TEXT : '');
564
+ }
565
+ });
566
+ }
567
+
568
+ // -------------------------------------------------------------------------
569
+ // Display state
570
+
571
+ let _showFavoritesOnly = false;
572
+ let _allTracks = [];
573
+
574
+ function _buildAllTracks() {
575
+ const scanned = scanTracks();
576
+ const scannedIds = new Set(scanned.map(t => t.id));
577
+ // Append custom tracks not already present from disk scan
578
+ const custom = _getCustomTracks(configService)
579
+ .filter(id => !scannedIds.has(id))
580
+ .map(id => ({ id, label: formatTrackLabel(id), isBuiltIn: false }));
581
+ return [...scanned, ...custom];
582
+ }
583
+
584
+ function _getVisibleTracks() {
585
+ if (!_showFavoritesOnly) return _allTracks;
586
+ const favs = getMusicFavorites(configService);
587
+ return _allTracks.filter(t => favs.includes(t.id));
588
+ }
589
+
590
+ function _getSelectedTrackId() {
591
+ const visible = _getVisibleTracks();
592
+ const entry = visible[trackList.selected];
593
+ return entry ? entry.id : null;
594
+ }
595
+
596
+ function _buildListItems(tracks, activeTrackId, favorites) {
597
+ return tracks.map(t => {
598
+ const isFav = favorites.includes(t.id);
599
+ const isActive = t.id === activeTrackId;
600
+ const isPrev = t.id === _playingTrackId;
601
+ const star = isFav ? '★' : ' ';
602
+ const dot = isPrev ? '♪' : (isActive ? '{green-fg}✓{/green-fg}' : ' ');
603
+ const tag = t.isBuiltIn ? '' : ' [custom]';
604
+ return ` ${star}${dot} ${t.label}${tag}${isPrev ? ' (playing)' : ''}`;
605
+ });
606
+ }
607
+
608
+ function refreshDisplay() {
609
+ _refreshing = true;
610
+ const savedIdx = trackList.selected ?? 0;
611
+
612
+ _allTracks = _buildAllTracks();
613
+ const { enabled, track: activeTrackId } = _getMusic(configService);
614
+ const favorites = getMusicFavorites(configService);
615
+ const visible = _getVisibleTracks();
616
+ const items = _buildListItems(visible, activeTrackId, favorites);
617
+
618
+ const activeTrack = _allTracks.find(t => t.id === activeTrackId);
619
+ const activeLabel = (activeTrack?.label ?? formatTrackLabel(activeTrackId ?? '')) || 'None';
620
+
621
+ trackList.setItems(items.length > 0 ? items : [' (no tracks match filter)']);
622
+ // Restore selection (setItems resets to 0)
623
+ const maxIdx = Math.max(0, (items.length > 0 ? items.length : 1) - 1);
624
+ trackList.select(Math.min(savedIdx, maxIdx));
625
+
626
+ // Re-apply inline hint if list is focused
627
+ if (_listFocused) {
628
+ _hintIdx = -1;
629
+ _hintBase = '';
630
+ _updateHint(trackList.selected ?? 0);
631
+ }
632
+
633
+ statusLine.setContent(
634
+ ` Music: ${formatMusicStatus(enabled)} | Active Track: ${activeLabel} | Filter: ${_showFavoritesOnly ? 'Favorites' : 'All'}`
635
+ );
636
+
637
+ // Update "Currently Selected" header
638
+ activeTrackText.setContent(`{${COLORS.activeFg}-fg}✓ ${activeLabel}{/${COLORS.activeFg}-fg}`);
639
+
640
+ _refreshing = false;
641
+ if (typeof updateHeaderStatus === 'function') updateHeaderStatus();
642
+ screen.render();
643
+ }
644
+
645
+ // -------------------------------------------------------------------------
646
+ // Key bindings on trackList
647
+
648
+ // [Enter] → open save modal for selected track
649
+ trackList.key(['enter'], () => {
650
+ const trackId = _getSelectedTrackId();
651
+ if (!trackId) return;
652
+ const label = _allTracks.find(t => t.id === trackId)?.label ?? formatTrackLabel(trackId);
653
+ _openSaveModal(trackId, label);
654
+ });
655
+
656
+ /**
657
+ * Save-track modal: Save Locally | Save Globally & Locally | Cancel | Preview
658
+ */
659
+ function _openSaveModal(trackId, displayName) {
660
+ const modal = blessed.box({
661
+ parent: screen,
662
+ top: 'center',
663
+ left: 'center',
664
+ width: 72,
665
+ height: 8,
666
+ border: { type: 'line' },
667
+ tags: true,
668
+ label: ` {${COLORS.activeFg}-fg}Set Background Track{/${COLORS.activeFg}-fg} `,
669
+ style: { border: { fg: COLORS.btnFocus }, bg: COLORS.contentBg },
670
+ });
671
+
672
+ blessed.text({
673
+ parent: modal,
674
+ top: 1,
675
+ left: 2,
676
+ right: 2,
677
+ content: `Set {${COLORS.valueFg}-fg}${displayName}{/${COLORS.valueFg}-fg} as your background track?`,
678
+ tags: true,
679
+ style: { bg: COLORS.contentBg },
680
+ });
681
+
682
+ const modalStatus = blessed.text({
683
+ parent: modal,
684
+ top: 3,
685
+ left: 2,
686
+ right: 2,
687
+ tags: true,
688
+ content: `{${COLORS.dimFg}-fg}Press Preview to audition this track{/${COLORS.dimFg}-fg}`,
689
+ style: { bg: COLORS.contentBg },
690
+ });
691
+
692
+ function _close() {
693
+ _killPlayingProcess();
694
+ _playingTrackId = null;
695
+ previewLine.setContent(_listFocused ? HINT_TEXT : '');
696
+ modal.destroy();
697
+ trackList.focus();
698
+ screen.render();
699
+ }
700
+
701
+ function _makeBtn(lbl, bg, left, top, onClick) {
702
+ const btn = blessed.button({
703
+ parent: modal,
704
+ content: lbl,
705
+ top,
706
+ left,
707
+ mouse: true,
708
+ keys: true,
709
+ shrink: true,
710
+ padding: { left: 1, right: 1 },
711
+ style: {
712
+ bg,
713
+ fg: 'white',
714
+ focus: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
715
+ hover: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
716
+ },
717
+ });
718
+ btn.key(['enter', 'space'], () => { _close(); onClick(); });
719
+ btn.on('click', () => btn.press());
720
+ return btn;
721
+ }
722
+
723
+ function _saveLocally() {
724
+ _setMusic(configService, { track: trackId });
725
+ applyTrackToAudioEffects(trackId);
726
+ refreshDisplay();
727
+ _showTrackChangedNotice(displayName);
728
+ }
729
+
730
+ function _saveGlobally() {
731
+ configService.setGlobal('backgroundMusic', { track: trackId });
732
+ }
733
+
734
+ const okLocalBtn = _makeBtn('Save Locally', COLORS.btnDefault, 2, 5, () => {
735
+ _saveLocally();
736
+ });
737
+ const okGlobalBtn = _makeBtn('Save Globally & Locally', '#2e7d32', 18, 5, () => {
738
+ _saveLocally();
739
+ _saveGlobally();
740
+ });
741
+ const cancelBtn = _makeBtn('Cancel', '#546e7a', 46, 5, () => {});
742
+
743
+ // Preview button — does NOT close the modal; plays/stops the track inline
744
+ const previewBtn = blessed.button({
745
+ parent: modal,
746
+ content: 'Preview',
747
+ top: 5,
748
+ left: 58,
749
+ mouse: true,
750
+ keys: true,
751
+ shrink: true,
752
+ padding: { left: 1, right: 1 },
753
+ style: {
754
+ bg: '#e65100',
755
+ fg: 'white',
756
+ focus: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
757
+ hover: { bg: COLORS.btnFocus, fg: COLORS.btnFocusFg, bold: true },
758
+ },
759
+ });
760
+ previewBtn.key(['enter', 'space'], () => {
761
+ const isPlaying = _playingTrackId === trackId;
762
+ _playTrack(trackId);
763
+ modalStatus.setContent(isPlaying
764
+ ? `{${COLORS.dimFg}-fg}Stopped.{/${COLORS.dimFg}-fg}`
765
+ : `{${COLORS.playingFg}-fg}♪ Playing: ${displayName}…{/${COLORS.playingFg}-fg}`
766
+ );
767
+ screen.render();
768
+ });
769
+ previewBtn.on('click', () => previewBtn.press());
770
+
771
+ // Tab/arrow navigation: SaveLocal → SaveGlobal → Cancel → Preview → SaveLocal
772
+ okLocalBtn.key(['tab', 'right'], () => { okGlobalBtn.focus(); screen.render(); });
773
+ okGlobalBtn.key(['tab', 'right'], () => { cancelBtn.focus(); screen.render(); });
774
+ cancelBtn.key(['tab', 'right'], () => { previewBtn.focus(); screen.render(); });
775
+ previewBtn.key(['tab', 'right'], () => { okLocalBtn.focus(); screen.render(); });
776
+ previewBtn.key(['left'], () => { cancelBtn.focus(); screen.render(); });
777
+ cancelBtn.key(['left'], () => { okGlobalBtn.focus(); screen.render(); });
778
+ okGlobalBtn.key(['left'], () => { okLocalBtn.focus(); screen.render(); });
779
+ okLocalBtn.key(['left'], () => { previewBtn.focus(); screen.render(); });
780
+
781
+ modal.key(['escape', 'q'], _close);
782
+
783
+ modal.setFront();
784
+ okLocalBtn.focus();
785
+ screen.render();
786
+ }
787
+
788
+ function _showTrackChangedNotice(displayName) {
789
+ const notice = blessed.box({
790
+ parent: screen,
791
+ top: 'center',
792
+ left: 'center',
793
+ width: 50,
794
+ height: 5,
795
+ border: { type: 'line' },
796
+ tags: true,
797
+ label: ` {${COLORS.activeFg}-fg}Done{/${COLORS.activeFg}-fg} `,
798
+ style: { border: { fg: COLORS.btnFocus }, bg: COLORS.contentBg },
799
+ content: `\n {${COLORS.activeFg}-fg}✓ Track set: ${displayName}{/${COLORS.activeFg}-fg}`,
800
+ });
801
+ notice.setFront();
802
+ screen.render();
803
+ let noticeDestroyed = false;
804
+ setTimeout(() => { if (!noticeDestroyed) { notice.destroy(); noticeDestroyed = true; screen.render(); } }, 2000);
805
+ }
806
+
807
+ // [Space] → preview/stop track (toggle)
808
+ trackList.key(['space'], () => {
809
+ const trackId = _getSelectedTrackId();
810
+ if (trackId) {
811
+ _playTrack(trackId);
812
+ refreshDisplay();
813
+ }
814
+ });
815
+
816
+ // [m/M] → toggle music enabled in config
817
+ trackList.key(['m', 'M'], () => {
818
+ const { enabled } = _getMusic(configService);
819
+ _setMusic(configService, { enabled: !enabled });
820
+ refreshDisplay();
821
+ });
822
+
823
+ // [*] → toggle favorite
824
+ trackList.key(['*'], () => {
825
+ const trackId = _getSelectedTrackId();
826
+ if (trackId) {
827
+ toggleMusicFavorite(configService, trackId);
828
+ refreshDisplay();
829
+ }
830
+ });
831
+
832
+ // [f/F] → toggle favorites filter
833
+ trackList.key(['f', 'F'], () => {
834
+ _showFavoritesOnly = !_showFavoritesOnly;
835
+ refreshDisplay();
836
+ });
837
+
838
+ // [↑] at top of list → jump to main header tab bar
839
+ trackList.key(['up'], () => {
840
+ if (trackList.selected === 0 && typeof focusMainTabBar === 'function') {
841
+ focusMainTabBar();
842
+ setTimeout(() => { trackList.select(0); screen.render(); }, 0);
843
+ }
844
+ });
845
+
846
+ // Escape at the list level → return to header tab bar
847
+ trackList.key(['escape'], () => {
848
+ if (typeof focusMainTabBar === 'function') { focusMainTabBar(); screen.render(); }
849
+ });
850
+
851
+ // ↓ at the last item → descend into the button row (Toggle Music gets focus first)
852
+ // Note: Tab is NOT used here — navigation.js registers screen.key(['tab']) to cycle tabs,
853
+ // so element.key(['tab']) + screen.key(['tab']) both fire, causing a simultaneous tab-cycle.
854
+ trackList.key(['down'], () => {
855
+ const visible = _getVisibleTracks();
856
+ if (trackList.selected >= visible.length - 1) {
857
+ toggleBtn.focus();
858
+ screen.render();
859
+ }
860
+ });
861
+
862
+ // ←/→ navigate between the two buttons
863
+ toggleBtn.key(['right'], () => { addCustomTrackBtn.focus(); screen.render(); });
864
+ addCustomTrackBtn.key(['right'], () => { toggleBtn.focus(); screen.render(); });
865
+ toggleBtn.key(['left'], () => { addCustomTrackBtn.focus(); screen.render(); });
866
+ addCustomTrackBtn.key(['left'], () => { toggleBtn.focus(); screen.render(); });
867
+
868
+ // ↑ or Escape from any button → back to track list
869
+ toggleBtn.key(['up', 'escape'], () => { trackList.focus(); screen.render(); });
870
+ addCustomTrackBtn.key(['up', 'escape'], () => { trackList.focus(); screen.render(); });
871
+
872
+ // Blinking █ on selected row while list is focused
873
+ let _tlBlink = { interval: null, on: false, sel: -1 };
874
+ process.on('exit', () => { if (_tlBlink.interval) clearInterval(_tlBlink.interval); });
875
+ function _tlTick() {
876
+ _tlBlink.on = !_tlBlink.on;
877
+ const items = trackList.items;
878
+ const cur = trackList.selected ?? 0;
879
+ if (_tlBlink.sel !== cur && _tlBlink.sel >= 0 && items[_tlBlink.sel]) {
880
+ items[_tlBlink.sel].setContent((items[_tlBlink.sel].content ?? '').replace(/ █$/, ''));
881
+ }
882
+ _tlBlink.sel = cur;
883
+ if (items[cur]) {
884
+ const base = (items[cur].content ?? '').replace(/ █$/, '');
885
+ items[cur].setContent(_tlBlink.on ? `${base} █` : base);
886
+ }
887
+ screen.render();
888
+ }
889
+ trackList.on('focus', () => {
890
+ _listFocused = true;
891
+ _tlBlink.on = true;
892
+ _tlBlink.sel = trackList.selected ?? 0;
893
+ _hintIdx = -1;
894
+ _hintBase = '';
895
+ _updateHint(_tlBlink.sel);
896
+ const items = trackList.items;
897
+ if (items[_tlBlink.sel]) items[_tlBlink.sel].setContent((items[_tlBlink.sel].content ?? '') + ' █');
898
+ if (!_playingTrackId) previewLine.setContent(HINT_TEXT);
899
+ screen.render();
900
+ _tlBlink.interval = setInterval(_tlTick, 500);
901
+ });
902
+ trackList.on('blur', () => {
903
+ _listFocused = false;
904
+ if (!_playingTrackId) previewLine.setContent('');
905
+ if (_tlBlink.interval) { clearInterval(_tlBlink.interval); _tlBlink.interval = null; }
906
+ const items = trackList.items;
907
+ const sel = trackList.selected ?? 0;
908
+ if (items[sel]) {
909
+ // Restore the hinted item to its clean base; for non-hinted items just strip █
910
+ items[sel].setContent(sel === _hintIdx ? _hintBase : (items[sel].content ?? '').replace(/ █$/, ''));
911
+ }
912
+ if (_hintIdx >= 0 && _hintIdx !== sel && items[_hintIdx]) {
913
+ items[_hintIdx].setContent(_hintBase);
914
+ }
915
+ _hintIdx = -1;
916
+ _hintBase = '';
917
+ screen.render();
918
+ });
919
+
920
+ // Refresh status text on cursor movement
921
+ trackList.on('select item', () => {
922
+ if (_refreshing) return;
923
+ _updateHint(trackList.selected ?? 0);
924
+ if (_tlBlink.interval) _tlTick(); // move █ to newly selected row
925
+ const { enabled, track: activeTrackId } = _getMusic(configService);
926
+ const activeTrack = _allTracks.find(t => t.id === activeTrackId);
927
+ const activeLabel = (activeTrack?.label ?? formatTrackLabel(activeTrackId ?? '')) || 'None';
928
+ statusLine.setContent(
929
+ ` Music: ${formatMusicStatus(enabled)} | Active Track: ${activeLabel} | Filter: ${_showFavoritesOnly ? 'Favorites' : 'All'}`
930
+ );
931
+ screen.render();
932
+ });
933
+
934
+ // Type-to-jump: press a letter to jump to first track whose label starts with it
935
+ const _trackJumpBlocked = new Set(['j', 'k', 'g', 'h', 'l', 'd', 'u', 'm', 'f']);
936
+ trackList.on('keypress', (ch, key) => {
937
+ if (!ch || key.ctrl || key.meta) return;
938
+ const lower = ch.toLowerCase();
939
+ if (!/^[a-z]$/.test(lower)) return;
940
+ if (_trackJumpBlocked.has(lower)) return;
941
+ const tracks = _getVisibleTracks();
942
+ const count = tracks.length;
943
+ if (count === 0) return;
944
+ const start = trackList.selected ?? 0;
945
+ for (let i = 1; i <= count; i++) {
946
+ const idx = (start + i) % count;
947
+ // Strip leading emoji/symbols to get first letter of track name
948
+ const firstLetter = tracks[idx].label.replace(/^[^a-zA-Z]*/, '')[0]?.toLowerCase() ?? '';
949
+ if (firstLetter === lower) {
950
+ trackList.select(idx);
951
+ screen.render();
952
+ break;
953
+ }
954
+ }
955
+ });
956
+
957
+ // -------------------------------------------------------------------------
958
+ // Tab Component Contract
959
+
960
+ return {
961
+ box,
962
+
963
+ show() {
964
+ box.show();
965
+ refreshDisplay();
966
+ screen.render();
967
+ },
968
+
969
+ hide() {
970
+ // Stop any preview when leaving the tab
971
+ _killPlayingProcess();
972
+ _playingTrackId = null;
973
+ previewLine.setContent('');
974
+ box.hide();
975
+ screen.render();
976
+ },
977
+
978
+ onFocus() {
979
+ trackList.focus();
980
+ screen.render();
981
+ },
982
+
983
+ onBlur() {
984
+ // Stop preview when focus leaves Music tab
985
+ _killPlayingProcess();
986
+ _playingTrackId = null;
987
+ },
988
+
989
+ getFooterText() {
990
+ return FOOTER_TEXT;
991
+ },
992
+
993
+ getFooterColor() {
994
+ return COLORS.footerBg;
995
+ },
996
+ };
997
+ }