Remove Electron and make Rust Slint the sole native client

This commit is contained in:
bit9992 committed 2026-11-10 17:53:53 +03:00
1 parent eb24965076
commit 220852f8cb
720 files changed
+2535 -130856

No files matched your search

+103 -122
View File
@@ -1,17 +1,17 @@
# TeamsPeach core bridge — protocol v1
# TeamsPeach core contract — native API and diagnostic protocol v1
Contract between the Electron **main** process and the native protocol core
(`teamspeach-core`, Rust, built on ReSpeak tsclientlib). The renderer never talks
to the core directly: main forwards only the commands listed here, after checking
`cmd` against this allowlist and argument shapes.
The Rust/Slint application uses `runtime::spawn(CoreConfig)` and
`CoreHandle::request(Command)` in process. `native/src/app/connections.rs` owns session workers;
`native/src/app/runtime/` dispatches captured UI intents through native services. Shared Rust
validation rejects invalid command shapes and semantics without a JSON round trip. The standalone
`teamspeach-core` newline-JSON adapter is diagnostic/automation-only, not the desktop transport or a
browser-host fallback. The framing/process sections below describe that adapter only.
The Rust library also exposes `runtime::spawn(CoreConfig)` for native hosts. It owns a dedicated
current-thread runtime per session; `CoreHandle::request(Command)` applies the same semantic validation
as this JSON adapter. The returned control events and bounded playback PCM are separate channels;
native capture uses `CapturedFrame` with original timestamp, generation and privacy epoch. Explicit
`shutdown()` joins the worker and releases profile/slot locks; Drop requests cancellation without
blocking the UI. Control-consumer loss/overflow ends the session rather than silently dropping state.
The desktop reference still uses this stdio protocol until the full native cutover is verified.
The core owns a dedicated current-thread runtime per session. Control events and bounded playback PCM
use separate channels; native capture uses `CapturedFrame` with original timestamp, generation and
privacy epoch. Explicit `shutdown()` joins the worker and releases profile/slot locks; Drop requests
cancellation without blocking Slint. Control-consumer loss/overflow ends the session, never silently
drops authoritative state. UI attachment generations and media/session ownership remain separate.
Capture invalidation also guards the actual deferred UDP socket send through the pinned vendored
transport. Old/expired frames cannot become valid merely by remaining in a transport retry queue.
@@ -25,10 +25,10 @@ boundaries; callers must not perform their blocking joins or capture work on the
teamspeach-core --data-dir <ABSOLUTE_DIR> [--connection-dir <ABSOLUTE_DIR>]
```
- `--data-dir` is resolved and passed **only by main** (e.g. `<userData>/core`).
The core creates it if missing. A standalone core locks it exclusively. Multi-server main starts
one core per server, sharing the vault lock and exclusively locking each distinct connection dir.
A conflicting instance fails with exit code 3; connection IDs/epochs remain main-owned.
- `--data-dir` is an absolute path supplied by a trusted diagnostic caller, never server content or
an arbitrary UI field. Standalone ownership is exclusive; distinct connection directories share
the vault lock and hold separate slot locks. A conflicting instance fails with exit code 3.
The native application owns connection IDs/epochs and equivalent locks through in-process services.
- **stdin**: UTF-8, one JSON object per line (`\n`, `\r\n` tolerated). Max line **256 KiB**;
a longer line is discarded up to its newline and answered with an `error` event
`bad_request` (no `id` can be recovered).
@@ -37,8 +37,8 @@ teamspeach-core --data-dir <ABSOLUTE_DIR> [--connection-dir <ABSOLUTE_DIR>]
`TEAMSPEACH_LOG` (`error|warn|info|debug|trace`, tracing filter syntax), default `info`.
- **stdin EOF** or `shutdown` command → graceful disconnect (if connected), then exit 0.
- Exit codes: `0` clean, `2` bad CLI arguments, `3` data dir locked/unusable, `1` fatal internal error.
- Windows dev binary: `target/release/teamspeach-core.exe`
(debug: `target/debug/teamspeach-core.exe`, or explicit `CARGO_TARGET_DIR`). Packaged: `resources/core/teamspeach-core[.exe]`.
- Workspace diagnostic binary: `target/release/teamspeach-core[.exe]` (or `CARGO_TARGET_DIR`).
Native packages link the core library, not a required packaged core subprocess.
The first stdout line is always:
@@ -54,7 +54,7 @@ Request (stdin):
{"id":"r1","cmd":"connect","args":{"address":"10.10.10.160:9987"}}
```
- `id`: string, 1–64 chars, chosen by main; echoed in the response.
- `id`: string, 1–64 chars, chosen by the diagnostic caller; echoed in the response.
Required for every command **except** `audio_frame` and `audio_end`
(high-rate, never answered; an `id` there is ignored).
- `cmd`: one of the commands in §4. Unknown `cmd` → `unknown_command`.
@@ -88,7 +88,7 @@ permission → `{"id":2568,"name":"PermissionsClientInsufficient","missing_permi
`detail` carries structured extra state where stated (e.g. `rename`).
Repository-authored `message` text and stderr diagnostics are English technical details, not UI
translation keys. The renderer selects a localized explanation by stable `code` and may append the
translation keys. The UI selects a localized explanation by stable `code` and may append the
technical detail. Do not translate protocol tokens, server-supplied text or user content, and do not
branch on human-readable message wording.
@@ -98,7 +98,7 @@ branch on human-readable message wording.
| `unknown_command` | `cmd` not in allowlist |
| `profile_missing` | no identity yet → call `profile_create` |
| `profile_exists` | `profile_create` when an identity already exists (never overwritten) |
| `identity_corrupt` | identity file unreadable/invalid/UID mismatch. Core **never** regenerates; user/main must resolve (restore backup / import) |
| `identity_corrupt` | identity file unreadable/invalid/UID mismatch. Core **never** regenerates; user/native service must resolve (restore backup / import) |
| `profile_corrupt` | profile (nickname) file unreadable/invalid |
| `invalid_nickname` | nickname rule violated (§4.3) |
| `nickname_required` | identity exists but no nickname saved (connect refused) |
@@ -116,7 +116,7 @@ branch on human-readable message wording.
| `target_changed` | private message/client target disappeared or numeric ID now refers to a different UID |
| `media_too_large` | file exceeds the size limit of its kind (§4.17) |
| `media_unsupported` | file is not a recognized image, or a banner reference the core cannot fetch |
| `external_media` | banner or avatar lives at an `https://` URL (`detail.url` for banners, `detail.urls` for avatars); main may fetch it itself |
| `external_media` | banner or avatar lives at an `https://` URL (`detail.url` for banners, `detail.urls` for avatars); native service may fetch it itself |
| `io` | data dir I/O failure |
| `internal` | bug; message has details |
@@ -182,33 +182,19 @@ Emits `state: connecting`, then on success `snapshot`, `audio_state`, `state: co
then the response `{"ok":true,"result":{"own_client_id":7}}`. On failure the response is
`connect_failed` and `state: disconnected` with `reason`.
#### Desktop bookmark orchestration (Electron IPC, not native commands)
#### Native bookmark orchestration (not additional protocol commands)
Main resolves saved bookmarks before dispatching `connect`; the renderer never passes a saved password
as a native argument. These IPC handlers require the trusted application top frame:
- `bookmarks:password-state(id)` returns availability and saved/not-saved flags, never plaintext.
- `bookmarks:password-set(id, expectedAddress, kind, value)` saves or clears (`value: ""`) the server or
channel password. `kind` is `server` or `channel`; nonempty values use OS `safeStorage` encryption.
- `bookmarks:password-reveal(id, expectedAddress, kind)` returns plaintext only for an explicit Reveal
action. Changing the window, target or credential during native storage interaction invalidates it.
- `bookmarks:connect(connectionId, bookmarkId, startup)` reads current metadata and decrypts in main.
A failed decrypt/binding check stops the operation; it never substitutes an empty password. Automatic
startup with `auto_connect_muted` sends `set_audio {input_muted:true}` before `connect`, rechecking the
captured connection/session and bookmark after the acknowledgement. Output mute is never changed.
- `bookmarks:startup()` returns enabled bookmark metadata in tree order once per main-process lifetime.
Renderer reloads cannot issue a second startup batch. Offscreen runs return an empty list and refuse
bookmark connects with `test_safety` before dispatching a core command.
Passwords live only as `server_password_encrypted` / `channel_password_encrypted` in the atomic prefs
record. Each envelope binds its purpose and exact trimmed address. Generic prefs writes preserve the
current ciphertext for unchanged targets, clear it on address changes, and permit new-ID copies only
from a same-address bookmark. Clearing remains possible without an available key store. Linux
`basic_text`, unknown backends and legacy hardcoded-key `v10` ciphertext are rejected. Platform semantics:
[Electron safeStorage](https://www.electronjs.org/docs/latest/api/safe-storage); the legacy Linux format is
documented in [Chromium OSCrypt](https://chromium.googlesource.com/chromium/src/+/2d15a8eb787a31d5bbab0ff4a6a539a0df7c99dc/components/os_crypt/os_crypt_linux.cc).
Windows DPAPI does not protect against other software running as the same OS user. Actual keyring/Keychain
operation and portability are not established by Windows or simulated-backend tests.
`native/src/services/bookmarks.rs`, `secrets.rs` and `native/src/app/runtime/` resolve bookmarks
before `connect`. UI intents identify bookmarks/operations, not host paths or decryption commands.
State reads expose availability without plaintext; reveal requires an explicit action bound to the
exact bookmark, trimmed address and purpose. Platform secret storage has no plaintext fallback.
Historical Electron ciphertext is never reused: read-only profile import records password re-entry.
Canceling a password prompt sends no connect. Address changes invalidate credentials; clearing works
without an available key store. Delayed work rechecks connection/session/UI generation and binding.
Startup-muted waits for input-mute acknowledgement and never changes output mute. Enumeration is
ordered and not duplicated by UI reattachment. Isolated runs disable network/device/OS actions.
Generic prefs cannot forge credentials/grants; OS-user encryption is not a portable backup or protection
against every program running as that user. Platform hardware key-store acceptance remains separate.
### 4.5 `disconnect` — `{message?: string}`
@@ -242,10 +228,10 @@ Initial state at process start: both `false`.
One 20 ms microphone frame: base64 (standard alphabet, padded) of **960 signed
16-bit little-endian mono samples at 48 kHz = 1920 bytes** (2560 base64 chars).
In transmit mode `direct` (see 4.11) the renderer decides: it sends frames only while
push-to-talk is held or the open microphone is on, and `audio_end` when it stops; the core
sends every frame. In mode `vad` the renderer sends frames continuously while connected and
not muted, and the core's voice detector decides which are sent. The core Opus-encodes 20 ms
In transmit mode `direct` (see 4.11), native audio services forward frames only when allowed by
push-to-talk/open-microphone and privacy gates, ending the burst on stop. In mode `vad`, current
authorized capture/DSP frames pass to the core detector. The diagnostic adapter accepts the same PCM.
The core Opus-encodes 20 ms
frames with the **current channel's codec**: Opus Voice (mono) or Opus Music (stereo — the
mono frame is duplicated to both channels). Legacy Speex/CELT channels →
`audio_codec_unsupported` event and nothing is sent. Outgoing queue bound: 10 frames
@@ -255,11 +241,10 @@ Not connected → frames dropped with one `not_connected` error event per burst.
deafened, or not allowed to talk by the server → frames dropped with one `audio_muted` event
per burst; in mode `vad` the detector state and preroll are discarded as well.
Before IPC, the capture worklet stamps each frame's final sample with its own AudioContext
time. The engine drops messages older than 200 ms in that same clock; a busy renderer must
not replay a long MessagePort backlog. This is separate from the native queue bound and
does not shorten VAD's intentional 100–300 ms preroll. Normal delivery, DSP preferences,
privacy gates, native worklet shutdown and output/per-peer gains are unchanged.
Native capture timestamps blocks using their original capture clock. Expired frames drop and privacy
epochs are invalidated before deferred work/socket sends; a busy UI cannot replay a backlog. This is
separate from queue bounds and intentional VAD preroll. Device switches, capture stop, reconnect,
mute/deafen and whisper transitions revoke old work without making already queued frames valid again.
Channel quality `q` remains clamped to 0–10: Voice targets `8000 + 4000*q` bps with
`OPUS_APPLICATION_VOIP`; Music targets `24000 + 8000*q` bps with `OPUS_APPLICATION_AUDIO`.
@@ -269,20 +254,17 @@ that display code alone does not justify lowering encoder targets. Evidence and
source hash are in `docs/evidence/voice-official-source-20261029.json`. No real server's
bitrate cap was queried or changed in this offline audit.
`scripts/audit-voice-timed.mjs --seconds 190 --verify` captures only a licensed fake WAV
through real Chromium into PCM, disconnected and with sink `none`. `--stall --seconds 12
--verify` exercises a bounded 600 ms renderer stall; `--exe <path>` uses the guarded
packaged launcher. The ignored Rust test `captured_speech_quality_matrix` accepts
`TEAMSPEACH_AUDIT_PCM` and `TEAMSPEACH_AUDIT_OUT` and runs the real encoder/receiver at
qualities 0/6/10, both codecs, including a synthetic channel-context reset at 90 seconds.
Timed metrics are in `docs/evidence/voice-timed-20261029.json`. They do not establish
natural-microphone quality, proprietary DSP equivalence or native Linux/ARM behavior.
Historical timed metrics are in `docs/evidence/voice-timed-20261029.json`; the browser capture harness
has been removed. Retain the 600 ms consumer-stall acceptance case: discard expired PCM, never replay it.
The ignored Rust `captured_speech_quality_matrix` accepts `TEAMSPEACH_AUDIT_PCM` and
`TEAMSPEACH_AUDIT_OUT` for real encoding/receiving at quality 0/6/10, both codecs and a context reset.
File-fed/generated media does not prove natural microphone quality, private DSP identity or Asahi hardware.
### 4.10 `audio_end` — no args (no `id`, no response)
Ends the current transmission burst (core sends the TeamSpeak end-of-voice packet). In mode
`vad` it also discards the detector state and preroll (capture stopped or the renderer stopped
forwarding).
`vad` it also discards the detector state and preroll when capture or the native audio service stops
forwarding.
### 4.11 `set_transmit` — `{mode: "direct"|"vad", detector?: "automatic"|"volume_gate"|"hybrid", sensitivity?: "high"|"normal"|"low", level_db?: number}`
@@ -310,7 +292,7 @@ since it are held (at most 15 = 300 ms) and sent before the current one, later s
Detector, filter history and preroll are reset on `audio_end`, mute/deafen, disconnect, channel
or codec change, when the server does not allow talking, and on every `set_transmit` that
changes between `direct`/`vad` or to another detector: before answering such a change the core
discards frames still queued from the previous mode and ends any open burst, and the renderer
discards frames still queued from the previous mode and ends any open burst; the native audio service
forwards nothing until it has this answer. A `set_transmit` that only changes `sensitivity` or
`level_db` of the active detector (the user moving the VAD level slider) applies from the next
frame without discarding audio or ending the spurt.
@@ -321,7 +303,7 @@ Result `{"mode":"direct"}`, `{"mode":"vad","detector":"automatic","sensitivity":
### 4.11a `set_local_volumes` — `{replace: bool, volumes: [{uid: string, db: number}]}`
Persisted local per-user volume modifiers pushed by main (`app/main/client-volumes.js`): `uid`
Persisted local per-user volume modifiers are pushed by the native service: `uid`
is the client's base64 unique identifier (1–128 chars), `db` −200..=10 in 0.5 dB steps (−200 =
silence, gain 10^(dB/20)). `replace:true` swaps the whole map (sent whenever a core becomes
ready), `false` upserts; a 0 dB entry removes the UID. At most 4096 entries per request. The
@@ -368,7 +350,7 @@ Sends `streamsignaling id=<stream_id> clid=<client_id> json=<compact JSON of jso
Examples of `json`: `{"cmd":"answer","args":{"answer":"<sdp>"}}`,
`{"cmd":"iceCandidate","args":{"mLine":0,"mid":"0","sdp":"candidate:..."}}`.
Publisher ICE restart responses use `{"cmd":"reconnectOffer","args":{"offer":"<sdp>"}}`.
The renderer allowlist accepts only `answer`, `iceCandidate`, and `reconnectOffer`, not arbitrary signaling commands.
Shared core validation accepts only `answer`, `iceCandidate`, and `reconnectOffer`, never arbitrary signaling commands.
Max serialized `json` size 60 KiB (the whole stdin line is capped at 256 KiB). Result `{}` or `server_error`.
### 4.15 `stream_leave` — `{stream_id: string, client_id: number}`
@@ -393,13 +375,13 @@ unlimited), and `audio` is boolean, serialized as `1`/`0`.
`stream_respond.decision` is boolean; acceptance requires nonempty SDP (`offer`, max
60000 UTF-8 bytes); denial requires an empty offer. `message` is at most 200 characters.
Eviction reason `4` is the official `KICKED` enum and cannot be chosen by the renderer.
Eviction reason `4` is the official `KICKED` enum and cannot be chosen by the UI.
All commands use the existing escaped `OutCommand` and server-acknowledgement path;
they do not synthesize successful server responses. A successful setup command is
not the stream ID: wait for our `notifystreamstarted` notification. Stopping while
that notification is pending retains the session solely to unregister its late ID.
The renderer publisher owns one peer per authorized UID and source tracks, and
The native publisher owns one peer per authorized UID and source tracks, and
reconciles client-ID reuse on every snapshot. Selected participants are a **local
UID allowlist**, not myTeamSpeak contacts: this mode advertises public metadata
(`accessibility=1`) but never sends an offer/media to an unlisted UID. The stream may
@@ -417,11 +399,10 @@ this sender. SFU publication is unsupported, never relabeled P2P.
Evidence: `docs/evidence/ts6-publisher-native.json` (DLL hash and legacy argument
assembly addresses), `ts6-publisher-ui-enums.json` (official JS enums/limit logic),
and `ts6-official-client.md`. Static reverse engineering is not live server proof.
`node scripts/smoke-stream-publish.cjs --out <dir>` runs an always-hidden/offscreen
production publisher-to-viewer test using generated canvas and tone only; no capture
device or server is opened. Rust unit tests check exact serialization and the real
stdio smoke checks parser/dispatch rejection offline. A controlled TS6 server and
official viewer are still required for live interoperability verification.
Historical generated publisher/viewer checks used only synthetic canvas/tone and no server/device.
The removed browser harness is not a current command. Native tests/smoke must exercise production
peers, decoded video/audio and stop/cleanup. Serialization/validation or disconnected diagnostic
rejection is not controlled-server/official-viewer interoperability proof.
### 4.16 `shutdown` — no args
@@ -441,7 +422,7 @@ cross the bridge: the core derives the server file from ids it already knows.
Result: `{"mime":"image/png","bytes":108726,"data":"<base64>"}`. `mime` is sniffed from the
bytes (`image/png|jpeg|gif|webp|x-icon|svg+xml`); anything else → `media_unsupported`.
Render only via `<img>`/canvas (SVG included). Cache by `icon_id` / `avatar_hash` / URL.
Decode validated image bytes through the native image path, never execute SVG/markup. Cache by icon/avatar/URL identity.
- Icon ids 100, 200, 300, 500, 600 are TeamSpeak's default group icons that clients ship;
servers have no file for them (verified live for each: error 2054 `FileInvalidPath`), so
@@ -450,7 +431,7 @@ Render only via `<img>`/canvas (SVG included). Cache by `icon_id` / `avatar_hash
- Banners: `ts3image://<host>?port=<p>&channel=<cid>&path=<dir>&filename=<name>` references
are fetched from that channel's file area on the connected server (port must match;
`..`/backslashes/control characters rejected). `http(s)://` → `external_media` with
`detail.url` for main to fetch (untrusted URL).
`detail.url` for native service to fetch (untrusted URL).
- At most 3 transfers run at once (the rest queue); each has a 20 s deadline (`io` error).
Server refusals surface as `server_error` with `ts_error`.
@@ -477,7 +458,7 @@ are offered. Permission metadata is `{id,name,description}` from `permissionlist
hardcoded server-version-specific numeric table.
`client_action` always requires `{client_id,uid,generation,action,...}`. Unknown fields,
missing required values and invalid ranges are rejected in both IPC and Rust.
missing required values and invalid ranges are rejected by shared Rust command validation.
| action | additional fields | behavior |
|---|---|---|
@@ -507,17 +488,17 @@ the bridge request ID. Connection reads expose `connection_*` fields, not login
Avatar bytes upload through `ftinitupload /avatar`; only after TCP upload completion does
the core send `clientupdate client_flag_avatar=<MD5>`. Success requires the server's
command acknowledgement; file-transfer and command errors remain visible. Uploads have
a bounded deadline and are canceled on disconnect. File-transfer keys never cross IPC.
a bounded deadline and are canceled on disconnect. File-transfer keys never reach the UI.
Protocol mutation results are `{}` only after server acknowledgement. Server refusals
include the existing numeric `ts_error` and `missing_permission`; preflight hints cannot
override a server rejection. Destructive confirmations belong to the renderer.
override a server rejection. Destructive confirmations belong to the UI.
Tests use escaped protocol fixtures and disconnected subprocess requests, never real
participant kicks, bans or permission/group mutations.
### 4.19 Channel file browser: `file_list`, `file_mkdir`, `file_rename`, `file_delete`, `file_download`, `file_upload`, `file_cancel`, `file_transfers`, `file_fetch_image`
Legacy TeamSpeak file transfer (`ftgetfilelist`, `ftcreatedir`, `ftrenamefile`, `ftdeletefile`, `ftinitdownload`, `ftinitupload`, `ftstop`), implemented in `core/src/file_transfer.rs` and `core/src/files_session.rs`. Every command needs an established connection (`not_connected` otherwise) and a channel the client can see (`not_found`). The main-only snapshot exception permits `channel_id:0` for listing `/icons/` and transferring `/icons/icon_<u32 CRC32>`; renderer file operations still require a nonzero channel. `channel_password` is optional; it travels as base64(SHA-1), like tsclientlib's own transfers, and an empty one is sent as the bare `cpw` flag.
Legacy TeamSpeak file transfer (`ftgetfilelist`, `ftcreatedir`, `ftrenamefile`, `ftdeletefile`, `ftinitdownload`, `ftinitupload`, `ftstop`), implemented in `core/src/file_transfer.rs` and `core/src/files_session.rs`. Every command needs an established connection (`not_connected` otherwise) and a channel the client can see (`not_found`). The native service-only snapshot exception permits `channel_id:0` for listing `/icons/` and transferring `/icons/icon_<u32 CRC32>`; UI file operations still require a nonzero channel. `channel_password` is optional; it travels as base64(SHA-1), like tsclientlib's own transfers, and an empty one is sent as the bare `cpw` flag.
Remote paths are UTF-8, start with `/`, are at most 512 characters, and every component is non-empty, not `.` or `..`, and contains no control character or backslash. A folder path (`file_list`) is normalized to `/` or `/a/b/`. A file or folder path (`file_mkdir`, `file_rename`, `file_delete`, `file_download`, `file_upload`, `file_fetch_image`) has no trailing slash and is not the root.
@@ -545,7 +526,7 @@ Remote paths are UTF-8, start with `/`, are at most 512 characters, and every co
**`storage`** is `{capability_extensions, httpft, s3, supported}`. It is computed from `virtualserver_capability_extensions` (tapped from `initserver`/`notifyserverupdated`/`notifyserveredited`) using the official substring test. Known `HTTPFT` or `s3` advertisements cause every file operation except transfer inspection/cancellation to fail with `media_unsupported` and storage detail **before any legacy command or local disk side effect**. No UI override falls back to a different store. Unknown/unannounced capability flags retain legacy requests and authoritative server errors; they do not prove newer-storage support.
**`file_download` and `file_upload` carry host paths. Only the Electron main process sends them**, built from native dialog results (`app/main/files-main.js`). They are absent from the renderer allowlist.
**Host paths belong only at the trusted core boundary.** Native file services resolve session/purpose-owned chooser grants before constructing download/upload commands; UI fields cannot provide arbitrary paths.
- `dest_dir` is an absolute, existing folder.
- `subdirs` are created inside it, never through an existing non-directory or symlink.
- Every created name, and the downloaded file name, must be storable on every supported OS. Refused: `/ \ : * ? " < > |`, control characters, a trailing dot or space, and Windows device names such as `CON` or `COM1.txt`.
@@ -557,7 +538,7 @@ Remote paths are UTF-8, start with `/`, are at most 512 characters, and every co
- With `overwrite:false` a server-side "file already exists" (0x0802) fails the transfer with code `file_exists`.
**Transfers**
- Main allocates app-global directional slots (default two each, configurable combined maximum ten); at most 512 native records per connection.
- Native scheduling allocates app-global directional slots (combined maximum ten); at most 512 native records per connection.
- Transfer ids are bridge-visible `u32` values, unique per connection.
- Lifecycle: `queued` → `starting` (`ftinit*` sent) → `running` (stream granted) → [`confirming`, upload only] → `done` | `failed` | `cancelled`.
- A transfer fails with an explicit error in these cases:
@@ -578,7 +559,7 @@ Remote paths are UTF-8, start with `/`, are at most 512 characters, and every co
Not implemented (explicit limits):
- The TeamSpeak 6 `HTTPFT` and `s3` branches. Exact recovered constructor arguments, bounded RIP-relative/native-function continuation, and unresolved endpoint/payload semantics are in `docs/evidence/ts6-filetransfer-native.json` and `docs/evidence/ts6-filetransfer-native-continuation.json`. These are static interoperability evidence, not server acknowledgements.
- Resume/pause.
- Drag-and-drop upload, because the renderer never holds host paths.
- Drag-and-drop upload without a purpose-bound native resource grant.
### `file_transfer` (event)
@@ -586,30 +567,32 @@ Not implemented (explicit limits):
New error codes (§3): `file_exists` (target name exists and replacing it was not confirmed; `detail.name`), `transfer_cancelled`.
Main chooser APIs take the originating `connectionId`, capture its session epoch, and reject delayed chooser completion after a connection change. Renderer chooser and overwrite-confirmation continuations also capture/recheck the originating connection/session before starting an operation. Tokens remain opaque local-path capabilities; deliberate reuse is not prohibited. Offscreen tests use disposable-profile fixture paths and never invoke a native dialog or OS folder opener.
Native chooser and overwrite-confirmation continuations capture/recheck the originating SessionKey before use. Grants bind purpose and session; delayed/revoked results cannot start work on a replacement connection. Isolated tests use disposable resources without OS dialogs/folder opening.
Offline regression sources: `test/files-main.test.mjs`, `test/files-renderer.test.mjs`, and `core/src/file_transfer.rs` tests (real loopback TCP transferred bytes/hash, upload/download cancellation, Unicode, empty/short/conflicting files and deterministic cancellation/publication gate). Their existence is not an execution result; final QA records execution after the global freeze.
Native regression requirements include real loopback bytes/hash, cancellation, Unicode, empty/short/conflicting files and deterministic cancellation/publication gates in `core/src/file_transfer.rs` and native file services. Existence is not an execution result.
### File Transfer preferences and app-wide scheduling
Official source: installed `html/client_ui/main.js` module `87209` (`SettingsFileTransfer`). It reads singleton workflow settings `alwaysAskForDownload`, `ft_max_parallel_downloads/uploads`, and global native `getTransferSpeedLimit`/`setTransferSpeedLimit`/`updateConcurrentTransferLimits` calls without a connection ID. This supports app-global, not multiplied per-tab, semantics. Source control values: speed 1–25600 MiB/s with 0.5 steps; concurrency at least one each, combined at most ten.
Implemented main-owned `files-settings.json` persists `alwaysAsk`, `downloadSlots`, `uploadSlots`, rate toggles and remembered rate values, plus `approvedDownloadDir`. The absolute folder never comes from renderer arguments or generic preference updates: only an explicit main native chooser (or disposable-profile offscreen fixture) writes it. The renderer receives a display basename. Choosing/copying is user-invoked; clipboard and native dialogs are disabled in offscreen tests. An unavailable saved folder fails explicitly instead of switching destinations. If no folder has been approved yet, downloading still asks.
`native/src/services/file_settings.rs` persists prompt/slot/rate controls and an approved destination.
A displayed basename is not a chooser grant; only explicit native chooser work approves destinations.
Isolated runs disable OS dialogs/clipboard. Missing destinations fail explicitly; unset ones ask.
Reject unknown/out-of-range settings and retain truthful atomic-save failures. Native scheduling owns
app-wide reservations across sessions/snapshot work: delayed events cannot duplicate slots, lower limits
drain old work and reconnect discards stale records. Current native defaults/bounds are authoritative,
not a browser IPC compatibility layer.
IPC: `files:settings/get`, `files:settings/set`, `files:settings/choose-default`, `files:settings/copy-default`. Set accepts only public booleans/numeric controls; unknown fields and out-of-range values fail. Default: always ask, two uploads/two downloads, rate limits disabled, remembered rates 10 MiB/s. Updates persist via temporary-file rename.
`TransferScheduler` in `app/main/files-settings.js` tracks native transfer IDs across server cores and allocates directional start slots globally. Native queues retain progress and cancellation while waiting. Start reservations survive event latency, preventing transient duplicate slots. Lowering concurrency does not abort existing/reserved work; those transfers drain before new starts. Closed/reconnected sessions discard obsolete scheduler records. Snapshot upload/download requests pass the same broker.
Main-only native `file_config` accepts `{download_slots,upload_slots,download_limit,upload_limit}`. Slot zero pauses new starts; CLI/default core behavior remains two per direction until configured. Rates are integer bytes/second; zero means unlimited. Config requires a connected native session and is absent from the renderer command allowlist. Changing rates updates the shared pacing limiter for already-running transfers; no streams are restarted.
Service-owned `file_config` accepts `{download_slots,upload_slots,download_limit,upload_limit}`. Zero slots pauses new starts; unconfigured diagnostic cores use two per direction. Rates are integer bytes/second, zero unlimited. Connected native scheduling configures this internally; UI cannot bypass the broker. Changes update live pacing without restarting streams.
Each direction's global byte ceiling is divided conservatively across currently demanded server cores. Every stream in a core shares one async pacing mutex; each TCP read/write chunk acquires a pacing turn (up to 64 KiB). Config decreases apply before increases. The aggregate rate is not multiplied by tabs; bounded bursts are one chunk per participating core, and already-scheduled chunks finish under their prior pacing interval. Unused per-core bandwidth is not borrowed until allocation changes, so this is a conservative ceiling rather than a work-conserving bandwidth optimizer. Downloads with short reads may be slower than the configured maximum, never faster because of short-read accounting. These user file/snapshot transfer limits do not throttle unrelated cached icon/avatar preview fetches.
Regression sources: `test/files-main.test.mjs` covers persisted approved destinations and illegal renderer path injection; `test/files-settings.test.mjs` covers cross-core aggregate slots/rates, delayed events, drain-on-reduction and cancellation; `core/src/file_transfer.rs::tests::download_rate_limit_paces_real_bytes_and_can_be_disabled` streams and hashes real loopback TCP bytes and asserts pacing at 1 MiB/s. These tests are prepared; only final QA execution establishes pass status.
Regression requirements include approved-destination persistence, rejected UI path injection, aggregate slots/rates, delayed events, drain-on-reduction, cancellation and real-byte pacing in `core/src/file_transfer.rs`. Only exercised QA establishes a pass.
### 4.20 Server/channel administration
Every mutation below is answered only after its real server command result. Permission hints never manufacture success. Requests capture a server connection ID in main and its native `generation`; stale mutations fail. Read replies are `{rows:[wire-key/string-value objects]}`, not HTML. Only one reader per notification type is allowed in flight; over 10,000 rows fails rather than silently truncating. Empty database/permission-list replies become empty rows.
Every mutation below is answered only after its real server command result. Permission hints never manufacture success. Requests capture a server connection ID in native service and its native `generation`; stale mutations fail. Read replies are `{rows:[wire-key/string-value objects]}`, not HTML. Only one reader per notification type is allowed in flight; over 10,000 rows fails rather than silently truncating. Empty database/permission-list replies become empty rows.
`admin_context {}` returns `{generation,server_uid,own_client_id,catalog_received,permissions,permissions_catalog,permission_error?}`. Permissions are the official named hint values (null if unknown); catalog entries are `{id,name,description}`.
@@ -655,13 +638,15 @@ Every mutation below is answered only after its real server command result. Perm
| `server_group_add_client` | `{generation,group_id,client_database_id}` |
| `server_group_member_add_uid` | `{generation,group_id,uid}`; official TS6 `vsgroupassignbyids json={version:1,add:[…]}`; short UID uses `migration`, long UID `client_uid`, group ID string |
Property allowlists and exact bounds are `core/src/admin.rs` and `app/main/admin-validate.js`: no arbitrary wire fields. Channel passwords are SHA-1/base64 encoded and flag derived; codecs 0..5, quality 0..10; permanence flags mutually exclusive. Main exposes only safe JS integers. Snapshot import reports unrepresentable large integers rather than rounding them.
UI `admin.js` supplies Away/status controls, channel and server menus, information views, talk-power queue, changed-only channel/server edit forms, bans/keys/temporary passwords and database/log dialogs. Connection/session/generation are captured before asynchronous work. Destructive actions need explicit confirmation; failed acknowledgements keep the form and error. Database pages are 100 entries; log offsets are explicit. Local server-event history is separate from server log retrieval.
Property allowlists/bounds are shared Rust contracts in `core/src/admin.rs` and core validation, never
arbitrary wire fields. Password encoding, codec/quality bounds and exclusive permanence remain required;
large snapshot integers must not round. Native server-action/runtime services project menus/forms/views
with captured connection/session/generation, explicit destructive confirmation and retained errors/forms
on failed acknowledgements. Database pages are 100; log offsets explicit; local events are not server logs.
### 4.21 Client-built server JSON snapshots
Snapshot export/import is main-owned orchestration in `server-snapshots.js` / `server-snapshot-codec.js`, never a fictitious `serversnapshotcreate` or ServerQuery command. It uses ordinary commands above and confirmed local file dialogs. Exact official schema 0.0.1, options, remapping, confirmations and evidence: [ts6spec-snapshots.md](evidence/official-parity/ts6spec-snapshots.md). Server/channel settings, groups, named permissions, members and icons are independently selected. Import is non-atomic: cancellation and per-item/property errors preserve a truthful partial report, not rollback or complete success. Source-backed modern channel banners, SFU endpoint and storage quota are typed mutations; HTTP/S3 icon transfer failures remain explicit, not silently omitted content.
Native snapshot orchestration in `native/src/services/snapshots.rs` uses ordinary core commands and chooser grants, never fictitious `serversnapshotcreate`/ServerQuery. Schema 0.0.1, options/remapping/confirmations: [ts6spec-snapshots.md](evidence/official-parity/ts6spec-snapshots.md). Select settings/groups/permissions/members/icons independently. Non-atomic import retains truthful partial/cancellation/error reports, not rollback/full success. Typed banner/SFU/storage mutations do not imply HTTPFT/S3 icon support.
### 4.22 Whisper routes
@@ -688,7 +673,7 @@ Files (`<directory>/<label>[_N]/`): `NN <name>.wav` per track (48 kHz mono s16le
Signal paths: client tracks = each speaker's decoded audio before local volume (official: "individual tracks stay untouched"); capture = frames this connection actually encoded and sent (after mute/PTT/VAD); master = the local playback mix with local volumes plus the sent capture. A full disk queue (2 s) drops whole 20 ms ticks, counts them and pads them with silence so tracks stay aligned. Headers are refreshed every 2 s. TeamsPeach's file layout/format is its own; the official native format is not published.
Starting a second recorder while prior files finalize is refused. Dropped capture includes queued TX discarded on pause/stop; dropped tails are padded through declared timelines, empty master is a valid 44-byte WAV. Header-finalization errors keep finalized false, are recorded, and actual final file bytes are recomputed. Multitrack taps are pre-gain/pre-AGC; master is post-client-gain/AGC plus sent capture, not renderer device output gain.
Starting a second recorder while prior files finalize is refused. Dropped capture includes queued TX discarded on pause/stop; dropped tails are padded through declared timelines, empty master is a valid 44-byte WAV. Header-finalization errors keep finalized false, are recorded, and actual final file bytes are recomputed. Multitrack taps are pre-gain/pre-AGC; master is post-client-gain/AGC plus sent capture, not native device output gain.
## 5. Events
@@ -770,7 +755,7 @@ Full replacement of the server view, emitted after connect and after every chang
(`fetch_avatar`); otherwise `myts_avatars` (TeamSpeak 6 / myTeamSpeak,
`client_myteamspeak_avatar` = `<variant>,<https url>`; live: variant 2 on
`storage.googleapis.com/ts-sys-myts-avatars/…`, publicly readable without an account,
served as `Content-Type: text/plain` but PNG bytes → main must sniff, not trust the
served as `Content-Type: text/plain` but PNG bytes → native service must sniff, not trust the
header). Multiple pairs are accepted separated by `;`/`|` (only one pair observed). A value
the core cannot parse is passed as `myts_avatar_unparsed`. `has_myts` = the client has a
myTeamSpeak id (`null` if not sent). Neither set → default avatar.
@@ -798,8 +783,8 @@ voice stream (also for self: `transmitting` in `audio_state`).
streams are active and output is not muted. Per-speaker jitter buffering and Opus
decoding (including packet-loss concealment) happen in the core. Local user volume
is applied to each decoded stereo stream **before summation**, never to the already
mixed renderer audio or through a server volume command. The linear range is
0–2 (0–200%, default 100%); a separate local mute preserves the selected volume.
mixed output audio or through a server volume command. Per-participant gain follows the dB contract
in §4.11a/§4.18; local mute preserves the selected modifier.
The final mono sum saturates to signed PCM range instead of wrapping. Amplified or
simultaneous loud voices can reach that existing saturation limit; no limiter or
automatic gain compensation is introduced. Global voice volume remains independent.
@@ -809,7 +794,7 @@ on each mix tick. It survives speech restarts and channel changes within the sam
connection, but resets on disconnect/reconnect or core exit. Departing clients'
decode queues are discarded before their numeric IDs can be reused. `speakers`
still reports active decoded streams even when local volume/mute makes them silent;
local volume does not change talking notifications. The renderer should keep a small
local volume does not change talking notifications. Native playback retains a small
playback ring (target 40–60 ms, drop oldest beyond ~200 ms, play silence on underrun).
### `text`
@@ -837,16 +822,16 @@ tsclientlib would discard them:
stream) the UI must report "SFU streams are not supported" instead of "no stream".
The core never logs stream payloads (SDP/ICE/tokens).
- `items`: one map per `|`-separated entry; keys and values are unescaped strings
(JSON/SDP stay raw strings — parse them in the renderer). Flags without value → `""`.
(JSON/SDP stay raw strings — parse/validate them in the native stream service). Flags without value → `""`.
### `error`
`{"event":"error","error":{...}}` — asynchronous error (see §3).
## 6. Identity storage (main-only concern)
## 6. Identity storage (native service ownership)
The private vault, nickname metadata and profile lock live in `--data-dir`; legacy identity/profile files are migrated by Store without changing keys or UIDs. UID is recomputed on read; corrupt data never triggers silent regeneration. Private writes are atomic and owner-only. Connection cores share the vault but hold distinct `--connection-dir` locks. Identity mutations serialize on the profile lock and refuse deleting identities currently used by live connections.
Main-only CLI (host paths from trusted main dialogs, never renderer-selected strings):
Diagnostic identity CLI (host paths from trusted native dialogs/callers, never arbitrary UI strings):
`teamspeach-core identity <list|create|update|default|delete|export|import|improve> --data-dir <DIR> …`
@@ -859,20 +844,16 @@ Results are `{ok:true,result}` or `{ok:false,error}`. Improvement also emits `{e
## 7. Build prerequisites
All platforms: Rust stable ≥ 1.89 (rustup), CMake (any version; `.cargo/config.toml` (repository root; cargo reads config from the working directory, so run cargo from the repo root or below)
sets `CMAKE_POLICY_VERSION_MINIMUM=3.5` for CMake ≥ 4 and forces the bundled libopus to be
built and linked statically: `LIBOPUS_STATIC=1`, `LIBOPUS_NO_PKG=1`), a C compiler, and
network access to crates.io and github.com (tsclientlib git dependencies at the pinned
revision, including its `tsdeclarations` submodule, fetched by cargo).
Use `rust-toolchain.toml`, installed C/C++ tools, CMake and Python 3. Repository `.cargo/config.toml`
controls static bundled Opus/CMake compatibility; run Cargo from the repository root. Application builds
also require source-built pinned Skia/libwebrtc and target SDKs through Cargo `xtask`; see README.
Keep normal Skia/WebRTC features: reduced-feature compilation is not product acceptance.
`CARGO_TARGET_DIR` is a workspace override. The standalone diagnostic binary can be built with
`cargo build --release --locked -p teamspeach-core`.
- Windows: target `x86_64-pc-windows-msvc`, Visual Studio Build Tools (MSVC) + Windows SDK.
The VS-bundled CMake must know the installed VS generator (with VS 18/2026 installed use
the VS 18 CMake 4.x; VS 2022's CMake 3.31 fails with "Could not create named generator").
- Linux/macOS: `cc`/`c++` toolchain and CMake; no system libopus needed.
- Build: `cargo build --release --locked --manifest-path core/Cargo.toml` →
`core/target/release/teamspeach-core[.exe]`. On memory-constrained machines add `-j 2`
(full parallelism exhausted the Windows commit limit here: link.exe `0xc000012d`).
- Tests: `cargo test --locked --manifest-path core/Cargo.toml` (unit tests + offline stdio
smoke of the built binary; no network).
Workspace tests cover offline core/stdio contracts. Physical media/live peers/server mutations require
separate authorization. Windows requires MSVC C++ tools/SDK and a compatible CMake VS generator;
Linux/macOS require native C/C++ tools/CMake, not system libopus. Lower parallelism with `--jobs`
when needed without weakening features or validation gates.
- tsclientlib is vendored with a small patch (`core/vendor/README.md`); third-party notices:
`core/THIRD_PARTY_NOTICES.md` (regenerate with `python core/tools/third_party_notices.py`).