Audio devices: fix permission origin (app://teamspeach/), real device lists, right-click device menus, voice TX diagnostics; version 0.1.2
This commit is contained in:
1 parent
8153e9b88b
commit
a3185229ee
25 files changed
+767
-50
No files matched your search
@@ -1,5 +1,20 @@
|
||||
# Changelog
|
||||
|
||||
## 0.1.2 — unreleased
|
||||
|
||||
- Fixed: Settings → Звук listed only "Системное устройство по умолчанию". Electron reports the app origin as
|
||||
`app://teamspeach/` and the permission check compared it with `app://teamspeach`, so Chromium withheld
|
||||
device ids and names. The audio-only permission policy now normalises origins (camera stays denied);
|
||||
real inputs and outputs are listed without starting the microphone, and the default entry names the
|
||||
device it points to.
|
||||
- Right-click (or Shift+F10 / Menu key) on the microphone and headphones buttons opens an input / output
|
||||
device menu sharing the Settings selection; left click still mutes/deafens.
|
||||
- Voice diagnostics in the local log: capture device and track state, push-to-talk presses with window
|
||||
focus, transmission bursts with frame count and peak level; a warning when two seconds of transmitted
|
||||
audio are silent. The push-to-talk hint says when the window is not focused (the key is read only there).
|
||||
- Core: identities whose private scalar starts with a zero byte are read correctly (≈0.4 % of new identities
|
||||
were rejected after restart).
|
||||
|
||||
## 0.1.1 — 2026-10-24
|
||||
|
||||
- Linux AppImages use the static AppImage runtime (electron-builder toolset `appimage` 1.0.3,
|
||||
|
||||
@@ -17,7 +17,7 @@ UI, evidence path given; **implemented** = code + unit/loopback tests, no live p
|
||||
| Private chat | proven | voice-chat run `15/16-*.png` |
|
||||
| Channel chat | proven error path | server denies guests: TS 2568, permission 224, shown in UI |
|
||||
| Server chat | implemented | not exercised live |
|
||||
| Mic/output device selection | implemented; output routing proven in loopback | `2026-10-24-loopback-browser-pipeline/` |
|
||||
| Mic/output device selection (Settings and right-click menus on the footer buttons) | proven on real hardware (Windows) | `2026-10-24-audio-devices/`: 6 inputs + 6 outputs listed without capture (matches the OS endpoint inventory), choice persists across restart, menus do not toggle mute/deafen; output routing also proven in loopback |
|
||||
| TS6 screenshare viewing (P2P): discovery, join, answer, ICE buffering, stop | proven | `2026-10-24-ts6-stream-view/`: AV1 2560×1440 ~59 fps, 2298 frames, D3D11 decoder |
|
||||
| Realign / reconnect offer renegotiation | implemented | unit tests + loopback (2 offers/2 answers); no realign seen live |
|
||||
| Stream audio | implemented | live stream advertised `audio=0`; loopback 139 inbound audio packets |
|
||||
|
||||
@@ -56,7 +56,10 @@ CI: `.gitea/workflows/ci.yml` (Gitea Actions, контейнеры на Linux x6
|
||||
используется одна и та же идентичность.
|
||||
3. Клик по каналу — переход (для каналов с паролем откроется поле ввода).
|
||||
4. Голос: «Нажми и говори» (по умолчанию F8 или кнопка в шапке) либо «Открытый микрофон»;
|
||||
кнопки микрофона и звука внизу слева видны серверу.
|
||||
кнопки микрофона и звука внизу слева видны серверу. Правый клик (или Shift+F10) по этим кнопкам
|
||||
открывает выбор устройства ввода/вывода — тот же, что в «Настройки → Звук»; обычный клик по-прежнему
|
||||
выключает микрофон/звук. Клавиша «нажми и говори» срабатывает, только когда окно TeamsPeach активно —
|
||||
об этом напоминает подсказка в шапке канала.
|
||||
5. Трансляции: у стримящего участника появится кнопка «Смотреть». Громкость, отключение звука,
|
||||
полный экран, «Прекратить просмотр» — на панели под видео. В строке статуса — реально
|
||||
согласованный кодек, разрешение и частота кадров.
|
||||
|
||||
+5
-5
@@ -20,6 +20,7 @@ if (profileOverride) {
|
||||
const { RENDERER_DIR, resolveCoreBinary, dataDir, logsDir, prefsFile } = require('./paths');
|
||||
const { CoreProcess } = require('./core-process');
|
||||
const { validateRequest } = require('./ipc-validate');
|
||||
const { permissionCheckAllowed, permissionRequestAllowed } = require('./permissions');
|
||||
const { Prefs } = require('./prefs');
|
||||
|
||||
const APP_SCHEME = 'app';
|
||||
@@ -372,13 +373,12 @@ function registerProtocol() {
|
||||
|
||||
function hardenSession() {
|
||||
const ses = session.defaultSession;
|
||||
// Electron passes origins as "app://teamspeach/"; the policy normalises them (see permissions.js).
|
||||
ses.setPermissionRequestHandler((_wc, permission, callback, details) => {
|
||||
const mediaTypes = details && Array.isArray(details.mediaTypes) ? details.mediaTypes : [];
|
||||
const audioOnly = mediaTypes.length > 0 && mediaTypes.every((t) => t === 'audio');
|
||||
callback(permission === 'media' && audioOnly && isAppUrl(details.requestingUrl));
|
||||
callback(permissionRequestAllowed(permission, details, APP_ORIGIN));
|
||||
});
|
||||
ses.setPermissionCheckHandler((_wc, permission, requestingOrigin) => {
|
||||
return (permission === 'media' || permission === 'speaker-selection') && requestingOrigin === APP_ORIGIN;
|
||||
ses.setPermissionCheckHandler((_wc, permission, requestingOrigin, details) => {
|
||||
return permissionCheckAllowed(permission, requestingOrigin, details, APP_ORIGIN);
|
||||
});
|
||||
ses.setDisplayMediaRequestHandler((_request, callback) => callback({}));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Media permission policy for the app's own origin. Electron reports origins as a URL spec with a
|
||||
* trailing slash ("app://teamspeach/"), so origins are compared after normalisation. Only audio is
|
||||
* ever allowed: microphone capture on request, device enumeration and output selection on check.
|
||||
* Camera, screen capture and every other permission stay denied.
|
||||
*/
|
||||
|
||||
// WHATWG URL reports "null" as the origin of non-special schemes such as app:, so scheme and host are
|
||||
// taken from the URL text directly.
|
||||
const ORIGIN_RE = /^([a-z][a-z0-9+.-]*):\/\/([^/?#\\]*)/i;
|
||||
|
||||
function normalizeOrigin(origin) {
|
||||
if (typeof origin !== 'string') return '';
|
||||
const m = ORIGIN_RE.exec(origin);
|
||||
return m ? `${m[1]}://${m[2]}`.toLowerCase() : '';
|
||||
}
|
||||
|
||||
function isAppOrigin(origin, appOrigin) {
|
||||
return normalizeOrigin(origin) === appOrigin;
|
||||
}
|
||||
|
||||
/** setPermissionCheckHandler: enumerateDevices labels/ids and setSinkId depend on this. */
|
||||
function permissionCheckAllowed(permission, requestingOrigin, details, appOrigin) {
|
||||
if (!isAppOrigin(requestingOrigin, appOrigin)) return false;
|
||||
if (permission === 'media') return Boolean(details) && details.mediaType === 'audio';
|
||||
return permission === 'speaker-selection';
|
||||
}
|
||||
|
||||
/** setPermissionRequestHandler: getUserMedia for audio only, from a page of the app. */
|
||||
function permissionRequestAllowed(permission, details, appOrigin) {
|
||||
if (permission !== 'media' || !details) return false;
|
||||
if (!isAppOrigin(details.requestingUrl, appOrigin)) return false;
|
||||
const types = Array.isArray(details.mediaTypes) ? details.mediaTypes : [];
|
||||
return types.length > 0 && types.every((t) => t === 'audio');
|
||||
}
|
||||
|
||||
module.exports = { normalizeOrigin, permissionCheckAllowed, permissionRequestAllowed };
|
||||
@@ -37,6 +37,7 @@
|
||||
<symbol id="i-palette" viewBox="0 0 24 24"><path d="M12 4a8 8 0 0 0 0 16c1.2 0 1.8-.8 1.8-1.7 0-1.3-1-1.6-1-2.6 0-1 .8-1.7 1.8-1.7H17a3 3 0 0 0 3-3C20 7.3 16.4 4 12 4z"/><circle cx="8" cy="11" r="1"/><circle cx="11" cy="7.8" r="1"/><circle cx="15" cy="8.3" r="1"/></symbol>
|
||||
<symbol id="i-keyboard" viewBox="0 0 24 24"><rect x="3" y="6.5" width="18" height="11" rx="2"/><path d="M7 10h.01M10.5 10h.01M14 10h.01M17 10h.01M8 14h8"/></symbol>
|
||||
<symbol id="i-info" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 11v5.5M12 7.8v.01"/></symbol>
|
||||
<symbol id="i-check" viewBox="0 0 24 24"><path d="M5.5 12.5l4.2 4.2 8.8-9.2"/></symbol>
|
||||
</svg>
|
||||
|
||||
<div id="boot" class="boot" role="status">
|
||||
@@ -286,6 +287,7 @@
|
||||
<button id="mic-test" class="btn btn-ghost btn-small" type="button" aria-pressed="false">Проверить микрофон</button>
|
||||
</div>
|
||||
<label class="field"><span class="field-label">Устройство вывода</span><select id="output-device"></select></label>
|
||||
<p id="device-status" class="hint" role="status"></p>
|
||||
</section>
|
||||
<section class="card" aria-labelledby="card-volume">
|
||||
<h2 id="card-volume" class="card-title">Громкость</h2>
|
||||
|
||||
@@ -11,6 +11,7 @@ import * as voice from './voice.js';
|
||||
import * as settings from './settings.js';
|
||||
import { serverBannerUrl, clearMedia } from './media.js';
|
||||
import * as servers from './servers.js';
|
||||
import { initDeviceMenus } from './device-menu.js';
|
||||
|
||||
let hostBannerKey = null;
|
||||
|
||||
@@ -475,8 +476,11 @@ async function boot() {
|
||||
});
|
||||
chat.initChat();
|
||||
servers.initServers({ savePrefs, connectTo });
|
||||
initDeviceMenus({ openAudioSettings: () => openSettings('audio') });
|
||||
watch.initWatch({ onChange: () => renderTree(), savePrefs });
|
||||
voice.initVoice({
|
||||
savePrefs,
|
||||
onOutputChanged: () => watch.applySink(),
|
||||
onPtt: () => renderSessionHead(),
|
||||
onTransmitChanged: () => {},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// Turns MediaDeviceInfo entries of one kind into select options. DOM-free for unit tests.
|
||||
//
|
||||
// Chromium adds aliases ("default", "communications") next to the physical endpoints and, without media
|
||||
// permission, returns one anonymous entry per kind (empty deviceId and label). Aliases are not offered as
|
||||
// separate choices; the system-default option names the device the alias currently points to.
|
||||
|
||||
const ALIASES = new Set(['default', 'communications']);
|
||||
|
||||
/** Strips Chromium's localized "<Default> - " prefix from the alias label to get the device name. */
|
||||
function aliasTarget(label) {
|
||||
const m = /^[^-]+ - (.+)$/.exec(label || '');
|
||||
return m ? m[1] : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{deviceId:string,label:string}[]} list entries of one kind
|
||||
* @param {string} selected saved deviceId ('' = system default)
|
||||
* @returns {{options:{value:string,label:string}[], physical:number, redacted:boolean}}
|
||||
*/
|
||||
export function buildDeviceOptions(list, selected) {
|
||||
const defaultEntry = list.find((d) => d.deviceId === 'default');
|
||||
const defaultName = aliasTarget(defaultEntry?.label);
|
||||
const options = [{ value: '', label: defaultName ? `Системное по умолчанию (${defaultName})` : 'Системное устройство по умолчанию' }];
|
||||
let physical = 0;
|
||||
for (const d of list) {
|
||||
if (!d.deviceId || ALIASES.has(d.deviceId)) continue;
|
||||
physical += 1;
|
||||
options.push({ value: d.deviceId, label: d.label || `Устройство без названия (${d.deviceId.slice(0, 8)})` });
|
||||
}
|
||||
if (selected && !options.some((o) => o.value === selected)) {
|
||||
options.push({ value: selected, label: 'Выбранное ранее устройство (сейчас не найдено)' });
|
||||
}
|
||||
// Entries exist but none carries an id: the engine withheld the list (no media permission).
|
||||
const redacted = physical === 0 && list.some((d) => !d.deviceId);
|
||||
return { options, physical, redacted };
|
||||
}
|
||||
@@ -124,7 +124,11 @@ export class AudioEngine {
|
||||
}
|
||||
});
|
||||
this.capture = { stream, source, node, sink, label: track ? track.label : '' };
|
||||
this.log('info', `audio: capture started (${track ? track.getSettings().sampleRate : '?'} Hz device)`);
|
||||
// The OS can mute a capture track (privacy switch, exclusive mode); record it for diagnosis.
|
||||
track.addEventListener('mute', () => this.log('warn', 'audio: capture track muted by the system'));
|
||||
track.addEventListener('unmute', () => this.log('info', 'audio: capture track unmuted'));
|
||||
const settings = track ? track.getSettings() : {};
|
||||
this.log('info', `audio: capture started "${track ? track.label : '?'}" ${settings.sampleRate ?? '?'} Hz, ${settings.channelCount ?? '?'} ch, muted=${track ? track.muted : '?'}, ec=${settings.echoCancellation} ns=${settings.noiseSuppression} agc=${settings.autoGainControl}`);
|
||||
return this.capture.label;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
// Context menus on the footer microphone/headphones buttons: pick the input or output device.
|
||||
// Uses the same discovery and selection path as Settings → Звук (voice.deviceChoices / choose*Device).
|
||||
// Opening never toggles mute or deafen; left click on the buttons keeps its own behaviour.
|
||||
import { $, h, icon } from './dom.js';
|
||||
import { S } from './state.js';
|
||||
import * as voice from './voice.js';
|
||||
|
||||
let open = null; // { menu, anchor, cleanup }
|
||||
let hooks = { openAudioSettings: () => {} };
|
||||
|
||||
export function initDeviceMenus(h0) {
|
||||
hooks = { ...hooks, ...h0 };
|
||||
bind($('#btn-mute'), 'input');
|
||||
bind($('#btn-deafen'), 'output');
|
||||
}
|
||||
|
||||
function bind(button, kind) {
|
||||
button.setAttribute('aria-haspopup', 'menu');
|
||||
button.addEventListener('contextmenu', (e) => {
|
||||
e.preventDefault();
|
||||
show(button, kind, { x: e.clientX, y: e.clientY });
|
||||
});
|
||||
button.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey)) {
|
||||
e.preventDefault();
|
||||
show(button, kind, null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function close({ restoreFocus = true } = {}) {
|
||||
if (!open) return;
|
||||
const { menu, anchor, cleanup } = open;
|
||||
open = null;
|
||||
cleanup();
|
||||
menu.remove();
|
||||
anchor.setAttribute('aria-expanded', 'false');
|
||||
if (restoreFocus) anchor.focus();
|
||||
}
|
||||
|
||||
async function show(anchor, kind, point) {
|
||||
close({ restoreFocus: false });
|
||||
const choices = await voice.deviceChoices();
|
||||
if (!choices) return;
|
||||
const data = kind === 'input' ? choices.input : choices.output;
|
||||
const selected = (kind === 'input' ? S.prefs.inputDeviceId : S.prefs.outputDeviceId) || '';
|
||||
const title = kind === 'input' ? 'Микрофон' : 'Устройство вывода';
|
||||
|
||||
const items = data.options.map((o) => {
|
||||
const item = h('button', {
|
||||
class: 'menu-item',
|
||||
type: 'button',
|
||||
role: 'menuitemradio',
|
||||
'aria-checked': String(o.value === selected),
|
||||
tabindex: '-1',
|
||||
}, h('span', { class: 'menu-check', 'aria-hidden': 'true' }, o.value === selected ? icon('check') : null), h('span', { class: 'menu-label', text: o.label }));
|
||||
item.addEventListener('click', async () => {
|
||||
close();
|
||||
if (o.value === selected) return;
|
||||
if (kind === 'input') await voice.chooseInputDevice(o.value);
|
||||
else await voice.chooseOutputDevice(o.value);
|
||||
});
|
||||
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: 'Настройки звука…' }));
|
||||
settingsItem.addEventListener('click', () => {
|
||||
close({ restoreFocus: false });
|
||||
hooks.openAudioSettings();
|
||||
});
|
||||
|
||||
const note = data.redacted || data.physical === 0 ? h('p', { class: 'menu-note', text: data.redacted ? 'Движок скрыл список устройств: доступно только системное устройство.' : kind === 'input' ? 'Микрофоны не найдены.' : 'Устройства вывода не найдены.' }) : null;
|
||||
const menu = h('div', { class: 'device-menu', role: 'menu', 'aria-label': title },
|
||||
h('div', { class: 'menu-title', text: title }),
|
||||
...items,
|
||||
note,
|
||||
h('div', { class: 'menu-sep', role: 'separator' }),
|
||||
settingsItem);
|
||||
document.body.appendChild(menu);
|
||||
anchor.setAttribute('aria-expanded', 'true');
|
||||
|
||||
// Anchor above the button (the footer sits at the bottom), clamped inside the viewport.
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
const mw = menu.offsetWidth;
|
||||
const mh = menu.offsetHeight;
|
||||
const margin = 8;
|
||||
let left = point ? point.x : rect.left;
|
||||
let top = (point ? point.y : rect.top) - mh - 6;
|
||||
if (top < margin) top = Math.min(rect.bottom + 6, window.innerHeight - mh - margin);
|
||||
left = Math.max(margin, Math.min(left, window.innerWidth - mw - margin));
|
||||
top = Math.max(margin, top);
|
||||
menu.style.left = `${Math.round(left)}px`;
|
||||
menu.style.top = `${Math.round(top)}px`;
|
||||
|
||||
const focusables = [...items, settingsItem];
|
||||
const focusAt = (i) => focusables[(i + focusables.length) % focusables.length].focus();
|
||||
const current = Math.max(0, items.findIndex((i) => i.getAttribute('aria-checked') === 'true'));
|
||||
focusAt(current);
|
||||
|
||||
const onKey = (e) => {
|
||||
const i = focusables.indexOf(document.activeElement);
|
||||
if (e.key === 'ArrowDown') { e.preventDefault(); focusAt(i + 1); }
|
||||
else if (e.key === 'ArrowUp') { e.preventDefault(); focusAt(i - 1); }
|
||||
else if (e.key === 'Home') { e.preventDefault(); focusAt(0); }
|
||||
else if (e.key === 'End') { e.preventDefault(); focusAt(focusables.length - 1); }
|
||||
else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close(); }
|
||||
else if (e.key === 'Tab') { close({ restoreFocus: false }); }
|
||||
};
|
||||
const onPointer = (e) => {
|
||||
if (!menu.contains(e.target) && e.target !== anchor) close({ restoreFocus: false });
|
||||
};
|
||||
const onResize = () => close({ restoreFocus: false });
|
||||
menu.addEventListener('keydown', onKey);
|
||||
document.addEventListener('pointerdown', onPointer, true);
|
||||
window.addEventListener('resize', onResize);
|
||||
window.addEventListener('blur', onResize);
|
||||
open = {
|
||||
menu,
|
||||
anchor,
|
||||
cleanup: () => {
|
||||
document.removeEventListener('pointerdown', onPointer, true);
|
||||
window.removeEventListener('resize', onResize);
|
||||
window.removeEventListener('blur', onResize);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { tp, call } from './core.js';
|
||||
import { errorText, keyLabel } from './text.js';
|
||||
import { toast } from './toast.js';
|
||||
import * as voice from './voice.js';
|
||||
import { applySink, watchStats } from './watch.js';
|
||||
import { watchStats } from './watch.js';
|
||||
|
||||
let hooks = { savePrefs: async () => {}, close: () => {}, onProfile: () => {} };
|
||||
|
||||
@@ -101,19 +101,9 @@ export function initSettings(h0) {
|
||||
else setText(status, `Импорт не удался: ${errorText(r.error)}`);
|
||||
});
|
||||
|
||||
$('#input-device').addEventListener('change', async (e) => {
|
||||
await hooks.savePrefs({ inputDeviceId: e.target.value });
|
||||
await voice.restartCapture();
|
||||
});
|
||||
$('#output-device').addEventListener('change', async (e) => {
|
||||
await hooks.savePrefs({ outputDeviceId: e.target.value });
|
||||
try {
|
||||
await voice.setOutputDevice(e.target.value);
|
||||
} catch (err) {
|
||||
toast(`Не удалось выбрать устройство вывода: ${err.message}`, 'error');
|
||||
}
|
||||
applySink();
|
||||
});
|
||||
// Same selection path as the microphone/headphones context menus (voice.js).
|
||||
$('#input-device').addEventListener('change', (e) => voice.chooseInputDevice(e.target.value));
|
||||
$('#output-device').addEventListener('change', (e) => voice.chooseOutputDevice(e.target.value));
|
||||
$('#voice-volume').addEventListener('input', (e) => {
|
||||
const v = Number(e.target.value);
|
||||
voice.setVoiceVolume(v);
|
||||
|
||||
+77
-25
@@ -4,6 +4,7 @@ import { $, setText } from './dom.js';
|
||||
import { S, isConnected, ownChannel } from './state.js';
|
||||
import { tp, log } from './core.js';
|
||||
import { AudioEngine } from './audio/engine.js';
|
||||
import { buildDeviceOptions } from './audio/devices.js';
|
||||
import { toast } from './toast.js';
|
||||
import { keyLabel } from './text.js';
|
||||
|
||||
@@ -11,10 +12,11 @@ export const voiceStats = { framesSent: 0, bursts: 0, framesPlayed: 0, level: 0
|
||||
|
||||
let engine = null;
|
||||
let sending = false;
|
||||
let burst = null;
|
||||
let micTest = false;
|
||||
let meterRaf = 0;
|
||||
let assigningPtt = null;
|
||||
let hooks = { onPtt: () => {}, onPttAssigned: () => {}, onTransmitChanged: () => {} };
|
||||
let hooks = { onPtt: () => {}, onPttAssigned: () => {}, onTransmitChanged: () => {}, savePrefs: async () => S.prefs, onOutputChanged: () => {} };
|
||||
|
||||
export function initVoice(h0) {
|
||||
hooks = { ...hooks, ...h0 };
|
||||
@@ -29,22 +31,26 @@ export function initVoice(h0) {
|
||||
});
|
||||
window.addEventListener('keydown', onKeyDown, true);
|
||||
window.addEventListener('keyup', onKeyUp, true);
|
||||
window.addEventListener('blur', () => setPtt(false));
|
||||
window.addEventListener('blur', () => {
|
||||
setPtt(false, 'window-blur');
|
||||
hooks.onPtt(false);
|
||||
});
|
||||
window.addEventListener('focus', () => hooks.onPtt(S.ptt));
|
||||
navigator.mediaDevices.addEventListener('devicechange', () => refreshDevices());
|
||||
const btn = $('#btn-ptt');
|
||||
btn.addEventListener('pointerdown', (e) => {
|
||||
if (e.button !== 0) return;
|
||||
btn.setPointerCapture(e.pointerId);
|
||||
setPtt(true);
|
||||
setPtt(true, 'button');
|
||||
});
|
||||
const release = () => setPtt(false);
|
||||
const release = () => setPtt(false, 'button');
|
||||
btn.addEventListener('pointerup', release);
|
||||
btn.addEventListener('pointercancel', release);
|
||||
btn.addEventListener('lostpointercapture', release);
|
||||
btn.addEventListener('keydown', (e) => {
|
||||
if ((e.key === ' ' || e.key === 'Enter') && !e.repeat) {
|
||||
e.preventDefault();
|
||||
setPtt(true);
|
||||
setPtt(true, 'button');
|
||||
}
|
||||
});
|
||||
btn.addEventListener('keyup', (e) => {
|
||||
@@ -80,6 +86,8 @@ export function shouldTransmit() {
|
||||
&& channelCanTransmit();
|
||||
}
|
||||
|
||||
const SILENCE = 0.0005; // about -66 dBFS
|
||||
|
||||
function onFrame(pcm, rms, peak) {
|
||||
voiceStats.level = peak;
|
||||
if (micTest && !meterRaf) meterRaf = requestAnimationFrame(drawMeter);
|
||||
@@ -89,11 +97,23 @@ function onFrame(pcm, rms, peak) {
|
||||
if (!sending) {
|
||||
sending = true;
|
||||
voiceStats.bursts += 1;
|
||||
burst = { frames: 0, peakMax: 0, warned: false, mode: S.prefs.transmitMode };
|
||||
log('info', `voice: burst start mode=${burst.mode} focused=${document.hasFocus()} capture=${engine.capturing}`);
|
||||
hooks.onTransmitChanged();
|
||||
}
|
||||
burst.frames += 1;
|
||||
if (peak > burst.peakMax) burst.peakMax = peak;
|
||||
// Two seconds of near-digital silence usually means the wrong input device or a muted interface channel.
|
||||
if (burst.frames === 100 && burst.peakMax < SILENCE && !burst.warned) {
|
||||
burst.warned = true;
|
||||
log('warn', 'voice: transmitting silence for 2 s (peak below -66 dBFS)');
|
||||
toast('Микрофон передаёт тишину. Проверьте устройство и уровень в «Настройки → Звук» («Проверить микрофон»).', 'error');
|
||||
}
|
||||
} else if (sending) {
|
||||
tp.endAudio();
|
||||
sending = false;
|
||||
log('info', `voice: burst end frames=${burst.frames} peak=${burst.peakMax > 0 ? (20 * Math.log10(burst.peakMax)).toFixed(1) : '-inf'} dBFS`);
|
||||
burst = null;
|
||||
hooks.onTransmitChanged();
|
||||
}
|
||||
}
|
||||
@@ -150,8 +170,23 @@ export function setVoiceVolume(pct) {
|
||||
engine.setVoiceVolume(pct);
|
||||
}
|
||||
|
||||
export async function setOutputDevice(id) {
|
||||
await engine.setOutputDevice(id);
|
||||
/** Saved input device for capture; used by Settings and by the microphone context menu. */
|
||||
export async function chooseInputDevice(deviceId) {
|
||||
await hooks.savePrefs({ inputDeviceId: deviceId });
|
||||
await restartCapture();
|
||||
await refreshDevices();
|
||||
}
|
||||
|
||||
/** Saved output device for voice and stream audio; used by Settings and by the headphones menu. */
|
||||
export async function chooseOutputDevice(deviceId) {
|
||||
await hooks.savePrefs({ outputDeviceId: deviceId });
|
||||
try {
|
||||
await engine.setOutputDevice(deviceId);
|
||||
} catch (err) {
|
||||
toast(`Не удалось выбрать устройство вывода: ${err.message}`, 'error');
|
||||
}
|
||||
hooks.onOutputChanged();
|
||||
await refreshDevices();
|
||||
}
|
||||
|
||||
export function playbackStats() {
|
||||
@@ -160,26 +195,40 @@ export function playbackStats() {
|
||||
|
||||
// ---------- devices ----------
|
||||
|
||||
export async function refreshDevices() {
|
||||
let devices = [];
|
||||
try {
|
||||
devices = await navigator.mediaDevices.enumerateDevices();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
fillSelect($('#input-device'), devices.filter((d) => d.kind === 'audioinput'), S.prefs.inputDeviceId, 'Микрофон');
|
||||
fillSelect($('#output-device'), devices.filter((d) => d.kind === 'audiooutput'), S.prefs.outputDeviceId, 'Динамики');
|
||||
let lastChoices = null;
|
||||
|
||||
/** Last enumerated choices ({input, output} from buildDeviceOptions), shared by Settings and the menus. */
|
||||
export async function deviceChoices() {
|
||||
await refreshDevices();
|
||||
return lastChoices;
|
||||
}
|
||||
|
||||
function fillSelect(select, list, selected, fallback) {
|
||||
const options = [{ value: '', label: 'Системное устройство по умолчанию' }];
|
||||
let n = 0;
|
||||
for (const d of list) {
|
||||
if (d.deviceId === 'default' || d.deviceId === 'communications' || d.deviceId === '') continue;
|
||||
n += 1;
|
||||
options.push({ value: d.deviceId, label: d.label || `${fallback} ${n}` });
|
||||
export async function refreshDevices() {
|
||||
const status = $('#device-status');
|
||||
let devices;
|
||||
try {
|
||||
devices = await navigator.mediaDevices.enumerateDevices();
|
||||
} catch (err) {
|
||||
setText(status, `Не удалось получить список устройств: ${err.name}: ${err.message}`);
|
||||
log('warn', `enumerateDevices failed: ${err.name}`);
|
||||
return;
|
||||
}
|
||||
if (selected && !options.some((o) => o.value === selected)) options.push({ value: selected, label: 'Выбранное устройство (не подключено)' });
|
||||
const input = buildDeviceOptions(devices.filter((d) => d.kind === 'audioinput'), S.prefs.inputDeviceId);
|
||||
const output = buildDeviceOptions(devices.filter((d) => d.kind === 'audiooutput'), S.prefs.outputDeviceId);
|
||||
fillSelect($('#input-device'), input.options, S.prefs.inputDeviceId);
|
||||
fillSelect($('#output-device'), output.options, S.prefs.outputDeviceId);
|
||||
let text;
|
||||
if (input.redacted || output.redacted) text = 'Движок скрыл список устройств (нет разрешения на доступ к звуковым устройствам). Доступно только системное устройство по умолчанию.';
|
||||
else if (input.physical === 0 && output.physical === 0) text = 'Звуковые устройства не найдены.';
|
||||
else if (input.physical === 0) text = `Микрофоны не найдены. Устройств вывода: ${output.physical}.`;
|
||||
else if (output.physical === 0) text = `Микрофонов: ${input.physical}. Устройства вывода не найдены.`;
|
||||
else text = `Найдено микрофонов: ${input.physical}, устройств вывода: ${output.physical}.`;
|
||||
setText(status, text);
|
||||
lastChoices = { input, output, status: text };
|
||||
log('info', `devices: inputs=${input.physical} outputs=${output.physical} redacted=${input.redacted || output.redacted}`);
|
||||
}
|
||||
|
||||
function fillSelect(select, options, selected) {
|
||||
select.replaceChildren(...options.map((o) => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = o.value;
|
||||
@@ -214,12 +263,13 @@ function onKeyUp(e) {
|
||||
if (e.code === S.prefs?.pttCode) setPtt(false);
|
||||
}
|
||||
|
||||
export function setPtt(down) {
|
||||
export function setPtt(down, source = 'key') {
|
||||
if (S.ptt === down) return;
|
||||
S.ptt = down;
|
||||
const btn = $('#btn-ptt');
|
||||
btn.setAttribute('aria-pressed', String(down));
|
||||
setText(btn, down ? 'Говорите…' : 'Удерживайте, чтобы говорить');
|
||||
if (S.prefs?.transmitMode === 'ptt') log('info', `voice: ptt ${down ? 'down' : 'up'} source=${source} focused=${document.hasFocus()}`);
|
||||
hooks.onPtt(down);
|
||||
}
|
||||
|
||||
@@ -233,6 +283,8 @@ export function capturePttKey() {
|
||||
export function transmitHint() {
|
||||
if (!S.prefs) return '';
|
||||
if (S.prefs.transmitMode === 'open') return 'Открытый микрофон';
|
||||
// The key is read only from this window: say so whenever another window has the focus.
|
||||
if (!document.hasFocus()) return `Окно неактивно — ${keyLabel(S.prefs.pttCode)} не сработает`;
|
||||
return `Клавиша: ${keyLabel(S.prefs.pttCode)}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -690,3 +690,29 @@ input[type="checkbox"], input[type="radio"] { accent-color: var(--accent); width
|
||||
.card-details[open] > summary { margin-bottom: 10px; }
|
||||
.card-details .diag-list { margin-bottom: 12px; }
|
||||
.details-title { font-size: 13px; font-weight: 600; color: var(--text-2); margin: 10px 0 6px; }
|
||||
|
||||
/* ---------- device context menus (footer microphone / headphones) ---------- */
|
||||
.device-menu {
|
||||
position: fixed;
|
||||
z-index: 20;
|
||||
min-width: 240px;
|
||||
max-width: min(420px, calc(100vw - 16px));
|
||||
max-height: calc(100vh - 16px);
|
||||
overflow-y: auto;
|
||||
padding: 6px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--surface);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.menu-title { padding: 6px 10px 6px; font-size: 12px; font-weight: 600; color: var(--text-3); }
|
||||
.menu-item { width: 100%; display: flex; align-items: center; gap: 8px; min-height: 32px; padding: 5px 10px 5px 6px; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text); font: inherit; font-size: 13px; text-align: left; cursor: pointer; }
|
||||
.menu-item:hover, .menu-item:focus-visible { background: var(--hover); outline: none; }
|
||||
.menu-item:focus-visible { box-shadow: inset 0 0 0 2px var(--focus); }
|
||||
.menu-item[aria-checked="true"] { font-weight: 600; }
|
||||
.menu-item-secondary { color: var(--text-2); }
|
||||
.menu-check { width: 18px; flex: none; display: inline-grid; place-items: center; color: var(--accent); }
|
||||
.menu-check .icon { width: 16px; height: 16px; }
|
||||
.menu-label { flex: 1; min-width: 0; overflow-wrap: anywhere; }
|
||||
.menu-note { margin: 4px 10px; font-size: 12px; color: var(--text-3); }
|
||||
.menu-sep { height: 1px; margin: 5px 4px; background: var(--border); }
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 50 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 60 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 61 KiB |
@@ -0,0 +1,80 @@
|
||||
{
|
||||
"steps": [
|
||||
{
|
||||
"name": "mic right-click",
|
||||
"menu": true,
|
||||
"inputMuted": false,
|
||||
"items": [
|
||||
{
|
||||
"label": "Системное по умолчанию (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": [
|
||||
"Системное по умолчанию (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": "after restart",
|
||||
"checkedIn": "Headset Microphone (Oculus Virtual Audio Device)",
|
||||
"checkedOut": "Realtek Digital Output (Realtek(R) Audio)",
|
||||
"persisted": true
|
||||
}
|
||||
],
|
||||
"console": [],
|
||||
"ok": true
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"steps": [
|
||||
{
|
||||
"name": "listed without capture",
|
||||
"inputs": 6,
|
||||
"outputs": 6,
|
||||
"inputLabels": [
|
||||
"Системное по умолчанию (Mic/Line/Inst 1-2 (MiniFuse 4))",
|
||||
"Loopback Mix Left/Right (MiniFuse 4)",
|
||||
"Headset Microphone (Oculus Virtual Audio Device)",
|
||||
"Line 3-4 (MiniFuse 4)",
|
||||
"Микрофон (DroidCam Audio)",
|
||||
"Микрофон (Virtual Desktop Audio)",
|
||||
"Mic/Line/Inst 1-2 (MiniFuse 4)"
|
||||
],
|
||||
"outputLabels": [
|
||||
"Системное по умолчанию (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)"
|
||||
],
|
||||
"status": "Найдено микрофонов: 6, устройств вывода: 6.",
|
||||
"conn": "disconnected",
|
||||
"framesSent": 0
|
||||
},
|
||||
{
|
||||
"name": "selected",
|
||||
"inputChoice": "Headset Microphone (Oculus Virtual Audio Device)",
|
||||
"outputChoice": "Realtek Digital Output (Realtek(R) Audio)",
|
||||
"toasts": [],
|
||||
"framesSent": 0
|
||||
},
|
||||
{
|
||||
"name": "after restart",
|
||||
"inputNow": "Headset Microphone (Oculus Virtual Audio Device)",
|
||||
"outputNow": "Realtek Digital Output (Realtek(R) Audio)",
|
||||
"persisted": true,
|
||||
"toasts": [],
|
||||
"conn": "disconnected"
|
||||
}
|
||||
],
|
||||
"console": [],
|
||||
"ok": true
|
||||
}
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "teamspeach",
|
||||
"version": "0.1.1",
|
||||
"version": "0.1.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "teamspeach",
|
||||
"version": "0.1.1",
|
||||
"version": "0.1.2",
|
||||
"license": "UNLICENSED",
|
||||
"devDependencies": {
|
||||
"electron": "44.9.3",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "teamspeach",
|
||||
"productName": "TeamsPeach",
|
||||
"version": "0.1.1",
|
||||
"version": "0.1.2",
|
||||
"description": "Desktop TeamSpeak 6 client: voice, chat and TS6 screenshare viewing",
|
||||
"main": "app/main/main.js",
|
||||
"private": true,
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
// Real-device context menus (NO fake-media flags, no server, no capture): right-click and Shift+F10 on the
|
||||
// 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 { 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'));
|
||||
const exe = opt('exe');
|
||||
mkdirSync(out, { recursive: true });
|
||||
const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-menu-'));
|
||||
const result = { steps: [], console: [] };
|
||||
const step = (name, data = {}) => {
|
||||
result.steps.push({ name, ...data });
|
||||
console.log(`[menu] ${name}`, JSON.stringify(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 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}`));
|
||||
await page.setViewportSize({ width: 1280, height: 800 }).catch(() => {});
|
||||
return { app, page };
|
||||
}
|
||||
const state = (page) => page.evaluate(() => ({
|
||||
audio: window.teamspeachDiagnostics.snapshot().audio,
|
||||
menu: Boolean(document.querySelector('.device-menu')),
|
||||
items: Array.from(document.querySelectorAll('.device-menu [role="menuitemradio"]')).map((i) => ({ label: i.textContent, checked: i.getAttribute('aria-checked') })),
|
||||
focused: document.activeElement?.id || document.activeElement?.className || '',
|
||||
inside: (() => { const m = document.querySelector('.device-menu'); if (!m) return null; const r = m.getBoundingClientRect(); return r.left >= 0 && r.top >= 0 && r.right <= innerWidth && r.bottom <= innerHeight; })(),
|
||||
}));
|
||||
|
||||
let app;
|
||||
let page;
|
||||
let failed = null;
|
||||
try {
|
||||
({ app, page } = await launch('run1'));
|
||||
await page.waitForSelector('#view-onboarding', { state: 'visible', timeout: 20000 });
|
||||
await page.fill('#onboarding-nick', 'MenuSmoke');
|
||||
await page.click('#onboarding-submit');
|
||||
await page.waitForSelector('#view-app', { state: 'visible', timeout: 20000 });
|
||||
|
||||
await page.click('#btn-mute', { button: 'right' });
|
||||
await page.waitForSelector('.device-menu');
|
||||
let s = await state(page);
|
||||
step('mic right-click', { menu: s.menu, inputMuted: s.audio.input_muted, items: s.items, insideViewport: s.inside, focused: s.focused });
|
||||
if (s.audio.input_muted) throw new Error('right-click toggled mute');
|
||||
await page.screenshot({ path: path.join(out, '62-mic-device-menu.png') });
|
||||
const pick = s.items[Math.min(2, s.items.length - 1)].label;
|
||||
await page.click(`.device-menu [role="menuitemradio"]:has-text("${pick.replace(/"/g, '\\"')}")`);
|
||||
await page.waitForTimeout(700);
|
||||
await page.click('#btn-settings');
|
||||
await page.click('#settings-nav .nav-item[data-panel="audio"]');
|
||||
const settingsInput = await page.$eval('#input-device', (el) => el.selectedOptions[0].textContent);
|
||||
step('menu choice reflected in settings', { pick, settingsInput, same: pick === settingsInput });
|
||||
if (pick !== settingsInput) throw new Error('settings not updated from menu');
|
||||
await page.click('#settings-back');
|
||||
|
||||
// Keyboard: Shift+F10 on the headphones button, arrows, Escape restores focus; deafen untouched.
|
||||
await page.focus('#btn-deafen');
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await page.waitForSelector('.device-menu');
|
||||
await page.keyboard.press('ArrowDown');
|
||||
s = await state(page);
|
||||
step('headphones Shift+F10', { menu: s.menu, outputMuted: s.audio.output_muted, items: s.items.map((i) => i.label), insideViewport: s.inside });
|
||||
await page.screenshot({ path: path.join(out, '63-output-device-menu.png') });
|
||||
await page.keyboard.press('Escape');
|
||||
s = await state(page);
|
||||
step('escape', { menuClosed: !s.menu, focusRestored: s.focused === 'btn-deafen', outputMuted: s.audio.output_muted });
|
||||
if (s.menu || s.focused !== 'btn-deafen' || s.audio.output_muted) throw new Error('escape/focus/deafen behaviour wrong');
|
||||
await page.click('#btn-deafen', { button: 'right' });
|
||||
await page.waitForSelector('.device-menu');
|
||||
const outPick = (await state(page)).items[Math.min(2, (await state(page)).items.length - 1)].label;
|
||||
await page.keyboard.press('Escape');
|
||||
await page.click('#btn-deafen', { button: 'right' });
|
||||
await page.click(`.device-menu [role="menuitemradio"]:has-text("${outPick.replace(/"/g, '\\"')}")`);
|
||||
await page.waitForTimeout(700);
|
||||
// Left click still toggles as before.
|
||||
await page.click('#btn-mute');
|
||||
s = await state(page);
|
||||
step('left click still toggles mute', { inputMuted: s.audio.input_muted });
|
||||
await page.click('#btn-mute');
|
||||
await app.close();
|
||||
|
||||
({ app, page } = await launch('run2'));
|
||||
await page.waitForSelector('#view-app', { state: 'visible', timeout: 20000 });
|
||||
await page.click('#btn-mute', { button: 'right' });
|
||||
await page.waitForSelector('.device-menu');
|
||||
const checkedIn = (await state(page)).items.find((i) => i.checked === 'true')?.label;
|
||||
await page.keyboard.press('Escape');
|
||||
await page.click('#btn-deafen', { button: 'right' });
|
||||
await page.waitForSelector('.device-menu');
|
||||
const checkedOut = (await state(page)).items.find((i) => i.checked === 'true')?.label;
|
||||
step('after restart', { checkedIn, checkedOut, persisted: checkedIn === pick && checkedOut === outPick });
|
||||
if (checkedIn !== pick || checkedOut !== outPick) throw new Error('menu choices not persisted');
|
||||
} catch (err) {
|
||||
failed = err;
|
||||
step('FAILED', { error: String(err.stack || err) });
|
||||
if (page) await page.screenshot({ path: path.join(out, 'fail.png') }).catch(() => {});
|
||||
} finally {
|
||||
if (app) await app.close().catch(() => {});
|
||||
rmSync(profile, { recursive: true, force: true });
|
||||
}
|
||||
result.ok = !failed;
|
||||
writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2));
|
||||
console.log(`[menu] ${result.ok ? 'OK' : 'FAILED'} → ${out}`);
|
||||
process.exit(result.ok ? 0 : 1);
|
||||
@@ -0,0 +1,105 @@
|
||||
// Real audio devices in Settings → Звук (NO fake-media flags): lists what the engine exposes without any
|
||||
// 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 { 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'));
|
||||
const exe = opt('exe');
|
||||
mkdirSync(out, { recursive: true });
|
||||
const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-devices-'));
|
||||
const result = { steps: [], console: [] };
|
||||
const step = (name, data = {}) => {
|
||||
result.steps.push({ name, ...data });
|
||||
console.log(`[devices] ${name}`, JSON.stringify(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 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}`));
|
||||
await page.setViewportSize({ width: 1280, height: 800 }).catch(() => {});
|
||||
return { app, page };
|
||||
}
|
||||
|
||||
const readSelects = (page) => page.evaluate(() => {
|
||||
const read = (id) => Array.from(document.querySelector(id).options).map((o) => ({ value: o.value ? 'id' : '', label: o.textContent }));
|
||||
return {
|
||||
inputs: read('#input-device'),
|
||||
outputs: read('#output-device'),
|
||||
inputValueIsDevice: Boolean(document.querySelector('#input-device').value),
|
||||
outputValueIsDevice: Boolean(document.querySelector('#output-device').value),
|
||||
status: document.querySelector('#device-status').textContent,
|
||||
capturing: window.teamspeachDiagnostics.snapshot().voice.framesSent,
|
||||
conn: window.teamspeachDiagnostics.snapshot().conn,
|
||||
toasts: Array.from(document.querySelectorAll('.toast[data-kind="error"]')).map((t) => t.textContent),
|
||||
};
|
||||
});
|
||||
|
||||
let app;
|
||||
let page;
|
||||
let failed = null;
|
||||
try {
|
||||
({ app, page } = await launch('run1'));
|
||||
await page.waitForSelector('#view-onboarding', { state: 'visible', timeout: 20000 });
|
||||
await page.fill('#onboarding-nick', 'DeviceSmoke');
|
||||
await page.click('#onboarding-submit');
|
||||
await page.waitForSelector('#view-app', { state: 'visible', timeout: 20000 });
|
||||
await page.click('#btn-settings');
|
||||
await page.click('#settings-nav .nav-item[data-panel="audio"]');
|
||||
await page.waitForFunction(() => document.querySelector('#device-status').textContent.length > 0, null, { timeout: 10000 });
|
||||
let s = await readSelects(page);
|
||||
step('listed without capture', { inputs: s.inputs.length - 1, outputs: s.outputs.length - 1, inputLabels: s.inputs.map((o) => o.label), outputLabels: s.outputs.map((o) => o.label), status: s.status, conn: s.conn, framesSent: s.capturing });
|
||||
await page.screenshot({ path: path.join(out, '60-audio-devices-listed.png') });
|
||||
if (s.inputs.length < 2 || s.outputs.length < 2) throw new Error('no physical devices listed');
|
||||
|
||||
// Choose the second physical device of each kind (first non-default entry after index 0).
|
||||
const inputChoice = await page.$eval('#input-device', (el) => el.options[Math.min(2, el.options.length - 1)].textContent);
|
||||
const outputChoice = await page.$eval('#output-device', (el) => el.options[Math.min(2, el.options.length - 1)].textContent);
|
||||
await page.selectOption('#input-device', { label: inputChoice });
|
||||
await page.selectOption('#output-device', { label: outputChoice });
|
||||
await page.waitForTimeout(1000);
|
||||
s = await readSelects(page);
|
||||
step('selected', { inputChoice, outputChoice, toasts: s.toasts, framesSent: s.capturing });
|
||||
await app.close();
|
||||
|
||||
({ app, page } = await launch('run2'));
|
||||
await page.waitForSelector('#view-app', { state: 'visible', timeout: 20000 });
|
||||
await page.click('#btn-settings');
|
||||
await page.click('#settings-nav .nav-item[data-panel="audio"]');
|
||||
await page.waitForFunction(() => document.querySelector('#device-status').textContent.length > 0, null, { timeout: 10000 });
|
||||
s = await readSelects(page);
|
||||
const inputNow = await page.$eval('#input-device', (el) => el.selectedOptions[0].textContent);
|
||||
const outputNow = await page.$eval('#output-device', (el) => el.selectedOptions[0].textContent);
|
||||
step('after restart', { inputNow, outputNow, persisted: inputNow === inputChoice && outputNow === outputChoice, toasts: s.toasts, conn: s.conn });
|
||||
await page.screenshot({ path: path.join(out, '61-audio-devices-after-restart.png') });
|
||||
if (inputNow !== inputChoice || outputNow !== outputChoice) throw new Error('selection not persisted');
|
||||
// Leave the profile as found: back to system defaults (profile is deleted anyway).
|
||||
await page.selectOption('#input-device', '');
|
||||
await page.selectOption('#output-device', '');
|
||||
} catch (err) {
|
||||
failed = err;
|
||||
step('FAILED', { error: String(err.stack || err) });
|
||||
} finally {
|
||||
if (app) await app.close().catch(() => {});
|
||||
rmSync(profile, { recursive: true, force: true });
|
||||
}
|
||||
result.ok = !failed;
|
||||
writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2));
|
||||
console.log(`[devices] ${result.ok ? 'OK' : 'FAILED'} → ${out}`);
|
||||
process.exit(result.ok ? 0 : 1);
|
||||
@@ -0,0 +1,36 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { buildDeviceOptions } from '../app/renderer/js/audio/devices.js';
|
||||
|
||||
test('without media permission Chromium returns one anonymous entry: reported as redacted, not as a device', () => {
|
||||
const r = buildDeviceOptions([{ deviceId: '', label: '' }], '');
|
||||
assert.equal(r.redacted, true);
|
||||
assert.equal(r.physical, 0);
|
||||
assert.deepEqual(r.options.map((o) => o.value), ['']);
|
||||
});
|
||||
|
||||
test('aliases are folded into the default option, physical endpoints listed with real ids', () => {
|
||||
const list = [
|
||||
{ deviceId: 'default', label: 'По умолчанию - Mic/Line/Inst 1-2 (MiniFuse 4)' },
|
||||
{ deviceId: 'communications', label: 'Связь - Mic/Line/Inst 1-2 (MiniFuse 4)' },
|
||||
{ deviceId: 'a1b2c3d4e5', label: 'Mic/Line/Inst 1-2 (MiniFuse 4)' },
|
||||
{ deviceId: 'f6g7h8i9j0', label: 'Микрофон (DroidCam Audio)' },
|
||||
];
|
||||
const r = buildDeviceOptions(list, '');
|
||||
assert.equal(r.redacted, false);
|
||||
assert.equal(r.physical, 2);
|
||||
assert.equal(r.options[0].label, 'Системное по умолчанию (Mic/Line/Inst 1-2 (MiniFuse 4))');
|
||||
assert.deepEqual(r.options.slice(1).map((o) => o.value), ['a1b2c3d4e5', 'f6g7h8i9j0']);
|
||||
});
|
||||
|
||||
test('an unnamed physical device keeps its real id and an honest label', () => {
|
||||
const r = buildDeviceOptions([{ deviceId: 'zz99yy88xx77', label: '' }], '');
|
||||
assert.equal(r.options[1].value, 'zz99yy88xx77');
|
||||
assert.equal(r.options[1].label, 'Устройство без названия (zz99yy88)');
|
||||
});
|
||||
|
||||
test('a saved device that is currently absent stays selectable and is labelled as missing', () => {
|
||||
const r = buildDeviceOptions([{ deviceId: 'a1', label: 'A' }], 'gone-device');
|
||||
assert.equal(r.options.at(-1).value, 'gone-device');
|
||||
assert.match(r.options.at(-1).label, /не найдено/);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
'use strict';
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { normalizeOrigin, permissionCheckAllowed, permissionRequestAllowed } = require('../app/main/permissions');
|
||||
|
||||
const APP = 'app://teamspeach';
|
||||
|
||||
test('origins are compared after normalisation (Electron reports "app://teamspeach/")', () => {
|
||||
assert.equal(normalizeOrigin('app://teamspeach/'), APP);
|
||||
assert.equal(normalizeOrigin('app://teamspeach'), APP);
|
||||
assert.equal(normalizeOrigin('app://teamspeach/index.html'), APP);
|
||||
assert.equal(normalizeOrigin('not a url'), '');
|
||||
assert.equal(normalizeOrigin(undefined), '');
|
||||
});
|
||||
|
||||
test('permission checks: audio devices and output selection for the app only', () => {
|
||||
// Exactly the arguments observed from Electron 44 on Windows (requestingOrigin with trailing slash).
|
||||
assert.equal(permissionCheckAllowed('media', 'app://teamspeach/', { mediaType: 'audio', securityOrigin: 'app://teamspeach/' }, APP), true);
|
||||
assert.equal(permissionCheckAllowed('speaker-selection', 'app://teamspeach/', {}, APP), true);
|
||||
assert.equal(permissionCheckAllowed('media', 'app://teamspeach/', { mediaType: 'video' }, APP), false, 'camera stays hidden');
|
||||
assert.equal(permissionCheckAllowed('media', 'app://teamspeach/', { mediaType: 'unknown' }, APP), false);
|
||||
assert.equal(permissionCheckAllowed('media', 'app://teamspeach/', undefined, APP), false);
|
||||
assert.equal(permissionCheckAllowed('media', 'https://evil.example/', { mediaType: 'audio' }, APP), false);
|
||||
assert.equal(permissionCheckAllowed('media', 'app://other/', { mediaType: 'audio' }, APP), false);
|
||||
assert.equal(permissionCheckAllowed('notifications', 'app://teamspeach/', {}, APP), false);
|
||||
assert.equal(permissionCheckAllowed('clipboard-read', 'app://teamspeach/', {}, APP), false);
|
||||
});
|
||||
|
||||
test('permission requests: microphone only, from an app page', () => {
|
||||
assert.equal(permissionRequestAllowed('media', { requestingUrl: 'app://teamspeach/index.html', mediaTypes: ['audio'] }, APP), true);
|
||||
assert.equal(permissionRequestAllowed('media', { requestingUrl: 'app://teamspeach/index.html', mediaTypes: ['audio', 'video'] }, APP), false);
|
||||
assert.equal(permissionRequestAllowed('media', { requestingUrl: 'app://teamspeach/index.html', mediaTypes: [] }, APP), false);
|
||||
assert.equal(permissionRequestAllowed('media', { requestingUrl: 'https://evil.example/', mediaTypes: ['audio'] }, APP), false);
|
||||
assert.equal(permissionRequestAllowed('display-capture', { requestingUrl: 'app://teamspeach/index.html' }, APP), false);
|
||||
assert.equal(permissionRequestAllowed('speaker-selection', { requestingUrl: 'app://teamspeach/index.html' }, APP), false);
|
||||
});
|
||||
Reference in new issue
Block a user