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.
263 lines
9.3 KiB
JavaScript
263 lines
9.3 KiB
JavaScript
'use strict';
|
|
|
|
const { spawn } = require('node:child_process');
|
|
const { EventEmitter } = require('node:events');
|
|
const readline = require('node:readline');
|
|
const fs = require('node:fs');
|
|
|
|
const READY_TIMEOUT_MS = 15000;
|
|
const STOP_TIMEOUT_MS = 6000;
|
|
const AUDIO_BACKLOG_LIMIT = 128 * 1024;
|
|
const MAX_LINE_BYTES = 256 * 1024;
|
|
|
|
const TIMEOUTS = {
|
|
connect: 60000,
|
|
disconnect: 10000,
|
|
rename: 15000,
|
|
join_channel: 15000,
|
|
send_text: 15000,
|
|
stream_list: 15000,
|
|
default: 15000,
|
|
};
|
|
|
|
/**
|
|
* Owns one `teamspeach-core` child process speaking the newline-JSON protocol of docs/bridge.md.
|
|
* With `connectionDir` the core is one of several simultaneous connection cores sharing the profile
|
|
* in `dataDir` (shared profile lock, exclusive lock on its own connection directory).
|
|
* Emits: 'event' (core event object), 'status' ({status, code?, message?, coreVersion?}).
|
|
*/
|
|
class CoreProcess extends EventEmitter {
|
|
constructor({ binary, dataDir, connectionDir, logFile, logLevel }) {
|
|
super();
|
|
this.binary = binary;
|
|
this.dataDir = dataDir;
|
|
this.connectionDir = connectionDir || null;
|
|
this.logFile = logFile;
|
|
this.logLevel = logLevel || 'info';
|
|
this.child = null;
|
|
this.pending = new Map();
|
|
this.nextId = 1;
|
|
this.status = 'stopped';
|
|
this.coreVersion = null;
|
|
this.stopping = false;
|
|
this.droppedAudioFrames = 0;
|
|
}
|
|
|
|
start() {
|
|
if (this.child) throw new Error('core already running');
|
|
this.stopping = false;
|
|
this.coreVersion = null;
|
|
rotateLog(this.logFile);
|
|
const log = fs.createWriteStream(this.logFile, { flags: 'a' });
|
|
const writeLog = (text) => { if (!log.destroyed && !log.writableEnded) log.write(text); };
|
|
let child;
|
|
let logFailed = false;
|
|
const onLogFailure = (err) => {
|
|
if (logFailed) return;
|
|
logFailed = true;
|
|
// A broken diagnostic destination must neither crash main nor leave stderr paused.
|
|
child?.stderr.unpipe(log);
|
|
child?.stderr.resume();
|
|
log.destroy();
|
|
const message = `Core log unavailable: ${err.message}`;
|
|
console.warn(message);
|
|
this.emit('status', { status: this.status, logError: message });
|
|
};
|
|
log.on('error', onLogFailure);
|
|
log.on('close', () => {
|
|
if (!log.writableFinished) onLogFailure(new Error('log destination closed before finishing'));
|
|
});
|
|
writeLog(`\n=== ${new Date().toISOString()} start ${this.binary}\n`);
|
|
|
|
try {
|
|
const args = ['--data-dir', this.dataDir];
|
|
if (this.connectionDir) args.push('--connection-dir', this.connectionDir);
|
|
child = spawn(this.binary, args, {
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
windowsHide: true,
|
|
env: { ...process.env, TEAMSPEACH_LOG: process.env.TEAMSPEACH_LOG || this.logLevel },
|
|
});
|
|
} catch (err) {
|
|
log.end();
|
|
this._setStatus('failed', { reason: 'spawn', message: err.message });
|
|
return;
|
|
}
|
|
this.child = child;
|
|
this._setStatus('starting');
|
|
|
|
child.stderr.pipe(log, { end: false });
|
|
child.stdin.on('error', (err) => writeLog(`[main] stdin error: ${err.message}\n`));
|
|
|
|
const rl = readline.createInterface({ input: child.stdout, crlfDelay: Infinity });
|
|
let exited = false;
|
|
const diagnostics = { write: writeLog };
|
|
rl.on('line', (line) => this._onLine(line, diagnostics));
|
|
|
|
const readyTimer = setTimeout(() => {
|
|
if (this.status === 'starting') {
|
|
writeLog('[main] core did not report ready in time, terminating\n');
|
|
this._setStatus('failed', { reason: 'ready_timeout', message: 'The core did not report ready within 15 seconds' });
|
|
child.kill();
|
|
}
|
|
}, READY_TIMEOUT_MS);
|
|
const onReady = () => clearTimeout(readyTimer);
|
|
this.once('ready-internal', onReady);
|
|
|
|
child.on('error', (err) => {
|
|
clearTimeout(readyTimer);
|
|
writeLog(`[main] spawn error: ${err.message}\n`);
|
|
this._setStatus('failed', { reason: 'spawn', message: err.message });
|
|
});
|
|
|
|
const finishProcess = (code, signal) => {
|
|
if (exited) return;
|
|
exited = true;
|
|
clearTimeout(readyTimer);
|
|
this.removeListener('ready-internal', onReady);
|
|
const expected = this.stopping;
|
|
if (expected || this.status !== 'failed') this._setStatus(expected ? 'stopped' : 'exited', { code, signal, message: exitMessage(code) });
|
|
};
|
|
// exit ends command availability; close owns final stdio/log disposal (also failed spawn).
|
|
child.once('exit', finishProcess);
|
|
|
|
// close also fires after a failed spawn (exit does not), and follows stdio closure.
|
|
child.on('close', (code, signal) => {
|
|
finishProcess(code, signal);
|
|
rl.close();
|
|
writeLog(`[main] core exited code=${code} signal=${signal}\n`);
|
|
if (!log.destroyed) log.end();
|
|
this.child = null;
|
|
for (const [, entry] of this.pending) {
|
|
clearTimeout(entry.timer);
|
|
entry.resolve({ ok: false, error: { code: 'core_exited', message: 'The core exited' } });
|
|
}
|
|
this.pending.clear();
|
|
});
|
|
|
|
}
|
|
|
|
_onLine(line, log) {
|
|
if (!line) return;
|
|
let msg;
|
|
try {
|
|
msg = JSON.parse(line);
|
|
} catch {
|
|
log.write(`[main] unparseable stdout line (${line.length} chars)\n`);
|
|
return;
|
|
}
|
|
if (msg === null || typeof msg !== 'object') return;
|
|
if (Object.prototype.hasOwnProperty.call(msg, 'id')) {
|
|
const entry = this.pending.get(msg.id);
|
|
if (!entry) return;
|
|
this.pending.delete(msg.id);
|
|
clearTimeout(entry.timer);
|
|
entry.resolve(msg.ok ? { ok: true, result: msg.result ?? {} } : { ok: false, error: normalizeError(msg.error) });
|
|
return;
|
|
}
|
|
if (msg.event === 'ready') {
|
|
if (this.status !== 'starting') return; // late/duplicate ready cannot resurrect an exited core
|
|
this.coreVersion = typeof msg.core_version === 'string' ? msg.core_version : null;
|
|
if (msg.protocol !== 1) {
|
|
log.write(`[main] unsupported core protocol ${msg.protocol}\n`);
|
|
this._setStatus('failed', { reason: 'protocol', protocol: msg.protocol, message: `Unsupported core protocol version: ${msg.protocol}` });
|
|
this.child?.kill();
|
|
return;
|
|
}
|
|
this.emit('ready-internal');
|
|
this._setStatus('ready', { coreVersion: this.coreVersion });
|
|
return;
|
|
}
|
|
if (typeof msg.event === 'string') this.emit('event', msg);
|
|
}
|
|
|
|
_setStatus(status, extra = {}) {
|
|
this.status = status;
|
|
this.emit('status', { status, ...extra });
|
|
}
|
|
|
|
get running() {
|
|
return this.child !== null;
|
|
}
|
|
|
|
request(cmd, args) {
|
|
if (!this.child || this.status !== 'ready') {
|
|
return Promise.resolve({ ok: false, error: { code: 'core_unavailable', message: 'The core is not running' } });
|
|
}
|
|
const id = `m${this.nextId++}`;
|
|
const payload = args === undefined ? { id, cmd } : { id, cmd, args };
|
|
const line = JSON.stringify(payload) + '\n';
|
|
if (Buffer.byteLength(line) > MAX_LINE_BYTES) {
|
|
return Promise.resolve({ ok: false, error: { code: 'bad_request', message: 'Request too large' } });
|
|
}
|
|
return new Promise((resolve) => {
|
|
const timeoutMs = TIMEOUTS[cmd] ?? TIMEOUTS.default;
|
|
const timer = setTimeout(() => {
|
|
this.pending.delete(id);
|
|
resolve({ ok: false, error: { code: 'timeout', message: `The core did not answer "${cmd}" within ${Math.round(timeoutMs / 1000)} s` } });
|
|
}, timeoutMs);
|
|
this.pending.set(id, { resolve, timer });
|
|
this.child.stdin.write(line);
|
|
});
|
|
}
|
|
|
|
/** audio_frame / audio_end: never answered. Frames are dropped instead of queueing unboundedly behind a stalled pipe. */
|
|
sendAudio(cmd, args) {
|
|
if (!this.child || this.status !== 'ready') return false;
|
|
if (cmd === 'audio_frame' && this.child.stdin.writableLength > AUDIO_BACKLOG_LIMIT) {
|
|
this.droppedAudioFrames += 1;
|
|
return false;
|
|
}
|
|
this.child.stdin.write(JSON.stringify(args === undefined ? { cmd } : { cmd, args }) + '\n');
|
|
return true;
|
|
}
|
|
|
|
async stop() {
|
|
const child = this.child;
|
|
if (!child) return;
|
|
this.stopping = true;
|
|
const exited = new Promise((resolve) => child.once('close', resolve));
|
|
if (this.status === 'ready') {
|
|
await Promise.race([this.request('shutdown'), delay(STOP_TIMEOUT_MS)]);
|
|
} else {
|
|
child.stdin.end();
|
|
}
|
|
const done = await Promise.race([exited.then(() => true), delay(STOP_TIMEOUT_MS).then(() => false)]);
|
|
if (!done && this.child) {
|
|
this.child.kill();
|
|
await Promise.race([exited, delay(2000)]);
|
|
}
|
|
}
|
|
}
|
|
|
|
function normalizeError(error) {
|
|
if (!error || typeof error !== 'object') return { code: 'internal', message: 'Empty error response' };
|
|
const out = { code: String(error.code ?? 'internal'), message: String(error.message ?? '') };
|
|
if (error.ts_error && typeof error.ts_error === 'object') out.ts_error = error.ts_error;
|
|
if (error.detail && typeof error.detail === 'object') out.detail = error.detail;
|
|
return out;
|
|
}
|
|
|
|
function exitMessage(code) {
|
|
switch (code) {
|
|
case 0: return 'The core exited';
|
|
case 2: return 'The core rejected its start arguments';
|
|
case 3: return 'The profile is in use by another TeamsPeach instance or the data directory is unavailable';
|
|
case 1: return 'Internal core error (details in core.log)';
|
|
default: return `The core exited with code ${code}`;
|
|
}
|
|
}
|
|
|
|
function rotateLog(file) {
|
|
try {
|
|
if (fs.statSync(file).size > 5 * 1024 * 1024) fs.renameSync(file, `${file}.1`);
|
|
} catch {
|
|
// no log yet
|
|
}
|
|
}
|
|
|
|
function delay(ms) {
|
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
}
|
|
|
|
module.exports = { CoreProcess };
|