Initial commit: browser-based TeamSpeak client

React frontend + Node gateway + Rust connector (tsclientlib) providing
connect, channel tree/switching, channel/server/private text chat, and
voice with voice activation and output device selection.
This commit is contained in:
Moepchi committed 2026-07-28 19:25:46 +02:00
commit b3e55a60b5
33 files changed
+7383

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
node_modules/
target/
dist/
dist-ssr/
*.log
.env
.env.local
.DS_Store
+3
View File
@@ -0,0 +1,3 @@
[submodule "tsclientlib"]
path = tsclientlib
url = https://github.com/ReSpeak/tsclientlib.git
+87
View File
@@ -0,0 +1,87 @@
# Installation
## Prerequisites
- **Node.js** 20+ and npm
- **Rust** (stable toolchain) — [rustup.rs](https://rustup.rs)
- **CMake** and a C/C++ toolchain — needed to build the Opus codec library
(`audiopus_sys`) used for voice. On Windows, the Visual Studio "Desktop
development with C++" workload covers this; on Linux, install `cmake` and
`build-essential` (or equivalent); on macOS, `cmake` via Homebrew plus Xcode
command line tools.
- **git**
## 1. Clone the repository
The Rust connector depends on the `tsclientlib` crate, vendored as a git
submodule — make sure to pull it in too:
```bash
git clone --recurse-submodules <your-repo-url>
cd ts-web-client
```
If you already cloned without `--recurse-submodules`:
```bash
git submodule update --init --recursive
```
## 2. Build the Rust connector
```bash
cd connector
cargo build
```
> **Note:** if the build fails with a CMake error like `Compatibility with
> CMake < 3.5 has been removed`, it's because the vendored Opus source uses an
> old `cmake_minimum_required`. Work around it with:
>
> ```bash
> CMAKE_POLICY_VERSION_MINIMUM=3.5 cargo build
> ```
> (On Windows PowerShell: `$env:CMAKE_POLICY_VERSION_MINIMUM = "3.5"; cargo build`)
This produces `connector/target/debug/ts-connector` (or `ts-connector.exe` on
Windows), which the gateway spawns automatically — no manual step needed
after this.
## 3. Install and start the gateway
```bash
cd gateway
npm install
npm run dev
```
This starts the WebSocket gateway on `ws://localhost:8080`.
## 4. Install and start the web frontend
In a separate terminal:
```bash
cd web
npm install
npm run dev
```
Vite will print a local dev URL (typically `http://localhost:5173`) — open
it in a browser.
## 5. Connect
In the web UI, enter the address of a TeamSpeak server and a nickname, then
click **Connect**. Voice requires microphone permission when you enable the
mic button; the output-device picker (if your browser supports it) requires
no extra permission.
## Rebuilding after changes
- Frontend and gateway changes hot-reload automatically (`npm run dev` in
both cases).
- Connector changes require a rebuild (`cargo build` in `connector/`) and a
reconnect from the browser — if the old `ts-connector` binary is still
running (an active browser connection), disconnect first or the build will
fail to overwrite the binary.
+43
View File
@@ -0,0 +1,43 @@
# TS Web Client
Browser-based client for TeamSpeak servers — same idea as the native
installable client, but running in a web browser. The TeamSpeak server side
stays exactly as-is (a regular TS server); only the client is being
reimagined.
**Status: private prototype, not for production use.**
## Features
- Connect to a real TeamSpeak (3/5/6) server
- Channel/client tree with correct ordering, click to switch channels
- Text chat: channel, server-wide, and private (1:1) — each in its own tab
- Voice with voice activation ("Sprachaktivierung", not push-to-talk),
adjustable sensitivity, and per-client speaking indicators
- Audio output device picker (routes playback to a chosen device)
- Light/dark theme
## Architecture
Browsers can't send raw UDP, which is what TeamSpeak's native protocol runs
over, so a pure client-side implementation isn't possible — a server-side
gateway is required that speaks the real TS protocol on one side and
WebSocket to the browser on the other.
```
Browser (web/) <--WebSocket--> Gateway (gateway/) <--stdin/stdout JSON--> Rust connector (connector/) <--TS3/TS5 protocol--> TeamSpeak Server
```
- **`web/`** — Vite + React frontend. TS3-lookalike UI: channel tree, chat
tabs, voice controls.
- **`gateway/`** — Node.js/TypeScript WebSocket server. Spawns the Rust
connector per browser connection and relays newline-delimited JSON events
between it and the browser.
- **`connector/`** — Rust binary wrapping [`tsclientlib`](https://github.com/ReSpeak/tsclientlib)
(vendored as a git submodule in `tsclientlib/`), the actual TS3/TS5
protocol implementation. Handles connecting, channel/client state, chat,
and Opus-encoded voice.
## Installation
See [INSTALL.md](INSTALL.md).
+3182
View File
File diff suppressed because it is too large. Load diff
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "ts-connector"
version = "0.1.0"
edition = "2021"
[dependencies]
tsclientlib = { path = "../tsclientlib/tsclientlib", default-features = false, features = ["default-tls", "audio"] }
tsproto-packets = { path = "../tsclientlib/utils/tsproto-packets" }
audiopus = "0.3.0-rc.0"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "io-std", "io-util"] }
futures = "0.3"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
clap = { version = "4", features = ["derive"] }
anyhow = "1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
base64 = "0.22"
+434
View File
@@ -0,0 +1,434 @@
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use anyhow::Result;
use audiopus::coder::Encoder as OpusEncoder;
use base64::Engine;
use clap::Parser;
use futures::prelude::*;
use serde::Serialize;
use tokio::io::{AsyncBufReadExt, BufReader};
use tsclientlib::audio::AudioHandler;
use tsclientlib::events::Event as BookEvent;
use tsclientlib::messages::c2s::OutSendTextMessagePart;
use tsclientlib::prelude::*;
use tsclientlib::{
data, ChannelId, ClientId, Connection, DisconnectOptions, MessageHandle, MessageTarget,
StreamItem, TextMessageTargetMode,
};
use tsproto_packets::packets::{AudioData, CodecType, OutAudio};
/// 20ms frames at 48kHz, which is what TeamSpeak's Opus voice codec expects.
const FRAME_SAMPLES: usize = 960;
const OUT_CHANNELS: usize = 2;
#[derive(Parser, Debug)]
#[command(author, about = "One-shot bridge: connects to a real TeamSpeak server and reports events as JSON lines on stdout")]
struct Args {
/// Server address, e.g. "192.168.178.108" or "192.168.178.108:9987"
#[arg(short, long)]
address: String,
/// Nickname to use on the server
#[arg(short, long, default_value = "Browser User")]
nickname: String,
}
#[derive(Serialize)]
struct ChannelInfo {
id: u64,
parent: u64,
order: u64,
name: String,
}
#[derive(Serialize)]
struct ClientInfo {
id: u16,
channel: u64,
name: String,
}
#[derive(Serialize)]
#[serde(tag = "type")]
enum Event {
#[serde(rename = "connected")]
Connected { welcome_message: String },
#[serde(rename = "channels")]
Channels { channels: Vec<ChannelInfo>, clients: Vec<ClientInfo> },
#[serde(rename = "chatMessage")]
ChatMessage { from: String, message: String },
#[serde(rename = "serverMessage")]
ServerMessage { from: String, message: String },
/// A direct (whisper) message. `partner_id`/`partner_name` always identify
/// the *other* side of the conversation, regardless of who sent it, so the
/// frontend can group messages into one thread per partner.
#[serde(rename = "privateMessage")]
PrivateMessage { partner_id: u16, partner_name: String, from_self: bool, message: String },
/// Mixed, decoded PCM audio ready to play: 16-bit signed little-endian,
/// stereo, 48kHz, base64-encoded.
#[serde(rename = "audioOut")]
AudioOut { pcm: String },
/// Ids of clients currently detected as talking.
#[serde(rename = "talkers")]
Talkers { clients: Vec<u16> },
#[serde(rename = "disconnected")]
Disconnected { reason: String },
#[serde(rename = "error")]
Error { message: String },
}
fn emit(event: &Event) {
println!("{}", serde_json::to_string(event).unwrap());
}
/// `Channel::order` is not a plain position, it's the id of the preceding
/// sibling channel (0 = first child of its parent) - effectively a linked
/// list per parent. This resolves that into a plain 0-based sequence index
/// per parent, so the frontend can just sort by it.
fn resolve_order(channels: &[&data::Channel]) -> HashMap<u64, u64> {
let mut by_parent: HashMap<u64, Vec<&data::Channel>> = HashMap::new();
for ch in channels {
by_parent.entry(ch.parent.0).or_default().push(ch);
}
let mut result = HashMap::new();
for (_, mut remaining) in by_parent {
let mut prev_id = 0u64;
let mut index = 0u64;
while !remaining.is_empty() {
match remaining.iter().position(|ch| ch.order.0 == prev_id) {
Some(pos) => {
let ch = remaining.remove(pos);
result.insert(ch.id.0, index);
index += 1;
prev_id = ch.id.0;
}
// Broken/incomplete chain: dump the rest rather than loop forever.
None => {
for ch in remaining.drain(..) {
result.insert(ch.id.0, index);
index += 1;
}
}
}
}
}
result
}
fn snapshot(con: &data::Connection) -> Event {
let channel_refs: Vec<&data::Channel> = con.channels.values().collect();
let order = resolve_order(&channel_refs);
let channels = channel_refs
.iter()
.map(|ch| ChannelInfo {
id: ch.id.0,
parent: ch.parent.0,
order: *order.get(&ch.id.0).unwrap_or(&0),
name: ch.name.clone(),
})
.collect();
let clients = con
.clients
.values()
.map(|c| ClientInfo { id: c.id.0, channel: c.channel.0, name: c.name.clone() })
.collect();
Event::Channels { channels, clients }
}
#[tokio::main]
async fn main() {
let args = Args::parse();
if let Err(e) = run(args).await {
emit(&Event::Error { message: e.to_string() });
}
}
async fn run(args: Args) -> Result<()> {
// stdout is a strict newline-delimited-JSON channel for the gateway to parse;
// all diagnostic logging must go to stderr instead.
tracing_subscriber::fmt().with_env_filter("warn").with_writer(std::io::stderr).init();
let con_config = Connection::build(args.address).name(args.nickname);
let mut con = con_config.connect()?;
// Wait for the initial book events (means we're logged in and have server state)
let r = con
.events()
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
.next()
.await;
if let Some(r) = r {
r?;
}
let welcome_message = con.get_state()?.server.welcome_message.clone();
emit(&Event::Connected { welcome_message });
// Subscribe to all channels so we actually receive the full channel/client list.
con.get_state()?.server.set_subscribed(true).send(&mut con)?;
// Give the server a moment to send the channel/client list, then emit a
// snapshot. Further snapshots are emitted below whenever book state changes.
{
let mut events = con.events().try_filter(|_| future::ready(false));
tokio::select! {
_ = tokio::time::sleep(tokio::time::Duration::from_millis(800)) => {}
_ = events.next() => {}
}
}
emit(&snapshot(con.get_state()?));
// Main loop: relay book updates as fresh snapshots, watch stdin for a
// "disconnect" command, watch the connection for the server hanging up.
let mut stdin_lines = BufReader::new(tokio::io::stdin()).lines();
let opus_encoder = OpusEncoder::new(
audiopus::SampleRate::Hz48000,
audiopus::Channels::Mono,
audiopus::Application::Voip,
)?;
let mut audio_handler = AudioHandler::<ClientId>::new();
let mut talking: HashSet<u16> = HashSet::new();
let mut audio_ticker = tokio::time::interval(tokio::time::Duration::from_millis(20));
// Commands sent via `send()` fail silently if the server rejects them (e.g.
// missing permission) - no reply is sent back without a return code. Using
// `send_with_result()` for text messages gets us a `MessageResult` event we
// can surface as a visible error instead of the message just vanishing.
let mut pending_messages: HashMap<MessageHandle, String> = HashMap::new();
enum LoopOutcome {
StdinLine(std::io::Result<Option<String>>),
ConEvent(Option<Result<StreamItem, tsclientlib::Error>>),
AudioTick,
}
loop {
let mut events = con.events();
let outcome = tokio::select! {
line = stdin_lines.next_line() => LoopOutcome::StdinLine(line),
ev = events.next() => LoopOutcome::ConEvent(ev),
_ = audio_ticker.tick() => LoopOutcome::AudioTick,
};
drop(events);
match outcome {
LoopOutcome::StdinLine(line) => match line {
Ok(Some(l)) => {
let l = l.trim();
if l == "disconnect" {
con.disconnect(DisconnectOptions::new())?;
con.events().for_each(|_| future::ready(())).await;
emit(&Event::Disconnected { reason: "client requested".into() });
break;
} else if let Some(rest) = l.strip_prefix("switch ") {
match rest.trim().parse::<u64>() {
Ok(id) => {
let part = {
let state = con.get_state()?;
let own = &state.clients[&state.own_client];
own.client_move(ChannelId(id))
};
if let Err(e) = part.send(&mut con) {
emit(&Event::Error { message: e.to_string() });
}
}
Err(_) => emit(&Event::Error { message: format!("Invalid channel id: {rest}") }),
}
} else if let Some(message) = l.strip_prefix("chat ") {
let part = OutSendTextMessagePart {
target: TextMessageTargetMode::Channel,
target_client_id: None,
message: Cow::Borrowed(message),
};
match part.send_with_result(&mut con) {
Ok(handle) => {
pending_messages.insert(handle, "Channel message".into());
}
Err(e) => emit(&Event::Error { message: e.to_string() }),
}
// No local echo here: the server reflects our own channel
// messages back to us too, so it arrives via the normal
// BookEvents/Event::Message path like anyone else's.
} else if let Some(message) = l.strip_prefix("serverchat ") {
let part = OutSendTextMessagePart {
target: TextMessageTargetMode::Server,
target_client_id: None,
message: Cow::Borrowed(message),
};
match part.send_with_result(&mut con) {
Ok(handle) => {
pending_messages.insert(handle, "Server message".into());
}
Err(e) => emit(&Event::Error { message: e.to_string() }),
}
// Same as channel chat: the server echoes this back to us too.
} else if let Some(rest) = l.strip_prefix("pm ") {
match rest.trim().split_once(' ') {
Some((id, message)) => match id.parse::<u16>() {
Ok(id) => {
let part = OutSendTextMessagePart {
target: TextMessageTargetMode::Client,
target_client_id: Some(ClientId(id)),
message: Cow::Borrowed(message),
};
match part.send_with_result(&mut con) {
Ok(handle) => {
pending_messages.insert(handle, "Private message".into());
}
Err(e) => emit(&Event::Error { message: e.to_string() }),
}
// Same as channel chat: the server echoes this back to
// us via BookEvents/Event::Message, no local echo needed.
}
Err(_) => emit(&Event::Error { message: format!("Invalid client id: {id}") }),
},
None => emit(&Event::Error { message: "Malformed pm command".into() }),
}
} else if let Some(b64) = l.strip_prefix("audio ") {
match base64::engine::general_purpose::STANDARD.decode(b64.trim()) {
Ok(bytes) => {
let samples: Vec<f32> = bytes
.chunks_exact(2)
.map(|c| i16::from_le_bytes([c[0], c[1]]) as f32 / 32768.0)
.collect();
if samples.len() == FRAME_SAMPLES {
let mut opus_output = [0u8; 1275];
match opus_encoder.encode_float(&samples, &mut opus_output) {
Ok(len) => {
let packet = OutAudio::new(&AudioData::C2S {
id: 0,
codec: CodecType::OpusVoice,
data: &opus_output[..len],
});
if let Err(e) = con.send_audio(packet) {
emit(&Event::Error { message: e.to_string() });
}
}
Err(e) => emit(&Event::Error { message: format!("Opus encode failed: {e}") }),
}
}
}
Err(e) => emit(&Event::Error { message: format!("Invalid audio payload: {e}") }),
}
}
// unrecognized lines are ignored
}
Ok(None) => {
emit(&Event::Disconnected { reason: "stdin closed".into() });
break;
}
Err(e) => {
emit(&Event::Error { message: e.to_string() });
break;
}
},
LoopOutcome::ConEvent(ev) => match ev {
Some(Ok(StreamItem::BookEvents(events))) => {
for event in &events {
if let BookEvent::Message { target, invoker, message } = event {
match target {
MessageTarget::Server => {
emit(&Event::ServerMessage {
from: invoker.name.clone(),
message: message.clone(),
});
}
MessageTarget::Channel => {
emit(&Event::ChatMessage {
from: invoker.name.clone(),
message: message.clone(),
});
}
MessageTarget::Client(other_id) => {
let own_id = con.get_state()?.own_client;
if invoker.id == own_id {
let partner_name = con
.get_state()?
.clients
.get(other_id)
.map(|c| c.name.clone())
.unwrap_or_default();
emit(&Event::PrivateMessage {
partner_id: other_id.0,
partner_name,
from_self: true,
message: message.clone(),
});
} else {
emit(&Event::PrivateMessage {
partner_id: invoker.id.0,
partner_name: invoker.name.clone(),
from_self: false,
message: message.clone(),
});
}
}
_ => {}
}
}
}
emit(&snapshot(con.get_state()?));
}
Some(Ok(StreamItem::Audio(packet))) => {
let from = match packet.data().data() {
AudioData::S2C { from, .. } => Some(ClientId(*from)),
AudioData::S2CWhisper { from, .. } => Some(ClientId(*from)),
_ => None,
};
if let Some(from) = from {
if let Ok(Some(new_talker)) = audio_handler.handle_packet(from, packet) {
if talking.insert(new_talker.0) {
emit(&Event::Talkers { clients: talking.iter().copied().collect() });
}
}
}
}
Some(Ok(StreamItem::MessageResult(handle, result))) => {
if let Some(label) = pending_messages.remove(&handle) {
if let Err(e) = result {
emit(&Event::Error { message: format!("{label} failed: {e}") });
}
}
}
Some(Ok(_)) => {}
Some(Err(e)) => {
emit(&Event::Disconnected { reason: e.to_string() });
break;
}
None => {
emit(&Event::Disconnected { reason: "server closed connection".into() });
break;
}
},
LoopOutcome::AudioTick => {
if !audio_handler.get_queues().is_empty() {
let mut buf = vec![0.0f32; FRAME_SAMPLES * OUT_CHANNELS];
let stopped = audio_handler.fill_buffer(&mut buf);
let mut talkers_changed = false;
for id in stopped {
if talking.remove(&id.0) {
talkers_changed = true;
}
}
if talkers_changed {
emit(&Event::Talkers { clients: talking.iter().copied().collect() });
}
let mut bytes = Vec::with_capacity(buf.len() * 2);
for sample in &buf {
let clamped = sample.clamp(-1.0, 1.0);
let pcm = (clamped * 32767.0) as i16;
bytes.extend_from_slice(&pcm.to_le_bytes());
}
emit(&Event::AudioOut { pcm: base64::engine::general_purpose::STANDARD.encode(bytes) });
}
}
}
}
Ok(())
}
+601
View File
@@ -0,0 +1,601 @@
{
"name": "ts-web-gateway",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ts-web-gateway",
"version": "0.1.0",
"dependencies": {
"ws": "^8.18.0"
},
"devDependencies": {
"@types/node": "^22.10.0",
"@types/ws": "^8.5.13",
"tsx": "^4.19.0",
"typescript": "^5.7.0"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
"integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
"integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
"integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
"integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
"integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
"integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
"integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
"integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
"integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
"integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
"integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
"integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
"integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
"integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
"integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
"integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
"integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
"integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
"integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
"integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
"integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
"integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
"integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
"integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
"integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
"integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@types/node": {
"version": "22.20.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.1.tgz",
"integrity": "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@types/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
"integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/esbuild": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
"integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.28.1",
"@esbuild/android-arm": "0.28.1",
"@esbuild/android-arm64": "0.28.1",
"@esbuild/android-x64": "0.28.1",
"@esbuild/darwin-arm64": "0.28.1",
"@esbuild/darwin-x64": "0.28.1",
"@esbuild/freebsd-arm64": "0.28.1",
"@esbuild/freebsd-x64": "0.28.1",
"@esbuild/linux-arm": "0.28.1",
"@esbuild/linux-arm64": "0.28.1",
"@esbuild/linux-ia32": "0.28.1",
"@esbuild/linux-loong64": "0.28.1",
"@esbuild/linux-mips64el": "0.28.1",
"@esbuild/linux-ppc64": "0.28.1",
"@esbuild/linux-riscv64": "0.28.1",
"@esbuild/linux-s390x": "0.28.1",
"@esbuild/linux-x64": "0.28.1",
"@esbuild/netbsd-arm64": "0.28.1",
"@esbuild/netbsd-x64": "0.28.1",
"@esbuild/openbsd-arm64": "0.28.1",
"@esbuild/openbsd-x64": "0.28.1",
"@esbuild/openharmony-arm64": "0.28.1",
"@esbuild/sunos-x64": "0.28.1",
"@esbuild/win32-arm64": "0.28.1",
"@esbuild/win32-ia32": "0.28.1",
"@esbuild/win32-x64": "0.28.1"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/tsx": {
"version": "4.23.1",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.1.tgz",
"integrity": "sha512-GQHnkIfxyx1wYCOS/wonik5MVRZU9hi1TEZmzGZSCJB1y9YgoZ8H6itNE/u4suE+yLmOzuE4E5S4TZ/ZX2wcWQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "~0.28.0"
},
"bin": {
"tsx": "dist/cli.mjs"
},
"engines": {
"node": ">=18.0.0"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
},
"node_modules/ws": {
"version": "8.21.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.1.tgz",
"integrity": "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"name": "ts-web-gateway",
"version": "0.1.0",
"private": true,
"description": "Gateway server: bridges browser (WebSocket) clients to a native TeamSpeak server",
"type": "module",
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc -p tsconfig.json",
"start": "node dist/index.js"
},
"dependencies": {
"ws": "^8.18.0"
},
"devDependencies": {
"@types/node": "^22.10.0",
"@types/ws": "^8.5.13",
"tsx": "^4.19.0",
"typescript": "^5.7.0"
}
}
+57
View File
@@ -0,0 +1,57 @@
import { WebSocketServer, type WebSocket } from "ws";
import { Ts3Connection, type Ts3ConnectOptions } from "./ts3/connection.js";
const PORT = Number(process.env.PORT ?? 8080);
const wss = new WebSocketServer({ port: PORT });
console.log(`Gateway listening on ws://localhost:${PORT}`);
wss.on("connection", (socket: WebSocket) => {
let connection: Ts3Connection | undefined;
socket.on("message", async (raw) => {
const msg = JSON.parse(raw.toString());
switch (msg.type) {
case "connect": {
const options: Ts3ConnectOptions = {
host: msg.host,
nickname: msg.nickname,
};
connection = new Ts3Connection(options);
connection.onEvent((event) => socket.send(JSON.stringify(event)));
await connection.connect();
break;
}
case "switchChannel": {
await connection?.switchChannel(msg.channelId);
break;
}
case "sendChatMessage": {
await connection?.sendChatMessage(msg.message);
break;
}
case "sendServerMessage": {
await connection?.sendServerMessage(msg.message);
break;
}
case "sendPrivateMessage": {
await connection?.sendPrivateMessage(msg.clientId, msg.message);
break;
}
case "sendAudio": {
await connection?.sendAudio(msg.pcm);
break;
}
default:
socket.send(
JSON.stringify({ type: "error", message: `Unknown message type: ${msg.type}` })
);
}
});
socket.on("close", () => {
connection?.disconnect();
});
});
+145
View File
@@ -0,0 +1,145 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { createInterface } from "node:readline";
import path from "node:path";
import { fileURLToPath } from "node:url";
/**
* Bridges to the real TeamSpeak client protocol via the `ts-connector` Rust
* binary (built on top of tsclientlib), since that protocol can't be spoken
* from Node/the browser directly. This process is spawned per connection and
* emits newline-delimited JSON events on stdout.
*/
export interface ChannelInfo {
id: number;
parent: number;
order: number;
name: string;
}
export interface ClientInfo {
id: number;
channel: number;
name: string;
}
export type Ts3ConnectionEvent =
| { type: "connected"; welcomeMessage: string }
| { type: "channels"; channels: ChannelInfo[]; clients: ClientInfo[] }
| { type: "chatMessage"; from: string; message: string }
| { type: "serverMessage"; from: string; message: string }
| { type: "privateMessage"; partnerId: number; partnerName: string; fromSelf: boolean; message: string }
| { type: "audioOut"; pcm: string }
| { type: "talkers"; clients: number[] }
| { type: "disconnected"; reason: string }
| { type: "error"; message: string };
export interface Ts3ConnectOptions {
host: string;
nickname: string;
}
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const CONNECTOR_BIN = path.resolve(
__dirname,
"../../../connector/target/debug",
process.platform === "win32" ? "ts-connector.exe" : "ts-connector"
);
export class Ts3Connection {
private listeners = new Set<(event: Ts3ConnectionEvent) => void>();
private child?: ChildProcessWithoutNullStreams;
constructor(private options: Ts3ConnectOptions) {}
onEvent(listener: (event: Ts3ConnectionEvent) => void): void {
this.listeners.add(listener);
}
private emit(event: Ts3ConnectionEvent): void {
for (const listener of this.listeners) listener(event);
}
async connect(): Promise<void> {
this.child = spawn(CONNECTOR_BIN, [
"--address",
this.options.host,
"--nickname",
this.options.nickname,
]);
createInterface({ input: this.child.stdout }).on("line", (line) => {
try {
const event = JSON.parse(line) as
| { type: "connected"; welcome_message: string }
| { type: "channels"; channels: ChannelInfo[]; clients: ClientInfo[] }
| { type: "chatMessage"; from: string; message: string }
| { type: "serverMessage"; from: string; message: string }
| { type: "privateMessage"; partner_id: number; partner_name: string; from_self: boolean; message: string }
| { type: "audioOut"; pcm: string }
| { type: "talkers"; clients: number[] }
| { type: "disconnected"; reason: string }
| { type: "error"; message: string };
if (event.type === "connected") {
this.emit({ type: "connected", welcomeMessage: event.welcome_message });
} else if (event.type === "privateMessage") {
this.emit({
type: "privateMessage",
partnerId: event.partner_id,
partnerName: event.partner_name,
fromSelf: event.from_self,
message: event.message,
});
} else {
this.emit(event);
}
} catch {
this.emit({ type: "error", message: `Unparseable connector output: ${line}` });
}
});
// stderr carries diagnostic tracing output from the connector (e.g. protocol
// schema warnings), not application-level errors - keep it server-side only.
this.child.stderr.on("data", (data) => {
console.error(`[ts-connector] ${data.toString()}`);
});
this.child.on("exit", (code) => {
if (code !== 0) {
this.emit({ type: "error", message: `Connector exited with code ${code}` });
}
});
}
async switchChannel(channelId: number): Promise<void> {
this.child?.stdin.write(`switch ${channelId}\n`);
}
async sendChatMessage(message: string): Promise<void> {
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
if (sanitized) this.child?.stdin.write(`chat ${sanitized}\n`);
}
async sendServerMessage(message: string): Promise<void> {
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
if (sanitized) this.child?.stdin.write(`serverchat ${sanitized}\n`);
}
async sendPrivateMessage(clientId: number, message: string): Promise<void> {
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
if (sanitized) this.child?.stdin.write(`pm ${clientId} ${sanitized}\n`);
}
async sendAudio(pcmBase64: string): Promise<void> {
this.child?.stdin.write(`audio ${pcmBase64}\n`);
}
async disconnect(): Promise<void> {
if (this.child && !this.child.killed) {
this.child.stdin.write("disconnect\n");
this.child.stdin.end();
}
this.listeners.clear();
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src"]
}
Submodule
+1
Submodule tsclientlib added at ee3bc6f45a.
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
+32
View File
@@ -0,0 +1,32 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the Oxlint configuration
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
```json
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"options": {
"typeAware": true
},
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
```
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>web</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1459
View File
File diff suppressed because it is too large. Load diff
+25
View File
@@ -0,0 +1,25 @@
{
"name": "web",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "oxlint",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.2.7",
"react-dom": "^19.2.7"
},
"devDependencies": {
"@types/node": "^24.13.2",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.3",
"oxlint": "^1.71.0",
"typescript": "~6.0.2",
"vite": "^8.1.1"
}
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="46" fill="none" viewBox="0 0 48 46"><path fill="#863bff" d="M25.946 44.938c-.664.845-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.287c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.497 0-3.578-1.842-3.578H1.237c-.92 0-1.456-1.04-.92-1.788L10.013.474c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.579 1.842 3.579h11.377c.943 0 1.473 1.088.89 1.83L25.947 44.94z" style="fill:#863bff;fill:color(display-p3 .5252 .23 1);fill-opacity:1"/><mask id="a" width="48" height="46" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M25.842 44.938c-.664.844-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.183c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.498 0-3.579-1.842-3.579H1.133c-.92 0-1.456-1.04-.92-1.787L9.91.473c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.578 1.842 3.578h11.377c.943 0 1.473 1.088.89 1.832L25.843 44.94z" style="fill:#000;fill-opacity:1"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#ede6ff" rx="5.508" ry="14.704" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -4.47 31.516)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#ede6ff" rx="10.399" ry="29.851" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -39.328 7.883)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#7e14ff" rx="5.508" ry="30.487" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -25.913 -14.639)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -32.644 -3.334)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -34.34 30.47)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#ede6ff" rx="14.072" ry="22.078" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="rotate(93.35 24.506 48.493)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx=".387" cy="8.972" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(39.51 .387 8.972)"/></g><g filter="url(#k)"><ellipse cx="47.523" cy="-6.092" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 47.523 -6.092)"/></g><g filter="url(#l)"><ellipse cx="41.412" cy="6.333" fill="#47bfff" rx="5.971" ry="9.665" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 41.412 6.333)"/></g><g filter="url(#m)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#n)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#o)"><ellipse cx="35.651" cy="29.907" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 35.651 29.907)"/></g><g filter="url(#p)"><ellipse cx="38.418" cy="32.4" fill="#47bfff" rx="5.971" ry="15.297" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 38.418 32.4)"/></g></g><defs><filter id="b" width="60.045" height="41.654" x="-19.77" y="16.149" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-54.613" y="-7.533" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filtLine truncated

After

Width:  |  Height:  |  Size: 9.3 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+334
View File
@@ -0,0 +1,334 @@
.ts-app {
--bg: #ffffff;
--bg-toolbar-1: #f5f6f8;
--bg-toolbar-2: #dfe2e6;
--border: #b7bcc3;
--border-soft: #d3d7db;
--text: #1a1a1a;
--text-muted: #888;
--accent: #2b4a6b;
--input-bg: #ffffff;
--input-text: #1a1a1a;
--button-bg-1: #fdfdfd;
--button-bg-2: #dde2e8;
--button-bg-hover-1: #ffffff;
--button-bg-hover-2: #e7ecf1;
--row-hover: #cfe4fb;
--client-text: #333;
--self-text: #0b5fa5;
--log-bg: #f7f8f9;
--log-text: #333;
--log-error: #b3261e;
display: flex;
flex-direction: column;
height: 100vh;
background: var(--bg);
color: var(--text);
color-scheme: light;
}
.ts-app.ts-theme-dark {
--bg: #1e1f22;
--bg-toolbar-1: #2b2d31;
--bg-toolbar-2: #232428;
--border: #3a3c42;
--border-soft: #35373d;
--text: #e3e5e8;
--text-muted: #9a9ca1;
--accent: #9db4d1;
--input-bg: #313338;
--input-text: #e3e5e8;
--button-bg-1: #3a3c42;
--button-bg-2: #2b2d31;
--button-bg-hover-1: #45474e;
--button-bg-hover-2: #35373d;
--row-hover: #35404d;
--client-text: #d5d7db;
--self-text: #7db2f0;
--log-bg: #202124;
--log-text: #c7c9cc;
--log-error: #f2867a;
color-scheme: dark;
}
/* Toolbar */
.ts-toolbar {
display: flex;
align-items: center;
gap: 1.5rem;
padding: 0.4rem 0.75rem;
background: linear-gradient(to bottom, var(--bg-toolbar-1), var(--bg-toolbar-2));
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.ts-app-title {
font-weight: 600;
color: var(--accent);
}
.ts-toolbar-fields {
display: flex;
align-items: center;
gap: 0.75rem;
}
.ts-toolbar-fields label {
display: flex;
align-items: center;
gap: 0.35rem;
color: var(--text);
}
.ts-toolbar-fields input:not([type="range"]) {
border: 1px solid var(--border);
border-radius: 2px;
padding: 0.15rem 0.4rem;
font-size: 12px;
background: var(--input-bg);
color: var(--input-text);
}
.ts-toolbar-fields input[type="range"] {
width: 80px;
}
.ts-toolbar-fields select {
border: 1px solid var(--border);
border-radius: 2px;
padding: 0.1rem 0.3rem;
font-size: 12px;
background: var(--input-bg);
color: var(--input-text);
max-width: 200px;
text-overflow: ellipsis;
}
.ts-toolbar-fields button {
max-width: 220px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ts-toolbar-fields button {
border: 1px solid var(--border);
border-radius: 3px;
background: linear-gradient(to bottom, var(--button-bg-1), var(--button-bg-2));
color: var(--text);
padding: 0.25rem 0.9rem;
cursor: pointer;
font-size: 12px;
}
.ts-toolbar-fields button:hover {
background: linear-gradient(to bottom, var(--button-bg-hover-1), var(--button-bg-hover-2));
}
.ts-theme-toggle {
padding: 0.2rem 0.5rem !important;
margin-left: auto;
}
/* Body / tree */
.ts-body {
flex: 1;
display: flex;
overflow: hidden;
background: var(--bg);
}
.ts-tree-panel {
width: 260px;
flex-shrink: 0;
overflow-y: auto;
padding: 0.4rem 0.5rem;
border-right: 1px solid var(--border-soft);
}
.ts-tree-empty {
color: var(--text-muted);
padding: 1rem;
font-style: italic;
}
.ts-tree-list {
list-style: none;
margin: 0;
padding-left: 1.1rem;
}
.ts-row {
display: flex;
align-items: center;
gap: 0.35rem;
padding: 1px 0.3rem;
border-radius: 2px;
white-space: nowrap;
line-height: 18px;
}
.ts-server-row {
font-weight: 600;
color: var(--accent);
padding-left: 0.3rem;
margin-bottom: 0.15rem;
}
.ts-channel-row {
cursor: pointer;
color: var(--text);
}
.ts-channel-row:hover {
background: var(--row-hover);
}
.ts-client-row {
color: var(--client-text);
padding-left: 0.65rem;
}
.ts-client-row.ts-self {
font-weight: 700;
color: var(--self-text);
}
.ts-client-row:not(.ts-self) {
cursor: pointer;
}
.ts-client-row:not(.ts-self):hover {
background: var(--row-hover);
}
.ts-client-row.ts-talking {
outline: 1px solid #4caf50;
border-radius: 2px;
background: color-mix(in srgb, #4caf50 15%, transparent);
}
.ts-mic-on {
background: color-mix(in srgb, #4caf50 30%, var(--button-bg-1)) !important;
}
/* Chat */
.ts-chat-panel {
flex: 1;
display: flex;
flex-direction: column;
min-width: 0;
}
.ts-chat-tabs {
flex-shrink: 0;
display: flex;
gap: 2px;
padding: 0.3rem 0.5rem 0;
border-bottom: 1px solid var(--border-soft);
overflow-x: auto;
}
.ts-chat-tab {
display: flex;
align-items: center;
gap: 0.4rem;
border: 1px solid var(--border-soft);
border-bottom: none;
border-radius: 3px 3px 0 0;
background: var(--bg-toolbar-1);
color: var(--text-muted);
padding: 0.25rem 0.6rem;
cursor: pointer;
font-size: 12px;
white-space: nowrap;
}
.ts-chat-tab-active {
background: var(--bg);
color: var(--text);
font-weight: 600;
}
.ts-chat-tab-unread:not(.ts-chat-tab-active) {
color: var(--self-text);
font-weight: 600;
}
.ts-chat-tab-close {
color: var(--text-muted);
padding: 0 0.15rem;
}
.ts-chat-tab-close:hover {
color: var(--log-error);
}
.ts-chat-messages {
flex: 1;
overflow-y: auto;
padding: 0.5rem 0.75rem;
}
.ts-chat-line {
padding: 1px 0;
word-break: break-word;
}
.ts-chat-from {
font-weight: 600;
color: var(--accent);
}
.ts-chat-input-row {
flex-shrink: 0;
display: flex;
gap: 0.4rem;
padding: 0.4rem 0.6rem;
border-top: 1px solid var(--border-soft);
}
.ts-chat-input-row input {
flex: 1;
border: 1px solid var(--border);
border-radius: 2px;
padding: 0.3rem 0.5rem;
font-size: 12px;
background: var(--input-bg);
color: var(--input-text);
}
.ts-chat-input-row button {
border: 1px solid var(--border);
border-radius: 3px;
background: linear-gradient(to bottom, var(--button-bg-1), var(--button-bg-2));
color: var(--text);
padding: 0.2rem 0.9rem;
cursor: pointer;
font-size: 12px;
}
/* Log */
.ts-log {
flex-shrink: 0;
max-height: 6.5rem;
overflow-y: auto;
border-top: 1px solid var(--border-soft);
background: var(--log-bg);
padding: 0.3rem 0.6rem;
font-family: ui-monospace, Consolas, monospace;
font-size: 11px;
}
.ts-log-info {
color: var(--log-text);
}
.ts-log-error {
color: var(--log-error);
}
+563
View File
@@ -0,0 +1,563 @@
import { useEffect, useRef, useState } from "react";
import "./App.css";
import {
AudioPlayer,
MicCapture,
SAMPLE_RATE,
hasNativeOutputPicker,
listAudioOutputDevices,
pickAudioOutputDevice,
setAudioOutputDevice,
} from "./voice";
const GATEWAY_URL = "ws://localhost:8080";
type LogEntry = { text: string; kind: "info" | "error" };
interface ChannelInfo {
id: number;
parent: number;
order: number;
name: string;
}
interface ClientInfo {
id: number;
channel: number;
name: string;
}
function ChannelIcon() {
return (
<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">
<path
d="M1.5 3.5c0-.55.45-1 1-1h3.4l1.2 1.4h6.4c.55 0 1 .45 1 1v7.1c0 .55-.45 1-1 1h-11c-.55 0-1-.45-1-1v-8.5Z"
fill="#e8c46a"
stroke="#b8923f"
strokeWidth="0.6"
/>
</svg>
);
}
function ClientIcon() {
return (
<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true">
<circle cx="8" cy="5.2" r="3" fill="#6d8fb0" />
<path d="M2 14c0-3.3 2.7-5.2 6-5.2s6 1.9 6 5.2v.3H2V14Z" fill="#6d8fb0" />
<circle cx="12.3" cy="12.3" r="2.6" fill="#4caf50" stroke="#fff" strokeWidth="0.8" />
</svg>
);
}
function ServerIcon() {
return (
<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">
<rect x="1.5" y="2" width="13" height="4.2" rx="0.6" fill="#7a8a99" stroke="#5c6b78" strokeWidth="0.5" />
<rect x="1.5" y="7" width="13" height="4.2" rx="0.6" fill="#8a9aab" stroke="#5c6b78" strokeWidth="0.5" />
<circle cx="3.5" cy="4.1" r="0.6" fill="#4caf50" />
<circle cx="3.5" cy="9.1" r="0.6" fill="#4caf50" />
</svg>
);
}
function ChannelTree({
channels,
clients,
parent,
ownClientId,
talkers,
onSelectChannel,
onOpenPrivateChat,
}: {
channels: ChannelInfo[];
clients: ClientInfo[];
parent: number;
ownClientId: number | null;
talkers: Set<number>;
onSelectChannel: (channelId: number) => void;
onOpenPrivateChat: (clientId: number, clientName: string) => void;
}) {
const children = channels.filter((c) => c.parent === parent).sort((a, b) => a.order - b.order);
if (children.length === 0) return null;
return (
<ul className="ts-tree-list">
{children.map((channel) => (
<li key={channel.id}>
<div className="ts-row ts-channel-row" onClick={() => onSelectChannel(channel.id)}>
<ChannelIcon />
<span>{channel.name}</span>
</div>
<ul className="ts-tree-list">
{clients
.filter((c) => c.channel === channel.id)
.map((c) => (
<li key={c.id}>
<div
className={`ts-row ts-client-row${c.id === ownClientId ? " ts-self" : ""}${
talkers.has(c.id) ? " ts-talking" : ""
}`}
onClick={c.id === ownClientId ? undefined : () => onOpenPrivateChat(c.id, c.name)}
title={c.id === ownClientId ? undefined : `Private chat with ${c.name}`}
>
<ClientIcon />
<span>{c.name}</span>
</div>
</li>
))}
</ul>
<ChannelTree
channels={channels}
clients={clients}
parent={channel.id}
ownClientId={ownClientId}
talkers={talkers}
onSelectChannel={onSelectChannel}
onOpenPrivateChat={onOpenPrivateChat}
/>
</li>
))}
</ul>
);
}
interface ChatEntry {
from: string;
message: string;
}
interface PmMessage {
fromSelf: boolean;
message: string;
}
interface PmThread {
partnerId: number;
partnerName: string;
messages: PmMessage[];
unread: boolean;
}
type ActiveTab = "channel" | "server" | number;
function App() {
const [host, setHost] = useState("localhost");
const [nickname, setNickname] = useState("Claude Code");
const [log, setLog] = useState<LogEntry[]>([]);
const [connected, setConnected] = useState(false);
const [channels, setChannels] = useState<ChannelInfo[]>([]);
const [clients, setClients] = useState<ClientInfo[]>([]);
const [chat, setChat] = useState<ChatEntry[]>([]);
const [serverChat, setServerChat] = useState<ChatEntry[]>([]);
const [chatInput, setChatInput] = useState("");
const [pmThreads, setPmThreads] = useState<Record<number, PmThread>>({});
const [activeTab, setActiveTab] = useState<ActiveTab>("channel");
const [theme, setTheme] = useState<"light" | "dark">(() =>
window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light"
);
const [micOn, setMicOn] = useState(false);
const [talkers, setTalkers] = useState<Set<number>>(new Set());
const [selfActive, setSelfActive] = useState(false);
const [vadThreshold, setVadThreshold] = useState(0.02);
const [outputDevices, setOutputDevices] = useState<MediaDeviceInfo[]>([]);
const [outputDeviceId, setOutputDeviceId] = useState("");
const [outputDeviceLabel, setOutputDeviceLabel] = useState("System default");
const socketRef = useRef<WebSocket | null>(null);
const chatEndRef = useRef<HTMLDivElement | null>(null);
const audioContextRef = useRef<AudioContext | null>(null);
const audioPlayerRef = useRef<AudioPlayer | null>(null);
const micCaptureRef = useRef<MicCapture | null>(null);
const activeTabRef = useRef<ActiveTab>("channel");
useEffect(() => {
chatEndRef.current?.scrollIntoView({ block: "nearest" });
}, [chat, serverChat, pmThreads, activeTab]);
useEffect(() => {
if (micCaptureRef.current) micCaptureRef.current.threshold = vadThreshold;
}, [vadThreshold]);
useEffect(() => {
activeTabRef.current = activeTab;
if (activeTab !== "channel") {
setPmThreads((prev) => {
const thread = prev[activeTab];
if (!thread || !thread.unread) return prev;
return { ...prev, [activeTab]: { ...thread, unread: false } };
});
}
}, [activeTab]);
const refreshOutputDevices = async () => {
try {
const devices = await listAudioOutputDevices();
setOutputDevices(devices);
} catch {
// Device labels/enumeration may be unavailable before mic permission is granted.
}
};
useEffect(() => {
navigator.mediaDevices?.addEventListener?.("devicechange", refreshOutputDevices);
return () => navigator.mediaDevices?.removeEventListener?.("devicechange", refreshOutputDevices);
}, []);
useEffect(() => {
return () => socketRef.current?.close();
}, []);
const appendLog = (entry: LogEntry) => setLog((prev) => [...prev, entry]);
const stopMic = () => {
micCaptureRef.current?.stop();
micCaptureRef.current = null;
setMicOn(false);
setSelfActive(false);
};
const handleConnect = () => {
const audioContext = new AudioContext({ sampleRate: SAMPLE_RATE });
audioContextRef.current = audioContext;
audioPlayerRef.current = new AudioPlayer(audioContext);
const socket = new WebSocket(GATEWAY_URL);
socketRef.current = socket;
socket.onopen = () => {
socket.send(JSON.stringify({ type: "connect", host, nickname }));
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
switch (data.type) {
case "connected":
setConnected(true);
setServerChat((prev) => [...prev, { from: "Server", message: data.welcomeMessage }]);
break;
case "channels":
setChannels(data.channels);
setClients(data.clients);
break;
case "chatMessage":
setChat((prev) => [...prev, { from: data.from, message: data.message }]);
break;
case "serverMessage":
setServerChat((prev) => [...prev, { from: data.from, message: data.message }]);
break;
case "privateMessage":
setPmThreads((prev) => {
const existing = prev[data.partnerId];
const thread: PmThread = existing ?? {
partnerId: data.partnerId,
partnerName: data.partnerName,
messages: [],
unread: false,
};
return {
...prev,
[data.partnerId]: {
...thread,
partnerName: data.partnerName,
messages: [...thread.messages, { fromSelf: data.fromSelf, message: data.message }],
unread: thread.unread || (!data.fromSelf && activeTabRef.current !== data.partnerId),
},
};
});
break;
case "audioOut":
audioPlayerRef.current?.playFrame(data.pcm);
break;
case "talkers":
setTalkers(new Set<number>(data.clients));
break;
case "disconnected":
setConnected(false);
setChannels([]);
setClients([]);
setChat([]);
setServerChat([]);
setPmThreads({});
setActiveTab("channel");
setTalkers(new Set());
stopMic();
appendLog({ text: `Disconnected: ${data.reason}`, kind: "info" });
break;
case "error":
appendLog({ text: data.message, kind: "error" });
break;
}
};
socket.onerror = () => appendLog({ text: "WebSocket error (is the gateway running?)", kind: "error" });
socket.onclose = () => {
setConnected(false);
stopMic();
audioContextRef.current?.close();
audioContextRef.current = null;
audioPlayerRef.current = null;
};
};
const handleDisconnect = () => socketRef.current?.close();
const handleToggleMic = async () => {
if (micOn) {
stopMic();
return;
}
const audioContext = audioContextRef.current;
if (!audioContext) return;
try {
const mic = new MicCapture(
audioContext,
(pcm) => socketRef.current?.send(JSON.stringify({ type: "sendAudio", pcm })),
(active) => setSelfActive(active),
vadThreshold
);
await mic.start();
micCaptureRef.current = mic;
setMicOn(true);
refreshOutputDevices();
} catch (error) {
appendLog({ text: `Microphone error: ${(error as Error).message}`, kind: "error" });
}
};
const handleOutputDeviceChange = async (deviceId: string, label?: string) => {
setOutputDeviceId(deviceId);
setOutputDeviceLabel(label || (deviceId ? `Output ${deviceId.slice(0, 6)}` : "System default"));
if (audioContextRef.current) await setAudioOutputDevice(audioContextRef.current, deviceId);
};
const handlePickOutputDevice = async () => {
try {
const device = await pickAudioOutputDevice();
if (device) await handleOutputDeviceChange(device.deviceId, device.label);
} catch (error) {
appendLog({ text: `Output device error: ${(error as Error).message}`, kind: "error" });
}
};
const handleSelectChannel = (channelId: number) => {
socketRef.current?.send(JSON.stringify({ type: "switchChannel", channelId }));
};
const handleSendChat = () => {
const message = chatInput.trim();
if (!message) return;
if (activeTab === "channel") {
socketRef.current?.send(JSON.stringify({ type: "sendChatMessage", message }));
} else if (activeTab === "server") {
socketRef.current?.send(JSON.stringify({ type: "sendServerMessage", message }));
} else {
socketRef.current?.send(JSON.stringify({ type: "sendPrivateMessage", clientId: activeTab, message }));
}
setChatInput("");
};
const handleOpenPrivateChat = (clientId: number, clientName: string) => {
setPmThreads((prev) => ({
...prev,
[clientId]: prev[clientId] ?? { partnerId: clientId, partnerName: clientName, messages: [], unread: false },
}));
setActiveTab(clientId);
};
const handleClosePrivateChat = (clientId: number) => {
setPmThreads((prev) => {
const next = { ...prev };
delete next[clientId];
return next;
});
setActiveTab((current) => (current === clientId ? "channel" : current));
};
const ownClient = clients.find((c) => c.name === nickname) ?? null;
const displayTalkers =
selfActive && ownClient ? new Set(talkers).add(ownClient.id) : talkers;
return (
<div className={`ts-app ts-theme-${theme}`}>
<div className="ts-toolbar">
<span className="ts-app-title">TS Web Client</span>
<div className="ts-toolbar-fields">
<label>
Server
<input value={host} onChange={(e) => setHost(e.target.value)} disabled={connected} />
</label>
<label>
Nickname
<input value={nickname} onChange={(e) => setNickname(e.target.value)} disabled={connected} />
</label>
{!connected ? (
<button onClick={handleConnect}>Connect</button>
) : (
<button onClick={handleDisconnect}>Disconnect</button>
)}
<button
className={micOn ? "ts-mic-on" : undefined}
onClick={handleToggleMic}
disabled={!connected}
title={micOn ? "Voice activation on - click to mute" : "Enable microphone (voice activation)"}
>
{micOn ? "🎤" : "🔇"}
</button>
<label title="Voice activation sensitivity">
🎚️
<input
type="range"
min={0.002}
max={0.15}
step={0.002}
value={vadThreshold}
onChange={(e) => setVadThreshold(Number(e.target.value))}
/>
</label>
{hasNativeOutputPicker() ? (
<button onClick={handlePickOutputDevice} title="Choose output device">
🔊 {outputDeviceLabel}
</button>
) : (
<label>
🔊
<select
value={outputDeviceId}
onChange={(e) => handleOutputDeviceChange(e.target.value)}
onFocus={refreshOutputDevices}
>
<option value="">System default</option>
{outputDevices.map((d) => (
<option key={d.deviceId} value={d.deviceId}>
{d.label || `Output ${d.deviceId.slice(0, 6)}`}
</option>
))}
</select>
</label>
)}
<button
className="ts-theme-toggle"
onClick={() => setTheme((t) => (t === "dark" ? "light" : "dark"))}
title="Toggle theme"
>
{theme === "dark" ? "☀️" : "🌙"}
</button>
</div>
</div>
<div className="ts-body">
<div className="ts-tree-panel">
{connected ? (
<>
<div className="ts-row ts-server-row">
<ServerIcon />
<span>{host}</span>
</div>
<ChannelTree
channels={channels}
clients={clients}
parent={0}
ownClientId={ownClient?.id ?? null}
talkers={displayTalkers}
onSelectChannel={handleSelectChannel}
onOpenPrivateChat={handleOpenPrivateChat}
/>
</>
) : (
<div className="ts-tree-empty">Not connected</div>
)}
</div>
<div className="ts-chat-panel">
<div className="ts-chat-tabs">
<button
className={`ts-chat-tab${activeTab === "server" ? " ts-chat-tab-active" : ""}`}
onClick={() => setActiveTab("server")}
>
Server
</button>
<button
className={`ts-chat-tab${activeTab === "channel" ? " ts-chat-tab-active" : ""}`}
onClick={() => setActiveTab("channel")}
>
Channel
</button>
{Object.values(pmThreads).map((thread) => (
<button
key={thread.partnerId}
className={`ts-chat-tab${activeTab === thread.partnerId ? " ts-chat-tab-active" : ""}${
thread.unread ? " ts-chat-tab-unread" : ""
}`}
onClick={() => setActiveTab(thread.partnerId)}
>
{thread.partnerName}
<span
className="ts-chat-tab-close"
onClick={(e) => {
e.stopPropagation();
handleClosePrivateChat(thread.partnerId);
}}
>
×
</span>
</button>
))}
</div>
<div className="ts-chat-messages">
{activeTab === "channel"
? chat.map((entry, i) => (
<div key={i} className="ts-chat-line">
<span className="ts-chat-from">{entry.from}:</span> <span>{entry.message}</span>
</div>
))
: activeTab === "server"
? serverChat.map((entry, i) => (
<div key={i} className="ts-chat-line">
<span className="ts-chat-from">{entry.from}:</span> <span>{entry.message}</span>
</div>
))
: pmThreads[activeTab]?.messages.map((entry, i) => (
<div key={i} className="ts-chat-line">
<span className="ts-chat-from">
{entry.fromSelf ? "You" : pmThreads[activeTab].partnerName}:
</span>{" "}
<span>{entry.message}</span>
</div>
))}
<div ref={chatEndRef} />
</div>
<div className="ts-chat-input-row">
<input
value={chatInput}
onChange={(e) => setChatInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleSendChat()}
disabled={!connected}
placeholder={
!connected
? "Not connected"
: activeTab === "channel"
? "Message channel..."
: activeTab === "server"
? "Message server..."
: `Message ${pmThreads[activeTab]?.partnerName}...`
}
/>
<button onClick={handleSendChat} disabled={!connected}>
Send
</button>
</div>
</div>
</div>
<div className="ts-log">
{log.map((entry, i) => (
<div key={i} className={entry.kind === "error" ? "ts-log-error" : "ts-log-info"}>
{entry.text}
</div>
))}
</div>
</div>
);
}
export default App;
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="77" height="47" fill="none" aria-labelledby="vite-logo-title" viewBox="0 0 77 47"><title id="vite-logo-title">Vite</title><style>.parenthesis{fill:#000}@media (prefers-color-scheme:dark){.parenthesis{fill:#fff}}</style><path fill="#9135ff" d="M40.151 45.71c-.663.844-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.493c-.92 0-1.457-1.04-.92-1.788l7.479-10.471c1.07-1.498 0-3.578-1.842-3.578H15.443c-.92 0-1.456-1.04-.92-1.788l9.696-13.576c.213-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.472c-1.07 1.497 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.087.89 1.83L40.153 45.712z"/><mask id="a" width="48" height="47" x="14" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M40.047 45.71c-.663.843-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.389c-.92 0-1.457-1.04-.92-1.788l7.479-10.472c1.07-1.497 0-3.578-1.842-3.578H15.34c-.92 0-1.456-1.04-.92-1.788l9.696-13.575c.213-.297.556-.474.92-.474H53.93c.92 0 1.456 1.04.92 1.788L47.37 13.03c-1.07 1.498 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.088.89 1.831L40.049 45.712z"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#eee6ff" rx="5.508" ry="14.704" transform="rotate(269.814 20.96 11.29)scale(-1 1)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#eee6ff" rx="10.399" ry="29.851" transform="rotate(89.814 -16.902 -8.275)scale(1 -1)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#8900ff" rx="5.508" ry="30.487" transform="rotate(89.814 -19.197 -7.127)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.928 4.177)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.738 5.52)scale(1 -1)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#eee6ff" rx="14.072" ry="22.078" transform="rotate(93.35 31.245 55.578)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx="14.592" cy="9.743" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(39.51 14.592 9.743)"/></g><g filter="url(#k)"><ellipse cx="61.728" cy="-5.321" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 61.728 -5.32)"/></g><g filter="url(#l)"><ellipse cx="55.618" cy="7.104" fill="#00c2ff" rx="5.971" ry="9.665" transform="rotate(37.892 55.618 7.104)"/></g><g filter="url(#m)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#n)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#o)"><ellipse cx="49.857" cy="30.678" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 49.857 30.678)"/></g><g filter="url(#p)"><ellipse cx="52.623" cy="33.171" fill="#00c2ff" rx="5.971" ry="15.297" transform="rotate(37.892 52.623 33.17)"/></g></g><path d="M6.919 0c-9.198 13.166-9.252 33.575 0 46.789h6.215c-9.25-13.214-9.196-33.623 0-46.789zm62.424 0h-6.215c9.198 13.166 9.252 33.575 0 46.789h6.215c9.25-13.214 9.196-33.623 0-46.789" class="parenthesis"/><defs><filter id="b" width="60.045" height="41.654" x="-5.564" y="16.92" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-40.407" y="-6.762" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="d" width="79.355" height="29.4" x="-35.435" y="2.801" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="e" width="79.579" height="29.4" x="-30.84" y="20.8" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="f" width="79.579" height="29.4" x="-29.307" y="21.949" color-interpolation-filters="sRGB" filterUnits="usLine truncated

After

Width:  |  Height:  |  Size: 8.5 KiB

+22
View File
@@ -0,0 +1,22 @@
:root {
color-scheme: light dark;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
height: 100%;
}
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
font-size: 13px;
}
#root {
height: 100vh;
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
+190
View File
@@ -0,0 +1,190 @@
// Encoding/decoding and Web Audio plumbing for the voice feature.
//
// The connector always speaks 48kHz PCM in 20ms frames: mono for the
// microphone -> server direction (which it Opus-encodes), stereo mixed
// for the server -> speakers direction (already decoded/mixed for us).
export const SAMPLE_RATE = 48000;
export const FRAME_SAMPLES = 960; // 20ms @ 48kHz
function int16ToBase64(samples: Int16Array): string {
const bytes = new Uint8Array(samples.buffer, samples.byteOffset, samples.byteLength);
let binary = "";
const chunkSize = 0x8000;
for (let i = 0; i < bytes.length; i += chunkSize) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
}
return btoa(binary);
}
function base64ToInt16(b64: string): Int16Array {
const binary = atob(b64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return new Int16Array(bytes.buffer);
}
/** How long transmission continues after the level drops back below the threshold, so words aren't clipped. */
const VAD_HANGOVER_SECONDS = 0.4;
/**
* Captures the microphone and emits base64-encoded mono 16-bit PCM frames.
*
* Uses voice activation (like TeamSpeak's own "Sprachaktivierung"): frames are
* only sent while the input level is above `threshold`, plus a short hangover
* so the tail of a word isn't cut off. `onActivity` reports transitions so the
* UI can show a local "currently transmitting" indicator.
*/
export class MicCapture {
private stream: MediaStream | null = null;
private source: MediaStreamAudioSourceNode | null = null;
private processor: ScriptProcessorNode | null = null;
private silence: GainNode | null = null;
private pending: number[] = [];
private active = false;
private activeUntil = 0;
threshold: number;
constructor(
private context: AudioContext,
private onFrame: (base64Pcm: string) => void,
private onActivity?: (active: boolean) => void,
threshold = 0.02
) {
this.threshold = threshold;
}
async start(): Promise<void> {
this.stream = await navigator.mediaDevices.getUserMedia({
audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true },
});
this.source = this.context.createMediaStreamSource(this.stream);
this.processor = this.context.createScriptProcessor(2048, 1, 1);
this.processor.onaudioprocess = (event) => {
const input = event.inputBuffer.getChannelData(0);
let sumSquares = 0;
for (let i = 0; i < input.length; i++) sumSquares += input[i] * input[i];
const rms = Math.sqrt(sumSquares / input.length);
const now = this.context.currentTime;
if (rms >= this.threshold) this.activeUntil = now + VAD_HANGOVER_SECONDS;
const shouldBeActive = now < this.activeUntil;
if (shouldBeActive !== this.active) {
this.active = shouldBeActive;
this.onActivity?.(this.active);
if (!this.active) this.pending = [];
}
if (!this.active) return;
for (let i = 0; i < input.length; i++) this.pending.push(input[i]);
while (this.pending.length >= FRAME_SAMPLES) {
const frame = this.pending.splice(0, FRAME_SAMPLES);
const int16 = new Int16Array(FRAME_SAMPLES);
for (let i = 0; i < FRAME_SAMPLES; i++) {
const clamped = Math.max(-1, Math.min(1, frame[i]));
int16[i] = clamped < 0 ? clamped * 32768 : clamped * 32767;
}
this.onFrame(int16ToBase64(int16));
}
};
// A ScriptProcessorNode only fires while connected to a destination; route
// it through a muted gain node so we don't hear our own mic echoed back.
this.silence = this.context.createGain();
this.silence.gain.value = 0;
this.source.connect(this.processor);
this.processor.connect(this.silence);
this.silence.connect(this.context.destination);
}
stop(): void {
this.processor?.disconnect();
this.silence?.disconnect();
this.source?.disconnect();
this.stream?.getTracks().forEach((t) => t.stop());
this.processor = null;
this.silence = null;
this.source = null;
this.stream = null;
this.pending = [];
if (this.active) {
this.active = false;
this.onActivity?.(false);
}
}
}
/** Output ("audiooutput") devices available for playback, e.g. for a device picker. */
export async function listAudioOutputDevices(): Promise<MediaDeviceInfo[]> {
const devices = await navigator.mediaDevices.enumerateDevices();
return devices.filter((d) => d.kind === "audiooutput");
}
type MediaDevicesWithPicker = MediaDevices & { selectAudioOutput?: () => Promise<MediaDeviceInfo> };
/** Whether the browser supports the native OS output-device picker (Chrome/Edge 105+). */
export function hasNativeOutputPicker(): boolean {
return typeof (navigator.mediaDevices as MediaDevicesWithPicker).selectAudioOutput === "function";
}
/**
* Opens the browser's native OS device chooser for audio output. Unlike
* `enumerateDevices()`, this lists every device the OS knows about (including
* ones like a USB headset that plain enumeration can otherwise omit) and asks
* the user to pick one, each call - no persistent listing to keep in sync.
*/
export async function pickAudioOutputDevice(): Promise<MediaDeviceInfo | null> {
const md = navigator.mediaDevices as MediaDevicesWithPicker;
if (typeof md.selectAudioOutput !== "function") return null;
return md.selectAudioOutput();
}
/**
* Routes an AudioContext's output to a specific device (empty string = system default).
* `setSinkId` on AudioContext is a fairly recent addition (Chrome 110+); older
* browsers simply keep using the system default output.
*/
export async function setAudioOutputDevice(context: AudioContext, deviceId: string): Promise<void> {
const ctx = context as AudioContext & { setSinkId?: (id: string) => Promise<void> };
if (typeof ctx.setSinkId !== "function") return;
await ctx.setSinkId(deviceId);
}
/** Schedules incoming base64-encoded stereo 16-bit PCM frames for gap-free playback. */
export class AudioPlayer {
private nextTime = 0;
constructor(private context: AudioContext) {}
playFrame(base64Pcm: string): void {
const int16 = base64ToInt16(base64Pcm);
const frames = int16.length / 2;
if (frames <= 0) return;
const buffer = this.context.createBuffer(2, frames, SAMPLE_RATE);
const left = buffer.getChannelData(0);
const right = buffer.getChannelData(1);
for (let i = 0; i < frames; i++) {
left[i] = int16[i * 2] / 32768;
right[i] = int16[i * 2 + 1] / 32768;
}
const source = this.context.createBufferSource();
source.buffer = buffer;
source.connect(this.context.destination);
const now = this.context.currentTime;
if (this.nextTime < now + 0.02) {
// First frame, or we fell behind - restart just ahead of now instead of
// letting a backlog build up.
this.nextTime = now + 0.02;
}
source.start(this.nextTime);
this.nextTime += frames / SAMPLE_RATE;
}
reset(): void {
this.nextTime = 0;
}
}
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"allowArbitraryExtensions": true,
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"module": "nodenext",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+7
View File
@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})