возможно исправил ошибку таймера с vMix

This commit is contained in:
2026-08-24 15:34:58 +03:00
parent 7d934a6ee6
commit 0ef8378dd1
7 changed files with 184 additions and 47 deletions

View File

@@ -4153,30 +4153,22 @@ function startCustomTooltips() {
}
function vmixCountdownSyncCommands(input, selectedName, millisecondsProvider, action = "start") {
// BUILD101: keep timer transport intentionally small and deterministic.
// Runtime is authoritative. vMix is only reseeded from the current Runtime
// value when the operator changes state; no ACK is required to change the web timer.
const target = { Input: String(input || "").trim(), SelectedName: String(selectedName || "").trim() };
const currentValue = () => {
const milliseconds = typeof millisecondsProvider === "function" ? millisecondsProvider() : millisecondsProvider;
return vmixCountdownValue(milliseconds);
};
if (!target.Input || !target.SelectedName) return [];
if (action === "stop") {
if (action === "stop" || action === "pause") {
return [
{ Function: "StopCountdown", ...target },
{ Function: "SetCountdown", ...target, Value: currentValue },
];
}
if (action === "pause") {
// vMix PauseCountdown is a toggle (pause/resume). SuspendCountdown is the
// deterministic pause-only command, so it cannot accidentally resume a timer.
return [
{ Function: "SuspendCountdown", ...target },
{ Function: "SetCountdown", ...target, Value: currentValue },
];
}
return [
// Hard-sync every launch: freeze any stale title countdown first, sample
// Runtime at actual send time, then start from exactly that value.
{ Function: "SuspendCountdown", ...target },
{ Function: "SetCountdown", ...target, Value: currentValue },
{ Function: "StartCountdown", ...target },
];
@@ -4648,6 +4640,55 @@ function startCustomTooltips() {
return queued;
}
function sendRuntimeVmixTimerSequence(commands) {
// BUILD101: timer transport is deliberately independent from the generic
// shortcut/title queue. The web timer has already changed state before this
// function is called, so Agent/vMix delivery is best-effort and must never
// block the operator from pressing Start/Stop again.
const rawCommands = typeof commands === "function" ? commands() : commands;
const clean = (rawCommands || []).map(compactVmixCommand).filter((command) => command.Function);
if (!clean.length) return Promise.resolve({ ok: true, applied: 0, requested: 0, results: [] });
const request = fetch("/api/hockey/vmix/sequence", {
method: "POST",
cache: "no-store",
credentials: "same-origin",
keepalive: true,
headers: { "Content-Type": "application/json" },
// Intentionally omit sequence_id/button_id. Agent 1.4+ can then send the
// tiny SetCountdown+Start/Stop pair as one vmix.batch instead of waiting
// for several interactive ACK round-trips.
body: JSON.stringify({
commands: clean,
device_id: currentRuntimeVmixDeviceId(),
session_token: currentRuntimeHockeySessionToken(),
}),
}).then(async (response) => {
let payload = {};
try { payload = await response.json(); } catch (_) {}
if (!response.ok) {
console.warn("vMix timer sync skipped", payload?.detail || `HTTP ${response.status}`);
return { ok: false, applied: 0, requested: clean.length, results: [], error: payload?.detail || `HTTP ${response.status}` };
}
const resultRows = Array.isArray(payload?.results) ? payload.results : [];
const successfulCommands = clean.filter((_command, index) => {
const row = resultRows[index];
return !row || row.ok !== false;
});
trackRuntimeOverlayCommands(successfulCommands, null);
if (payload?.overlay_state) applyServerRuntimeOverlayState(payload.overlay_state);
if (payload?.ok === false) console.warn("vMix timer sync partially failed", payload);
return payload;
}).catch((error) => {
console.warn("vMix timer sync unavailable; Runtime continues locally", error);
return { ok: false, applied: 0, requested: clean.length, results: [], error: String(error?.message || error || "vmix_timer_sync_error") };
});
// Do not await this from timer controls. The returned Promise is only useful
// for diagnostics/tests; local Runtime state is never rolled back on failure.
return request;
}
function splitVmixInputs(value) {
return String(value || "").split(/[;,\n]+/).map((item) => item.trim()).filter(Boolean);
}
@@ -4710,7 +4751,7 @@ function startCustomTooltips() {
}
}
if (!commands.length) return false;
await sendRuntimeVmixSequence(commands);
sendRuntimeVmixTimerSequence(commands);
return true;
}
@@ -5024,9 +5065,9 @@ function startCustomTooltips() {
&& (force || assignmentChanged || previous?.running !== true);
if (entry.event.running) {
if (force || assignmentChanged || startingCountdown) {
// BUILD98: deterministic hard sync. Suspend is pause-only in vMix;
// PauseCountdown is a toggle and could accidentally resume a stale timer.
stopCommands.push({ Function: "SuspendCountdown", Input: target.input, SelectedName: target.selected_name });
// BUILD101: while the web penalty is running, only reseed then run.
// Do not inject an extra Stop before every Start; Runtime already owns
// the state and the short SetCountdown+Start pair is enough.
setCommands.push({ Function: "SetCountdown", Input: target.input, SelectedName: target.selected_name, Value: () => vmixCountdownValue(entry.event.remainingMs) });
}
if (startingCountdown) {
@@ -5035,7 +5076,7 @@ function startCustomTooltips() {
} else if (force || assignmentChanged || previous?.running !== false) {
// Freeze the title and seed the exact Runtime value, but never run a
// prepared/paused penalty until the web event itself is running.
stopCommands.push({ Function: "SuspendCountdown", Input: target.input, SelectedName: target.selected_name });
stopCommands.push({ Function: "StopCountdown", Input: target.input, SelectedName: target.selected_name });
setCommands.push({ Function: "SetCountdown", Input: target.input, SelectedName: target.selected_name, Value: () => vmixCountdownValue(entry.event.remainingMs) });
}
} else {
@@ -5098,7 +5139,7 @@ function startCustomTooltips() {
}
// Old plate OUT/Stop first, then set/start the single current countdown, then IN.
const commands = [...outCommands, ...stopCommands, ...setCommands, ...runCommands, ...inCommands];
if (commands.length) await sendRuntimeVmixSequence(commands);
if (commands.length) sendRuntimeVmixTimerSequence(commands);
return commands.length;
}
@@ -5218,9 +5259,13 @@ function startCustomTooltips() {
const penalties = currentHockeyPenaltyEntries();
if (step.sync_vmix_game && step.game_vmix_input) {
if (!gameTimerState) throw new Error(`Основной таймер «${step.game_timer_action_id}» не найден`);
if (!step.game_vmix_selected_name) throw new Error("Выберите Text / SelectedName основного таймера в vMix");
if (step.game_vmix_mode === "text") {
if (!gameTimerState || !step.game_vmix_selected_name) {
console.warn("vMix game timer sync skipped: timer target is incomplete", {
action_id: step.game_timer_action_id || "hockey_game_timer",
input: step.game_vmix_input || "",
selected_name: step.game_vmix_selected_name || "",
});
} else if (step.game_vmix_mode === "text") {
setVmixTimerMirror(step.game_timer_action_id || "hockey_game_timer", step.game_vmix_input, step.game_vmix_selected_name);
commands.push({ Function: "SetText", Input: step.game_vmix_input, SelectedName: step.game_vmix_selected_name, Value: formatTimerValue(gameTimer, gameTimerState) });
} else if (pausing) {
@@ -5245,7 +5290,10 @@ function startCustomTooltips() {
sideEntries.forEach(({ component, event }, index) => {
const target = targets[index] || null;
if (!target?.input) return;
if (!target.selected_name) throw new Error(`Для таймера удаления ${side === "home" ? "HOME" : "AWAY"} выберите Text / SelectedName`);
if (!target.selected_name) {
console.warn(`vMix penalty timer ${side === "home" ? "HOME" : "AWAY"} skipped: SelectedName is empty`, target);
return;
}
const sourceSide = String(event.player?.side || event.side || side);
if (step.penalty_vmix_mode === "text") {
setVmixPenaltyMirror(component, event, target.input, target.selected_name, { stepId: step.id, targetId: target.id, side: sourceSide, overlay: target.overlay });
@@ -5267,17 +5315,21 @@ function startCustomTooltips() {
});
}
const vmixResult = commands.length ? await sendRuntimeVmixSequence(commands, execution) : { ok: true, applied: 0 };
// BUILD101: local timer state is already final at this point. vMix sync is
// fire-and-forget and cannot keep the Shortcut in a "running" state while
// Agent is offline/slow. The next Space press therefore always controls
// Runtime immediately.
if (commands.length) sendRuntimeVmixTimerSequence(commands);
if (step.start_web_game && step.game_vmix_mode === "text" && gameTimer && gameTimerState) {
await pushVmixTimerMirror(gameTimer, gameTimerState, { force: true });
pushVmixTimerMirror(gameTimer, gameTimerState, { force: true }).catch(() => {});
}
if (step.penalty_vmix_mode === "text" && !pausing) {
for (const { component, event } of penalties) {
await pushVmixPenaltyMirror(component, event, { force: true });
}
penalties.forEach(({ component, event }) => {
pushVmixPenaltyMirror(component, event, { force: true }).catch(() => {});
});
}
return { ok: true, action, vmix: vmixResult, penalties: penalties.length };
return { ok: true, action, vmix: { ok: true, queued: commands.length }, penalties: penalties.length };
}
case "delay":
await new Promise((resolve) => setTimeout(resolve, clamp(Number(step.milliseconds) || 0, 0, 10000)));
@@ -5290,13 +5342,33 @@ function startCustomTooltips() {
}
}
function shortcutSequenceTimerControlSteps(sequence) {
return (sequence?.steps || []).filter((step) => step?.enabled !== false && ["timer_command", "hockey_vmix_timers_start"].includes(step?.type));
}
function runShortcutTimerControlsWhileBusy(sequence, meta = {}) {
const timerSteps = shortcutSequenceTimerControlSteps(sequence);
if (!timerSteps.length) return false;
const execution = { sequence_id: "", sequence_name: "", button_id: "" };
timerSteps.forEach((step) => {
// runShortcutSequenceStep performs the local state change synchronously before
// its Promise resolves. BUILD101 timer/vMix transport does not await Agent.
runShortcutSequenceStep(sequence, step, execution).catch((error) => {
console.warn("Timer shortcut while sequence busy failed locally", error);
});
});
return true;
}
async function runShortcutSequence(sequenceOrId, meta = {}) {
const sequence = typeof sequenceOrId === "string" ? shortcutSequenceById(sequenceOrId) : sequenceOrId;
if (!sequence || sequence.enabled === false) return false;
if (state.runningShortcutSequences.has(sequence.id)) {
// Remember at most ONE follow-up action. This makes Start → Stop reliable when
// Agent ACK is still pending, while repeated impatient Space presses cannot
// accumulate five future toggles and flip the timer back and forth later.
// BUILD101: timer controls are never queued behind title/Agent ACK traffic.
// If the timer is already visibly running, the next physical Space press must
// stop it immediately even while some unrelated title command is still waiting.
if (runShortcutTimerControlsWhileBusy(sequence, meta)) return true;
// Non-timer shortcuts keep one safe follow-up action rather than accumulating.
if (!state.pendingShortcutSequenceRuns.has(sequence.id)) {
state.pendingShortcutSequenceRuns.set(sequence.id, { ...meta, queued: true });
}
@@ -13774,7 +13846,7 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
<div class="shortcut-finish-action-list">${timerFinishActionRows(step)}</div>
<div class="shortcut-vmix-inventory-note"><span>${escapeHtml(shortcutInventoryLabel())}</span><small>Для каждого countdown теперь обязательно выбирается конкретный Text / SelectedName. Это исключает отправку времени в первый текстовый элемент по умолчанию.</small></div>
<p class="shortcut-step-note">Режим <b>Countdown vMix</b> рекомендуется и используется по умолчанию: при каждом запуске или продолжении веб сначала отправляет актуальное время через <code>SetCountdown</code>, затем <code>StartCountdown</code>; каждую секунду значение не передаётся. <b>Text mirror</b> оставлен только как режим совместимости для старых титров. Для верхнего счёта используется одна penalty-плашка: при реальном большинстве она показывается на стороне команды преимущества и отсчитывает ближайшее изменение численного состава; при чистом равном обоюдном удалении плашка не выводится. Режим «Все удаления по слотам» оставлен как дополнительный. Действие по окончании показывает выбранный Input в заданном Overlay и автоматически убирает его через указанное время.</p>
<p class="shortcut-step-note">Режим <b>Countdown vMix</b>: веб-таймер является главным. Start сразу меняет состояние Runtime и независимо отправляет <code>SetCountdown → StartCountdown</code> в vMix; Pause/Stop сразу останавливают Runtime и независимо отправляют <code>StopCountdown → SetCountdown</code>. Ошибка Agent не блокирует управление таймером. Каждую секунду значение в vMix не передаётся. <b>Text mirror</b> оставлен только для совместимости со старыми титрами. Для верхнего счёта используется одна penalty-плашка: при реальном большинстве она показывает ближайшее изменение численного состава; при чистом равном обоюдном удалении сама по себе не появляется.</p>
</div>`;
} else if (step.type === "delay") {
body.innerHTML = `<div class="shortcut-step-grid"><label>Задержка, мс<input type="number" min="0" max="10000" step="10" data-step-field="milliseconds" value="${Number(step.milliseconds) || 0}"></label></div>`;