Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitleaksignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
14 changes: 14 additions & 0 deletions app/src/lib/draft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<AppState['config']>;
theme?: AppState['theme'];
interactive?: AppState['interactive'];
customOverlays?: AppState['customOverlays'];
};

const sources = new Map<string, DraftSource>();
Expand Down Expand Up @@ -55,6 +65,10 @@ export const dirtyKeys = () => [...new Set([...sources.values()].flatMap(s => (s
let busy = false;
let operation: Promise<unknown> | 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;
Expand Down
26 changes: 19 additions & 7 deletions app/src/lib/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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(() => {}); });
Expand All @@ -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);
Expand Down Expand Up @@ -302,25 +304,33 @@ 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
// lista de chat (tope 200, #48) y del evento solo toma lo demás. Los borrados y las
// 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);
Expand All @@ -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(() => {});
Expand Down
11 changes: 10 additions & 1 deletion app/src/lib/manual-draft.ts
Original file line number Diff line number Diff line change
@@ -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<P extends object, B> = {
Expand All @@ -13,6 +13,8 @@ type Options<P extends object, B> = {
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<P extends object, B> implements DraftSource {
Expand Down Expand Up @@ -79,6 +81,13 @@ export class ManualDraft<P extends object, B> 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) };
}
Expand Down
9 changes: 7 additions & 2 deletions app/src/lib/patch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -13,6 +13,8 @@ type Snapshot<B extends object> = {
restore: (saved: B) => void;
persist?: (sent: Patch, themeId?: string) => Promise<B>;
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<B extends object>(method: string, url: string, snap: Snapshot<B>, ms = 400) {
let timer: ReturnType<typeof setTimeout> | undefined;
Expand All @@ -27,6 +29,7 @@ export function patcher<B extends object>(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);
Expand All @@ -49,7 +52,7 @@ export function patcher<B extends object>(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);
Expand All @@ -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
Expand All @@ -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)
Expand Down
6 changes: 5 additions & 1 deletion app/src/panel/views/Apariencia.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<ThemeInfo>('/api/theme');
if (!active.current) return;
Expand All @@ -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(); };
Expand Down
6 changes: 4 additions & 2 deletions app/src/panel/views/ChatWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.'); }
Expand All @@ -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);
Expand Down
8 changes: 7 additions & 1 deletion app/src/panel/views/Editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand All @@ -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(); };
Expand Down
2 changes: 2 additions & 0 deletions app/src/panel/views/Overlays.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion docs/releases/v0.21.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Loading