Merge pull request #1 from Moepchi/fix/pr-4-review-bugs

Fix 8 correctness bugs found in review of TeaSpeak/GTS + multi-join PR
This commit is contained in:
Nico B. authored and GitHub committed 2026-09-06 01:20:59 +02:00
commit a118c0f58e
4 files changed
+93 -20

No files matched your search

+14 -9
View File
@@ -574,9 +574,8 @@ fn snapshot(con: &data::Connection) -> Event {
})
.collect::<Vec<_>>();
// 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()
@@ -611,12 +610,13 @@ fn snapshot(con: &data::Connection) -> Event {
.collect::<Vec<_>>();
// 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);
@@ -2150,10 +2150,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(),
+18 -2
View File
@@ -796,9 +796,25 @@ export class Ts3Connection {
async disconnect(message = ""): Promise<void> {
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<void>((resolve) => {
const timeout = setTimeout(() => {
child.kill();
resolve();
}, 3000);
child.once("exit", () => {
clearTimeout(timeout);
resolve();
});
});
}
this.listeners.clear();
}
+58 -9
View File
@@ -660,8 +660,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<string, { id: number; at: number }>();
let switchArmedUntil = 0;
function ChannelTree({
@@ -673,6 +675,7 @@ function ChannelTree({
serverGroups,
groupIconImages,
selected,
sessionKey,
onSelectItem,
onSwitchChannel,
onOpenPrivateChat,
@@ -688,6 +691,9 @@ function ChannelTree({
serverGroups: GroupEntry[] | null;
groupIconImages: Record<string, string>;
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;
@@ -745,13 +751,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={() => {
@@ -893,6 +899,7 @@ function ChannelTree({
serverGroups={serverGroups}
groupIconImages={groupIconImages}
selected={selected}
sessionKey={sessionKey}
onSelectItem={onSelectItem}
onSwitchChannel={onSwitchChannel}
onOpenPrivateChat={onOpenPrivateChat}
@@ -5301,7 +5308,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();
@@ -5384,6 +5391,7 @@ function AppInner() {
log,
hasConnected: hasConnectedRef.current,
previousClients: previousClientsRef.current,
micWasOn: micOn,
});
const applyParkedToUi = (parked: ParkedSessionState) => {
@@ -5417,6 +5425,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;
};
@@ -5454,6 +5470,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<SessionTabInfo>) => {
setSessionTabs((prev) => prev.map((t) => (t.id === id ? { ...t, ...patch } : t)));
};
@@ -5491,6 +5523,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);
@@ -5499,6 +5532,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 }) => {
@@ -5523,6 +5560,7 @@ function AppInner() {
}
}
sessionsRef.current.delete(id);
lastChannelClickBySession.delete(id);
setSessionTabs((prev) => prev.filter((t) => t.id !== id));
if (activeSessionIdRef.current !== id) {
@@ -5537,9 +5575,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;
@@ -6241,6 +6281,16 @@ function AppInner() {
useEffect(() => {
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(
JSON.stringify({
type: "setWhisperTargets",
@@ -6249,8 +6299,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;
@@ -8685,6 +8733,7 @@ function AppInner() {
serverGroups={serverGroups}
groupIconImages={serverIconImages}
selected={selected}
sessionKey={activeSessionId ?? ""}
onSelectItem={handleSelectItem}
onSwitchChannel={handleSwitchChannel}
onOpenPrivateChat={handleOpenPrivateChat}
@@ -8839,7 +8888,7 @@ function AppInner() {
</div>
<div className="ts-log">
{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)";
+3
View File
@@ -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<ParkedSessionState>): ParkedS
log: [],
hasConnected: false,
previousClients: null,
micWasOn: false,
...partial,
};
}