Fail closed on a missing microphone, release partial capture setup, menus show enumeration failures; deterministic packaged smoke launch; NSIS custom-profile update guard

This commit is contained in:
omar committed 2026-10-24 07:07:05 +03:00
1 parent 7afce5ab20
commit 2a71d63b7b
37 files changed
+838 -310

No files matched your search

+7
View File
@@ -29,6 +29,13 @@
downloads. Version 0.1.1 and older require a first manual installation of an updater-capable version.
- Fixed capture cancellation during pending microphone acquisition and prevented device changes from
being applied when saving the selected device fails.
- A saved microphone that is no longer available is reported as unavailable; TeamsPeach no longer opens
a different microphone in its place. Choosing an available device restores capture while connected or
during the microphone test, and opens nothing otherwise. A failure while building the capture chain
releases the microphone.
- The microphone and headphones menus show a failed device enumeration instead of an earlier list.
- Windows installations started with a custom profile (`TEAMSPEACH_PROFILE_DIR`) only offer manual
updates, because the installer would restart TeamsPeach on the default profile.
## 0.1.1 — 2026-10-24
+11 -1
View File
@@ -529,7 +529,17 @@ app.whenReady().then(() => {
registerProtocol();
hardenSession();
registerIpc();
createWindow();
if (process.env.TEAMSPEACH_TEST_HOLD_WINDOW === '1') {
// Test harness only (scripts/lib/electron-app.mjs with --exe): Playwright cannot inject its startup loader
// into a packaged app, and attaching while the first page commits loses its utility world, so the harness
// attaches first and then creates the window through this hook.
globalThis.__teamspeachCreateWindow = () => {
delete globalThis.__teamspeachCreateWindow;
createWindow();
};
} else {
createWindow();
}
startCore();
// Updates come only from published releases of the public repo; nothing installs without a click.
updates = createUpdateService({
+13 -4
View File
@@ -117,8 +117,15 @@ function createUpdateService({
appImagePath = () => process.env.APPIMAGE,
argv = process.argv,
feedTimeoutMs = FEED_TIMEOUT_MS,
profileOverride = process.env.TEAMSPEACH_PROFILE_DIR,
}) {
const currentVersion = electronApp.getVersion();
// The NSIS installer restarts the app through Explorer (StdUtils.ExecShellAsUser), which does not pass this
// process's environment on: an app running on a TEAMSPEACH_PROFILE_DIR profile would come back on the
// default profile. Such a run is offered the release page (manual install) instead of an automatic install.
// AppImage relaunch (app.relaunch) keeps the environment and is not affected.
const installBlock = target.kind === 'nsis' && profileOverride ? 'custom-profile' : null;
const autoInstall = target.mode === 'auto' && !installBlock;
let offered = null; // { candidate, updater } — release in state.available and the instance that checked it
let downloaded = null; // { candidate, updater } — verified package ready to install
let downloading = null; // { updater, token }
@@ -130,7 +137,8 @@ function createUpdateService({
const state = {
currentVersion,
channel: 'preview',
mode: target.mode,
mode: installBlock ? 'manual' : target.mode,
manualReason: installBlock, // null | 'custom-profile'
target: target.id,
phase: target.mode === 'none' ? 'disabled' : 'idle',
lastCheckedAt: null,
@@ -143,7 +151,7 @@ function createUpdateService({
disabledParams: target.mode === 'none' ? { platform: target.platform, arch: target.arch } : null,
};
logger.info(`updater: version ${currentVersion} pid ${process.pid} target ${target.id} mode ${target.mode}`);
logger.info(`updater: version ${currentVersion} pid ${process.pid} target ${target.id} mode ${state.mode}${installBlock ? ` (${installBlock})` : ''}`);
function channel() {
const value = prefs.get().updateChannel;
@@ -318,7 +326,7 @@ function createUpdateService({
/** Background downloads wait while the user is connected; a manual request downloads now. */
function download({ manual }) {
if (busy) return busy.then(snapshot);
if (target.mode !== 'auto' || !offered || (state.phase !== 'available' && state.phase !== 'deferred')) return Promise.resolve(snapshot());
if (!autoInstall || !offered || (state.phase !== 'available' && state.phase !== 'deferred')) return Promise.resolve(snapshot());
if (!manual && isSessionActive()) {
if (state.phase !== 'deferred') {
logger.info('updater: download deferred until the session ends');
@@ -333,7 +341,7 @@ function createUpdateService({
function check({ manual }) {
if (target.mode === 'none' || state.phase === 'installing') return Promise.resolve(snapshot());
return exclusive(runCheck)
.then((s) => (s.phase === 'available' && target.mode === 'auto' ? download({ manual: false }) : s))
.then((s) => (s.phase === 'available' && autoInstall ? download({ manual: false }) : s))
.then((s) => {
if (manual) logger.info(`updater: manual check → ${s.phase}`);
return s;
@@ -350,6 +358,7 @@ function createUpdateService({
*/
function install(options) {
const confirmInterrupt = Boolean(options && options.confirmInterrupt === true);
if (installBlock) return { ok: false, code: installBlock };
if (target.mode !== 'auto' || state.phase !== 'downloaded' || !downloaded || offered !== downloaded) {
return { ok: false, code: 'not-ready' };
}
+40 -24
View File
@@ -113,38 +113,54 @@ export class AudioEngine {
};
if (deviceId) audio.deviceId = { exact: deviceId };
let stream;
let fellBack = false;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
} catch (err) {
if (!(deviceId && err && err.name === 'OverconstrainedError') || gen !== this.captureGen) throw err;
delete audio.deviceId;
stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
fellBack = true;
// A saved microphone that is gone is an error: never open a different microphone in its place.
if (deviceId && err && err.name === 'OverconstrainedError') {
throw Object.assign(new Error('Selected microphone is not available'), { name: 'OverconstrainedError', code: 'device_unavailable' });
}
throw err;
}
if (gen !== this.captureGen) {
for (const t of stream.getTracks()) t.stop();
return null;
}
if (fellBack) this.onError({ code: 'device_fallback', message: 'Selected microphone unavailable; using the default microphone' });
const ctx = this.ctx;
const source = ctx.createMediaStreamSource(stream);
const node = new AudioWorkletNode(ctx, 'tp-capture', {
numberOfInputs: 1,
numberOfOutputs: 1,
outputChannelCount: [1],
channelCount: 1,
channelCountMode: 'explicit',
channelInterpretation: 'speakers',
});
const sink = ctx.createGain();
sink.gain.value = 0;
node.port.onmessage = (event) => {
const data = event.data;
if (data.type === 'frame') this.onFrame(data.pcm, data.rms, data.peak);
else if (data.type === 'error') this.onError({ code: 'capture', message: data.message });
};
source.connect(node).connect(sink).connect(ctx.destination);
let source = null;
let node = null;
let sink = null;
try {
const ctx = this.ctx;
source = ctx.createMediaStreamSource(stream);
node = new AudioWorkletNode(ctx, 'tp-capture', {
numberOfInputs: 1,
numberOfOutputs: 1,
outputChannelCount: [1],
channelCount: 1,
channelCountMode: 'explicit',
channelInterpretation: 'speakers',
});
sink = ctx.createGain();
sink.gain.value = 0;
node.port.onmessage = (event) => {
const data = event.data;
if (data.type === 'frame') this.onFrame(data.pcm, data.rms, data.peak);
else if (data.type === 'error') this.onError({ code: 'capture', message: data.message });
};
source.connect(node).connect(sink).connect(ctx.destination);
} catch (err) {
// The microphone is already open: release it and whatever was built before rethrowing.
if (node) node.port.onmessage = null;
for (const part of [source, node, sink]) {
try {
part?.disconnect();
} catch {
// never connected
}
}
for (const t of stream.getTracks()) t.stop();
throw err;
}
const track = stream.getAudioTracks()[0];
track.addEventListener('ended', () => {
if (this.capture && this.capture.stream === stream) {
+14 -5
View File
@@ -96,6 +96,20 @@ function show(anchor, kind, point) {
voice.deviceChoices().then((choices) => {
if (!open || open.gen !== gen || !choices) return; // closed or replaced meanwhile
const settingsItem = h('button', { class: 'menu-item menu-item-secondary', type: 'button', role: 'menuitem', tabindex: '-1' }, h('span', { class: 'menu-check', 'aria-hidden': 'true' }), h('span', { class: 'menu-label', text: t('ui.audio.settings') }));
settingsItem.addEventListener('click', () => {
close({ restoreFocus: false });
hooks.openAudioSettings();
});
if (choices.error) {
// Enumeration failed now: show that instead of any earlier list.
body.replaceChildren(h('p', { class: 'menu-note', role: 'alert', text: t('message.could.not.list.devices.p0.p1', { p0: choices.error.name, p1: choices.error.message }) }), h('div', { class: 'menu-sep', role: 'separator' }), settingsItem);
menu.removeAttribute('aria-busy');
position(menu, anchor, point);
focusables = [settingsItem];
if (menu.contains(document.activeElement)) focusAt(0);
return;
}
const data = kind === 'input' ? choices.input : choices.output;
const selected = (kind === 'input' ? S.prefs.inputDeviceId : S.prefs.outputDeviceId) || '';
const items = data.options.map((o) => {
@@ -114,11 +128,6 @@ function show(anchor, kind, point) {
});
return item;
});
const settingsItem = h('button', { class: 'menu-item menu-item-secondary', type: 'button', role: 'menuitem', tabindex: '-1' }, h('span', { class: 'menu-check', 'aria-hidden': 'true' }), h('span', { class: 'menu-label', text: t('ui.audio.settings') }));
settingsItem.addEventListener('click', () => {
close({ restoreFocus: false });
hooks.openAudioSettings();
});
const note = data.redacted || data.physical === 0
? h('p', { class: 'menu-note', text: data.redacted ? t('ui.the.engine.hid.the.device.list.only') : kind === 'input' ? t('ui.no.microphones.found') : t('ui.no.output.devices.found') })
: null;
+1 -1
View File
@@ -27,7 +27,7 @@ const ERROR_TEXT = {
get core_missing() { return t('ui.core.executable.not.found'); },
get connected() { return t('ui.disconnect.from.the.server.first2'); },
get forbidden() { return t('ui.action.forbidden'); },
get device_fallback() { return t('error.device_fallback'); },
get device_unavailable() { return t('error.device_unavailable'); },
get device_lost() { return t('error.device_lost'); },
get capture() { return t('error.capture'); },
};
+2 -1
View File
@@ -38,7 +38,8 @@ function statusText(s) {
}
case 'available': {
const base = t(s.available?.preview ? 'update.ui.status.availablePreview' : 'update.ui.status.available', { version });
return s.mode === 'manual' ? `${base} ${t('update.ui.status.manual')}` : base;
if (s.mode !== 'manual') return base;
return `${base} ${s.manualReason ? codeText('manual', s.manualReason, {}) : t('update.ui.status.manual')}`;
}
case 'deferred':
return t('update.ui.status.deferred', { version });
+8 -2
View File
@@ -142,13 +142,17 @@ export async function syncCapture() {
});
if (label !== null) refreshDevices();
} catch (err) {
toast(() => t('message.microphone.access.unavailable.p0', { p0: err.message || err.name }), 'error');
if (err.code === 'device_unavailable') toast(() => errorText(err), 'error');
else toast(() => t('message.microphone.access.unavailable.p0', { p0: err.message || err.name }), 'error');
log('error', `capture failed: ${err.name} ${err.message}`);
}
}
/**
* Re-opens the microphone with the current preferences. Also used after a failed start, so a newly chosen
* device recovers capture whenever capture is wanted (connected or mic test); otherwise nothing opens.
*/
export async function restartCapture() {
if (!engine.capturing && !engine.captureStarting) return;
engine.stopCapture();
await syncCapture();
}
@@ -210,6 +214,8 @@ export async function refreshDevices() {
try {
devices = await navigator.mediaDevices.enumerateDevices();
} catch (err) {
// The menus must show this failure, not an earlier successful list.
lastChoices = { error: { name: err.name, message: err.message } };
setText(status, () => t('message.could.not.list.devices.p0.p1', { p0: err.name, p1: err.message }));
log('warn', `enumerateDevices failed: ${err.name}`);
return;
+3 -1
View File
@@ -423,7 +423,7 @@
"other": "{count} members"
},
"error.detail": "Error ({code}): {detail}",
"error.device_fallback": "Selected microphone unavailable; using the system default.",
"error.device_unavailable": "The selected microphone is not available. Choose another device in Settings → Audio or by right-clicking the microphone button.",
"error.device_lost": "The microphone was disconnected. Choose an available device in Settings → Audio.",
"update.disabled.dev-build": "This development build does not install updates",
"update.disabled.unsupported-platform": "Updates are not supported on {platform} {arch}",
@@ -443,6 +443,8 @@
"update.skip.incomplete-release": "Release {tag} is incomplete. File: {file}. {detail}",
"update.install.session-active": "End the current call or confirm interrupting it to install.",
"update.install.not-ready": "No verified update is ready to install.",
"update.install.custom-profile": "Automatic install is off for a custom profile: the installer would restart TeamsPeach on the default profile. Install the update manually from the release page.",
"update.manual.custom-profile": "Automatic install is off for a custom profile: the installer would restart TeamsPeach on the default profile. Install the update manually from the release page.",
"update.install.install-failed": "Could not install release {tag}: {detail}",
"language.russian": "Russian",
"update.channel.hint": "Preview includes prereleases; Stable excludes them.",
+3 -1
View File
@@ -425,7 +425,7 @@
"other": "{count} участника"
},
"error.detail": "Ошибка ({code}): {detail}",
"error.device_fallback": "Выбранный микрофон недоступен; используется системный по умолчанию.",
"error.device_unavailable": "Выбранный микрофон недоступен. Выберите другое устройство в Настройки → Звук или правым кликом по кнопке микрофона.",
"error.device_lost": "Микрофон отключён. Выберите доступное устройство в Настройки → Звук.",
"update.disabled.dev-build": "Эта сборка для разработки не устанавливает обновления",
"update.disabled.unsupported-platform": "Обновления не поддерживаются на {platform} {arch}",
@@ -445,6 +445,8 @@
"update.skip.incomplete-release": "Релиз {tag} неполный. Файл: {file}. {detail}",
"update.install.session-active": "Завершите разговор или подтвердите его прерывание для установки.",
"update.install.not-ready": "Проверенное обновление ещё не готово к установке.",
"update.install.custom-profile": "Автоматическая установка отключена для отдельного профиля: установщик перезапустил бы TeamsPeach с профилем по умолчанию. Установите обновление вручную со страницы релиза.",
"update.manual.custom-profile": "Автоматическая установка отключена для отдельного профиля: установщик перезапустил бы TeamsPeach с профилем по умолчанию. Установите обновление вручную со страницы релиза.",
"update.install.install-failed": "Не удалось установить релиз {tag}: {detail}",
"language.russian": "Русский",
"update.channel.hint": "Предварительный канал включает предварительные версии; стабильный исключает их.",
+19
View File
@@ -63,3 +63,22 @@ logs show a connection and an opened microphone, but no burst logging existed th
user-controlled: hold the in-window push-to-talk button (or F8 with TeamsPeach focused) while the official
client listens. Synthetic two-TeamsPeach voice tests (fake capture, empty channel) pass and are not
hardware proof.
## Packaged smoke harness: launch race (found and fixed)
`runtime/2026-10-24-packaged-launch-race/` keeps the first packaged run of 0.1.2-rc.1 (7afce5a): `theme` and
`menus` passed; `devices` and `ui` failed with `electron.launch: Timeout`. Cause: with `executablePath`
Playwright cannot inject its `-r loader.js` (which in a dev run holds `ready` until it has attached); when it
attaches to the packaged app while the first page is committing, it loses its utility world and the launch
never completes (6 of 6 isolated probes hung; passing `-r loader.js` to the packaged exe is ignored, 5 of 5
hung). CI run #21 failed the same way. Fix: dev runs use Playwright's own loader (no `executablePath`);
packaged runs start with `TEAMSPEACH_TEST_HOLD_WINDOW=1`, which defers window creation until the harness
calls the main-process hook (`scripts/lib/electron-app.mjs`). Without that variable the app starts as before.
## Device choice and capture safety (rc.1 additions)
- A saved microphone that no longer exists fails closed (`device_unavailable`): no second `getUserMedia`
without the device id, no default microphone, nothing sent. Choosing an available device restarts capture
only while connected or during the microphone test. Tests: `test/voice-capture.test.mjs`,
`test/audio-engine.test.mjs`.
- A failure while building the capture graph after the microphone opened stops its tracks and disconnects the
partial nodes before rethrowing.
- A failed `enumerateDevices()` replaces the cached choices, so the menus show the failure, not an older list.
@@ -0,0 +1,10 @@
{
"steps": [
{
"name": "FAILED",
"error": "electron.launch: Timeout 180000ms exceeded.\nCall log:\n\u001b[2m - <launching> \"C:\\Users\\Admin\\Desktop\\projects\\TeamsPeach\\dist\\win-unpacked\\TeamsPeach.exe\" \"--inspect=0\" \"--remote-debugging-port=0\"\u001b[22m\n\u001b[2m - <launched> pid=4588\u001b[22m\n\u001b[2m - [pid=4588][out]\u001b[22m\n\u001b[2m - [pid=4588][err] Debugger listening on ws://127.0.0.1:63427/fe8be778-dfa5-4682-a04e-1fbfc456af8f\u001b[22m\n\u001b[2m - [pid=4588][err] For help, see: https://nodejs.org/learn/getting-started/debugging\u001b[22m\n\u001b[2m - <ws connecting> ws://127.0.0.1:63427/fe8be778-dfa5-4682-a04e-1fbfc456af8f\u001b[22m\n\u001b[2m - <ws connected> ws://127.0.0.1:63427/fe8be778-dfa5-4682-a04e-1fbfc456af8f\u001b[22m\n\u001b[2m - [pid=4588][err] Debugger attached.\u001b[22m\n\u001b[2m - [pid=4588][err]\u001b[22m\n\u001b[2m - [pid=4588][err] DevTools listening on ws://127.0.0.1:63429/devtools/browser/5f28a818-8da7-4cf7-a0ac-26a82d2ac4ef\u001b[22m\n\u001b[2m - <ws connecting> ws://127.0.0.1:63429/devtools/browser/5f28a818-8da7-4cf7-a0ac-26a82d2ac4ef\u001b[22m\n\u001b[2m - <ws connected> ws://127.0.0.1:63429/devtools/browser/5f28a818-8da7-4cf7-a0ac-26a82d2ac4ef\u001b[22m\n\n at async launch (C:\\Users\\Admin\\Desktop\\projects\\TeamsPeach\\scripts\\smoke-devices.mjs:27:15)\n at async file:///C:/Users/Admin/Desktop/projects/TeamsPeach/scripts/smoke-devices.mjs:59:20"
}
],
"console": [],
"ok": false
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

@@ -0,0 +1,95 @@
{
"steps": [
{
"name": "mic right-click",
"menu": true,
"inputMuted": false,
"capturing": false,
"framesSent": 0,
"items": [
{
"label": "System default (Mic/Line/Inst 1-2 (MiniFuse 4))",
"checked": "true"
},
{
"label": "Loopback Mix Left/Right (MiniFuse 4)",
"checked": "false"
},
{
"label": "Headset Microphone (Oculus Virtual Audio Device)",
"checked": "false"
},
{
"label": "Line 3-4 (MiniFuse 4)",
"checked": "false"
},
{
"label": "Микрофон (DroidCam Audio)",
"checked": "false"
},
{
"label": "Микрофон (Virtual Desktop Audio)",
"checked": "false"
},
{
"label": "Mic/Line/Inst 1-2 (MiniFuse 4)",
"checked": "false"
}
],
"insideViewport": true,
"focused": "menu-item"
},
{
"name": "menu choice reflected in settings",
"pick": "Headset Microphone (Oculus Virtual Audio Device)",
"settingsInput": "Headset Microphone (Oculus Virtual Audio Device)",
"same": true
},
{
"name": "headphones Shift+F10",
"menu": true,
"outputMuted": false,
"items": [
"System default (Main Left/Right (MiniFuse 4))",
"Main Left/Right (MiniFuse 4)",
"Realtek Digital Output (Realtek(R) Audio)",
"Virtual Left/Right (MiniFuse 4)",
"LG ULTRAGEAR (NVIDIA High Definition Audio)",
"Наушники (Oculus Virtual Audio Device)",
"Aux Left/Right (MiniFuse 4)"
],
"insideViewport": true
},
{
"name": "escape",
"menuClosed": true,
"focusRestored": true,
"outputMuted": false
},
{
"name": "left click still toggles mute",
"inputMuted": true
},
{
"name": "rapid mic → headphones while enumeration pending",
"menus": 1,
"outputExpanded": "true",
"inputExpanded": "false",
"items": 7
},
{
"name": "dismissed before enumeration finished",
"menus": 0,
"focused": "connect-address",
"expanded": "false"
},
{
"name": "after restart",
"checkedIn": "Headset Microphone (Oculus Virtual Audio Device)",
"checkedOut": "Realtek Digital Output (Realtek(R) Audio)",
"persisted": true
}
],
"console": [],
"ok": true
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

@@ -0,0 +1,43 @@
{
"steps": [
{
"name": "os app theme",
"appsUseTheme": "dark"
},
{
"name": "new profile: onboarding",
"themeSource": "dark",
"windowBackground": "#1A1817",
"prefersDark": true,
"bodyBackground": "rgb(27, 32, 41)",
"bg": "#1b2029"
},
{
"name": "settings shows dark selected",
"checked": "dark"
},
{
"name": "switched to light",
"themeSource": "light",
"windowBackground": "#1A1817",
"prefersDark": false,
"bodyBackground": "rgb(246, 243, 240)",
"bg": "#f6f3f0"
},
{
"name": "restart keeps light",
"themeSource": "light",
"windowBackground": "#F6F3F0",
"prefersDark": false,
"bodyBackground": "rgb(246, 243, 240)",
"bg": "#f6f3f0",
"stored": "light"
},
{
"name": "stored \"system\" kept",
"legacyStored": "system",
"prefersDark": true
}
],
"ok": true
}
+17
View File
@@ -46,6 +46,7 @@ preview that the channel hides.
| Installation | Detection | Behaviour |
|---|---|---|
| Windows x64, NSIS installer | `Uninstall TeamsPeach.exe` next to the executable | download, then silent NSIS update after the user confirms; the installer starts the new version |
| Windows x64, NSIS installer, started with `TEAMSPEACH_PROFILE_DIR` | as above + profile override | notification only (`mode: 'manual'`, `manualReason: 'custom-profile'`); never downloads or installs, `update:install` returns `custom-profile` even when the user confirms |
| Linux x64 / arm64 AppImage | `APPIMAGE` environment variable | download, then the AppImage file is replaced and the app relaunches after the user confirms |
| Windows x64 zip, Linux tar.gz | otherwise | notification only; "open release page"; the user replaces files manually |
| macOS, Windows ARM64, development runs | — | updates disabled (`disabledCode`) — no builds are published for them |
@@ -106,3 +107,19 @@ The service log is `logs/updater.log` in the profile directory (English).
profile under Xvfb with `APPIMAGE_EXTRACT_AND_RUN=1`, lets it update itself from the real release server,
and checks the relaunched version, the installed file against the feed sha512, and that UID, nickname,
bookmark and device preference are unchanged (`scripts/update-e2e.mjs`).
- `scripts/update-live-check.mjs --as <version>`: real check, download and sha512 verification against the
public release server through the platform's real updater (NSIS on Windows, AppImage on Linux) in a
dev-mode harness with a temp profile and cache. It never installs.
### Why the Windows install is not tested on a normal user account
A silent NSIS update with `--force-run` relaunches the app through `StdUtils.ExecShellAsUser`
(`templates/nsis/common.nsh`, `installSection.nsh`), i.e. `IShellDispatch2::ShellExecute` of the desktop shell
on the Start Menu shortcut. The new process inherits Explorer's environment, not the installer's, so a
`TEAMSPEACH_PROFILE_DIR` test profile is not carried over, and the installer writes to the per-user
installation registered for `dev.teamspeach.desktop`. An install test therefore needs a separate Windows
account or VM; on a normal account only check, download and verification are exercised
(`update-live-check.mjs`). For the same reason the product never self-updates an NSIS installation that runs
on a `TEAMSPEACH_PROFILE_DIR` profile: the updated app would come back on the default profile, so such a run
gets the release page and a reason instead (engine test scenario "custom profile"). The AppImage relaunch
uses `app.relaunch`, which keeps the environment, so a custom profile survives it.
+29
View File
@@ -0,0 +1,29 @@
// Deterministic Playwright launch of TeamsPeach for the smoke scripts.
//
// Dev tree: no executablePath, so Playwright starts its bundled Electron with its own `-r loader.js`, which
// holds the app's `ready` until Playwright has attached.
// Packaged build (--exe): Playwright cannot inject that loader, and when it attaches while the first page is
// committing its utility world is lost and `electron.launch` hangs. The app is therefore started with
// TEAMSPEACH_TEST_HOLD_WINDOW=1 and the window is created through the main-process hook only after attach.
import { _electron as electron } from 'playwright-core';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
export const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
/**
* @param {{ exe?: string, profile: string, args?: string[], env?: object, colorScheme?: null | 'light' | 'dark', timeout?: number }} o
*/
export async function launchApp({ exe, profile, args = [], env = {}, colorScheme = null, timeout }) {
const baseEnv = { ...process.env, TEAMSPEACH_PROFILE_DIR: profile, ...env };
if (!exe) return electron.launch({ args: [root, ...args], env: baseEnv, colorScheme, timeout });
const app = await electron.launch({
executablePath: path.resolve(exe),
args,
env: { ...baseEnv, TEAMSPEACH_TEST_HOLD_WINDOW: '1' },
colorScheme,
timeout,
});
await app.evaluate(() => globalThis.__teamspeachCreateWindow());
return app;
}
+2 -5
View File
@@ -7,16 +7,13 @@
// while callbacks are pending). It is NOT TeamSpeak interoperability: see scripts/probe-stream.mjs.
//
// node scripts/loopback-stream.mjs --out docs/evidence/runtime/<name>
import { _electron as electron } from 'playwright-core';
import { launchApp } from './lib/electron-app.mjs';
import { mkdirSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const require = createRequire(import.meta.url);
const electronPath = require('electron');
const argv = process.argv.slice(2);
const out = path.resolve(root, argv[argv.indexOf('--out') + 1] ?? 'loopback-out');
mkdirSync(out, { recursive: true });
@@ -103,7 +100,7 @@ let page;
let failed = null;
try {
// Synthetic capture device only: getUserMedia permission unlocks real output-device enumeration.
app = await electron.launch({ executablePath: electronPath, args: [root, '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'], env: { ...process.env, TEAMSPEACH_PROFILE_DIR: profile } });
app = await launchApp({ profile, args: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'] });
page = await app.firstWindow();
page.on('console', (m) => result.console.push(`${m.type()}: ${m.text()}`));
page.on('pageerror', (e) => result.console.push(`pageerror: ${e.message}`));
+2 -5
View File
@@ -3,16 +3,13 @@
// No video pixels are saved: the video element is hidden for the UI screenshot.
//
// node scripts/probe-stream.mjs --server 10.10.10.160:9987 --channel cs --out docs/evidence/runtime/<name> [--seconds 40]
import { _electron as electron } from 'playwright-core';
import { launchApp } from './lib/electron-app.mjs';
import { mkdirSync, writeFileSync, mkdtempSync, readFileSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const require = createRequire(import.meta.url);
const electronPath = require('electron');
const argv = process.argv.slice(2);
const opt = (n, d) => (argv.indexOf(`--${n}`) >= 0 ? argv[argv.indexOf(`--${n}`) + 1] : d);
const server = opt('server');
@@ -34,7 +31,7 @@ let app;
let page;
let failed = null;
try {
app = await electron.launch({ executablePath: electronPath, args: [root], env: { ...process.env, TEAMSPEACH_PROFILE_DIR: profile } });
app = await launchApp({ profile });
page = await app.firstWindow();
page.on('console', (m) => result.console.push(`${m.type()}: ${m.text()}`));
page.on('pageerror', (e) => result.console.push(`pageerror: ${e.message}`));
+2 -4
View File
@@ -2,15 +2,13 @@
// footer microphone/headphones buttons open the device menu without toggling mute/deafen; choosing an
// entry updates Settings and persists; Escape restores focus.
// node scripts/smoke-devices-menu.mjs --out docs/evidence/runtime/<name> [--exe packaged.exe]
import { _electron as electron } from 'playwright-core';
import { launchApp } from './lib/electron-app.mjs';
import { mkdirSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const electronPath = createRequire(import.meta.url)('electron');
const argv = process.argv.slice(2);
const opt = (n, d) => (argv.indexOf(`--${n}`) >= 0 ? argv[argv.indexOf(`--${n}`) + 1] : d);
const out = path.resolve(root, opt('out', 'smoke-out'));
@@ -24,7 +22,7 @@ const step = (name, data = {}) => {
};
async function launch(label) {
const app = await electron.launch({ executablePath: exe ? path.resolve(exe) : electronPath, args: exe ? [] : [root], env: { ...process.env, TEAMSPEACH_PROFILE_DIR: profile }, colorScheme: null });
const app = await launchApp({ exe, profile });
const page = await app.firstWindow();
page.on('console', (m) => result.console.push(`${label} ${m.type()}: ${m.text()}`));
page.on('pageerror', (e) => result.console.push(`${label} pageerror: ${e.message}`));
+2 -9
View File
@@ -2,15 +2,13 @@
// capture, selects a non-default microphone and output, restarts and checks the choice persisted.
// Never connects to a server, never starts the microphone, plays nothing.
// node scripts/smoke-devices.mjs --out docs/evidence/runtime/<name> [--exe packaged.exe]
import { _electron as electron } from 'playwright-core';
import { launchApp } from './lib/electron-app.mjs';
import { mkdirSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const electronPath = createRequire(import.meta.url)('electron');
const argv = process.argv.slice(2);
const opt = (n, d) => (argv.indexOf(`--${n}`) >= 0 ? argv[argv.indexOf(`--${n}`) + 1] : d);
const out = path.resolve(root, opt('out', 'smoke-out'));
@@ -24,12 +22,7 @@ const step = (name, data = {}) => {
};
async function launch(label) {
const app = await electron.launch({
executablePath: exe ? path.resolve(exe) : electronPath,
args: exe ? [] : [root],
env: { ...process.env, TEAMSPEACH_PROFILE_DIR: profile },
colorScheme: null,
});
const app = await launchApp({ exe, profile });
const page = await app.firstWindow();
page.on('console', (m) => result.console.push(`${label} ${m.type()}: ${m.text()}`));
page.on('pageerror', (e) => result.console.push(`${label} pageerror: ${e.message}`));
+2 -4
View File
@@ -1,15 +1,13 @@
// Real Electron localization smoke. Uses only a disposable disconnected profile; never captures audio.
// No locale emulation, fake devices, server connections, or changes to the owner's profile.
import { _electron as electron } from 'playwright-core';
import { launchApp } from './lib/electron-app.mjs';
import assert from 'node:assert/strict';
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const executablePath = createRequire(import.meta.url)('electron');
const outArg = process.argv.indexOf('--out');
const out = path.resolve(root, outArg >= 0 ? process.argv[outArg + 1] : 'smoke-out/i18n');
const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-i18n-'));
@@ -25,7 +23,7 @@ const withoutLanguage = ({ language, ...rest }) => rest;
const state = () => page.evaluate(() => window.teamspeachDiagnostics.snapshot());
async function launch() {
app = await electron.launch({ executablePath, args: [root], env: { ...process.env, TEAMSPEACH_PROFILE_DIR: profile }, colorScheme: null });
app = await launchApp({ profile });
page = await app.firstWindow();
page.on('pageerror', (error) => errors.push(error.message));
await page.setViewportSize({ width: 1280, height: 800 });
+2 -10
View File
@@ -1,15 +1,13 @@
// Real UI smoke: saved servers (save → edit → delete → restart → one-click connect with the same UID,
// microphone muted), sectioned settings navigation while connected (connection untouched), screenshots.
// node scripts/smoke-servers.mjs --server 10.10.10.160:9987 --out docs/evidence/runtime/<name> [--exe packaged.exe] [--theme dark]
import { _electron as electron } from 'playwright-core';
import { launchApp } from './lib/electron-app.mjs';
import { mkdirSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const electronPath = createRequire(import.meta.url)('electron');
const argv = process.argv.slice(2);
const opt = (n, d) => (argv.indexOf(`--${n}`) >= 0 ? argv[argv.indexOf(`--${n}`) + 1] : d);
const server = opt('server');
@@ -25,13 +23,7 @@ const step = (name, data = {}) => {
const diag = (page) => page.evaluate(() => window.teamspeachDiagnostics.snapshot());
async function launch(label) {
const app = await electron.launch({
executablePath: exe ? path.resolve(exe) : electronPath,
args: exe ? [] : [root],
env: { ...process.env, TEAMSPEACH_PROFILE_DIR: profile },
// Playwright emulates a light colour scheme by default; null keeps the app's real theme handling.
colorScheme: null,
});
const app = await launchApp({ exe, profile });
const page = await app.firstWindow();
page.on('console', (m) => result.console.push(`${label} ${m.type()}: ${m.text()}`));
page.on('pageerror', (e) => result.console.push(`${label} pageerror: ${e.message}`));
+2 -4
View File
@@ -2,16 +2,14 @@
// a new profile is dark from the first frame (window background + onboarding), light chosen in Settings
// persists across restart, and a stored legacy choice ('system') is kept untouched.
// node scripts/smoke-theme.mjs --out docs/evidence/runtime/<name> [--exe packaged.exe]
import { _electron as electron } from 'playwright-core';
import { launchApp } from './lib/electron-app.mjs';
import { mkdirSync, writeFileSync, mkdtempSync, rmSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
import { execFileSync } from 'node:child_process';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const electronPath = createRequire(import.meta.url)('electron');
const argv = process.argv.slice(2);
const opt = (n, d) => (argv.indexOf(`--${n}`) >= 0 ? argv[argv.indexOf(`--${n}`) + 1] : d);
const out = path.resolve(root, opt('out', 'smoke-out'));
@@ -34,7 +32,7 @@ function osTheme() {
}
async function launch(profile) {
const app = await electron.launch({ executablePath: exe ? path.resolve(exe) : electronPath, args: exe ? [] : [root], env: { ...process.env, TEAMSPEACH_PROFILE_DIR: profile }, colorScheme: null });
const app = await launchApp({ exe, profile });
const page = await app.firstWindow();
await page.setViewportSize({ width: 1280, height: 800 }).catch(() => {});
return { app, page };
+2 -4
View File
@@ -1,15 +1,13 @@
// Read-only live check of server metadata rendering: connect muted, stay in the default channel,
// count rendered group labels/icons, channel icons/banners and avatars, screenshot the tree.
// node scripts/smoke-tree.mjs --server 10.10.10.160:9987 --out docs/evidence/runtime/<name>
import { _electron as electron } from 'playwright-core';
import { launchApp } from './lib/electron-app.mjs';
import { mkdirSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const electronPath = createRequire(import.meta.url)('electron');
const argv = process.argv.slice(2);
const opt = (n, d) => (argv.indexOf(`--${n}`) >= 0 ? argv[argv.indexOf(`--${n}`) + 1] : d);
const out = path.resolve(root, opt('out', 'smoke-out'));
@@ -18,7 +16,7 @@ const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-tree-'));
const result = { steps: [], console: [] };
let app;
try {
app = await electron.launch({ executablePath: electronPath, args: [root], env: { ...process.env, TEAMSPEACH_PROFILE_DIR: profile } });
app = await launchApp({ profile });
const page = await app.firstWindow();
page.on('console', (m) => result.console.push(`${m.type()}: ${m.text()}`));
page.on('pageerror', (e) => result.console.push(`pageerror: ${e.message}`));
+2 -9
View File
@@ -4,16 +4,13 @@
// node scripts/smoke-ui.mjs --out docs/evidence/runtime/<name> [--server 10.10.10.160:9987] [--profile DIR]
//
// Writes screenshots and result.json (UIDs are public identifiers; no private key ever leaves the core).
import { _electron as electron } from 'playwright-core';
import { launchApp } from './lib/electron-app.mjs';
import { mkdirSync, writeFileSync, mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const require = createRequire(import.meta.url);
const electronPath = require('electron');
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => {
if (a.startsWith('--')) acc.push([a.slice(2), all[i + 1] && !all[i + 1].startsWith('--') ? all[i + 1] : 'true']);
@@ -32,11 +29,7 @@ const step = (name, data = {}) => {
async function launch(label) {
const extra = [...(process.env.TEAMSPEACH_SMOKE_EXTRA_ARGS ?? '').split(' ').filter(Boolean), ...(args.fakemic ? ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'] : [])];
// --exe runs a packaged build instead of the development tree.
const app = await electron.launch({
executablePath: args.exe ? path.resolve(args.exe) : electronPath,
env: { ...process.env, TEAMSPEACH_PROFILE_DIR: profile },
args: args.exe ? extra : [root, ...extra],
});
const app = await launchApp({ exe: args.exe, profile, args: extra });
const page = await app.firstWindow();
page.on('console', (msg) => result.console.push(`${label} ${msg.type()}: ${msg.text()}`));
page.on('pageerror', (err) => result.console.push(`${label} pageerror: ${err.message}`));
+2 -9
View File
@@ -6,16 +6,13 @@
//
// The synthetic microphone (--use-fake-device-for-media-stream) replaces only the capture device;
// everything after getUserMedia (worklet, IPC, core Opus, server, decode, mix, playback) is the real path.
import { _electron as electron } from 'playwright-core';
import { launchApp } from './lib/electron-app.mjs';
import { mkdirSync, writeFileSync, mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const require = createRequire(import.meta.url);
const electronPath = require('electron');
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
@@ -37,11 +34,7 @@ const step = (name, data = {}) => {
async function launch(label, nickname) {
const profile = mkdtempSync(path.join(tmpdir(), `teamspeach-${label}-`));
const app = await electron.launch({
executablePath: electronPath,
args: [root, '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'],
env: { ...process.env, TEAMSPEACH_PROFILE_DIR: profile },
});
const app = await launchApp({ profile, args: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'] });
const page = await app.firstWindow();
page.on('console', (m) => result.console.push(`${label} ${m.type()}: ${m.text()}`));
page.on('pageerror', (e) => result.console.push(`${label} pageerror: ${e.message}`));
+178 -156
View File
@@ -1,156 +1,178 @@
// End-to-end self-update of a real, published Linux AppImage (no mocks, no credentials):
// 1. start the OLD published AppImage with a disposable profile and create an identity, bookmark, device pref;
// 2. let its updater find, download and verify the NEWER published release from git.eeee.moe;
// 3. confirm install: the AppImage file is replaced and the app relaunches by itself after exiting;
// 4. the relaunched process reports the new version; its file matches the release feed's sha512;
// 5. start the new AppImage again: version, UID, nickname, bookmark and device pref are unchanged.
//
// xvfb-run -a node scripts/update-e2e.mjs --from <old.AppImage> --to-tag v0.1.2-rc.2 --out update-e2e-out
//
// Runs AppImages with APPIMAGE_EXTRACT_AND_RUN=1 (no FUSE needed). Everything lives in a temp directory:
// profile, updater cache, the "installed" AppImage. The user's own installation is never touched.
import { _electron as electron } from 'playwright-core';
import { createHash } from 'node:crypto';
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { parseFeed } from './update-feed-check.mjs';
const argv = process.argv.slice(2);
const opt = (n) => (argv.indexOf(`--${n}`) >= 0 ? argv[argv.indexOf(`--${n}`) + 1] : undefined);
const fromImage = opt('from');
const toTag = opt('to-tag');
const out = path.resolve(opt('out') ?? 'update-e2e-out');
if (!fromImage || !toTag || process.platform !== 'linux') {
console.error('usage (Linux): update-e2e.mjs --from <old.AppImage> --to-tag <vX> [--out dir]');
process.exit(2);
}
const toVersion = toTag.slice(1);
const RELEASE = 'https://git.eeee.moe/TeamsPeach/client/releases/download';
mkdirSync(out, { recursive: true });
const work = mkdtempSync(path.join(tmpdir(), 'teamspeach-update-e2e-'));
const apps = path.join(work, 'apps');
const profile = path.join(work, 'profile');
mkdirSync(apps);
const installed = path.join(apps, path.basename(fromImage));
copyFileSync(fromImage, installed);
chmodSync(installed, 0o755);
const env = {
...process.env,
TEAMSPEACH_PROFILE_DIR: profile,
XDG_CACHE_HOME: path.join(work, 'cache'),
APPIMAGE_EXTRACT_AND_RUN: '1',
};
const result = { startedAt: new Date().toISOString(), fromImage: path.basename(fromImage), toTag, steps: [] };
const step = (name, data = {}) => {
result.steps.push({ name, at: new Date().toISOString(), ...data });
console.log(`[update-e2e] ${name} ${JSON.stringify(data)}`);
};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const sha512 = (file) => createHash('sha512').update(readFileSync(file)).digest('base64');
const updaterLog = () => {
const file = path.join(profile, 'logs', 'updater.log');
return existsSync(file) ? readFileSync(file, 'utf8') : '';
};
async function launch(image, label) {
const app = await electron.launch({ executablePath: image, args: ['--no-sandbox'], env, timeout: 120000 });
const page = await app.firstWindow({ timeout: 120000 });
page.on('console', (m) => m.type() === 'error' && step(`${label} console error`, { text: m.text().slice(0, 300) }));
return { app, page };
}
const diag = (page) => page.evaluate(() => window.teamspeachDiagnostics.snapshot());
async function waitFor(fn, ms, what) {
const end = Date.now() + ms;
for (;;) {
const v = await fn();
if (v) return v;
if (Date.now() > end) throw new Error(`timed out waiting for ${what}`);
await sleep(1000);
}
}
let failed = null;
try {
// 1. Old version, fresh profile.
let { app, page } = await launch(installed, 'old');
await page.waitForSelector('#view-onboarding', { state: 'visible', timeout: 60000 });
await page.fill('#onboarding-nick', 'UpdateProof');
await page.click('#onboarding-submit');
await page.waitForSelector('#view-app', { state: 'visible', timeout: 60000 });
const before = await diag(page);
const oldInfo = await page.evaluate(() => window.teamspeach.getAppInfo());
const bookmark = { id: 'upd0001', name: 'Update proof', address: '192.0.2.10:9987' };
await page.evaluate((b) => window.teamspeach.setPrefs({ savedServers: [b], inputDeviceId: 'update-proof-device' }), bookmark);
step('old version running', { version: oldInfo.appVersion, uid: before.profile.uid, nickname: before.profile.nickname });
// 2. Real check + download from the public release server.
const checked = await page.evaluate(() => window.teamspeach.checkForUpdates());
step('check', { phase: checked.phase, available: checked.available, error: checked.error, skipped: checked.newerWithoutBuild });
const ready = await waitFor(async () => {
const s = await page.evaluate(() => window.teamspeach.getUpdateState());
if (s.phase === 'error') throw new Error(`updater error ${JSON.stringify(s.error)}`);
return s.phase === 'downloaded' && s;
}, 600000, 'download');
step('downloaded and verified by electron-updater', { available: ready.available, target: ready.target });
if (ready.available.version !== toVersion) throw new Error(`offered ${ready.available.version}, expected ${toVersion}`);
// 3. User confirms install (also confirming interruption, as the UI would).
const exited = new Promise((r) => app.process().once('exit', (code, signal) => r({ code, signal })));
const install = await page.evaluate(() => window.teamspeach.installUpdate(true)).catch((e) => ({ evaluateEnded: e.message.slice(0, 200) }));
step('install requested', { install });
step('old process exited', await Promise.race([exited, sleep(180000).then(() => ({ timeout: true }))]));
// 4. Relaunch happened by itself: the new version logs its start with its pid.
const started = await waitFor(() => {
const m = new RegExp(`updater: version ${toVersion.replace(/\./g, '\\.')} pid (\\d+) target (\\S+)`).exec(updaterLog());
return m && { pid: Number(m[1]), target: m[2] };
}, 180000, 'relaunched new version');
step('new version relaunched automatically', started);
const files = readdirSync(apps);
const newImage = path.join(apps, files.find((f) => f.endsWith('.AppImage')));
const feedName = `${toVersion.includes('-') ? toVersion.split('-')[1].split('.')[0] : 'latest'}-linux.yml`;
const feedRes = await fetch(`${RELEASE}/${toTag}/${feedName}`);
if (!feedRes.ok) throw new Error(`feed ${feedName}: HTTP ${feedRes.status}`);
const feed = parseFeed(await feedRes.text());
const fileSha = sha512(newImage);
step('installed file', { files, sha512MatchesFeed: fileSha === feed.files[0].sha512, feedFile: feed.files[0].url });
if (files.length !== 1 || path.basename(newImage) !== feed.files[0].url || fileSha !== feed.files[0].sha512) {
throw new Error('installed AppImage does not match the release feed');
}
process.kill(started.pid, 'SIGTERM');
await waitFor(() => !existsSync(`/proc/${started.pid}`), 60000, 'relaunched app to exit');
await sleep(2000);
// 5. Start the new AppImage again: same identity and preferences, new version.
({ app, page } = await launch(newImage, 'new'));
await page.waitForSelector('#view-app', { state: 'visible', timeout: 60000 });
const after = await diag(page);
const newInfo = await page.evaluate(() => window.teamspeach.getAppInfo());
const prefs = await page.evaluate(() => window.teamspeach.getPrefs());
const state = await page.evaluate(() => window.teamspeach.getUpdateState());
await page.screenshot({ path: path.join(out, 'after-update.png') });
await app.close();
const kept = {
version: newInfo.appVersion,
uidSame: after.profile.uid === before.profile.uid,
nicknameSame: after.profile.nickname === before.profile.nickname,
bookmarkSame: JSON.stringify(prefs.savedServers) === JSON.stringify([bookmark]),
deviceSame: prefs.inputDeviceId === 'update-proof-device',
updater: { phase: state.phase, target: state.target, mode: state.mode },
};
step('after update', kept);
if (kept.version !== toVersion || !kept.uidSame || !kept.nicknameSame || !kept.bookmarkSame || !kept.deviceSame) {
throw new Error('state after update is wrong');
}
} catch (err) {
failed = err;
step('FAILED', { error: err.message });
}
result.updaterLog = updaterLog().split('\n').filter((l) => / updater: /.test(l));
result.ok = !failed;
writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2));
process.exit(failed ? 1 : 0);
// End-to-end self-update of a real, published Linux AppImage (no mocks, no credentials):
// 1. start the OLD published AppImage with a disposable profile and create an identity, bookmark, device pref;
// 2. let its updater find, download and verify the NEWER published release from git.eeee.moe;
// 3. confirm install: the AppImage file is replaced and the app relaunches by itself after exiting;
// 4. the relaunched process reports the new version; its file matches the release feed's sha512;
// 5. start the new AppImage again: version, UID, nickname, bookmark and device pref are unchanged.
//
// xvfb-run -a node scripts/update-e2e.mjs --from <old.AppImage> --to-tag v0.1.2-rc.2 --out update-e2e-out
//
// Runs AppImages with APPIMAGE_EXTRACT_AND_RUN=1 (no FUSE needed). Everything lives in a temp directory:
// profile, updater cache, the "installed" AppImage. The user's own installation is never touched.
import { chromium } from 'playwright-core';
import { createHash } from 'node:crypto';
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { launchApp } from './lib/electron-app.mjs';
import { parseFeed } from './update-feed-check.mjs';
const argv = process.argv.slice(2);
const opt = (n) => (argv.indexOf(`--${n}`) >= 0 ? argv[argv.indexOf(`--${n}`) + 1] : undefined);
const fromImage = opt('from');
const toTag = opt('to-tag');
const out = path.resolve(opt('out') ?? 'update-e2e-out');
if (!fromImage || !toTag || process.platform !== 'linux') {
console.error('usage (Linux): update-e2e.mjs --from <old.AppImage> --to-tag <vX> [--out dir]');
process.exit(2);
}
const toVersion = toTag.slice(1);
const RELEASE = 'https://git.eeee.moe/TeamsPeach/client/releases/download';
mkdirSync(out, { recursive: true });
const work = mkdtempSync(path.join(tmpdir(), 'teamspeach-update-e2e-'));
const apps = path.join(work, 'apps');
const profile = path.join(work, 'profile');
mkdirSync(apps);
const installed = path.join(apps, path.basename(fromImage));
copyFileSync(fromImage, installed);
chmodSync(installed, 0o755);
const env = { XDG_CACHE_HOME: path.join(work, 'cache'), APPIMAGE_EXTRACT_AND_RUN: '1' };
const result = { startedAt: new Date().toISOString(), fromImage: path.basename(fromImage), toTag, steps: [] };
const step = (name, data = {}) => {
result.steps.push({ name, at: new Date().toISOString(), ...data });
console.log(`[update-e2e] ${name} ${JSON.stringify(data)}`);
};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const sha512 = (file) => createHash('sha512').update(readFileSync(file)).digest('base64');
const updaterLog = () => {
const file = path.join(profile, 'logs', 'updater.log');
return existsSync(file) ? readFileSync(file, 'utf8') : '';
};
async function launch(image, label) {
const app = await launchApp({ exe: image, profile, args: ['--no-sandbox'], env, timeout: 120000 });
const page = await app.firstWindow({ timeout: 120000 });
page.on('console', (m) => m.type() === 'error' && step(`${label} console error`, { text: m.text().slice(0, 300) }));
return { app, page };
}
const diag = (page) => page.evaluate(() => window.teamspeachDiagnostics.snapshot());
async function waitFor(fn, ms, what) {
const end = Date.now() + ms;
for (;;) {
const v = await fn();
if (v) return v;
if (Date.now() > end) throw new Error(`timed out waiting for ${what}`);
await sleep(1000);
}
}
let failed = null;
try {
// 1. Old version, fresh profile.
let { app, page } = await launch(installed, 'old');
await page.waitForSelector('#view-onboarding', { state: 'visible', timeout: 60000 });
await page.fill('#onboarding-nick', 'UpdateProof');
await page.click('#onboarding-submit');
await page.waitForSelector('#view-app', { state: 'visible', timeout: 60000 });
const before = await diag(page);
const oldInfo = await page.evaluate(() => window.teamspeach.getAppInfo());
const bookmark = { id: 'upd0001', name: 'Update proof', address: '192.0.2.10:9987' };
await page.evaluate((b) => window.teamspeach.setPrefs({ savedServers: [b], inputDeviceId: 'update-proof-device' }), bookmark);
step('old version running', { version: oldInfo.appVersion, uid: before.profile.uid, nickname: before.profile.nickname });
// 2. Real check + download from the public release server.
const checked = await page.evaluate(() => window.teamspeach.checkForUpdates());
step('check', { phase: checked.phase, available: checked.available, error: checked.error, skipped: checked.newerWithoutBuild });
const ready = await waitFor(async () => {
const s = await page.evaluate(() => window.teamspeach.getUpdateState());
if (s.phase === 'error') throw new Error(`updater error ${JSON.stringify(s.error)}`);
return s.phase === 'downloaded' && s;
}, 600000, 'download');
step('downloaded and verified by electron-updater', { available: ready.available, target: ready.target });
if (ready.available.version !== toVersion) throw new Error(`offered ${ready.available.version}, expected ${toVersion}`);
// 3. User confirms install (also confirming interruption, as the UI would). The relaunched process inherits
// this process's environment: drop the test-only window hold so it starts exactly like a normal launch, and
// remove the old DevToolsActivePort so the new process's port can be found.
await app.evaluate(() => {
delete process.env.TEAMSPEACH_TEST_HOLD_WINDOW;
});
rmSync(path.join(profile, 'DevToolsActivePort'), { force: true });
const exited = new Promise((r) => app.process().once('exit', (code, signal) => r({ code, signal })));
const install = await page.evaluate(() => window.teamspeach.installUpdate(true)).catch((e) => ({ evaluateEnded: e.message.slice(0, 200) }));
step('install requested', { install });
step('old process exited', await Promise.race([exited, sleep(180000).then(() => ({ timeout: true }))]));
// 4. Relaunch happened by itself: the new version logs its start with its pid.
const started = await waitFor(() => {
const m = new RegExp(`updater: version ${toVersion.replace(/\./g, '\\.')} pid (\\d+) target (\\S+)`).exec(updaterLog());
return m && { pid: Number(m[1]), target: m[2] };
}, 180000, 'relaunched new version');
step('new version relaunched automatically', started);
// The relaunched app inherited --remote-debugging-port=0: attach over CDP and read its own window.
const port = await waitFor(() => {
const f = path.join(profile, 'DevToolsActivePort');
return existsSync(f) && Number(readFileSync(f, 'utf8').split('\n')[0]);
}, 120000, 'DevToolsActivePort of the relaunched app');
const browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`);
const relaunchedPage = await waitFor(async () => {
for (const ctx of browser.contexts()) for (const p of ctx.pages()) if (p.url().startsWith('app://')) return p;
return null;
}, 120000, 'window of the relaunched app');
await relaunchedPage.waitForSelector('#view-app', { state: 'visible', timeout: 60000 });
const relaunched = {
version: (await relaunchedPage.evaluate(() => window.teamspeach.getAppInfo())).appVersion,
uid: (await diag(relaunchedPage)).profile.uid,
};
await relaunchedPage.screenshot({ path: path.join(out, 'relaunched.png') });
await browser.close().catch(() => {});
step('relaunched window', { ...relaunched, uidSame: relaunched.uid === before.profile.uid });
if (relaunched.version !== toVersion || relaunched.uid !== before.profile.uid) throw new Error('relaunched app has the wrong version or identity');
const files = readdirSync(apps);
const newImage = path.join(apps, files.find((f) => f.endsWith('.AppImage')));
const feedName = `${toVersion.includes('-') ? toVersion.split('-')[1].split('.')[0] : 'latest'}-linux.yml`;
const feedRes = await fetch(`${RELEASE}/${toTag}/${feedName}`);
if (!feedRes.ok) throw new Error(`feed ${feedName}: HTTP ${feedRes.status}`);
const feed = parseFeed(await feedRes.text());
const fileSha = sha512(newImage);
step('installed file', { files, sha512MatchesFeed: fileSha === feed.files[0].sha512, feedFile: feed.files[0].url });
if (files.length !== 1 || path.basename(newImage) !== feed.files[0].url || fileSha !== feed.files[0].sha512) {
throw new Error('installed AppImage does not match the release feed');
}
process.kill(started.pid, 'SIGTERM');
await waitFor(() => !existsSync(`/proc/${started.pid}`), 60000, 'relaunched app to exit');
await sleep(2000);
// 5. Start the new AppImage again: same identity and preferences, new version.
({ app, page } = await launch(newImage, 'new'));
await page.waitForSelector('#view-app', { state: 'visible', timeout: 60000 });
const after = await diag(page);
const newInfo = await page.evaluate(() => window.teamspeach.getAppInfo());
const prefs = await page.evaluate(() => window.teamspeach.getPrefs());
const state = await page.evaluate(() => window.teamspeach.getUpdateState());
await page.screenshot({ path: path.join(out, 'after-update.png') });
await app.close();
const kept = {
version: newInfo.appVersion,
uidSame: after.profile.uid === before.profile.uid,
nicknameSame: after.profile.nickname === before.profile.nickname,
bookmarkSame: JSON.stringify(prefs.savedServers) === JSON.stringify([bookmark]),
deviceSame: prefs.inputDeviceId === 'update-proof-device',
updater: { phase: state.phase, target: state.target, mode: state.mode },
};
step('after update', kept);
if (kept.version !== toVersion || !kept.uidSame || !kept.nicknameSame || !kept.bookmarkSame || !kept.deviceSame) {
throw new Error('state after update is wrong');
}
} catch (err) {
failed = err;
step('FAILED', { error: err.message });
}
result.updaterLog = updaterLog().split('\n').filter((l) => / updater: /.test(l));
result.ok = !failed;
writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2));
process.exit(failed ? 1 : 0);
+24
View File
@@ -0,0 +1,24 @@
// Real check + download + sha512 verification against the PUBLIC release server, as an installation of
// version --as would do it on this platform (Windows: NSIS updater, Linux: AppImage updater). Runs the update
// service in a dev-mode Electron harness with a temp profile and temp updater cache. Never installs.
//
// node scripts/update-live-check.mjs --as 0.1.2-rc.1 [--channel preview|stable] [--out result.json]
import { writeFileSync } from 'node:fs';
import { runUpdateHarness } from '../test/fixtures/run-update-harness.mjs';
const argv = process.argv.slice(2);
const opt = (n) => (argv.indexOf(`--${n}`) >= 0 ? argv[argv.indexOf(`--${n}`) + 1] : undefined);
const version = opt('as');
if (!version) {
console.error('usage: update-live-check.mjs --as <version> [--channel preview|stable] [--out file]');
process.exit(2);
}
const result = await runUpdateHarness({
version,
timeoutMs: 15 * 60 * 1000,
extraEnv: { UPDATE_HARNESS_LIVE: '1', UPDATE_HARNESS_CHANNEL: opt('channel') ?? 'preview' },
});
const text = JSON.stringify({ checkedAt: new Date().toISOString(), ...result }, null, 2);
if (opt('out')) writeFileSync(opt('out'), text);
console.log(text);
process.exit(result.live && result.live.phase !== 'error' ? 0 : 1);
+31
View File
@@ -79,3 +79,34 @@ test('a failure of a superseded start is ignored; a current failure is reported'
await assert.rejects(current, { name: 'NotAllowedError' });
assert.equal(engine.captureStarting, false);
});
test('a missing explicit device is an error with no second request for another microphone', async () => {
const { engine, pending, flush } = setup();
const start = engine.startCapture({ deviceId: 'gone' });
await flush();
pending[0].reject(Object.assign(new Error('not found'), { name: 'OverconstrainedError' }));
await assert.rejects(start, { code: 'device_unavailable' });
await flush();
assert.equal(pending.length, 1);
assert.equal(engine.capturing, false);
});
test('a failure while building the capture graph releases the opened microphone', async () => {
const { engine, pending, flush } = setup();
const disconnected = [];
engine.ctx.createMediaStreamSource = () => ({ connect: (n) => n, disconnect: () => disconnected.push('source') });
globalThis.AudioWorkletNode = class {
constructor() {
throw new Error('worklet not registered');
}
};
const start = engine.startCapture({});
await flush();
const stream = fakeStream('mic');
pending[0].resolve(stream);
await assert.rejects(start, /worklet not registered/);
assert.equal(stream.track.stopped, true);
assert.deepEqual(disconnected, ['source']);
assert.equal(engine.capturing, false);
assert.equal(engine.captureStarting, false);
});
+51
View File
@@ -0,0 +1,51 @@
// Launches test/fixtures/update-harness.cjs in Electron as an unpackaged app of the given version, with
// profile, updater cache and a dummy old AppImage inside a temp directory that is removed afterwards.
import { spawn } from 'node:child_process';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
export async function runUpdateHarness({ version, extraEnv = {}, timeoutMs = 120000 }) {
const tmp = mkdtempSync(path.join(os.tmpdir(), 'teamspeach-update-'));
try {
const appDir = path.join(tmp, 'app');
const cache = path.join(tmp, 'cache');
for (const d of [appDir, cache]) mkdirSync(d, { recursive: true });
// app.getVersion() comes from this package.json.
writeFileSync(path.join(appDir, 'package.json'), JSON.stringify({ name: 'teamspeach-update-harness', version, main: 'main.js' }));
writeFileSync(path.join(appDir, 'main.js'), `require(${JSON.stringify(path.join(repo, 'test', 'fixtures', 'update-harness.cjs'))});\n`);
const oldAppImage = path.join(tmp, `TeamsPeach-${version}.AppImage`);
writeFileSync(oldAppImage, 'old');
const args = [appDir];
if (process.platform === 'linux') args.push('--no-sandbox');
const env = {
...process.env,
UPDATE_HARNESS_REPO: repo,
UPDATE_HARNESS_TMP: tmp,
// electron-updater's download cache lives under these; keep it inside the temp dir.
LOCALAPPDATA: cache,
XDG_CACHE_HOME: cache,
APPIMAGE: oldAppImage,
...extraEnv,
};
delete env.ELECTRON_RUN_AS_NODE;
const child = spawn(require('electron'), args, { env, stdio: ['ignore', 'pipe', 'pipe'] });
let out = '';
let err = '';
child.stdout.on('data', (d) => (out += d));
child.stderr.on('data', (d) => (err += d));
const timer = setTimeout(() => child.kill(), timeoutMs);
const code = await new Promise((r) => child.on('exit', r));
clearTimeout(timer);
const line = out.split('\n').find((l) => l.startsWith('UPDATE_HARNESS_RESULT '));
if (!line) throw new Error(`harness failed (exit ${code}):\n${out}\n${err.slice(-4000)}`);
return JSON.parse(line.slice('UPDATE_HARNESS_RESULT '.length));
} finally {
rmSync(tmp, { recursive: true, force: true });
}
}
+52 -2
View File
@@ -5,6 +5,8 @@
// the protocol layer of BOTH sessions involved (default session: release list; "electron-updater": feeds and
// packages), so HTTP handling, sha512 verification and the download cache are the library's own.
// Never installs anything. Prints one JSON line with the scenario results and exits.
// With UPDATE_HARNESS_LIVE=1 it instead checks and downloads from the real public release server
// (scripts/update-live-check.mjs).
const crypto = require('node:crypto');
const fs = require('node:fs');
@@ -77,7 +79,7 @@ const cacheDirName = `teamspeach-updater-harness-${process.pid}`;
const updateConfig = path.join(tmp, 'app-update.yml');
fs.writeFileSync(updateConfig, `provider: generic\nurl: https://git.eeee.moe/\nupdaterCacheDirName: ${cacheDirName}\n`);
function service({ channel = 'preview', sessionActive = false, feedTimeoutMs } = {}) {
function service({ channel = 'preview', sessionActive = false, feedTimeoutMs, profileOverride = null, electronApp = app, installCalls = null } = {}) {
const prefsValues = { updateChannel: channel };
const session = { active: sessionActive };
const svc = createUpdateService({
@@ -86,10 +88,14 @@ function service({ channel = 'preview', sessionActive = false, feedTimeoutMs } =
send: () => {},
target: TARGET,
feedTimeoutMs,
profileOverride,
electronApp,
createUpdater: (t, logger, ch) => {
const u = createElectronUpdater(t, logger, ch);
u.forceDevUpdateConfig = true;
u.updateConfigPath = updateConfig;
// Recorded instead of executed: the harness never installs or quits.
if (installCalls) u.quitAndInstall = (...args) => installCalls.push(args);
return u;
},
});
@@ -177,6 +183,30 @@ const scenarios = {
const { svc } = service({ channel: 'stable' });
return pick(await svc.check({ manual: true }));
},
async customProfile() {
addRelease('v0.1.2-rc.2');
const installCalls = [];
const relaunches = [];
let quits = 0;
const fakeApp = { getVersion: () => app.getVersion(), isPackaged: false, relaunch: (o) => relaunches.push(o), quit: () => (quits += 1) };
const { svc } = service({ profileOverride: path.join(tmp, 'custom-profile'), electronApp: fakeApp, installCalls });
const checked = await svc.check({ manual: true });
const afterManualDownload = (await svc.download({ manual: true })).phase;
const install = svc.install({ confirmInterrupt: true });
return {
target: TARGET.kind,
mode: checked.mode,
manualReason: checked.manualReason,
phase: checked.phase,
available: checked.available && checked.available.version,
afterManualDownload,
packageRequested: requests.some((r) => /\.(exe|AppImage)(\?|$)/.test(r.url)),
install,
installCalls,
relaunches: relaunches.map((o) => ({ execPathIsAppImage: o.execPath === process.env.APPIMAGE })),
quits,
};
},
async sameAndOlder() {
addRelease('v0.1.2-rc.1');
addRelease('v0.1.1');
@@ -187,9 +217,29 @@ const scenarios = {
},
};
/** UPDATE_HARNESS_LIVE=1: the REAL release server, no interception; checks and downloads, never installs. */
async function live() {
const { svc } = service({ channel: process.env.UPDATE_HARNESS_CHANNEL || 'preview' });
const s = await svc.check({ manual: true });
const out = { ...pick(s), target: TARGET.id, cachedSha512: cachedPackageSha() };
if (s.available) {
const feedName = source.feedFileName(TARGET, s.available.version);
const res = await fetch(`${source.releaseDownloadBase(s.available.tag)}${feedName}`);
const feed = await res.text();
out.feed = { name: feedName, sha512: (/^ {4}sha512: (\S+)$/m.exec(feed) || [])[1], url: (/^ {2}- url: (\S+)$/m.exec(feed) || [])[1] };
out.cachedMatchesFeed = out.cachedSha512 === out.feed.sha512;
}
return out;
}
async function run() {
for (const ses of [session.defaultSession, session.fromPartition('electron-updater', { cache: false })]) ses.protocol.handle('https', handle);
const results = { version: app.getVersion(), target: TARGET.id };
if (process.env.UPDATE_HARNESS_LIVE === '1') {
results.live = await live();
process.stdout.write(`UPDATE_HARNESS_RESULT ${JSON.stringify(results)}\n`);
return;
}
for (const ses of [session.defaultSession, session.fromPartition('electron-updater', { cache: false })]) ses.protocol.handle('https', handle);
for (const [name, fn] of Object.entries(scenarios)) {
reset();
try {
+24 -49
View File
@@ -2,59 +2,12 @@
// test/fixtures/update-harness.cjs). Needs a display on Linux (CI runs it under xvfb-run).
import test from 'node:test';
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { runUpdateHarness } from './fixtures/run-update-harness.mjs';
const require = createRequire(import.meta.url);
const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const noDisplay = process.platform === 'linux' && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY;
async function runHarness() {
const tmp = mkdtempSync(path.join(os.tmpdir(), 'teamspeach-update-'));
try {
const appDir = path.join(tmp, 'app');
const cache = path.join(tmp, 'cache');
for (const d of [appDir, cache]) mkdirSync(d, { recursive: true });
// The running version comes from this package.json (app.getVersion()).
writeFileSync(path.join(appDir, 'package.json'), JSON.stringify({ name: 'teamspeach-update-harness', version: '0.1.2-rc.1', main: 'main.js' }));
writeFileSync(path.join(appDir, 'main.js'), `require(${JSON.stringify(path.join(repo, 'test', 'fixtures', 'update-harness.cjs'))});\n`);
const oldAppImage = path.join(tmp, 'TeamsPeach-0.1.2-rc.1.AppImage');
writeFileSync(oldAppImage, 'old');
const args = [appDir];
if (process.platform === 'linux') args.push('--no-sandbox');
const env = {
...process.env,
UPDATE_HARNESS_REPO: repo,
UPDATE_HARNESS_TMP: tmp,
// electron-updater's download cache lives under these; keep it inside the temp dir.
LOCALAPPDATA: cache,
XDG_CACHE_HOME: cache,
APPIMAGE: oldAppImage,
ELECTRON_ENABLE_LOGGING: '',
};
delete env.ELECTRON_RUN_AS_NODE;
const child = spawn(require('electron'), args, { env, stdio: ['ignore', 'pipe', 'pipe'] });
let out = '';
let err = '';
child.stdout.on('data', (d) => (out += d));
child.stderr.on('data', (d) => (err += d));
const timer = setTimeout(() => child.kill(), 120000);
const code = await new Promise((r) => child.on('exit', r));
clearTimeout(timer);
const line = out.split('\n').find((l) => l.startsWith('UPDATE_HARNESS_RESULT '));
if (!line) throw new Error(`harness failed (exit ${code}):\n${out}\n${err.slice(-4000)}`);
return JSON.parse(line.slice('UPDATE_HARNESS_RESULT '.length));
} finally {
rmSync(tmp, { recursive: true, force: true });
}
}
test('update service + electron-updater behaviour against an emulated Gitea release server', { skip: noDisplay && 'no display (run under xvfb-run)', timeout: 180000 }, async (t) => {
const r = await runHarness();
const r = await runUpdateHarness({ version: '0.1.2-rc.1' });
for (const [name, v] of Object.entries(r)) if (v && v.thrown) assert.fail(`${name}: ${v.thrown}`);
assert.equal(r.version, '0.1.2-rc.1');
@@ -113,6 +66,28 @@ test('update service + electron-updater behaviour against an emulated Gitea rele
assert.equal(r.stableChannel.newerPreview, '0.1.3');
});
await t.test('custom profile: NSIS never installs (Explorer relaunch would drop the profile); AppImage keeps its env', () => {
const c = r.customProfile;
assert.equal(c.available, '0.1.2-rc.2');
if (c.target === 'nsis') {
assert.equal(c.mode, 'manual');
assert.equal(c.manualReason, 'custom-profile');
assert.equal(c.phase, 'available');
assert.equal(c.afterManualDownload, 'available');
assert.equal(c.packageRequested, false);
assert.deepEqual(c.install, { ok: false, code: 'custom-profile' });
assert.deepEqual(c.installCalls, []);
assert.equal(c.quits, 0);
} else {
assert.equal(c.mode, 'auto');
assert.equal(c.manualReason, null);
assert.equal(c.phase, 'downloaded');
assert.deepEqual(c.install, { ok: true });
assert.deepEqual(c.installCalls, [[true, false]]);
assert.deepEqual(c.relaunches, [{ execPathIsAppImage: true }]);
}
});
await t.test('same version, older versions and older prereleases are not even fetched', () => {
assert.equal(r.sameAndOlder.phase, 'up-to-date');
assert.equal(r.sameAndOlder.feedRequests, 0);
+143
View File
@@ -0,0 +1,143 @@
// voice.js device and capture policy against stubbed DOM, Web Audio and getUserMedia (no real devices):
// a missing saved microphone never falls back to another one, a newly chosen device recovers capture only
// while capture is wanted, and a failed enumeration replaces the device menus' earlier list.
import test from 'node:test';
import assert from 'node:assert/strict';
const timeout = globalThis.setTimeout;
globalThis.setTimeout = (fn, ms, ...args) => {
const id = timeout(fn, ms, ...args);
id.unref?.();
return id;
};
class FakeNode {
constructor() {
Object.assign(this, { style: {}, dataset: {}, children: [], textContent: '', value: '', className: '' });
this.classList = { add() {}, remove() {}, toggle() {}, contains: () => false };
}
addEventListener() {}
removeEventListener() {}
setAttribute() {}
getAttribute() { return null; }
removeAttribute() {}
appendChild(child) { this.children.push(child); return child; }
replaceChildren(...children) { this.children = children; }
remove() {}
focus() {}
setPointerCapture() {}
querySelector() { return new FakeNode(); }
querySelectorAll() { return []; }
get firstElementChild() { return this.children[0] ?? new FakeNode(); }
}
const elements = new Map();
globalThis.Node = FakeNode;
globalThis.document = {
querySelector: (selector) => {
if (!elements.has(selector)) elements.set(selector, new FakeNode());
return elements.get(selector);
},
querySelectorAll: () => [],
createElement: () => new FakeNode(),
createElementNS: () => new FakeNode(),
createTextNode: () => new FakeNode(),
hasFocus: () => true,
documentElement: new FakeNode(),
};
globalThis.window = globalThis;
globalThis.addEventListener = () => {};
globalThis.requestAnimationFrame = () => 0;
const sent = [];
globalThis.teamspeach = { onAudio() {}, sendAudioFrame: (f) => sent.push(f), endAudio() {}, log() {} };
const calls = [];
const opened = [];
let enumerate = async () => [
{ kind: 'audioinput', deviceId: 'mic-2', label: 'Mic 2', groupId: 'g2' },
{ kind: 'audiooutput', deviceId: 'out-1', label: 'Out 1', groupId: 'g3' },
];
Object.defineProperty(globalThis, 'navigator', {
configurable: true,
value: {
mediaDevices: {
addEventListener() {},
enumerateDevices: () => enumerate(),
getUserMedia: async (constraints) => {
calls.push(constraints);
const id = constraints.audio.deviceId?.exact;
if (id === 'gone') throw Object.assign(new Error('Requested device not found'), { name: 'OverconstrainedError' });
const track = { label: id ?? 'default', muted: false, stopped: false, stop() { this.stopped = true; }, addEventListener() {}, getSettings: () => ({}) };
opened.push(track);
return { getTracks: () => [track], getAudioTracks: () => [track] };
},
},
},
});
const node = () => ({ connect: (next) => next, disconnect() {}, gain: { value: 1, setTargetAtTime() {} } });
globalThis.AudioContext = class {
constructor() {
Object.assign(this, { state: 'running', sampleRate: 48000, baseLatency: 0, currentTime: 0, destination: {} });
this.audioWorklet = { addModule: async () => {} };
}
createGain() { return node(); }
createMediaStreamSource() { return node(); }
async resume() {}
async setSinkId() {}
};
globalThis.AudioWorkletNode = class {
constructor() { Object.assign(this, node(), { port: { postMessage() {}, onmessage: null } }); }
};
const { S } = await import('../app/renderer/js/state.js');
const voice = await import('../app/renderer/js/voice.js');
S.prefs = { inputDeviceId: 'gone', outputDeviceId: '', echoCancellation: true, noiseSuppression: true, autoGainControl: true, transmitMode: 'open', pttCode: 'F8', voiceVolume: 100 };
voice.initVoice({ savePrefs: async (partial) => (S.prefs = { ...S.prefs, ...partial }) });
const connect = () => {
S.conn = { state: 'connected', address: 'x', reason: null };
S.snap = { clients: [], channels: [], own_client_id: 1, own_channel_id: 1 };
};
const disconnect = () => {
S.conn = { state: 'disconnected', address: '', reason: null };
S.snap = null;
};
test('a missing saved microphone fails closed: no other microphone is opened, nothing is sent', async () => {
connect();
await voice.syncCapture();
assert.equal(calls.length, 1);
assert.deepEqual(calls[0].audio.deviceId, { exact: 'gone' });
assert.equal(opened.length, 0);
assert.equal(voice.isCapturing(), false);
assert.equal(sent.length, 0);
});
test('choosing an available microphone after the failure recovers capture while connected', async () => {
await voice.chooseInputDevice('mic-2');
assert.equal(calls.length, 2);
assert.deepEqual(calls[1].audio.deviceId, { exact: 'mic-2' });
assert.equal(voice.isCapturing(), true);
assert.equal(opened.at(-1).label, 'mic-2');
});
test('while disconnected, choosing a microphone opens nothing', async () => {
disconnect();
await voice.syncCapture();
assert.equal(voice.isCapturing(), false);
assert.equal(opened.at(-1).stopped, true);
await voice.chooseInputDevice('mic-3');
assert.equal(calls.length, 2);
assert.equal(voice.isCapturing(), false);
});
test('a failed enumeration replaces the earlier device list for the menus', async () => {
const ok = await voice.deviceChoices();
assert.ok(ok.input.options.some((o) => o.value === 'mic-2'));
enumerate = async () => {
throw Object.assign(new Error('enumeration failed'), { name: 'NotReadableError' });
};
const failed = await voice.deviceChoices();
assert.deepEqual(failed, { error: { name: 'NotReadableError', message: 'enumeration failed' } });
assert.equal(failed.input, undefined);
});