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.
This commit is contained in:
Moepchi committed 2026-09-06 00:20:33 +02:00
1 parent cd6928b407
commit 9702c671e8
4 files changed
+93 -20

No files matched your search

+14 -9
View File
@@ -569,9 +569,8 @@ fn snapshot(con: &data::Connection) -> Event {
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
// Bookkeeping includes ServerQuery clients (`ClientType::Query`); hide them // Bookkeeping includes ServerQuery clients (`ClientType::Query`); hide them
// from the channel tree / client lists. Online counters still use the // from the channel tree / client lists, and from the online-count fallback
// server-reported total (often includes Query) via `client_count` below. // below too, so the number shown never counts a client the list doesn't.
let all_clients_count = con.clients.len() as u16;
let clients = con let clients = con
.clients .clients
.values() .values()
@@ -606,12 +605,13 @@ fn snapshot(con: &data::Connection) -> Event {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
// Prefer server-reported counters (GTS/TS `virtualserver_*` via notifyserverupdated) // Prefer server-reported counters (GTS/TS `virtualserver_*` via notifyserverupdated)
// but never under-report vs. the full bookkeeping client set including Query // but never under-report vs. the visible (non-Query) client set (stale
// (stale optional_data after joins would otherwise freeze the InfoPanel left number). // optional_data after joins would otherwise freeze the InfoPanel left number).
let opt = con.server.optional_data.as_ref(); let opt = con.server.optional_data.as_ref();
let visible_channels = channels.len() as u64; let visible_channels = channels.len() as u64;
let visible_clients_count = clients.len() as u16;
let server_clients_online = 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 = let server_channels_online =
opt.map(|d| d.channel_count.max(visible_channels)).unwrap_or(visible_channels); 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 pending_server_conninfo {
if let Some(data) = &con.get_state()?.server.connection_data { let state = con.get_state()?;
// TeaSpeak/TS may report packet loss as a fraction (0–1) or percent. // 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 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 { emit(&Event::ServerConnectionInfo {
ping_ms: data.ping.as_seconds_f64() * 1000.0, ping_ms: data.ping.as_seconds_f64() * 1000.0,
connected_secs: data.connected_time_total.whole_seconds(), connected_secs: data.connected_time_total.whole_seconds(),
+18 -2
View File
@@ -789,9 +789,25 @@ export class Ts3Connection {
async disconnect(message = ""): Promise<void> { async disconnect(message = ""): Promise<void> {
if (this.child && !this.child.killed) { if (this.child && !this.child.killed) {
const child = this.child;
const sanitized = message.replace(/[\r\n]+/g, " ").trim(); const sanitized = message.replace(/[\r\n]+/g, " ").trim();
this.child.stdin.write(`disconnect ${sanitized}\n`); child.stdin.write(`disconnect ${sanitized}\n`);
this.child.stdin.end(); 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<void>((resolve) => {
const timeout = setTimeout(() => {
child.kill();
resolve();
}, 3000);
child.once("exit", () => {
clearTimeout(timeout);
resolve();
});
});
} }
this.listeners.clear(); this.listeners.clear();
} }
+58 -9
View File
@@ -657,8 +657,10 @@ function ServerIcon() {
); );
} }
/** Survives ChannelTree remounts when Select's setState rebuilds the tree. */ /** Survives ChannelTree remounts when Select's setState rebuilds the tree.
let lastChannelClick: { id: number; at: number } | null = null; * 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<string, { id: number; at: number }>();
let switchArmedUntil = 0; let switchArmedUntil = 0;
function ChannelTree({ function ChannelTree({
@@ -670,6 +672,7 @@ function ChannelTree({
serverGroups, serverGroups,
groupIconImages, groupIconImages,
selected, selected,
sessionKey,
onSelectItem, onSelectItem,
onSwitchChannel, onSwitchChannel,
onOpenPrivateChat, onOpenPrivateChat,
@@ -685,6 +688,9 @@ function ChannelTree({
serverGroups: GroupEntry[] | null; serverGroups: GroupEntry[] | null;
groupIconImages: Record<string, string>; groupIconImages: Record<string, string>;
selected: SelectedItem | null; 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; onSelectItem: (item: SelectedItem) => void;
onSwitchChannel: (channelId: number) => void; onSwitchChannel: (channelId: number) => void;
onOpenPrivateChat: (clientId: number, clientName: string) => void; onOpenPrivateChat: (clientId: number, clientName: string) => void;
@@ -742,13 +748,13 @@ function ChannelTree({
// click's Select setState remounts this row before the second click. // click's Select setState remounts this row before the second click.
// Spacers are joinable (TS/GTS): visual-only difference. // Spacers are joinable (TS/GTS): visual-only difference.
const now = performance.now(); const now = performance.now();
const prev = lastChannelClick; const prev = lastChannelClickBySession.get(sessionKey) ?? null;
if (prev && prev.id === channel.id && now - prev.at < 450) { if (prev && prev.id === channel.id && now - prev.at < 450) {
lastChannelClick = null; lastChannelClickBySession.delete(sessionKey);
switchArmedUntil = now + 50; switchArmedUntil = now + 50;
onSwitchChannel(channel.id); onSwitchChannel(channel.id);
} else { } else {
lastChannelClick = { id: channel.id, at: now }; lastChannelClickBySession.set(sessionKey, { id: channel.id, at: now });
} }
}} }}
onDoubleClick={() => { onDoubleClick={() => {
@@ -890,6 +896,7 @@ function ChannelTree({
serverGroups={serverGroups} serverGroups={serverGroups}
groupIconImages={groupIconImages} groupIconImages={groupIconImages}
selected={selected} selected={selected}
sessionKey={sessionKey}
onSelectItem={onSelectItem} onSelectItem={onSelectItem}
onSwitchChannel={onSwitchChannel} onSwitchChannel={onSwitchChannel}
onOpenPrivateChat={onOpenPrivateChat} 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) => { const startTreeResize = (e: React.MouseEvent) => {
e.preventDefault(); e.preventDefault();
@@ -5276,6 +5283,7 @@ function AppInner() {
log, log,
hasConnected: hasConnectedRef.current, hasConnected: hasConnectedRef.current,
previousClients: previousClientsRef.current, previousClients: previousClientsRef.current,
micWasOn: micOn,
}); });
const applyParkedToUi = (parked: ParkedSessionState) => { const applyParkedToUi = (parked: ParkedSessionState) => {
@@ -5309,6 +5317,14 @@ function AppInner() {
setLog(parked.log); setLog(parked.log);
hasConnectedRef.current = parked.hasConnected; hasConnectedRef.current = parked.hasConnected;
previousClientsRef.current = parked.previousClients; 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; cleanDisconnectRef.current = false;
}; };
@@ -5344,6 +5360,22 @@ function AppInner() {
cleanDisconnectRef.current = false; 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<SessionTabInfo>) => { const updateTabMeta = (id: string, patch: Partial<SessionTabInfo>) => {
setSessionTabs((prev) => prev.map((t) => (t.id === id ? { ...t, ...patch } : t))); 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 }); const parked = target.parked ?? emptyParkedState({ host: target.id });
target.parked = null; target.parked = null;
applyParkedToUi(parked); applyParkedToUi(parked);
resetPerServerCaches();
socketRef.current = target.socket as WebSocket | DemoSocket | null; socketRef.current = target.socket as WebSocket | DemoSocket | null;
activeSessionIdRef.current = id; activeSessionIdRef.current = id;
setActiveSessionId(id); setActiveSessionId(id);
@@ -5389,6 +5422,10 @@ function AppInner() {
connected: parked.connected, connected: parked.connected,
connecting: parked.connecting, 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 }) => { const removeSession = (id: string, opts?: { skipSocketClose?: boolean }) => {
@@ -5413,6 +5450,7 @@ function AppInner() {
} }
} }
sessionsRef.current.delete(id); sessionsRef.current.delete(id);
lastChannelClickBySession.delete(id);
setSessionTabs((prev) => prev.filter((t) => t.id !== id)); setSessionTabs((prev) => prev.filter((t) => t.id !== id));
if (activeSessionIdRef.current !== id) { if (activeSessionIdRef.current !== id) {
@@ -5427,9 +5465,11 @@ function AppInner() {
const parked = nextRec.parked ?? emptyParkedState(); const parked = nextRec.parked ?? emptyParkedState();
nextRec.parked = null; nextRec.parked = null;
applyParkedToUi(parked); applyParkedToUi(parked);
resetPerServerCaches();
socketRef.current = nextRec.socket as WebSocket | DemoSocket | null; socketRef.current = nextRec.socket as WebSocket | DemoSocket | null;
activeSessionIdRef.current = nextId; activeSessionIdRef.current = nextId;
setActiveSessionId(nextId); setActiveSessionId(nextId);
if (parked.micWasOn) void startMic();
} else { } else {
clearActiveUi(); clearActiveUi();
socketRef.current = null; socketRef.current = null;
@@ -6116,6 +6156,16 @@ function AppInner() {
useEffect(() => { useEffect(() => {
if (!connected) return; if (!connected) return;
const prev = prevWhisperTargetsRef.current;
const setsEqual = (a: Set<number>, b: Set<number>) => 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( socketRef.current?.send(
JSON.stringify({ JSON.stringify({
type: "setWhisperTargets", 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 wasEmpty = !prev || (prev.channels.size === 0 && prev.clients.size === 0);
const isEmpty = whisperChannelIds.size === 0 && whisperClientIds.size === 0; const isEmpty = whisperChannelIds.size === 0 && whisperClientIds.size === 0;
if (wasEmpty && isEmpty) return; if (wasEmpty && isEmpty) return;
@@ -8541,6 +8589,7 @@ function AppInner() {
serverGroups={serverGroups} serverGroups={serverGroups}
groupIconImages={serverIconImages} groupIconImages={serverIconImages}
selected={selected} selected={selected}
sessionKey={activeSessionId ?? ""}
onSelectItem={handleSelectItem} onSelectItem={handleSelectItem}
onSwitchChannel={handleSwitchChannel} onSwitchChannel={handleSwitchChannel}
onOpenPrivateChat={handleOpenPrivateChat} onOpenPrivateChat={handleOpenPrivateChat}
@@ -8692,7 +8741,7 @@ function AppInner() {
</div> </div>
<div className="ts-log"> <div className="ts-log">
{log.slice(-1).map((entry, i) => { {log.slice(-50).map((entry, i) => {
let text = entry.text; let text = entry.text;
if (/os[- ]?error\s*10049/i.test(text) || /angeforderte Adresse ist in diesem Kontext ungültig/i.test(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)"; text = "File-Transfer fehlgeschlagen (ungültige Adresse)";
+3
View File
@@ -90,6 +90,8 @@ export type ParkedSessionState = {
log: LogEntry[]; log: LogEntry[];
hasConnected: boolean; hasConnected: boolean;
previousClients: ClientInfo[] | null; 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 = { export type SessionTabInfo = {
@@ -140,6 +142,7 @@ export function emptyParkedState(partial?: Partial<ParkedSessionState>): ParkedS
log: [], log: [],
hasConnected: false, hasConnected: false,
previousClients: null, previousClients: null,
micWasOn: false,
...partial, ...partial,
}; };
} }