From 9702c671e8b84842583f309a3bb5885d92b7ff39 Mon Sep 17 00:00:00 2001 From: Moepchi Date: Sun, 6 Sep 2026 00:20:33 +0200 Subject: [PATCH] Fix 8 correctness bugs found in code review of PR #4 - Connection log only ever rendered the single latest entry (log.slice(-1) -> log.slice(-50)), and appendLog grew log[] unbounded - Mic stayed off after switching back to a parked multi-join tab (added ParkedSessionState.micWasOn, restore mic on switch-back) - Packet-loss heuristic guessed fraction-vs-percent by magnitude, which can't disambiguate; now branches on actual server type (GTS vs TS3) - serverGroups/channelGroups/permissionCatalog/banList/fileBrowser were page-global caches never invalidated on multi-join tab switch, so a newly active tab could show another server's stale data - ServerQuery clients were filtered from the client list but still counted in the online-total fallback; total now matches the list - gateway disconnect() resolved before the connector child process actually exited, allowing two connector processes to run briefly on a fast reconnect; now waits for exit (with a hard-kill fallback) - switching a parked multi-join tab back in replayed a spurious whisper-target log entry and resent setWhisperTargets even when nothing changed, because the diff was against the wrong tab's ref - double-click-to-join channel detection used module-level state, so a click in one multi-join tab could pair with a click in another tab's tree as a false double-click; now keyed per session Note: could not verify with a full cargo build - the PR's own 'Update tsclientlib' commit (cd6928b) points at a tsclientlib submodule commit that isn't pushed to any reachable branch (not even the PR author's own fork), so nobody can currently build this PR end-to-end. That is unrelated to these fixes. --- connector/src/main.rs | 23 +++++++----- gateway/src/ts3/connection.ts | 20 +++++++++-- web/src/App.tsx | 67 ++++++++++++++++++++++++++++++----- web/src/connectionSessions.ts | 3 ++ 4 files changed, 93 insertions(+), 20 deletions(-) diff --git a/connector/src/main.rs b/connector/src/main.rs index 9ba903e..d7f8849 100644 --- a/connector/src/main.rs +++ b/connector/src/main.rs @@ -569,9 +569,8 @@ fn snapshot(con: &data::Connection) -> Event { }) .collect::>(); // Bookkeeping includes ServerQuery clients (`ClientType::Query`); hide them - // from the channel tree / client lists. Online counters still use the - // server-reported total (often includes Query) via `client_count` below. - let all_clients_count = con.clients.len() as u16; + // from the channel tree / client lists, and from the online-count fallback + // below too, so the number shown never counts a client the list doesn't. let clients = con .clients .values() @@ -606,12 +605,13 @@ fn snapshot(con: &data::Connection) -> Event { .collect::>(); // Prefer server-reported counters (GTS/TS `virtualserver_*` via notifyserverupdated) - // but never under-report vs. the full bookkeeping client set including Query - // (stale optional_data after joins would otherwise freeze the InfoPanel left number). + // but never under-report vs. the visible (non-Query) client set (stale + // optional_data after joins would otherwise freeze the InfoPanel left number). let opt = con.server.optional_data.as_ref(); let visible_channels = channels.len() as u64; + let visible_clients_count = clients.len() as u16; let server_clients_online = - opt.map(|d| d.client_count.max(all_clients_count)).unwrap_or(all_clients_count); + opt.map(|d| d.client_count.max(visible_clients_count)).unwrap_or(visible_clients_count); let server_channels_online = opt.map(|d| d.channel_count.max(visible_channels)).unwrap_or(visible_channels); @@ -2120,10 +2120,15 @@ async fn run(args: Args) -> Result<()> { } } if pending_server_conninfo { - if let Some(data) = &con.get_state()?.server.connection_data { - // TeaSpeak/TS may report packet loss as a fraction (0–1) or percent. + let state = con.get_state()?; + // GreenTeaSpeak reports packet loss already as a percent; classic + // TeamSpeak3/TeaSpeak report it as a fraction (0-1). A value's magnitude + // alone can't disambiguate a healthy GTS server (e.g. 0.5%) from a bad + // TS3 one (e.g. 0.5 = 50%), so branch on the actual server type instead. + let is_gts = is_greenteaspeak_server_version(&state.server.version); + if let Some(data) = &state.server.connection_data { let loss = data.packetloss_total; - let packet_loss_percent = if loss <= 1.0 { loss * 100.0 } else { loss }; + let packet_loss_percent = if is_gts { loss } else { loss * 100.0 }; emit(&Event::ServerConnectionInfo { ping_ms: data.ping.as_seconds_f64() * 1000.0, connected_secs: data.connected_time_total.whole_seconds(), diff --git a/gateway/src/ts3/connection.ts b/gateway/src/ts3/connection.ts index b6c7d65..2886595 100644 --- a/gateway/src/ts3/connection.ts +++ b/gateway/src/ts3/connection.ts @@ -789,9 +789,25 @@ export class Ts3Connection { async disconnect(message = ""): Promise { if (this.child && !this.child.killed) { + const child = this.child; const sanitized = message.replace(/[\r\n]+/g, " ").trim(); - this.child.stdin.write(`disconnect ${sanitized}\n`); - this.child.stdin.end(); + child.stdin.write(`disconnect ${sanitized}\n`); + child.stdin.end(); + // Wait for the connector process to actually exit before returning, so a + // caller that immediately reconnects (index.ts's "connect" handler) never + // spawns a replacement while this one is still shutting down - two + // connector processes would otherwise briefly hold the same audio/socket + // resources. Fall back to a hard kill if it doesn't exit on its own. + await new Promise((resolve) => { + const timeout = setTimeout(() => { + child.kill(); + resolve(); + }, 3000); + child.once("exit", () => { + clearTimeout(timeout); + resolve(); + }); + }); } this.listeners.clear(); } diff --git a/web/src/App.tsx b/web/src/App.tsx index 86b6322..2b171e6 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -657,8 +657,10 @@ function ServerIcon() { ); } -/** Survives ChannelTree remounts when Select's setState rebuilds the tree. */ -let lastChannelClick: { id: number; at: number } | null = null; +/** Survives ChannelTree remounts when Select's setState rebuilds the tree. + * Keyed per session (multi-join tab) so a click in one tab's tree can never + * be paired with a click in another tab's tree as a false double-click. */ +const lastChannelClickBySession = new Map(); let switchArmedUntil = 0; function ChannelTree({ @@ -670,6 +672,7 @@ function ChannelTree({ serverGroups, groupIconImages, selected, + sessionKey, onSelectItem, onSwitchChannel, onOpenPrivateChat, @@ -685,6 +688,9 @@ function ChannelTree({ serverGroups: GroupEntry[] | null; groupIconImages: Record; selected: SelectedItem | null; + /** Identifies which multi-join tab this tree belongs to, so the manual + * double-click detection below can't pair clicks across two tabs. */ + sessionKey: string; onSelectItem: (item: SelectedItem) => void; onSwitchChannel: (channelId: number) => void; onOpenPrivateChat: (clientId: number, clientName: string) => void; @@ -742,13 +748,13 @@ function ChannelTree({ // click's Select setState remounts this row before the second click. // Spacers are joinable (TS/GTS): visual-only difference. const now = performance.now(); - const prev = lastChannelClick; + const prev = lastChannelClickBySession.get(sessionKey) ?? null; if (prev && prev.id === channel.id && now - prev.at < 450) { - lastChannelClick = null; + lastChannelClickBySession.delete(sessionKey); switchArmedUntil = now + 50; onSwitchChannel(channel.id); } else { - lastChannelClick = { id: channel.id, at: now }; + lastChannelClickBySession.set(sessionKey, { id: channel.id, at: now }); } }} onDoubleClick={() => { @@ -890,6 +896,7 @@ function ChannelTree({ serverGroups={serverGroups} groupIconImages={groupIconImages} selected={selected} + sessionKey={sessionKey} onSelectItem={onSelectItem} onSwitchChannel={onSwitchChannel} onOpenPrivateChat={onOpenPrivateChat} @@ -5193,7 +5200,7 @@ function AppInner() { }; }, []); - const appendLog = (entry: LogEntry) => setLog((prev) => [...prev, entry]); + const appendLog = (entry: LogEntry) => setLog((prev) => [...prev.slice(-(MAX_LOG_ENTRIES - 1)), entry]); const startTreeResize = (e: React.MouseEvent) => { e.preventDefault(); @@ -5276,6 +5283,7 @@ function AppInner() { log, hasConnected: hasConnectedRef.current, previousClients: previousClientsRef.current, + micWasOn: micOn, }); const applyParkedToUi = (parked: ParkedSessionState) => { @@ -5309,6 +5317,14 @@ function AppInner() { setLog(parked.log); hasConnectedRef.current = parked.hasConnected; previousClientsRef.current = parked.previousClients; + // Sync the "previous" whisper-target baseline to the tab we're restoring, + // so the whisper-target effect (keyed on whisperChannelIds/whisperClientIds) + // sees no change on this switch and doesn't replay a spurious started/stopped + // log entry or resend setWhisperTargets for a target that didn't change. + prevWhisperTargetsRef.current = { + channels: new Set(parked.whisperChannelIds), + clients: new Set(parked.whisperClientIds), + }; cleanDisconnectRef.current = false; }; @@ -5344,6 +5360,22 @@ function AppInner() { cleanDisconnectRef.current = false; }; + // serverGroups/channelGroups/permissionCatalog/banList/fileBrowser* are + // per-server data cached at the page level rather than per-tab (they're not + // part of ParkedSessionState). Without invalidating them on a multi-join tab + // switch, the existing "if (!serverGroups) fetch" guards would keep serving + // the previous session's server the newly active tab belongs to. + const resetPerServerCaches = () => { + setServerGroups(null); + setChannelGroups(null); + setPermissionCatalog(null); + permissionCatalogRequestedRef.current = false; + setBanList(null); + setFileBrowserTarget(null); + setFileBrowserPath("/"); + setFileBrowserEntries(null); + }; + const updateTabMeta = (id: string, patch: Partial) => { setSessionTabs((prev) => prev.map((t) => (t.id === id ? { ...t, ...patch } : t))); }; @@ -5381,6 +5413,7 @@ function AppInner() { const parked = target.parked ?? emptyParkedState({ host: target.id }); target.parked = null; applyParkedToUi(parked); + resetPerServerCaches(); socketRef.current = target.socket as WebSocket | DemoSocket | null; activeSessionIdRef.current = id; setActiveSessionId(id); @@ -5389,6 +5422,10 @@ function AppInner() { connected: parked.connected, connecting: parked.connecting, }); + // parkActiveSession() above stopped the mic when leaving the previous tab - + // restore it here if it was on for the tab we're switching back to, so + // re-entering a tab doesn't silently leave the user unable to transmit. + if (parked.micWasOn) void startMic(); }; const removeSession = (id: string, opts?: { skipSocketClose?: boolean }) => { @@ -5413,6 +5450,7 @@ function AppInner() { } } sessionsRef.current.delete(id); + lastChannelClickBySession.delete(id); setSessionTabs((prev) => prev.filter((t) => t.id !== id)); if (activeSessionIdRef.current !== id) { @@ -5427,9 +5465,11 @@ function AppInner() { const parked = nextRec.parked ?? emptyParkedState(); nextRec.parked = null; applyParkedToUi(parked); + resetPerServerCaches(); socketRef.current = nextRec.socket as WebSocket | DemoSocket | null; activeSessionIdRef.current = nextId; setActiveSessionId(nextId); + if (parked.micWasOn) void startMic(); } else { clearActiveUi(); socketRef.current = null; @@ -6116,6 +6156,16 @@ function AppInner() { useEffect(() => { if (!connected) return; + const prev = prevWhisperTargetsRef.current; + const setsEqual = (a: Set, b: Set) => a.size === b.size && [...a].every((x) => b.has(x)); + const unchanged = + !!prev && setsEqual(prev.channels, whisperChannelIds) && setsEqual(prev.clients, whisperClientIds); + prevWhisperTargetsRef.current = { channels: new Set(whisperChannelIds), clients: new Set(whisperClientIds) }; + // Nothing actually changed for the now-active session (e.g. this run was + // triggered by restoring a parked multi-join tab, not by the user toggling + // a whisper target) - skip both the gateway resend and the log entry below. + if (unchanged) return; + socketRef.current?.send( JSON.stringify({ type: "setWhisperTargets", @@ -6124,8 +6174,6 @@ function AppInner() { }) ); - const prev = prevWhisperTargetsRef.current; - prevWhisperTargetsRef.current = { channels: new Set(whisperChannelIds), clients: new Set(whisperClientIds) }; const wasEmpty = !prev || (prev.channels.size === 0 && prev.clients.size === 0); const isEmpty = whisperChannelIds.size === 0 && whisperClientIds.size === 0; if (wasEmpty && isEmpty) return; @@ -8541,6 +8589,7 @@ function AppInner() { serverGroups={serverGroups} groupIconImages={serverIconImages} selected={selected} + sessionKey={activeSessionId ?? ""} onSelectItem={handleSelectItem} onSwitchChannel={handleSwitchChannel} onOpenPrivateChat={handleOpenPrivateChat} @@ -8692,7 +8741,7 @@ function AppInner() {
- {log.slice(-1).map((entry, i) => { + {log.slice(-50).map((entry, i) => { let text = entry.text; if (/os[- ]?error\s*10049/i.test(text) || /angeforderte Adresse ist in diesem Kontext ungültig/i.test(text)) { text = "File-Transfer fehlgeschlagen (ungültige Adresse)"; diff --git a/web/src/connectionSessions.ts b/web/src/connectionSessions.ts index ba75843..846f3eb 100644 --- a/web/src/connectionSessions.ts +++ b/web/src/connectionSessions.ts @@ -90,6 +90,8 @@ export type ParkedSessionState = { log: LogEntry[]; hasConnected: boolean; previousClients: ClientInfo[] | null; + /** Whether the mic was on for this tab when it was parked, so switching back restores it. */ + micWasOn: boolean; }; export type SessionTabInfo = { @@ -140,6 +142,7 @@ export function emptyParkedState(partial?: Partial): ParkedS log: [], hasConnected: false, previousClients: null, + micWasOn: false, ...partial, }; }