From 38473b761df05051d994ddb07c123f7a1906990a Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 20 Oct 2026 20:47:14 +0300 Subject: [PATCH] Design the engine on voelin_proto::link::Session (docs/session-seam.md) The first half of plan step 7: every LinkCmd, LinkEvent and StreamCmd variant mapped to the Session API and back, with the decision for what v1 cannot carry yet (streams on a local port, TeamSpeak-only connect options on the ts3server:// link, presence fix-ups F1-F10 through Foreign); SessionLink over a Backends registry on the engine side, LinkSession over TsLink on the TeamSpeak side; connect, close, error texts, Features and LinkStats; RTP framing of voice against voelin-audio's packets; credentials with the account left as a hook; files through read_file and write_file; the FakeLink tests through the adapter, then on FakeSession and FakeHost, and which conformance cases the TeamSpeak session can run; three slices with acceptance, and the follow-ups for the protocol repository and for the move to VoelinGateWay. Co-Authored-By: Claude Opus 5.5 --- docs/session-seam.md | 846 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 846 insertions(+) create mode 100644 docs/session-seam.md diff --git a/docs/session-seam.md b/docs/session-seam.md new file mode 100644 index 0000000..63ebd71 --- /dev/null +++ b/docs/session-seam.md @@ -0,0 +1,846 @@ +# The session seam: the engine on `voelin_proto::link::Session` + +Status: design (2026-10-20), nothing implemented yet; section 10 has the +slices. + +Design for the first half of plan step 7 (Phase 4): the engine consumes +`voelin_proto::link::Session`, `ServerLink` becomes an adapter over it, and +the TeamSpeak link (`TsLink`) becomes a `Session` implementation that still +lives in this repository, in process. The second half (the TeamSpeak +`Session` implementation moves to VoelinGateWay as `voelin-gateway-ts`, and +`voelin-stream`'s dependency on `voelin-media` is split) is out of scope +here; section 11 lists what it has to do. + +Read for this design: `crates/voelin-core/src/link.rs`, `ts_link.rs`, +`voice.rs`, `book.rs`, `stream.rs`, `files.rs`, `session.rs` (its use of the +link), `tests/link_fake.rs`, `voelin-audio/src/packet.rs`; and in +VoelinProtocol (main `c8e0e5a`) `crates/voelin-proto/src/link.rs`, +`media.rs` with `media/`, `test_util/` (FakeHost, FakeSession, +FakeConnector, FakeAccountAgent, the conformance suite), +`proto/voelin/v1/*.proto`, `crates/voelin-model/src/replica/` and +`docs/protocol.md` sections 1.2, 1.3, 2.4, 2.5, 4.7, 5, 6, 9.1, 11 and 13.8. + +## 1. Terms and the decisions in one place + +| Term | Meaning here | +|---|---| +| **engine** | `voelin-core` without the TeamSpeak implementation: `lib.rs`, `session.rs`, history, contacts, cache, settings, the audio thread, the adapter below. | +| **SessionLink** | New, engine side. A `ServerLink` whose connections are `Arc`s from the registry: it turns `LinkCmd`s into `Session` calls and pushes, signals and media into `LinkEvent`s. `session.rs` keeps talking `LinkCmd`/`LinkEvent` to it. | +| **Backends** | New, engine side. The registry of connectors by address scheme: `voelin_proto::link::Connectors` plus the in-process connectors that also hand the engine local ports (below). | +| **LinkSession** | New, TeamSpeak side. A `Session` over any `ServerLink`, generic in the link. `LinkSession` is the in-process TeamSpeak `Session`; `LinkSession` is what the link tests run through. | +| **TsConnector** | New, TeamSpeak side. The `Connector` for `ts3server` and `teamspeak` (and addresses without a scheme) that makes `LinkSession`s. | +| **StreamPort** | New, local extension. The in-process channel that carries `LinkCmd::Stream` and the stream events past the `Session` trait while TeamSpeak 6 streams are not yet v1 entities (section 6.4). | +| **old model** | The client's TeamSpeak-shaped types (`Presence`, `ChannelInfo`, `ClientInfo`, `ChatMessage`, `ServerDetails`) that `session.rs` and the UI use. | + +Decisions: + +1. **Two adapters, one vocabulary in the middle.** `session.rs` is not + rewritten: it keeps `LinkCmd`/`LinkEvent`. SessionLink translates them to + and from v1; LinkSession translates v1 to and from the inner link's + `LinkCmd`/`LinkEvent`. With a fake link inside, the pair round-trips, so + the existing FakeLink tests check both translations (slice 1). +2. **The engine keeps a replica.** SessionLink feeds every push into + `voelin_model::replica::Replica` and projects it into the old model with + `replica::convert` plus the fix-ups of section 5.3. This needs the + protocol's `voelin-model` (a superset of the client's, byte for byte the + same in `presence.rs`, `server.rs`, `chat.rs`, `percent.rs`), so slice 1 + switches the client's `voelin-model` to the protocol crate (the plan's + section 4 already moves it there). Two crates named `voelin-model` in one + graph would make `scripts/own-crates.sh`'s `-p voelin-model` ambiguous, so + there is no half-way. +3. **Streams stay on a local port in this half.** TeamSpeak 6 streams are + peer to peer; v1 carries only their signalling (`Stream`, `Viewer`, + `RespondViewer`, `KickViewer`, `Signal{stream}`, protocol 6.11 and 11.1). + Moving the str0m peer out of the TeamSpeak stream task and mapping its + signalling is the second half's first item; here `LinkCmd::Stream` and + the stream events pass through `StreamPort`, unchanged. +4. **File transfers go through v1 now.** `read_file`/`write_file` carry them; + the engine does the copying, progress and cancel itself, and the + TeamSpeak side hands out the raw transfer connection (two new inner + commands, section 8). +5. **TeamSpeak-only connect options ride the `ts3server://` link** that + `voelin_model::link::ServerLink::to_url` already writes (`channel`/`cid`, + `channelpassword`), until v1 has a field for them (follow-up P1); the + client version `TsConnector` impersonates rides it too, as a parameter of + our own (`client_version`). +6. **No TeamSpeak type crosses the seam**: what crosses is `voelin_proto` + types, the old model (TeamSpeak-shaped, but the client's own types), + `voelin-audio` packets and the core-owned stream types. Section 10 says + which public items still name `voelin-stream` peer types, and why. + +## 2. Shape after this half + +``` +UI ── Engine (Command / Event) ── session.rs (merge, dedup, history, contacts) + │ LinkCmd ↓ ↑ LinkEvent + SessionLink (engine side: replica, projection, + │ media framing, transfers, talk tracker) + │ Arc + pushes + MediaSink + │ (+ StreamPort for in-process connectors) + Backends ─────┼──────────────────────────┐ + (scheme registry) ▼ ▼ + TsConnector → LinkSession any Connector: FakeConnector + (ts3server, teamspeak, no scheme) (tests), QuicConnector (later) + │ LinkCmd ↓ ↑ LinkEvent (inner, TS side) + TsLink: voice.rs, book.rs, stream.rs, versions.rs, + identity.rs on tsclientlib, voelin-stream +``` + +The gateway (`tsgw`) and ServerQuery sources of a session are not behind +the seam in this half: they are the other two sources of `session.rs` +(`gateway.rs`, `query.rs`) and become a second `Session` to a gateway daemon +later (protocol 11.2, follow-up H5). Only their public command types change +in slice 3 (section 10). + +## 3. The mapping + +### 3.1 `LinkCmd` → `Session` + +Every variant of `voelin_core::link::LinkCmd`. "SessionLink" is what the +engine does; "LinkSession" is how the TeamSpeak side answers. `S` is the +server id from the connect sequence (section 4.2), `P` our participant id, +`slot` our media slot. Text in errors is reproduced exactly as `TsLink` +writes it today (section 4.6). + +| `LinkCmd` | Session call (SessionLink) | Answer and what the engine reports | LinkSession (TeamSpeak side) | +|---|---|---|---| +| `SendChat(target, text)` | `request(Put{writes:[Message{channel_id, text, format, nonce}]})`. `Channel(cid)`: that channel. `Server`: the channel of kind `SERVER_CHAT` in SERVER(S). `Private(uid)`: the DM channel in HOME whose other recipient's `User` has that uid; without one, first `request(Put{Channel{server_id:0, kind:DM, recipients:[user]}})`. `format`: `BBCODE` when the session offers `chat.bbcode`, else `MARKDOWN`. | `Entities` ignored (the `Change` that follows is the echo, section 3.2). `Rejected` → `LinkEvent::Error("message: {Error.message}")`. No `User` for `uid` → `Error("private message: the client is not on the server (send an offline message instead)")`, without a request. | Inner `SendChat`. A VOICE channel other than our own is refused `NOT_IN_CHANNEL`. Answered at once with the message as written (local id and rev): `TsLink` reports success of a text message nowhere, failures come later as a notice (section 3.2). The answer adds no `Change`: the inner link's echo is the `Change`, with an id of its own, because the inner link does not tie the echo to the send (H1 does). A `Put Channel{DM}` answers the synthetic DM channel (section 5.2) and puts it in HOME. | +| `Move(channel, password)` | `request(JoinVoice{server_id:S, channel_id, password})` (`None` → empty). | Own `VoiceState` → nothing (the move shows in LIVE). `Rejected` → `Event::JoinFailed{channel, reason}`: `PASSWORD` → `JoinFailure::Password`, `FULL` → `Full`, any other → `Other(Error.message)`. | Already in that channel: answer the own `VoiceState`, send nothing (today `ChannelAlreadyIn` is silent too). Else inner `Move`; answered when our channel becomes `channel_id` (own `VoiceState`), refused when the inner link reports `Event::JoinFailed` for it (`Password` → `PASSWORD`, `Full` → `FULL`, `Other(text)` → `FORBIDDEN` with `text`), `SessionError::Timeout` after 10 s. The first `JoinVoice` of a connection confirms the seat (section 4.2). | +| `SetInputMuted(b)` | `notify(Put{Write{VoiceState{S, P, self_mute:b}, paths:[self_mute]}})` (protocol 4.7: own voice flags are fire and forget). | `Err` only for a closed session: ignored. | Inner `SetInputMuted(b)`. | +| `SetOutputMuted(b)` | `notify(Put{Write{VoiceState{S, P, self_deaf:b}, paths:[self_deaf]}})`. | As above. | Inner `SetOutputMuted(b)`. | +| `Audio(EncodedVoice)` | `send_media(MediaClass::Voice, MediaPacket{flow: FlowId::new(slot, voice_sub::CHANNEL), rtp})`, RTP as in section 6.1. | `Dropped`: counted (stats). `NotOwned` (no slot yet), `TooLarge` (over `stats().max_rtp`): dropped, logged once per connection. `Closed`: ignored. | Inner `Audio(EncodedVoice{codec, payload})` for our own slot only (section 6.2). | +| `Stream(StreamCmd)` | None in this half: `StreamPort::send(cmd)` (section 6.4; the v1 mapping of every `StreamCmd` is table 6.4). Without a port the engine reports no `streams` capability, so `session.rs` never sends it. | Bus events and `OwnStream`/`StreamAudio`/`StreamAudioEnded` come back through the port. | Inner `Stream(cmd)`, in issue order with everything else (one queue). | +| `Poke{client, message}` | `request(Signal{to:SignalTarget{server_id:S, participant_id:client}, body:Poke{message}})`. | `Ack` → nothing. `Rejected` → `Error("poke: {Error.message}")`. | Inner `Poke`; answered `Ack` at once (failures come as a notice). | +| `ListFiles{request, dir}` | `request(List{kind:FILE, parent:dir.channel, path:dir.path, password})` (refused locally without `files`). | `Event::FileList{request, channel, path: files::normalize_dir(path), result}`: `Ok` with each `FileEntry` as `files::FileEntry{name, size, modified_s: modified_ms/1000, is_dir}`, or `Err(text)`. | Inner `ListFiles` with a request id of its own; its `Event::FileList` becomes the `Entities` answer (`modified_ms = modified_s * 1000`), or `Rejected` with the text. | +| `Download{transfer, file, sink, report}` | `report(Requested)`, then `read_file(FileRead{target: Path(FilePath{channel_id, path, password}), offset: sink.offset(), length:0})`; the engine runs `files::download` (made generic over `AsyncRead`) on `Download.body` with `FileEntry.size` from `head`. A picture (`transfer: None`) keeps today's limit (`cache::MAX_PICTURE_BYTES`) and deadline (`image_download_time`), now applied here. | `TransferState`s through `report`, as today. `Err` → `report(Failed(text))`. The task is kept under `transfer` for `CancelTransfer`. | Inner `OpenRead` (new, section 8): the TeamSpeak transfer connection itself becomes `body`, `head` is `FileEntry{size}`. | +| `Upload{transfer, file, from, overwrite, resume, report}` | Size and kind of `from` checked here (today's texts: "{path} is not a file", "{path}: {error}"). With `resume`, the offset is the `size` of the target in `List{FILE}` of its directory (0 when absent). `write_file(FileWrite{target: Path(...), size, offset, overwrite})`; the engine runs `files::upload` (generic over `AsyncWrite`) into `Upload.body`, then awaits `Upload.done`. | `TransferState`s as today; `Done` after `done` resolved. | Inner `OpenWrite` (new): the transfer connection becomes `body`; the server's seek position must equal `offset`, else `CONFLICT` "the server has N bytes" (follow-up P4). `done` resolves when the inner job reports the end. | +| `CancelTransfer(id)` | No call: the engine aborts its copy task (dropping the body cancels on both v1 and TeamSpeak), removes the `.part` file, reports `Cancelled`; an unknown id is logged, as today. | — | The dropped connection ends the TeamSpeak transfer. | +| `DeleteFiles{request, channel, password, paths}` | `request(Delete{keys:[FileEntry{channel_id, path: dir, name, password}...]})`, one key per path (`/dir/name` split at the last `/`). | `request: Some` → `Event::RequestDone{request, result}`; `None` → nothing (best effort). | Keys grouped by channel → inner `DeleteFiles{request: Some(own id)}` each; `RequestDone` → `Ack` or `Rejected`. | +| `RenameFile{request, from, to}` | `request(Put{writes:[Write{FileEntry{channel_id: to.channel, path, name, password: to.password, from_channel_id: from.channel, from_path: from.path, from_password}}]})` (a create of an unused key: no `paths`). | `RequestDone{request, result}`. | Inner `RenameFile`. | +| `CreateDirectory{request, dir}` | `request(Put{writes:[Write{FileEntry{channel_id, path, name, is_dir: true, password}}]})`. | `RequestDone{request, result}`. | Inner `CreateDirectory`. | +| `SetAvatarHash{request, hash}` | `request(Put{writes:[Write{User{id: own user, avatar: Image{hash}}, paths:[avatar.hash]}]})` (the leaf path, so the myTeamSpeak `url` in the same `Image` stays). | `Some(request)` → `RequestDone`; `None` → `Rejected` becomes `Error("avatar: …")`. | Inner `SetAvatarHash`. (`replica::convert` reads the TeamSpeak avatar from `User.avatar.hash`; follow-up P7 on `Member.avatar`.) | +| `OfflineList{request}` | `request(List{kind:MAIL})` (refused locally without `mailbox`). | `Event::OfflineMessages{request, result}` from the `Mail`s (`OfflineMessageInfo` fields from `id`, `from_uid`, `from_name`, `subject`, `ts_ms`, `read`). | Inner `OfflineList`; its event becomes `Entities[Mail…]`. | +| `OfflineGet{request, id}` | `request(List{kind:MAIL, ids:[id]})` (v1: `List{MAIL, ids}` returns the text). | `Event::OfflineMessage{request, result}`. | Inner `OfflineGet`. | +| `OfflineAdd{request, to_uid, subject, text}` | `request(Put{writes:[Write{Mail{id:0, to_uid, subject, text}}]})`. | `RequestDone`. | Inner `OfflineAdd`; answers the mail as written (id 0: `messageadd` returns none). | +| `OfflineDelete{request, id}` | `request(Delete{keys:[Mail{id}]})`. | `RequestDone`. | Inner `OfflineDelete`. | +| `OfflineFlag{request, id, read}` | `request(Put{writes:[Write{Mail{id, read}, paths:[read]}]})`. | `RequestDone`. | Inner `OfflineFlag`. | +| `Disconnect` | `close(CloseCode::Normal, "")`, then `closed()`. A closed command channel does the same. | `LinkEvent::Disconnected(None)` (section 4.5). | Inner `Disconnect`; `closed()` resolves `Local(Normal)` when the inner link reports its end. | + +Requests with a `RequestId` that cannot be sent (no session yet, closed) +answer as today: `session.rs` already reports "not connected with voice" +before a link exists; SessionLink reports `SessionError` texts (4.6). + +### 3.2 `Session` → `LinkEvent` + +Every variant of `voelin_core::link::LinkEvent`. + +| `LinkEvent` | Source on the `Session` side | Rule | +|---|---|---| +| `Connected{name, backend, capabilities, own_client, server_uid, own_uid}` | `Welcome`, the SERVER(S) sync, the answer to the first `JoinVoice`, the own `User`. | Sent once, after the connect sequence (4.2). `name` = `Server.name`; `backend` from `Welcome.host.backend` (table 4.7); `capabilities` from `features()` (table 4.7); `own_client` = `P` as `u16`; `server_uid` = `server_key(Server.uid)` (5.3, F3); `own_uid` = `uid_text` of the own `User` (the `User` of our `VoiceState.user_id`, else `Welcome.user_id`), `None` when the replica has none yet. | +| `Presence(Box)` | `Change`/`SyncEnd` of SERVER(S) and LIVE(S); talk tracker. | After the pushes that are there now are applied (drain, then one snapshot), if SERVER or LIVE changed: `replica.presence_model(S)` with the fix-ups F1-F10. One TeamSpeak book update is one inner `Presence`, one or two `Change`s, and still one snapshot. | +| `OwnChannel(cid)` | Our `VoiceState.channel_id` in LIVE. | After every `Presence`, when known and not 0 (as `TsLink` does after every snapshot). | +| `Chat(ChatMessage)` | `Change.put` of a `Message`, and messages of a `SyncBegin`..`SyncEnd`, in a subscribed CHAT scope (4.3). | Once per `(channel_id, id)` per connection; `replica.chat_message(channel, id)` gives target, author name, author uid, author participant, `ts_ms`, `via_relay` (`MESSAGE_FLAG_RELAYED`). Answers to our own `Put` are not applied to the replica: our own message is reported when its `Change` arrives, which is today's echo, and `session.rs` merges it with the row it stored (test `a_sent_message_and_its_echo_are_one_message`). | +| `Poke{from, from_uid, from_name, message}` | Push `Signal{from_user, from_participant, body: Poke{message}}`. | `from` = `from_participant` as `u16`; `from_uid` = `uid_text` of `User(from_user)`; `from_name` = the participant's `VoiceState.nick`, else the `User.name`. A sender outside our view is delivered as a bare `User` first (5.2). | +| `Audio(VoicePacket)` | `MediaSink` packets on a voice slot. | Section 6.1. | +| `Talking{client, talking}` | `MediaSink` packets on a voice slot (protocol 6.4: talking in the own channel comes from media). | The first packet of a slot → `true`; 400 ms without one → `false` (250 ms tick): the rule of `voice.rs` today. Also fills `ClientInfo.talking` (F8). | +| `OwnStream(OwnStreamEvent)` | `StreamPort` events. | Passed through. | +| `StreamAudio{stream, time, data}` | `StreamPort` events. | Passed through. | +| `StreamAudioEnded(stream)` | `StreamPort` events. | Passed through. | +| `Error(text)` | (a) `Rejected` answers to commands that have no `RequestId` (`SendChat`, `Poke`, `SetAvatarHash{request: None}`); (b) push `Signal{notice{level: ERROR or WARNING}}`; (c) `ScopeClosed` of SERVER(S) or LIVE(S). | (a) `"{what}: {Error.message}"`, `what` = `message`, `poke`, `avatar` (today's labels); (b) `Notice.text`; (c) `ScopeClosed.message`, and the presence is emptied. | +| `Disconnected(reason)` | `closed()`; a failed `connect`; a connect sequence that does not finish. | Section 4.5. Sent once; the `StreamPort`'s closing events may follow, as the contract of `link.rs` already allows. | + +What the `Session` side produces and no `LinkEvent` carries, with the +decision for each: + +| Session output | Decision in this half | +|---|---| +| `Push::SyncBegin`/`SyncEnd`/`Change` of HOME | Applied to the replica: DM channels (CHAT subscriptions, 4.3), the own `User`, bare `User`s of senders. No event of their own. | +| `Push::Heads` | Ignored: no unread source in the engine uses it yet (TeamSpeak sends none). | +| `Push::HostUpdate` | Updates the feature set SessionLink checks requests against. Capabilities are not announced again: `LinkEvent` has no update, and TeamSpeak never sends one. Follow-up (client): `Event::ServerInfo` again on a `HostUpdate`. | +| `Push::ScopeClosed` | CHAT: unsubscribed, nothing reported. SERVER or LIVE: `Error` and an empty presence (row `Error` above). HOME: logged. | +| `Signal{typing}` | Ignored (the engine has no typing indicator; TeamSpeak types only in DMs). | +| `Signal{stream}`, `Signal{layer_target}` | Not sent by `LinkSession` (streams use the port). Ignored with a log. Second half: the engine's stream task (H2). | +| `Signal{encoder_hint}` | Ignored. Follow-up (client): Opus bitrate and `packet_loss_perc` from it (protocol 6.7). | +| `Signal{reminder}` | Ignored (no events feature in the engine). | +| `Signal{notice{level: INFO}}` | Logged at info. | +| `Signal{speaking}` | Not asked for (no `SUBSCRIBE_OPTION_SPEAKING`). Follow-up with talking in other channels. | +| Media on stream slots (sub 0-4), `FlowId::FEEDBACK`, `FlowId::PROBE` | Dropped (no SFU streams in this half). | +| `stats()` (`LinkStats`) | Section 4.7. | +| `Connected.host_uid` | Not pinned for TeamSpeak (`[0; 32]`, no host key). Kept for a later pin store for `voelin://` hosts. | +| `Welcome.resume_token`, `Welcome.ice`, `Welcome.observed_addr`, `Welcome.time_ms`, `Welcome.limits` | Kept by SessionLink, unused in this half (4.4). `limits.max_message_chars` is not enforced (the UI's own limit stays). | + +## 4. How the engine owns a `Session` + +### 4.1 The registry + +`voelin_core::link::Backends` holds the connectors by scheme: + +- `connectors: voelin_proto::link::Connectors` for plain connectors + (`Backends::register(Arc)`: `FakeConnector` in tests, the + QUIC connector later); +- in-process connectors that also give local ports: a crate-private trait + `LocalConnector: Connector` with + `connect_local(params, LocalCtx) -> BoxFuture>`, + where `LocalCtx` is what an in-process backend needs besides + `ConnectParams` (session id, the event bus, the frames bus, the settings, + the stream peer configuration, whether audio is open) and `LocalConnected` + is `Connected` plus `Option`. + +Lookup: the scheme of `ConnectParams.address` (lowercase, before `://`); an +address without a scheme is a TeamSpeak bookmark and gets `ts3server`. A +local connector for the scheme wins over a plain one; none → `Disconnected` +with "no connector for {address}" (the text of `Connectors::connect`). + +`Engine::start` and `start_with` use `Backends::default()`, which registers +`TsConnector` (schemes `ts3server`, `teamspeak`) with the engine's myTeamSpeak +watches (4.8). New: `Engine::start_with_backends(settings, history, backends)`. +`Engine::start_with_link(settings, history, link)` stays in slices 1 and 2: it +registers a local `LinkConnector` that answers every scheme with a +`LinkSession` over the given link, so the link tests go through the whole +adapter. + +### 4.2 Connect sequence + +SessionLink is a `ServerLink`: `session.rs` calls `spawn` exactly as today +and shows `Connecting` until `Connected`. + +1. Build `ConnectParams` (section 7 for the credential). In slice 1 the + options still carry TeamSpeak types, so one function of the TeamSpeak + module, `ts_session::connect_params(&ConnectOptions)`, builds them; it + also writes the resolved client version into the link parameter + `client_version` in a text form of its own. Slice 3 moves the building + into SessionLink over the neutral `VoiceOptions`, and `client_version` + carries the user's spec instead. The fields: + `address` = the `ts3server://` link of the bookmark address with + `channel`/`cid` and `channelpassword` (`ServerLink::to_url` of the model's + `link.rs`; a name clash with the trait, nothing more), or the address as + given when it has a scheme; `hello` = `Hello{version:1, client: + ClientInfo{name:"Voelin", version, platform, kind}, nickname, password: + server password, invite_code: privilege key, ..}`; `host_pin: None`; + `trust`: refuses (no TOFU dialog yet; TeamSpeak has no host key); + `media`: SessionLink's sink; `push_capacity: 1024`; `timeout: 35 s` (the + TeamSpeak connect gives up at 30 s with its own text, which should win); + `account: None`, `issuer_trust: Unknown`, `linked: []`. + The link can hold a channel password: neither side logs it (the + connector logs the host and port), and `session.rs` keeps keying history + and aliases by the bookmark address, not by the link. +2. `Backends::connect`. `Err(e)` → `Disconnected(Some(text(e)))`, end. +3. `request(List{kind: SERVER})`; the server `S` is the only one listed (or + the lowest id; follow-up P3 for hosts with several). `FakeHost` files no + `Server` stub in HOME (follow-up P9), so HOME is not used to find it. +4. `Subscribe` HOME, SERVER(S) and LIVE(S), each after `replica.subscribe`. +5. Apply pushes until the three `SyncEnd`s. 30 s without them → close, + `Disconnected(Some("timed out while connecting"))`. +6. `request(JoinVoice{server_id:S, channel_id, password})`: `channel_id` from + the bookmark's channel (`/` directly, a path resolved in the synced + tree with `split_channel_path`), else `Server.default_channel_id`. The + answer is our `VoiceState`: `P`, `slot`. TeamSpeak seats a client at + connect, so `LinkSession` answers the first `JoinVoice` of a connection + with the seat it has (participant = our client id, channel as far as it + knows it, 0 before the first snapshot) and moves nothing; the seat was + chosen by the link's `channel` parameter. A refused first `JoinVoice` → + close, `Disconnected(Some(Error.message))`. +7. Report `Connected`, then `Presence`, then `OwnChannel` (the order + `session.rs` and its tests expect). +8. Subscribe CHAT for the server chat, our channel and each DM (4.3). +9. Loop, `select!` biased in this order: the command channel, pushes, + media, `closed()`, the 250 ms tick (talk tracker, stats). Pushes before + media, so a talker's `VoiceState` is known before their first packet + (both come from one in-process task on the TeamSpeak side). + +`LinkSession` answers `List{SERVER}`, `Subscribe` and `Unsubscribe` from its +own state, without an inner command; an op it does not implement is +`UNSUPPORTED` with the op's feature in `Error.feature`. + +### 4.3 Which CHAT scopes + +TeamSpeak delivers the chat of our own channel, the server chat and private +messages; everything else needs a gateway. SessionLink subscribes exactly +that: CHAT(server chat channel), CHAT(our channel) (re-subscribed when we +move, the old one unsubscribed; `Limits.max_chat_subscriptions` is 16), and +CHAT(dm) for each DM channel HOME holds. A message that arrives before its +scope is subscribed is not lost: `LinkSession` keeps the messages of the +connection per channel (the 50 newest, the default CHAT window of +protocol 5.4) and sends them in the full sync; SessionLink reports each +`(channel, id)` once. A first private message from someone new therefore +arrives as: HOME `Change` (the DM channel), Subscribe CHAT(dm), its sync. +A cursor kept per CHAT scope makes a re-subscription after moving back a +delta where the session offers `sync.delta` (`LinkSession` does, within one +connection). + +### 4.4 Reconnect and resume + +- **Engine-initiated** (`Command::ConnectVoice` again): unchanged. + `session.rs` gives the old link `StreamCmd::Shutdown`, then `Disconnect`; + both reach the old session through one ordered queue (4.5), and the + generation filter drops what the old one still says. +- **Transport**: TeamSpeak's own reconnect inside `tsclientlib` + (`DisconnectedTemporarily`) stays invisible at the seam, as it is today + (the snapshots go on). A new client id after such a reconnect is not + announced, as today. The native TeamSpeak session of the second half + starts a new epoch instead (H1). +- **Resume**: `LinkSession` does not offer `resume`. SessionLink keeps the + last `Welcome.resume_token` and the CHAT cursors per session and address, + and sends neither in this half: no `voelin://` connector is registered. + Reconnecting with backoff (protocol 2.5) is the SDK's (H8). + +### 4.5 Close + +| How it ended | `closed()` | `LinkEvent::Disconnected` | +|---|---|---| +| `LinkCmd::Disconnect`, or the command channel closed | `Local(Normal)` | `None` | +| The inner link ended unasked without a reason | `Remote{code: Normal, reason: ""}` | `None` | +| The inner link ended with a reason (kicked, server gone, timeout) | `Network(reason)` | `Some(reason)` | +| A v1 host closed with a code | `Remote{code, reason}` | `Some(reason)`, or the code's name when `reason` is empty; `None` for `Normal` with no reason | +| Idle timeout | `TimedOut` | `Some("timed out")` | + +`LinkSession` keeps one queue for everything that reaches the inner link: +`Session` calls, `StreamPort` sends and `close`. The order a caller issues +them in is the order the inner link sees (the `Session` contract for +mutations, and what `a_reconnect_shuts_the_streams_down_before_the_old_connection` +checks: `Stream(Shutdown)` before `Disconnect`). + +### 4.6 Errors and their texts + +`text(SessionError)`: `Rejected(e)` → `e.message`; `Closed(reason)` → the +reason as in 4.5; `Timeout` → "timed out while connecting" during connect, +"timed out" otherwise; `Unsupported(f)` → "not offered by this server: {f}"; +`HostIdentity(t)`, `Protocol(t)` → `t`; `Io(e)` → `e.to_string()`. +`LinkSession` puts `TsLink`'s own texts in `Error.message` and +`CloseReason::Network`, so what the user reads does not change. + +### 4.7 Where `Features`, `BackendInfo` and `LinkStats` surface + +`Welcome.host.backend` → `BackendInfo`: + +| v1 `BackendInfo{product, flavor}` | engine `BackendInfo.product` | +|---|---| +| `teamspeak`, `ts3` | `TeamSpeak 3` | +| `teamspeak`, `ts6` | `TeamSpeak 6` | +| `teamspeak`, empty (not recognised) | empty (`version` = what the server said) | +| anything else | `product` as given | + +`LinkSession` writes the inverse from the inner `Connected.backend` +(`TeamSpeak 3` → `teamspeak`/`ts3`, ...), so every value round-trips. + +`features()` (narrowed by `Server.features`) → `Capabilities`: + +| `Capabilities` | from | +|---|---| +| `streams` | `streams`, and the connection has a `StreamPort` (this half) | +| `file_transfer` | `files` | +| `offline_messages` | `mailbox` | +| `raw_query`, `ssh_query`, `http_query` | no feature: they describe ServerQuery access to a TeamSpeak server, not the session. Derived from the flavor as `ServerFlavor::capabilities` does (`ts3`: raw and SSH; `ts6`: SSH and HTTP). They go with the query observer (H5); follow-up P10. | + +`LinkSession`'s features are what it implements: `voice`, `chat`, +`chat.bbcode`, `dm`, `sync.delta`, `roles`, `roles.channel`; with file +transfer `files`, `files.upload`; with offline messages `mailbox`; with +streams `streams`, `streams.p2p`, `streams.audio`, `streams.approval`. Not +`voice.whisper`, `chat.typing` or the moderation set: the inner link cannot +do them (the native session of H1 offers the whole TeamSpeak column of +protocol 9.1). SessionLink refuses locally (`Features::require`) what needs a +missing feature: `List{FILE}`, file reads and writes (`files`, +`files.upload`), `Mail` (`mailbox`). + +`LinkStats`: no UI surface in this half (the engine has no event for +connection quality). SessionLink reads `stats()` on the tick: `max_rtp` +bounds outgoing voice packets; `rtt`, `loss`, `media_dropped` and `degraded` +are logged at debug every 10 s and when `degraded` changes. `LinkSession` +reports `max_rtp: MAX_RTP` and zeros. Follow-ups: an engine event for +connection quality, and the encoder's FEC and loss from `LinkStats` and +`encoder_hint` (protocol 6.7). + +### 4.8 What `LinkCtx` becomes + +| `LinkCtx` field | Where it goes | +|---|---| +| `session` | SessionLink (it reports with it); `LocalCtx.session` for the stream task. | +| `events` | SessionLink reports answers itself; `LocalCtx.events` for the stream task's bus events. Inside `LinkSession`, the inner link gets a bus of its own: `FileList`, `JoinFailed`, `OfflineMessages`, `OfflineMessage` and `RequestDone` from it answer pending requests, every other event (the stream task's) is forwarded to the engine's bus unchanged. Capacity 4096, and every pending request has a timeout, so a lagging receiver cannot hang one forever. | +| `frames` | `LocalCtx.frames`, passed to the inner link as is. | +| `settings` | SessionLink (progress cadence `files.progress_ms`); `LocalCtx.settings` for the stream task. | +| `myts_identity`, `myts_data` | `TsConnector` (it gets the engine's watches in slices 1 and 2, has its own setters in slice 3); the account hook of section 7 replaces them later (H4). | + +## 5. Presence across the seam + +### 5.1 The rule + +`project(translate(p)) == p` for every presence a TeamSpeak link reports: +`translate` is `LinkSession`'s old model → v1 entities, `project` is +SessionLink's replica → old model. A unit test checks it on the book +fixtures of `book.rs` (TeamSpeak 3 and 6) and on a generated set of +TeamSpeak-shaped presences; the FakeLink tests check it end to end. + +### 5.2 Ids and entities on the TeamSpeak side + +Protocol 11.1 "Ids", made concrete for `LinkSession`: + +| v1 | from the old model | +|---|---| +| server id | 1 (one virtual server per connection) | +| `Server` (SERVER(1)) | `ServerDetails` and `server_name`; `uid` = `ts:` + the server uid `TsLink` computes; `host_message_mode`, banner, host button, icon (`Image{hash: id}`), `max_members`, `priority_dim_db`, `default_role_id` = sgid, `default_channel_role_id` = cgid with bit 62; `foreign{system:"teamspeak", kind:"server", json:{"platform", "version"}}`, the strings the server sent (F4, F5) | +| channel id | cid; `kind: VOICE`; `position` from the order chain (1024 per step); `needed{TALK}`; `icon`; banner; `max_members` (with `foreign{"max_clients":0}` for a limit of 0, F7) | +| server chat | `Channel{id: 1 << 63, kind: SERVER_CHAT}` in SERVER(1) | +| DM channel | `Channel{id, server_id: 0, kind: DM, recipients: [own user, peer user]}` in HOME, made when a message to or from the peer needs it; `id` has bit 63 set and the FNV-1a 64 hash of the peer's uid in the low 63 bits (1 when they come out 0, so it never equals the server chat's id) | +| role id | sgid (`RoleScope::SERVER`); cgid with bit 62 (`RoleScope::CHANNEL`); `position` = −`sort_id`; `name_mode`; `kind`; `icon` | +| user id | `database_id`; a sender with none, or outside our view, gets bit 63 set and the FNV-1a 64 hash of its uid in the low 63 bits | +| `User` | `uid` = base64-decoded unique id, `uid_kind` `TS3` (`TS6` on a TeamSpeak 6 server); a uid that is not canonical base64 (a ServerQuery client's login name) leaves `uid` empty and goes into `foreign{system:"teamspeak", kind:"user", json:{"uid"}}` (F10); `name`; `avatar: Image{hash: avatar MD5, url: myTeamSpeak avatar}`; `badges`; `country` | +| `Member` | `roles` = server groups; `channel_roles` = {channel: channel group with bit 62}; `description`; `foreign{system:"teamspeak", kind:"client", json:{"icon"}}` (F6) | +| `Presence` | `status: IDLE` with `text` = away message when away, else `ONLINE` | +| participant id | client id; `VoiceState{nick, channel_id, slot: client id + 1, self_mute, self_deaf, talker, talk_power, priority_speaker, channel_commander, recording, streaming, kind: QUERY for query clients}` | +| message id | per connection: milliseconds since the Unix epoch shifted left by 12 bits, plus a counter in the low 12 bits | +| rev, epoch | one counter per `LinkSession` from 1; the epoch is new per connection | +| `Mail` id | the TeamSpeak offline message id | + +Each inner `Presence` is diffed against the previous one: changed entities +are put, gone ones deleted, one `Change` per scope. A poke or chat message +from someone the snapshot does not hold is preceded by a `Change` that puts a +bare `User` (synthetic id, uid, name) into LIVE: it shows in no presence (no +`VoiceState`) and lets the engine name the sender (follow-up P5). + +### 5.3 The engine's projection: `presence_model` and its fix-ups + +`replica::convert` targets the old model already. Where it says less than +`TsLink` does, SessionLink fixes the result up in one module +(`link/project.rs`), each fix with a follow-up for the protocol repository +(P6, P7). The old model is TeamSpeak-shaped, and these fix-ups apply the +TeamSpeak gateway's id rules of protocol 11.1 so the UI keeps the ids it +has; they go when the UI reads the replica (H7). + +| | Fix-up | Why | +|---|---|---| +| F1 | Leave out channels of kind `SERVER_CHAT`, `DM`, `GROUP_DM`, `THREAD`. | `presence_model` leaves out threads only; the server chat would show as a channel. | +| F2 | On a TeamSpeak backend (`backend.product == "teamspeak"`), clear bit 62 of `RoleScope::CHANNEL` role ids (channel groups, `ClientInfo.channel_group`, `ServerDetails.default_channel_group`). | Today's ids are TeamSpeak's cgids; requests to the gateway and the UI's group lookups use them. | +| F3 | `server_key(uid)`: `Server.uid` without a leading `ts:`; used for `server_uid` and `ServerDetails.uid`. | History rows, aliases and the merge with the gateway and query sources are keyed by today's form. Goes with H5 (and a history key migration). | +| F4 | `ServerDetails.version` from `Server.foreign` (`teamspeak`/`server`, key `version`), else `Welcome.host.backend.version`. | `server_details` leaves it empty by design, and `BackendInfo.version` is the parsed version, not always the string the server sent. | +| F5 | `ServerDetails.platform` from `Server.foreign` (`teamspeak`/`server`, key `platform`). | v1 has no field for the server's OS. | +| F6 | `ClientInfo.icon` from `Member.foreign` (`teamspeak`/`client`, key `icon`). | v1 has no client icon; `client_info` sets 0. | +| F7 | `ChannelInfo.max_clients = Some(0)` from `Channel.foreign` key `max_clients`. | `max_members: 0` means unlimited; a TeamSpeak limit of 0 cannot be said. | +| F8 | `ClientInfo.talking` = `Some(talk tracker)` where the session offers `voice`, else `None`. | Talking comes from media (protocol 6.4); `client_info` sets `None`. | +| F9 | `ClientInfo.streaming = None` where the session lacks `streams`. | `client_info` always gives `Some`; TeamSpeak 3 reports none. | +| F10 | `ClientInfo.uid`, a message author's and a poke sender's uid from `User.foreign` (`teamspeak`/`user`, key `uid`) when `User.uid` is empty. | ServerQuery clients' uids are login names, which `User.uid` (bytes, base64 for TeamSpeak) cannot hold. | + +### 5.4 Normalised fixtures + +A TeamSpeak link never reports some states the FakeLink fixtures use; through +the adapter they come back normalised, so slice 1 changes the fixture +builders, never the assertions (except one, below): + +- sibling channels form an order chain (`GAMES.order = LOBBY`, not both 0); +- every client has a `database_id`, `talking: Some(false)` and the + `channel_group` it would have (`None` stays `None`); +- `presence().server` names the server and its uid as `TsLink` fills them; +- `Talking` is played as a voice packet of the talker (`LinkEvent::Audio`), + because the engine derives it from media; the test still expects + `Event::Talking{client: 8, talking: true}`; +- `commands_reach_the_link` no longer expects the engine's request id (5) + in the inner `ListFiles`: the id the inner link sees is `LinkSession`'s + (v1 request ids belong to the session). This is the one changed + assertion. + +## 6. Media across the seam + +### 6.1 Voice, engine side + +`voelin-audio`'s `EncodedVoice`/`VoicePacket` stay what the audio thread +speaks; SessionLink frames them in the v1 media codec (`voelin_proto::media`). + +Sending (`LinkCmd::Audio`): flow `FlowId::new(slot, voice_sub::CHANNEL)` +(the engine has no whisper or priority voice yet), `RtpHeader::new(PT_OPUS, +seq, timestamp)`, SSRC = flow; `seq` counts every packet from 0; +`timestamp` advances by the previous packet's Opus duration +(`media::opus::packet_ticks`, 960 for 20 ms); marker on the first packet of a +spurt; `EncodedVoice::is_end()` becomes an RTP packet with an empty payload, +sent once (protocol 6.4 sends it twice; the TeamSpeak side would turn that +into two TeamSpeak end packets, so twice waits for H1). `MediaClass::Voice`. + +Receiving (`MediaSink::media`, never blocking: into the loop's queue): a +voice flow is `slot` → our replica's `VoiceState` with that slot → +`TalkerId(participant as u16)`; `sub` 1-6 → `whisper: true`; `seq` = RTP +sequence; `payload` = RTP payload (empty ends the spurt; `VoicePacket::is_end` +also takes one byte); `codec` = `Music` when the Opus TOC has the stereo flag, +else `Voice`. The codec is informational on this path: the jitter buffer +decodes every talker with one stereo decoder (`jitter.rs`), so a frame coded +mono inside a music stream decodes the same. Unknown slots are dropped +(logged once). The talk tracker sees every voice packet. + +### 6.2 Voice, TeamSpeak side + +`LinkSession` re-wraps, never transcodes (protocol 1.2): an inner +`VoicePacket` becomes RTP on the talker's slot (client id + 1), sub 1 for +whispers else 0, `seq` = TeamSpeak packet id, timestamp from the TOC +durations on an unwrapped packet-id counter and wall-clock time across +silences, marker after an end or 250 ms of silence, empty payload for the +end. Sub 7 (priority voice) is not used: the mixer dims by the presence's +`priority_speaker` flag, as today. Uplink: RTP on our slot loses its header +and becomes `EncodedVoice{codec: Music if the TOC is stereo else Voice, +payload}`; the engine encodes `VoiceCodec::Voice` only (`audio.rs`), so +TeamSpeak keeps receiving Opus Voice. Packets of another slot are +`NotOwned`, over `MAX_RTP` `TooLarge`. + +### 6.3 Media classes + +| Class | Used in this half | +|---|---| +| `Voice` | our voice | +| `StreamAudio`, `Video`, `Feedback`, `Probe` | not used: TeamSpeak 6 streams are peer to peer, so no stream media crosses a `Session` (protocol 6.11, 11.1); the SFU path comes with VoelinServer | + +### 6.4 Streams: the port now, v1 later + +`StreamPort` is `{ cmds: UnboundedSender, events: +UnboundedReceiver }`, `StreamEvent` = `OwnStream`, `StreamAudio`, +`StreamAudioEnded`; the stream task's bus events go to the engine's bus, +its frames to the frames bus (both through `LocalCtx`). The watched streams' +video (`StreamFrame`) and audio never cross the `Session` trait in this half. + +The v1 mapping the second half implements (H2), per `StreamCmd` variant: + +| `StreamCmd` | v1 (peer to peer, what TeamSpeak 6 needs) | SFU (VoelinServer, later) | +|---|---|---| +| `Start{setup, auto_accept}` | `Put Stream{kind, title, mode: P2P, access: OPEN if auto_accept else ASK, viewer_limit, audio, bitrate_kbps}`; `accessibility` and `mode` 1 in `Stream.foreign` | `mode: SFU`, `layers` | +| `Stop` | `Delete Stream{id}` | same | +| `Respond{viewer, accept}` | `RespondViewer{stream_id, participant_id, accept, offer}` (offer from the engine's peer) | without offer | +| `Kick{viewer}` | `KickViewer{stream_id, participant_id, reason: KICKED}` | same | +| `Watch{stream_id}` | `Put Viewer{stream_id, participant_id: P, audio, decodes}` | same | +| `Leave{stream_id}` | `Delete Viewer` (own) | same | +| `RequestKeyframe{stream_id}` | inside the WebRTC peer (PLI) | RTCP PLI on `FlowId::FEEDBACK` (`MediaClass::Feedback`) | +| `Undecodable{stream_id}` | renegotiate without the codec (`Signal{stream: offer}`) | `Put Viewer{decodes}` | +| `WatchLayer{stream_id, layer}` | `Signal{stream: layer}` (`x-voelin-layer`) | `Put Viewer{max_layer}` | +| `Layers(specs)` | `Put Stream{layers}` and the local encoders | same | +| `LayerFormat{layer, format}` | local (encoder to peer) | local | +| `SrtpProfiles(names)` | local (peer configuration) | n/a | +| `Frame(frame)`, `VideoFrame(frame, format)` | local (the peer sends them) | `send_media(Video, RTP on the stream slot, sub = layer)` | +| `Friends(clients)` | local (`stream.permissions` decides who is admitted) | `access: FRIENDS` on the host | +| `Directory(streams)` | the gateway daemon's session (protocol 11.2) | n/a | +| `Shutdown(reason)` | local (peer teardown), then `close` | same | + +And back: `OwnStream` ← our `Stream` in LIVE (put, viewer count, delete); +`StreamAudio` ← the peer (SFU: stream slot sub 4, `MediaClass::StreamAudio`); +`StreamAudioEnded` ← the stream or our `Viewer` deleted; the bus events +`StreamsChanged`, `StreamViewers`, `StreamViewerRequest` (a `Viewer` in state +`PENDING`), `WatchState` ← `Stream` and `Viewer` entities; `StreamLayerBitrate` +← the peer's estimate (SFU: `Signal{layer_target}`). + +## 7. Identity and credentials + +- **TeamSpeak identities** go as `Credential::Foreign{kind: "teamspeak", + blob}`, `blob` = the JSON of the `KIND_TEAMSPEAK` `IdentityBlob` of the + KeyStore (`voelin-store` keeps tsproto's `Identity` JSON verbatim). + `TsConnector` parses it back into the `tsclientlib::Identity` it connects + with. No identity in the options (`voelinctl` without `--identity`) is an + empty blob, and the connector generates one as `tsclientlib` does today + (follow-up P11 writes the convention down). +- **The Voelin key** goes as `Credential::Voelin(Arc)`: a + `KIND_VOELIN` blob's `voelin_key()` (`IdentityKey` implements `Signer`), or + a `FileSigner`. Nothing uses it in this half (no `voelin://` connector), but + the conversion is there and tested. +- **The account** is a hook: `ConnectParams.account` is `None` and + `issuer_trust` `Unknown`. `Backends` gets an + `Option>` slot, set by nobody yet. A blob whose + binding has custody SERVICE (no local secret) would be + `Credential::Account{kind: "teamspeak", integration_id}`; without an agent + the connector fails the connect (its contract in `ConnectParams`), and the + engine reports that as `Disconnected`. No such blob reaches the engine + yet. myTeamSpeak keeps going through `TsConnector`'s + watches (4.8) until it moves to `AccountAgent::use_integration` + (`myteamspeak.handshake`, protocol 13.8; H4). +- **Host trust**: `TsConnector` ignores `trust` and `host_pin` (no TLS). The + engine passes a `HostTrust` that refuses until the UI has a TOFU dialog. +- **Slice 1 keeps the API**: `VoiceOptions.identity` is still a + `tsclientlib::Identity`; one function in the TeamSpeak module turns it into + the `Credential`. Slice 3 makes it an `IdentityBlob` (section 10). + +## 8. Files + +The engine owns transfers end to end: progress (`files.progress_ms`), the +`.part` file and its rename, cancel, resume, the picture limits. The +TeamSpeak side only opens the transfer connection, through two inner +commands added to `LinkCmd` in slice 1: + +- `OpenRead{file: Remote, offset, reply: oneshot>}`: + `download_file`, then the `FileDownload` stream and its size go to `reply` + instead of into `files::download`; `FiletransferFailed` → `Err` with the + text `transfer_error` writes today. +- `OpenWrite{file, size, overwrite, resume, reply: oneshot>}`: + `upload_file`, then the `FileUpload` stream and its `seek_position`. + +`files::download` and `files::upload` take `AsyncRead`/`AsyncWrite` instead +of `TcpStream` (their tests keep using TCP). The old `Download`, `Upload` and +`CancelTransfer` handling in `voice.rs` is dead for `LinkSession` from +slice 1 (it never sends them inward) and is deleted in slice 3. Avatars and +icons keep their channel-0 paths (`/avatar_`, `/icon_`) as +`FilePath` reads; v1 has them as attachments (H6). + +## 9. Tests + +### 9.1 `tests/link_fake.rs` through the adapter (slice 1) + +`Engine::start_with_link(FakeLink)` now wraps the link in `LinkSession` and +drives it through SessionLink, so all seven tests run both translations: + +| Test | What it proves through the adapter | +|---|---| +| `presence_follows_the_link_until_it_disconnects` | connect sequence and event order, presence round trip, poke, talking from media, notice → `Error`, `Disconnected(Some)` | +| `commands_reach_the_link` | `SendChat`, `Move`, `SetInputMuted`, `Poke`, `ListFiles` survive both translations; no streams without the capability; stream commands through `StreamPort`; replaced link gets `Disconnect` | +| `a_reconnect_shuts_the_streams_down_before_the_old_connection` | `StreamPort` and `close` share one ordered queue | +| `a_sent_message_and_its_echo_are_one_message` | our message's `Change` is today's echo | +| `a_message_that_comes_twice_is_shown_once` | four `Change`s, `RELAYED` flag, dedup in `session.rs` | +| `history_is_kept_across_the_connection` | DM channel in HOME, late CHAT subscription, `Private(uid)` target | +| `a_replaced_connection_is_ignored` | generation filter with a link that keeps talking after `Disconnect` | + +### 9.2 FakeSession and FakeHost (slice 2) + +New `tests/session_fake.rs`: `Engine::start_with_backends` with a +`FakeConnector` (scheme `fake`) registered, `VoiceOptions::new("fake://host", +...)`, the `FakeHost` filled with `Server`, VOICE `Channel`s, `Role`s, +`User`s, `Member`s and `VoiceState`s through `FakeHost::put` (it stores what +a client cannot set, such as authors), `FakeHandle` for pushes, media, +scripts, held requests and kills. `voelin-proto` with `test-util` is a +dev-dependency of `voelin-core`. + +| link_fake test | FakeSession version | +|---|---| +| `presence_follows_the_link_until_it_disconnects` | host state + `JoinVoice` (the fake assigns `P` and `slot`); `Welcome.host.backend` set with `FakeHost::set_welcome`; poke as `FakeHandle::push(Signal{poke})`; talking by `inject_media` on alice's slot; `Signal{notice}` → `Error`; `kill(Network("server shut down"))` → `"voice: server shut down"`. | +| `commands_reach_the_link` | `FakeHandle::requests()` shows `Put{Message}`, `JoinVoice{password}`, the `notify` (id 0) of `self_mute`, `Signal{poke}` (the fake answers signals `Ack`), and `List{FILE}` (the fake refuses `List.path`: scripted with `Script::answer("list", ...)`). The stream half stays a link test (below). | +| `a_reconnect_shuts_the_streams_down_before_the_old_connection` | stays a link test: it checks the `StreamPort` ordering, which a `FakeSession` has no part in (until H2). | +| `a_sent_message_and_its_echo_are_one_message` | the fake stores our `Put` and pushes its `Change` to CHAT(our channel). | +| `a_message_that_comes_twice_is_shown_once` | four `FakeHost::put(Message)`, one with `MESSAGE_FLAG_RELAYED`. | +| `history_is_kept_across_the_connection` | a DM `Channel{server_id: 0}` (HOME) and its messages; `close` and reopen. | +| `a_replaced_connection_is_ignored` | stays a link test: a closed `FakeSession` stops pushing, so the stale events cannot be produced on purpose. | + +New tests the v1 path needs: a connect that fails (`FakeConnector::fail_next`) +→ `Disconnected(Some(text))`; CHAT re-subscription after moving back is a +delta (`sync.delta`); `ScopeClosed` of CHAT and of LIVE; `Rejected` answers +→ `RequestDone`/`Error` texts; our voice in `FakeHandle::sent_media()` (PT +111, SSRC = flow, marker, empty end, sequence); download and upload against +the fake's channel files, resume offset from a scripted `List`; offline +messages through scripted `Mail` answers (the fake does not store `Mail`); +`HostUpdate` changing the refused features; the conformance suite run +against a `FakeSession` reached through `Backends` (17 cases, a check that +the registry hands the session over untouched). + +The link tests that stay (`a_reconnect_shuts_the_streams_down...`, the stream +half of `commands_reach_the_link`, `a_replaced_connection_is_ignored`) remain +in `tests/link_fake.rs` in slice 2 and move into the crate in slice 3, when +`ServerLink` is no longer public. + +### 9.3 The conformance suite against the TeamSpeak `Session` + +`conformance::run_case` with a harness that opens a `LinkSession` +through `TsConnector` on the dev servers (`VOELIN_LIVE=1`, TeamSpeak 3 and 6 +of `dev/docker-compose.yml`). The suite's `Fixture` needs a `FakeHandle` of +the backend; the TeamSpeak server has none, so the harness passes the handle +of an unrelated `FakeHost` and runs only the cases that never touch it: + +| Case | Expected | Why | +|---|---|---| +| `welcome_matches_features` | passes | session only | +| `close_ends_the_session` | passes | session only | +| `a_stale_rev_conflicts_and_a_patch_writes_only_its_paths` | skipped | no `chat.edit` | +| `requests_apply_in_the_order_they_were_issued` | skipped | no `chat.edit` | +| `list_pages_history` | skipped | no `chat.history` (the embedded gateway keeps no history) | +| `idempotency_keys_apply_a_put_once` | skipped | no `idempotency` | +| `subscribe_syncs_the_scope` | cannot pass | writes to channel 4001, which the server lacks; TeamSpeak channel chat reaches only the own channel | +| `subscribe_resumes_from_a_cursor` | cannot pass | same (4002) | +| `put_answers_entities_and_pushes_the_change_with_the_same_rev` | cannot pass | same (4003) | +| `delete_answers_an_ack_and_pushes_the_removal` | cannot pass | TeamSpeak cannot delete a message; the case needs only `chat` instead of `chat.delete`, so it fails instead of skipping (P8) | +| `a_key_names_an_entity_without_its_server` | cannot pass | needs nothing, but creates `ScheduledEvent` and `Emoji`, which TeamSpeak lacks (P8) | +| `cancel_before_apply_is_cancelled` | cannot run | holds the backend (`FakeHandle::hold`) | +| `notifications_are_fire_and_forget` | cannot run | reads the backend's request log; typing goes to channel 1 | +| `renew_account_follows_the_feature` | cannot run | changes the backend's features by `FakeHandle::push` | +| `media_loops_back` | cannot pass | a TeamSpeak server does not return a client's own voice | +| `files_round_trip` | cannot pass | writes an `AttachmentSlot`; TeamSpeak has channel files, no message attachments; the case needs `files` instead of `chat.attachments` (P8) | +| `the_backend_can_end_the_session` | cannot run | `FakeHandle::kill`; and `LinkSession` reports a kick as `Network(text)`, not `Remote{KICKED}`, until H1 | + +What the suite cannot reach is covered by TeamSpeak session tests of their +own (live, both servers): an own-channel `Put Message` answered, then +pushed to the other session's CHAT scope and back to ours as a `Change` (ids +agree only with H1's native session); `JoinVoice` refusal codes +(`PASSWORD`, `FULL`); a poke `Signal` between two sessions; voice RTP from +one session's slot reaching the other's `MediaSink` (sequence, marker, end); +a channel file written with `write_file` and read back from an offset with +`read_file`. + +## 10. Slices + +Every slice: `cargo fmt --all --check`; `cargo clippy $(scripts/own-crates.sh) +--all-targets --no-deps --locked -- -D warnings`; `cargo test -p voelin-core +--locked` (also `--features media`), the tests of every crate the slice +touches; `cargo check --workspace --locked`; `cargo deny --locked check`; +`scripts/notices.sh` with `THIRD_PARTY_NOTICES.md` regenerated whenever +`Cargo.lock` changes; docs on new public items; the live tests and +`scripts/it-smoke.sh` engine scenarios against the TeamSpeak dev servers +(this repository's `dev/docker-compose.yml`, the same as VoelinGateWay's) +with the results compared to the baseline. One commit per step is fine; no +history rewrite. + +### Slice 0 (precondition): baseline + +On `main` (`59fec5b`), before any code: `VOELIN_LIVE=1 cargo test -p +voelin-core --features media-desktop --test live --test voice_features +--test stream_live --test media_live`, and `scripts/it-smoke.sh ts3 ts6`. +Record which pass, which fail and why: the plan notes they have not run +since Phase 4 step 1, and slice 1's "no behaviour change" is measured +against this record, not against an assumption. + +### Slice 1: the adapter + +1. **Protocol crates at one revision.** `voelin-identity`, `voelin-proto` + and `voelin-model` from VoelinProtocol at one rev (main `c8e0e5a` or + later: it has `AccountAgent`, `IssuerTrust`, `Credential::Account`; + `voelin-identity` changed only in `cert.rs` and `revocation.rs` since + `64808cc`). `crates/voelin-model` is removed and every crate that used it + takes `voelin-model = { workspace = true }` (`voelin-core`, `-ui`, + `-gateway`, `-gateway-proto`, `-observer`, `-android`, `voelinctl`: a + one-line manifest change each, the UI's being a compile fix); the + `[patch]` recipe of `docs/building.md` gains `voelin-model`. + Acceptance: whole workspace builds, all tests green, no source change + besides manifests. Of the model crate's files only `lib.rs` (two more + modules, `perms` and `replica`) and `badges.rs`, `link.rs`, `tree.rs` + (a doc comment and two equivalent expressions) differ. +2. **The seam.** `link/` (Backends, SessionLink, project, media), + `ts_session.rs` (LinkSession, TsConnector, `LinkConnector` for + `start_with_link`), `OpenRead`/`OpenWrite` in `voice.rs`, `files.rs` + generic, `Engine::start_with_backends`. + Acceptance: + - `git diff main -- crates/voelin-core/src/session.rs` is empty; + - the seven tests of `tests/link_fake.rs` pass through the adapter with + only the fixture changes of 5.4; + - unit tests: the presence round trip of 5.1 (book fixtures and generated + presences), `LinkCmd` → v1 → inner `LinkCmd` for every row of + table 3.1 with a recording link, v1 media framing both ways (sequence, + marker, end, whisper, TOC codec), talk tracker timing (400 ms), the close + table of 4.5, the error texts of 4.6, the backend and capability tables + of 4.7; + - live tests and smoke scenarios: no result worse than the baseline + (section 0), in particular `engine_voice_check` (files, avatar, poke, + private and offline messages, friend online, blocked poke), voice + round trip, the TeamSpeak 6 stream scenarios; + - `rg -n 'tsclientlib|tsproto|voelin_query'` over the new + Session-facing modules (`link/backends.rs`, `link/session_link.rs`, + `link/project.rs`, `link/media.rs`) is empty; TeamSpeak types appear + only in `ts_session.rs` and the files that had them before + (`link/mod.rs` keeps `ConnectOptions` and `LinkCtx` until slice 3). + No public item is removed in this slice. + +### Slice 2: tests on FakeSession and FakeHost + +- `tests/session_fake.rs` as in 9.2, the conformance run through `Backends` + (17 of 17), the live TeamSpeak conformance subset of 9.3 with the expected + verdicts asserted per case (2 pass, 4 skipped, the rest not run, each with + the reason of the table in a comment), and the TeamSpeak session tests of + 9.3. +- `tests/link_fake.rs` keeps only the three link tests named in 9.2. +- Acceptance: all of it green on both dev servers; a deliberately broken + translation (for instance a dropped `self_mute` path) makes a + `session_fake` test fail, shown once in the report. + +### Slice 3: the `ServerLink` layer where it is redundant; TeamSpeak types out of the API + +- `ServerLink`, `TsLink`, `Engine::start_with_link`, `LinkCtx`, `LinkCmd`, + `LinkEvent` and `Remote` are no longer public (the engine keeps `LinkCmd` + and `LinkEvent` as `session.rs`'s private vocabulary; the TeamSpeak module + keeps the inner trait). The remaining link tests become unit tests in the + crate. +- `src/ts/` holds the TeamSpeak implementation: `ts_link.rs`, `voice.rs`, + `book.rs`, `ts_session.rs`, `versions.rs`, `identity.rs` (moved with + history). Public as `voelin_core::ts`: `TsConnector` (with + `set_myts_identity` and `set_myts_data`), `versions`, `identity`. This + module is what moves to VoelinGateWay. +- `VoiceOptions` (no longer an alias of `ConnectOptions`): `identity: + Option`, `client_version: Option` (a spec for + `ts::versions::resolve`, passed to `TsConnector` as the link parameter + `client_version`; `Link::parse` ignores unknown keys), `stream_peer: + PeerConfig`, the rest unchanged. +- `Command::SetMytsIdentity` and `SetMytsData` removed (nothing sends them; + `TsConnector`'s setters replace them). `ObserveGateway.identity` becomes a + `Box` (`gateway.rs` parses it); `ObserveQuery.connect` + becomes a core-owned `QueryLogin` (transport, address, user, secret, + server port, server id) that `query.rs` turns into `voelin_query::Connect`. + The public `gateway::connect(url, identity)` takes the blob too (nothing + outside the crate calls it today). +- `voice.rs` loses `Download`, `Upload`, `CancelTransfer`; the picture limits + live in SessionLink only. +- `docs/architecture.md`: "The server link" becomes "The session seam" + (registry, SessionLink, the TeamSpeak module, `StreamPort`, the fix-ups of + 5.3, what is still TeamSpeak-shaped: `u16` client ids and the old model); + the crate table row of `voelin-core` follows; this document's status line. +- `CHANGELOG.md`: it lists user-visible changes only. An entry under + "Changed" only if a difference against the baseline remains visible (none + is intended); the reviewer confirms none was needed. +- UI and `voelinctl`: compile fixes only (identity blob instead of + `tsclientlib::Identity`, the spec string for `client_version`, + `voelin_core::ts::{versions, identity}` paths, `QueryLogin`). +- Acceptance: + - `rg -n 'tsclientlib|tsproto|voelin_query' crates/voelin-core/src --glob + '!ts/**' --glob '!gateway.rs' --glob '!query.rs' --glob '!stream.rs'` is + empty, and the four exceptions use them privately: `gateway.rs` and + `query.rs` are the two observer sources (H5), `stream.rs` is the + TeamSpeak 6 stream task behind `StreamPort` (H2, H3); + - `session.rs` names no TeamSpeak crate; + - no public item outside `voelin_core::ts` names a type of + `tsclientlib`, `tsproto*` or `voelin-query` (checked with `cargo doc` + and a grep of `pub` items); `voelin_core::stream` still re-exports the + WebRTC peer types of `voelin-stream` (`PeerConfig`, `MediaFrame`, + `MediaKind`, `MediaTime`, `Frequency`, `VideoFormat`, `VideoCodec`, + `Codec`, `FrameSource`, `SyntheticSource`): they belong to the peer, + which protocol 6.11 and 11.1 keep in the client, and land in a crate of + their own when `voelin-stream` is split (H3); + - `cargo tree -p voelin-core -e normal | grep -E 'tsclientlib|tsproto'` + may still list them (the TeamSpeak module is still in the crate); + - all of slice 1's and slice 2's checks, live tests and smoke included. + +## 11. Follow-ups + +### 11.1 For the protocol repository (seam, schema, model, suite) + +Nothing here blocks this half: each has a workaround above. + +| # | What | Workaround meanwhile | +|---|---|---| +| P1 | `Hello` has no initial voice channel (path or id, password) for backends that seat a client at connect; a Voelin host could also take it to save the `JoinVoice` round trip. | `ts3server://` link parameters `channel`/`cid`, `channelpassword` (4.2). | +| P2 | Write down that the first `JoinVoice` of a session that its backend seated at connect answers the seat without moving (11.1). | `LinkSession` does it. | +| P3 | A host with several servers: the address (or `Welcome`) should name the one to use. | `List{SERVER}`, the only or lowest one. | +| P4 | `write_file` should answer the offset the backend appends at (`Upload.offset`), so a resume needs no `List`. | `List{FILE}` before a resumed upload; `CONFLICT` on a mismatch. | +| P5 | No sender name or uid for a `Signal` (poke) or message author outside the receiver's view (hidden ServerQuery clients). | A bare `User` with a synthetic id before the signal (5.2). | +| P6 | Schema gaps of TeamSpeak presence: a client icon, a channel limit of 0, the server's platform and version string as sent, a uid that is no byte string (ServerQuery login names). | `Foreign` keys `icon`, `max_clients`, `platform`, `version`, `uid` (F4-F7, F10). | +| P7 | `replica::convert`: SERVER_CHAT and DM channels in `presence_model`; the per-server TeamSpeak avatar read from `User.avatar` instead of `Member.avatar`; `streaming: Some(false)` without the feature; empty `version`; channel role ids not given back; client icon 0; `talking` always `None`. | Fix-ups F1-F10. | +| P8 | Conformance suite: a backend driver trait (hold, release, kill, push, request log) instead of `FakeHandle`, so backend-driven cases run on any backend; chat channel and server chosen by the harness instead of 4001-4020; `needs` fixed (`chat.delete` for the delete case; events and emoji for `a_key_names_...`; `chat.attachments` or a `FilePath` variant for `files_round_trip`); a two-session `media_loops_back` for backends that do not loop back. | The subset of 9.3 and TeamSpeak tests of our own. | +| P9 | `FakeHost` files no `Server` stub or own `Member` in HOME (protocol 5.2). | `List{SERVER}` (4.2). | +| P10 | ServerQuery capabilities (raw, SSH, HTTP) have no feature string. | From the flavor (4.7); they leave with the observer (H5). | +| P11 | Protocol 11.1 could name `Hello.invite_code` ↔ `client_default_token` (privilege keys), and section 13.8 the empty `Credential::Foreign` blob as "generate an identity". | Done that way here. | + +### 11.2 The second half (TeamSpeak `Session` to VoelinGateWay) + +| # | What | +|---|---| +| H1 | A native TeamSpeak `Session` replaces `LinkSession`: `voice.rs` speaks v1 (book → entities without the old model, notifications → `Change`s), real answers for chat and pokes (read-your-writes, errors on the request), a kick as `Remote{KICKED}`, `tsclientlib`'s own reconnect as a new epoch and a full resync, ping and loss in `LinkStats`, whispers (sub 1-6), priority voice (sub 7), typing, the end of a spurt sent twice collapsed to one TeamSpeak packet, every TeamSpeak feature of protocol 9.1. | +| H2 | Streams on v1: the stream task's WebRTC peer moves to the engine and speaks `Stream`/`Viewer`/`RespondViewer`/`KickViewer`/`Signal{stream}` (table 6.4); the TeamSpeak session translates TeamSpeak 6's stream commands (`setupstream`, `joinstreamrequest`, `respondjoinstreamrequest`, `removeclientfromstream`, `streamsignaling`, the notifications); `StreamPort` and `LocalConnector`'s stream part go. | +| H3 | `voelin-stream` split rather than inverted: the TeamSpeak 6 signalling (commands, notifications, signal JSON) goes to VoelinGateWay with the TeamSpeak session; the str0m peer with `PeerConfig`, `MediaFrame`, `VideoFormat`, codecs and simulcast stays client side (with `voelin-media`, or a crate of its own), because protocol 6.11 and 11.1 put the peer in the client. Then nothing in VoelinGateWay depends on `voelin-media`, and the cycle the plan worries about cannot form. | +| H4 | myTeamSpeak through `AccountAgent` (`myteamspeak.handshake` with the 32-byte digest, the presentation, sign-out clearing, protocol 13.8) instead of `TsConnector`'s watches; `Credential::Account` for custody SERVICE identities. | +| H5 | The gateway (`tsgw`) and query sources become a second `Session` to a gateway daemon (protocol 11.2); then F3's `ts:` rule (with a history key migration) and the query capabilities go. | +| H6 | Avatars and icons as attachments (`Image.attachment_id`, content-addressed cache) instead of channel-0 paths. | +| H7 | The UI on the replica (Phase 5): the old-model projection and F1-F10 go; `u16` client ids widen to `u32` participants. | +| H8 | Reconnect with backoff, resume tokens and persisted cursors move to `voelin-sdk` once it exists; the engine consumes the SDK. | +| H9 | Move `src/ts/` (with its live tests) to `voelin-gateway-ts` (features `basic`, `streams`), first behind a `ts` feature of `voelin-core`, then by git tag; the exit check of plan step 6, `cargo tree -p voelin-core -e normal \| grep -E 'tsclientlib\|tsproto'` empty, holds after H1-H3 and this. | + +### 11.3 Coordination + +- `phase5/ui-vm` adds `crates/voelin-ui-vm` and moves UI logic (servers, + settings) into it. Slice 1's model switch needs its manifest on + `voelin-model.workspace = true`; slice 3's API changes (identity blob, + `client_version` spec, `ts::` paths, `QueryLogin`) need compile fixes where + that branch moved `VoiceOptions` and `ObserveQuery` construction. Merge + `phase5/ui-vm` before slice 3, or plan the fixes on top of it. +- Branches that still edit `crates/voelin-model` must make those changes in + VoelinProtocol after slice 1. + +## 12. Risks + +| Risk | Mitigation | +|---|---| +| A presence field gets lost between the two translations (a UI detail disappears). | Round-trip tests on the book fixtures and generated presences; F1-F10 listed; live smoke against the baseline. | +| Event timing changes: `Connected` now follows three syncs and a `JoinVoice`; snapshots are coalesced. | All in process for TeamSpeak (microseconds); the FakeLink tests pin the order; `session.rs` is unchanged. | +| The inner bus of `LinkSession` lags and a request never gets its answer. | Capacity 4096, a timeout on every pending request, lag logged. | +| A uid that round-trips through `User.uid` on one side and through `Foreign` on the other (F10) would key contacts and private history differently. | Both sides use one rule (canonical base64 → bytes, anything else → `Foreign`), asserted by the round-trip test on TeamSpeak 3 and 6 uids, ServerQuery login names and the FakeLink fixtures' `alice=`; checked live (contacts and private history keyed by uid). | +| The model crate switch collides with other branches. | 11.3; the switch is manifest-only. | +| Two adapters cost CPU per voice packet (RTP wrap and unwrap in process). | About a hundred bytes copied per 20 ms per talker; measured once in slice 1 against the baseline's CPU with the smoke's voice scenario. |