const API = "http://127.0.0.1:18765"; let rec, ctx, tab, mic, q = Promise.resolve(), name; // state: idle | recording | transcribing | done | error ; popup polls it const S = { state: "idle", name: "", t0: 0, t1: 0, chunks: 0, mic: false, text: "" }; chrome.runtime.onMessage.addListener((m, _s, send) => { if (m.to !== "off") return; if (m.cmd === "status") send(S); if (m.cmd === "start") start(m.id, m.tabId).then(() => send({ ok: true }), e => { S.state = "error"; S.text = String(e); send({ err: String(e) }); }); if (m.cmd === "events") { for (const e of m.events) if (e.ts >= S.t0) S.ev.push({ t: (e.ts - S.t0) / 1000, kind: e.kind, who_key: e.who_key, who: e.who, text: e.text }); } if (m.cmd === "stop") { rec.stop(); send({ ok: true }); } return true; }); async function flushEv() { if (!S.ev.length) return; const b = S.ev.splice(0); try { const r = await fetch(`${API}/events?name=${name}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(b) }); if (!r.ok) throw 0; S.evSent += b.length; } catch { S.failed++; } } async function start(id, tabId) { name = "teams_" + new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19); const src = { mandatory: { chromeMediaSource: "tab", chromeMediaSourceId: id } }; tab = await navigator.mediaDevices.getUserMedia({ audio: src, video: src }); ctx = new AudioContext(); const dest = ctx.createMediaStreamDestination(); const t = ctx.createMediaStreamSource(tab); t.connect(dest); t.connect(ctx.destination); // tabCapture mutes the tab; play it back try { // needs one-time grant via mic.html mic = await navigator.mediaDevices.getUserMedia({ audio: true }); ctx.createMediaStreamSource(mic).connect(dest); } catch { mic = null; } const out = new MediaStream([...tab.getVideoTracks(), ...dest.stream.getAudioTracks()]); rec = new MediaRecorder(out, { mimeType: "video/webm;codecs=vp8,opus", videoBitsPerSecond: 1e6 }); rec.ondataavailable = e => { q = q.then(() => fetch(`${API}/chunk?name=${name}`, { method: "POST", body: e.data })).then(() => S.chunks++, () => S.failed++).then(flushEv); }; rec.onstop = async () => { S.state = "transcribing"; S.t1 = Date.now(); try { await q; await flushEv(); [tab, mic].forEach(s => s && s.getTracks().forEach(t => t.stop())); ctx.close(); const r = await fetch(`${API}/stop?name=${name}`, { method: "POST" }); S.text = await r.text(); S.state = r.ok ? "done" : "error"; } catch (e) { S.text = "server down or failed: " + e; S.state = "error"; } rec = null; }; Object.assign(S, { state: "recording", name, t0: Date.now(), chunks: 0, failed: 0, mic: !!mic, text: "", ev: [], evSent: 0, tabId }); rec.start(10000); }