diff --git a/.gitleaksignore b/.gitleaksignore index 135be9b..a344016 100644 --- a/.gitleaksignore +++ b/.gitleaksignore @@ -11,3 +11,6 @@ a264f9bd666e25d9da346d8a0457fd817e275203:test/security-247.test.mjs:generic-api- a264f9bd666e25d9da346d8a0457fd817e275203:test/security-247.test.mjs:generic-api-key:175 a264f9bd666e25d9da346d8a0457fd817e275203:test/security-247.test.mjs:generic-api-key:176 a264f9bd666e25d9da346d8a0457fd817e275203:test/security-247.test.mjs:generic-api-key:177 +# False positives: a synthetic YouTube key in the #351 panel sync test (commit d24bf88); later commits build it at runtime. +d24bf8853ccdca8c1be5f6850e634a398cecab73:test/panel-config-sync.test.mjs:generic-api-key:56 +d24bf8853ccdca8c1be5f6850e634a398cecab73:test/panel-config-sync.test.mjs:generic-api-key:59 diff --git a/app/src/lib/draft.ts b/app/src/lib/draft.ts index 083d7d5..f2f8e85 100644 --- a/app/src/lib/draft.ts +++ b/app/src/lib/draft.ts @@ -21,6 +21,16 @@ export type DraftSource = { prepareSave: () => PreparedSave | undefined; discard: () => void; protect?: (state: AppState) => AppState; + /** #351: saved values just received from the server; Discard must restore these, not older ones. */ + rebase?: (server: ServerSnapshot) => void; +}; + +/** Saved values the server just sent (config sections, theme, interactive, custom overlays). */ +export type ServerSnapshot = { + config?: Partial; + theme?: AppState['theme']; + interactive?: AppState['interactive']; + customOverlays?: AppState['customOverlays']; }; const sources = new Map(); @@ -55,6 +65,10 @@ export const dirtyKeys = () => [...new Set([...sources.values()].flatMap(s => (s let busy = false; let operation: Promise | undefined; export const isSaving = () => busy; +/** Open drafts move their Discard baseline to the values the server just sent (#351). */ +export function rebaseDrafts(server: ServerSnapshot) { + for (const source of sources.values()) source.rebase?.(server); +} export function protectDrafts(state: AppState) { for (const source of sources.values()) state = source.protect?.(state) ?? state; return state; diff --git a/app/src/lib/live.ts b/app/src/lib/live.ts index faf7dc9..6c5e02f 100644 --- a/app/src/lib/live.ts +++ b/app/src/lib/live.ts @@ -5,7 +5,7 @@ import { warnUnknownClientEvent } from '../../../src/events.mjs'; // contrato ú import { LOOK_SECTIONS } from '../../../src/theme-looks.mjs'; import { mergeChat } from './chat-merge.mjs'; import { api, withKey } from './api'; -import { holding, isStale, observeActiveTheme, onStaleDiscard, protectDrafts, registerDraft, type DraftSource } from './draft'; +import { holding, isStale, observeActiveTheme, onStaleDiscard, protectDrafts, rebaseDrafts, registerDraft, type DraftSource } from './draft'; import { ManualDraft } from './manual-draft'; import type { AppState, ChatMessage, Config, LiveEventName, InterviewControl, LiveEvents, PrompterState, Timeline } from './types'; @@ -111,11 +111,12 @@ class Live { restore: (saved, discarded) => this.update(s => ({ config: { ...s.config, ...Object.fromEntries(Object.entries(saved).filter(([key]) => Object.hasOwn(discarded, key))) } })), protect: (state, intent) => ({ ...state, config: deepMerge(state.config, intent) }), + rebase: (server, saved) => (server.config ? { ...saved, ...server.config } as Config : undefined), }); this.configSource = { dirty: this.configDraft.dirty, stale: this.configDraft.stale, keys: this.configDraft.keys, prepareSave: () => { clearTimeout(this.cfgTimer); return this.configDraft.prepareSave(); }, - discard: () => this.discardConfig(), protect: this.configDraft.protect, + discard: () => this.discardConfig(), protect: this.configDraft.protect, rebase: this.configDraft.rebase, }; registerDraft('config', this.configSource); onStaleDiscard(() => { void this.load().catch(() => {}); }); @@ -134,6 +135,7 @@ class Live { restore: (saved, discarded) => this.update(s => ({ config: { ...s.config, ...Object.fromEntries(Object.entries(saved).filter(([key]) => Object.hasOwn(discarded, key))) } })), protect: (state, intent) => ({ ...state, config: deepMerge(state.config, intent) }), + rebase: (server, saved) => (server.config ? { ...saved, ...server.config } as Config : undefined), }); this.programSource = this.programDraft; registerDraft('program', this.programSource); @@ -302,17 +304,17 @@ class Live { on('persistence', p => { this.touchStatus({ persistence: p }); this.update(s => ({ status: { ...s.status, persistence: p } })); }); on('pause', p => { this.touchStatus({ pause: p }); this.update(s => ({ status: { ...s.status, pause: p } })); }); on('history', h => this.update(() => ({ history: h }))); - on('interactive', i => this.update(() => ({ interactive: i }))); + on('interactive', i => { rebaseDrafts({ interactive: i }); this.update(() => ({ interactive: i })); }); on('viewers', v => this.update(() => ({ viewers: v }))); on('teleprompter', t => this.update(() => ({ teleprompter: t }))); - on('theme', ({ alertPreviews, ...theme }) => this.update(() => ({ + on('theme', ({ alertPreviews, ...theme }) => (rebaseDrafts({ theme }), this.update(() => ({ theme, // Preserve confirmed fingerprints outside protectDrafts' editable theme/config. ...(alertPreviews ? { alertPreviews } : {}), - }))); + })))); on('timers', t => this.update(() => ({ timers: t }))); // Overlays propios: la lista completa en cada cambio (panel, MCP o API). - on('customOverlays', list => this.update(() => ({ customOverlays: list }))); + on('customOverlays', list => { rebaseDrafts({ customOverlays: list }); this.update(() => ({ customOverlays: list })); }); on('customOverlayCss', css => this.update(s => ({ config: { ...s.config, customOverlayCss: css } }))); on('meld', m => this.update(s => ({ meld: { ...s.meld, session: m } }))); // El evento 'widgets' trae la ventana corta del overlay (50): el panel conserva SU @@ -320,7 +322,15 @@ class Live { // limpiezas llegan por chatDelete/chatClear y el snapshot de load() manda al reconectar. on('widgets', w => { this.widgetsTouch++; - this.update(s => ({ widgets: { ...w, chat: s.widgets?.chat ?? w.chat } })); + // #351: the event also carries the saved widget settings (engine.widgetState()). Keep + // config.widgets current so open forms see changes made outside the panel (MCP, another + // window); draft protection puts any unsaved local edit back on top in update(). + const saved = (w as { widgets?: unknown }).widgets as AppState['config']['widgets'] | undefined; + if (saved) rebaseDrafts({ config: { widgets: saved } }); + this.update(s => ({ + widgets: { ...w, chat: s.widgets?.chat ?? w.chat }, + ...(saved && s.config && !sameContent(s.config.widgets, saved) ? { config: { ...s.config, widgets: saved } } : {}), + })); }); on('chat', m => { for (const ids of this.inflightChat) ids.add(m.id); @@ -341,6 +351,8 @@ class Live { on('prompter', p => { this.prompter = { ...this.prompter, ...p }; this.emit(); }); on('config', c => { const changed = observeActiveTheme(c.themes?.activeId); + // A theme switch sends another theme's values: those drafts become stale, never rebased. + if (!changed) rebaseDrafts({ config: c }); this.update(s => ({ config: { ...s.config, ...c } })); // Keep stale edits visible until Discard; otherwise synchronize all swapped sections. if (changed && !isStale()) void this.load().catch(() => {}); diff --git a/app/src/lib/manual-draft.ts b/app/src/lib/manual-draft.ts index b688226..3c99573 100644 --- a/app/src/lib/manual-draft.ts +++ b/app/src/lib/manual-draft.ts @@ -1,6 +1,6 @@ // One manual source: prepared intent is separate from edits made after the click. // Adapters supply domain snapshots/merging; this buffer never schedules an autosave. -import { draftChanged, saveSources, themeIdentity, type DraftSource, type PreparedSave } from './draft'; +import { draftChanged, saveSources, themeIdentity, type DraftSource, type PreparedSave, type ServerSnapshot } from './draft'; import type { AppState } from './types'; type Options

= { @@ -13,6 +13,8 @@ type Options

= { restore: (saved: B, discarded: P) => void; keys?: (patch: P) => string[]; protect?: (state: AppState, intent: P) => AppState; + /** #351: the baseline matching what the server just sent, or undefined when it does not apply. */ + rebase?: (server: ServerSnapshot, saved: B) => B | undefined; }; export class ManualDraft

implements DraftSource { @@ -79,6 +81,13 @@ export class ManualDraft

implements DraftSource { if (saved && this.active) this.options.restore(saved.value, discarded); draftChanged(); }; + /** #351: Discard restores the latest saved value. Never during a save (run() resets the + * baseline) nor for a draft of another theme (its baseline belongs to that theme). */ + rebase = (server: ServerSnapshot) => { + if (!this.baseline || this.intent || this.stale() || !this.options.rebase) return; + const next = this.options.rebase(server, this.baseline.value); + if (next !== undefined) this.baseline = { value: structuredClone(next) }; + }; updateBaseline(update: (saved: B) => B) { if (this.baseline) this.baseline = { value: update(this.baseline.value) }; } diff --git a/app/src/lib/patch.ts b/app/src/lib/patch.ts index 792df95..d82aeec 100644 --- a/app/src/lib/patch.ts +++ b/app/src/lib/patch.ts @@ -3,7 +3,7 @@ import { api } from './api'; import { deepMerge, live } from './live'; import { toast } from './ui'; -import { flushSources, holding, registerDraft, type DraftSource } from './draft'; +import { flushSources, holding, registerDraft, type DraftSource, type ServerSnapshot } from './draft'; import { ManualDraft } from './manual-draft'; import type { AppState, WidgetsConfig } from './types'; @@ -13,6 +13,8 @@ type Snapshot = { restore: (saved: B) => void; persist?: (sent: Patch, themeId?: string) => Promise; protect: (state: AppState, intent: Patch) => AppState; + /** #351: this source's saved value inside a server snapshot, if it carries one. */ + rebase?: (server: ServerSnapshot) => B | undefined; }; export function patcher(method: string, url: string, snap: Snapshot, ms = 400) { let timer: ReturnType | undefined; @@ -27,6 +29,7 @@ export function patcher(method: string, url: string, snap: Sna }, publish: (saved, newer) => snap.restore(deepMerge(saved, newer)), restore: snap.restore, protect: snap.protect, + rebase: snap.rebase ? server => snap.rebase!(server) : undefined, }); const sendAutomatic = async () => { clearTimeout(timer); @@ -49,7 +52,7 @@ export function patcher(method: string, url: string, snap: Sna }; const discard = () => { clearTimeout(timer); buffer.discard(); }; const source: DraftSource = { - dirty: buffer.dirty, stale: buffer.stale, keys: buffer.keys, protect: buffer.protect, + dirty: buffer.dirty, stale: buffer.stale, keys: buffer.keys, protect: buffer.protect, rebase: buffer.rebase, prepareSave: () => { clearTimeout(timer); return buffer.prepareSave(); }, discard, }; registerDraft(url, source); @@ -61,6 +64,7 @@ const W = patcher('PUT', '/api/widgets', { restore: saved => live.update(s => ({ config: { ...s.config, widgets: saved } })), persist: async (sent, themeId) => (await api<{ widgets: WidgetsConfig }>('PUT', '/api/widgets', sent, { themeId })).widgets, protect: (state, intent) => ({ ...state, config: { ...state.config, widgets: deepMerge(state.config.widgets, intent) } }), + rebase: server => server.config?.widgets, }); export function patchWidgets(patch: Patch) { W.push(patch); // captures the original before mutating live; later edits keep that copy @@ -71,6 +75,7 @@ const IX = patcher('PUT', '/api/interactive/config', { take: () => live.state!.interactive.config, restore: saved => live.update(s => ({ interactive: { ...s.interactive, config: saved } })), protect: (state, intent) => ({ ...state, interactive: { ...state.interactive, config: deepMerge(state.interactive.config, intent) } }), + rebase: server => server.interactive?.config, }); export function patchIx(section: string, patch: Patch) { IX.push({ [section]: patch }); // capture before the first optimistic edit (S1) diff --git a/app/src/panel/views/Apariencia.tsx b/app/src/panel/views/Apariencia.tsx index e5d1f7c..69ad2c3 100644 --- a/app/src/panel/views/Apariencia.tsx +++ b/app/src/panel/views/Apariencia.tsx @@ -49,7 +49,11 @@ export function Apariencia({ parts }: { parts: string[] }) { publish: (saved, newer) => { info.current = saved; live.update(() => ({ theme: deepMerge(saved.theme, newer) })); }, restore: saved => { info.current = saved; live.update(() => ({ theme: saved.theme })); }, protect: (state, intent) => ({ ...state, theme: deepMerge(state.theme, intent) }), + // #351: Discard restores the theme as last saved, even when saved elsewhere (MCP, another window). + rebase: (server, saved) => (server.theme ? { ...saved, theme: server.theme } : undefined), })); + // Without a draft the live theme is the saved one: keep the next draft's baseline current too. + useEffect(() => { if (info.current && t && !buffer.dirty()) info.current = { ...info.current, theme: t }; }, [t, buffer]); const load = guard(async () => { const loaded = await get('/api/theme'); if (!active.current) return; @@ -70,7 +74,7 @@ export function Apariencia({ parts }: { parts: string[] }) { useEffect(() => { load(); const unregister = registerDraft('theme', { - dirty: buffer.dirty, stale: buffer.stale, keys: buffer.keys, protect: buffer.protect, + dirty: buffer.dirty, stale: buffer.stale, keys: buffer.keys, protect: buffer.protect, rebase: buffer.rebase, prepareSave: () => { clearTimeout(timer.current); return buffer.prepareSave(); }, discard, }); return () => { active.current = false; clearTimeout(timer.current); clearTimeout(sampleTimer.current); unregister(); buffer.dispose(); }; diff --git a/app/src/panel/views/ChatWidget.tsx b/app/src/panel/views/ChatWidget.tsx index a7e82f6..4954ca0 100644 --- a/app/src/panel/views/ChatWidget.tsx +++ b/app/src/panel/views/ChatWidget.tsx @@ -59,8 +59,8 @@ function VariantFields({ id, initial, anims, refresh }: { id: string; initial: C keys: () => ['chat'], persist: async (changes, themeId) => { await put<{ variant: ChatVariant }>(`${ROUTE}/${enc(id)}`, changes, { themeId }); - // A PUT reply only describes this id and widgets events do not update config.widgets. - // Re-read before publishing so a concurrent change to another variant is not overwritten. + // A PUT reply only describes this id. Re-read before publishing so a concurrent change to + // another variant is not overwritten (widgets events also refresh config.widgets, #351). let variants: ChatVariant[]; try { variants = await refresh(); } catch { throw new Error('Se guardó el cambio, pero no se pudo actualizar la lista. Reintenta antes de cambiar de variante.'); } @@ -70,6 +70,8 @@ function VariantFields({ id, initial, anims, refresh }: { id: string; initial: C }, publish: (result, newer) => { savedRef.current = result; setSaved(result); setDraft(newer); }, restore: result => { savedRef.current = result; setSaved(result); setDraft({}); }, + // #351: Discard restores this variant as last saved, even when saved elsewhere. + rebase: server => server.config?.widgets?.chatVariants?.find(v => v.id === id), })); useEffect(() => { const unregister = registerDraft('chat-variant:' + id, buffer); diff --git a/app/src/panel/views/Editor.tsx b/app/src/panel/views/Editor.tsx index a8dde60..ffbd7d0 100644 --- a/app/src/panel/views/Editor.tsx +++ b/app/src/panel/views/Editor.tsx @@ -174,6 +174,12 @@ function useEditor(t: Target) { publish: (saved, newer) => live.update(s => ({ config: overlay({ ...s, ...replaceTarget(s, t, saved) }, newer).config })), restore: saved => live.update(s => replaceTarget(s, t, saved)), protect: overlay, + // #351: Discard restores this alert/command/timer as last saved, even if saved elsewhere. + rebase: server => { + const section = t.kind === 'command' ? 'commands' : t.kind === 'timer' ? 'timers' : 'alerts'; + if (!server.config || !Object.hasOwn(server.config, section)) return undefined; + return findTarget({ config: server.config }, t); // undefined when deleted remotely: keep the baseline + }, }); }); const preview = async () => { @@ -199,7 +205,7 @@ function useEditor(t: Target) { }; useEffect(() => { const unregister = registerDraft('editor:' + JSON.stringify(t), { - dirty: buffer.dirty, stale: buffer.stale, keys: buffer.keys, protect: buffer.protect, + dirty: buffer.dirty, stale: buffer.stale, keys: buffer.keys, protect: buffer.protect, rebase: buffer.rebase, prepareSave: () => { clearTimeout(timer.current); return buffer.prepareSave(); }, discard, }); return () => { active.current = false; clearTimeout(timer.current); unregister(); buffer.dispose(); }; diff --git a/app/src/panel/views/Overlays.tsx b/app/src/panel/views/Overlays.tsx index 2a74e6f..da8f807 100644 --- a/app/src/panel/views/Overlays.tsx +++ b/app/src/panel/views/Overlays.tsx @@ -94,6 +94,8 @@ function OverlaySlide({ id }: { id: string }) { live.update(s => ({ customOverlays: (s.customOverlays || []).map(o => (o.id === baseline.id ? baseline : o)) })); }, restore: baseline => { savedRef.current = baseline; setSaved(baseline); setDraft(null); setPending(null); }, + // #351: Discard restores the overlay as last saved, even when the agent changed it meanwhile. + rebase: server => server.customOverlays?.find(o => o.id === id), })); useEffect(() => { const unregister = registerDraft('overlay:' + id, buffer); diff --git a/docs/releases/v0.21.0.md b/docs/releases/v0.21.0.md index 0eaabc7..9ce9f59 100644 --- a/docs/releases/v0.21.0.md +++ b/docs/releases/v0.21.0.md @@ -4,7 +4,7 @@ Crea widgets que se configuran con un formulario, muestra tus redes sociales en ### Novedades -- **Personalizados con campos de ajustes:** un overlay propio puede declarar campos (texto, número, interruptor, selección, color, lista o archivo) y se configura desde un formulario en el panel, sin tocar el código. Los valores llegan a la capa en directo sin recargarla. Tu agente puede crearlos y rellenarlos por MCP, así que puedes tener widgets nuevos sin esperar a una versión de antena. +- **Personalizados con campos de ajustes:** un overlay propio puede declarar campos (texto, número, interruptor, selección, color, lista o archivo) y se configura desde un formulario en el panel, sin tocar el código. Los valores llegan a la capa en directo sin recargarla. Tu agente puede crearlos y rellenarlos por MCP, así que puedes tener widgets nuevos con los datos que ya ofrece antena sin esperar a una versión. - **La sección «Overlays» ahora se llama «Personalizados»:** solo cambia el nombre en el panel. Las direcciones de tus fuentes de navegador (`/custom/…`) y las herramientas MCP siguen igual. - **Redes sociales:** nuevo widget con tus perfiles en una barra, cada uno con el icono de su plataforma y tu nick. Admite Twitch, YouTube, X, Instagram, TikTok, GitHub, Discord, Kick, LinkedIn y tu web, hasta 12 redes en el orden que elijas, con etiqueta opcional y CSS propio. - **Ticker con página propia:** el ticker ya no comparte página con **Últimos**. Tiene su propia fuente, vista previa y ajustes, y puedes elegir qué tipos de apoyo recorre. Mientras no los cambies, sigue usando los mismos que **Últimos**, así que tu configuración actual no cambia. diff --git a/src/server.mjs b/src/server.mjs index 7d66703..395abd3 100644 --- a/src/server.mjs +++ b/src/server.mjs @@ -514,10 +514,16 @@ export async function createApp({ dataDir, mediaDir = process.env.ANTENA_MEDIA | // #39: an open dock follows saved layout/module and shortcut changes without reloading. let includeDockConfig = false; let includeThemesConfig = false; + // #351: sections the panel edits that only reach it through this event. Once one changes + // outside the panel (MCP, another window, generic config API, import), it travels in every + // later config event too, so an open form never keeps a stale value to save back. + const PANEL_CONFIG_SECTIONS = ['overlay', 'commands', 'timers', 'filters', 'tts', 'meld', 'youtube', 'twitch', 'panel', 'sessions']; + const includedSections = new Set(); const pushPanelConfig = () => { const config = store.publicConfig(); bus.send('config', { prompter: store.config.prompter, chat: store.config.chat, alerts: config.alerts, + ...Object.fromEntries([...includedSections].map(key => [key, config[key]])), ...(includeProgramConfig ? { program: config.program, obs: config.obs } : {}), ...(includeDiscordConfig ? { discord: config.discord } : {}), ...(includeScheduleConfig ? { scheduleCalendar: config.scheduleCalendar } : {}), @@ -537,8 +543,16 @@ export async function createApp({ dataDir, mediaDir = process.env.ANTENA_MEDIA | bus.send('theme', { ...publicTheme(store.config.theme), alertPreviews: alertPreviews() }, ['panel']); } if (patch.widgets || patch.all) engine.pushWidgets(); - if (patch.themes && patch.interactive) pushInteractive(); - if (patch.themes && patch.timers) bus.send('timers', timers.snapshot(), ['panel']); + // #351: settings written through the generic config API (or import) reach the panel too; + // these modules read their settings from the store, so the snapshot is current. + if (patch.interactive || patch.all) pushInteractive(); + if (patch.teleprompter || patch.all) bus.send('teleprompter', teleprompter.snapshot(), ['teleprompter', 'panel']); + if (patch.viewers || patch.all) { + const snap = viewers.snapshot(); + bus.send('viewers', snap, ['panel']); + bus.send('viewers', publicViewers(snap), ['widget']); + } + if (patch.timers || patch.all) bus.send('timers', timers.snapshot(), ['panel']); // Overlays editados fuera de sus rutas (PUT /api/config, config/set o el MCP genérico): // mismo par de eventos que onChange, para que la vista previa y las capas se recarguen. if (patch.customOverlays || patch.all) { @@ -550,7 +564,12 @@ export async function createApp({ dataDir, mediaDir = process.env.ANTENA_MEDIA | // Incluye alertas editadas fuera de este panel (MCP, otra ventana, el móvil). if (patch.dock || patch.shortcuts) includeDockConfig = true; if (patch.themes) includeThemesConfig = true; - if (patch.prompter || patch.chat || patch.alerts || patch.dock || patch.shortcuts || patch.themes || patch.all) pushPanelConfig(); + // meld is the legacy alias of program: publish program/obs from this single event. + const programChanged = !!(patch.meld || patch.program || patch.obs); + if (programChanged) includeProgramConfig = true; + const panelSections = PANEL_CONFIG_SECTIONS.filter(key => patch[key] || patch.all); + for (const key of panelSections) includedSections.add(key); + if (patch.prompter || patch.chat || patch.alerts || patch.dock || patch.shortcuts || patch.themes || programChanged || panelSections.length || patch.all) pushPanelConfig(); }); // la persistencia puede fallar sin emitir 'change' (o estar en vuelo): el panel necesita su propio canal store.on('persistence', state => bus.send('persistence', state, ['panel'])); @@ -1154,7 +1173,9 @@ export async function createApp({ dataDir, mediaDir = process.env.ANTENA_MEDIA | // A config import may replace the interviews and the active item. if (patch.interviews) { bus.send('interview', { item: interviews.activeItem() }, ['widget']); bus.send('interviewControl', interviews.control(), ['panel']); } // Publish only after password changes have completed; publicConfig masks the value. - if (patch.program || patch.obs) { includeProgramConfig = true; pushPanelConfig(); } + // Published again here (#351): the store 'change' listener already sent program/obs/meld, but + // only now is the OBS password stored, so this snapshot carries the final passwordSet. + if (patch.program || patch.obs || patch.meld) { includeProgramConfig = true; pushPanelConfig(); } if (patch.scheduleCalendar || patch.all) { if (!store.config.scheduleCalendar?.enabled && scheduleIdentityPending) { scheduleEpoch++; scheduleIdentityPending = false; diff --git a/test/config-snapshot-coalescing.test.mjs b/test/config-snapshot-coalescing.test.mjs index 94f3af7..2afd479 100644 --- a/test/config-snapshot-coalescing.test.mjs +++ b/test/config-snapshot-coalescing.test.mjs @@ -43,7 +43,9 @@ const viewPatch = { chat: { sendTo: 'both' }, prompter: { fontSize: 30 } }; const alertsPatch = { alerts: { follow: { title: 'Updated synthetic alert' } } }; const snapshot = store => ({ prompter: store.config.prompter, chat: store.config.chat, alerts: store.publicConfig().alerts }); -function verify({ store, slow, healthy, outsiders }) { +// #351: after a full change (import), the snapshot also carries the other panel-edited sections. +const PANEL_SECTIONS = ['overlay', 'commands', 'timers', 'filters', 'tts', 'meld', 'youtube', 'twitch', 'panel', 'sessions']; +function verify({ store, slow, healthy, outsiders }, { all = false } = {}) { assert.equal(slow.configs().length, 1, 'queued config must wait for drain'); slow.emit('drain'); const delivered = slow.configs(); @@ -52,11 +54,13 @@ function verify({ store, slow, healthy, outsiders }) { assert.equal(merged.chat.sendTo, 'both', 'drain must not leave chat at its old value'); assert.equal(merged.prompter.fontSize, 30, 'drain must not leave prompter at its old value'); assert.equal(merged.alerts.follow.title, alertsPatch.alerts.follow.title); - assert.deepEqual(delivered.at(-1), snapshot(store), 'retained config is self-contained'); + const expected = all ? { ...snapshot(store), ...Object.fromEntries(PANEL_SECTIONS.map(k => [k, store.publicConfig()[k]])) } : snapshot(store); + assert.deepEqual(delivered.at(-1), expected, 'retained config is self-contained'); for (const config of healthy.configs()) { - assert.deepEqual(Object.keys(config).sort(), ['alerts', 'chat', 'prompter'], 'no extra config sections or credentials'); + assert.deepEqual(Object.keys(config).filter(k => !(all && PANEL_SECTIONS.includes(k))).sort(), ['alerts', 'chat', 'prompter'], 'no extra config sections or credentials'); + assert.doesNotMatch(JSON.stringify(config), /SYNTHETIC_TEST_ACCESS/, 'the access key never reaches the panel snapshot'); } - assert.deepEqual(healthy.configs().at(-1), snapshot(store)); + assert.deepEqual(healthy.configs().at(-1), expected); for (const res of outsiders) assert.equal(res.configs().length, 0, 'config remains panel-only'); } @@ -85,15 +89,16 @@ test('patch.all emits exactly one complete panel snapshot', async t => { const before = app.healthy.configs().length; app.store.emit('change', { all: true }); assert.equal(app.healthy.configs().length, before + 1); - verify(app); + verify(app, { all: true }); }); -test('unrelated config changes do not publish a config snapshot', async t => { +test('global alert settings changed outside the panel publish a config snapshot that keeps them (#351)', async t => { const app = await fixture(t); await app.store.patchConfig({ overlay: { volume: 0.5 } }); - app.slow.emit('drain'); - assert.equal(app.slow.configs().length, 1); - assert.equal(app.healthy.configs().length, 1); + assert.equal(app.healthy.configs().length, 2, 'the overlay change reaches the panel'); + assert.equal(app.healthy.configs().at(-1).overlay.volume, 0.5); + await app.store.patchConfig(viewPatch); + assert.equal(app.healthy.configs().at(-1).overlay.volume, 0.5, 'later config events keep carrying overlay'); for (const res of app.outsiders) assert.equal(res.configs().length, 0); }); diff --git a/test/config-versioning.test.mjs b/test/config-versioning.test.mjs index d070532..ffc0340 100644 --- a/test/config-versioning.test.mjs +++ b/test/config-versioning.test.mjs @@ -192,7 +192,9 @@ test('un cambio por alias publica program en el SSE y conserva ese estado en el let event = await nextConfig(); assert.deepEqual(event.program, { kind: 'meld', autoSession: false, recordOnStart: true }); assert.equal((await f.call('PUT', '/api/config', { chat: { sendTo: 'youtube' } })).status, 200); - event = await nextConfig(); + // #351: a program write may publish twice (store change, then after the OBS password is + // stored); wait for the event that carries the chat change. + do event = await nextConfig(); while (event.chat.sendTo !== 'youtube'); assert.equal(event.chat.sendTo, 'youtube'); assert.deepEqual(event.program, { kind: 'meld', autoSession: false, recordOnStart: true }); await reader.cancel(); ctrl.abort(); }); diff --git a/test/groups.json b/test/groups.json index 06dd971..2a51d25 100644 --- a/test/groups.json +++ b/test/groups.json @@ -76,6 +76,7 @@ "test/overlay-queue-cap.test.mjs", "test/overlay-queue-protected-types.test.mjs", "test/overlay-theme-deferral.test.mjs", + "test/panel-config-sync.test.mjs", "test/panel-tokens.test.mjs", "test/platform-icons.test.mjs", "test/program-boundary.test.mjs", @@ -254,6 +255,7 @@ "test/widget-layout-browser.test.mjs", "test/widget-preview-save-browser.test.mjs", "test/widget-slot-mode.test.mjs", + "test/widgets-remote-sync-browser.test.mjs", "test/ws-layers-browser.test.mjs", "test/youtube-subscriber-count-browser.test.mjs", "test/youtube-subscriber-overlay-browser.test.mjs" diff --git a/test/panel-config-sync.test.mjs b/test/panel-config-sync.test.mjs new file mode 100644 index 0000000..67759bc --- /dev/null +++ b/test/panel-config-sync.test.mjs @@ -0,0 +1,117 @@ +// #351: every config section the panel edits reaches it when it changes outside the panel +// (MCP, another window, generic config API, import), and keeps travelling in later config +// events because the bus retains only the latest 'config' snapshot per client. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import { mkdtemp } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createApp } from '../src/server.mjs'; + +function sink() { + const res = new EventEmitter(); + res.frames = []; + res.writableLength = 0; + res.write = frame => { res.frames.push(frame); return true; }; + res.events = name => res.frames.filter(f => f.startsWith(`event: ${name}\n`)).map(f => JSON.parse(f.split('\ndata: ')[1])); + return res; +} + +async function fixture(t) { + const dir = await mkdtemp(path.join(tmpdir(), 'antena-panel-config-sync-')); + const app = await createApp({ dataDir: dir, mediaDir: path.join(dir, 'media'), log: () => {} }); + t.after(() => app.closeHttp()); + const panel = sink(), widget = sink(); + app.bus.addClient(panel, 'panel'); + app.bus.addClient(widget, 'widget'); + return { app, panel, widget, last: () => panel.events('config').at(-1) }; +} + +const CHANGES = [ + ['overlay', { overlay: { css: '.alert { color: red; }', volume: 0.4 } }, c => c.overlay.css === '.alert { color: red; }' && c.overlay.volume === 0.4], + ['commands', { commands: [{ id: 'hola', trigger: '!hola', response: 'Hola' }] }, c => c.commands?.[0]?.trigger === '!hola'], + ['timers', { timers: [{ id: 't1', message: 'Sígueme', intervalMin: 10, enabled: true }] }, c => c.timers?.[0]?.message === 'Sígueme'], + ['filters', { filters: { blockedWords: ['spoiler'] } }, c => c.filters?.blockedWords?.[0] === 'spoiler'], + ['tts', { tts: { rate: 1.2 } }, c => c.tts?.rate === 1.2], + ['meld', { meld: { autoSession: true } }, c => c.meld?.autoSession === true], + ['panel', { panel: { onboardingDone: true } }, c => c.panel?.onboardingDone === true], +]; + +test('each panel-edited section changed outside the panel reaches it and keeps travelling', async t => { + const { app, panel, widget, last } = await fixture(t); + for (const [name, patch, check] of CHANGES) { + const before = panel.events('config').length; + await app.store.patchConfig(patch); + assert.ok(panel.events('config').length > before, `${name}: a config event reaches the panel`); + assert.ok(check(last()), `${name}: the panel gets the new value`); + } + // Sticky: the latest snapshot still carries every section changed before it. + for (const [name, , check] of CHANGES) assert.ok(check(last()), `${name}: still present in the latest config event`); + assert.equal(widget.events('config').length, 0, 'config stays panel-only'); +}); + +// Built at runtime so no key-shaped literal lands in the source (scanner convention, see .gitleaksignore). +const FAKE_KEY = ['SYNTHETIC', 'YT', 'KEY', '1234'].join('_'); + +test('secrets stay masked in the config sections sent to the panel', async t => { + const { app, last } = await fixture(t); + await app.store.patchConfig({ youtube: { apiKey: FAKE_KEY } }); + const sent = last(); + assert.ok(sent.youtube, 'youtube settings reach the panel'); + assert.notEqual(sent.youtube.apiKey, FAKE_KEY); + assert.match(sent.youtube.apiKey, /^••••/); + assert.ok(!JSON.stringify(sent).includes(FAKE_KEY)); +}); + +test('a timers change also refreshes the timers list the panel shows', async t => { + const { app, panel } = await fixture(t); + const before = panel.events('timers').length; + await app.store.patchConfig({ timers: [{ id: 't1', message: 'Sígueme', intervalMin: 10, enabled: true }] }); + assert.ok(panel.events('timers').length > before, 'the timers snapshot reaches the panel'); +}); + +test('config import (all) sends every panel-edited section at once', async t => { + const { app, last } = await fixture(t); + app.store.emit('change', { all: true }); + const sent = last(); + for (const key of ['prompter', 'chat', 'alerts', 'overlay', 'commands', 'timers', 'filters', 'tts', 'meld', 'youtube', 'twitch', 'panel', 'sessions']) { + assert.ok(Object.hasOwn(sent, key), `${key} is part of the full snapshot`); + } +}); + +test('interactive, teleprompter and viewers settings written through the generic config reach the panel', async t => { + const { app, panel } = await fixture(t); + const wait = ms => new Promise(r => setTimeout(r, ms)); + for (const [section, event] of [['interactive', 'interactive'], ['teleprompter', 'teleprompter'], ['viewers', 'viewers']]) { + const before = panel.events(event).length; + await app.store.patchConfig({ [section]: {} }); // e.g. PUT /api/config or /api/config/set from MCP + await wait(250); // interactive snapshots are burst-coalesced + assert.ok(panel.events(event).length > before, `${section}: the panel gets a fresh ${event} snapshot`); + } +}); + +test('meld connect/disconnect and OBS password writes reach the panel with correct passwordSet and no secret in any client', async t => { + const { app, panel, widget } = await fixture(t); + for (const o of [app.meld, app.program, app.obs].filter(Boolean)) o.start = () => {}; // never touch a real Meld/OBS + await new Promise((r, j) => { app.server.once('error', j); app.server.listen(0, '127.0.0.1', r); }); + const base = `http://127.0.0.1:${app.server.address().port}`; + const call = (m, u, b) => fetch(base + u, { method: m, headers: { 'content-type': 'application/json' }, body: JSON.stringify(b ?? {}) }); + const last = () => panel.events('config').at(-1); + assert.equal((await call('PUT', '/api/config', { obs: { password: 'SYNTH_OBS_PW_1' } })).status, 200); + assert.equal(last().obs.passwordSet, true); + assert.equal((await call('POST', '/api/config/set', { path: 'obs.password', value: '' })).status, 200); + assert.equal(last().obs.passwordSet, false); + assert.equal((await call('POST', '/api/meld/connect')).status, 200); + assert.equal(last().meld.enabled, true); + assert.equal((await call('POST', '/api/meld/disconnect')).status, 200); + assert.equal(last().meld.enabled, false); + for (const f of [...panel.frames, ...widget.frames]) assert.doesNotMatch(f, /SYNTH_OBS_PW_1/); +}); + +test('viewers written through the generic config send only the public projection to widgets', async t => { + const { app, panel, widget } = await fixture(t); + await app.store.patchConfig({ viewers: {} }); + assert.deepEqual(Object.keys(widget.events('viewers').at(-1)).sort(), ['twitch', 'youtube']); + assert.ok(Object.hasOwn(panel.events('viewers').at(-1), 'settings')); +}); diff --git a/test/widgets-remote-sync-browser.test.mjs b/test/widgets-remote-sync-browser.test.mjs new file mode 100644 index 0000000..d2e1910 --- /dev/null +++ b/test/widgets-remote-sync-browser.test.mjs @@ -0,0 +1,148 @@ +// #351: a widget change made outside the panel (MCP, another window) reaches an open form, +// a later save does not write the stale value back, and unsaved local edits survive it. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createApp } from '../src/server.mjs'; +import { closeAll, closeChrome, openChromePage, skipIfNoBrowserOrUi, waitDom } from './helpers/react-browser.mjs'; +import { evaluateChrome } from './helpers/chrome-dom.mjs'; + +const CSS = `[...document.querySelectorAll('main label')].find(l => l.textContent.trim().startsWith('CSS de «últimos»'))?.querySelector('textarea')`; +const LABEL = `document.querySelector('main input[placeholder^="Últimos"]')`; +const SAVE = `[...document.querySelectorAll('button')].find(b => /^Guardar/.test(b.textContent.trim()) && !b.disabled)`; +const SAVED = `document.querySelector('.lv-dirty')?.textContent === 'Todo guardado'`; +const type = (el, value) => `(() => { const el = ${el}; Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), 'value').set.call(el, ${JSON.stringify(value)}); el.dispatchEvent(new Event('input', { bubbles: true })); return true; })()`; + +async function start(t) { + const dataDir = await mkdtemp(path.join(tmpdir(), 'antena-widgets-remote-sync-')); + t.after(() => rm(dataDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })); + const app = await createApp({ dataDir, mediaDir: path.join(dataDir, 'media'), log: () => {} }); + await new Promise(r => app.server.listen(0, '127.0.0.1', r)); + const base = `http://127.0.0.1:${app.server.address().port}`; + const put = async (url, body) => { const r = await fetch(base + url, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); assert.equal(r.status, 200, url); }; + await put('/api/config', { panel: { onboardingDone: true } }); + return { app, base, put, stop: () => { app.viewers.stop(); app.meld.stop(); app.server.closeAllConnections(); app.server.close(); } }; +} + +test('a remote widget change reaches the open form and a later save does not overwrite it', { timeout: 120000 }, async t => { + const bin = await skipIfNoBrowserOrUi(t); + if (!bin) return; + const { app, base, put, stop } = await start(t); + let chrome; + try { + chrome = await openChromePage(bin, base + '/#/widgets/latest'); + const c = chrome.cdp, ev = s => evaluateChrome(c, s); + await waitDom(c, `!!(${CSS}) && !!(${LABEL})`, { timeoutMs: 15000 }); + assert.equal(await ev(`${CSS}.value`), ''); + + await put('/api/widgets', { latest: { css: '.remote { color: red; }' } }); // MCP / another window + await waitDom(c, `${CSS}.value === '.remote { color: red; }'`, { timeoutMs: 8000 }); + + await ev(type(LABEL, 'Gracias por el apoyo')); + await waitDom(c, `!!(${SAVE})`, { timeoutMs: 5000 }); + await ev(`${SAVE}.click(); true`); + await waitDom(c, SAVED, { timeoutMs: 8000 }); + assert.equal(app.store.config.widgets.latest.label, 'Gracias por el apoyo'); + assert.equal(app.store.config.widgets.latest.css, '.remote { color: red; }', 'the remote change is kept'); + } finally { + await closeAll(() => chrome && closeChrome(chrome), stop); + } +}); + +test('an unsaved local edit survives a remote change to another field', { timeout: 120000 }, async t => { + const bin = await skipIfNoBrowserOrUi(t); + if (!bin) return; + const { app, base, put, stop } = await start(t); + let chrome; + try { + chrome = await openChromePage(bin, base + '/#/widgets/latest'); + const c = chrome.cdp, ev = s => evaluateChrome(c, s); + await waitDom(c, `!!(${CSS}) && !!(${LABEL})`, { timeoutMs: 15000 }); + await ev(type(CSS, '.mine { color: blue; }')); + await waitDom(c, `!!(${SAVE})`, { timeoutMs: 5000 }); + + await put('/api/widgets', { latest: { label: 'Remoto' } }); + await waitDom(c, `${LABEL}.value === 'Remoto'`, { timeoutMs: 8000 }); + assert.equal(await ev(`${CSS}.value`), '.mine { color: blue; }', 'the local edit stays visible'); + + await ev(`${SAVE}.click(); true`); + await waitDom(c, SAVED, { timeoutMs: 8000 }); + assert.equal(app.store.config.widgets.latest.css, '.mine { color: blue; }'); + assert.equal(app.store.config.widgets.latest.label, 'Remoto', 'the remote change to another field is kept'); + } finally { + await closeAll(() => chrome && closeChrome(chrome), stop); + } +}); + +test('the global alert CSS changed outside the panel reaches the open alert editor (#351)', { timeout: 120000 }, async t => { + const bin = await skipIfNoBrowserOrUi(t); + if (!bin) return; + const { app, base, put, stop } = await start(t); + let chrome; + try { + chrome = await openChromePage(bin, base + '/#/alertas/follow/css'); + const c = chrome.cdp, ev = s => evaluateChrome(c, s); + const tab = `[...document.querySelectorAll('main button, main [role=radio]')].find(b => b.textContent.trim() === 'Todas las alertas')`; + const GLOBAL = `[...document.querySelectorAll('main textarea')].find(x => (x.placeholder || '').startsWith('/* Se aplica a TODAS las alertas'))`; + await waitDom(c, `!!(${tab})`, { timeoutMs: 15000 }); + await ev(`${tab}.click(); true`); + await waitDom(c, `!!(${GLOBAL})`, { timeoutMs: 5000 }); + await put('/api/config', { overlay: { css: '.alert { --accent: #00E0FF; }' } }); // MCP css_global / another window + await waitDom(c, `${GLOBAL}.value === '.alert { --accent: #00E0FF; }'`, { timeoutMs: 8000 }); + assert.equal(app.store.config.overlay.css, '.alert { --accent: #00E0FF; }'); + } finally { + await closeAll(() => chrome && closeChrome(chrome), stop); + } +}); + +test('Discard after a remote change restores the latest saved values, not older ones (#351)', { timeout: 120000 }, async t => { + const bin = await skipIfNoBrowserOrUi(t); + if (!bin) return; + const { app, base, put, stop } = await start(t); + let chrome; + try { + await put('/api/widgets', { latest: { css: '.saved { color: green; }' } }); + chrome = await openChromePage(bin, base + '/#/widgets/latest'); + const c = chrome.cdp, ev = s => evaluateChrome(c, s); + await waitDom(c, `!!(${CSS}) && ${CSS}.value === '.saved { color: green; }' && !!(${LABEL})`, { timeoutMs: 15000 }); + await ev(type(CSS, '.mine { color: blue; }')); + await waitDom(c, `!!(${SAVE})`, { timeoutMs: 5000 }); + await put('/api/widgets', { latest: { label: 'Remoto' } }); // saved elsewhere while editing + await waitDom(c, `${LABEL}.value === 'Remoto'`, { timeoutMs: 8000 }); + const discard = `[...document.querySelectorAll('button')].find(b => b.textContent.trim() === 'Descartar' && !b.disabled)`; + await ev(`${discard}.click(); true`); + await waitDom(c, `${CSS}.value === '.saved { color: green; }'`, { timeoutMs: 5000 }); + assert.equal(await ev(`${LABEL}.value`), 'Remoto', 'the remote label is not rolled back to the value before it'); + assert.equal(app.store.config.widgets.latest.label, 'Remoto'); + assert.equal(app.store.config.widgets.latest.css, '.saved { color: green; }'); + } finally { + await closeAll(() => chrome && closeChrome(chrome), stop); + } +}); + +test('Discard in the alert editor restores the alert CSS saved elsewhere meanwhile (#351)', { timeout: 120000 }, async t => { + const bin = await skipIfNoBrowserOrUi(t); + if (!bin) return; + const { app, base, put, stop } = await start(t); + let chrome; + try { + await put('/api/alerts/follow', { css: '.alert { --accent: #111111; }' }); + chrome = await openChromePage(bin, base + '/#/alertas/follow/css'); + const c = chrome.cdp, ev = s => evaluateChrome(c, s); + const OWN = `[...document.querySelectorAll('main textarea')].find(x => (x.placeholder || '').startsWith('/* Tu CSS gana'))`; + await waitDom(c, `!!(${OWN}) && ${OWN}.value === '.alert { --accent: #111111; }'`, { timeoutMs: 15000 }); + await ev(type(OWN, '.alert { --accent: #222222; }')); + await waitDom(c, `!!(${SAVE})`, { timeoutMs: 5000 }); + await put('/api/alerts/follow', { css: '.alert { --accent: #333333; }' }); // another window saves this alert + await new Promise(r => setTimeout(r, 600)); + assert.equal(await ev(`${OWN}.value`), '.alert { --accent: #222222; }', 'the local edit stays while it is unsaved'); + const discard = `[...document.querySelectorAll('button')].find(b => b.textContent.trim() === 'Descartar' && !b.disabled)`; + await ev(`${discard}.click(); true`); + await waitDom(c, `${OWN}.value === '.alert { --accent: #333333; }'`, { timeoutMs: 5000 }); + assert.equal(app.store.config.alerts.follow.css, '.alert { --accent: #333333; }'); + } finally { + await closeAll(() => chrome && closeChrome(chrome), stop); + } +});