const $ = id => document.getElementById(id); const off = msg => chrome.runtime.sendMessage({ to: "off", ...msg }); const mmss = ms => { const s = Math.floor(ms / 1000); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; }; let S = { state: "idle" }, lastErr = ""; function render() { const go = $("go"), st = $("st"); go.disabled = S.state === "transcribing"; go.textContent = S.state === "recording" ? "Stop + transcribe" : "Start"; st.textContent = { idle: "idle - open a Teams tab and press Start", recording: `REC ${mmss(Date.now() - S.t0)} | ${S.chunks} chunks uploaded${S.failed ? ` | ${S.failed} FAILED (server down?)` : ""} | mic ${S.mic ? "on" : "OFF (grant it)"} | eventi call: ${S.evSent || 0}`, transcribing: `invio alla pipeline...`, done: `inviato alla pipeline — stato e report su http://127.0.0.1:18765/`, error: "ERROR (see below)", }[S.state]; if (S.text) $("txt").textContent = S.text; } async function poll() { if (await chrome.offscreen.hasDocument()) S = (await off({ cmd: "status" })) || S; else S = lastErr ? { state: "error", text: lastErr } : { state: "idle" }; render(); } $("go").onclick = async () => { if (S.state === "recording") { if (S.tabId != null) await chrome.tabs.sendMessage(S.tabId, { cmd: "cap-stop" }).catch(() => {}); await new Promise(r => setTimeout(r, 300)); await off({ cmd: "stop" }); return poll(); } lastErr = ""; try { const [t] = await chrome.tabs.query({ active: true, currentWindow: true }); if (t.url?.startsWith("chrome-extension:")) throw new Error("This is the extension's own page. Switch to the Teams tab, then click the icon."); const id = await chrome.tabCapture.getMediaStreamId({ targetTabId: t.id }); if (!(await chrome.offscreen.hasDocument())) await chrome.offscreen.createDocument({ url: "offscreen.html", reasons: ["USER_MEDIA"], justification: "record tab" }); const r = await off({ cmd: "start", id, tabId: t.id }); if (r?.err) throw new Error(r.err); chrome.tabs.sendMessage(t.id, { cmd: "cap-start" }).catch(() => {}); } catch (e) { lastErr = String(e); } render(); poll(); }; poll(); setInterval(poll, 1000);