Files
client/app/main/appaudio-main.js
T
omar e6464bc4ed feat: checkpoint account-free client workflows and source-matched UI
Preserve accumulated client implementation since v0.1.4, including local identities, multi-server state, chat, administration, audio and streaming controls. Refine official-source layout, original artwork, responsive composer overflow, settings navigation and chat scroll anchoring.

Current verification: Node suite passes; isolated packaged chat and responsive control smokes pass without device capture. Native core is reused, not rebuilt in this pass. Strict whole-screen visual parity remains incomplete; no 1:1 or cross-platform acceptance claim. Local checkpoint only; no release or push.
2026-11-01 19:43:18 +03:00

327 lines
18 KiB
JavaScript

'use strict';
const { spawn } = require('node:child_process');
const { randomUUID } = require('node:crypto');
const PCM_BYTES = 3840;
const MAX_APPS = 8;
const MAX_IN_FLIGHT = 4;
const fail = (code, message) => ({ ok: false, error: { code, message } });
const error = (message) => new Error(message);
const object = value => value && typeof value === 'object' && !Array.isArray(value);
const keys = (value, allowed) => object(value) && Object.keys(value).every(key => allowed.includes(key));
const identifier = value => typeof value === 'string' && value.length > 0 && value.length <= 256 && !/[\x00-\x20]/.test(value);
// Bound unfinished lines too: readline's line event alone cannot bound a corrupt helper.
function readLines(stream, limit, onLine, onError) {
let pending = '';
let failed = false;
stream.setEncoding('utf8');
stream.on('data', chunk => {
if (failed) return;
pending += chunk;
let end;
while ((end = pending.indexOf('\n')) >= 0) {
if (end > limit) { failed = true; onError(error('Application audio helper exceeded its frame limit.')); return; }
const line = pending.slice(0, end);
pending = pending.slice(end + 1);
try { if (line) onLine(JSON.parse(line)); } catch (cause) { failed = true; onError(cause); return; }
}
if (pending.length > limit) { failed = true; onError(error('Application audio helper exceeded its frame limit.')); }
});
stream.on('error', onError);
stream.on('end', () => { if (!failed && pending.trim()) onError(error('Application audio helper returned a truncated frame.')); });
}
function validPcm(frame) {
return object(frame) && frame.event === 'pcm' && Number.isSafeInteger(frame.sequence) && frame.sequence >= 0 &&
typeof frame.pcm === 'string' && frame.pcm.length === 5120 && /^[A-Za-z0-9+/]+$/.test(frame.pcm) && Buffer.from(frame.pcm, 'base64').length === PCM_BYTES;
}
class AppAudioController {
constructor({ resolveBinary, getWindow, trustedFrame, spawnProcess = spawn, ownPid = process.pid, now = Date.now }) {
this.resolveBinary = resolveBinary;
this.getWindow = getWindow;
this.trustedFrame = trustedFrame;
this.spawnProcess = spawnProcess;
this.ownPid = ownPid;
this.now = now;
this.observed = new Map();
this.grant = null;
this.active = null;
this.pendingSession = null;
this.listing = null;
this.generation = 0;
this.listChildren = new Set();
this.bound = new WeakSet();
}
bindWindow() {
const contents = this.getWindow()?.webContents;
if (!contents || this.bound.has(contents)) return;
this.bound.add(contents);
contents.on('did-start-navigation', (_event, _url, _inPlace, isMainFrame) => { if (isMainFrame) this.stopAll(); });
contents.on('render-process-gone', () => this.stopAll());
contents.on('destroyed', () => this.stopAll());
}
authorizeSelection(frame, sourceId) {
this.stopAll();
this.bindWindow();
if (!this.trustedFrame(frame)) return {};
const sessionId = randomUUID();
this.grant = { sessionId, frame, sourceId, expiresAt: this.now() + 30000, confirmed: false };
return { appAudioSessionId: sessionId };
}
confirmSelection(frame) {
if (this.grant?.frame === frame && this.trustedFrame(frame) && this.grant.expiresAt >= this.now()) this.grant.confirmed = true;
}
spawn(args) {
const child = this.spawnProcess(this.resolveBinary(), ['app-audio', ...args], { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
child.stdin.on('error', () => {});
// Never retain unbounded diagnostics or forward native process details to a renderer.
child.stderr.resume();
return child;
}
terminate(child) {
if (child.exitCode !== null && child.exitCode !== undefined) return;
child.stdin.end();
const timer = setTimeout(() => child.kill(), 250);
timer.unref?.();
child.once('close', () => clearTimeout(timer));
}
enumerate() {
return new Promise((resolve, reject) => {
let child;
try { child = this.spawn(['list']); } catch (cause) { reject(cause); return; }
this.listChildren.add(child);
let result;
let settled = false;
const timer = setTimeout(() => finish(error('Application audio enumeration timed out.')), 12000);
const finish = cause => {
if (settled) return;
settled = true;
clearTimeout(timer);
this.listChildren.delete(child);
if (cause) { this.terminate(child); reject(cause); } else resolve(result);
};
readLines(child.stdout, 256 * 1024, value => {
if (result !== undefined || !object(value) || typeof value.supported !== 'boolean' || !Array.isArray(value.applications) || value.applications.length > 2048) throw error('Invalid application audio list.');
if (value.supported && !['process-tree', 'audio-stream'].includes(value.scope)) throw error('Unsupported application audio scope.');
const hostAncestors = value.hostAncestors;
if (value.supported && value.scope === 'process-tree' && (!Array.isArray(hostAncestors) || hostAncestors.length > 128 || !hostAncestors.includes(this.ownPid) || hostAncestors.some(pid => !Number.isSafeInteger(pid) || pid <= 0))) throw error('Native helper did not establish process-tree self-exclusion.');
const applications = value.applications.map(app => {
if (!object(app) || !identifier(app.id) || typeof app.label !== 'string' || app.label.length > 4096 || !Number.isSafeInteger(app.pid) || app.pid <= 0 || !Array.isArray(app.ancestors) || app.ancestors.length > 128 || app.ancestors.some(pid => !Number.isSafeInteger(pid) || pid <= 0)) throw error('Invalid application audio identity.');
return { id: app.id, label: app.label, pid: app.pid, ancestors: app.ancestors };
}).filter(app => app.pid !== this.ownPid && !app.ancestors.includes(this.ownPid) && (value.scope !== 'process-tree' || !hostAncestors.includes(app.pid)));
if (new Set(applications.map(app => app.id)).size !== applications.length) throw error('Duplicate application audio identity.');
result = { supported: value.supported, platform: value.platform, scope: value.scope, reason: typeof value.reason === 'string' ? value.reason.slice(0, 4096) : undefined, applications: value.supported ? applications : [] };
}, finish);
child.once('error', finish);
child.once('close', code => finish(code !== 0 || result === undefined ? error('Application audio enumeration failed.') : null));
});
}
async list() {
this.bindWindow();
const generation = this.generation;
try {
const result = await this.enumerate();
if (generation !== this.generation) return fail('appaudio_cancelled', 'Application audio selection was cancelled.');
this.observed = new Map(result.applications.map(app => [app.id, app]));
return { ok: true, ...result };
} catch (cause) { return fail('appaudio_unavailable', cause.message); }
}
async start(frame, options) {
const scope = options?.scope ?? 'selected';
if (!keys(options, ['sessionId', 'ids', 'scope']) || !['selected', 'all', 'exclude'].includes(scope) || !identifier(options.sessionId) || !Array.isArray(options.ids) || options.ids.length > MAX_APPS || (scope === 'selected' && !options.ids.length) || (scope === 'all' && options.ids.length) || options.ids.some(id => !identifier(id)) || new Set(options.ids).size !== options.ids.length) return fail('invalid_appaudio_options', 'Choose an audio scope and at most eight observed applications.');
const grant = this.grant;
if (!grant || grant.sessionId !== options.sessionId || grant.frame !== frame || !grant.confirmed || grant.expiresAt < this.now() || !this.trustedFrame(frame)) return fail('appaudio_selection_expired', 'Explicitly select and preview a broadcast source before capturing application audio.');
if (options.ids.some(id => !this.observed.has(id))) return fail('appaudio_not_observed', 'Select applications from the current audio list.');
this.grant = null; // one use, including failures and concurrent requests
const pending = { id: options.sessionId, frame };
this.pendingSession = pending;
const generation = this.generation;
try {
const fresh = await this.enumerate();
if (generation !== this.generation || !this.trustedFrame(frame)) return fail('appaudio_cancelled', 'Application audio selection was cancelled.');
if (!fresh.supported) return fail('appaudio_unsupported', fresh.reason || 'Application audio is not supported on this platform.');
const selected = this.selectScope(fresh, options.ids, scope);
if (scope === 'selected' && selected.length !== options.ids.length) return fail('appaudio_selection_expired', 'A selected audio application exited or changed identity.');
const session = { id: options.sessionId, frame, children: new Set(), captures: new Map(), inFlight: new Set(), nextToken: 1, closed: false, rejectReady: new Set(), scope, ids: [...options.ids], refreshTimer: null };
this.active = session;
if (scope !== 'selected') this.send(session, { event: 'applications', applications: selected.map(app => ({ id: app.id, label: app.label })) });
await Promise.all(selected.map(app => this.capture(session, app.id)));
if (session.closed || generation !== this.generation) return fail('appaudio_cancelled', 'Application audio selection was cancelled.');
if (scope !== 'selected') this.refreshScope(session);
return { ok: true, sessionId: session.id };
} catch (cause) {
if (generation === this.generation) this.stopAll();
return fail(cause.code || 'appaudio_failed', cause.message);
} finally {
if (this.pendingSession === pending) this.pendingSession = null;
}
}
selectScope(fresh, ids, scope) {
const chosen = new Set(ids);
const excludedPids = new Set(ids.map(id => this.observed.get(id)?.pid).filter(Boolean));
let selected = fresh.applications.filter(app => scope === 'all' || (scope === 'selected' ? chosen.has(app.id)
: !chosen.has(app.id) && !excludedPids.has(app.pid) && !app.ancestors.some(pid => excludedPids.has(pid))));
if (fresh.scope === 'process-tree') {
if (scope === 'exclude' && selected.some(app => fresh.applications.some(other => chosen.has(other.id) && other.ancestors.includes(app.pid)))) {
throw error('The excluded application shares a captured ancestor process tree. This backend cannot separate that ancestor without also recording the excluded app; choose Selected Apps instead.');
}
const roots = selected.filter(app => !selected.some(other => other.id !== app.id && (app.ancestors.includes(other.pid) || (app.pid === other.pid && other.id < app.id))));
if (scope === 'selected' && roots.length !== selected.length) throw Object.assign(error('Choose only one member of an application process tree to avoid duplicate audio.'), { code: 'appaudio_overlap' });
selected = roots;
}
if (selected.length > MAX_APPS) throw error('This audio scope exceeds the eight-application capture limit. Narrow the scope; no applications were silently omitted.');
return selected;
}
refreshScope(session) {
clearTimeout(session.refreshTimer);
session.refreshTimer = setTimeout(async () => {
if (session.closed) return;
try {
const fresh = await this.enumerate();
if (session.closed) return;
if (!fresh.supported) throw error(fresh.reason || 'Application audio became unavailable.');
const selected = this.selectScope(fresh, session.ids, session.scope);
const wanted = new Set(selected.map(app => app.id));
for (const [id, capture] of session.captures) if (!wanted.has(id)) {
session.captures.delete(id); capture.retired = true; this.terminate(capture.child);
}
this.send(session, { event: 'applications', applications: selected.map(app => ({ id: app.id, label: app.label })) });
await Promise.all(selected.filter(app => !session.captures.has(app.id)).map(app => this.capture(session, app.id)));
if (!session.closed) this.refreshScope(session);
} catch (cause) {
if (!session.closed) { this.send(session, { event: 'error', code: 'appaudio_scope_failed', message: cause.message }); this.stopAll(); }
}
}, 1000);
}
capture(session, id) {
return new Promise((resolve, reject) => {
const child = this.spawn(['capture', id]);
session.children.add(child);
const capture = { child, retired: false };
session.captures.set(id, capture);
let formatted = false;
let sequence = -1;
let ready = false;
let ended = false;
const timer = setTimeout(() => finish(error('Application audio activation timed out.')), 12000);
const rejectReady = cause => { clearTimeout(timer); if (!ready) { ready = true; reject(cause); } };
session.rejectReady.add(rejectReady);
const finish = cause => {
if (ended) return;
ended = true;
clearTimeout(timer);
session.rejectReady.delete(rejectReady);
if (capture.retired) { rejectReady(error('Application left the audio scope.')); return; }
if (formatted && session.scope !== 'selected' && !session.closed) {
// A normal app exit changes a dynamic scope; a still-present broken recorder is an error.
void this.enumerate().then(fresh => {
if (session.closed || capture.retired) return;
if (!fresh.supported || fresh.applications.some(app => app.id === id)) throw cause || error('Application audio recorder stopped unexpectedly.');
capture.retired = true; session.captures.delete(id); this.terminate(child);
this.refreshScope(session);
}).catch(failure => {
if (!session.closed) { this.send(session, { event: 'error', code: 'appaudio_ended', message: failure.message }); this.stopAll(); }
});
return;
}
rejectReady(cause || error('The selected audio application stopped.'));
if (!session.closed) {
this.send(session, { event: 'error', code: 'appaudio_ended', message: cause?.message || 'The selected audio application stopped.' });
this.stopAll();
}
};
readLines(child.stdout, 8192, packet => {
if (session.closed || capture.retired) return;
if (!formatted) {
if (packet?.event !== 'format' || packet.sampleRate !== 48000 || packet.channels !== 2 || packet.format !== 's16le' || packet.frames !== 960) throw error('Invalid application audio format.');
formatted = true;
clearTimeout(timer);
ready = true;
session.rejectReady.delete(rejectReady);
resolve();
return;
}
if (!validPcm(packet) || packet.sequence <= sequence) throw error('Invalid application audio PCM frame.');
sequence = packet.sequence;
// Keep draining native pipes but drop realtime frames while the renderer is
// stalled. At most four unacknowledged PCM events can cross Electron IPC.
if (session.inFlight.size >= MAX_IN_FLIGHT) return;
const token = session.nextToken++;
session.inFlight.add(token);
this.send(session, { event: 'pcm', id, sequence, pcm: packet.pcm, token });
}, finish);
child.once('error', finish);
child.once('close', () => { session.children.delete(child); finish(); });
});
}
send(session, packet) {
const win = this.getWindow();
if (session.closed || !win || win.isDestroyed() || !this.trustedFrame(session.frame)) { this.stopAll(); return; }
try { win.webContents.send('appaudio:event', { sessionId: session.id, ...packet }); } catch { this.stopAll(); }
}
ack(frame, options) {
if (!keys(options, ['sessionId', 'token']) || !Number.isSafeInteger(options.token)) return;
const session = this.active;
if (session?.frame === frame && session.id === options.sessionId) session.inFlight.delete(options.token);
}
stop(frame, options) {
if (!keys(options, ['sessionId']) || !identifier(options.sessionId)) return fail('invalid_appaudio_options', 'Invalid audio capture session.');
if ((this.active?.id === options.sessionId && this.active.frame === frame) || (this.pendingSession?.id === options.sessionId && this.pendingSession.frame === frame) || (this.grant?.sessionId === options.sessionId && this.grant.frame === frame)) this.stopAll();
return { ok: true };
}
stopAll() {
this.generation++;
this.grant = null;
this.pendingSession = null;
const session = this.active;
this.active = null;
if (session) {
const win = this.getWindow();
if (win && !win.isDestroyed() && this.trustedFrame(session.frame)) {
try { win.webContents.send('appaudio:event', { sessionId: session.id, event: 'stopped', message: 'Application audio capture stopped.' }); } catch { /* Window teardown still owns disposal. */ }
}
session.closed = true;
clearTimeout(session.refreshTimer);
session.captures.clear();
session.inFlight.clear();
for (const reject of session.rejectReady) reject(error('Application audio capture was cancelled.'));
session.rejectReady.clear();
for (const child of session.children) this.terminate(child);
session.children.clear();
}
for (const child of this.listChildren) this.terminate(child);
}
registerIpc(ipcMain, trustedSender) {
const trusted = event => trustedSender(event) && this.trustedFrame(event.senderFrame);
const handle = (channel, fn) => ipcMain.handle(channel, (event, options) => trusted(event) ? fn(event.senderFrame, options) : fail('forbidden', 'Application audio is restricted to the application top frame.'));
handle('appaudio:list', () => {
if (!this.listing) this.listing = this.list().finally(() => { this.listing = null; });
return this.listing;
});
handle('appaudio:start', (frame, options) => this.start(frame, options));
handle('appaudio:stop', (frame, options) => this.stop(frame, options));
ipcMain.on('appaudio:ack', (event, options) => { if (trusted(event)) this.ack(event.senderFrame, options); });
}
}
module.exports = { AppAudioController, readLines, validPcm, MAX_IN_FLIGHT };