323 Commits
Author SHA1 Message Date
faumaray a3964f65f9 Merge branch phase5/gpui-voice into main (GPUI slice 3: voice page, call bar, PTT guards)
CI / Linux checks (push) Failing after 1m47s
2026-11-23 18:38:46 +03:00
faumarayandGemini 4 Neon f4afd83a5f docs: document GPUI voice fix round (PTT guards, compact stage, tooltips)
Update `docs/ui.md` ("The voice page and the call bar") and `CHANGELOG.md` for the fix round: fail-closed `hotkey.rs` loop, hardened `AppState` / `Sidebar` / `MainView` push-to-talk state machine (`button_held`, `hotkey_held`, `shutting_down`, per-event disconnect handling, mode/server/delete/focus/shutdown guards), centred smaller stage and re-shot compact screenshots (`15a1b60`, Xvfb `:621`/`:622`, Mesa 26.3.0 lavapipe), and `IconButton` dynamic tooltip refresh via `ElementId::NamedChild`.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
2026-11-23 08:35:10 +03:00
faumarayandGemini 4 Neon b83481e4cc voelin-gpui: refresh toggle icon button tooltips when their label changes
Key `IconButton`'s GPUI element ID by both its base ID and its label (`ElementId::NamedChild(Arc::new(self.id), self.label)`) while keeping `.debug_selector(...)` equal to `self.id.to_string()`. When a toggle button's label changes (e.g. `call-mic`, `call-sound`, `member-mute`, `user-mic`, `user-sound`, `voice-stage`), GPUI drops stale hover/tooltip state from the old ID and builds the updated tooltip label while all existing debug selectors stay unchanged.

Add a GPUI test covering `call-mic`, `call-sound`, `member-mute`, and `voice-stage` across state flips while hovered.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
2026-11-23 08:31:11 +03:00
faumarayandGemini 4 Neon 15a1b60d8a voelin-gpui: centre the voice page's smaller stage while it fits
Make the compact stage scroll container a flex row (`.flex().flex_row()`) and mark its inner participant row `.flex_none().mx_auto()`, so 1–5 participants centre horizontally above the call bar when they fit while crowded channels (12–25+ people) still start at the left padding and scroll sideways without clipping the first participant.

Add a GPUI layout test pinning both cases (2 and 5 people centred, 25 people unclipped on the left and overflowing horizontally) and re-shoot the two compact screenshots at 1440×960.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
2026-11-23 08:26:14 +03:00
faumarayandGemini 4 Neon a16e4d4b93 voelin-gpui: harden push-to-talk and global hotkey transmit state machine
Track the window hold-to-talk button (`button_held`) beside the global hotkey (`hotkey_held`) and a `shutting_down` flag in `AppState`, closing Security Review MEDIUM #2 and Opus gate probes P1, P2, P3, P4, P5, P6, and P8:

- `stop_transmitting_if_unheld`, `release_button_hold`, and `release_hotkey_hold` keep transmit active while either source holds the session and avoid duplicate start/stop commands (P6).
- `hotkey_transmit(true)` on a different connected server stops the previous held session before starting the new one (Security MEDIUM #2 / P2), while `select_server` preserves `hotkey_held` (P2b) and releases `button_held` when the held server leaves the screen (P8).
- `handle_events` checks `Connected -> !Connected` transitions per event inside the batch loop so a drop and reconnect within one 64-event batch still releases both holds and emits `SetTransmitting(false)` once (P3).
- `setting_changed` releases `button_held` when `audio.transmit` leaves `PushToTalk` (P1/P1b); `delete_bookmark` clears holds on the removed session (P4); `shutdown` sets `shutting_down`, drops `ptt`, and releases both holds before closing sessions, ignoring late `Later` presses (P5).
- `Sidebar` clears `holding` whenever voice disconnects, transmit leaves push-to-talk, the shown server changes, or `AppState::button_held` no longer matches; `MainView`'s focus-loss observer unconditionally releases `Sidebar` and `AppState::push_to_talk(false)` without cutting `hotkey_held`.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
2026-11-23 08:21:09 +03:00
faumarayandGemini 4 Neon 116a26652a voelin-gpui: release global hotkey transmit on desktop removal and task exit
When the desktop's GlobalShortcuts portal or backend removes the registered push-to-talk hotkey while it is held, or when the hotkey command channel closes on task exit, GlobalPtt's event loop now calls transmit(false) before reporting the status or exiting so the microphone cannot stay open.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
2026-11-23 08:13:07 +03:00
faumarayandClaude Sonnet 5.5 1a656eef86 voelin-gpui: a test that the voice page marks no chat as read; a heading
Asking for the voice page opens the channel's chat tab in the state
(logic::show_voice_view, open_chat with focus), which a front end that shows no
chat must not mark as read: the test looks at the store. The properties and
callbacks heading of the voice section is named for the page, so that its anchor
does not collide with the tree section's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 11:00:45 +03:00
faumarayandClaude Sonnet 5.5 4b83c649f7 docs/ui.md: the displays of the voice page's final runs, and a sentence
The pictures were taken on Xvfb :511 to :514 and the figures on :531 and :532 of
the final build (the earlier figures, of 65b60f2, on :431 and :432); the
sentence on the smaller stage said something about the phone it did not mean.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:56:12 +03:00
faumarayandClaude Sonnet 5.5 bc22a97372 docs: the voice page and the call bar (GPUI slice 3)
docs/ui.md: the voice page section (what is on screen, the release guard of Hold
to talk, the global push-to-talk key, the properties and callbacks of the
slice, what the page costs idle and with a talker at 10 Hz, what was seen against
the TeamSpeak 3 and 6 development servers), "What is next" item 3 done, "For the
next slices" pruned (the Hold to talk risk, the hotkey's runtime note and the
SettingChanged note settled, the tree model's note updated) and what this slice
leaves to the chat and stream slices added, the tree section's tables and the
settings row brought up to date; the CHANGELOG entry; the spikes report's
status; six pictures under docs/ui/ (the larger and the smaller stage, dark and
light, the page against a real TeamSpeak 3 talker, a person's card).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:50:09 +03:00
faumarayandClaude Sonnet 5.5 71407181c0 voelin-gpui: the voice page's larger stage scrolls when its rows outgrow the page
A channel of fifty people wraps into ten rows of large avatars, which pushed the
call bar off the page (found with a test of 45 people: the bar was 600 pixels
under the page). The people shrink to what the header and the call bar leave and
scroll with the wheel; the smaller stage's row scrolls sideways (GPUI turns a
vertical wheel into a sideways one for a container that scrolls only that way).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:42:01 +03:00
faumarayandClaude Sonnet 5.5 373805984c voelin-gpui: a disabled icon button keeps its tooltip
The Slint IconButton shows its tooltip while disabled too, which is how the
voice page's stage button says why it is off in a window too short for the
larger stage.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:33:18 +03:00
faumarayandClaude Sonnet 5.5 d2267e55e7 voelin-gpui: run starts the hotkey, the state does not
The previous commit started the global push-to-talk task in AppState::new when
there was an engine, which a test of the state with a real engine has: it
asked the desktop for a shortcut (the X11 backend on whatever DISPLAY is set,
the portal on a Wayland session: a dialog on the user's desktop) and the task's
status line came back to the foreground from a tokio thread, which the test
scheduler reported as a test that is not deterministic (one run in six of
closing_counts_the_sessions_the_engine_was_told_to_close). run() starts it
once the window is open (AppState::start_global_ptt), the state never does,
and the test says so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:33:18 +03:00
faumarayandClaude Sonnet 5.5 65b60f2bb7 voelin-gpui: a test for the deafen mark of the voice page
A person whose sound is off has the headphone mark in the corner of their
avatar, and a talker's bars win over the marks, as in the Slint page.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:18:15 +03:00
faumarayandClaude Sonnet 5.5 c566716b45 voelin-gpui: the volume of a person, on the member card
The Volume rows of the Slint member card (members.slint): what the person is
played at in percent, a mute for us and a slider (0 to 200, steps of 5), both
off for a person the server gave no unique id, since the choice is kept by it.
A click on a person on the voice page or in the members panel opens the card,
so the volume is a click away from the people the voice page shows. The slider
and the button are the actions SetMemberVolume and SetMemberMuted, which go
through voelin-ui-vm's settings_page logic (open_client, then
client_playback_changed: the engine's SetClientVolume and SetClientMuted, the
`client_playback` key, the tree's mark of who is muted), the logic the Slint
front end's volume dialog calls; the dialogs slice keeps the dialog itself.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:17:49 +03:00
faumarayandClaude Sonnet 5.5 04223a785c voelin-gpui: the transmit mode, the volumes and the stage follow the settings
SettingChanged is no longer ignored for the keys the voice page depends on, as
the Slint front end's setting_changed reads them again: `audio` (the transmit
mode: the voice card has Hold to talk for push-to-talk and says "Voice
activity" or "Open microphone" for the other modes, where it had a button or
nothing), `client_playback` (the clients' volumes: the tree and the card show
who is muted) and `ui.voice_compact` (the voice page's stage). The areas that
show them are raised; the development switches keep what they set, and the
sample servers' stage is not read back.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:15:31 +03:00
faumarayandClaude Sonnet 5.5 0b55811e5a voelin-gpui: the global push-to-talk hotkey, started on the engine's runtime
docs/ui.md's list for the next slices: the hotkey portal calls tokio::spawn and
panics where no tokio runtime is current, and a GPUI foreground task has none,
so the task of voelin_platform's HotkeyManager is spawned on the engine's
runtime (hotkey.rs, the Slint front end's GlobalPtt repeated as engine.rs
repeats HostedEngine: it needs the runtime and the front end's own way back to
its state, and the Slint crate cannot be a dependency; tokio's `macros` feature
for its select!, Cargo.lock unchanged). It starts at launch with the settings'
`ui` key (`global_ptt`, `ptt_key`) when there is an engine and no sample
servers, and says how the key stands in the log and in AppState::ptt_status. Its
presses and releases cross to GPUI's thread through Later: a press transmits
into the session on screen while that has voice, and the release ends the
session the press began in, whichever is on screen then; the voice that drops
under a held key ends the hold. The window losing the focus does not cut it:
the key is meant for use while another window has the focus. A change of the key
at run time is the settings slice's (AppState::set_global_ptt is its entry).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:13:46 +03:00
faumarayandClaude Sonnet 5.5 3253357eda voelin-gpui: the release guard of Hold to talk
The risk slice 2 recorded: a key or the button held while voice drops leaves
transmit on. Two cases, two guards. Voice that drops: the voice card, with the
button, goes with it and nothing is left to release, and the session keeps
`transmitting` into the next connection; after each batch of engine events the
root state tells the session SetTransmitting(false) once for every session that
was connected before it and is not after it and still says it transmits (the
engine's own report, so no flag of ours can go stale; it does not answer the
engine's answer, nor a reconnect). The sidebar's own hold is cleared by its
observer of the state, which sets its own field and sends nothing. A window
that loses the focus while the button is held: the mouse button comes up
elsewhere, so MainView's window-activation observer lets the button go and the
session is told. A window that holds nothing sends nothing, since the global
hotkey is meant for use while another window has the focus.

Tests: both guards (and that each fails without its guard, which was checked by
removing it), the hold that is not one, nothing sent for a window that held
nothing.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:10:29 +03:00
faumarayandClaude Sonnet 5.5 3bf21f1b26 voelin-gpui: the sidebar's server card has the server's banner behind it
server_banner, which the tree slice left out, is behind the card as in
ServerHeader of channels.slint: the picture covers the card (cropped to its
padding box, so the border stays), the same surface veil as the tree's banner
rows lies over it, and the stats line reads in the text colour instead of the
muted one. A server without a banner, or whose picture has not arrived, has the
plain card. The picture's corners are square, as the tree's banner rows': GPUI
clips to rectangles.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:05:25 +03:00
faumarayandClaude Sonnet 5.5 ba4fe3c8ca voelin-gpui: the voice channel page and its call bar
Slice 3 of plan section 6 step 3, first part. VoicePage is a cached pane of its
own, a sibling of the server page that MainView puts in the main area while
the page is asked for (show_voice_view, through voelin-ui-vm's logic) and voice
is connected, as the Slint VoiceView is. It shows the channel (name, topic,
banner under the surface veil, "N in voice / limit total"), the people of our
channel as TreeView::members gives them through the tree model's Voice event
(the ring that is green while they talk and blue while they stream, the bars or
the microphone and sound marks in the corner, the crown, "Speaking",
"Streaming", "Away"; a click opens the card), and the call bar: mute, deafen,
Share and the voice settings (both logged until their slices), Leave. The
smaller stage, one row of small avatars, is ui.voice_compact and always in a
window under 800 pixels tall, which MainView pushes into the pane (a cached
pane does not see a resize); VOELIN_OPEN=voice[:compact] asks for it, the
sample servers keep nothing. The server page gets a Voice channel button for
the way in, and the meter counts the page's renders.

Tests on the test platform: the page takes the main area and gives it back, the
people and their marks, talking and mute events redraw the page once and the
rail, top bar and main area not at all (one model build for three lists),
Leave reaches the engine, the call bar's buttons, the stage kept in the
settings and forced short, the banner.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:02:35 +03:00
faumarayandClaude Sonnet 5.5 3fb5de8f32 voelin-gpui: an avatar's picture rounds its own corners
The avatar's face clipped its picture with overflow_hidden, which GPUI makes a
rectangle: a person's picture was a square with the round avatar's ring around
it (the members panel and the tree showed it at 22 to 46 pixels, the voice
page's 80 pixel avatars make it plain). The image element takes the radius
itself.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:01:34 +03:00
faumarayandClaude Sonnet 5.5 6e866b95f6 voelin-gpui: the tree model keeps the people of our voice channel
TreeView::members was built with every tree build and thrown away. The model
keeps it now and emits it as TreeEvent::Voice (the whole list, as it is now)
when it differs from the last: the voice page of the next commits takes its
people from the same build as the tree and the members panel, not from one
of its own, so a talker is still one build for three lists.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 09:51:33 +03:00
faumarayandClaude Fable 5.1 42d74b9594 Merge phase5/gpui-tree-minors: the minors of GPUI slice 2's gate and review (rows in the pane events, talking marks restored for parity, restore_tree on a removed server, banner tints, the no-match text, Escape after a click, the demo-folder leak, the cost records)
CI / Linux checks (push) Successful in 28m17s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 09:25:47 +03:00
faumarayandClaude Fable 5.1 50071d39f4 voelin-gpui: TreeModel watches the one AREAS list; docs/ui.md's signals intro names the parity ruling (review minors)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 09:25:47 +03:00
faumarayandClaude Sonnet 5.5 64b17159be voelin-gpui: the tree has no words of its own for a search it does not have
The tree's empty_words had an arm for Emptiness::NoMatch with a string no user
can reach: the tree's emptiness comes from Emptiness::of, which never says
NoMatch (the members' search is the panel's, TreeModel::people_emptiness). The
arm shares the Connect words now, with the reason in a comment.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 08:26:15 +03:00
faumarayandClaude Sonnet 5.5 a2bdc9d745 docs/ui.md: the tree and the members on the sample server and the dev servers again, after the minors round
The runs of the round's acceptance on the release build of the branch's tip,
each on a display of its own: the talking ring and bars and a selected and a
hovered banner row on the sample server, the Escape after a click on the
password prompt's card, the members search with no match against the
TeamSpeak 3 and 6 development servers (one connect to each, read-only, a clean
close with status 0 and no ghost client on the TeamSpeak 3 one), and the
talking run's figures again at the tip.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 08:25:56 +03:00
faumarayandClaude Sonnet 5.5 1dbe5d5dca docs/ui.md: the records of the tree slice's gate and review for the next slices
What the gate and the review left to the slices that meet them, in "For the
next slices": the model builds the whole tree_view for every batch it hears of
(O(people), a stat per picture; a batch is one build now, a talking-only
refresh path or a reuse of the ImageRefs belongs to the voice page or later);
the rail, the top bar and the main area refresh on the servers flag only, so a
flag voelin-ui-vm forgets to set leaves both front ends stale; the members
search's caret blink draws the window twice a second (measured: 2.00 frames, 2.00
renders of the sidebar and the panel, llvmpipe at 21 % of a core); the
voelin-ui-vm versions of the joins and the card that only the GPUI front end
calls, whose Slint copies can drift; and the TeamSpeak 3 development server's
ban of a burst of connects from one address. The coalescing of the three
signals of a picture that arrives is the commit before, and the first of the
round's has the rule for observers of the signals.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 08:07:11 +03:00
faumarayandClaude Sonnet 5.5 0352d67651 voelin-gpui: the tree model builds its rows once for a change that raises three signals
The model listens to the tree, toolbar and member card signals, and one batch
can raise all three (a picture that arrives raises them all): every observer
call built the whole tree_view again, O(people) with two stats per picture,
so an AvatarReady or PictureReady cost three builds, two of them to find the
rows the first had made. The signals of a batch are raised before the first
is heard, so the model now keeps the generations it last built at and a
refresh finds nothing new when it is the second or third of the batch.

A test counts the builds (TreeModel::refreshes): a picture that arrives is
one build, and so is a batch of two events that raise the same signals (the
picture was three builds with the check disabled). The probe of the first
commit of the round still has its two refreshes in one flush (its observer
raises the signals again), and passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 08:04:33 +03:00
faumarayandClaude Sonnet 5.5 5a5fd9978d voelin-gpui: the banner test removes the sample pictures' folder it made
a_banner_is_drawn_under_a_veil opens the sample servers with their pictures,
which are files of a folder named voelin-gpui-demo-<pid>-N in the temporary
directory; the window's close removes it (AppState::shutdown), but the test
never closes the window and the entity of a gpui test is not released when the
test ends, so every run of the lib binary left a folder: eight runs with TMPDIR
pointing at an empty directory left eight. The test ends with the app's
shutdown now, after asserting that the folder was there and is gone; eight
runs leave TMPDIR empty.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 08:03:17 +03:00
faumarayandClaude Sonnet 5.5 244226d15c voelin-gpui: Escape closes the password prompt wherever in it the last click was
The prompt closed on Escape only while its field had the focus: the field's
own Escape has nothing to undo and passes the key on, and a listener on the
prompt took it. A click on the card off the field (its heading, the disabled
Join) moves the focus away from the field, and with nothing in the prompt
focusable the window's root took it (MainView's focus handle), so the prompt's
key context was off the dispatch path and Escape did nothing.

Escape is now a key binding of the prompt's key context (bound by
shell::bind_keys beside gpui_kit::init, in run() and in the tests), which
dispatches CancelChannelPassword, and the prompt's scrim holds a focus handle
of its own, so a click anywhere in the card leaves the context on the path.
The field's Escape still passes the key on and the binding closes the prompt;
the listener on the field's action is gone (with it the binding would close
twice). A test clicks the card's corner and the disabled Join and presses
Escape: it failed before (the prompt stayed), and the existing prompt test,
which presses Escape in the field, still passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 08:01:54 +03:00
faumarayandClaude Sonnet 5.5 c044f7279a voelin-gpui: a search with no match says "Nobody matches."; connecting is loading
The members panel said "Connect to see who is here." for every empty list
that was not loading, so a search that matched nobody on a connected server
told the user to connect. Emptiness has NoMatch now ("Nobody matches."), for
a non-empty search over a server that has people and leaves none of them; it
is the panel's own (TreeModel::people_emptiness): the tree is not searched,
so the shared Emptiness::of never says it and the tree pane is not told when
the search comes to match nobody (a test counts its renders across the
change). A server whose voice is connecting is Loading, as one that is
observed is, in both panes: its channels and people are on the way.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 08:00:33 +03:00
faumarayandClaude Sonnet 5.5 f28c02a18c voelin-gpui: a banner row shows its selection and its hover over the picture
A channel row paints its selected and hover backgrounds on the row, and the
banner picture, drawn from the indent on, covers them: a banner row showed a
strip of hover left of the picture and no selection at all. channels.slint
tints the hover over the picture with a translucent child (surface-3 at 50 %),
as the own channel's tint is drawn here; the row now does the same, with a
child above the veil for the selected row (surface 3 at 75 %, a state Slint
has none for) and one for the hover (50 %, through the row's group, so the
pointer anywhere on the row tints it). Our own channel keeps its accent tint.

A test selects two banner rows of the sample server in turn and finds the
tint on the selected one only; docs/ui/gpui-tree-banner-selected-dark.png
shows Raid Night selected and the pointer on Music (release build, lavapipe on
Xvfb :233 with openbox).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 07:48:58 +03:00
faumarayandClaude Sonnet 5.5 cc143f312d voelin-gpui: the server shown after a removal has its remembered folds
restore_tree (the folds ui.tree remembers for a server, put into its session
once) ran only in select_server, so the server that came on screen when the
one shown was removed, or when a save or a connect put another on screen, had
none of its folds: its tree showed everything open, and the next fold wrote
the one just made over what was stored.

transition_with, which every transition runs through, now restores the folds
of whichever server it leaves on screen before anything draws it, and
select_server no longer does it by itself. Two tests: removing the server on
screen shows the next with its stored fold, and a fold made then is added to
it where it used to replace it ([3, 7], not [3]); a save of another server
shows it the same way. Both failed on the code before (no session for the
server shown, so no folds).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 07:43:24 +03:00
faumarayandClaude Sonnet 5.5 122b2d29fa voelin-gpui: the tree marks who talks again, the ring on the avatar and the bars on the row
The gate ruled for parity: the tree cleared `talking` on every row to keep its
pane from being drawn with each start and stop of someone's voice, and the
Slint tree (channels.slint) has the speaking ring on the avatar and the bars
on the row. The model keeps the flag now and client_row draws the ring
(Avatar::speaking) and the bars, 14 pixels as SpeakingBars is, after the badges
and before the LIVE mark, as the Slint row orders them.

The cost was measured with the meter at 10 starts and stops a second (the
sample server, release build, lavapipe on Xvfb :231): the tree pane is
rendered once for each, 9.97 a second for 9.97 events, as the members panel is,
and the rail, the top bar and the main area not at all; 102 % of a core in
all, 5.0 % of it GPUI's thread, which is what the run before the change had
(3.1 % to 5.0 %). docs/ui.md replaces the paragraph that said the tree carries
no talking with the figure; the tests that counted the tree as not drawn count
it as drawn once (a talker changes one row and draws the tree once; the tree
and the members panel and no other pane), and the sample server's tree marks
Kairo.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 07:42:20 +03:00
faumarayandClaude Sonnet 5.5 6b01e25391 voelin-gpui: the tree and members events carry the rows their operations lead to
TreeEvent::Rows and ::People carried the row operations only, and the panes
applied them to the model's rows read when the event was delivered. A model
that refreshes twice in one flush (it listens to the tree, toolbar and member
card signals, and a batch raises several) holds the second rows by the time a
pane hears of the first operations, so an observer that changes the state
inside the flush made the first operations index the second rows: the gate's
probe, select_server from the observer of the toolbar signal during a
Presence flush, panicked in ChannelTree::apply on the shrink.

The events now carry the rows (Rows(Changes, Arc<Vec<TreeItem>>), People the
same) and the panes apply the operations to the rows they have and keep the
carried ones, so the events lead from the rows a pane started with to the
model's last whatever the order of the flush. apply checks the counts in
debug builds (debug_check), and "For the next slices" has the rule: a signal's
observer reads the state and sets its own fields, a change of the root state
is an action's or a task's. The probe is a test
(a_state_change_inside_a_flush_does_not_apply_old_operations_to_new_rows); it
panicked on the code before ("index out of bounds: the len is 0 but the index
is 3", channels.rs) and passes now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 07:22:58 +03:00
faumarayandClaude Fable 5.1 e61919ebf4 Merge phase5/gpui-tree: slice 2 of the GPUI front end, the channel tree and the members panel as cached panes with per-area signals (plus the shell minors' three preliminaries)
CI / Linux checks (push) Successful in 31m33s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 07:13:40 +03:00
Aleksey Selihov b08bda599d Merge pull request 'CI: the VoelinProtocol deploy key lives for one trusted fetch step' (#2) from phase5/ci-deploy-key-hardening into main
CI / Linux checks (push) Successful in 32m20s
2026-10-28 01:27:14 +00:00
faumarayandClaude Sonnet 5.5 9139e50b5e docs/ui.md: the server card's banner has a home in the next slice's list
The table of the Bridge's properties says server_banner is not drawn by the
sidebar's server card and that the voice page and call bar slice takes it;
that slice's item in "What is next" now names it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 04:18:55 +03:00
faumarayandClaude Sonnet 5.5 4141b9b3aa docs/ui.md: the meter and the live runs again on the build with the review's fixes
The release build of bad5312 on my own displays: idle 0.6 % and no pane
rendered, a sample person talking 10 times a second rendered the sidebar and
the members panel 10 times a second and no other pane; against the TeamSpeak 3
development server the double-click join, the password prompt (Join dimmed,
Enter on an empty field and Escape, a wrong password asked again in words, the
right one joining) and the close (status 0, no ghost client), and the TeamSpeak
6 server's tree and panel.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 04:01:28 +03:00
faumarayandClaude Sonnet 5.5 14091c4202 docs: the ui.tree row, every property and callback of the two panes, the long lines
The review of the channel tree slice: the Settings table of docs/ui.md has a
ui.tree row (JSON by server id, written by the GPUI front end only); "The
callbacks and the properties" lists every Bridge property and callback (and
the Nav functions) that channels.slint and members.slint use, with the plan's
13 and 6 named inside them and each with its GPUI counterpart or the slice
that takes it (watch_client, member_action, member_volume and server_banner
included); the tree's banner veil, the one-letter small avatars and the
password prompt's empty field and Escape are described; the two tree pictures
with banners (light and dark) are taken again on the release build of bad5312.
The paragraphs the previous re-wrap left long are wrapped, the CHANGELOG entry
and the spikes report's status say what the review closed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:54:35 +03:00
faumarayandClaude Sonnet 5.5 bad5312bfd voelin-gpui: the password prompt ignores an empty field and Escape closes it
The Slint dialog (ChannelPasswordDialog) turns Join off and ignores Enter
while the field is empty, keeping the dialog open, and closes on Escape. The
prompt here took itself away before join_with_password refused an empty
password, so Join or Enter on an empty field closed it without a join, and
Escape did nothing (the field's own Escape passes the key on).

The submit now reads the field first and leaves the prompt open when it is
empty; Join is disabled while it is (the field's changes redraw the prompt);
the prompt handles the Escape the field passes on and cancels. The prompt's
test covers Join and Enter on an empty field, Escape (nothing sent, the
channel no longer the one to join), and a typed password entered with Enter.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:49:05 +03:00
faumarayandClaude Sonnet 5.5 c158bdda00 voelin-gpui: an avatar under 28 pixels shows one letter, at half its size
The tree's 22 pixel avatars wrote two-letter initials at 0.38 of their size,
about 8 pixels, cramped; avatar.slint writes the first letter at 0.5 of the
size under 28 pixels, through voelin_ui_vm::avatar::first_letter. The rail's
and the cards' larger avatars are as they were. A test states the rule at 22,
27.9 and 28 pixels, for an empty name and for a letter with a mark.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:48:47 +03:00
faumarayandClaude Sonnet 5.5 f8cf6a3561 voelin-gpui: a channel's banner is drawn under the surface veil, as the Slint tree's
A channel row drew its banner picture at full strength under the name, so
Theme.text could sit on a picture of its own colour (dark text on the sample
server's dark banners in the light theme, light text on a bright TS6 banner in
the dark one). banner-picture.slint lays the surface colour over the picture,
74 % opaque on the left and 66 % on the right; the row now does the same, over
the picture and under the tint of our own channel.

A test keeps the veil: the text of both themes has more than 4.5 to 1 against
the weakest end over a black and over a white picture, and the gradient is the
surface colour at those two opacities; another finds the veil on the sample
server's banner rows and on no other.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:48:31 +03:00
faumarayandClaude Sonnet 5.5 3f7aecfd61 docs: ci.md, wording of the run 1224 note
CI / Linux checks (pull_request) Successful in 32m49s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:39:51 +03:00
faumarayandClaude Sonnet 5.5 06478dc13a docs: ci.md says what run 1224's cancellation was (observed, not explained)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:37:47 +03:00
faumarayandClaude Sonnet 5.5 36c90c4595 docs: ci.md records what was seen on runs 1225 and 1226 and what was only rehearsed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:37:38 +03:00
faumarayandClaude Sonnet 5.5 4b31564d51 ci: the temporary commit reverted (MIN_MASKING_RUNNER_VERSION back to 3.1.0): the workflow is that of the commit before it
Run 1225 of the temporary commit: the runner "Perfrormance Runner" (v3.1.0) was
refused by the check, the job failed there, the system packages, the toolchain,
the key step, the fetch and the checks were not started and left no line in the
log, the cleanup step said that no key is left, and the log has no mention of the
secret.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 03:00:05 +03:00
faumarayandClaude Sonnet 5.5 2005d26649 ci: TEMPORARY, MIN_MASKING_RUNNER_VERSION 99.0.0, to see the gate refuse a real runner (reverted by the next commit)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 02:59:14 +03:00
faumarayandClaude Sonnet 5.5 2cf8bc7fda docs: VoelinProtocol access (ci.md) for the fetch-then-delete key, the runner gate and the fork check; deploy key id 7
ci.md rewrites "VoelinProtocol access" on the model of VoelinGateWay's: the
steps in order, the fork rule in the expression and the script, the release
agent, the four images, the runners that printed the keys, how to look at a run,
what the hardening does not do. The Gitea intro no longer says that pushes and
pull requests are off (the workflow has run on them since 2026-10-12).
building.md and release.md follow; CHANGELOG appended.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 02:55:23 +03:00
faumarayandClaude Sonnet 5.5 91dce84b36 release and the images: the agent only for cargo fetch, stopped after the builds, never on a runner that may print the key
release.yml checks the runner version before any step names the secret (same
gate as ci.yml), starts the ssh-agent only on the positive flag, and stops it in
an always() step right after the last build, so the artifact upload and the
release draft have neither the key nor the socket. The four Dockerfiles (linux,
windows, android, the gateway image) give the agent to `RUN cargo fetch --locked`
only; the build after it has no ssh mount and is offline (--offline, and
CARGO_NET_OFFLINE for the Android Gradle task, which starts cargo-ndk).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 02:55:23 +03:00
faumarayandClaude Sonnet 5.5 cfde421af4 CI: the VoelinProtocol deploy key lives for one step, cargo fetch, and the checks run offline
The job checks first that it may hold the key (a runner that reports 3.1.0 or
newer, which masks a multi-line secret in the log; on a pull request, a head
branch in this repository, asked in the job-level expression and again in the
script from the head repository's name), installs the system packages and the
toolchain, writes the key to a directory of its own for one step (no ~/.ssh
configuration; the step removes the directory itself on any way out but its last
line), fetches with `ssh -i` and the committed host key (`cargo fetch --locked`)
and deletes it, and a step that always runs deletes it again. The checks action
has no input and no secret and every cargo command in it is --offline.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 02:55:23 +03:00
faumarayandClaude Sonnet 5.5 0e01b60930 docs: re-wrap three lines the slice's own edits left long
The maximized paragraph of docs/ui.md (the guard sentence joined onto a
line), the sequences bullet of "Shared with the Slint front end", and the
spikes report's shell paragraph. Prose only; no word changed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 01:56:39 +03:00
faumarayandClaude Sonnet 5.5 639a173092 docs/ui.md: name the binary of the first meter run and of the live run exactly
Both were release builds of the tree that aa640cf then committed (built just
before it; the commit added tests after), not of a commit of their own.
Prose only: the own-crates result of b27b7c7 applies.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 01:56:02 +03:00
faumarayandClaude Sonnet 5.5 b27b7c7f32 docs/ui.md: the figures of the final code commit and where each run's binary came from
The idle and talking figures are measured again on the release build of
faef132 (97 % of a core at 9.7 frames a second with a sample person talking
ten times a second, of it 91 % the software renderer and 5 % GPUI's thread;
the first, quieter run is kept beside it), the live run names its binary
(aa640cf), and the sample pictures' folder is said to go when the window
closes (checked on a real Alt+F4).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 00:47:23 +03:00
faumarayandClaude Sonnet 5.5 faef1325ab voelin-gpui: the sample pictures only when asked and removed at close; two small fixes
- The sample servers' pictures were written to a folder of the temporary
  directory by every state that showed them, tests included, and the folder
  went only with a dropped state, which the test platform and a killed run
  never do. The pictures are now a switch (Switches::demo_pictures: what
  VOELIN_DEMO_UI sets, and what a test asks for by name) and the folder is
  removed when the window closes (AppState::shutdown) as well as with the
  state.
- The tree does not redraw for a change of the people's count, which is the
  members panel's, and an unfolded channel leaves no empty entry in what the
  trees remember.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 00:40:25 +03:00
faumarayandClaude Sonnet 5.5 68a1694d7b docs: the channel tree and the members panel, its pictures, figures and records
docs/ui.md: a section for slice 2 (what is on screen, the per-area signals
and cached panes with the three rules GPUI taught, what a change costs, seen
against the TeamSpeak 3 and 6 development servers, the callbacks and the
properties as tables, what differs from the Slint tree and panel), the
switches VOELIN_DEMO_SERVER and VOELIN_DEMO_TALK and the per-pane counters of
the meter, what is shared with the Slint front end, "What is next" (the voice
page and the call bar are next) and "For the next slices" without what this
slice did (cached panes and signals, the pictures), with the click and hover
cost, the missing scrollbar and the three copies that stay in the Slint
crate. The four pictures are the shell at 1440 by 960 under
scripts/gpui-shot.sh on a display of its own. The CHANGELOG and the spikes
report's status say what landed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 00:24:28 +03:00
faumarayandClaude Sonnet 5.5 aa640cf2b0 voelin-gpui: VOELIN_DEMO_SERVER, the logged Move to my channel, and what a click costs
- VOELIN_DEMO_SERVER=<0..2> puts another sample server on screen: the second
  is observed and the third is not connected, both with empty trees, which is
  how the pictures of an empty server are made.
- The person's context menu offers Move to my channel; the engine has no
  command to move another client, so the action is logged.
- A test that holds what the caches cannot save: pressing and releasing a
  clickable element refresh the window, so a click renders every pane, and a
  hover renders only the pane the pointer is over.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 00:14:46 +03:00
faumarayandClaude Sonnet 5.5 26302bcdde voelin-gpui: the members panel and the member card, the sample server's pictures and a talker
Slice 2, second half. The right panel of a server on screen (as wide as
ui.members_width) is everyone on the server in sections from voelin-ui-vm's
rows (server_members: those streaming first, then each server group), with
"Members - N", a search (search_members), and per person the avatar with its
presence dot and speaking ring, the name with the admin, priority, commander
and recording marks and their myTeamSpeak badges, what they do, the role,
LIVE, the mute marks and the hand of a person who needs talk power. It is a
cached pane over a virtual list that applies the model's row operations, and
the pane a talker redraws: nothing else of the window is told.

A click on a person opens their card over the panel (tree::member_card:
name, status, description, groups, badges, talk power, country) with a scrim
a click outside closes; it follows the person while open and goes when they
leave. Its buttons (volume, message, poke, friends, block) are the slices
of those dialogs.

Development: VOELIN_DEMO_UI now also delivers the first sample server's
avatars, icons, banners and badges as files of a folder of the state's own
(removed with it), and VOELIN_DEMO_TALK=10 makes a sample person start and
stop talking that many times a second through the app's events: what the
meter measures while someone talks.

Tests: the sections and the search, a talker redraws the members panel and
no other pane, the card (open, follows, closes three ways, goes with the
person), an avatar written again shows under a new key and the old copy goes
from the asset cache, the sample pictures and the talker.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 00:03:39 +03:00
faumarayandClaude Sonnet 5.5 b1f673fce3 voelin-gpui: the channel tree, with a password prompt and what it remembers
Slice 2, first half: the sidebar's placeholder becomes the selected
server's channel tree from voelin-ui-vm's rows (tree_view): nested
channels with their spacers, icons, banners, lock and counts, and the
people in them with their avatar, badges and marks. A TreeModel entity
builds the rows once for both panes on the tree, toolbar and member-card
signals and tells what differs (list::diff, the row operations the Slint
front end applies to its VecModel); ChannelTree is a cached pane over a
virtual list that applies them, so a person who joins is a row inserted
and the scroll stays. The rows carry no `talking`: a talker redraws the
members panel, not the tree (docs/ui.md says so).

A click selects a channel, a double-click joins it (sequence::join_channel:
the move, the prompt for a locked channel's password, a connect into it
without voice), the chevron folds it, a right-click offers Join, fold and
Edit channel (logged: the channel editor is another slice), a click on a
person is logged (their volume dialog is another slice). The password
prompt (Update::password) is a card over the window, asking again when the
server refuses the password. The folds and the selection are kept per
server in ui.tree and found again by the next run.

The shell's cached panes lay out their root at the size the place gives
them (size_full), which the main area needed.

Tests: the sample server's rows, folding and its settings, the round trip
through a closed run, double-click and action join, the password prompt
and its refusal, a move (the exact row operations) and a mute (one row),
a talker leaves the tree alone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:56:39 +03:00
faumarayandClaude Sonnet 5.5 d0bcf1f5b2 voelin-gpui: pictures keyed by the file and its stamp, Update.reloaded honoured
GPUI's img(path) keeps what it decoded under the path alone, so a
picture the engine writes again into the same cache file (an avatar or
a server icon that changed) stayed stale on screen. Pictures are now
drawn through a loader keyed by PictureKey, the path and the Stamp the
reference carries (voelin-ui-vm's ImageSource::File): a reference made
after the file changed is another picture, decoded anew, and the lists
that show it compare unequal and draw the row again. perform hands the
paths of Update.reloaded to pictures::forget_stale, which drops the
copies decoded under a stamp the file no longer has and the textures the
atlas made of them. The Avatar widget uses it.

Tests: the key follows the file; a picture rewritten into the same file
is decoded again and the old copy is dropped from the asset cache.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:40:36 +03:00
faumarayandClaude Sonnet 5.5 b133412700 voelin-gpui: Update.refresh as per-area signals, the shell's panes cached
The "for the next slices" design of the shell's review. The root state
turns the flags of an update into entities with a generation, one per
area (servers, toolbar, tree, member card; crate::signals), raised once
per batch of engine events and once per transition, and the rail, the
top bar, the sidebar and the main area listen to their areas instead of
asking the root whether anything changed for them. The rail, the top bar
and the main area are embedded with Entity::cached and a size of their
own, so gpui-pre renders them again only when they were notified, and
the meter counts the renders of each pane (rail, topbar, sidebar, tree,
main, members) beside the window's frames.

voelin-ui-vm: Refresh::merge, for the flags of a batch.

Tests: a burst raises each area once per batch; a change of the voice
card renders the sidebar with every frame and none of the cached panes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:37:37 +03:00
faumarayandClaude Sonnet 5.5 a2b064bb57 voelin-ui-vm: what the channel tree and the members need of both front ends
The GPUI tree and members pane (the next commits) call these; the Slint
front end keeps its own copies of two of them, since voelin-ui is not
edited in this round (docs/ui.md says which).

- tree::member_card: the card over a member row, built from the session,
  the contacts and the local playback (the Slint members.rs builds the
  same inline).
- servers::sequence::join_channel, join_with_password and connect_into:
  a double-click in the tree, the password dialog's Join, and the connect
  into a channel of a server with no voice (the Slint bind/servers.rs
  has the same three, over logic::join_channel).
- servers::logic::open_member: the card of a client opens or closes.
- settings::UI_TREE (ui.tree), TreeState: the channels each server's tree
  has folded shut and the channel selected, by bookmark id. Like ui.window
  it is the GPUI front end's own key; Slint's tree forgets both at exit.
- image::Stamp is Hash, so a front end can key a decoded picture by the
  file and the stamp it had.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:30:59 +03:00
faumarayandClaude Sonnet 5.5 6b8f933ece Re-wrap the four over-long lines the shell's review named
CHANGELOG.md (the shell's entry), docs/ui.md (the maximized paragraph),
docs/design/gpui-spikes.md (the status paragraph) and the module doc of
voelin-gpui's app.rs: prose only, no word changed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:23:36 +03:00
faumarayandClaude Sonnet 5.5 870eb5d938 voelin-ui: the settings page asks the store which identity a bookmark uses
The Slint settings page kept its own copy of Store::identity_id_for and
Store::identity_for (the bookmark's identity if the store has it, else
the default). Both now call the store's, after looking the bookmark's
named identity up: the shell's minors review found the copy, and the
GPUI front end and voelin-ui-vm already use the store's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:23:31 +03:00
faumarayandClaude Sonnet 5.5 9ab56ec973 voelin-gpui: the maximize guard covers the first two reports only
A window opened to be maximized dropped every windowed report until it
was seen maximized, so a resize the user made before the window manager
answered (or under one that never maximizes, a tiling one) was never
kept. The guard is now a budget of OPENING_REPORTS = 2 windowed reports,
the place the window opened with and the configure an X11 window manager
may send at the map; a maximized report ends it, and the reports after
it are the user's. Tests on the GPUI test platform: the root state keeps
the third report, the shell keeps a resize that follows the two. The
sentence in docs/ui.md says so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:22:40 +03:00
faumarayandClaude Fable 5.1 0d44148ef5 Merge phase5/gpui-shell-minors: the minors of the shell's gate (the redraw records and the cached-panes note, the maximize restored on X11 after the first frame, the pictures at 1440x960, no DNS in a test, the helpers both front ends share moved into voelin-ui-vm, the ui.window row)
CI / Linux checks (push) Failing after 50m20s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 22:50:32 +03:00
faumaray daa2111ea1 Merge remote-tracking branch 'origin/main' into phase5/gpui-shell-minors 2026-10-27 22:50:14 +03:00
faumarayandClaude Fable 5.1 cc7c45b371 Merge phase4/protocol-pin-v0.2.0: VoelinProtocol pinned at the tag v0.2.0 (root and spikes workspaces), the spikes' stale lock repaired
CI / Linux checks (push) Has been cancelled
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 22:18:48 +03:00
faumarayandClaude Fable 5.1 5710aa9f79 docs: building.md says tag, not rev, and warns about cargo update -p; the seam's header names 17.9 (review nits of the pin move)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 22:18:48 +03:00
faumarayandClaude Sonnet 5.5 463ce872f2 docs/ui.md: corrections to the minors round's records
Update's description lists the gateways to look up (Update::discover), the
Wayland maximize is said to be expected, not seen (it was not run here), and
three lines of the new text are wrapped like the rest.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 21:55:51 +03:00
faumarayandClaude Sonnet 5.5 fd6bc19c78 docs: the pin is the tag v0.2.0
CHANGELOG.md, "Unreleased": the line that VoelinProtocol's CHANGELOG offers
consumers when they pin (the sign-out lists a key once, Debug of the
messages prints <redacted> for secrets). docs/building.md names the tag, how
a later release is taken and the spikes' own lock; docs/ci.md and
docs/architecture.md name the three crates and the tag, and ci.md says that
the deploy key, the host key and the read check of the CI step are the same
for a tag. docs/session-seam.md: 17.9 records the move (the commits, the lock
edited by hand and why, what "For consumers" meant for the tests, what ran),
and the four sentences that named the old rev name the tag or the pin of
task 34.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 21:17:53 +03:00
faumarayandClaude Sonnet 5.5 6938dbed3a Pin VoelinProtocol at the tag v0.2.0
The three entries of [workspace.dependencies] (voelin-identity, voelin-proto,
voelin-model) were pinned by rev c5bb6b9 and are now { git, tag = "v0.2.0" }
(a45c154), and so is voelin-model in spikes/gpui. Cargo.lock of both
workspaces changes in those packages only: the three sources, and
voelin-model 0.1.0 -> 0.2.0 (the crates' manifests are otherwise the same
at both revisions, so the lock was edited by hand and checked with
--locked; `cargo update -p` also moved eleven unrelated edges, such as
windows-sys 0.61.2 -> 0.52.0, and was discarded). One revision of each
crate in both locks. THIRD_PARTY_NOTICES.md is unchanged
(scripts/notices.sh --check is clean).

What "For consumers" of the protocol's CHANGELOG lists for this pin:
- KeyStore::sign_out lists a device key once. The test that unbinds a device
  key whose row carries a device-only binding counted it with `contains`; it
  now counts one entry in `unbound` and none in `removed`, and a new test
  does the same for Forget (one entry in `removed`, none in `unbound`). Both
  fail with the pin at c5bb6b9.
- Debug of Hello, Welcome, Server and others prints <redacted>: no test of
  the client compares a Debug text of a protocol message.
- The conformance suite still has 17 cases; the two places that named the old
  rev in a string or a comment name the tag.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 21:03:05 +03:00
faumarayandClaude Sonnet 5.5 dccedf2fcd spikes/gpui: Cargo.lock follows voelin-platform's zbus change
ed49c28 (zbus on async-io alone in every binary) changed what the spikes'
graph enables of tokio and zbus, and the spikes' lock was not refreshed:
`cargo build --locked` in spikes/gpui failed on main with "cannot update the
lock file". The lock loses three dependency edges and nothing else: tokio's
signal-hook-registry and tracing, and zbus's tokio. No package is added,
removed or moved.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 20:45:58 +03:00
faumarayandClaude Sonnet 5.5 4f85b5539e docs: the shell's minors round recorded, with the gate's four risks
docs/ui.md: a paragraph in the shell section for the minors round, the run
under openbox before and after the maximize fix (the same copy of a database
that says maximized: true: not maximized and overwritten with false before,
maximized and kept after), the maximize beside the position caveat of "For the
next slices" with the one race it cannot rule out, and the four risks the gate
found by reading: the server on screen not remembered across restarts, an open
form dropped without asking on a rail click, Hold to talk staying on if voice
drops while held, a tiling compositor's tile stored as the window size.
The spikes report's status paragraph says the shell was gated and its minors
closed on this branch.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 20:40:06 +03:00
faumarayandClaude Sonnet 5.5 f7ebab0859 docs/ui.md: the ui.window row of the settings table, and assets.rs in the step 9 note
The settings table lacked the key the shell added: ui.window, JSON
{width, height, x?, y?, maximized}, no default, written by the GPUI front end
only. The note on what reads crates/voelin-ui/ui until Slint goes lists
assets.rs's include_bytes! of logo.svg beside the parity test, build.rs and
fonts.rs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 20:08:49 +03:00
faumarayandClaude Sonnet 5.5 a77ccc0415 voelin-ui-vm: the server sequences both front ends ran twice are one
The GPUI shell repeated the Slint crate's connect, observe, gateway lookup,
save and remove of a server, its default nickname, its FallbackSecrets and its
settings opening and key registration. They now live once and both front ends
call them:

- voelin_ui_vm::servers::sequence: connect_voice(_to), observe,
  discover_gateway, gateway_found, select_server, save_bookmark,
  save_and_connect, delete_bookmark, bookmark_form and default_nickname, as
  transitions over the state, the Cx and a Backing (the store, the secrets,
  the identity a connection uses). The commands, the status line and what to
  keep go out through the Update as for every other transition; a new field,
  Update::discover, asks the front end to look a gateway up (the thread hop
  stays with each front end: Later in GPUI, later() in Slint). stream_peer is
  the one input a front end gives (Slint's codecs; GPUI passes none).
- voelin_ui_vm::settings::open_settings and register_keys; a front end adds
  its own key (ui.window, studio.ui) through a function it passes, so Slint's
  settings page still lists what it listed.
- voelin_store::FallbackSecrets (feature keyring) and Store::identity_for.
- voelin-ui: the methods of servers/bind.rs, open_settings and default_secrets
  call them, so their call sites are unchanged; host.rs gets transition_with
  and the discover arm of perform. voelin-gpui: AppState's methods and the
  Backend call them. What cannot move is named in docs/ui.md.

voelin-ui-vm now depends on tracing (the sequences log as the copies did): one
line of Cargo.lock, THIRD_PARTY_NOTICES.md unchanged (scripts/notices.sh
--check clean), cargo deny check clean. The sequences have ten tests over a
fake front end (commands, status, store, secrets, gateways), open_settings and
Store::identity_for one each; the GPUI and Slint suites pass unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 20:05:46 +03:00
faumarayandClaude Sonnet 5.5 01bf128c58 voelin-gpui: the connect test makes no DNS query
a_connect_reaches_the_engine_and_its_answer_reaches_the_rail connects a
server called ts.example, and a connect looks the server's gateway up:
SRV queries for _tsgws._tcp.ts.example sent to the resolver (docs/ci.md
says tests use no DNS). The test now marks the lookup done before the
connect, as the second connect of a run finds it, and its comment says so
(it also claimed nothing left the machine).

strace -f -e trace=connect,sendto,sendmsg,sendmmsg on the lib test binary:
the old binary's test sends to 127.0.0.53:53 (and asks nscd over a unix
socket); the new one, alone and with all 79 tests of the binary, makes
no connect and no send at all.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 19:32:14 +03:00
faumarayandClaude Sonnet 5.5 806f9c6f2e docs/ui: the shell and swatch pictures at 1440 by 960
The committed pictures were 1438 by 935 (and the form 1280 by 800): taken
on a screen as large as the window, where openbox fits the window and its
frame into the screen. Regenerated the five shell pictures and the two
swatch pictures on a headless X display of 3840 by 2160 (scripts/gpui-shot.sh
under spikes/gpui/headless.sh; the form with xdotool clicks and typing), all
exactly 1440 by 960 and truecolour. docs/ui.md and the script's header now say
the screen must be larger than the window, and how the form was taken.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 19:31:30 +03:00
faumarayandClaude Sonnet 5.5 302524a144 voelin-gpui: a window left maximized is maximized again, and stays remembered so
GPUI asks for a maximized window before it maps it, and an X11 window manager
manages a window only from its map (openbox loses the request), so a window
the last run left maximized opened at its restored size, and the next close
overwrote maximized:true with false.

MainView now zooms the window at its first frame when it was opened to be
maximized and is not by then (zoom toggles on X11, so a maximized one is left
alone). The root state keeps what such a window reports as not the user's
until the window has been seen maximized, so a run that ends first, or one
whose window manager never maximizes, leaves maximized:true as it found it;
a maximized window is kept with the size it returns to (X11 reports the
screen's). GPUI's test platform has no zoom, so the tests count the request
and play the window manager's answer; the X11 behaviour was seen under
openbox on a private Xvfb and is recorded in docs/ui.md. CHANGELOG notes it.

Also wraps the module comment of app.rs that the previous commit left long.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 19:29:29 +03:00
faumarayandClaude Sonnet 5.5 7c0f385f2f docs: a part's notify draws the whole window, not just the part
The records said the shell's parts draw only when what they show changed.
In gpui-pre 0.3.10 a child view embedded with .child(entity) is rendered
on every frame (only Entity::cached and AnyView::cached reuse a subtree),
so a part that is told tells the window, and the window draws every part.
Correct the shell section of docs/ui.md, the status paragraph of the
spikes report and the module comments of the shell and the root state,
and add to "For the next slices" the gate's notes: heavy panes cached and
Update.refresh turned into per-area signals, Update.reloaded ignored and
img() caching by path, SettingChanged for audio and playback not reloaded.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 19:12:52 +03:00
faumarayandClaude Fable 5.1 0d32ac25f0 Merge phase5/gpui-shell: slice 1 of the GPUI front end, the desktop shell (the store at start, the server rail, the sidebar, the top bar, the main area, window state in ui.window, the bookmark and connect actions through voelin-ui-vm)
CI / Linux checks (push) Successful in 40m16s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 19:07:32 +03:00
faumarayandClaude Sonnet 5.5 8773d8df5b docs/ui.md: the idle figures name the commit they were measured on
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 17:29:56 +03:00
faumarayandClaude Sonnet 5.5 770943cde9 docs/ui: the swatch pictures without the line of state
The window's line of state (the version, the connections, the engine events,
the seconds up) is gone with the shell: the swatch page fills the window, so
the two pictures are made again with the binary of this branch
(scripts/gpui-shot.sh swatch 1440x960, dark and light).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 17:27:07 +03:00
faumarayandClaude Sonnet 5.5 2e961eb411 docs: the GPUI desktop shell (docs/ui.md, CHANGELOG, the spikes report's status)
docs/ui.md, "The GPUI front end": what exists now (the store at start, the
shell's entities, the quiet tick), the shell's section with its pictures (the
empty shell and a server on screen, dark and light, and the server form, made
with scripts/gpui-shot.sh on a headless display), the eleven actions against
the Slint callbacks, the store, the window's place and what the shell leaves
out, the figures idle (0.3 to 0.5 % of a core, 192 MiB, no frame drawn while
nothing happens) and what was seen against the TeamSpeak 3 development server
(connect, mute, disconnect, reconnect, close with no ghost client); the
slice list says the shell is done and the channel tree is next, and "For the
next slices" says what the shell settled (the event task, the tick, the close
grace) and what it found (the focus the root's handlers need, the window
manager's say over the position).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 17:24:56 +03:00
faumarayandClaude Sonnet 5.5 b218059a20 voelin-gpui: the close grace sleeps inside the runtime
`runtime.block_on(tokio::time::sleep(CLOSE_GRACE))` makes the Sleep before
block_on enters the runtime, which panics ("there is no reactor running") on
the GPUI thread; the foundation had it because no slice opened a session, so
the grace never ran. The first end-to-end close against a server (the TS3 dev
server, a connected window closed with Alt+F4) found it: exit status 101 after
the engine had sent the close. The sleep is made in an async block now, as the
Slint front end does, and a test calls the wait from a thread that is no
runtime thread (it fails with the old form).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 17:24:30 +03:00
faumarayandClaude Sonnet 5.5 6b4341ab8c voelin-gpui: the desktop shell, the server rail, the sidebar, the top bar and the main area
Slice 1 of plan section 6 step 3 (docs/ui.md, "The GPUI front end"). The window
is the shell of ui/shells/desktop.slint, as entities that observe the root
state and tell the window only when what they show changed (they compare their
view of the state, so an engine event about a talker, a tick or a setting that
is not the theme's draws nothing):

- shell/rail.rs: the saved servers as avatars with their tints, initials,
  presence dots, unread and live marks, the selection pill and ring, the plus
  that adds a server and the settings button; a second click edits a server,
  as the Slint rail's double click does.
- shell/sidebar.rs: the server on screen with its stats, the place of the
  channel tree (slice 2), the voice card (disconnect, copy an invite, hold to
  talk) while voice is connecting or connected, and the user card with the
  microphone and sound buttons.
- shell/topbar.rs: the page's title, the search box and the settings button;
  the last two are logged until their slices exist.
- shell/main_panel.rs: "No server selected" with the way to add one, or the
  server on screen with Connect, Disconnect and Edit.
- shell/form.rs: the server form (address, name, nickname, password; Save,
  Save and connect, Cancel, and a Remove that asks twice) in the place of the
  main area until the dialogs slice.
- shell/toast.rs: the status line as a toast for a few seconds.

The eleven callbacks of bind/servers.rs that the shell has are GPUI actions
(shell/actions.rs: select, connect, disconnect, mute the microphone, mute the
sound, push to talk, edit, save, save and connect, delete, invite): a click
dispatches one, the window's root view handles it by asking the root state.
The window takes its title from the server on screen ("Voelin - Nightfall"),
keeps a focus of its own so that actions always find their handlers, tells the
root state where it is (ui.window), and opens where it was left (the size
always; the position where a screen still shows it and the window manager
honours one). The logo is served by the assets.

scripts/gpui-shot.sh finds the window by its title's prefix now that the title
follows the server.

Tests on GPUI's test platform draw the window and click it: a server added
appears in the rail, a click selects it and titles the window, a connect
reaches the engine, an engine event updates the rail and the cards, the form
adds, edits and removes, the toast goes, the window's place round-trips, an
idle window is not told, the sample servers fill the shell.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 16:53:03 +03:00
faumarayandClaude Sonnet 5.5 e66238847d voelin-gpui: the store at start, the shell's actions on the root state, quiet loops
The window opens the client's store as the Slint front end's run() does
(backend.rs): the database in the platform's data directory (VOELIN_DATA_DIR
moves it), the settings service on it with the UI's keys, the secrets (the OS
keyring, memory when it refuses), the default identity (made and kept when the
store has none), the chat history and the settings handed to the engine. The
state starts from the store's bookmarks, the settings' theme and text size
(a development switch still wins), and the sample servers of VOELIN_DEMO_UI
through the app's own events with nothing sent to the engine or kept.

AppState gains the callbacks of bind/servers.rs that the shell has: select a
server (and observe it through its gateway or query login, the gateway looked
up on the engine's runtime and handed back through Later), connect and
disconnect voice, mute the microphone and the sound, hold to talk, copy an
invite, and add, edit, save-and-connect and remove a bookmark, all through
voelin-ui-vm's logic; perform() carries out an Update as far as this front end
has the parts (commands, status, what to keep, the theme settings). It keeps
the window's place in ui.window at the tick and at close, and opens the window
where it was left if a screen still shows its corner.

The engine-event task takes what is queued (BATCH, 64) in one update with one
notification and yields to GPUI's executor between steps; the tick counts and
notifies nobody, since nothing the shell shows moves with the clock.

Tests: one per behaviour on GPUI's test platform (the store's servers, select,
save, edit, remove, connect, the other commands, observe, the sample servers,
the theme settings, the window's place, the burst and the quiet tick), and a
connect through a real engine with no connector, which answers that none
serves the address.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 16:34:14 +03:00
faumarayandClaude Sonnet 5.5 bc390f433c voelin-ui-vm: the setting ui.window, the main window's size and position
WindowState (size, position when the platform tells one, maximized) kept as
the optional JSON key ui.window: whole pixels, a damaged value refused by its
validation, none until a run has left one. A key of its own, not a field of
the ui blob (which both front ends read) and not in appearance_keys() (which
the Slint front end registers): the GPUI front end registers and writes it,
the Slint one does not know it. Its stored value survives in the database
either way, as every unregistered key does.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 16:34:14 +03:00
faumarayandClaude Fable 5.1 ba224e1dff Merge phase5/gpui-foundation: the foundation of the GPUI front end (Rust 1.95, ashpd on async-io with zbus on one executor, crates/voelin-gpui on gpui-kit 0.8.1, the root entity and the engine's event loop, VoelinTheme with Inter and Lucide, the meter)
CI / Linux checks (push) Successful in 1h10m33s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 15:22:04 +03:00
faumarayandClaude Sonnet 5.5 d84b54270c docs/design/gpui-spikes.md: the status paragraph records the foundation's review, gate and minors round
The report's status paragraph said the foundation landed and stopped there, and
that the figures on the page were still 0.8.0's. It now says the foundation was
reviewed and gated the same day (no blocker, no major, six minors), lists the
minors that are closed in the commits after it, points at docs/ui.md "For the
next slices" for the risks left to the slices, and excepts the two video cases
the review ran again on 0.8.1 from "still 0.8.0's".

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 13:49:35 +03:00
faumarayandClaude Sonnet 5.5 2e22fd567c docs/media.md: the portal capture no longer needs a tokio runtime to start
The Portal note said `start` needs a tokio runtime because zbus runs on it. Since
the move of ashpd to `async-io` (e325b65) zbus runs every connection on an I/O
thread of its own, whichever thread builds it, and the note in portal.rs says
so (corrected in ed49c28); this record was not among the four the gate listed
and had been left behind. `stop` is the one that needs the runtime, and only to
close the portal session in the background (elsewhere the session closes with
the connection): the note now says both.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 13:49:15 +03:00
faumarayandClaude Sonnet 5.5 8f3d809e8a voelin-gpui: fonts.rs points at the report's "Open choices for step 3", which exist
The module comment sent the colour emoji to docs/design/gpui-spikes.md,
"Emoji", a section the report does not have (the colour emoji gap is a
paragraph of spike 2, and the choice is under "Open choices for step 3"): the
same dangling pointer docs/ui.md had in the slice 4 line, found by grep in the
round that fixed that one.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 13:49:15 +03:00
faumarayandClaude Sonnet 5.5 e5f8821f67 docs/ui.md: "For the next slices", the risks of the gate and the review; the report's quiet-machine figures
The risks the Opus gate and the review of the foundation left to the slices
that meet them, each with where it sits in the code: the engine-event task
drains its channel without yielding, the tick notifies the root every second,
voelin-platform's hotkey portal calls tokio::spawn (start it on the engine's
runtime as Slint's GlobalPtt::start does), PortalCapture::stop closes the
portal session only inside a tokio runtime, gpui-component's ThemeRegistry
observer overwrites VoelinTheme's mapping on any registry change, the parity
test and build.rs read crates/voelin-ui/ui (they move at step 9), system
mode's first frame is Light until the colour-scheme portal answers, the gate's
deviations from the report's mapping table (bg-rail not mapped, one scrim for
three, gpui-base's non-colour tokens not written), and the close grace not
seen end to end until a slice opens sessions.

docs/design/gpui-spikes.md: "the 1440p60 figures were not reproduced on
0.8.1" now carries the review's quiet-machine re-run of the two cases (static
61 fps, raw 59.1 fps, load average 8 to 12, llvmpipe).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:31:05 +03:00
faumarayandClaude Sonnet 5.5 5c94b15820 voelin-gpui: the parity test notices a second brush or string in theme.slint
The test compared the brush and string declarations of theme.slint by name
only (one backdrop, one font-family and the mode string), so a second brush or
string token in the Slint file passed unseen while docs/ui.md said a token on
one side only fails the test. It now asserts the brush declarations are
exactly {backdrop} and the strings exactly {mode, font-family}, and a test
adds a brush and a string to a copy of the file (a mutant) and checks both are
named: red with the previous rule ("backdrop-soft goes unnoticed"), green
with this one.

A Rust-only second brush or string is still not seen (tokens.rs has one
gradient and one family that the test cannot enumerate); docs/ui.md says so
instead of promising it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:29:02 +03:00
faumarayandClaude Sonnet 5.5 977b942cd0 docs/ui.md: slice 4 points at the report's "Open choices for step 3", which exist
The list of slices sent the chat slice to a section "Emoji" of
docs/design/gpui-spikes.md, which has none (the colour emoji gap is a
paragraph of spike 2). It now names the section "Open choices for step 3" and
the two open choices the chat slice touches there, emoji and links.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:26:45 +03:00
faumarayandClaude Sonnet 5.5 caf77561a9 about-assets.md: the Lucide 1.43 catalogue of gpui-kit-assets embedded in voelin-gpui
voelin-gpui embeds gpui-kit-assets' catalogue (Lucide 1.43.0, 1,818 icons,
beside 12 icons of the crate's own under its Apache-2.0 licence) behind the
client's own 1.48 set, and the notices named only the 1.48 set. The new line
has the same copyright holder, and the ISC and Feather MIT texts already
below are the catalogue's (its LICENSE-LUCIDE). THIRD_PARTY_NOTICES.md is
regenerated with scripts/notices.sh.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:26:17 +03:00
faumarayandClaude Sonnet 5.5 5af85b4aa2 docs/design/gpui-spikes.md: the lock figures of the foundation, 292 entries with their two sources
The size paragraph said gpui-kit adds 279 entries (208 new names) to
Cargo.lock. The foundation's lock has 1,321 entries against main's 1,029: 292,
218 of them new names. 279 come from gpui-kit and 13 from voelin-gpui's
`gpui-pre` `test-support` dev-dependency, which ships in no binary (the lock
without that line has 1,308 entries).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:25:04 +03:00
faumarayandClaude Sonnet 5.5 ed49c283a2 voelin-platform: zbus on async-io alone in every binary (notify-rust z), and a test for the order of ashpd's callers
ashpd 0.13.13 keeps one session connection per process (a static in its
proxy.rs), and zbus 5.19 picks that connection's executor once, from
Handle::try_current() on the thread that builds it, when both its `tokio` and
`async-io` features are compiled in. The first ashpd caller therefore decided
the executor of every later portal call: a tokio caller first, then a caller
with no runtime (a GPUI foreground task), panics with "there is no reactor
running" (get_property("version") sets up zbus's property cache, which calls
tokio::task::spawn). The merged binary was safe only because GPUI's
colour-scheme call builds the connection before the engine's portal calls.

voelin-platform's notify-rust asks for `z` (async-io) in place of
`z-with-tokio`, and the stand-in portal's zbus dev-dependency for `async-io`
instead of `tokio`: a test binary with both features shows the panic even when
the binaries do not have it. `cargo tree -e features -i zbus` now names
`tokio` nowhere; Cargo.lock loses zbus's tokio edge and tokio's tracing edge
(THIRD_PARTY_NOTICES.md is unchanged).

tests/proxy.rs gets the gate's probe shape on a private dbus-run-session bus
(skipped with a printed reason where none can be made): a tokio caller first,
then a caller with no runtime. It fails with the panic on the tree before this
change, and still did with only notify-rust moved, which is why the
dev-dependency moved too.

The four records that described the move wrongly are corrected:
docs/design/gpui-spikes.md "Dependencies", the comment of
PortalCapture::start, voelin-media's Cargo.toml and CHANGELOG.md (whose
Slint-only sentence goes: the Slint app's zbus connections move to async-io
threads too).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:24:19 +03:00
faumarayandClaude Sonnet 5.5 3f4dc700af voelin-gpui: the meter's /proc test waits for a CPU tick instead of burning 60 ms
this_process_can_be_read_on_linux burned CPU for 60 ms of wall time and
asserted that some thread group used a tick (10 ms) of it. On a busy machine
this thread gets less than a tick in 60 ms: with 5 busy loops on the test's
core, 39 of 40 runs failed at `!threads.is_empty()`. The test now burns CPU
until a second reading shows the process's tick count above the first and a
thread group above its own (a 30 s deadline only ends a hang, as
docs/testing/load.md asks), then asserts; 40 of 40 pass under the same
recipe (taskset to one core, 5 busy loops, 40 runs).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:19:30 +03:00
faumarayandClaude Sonnet 5.5 7cabc2c13d docs/ui.md: which of the GPUI tests need a display
The Tests bullet said the tests need no display and then named
tests/launch_failure.rs, one case of which starts the binary on the test
display of VOELIN_X11_TEST_DISPLAY (skipped without it, like the X11 tests of
voelin-media and voelin-platform); the other case needs no display at all.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 10:10:11 +03:00
faumarayandClaude Sonnet 5.5 d3fa8d85f0 docs: the spikes' README and report no longer put the repository on Rust 1.94
Since 5ce5c0d the repository is on 1.95.0, but spikes/gpui/README.md still
said no gpui-kit builds with "the repository's Rust 1.94" and the report's risk
table said "the client is on 1.94". The README now says the 1.94 the
repository used before 5ce5c0d (the E0658 demonstration with TOOLCHAIN=1.94
stays as the historical evidence), the risk row says the client moved to 1.95.0
in 5ce5c0d (seven lints fixed), and the report's "Settled for step 3" sentence
about the same failure names the 1.94 of before that commit too.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 09:42:49 +03:00
faumarayandClaude Sonnet 5.5 6852204277 voelin-gpui: Later::run says what its answer promises
The doc said `false` "when the window is gone". The loop that drains the jobs
learns that the entity was released only when a job reaches it: the first job
sent after the release still answers `true` and is never run, and only the
next call is refused (a hotkey or decoder thread that calls run() after the
window went and before another job could so believe a job was queued that
never ran). The doc says that now ("false once a job has found the window
gone", true promises that the job was queued), and a test pins the order: the
job after the release is queued and never runs, the one after it is refused.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 09:42:21 +03:00
faumarayandClaude Sonnet 5.5 efc7db57a3 voelin-gpui: closing the window gives the engine time to send the session closes
The window's close sends CloseSession for every session (AppState::shutdown)
and ended the app straight into runtime.shutdown_timeout(2 s), which waits for
blocking tasks only and drops the engine's async tasks: the commands could go
with the runtime and leave ghost clients on the servers until they time out.
voelin-ui sleeps 500 ms in that case before shutting its runtime down
(app.rs after ui.run()); run() does the same now. shutdown() returns how many
sessions it told the engine to close, the close handler keeps that number for
run() (the App and its entities are gone once GPUI's loop has returned), and
run() waits CLOSE_GRACE only when it is not zero. A comment in run() tells the
slices that add another way to end the app to call shutdown() too.

The GPUI window cannot open a session in this slice, so the wait is not seen
end to end; the tests pin the count: with an engine a state holding a session
answers 1 and a state with none 0, without an engine 0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 09:42:10 +03:00
faumarayandClaude Sonnet 5.5 a4694e944b voelin-gpui: a window that cannot open ends the app with the reason, not a hang
When open_main_window failed (no usable Vulkan or GL driver), run() stored the
error and called cx.quit() inside the launch callback. GPUI's Linux platform
calls that callback before it starts its event loop, and calloop's
EventLoop::run clears its stop signal on entry, so the quit was lost: the
binary stayed alive with no window and no message (reproduced on a private
Xvfb with VK_DRIVER_FILES, __EGL_VENDOR_LIBRARY_DIRS and LIBGL_DRIVERS_PATH
pointing nowhere: exit 124 under `timeout`, nothing in the log after "Creating
colormap"), and the `failure` that main was to print was never returned. The
quit is a foreground task now, which runs inside the loop: the same run exits
with status 1 and "cannot open the main window / Failed to create surface".

With no display server at all GPUI starts its headless platform, whose
open_window succeeds with a window that draws nothing, so the same silent hang
came from there; open_main_window refuses a compositor named "headless" with
"no display: neither DISPLAY nor WAYLAND_DISPLAY names a display server".

tests/launch_failure.rs starts the built binary both ways (the driver case
under VOELIN_X11_TEST_DISPLAY, skipped where the machine's driver is found
anyway; the display case needs none) and fails when the process outlives two
minutes; with the old cx.quit() the driver test fails after 120 s, with the fix
both pass in a third of a second. docs/ui.md ("Running it") says what a missing
driver and a missing display look like; CHANGELOG.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 09:41:53 +03:00
faumarayandClaude Sonnet 5.5 97d51fb226 CI and docs: libxkbcommon-x11-dev and libxcb1-dev, which the GPUI front end links
The release binary of voelin-gpui links libxcb.so.1 and libxkbcommon-x11.so.0
(`readelf -d`: libxcb, libxkbcommon, libxkbcommon-x11, libasound, libm, libc)
and opens libwayland-client.so.0, libvulkan.so.1 and libEGL.so.1 by name
(`strings`). The development packages of the first two were in no package
list, so a workspace build on the Ubuntu runner (CI builds every member)
would have failed to link: .github/actions/system-deps, the CI example in
docs/ci.md, docker/linux.Dockerfile ("the same libraries as CI") and the apt
line of docs/building.md name libxkbcommon-x11-dev and libxcb1-dev now, and
building.md and docs/ui.md say what the GPUI front end links and what it
opens by name (an earlier sentence of mine had all of them opened by name).
Not run: no Ubuntu runner or image here; this machine builds with Nix's
libraries, where the headers come from the same projects.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 08:10:37 +03:00
faumarayandClaude Sonnet 5.5 d4f9e59ed6 scripts/gpui-shot.sh: ImageMagick 6 (convert, identify) where magick is not there
Debian and Ubuntu ship ImageMagick 6, which has no `magick`; the script now
uses `convert` and `identify` when `magick` is missing, and its header names
what it needs (xdotool, xwd, ImageMagick). Both branches were run on Xvfb
:98 (the second with a PATH that has `convert` and `identify` only): the
swatch picture is 1440x960 and the window closes with exit code 0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 07:47:36 +03:00
faumarayandClaude Sonnet 5.5 172d6247c6 docs: "The GPUI front end" in docs/ui.md, the spikes report's status and notes, README
docs/ui.md gains the section "The GPUI front end": what exists (the crate's
files and what each does), the root state and its three loops (the engine's
events through a foreground task, the one-second tick, Later for other
threads, and why Later exists: GPUI's AsyncApp is not Send), the tests and why
they use gpui-pre's test-support and not gpui-kit's, how to run it (what
GPUI needs at run time: Vulkan or OpenGL, lavapipe in software, a window
manager on X11), the development switches in a table, how the screenshots are
made (scripts/gpui-shot.sh, and the NixOS recipe over the spikes' headless
display) with the two swatch pictures, the theme in its two layers with the
mapping from the Voelin tokens to gpui-component's ThemeColor fields, the
mode, Inter and Lucide, and what is next: the plan's slices 1 to 9 with what
each takes from the Bridge, the conditions the spikes set (the emoji patch
before chat, a GPU run before the viewer, Wayland's preedit) and the steps
around them.

docs/design/gpui-spikes.md: the status paragraph says the foundation of step 3
landed (items 1 to 4 and 6 of its list; the shell is next) and points to
docs/ui.md; "Before step 3 can start" and "Dependencies" say the Rust move and
the ashpd move are done, with what zbus does with both features and the test
that calls ashpd with no tokio runtime; the size bullet gives what gpui-kit
adds to the root lock (279 entries, about 195 packages on Linux, two new
licences); a paragraph after the first slice's list says which items are done
and how.

README.md: the crate's bullet says what the window has so far.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 07:16:22 +03:00
faumarayandClaude Sonnet 5.5 a2fad4569a voelin-gpui: the backdrop's GPUI gradient in one place (Backdrop::to_gpui)
GPUI's gradient has two colour stops and the Slint backdrop three, so what
GPUI draws is the first and the last; that choice was written inline in the
swatch page. It is a method of the token now (theme/mod.rs), with a test that
it is the gradient of the first and the last stops and not of the middle one,
and the swatch calls it. No change on screen.

Checked on Rust 1.95.0: fmt, clippy -D warnings --no-deps (all targets),
`cargo test -p voelin-gpui` (31 tests).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 07:15:31 +03:00
faumarayandClaude Sonnet 5.5 109e1d1839 voelin-gpui: the cost meter as a development switch (VOELIN_METER=1), logged once a second
meter.rs is spike_common::meter of the GPUI spikes
(spikes/gpui/common/src/meter.rs, docs/design/gpui-spikes.md) without the
measuring run's summary and exit: once a second, on a thread of its own, a
log line (target voelin_gpui::meter, level info) with the process's CPU in
percent of one core, the resident memory, the CPU of each group of threads
(a thread's name without its trailing number: `llvmpipe-12` is `llvmpipe`,
which tells the software renderer's share, work a GPU would take, from
GPUI's thread, the engine's runtime and the codecs; the busiest first, groups
under 0.5 % left out), the app's own counters per second and the voice
connections as a gauge:

  cpu 11.9% rss 250.4 MiB | threads llvmpipe 5.9 voelin-gpui 5.0 |
  engine_events 0.0/s ticks 1.0/s renders 1.0/s later_jobs 0.0/s | connections 0

The counters (`Counters`: engine events handled, ticks, renders, jobs run
through `Later`, connections up) are shared with the root state and the main
view, which count in `handle_event`, `tick`, the later task and `render`; the
numbers come from /proc/self (a note and a warning say so where there is none;
rustix's `param` for the page size and the clock tick, Linux only, no new
package: the lock gains the edge). The line is a pure function with a test,
as are the thread grouping and the stat parser (a name with spaces and
parentheses), and one test reads this process and checks it has threads and
memory. The root state's tests now also check the counters (events, the
connection gauge, three ticks, a job from another thread).

`VOELIN_METER=1` starts it (dev.rs parses it with the other switches).
Running the debug binary on the swatch page on Xvfb :97 logs the lines above
(about 12 % of a core when idle, the software renderer 6 to 11 % of it, one
frame a second); the window closes with exit code 0. The default log filter
now leaves out GPUI's "failed to load font .SystemUIFont" warning, which
every start printed (gpui-component asks for the platform UI font before the
theme names Inter; the text system falls back).

Checked on Rust 1.95.0: fmt, clippy -D warnings --no-deps (all targets),
`cargo test -p voelin-gpui` (30 tests), cargo deny, `scripts/notices.sh
--check`.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 07:12:56 +03:00
faumarayandClaude Sonnet 5.5 2690b8a802 voelin-gpui: VoelinTheme (every token of theme.slint, light and dark) written into gpui-component, Inter, the client's Lucide icons, the swatch page
Two layers, as the spikes' report settled:
1. `VoelinTheme`, a GPUI global (theme/tokens.rs): the 43 colour tokens of
   ui/theme.slint for light and dark (generated from the Slint file by a
   script, then checked by the test below), the backdrop gradient, and
   `Metrics`: the radii, spacing, type sizes, weights, control and shell
   sizes and the two durations at a text size factor (font-scale: the
   sidebar's `264 * max(1, scale)` and the top bar's `max(44, control + 8)`
   included).
2. gpui-component's `ThemeColor`, written on every change (theme/components.rs):
   the base of the report's table (background, foreground, border, input,
   ring, overlay; primary with hover, active and foreground from the client's
   accent; secondary and muted from surface-2 and its raised steps;
   gpui-component's "accent", which is a hover background, from surface-3;
   popover; list, table, sidebar, title and status bar, tabs, switch, slider,
   scrollbar, link, selection; danger, success, warning and info with a hover
   and active made by mixing and a text that is white or the window's ink,
   whichever contrasts more) and the 28 `button_*` fields a theme file would
   derive from them (without them the buttons keep the default theme's
   blue). The mixing, the WCAG contrast and `readable` are `Rgba` methods with
   tests. The window's background is bg-app; the backdrop and bg-rail stay in
   `VoelinTheme` (gpui-component has no rail, and GPUI's gradient has two
   stops against Slint's three: the swatch draws the first and the last and
   says so).
The mode (`Choice`: system, light, dark) follows the window's appearance in
`system` (`observe_window_appearance` calls `set_system_appearance`; a light
or dark choice ignores the window) and sets the platform's window appearance
where the platform draws the frame (macOS; a no-op elsewhere). The text size
factor rewrites the metrics, the theme's font size (font-body) and radii.

theme/slint_parity.rs reads ui/theme.slint at test time (`include_str!`) and
compares every declaration of the `Theme` global with tokens.rs by name: the
colours (dark and light), every length with the file's own arithmetic (a
small evaluator of `*`, `+`, `max()` and token references) at four text
sizes, the weights, durations, the font family and the backdrop's stops, and
fails on a name on one side only or a declaration kind it does not know. A
mutation check (accent, radius-md and the top bar's formula changed in
tokens.rs) failed the tests with the names of the tokens, then was reverted.

fonts.rs adds the five Inter TTFs of the Slint front end (`include_bytes!`)
to GPUI's text system; the theme names the family. build.rs turns the 147
Lucide 1.48 SVGs of crates/voelin-ui/ui/assets/icons into a sorted table of
`include_bytes!` (std only, no new dependency) that assets.rs serves as
gpui-component's `icons/<name>.svg` before gpui-kit-assets' Lucide 1.43
catalogue (1,830 paths, which answers the rest and, as it does, an error for
a path it lacks); a test checks that `mic.svg` is the client's, differs from
the catalogue's, and that other icons fall through.

Development switches (dev.rs): `VOELIN_OPEN=swatch`, `VOELIN_DEV_THEME=
dark|light|system`, `VOELIN_FONT_SCALE`, `VOELIN_WINDOW_SIZE` (the Slint
front end's names where they exist). swatch.rs is the page: the 43 colours in
the groups of docs/ui.md's "Theme tokens" table with name and value (a test
checks each token is in exactly one group), the backdrop, radii, spacing,
the type scale, buttons, switches and checkboxes of gpui-component and 16
icons; it scrolls when the window is smaller. scripts/gpui-shot.sh makes the
screenshot headless the way scripts/shots.sh does for Slint (xvfb-run, or
GPUI_SHOT_HEADLESS=1 under headless.sh on NixOS; Wayland, the session bus
and the XDG directories out of the environment), then closes the window with
Alt+F4 and reports how the app ended. docs/ui/gpui-swatch-dark.png and
-light.png are its output (Xvfb :97, openbox, lavapipe via wgpu's Vulkan
backend, the debug binary, 1440x960, truecolour: a 256-colour reduction would
change the tokens' values; the Slint pictures live in docs/screenshots/, the
task asked for docs/ui/).

Checked on Rust 1.95.0: fmt, clippy -D warnings --no-deps (all targets, the
build script included), `cargo test -p voelin-gpui` 26 tests, cargo deny,
`scripts/notices.sh --check`.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 07:07:10 +03:00
faumarayandClaude Sonnet 5.5 27a13fcc7c voelin-gpui: the root Entity<AppState>, the engine's events through a foreground task, the one-second tick, later()
crates/voelin-gpui/src/app.rs holds the root entity: the toolkit-free
voelin_ui_vm state (`AppState<Vec<ChatLine>>`) and `Social`, with
`events::handle` as the one dispatch of an engine event (the entry point
both front ends use; its Update's engine commands are sent, its warnings
logged, the rest belongs to the slices that draw it). Three loops, spawned by
`AppState::new` and ended when the entity is released:
- the engine's events: a foreground task awaits the tokio receiver of the
  hosted engine (no reactor needed, as the plan says), `this.update` and
  `cx.notify()`: spike 3's hotkey task;
- the tick: a loop of `background_executor().timer(1 s)`;
- `Later`, for other threads: GPUI's `AsyncApp` holds an Rc-based weak
  handle and is not Send (read in gpui-pre's async_context.rs), so a thread
  that wants to touch the entity holds a Send handle that queues a boxed
  closure; a third foreground task, which owns the cloned AsyncApp, runs it
  with the entity. This is the Slint front end's `later(|app| ...)`.
engine.rs repeats the ~25 lines of voelin-ui's `HostedEngine::start` (the
engine on a tokio runtime, its events forwarded into an unbounded channel):
that type lives in the Slint crate (crates/voelin-ui/src/app.rs), which this
crate cannot depend on and this task does not touch. dev.rs reads
VOELIN_WINDOW_SIZE. lib.rs `run()` logs through tracing (`VOELIN_LOG`, else
`RUST_LOG`, else a filter that shows GPUI's adapter line), starts the engine's
runtime, opens the window on the entity and, on close, tells the engine to
close the sessions and ends the app. view.rs shows the one line of state the
task asked for: version, voice connections up, engine events handled, seconds
up; each part moves by one of the loops.

Seven tests, none needing a display (GPUI's test platform): an injected
engine event (a voice state) reaches the entity and its status line, the
entity notifies its observers, the tick runs once per advanced second, a job
from another thread runs on the entity, and a real engine (HostedEngine on a
tokio runtime) delivers a real event (a setting changed by a command) to the
entity through the same task; the window-size switch parses and refuses
nonsense. The real-engine test calls `allow_parking`, as GPUI's test
scheduler calls a wake from a tokio thread a non-deterministic test
otherwise. The tests use `gpui-pre` (renamed `gpui`) with its `test-support`
as a dev-dependency, pinned `=0.3.10` beside gpui-kit's own pin: gpui-kit's
`test-support` feature names the optional `gpui-fast` backend in weak
features, which makes cargo lock gpui-fast and its tree and pins taffy to
0.15.0 for every build (reproduced in a scratch project: 793 packages
without the feature, 820 with it). The lock gains only gpui-pre's own
test-support crates (proptest and its few, futures-concurrency, postage);
THIRD_PARTY_NOTICES.md does not move (dev-dependencies are out of it) and
cargo deny passes.

Run on Xvfb :97 (headless.sh) with the debug binary: the window opens in
0.1 s, shows "Voelin 0.0.1-alpha · 0 connections · 1 engine event · 2 s up"
and, four seconds later, "... · 6 s up" (the one engine event is the real
engine's own at start); Alt+F4 ends the app with exit code 0 in 132 ms.
Checked on Rust 1.95.0: fmt and clippy -D warnings (all targets, --no-deps),
`cargo test -p voelin-gpui` (3 runs, 7 tests each), cargo deny.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 06:56:08 +03:00
faumarayandClaude Sonnet 5.5 8f234e0051 voelin-gpui: the GPUI front end's crate on gpui-kit 0.8.1, a window titled Voelin that opens and closes
The second front end of plan section 6 step 3: crates/voelin-gpui with
the binary voelin-gpui, in the workspace's members and default-members next
to voelin-ui (two binaries until parity; voelin-ui stays the app).
gpui-kit is a workspace dependency pinned `=0.8.1` (the version the three
spikes were rebuilt on in the commit before). The crate asks for gpui-kit
and the app's name and id from voelin-platform (APP_NAME as the window's
title, APP_ID as its app id); `run()` opens one window whose
`on_window_should_close` ends the app, and returns the error when the
window cannot be opened (no display).

Checked on Xvfb :97 (headless.sh: openbox, a private bus, lavapipe through
wgpu's Vulkan backend, state under .scratch): the debug binary opens a
window named "Voelin" (xdotool search) in 0.3 s and ends with exit code 0
when openbox sends the close request (Alt+F4).

Cargo.lock: 279 more package entries (208 new names; no existing version
moved, other versions of 61 names were added beside theirs): GPUI's
gpui-pre family, wgpu 30, gpui-component with its Markdown, HTML, chart and
table support, cosmic-text, the Linux platform crates. The root workspace
already carried Slint's and the codecs' dependencies, so this is 195 new
packages on Linux, not the ~1,000 of the spikes' lock (which has the root's
packages too). deny.toml and about.toml name the two licences no crate of
the tree had: 0BSD (enum-iterator and enum-iterator-derive, under
gpui-component) and CC0-1.0 (notify 8, the file watcher of gpui-component,
and tiny-keccak, under the X input method client of gpui-pre-linux); no
other licence, no advisory, no ban and no source is new (`cargo deny
--locked --workspace check`: advisories, bans, licenses and sources ok).
THIRD_PARTY_NOTICES.md is regenerated (scripts/notices.sh, cargo-about
0.9.2, no warning; `--check` clean). There is no new clarification: cargo-about
finds every text.

Docs: CHANGELOG, docs/ui.md (the structure tree names the crate and the
intro the second front end), docs/building.md (the dependency list: Vulkan
or OpenGL at run time, what GPUI loads by name, a window manager on X11; no
new development package), README (the crate list and the run command) and
CLAUDE.md, which had no crate sentence (it only says "own crates"): it now
says there are two front ends on one engine and what they share.

Checked on Rust 1.95.0: cargo fmt and cargo clippy -D warnings --no-deps
over the own crates (all targets); cargo deny; scripts/notices.sh --check.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 06:46:59 +03:00
faumarayandClaude Sonnet 5.5 6fc84e9e44 spikes/gpui: rebuilt on gpui-kit 0.8.1 (gpui-pre 0.3.10, wgpu 30), nothing regresses; the pin result in the report
0.8.1 came out on 2026-10-26, a day after the 0.8.0 the three spikes were
measured on. `=0.8.1` in spikes/gpui/Cargo.toml and `cargo update -p
gpui-kit --precise 0.8.1` move 40 packages of the lock (1,069 entries
before, 1,065 after): gpui-kit, gpui-base, gpui-component and
gpui-kit-assets to 0.8.1, the 19 gpui-pre crates to 0.3.10, wgpu 29 to 30
(naga 29 to 30), taffy 0.13 to 0.15. No source change: the spikes build as
they were, release, on Rust 1.95.0.

One run of each README's measurement command on Xvfb :96 (openbox, a
private bus, lavapipe through wgpu's Vulkan backend, state under .scratch)
with the machine at a load average of 64 to 80 (the 0.8.0 runs: 28 to 53):
- composer drive.sh 8 PASS, ime.sh 3 PASS, windows drive.sh 11 PASS, no FAIL;
  the composer's screenshot differs from the committed one in 579 of 900,000
  pixels;
- video: static 1440p 22.7 fps shown at 259 % CPU (11.4 % of CPU per fps,
  0.8.0: 11.7), raw 1440p60 13.4 fps at 174 % (13.0; 0.8.0: 12.5 to 13.1),
  memory flat with drop_image, +408 MiB in 10 s without it; windows-both
  123 % of a core, the preview shown 14.4 of 15 a second, memory flat.
The frame rates are lower than 0.8.0's because of the load; the cost of a
shown frame is the same. The report says plainly that the 42 to 49 fps raw
1440p figures were not reproduced on 0.8.1, only the cost per frame was.

So the pin is gpui-kit 0.8.1, exactly. docs/design/gpui-spikes.md ("The
version to pin", the status paragraph, the setup table) and the spikes'
README say so; its figures stay 0.8.0's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 06:36:31 +03:00
faumarayandClaude Sonnet 5.5 e325b65d42 ashpd on async-io in voelin-media (pipewire) and voelin-platform (portal)
GPUI's Linux backend enables ashpd's `async-io` feature, and ashpd 0.13.13
refuses `async-io` and `tokio` at once (compile_error! in its lib.rs), so
a binary could not hold the portals and gpui-kit. voelin-media's `pipewire`
feature (the screen-cast and camera portals) and voelin-platform's `portal`
feature (global shortcuts, file chooser, proxy resolver) now ask ashpd for
`async-io`; Cargo.lock loses ashpd's edge to tokio and nothing else (the
package set is the same: THIRD_PARTY_NOTICES.md is unchanged and
`scripts/notices.sh --check` clean).

What zbus 5.19 does with the features (read in its abstractions/mod.rs):
with both `async-io` and `tokio` compiled in it picks per connection, tokio
when a tokio runtime is current on the calling thread, else async-io with an
I/O thread of its own. The workspace has both on already (notify-rust asks
for zbus/tokio, secret-service and others for its defaults), so the engine's
portal calls, which run inside its tokio runtime, still use tokio; a caller
with no runtime (GPUI's foreground executor) gets the I/O thread. Built on
its own, voelin-media has `async-io` only.

The source needed no change beyond a doc comment (capture/portal.rs said
the connection needs a tokio runtime). tests/proxy.rs gains a second test on
the same stand-in portal: ashpd's ProxyResolver called from a thread with no
tokio runtime, polled by hand, gets the answer. Both tests run again under
`dbus-run-session` on a bus of their own (the harness takes the test's name).

Checked on Rust 1.95.0: fmt and clippy (-D warnings, --no-deps) of the own
crates; `cargo test -p voelin-platform -p voelin-media`: all pass, including
tests/proxy.rs (2 tests), the portal-less-bus tests of both crates run with
no session bus (`unavailable_without_session_bus`, the `proxy::tests` that
need none), and tests/pipewire_apps.rs against a private PipeWire and
WirePlumber (found on PATH, ran: 2 passed in 2.7 s). The live portal
(a desktop's screen-cast dialog, the shortcut binding) was not exercised:
no desktop session is used by these runs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 06:18:00 +03:00
faumarayandClaude Sonnet 5.5 5ce5c0db82 Rust 1.95: rust-toolchain.toml, the workspace rust-version and the gateway image; the lints 1.95 adds
gpui-kit (every gpui-pre 0.3.x) calls std::hint::cold_path, stable since
1.95.0, so the client moves from 1.94 to 1.95 before the GPUI front end
can build (docs/design/gpui-spikes.md, "Rust 1.95 or newer"). rustc 1.95.0
(59807616e 2026-04-14), cargo 1.95.0, clippy and rustfmt of the same
release were used.

rust-toolchain.toml and the workspace's rust-version say 1.95;
crates/voelin-gateway/Dockerfile builds from rust:1.95-bookworm (cargo
refuses a 1.94 image once rust-version is 1.95). docs/building.md names
the Rust version for a local build; docs/ci.md says a channel change in
rust-toolchain.toml is all the runner needs (they named no version
before).

Clippy of 1.95 adds `collapsible_match` for an `if` that is a match arm's
only statement, `unnecessary_sort_by` and `manual_checked_ops`; they
flagged seven spots in four crates, none a behaviour change:
- voelin-media capture::forward: a let-else instead of a match whose arm
  holds one `if`;
- voelin-media ffmpeg::sys: `sort_by_key` with `Reverse` (two places);
- voelin-media studio:📷 `checked_div` for the frame interval;
- voelin-stream peer and session: the condition in a local before the
  `if` (a guard would carry a side effect: `remove`);
- voelinctl engine and session: the same.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 06:00:40 +03:00
faumarayandClaude Fable 5.1 296664ffa9 Merge phase5/gpui-spikes: the three GPUI spikes (video frames in img(), the composer with preedit, a second window on the shared model) and docs/design/gpui-spikes.md: go for all three
CI / Linux checks (push) Failing after 0s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 05:04:06 +03:00
faumarayandClaude Fable 5.1 df3b2074b9 spikes/gpui: voelin-model pinned at c5bb6b9 like the client's crates (one voelin_model in the graph after the keystore merge)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 05:04:06 +03:00
faumaray 02b2b470fc Merge remote-tracking branch 'origin/main' into phase5/gpui-spikes 2026-10-27 04:59:04 +03:00
faumarayandClaude Fable 5.1 ee971f30bc docs/design/gpui-spikes.md: the matched --no-drop re-run claims no cause for its rate (review minor)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 04:59:04 +03:00
faumarayandClaude Sonnet 5.5 8c172f4dc5 spikes/gpui/README.md: the nightly clippy command; report: 9.6 as measured
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 04:54:24 +03:00
faumarayandClaude Sonnet 5.5 6f2c64aa63 docs/design/gpui-spikes.md: video headline labelled raw, quiet-window pipeline figure, the --no-drop XDamage row explained
The headline video figure (status table, the go paragraph, the software
bullet) is the raw source, frames from memory with no decoder: it now
says so. The pipeline rows (22.9 fps at 1080p, 9.6 at 1440p) were load
artifacts: the page now carries the reviewer's quiet-window run of
pipeline-1440p60 (40.8 fps shown, XDamage 41.3, encoded 50.4, decoded
49.5, process 1047 %, encoder 454 %, llvmpipe 476 %, memory flat, load
23.5 / 30.6; not repeated here, the load stayed above 40), says the
pipeline rows scale with free CPU (the in-process encoder takes 450 to
1000 %) and that the cases are bound by CPU contention, the encoder being
the largest user. The go verdict stays.

The XDamage exception of the --no-drop case is a measurement artifact,
not frames counted and not presented: measure.sh runs damage-count for
69 s with 10 s of warm-up while the case lasts 12 s with 2 s, so the mean
spreads two seconds of window over 59. Second by second the counts match
(13.8 against 13.6; the reviewer's run 5.2 against 5.1) and a re-run with
the counter set to the case's own length gave 6.8 against 7.0 (Xvfb :93,
lavapipe, load 43 / 47). The video README's case row says so. No code
change.

The status paragraph records this round in two sentences (gpui-kit 0.8.1
of 2026-10-26 still unmeasured).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 04:51:49 +03:00
faumarayandClaude Sonnet 5.5 24069ac170 spikes/gpui: clippy -D warnings clean on nightly (as_chunks, bounded range)
Nightly's clippy flagged the two chunks_exact(4) loops of
common/src/bgra.rs (chunks_exact_to_as_chunks): both now use
as_chunks::<4>() and as_chunks_mut::<4>() (stable since 1.88). Behind
them, because clippy stops at the first crate that fails, it flags the
raw source's `for n in 0u64..` in video/src/main.rs
(for_unbounded_range): now `0..=u64::MAX`, the same loop.

`cargo clippy --locked --all-targets -- -D warnings` is clean on 1.95.0
and on nightly 2026-10-24 (through shell.sh); the README and the
report's clippy sentence say so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 04:45:53 +03:00
faumarayandClaude Fable 5.1 439a47f656 Merge phase4/keystore-task34: the key store follows task 34 (a sign-out keeps every key, only a forget deletes), VoelinProtocol crates pinned at c5bb6b9, the load-proof checkpoint tests
CI / Linux checks (push) Failing after 0s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 04:42:24 +03:00
faumaray 9c4bd29cb2 Merge remote-tracking branch 'origin/main' into phase4/keystore-task34
# Conflicts:
#	CHANGELOG.md
2026-10-27 04:34:14 +03:00
faumarayandClaude Fable 5.1 997c07b70e docs: the 17.7 row says where the one-second bound went (review minor of the keystore minors round)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 04:34:02 +03:00
faumarayandClaude Opus 5.5 5c36aae55e docs: the spikes' nightly clippy result as it is
The report and the spikes' README said the spikes pass clippy on 1.95.0
and on nightly; the final run's nightly clippy (1.101.0-nightly of
2026-10-23) has a lint 1.95 does not, chunks_exact_to_as_chunks, which
flags two chunks_exact(4) loops in spikes/gpui/common/src/bgra.rs. Both
now say so; the code is left as it is (clippy on 1.95.0, the pinned
toolchain of the spikes, is clean at every commit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 03:24:09 +03:00
faumarayandClaude Opus 5.5 3167817b89 docs/design/gpui-spikes.md: the three GPUI spikes measured, go for all three
Plan section 6 step 1's report: the setup (Xvfb :91 with openbox, Mesa
lavapipe through wgpu's Vulkan backend, gpui-kit 0.8.0, Rust 1.95.0, the
load of each run), and per spike the figures and checks with a go/no-go
against the plan's criteria:

- video: img() with the port of video.rs' delivery holds 42 to 49 fps at
  1440p60 and 55 to 58 at 1080p60 on the software device, the static
  control 60 to 62; drop_image keeps the atlas flat (without it +1.9 GiB
  in 10 s); a new 1440p picture costs GPUI's thread 6 to 7 ms (a new atlas
  texture and two copies); a persistent texture needs a GPUI change; the
  Slint demo stream compared on the same display at its 720p30;
- composer, IME, chat lines: all checks pass, X11 preedit with fcitx5 and
  Pinyin works, Wayland preedit not exercised headless; colour emoji in
  U+1F600-U+1F640 need a one-line GPUI patch (tried in a scratch build);
  InteractiveText loses clicks shorter than a frame;
- second window: shared root entity, focus, fullscreen, close and the X11
  global hotkey all pass; the shared preview's cost.

Settled for step 3: gpui-kit =0.8.0 (0.8.1 noted), Rust 1.95 (the 1.94
error), ashpd on async-io, the wgpu renderer (not blade) on X11 and
Wayland, Inter and Lucide, the theme tokens against gpui-component's, the
first slice, the plan's risks restated, the open choices, and what this
attempt changed in the interrupted one's work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 03:18:23 +03:00
faumarayandClaude Opus 5.5 b6f8f16108 spikes/gpui: headless-wayland.sh stops its compositor
nixpkgs' sway wrapper runs sway under a dbus-run-session of its own when
no session bus is set, so the script's kill reached dbus-run-session and
every run left a headless sway behind. It now runs sway-unwrapped, which
is the process it kills, and clears sockets a dead compositor left in its
private runtime directory before it waits for the new one's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 03:12:16 +03:00
faumarayandClaude Opus 5.5 f9f95dbf0d spikes/gpui: the Slint app's logs stay out of the desktop's state directory
headless.sh and headless-wayland.sh set XDG_STATE_HOME to the run's state
directory as they set the other XDG directories: the Slint app (the
slint-720p30 case) keeps its log files there, and its runs had written
them to the desktop's ~/.local/state/voelin/logs.

measure.sh waits for the Slint app's window (up to 60 s; it took more than
20 s to appear on a busy machine, past the fixed 8 s the case waited) and
then measures it for the case's full length. The video README gives the
static cases and the Wayland run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 02:38:08 +03:00
faumarayandClaude Opus 5.5 1ffcf690cc spikes/gpui/windows: spike 3, a second window on the shared model
A main window and a Studio-like window (cx.open_window through
gpui_kit::open_window) both render views that observe one root entity: a
counter both change, the push-to-talk state, which window is active, and
the studio's preview. Closing the studio window docks it
(on_window_should_close), closing the main window ends the app, F11
toggles fullscreen, Ctrl+Tab activates the other window. The global
push-to-talk key is voelin-platform's X11 hotkey (XInput2 raw events),
read by a GPUI foreground task. The preview comes from voelin-media's
studio compositor and its preview tap, one BGRA RenderImage shown by both
windows, the replaced one dropped from every atlas. drive.sh runs the
scenario and its checks on the headless display.

From the interrupted attempt, changed here: the window's size after a
fullscreen toggle is logged once the window manager has set it (the
toggle's own bounds are the old ones) and checked (1000x900 back);
drive.sh says how long the app took to end; measure.sh (new) runs the
three cost cases into $OUT instead of the README's commands, which wrote
into the current directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:43:43 +03:00
faumarayandClaude Opus 5.5 c81d4ea666 spikes/gpui/composer: spike 2, the composer, preedit and chat lines
gpui-component's Textarea as the composer (auto-grow, placeholder), emoji
from a picker of voelin-ui-vm's emoji archive inserted at the caret,
pictures and file paths pasted as attachments (Textarea::on_paste),
Ctrl+Enter bound to Send in the Input context after gpui-component's own
bindings. Sample messages go through voelin_ui_vm::chat::line and are drawn
as StyledText with one GPUI text run per TextRun inside InteractiveText,
links clickable (masked ones ask first). The preedit is GPUI's own (XIM on
X11, text-input-v3 on Wayland); the spike reads the marked range and
prints it. drive.sh runs the scenario on the headless display, ime.sh the
X11 preedit with fcitx5 and Pinyin.

From the interrupted attempt, changed here: runs instead of highlights, so
each run has its font (emoji runs in Noto Color Emoji, code in the theme's
monospace font: the row's font_family("monospace") resolved to no
monospace font); a sample line of the smileys DejaVu Sans also has; the
picker in the emoji font; the font probe (whose get_font_for_id printed
"?" for every fallback font) replaced by an emoji probe that counts the
glyphs GPUI draws in colour (ShapedGlyph::is_emoji), printed by drive.sh as
findings for the system's and a Noto-only font configuration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:43:43 +03:00
faumarayandClaude Opus 5.5 fd421b9982 spikes/gpui/video: spike 1, decoded video as BGRA RenderImages in img()
video.rs' delivery (deliver, FrameSlot, Handoff, Buffers; video.rs:360-480)
ported to GPUI: the decoder hands over its newest frame only, a converter
thread turns it into an Arc<RenderImage> (BGRA, spike_common::bgra), the
window takes the newest from a Latest in render and drops the one it
replaces from every window's atlas (cx.drop_image). A RenderImage owns its
pixels with no way back to them, so Buffers' reuse cannot be ported.

Sources: --mode pipeline is LocalPreview with SourceId::Synthetic through
the real VP8 encoder and decoder, as Video::demo; --mode raw hands I420
frames from memory to the converter; --mode static (added in this attempt)
is the control: one picture, uploaded once, the window repainted every
frame. --convert rgba measures voelin-media's conversion in place,
--no-drop is the negative control for drop_image, --bench times RGBA
against BGRA. measure.sh runs every case on the headless display, with
damage-count beside it and the Slint app's demo stream for comparison.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:43:30 +03:00
faumarayandClaude Opus 5.5 c9859bcfb4 spikes/gpui: the GPUI spikes' workspace, environment and meter
Plan section 6 step 1. A Cargo workspace of its own under spikes/gpui (own
lock, not a member of the root workspace, so the root's lock, deny policy,
notices and CI are untouched; it builds into the checkout's target/), on
gpui-kit pinned to =0.8.0. No gpui-kit release builds on Rust 1.94 (every
gpui-pre 0.3.x calls std::hint::cold_path, stable since 1.95), so the
workspace says rust-version 1.95.

- shell.sh: the toolchain (1.95.0, 1.94, stable or nightly, all from one
  pinned fenix), the native libraries, Mesa's lavapipe as the only Vulkan
  driver, Xvfb, openbox and the X tools, Noto Color Emoji and Noto Sans CJK.
- headless.sh: a private Xvfb display with openbox and a private session
  bus, never the desktop's; headless-wayland.sh: sway's headless backend.
- spike-common: CPU by thread group and memory from /proc once a second
  with the spike's counters (meter), proc-meter and damage-count for
  programs without a meter (the Slint app), Inter and the emoji/CJK fonts,
  the client's Lucide icons as GPUI assets, and the BGRA twin of
  voelin_media::convert::to_rgba.

From the interrupted 2026-10-25 attempt, kept; changed here: shell.sh takes
1.94 and nightly from the pinned fenix (the store paths it named were
garbage-collected), the README's headless-wayland.sh paragraph (sway, not
weston), its fmt command (-p, not --all), its toolchain and nixpkgs lines,
and the font docs (GPUI drops Noto Color Emoji from a fallback chain).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:43:20 +03:00
faumarayandClaude Fable 5.1 2e985d793c Merge phase5/ui-vm-2: the remaining Slint controllers split into toolkit-free logic (voelin-ui-vm) and Slint bind files, the engine-event transitions in vm::events::apply, the ui-vm gate follow-ups (plan section 6 step 2)
CI / Linux checks (push) Successful in 25m39s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 10:59:44 +03:00
faumarayandClaude Sonnet 5.5 f183b22b63 voelin-store: the writer of the blocked-checkpoint test paces itself by its own commits
The first version of this test (2cbb816) still failed under heavy load, with
the sign-out itself returning DatabaseBusy. The cause is the writer's fixed
pause of 5 ms: when disk pressure makes each of its commits take 100 ms and
more, it holds the writer lock nearly all the time, and the sign-out, whose
busy timeout is the default five seconds, never gets it between two commits.
(The commit message of 2cbb816 blamed the writer's synchronous = FULL; the
setting is right to mirror the app, but it was not the cause.)

Reproduced without load by delaying every pwrite64 of the process by 700 ms
(strace -f -e inject=pwrite64:delay_enter=700ms): the test of 2cbb816 fails
with DatabaseBusy from the sign-out in two runs of two, this version passes in
two of two. The lib test of 2cbb816 passes with the same delay and with fsync
delayed by 3 s as well.

Now the writer pauses ten times as long as its last write took (5 ms at least),
so its share of the lock stays under a tenth whatever the disk does, and the
sign-out starts only after the writer has written once (a thread of a busy
machine can start after the whole sign-out is over, which made "the writer
never ran" a failure of the machine). A drop guard ends the writer if an
assertion of the test fails first.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 10:54:10 +03:00
faumarayandClaude Fable 5.1 4491ecee25 Merge main (3930ef2) into phase5/ui-vm-2
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 10:45:33 +03:00
faumarayandClaude Fable 5.1 785bbd050b docs: the three minors of the Opus gate of phase5/ui-vm-2
docs/ui.md: the app.rs row of the step-3 table points the toolbar and
tree refreshes at servers/bind.rs, where they live; app.rs only calls them.
voelin-ui-vm host.rs: the doc of Update::rest matches the events module
(the Studio's stream, a changed setting, the offline-message answers; the
watched and shared streams are state and go through the stream effects).
CHANGELOG: the two visible fixes of the branch are named instead of
"nothing changes on screen".

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 10:45:33 +03:00
faumarayandClaude Sonnet 5.5 8c891a057e docs: session-seam 17.6 records the double listing in the trait's sign_out
When the device key's own row carries a device-only binding, the provided
KeyStore::sign_out of VoelinProtocol (c5bb6b9) lists the key twice in
SignOut.unbound: in its loop over the identities bound to the account and in the
Auto branch. The tests of this repository use contains and do not mind (a probe
counted two entries for the key with either value of bound_existing_key); the
fix is a follow-up for VoelinProtocol.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 09:16:21 +03:00
faumarayandClaude Sonnet 5.5 2df0b91edd CHANGELOG: the key store entry in the present tense
"The key store now keeps the device key when signing out ...", with the
sentence that nothing changes on screen yet kept.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 09:15:43 +03:00
faumarayandClaude Sonnet 5.5 9f720d75bd docs: rewrap the four lines of the key store text that passed 80 columns
Two in docs/architecture.md (the sign-out paragraph and item 2 of open
question 10) and two in docs/session-seam.md 17.6 (the voelin-store leak
bullet), refilled to the width of the files. The words are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 09:15:31 +03:00
faumarayandClaude Sonnet 5.5 2cbb816686 voelin-store: the two blocked-checkpoint tests no longer decide by the clock
a_reader_that_blocks_the_checkpoint_... and store::tests::a_blocked_checkpoint_...
bounded the wall clock of a checkpoint (1 s) and gave the concurrent writer a
busy timeout of 1 s. A checkpoint ends in two fsyncs, which take seconds under
disk pressure: the review's sequences failed 7 of 8 and 6 of 8 at I/O pressure
of 10 to 30 %, and dd conv=fsync loops beside 32 busy loops made the lib test
wait 6 s and the sign-out 5 s ("database is locked" for the writer,
DatabaseBusy for the sign-out, whose writer neighbour committed with
synchronous = FULL).

The integration test now asserts what it means without a time: the sign-out
finishes, the writer (set up as the app's connections are, synchronous =
NORMAL, a busy timeout of a minute) gets through without an error, and one
checkpoint is made for the four removals. It is renamed from "costs
milliseconds". The lib test sets the connection's busy timeout to an hour, calls
checkpoint_truncate once and requires that it came back while the reader still
held its snapshot (the reader lets go from a watchdog after 30 s, so a
checkpoint that does not give up fails the test instead of hanging it), that the
reader blocked it, and that the timeout is the hour again. With the line that
sets CHECKPOINT_WAIT removed the lib test fails after 30 s.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 09:14:22 +03:00
faumarayandClaude Sonnet 5.5 9e9db0e160 docs: CHANGELOG for the key store and the leak, and the old protocol revision named nowhere
CHANGELOG: one line under Changed for the sign-out that keeps the device key
and the identity text that errors no longer repeat.

docs/session-seam.md: the four places that named the old protocol revision (the
reading list of the design, slice 1, the conformance run, the lock merge of the
gate round) are records of that round; they now say "the pin of that round" and
name c5bb6b9 only where it is the revision the statement was checked at (the
suite has 17 cases in the same order at c5bb6b9 too).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 07:08:51 +03:00
faumarayandClaude Sonnet 5.5 18b280df7e voelin-store: a damaged TeamSpeak identity row is reported by its kind of damage, never by its text
Store::identity and Store::identities read the stored JSON of a TeamSpeak
identity with `?`, so a row whose data was damaged outside the client came back
as Error::Json carrying serde_json's message, and that message quotes a value
it refuses: tsproto reports a key that does not import as an invalid value, the
key string and all. The error reaches status lines, events and logs.

identity_from_json classifies the error as voelin-core's ts::identity::from_json
does (voelin-core depends on voelin-store, so the classification is here too):
Error::Identity { damage: IdentityDamage, line, column } says malformed, cut
short, not an identity or unreadable, and where, and nothing of the text.
Error::Json stays for the bookmarks and settings, which hold no secret.

The key store was checked as the recorded leak (docs/session-seam.md 17.6)
names it, and does not leak: check_teamspeak (keystore.rs) drops the parse
error with `let Ok(..) else`, Columns::level uses `map_or`, and the warning of a
damaged binding names the row's kind and uid. A test pins that too.

tests/identity_text.rs damages a row six ways (a key that does not import, a
counter of the wrong type, syntax, a text cut inside its key, bytes that are no
UTF-8 as a BLOB and as TEXT) through a second connection, calls everything of
Store and SqliteKeyStore that reads or writes it, and looks through the errors
(text, Debug and sources) and every log line at TRACE (a capturing subscriber in
tests/support) for any 8 characters in a row of the row's data. A control shows
that serde's own message quotes the value and that the capture sees a warning.
With identity_from_json returning the old error the first test fails, naming
the quoted key; the key store test is a guard.

docs/session-seam.md 17.6: the leak bullet is closed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 07:08:35 +03:00
faumarayandClaude Sonnet 5.5 412f909d18 docs: the key store keeps every key at sign-out; the three parts of open question 10 and the duties of the GPUI client (Phase 2 task 34)
docs/architecture.md, "Identities": the sign-out wording follows the trait of
c5bb6b9 (the device key stays, unbound, whether it predates the account or not;
the account record and the synced copies are what it deletes; the release is
the service's operation and the same local sign-out; the deletion of an account
releases every device key and the same sign-out is its local half), and records
the screens' duties as the GPUI client's: the sign-out dialog with "Forget this
device's identity" and an export first, the release in Settings -> Account, and
the delete-account dialog, which must warn that the account's servers become
unreachable and offer an export of the device keys first. The reasons of the
refusal of a synced device key and of the checkpoint are reworded to match
keystore.rs.

docs/session-seam.md 17.6: a bullet for the key store's follow-up, with what it
did and what it did not need (no release call, no "released" record).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 07:02:31 +03:00
faumarayandClaude Sonnet 5.5 ca142fd3f2 voelin-store: the local half of releasing a device key is the sign-out, and the store needs nothing more
AccountClient::release (voelin-account-client at c5bb6b9) asks the service to
release the key and then runs KeyStore::sign_out with DeviceKeyChoice::Auto, so
the unbind of one key that keeps its data is the sign-out's own step (and a put
of the blob without its binding for a single key). Open question 10 and
protocol 13.6 ask the client to remember nothing: the service holds the
registration of the key, and the client learns that a key is still registered
with an account it signed out of from the service's answer to a sign-in or a
sign-up (CONFLICT, field device). So there is no "released" record and no new
store call; keystore.rs says so, and says the same of the deletion of an
account, whose local half is this sign-out.

Two tests pin what the client relies on after a release: the key is kept byte
for byte and unbound, then is the device key of a record of another account,
and a sign-out of that account keeps it again (its copies go); and a release
whose local half was cut short is finished by a sign-out with Auto, and a
second one finds nothing to do.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 07:01:42 +03:00
faumarayandClaude Sonnet 5.5 c0e8a533a4 voelin-store: SqliteKeyStore follows task 34, a sign-out keeps every key and only a forget deletes one
The module documents of keystore.rs are rewritten to the rule of open question
10 (accounts design, answered 2026-10-24): a sign-out keeps the device key
unbound whether it predates the account or the client made it for the account
(bound_existing_key is the client's wording and no rule reads it), the
identities only this device holds are unbound and kept, and "Forget this
device's identity" is the only deletion of a key of the device: signed in it is
sign_out with DeviceKeyChoice::Forget(uid), signed out it is KeyStore::remove
(a TeamSpeak identity: Store::delete_identity). The store has no export call;
the docs say where the UI reads the bytes (voelin_key + to_pkcs8, Store::identity
+ ts::identity::export) before it forgets, which also serves the delete-account
dialog's export of the device keys.

What a sign-out still deletes is not a key of the device, and the docs now say
so truthfully: the synced copies of integration secrets (private keys, scrubbed
from the file and its log like any deleted key), the account record (no
secret), and with Forget the device key. That is why SignOutPass stays: the
trait's sign-out removes those rows, and the log is still truncated once after
the last step, not per row, and not at all when nothing was deleted.

The refusal of a synced device key stays and is reworded: the sign-out keeps the
device key, but its first step deletes every synced copy before it reads the
record, so a device key stored synced would be deleted all the same.

Tests (the turned-around ones are in the previous commit): the device key's
whole row is unchanged by a sign-out, with and without the flag; a key that
carries a device-only binding is unbound and nothing else of its row changes;
a sign-out scrubs what it deletes and leaves the kept keys in the file; the
blocked-checkpoint test counts exactly one blocked checkpoint for four
removals (Forget, so the removals are four as before), through a TRACE-level
capture in tests/support; a sign-out that deletes nothing does not checkpoint;
a key kept by a sign-out is exported, forgotten with no trace in the file or
the log, and restored from the export.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 06:58:22 +03:00
faumarayandClaude Sonnet 5.5 4bd3d7a971 deps: voelin-identity, voelin-proto and voelin-model at VoelinProtocol c5bb6b9 (Phase 2 task 34)
The three protocol crates move together, as docs/building.md says: the
identity crate depends on voelin-proto of the same revision, so moving it
alone would put two voelin-proto packages in the lock.

c5bb6b9 is the protocol's main with task 34 (open question 10): the provided
KeyStore::sign_out keeps the device key whatever AccountRecord.bound_existing_key
says (only DeviceKeyChoice::Forget deletes it), and the crate gains Adoption,
Release and REVOCATION_KIND_RELEASED. Nothing in the workspace needed a source
change to compile (cargo check --workspace --all-targets --locked is clean on
1.94); the conformance Fixture of voelin-proto now holds an Arc<dyn Backend>,
and FakeHandle implements it, so the two callers build as they were. The
suite still has 17 cases, in the same order, so the two comments that named
the old revision name c5bb6b9.

Cargo.lock: the three source lines only. `cargo update -p ...` also flips
windows-sys 0.52 to 0.61 and itertools 0.14 to 0.13 in unrelated entries;
those are not taken, `--locked` accepts the file without them.
THIRD_PARTY_NOTICES.md regenerated (scripts/notices.sh): unchanged, the
workspace and git crates are not in it.

The voelin-store tests that pinned the old sign-out (a key made for the
account is deleted by Auto) are turned around here, in the same commit,
because they cannot pass with the new trait: the key stays, unbound, and only
Forget deletes it. The rest of the sign-out follow-up (the module documents,
the refusal wording, the new tests) is the next commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 06:53:29 +03:00
faumarayandClaude Fable 5.1 3930ef2945 Merge phase5/test-hygiene: test hygiene after the runner-image round (DatabaseBusy twin, closed-port race, the load-only flakes, ts6_banners alone with its server, docs/testing/load.md)
CI / Linux checks (push) Failing after 5m13s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 06:12:04 +03:00
faumarayandClaude Fable 5.1 8614b120fe docs: load.md records the review's undecodable_video flake and the seven unformatted intermediate commits
The review's 100 whole-binary runs of the head saw
media::tests::undecodable_video_is_noticed_through_the_pipeline fail once
at load 106-146 (untouched by the round); it joins "Seen and left alone".
cargo fmt differed at seven intermediate commits, not six (the shell-only
5c029a9 sits on the unformatted tree); the orchestrator waives per-commit
rustfmt for them, fixed forward in 94195db, history not rewritten.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 06:11:47 +03:00
faumarayandClaude Sonnet 5.5 f791d3926f docs: testing/load.md names its own commits
The record's table said "this one" for the commit that adds the page; there
are two, the page and its record.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 04:54:19 +03:00
faumarayandClaude Sonnet 5.5 376925a96e docs: testing/load.md records the round, its commits and what ran
The record of the round at the top of the page, in the form of the earlier
rounds' records: the branch and its base, the fallback for the unregistered
mao-* agents, the commit table (which commits are the cut-off run's, which are
this attempt's, which are beyond the list), the two hunks dropped from the
cut-off run's tree, and a table of the checks that ran on the final tree. The
scope test's row gets the failures of the earlier tree that only had the first
half of its fix.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 04:54:03 +03:00
faumarayandClaude Sonnet 5.5 d4ccb8c8b8 docs: testing/load.md, how to make a machine busy and what the load-only tests assert
The recipe of the round (32 busy loops beside many runs of a test binary, a
build before and one after run alternately), the rules the fixes followed, the
table of the tests that failed only under load with their counts before and
after, the account-change test of the seam follow-ups (not reproduced; the
timing of its steps against its deadlines, and the reading of the code that
found no race), the tests seen at heavier load and left alone, and the
engine stage of the live smoke (ts6_banners failed because the test shared the
TeamSpeak 6 server with the others; what the smoke still does not do
reliably). docs/ci.md points to it from the section on the job image.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 04:34:05 +03:00
faumarayandClaude Sonnet 5.5 ad806606ac Say in the smoke script which of its checks still flake
After the roundtrip and ts6_banners fixes the smoke passed two of three runs
on the head of the branch; the third failed at the directory check of the
TeamSpeak 6 stage, `the directory did not list the stream`. The viewer of that
check ends when it has 30 frames and the script looks for the directory's
`"title"` line, which the viewer prints only if its own gateway session had
connected by then; in the failed run it was still `observe=Connecting`. The
fix is in voelinctl engine (end the viewer on both), not in a round about
tests, so the comment above directory_check records it, with the earlier
`expected output did not appear` of the gateway stage that was seen with the
same engine state.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 04:34:05 +03:00
faumarayandClaude Sonnet 5.5 f508e5bec4 Count frames, not a pause, in the automatic-bitrate test's "not per frame" check
Beyond the list of this round, found by its final whole-binary run: 1 of 150
runs of the voelin-core lib beside 32 busy loops failed in
an_automatic_bitrate_follows_the_stream, at the assertion that the sink is told
the layer's format once per change and not per frame (`left: 2, right: 1`), and
the unchanged test failed 2 of 900 runs of its own beside the same load.

The sink is told twice for the first picture, and the test counted in between:
Streamer::attach tells it the format from the size captured so far (when a
frame has been captured before the attach), and the encoder tells it again
before its first frame, because its record of what it told starts empty. The
test waited for the format, took the count, slept 200 ms and compared; on a
busy machine the encoder's first frame comes later than the 200 ms.

The test now waits until a frame has been handed over (the encoder tells before
it hands over, so both tellings are done), takes the count, waits for five more
frames, and compares: "per frame" is counted in frames. The deadline of 30 s
only ends a hang. 0 failures of 600 runs of the test beside 32 busy loops.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:59:07 +03:00
faumarayandClaude Sonnet 5.5 94195db16a Format four spots of the test changes of this round with rustfmt
cargo fmt on the own crates changed these four places of the commits before:
the match arm of ask_files_until, the closure of the features test, the count
closure of streamer_sends_opus and the call of preview_until in the studio
test. No change of meaning. Each of those commits passes clippy on its own;
rustfmt was not clean in them until this one.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:42:19 +03:00
faumarayandClaude Sonnet 5.5 5c029a982a Start the smoke's action when its listener is on the server, not after 3 s
roundtrip started the listener in the background, waited a fixed 3 s and ran
the action (the poke, the private message, the avatar request, the file
upload). A dev server that is slow to let a client in (4 s and more, 13 s
seen, when the machine is busy) left the action running against a client that
was not on the server yet: `error: message: the client is not on the server`,
and `FAIL: private message: the action failed` (the action's client printed
`connected: 2 clients` and the listener's `connected: 1 clients` came after).
That is one of the places at which the earlier steps of the smoke flaked.

voelinctl engine prints `connected: N clients` once its client is on the
server and has seen the presence, for every action; roundtrip now waits for
that line in the listener's log (60 s at most, and not when the listener has
ended) and then 1 s more, for the others on the server to see the listener.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:30:02 +03:00
faumarayandClaude Sonnet 5.5 069fd2ac12 Run ts6_banners with the TeamSpeak 6 server to itself
The engine stage of the live smoke failed in every run that reached it, before
and after every recent branch, at crates/voelin-core/tests/live.rs
`disabled policy must prevent HTTP requests` (ts6_banners, left: 4, right: 0),
while the six tests of the file passed one after the other.

ts6_banners sets and unsets the TeamSpeak 6 server's banners, and it counts the
requests that reach an HTTP server of its own for the images it set, to show
that an engine whose policy is disabled makes none. The server tells every
client that connects while the banners are set where they are, and an engine
fetches what it is told (as it should): the other tests of the binary, which
cargo runs side by side, connect engines to the same server, and their
requests were counted as the engine under test's. Reproduced against the
development servers with the tests in pairs: ts6_banners alone passes (62 s),
with ts6_avatars, ts6_engine or ts6_channel_joins at the same time it fails
(`left: 2` or, in the join test's case, a later count, `left: 6, right: 4`),
and the TS3 and TS6 tests without it pass in any combination. So the test was
wrong, not the engine or the script's ordering: it needs the server to itself.

The TeamSpeak 6 tests that connect now hold a lock shared and ts6_banners
holds it exclusively, so it runs before or after them and not meanwhile. The
smoke is not run with --test-threads=1 for this: that would hide it, not
remove it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:29:42 +03:00
faumarayandClaude Sonnet 5.5 661a607a35 Make two more link and media tests independent of how long the machine takes
Beyond the list of this round, found by its load runs and rarer than the tests
of the list: in about 500 runs of the whole voelin-core lib beside 32 busy
loops, a_scope_bigger_than_the_channel_is_sent_in_bigger_chunks failed 3 times
(the scope had 1 channel, not 5,003) and streamer_sends_opus 2 times (the
`video too` expectation). The fixes are of the mechanism the code shows; the
runs after them (docs/testing/load.md) are too few to count a rate that low.

a_scope_...: the connector waits 250 ms for a link's first snapshot after it
said it is connected, and the test made its 5,000 channels after saying it, so
a busy machine made the session without them. The channels are made first. The
scope is also sent whole only if the presence is in the host's state when it
is asked for, so the test now sends a voice packet of one of the presence's
clients and waits for it to come through: the link takes its events in order,
and a packet of a client comes through only once the presence is in.

streamer_sends_opus: it waited for ten frames of audio and then expected a
frame of video, but audio is made quickly and a busy machine can keep the
video encoder from its first frame for longer. It now waits for ten frames of
audio and one of video, whichever the encoders make first; its deadline, 30 s,
only ends a hang.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:27:19 +03:00
faumarayandClaude Sonnet 5.5 92d02b0e00 Wait for the studio's delivered count in the capture-backend test
Beyond the list of this round, found by its load runs: in 150 runs of the
whole voelin-media test binary beside 32 busy loops, 11 failed, 9 of them in
packets_reach_the_outputs_and_the_studio_is_a_capture_backend at
`assert!(studio.shared.delivered.load(..) > 0)` (the other 2 in
it_composes_into_the_preview_and_follows_commands, fixed in the commit before).

The studio counts a frame as delivered after it has handed it to the capture
sink (`sink.frame(..)`, then `delivered.fetch_add`), so a test that has just
received the frame can read the count before it is made. The test now waits
for the count to become non-zero after it has the frame; the wait for the
frame is 30 s instead of 5 s, and the wait for the count 30 s, which only end
a hang.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:56 +03:00
faumarayandClaude Sonnet 5.5 9d04e0158a Wait for a preview frame of the size and scene asked for in the studio test
it_composes_into_the_preview_and_follows_commands took the first preview frame
after SetPreview and asserted its size. The studio composes from the moment it
starts, at the preview size and rate it has then (480x270, 15 fps), so the
first frame there is can be one of that size, composed before the command was
applied; on a busy machine it is. The 2 s waits for the new scene's colour
and the test's overall 5 s and 10 s limits measured the machine too.

preview_until now reads the preview until a frame that the test takes comes,
and looks at 20 frames at most: the preview keeps only the latest frame, so
few older ones are waiting or on their way, and the number of frames looked at
is the bound by the work. The wait for each frame, 30 s, only ends a hang.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:33 +03:00
faumarayandClaude Sonnet 5.5 77304604fe Let the stream task say when it is done in the layer-format test
layer_formats_reach_the_live_stream sent the same layer format a second time
and then slept 200 ms before asserting that no keyframe was asked for, which
tests that the stream task had not got to the command within 200 ms. It is the
task that asks for a keyframe (when the layer's bitrate changes) and it takes
its commands in the order they are sent, from the sink and from the handle
through the same channel. The test now sends a command whose answer is an
error event (Kick of a viewer, 65535, that is none) and waits for that
event: it comes after everything the format set going, and nothing is left to
wait out. A keyframe request the viewer's side makes late is not covered, and
none was seen.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:33 +03:00
faumarayandClaude Sonnet 5.5 c5bb74ffcb Ask the file list one question at a time in the server-features test
the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list asked for
the lobby's file list every 20 ms until the answer was the one it wanted. The
bus holds 16 events, so on a busy machine the answers fell behind it (and
behind the host's work) and the one that counted was lost in the backlog, or
an answer to a question asked before the host narrowed what it offers was
taken for one asked after.

A helper, ask_files_until, now asks one question and reads the bus until that
question's answer comes, then asks the next only if the answer was not the one
wanted. Every question is answered before the next is asked, so those asked
after the update is pushed are the ones the update can refuse; nothing has to
be told apart by number, and nothing is waited out by the clock. The test
checks that the answer after the server lifted its list came from the host.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:33 +03:00
faumarayandClaude Sonnet 5.5 81c40a4b09 Wait for the states audio_sources_change_live asserts, and keep feeding the microphone
audio_sources_change_live failed 6 of 200 runs beside 32 busy loops, in two
ways. It waited for the sources' meters and then asserted their state and the
mixer's level and limiter, which are set at other times than the meters: the
state could still be Starting when the meters showed the tones. And its
microphone thread published 50 chunks of 20 ms, one second, and the source
takes what is published only from when it runs, which a busy machine delays
by any time, so the test then waited 5 s for a level that had gone by.

The first wait now includes the state, the mix and the limiter. The thread
publishes until the test has heard the tone (or, as a cap that ends a thread
whose test failed first, 120 s), and the second wait includes the window
source's error and the muted tone's own level, which the test asserted right
after it. The deadlines of the waits, 30 s, only end a hang; what is waited
for is a state.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:22 +03:00
faumarayandClaude Sonnet 5.5 25be4337a8 State what the preview's rates are, not what a busy machine reaches
The end of local_preview_decodes_the_pattern asked the rates of the second
since the first stats call to be 20 to 40 pictures and 100,000 to 5,000,000
bits a second. How many pictures a second the pipeline manages is a property
of the machine's load, and a second of sleep is longer than a second when the
machine is busy; neither is what the stats are about. What they promise is
that fps and bitrate are the counters' change over the time since the call
before.

The test now times its two stats calls and the sleep between them. The time
the stats measured lies between the two spans that the test measured around
it (from the end of the first call to the start of the second, and from the
start of the first to the end of the second), so the reported fps has to be
the pictures counted in that time, within the rounding of fps, and the
bitrate the bits counted in it, within the cut-off of bitrate. At least one
picture has to have come in the second.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:22 +03:00
faumarayandClaude Sonnet 5.5 f9bfd5d305 Check the test pattern's structure, not its pixels within a tolerance
rectangle_span, the pixel check of local_preview_decodes_the_pattern and
test_pattern_through_stream_tasks, asked every pixel further than two columns
from the rectangle's edges to be within 24 per channel of the rectangle's
colour or of the background. The streamer's VP8 speed control lowers the
quality when the encoder falls behind, and a flat colour then moves by 30 and
more per channel (seen: [33, 31, 101] and [50, 33, 48] for the background
[24, 40, 72], [255, 85, 5] for the rectangle [240, 90, 30]), still nowhere
near the other colour. A tolerance of 40 was tried and reverted: it only moves
the load at which it fails.

A pixel is now whichever of the pattern's two colours it is nearer to, and
what the test is about is the row's structure: background, one run of the
rectangle, background. The first and last pixel that are the rectangle's give
the span; everything between them, but the two blurred columns at each end,
has to be the rectangle's too, and the callers still check the span's width
and that it moves. A stray rectangle-coloured pixel in the background
stretches the span over background and fails there.

Before, the two tests failed 4 and 2 of 100 runs each beside 32 busy loops; see
docs/testing/load.md for the runs after.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:13 +03:00
faumarayandClaude Sonnet 5.5 0bc6abadfe Name the step in which the account-change test timed out
account_change_cancels_pending_handshake was seen to fail about once in 130
runs of the whole suite under load, and the failure was not kept. Its three
timeouts (5 s for the first handshake packet, 5 s for a packet from a new
socket after the account changed, 2 s for the connection to end after the
account source closed) were bare unwrap()s, so a failure said only that a
timeout had elapsed, at a line. Each now says which step it was.

No race was found, in the test or in the code it drives. The account receiver
has seen its version before the connection is made, so a change after the
first packet always restarts the connection; the restart opens a new socket,
so a packet from another port is a packet of the new connection; dropping the
sender makes changed() fail, which ends the loop with the reason the test
expects. The ways the test can fail are those three deadlines. With the steps
timed (a throw-away instrumented build, not committed), 300 runs of the test
alone, eight at a time beside 32 busy loops, all passed, and the steps took at
most 34 ms, 33 ms and 9 ms against deadlines of 5000, 5000 and 2000 ms. So
the failure needs a stall of seconds, which is the machine's and not a
property of the test; docs/testing/load.md has the numbers and what to do if
it is seen again.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:12 +03:00
faumarayandClaude Fable 5.1 de89fddcb6 deps: crypto-bigint 0.7.7, ctutils 0.4.5, rustls-webpki 0.103.16, tokio 1.54.1, webpki-root-certs 1.0.11 (RUSTSEC-2026-0382, -0383, -0385, -0386, -0387); notices regenerated
CI / Linux checks (push) Successful in 37m31s
RUSTSEC-2026-0387 stays on the crypto-bigint 0.5 and 0.6 lines that the
tsclientlib fork pins (p256 0.13 in tsproto-types, crypto-bigint in tsproto);
ignored until 2026-12-20 with the fork's move to p256 0.14 as the follow-up.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 02:44:31 +03:00
faumarayandClaude Sonnet 5.5 e465a55b9e Give the fallback gateway test a port that stays refused
the_next_published_gateway_is_used_when_one_fails took its "port nothing
listens on" by binding a listener to port 0 and dropping it at once. A port
that is free only for a moment can be given to another socket before the
engine connects to it: the other tests of the binary bind port 0 for their
fake gateways and proxies, and the one that gets the port answers the
connection, so the test then passes over a gateway that is no longer closed,
or fails on the 650 ms deadline.

The test now binds a TCP socket and keeps it, without listening, for its
whole length: the port is taken, so nobody else gets it, and a connection to
it is refused at once. It checks that refusal before it relies on it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 02:21:55 +03:00
faumarayandClaude Sonnet 5.5 ac957a0c87 Reopen the history database of the gateway test after the engine has closed it
history_on_open_paging_and_offline_messages drops its engine and opens the same
database again for the restart it tests, the same shape as the contacts test
that 0d67dd7 fixed: dropping an Engine does not close the history database, the
engine task ends later and closing the connection checkpoints the write-ahead
log under an exclusive lock, and a History::open meanwhile waits for that lock
only for the 5 s busy timeout, failing with DatabaseBusy on a loaded disk.

The test now waits until the -wal file is gone before it reopens. The helper
that does so (closed) moves from voice_features.rs to tests/common/mod.rs,
which both test binaries declare.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 02:21:55 +03:00
faumarayandClaude Sonnet 5.5 35408a3dfe Require the portal proxy test's child to report one passed test
The test runs itself again under dbus-run-session and, on a zero exit, returned
without looking at what the child printed. A child that ran no test at all
(its --exact filter matching nothing, as after a rename of the test) also exits
0 and printed "running 0 tests ... 0 passed", so the wrapper passed having
checked nothing. A zero exit now has to come with libtest's "test result: ok.
1 passed;" in the child's output, else the wrapper fails with that output.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 02:20:03 +03:00
faumarayandClaude Sonnet 5.5 7e63092bcd Say in from_json's doc who reads the identity text through it
The doc said every reader of the TeamSpeak identity text refuses it through
from_json. Only voelin-core reads it through there: voelin-store parses the
same text on its own (keystore.rs check_teamspeak and level, store.rs list),
and drops or forwards serde's message by its own rules. The doc now names
voelin-core and says voelin-store parses it too.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 02:19:48 +03:00
faumarayandClaude Fable 5.1 2ffe5ffb99 Merge phase5/tests-under-runner: the workspace suite green as root inside the runner image
CI / Linux checks (push) Failing after 35m27s
Every machine assumption of the tests fixed (root writes anywhere, no sound
card, no session bus, no GPU, no FFmpeg, no H.264 encoder, no display beyond
xvfb, no TeamSpeak servers, no DNS); a cancelled download's part file removed
after its task stopped (a real defect a test exposed). docs/ci.md: how to run
the suite the way CI runs it. Sonnet review accepted; its three docs minors
are in the last commit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 02:04:09 +03:00
faumarayandClaude Fable 5.1 e807df40e5 docs: ci.md quotes the right git error, removes root's files, names the bare clone, follows main's loopback and D-Bus tests; .scratch/ ignored
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 02:04:08 +03:00
faumaray a8dbc5ba74 Merge remote-tracking branch 'origin/main' into phase5/tests-under-runner 2026-10-25 02:03:16 +03:00
faumarayandClaude Sonnet 5.5 6c8d4bbb61 Bring the status of docs/ui.md up to date with the merge of main 6e0df51
One paragraph: what the merge brought (the session seam, the CI deploy key, the
media codec test and the seam follow-ups, none of it in the UI crates), that the
.set_ counts of the table were counted again on the merged tree and stand, and
where the colour of a chat's avatar is chosen (servers::logic::conversation_tint,
pinned by a test).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 23:37:10 +03:00
faumarayandClaude Sonnet 5.5 08a899cf01 Pin the colour of a chat's avatar with a test that fails when it falls back to black
The ui-vm gate's minor "server_tint falls back to black" was closed by a
fallback in App::conversation_item, `.unwrap_or_else(|| vm::avatar::tint(&title))`,
that no test could fail: replacing it with `.unwrap_or_default()` (opaque
black) left cargo test -p voelin-ui -p voelin-ui-vm green.

The choice of (kind, session) -> colour is now a pure function in
voelin-ui-vm, servers::logic::conversation_tint(state, kind, session, title),
and messages.rs calls it. A test pins the three cases: a server chat of a
server in the list takes the rail's colour, a server chat whose server is
gone takes the colour of its title, and a channel's or a person's chat (with
or without a known server) takes the colour of its title. The titles are
chosen so that the title's colour differs from the server's, and the test
asserts that. App::server_tint, whose only caller this was, is removed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 23:36:19 +03:00
faumarayandClaude Sonnet 5.5 9e7452ec2a Merge main (6e0df51) into phase5/ui-vm-2
Main gained phase0/ci-private-dependency (the CI deploy key and the checks
action), phase5/media-codec-test (a media test stated for machines without an
H.264 encoder) and phase4/seam-followups (five flaky tests fixed, the
identity-text leak closed, docs/session-seam.md 17.8 onwards). None of it
touches the UI crates: the merge is clean, with no conflict, and Cargo.lock
and THIRD_PARTY_NOTICES.md are unchanged by it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 23:17:40 +03:00
faumarayandClaude Sonnet 5.5 1de2725f19 Remove a cancelled download's part file after its task has stopped
The download test, which 61458df of this branch made wait for the part file,
exposed a defect of the link: a download reports Started just before it opens its part file, and the
open ran on tokio's blocking pool. Link::cancel() aborted the task and removed
the part file at once; when the cancel came between Started and the end of the
open, there was no file yet to remove, the abort cannot stop an open that is
already on the blocking pool, and the open then made an empty `<name>.part`
next to the target after the transfer had been reported Cancelled. The user
sees a leftover file, and a later download with `resume` continues from it.

files::receive now makes the directory and opens the part file with std::fs in
one step (the same kind of small blocking call as Sink::offset and the removal
in cancel, which already ran on the loop), so an abort, which takes effect at
an await, cannot come in the middle of it. Link::cancel() keeps the task's
JoinHandle instead of its AbortHandle, aborts the task, and removes the part
file and reports Cancelled from a task of its own after the aborted one has
stopped: the file the task made is then there to be found, or the task never
got to make one. Cancelled is therefore reported after the removal and after
the task has stopped, where it was reported before both.

The test goes back to the shape it had before 61458df: it cancels as soon as
the transfer is Started (and now fails loudly if it never was). That shape
failed in 10 of 100 runs of the voelin-core lib tests three at a time with 16
busy loops beside them on a 32-core machine, and in the final runs of the CI
test step in the runner image of this task (the second of three); with this
change it failed in none of 200 such runs. The link and files tests pass.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 23:07:48 +03:00
faumarayandClaude Sonnet 5.5 443559aa79 Take the keyframe baseline of the layer-format test after the streamer has settled
stream::tests::layer_formats_reach_the_live_stream asserts that telling the
sink the same layer format twice asks for no second keyframe: it drains the
sink's keyframe requests, changes the format, waits for the request that
follows, tells the same format again and expects none within 200 ms. It failed
once ("nothing changed", stream.rs:1326) in the first of the three final runs of
the CI test step in the runner image of this task, with the machine busy with
another job.

Requests reach the sink from the stream going live, from the streamer's own
view of its viewer connecting (PeerEvent::Connected, a moment after the viewer
sees WatchState::Connected, which is all the test waited for), from the
viewer's picture requests, and from a changed layer. The test drained once,
right after the viewer's side was connected, so a request of one of the first
three that arrives later is taken for the one the changed format asked for, and
the real one then arrives after the "same again" and is counted as a change.
This could not be reproduced here (0 in 400 runs of the single test, 32 at a
time with 48 busy loops, nor in 200 runs of the lib tests); the change closes
those windows as far as they can be named: the test waits for the streamer's
own Connected (StreamViewers) as well, and drains until a moment longer than
the merge interval of requests (250 ms) passes with no request, before the
format is changed. The assertions are those of before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 21:42:15 +03:00
faumarayandClaude Sonnet 5.5 272de7a13d Read the streamer's stats until they show what the viewer already saw
Two voelin-core tests read Streamer::stats() once, at the moment a consumer had
seen the effect, and the stats lag behind it:

- stream::tests::test_pattern_through_stream_tasks asserted `video_frames >= 15`
  right after the viewer had decoded 15 pictures. The encoder counts a frame
  after the sink has taken it (`sink.send_video(..)`, then `fetch_add`), so the
  15th picture can be at the viewer first: video_frames was 14 with
  captured_frames 15 and the picture on screen.
- media::tests::an_automatic_bitrate_follows_the_stream asserted the layer's
  bitrate in the stats right after the sink had been told the layer's format;
  the stats had 0 (the layer's target is stored by the encoder thread, not by
  the call that tells the sink).

Both now poll for the value with a deadline (5 s, and 10 s as the test's other
waits), which is the same assertion without the order of two threads. Before,
on a 32-core machine with 32 busy loops beside the runs: the first failed on
that assertion in 7 of 150 runs of the stream tests six at a time, the second
in 19 of 120 runs of the voelin-core lib tests six at a time. After, in 200
runs of the lib tests three at a time with 16 busy loops beside them, neither
failed on these assertions.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 21:42:03 +03:00
faumarayandClaude Sonnet 5.5 61458df625 Cancel the download test's transfer only once its part file is made
link::tests::a_file_is_downloaded_through_the_connection_the_link_opens waited
for the Started state and then cancelled, expecting the part file to be gone
100 ms later. The download reports Started just before it opens the part file
(files::download, then receive), and the open runs on tokio's blocking pool. A
cancel that arrives in between finds no part file to remove (link cancel()
removes it at once and reports Cancelled), the aborted task cannot stop the
open that is already going on, and the part file is made after the cancel:
`assert!(!part.exists())` failed. It did so in the second of the final runs of
the CI test step in the runner image of this task, and in 10 of 100 runs of
the voelin-core lib tests with three of them at a time and 16 busy loops
beside them on a 32-core machine (none in 200 such runs with this change).

The test now waits for the part file itself, which is what "the transfer
waits in the middle" means, and checks that Started was reported.

This is a real, if small, defect of the product that the test exposed: a
cancel in the moment between Started and the end of the open leaves an empty
`<name>.part` next to the target. It is not fixed here: closing it takes
reporting Started after the open (it also feeds the chat and the preview size
limit) or waiting for the aborted task before the part is removed, which is a
change of the transfer code and not of a test. Recorded in the report of this
branch.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 21:41:37 +03:00
faumarayandClaude Sonnet 5.5 637ee58979 Record log lines in the tests through one subscriber for the whole process
web::tests::info_lines read the lines a closure logs with
tracing::subscriber::with_default. While that scoped subscriber is the only
one alive, tracing-core registers a callsite that another thread meets first
against that thread's own default, which is none, and the callsite stays
disabled for every thread. session::banner_tests::
a_failing_banner_is_logged_once_with_its_address flakes this way (lines == []):
it failed in one of eight runs of the CI test step in the runner image of
this task (assertion `left == right` failed: [] left: 0 right: 1 at
session.rs:2541; it passed in the other seven). Several other tests reach the same
"banner not downloaded" callsite through image_finished while it runs.

info_lines now installs a recording subscriber as the global default the first
time it is called, and each call records into a buffer of its own thread, so
every callsite is registered against the same subscriber and no scoped
dispatcher is created or dropped while tests run. The result is the same: the
lines `f` logged at info and above on its thread. The new test
info_lines_see_a_callsite_another_thread_met_first fails with the old helper
(lines == []) and passes with the new one.

The same change is 4be37e1 on phase4/seam-followups (not merged yet; it
measured 1 failure in 300 runs of banner_tests before and 0 in 600 after),
taken here unchanged so that a CI run of this branch does not stop on it and
the two branches merge without a conflict.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 20:08:50 +03:00
faumarayandClaude Sonnet 5.5 26ee8c38c1 Document the fields of the mirrored bridge structs and lift the exemption
The gate minor "field docs on the mirrored bridge structs" was answered with
`#![allow(missing_docs)]` on `bridge` and `studio_bridge`, and the crate's
comment said 400 or so fields. The two modules have 559 pub fields; 210
carried a comment of the .slint files and 349 (288 and 61) had none there.
Each of those is described now, from the code that fills it (the producers
in the view model and in voelin-ui, the settings keys' own documentation,
the gateway protocol's types), and the allow is gone: `#![warn(missing_docs)]`
holds for the whole crate and clippy -D warnings fails on a field without a
comment (checked by deleting one). docs/ui.md and lib.rs give the real
numbers.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:56:38 +03:00
faumarayandClaude Sonnet 5.5 9aea876437 Ask improve_level for more than the test identity already has
ts::identity::tests::improve_level_keeps_the_key made its identity with
Identity::create(), which stops at the first counter whose level is 8 or more,
and asked improve_level for 13. About one identity in 32 has 13 or more
already, and improve_level then returns it as it is, so the assertion that the
counter grew fails. The test does not depend on the machine: it failed 9 times
in 300 runs of the single test on a developer machine, and once in the
offline run in the runner image of this task, a CI run that fails one time in
about thirty for it.

The target is now three levels above what the identity has, so the search
always runs. The assertions on the level, the callbacks and the counter use
that target.

The same change is 9254e08 on phase4/seam-followups (which also fixes four
other tests that fail on their own and is not merged yet): it is taken here
unchanged so that a CI run of this branch does not stop on it, and the two
branches merge without a conflict.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:53:00 +03:00
faumarayandClaude Sonnet 5.5 370eaf94ed Point the references to the controllers the split removed at their folders
`servers.rs`, `chat.rs`, `streams.rs` and `settings_page.rs` of voelin-ui
are `servers/`, `chat/`, `streams/` and `settings_page/` since the split
(the Slint side in `bind.rs`, the decisions in voelin-ui-vm), and
`adopt_server_name` is in the view model's `events`. The comments of
`events.rs`, `app.rs`, `studio/bind.rs` and `dev/bind.rs`, and the
add-server section of docs/ui.md, named the old files. The "before" names in
the table of the `.set_` counts stay: they are the files as they were.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:44:14 +03:00
faumarayandClaude Sonnet 5.5 b439b9fbb2 Count the status line's calls in docs/ui.md as the files have them
Of the 230 `.set_` lines of the seven files at ad20979, 36 are calls of
`set_status(`, not 37: the 37th hit was `set_status_text`, the Bridge write
inside `set_status`, which is one of the ten direct writes already. Say so,
and give the share of Bridge writes (186 of 230) next to the two fractions.
`messages.rs` has 11 `.set_` calls since the offline message's text is taken
in by the view model (the row said 12).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:43:51 +03:00
faumarayandClaude Sonnet 5.5 f8447ec9f8 Test that a picture of pixels reaches Slint as wide, as high and in place
The length check of the pixels is in `Pixels::new`, but the Rgba arm of
`convert::image` had no test: a picture drawn with its width and height
swapped passed all 22 tests of voelin-ui. A 3 by 2 picture whose pixels
hold their own column and row is converted, and its Slint size and four of
its pixels are read back (the swap fails the test).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:43:20 +03:00
faumarayandClaude Sonnet 5.5 56ce2cb739 Pin the notice kind names and the settings page title again
The social split deleted `notice_names_and_setting_pages` from voelin-ui
without moving it. The Slint side picks the bell's colours and icons by the
kind names ("poke", "mention", "event", "friend") and nothing but the one
"mention" assertion and the Keybinds search pinned them. The names of all
five kinds are tested next to `NoticeKind`, and the "Voice & Video" title
next to the list it is in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:39:49 +03:00
faumarayandClaude Sonnet 5.5 91d70702f3 Take the text of an offline message in before the redraw, not after it
The social split left the offline message's state change in the front end's
`rest` events, which `perform` handled after it drew the conversations:
`refresh_chats` drew the open message while `dm.mail` was still empty and
the inbox row was still unread, and nothing drew the page again. Before the
split `social_event` wrote both ahead of `social_refresh`.

`Event::OfflineMessage` is now taken in by `social::logic::event` like the
other offline events: the text is `Social::mail`, the inbox row turns read,
and a failure is the status line. `events::apply` no longer parks the event
in `rest`, so a tape test in `voelin-ui-vm` sees it (the mutation that
parks it fails the test). `perform` also handles what is left in `rest`
(a setting, the studio's stream, the request answers) before it draws, as
every such event ran before the redraw ahead of the split.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:33:29 +03:00
faumarayandClaude Sonnet 5.5 172bee5337 Say what the tests print when they skip only as precisely as the code does
The table of docs/ci.md quoted one skip message per row, but the tests print
several wordings per piece (for the H.264 encoder: "skipped: no H.264
encoder", "skipped: needs VP8 and H.264 encoders", "no h264_vaapi or H.264
decoder, skipped"; for FFmpeg: "FFmpeg not installed, skipped", "no FFmpeg with
libavformat, skipped", ...), and some live tests return without printing. The
rows now say a skipped line naming the piece, and keep an exact string only
where the code has exactly that one.

The row on DNS and the internet sat under a column headed "The image has no",
which read as if the job had no network; it has, for apt, rustup and crates.
The column is now headed "A test cannot count on" and the row says the tests
use no DNS or internet and names the #[ignore]d ones that would.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:11:42 +03:00
faumarayandClaude Sonnet 5.5 ac6937289d Name in docs/ci.md the job image the runner really registers
Runner setup told to register ubuntu-24.04:docker://ghcr.io/catthehacker/
ubuntu:act-24.04 while the new section on the tests says the test step runs in
docker.gitea.com/runner-images:ubuntu-24.04. The runner of this machine
(gitea-runner-performance, register script of its NixOS unit) is registered
with ubuntu-24.04:docker://docker.gitea.com/runner-images:ubuntu-24.04, and
`docker ps` shows its CI tasks running that image, so the label line was the
stale one. It now names that image, the network list names its registry in
place of GHCR, and the tests section says it is the image of the
ubuntu-24.04 label.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:11:03 +03:00
faumarayandClaude Sonnet 5.5 cd08498092 Make the documented image run start cargo, and its VoelinProtocol mirror work
The docker run that docs/ci.md prints for the tests under the job image hung
for ever once the apt and rustup setup was done: bash -c execs its last
command, so xvfb-run became the container's process 1 and never started cargo
(probed: with the runner image and xvfb installed, xvfb-run -a as process 1
stays up with an idle Xvfb, and the same command under --init finishes). The
command now has --init. The runner is not affected: it starts its steps with
docker exec.

The hint for the private dependency is part of the block now, so the block
runs as printed: the bare clone is mounted at /protocol.git (it was never
mounted into the container before) and `git config` runs with -C /, because a
git worktree's .git file points outside the /src mount and git config in /src
exits 128 with "gitfile does not point to a valid repository".

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:11:03 +03:00
faumarayandClaude Fable 5.1 6e0df5178e Merge phase4/seam-followups: the gate's identity-text minor, the H9 edge list, five flaky tests
CI / Linux checks (push) Failing after 27m35s
An unreadable TeamSpeak identity is refused without its key in the text (the
classification of from_blob shared as from_json); VoiceOptions fields and
Backends::set_account documented; docs/session-seam.md 17.6 holds the complete
engine/ts edge list for the second half; improve_level, the contacts database
reopen, the banner log subscriber, the two localhost tests and the portal proxy
test made deterministic. Sonnet review accepted; its five minors (two more
DatabaseBusy/port races in tests/gateway.rs, a 1-in-130 voice handshake flake,
the from_json doc, the proxy wrapper's success check) go to the next
test-hygiene round.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-24 17:32:58 +03:00
faumarayandClaude Sonnet 5.5 8541d7c9e5 Document what the Linux job image lacks and how the tests cope
The test step runs as root in docker.gitea.com/runner-images:ubuntu-24.04
with only the apt packages of the system-dependencies action. docs/ci.md now
says how to run the CI's test command in that image with --no-fail-fast, and
lists what the image has no (a regular user, sound card, PipeWire daemons, a
session bus, GPU and VA-API, FFmpeg, an H.264 encoder, Wayland, a browser, the
TeamSpeak dev servers) with what each kind of test does about it. It also
records that two voelin-core tests fail on a machine whose ::1 swallows
connections, whatever the change under test is.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 17:16:19 +03:00
faumarayandClaude Sonnet 5.5 2c9c739732 Make an_unwritable_path_fails_at_once hold for root
The test started a recording at /nonexistent-root-dir/x/clip.webm and expected
an error. Recorder::start creates the missing parent directories, which a
regular user cannot do below / but root can: under the runner image (Gitea
run 1091, docker.gitea.com/runner-images:ubuntu-24.04, root) the call
succeeded, created /nonexistent-root-dir and left a file behind.

The test now builds its unwritable paths in a temporary directory from things
that fail for every user: a path below a regular file (ENOTDIR, so
create_dir_all fails) and a path that names an existing directory (EISDIR, so
File::create fails). The unknown-container name is checked in the same place
and also asserts that no file was created. Reproduced in the runner image as
root with the old test failing and the new one passing.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 16:42:41 +03:00
faumarayandClaude Fable 5.1 c91a3b719d Merge phase5/media-codec-test: peer_config_follows_codecs on a machine without an H.264 encoder
CI / Linux checks (push) Failing after 25m38s
The first CI run that could fetch the private dependency failed on this test
under the runner image. It now states preferred_codec's contract on any
machine. Reproduced and shown green inside docker.gitea.com/runner-images:ubuntu-24.04.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-24 15:34:27 +03:00
faumarayandClaude Sonnet 5.5 81def06144 Test that voice_options hands the version spec on as the spec
After the seam merge VoiceOptions::client_version is the spec string that the
engine resolves when it connects (docs/session-seam.md 17.3), and voice_options
only resolves it eagerly to tell the user at once. The test pins both: no spec
leaves None, a spec that resolves is passed on as written, one that does not
is refused with the message.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:29:30 +03:00
faumarayandClaude Sonnet 5.5 f374f5797b Record the round after the gate in the design of the session seam
17.8: the commits of the follow-up round, the five flaky tests (all fixed, how
each was reproduced and what the evidence is, including the two that are
rewrites and the one that was never seen again), and what ran on both
toolchains: fmt and clippy per commit, the lib suite ten times in a row on
each with no exclusions, the integration tests, cargo doc, the workspace check
with the environment that made it build, and the smoke script before and after
on fresh stacks. The status line names the round.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:26:46 +03:00
faumarayandClaude Sonnet 5.5 6329e56780 Make peer_config_follows_codecs state what preferred_codec promises on any machine
The test compared preferred_codec(&all, Some(H264)).is_some() with whether an
H.264 encoder exists. preferred_codec falls back to another encodable codec
when the configured one cannot be encoded, so is_some() is true on every
machine with any encoder and the assertion held only where an H.264 encoder
exists. The first CI run that could fetch the private dependency (Gitea run
1089, runner image without an H.264 encoder) failed on it; a developer machine
with FFmpeg or a GPU passed.

The test now says the contract: a configured H.264 is the result when
all.encoder_codecs() has it, and otherwise the result equals the automatic
choice, preferred_codec(&all, None). The built-in codecs (no OpenH264) pin both
branches on every machine: VP9 configured gives VP9, H.264 configured gives
the automatic choice, VP8.

The H.264-in-software offer assertion assumed VP8 second after H.264
(offer_codecs(&all, H264)[..2]). A hardware AV1 or VP9 encoder ranks before
libvpx's VP8, so a machine with software H.264 and one of them fails it (the
dev machine does with the named av1_vaapi encoder and hardware off). It now
says H.264 leads exactly the codecs the VP8-led offer has.

Checked at 9714dc2 in docker.gitea.com/runner-images:ubuntu-24.04 with the
apt packages of .github/actions/system-deps and rustup 1.94: the test failed
at media.rs:3426 and passes now; the voelin-core lib tests there were 268
passed, 1 failed, 2 ignored before and are 269 passed, 0 failed, 2 ignored
after.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:06:54 +03:00
faumarayandClaude Sonnet 5.5 d677273f06 Bring docs/ui.md up to date with the splits and what is left of step 2
The numbers of the .set_ table are counted with the command the text names, all
on one base (the files before this round's splits, ad20979) where the text
mixed the counts before and after the event move (chat.rs 38 or 33, servers.rs
37 or 32), and now include the social, dev and host files that the text left
out. Plan section 6 step 2 is stated as done, with what is left for the GPUI
step: the rest of app.rs, the small controllers, and the events page of
events.rs, which is no dispatch (the dispatch moved to voelin_ui_vm::events).
The two mirror modules' field docs are said to be exempted by the crate's lint
(349 fields), not documented. CHANGELOG.md's entry for voelin-ui-vm names the
areas that moved.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:01:01 +03:00
faumarayandClaude Sonnet 5.5 8aa5d6729b Write the user's gateway requests as a list, not an or-pattern
rustfmt 1.94 (the pinned toolchain) and the nightly rustfmt lay out the long
or-pattern of failure_text differently, so voelin-ui-vm, clean on both when it
was merged, was not any more. A list of the eleven requests is laid out the
same by both; the requests and the answer are the same.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:01:01 +03:00
Aleksey Selihov 9714dc2226 Merge pull request 'CI and release builds read the private VoelinProtocol repository' (#1) from phase0/ci-private-dependency into main
CI / Linux checks (push) Failing after 22m41s
2026-10-24 11:46:50 +00:00
faumarayandClaude Sonnet 5.5 c35bbb5ba8 Run the portal proxy test on a bus of its own, or say it checked nothing
voelin-platform's tests/proxy.rs says to run it under dbus-run-session, and
without DBUS_SESSION_BUS_ADDRESS it returned at once. With one set it ran on
the desktop's bus and failed at "the portal leaves the bus": the test has its
stand-in release org.freedesktop.portal.Desktop, and the first call afterwards
starts the real xdg-desktop-portal, which the bus can start by name; it
answers instead of the "missing" the test expects for a minute. A private bus
from plain dbus-run-session starts it the same way (the test failed the same
three times under it here), so the documented way did not work on a desktop
that has the portal installed.

The test now runs itself again under dbus-run-session with a bus configuration
of its own, a session bus without service directories, so that nothing on it
can be started by name. Without dbus-run-session, or when the bus does not
come up, it says "skipped, nothing was checked" with the reason and passes;
when the test ran on its bus and failed, it fails with the output. The
stand-in and the assertions are the ones that were there.

On the bus with the default services the same inner test still fails as
before (checked by hand), and on the bus of its own it passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:32:53 +03:00
faumarayandClaude Sonnet 5.5 a90bb70ee6 Let the test SOCKS proxy dial localhost at the IPv4 loopback
web::tests::pictures_go_through_the_proxy_named_for_each_hop downloads
http://localhost:<port>/banner through a SOCKS5h proxy of its own and asserts
that the proxy was given the name "localhost:<port>". The test proxy then
connected to that name through the system's resolver, and on a machine that
resolves localhost to ::1 only (this one) the server, which listens on
127.0.0.1, was not reachable: the download timed out after 20 s.

The proxy still reports the name it was given, as SOCKS5h says, and dials
localhost at 127.0.0.1 like the server it stands in front of.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:29:29 +03:00
faumarayandClaude Sonnet 5.5 e614a1c3f1 Probe localhost at the IPv4 loopback in the discovery test
discover::tests::without_records_the_gateway_itself_is_asked starts a server on
127.0.0.1 and has the discovery ask the gateway at "127.0.0.1",
"127.0.0.1:9987" and "localhost". The probe connected to the name through the
system's resolver, and on a machine that resolves localhost to ::1 only (this
one) nothing listens there: the third address found no gateway.

The test helper that makes the probe, probing, connects to localhost at
127.0.0.1 instead. What the test checks is that the gateway is asked at the
name localhost, not what the resolver makes of it, so it no longer depends on
the resolver.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:29:29 +03:00
faumarayandClaude Sonnet 5.5 4be37e1fd1 Record log lines in the tests through one subscriber for the whole process
web::tests::info_lines read the lines a closure logs with
tracing::subscriber::with_default. While that scoped subscriber is the only
one alive, tracing-core registers a callsite that another thread meets first
against that thread's own default, which is none, and the callsite stays
disabled for every thread. session::banner_tests::
a_failing_banner_is_logged_once_with_its_address flaked this way (lines == [],
once in a full run of slice 3); several other tests reach the same
"banner not downloaded" callsite through image_finished while it runs. The old
helper failed 1 of 300 runs of banner_tests, and always on a single thread
that meets the callsite first (the new test below).

info_lines now installs a recording subscriber as the global default the first
time it is called, and each call records into a buffer of its own thread, so
every callsite is registered against the same subscriber and no scoped
dispatcher is created or dropped while tests run. The result is the same: the
lines `f` logged at info and above on its thread. The new test
info_lines_see_a_callsite_another_thread_met_first fails with the old helper
(lines == []) and passes with the new one; the new helper failed 0 of 600
runs of the same tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:28:07 +03:00
faumarayandClaude Sonnet 5.5 0d67dd7433 Reopen the contacts database after the first engine has closed it
voice_features::contacts_are_kept_in_the_database dropped its engine and opened
the same database again at once. Dropping an Engine does not close the history
database: the engine task ends later, the history writer is joined there, and
closing the connection checkpoints the write-ahead log under an exclusive lock
with fsyncs. The second History::open waits for that lock only for the 5 s busy
timeout, and fails with DatabaseBusy when a loaded disk makes the close take
longer (seen as 3 failures in 8 runs, 10 in 24 with eight runs at a time).

The test now waits until the -wal file is gone, which SQLite does when the last
connection closes, before it reopens: the restart of a process, as the test
means it. With every fsync of the test process delayed by 6 s (strace -e
inject=fsync,fdatasync:delay_enter=6000000) the old test failed every time at
the reopen with DatabaseBusy, and the new one passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:24:30 +03:00
faumarayandClaude Fable 5.1 b8ba43f0c9 Check each OpenSSH tool on its own and stop only an agent this job started
CI / Linux checks (pull_request) Failing after 21m18s
command -v with two names returns 0 when one resolves, so the guards were
weaker than they read. The release workflow's final step killed whatever agent
SSH_AGENT_PID named; it now needs the marker the start step writes after it
succeeded. Two documentation lines re-wrapped (the review's three minors).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-24 14:24:19 +03:00
faumarayandClaude Sonnet 5.5 9254e08daa Ask improve_level for more than the test identity already has
ts::identity::tests::improve_level_keeps_the_key made its identity with
Identity::create(), which stops at the first counter whose level is 8 or more,
and asked improve_level for 13. About one identity in 32 has 13 or more
already, and improve_level then returns it as it is, so the assertion that the
counter grew failed: 8 failures in 300 runs of the single test before this
change, 0 in 300 after.

The target is now three levels above what the identity has, so the search
always runs. The assertions on the level, the callbacks and the counter use
that target.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:21:22 +03:00
faumarayandClaude Sonnet 5.5 96ff0e0028 Write down the complete edge list between the engine and src/ts for H9
17.6 of docs/session-seam.md named two engine-to-ts edges; the Opus gate of the
merge found the rest. Each line was checked with rg and cargo tree:

- the engine into src/ts: Backends::default and register_teamspeak, the uid and
  id rule of the projection, gateway.rs from_blob/to_blob (H5), the public
  voelin_core::ts paths and their users in voelinctl and the UI crates, the
  API docs that link into ts, and the test-only edges;
- what a TeamSpeak connector in another crate cannot do with
  Backends::register (no LocalCtx, no StreamPort): streams across the crate
  boundary need H2 or a public extension trait;
- src/ts into engine-private items (link, stream, files, offline, the crate
  root, settings), with the conclusion that the "by git tag" step needs H1 and
  H2 or a shared vocabulary crate, else voelin-core and voelin-gateway-ts form
  a cycle;
- what else keeps tsclientlib and tsproto in voelin-core's tree, so that the
  exit check needs H5 too, and voelin-store, voelin-stream and
  voelin-gateway-proto lose the dependency;
- the split of stream.rs;
- the same key-quoting leak in voelin-store's Store::identity, not closed.

The H9 row of 11.2 points to the list and no longer says the exit check holds
after H1-H3 alone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:20:02 +03:00
faumarayandClaude Sonnet 5.5 84f4a4835f Make cargo doc of voelin-ui-vm pass with -D warnings
RUSTDOCFLAGS=-D warnings failed with twelve errors, none of them new
behaviour: public docs linking to the private server_lines and PRESETS
(plain code spans now), Event::... links in state.rs that name voelin_core's
Event without importing it (voelin_core::Event::..), an unclosed <id> tag in
a bridge field comment (a code span), and three explicit link targets that
the label already resolves to.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:19:17 +03:00
faumarayandClaude Sonnet 5.5 371e4d77c8 Merge main (c60acf9, the session seam) into phase5/ui-vm-2
The engine of main runs on voelin_proto::link::Session; this branch had split
the Slint controllers into <area>/logic.rs (voelin-ui-vm) and <area>/bind.rs
(voelin-ui) before that merge and was never reviewed. One conflict, the one
the Opus gate of the seam merge predicted:

- crates/voelin-ui/src/servers.rs (modify/delete): this branch had split the
  file into servers/bind.rs and voelin-ui-vm's servers/logic.rs; main had
  changed the file for the seam (docs/session-seam.md 17.3). The file stays
  deleted and the changes of main are made where the code now is:
  servers/bind.rs sends ts::identity::to_blob(&identity) in ConnectVoice and in
  both ObserveGateway sends, builds voelin_core::QueryLogin {address,
  allowlisted: false} with voelin_core::QueryTransport for ObserveQuery, names
  ts::identity::DEFAULT_NICKNAME, and its tests import ts::identity::{Found,
  LaunchImport}; servers/logic.rs imports ts::identity::LaunchImport (and
  links ts::identity::import_new), and voice_options keeps the eager
  ts::versions::resolve for the message and assigns Some(spec.clone()) to
  VoiceOptions::client_version (the engine resolves the spec when it
  connects).

Cargo.lock merged without a conflict and differs from main's only by the edge
of voelin-ui-vm to roxmltree, which this branch added (d9de95b).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:18:43 +03:00
faumarayandClaude Sonnet 5.5 563482db72 Document VoiceOptions.nickname and server_password; correct Backends::set_account
Both fields were carried over from ConnectOptions without a doc: what the
nickname is on each kind of server and that an empty one falls back to the
link's nickname parameter; that the server password is Hello.password, falls
back to the link's password parameter and is not the channel's.

Backends::set_account said the connectors use the account (the QUIC
connector's certificate, the TeamSpeak connector's myTS ID proof). No connector
reads ConnectParams.account yet: the TeamSpeak one is given the myTeamSpeak
account through TsConnector's setters, and the QUIC connector does not exist.
The doc says so and names H4 as the step that moves the proof to this hook.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:17:16 +03:00
faumarayandClaude Sonnet 5.5 a856f90c6b Refuse an unreadable TeamSpeak identity without its key in the text
The Opus gate of the merge found that ts_session::inner_options put the raw
serde_json error into the refusal of an identity it cannot read, and tsproto's
key visitor reports a key that does not import as invalid_value(Unexpected::Str(
key), ..), so the private key string reached LinkEvent::Disconnected(Some(text)),
Event::Error and the UI status line.

The classification ts::identity::from_blob already had (malformed, cut short,
not an identity, unreadable, with line and column, never the value) is now
ts::identity::from_json, which takes the JSON text; from_blob and inner_options
both use it, so the refusal is worded in one place. A credential that is not
UTF-8 is refused as "it is not text".

Tests: identity::tests (a key that lost its last two characters: the JSON
reader's own message quotes it, from_json and from_blob do not; no 8-character
piece of the key), ts_session::tests (inner_options), link::tests (the
LinkEvent::Disconnected text through SessionLink with the real connector) and
session_fake (ConnectVoice through the engine: the Disconnected state, the
Error event and every event after it). All three connector-side tests fail with
the serde_json text put back.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:16:06 +03:00
faumarayandClaude Fable 5.1 c60acf9de0 Merge phase4/session-seam: the engine on voelin_proto::link::Session (plan Phase 4 step 7, first half)
CI / Linux checks (push) Failing after 49s
Slices 1 to 3 of docs/session-seam.md plus the merge of main ad20979 and the
minors round: SessionLink and the Backends registry put the engine on
Arc<dyn Session>; the TeamSpeak implementation is a Session under
voelin_core::ts; ServerLink, TsLink, LinkCmd, LinkEvent, LinkCtx and Remote are
private; VoiceOptions, QueryLogin and IdentityBlob are the public API changes.
Sonnet review accepted each slice; the Opus gate accepted the branch with one
minor (the TeamSpeak connector's refusal of an unreadable identity puts the
serde_json error, and so the key text, into the message: a follow-up).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-24 13:56:17 +03:00
faumarayandClaude Sonnet 5.5 e5956e40e9 Set CARGO_NET_GIT_FETCH_WITH_CLI in the CI workflow's own env as well
The checks action exports it through GITHUB_ENV, which depends on the runner
handing a composite action's environment file on to the later steps of the
job. If a runner did not, Cargo would silently go back to its built-in git
client, which cannot use the deploy key's IdentityFile, and fail with a
confusing authentication error in the first cargo command. The workflow-level
env does not depend on that, so both are set; the access check step still
exercises the key, the host key and the ssh configuration through git.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 13:45:56 +03:00
faumarayandClaude Sonnet 5.5 6e774873bf Document how CI and the release builds read the private VoelinProtocol repository
docs/ci.md gets a "VoelinProtocol access" section: why every cargo command
needs the access (Cargo resolves the whole workspace, so the gateway image
needs it too), the deploy key and the repository secret
VOELIN_PROTOCOL_DEPLOY_KEY, what the checks action, the release workflow and
the Dockerfiles do with it, why Cargo is told to use the system git, the
committed host key line with its fingerprint and the two commands that
re-check it, the effect on fork pull requests, and what each failure message
means. The runner setup no longer says that a fresh checkout does not build
there. docs/building.md says that the Docker builds need an ssh-agent with a
key that can read VoelinProtocol (--ssh default) and summarises the CI setup;
the plain docker build commands in it and in docs/gateway-admin.md gain
--ssh default, without which they would now stop at the cargo step.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 13:44:44 +03:00
faumarayandClaude Sonnet 5.5 b89116c0f4 Let the Docker builds fetch the private VoelinProtocol repository with an ssh-agent
Every cargo command in the images (linux, windows, android and the gateway
image) failed for the same reason as the CI job: Cargo resolves the whole
workspace, which includes the git dependency voelin-identity on the private
Voelin/VoelinProtocol repository, and the images had no SSH access to it. The
crates that depend on voelin-identity are voelin-store and, through it,
voelin-core, voelin-ui, voelin-ui-vm, voelin-android and voelinctl; the
gateway crate does not, but `cargo build -p voelin-gateway` fails without
access too (checked with an empty CARGO_HOME), so its Dockerfile needs the
same.

Each cargo RUN gets --mount=type=ssh,required=true: the build is handed the
caller's ssh-agent (docker build --ssh default), the key stays in the agent
and never reaches a layer or the build context, and a build without --ssh
fails at that step with "unset ssh forward key default". The build stage
copies the host key committed in .gitea/known_hosts to
/etc/ssh/ssh_known_hosts and sets CARGO_NET_GIT_FETCH_WITH_CLI=true, so that
Cargo uses the system git and ssh. The toolchain stages install git and
openssh-client where they were missing; the gateway Dockerfile gets the
syntax directive the others already have. scripts/docker-build.sh passes
--ssh default and stops early, with a message, when ssh-add -l shows no agent
or no key.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 13:43:12 +03:00
faumarayandClaude Sonnet 5.5 437b508047 Start an ssh-agent with the VoelinProtocol deploy key in the release workflow
The Docker builds run cargo, which has to fetch the private VoelinProtocol
repository over SSH. After checkout the workflow now loads the deploy key
(secret VOELIN_PROTOCOL_DEPLOY_KEY) into a new ssh-agent through stdin, so
the key is never written to the runner's disk and never reaches an image
layer, and exports SSH_AUTH_SOCK and SSH_AGENT_PID for the later steps. The
agent is started with a nine hour key lifetime and stopped by a last step
that runs even after a failure, because the release runner is a persistent
host. The gateway image, which is built with a plain docker build and not
through scripts/docker-build.sh, gets --ssh default; the Dockerfiles use it
in the next commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 13:34:08 +03:00
faumarayandClaude Sonnet 5.5 8b6dcbf442 Give the Linux checks read access to the private VoelinProtocol repository
The workspace depends on voelin-identity from Voelin/VoelinProtocol over SSH,
and the job container had no key and no known_hosts, so the first cargo
command failed with "unknown SSH host key" (runs 1037 and 1050).

The checks action takes the private half of a read-only deploy key as the
input protocol-deploy-key (secrets are not visible inside a composite action,
so ci.yml passes ${{ secrets.VOELIN_PROTOCOL_DEPLOY_KEY }}). Its first step
fails at once, with a message that names the secret, when the input is empty
or not a private key; it writes the key to ~/.ssh/voelin_protocol (0600),
appends the host key line committed in .gitea/known_hosts, writes a Host
block for git.faumaray.com (User gitea, IdentityFile, IdentitiesOnly,
StrictHostKeyChecking yes) and sets CARGO_NET_GIT_FETCH_WITH_CLI=true and
GIT_SSH_COMMAND for the rest of the job: Cargo's built-in git client cannot
use an IdentityFile, the system git and ssh can. The key reaches the step
through the environment only, is never echoed, and only the public
fingerprint is printed. A second step, after the system packages, runs
git ls-remote against VoelinProtocol, so a wrong key or a changed host key
fails there and not minutes later inside a cargo command.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 13:34:08 +03:00
faumarayandClaude Sonnet 5.5 5afa5a9740 Commit the SSH host key of git.faumaray.com for the CI and release builds
Cargo reaches the private VoelinProtocol repository over SSH and, in a fresh
job container or image, has no known_hosts: every cargo command failed with
"unknown SSH host key" (runs 1037 and 1050). The server (Gitea's built-in SSH,
SSH-2.0-Go) offers an RSA host key only; the line is committed here, after
checking its fingerprint (SHA256:fugBYnqAnqmTLsGpafVgQF9gPQzJqps7uHvs48blg2A)
against ssh-keyscan and Cargo's own report, so that jobs trust the reviewed
key instead of fetching one while they run. The next commits use it in the
checks action, the release workflow and the Dockerfiles.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 13:28:02 +03:00
faumarayandClaude Fable 5.1 37f8fe9bc1 Say what the transfer commands did before f1df886: a notice and a hanging report, not a dropped connection
The review of the merge-and-minors round read ts/voice.rs: the Input::Cmd arm
sends a command's error as LinkEvent::Error and keeps the connection, so the
old anyhow::bail! never ended the TeamSpeak session. The 17.7 row said it did.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-24 12:57:30 +03:00
faumarayandClaude Sonnet 5.5 d5d85b3f3d Record the round after the review of slice 3 in the design of the session seam
17.7: the merge of main (ad20979), what it conflicted on and what it needed to
compile, the four minors of the review with their commits, and what ran on the
merged tree: fmt and clippy per commit, tests on both toolchains, the lib
suite ten times in a row, cargo doc, the acceptance of section 10 (including
the rustdoc JSON walk), the notices check, and the smoke script and the live
binaries before and after. The status line follows.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 11:43:48 +03:00
faumarayandClaude Sonnet 5.5 f1df88690b Fail a transfer the TeamSpeak link is given, not its connection
ts::voice::Voice::command answered LinkCmd::Download, Upload and CancelTransfer
with anyhow::bail!, which ends the whole TeamSpeak connection: chat, voice,
presence and the stream task with it. SessionLink copies the bytes of a
transfer itself and never sends them, but a command that does arrive is that
transfer's failure, not the connection's. Download and Upload answer their
report with TransferState::Failed and the connection goes on; CancelTransfer
has no report and nothing to cancel, so it is logged at debug.

A unit test gives an unconnected Voice the three commands: each returns Ok, the
two reports see Failed, nothing is pending.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 11:00:57 +03:00
faumarayandClaude Sonnet 5.5 76a884a779 Correct the paths and statements slice 3 left stale
- docs/session-seam.md 4.1: the TsConnector owns the myTeamSpeak account since
  a451f02; it is not registered "with the engine's watches".
- docs/session-seam.md 16.1: the live tests are src/ts/ts_session/live_tests.rs.
- docs/session-seam.md section 10: the acceptance rg is given as it runs from
  the repository root (--glob '!**/ts/**'); from crates/voelin-core/src the
  first glob is '!ts/**'.
- ts/voice.rs module documentation: the type that runs it is ts_link::TsLink
  (crate::TsLink is gone).
- link/tests.rs: ts/ts_session/driver.rs.
- voelin-store (IdentityOrigin::Imported, a one-word path) and
  docs/research/ui-review.md: voelin_core::ts::identity, ts/voice.rs.
- docs/audio.md: LinkCmd::Audio and LinkEvent::Audio are in link/mod.rs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 11:00:17 +03:00
faumarayandClaude Sonnet 5.5 f0d20cc02f Document QueryLogin.transport
The one public field of QueryLogin without a doc comment.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 10:58:50 +03:00
faumarayandClaude Sonnet 5.5 87926e9b59 Refuse a TeamSpeak identity that holds no JSON
link::connect::credential sent a TeamSpeak IdentityBlob with an empty json as
an empty Credential::Foreign blob, which is what the TeamSpeak connector reads
as "make an identity up" (identity: None). An identity that holds nothing is no
identity: it is refused with SessionError::Protocol, as the Voelin branch
refuses a key that cannot be read, before any connector is asked. The comment
of ts::identity::to_blob ("a blob with no JSON is refused when it is used")
holds on both paths now: the gateway's from_blob already refused it.

Two tests: connect_params refuses "" and white space and still sends none as
the empty blob; an engine on the fake host answers ConnectVoice with the reason
and the connector is never asked and makes no session.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 10:58:34 +03:00
faumarayandClaude Sonnet 5.5 e13d401b9c Merge main (ad20979) into phase4/session-seam
Main brings the merge of phase5/ui-vm: the toolkit-free crates/voelin-ui-vm
crate and the logic/bind split of crates/voelin-ui. Conflicts, and what each
resolution keeps:

- crates/voelin-ui/src/settings_pages.rs: main deleted it (it is
  settings_pages/{mod,bind}.rs and voelin-ui-vm's settings_pages/logic.rs
  now), this branch had changed its voelin_core::identity paths. Deleted; the
  paths are voelin_core::ts::identity:: in bind.rs and in logic.rs.
- crates/voelin-ui/src/identities.rs: the module comment names
  voelin_core::ts::identity::import_new (this branch) and settings_pages/
  (main).
- docs/architecture.md: the voelin-core row of this branch with the
  voelin-ui-vm and voelin-ui rows of main.

Not conflicts, but needed to compile: voelin-ui-vm named the in-tree
voelin-model by path, which this branch moved to the protocol repository
(workspace dependency), and imported voelin_core::identity::Found, which is
voelin_core::ts::identity::Found. Cargo.lock merged without a conflict and
resolves with --locked; THIRD_PARTY_NOTICES.md is up to date
(scripts/notices.sh --check).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 10:32:05 +03:00
faumarayandClaude Sonnet 5.5 6a08147f93 Record slice 3 in the design of the session seam
Section 17: what was done, commit by commit; where the code differs from the
text of section 10 (QueryLogin.allowlisted, the ServerLink trait moved rather
than made private, Backends::register_teamspeak, files::upload deleted, the
directory the acceptance rg runs from); the API changes that phase5/ui-vm-2
has to absorb; the acceptance list; what ran against the baseline (fmt,
clippy per commit, tests on both toolchains, cargo doc, notices, the smoke
script and the live tests before and after); the follow-ups. The status line,
4.1, 4.8, 9, 11.2 (H9's two edges into src/ts) and 16.1 follow.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 08:28:14 +03:00
faumarayandClaude Sonnet 5.5 d0092e467a Describe the session seam in the architecture document
"The server link" is "The session seam": the registry, SessionLink and the
vocabulary it shares with session.rs (crate-private now), what a session asks
for in VoiceOptions, the TeamSpeak module (voelin_core::ts), StreamPort, the
tests, and what is still TeamSpeak-shaped. The crate table row of voelin-core
follows.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 07:27:49 +03:00
faumarayandClaude Sonnet 5.5 f63d459865 Keep the crate's documentation free of links that do not resolve
cargo doc with warnings denied failed on efacb41 and on main alike, with eight
errors (six with the media features on): the cache's module documentation
linked to private items, and the crate documentation to modules and a type
that exist only with the media features. They are plain code spans now, so
that RUSTDOCFLAGS='-D warnings' cargo doc --no-deps -p voelin-core passes,
with and without --features media-desktop.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 07:24:37 +03:00
faumarayandClaude Sonnet 5.5 ca34f84610 Let a query login say that its address is on the server's allowlist
The engine's own query connections used the query crate's default line
options, which keep a client-side limit of nine commands in three seconds. The
live tests passed voelin_query::Connect with that limit off, because the
development servers allowlist their clients, and with the limit on the
channel relay of ts3_engine and ts6_engine did not connect within the two
seconds the test waits before it speaks. QueryLogin gets the one bit the
tests had: allowlisted, off for the application (which cannot know), on for
the tests, and the UI's login says false, as it always effectively did.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 07:23:46 +03:00
faumarayandClaude Sonnet 5.5 d70a3582f2 Take the transfers the engine does itself out of the TeamSpeak connection
voice.rs handled Download, Upload and CancelTransfer with a copying task per
transfer, a progress cadence, the picture limits and a cancel table; none of
it is reachable since SessionLink copies the bytes itself over the
connections OpenRead and OpenWrite open (the picture limits and the
negotiation deadline live there, tested in link/tests.rs). The connection
keeps the two connection jobs and refuses the three commands in words;
files::upload and its close wait go with it (SessionLink uses upload_to, and
the TCP test of the upload runs through that), and the test of the picture
download time moves to the cache, which owns the function.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 07:07:52 +03:00
faumarayandClaude Sonnet 5.5 1edc52ce74 Make the engine's link vocabulary private and the options neutral
VoiceOptions is a struct of its own, no longer an alias of the TeamSpeak
link's options: identity is an IdentityBlob and client_version a spec for
ts::versions::resolve, which rides the address as the link parameter
client_version and which the TeamSpeak connector resolves (a spec it refuses
fails the connect in words). SessionLink builds the connect parameters
(link/connect.rs: the bookmark's link, the hello, the credential of the
identity's kind, now also a Voelin key's signer) and session.rs holds it
directly: the ServerLink trait between them was redundant. The trait lives
on in the TeamSpeak module (ts/ts_link.rs, with the TeamSpeak-typed
ConnectOptions) for TsLink and the in-memory link of the tests.

ServerLink, TsLink, LinkCtx, LinkCmd, LinkEvent and Remote are crate-private,
Engine::start_with_link is gone, and the three tests that needed the inner
link (tests/link_fake.rs) are unit tests of link/ now. The rg over the crate
for tsclientlib, tsproto and voelin_query, outside ts/ and the three files
that use them privately (gateway.rs, query.rs, stream.rs), is empty. The UI
and voelinctl get compile fixes: the identity blob and the spec string.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 06:59:44 +03:00
faumarayandClaude Sonnet 5.5 be84874a09 Take the gateway's identity as a blob and the query login as the engine's own type
Command::ObserveGateway.identity is a Box<IdentityBlob> (a TeamSpeak
identity as the key store keeps it; voelin_core::ts::identity::to_blob and
from_blob convert) and gateway::connect takes the blob too; gateway.rs reads
it itself, and one it cannot read ends the observation with its reason
instead of reaching the gateway. Command::ObserveQuery.connect is a
QueryLogin (transport, address, user, secret, server port and id) that
query.rs turns into voelin_query::Connect with the query crate's own line
options, which is what the UI always passed. voelin_core re-exports
IdentityBlob; voelin-identity is a dependency of voelin-core now, so
Cargo.lock gains that edge (the crate was in the graph already, and no
third-party package is added: THIRD_PARTY_NOTICES.md is unchanged).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 06:29:50 +03:00
faumarayandClaude Sonnet 5.5 a451f027f3 Give the myTeamSpeak account to the TeamSpeak connector, not to the engine
Command::SetMytsIdentity and SetMytsData are gone (nothing sent them): the
account's proof and what servers are shown of it belong to TeamSpeak, and the
engine only forwarded two watch channels through every session to the link's
context. TsConnector is public now, with set_myts_identity and set_myts_data;
it owns the senders (shared by its clones through its TsLink) and each
connection holds them for as long as it runs, so a session outlives its
connector as it outlived the engine's loop. Backends::register_teamspeak
takes a connector whose clone the application keeps, and Backends::default
registers one of its own. LinkCtx, LocalCtx, SessionHandle and Session lose
the watches, and the test of the standalone context's senders is a test of
the account's: a connection keeps it open.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 06:17:16 +03:00
faumarayandClaude Sonnet 5.5 029b8464b7 Move the TeamSpeak implementation into src/ts
ts_link.rs, voice.rs, book.rs, ts_session/, versions.rs and identity.rs move
under crates/voelin-core/src/ts (git mv, so git log --follow keeps their
history). voelin_core::versions and voelin_core::identity are
voelin_core::ts::versions and voelin_core::ts::identity now; the UI and
voelinctl follow with the new paths. Nothing else changes: the module
declarations, the use paths and the path of Versions.csv are the only
edits to the moved files.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 06:08:10 +03:00
faumarayandClaude Sonnet 5.5 362e2b9da1 Assert the unique ids and the server's uid in the presence test
presence_follows_the_host_until_it_ends showed the clients' names and
channels but not what the engine keys contacts and private history by: the
unique id of each client (the base32 of a Voelin user's 32 bytes) and the
server's unique id in ServerDetails.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 05:58:27 +03:00
faumarayandClaude Sonnet 5.5 b92379d01b Name the replaced session and the refused stream in tests of their own
The tail of a_reconnect_finds_the_state_the_first_session_left (a connect
while connected replaces the session) and the end of
commands_reach_the_host_as_requests (a host without streams is not asked
for one) are tests of their own now, so that each name says what is
checked.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 05:56:28 +03:00
faumarayandClaude Sonnet 5.5 dd9140e1ea Check that the conformance suite is known before the cases that do not apply run
cases_that_do_not_apply_fail zips the suite's cases with EXPECTED, so a case
the protocol repository adds would have been left out without a word. It
calls the_suite_is_known first, as the conformance subset does.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 05:55:52 +03:00
faumarayandClaude Sonnet 5.5 efacb41894 Correct the record of a reconnect's replay and of the live module's prerequisite
Section 16 of the design said that after a reconnect to a v1 host the
display is right and only the store is wrong, because Dedup drops the copy
of the event. That holds only for the messages within 4 s of the newest one
seen: Dedup evicts what is older than that relative to the incoming
message, so a replayed older message is shown again as a live Event::Chat
and stored again. Corrected in 4.4, 16.1, 16.4 and F3 (16.5), with the two
ignored tests that pin the display and the store, and in P17 and H10: only
the CHAT-cursor resume cures both, and only within an epoch.

Also: the introduction of section 16 names the two production changes (F1,
F2), not three; the move-back test now sends two messages 10 s apart and
the record says what the single-message version did not prove; the live
module raises the anti-flood limits itself and the record says so and what
ran (a fresh stack before and after, in series and in parallel, and the
smoke script before and after on freshly reset stacks); the toolchains of
the review round, the nightly that replaced 2026-10-19, and the per-commit
checks.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 04:54:16 +03:00
faumarayandClaude Sonnet 5.5 9283191e58 Raise the anti-flood limits of the development servers from the live module
On a freshly started stack the live module failed 8 tests of 12 with
ConnectFailedBanned: a server with its default anti-flood limits bans the
address that connects as often as these tests do, after three or four
connections. scripts/it-smoke.sh sets the limits when it prepares its admin
identity, so the module passed only after the smoke script had run.

The module now raises virtualserver_antiflood_points_needed_ip_block and
..._command_block itself before its first connection, once per server and
run, through the ServerQuery admin login that refused_moves uses, and clears
the bans of an earlier run with bandelall (banclear is not a command of
either server). The command of the module header works on a fresh stack.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 04:13:13 +03:00
faumarayandClaude Sonnet 5.5 81d1de86e1 Show in the tests that a reconnect's replay is shown again, and what the passing ones prove
a_reconnect_finds_the_state_the_first_session_left passed for a narrower
reason than its comment said: the one message seen before the disconnect is
the newest one, so Dedup (which holds the messages up to 4 s older than the
last one it was asked about) still held it and dropped the host's replay.
With two messages more than 4 s apart the replay of the older one reaches the
user as a live Event::Chat, and no test saw it: the ignored test of the
stored rows used the same one-message setup.

- The ignored replay test is now two, over one scenario: two messages 10 s
  apart are seen, the session ends, a third is said while we are away, a
  second session connects. One asserts that only "while away" is shown (it
  sees ["first", "while away"]), the other that the history has each message
  once (it sees every row twice). The comments of the passing reconnect test
  say what it proves: a message inside Dedup's window is not shown again.
- the_chat_of_a_channel_is_resubscribed_when_we_move_back passed without the
  `seen` check of SessionLink for the same reason (the message seen before is
  the newest one Dedup holds). It now sees two messages 10 s apart before it
  moves away and fails with the check disabled ("before" comes again).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 04:13:13 +03:00
faumarayandClaude Sonnet 5.5 2089f7ceba Record slice 2 in the design of the session seam
Section 16: what the tests on the fake host and the TeamSpeak sessions
cover, the verdict of every case of the conformance suite on both
development servers with the reason it was observed to fail or be skipped,
where the code differs from 9.2 and 9.3 (the CHAT re-subscription is a full
sync, a reconnect resumes nothing, the conformance and live tests are
in-crate), the three things the tests found (our own voice played back, a
session made outside an engine ending by itself, a v1 host's replay stored
twice after a reconnect, the last one open), the protocol and second-half
follow-ups, the deliberately broken translation, and what ran.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 02:29:40 +03:00
faumarayandClaude Sonnet 5.5 226933fcdc Run the link conformance subset and the session scenarios on both TeamSpeak servers
ts_session/live_tests.rs (VOELIN_LIVE=1, the development servers) holds the
TeamSpeak Session tests of docs/session-seam.md section 9.3, made through
TsConnector's plain Connector interface:

- the conformance suite of the protocol repository, every case listed with
  what a TeamSpeak session does with it: two pass (welcome_matches_features,
  close_ends_the_session), four are skipped for a feature the session lacks
  (chat.edit, chat chat.history, idempotency), and the rest do not apply;
  a case the suite gains fails until it is listed;
- what the suite cannot reach: an own-channel message answered and pushed to
  the other session and back, the PASSWORD and FULL refusals of a move, a
  poke between two sessions, voice RTP from one slot to the other session's
  media sink (marker, order, an empty payload at the end), and a channel file
  written with write_file and read back from an offset with read_file.

Two tests, ignored by default, run the cases that do not apply and watch each
fail; the reason in the table is what the case did when it was run.

scripts/it-smoke.sh runs the module before its engine stage.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 02:02:39 +03:00
faumarayandClaude Sonnet 5.5 659798e5f9 Keep the account watches of a session made outside an engine open
A TeamSpeak session made through the plain Connector interface (the way the
conformance suite and any client of the seam that is no engine make one) got
a LocalCtx::standalone() whose only job is to hold the senders of the
myTeamSpeak watches. connect_link dropped that context when it returned, the
senders went with it, and the TeamSpeak link ends its connection with
"account source closed" when a watch has no sender: the session died by
itself a moment after it was handed out. The engine's own path was never
affected, its watches belong to the engine.

The context now moves into the driver task and lives as long as the session.

Found by running the link conformance suite against the development servers:
close_ends_the_session passed vacuously and the_backend_can_end_the_session
saw the session end with that text. The new test fails without this change
("the identity watch lost its sender").

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 02:02:07 +03:00
faumarayandClaude Sonnet 5.5 8d07502e1e Drop the media that comes back on our own slot
A session that loops our voice back (the fake host of the protocol
repository does, so that a test sees media move) made the engine hand our
own packets to the audio thread and show us as talking: the slot map holds
every participant of the server, ourselves included. The engine never plays
itself from the network (a sidetone is local), so on_media returns for the
packets of the slot the host gave us. TeamSpeak never sends a client its own
voice, so nothing changes for the servers the engine reaches today.

Found by the fake-host tests; the test failed before this change with
[1, 50] as the talkers heard (us, then alice).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 01:16:51 +03:00
faumarayandClaude Sonnet 5.5 82da64d8d3 Test the voice path and the conformance suite on the fake host
link/fake_tests.rs holds the tests that need what is private to the crate:

- our voice leaves as RTP on the slot the host gave us (sequence, marker on
  the first packet of a spurt, timestamps that advance by the previous
  packet's duration, an end of spurt that is an empty payload sent once, the
  SSRC that is the flow), read from FakeHandle::sent_media;
- the voice of other slots reaches the audio thread: the talker of the slot,
  a whisper sub-flow, stereo Opus as music, the end of a spurt, and what is
  no voice of a known slot (an unknown slot, probes, feedback) dropped;
- the link conformance suite of the protocol repository, 17 cases, run
  against the session Backends::connect hands over: all pass, none skipped.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 01:16:23 +03:00
faumarayandClaude Sonnet 5.5 f9d3f86896 Test the engine on the protocol repository's fake host
tests/session_fake.rs runs the engine through Engine::start_with_backends
with a FakeConnector registered, so a session of the engine is a
voelin_proto::link::Session that no TeamSpeak code made. The host is a
FakeHost filled through put; FakeHandle plays the backend of one session.

The scenarios of link_fake.rs move over (presence until the host ends the
session, commands as v1 requests, a sent message and its echo, the dedup of
a message that comes twice, history across the session), and the ones the
v1 path needs are new: how a session ends and the text the user reads, what
a host refuses and the words it says it in, the chat of a channel
subscribed again when we move back (in full: there is no cursor), closed
scopes, a HostUpdate that changes what the engine asks for, offline messages
as Mail, files through read_file and write_file with a resumed upload, file
operations as FileEntry puts and deletes, the media of a session routed to
the talker of its slot, a reconnect that finds the state the first session
left, and a connect that fails.

link_fake.rs keeps the three tests that need the inner link: the stream
commands (they travel on a port a Session has no part in), the order in
which a reconnect shuts the streams and the old connection down, and a link
that keeps talking after its connection was replaced.

One test is ignored with its reason: a v1 host sends the window of a chat
scope again after a reconnect, and the engine stores the copy (the history
merges copies of different sources only). TeamSpeak never replays, so no
host the engine reaches today meets it; docs/session-seam.md will say so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 01:15:34 +03:00
faumarayandClaude Sonnet 5.5 bfc52e2688 Record the third review round in the design of the session seam
Section 15 lists the seven findings with their fix and test, what the fixes
leave as it was (the move shortcut and the window it keeps), and what ran:
format, clippy, tests and the workspace check on 1.94 and nightly, and the
smoke and live runs against fresh dev servers. The other sections say what
changed: the media and push channels have no order between them (4.2 step 9,
13), the second changed test (5.4), the move rule and the transfer deadline
(3.1), the nameless sender (5.2), the address rules (4.2) and the narrowed
features (4.7).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 23:21:07 +03:00
faumarayandClaude Sonnet 5.5 5df011f08c Count only the refusals that come after the host's update in the features test
The last wait of the test asked for file lists until one was refused locally and
took the first refusal on the bus. The asks made before the HostUpdate reached
SessionLink are refused too while the server's list stands, and their events can
still be unread on the bus, so the wait could end before the update had been
applied. It accepts a refusal of a request made after the update only.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:45:38 +03:00
faumarayandClaude Sonnet 5.5 2bee828022 Refuse the bookmark addresses that a ts3server:// link would change
The engine hands the TeamSpeak side its bookmark as a ts3server:// link and
reads the options back from it. A link cannot say all an address can: a port
that is no u16 (host:99999) was dropped silently and the connection went to the
default port; a bare host with a '?' in it ended there and hid the channel
behind the next '?' that to_url writes; a '/' or '#' ended the host and a '%'
was decoded. The TeamSpeak library had refused every one of those when it
resolved the address.

connect_params returns a Result now. A bookmark whose port is not a number from
1 to 65535 (in host:port and [v6]:port), or whose host is empty, holds a '?',
'#', '/' or '%', white space or a control character, or has an unclosed '[',
fails the connect with a reason that shows the address without its query. The
other normalisations of the round trip (blanks cut, [v6] without a port read
as v6, an empty option is none, the model's rules for an address that is a
link) are listed in docs/session-seam.md.

Tests: the refused and the accepted addresses (the channel survives the round
trip of each accepted one), the empty options, and a connect with a bad port
that ends in Disconnected with the reason before any link is asked.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:30:03 +03:00
faumarayandClaude Sonnet 5.5 b8db1a85f0 Narrow the features of a session by the server's list
docs/session-seam.md 4.7 says features() is narrowed by Server.features, and
Features::narrowed exists for it, but SessionLink took Session::features() as
it was and a HostUpdate replaced the set wholesale. Against a host whose
server offers fewer features, Capabilities and the local Features::require
refusals were too generous.

SessionLink keeps the host's set and the set of the server (the host's,
narrowed by the Server entity's list; an empty list keeps all of them), and
recomputes the second when the SERVER scope changes or syncs and after a
HostUpdate. Capabilities, the local refusals and the presence fix-ups use it.

Test (over the protocol repository's fake host): a server that lists no files
leaves file transfer out of the capabilities and refuses a file list without
asking the host; an empty list brings it back; a HostUpdate that drops files
takes it away again. It fails on the code before this commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:29:36 +03:00
faumarayandClaude Sonnet 5.5 6a2f00a636 Name a poke from a sender with no unique id who is not on the snapshot
Driver::sender made a synthetic user id for such a sender ("client:N") but put
no User entity into LIVE, so SessionLink::signal found no User and the nick of
the poke was empty. The earlier fix covered senders that have a unique id only.

The driver now puts a bare User with the name the link gave and no uid into
LIVE, keyed by the synthetic client id, before it pushes the signal (so it
shows in no presence, and the poke's from_uid stays none). A client id is given
again to whoever connects next, so the user is replaced when the same client
id comes back with another name; a sender with an empty name gets none.

Test: a poke from client 77 with no unique id is named, and named again with
the new name when the client id comes back as somebody else. It fails on the
code before this commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:29:08 +03:00
faumarayandClaude Sonnet 5.5 b0b1c82ddc Leave the deadline of a transfer's negotiation to the caller
LinkSession gave the reply to an OpenRead or OpenWrite 30 seconds, for every
transfer. Only pictures had a deadline before the seam (IMAGE_NEGOTIATION,
which SessionLink still applies to them); a file the user asked for waited for
a slow server as long as it took. With the extra deadline such a transfer
failed with "timed out", and the inner job stayed in voice.rs until the server
opened it, found nobody to hand the connection to, and dropped it.

The driver waits without a deadline now. A caller that drops the call (the
picture's deadline, a cancel) is noticed through the closed reply channel, and
the driver's wait ends, dropping the receiver that the inner job holds.

Test (virtual time): a read and a write wait 120 seconds for the server and
then open; a read that is dropped closes the reply of the inner job. It fails
on the code before this commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:28:32 +03:00
faumarayandClaude Sonnet 5.5 96dece42e6 Send a move to the link while another move of ours is on its way
Driver::join answered a JoinVoice with the own voice state and sent no Move
whenever the snapshot showed us in the requested channel. A move to another
channel that the link had not answered yet left the snapshot where it was, so
a second request back into the old channel was dropped without an error and
the user ended up in the channel of the first move. The baseline forwarded
every Move to the link (which swallows "already in that channel" itself).

A move into the channel the snapshots show is answered at once only while no
move of ours is pending; otherwise it goes to the link in order. The link says
nothing to a move into the channel it is in, so a refusal of the first move
now also answers the pending moves into the channel the snapshots show,
instead of leaving the second to its ten seconds.

Tests: a move made while another is on its way reaches the link and both are
answered by their snapshots (and a move into the channel we are in is still
answered without the link when none is pending); a move back after a refused
move is answered at once. Both fail on the code before this commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:28:07 +03:00
faumarayandClaude Sonnet 5.5 e06ed43b07 Bind the count in the subscription wait so both rustfmt versions format it alike
Nightly rustfmt wanted `.count()` and `== 3` on separate lines in the wait for
the three subscriptions of a_session_that_ends_during_the_connect_syncs_says_why,
1.94 (which CI pins) did not. The count is a local now, and the comparison a
line of its own. Nightly rustfmt differs from the baseline's six diffs only
(history.rs, encoder.rs, discovery.rs, chat.rs, studio.rs, engine.rs) after it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:26:44 +03:00
faumarayandClaude Sonnet 5.5 6b2b792926 Do not let the fake-link presence test depend on the order of media and pushes
presence_follows_the_link_until_it_disconnects played a voice packet, a poke
and an error in one go and waited for Talking, the poke and the error in that
order. Talking comes from the media queue and the poke and the error from the
push channel, and the loop of SessionLink cannot order two channels: when the
push was polled first the engine reported Poke, Error, Talking, the wait for
Talking skipped the first two and the next wait timed out. It failed in 22 of
300 isolated runs (the baseline never did).

The test now plays the voice packet, waits for Talking, and only then plays the
poke and the error. The design records the change (it is a change of the order
of the steps, not of an assertion).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:26:28 +03:00
faumarayandClaude Sonnet 5.5 bf72d85a22 Split the development switches: the sample data into voelin-ui-vm
dev/logic.rs now has the sample of VOELIN_DEMO_UI as plain values and as
the events a server would send: the servers and their presence, the
pictures (PNG bytes the front end saves), the chats with their pins and
topics, the contacts, the private chats, the poke, the offline messages,
the gateway's events, the notices and the recordings, and the older pages
that answer scrolling up. The helpers that only look at the state (the
divider of VOELIN_OPEN=unread, the first locked channel) moved with it. The
Slint side (dev/bind.rs) keeps the switches, the window and the screenshot,
and feeds the sample through the app's own events; a test replays the
whole sample through events::handle and checks the state it leaves.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 13:57:42 +03:00
faumarayandClaude Sonnet 5.5 2d6cbf66af Split the social controller: the friends, the bell, the search and the social events into voelin-ui-vm
social/logic.rs now has the contacts as rows (contact_item, people), the
buttons of a contact and what they ask the window to do next, the bell
(notify, the rows, read, clear, open), the search with what each result
opens, and what an engine event does to the friends, the pokes, the offline
messages and the notices (event). events::handle runs that first, then
events::apply, so a front end has one entry point; Social<D> is the state
those keep, with what the messages page keeps as D for now. Refresh got
people, conversations and dm, the host got dm_shown and now_ms, and
Persist.Settings pages are told apart from the new notices. The Slint side
(social/bind.rs) writes the Bridge, shows the desktop toasts and navigates.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 13:41:29 +03:00
faumarayandClaude Sonnet 5.5 52e39f0b5a Split the settings page controller: the audio form, the switches and the volume dialog into voelin-ui-vm
settings_page/logic.rs now has what the page shows when it opens (the
device choices, the form, the push-to-talk and H.264 switches), what a
change of the form sends to the engine, the microphone test, the push-to-talk
key to register, the crash notice and the H.264 rows, and the client volume
dialog (what it fills from, what it plays and keeps, which client
VOELIN_OPEN=client opens). The audio settings and the clients' volumes are
kept through Persist::Audio and Persist::Playback. The Slint side
(settings_page/bind.rs) lists the devices, owns the hotkey, the codec and
the crash reports, and writes the Bridge.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 13:09:37 +03:00
faumarayandClaude Sonnet 5.5 156df9d95b Split the servers controller: the rail, the card, the tree and the moves into voelin-ui-vm
servers/logic.rs now has what a server does to the state and says in plain
data: which server is shown and forgotten, how it is observed (a plan:
nothing, retry, gateway, query or discover), what finding the gateways
comes to, joining a channel (a move, the password question, or connecting
into it), the members' search, the voice view and the invite link, and the
rail, the server card and the channel tree as rows and values (rail,
toolbar, tree_view, server_tint). The Slint side (servers/bind.rs) keeps
the store, the secrets and the engine commands, and writes the Bridge and
the models from what the logic returns.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 12:57:24 +03:00
faumarayandClaude Sonnet 5.5 02a3b3eab0 Split the chat controller: the chat view, the user's moves and the lines into voelin-ui-vm
chat/logic.rs now has what the chat view shows (the strip, the lines with
their divider and downloads, the pins, the topics and the counts, as plain
data), the lines of a tab or of an open topic (lines_of, also for the Stream
Studio's chat, with the pokes of a private chat's peer), and what the user's
moves do: select and close a tab, send, ask for older messages, mark read,
react, pin, the topics, download, attach and upload. The Slint side
(chat/bind.rs) writes the Bridge and the models from it and calls the
transitions. Poke and its lines moved to voelin_ui_vm::social.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 07:05:58 +03:00
faumarayandClaude Sonnet 5.5 b5ea0c3e95 Send a scope that is bigger than the push channel in bigger chunks
A sync is sent whole or not at all, so that a scope is never left half sent;
that needs the channel to have room for every frame of it. A scope with more
frames than the channel holds when it is empty (more than 16 frames of 256
entities on the smallest channel) could never be sent and stayed lagged for
ever. The chunks of such a sync are now as big as the channel needs, so every
sync fits an empty channel. A test syncs a SERVER scope of 5,000 channels over
the smallest channel.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:53:26 +03:00
faumarayandClaude Sonnet 5.5 0d2ad3f250 Split the streams controller: the state, the events and the rows into voelin-ui-vm
What we share and what we watch are in the AppState now (Sharing, Watching),
with the transitions of the engine's stream events (apply handles them, the
Stream Studio's stream excepted), the user's choices (watch, leave, volume,
quality, the share dialog's plan, the capture that started) and the rows and
texts of the streams panel, the share card and the viewer, as plain data in
streams/logic.rs with tests of their own. The Slint side (streams/bind.rs)
writes the Bridge, owns the capture and the decoder, and attaches or drops
them as an update says (StreamEffects).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:48:18 +03:00
faumarayandClaude Sonnet 5.5 88f58ea468 Record the review round in the design of the session seam
Sections 3, 4.1 to 4.4 and 13 say what changed (notify, the talking hint, the
address text, the close reason of a connect, the chat scope limit and the SyncEnd
of a CHAT scope, the seat across tsclientlib's reconnect), the risk table has the
lagging consumer, and section 14 lists the eight findings with their fix and
test. Follow-ups P13 (a speaking hint for the own channel) and P14 (what a
backend that reconnects inside a session tells its consumer) are for the
protocol repository.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:34:17 +03:00
faumarayandClaude Sonnet 5.5 038f3841df Test the review's fixes through both adapters
Each test fails on the code before the two previous commits (checked against
2d71903 with these tests applied: eleven failures):

- the connection across TeamSpeak's own reconnect: the engine follows a new
  client id (OwnChannel, the chat of the channel, what we say, the voice slot,
  the flags), and stays the client it was while a ghost lingers;
- private messages from 24 peers all arrive;
- a talker the link hears but does not forward as Opus is shown as talking;
- notify refuses what has a stream of its own and runs the rest;
- a session that ends while the connect waits for the syncs says why (a fake
  host that answers the subscriptions and is killed with a reason);
- the text of an address nobody serves keeps the channel password out;
- a consumer that does not read the pushes does not stall the voice, and gets
  the scope again whole when it reads.

The rig can connect as a TeamSpeak 3 server, which is what makes the engine
follow its seat.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:34:17 +03:00
faumarayandClaude Sonnet 5.5 09a0ef3ad5 Make the engine side of the seam report every chat message, follow our seat and believe the host
The review found four defects in SessionLink and the link module, fixed here:

- A message of a CHAT scope's first full sync could be lost. The replica stages
  a full sync until its SyncEnd, so a message of a Change of the sync cannot be
  read when the Change is applied, and SyncBegin, Change and SyncEnd may come
  in different batches; but (channel, id) was marked as reported before the
  replica was asked for the message. A message is marked as reported only when
  it was shown now, and at the SyncEnd of a CHAT scope the messages of that
  channel not shown yet are (two deterministic unit tests, one with SyncEnd in
  a later batch and one for a message that comes before its scope).
- When the push channel ended during the connect syncs, the real close reason
  of the session was thrown away and the engine showed a silent disconnect. It
  now asks closed() (and closes a session that has not ended: a refusal with no
  words).
- The CHAT scopes were limited to 16 whatever the host said. The limit is now
  Welcome.limits.max_chat_subscriptions (0 or none: the v1.0 default of 16); the
  server chat and our channel come first, then the private conversations, the
  newest (highest id) first.
- The own participant was pinned to the one of the connect. Behind a TeamSpeak
  host the seat now follows our user: it stays while the participant is ours
  and moves to the participant that carries our user id when the seat is gone
  (tsclientlib's reconnect makes us another client) or no longer carries it (a
  ghost of the old connection); a seat whose user id changed by itself is
  followed. OwnChannel, the voice flags, the uplink slot and the chat scope of
  our channel follow.

A Signal{speaking} of the host is believed (TalkTracker::hint) until the host
says it is over: that is how a talker whose packets are no Opus is shown as
talking. The documentation of LinkEvent::Talking, OwnChannel and
Connected.own_client says what the adapter derives and what it does not.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:34:00 +03:00
faumarayandClaude Sonnet 5.5 4ddfdef04f Make the TeamSpeak session keep up with a lagging consumer, a reconnect and the contract
The task behind LinkSession (ts_session/driver.rs) is where the review found
five defects, all fixed here:

- It awaited pushes.send() on the bounded push channel, so a consumer that
  lagged stalled the voice media and the commands that share the task. It now
  never waits: a push that finds the channel full is dropped, its scope is
  marked as lagged and sent again whole (SyncBegin .. SyncEnd, all frames or
  none) once the channel has room, as ConnectParams.push_capacity documents; a
  signal has no scope and is dropped. The functions that only awaited the push
  are plain functions now.
- The own client id was the one of the connect for the whole connection, so
  after tsclientlib's own reconnect (a new client id, the same unique id) the
  own channel, the poke target, the own VoiceState, the author of our messages
  and the slot send_media checks were all the old client's. The task now follows
  the snapshots: it stays the client it was while that client is there, and
  else is the newest client of its unique id; the own client keeps the database
  id when an identity is there twice (entities::build), so the user stays the
  same; LinkSession.send_media reads the slot from a shared atomic.
- CHAT subscriptions were limited to 16 in process, so private messages from
  the 15th peer of a connection were never delivered. The limit is 65,536
  (Welcome.limits says so, and the total of subscriptions follows).
- notify accepted List, FileRead and FileWrite and ignored them. Only an op of
  the control stream goes without an answer now (a misplaced op is a Protocol
  error, as on FakeSession); our mute flags go to the link, and any other op is
  run as the request it is. A notify on a session that has closed is refused
  also while the task is still on its way out.
- The link's own Talking was dropped, so a talker whose packets TsLink does not
  forward as Opus (Speex, CELT) was no longer shown as talking. It goes on as a
  Signal{speaking} hint.

The assertion of the Welcome test on the limit follows. The engine side of the
reconnect, the limit and the hint is the next commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:33:17 +03:00
faumarayandClaude Sonnet 5.5 080d8873bb Keep the channel password out of the text of an address no connector serves
Backends::connect handed an address that no plain connector serves to
Connectors::connect, whose error names the whole address: "no connector for
ts3server://host?port=9987&channelpassword=...". The text is shown to the user
and may be logged, and a TeamSpeak link carries the channel password (and a
voelin:// link a host pin) in its query and fragment.

The registry now looks the connector up itself and cuts the address at ? and #
in the text (without_query, which the "not a TeamSpeak server address" error of
the TeamSpeak side uses too, so that one also loses a pin).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:32:19 +03:00
faumarayandClaude Sonnet 5.5 03d1c3bd07 Move the state transition of every engine event that the AppState holds into voelin-ui-vm
events::apply(state, host, event) changes the AppState for an engine Event and
returns an Update: the parts to draw again (Refresh, each once), the status
line, the engine commands, what to keep (Persist), pictures to decode again,
the password dialog, notices for the bell, the chats that changed, a stream to
watch. Host is what a transition asks while it runs (is the chat on screen,
the store's read markers, the preview limit); the Slint client answers it in
host.rs and carries the update out there, so App::handle_event is
social_event, apply_event and social_refresh. The chat transitions (tabs,
messages, what is read, pins and topics, files), the pictures linked in
chats, the server's name, icon and gateway, joining again and the password
prompt, the last place of voice and the stored volumes moved with it; Spot,
the notice types, own_uids and peer_name moved to the view model crate.

Update::rest hands back the events whose state is not in the AppState yet
(the streams we share and watch, the studio's stream, a setting that
changed); the friends, pokes and offline messages are still looked at by
social.rs before and after. The vm tests replay tapes of events against a
fake Host.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:30:39 +03:00
faumarayandClaude Sonnet 5.5 0672b21758 Warn about undocumented public items of voelin-ui-vm
#![warn(missing_docs)] on the crate, with the fields and variants that had
no docs documented (BBCode styles and spans, settings, the tree's input) and
a targeted allow on the two mirror modules, bridge and studio_bridge, whose
fields are those of the Slint structs and are explained by the comments in
bridge.slint and studio-bridge.slint.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 05:55:24 +03:00
faumarayandClaude Sonnet 5.5 12b2773791 Say what docs/ui.md counts, with the true share and the studio's base
The table of controllers still to split now states its measure (every .set_
call, the status line's included), the share of Bridge writes as counted
(four fifths with the status line, two thirds without), the base counts
before the work on voelin-ui-vm (studio.rs 64, settings_pages.rs 52), why the
studio went before streams.rs, and what ImageSource::size() does now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 05:55:24 +03:00
faumarayandClaude Sonnet 5.5 d9de95b985 Make a picture's size mean it shows, and keep pixels the size they say
ImageSource::size() read a raster file's header, so a cache file that was
cut short or garbled after the header counted as showable, where the Slint
version's decoded image was empty. A raster picture is now decoded to tell
(the first frame, with the limits the Slint side uses) and an SVG must parse
as XML with an svg root (roxmltree, already in the tree through the vector
renderer); the answer is kept per file stamp, and per key and content hash for
a downloaded picture, and decoding runs outside the lock. The size check of
the pixel count no longer overflows on a header that claims u32::MAX.

ImageSource::Rgba holds a Pixels value that can only be made with the right
length, so the Slint conversion cannot hand clone_from_slice bytes that do
not fit (it panics on that).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 05:52:16 +03:00
faumarayandClaude Sonnet 5.5 f92a14fc84 Fall back to the name's colour for a chat whose server is gone
server_tint answered opaque black for a server that is not in the list,
where the Slint version answered transparent. It now answers none, and the
direct-message list picks the colour of the chat's own title, as it does for
every chat that is not a server's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 05:31:35 +03:00
faumarayandClaude Fable 5.1 ad2097963e Merge phase5/ui-vm: the toolkit-free voelin-ui-vm crate (plan section 6 step 2)
CI / Linux checks (push) Failing after 1m7s
Shared view-model types (ImageSource, Rgb, list diffing), the view models,
the BBCode reader and the Twemoji archive, SessionView/Tab/Msg and the App
state moved out of the Slint crate into voelin-ui-vm; the Slint crate keeps
adapters and bindings (studio and settings split into logic and bind).
Opus gate accepted with five minors left as follow-ups (server_tint falls
back to black, ImageSource::size reads headers only, convert::image does
not check the RGBA length, docs/ui.md metric wording, field docs on the
mirrored bridge structs).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 02:16:48 +03:00
faumarayandClaude Sonnet 5.5 2d71903e8f Write two loops of the seam as newer clippy wants them
A nightly clippy (1.101) flags two places of the session seam that the pinned
1.94 does not: the sibling placement of ts_session/entities.rs is a while let
loop, and the generated channel tree of the presence round trip in book.rs
counts with its loop variable. Neither changes behaviour (the same random
stream, the same ids).

The remaining nightly findings are in code this branch does not touch:
audio.rs and media.rs of voelin-core (chunks_exact), voice.rs (a large Err
variant), voelin-audio, voelin-media and voelin-ui.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 02:13:19 +03:00
faumarayandClaude Sonnet 5.5 9bec557c81 Record the second smoke and live runs in the design
The first run of the adapter's smoke failed the stream directory scenario (the
fix is the previous commit); the second ran every per-server scenario of
scripts/it-smoke.sh on TeamSpeak 3 and 6 to the end, and the serial live tests
of voelin-core passed again (live 6, media_live 2, stream_live 3,
voice_features 3). The script's last stage fails as it does on the baseline
(ts6_banners, when the live tests run in parallel).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 01:48:13 +03:00
faumarayandClaude Sonnet 5.5 8c62030e5b Hold the stream task's reports until the engine has announced the connection
The first smoke run of the adapter failed its stream directory scenario (the
late viewer's WatchStream was refused with "not connected with voice"), and an
alternating probe of that scenario with the baseline binary and this one on the
TeamSpeak 6 dev server failed 3 of 6 for this branch and none of the baseline's
four runs the server's clone limit left alone.

The cause is an ordering the adapter lost. The TeamSpeak 6 stream task puts
Event::StreamsChanged on the engine's bus itself; behind a session the engine
hears of the connection only after the connect sequence (several requests
through the driver), while the stream task lists the server's streams as soon as
the server tells it, so a client that acts on the first list asked for a watch
before the engine knew it had voice.

The ts_session driver now holds the bus events of a link with streams that are
no answer to a request until the engine's first stream command (session.rs
sends one in its handling of Connected right after emitting the state), or for
three seconds. Three unit tests pin the hold, its end, and that a link without
streams is not held. The same probe passes 8 of 8; docs/session-seam.md section
13 records it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 01:41:14 +03:00
faumarayandClaude Sonnet 5.5 bc9ccbc85e Measure the voice path through both adapters; test the engine on a registered connector
- A unit test frames 5,000 Opus packets each way through SessionLink, the
  TeamSpeak session and the recording link and prints the cost per packet
  (about 7 microseconds to the host, 10 from it in a debug build; the test
  bounds each direction at 500 microseconds). docs/session-seam.md section 13
  records the figures, which were the one thing slice 1 had not measured.
- tests/session_backends.rs: the engine over voelin-proto's FakeConnector
  through Engine::start_with_backends (connect, server name and backend,
  channels, a move, disconnect), and the registry's error text for an address
  no connector serves.
- The error of a TeamSpeak connector given an address that is not a TeamSpeak
  one no longer prints the query, where a channel password rides.
- The note on the two library tests that need the name localhost to resolve to
  127.0.0.1 says so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 00:41:04 +03:00
faumarayandClaude Sonnet 5.5 1b7abdf4c7 Record slice 1 in the design; consume a host that is no TeamSpeak one
- docs/session-seam.md: the status line, and section 13 with how the code
  differs from the design, a follow-up for the protocol repository (P12), and
  what ran against the baseline.
- docs/architecture.md and the crate docs describe the engine on the Session.
- A departed client's talk state is dropped before the new snapshot replaces
  the table it is looked up in.
- The backend of a host that names none is its product and version.
- A unit test drives the engine over the protocol repository's FakeSession
  through the registry: connect, presence, a move, chat in the channel,
  disconnect.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 22:25:56 +03:00
faumarayandClaude Sonnet 5.5 c473ab216e Run the engine on voelin_proto::link::Session
The engine's voice source is now a voelin_proto::link::Session obtained from a
registry of connectors (docs/session-seam.md, slice 1):

- link::Backends keeps the plain connectors of voelin_proto::link::Connectors
  and the in-process ones that also hand the engine a port for TeamSpeak 6
  streams; the scheme of the address picks the connector, an address without
  one is a TeamSpeak bookmark.
- link::SessionLink is the engine's ServerLink. session.rs is unchanged and
  still speaks LinkCmd and LinkEvent; SessionLink runs the connect sequence
  (List the server, subscribe HOME, SERVER and LIVE, take the seat), keeps a
  voelin_model::replica::Replica, projects it into the client's older model
  (link/project.rs, the fix-ups F1 to F10), frames voice as RTP and derives
  who talks from the media (link/media.rs), and turns every command into the
  Session call of its row. Transfers copy through read_file and write_file.
- ts_session makes a TeamSpeak connection a Session: LinkSession over any
  ServerLink translates the link's commands, events and presence snapshots to
  v1 entities, pushes, answers and RTP; TsConnector makes them for
  ts3server:// and teamspeak:// addresses with TsLink inside, and
  LinkConnector for the link of Engine::start_with_link.
- voice.rs opens the transfer connection itself for the new OpenRead and
  OpenWrite commands; files::download and upload are generic over the stream.
- Engine::start_with_backends is new; start_with and start_with_link go
  through the registry.

tests/link_fake.rs runs through both adapters; its fixtures are normalised as
the design says (an order chain, database ids, talking from media, the server
named, channel chat for the channel we are in), and the request id the link
sees is the session's own. New unit tests cover every row of the mapping with a
recording link, the TeamSpeak session on its own, media framing both ways, the
talk tracker, the close table, the error texts, the backend and capability
tables, the connect parameters, and the presence round trip on book fixtures
and generated presences.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 22:13:07 +03:00
faumarayandClaude Sonnet 5.5 fb8e6b63dd Take voelin-model from VoelinProtocol and add voelin-proto
voelin-identity, voelin-proto and voelin-model now come from one revision of
the protocol repository (main c8e0e5a: the session seam voelin_proto::link
with its account types, and the replica in voelin-model). The client's own
crates/voelin-model is removed: the protocol's crate is a superset, identical
in presence, server, chat and percent, and differs in badges.rs, link.rs and
tree.rs only by a doc comment and two equivalent expressions, and adds the
perms and replica modules. Every crate that used it takes
voelin-model.workspace = true. voelin-core depends on voelin-proto (and, in
its dev-dependencies, on the test-util fakes), which the engine will consume
in the next commits.

Manifests, the lock file and docs only: no source change. THIRD_PARTY_NOTICES.md
is unchanged (scripts/notices.sh --check: up to date).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 21:26:06 +03:00
faumarayandClaude Opus 5.5 38473b761d 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 <noreply@anthropic.com>
2026-10-20 20:47:14 +03:00
faumarayandClaude Sonnet 5.5 5d66be43d4 Document the public functions, constants and types of voelin-ui-vm that had no docs
The items moved from a private module of voelin-ui, where they needed none;
as public API of the new crate they get a line each. The fields of the bridge
structs, which mirror bridge.slint field by field (module docs), and a few
self-describing fields and variants are left as they are.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 20:40:51 +03:00
faumarayandClaude Sonnet 5.5 668c1a8038 Give the bridge struct counts as they are in docs/ui.md
The text said 49 (the plan's figure); bridge.rs has 51 and studio_bridge.rs
10, and MytsBadge and MytsForm stay in Slint.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 20:37:49 +03:00
faumarayandClaude Sonnet 5.5 0447e6bc92 Say in the notices that the Twemoji archive lives in voelin-ui-vm
The asset list in about-assets.md (and the copy appended to
THIRD_PARTY_NOTICES.md) put all bundled assets in crates/voelin-ui; the
archive moved with the emoji reader. Cargo.lock only gained the own crate,
so no third-party entry changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 20:34:18 +03:00
faumarayandClaude Sonnet 5.5 2b113479ec Point the Slint files' header comments at voelin-ui-vm
bridge.slint and studio-bridge.slint still named src/vm/ and src/studio.rs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 19:55:19 +03:00
faumarayandClaude Sonnet 5.5 a4aa58f7be Count the sample chat's ids with zip instead of a loop counter
Newer clippy (nightly) reports explicit_counter_loop for the sample
messages' id in dev.rs, which failed `cargo clippy -D warnings` on nightly
for voelin-ui. Same ids, 1 upwards.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 19:46:50 +03:00
faumarayandClaude Sonnet 5.5 767a9dad46 Document the two UI crates, the adapter boundary and the controllers still to split
docs/ui.md: the structure of voelin-ui-vm and voelin-ui, a "Two crates"
section (values, lists, conversion, state, logic/bind) and the written list
of the controllers that still interleave logic with Bridge writes, with
their .set_ counts, for the next round; the pointers to the moved files
(Twemoji archive, BBCode reader, settings pages, studio) are corrected.
docs/architecture.md: the crate table has voelin-ui-vm. README.md and
CHANGELOG.md name the new crate. Module comments that pointed at studio.rs
and vm/ point at studio/ and the crate.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 16:06:29 +03:00
faumarayandClaude Sonnet 5.5 ce0e6e1f62 Split the Stream Studio: logic into voelin-ui-vm, the windows and the engine in bind.rs
studio.rs (62 Bridge writes) is split like the settings pages. What the
studio decides lives in voelin_ui_vm::studio::logic:

- StudioData, the state apart from the running parts (settings, scenes,
  status, statistics, destination, stream, pickers, overlays), with the
  bitrate and layers a stream starts with, the hidden-tick counter, the
  preview size, the destination choice, the stream settings form and the
  header/bottom-bar status (status_view, with the front end's side passed
  in as a StatusContext), the overlays the switches ask for;
- where the stream goes (destinations, their names and rows, the channel
  tab of the stream chat), the stream settings panel's edits, the output,
  the layer, source, picker and mixer controls (source_action,
  source_change, camera/screen/audio pickers, main_source_changes), the
  studio settings dialog, event and ending texts;
- the studio's own settings type and key (StudioUi, STUDIO_UI), the demo
  studio's sample scenes, viewers, stream and chat message.

voelin-ui keeps studio/mod.rs (StudioState: the models, the running
studio, the windows, the mixer handles, plus StudioData) and studio/bind.rs
(the engine tasks, the preview, the encoder, the two windows' StudioBridge
writes, the camera and screen listing, the chat and stream commands). The
demo settings return their problems instead of logging them. SessionView
and Tab methods that need no Default list type no longer ask for one.
28 new tests cover the logic.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 16:01:12 +03:00
faumarayandClaude Sonnet 5.5 03f4a92161 Split the settings pages: logic into voelin-ui-vm, the Bridge writes stay in bind.rs
settings_pages.rs had 52 Bridge writes interleaved with what the pages
show and change. The decisions now live in
voelin_ui_vm::settings_pages::logic and work on the settings service, the
AppState and the plain bridge rows:

- the forms read from the settings (video, streaming, notifications,
  privacy, advanced), the layer and audio-source rows and the filtered list
  of all settings;
- the settings written from the forms (apply_video, apply_streaming,
  layer, audio source, SRTP profile, notification, privacy and advanced
  edits), each returning the messages for the status line instead of
  writing them;
- the Integrations rows (gateways, configuration keys, permission rules,
  encoders and decoders with their status texts) and the Profiles rows
  (identities, bookmark pickers, what an import found, the account form);
- the pages' own state (PagesState, Improving), the layer, preset and
  codec helpers, allowed_index/of and origin_label, with the tests that
  went with them and tests for each of the above.

voelin-ui keeps settings_pages/{mod,bind}.rs: Pages (PagesState plus the
camera preview and the audio-app watcher), the Bridge and model writes, and
what a change sets going (camera, engine, identity store, threads). A
message the logic returns is logged and shown as before; the one visible
difference is that the "A layer needs a size" hint is logged with it.
serde_json becomes a regular dependency of voelin-ui-vm (the JSON typed into
the Advanced list); the lock file is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 15:31:53 +03:00
faumarayandClaude Fable 5.1 59fec5b19f Merge phase4/store-hygiene: identity store follow-ups and cargo-deny advisories
CI / Linux checks (push) Failing after 58s
A sign-out finishes when a row's binding columns cannot be read; deleted
keys are overwritten (secure_delete) and the log is truncated once per
sign-out with a short wait; the device key refuses a synced binding; the
unbind step keeps non-text data byte for byte; rustls and yoke-derive
updated, wasapi ignored until 2026-12-20. Two Opus gates accepted; the
last left two minors (wording of where deleted bytes may stay; a test
that counts the checkpoint) as follow-ups.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-20 15:18:06 +03:00
faumarayandClaude Sonnet 5.5 ac4cee0a8f Move SessionView, Tab, Msg and the App data fields into voelin-ui-vm::state
The sessions and their chat tabs, the downloads, pins and linked pictures,
and the data the screens share (the servers, the settings, the dialogs'
targets, the share and watch bookkeeping) no longer live in the Slint
crate. `SessionView<L>` and `Tab<L>` are generic over the list type of a
tab's chat lines: the Slint app plugs in `Rows<ChatLine>`
(`app::ChatRows`), a GPUI view can use a plain `Vec`. `App` keeps one
`AppState` in `state` and the Slint models; every `self.sessions`,
`self.current`, `self.bookmarks`, ... becomes `self.state.<field>`.

server_icon and server_icon_for stay with the session: `ImageRef` is
toolkit-free now, so they need no adapter. Tests for the tab and session
logic (private chat focus, tab removal, read markers, the divider) are
new, since that logic could not be tested without the Slint crate before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 15:01:24 +03:00
faumarayandClaude Sonnet 5.5 670ed9f29b Keep the stored bytes when a sign-out unbinds a row whose data is not text
KeyStore::get reads a data column that is a BLOB, or TEXT of bytes that are no
UTF-8, as text with the odd bytes replaced. The sign-out's unbind step puts that
text back with the binding removed; REBIND (data = ?3) matches nothing for such
a row, so put fell through to the full write: the lossy string replaced the
original bytes (invalid UTF-8 became U+FFFD, a BLOB became TEXT), and for a
TeamSpeak row the replaced text is no identity, so check_teamspeak refused it
and the sign-out could never finish for that row.

- put() now tries a second statement when REBIND changed nothing:
  rebind_stored_bytes reads the stored data raw and, if it reads (lossy_text) as
  exactly the blob's JSON, updates only the four binding columns by (kind, uid)
  (REBIND_BYTES) and returns without check_teamspeak, so the original bytes are
  kept and the TeamSpeak case unsticks. Any other JSON is a new identity for the
  uid, checked and stored as before.
- The doc sentences at the top of keystore.rs (what a binding-only put and a
  non-text data column mean) and docs/architecture.md are narrowed to what holds:
  the bytes are kept for the text get returned, any other text replaces them.

Tests: the gate's probe (a bound voelin row with data x'7b2276223aff317d', two
future-kind rows, one a BLOB and one TEXT of no UTF-8, and two TeamSpeak BLOB
rows, one of a good identity and one of garbage): sign_out(Auto) and
sign_out(Forget) are Ok and every data value is byte-identical afterwards; a put
of what get read changes the binding and keeps the bytes; a put of other data is
checked and replaces them. The three tests fail on the previous code.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 14:35:46 +03:00
faumarayandClaude Sonnet 5.5 0ac4095143 Bound the checkpoint after a removed key to a short wait, once per sign-out
Store::truncate_wal ran PRAGMA wal_checkpoint(TRUNCATE) with the connection's
busy timeout of five seconds. A checkpoint that truncates holds the writer lock
of the log while it waits for readers, so a reader that kept a snapshot made
every removed row cost the whole timeout with the store's mutex held, and other
writers failed with "database is locked" meanwhile. KeyStore::sign_out removes
up to four rows (the synced copies, the device key, the record) and ran the
checkpoint after each: 20 s and failing writers in the gate's probe.

- truncate_wal now sets a busy timeout of 150 ms (CHECKPOINT_WAIT) around the
  pragma and restores the timeout the connection had (read back with PRAGMA
  busy_timeout, so a value set by a caller survives) whatever the checkpoint
  returned. A blocked checkpoint still leaves the delete standing and warns.
- SqliteKeyStore overrides sign_out: the trait's own steps run on a private
  SignOutPass whose remove deletes the row and notes it, and the sign-out
  truncates the log once after its last step (also when a step failed, the
  removals before it have happened). KeyStore::remove on its own still
  truncates after the row it removed.
- The three sentences that said the bytes "stay in the log until the next
  checkpoint" (keystore.rs, Store::truncate_wal, docs/architecture.md) are
  corrected: they go when a later checkpoint truncates the log, later writes
  overwrite those frames, or the last connection closes and the log is deleted.

Tests: with a raw connection holding a read snapshot, a sign-out with four
removals returns in about 170 ms (it took 20 s) while a writer on another
connection with a one-second busy timeout writes throughout without an error
(it got "database is locked" nineteen times), and the next removal after the
reader is gone truncates the log again; a unit test shows a blocked
truncate_wal returns in under a second, leaves the log, and restores a
non-default busy timeout, and that the same call truncates once the reader is
gone. Both tests fail on the previous code.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 10:21:49 +03:00
faumarayandClaude Sonnet 5.5 ce7ec3afb7 Move the view models into voelin-ui-vm; the Slint models take plain rows
vm/{avatar,tree,servers,streams,home,chat,social,studio} and the UI
settings (settings.rs: keys, UiSettings, LastVoice, ClientPlaybackMap,
the audio form) move into voelin-ui-vm with their tests (102 there now;
the 86 view-model tests of voelin-ui all survive, the old list::sync test
became the list::diff tests). They produce the plain bridge structs, with
Rgb for colours and ImageRef for pictures:

- a file picture is ImageSource::File { path, stamp }: the engine writes
  a picture that arrives again into the same file, so the length and
  write time are part of the reference and a changed file redraws its
  row; size() reads the header once per stamp (no toolkit decoder);
- pictures held in memory (chat previews) are ImageSource::Memory;
- the line cache of the chat no longer keeps Slint models alive for
  pointer equality: plain lines compare by value, so an unchanged
  message makes the same line with or without the cache.

voelin-ui keeps every model as bind::rows::Rows<T>: the plain rows last
shown plus the VecModel, synced with list::diff, converting only the rows
that changed (bind/convert has the From impls). The controllers hand the
view-model rows to Rows::sync and convert forms at the bridge
(`.into()`); crate::vm is now `voelin_ui_vm as vm`, so paths stay.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 10:20:55 +03:00
faumarayandClaude Sonnet 5.5 8e6838a00f Move the BBCode reader and the Twemoji archive into voelin-ui-vm
Both are pure (no Slint): vm/bbcode.rs and emoji.rs with their tests and
the packed archive (assets/twemoji.bin, with its license note; the
packing script writes it there). voelin-ui keeps the paths
crate::vm::bbcode and crate::emoji as re-exports until the callers move.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 09:15:44 +03:00
faumarayandClaude Sonnet 5.5 4dc8272c64 Add voelin-ui-vm: toolkit-free view-model types and the Slint adapter
New crate voelin-ui-vm with no UI toolkit in its tree: ImageRef
(Arc<ImageSource>: File, Rgba, Svg, Memory, None, with size()), Rgb for
colours, list::diff(old, new) -> Changes (updates, removals and
insertions by index) and the bridge structs as plain Clone + PartialEq
values (the 51 of bridge.slint without the account's two, and the 10 of
studio-bridge.slint). Strings are Arc<str>, lists Vec.

voelin-ui keeps the temporary seam: From impls between every bridge
struct and its Slint twin (bind/convert), and bind/rows.rs, which applies
Changes to a VecModel and converts only the rows that changed. The
viewer's quality list is the first model on it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 08:53:13 +03:00
faumarayandClaude Sonnet 5.5 2e026a043c Update rustls and yoke-derive for cargo deny, ignore wasapi until 0.25
cargo deny check failed on the advisories of the base lock:

- rustls 0.23.45 (RUSTSEC-2026-0346 to 0349: Debug output of client session
  values, buffered data after ECH rejection, unbounded brotli certificate
  decompression, ServerHello downgrade): cargo update -p rustls --precise
  0.23.46, which the advisories name as the fix.
- yoke-derive 0.8.3 was yanked: cargo update -p yoke-derive --precise 0.8.4.
- wasapi 0.24.0 (RUSTSEC-2026-0332, unsound WaveFormat::parse): the fix is
  wasapi 0.25.0, a breaking release of a Windows-only dependency of
  voelin-media, which the Linux CI can neither build nor test, so it is not a
  semver update. voelin-media never calls WaveFormat::parse (it only builds
  formats with WaveFormat::new). deny.toml ignores the advisory with that
  reason and a date: remove by 2026-12-20, by upgrading wasapi on a Windows
  machine. cargo-deny cannot enforce the date; the comment and the reason say it.

Cargo.lock changes only those two packages (cargo's re-resolution also moved
tempfile to getrandom 0.3.4; that is put back to 0.4.3 by hand so the diff is
the advisories' and nothing else; cargo metadata --locked accepts it).
THIRD_PARTY_NOTICES.md is regenerated (scripts/notices.sh, cargo-about 0.9.2)
for the two version numbers.

cargo deny --locked --workspace check: advisories, bans, licenses and sources
ok.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 08:46:58 +03:00
faumarayandClaude Sonnet 5.5 3c59f24608 Refuse to store the device key as a synced copy
KeyStore::sign_out deletes every identity bound with synced = true in its
first step, before it reads the account record that says which Voelin key is
the device key and whether it predates the account. A device key stored with
synced = true was therefore deleted even where the record says to keep it.
Nothing in this crate stored such a key, but the store accepted it.

SqliteKeyStore::put now refuses, with an error that names the key and the
record and says why, a voelin blob with synced = true while an account record
names its uid as the device key, and also while an account record cannot be
read (it may name the key, and the sign-out would delete it on that guess).
The state is also reached from the other side, so a put of an account record
whose device key is already stored as a synced copy is refused as well. A
binding with synced = false is accepted: a sign-out unbinds it and then follows
the record. The check runs before the binding-only fast path, so a put of the
key's own data cannot rebind it as synced.

Documented in keystore.rs and docs/architecture.md. Tests cover the refusal
for records that keep and that delete the key (the error text, the row left
untouched, the sign-out still following the record), another key that may be
synced, no record or a record naming another key, a record put naming a synced
copy, and unreadable records; the three refusal tests fail without the check.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 08:31:36 +03:00
faumarayandClaude Sonnet 5.5 248955b85c Overwrite a deleted key and truncate the log after it
SQLite's secure_delete was off: a deleted row stayed in the free space of its
page, and the frame of the write-ahead log that held that page kept the key
until the log was reset. Every connection (Store::init) now sets
secure_delete = ON next to foreign_keys, and Store::delete_identity and
KeyStore::remove (how a sign-out deletes the device key, the synced copies and
the account record) run PRAGMA wal_checkpoint(TRUNCATE) after a row was
deleted, so the page with the overwritten row is copied into client.db and the
log is empty.

The truncate is best effort: the delete has happened and a sign-out must still
finish, so a checkpoint that another connection blocks, or that fails, only
logs a warning that the bytes stay in the log until the next checkpoint.
Keys deleted before this change stay in the free pages until a VACUUM; the
architecture notes say so.

Tests read client.db and client.db-wal as bytes: the PKCS#8 text of a Voelin
device key (sign-out with Auto, and with Forget), a synced TeamSpeak copy's key,
a TeamSpeak identity deleted by Store::delete_identity and a key removed
through KeyStore::remove are present before and in neither file after, another
key is still stored and the log is empty; and secure_delete reads 1 on every
connection. Each raw-file test fails with either measure taken out.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 08:27:56 +03:00
faumarayandClaude Sonnet 5.5 4944a0694b Let a sign-out finish when a row's binding columns cannot be read
SqliteKeyStore::list() failed on the first row whose binding columns were
damaged outside this crate (synced = 2 on the account record, say), and
KeyStore::sign_out starts with list() through bound_to(): it never reached the
record, so it could never finish, and DeviceKeyChoice::Forget did not delete
the key it was given either. get() failed the same way where sign_out reads
the record and the device key.

A row whose binding columns cannot be read (refused by
AccountBinding::from_columns, or a value of the wrong type) is now listed and
read as unbound, with a tracing warning that names the row and the reason and
quotes no content. Unbound is the reading that never deletes on a guess: such
a row is not deleted as a synced copy, and a put of it writes four good
columns. A data column that is not text is read as text with the odd bytes
replaced, so a record that cannot be read is deleted by the trait's sign_out
instead of its read failing; a row whose kind or uid is not text cannot be
addressed and the list leaves it out with a warning. list() now fails only
when the database does.

Tests: the gate's probe (UPDATE identities SET synced = 2 WHERE kind =
'account', then sign_out with Auto and with Forget on a store with
bound_existing_key true and false), more damage to the record row, the device
key row and a synced copy, and the unreadable data and kind/uid cases; the
test that asserted the old precise errors of get() and list() now asserts the
unbound reading. The six new tests fail on the previous keystore.rs.

voelin-store gets the tracing dependency (already in the lock); Cargo.lock
changes, THIRD_PARTY_NOTICES.md is unchanged by it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 08:23:55 +03:00
faumarayandClaude Fable 5.1 7c6d149f78 Merge phase4/identity-store: voelin-identity key store on SQLite (Phase 4 step 2)
CI / Linux checks (push) Failing after 40s
voelin-identity from VoelinProtocol as a git dependency pinned by rev;
the identity migrations as schema versions 6 and 7 (kind column, account
binding columns); voelin_identity::KeyStore on the identities table with
bindings and the account sign-out rules; notices regenerated; the sibling
checkout recipe in docs/building.md. Opus gate accepted with three minors
(damaged binding columns block sign-out, secure_delete off, one commit red
on the notices job) left as follow-ups. Building now needs read access to
the private VoelinProtocol repository (docs/building.md, docs/ci.md).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-20 08:11:14 +03:00
faumarayandClaude Sonnet 5.5 4ab019fcb8 Document the key store's error text, the rebind put and the notices step
architecture.md: a refused TeamSpeak blob says only that it is refused, never
its JSON (a private key), and a put that changes only a row's binding does not
read the JSON again, so a damaged row cannot keep a sign-out from unbinding
it. building.md: moving the protocol pin commits Cargo.lock together with the
notices scripts/notices.sh regenerates; the CI notices job fails on a stale
THIRD_PARTY_NOTICES.md, which is what 015c938 did.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 06:21:45 +03:00
faumarayandClaude Sonnet 5.5 71edc7cc2f Unbind a bound TeamSpeak row without reading its JSON again
KeyStore::sign_out unbinds a device-only secret by get() and put() of the
same blob with the binding cleared. put() ran check_teamspeak on the data
first, so a bound row whose JSON had been damaged outside this crate made the
put fail on every call: the account record was never reached, and with
DeviceKeyChoice::Forget the order of the sign-out kept the named key from
being deleted by the retry loop the module doc promised was unnecessary.

put() now first tries a statement that rewrites only the four binding columns
of the row of the same (kind, uid) whose data equals the blob's, and returns
if it changed a row. Anything else, a new row or other data, goes through the
check and the upsert as before: damage is not replaced by more damage, a
stranger's key still cannot take over a uid, and another kind's put of a held
uid is still refused. Nothing but the binding of the row is written, so the
name, origin, default flag and creation time stay as they were.

Tests: sign_out (Auto, and Forget with and without bound_existing_key)
completes on a damaged bound row, deletes the record, unbinds the row and
leaves its data as it was; the put cases above; each fails on the previous
commit. The scratch directories of the test file are unique per call now, as
two tests that pass the same name run side by side.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 06:21:10 +03:00
faumarayandClaude Sonnet 5.5 f3345bccf2 Do not quote a TeamSpeak key in the error of a refused put
SqliteKeyStore::put checked a TeamSpeak blob by parsing its JSON as a
tsproto::Identity and forwarded serde's error. tsproto's key visitor answers
a key it cannot decode with invalid_value(Unexpected::Str(key)), so the
message read `invalid value: string "<the key text>", expected a P256 private
ecc key`: the private key reached Display and Debug of the KeyStoreError, and
so any log line that reports it.

check_teamspeak now drops the serde error and returns a Backend error of
fixed text (Refused::NotATeamSpeakIdentity). The test puts a blob with a
malformed key string, first checks that serde does quote it (so the case
proves something), and asserts that neither Display, Debug nor pretty Debug
of the error or of any error in its source chain contains the string.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 06:20:41 +03:00
faumarayandClaude Sonnet 5.5 143bc945f7 Keep the per-developer .cargo out of the Docker build context
docs/building.md tells developers to put a [patch] to a sibling
VoelinProtocol checkout in .cargo/config.toml. It is git-ignored but was not
in .dockerignore, so it was sent to the daemon with every docker build and
could redirect the dependency to a path that does not exist in the image.
Only the root .cargo is excluded: third_party/dimpl/.cargo is committed and
stays.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 06:19:11 +03:00
faumarayandClaude Sonnet 5.5 b68aeb6829 Regenerate the third-party notices for the protocol dependency
015c938 changed Cargo.lock without regenerating THIRD_PARTY_NOTICES.md, so
the third-party notices job (scripts/notices.sh --check) failed on this
branch. voelin-identity brings x509-cert 0.3 and der_derive 0.8, both MIT
OR Apache-2.0: two more crates under the MIT License row of the summary,
and two names on existing "Used by" lines. Regenerated with cargo-about
0.9.2, the version the script requires. The protocol crates themselves are
publish = false and left out by about.toml, like the client's own.

015c938 on its own is still red on that job: history is not rewritten, and
this commit is the fix that follows it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 06:18:58 +03:00
faumarayandClaude Sonnet 5.5 87f4a574e6 Document the identity store in architecture.md and the changelog
A new Identities section says what the identities table holds now (the kinds,
the binding, the two schema versions and whose SQL they are), what Store and
SqliteKeyStore each do with it, what the TeamSpeak level and the sign-out
mean on this table, and that the engine and the UI do not use the key store
yet. The voelin-store row of the workspace table names the new content, and
the changelog notes the migration and the new access requirement for the
private protocol repository.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 05:52:00 +03:00
faumarayandClaude Sonnet 5.5 526e59d5ca Test the sign-out of the account on the SQLite store
KeyStore::sign_out is voelin-identity's, generic over the trait, so the
store uses it as it is and these tests run it on the SQLite table, each case
of the protocol's section 13.6 as its own test:

- the account record and the synced copies are removed and the unsynced bound
  identities are left unbound, byte for byte;
- the device key is kept, unbound and byte for byte (the stored blob is
  equal, the key signs the same bytes), when the record says
  bound_existing_key, and deleted when it does not;
- DeviceKeyChoice::Forget(device uid) deletes the key it names in both
  cases and no other, and a uid that is not stored deletes nothing;
- a record without the flag keeps the key;
- an unreadable record (unknown version, damaged JSON, an empty object) is
  deleted before the error is reported; with Forget the named key is deleted
  even then; a second call completes without bringing the key back;
- a sign-out that stopped half way can be run again;
- the result is durable in the file, and the kept key's row has no account.

The five hand-made mutants of the protocol's own acceptance (Auto always
deleting, Forget keeping, a missing flag reading false, the unreadable record
left behind, Forget deleting only after the record was read) were applied to
a copy of voelin-identity through the documented [patch] recipe, and each is
caught by these tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 05:51:30 +03:00
faumarayandClaude Sonnet 5.5 2898281d35 Implement voelin-identity's KeyStore on the SQLite identities table
SqliteKeyStore is the identities table as a KeyStore: every kind (TeamSpeak,
a Voelin key, the account record, an unknown kind that passes through) with
the account binding of the columns that ADD_ACCOUNT_COLUMNS added. It owns a
Store behind a mutex, because a KeyStore is Sync and a connection is not;
with_store runs the TeamSpeak methods on the same connection. The trait's
provided methods (bound_to, account_record, put_account_record, sign_out)
are used as they are.

- put is one upsert; a replaced row keeps its name, origin, default flag and
  creation time, and a blob without a binding unbinds the row. The uid is
  UNIQUE across kinds, so a uid another kind holds is a backend error that
  replaces nothing; get and remove are addressed by kind and uid.
- The TeamSpeak level stays computed from the key and counter, as before; the
  level of a blob that is put is not stored. A TeamSpeak row whose JSON was
  damaged outside this crate lists and reads with level 0.
- A TeamSpeak blob is stored only if its JSON is a tsproto identity and its
  key has the uid the blob names. Without the first one bad row breaks the
  list of TeamSpeak identities; without the second a blob could replace, by
  its uid, the key of a different identity.

Tests copy the exercise() cases of voelin-identity's tests/storage.rs into
the client (with the two deviations of a SQLite store, marked), round-trip
bound and synced entries through the table and a reopen with their raw
columns, and load a client.db migrated from schema versions 5 and 6 through
the key store: kind teamspeak, no binding, JSON byte for byte, origin and
default flag kept.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 05:48:51 +03:00
faumarayandClaude Sonnet 5.5 0137d03d5b Run the identity migrations of voelin-identity as schema versions 6 and 7
ADD_KIND_COLUMN and then ADD_ACCOUNT_COLUMNS are the next two entries of the
user_version list, in the order the protocol's Phase 2 tasks 7 and 28 give.
Every identity that exists stays what it was: kind teamspeak, unbound, its
JSON untouched, its origin and default flag kept, and the level still
computed from the key.

The TeamSpeak methods of Store (identities, identity, update, rename, delete,
set_default) now act on rows of kind teamspeak only, so that a Voelin key or
the account record in the same table can never be listed as a tsproto
identity (listing would fail on its JSON) or renamed, changed or deleted by
the old API. Their signatures are unchanged.

Tests build a client.db at the current schema (version 5) and at version 6
from the migration list itself, open it, and check both steps: the fixture
row (the real tsproto serialization, its uid and level checked against
tsproto), a second generated identity, the raw columns, the old API, and a
reopen that runs nothing twice. A test pins the SQL of both migrations
against the protocol's strings so that a newer protocol revision cannot
change a shipped version.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 05:43:52 +03:00
faumarayandClaude Sonnet 5.5 015c938212 Depend on voelin-identity from the private VoelinProtocol repository
voelin-store will keep Voelin identities and the signed-in account next to
the TeamSpeak ones (Phase 4 step 2, protocol Phase 2 tasks 7 and 28), through
the identity blobs and the KeyStore trait of voelin-identity.

The dependency is a workspace git dependency on the SSH URL that the
protocol's docs/development.md names, pinned by commit (64808cc, the head of
its main when task 28 was accepted), so that a per-developer
.cargo/config.toml [patch] can redirect it to a sibling checkout. The recipe
is in docs/building.md; .cargo/ is ignored so it is never committed.
deny.toml allows that one git source. CI and the Docker builds need read
access to the private repository (a deploy key or a token); docs/ci.md and
docs/building.md say so.

Cargo.lock gains voelin-identity, voelin-proto, x509-cert 0.3 and
der_derive 0.8.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 05:41:52 +03:00
faumarayandClaude Fable 5.1 cb595a0621 claude: cap effort at xhigh for every role
CI / Linux checks (push) Failing after 36m48s
The user asked for xhigh as the maximum effort. The designer and the
Opus reviewer drop from max to xhigh, and settings.json sets
maxEffortLevel so nothing in this repository exceeds it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-19 22:10:09 +03:00
faumarayandClaude Sonnet 5.5 ff054008c3 Settle the small leftovers of the earlier reviews
CI / Linux checks (push) Failing after 20m23s
- jitter.rs: short_packet_fuzz takes payloads of 0..=100 bytes (was under
  12) and 3000 iterations (was 500).
- ui-review.md: the whisper row pointed at voelin-audio/src/encode.rs:90;
  the C2S-only packet is built by out_audio in voelin-core/src/voice.rs.
- mixer.rs: the module doc's first paragraph is reflowed, and
  Mixer::set_priority names its parameter talkers, not clients.
- stream.rs: api_types_convert_at_the_boundary asserts the remaining
  variants: every ViewerState, StreamKind (both ways) and LeaveReason
  (alone and inside EndReason::Removed).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 18:09:21 +03:00
faumarayandClaude Sonnet 5.5 cfd9cba2dd Document what is still TeamSpeak's in the seam and the real event order
link.rs and architecture.md now list every part of the ServerLink seam that
still has TeamSpeak types or shape: ConnectOptions.identity and
client_version, the account proof in LinkCtx, the u16 client ids, the
Presence snapshots, and the stream vocabulary of voelin-stream (PeerConfig,
MediaFrame, VideoFormat, VideoCodec, FrameSource). StreamAudioEnded joins the
event list.

Disconnected is no longer promised to be the last event: the stream task is a
task of its own that winds down after the connection, so OwnStream(Ended) and
StreamAudioEnded may follow it. The docs say TsLink ends the stream task as
the connection's loop ends (usually before Disconnected, not always) and that
the session does not depend on the order: it ends our stream and the watched
audio itself on Disconnected and ignores what the link says after it. The
reconnect order (StreamCmd::Shutdown before Disconnect) is documented too.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 18:06:54 +03:00
faumarayandClaude Sonnet 5.5 e0ac95ee79 Pin the order of a reconnect in the FakeLink tests
The session ends the streams of a connection it replaces by sending
StreamCmd::Shutdown through that connection and only then Disconnect; a link
that stops reading commands at Disconnect (TsLink) relies on it. The new test
connects with streams, takes the directory, connects again and asserts the old
connection is given Shutdown before Disconnect. Swapping the two sends in
Session::command makes it fail.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 18:04:34 +03:00
faumarayandClaude Sonnet 5.5 a5125b3998 End the connection's streams as the loop ends, not after the shutdown
The ConnectionStreams guard was dropped only after shutdown_connection, which
can wait up to three seconds. The loop no longer reads commands once it has
broken, so a StreamCmd::Shutdown the session sent in that window never
reached the stream task; the task ran on until the guard dropped. Drop the
guard right after the loop. The stream task's shutdown needs nothing of the
connection (it reports to the session's channels), so nothing relied on the
late drop.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 18:04:34 +03:00
faumarayandClaude Sonnet 5.5 ac4464db7b Format the voelinctl stream watcher with rustfmt 1.94
The stream-types commit shortened a let-chain in tools/voelinctl/src/engine.rs
that rustfmt 1.94 (the CI toolchain) lays out differently from nightly.
`cargo fmt --check` over scripts/own-crates.sh now passes on 1.94.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 18:02:30 +03:00
faumarayandClaude Sonnet 5.5 6c1898bf5a Put the voice source behind a ServerLink
The session no longer spawns the TeamSpeak connection itself. link.rs adds
ServerLink (spawn(options, ctx, cmds, events)) with LinkCmd and LinkEvent,
VoiceCmd and VoiceEvent moved and renamed, plus ConnectOptions (VoiceOptions
stays as its name for the app), LinkCtx and Remote. TsLink (ts_link.rs) is
the TeamSpeak implementation and the engine's default; Engine::start_with_link
takes another.

The stream task moves inside the connection: voice.rs spawns it when the
server has streams, feeds it the server's notifications and the clients'
channels, and sends its requests. The session reaches it only through
LinkCmd::Stream(StreamCmd) and hears of our own stream (OwnStream) and the
audio of watched streams (StreamAudio) as link events, so the link holds no
handle on the audio thread. stream.rs keeps its tests, adapted to the split
of StreamInput into StreamCmd and the link-private input.

tests/link_fake.rs drives the session with an in-memory link: connect,
presence, commands, a message sent and echoed, a message that comes twice,
history, and a replaced connection, without a TeamSpeak crate. The
architecture doc describes ServerLink and the planned move of TsLink to
VoelinGateWay and the QUIC link of VoelinProtocol.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 15:54:08 +03:00
faumarayandClaude Sonnet 5.5 da372dfe10 Give the stream API core-owned types
Command and Event no longer carry voelin-stream's types. voelin-core owns
StreamInfo, ViewerInfo, StreamSetup, StreamKind, ViewerState, EndReason and
LeaveReason (stream_types.rs) with u16 client ids, a viewer's SRTP profile
as its name and its codec as voelin_media::Codec; stream.rs converts at the
boundary. Command::SetSrtpProfiles takes profile names, which the stream
task parses.

EncodedFrame, LayerSpec, LayerId and LayerSet move into voelin-media
(stream::EncodedFrame, layer); voelin-stream depends on it and re-exports
them, so the engine, the stream sessions and voelinctl share one type. The
crate is now a plain dependency of voelin-core (feature media keeps the
module and WHIP), and its str0m feature is gone with str0m always there.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 15:01:24 +03:00
faumarayandClaude Sonnet 5.5 b0f95a384f Take ServerFlavor out of the engine API
Event::ServerInfo carried voelin_model::ServerFlavor, a TeamSpeak notion. It
now carries backend: BackendInfo { product, version } (plain strings, with
label() for a sentence) next to the capabilities. The voice source decides
the flavor from the version string (voice.rs backend_of) and puts the
backend and capabilities in VoiceEvent::Connected; session.rs forwards them
and no longer classifies anything.

The UI reads backend.product for a server's chip (ServerItem.flavor becomes
product, as does the session view's field) and backend.label() for the
"Connected to ..." status line; the sample data builds its own backend and
the TeamSpeak 6 capabilities, pinned against the flavor's by a test.
voelinctl's engine mode prints the label. ServerFlavor stays in voelin-model
for the gateway and the voice source.

Shown text is unchanged. New tests: the voice source's backend for TS3, TS6
and an unrecognised version, BackendInfo::label, the status line, the sample
servers' backends, and the server item's product.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 13:59:20 +03:00
faumarayandClaude Sonnet 5.5 df7be67d4c Move voice packet types into voelin-audio
voelin-audio no longer depends on tsclientlib or tsproto-packets. Its
boundary is now plain types in packet.rs: TalkerId, VoiceCodec, VoicePacket
(talker, seq, codec, whisper, payload) and EncodedVoice (codec, payload; an
empty payload ends the transmission). The jitter buffer moves from
tsclientlib::audio into jitter.rs and reads VoicePacket fields; the encoder
returns EncodedVoice and the mixer is keyed by TalkerId.

In voelin-core, voice.rs is the only place that wraps EncodedVoice into a
TeamSpeak audio packet and reads one into a VoicePacket (codecs other than
Opus are dropped there, where the jitter buffer rejected them before);
audio.rs and session.rs work on the new types. voelinctl converts at its
own edge. Behaviour is unchanged: the one-hour drift simulation gives the
same latencies as before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 13:06:46 +03:00
321 changed files with 89370 additions and 15023 deletions

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
name: mao-designer
description: Produces designs and acceptance criteria for a task, and handles escalations from mao-implementer after 3 failed attempts. Use before delegating non-trivial work and whenever an implementation is stuck.
model: opus
effort: max
effort: xhigh
---
You are **mao-designer**, the design and escalation role of the Voelin
+1 -1
View File
@@ -2,7 +2,7 @@
name: mao-opus-reviewer
description: Final, fresh and independent review of substantive code changes for correctness, architecture and unresolved risks. Reports concrete defects; does not fix code. Use after the sonnet review, in a new agent, never in the design agent's conversation.
model: opus
effort: max
effort: xhigh
tools: Read, Grep, Glob, Bash
---
+2 -1
View File
@@ -1,5 +1,6 @@
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"model": "fable",
"effortLevel": "xhigh"
"effortLevel": "xhigh",
"maxEffortLevel": "xhigh"
}
+4
View File
@@ -2,6 +2,10 @@
# the sources only. Builds keep target/ in cache mounts, never in the context.
.git
.claude
# The per-developer .cargo/config.toml (docs/building.md, a [patch] to a sibling
# VoelinProtocol checkout): never part of a build. Only the root one; the
# committed third_party/dimpl/.cargo stays.
.cargo
target
dist
fuzz/target
+29 -22
View File
@@ -1,26 +1,21 @@
name: Linux checks
description: Shared Linux validation for Gitea CI and release packaging.
description: >
Linux validation for Gitea CI: formatting, Clippy, the build, the tests, the
dependency policy, the third-party notices and the release tooling tests. It
runs after the job has fetched every dependency (the steps before it in
.gitea/workflows/ci.yml: system packages, the Rust toolchain and `cargo fetch`
with the read-only deploy key for the private VoelinProtocol repository) and
has deleted the key (docs/ci.md, "VoelinProtocol access"). This action has no
input and no secret, and every cargo command in it is --offline (or has
CARGO_NET_OFFLINE set where a script or a plugin starts cargo): it needs no key
and cannot use one, so the build scripts, procedural macros and tests it runs
hold none.
runs:
using: composite
steps:
- uses: ./.github/actions/system-deps
- name: Install pinned Rust toolchain
run: |
set -euo pipefail
export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}"
export PATH="$CARGO_HOME/bin:$PATH"
if ! command -v rustup >/dev/null 2>&1; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | \
sh -s -- -y --profile minimal --default-toolchain none
fi
if [[ -f "$CARGO_HOME/env" ]]; then
# shellcheck source=/dev/null
source "$CARGO_HOME/env"
fi
echo "$CARGO_HOME/bin" >> "$GITHUB_PATH"
rustup toolchain install
shell: bash
- name: rustfmt (own crates)
env:
CARGO_NET_OFFLINE: "true"
run: |
set -euo pipefail
packages=$(scripts/own-crates.sh)
@@ -28,33 +23,45 @@ runs:
cargo fmt "${packages[@]}" --check
shell: bash
- name: clippy (own crates, deny warnings)
env:
CARGO_NET_OFFLINE: "true"
run: |
set -euo pipefail
packages=$(scripts/own-crates.sh)
read -r -a packages <<< "$packages"
cargo clippy "${packages[@]}" --all-targets --no-deps --locked -- -D warnings
cargo clippy "${packages[@]}" --all-targets --no-deps --locked --offline -- -D warnings
shell: bash
- name: clippy (workspace, report warnings)
run: cargo clippy --workspace --all-targets --locked
run: cargo clippy --workspace --all-targets --locked --offline
shell: bash
- name: Build
run: cargo build --workspace --all-targets --locked
run: cargo build --workspace --all-targets --locked --offline
shell: bash
- name: Test (X11 enabled)
run: |
# DISPLAY is assigned by xvfb-run, then expanded by the inner shell.
# shellcheck disable=SC2016
xvfb-run -a bash -c 'VOELIN_X11_TEST_DISPLAY="$DISPLAY" cargo test --workspace --locked'
xvfb-run -a bash -c 'VOELIN_X11_TEST_DISPLAY="$DISPLAY" cargo test --workspace --locked --offline'
shell: bash
- name: Install cargo-deny and cargo-about
# The only cargo commands here that go online: they download two tools from
# crates.io and build them. They read no manifest of this workspace and
# nothing in the job gives them a key.
run: |
cargo install cargo-deny --locked --version 0.20.2
cargo install cargo-about --locked --version 0.9.2 --features cli
shell: bash
- name: Dependency policy
# cargo-deny's own --offline would also stop it from fetching the RustSec
# advisory database, which the check needs (from github.com, no key).
# CARGO_NET_OFFLINE keeps only the `cargo metadata` it runs offline.
env:
CARGO_NET_OFFLINE: "true"
run: cargo deny --locked --workspace check
shell: bash
- name: Third-party notices
env:
CARGO_NET_OFFLINE: "true"
run: scripts/notices.sh --check
shell: bash
- name: Release tooling regressions
+11
View File
@@ -0,0 +1,11 @@
# SSH host key of git.faumaray.com (Gitea's built-in SSH server, which offers an
# RSA host key only). Fingerprint SHA256:fugBYnqAnqmTLsGpafVgQF9gPQzJqps7uHvs48blg2A,
# recorded on 2026-10-24 with `ssh-keyscan -t rsa git.faumaray.com`.
#
# Committed, never fetched while a job runs, so a CI or release build trusts the
# key reviewed here and not whatever answers on the network at that moment.
# Read in place by ssh (-o UserKnownHostsFile, in the command line that the fetch
# step of .gitea/workflows/ci.yml gives git: nothing is appended to ~/.ssh) and
# COPYed by docker/*.Dockerfile and crates/voelin-gateway/Dockerfile. How to
# re-check it and how to rotate it: docs/ci.md, "VoelinProtocol access".
git.faumaray.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==
+246 -1
View File
@@ -1,7 +1,22 @@
name: CI
# Linux checks for Gitea act_runner; runner setup and scope: docs/ci.md.
# Off for pushes and pull requests: run by hand only.
# Runs on pushes to main and on pull requests (not when only docs or Markdown
# files change, apart from THIRD_PARTY_NOTICES.md), and by hand.
#
# The workspace depends on the private VoelinProtocol repository over SSH, so
# the job needs the read-only deploy key (the repository secret
# VOELIN_PROTOCOL_DEPLOY_KEY). The key exists for one step only: "Fetch the
# dependencies" runs `cargo fetch` with it, before any build script, procedural
# macro or test of the repository has run, and deletes it again. Everything after
# that (the composite action .gitea/actions/checks) runs `--offline` in a job that
# holds no key. docs/ci.md, "VoelinProtocol access", has the whole story; the
# order of the steps is part of it:
#
# 1. check that this job may hold the key (the runner, the pull request's head)
# 2. system packages and the Rust toolchain (no key yet)
# 3. install the key into a directory of its own, 4. fetch with it and delete it
# 5. delete it again whatever happened, 6. the checks, offline
on:
push:
branches: ["main"]
@@ -20,15 +35,245 @@ on:
env:
CARGO_TERM_COLOR: always
# Cargo fetches the private VoelinProtocol dependency with the system git and
# ssh, whose command line the fetch step sets (docs/ci.md, "VoelinProtocol
# access"); Cargo's own git client could not use that key file.
CARGO_NET_GIT_FETCH_WITH_CLI: "true"
jobs:
linux:
name: Linux checks
runs-on: ubuntu-24.04
timeout-minutes: 180
env:
# 'yes' unless this run is a pull request whose head branch lives in
# another repository. For a pull request Gitea's event payload has
# github.event.pull_request.head.repo.full_name, the repository that holds
# the branch to be merged: this repository (equal to github.repository)
# for a branch pushed here, the fork's own name for a fork. Any other
# event (push, workflow_dispatch) has no pull request and the first
# operand is true at once. An absent or unequal name reads 'no', and the
# check below treats everything but 'yes' as no. The check asks the same
# question again in its script, from the head repository's name itself.
VOELIN_PR_HEAD_HERE: ${{ (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && 'yes' || 'no' }}
defaults:
run:
shell: bash
steps:
- uses: https://github.com/actions/checkout@v4
# A runner prints the `env:` of a step in the job log when the step starts,
# and the runner "gitea-runner-docker" v0.6.1 printed a multi-line secret
# there in clear (the deploy keys of all four repositories, 2026-10-27; they
# were rotated the next day). Both runners carry the same labels, so
# `runs-on` cannot keep the job off it. What the workflow can do is not to
# start the step that declares the secret on such a runner, and not to give
# the secret to a fork's pull request: this step decides, before any step
# names the secret, and writes the one positive flag that the key step asks
# for. Without the flag the job stops here: the key is not optional (nothing
# builds without voelin-identity), and a green job that checked nothing
# would be worse than a red one that says why.
- name: Check that this job may hold the VoelinProtocol deploy key
env:
# The oldest runner version known to mask a multi-line secret in the
# log. Lower it only after a canary secret has been shown masked on
# that runner (docs/ci.md, "VoelinProtocol access"). release.yml has
# the same line.
MIN_MASKING_RUNNER_VERSION: 3.1.0
PR_HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
run: |
set -euo pipefail
version="${GITEA_ACTIONS_RUNNER_VERSION:-}"
name="${RUNNER_NAME:-an unnamed runner}"
problems=()
masks=no
if [[ "$version" =~ ^v?([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
oldest="$(printf '%s\n%s\n' "$MIN_MASKING_RUNNER_VERSION" "${BASH_REMATCH[1]}" | sort -V | head -n 1)"
if [[ "$oldest" == "$MIN_MASKING_RUNNER_VERSION" ]]; then
masks=yes
echo "Runner $name reports version $version, which masks secrets in the log (at least $MIN_MASKING_RUNNER_VERSION)."
fi
fi
if [[ "$masks" != yes ]]; then
problems+=("the runner ($name) reports version '${version:-none}', and only a runner of version $MIN_MASKING_RUNNER_VERSION or newer is known to keep the deploy key out of the job log (gitea-runner-docker v0.6.1 printed it in clear). Run the job again: it may be given another runner")
fi
# The pull request's head. The job-level expression has answered in
# VOELIN_PR_HEAD_HERE; the answer is asked for again here, from the
# head repository's name and the repository's, so that a mistake in
# one of the two places does not hand the key to a fork's code. A pull
# request (any event whose name starts with pull_request, or any event
# that carries a head repository) passes only with a head repository
# that is named and is this repository.
head_here=yes
[[ "${VOELIN_PR_HEAD_HERE:-}" == yes ]] || head_here=no
case "${GITHUB_EVENT_NAME:-}" in
pull_request*) pull_request=yes ;;
*) pull_request=no ;;
esac
[[ -z "${PR_HEAD_REPO:-}" ]] || pull_request=yes
if [[ "$pull_request" == yes ]]; then
if [[ -z "${PR_HEAD_REPO:-}" || "$PR_HEAD_REPO" != "${GITHUB_REPOSITORY:-}" ]]; then
head_here=no
fi
fi
if [[ "$head_here" == yes ]]; then
if [[ "$pull_request" == yes ]]; then
echo "Event ${GITHUB_EVENT_NAME:-unknown}: the pull request's head is in $PR_HEAD_REPO, which is this repository, not a fork."
else
echo "Event ${GITHUB_EVENT_NAME:-unknown}: no pull request, the code is this repository's own."
fi
else
problems+=("the pull request's head repository is '${PR_HEAD_REPO:-unknown}', and this repository is ${GITHUB_REPOSITORY:-unknown}, so it is a fork's pull request (or the event did not say where the head is), and the key is not given to a fork's code. Push the branch to ${GITHUB_REPOSITORY:-this repository} to have it checked")
fi
if ((${#problems[@]})); then
for problem in "${problems[@]}"; do
echo "::error::The VoelinProtocol deploy key is not given to this job: $problem." >&2
done
echo "::error::The job stops here: the workspace cannot be built without the private VoelinProtocol repository (docs/ci.md, VoelinProtocol access)." >&2
exit 1
fi
echo "VOELIN_KEY_ALLOWED=yes" >> "$GITHUB_ENV"
# Native libraries and tools (apt), the same action as GitHub CI. The job
# image has git and the OpenSSH client; the key step checks for ssh.
- uses: ./.github/actions/system-deps
- name: Install pinned Rust toolchain
run: |
set -euo pipefail
export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}"
export PATH="$CARGO_HOME/bin:$PATH"
if ! command -v rustup >/dev/null 2>&1; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | \
sh -s -- -y --profile minimal --default-toolchain none
fi
if [[ -f "$CARGO_HOME/env" ]]; then
# shellcheck source=/dev/null
source "$CARGO_HOME/env"
fi
echo "$CARGO_HOME/bin" >> "$GITHUB_PATH"
rustup toolchain install
# The key, as late as it can be: after the packages and the toolchain have
# been installed, right before the one step that uses it.
- name: Install the VoelinProtocol deploy key
# Both lines below ask for the positive flag of the check above. On a
# runner that is not known to mask the secret (or whose expression context
# does not hold what an earlier step wrote to GITHUB_ENV) the flag reads
# empty: the step is not started, so it prints no header, and the
# expression is empty as well, in case a runner prints a header anyway.
# The key reaches the step through the environment only: never in the
# script text, never echoed, no `set -x`. A pull request from a fork gets
# no secrets from Gitea and fails the check above before it gets here.
if: env.VOELIN_KEY_ALLOWED == 'yes'
env:
PROTOCOL_DEPLOY_KEY: ${{ env.VOELIN_KEY_ALLOWED == 'yes' && secrets.VOELIN_PROTOCOL_DEPLOY_KEY || '' }}
run: |
set -euo pipefail
umask 077
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
echo "::error::The VoelinProtocol deploy key is empty. Set the repository secret VOELIN_PROTOCOL_DEPLOY_KEY to the private key of the read-only deploy key on Voelin/VoelinProtocol (docs/ci.md, VoelinProtocol access)." >&2
exit 1
fi
for tool in ssh ssh-keygen; do
command -v "$tool" > /dev/null || {
echo "::error::The job image needs the OpenSSH client: $tool is missing." >&2
exit 1
}
done
[[ -s "$GITHUB_WORKSPACE/.gitea/known_hosts" ]] || {
echo "::error::.gitea/known_hosts is missing from the checkout." >&2
exit 1
}
# A directory of this job's own (mode 0700, a name that nothing else
# uses, so a host runner that keeps its temporary directory between
# jobs does not share it). On any way out of this step but the last
# line, the step removes it itself; the directory is left only for the
# fetch step, which removes it in turn. Its name goes to the later
# steps first, so that the cleanup step finds it even if this step is
# killed.
key_dir="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/voelin-protocol-key.XXXXXX")"
installed=
trap '[[ -n "$installed" ]] || rm -rf "$key_dir"' EXIT
echo "VOELIN_PROTOCOL_KEY_DIR=$key_dir" >> "$GITHUB_ENV"
key_file="$key_dir/id"
# Whatever the secret store did to the line ends and the final newline,
# OpenSSH needs LF lines, the BEGIN line first and a newline at the end.
printf '%s\n' "$PROTOCOL_DEPLOY_KEY" | tr -d '\r' | sed '/^[[:space:]]*$/d' > "$key_file"
unset PROTOCOL_DEPLOY_KEY
chmod 600 "$key_file"
if ! public=$(ssh-keygen -y -f "$key_file" < /dev/null); then
echo "::error::VOELIN_PROTOCOL_DEPLOY_KEY is not an unencrypted OpenSSH or PEM private key." >&2
exit 1
fi
# The fingerprint of the public half, to compare with the deploy key in
# the VoelinProtocol settings.
printf 'Deploy key installed: %s\n' "$(ssh-keygen -lf - <<< "$public")"
echo "VOELIN_PROTOCOL_KEY=installed" >> "$GITHUB_ENV"
installed=1
# The only step that uses the key, and the only place that sets
# GIT_SSH_COMMAND: not in GITHUB_ENV, so no later step has it.
- name: Fetch the dependencies with the deploy key
run: |
set -euo pipefail
if [[ "${VOELIN_PROTOCOL_KEY:-}" != installed || -z "${VOELIN_PROTOCOL_KEY_DIR:-}" ]]; then
echo "::error::The deploy key was not installed by the step before (the check at the start of the job or the key step did not pass its flag on)." >&2
exit 1
fi
key_dir="$VOELIN_PROTOCOL_KEY_DIR"
key_file="$key_dir/id"
# On every way out of this step, a failed fetch included.
trap 'rm -rf "$key_dir"' EXIT
[[ -f "$key_file" ]] || { echo "::error::The deploy key file is missing." >&2; exit 1; }
# The system git runs this ssh command, so the key and the host key are
# named outright and nothing in ~/.ssh or /etc/ssh is read: -F /dev/null
# leaves out every ssh config file, -i with IdentitiesOnly and no agent
# offers this one key, and the only host key accepted is the reviewed
# line in .gitea/known_hosts, never one fetched now (a changed or unknown
# host key fails rather than asks). The paths are absolute: Cargo runs
# git in its own directory under CARGO_HOME, not in the checkout.
export GIT_TERMINAL_PROMPT=0
export GIT_SSH_COMMAND="ssh -F /dev/null -i '$key_file' -o IdentitiesOnly=yes -o IdentityAgent=none -o UserKnownHostsFile='$GITHUB_WORKSPACE/.gitea/known_hosts' -o GlobalKnownHostsFile=/dev/null -o StrictHostKeyChecking=yes -o BatchMode=yes -o ConnectTimeout=30"
# The first thing that touches the server with the key, so that a wrong
# key or a changed host key fails here with a clear message and not
# minutes later inside Cargo.
if ! timeout 120 git ls-remote --exit-code \
ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git HEAD > /dev/null; then
echo "::error::git cannot read Voelin/VoelinProtocol over SSH with the deploy key. 'Permission denied (publickey)' above: the key is not registered on that repository (or is not the one in VOELIN_PROTOCOL_DEPLOY_KEY). 'Host key verification failed': .gitea/known_hosts no longer matches the server (docs/ci.md, VoelinProtocol access)." >&2
exit 1
fi
echo "Voelin/VoelinProtocol is readable with the deploy key."
# Cargo reads the manifests and Cargo.lock and downloads every package
# of the lock file (all targets: cargo deny and cargo about, later, read
# the whole graph). It runs no build script, procedural macro or test
# of the repository. Nothing else in the job needs the key: every later
# cargo command is --offline.
cargo fetch --locked
unset GIT_SSH_COMMAND
rm -rf "$key_dir"
[[ ! -e "$key_dir" ]] || { echo "::error::The deploy key could not be removed from the job." >&2; exit 1; }
echo "The deploy key is removed from the job."
# Whatever happened to the two steps above (a failed fetch, a key that was
# installed and never fetched with, a cancelled job), the key is gone before
# the checks start. Idempotent: the fetch step has already removed it.
- name: Delete the deploy key
if: always()
run: |
set -euo pipefail
key_dir="${VOELIN_PROTOCOL_KEY_DIR:-}"
if [[ -n "$key_dir" && -e "$key_dir" ]]; then
rm -rf "$key_dir"
[[ ! -e "$key_dir" ]] || { echo "::error::The deploy key could not be removed from the job." >&2; exit 1; }
echo "The deploy key is removed from the job."
else
echo "No deploy key is left in the job."
fi
{
echo "VOELIN_PROTOCOL_KEY_DIR="
echo "VOELIN_PROTOCOL_KEY="
} >> "$GITHUB_ENV"
# Formatting, Clippy, build, tests, dependency policy, notices: all
# offline, in a job that holds no key (docs/ci.md, "VoelinProtocol access").
- uses: ./.gitea/actions/checks
+97 -1
View File
@@ -32,6 +32,81 @@ jobs:
docker info >/dev/null
# Remove only output owned by this workflow in its checkout.
rm -rf dist
# The workspace depends on the private VoelinProtocol repository over SSH
# (docs/ci.md, "VoelinProtocol access"). The Docker builds fetch it with an
# ssh-agent (`docker build --ssh default`): the key lives in the agent's
# memory, never on disk and never in an image layer, and only the
# `cargo fetch` of each Dockerfile is given the agent (the build that
# follows is --offline and has no ssh mount, so the build scripts and
# procedural macros run without the key). The agent is stopped by the step
# right after the last build, whatever the builds did; the lifetime below
# ends the key anyway if the runner dies first.
#
# A runner prints the `env:` of a step in the job log when the step starts,
# and the runner "gitea-runner-docker" v0.6.1 printed a multi-line secret
# there in clear (2026-10-27; the keys were rotated the next day). It
# carries the same labels as the release runner, so `runs-on` cannot keep
# the job off it: this step decides, before any step names the secret, and
# writes the one positive flag that the agent step asks for. Without the
# flag the job stops here (no package can be built without voelin-identity).
# ci.yml has the same step, with the check of a pull request's head repository
# that a release (tags and manual runs only) does not need.
- name: Check that this runner may hold the VoelinProtocol deploy key
env:
# The oldest runner version known to mask a multi-line secret in the
# log. Lower it only after a canary secret has been shown masked on
# that runner (docs/ci.md, "VoelinProtocol access"). ci.yml has the
# same line.
MIN_MASKING_RUNNER_VERSION: 3.1.0
run: |
set -euo pipefail
version="${GITEA_ACTIONS_RUNNER_VERSION:-}"
name="${RUNNER_NAME:-an unnamed runner}"
if [[ "$version" =~ ^v?([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
oldest="$(printf '%s\n%s\n' "$MIN_MASKING_RUNNER_VERSION" "${BASH_REMATCH[1]}" | sort -V | head -n 1)"
if [[ "$oldest" == "$MIN_MASKING_RUNNER_VERSION" ]]; then
echo "Runner $name reports version $version, which masks secrets in the log (at least $MIN_MASKING_RUNNER_VERSION)."
echo "VOELIN_KEY_ALLOWED=yes" >> "$GITHUB_ENV"
exit 0
fi
fi
echo "::error::The VoelinProtocol deploy key is not given to this job: the runner ($name) reports version '${version:-none}', and only a runner of version $MIN_MASKING_RUNNER_VERSION or newer is known to keep the deploy key out of the job log (gitea-runner-docker v0.6.1 printed it in clear). Run the job again: it may be given another runner." >&2
echo "::error::The job stops here: no package can be built without the private VoelinProtocol repository (docs/ci.md, VoelinProtocol access)." >&2
exit 1
- name: Start ssh-agent with the VoelinProtocol deploy key
# Both lines below ask for the positive flag of the check above: on a
# runner that is not known to mask the secret (or whose expression context
# does not hold what an earlier step wrote to GITHUB_ENV) the step is not
# started and the expression is empty as well, in case a runner prints a
# header anyway. The key reaches the step through the environment only:
# never in the script text, never echoed, no `set -x`.
if: env.VOELIN_KEY_ALLOWED == 'yes'
env:
PROTOCOL_DEPLOY_KEY: ${{ env.VOELIN_KEY_ALLOWED == 'yes' && secrets.VOELIN_PROTOCOL_DEPLOY_KEY || '' }}
run: |
set -euo pipefail
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
echo "::error::The repository secret VOELIN_PROTOCOL_DEPLOY_KEY is missing or empty. It holds the private key of the read-only deploy key on Voelin/VoelinProtocol (docs/ci.md, VoelinProtocol access)." >&2
exit 1
fi
for tool in ssh-agent ssh-add; do
command -v "$tool" > /dev/null || { echo "::error::The runner needs the OpenSSH client: $tool is missing." >&2; exit 1; }
done
eval "$(ssh-agent -s -t 32400)" > /dev/null
started=
trap '[[ -n "$started" ]] || ssh-agent -k > /dev/null' EXIT
# LF lines and one final newline, whatever the secret store did.
printf '%s\n' "$PROTOCOL_DEPLOY_KEY" | tr -d '\r' | sed '/^[[:space:]]*$/d' | ssh-add -q -
unset PROTOCOL_DEPLOY_KEY
# The fingerprint of the public half, to compare with the deploy key.
ssh-add -l
{
echo "SSH_AUTH_SOCK=$SSH_AUTH_SOCK"
echo "SSH_AGENT_PID=$SSH_AGENT_PID"
# Only an agent this job started is stopped at the end.
echo "VOELIN_AGENT_STARTED=1"
} >> "$GITHUB_ENV"
started=1
- name: Linux packages
run: scripts/docker-build.sh linux --progress=plain
- name: Windows packages (MinGW)
@@ -77,9 +152,30 @@ jobs:
set -euo pipefail
version=$(sed -n 's/^version = "\(.*\)"$/\1/p' crates/voelin-gateway/Cargo.toml | head -n 1)
test -n "$version"
docker build -f crates/voelin-gateway/Dockerfile -t "tsgw:$version" -t tsgw:latest .
DOCKER_BUILDKIT=1 docker build --ssh default -f crates/voelin-gateway/Dockerfile -t "tsgw:$version" -t tsgw:latest .
mkdir -p dist/gateway
docker save "tsgw:$version" tsgw:latest | gzip > dist/gateway/tsgw-image.tar.gz
# Right after the builds, the only steps that use the agent, and whatever
# they did (a failed build, a cancelled job): the steps after this one
# (the artifact upload, the release draft with its token) have neither the
# key nor the socket.
- name: Stop the ssh-agent
if: always()
run: |
if [[ -n "${VOELIN_AGENT_STARTED:-}" && -n "${SSH_AGENT_PID:-}" ]]; then
if ssh-agent -k > /dev/null; then
echo "The ssh-agent with the deploy key is stopped."
else
echo "::warning::ssh-agent -k failed; the agent ends by itself when its lifetime (nine hours) is over." >&2
fi
else
echo "No ssh-agent of this job is running."
fi
{
echo "SSH_AUTH_SOCK="
echo "SSH_AGENT_PID="
echo "VOELIN_AGENT_STARTED="
} >> "$GITHUB_ENV"
- name: Collect packages and checksums
run: |
set -euo pipefail
+3 -2
View File
@@ -16,7 +16,8 @@ runs:
- name: apt packages
if: runner.os == 'Linux'
shell: bash
# ALSA (audio devices), fontconfig + xkbcommon (UI), libvpx + dav1d
# ALSA (audio devices), fontconfig + xkbcommon (UI), xkbcommon-x11 + xcb (linked
# by the GPUI front end), libvpx + dav1d
# (video codecs), PipeWire + SPA (screen and audio capture), libclang
# (bindgen), Xvfb (X11 tests).
run: |
@@ -27,7 +28,7 @@ runs:
"${sudo[@]}" apt-get update
"${sudo[@]}" apt-get install -y --no-install-recommends \
build-essential ca-certificates cmake curl git jq pkg-config python3 \
libasound2-dev libfontconfig1-dev libxkbcommon-dev \
libasound2-dev libfontconfig1-dev libxkbcommon-dev libxkbcommon-x11-dev libxcb1-dev \
libvpx-dev libdav1d-dev libpipewire-0.3-dev libspa-0.2-dev libclang-dev \
xvfb xauth
+3
View File
@@ -1,3 +1,6 @@
/target/
/dev/.state/
/dist/
/.cargo/
# agent scratch of a worktree (the MAO policy in CLAUDE.md)
/.scratch/
+125
View File
@@ -8,6 +8,69 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
### Added
- `voelin-gpui`, the GPUI front end of the desktop app, in its first form: a
window fed by the same engine and the same view models as the Slint app
(`cargo run -p voelin-gpui --release`), in the Voelin theme: every colour,
radius, size and type token of the Slint app's `theme.slint`, light and dark
(a test reads the Slint file and fails when the two differ), written into
the widget library's theme too, in Inter, with the Slint app's Lucide icons.
`system` mode follows the window's appearance. `VOELIN_OPEN=swatch` shows
every token, a few widgets and the icons (`VOELIN_DEV_THEME`,
`VOELIN_FONT_SCALE`, `VOELIN_WINDOW_SIZE`; screenshots with
`scripts/gpui-shot.sh`, docs/ui/). `VOELIN_METER=1` logs what it costs once a
second: the CPU by group of threads, the memory and its own counters. A
window that cannot open (no driver, no display server) ends the app with
the reason and exit status 1. The Slint app (`voelin`) is unchanged and
stays the app; both run on one engine until the GPUI one reaches parity
(docs/ui.md). It needs Vulkan or OpenGL at run time (Mesa's lavapipe renders
in software); no package ships it yet.
- The GPUI front end's desktop shell: the server rail, the top bar, the
sidebar and the main area, on the client's own database (the servers saved in
the Slint app are there, and the other way round). Add, edit, select and
remove a server, connect and disconnect voice, mute the microphone and the
sound, hold to talk and copy an invite link, as in the Slint app; the window's
title names the server on screen, and its size and whether it was maximized
are kept for the next run (setting `ui.window`; on X11 the window is
maximized once it is shown, not before the window manager has it, and a
resize made before it answers is kept). The chat and the other pages are the
next slices; the search and the settings buttons only log that.
`VOELIN_DEMO_UI=1` shows the Slint app's sample servers without sending or
keeping anything (docs/ui.md, "The desktop shell").
- The GPUI front end's channel tree and members panel. The server on screen's
channels nest in the sidebar with their spacers, icons, banners (under a veil
that keeps the names readable on any picture), locks and counts, and the
people in them with their badges and marks; a click selects a channel, a
double-click joins it (a locked one asks for its password: Enter joins, and
Escape closes the prompt), the chevron folds it, a right-click offers the
same, and what is folded and selected is kept for each server (setting
`ui.tree`). The panel on the right lists everyone on the server in sections,
with a search; a click on a person opens their card. A person who starts or
stops talking is marked in the tree (the ring on their avatar and the bars on
their row, as in the Slint app) and the members panel, which are redrawn for
it and nothing else of the window, and the pictures the engine writes again show
at once. `VOELIN_METER=1` counts the renders of each pane;
`VOELIN_DEMO_SERVER` and `VOELIN_DEMO_TALK` pick the sample server and make a
sample person talk (docs/ui.md, "The channel tree and the members").
- The GPUI front end's voice channel page and call bar. A server's Voice channel
button (or `VOELIN_OPEN=voice`) shows the channel we are in with its topic,
its banner and who is there: large avatars ringed green while they talk and
blue while they stream, with the marks of a microphone or sound that is off,
and under them the call bar (mute, deafen, share and the voice settings, which
only log until their pages come, and Leave). The smaller stage, one row of
small avatars centred while it fits and scrolling sideways when crowded, is
remembered and a window under 800 pixels tall always has it (the same setting
as the Slint app's); toggle icon buttons refresh their tooltips as soon as
their state flips. The sidebar's server card shows the server's banner, a
person's card has their volume and a mute for us, and the voice card says the
transmit mode when it is not push-to-talk. Hold to talk and the global
push-to-talk key (`Ctrl+Shift+T` by default, as in the Slint app, working
while another window has focus) track button and hotkey holds independently and
fail closed across voice drops (including drop and reconnect within one event
batch), window focus loss, leaving push-to-talk mode, switching or removing
servers, repeated portal activations across servers, desktop shortcut removal,
hotkey task exit, and window shutdown. A person's picture is round in its
avatar. `voelin-gpui` is still not the app (docs/ui.md, "The voice page and
the call bar").
- Log files: each run logs to `<state>/voelin/logs/voelin.log`, the previous
four runs are kept; `VOELIN_LOG` sets what is logged. Settings → Advanced
opens the folder.
@@ -69,6 +132,43 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
### Changed
- The desktop portals (screen capture and camera through PipeWire, the push to
talk shortcut, the file chooser and the proxy settings) talk to D-Bus through
ashpd on `async-io` instead of `tokio`. Nothing changes on screen; the GPUI
front end, which is being built, enables ashpd's `async-io` and ashpd cannot
have both. Every D-Bus connection of the apps, the desktop notifications'
included, now runs on an I/O thread of its own, whichever part of the app
asks first.
- The build needs Rust 1.95 (`rust-toolchain.toml` and the workspace's
`rust-version`; 1.95.0 was used to check it), up from 1.94: the GPUI
front end, which is being built, depends on a library that calls a function
stable since 1.95. Nothing changes in the apps; the gateway's Docker image
builds from `rust:1.95-bookworm`.
- The key store now keeps the device key when signing out of an account,
unbound, whether it was in use before the account or was made for it; "Forget
this device's identity" is the only way a key is deleted. The identity store
also reports a damaged TeamSpeak identity by the kind of damage and never
repeats its key in an error. Nothing changes on screen yet: accounts and
sign-in are later steps.
- The view models, the app's state, the state change of every engine event and
the decisions of the settings pages, the Stream Studio, the streams, the chat,
the servers, the audio settings page, the friends and the development
switches moved out of `voelin-ui` into a new crate, `voelin-ui-vm`, which
depends on no UI toolkit (a second front end can use it); `voelin-ui`
converts its plain rows into Slint's and keeps the window, the Bridge writes
and the engine's tasks. The chat formatting reader and the
Twemoji archive moved with them. Two things change on screen: the chat of
a server that is gone takes the colour of its title instead of opaque
black, and a cached avatar file cut after a valid header shows the
initials instead of a broken picture. See docs/ui.md, "Two crates".
- The identity store keeps identities of more than one kind (TeamSpeak, a Voelin
key, the signed-in account) with the account each belongs to, as a
`voelin-identity` key store, in two database migrations. Existing
databases migrate on first start and every identity stays what it was (kind
TeamSpeak, no account, same key, name, origin and default); nothing changes
on screen yet. The build now fetches `voelin-identity` from the private
VoelinProtocol repository, so a fresh checkout needs read access to it
(see docs/building.md).
- Selecting a server observes it through its gateway at once; the Observe
button is gone. The server dialog asks only for the address, password,
name and nickname: the gateway is found from the address.
@@ -168,6 +268,28 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
connections, so tsgw no longer earns a 600 second ban. It starts while
the TeamSpeak server is still down and connects once it is up, its
`/health` says what is missing, and it stops cleanly on SIGTERM.
- The client builds on VoelinProtocol's release `v0.2.0` (the tag, no longer a
commit) for `voelin-identity`, `voelin-proto` and `voelin-model`; nothing the
apps do changes. Two differences underneath: signing out of an account lists
a kept device key once (a key whose row carried a device-only binding was
listed twice), and the debug text of the protocol's messages (`Hello`,
`Welcome`, `Server`, `Channel`, `Member` and the others whose secrets
VoelinProtocol lists) shows `<redacted>` in place of a password or a token, so
a log line or a failed test that prints one does not show it.
- CI and the package builds give the VoelinProtocol deploy key only to the step
that fetches the sources. The CI job writes the key to a directory of its own
(no `~/.ssh` configuration), uses it for `cargo fetch` as `ssh -i` with the
committed host key, and deletes it right after and again in a step that always
runs; the formatting, Clippy, build, test and policy steps, which run the
repository's build scripts and tests, are `--offline` and run in a job without
the key. The Docker builds (Linux, Windows, Android and the gateway image)
fetch in a `RUN` with the ssh mount and build `--offline` without it, and the
release workflow stops its ssh-agent right after the last build. A job gives
the key only to a runner that reports version 3.1.0 or newer (the old runner
gitea-runner-docker v0.6.1 printed a multi-line secret in the job log; the
deploy key was replaced, id 7) and, on a pull request, only when its head
branch is in this repository; otherwise it stops with the reason. See
docs/ci.md, "VoelinProtocol access".
### Removed
@@ -180,6 +302,9 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
### Fixed
- A deleted identity key no longer stays in the database file: SQLite overwrites
what it deletes, and the log is truncated after a key is deleted (an identity
you delete, a key a sign-out deletes).
- Hover help in the Stream Studio (a source's error, the status details)
shows each time and closes when the pointer leaves; it showed only once,
and stayed open until a click.
+8 -2
View File
@@ -8,6 +8,12 @@ org `Voelin`; the current plan lives in the approved plan file referenced in
`cargo fmt` (hard tabs, `rustfmt.toml`) and `cargo clippy -D warnings` on the
project's own crates (`scripts/own-crates.sh`) green.
Two front ends run on one engine until the second reaches parity:
`crates/voelin-ui` (Slint, the `voelin` binary, the app today) and
`crates/voelin-gpui` (GPUI on an exactly pinned `gpui-kit`, the `voelin-gpui`
binary, under construction); `crates/voelin-ui-vm` holds what they share, the
view models and the state, with no UI toolkit (`docs/ui.md`).
## Hosting: Gitea, not GitHub
- The source of truth is **https://git.faumaray.com** (Gitea). Pull requests,
@@ -30,10 +36,10 @@ review, help) and does not delegate it again or spawn further orchestration.
| Agent | Model / effort | Job |
|---|---|---|
| main session | (settings) | **Orchestrator**: decomposes work, delegates, tracks progress and attempt counts, resolves escalations, reports results. Delegates implementation, investigation, testing and review rather than doing them inline. |
| `mao-designer` | opus / max | Designs, acceptance criteria, escalation handling |
| `mao-designer` | opus / xhigh | Designs, acceptance criteria, escalation handling |
| `mao-implementer` | sonnet / xhigh | Implements, runs checks, self-reviews; escalates after 3 failed attempts |
| `mao-sonnet-reviewer` | sonnet / xhigh | Fresh, independent implementation review |
| `mao-opus-reviewer` | opus / max | Fresh, final independent review of substantive code changes (correctness, architecture, unresolved risks) |
| `mao-opus-reviewer` | opus / xhigh | Fresh, final independent review of substantive code changes (correctness, architecture, unresolved risks) |
| `mao-helper` | haiku | Focused file searches, summaries, routine git operations within the user's authorization |
### Before delegating
Generated
+3764 -150
View File
File diff suppressed because it is too large. Load diff
+27 -3
View File
@@ -15,14 +15,15 @@ members = [
"crates/voelin-core",
"crates/voelin-gateway",
"crates/voelin-gateway-proto",
"crates/voelin-gpui",
"crates/voelin-media",
"crates/voelin-model",
"crates/voelin-observer",
"crates/voelin-platform",
"crates/voelin-query",
"crates/voelin-store",
"crates/voelin-stream",
"crates/voelin-ui",
"crates/voelin-ui-vm",
"tools/voelinctl",
]
default-members = [
@@ -36,23 +37,46 @@ default-members = [
"crates/voelin-core",
"crates/voelin-gateway",
"crates/voelin-gateway-proto",
"crates/voelin-model",
"crates/voelin-gpui",
"crates/voelin-observer",
"crates/voelin-platform",
"crates/voelin-query",
"crates/voelin-store",
"crates/voelin-stream",
"crates/voelin-ui",
"crates/voelin-ui-vm",
"tools/voelinctl",
]
[workspace.package]
edition = "2024"
rust-version = "1.94"
rust-version = "1.95"
license = "MIT OR Apache-2.0"
repository = "https://github.com/Faumaray/Voelin"
publish = false
[workspace.dependencies]
# The protocol repository is private (VoelinProtocol). This is the SSH URL its
# docs/development.md names, so that a per-developer .cargo/config.toml [patch]
# can point it at a sibling checkout (docs/building.md, "Working with a sibling
# VoelinProtocol checkout"). Pinned by the release tag (v0.2.0 is the first with the
# protocol crates; its README, "Releases", says how): the three crates below are at
# one tag, so the lock has one revision of each, and moving to a newer release means
# changing the `tag` of all three together (docs/building.md, "Depending on
# VoelinProtocol"). The account-bound KeyStore whose sign-out keeps every device key
# and the release of a device key, Phase 2 task 34, and the account types of the
# session seam are in it.
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
# The backend-neutral session seam (`voelin_proto::link`) and the v1 messages.
voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
# The UI-facing domain model and the client's replica of v1 entities.
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", tag = "v0.2.0" }
# GPUI, gpui-component and their assets for the GPUI front end (voelin-gpui). Pre-1.0:
# pinned exactly (it pins its `gpui-pre` snapshot exactly too), upgraded in commits of
# their own after rebuilding spikes/gpui on the new release (docs/design/gpui-spikes.md,
# "The version to pin").
gpui-kit = "=0.8.1"
[workspace.lints.rust]
# deny, not forbid: generated code (Slint) needs a local allow.
unsafe_code = "deny"
+11 -1
View File
@@ -28,7 +28,7 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
- `crates/proto/`: vendored tsclientlib, modernised (TS6 fields and stream
messages, faster off-thread Init1 puzzle, `curve25519-dalek` 4, fuzzing fixes;
see [UPSTREAM.md](crates/proto/UPSTREAM.md))
- `crates/voelin-model`: server flavor detection (TS3 / TS6) and capabilities
- `voelin-model` (from VoelinProtocol, a git dependency): domain model, server flavor detection (TS3 / TS6) and capabilities
- `crates/voelin-audio`: Opus voice encoding, framing, resampling, WAV, jitter buffer/mixer, cpal devices
- `crates/voelin-store`: SQLite store for identities, bookmarks, settings and chat history; keyring secrets
- `crates/voelin-query`: ServerQuery client over raw TCP, SSH and HTTP WebQuery (events, rate limiting, keepalive)
@@ -45,6 +45,14 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
(in the window and as a global hotkey), audio settings with a level meter, per-client volume, and on
TeamSpeak 6 streams: watch in a viewer, share the screen with sound. Desktop and phone layouts
from one design system, dark and light themes, text size, emoji ([docs/ui.md](docs/ui.md))
- `crates/voelin-ui-vm`: the view models and the app's state behind the UI, with no UI toolkit: engine state
as plain rows and forms, chat formatting, the Twemoji archive, and what the settings pages and the
Stream Studio decide; `voelin-ui` puts them on Slint windows ([docs/ui.md](docs/ui.md))
- `crates/voelin-gpui` (`voelin-gpui`): the GPUI front end, under construction, on the same engine and
view models as the Slint one, which stays the app until it reaches parity: a window with the engine's
state in one line, the Voelin theme (every token of the Slint one's `theme.slint`, light and dark, in
Inter with the same Lucide icons; `VOELIN_OPEN=swatch` shows them) and a cost meter (`VOELIN_METER=1`)
([docs/ui.md](docs/ui.md), "The GPUI front end")
- `crates/voelin-stream`: TeamSpeak 6 streams: stream commands and notifications, JSON signalling,
WebRTC peers (str0m) with host and STUN candidates. A live test streams VP8 + Opus between two
clients through a TS6 server
@@ -76,6 +84,8 @@ The UI (design system, desktop and phone layouts, emoji, how to add a screen) is
```sh
# Desktop app
cargo run -p voelin-ui --bin voelin
# The GPUI front end, under construction (Vulkan or OpenGL at run time)
cargo run -p voelin-gpui --release
# Local servers (use REGISTRY=mirror.gcr.io if Docker Hub rate-limits you)
docker compose -f dev/docker-compose.yml up -d
+3267 -50
View File
File diff suppressed because it is too large. Load diff
+9 -1
View File
@@ -3,13 +3,21 @@
<!-- From about-assets.md, appended by scripts/notices.sh. -->
The user interface bundles these assets (in crates/voelin-ui):
The user interface bundles these assets (in crates/voelin-ui, the Twemoji
archive in crates/voelin-ui-vm):
- Inter (the UI font), Copyright (c) 2016 The Inter Project Authors, under
the SIL Open Font License 1.1 (OFL-1.1; text below).
- Lucide icons (lucide-static 1.48.0), Copyright (c) Lucide Icons and
Contributors, under the ISC License; the icons derived from Feather are
Copyright (c) 2013-present Cole Bemis, under the MIT License (texts below).
- Lucide icons 1.43.0 (the 1,818 icons of the catalogue of gpui-kit-assets
0.8.1, embedded in the GPUI front end, crates/voelin-gpui, behind the
client's own set above), Copyright (c) Lucide Icons and Contributors, under
the ISC License; the icons derived from Feather are Copyright (c) 2013-present
Cole Bemis, under the MIT License (the same texts, below). The catalogue's
12 other icons are the crate's own, under its Apache-2.0 licence (listed with
the crates).
- Twemoji 15.0 (the emoji images): Twemoji graphics by Twitter, Inc and other
contributors, licensed under CC-BY 4.0
(https://creativecommons.org/licenses/by/4.0/). The SVG files are packed
+4
View File
@@ -23,6 +23,10 @@ accepted = [
"LicenseRef-Slint-Royalty-free-2.0",
# libbz2-rs-sys (unpacks Cisco's OpenH264 download in voelin-media).
"bzip2-1.0.6",
# The GPUI front end: 0BSD (enum-iterator, enum-iterator-derive) and CC0-1.0
# (notify 8, tiny-keccak); see deny.toml.
"0BSD",
"CC0-1.0",
]
# What the apps ship on: the desktop app on Linux (x86_64, and aarch64 for
+1 -5
View File
@@ -19,7 +19,7 @@ tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "sync", "
tracing = "0.1.44"
voelin-core = { path = "../voelin-core" }
# Channels and people for the voice notification.
voelin-model = { path = "../voelin-model" }
voelin-model = { workspace = true }
[target.'cfg(target_os = "android")'.dependencies]
anyhow = "1.0.104"
@@ -32,9 +32,5 @@ voelin-platform = { path = "../voelin-platform", default-features = false }
voelin-store = { path = "../voelin-store" }
voelin-ui = { path = "../voelin-ui" }
[dev-dependencies]
# Client ids of stream viewers in the tests.
tsclientlib = { path = "../proto/tsclientlib" }
[lints]
workspace = true
+3 -3
View File
@@ -194,7 +194,7 @@ fn connected(viewers: &[ViewerInfo]) -> usize {
mod tests {
use voelin_core::SessionState;
use voelin_core::stream::EndReason;
use voelin_model::{Capabilities, ChannelInfo, ClientInfo, ServerFlavor};
use voelin_model::{Capabilities, ChannelInfo, ClientInfo};
use super::*;
@@ -244,7 +244,7 @@ mod tests {
let info = Event::ServerInfo {
session: 1,
name: "Home".into(),
flavor: ServerFlavor::Unknown(String::new()),
backend: voelin_core::BackendInfo::default(),
capabilities: Capabilities::default(),
};
assert_eq!(fg.update_at(&info, 6).voice, notice("Connecting…", "Home", false, 0));
@@ -316,7 +316,7 @@ mod tests {
};
assert_eq!(fg.screen(), screen("Live in Chill Zone", "a server").flatten());
let viewer = |client, state| ViewerInfo {
client: tsclientlib::ClientId(client),
client,
state,
message: String::new(),
layer: None,
+1 -3
View File
@@ -1,7 +1,7 @@
[package]
name = "voelin-audio"
version = "0.1.0"
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices."
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices, independent of the voice transport."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
@@ -25,8 +25,6 @@ sonora-agc2 = "0.2"
sonora-simd = "0.2"
thiserror = "2.0.21"
tracing = "0.1.44"
tsclientlib = { path = "../proto/tsclientlib" }
tsproto-packets = { path = "../proto/tsproto-packets" }
[dev-dependencies]
serde_json = "1"
+43 -55
View File
@@ -1,45 +1,15 @@
//! Opus encoding into TeamSpeak voice packets.
//! Opus encoding of 20 ms frames into [`EncodedVoice`].
use opus2::{Application, Bitrate, Channels, Encoder};
use tsproto_packets::packets::{AudioData, CodecType, OutAudio, OutPacket};
use crate::pcm::{FRAME_SAMPLES, SAMPLE_RATE};
use crate::packet::{EncodedVoice, VoiceCodec};
use crate::pcm::SAMPLE_RATE;
use crate::{Error, Result};
/// Largest possible Opus packet.
const MAX_PACKET: usize = 1275;
/// The two Opus codecs TeamSpeak channels use.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VoiceCodec {
/// Mono, tuned for speech (`CodecType::OpusVoice`).
Voice,
/// Stereo, tuned for music (`CodecType::OpusMusic`).
Music,
}
impl VoiceCodec {
pub fn channels(self) -> usize {
match self {
VoiceCodec::Voice => 1,
VoiceCodec::Music => 2,
}
}
pub fn codec_type(self) -> CodecType {
match self {
VoiceCodec::Voice => CodecType::OpusVoice,
VoiceCodec::Music => CodecType::OpusMusic,
}
}
/// Samples (all channels) in one 20 ms frame.
pub fn frame_len(self) -> usize {
FRAME_SAMPLES * self.channels()
}
}
/// Encodes 20 ms frames of 48 kHz audio into voice packets.
/// Encodes 20 ms frames of 48 kHz audio into Opus packets.
pub struct VoiceEncoder {
encoder: Encoder,
codec: VoiceCodec,
@@ -53,7 +23,7 @@ impl VoiceEncoder {
VoiceCodec::Music => (Channels::Stereo, Application::Audio),
};
let mut encoder = Encoder::new(SAMPLE_RATE, channels, application)?;
// Survive some packet loss: TeamSpeak voice is plain UDP.
// Survive some packet loss: voice travels over unreliable datagrams.
encoder.set_inband_fec(true)?;
encoder.set_packet_loss_perc(5)?;
Ok(Self { encoder, codec, out: vec![0; MAX_PACKET] })
@@ -82,26 +52,25 @@ impl VoiceEncoder {
Ok(&self.out[..len])
}
/// Encode one frame into a packet ready for `Connection::send_audio`.
/// The connection assigns the packet id.
pub fn encode(&mut self, frame: &[f32]) -> Result<OutPacket> {
let codec = self.codec.codec_type();
let data = self.encode_to_bytes(frame)?;
Ok(OutAudio::new(&AudioData::C2S { id: 0, codec, data }))
/// Encode one frame for the transport to send. The transport assigns the
/// packet number.
pub fn encode(&mut self, frame: &[f32]) -> Result<EncodedVoice> {
let codec = self.codec;
let payload = self.encode_to_bytes(frame)?.to_vec();
Ok(EncodedVoice { codec, payload })
}
/// The empty packet that tells listeners the transmission ended.
pub fn end_of_stream(&self) -> OutPacket {
OutAudio::new(&AudioData::C2S { id: 0, codec: self.codec.codec_type(), data: &[] })
pub fn end_of_stream(&self) -> EncodedVoice {
EncodedVoice { codec: self.codec, payload: Vec::new() }
}
}
#[cfg(test)]
mod tests {
use tsproto_packets::packets::{Direction, InAudioBuf};
use super::*;
use crate::pcm;
use crate::packet::{TalkerId, VoicePacket};
use crate::pcm::{self, FRAME_SAMPLES};
/// Encode a tone, feed the packets through the mixer (jitter buffer +
/// decoder), and check the tone comes out.
@@ -112,15 +81,16 @@ mod tests {
let tone = pcm::sine(1000.0, 1.0, 0.5);
let mut decoded = Vec::new();
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
let data = encoder.encode_to_bytes(frame).unwrap().to_vec();
let packet = OutAudio::new(&AudioData::S2C {
id: i as u16,
codec: CodecType::OpusVoice,
from: 7,
data: &data,
});
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
mixer.handle_packet(tsclientlib::ClientId(7), packet).unwrap();
let sent = encoder.encode(frame).unwrap();
assert_eq!(sent.codec, VoiceCodec::Voice);
let packet = VoicePacket {
talker: TalkerId(7),
seq: i as u16,
codec: sent.codec,
whisper: false,
payload: sent.payload,
};
mixer.handle_packet(packet).unwrap();
let mut out = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut out);
decoded.extend(pcm::to_mono(&out, 2));
@@ -131,6 +101,24 @@ mod tests {
assert!(ratio > 0.8, "tone ratio {ratio}");
}
#[test]
fn end_of_stream_has_no_payload() {
let encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
let end = encoder.end_of_stream();
assert_eq!(end, EncodedVoice { codec: VoiceCodec::Music, payload: vec![] });
assert!(end.is_end());
}
#[test]
fn encoded_frames_carry_codec_and_audio() {
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();
let a = voice.encode(&[0.1; FRAME_SAMPLES]).unwrap();
let b = music.encode(&[0.1; FRAME_SAMPLES * 2]).unwrap();
assert_eq!((a.codec, b.codec), (VoiceCodec::Voice, VoiceCodec::Music));
assert!(!a.is_end() && !b.is_end());
}
#[test]
fn rejects_wrong_frame_size() {
let mut encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
+879
View File
@@ -0,0 +1,879 @@
//! Handle receiving audio.
//!
//! Moved here from the vendored `tsclientlib::audio` and made independent of the
//! transport: it reads [`VoicePacket`]s, whatever carried them.
//!
//! The [`AudioHandler`] collects all incoming audio packets and queues them per
//! talker. It decodes the audio, handles out-of-order packets and missing
//! packets. It automatically adjusts the queue length based on the jitter of
//! incoming packets.
use std::cmp::Reverse;
use std::collections::{HashMap, VecDeque};
use std::convert::TryInto;
use opus2::{Channels, Decoder, packet};
use thiserror::Error;
use tracing::{Span, debug, info_span, trace, warn};
use crate::packet::{TalkerId, VoicePacket};
const SAMPLE_RATE: u32 = 48_000;
const CHANNELS: Channels = Channels::Stereo;
const CHANNEL_NUM: usize = 2;
/// If this amount of packets is lost consecutively, we assume the stream stopped.
const MAX_PACKET_LOSSES: usize = 3;
/// Store the buffer sizes for the last `LAST_BUFFER_SIZE_COUNT` packets.
const LAST_BUFFER_SIZE_COUNT: u8 = 255;
/// The amount of samples to maximally buffer. Equivalent to 0.5 s.
const MAX_BUFFER_SIZE: usize = 48_000 / 2;
/// Maximum number of packets in the queue.
const MAX_BUFFER_PACKETS: usize = 50;
/// Buffer for maximal 0.5 s without playing anything.
const MAX_BUFFER_TIME: usize = 48_000 / 2;
/// Duplicate or remove every `step` sample when speeding-up.
const SPEED_CHANGE_STEPS: usize = 100;
/// The usual amount of samples in a frame.
///
/// Use 48 kHz, 20 ms frames (50 per second) and mono data (1 channel).
/// This means 1920 samples and 7.5 kiB.
const USUAL_FRAME_SIZE: usize = 48000 / 50;
type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
#[error("Failed to create opus decoder: {0}")]
CreateDecoder(#[source] opus2::Error),
#[error("Opus decode failed: {error} (packet: {packet:?})")]
Decode {
#[source]
error: opus2::Error,
packet: Option<Vec<u8>>,
},
#[error("Get duplicate packet id {0}")]
Duplicate(u16),
#[error("Failed to get packet samples: {0}")]
GetPacketSample(#[source] opus2::Error),
#[error("Audio queue is full, dropping")]
QueueFull,
#[error("Audio packet is too late, dropping (wanted {wanted}, got {got})")]
TooLate { wanted: u16, got: u16 },
#[error("Packet has too many samples")]
TooManySamples,
}
#[derive(Clone, Debug)]
struct SlidingWindowMinimum<T: Copy + Default + Ord> {
/// How long a value stays in the sliding window.
size: u8,
/// This is a sliding window minimum, it contains
/// `(insertion time, value)`.
///
/// When we insert a value, we can remove all bigger sample counts,
/// thus the queue always stays sorted with the minimum at the front
/// and the maximum at the back (latest entry).
///
/// Provides amortized O(1) minimum.
/// Source: https://people.cs.uct.ac.za/~ksmith/articles/sliding_window_minimum.html#sliding-window-minimum-algorithm
queue: VecDeque<(u8, T)>,
/// The current insertion time.
cur_time: u8,
}
#[derive(Debug)]
struct QueuePacket {
packet: VoicePacket,
samples: usize,
id: u16,
}
/// A queue for audio packets for one audio stream.
pub struct AudioQueue {
span: Span,
decoder: Decoder,
pub volume: f32,
/// The id of the next packet that should be decoded.
///
/// Used to check for packet loss.
next_id: u16,
/// If the last packet was a whisper packet.
whispering: bool,
packet_buffer: VecDeque<QueuePacket>,
/// Amount of samples in the `packet_buffer`.
packet_buffer_samples: usize,
/// Temporary buffer that contains the samples of one decoded packet.
decoded_buffer: Vec<f32>,
/// The number of samples in `decoded_buffer` that have been returned.
decoded_pos: usize,
/// The number of samples in the last packet.
last_packet_samples: usize,
/// The last `packet_loss_num` packet decodes were a loss.
packet_loss_num: usize,
/// The amount of samples to buffer until this queue is ready to play.
buffering_samples: usize,
/// The amount of packets in the buffer when a packet was decoded.
///
/// Uses the amount of samples in the `packet_buffer` / `USUAL_PACKET_SAMPLES`.
/// Used to expand or reduce the buffer.
last_buffer_size_min: SlidingWindowMinimum<u8>,
last_buffer_size_max: SlidingWindowMinimum<Reverse<u8>>,
/// Buffered for this duration.
buffered_for_samples: usize,
}
/// Handles incoming audio, has one [`AudioQueue`] per talker.
#[derive(Default)]
pub struct AudioHandler {
queues: HashMap<TalkerId, AudioQueue>,
/// Buffer this amount of samples for new queues before starting to play.
///
/// Updated when a new queue gets added.
avg_buffer_samples: usize,
}
impl<T: Copy + Default + Ord> SlidingWindowMinimum<T> {
fn new(size: u8) -> Self {
Self { size, queue: Default::default(), cur_time: 0 }
}
fn push(&mut self, value: T) {
while self.queue.back().map(|(_, s)| *s >= value).unwrap_or_default() {
self.queue.pop_back();
}
let i = self.cur_time;
self.queue.push_back((i, value));
while self
.queue
.front()
.map(|(i, _)| self.cur_time.wrapping_sub(*i) >= self.size)
.unwrap_or_default()
{
self.queue.pop_front();
}
self.cur_time = self.cur_time.wrapping_add(1);
}
fn get_min(&self) -> T {
self.queue.front().map(|(_, s)| *s).unwrap_or_default()
}
}
impl AudioQueue {
fn new(packet: VoicePacket) -> Result<Self> {
let last_packet_samples =
packet::get_nb_samples(&packet.payload, SAMPLE_RATE).map_err(Error::GetPacketSample)?;
if last_packet_samples > MAX_BUFFER_SIZE {
return Err(Error::TooManySamples);
}
let last_packet_samples = last_packet_samples * CHANNEL_NUM;
let whispering = packet.whisper;
let decoder = Decoder::new(SAMPLE_RATE, CHANNELS).map_err(Error::CreateDecoder)?;
let mut res = Self {
span: Span::current(),
decoder,
volume: 1.0,
next_id: packet.seq,
whispering,
packet_buffer: Default::default(),
packet_buffer_samples: 0,
decoded_buffer: Default::default(),
decoded_pos: 0,
last_packet_samples,
packet_loss_num: 0,
buffering_samples: 0,
last_buffer_size_min: SlidingWindowMinimum::new(LAST_BUFFER_SIZE_COUNT),
last_buffer_size_max: SlidingWindowMinimum::<Reverse<u8>>::new(LAST_BUFFER_SIZE_COUNT),
buffered_for_samples: 0,
};
res.add_buffer_size(0);
res.add_packet(packet)?;
Ok(res)
}
pub fn get_decoder(&self) -> &Decoder {
&self.decoder
}
pub fn is_whispering(&self) -> bool {
self.whispering
}
/// Size is in samples.
fn add_buffer_size(&mut self, size: usize) {
if let Ok(size) = (size / USUAL_FRAME_SIZE).try_into() {
self.last_buffer_size_min.push(size);
self.last_buffer_size_max.push(Reverse(size));
} else {
warn!(parent: &self.span, size, "Failed to put amount of packets into an u8");
}
}
/// The approximate deviation of the buffer size.
fn get_deviation(&self) -> u8 {
let min = self.last_buffer_size_min.get_min();
let max = self.last_buffer_size_max.get_min();
max.0 - min
}
fn add_packet(&mut self, packet: VoicePacket) -> Result<()> {
let _span = self.span.enter();
if self.packet_buffer.len() >= MAX_BUFFER_PACKETS {
return Err(Error::QueueFull);
}
let samples;
if packet.is_end() {
// End of stream
samples = 0;
} else {
samples = packet::get_nb_samples(&packet.payload, SAMPLE_RATE)
.map_err(Error::GetPacketSample)?;
if samples > MAX_BUFFER_SIZE {
return Err(Error::TooManySamples);
}
}
let id = packet.seq;
let packet = QueuePacket { packet, samples, id };
if id.wrapping_sub(self.next_id) > MAX_BUFFER_PACKETS as u16 {
return Err(Error::TooLate { wanted: self.next_id, got: id });
}
// Put into first spot where the id is smaller
let i = self.packet_buffer.len()
- self
.packet_buffer
.iter()
.enumerate()
.rev()
.take_while(|(_, p)| p.id.wrapping_sub(id) <= MAX_BUFFER_PACKETS as u16)
.count();
// Check for duplicate packet
if let Some(p) = self.packet_buffer.get(i)
&& p.id == packet.id
{
return Err(Error::Duplicate(p.id));
}
trace!("Insert packet {} at {}", id, i);
let last_id = self.packet_buffer.back().map(|p| p.id.wrapping_add(1)).unwrap_or(id);
if last_id <= id {
self.buffering_samples = self.buffering_samples.saturating_sub(samples);
// Reduce buffering counter by lost packets if there are some
self.buffering_samples = self
.buffering_samples
.saturating_sub(usize::from(id - last_id) * self.last_packet_samples);
}
self.packet_buffer_samples += packet.samples;
self.packet_buffer.insert(i, packet);
Ok(())
}
fn decode_packet(&mut self, packet: Option<&QueuePacket>, fec: bool) -> Result<()> {
let _span = self.span.clone().entered();
trace!(has_packet = packet.is_some(), fec, "Decoding packet");
let packet_data;
let len;
if let Some(p) = packet {
packet_data = &p.packet.payload[..];
len = p.samples;
self.whispering = p.packet.whisper;
} else {
// An empty slice signals packet loss to the decoder
packet_data = &[];
len = self.last_packet_samples;
}
self.packet_loss_num += 1;
let orig_buffer_len = self.decoded_buffer.len();
self.decoded_buffer.resize(orig_buffer_len + len * CHANNEL_NUM, 0.0);
let len = self
.decoder
.decode_float(packet_data, &mut self.decoded_buffer[orig_buffer_len..], fec)
.map_err(|e| Error::Decode {
error: e,
packet: packet.map(|p| p.packet.payload.clone()),
})?;
self.last_packet_samples = len;
self.decoded_buffer.truncate(orig_buffer_len + len * CHANNEL_NUM);
// Update packet_loss_num
if packet.is_some() && !fec {
self.packet_loss_num = 0;
}
// Update last_buffer_size
let mut count = self.packet_buffer_samples;
if let Some(last) = self.packet_buffer.back() {
// Lost packets
trace!(
last.id,
next_id = self.next_id,
first_id = self.packet_buffer.front().unwrap().id,
buffer_len = self.packet_buffer.len(),
"Ids"
);
count += (usize::from(last.id.wrapping_sub(self.next_id)) + 1
- self.packet_buffer.len())
* self.last_packet_samples;
}
self.add_buffer_size(count);
Ok(())
}
/// Decode data and return the requested length of buffered data.
///
/// Returns `true` in the second return value when the stream ended,
/// `false` when it continues normally.
pub fn get_next_data(&mut self, len: usize) -> Result<(&[f32], bool)> {
let _span = self.span.clone().entered();
if self.buffering_samples > 0 {
if self.buffered_for_samples >= MAX_BUFFER_TIME {
self.buffering_samples = 0;
self.buffered_for_samples = 0;
trace!(
buffered_for_samples = self.buffered_for_samples,
buffering_samples = self.buffering_samples,
"Buffered for too long"
);
} else {
self.buffered_for_samples += len;
trace!(
buffered_for_samples = self.buffered_for_samples,
buffering_samples = self.buffering_samples,
"Buffering"
);
return Ok((&[], false));
}
}
// Need to refill buffer
self.decoded_buffer.drain(..self.decoded_pos);
while self.decoded_buffer.len() < len {
trace!(decoded_buffer = self.decoded_buffer.len(), len, "get_next_data");
// Decode a packet
if let Some(packet) = self.packet_buffer.pop_front() {
if packet.packet.is_end() {
// End of stream
return Ok((&self.decoded_buffer, true));
}
self.packet_buffer_samples -= packet.samples;
let cur_id = self.next_id;
self.next_id = self.next_id.wrapping_add(1);
if packet.id != cur_id {
debug_assert!(
packet.id.wrapping_sub(cur_id) < MAX_BUFFER_PACKETS as u16,
"Invalid packet queue state: {} < {}",
packet.id,
cur_id
);
// Packet loss
debug!(need = cur_id, have = packet.id, "Audio packet loss");
if packet.id == self.next_id {
// Can use forward-error-correction
self.decode_packet(Some(&packet), true)?;
} else {
self.decode_packet(None, false)?;
}
self.packet_buffer_samples += packet.samples;
self.packet_buffer.push_front(packet);
} else {
self.decode_packet(Some(&packet), false)?;
}
} else {
debug!("No packets in queue");
// Packet loss or end of stream
self.decode_packet(None, false)?;
}
if self.last_packet_samples == 0 {
break;
}
// Check if we should speed-up playback
let min = self.last_buffer_size_min.get_min();
let dev = self.get_deviation();
if min > (MAX_BUFFER_SIZE / USUAL_FRAME_SIZE) as u8 {
debug!(min, "Truncating buffer");
// Throw out all but min samples
let mut keep_samples = 0;
let keep = self
.packet_buffer
.iter()
.rev()
.take_while(|p| {
keep_samples += p.samples;
keep_samples < usize::from(min) + USUAL_FRAME_SIZE
})
.count();
let len = self.packet_buffer.len() - keep;
self.packet_buffer.drain(..len);
self.packet_buffer_samples = self.packet_buffer.iter().map(|p| p.samples).sum();
if let Some(p) = self.packet_buffer.front() {
self.next_id = p.id;
}
} else if min > dev {
// Speed-up
debug!(
min,
cur_packet_count = self.packet_buffer.len(),
last_packet_samples = self.last_packet_samples,
dev,
"Speed-up buffer"
);
let start = self.decoded_buffer.len() - self.last_packet_samples * CHANNEL_NUM;
for i in 0..(self.last_packet_samples / SPEED_CHANGE_STEPS) {
let i = start + i * (SPEED_CHANGE_STEPS - 1) * CHANNEL_NUM;
self.decoded_buffer.drain(i..(i + CHANNEL_NUM));
}
}
}
self.decoded_pos = len;
Ok((&self.decoded_buffer[..len], false))
}
}
impl AudioHandler {
pub fn new() -> Self {
Default::default()
}
/// Delete all queues
pub fn reset(&mut self) {
self.queues.clear();
}
pub fn get_queues(&self) -> &HashMap<TalkerId, AudioQueue> {
&self.queues
}
pub fn get_mut_queues(&mut self) -> &mut HashMap<TalkerId, AudioQueue> {
&mut self.queues
}
/// `buf` is not cleared before filling it.
///
/// Returns the clients that are not talking anymore.
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<TalkerId> {
self.fill_buffer_with_proc(buf, |_, _| {})
}
/// `buf` is not cleared before filling it.
///
/// Same as [`Self::fill_buffer`] but before merging a queue into the output buffer, a preprocessor
/// function is called. The queue volume is applied after calling the preprocessor.
///
/// Returns the clients that are not talking anymore.
pub fn fill_buffer_with_proc<F: FnMut(&TalkerId, &[f32])>(
&mut self,
buf: &mut [f32],
mut handle: F,
) -> Vec<TalkerId> {
trace!(len = buf.len(), "Filling audio buffer");
let mut to_remove = Vec::new();
for (id, queue) in self.queues.iter_mut() {
if queue.packet_loss_num >= MAX_PACKET_LOSSES {
debug!(packet_loss_num = queue.packet_loss_num, "Removing talker");
to_remove.push(*id);
continue;
}
let vol = queue.volume;
match queue.get_next_data(buf.len()) {
Err(error) => {
warn!(%error, "Failed to decode audio packet");
}
Ok((r, is_end)) => {
handle(id, r);
for i in 0..r.len() {
buf[i] += r[i] * vol;
}
if is_end {
to_remove.push(*id);
}
}
}
}
for id in &to_remove {
self.queues.remove(id);
}
to_remove
}
/// Add a packet to the queue of its talker.
///
/// If a new talker started talking, returns its id.
pub fn handle_packet(&mut self, packet: VoicePacket) -> Result<Option<TalkerId>> {
let id = packet.talker;
let empty = packet.is_end();
if let Some(queue) = self.queues.get_mut(&id) {
queue.add_packet(packet)?;
Ok(None)
} else {
if empty {
return Ok(None);
}
let _span = info_span!("audio queue", client = ?id);
trace!("Adding talker");
let mut queue = AudioQueue::new(packet)?;
if !self.queues.is_empty() {
// Update avg_buffer_samples
let total: usize = self
.queues
.values()
.map(|q| usize::from(q.last_buffer_size_min.get_min()))
.sum();
self.avg_buffer_samples = USUAL_FRAME_SIZE + total / self.queues.len();
}
queue.buffering_samples = self.avg_buffer_samples;
self.queues.insert(id, queue);
Ok(Some(id))
}
}
}
#[cfg(test)]
mod test {
use opus2::Encoder;
use super::*;
use crate::packet::VoiceCodec;
type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
const ID: TalkerId = TalkerId(0);
fn packet(seq: u16, payload: &[u8]) -> VoicePacket {
VoicePacket {
talker: ID,
seq,
codec: VoiceCodec::Music,
whisper: false,
payload: payload.to_vec(),
}
}
enum SimulateAction {
CreateEncoder,
/// Create packet with id.
///
/// The `bool` is `false` if packet handling should fail.
ReceivePacket(u16, bool),
ReceiveRaw(u16, Vec<u8>),
/// Fetch audio of this sample count and expect a certain packet id.
FillBuffer(usize, Option<u16>),
/// Custom check
Check(Box<dyn FnOnce(&AudioHandler)>),
}
fn simulate(actions: Vec<SimulateAction>) -> TestResult {
let mut encoder = None;
let mut opus_output = [0; 1275]; // Max size for an opus packet
let mut handler = AudioHandler::new();
for a in actions {
println!("\nCurrent state");
for q in &handler.queues {
print!("Queue {:?}:", q.0);
for p in &q.1.packet_buffer {
print!(" {:?},", p);
}
println!();
}
match a {
SimulateAction::CreateEncoder => {
encoder = Some(Encoder::new(
48_000,
opus2::Channels::Mono,
opus2::Application::Voip,
)?);
}
SimulateAction::ReceivePacket(i, success) => {
let e = encoder.as_mut().unwrap();
let data = vec![i as f32; USUAL_FRAME_SIZE];
let len = e.encode_float(&data, &mut opus_output[..])?;
if handler.handle_packet(packet(i, &opus_output[..len])).is_ok() != success {
return Err(format!(
"handle_packet returned {:?} but expected {:?}",
!success, success
)
.into());
}
}
SimulateAction::ReceiveRaw(i, data) => {
let _ = handler.handle_packet(packet(i, &data));
}
SimulateAction::FillBuffer(size, expect) => {
let mut buf = vec![0.0; size * 2]; // Stereo
let cur_packet_id =
handler.queues.get(&ID).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
handler.fill_buffer(&mut buf);
let next_packet_id =
handler.queues.get(&ID).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
if expect.is_some() {
assert_eq!(expect, cur_packet_id);
assert_ne!(cur_packet_id, next_packet_id);
}
}
SimulateAction::Check(f) => {
f(&handler);
}
}
}
Ok(())
}
#[test]
fn sliding_window_minimum() {
let data = &[
(5, 5),
(6, 5),
(3, 3),
(4, 3),
(6, 3),
(5, 3),
(6, 3),
(6, 4),
(6, 5),
(6, 5),
(6, 6),
(7, 6),
(5, 5),
];
let mut window = SlidingWindowMinimum::new(5);
assert_eq!(window.get_min(), 0);
for (i, (val, min)) in data.iter().enumerate() {
println!("{:?}", window);
window.push(*val);
assert_eq!(window.get_min(), *min, "Failed in iteration {} ({:?})", i, window);
}
}
#[test]
fn sliding_window_minimum_full() {
let mut window = SlidingWindowMinimum::new(255);
window.push(1);
assert_eq!(window.get_min(), 1);
for _ in 0..254 {
window.push(2);
}
assert_eq!(window.get_min(), 1);
window.push(2);
assert_eq!(window.get_min(), 2);
}
#[test]
fn packets_wrapping() {
let mut handler = AudioHandler::new();
let mut buf = vec![0.0; 48_000 / 100 * 2];
for i in 0..100 {
let seq = 65_500u16.wrapping_add(i);
handler.handle_packet(packet(seq, &[0, 0, 0, 0, 0, 0, 0])).unwrap();
if i > 5 {
handler.fill_buffer(&mut buf);
}
}
}
/// Short and malformed packets of any content are errors, never panics.
#[test]
fn short_packet_fuzz() {
let mut handler = AudioHandler::new();
let mut buf = vec![0.0; 48_000 / 100 * 2];
let mut state = 0x2545_f491_4f6c_dd1du64;
let mut next = move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state
};
for _ in 0..3_000 {
// Payloads of 0..=100 bytes: empty, a lone TOC byte, and frames of any shape.
let len = (next() % 101) as usize;
let payload: Vec<u8> = (0..len).map(|_| next() as u8).collect();
let _ = handler.handle_packet(packet(30, &payload));
handler.fill_buffer(&mut buf);
handler.fill_buffer(&mut buf);
}
}
#[test]
fn packets_wrapping2() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
for i in 0..100 {
let i = 65_500u16.wrapping_add(i);
a.push(SimulateAction::ReceivePacket(i, true));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
}
for _ in 0..4 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
#[test]
fn silence() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
for _ in 0..100 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
simulate(a)
}
#[test]
fn reversed() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
for i in 0..5 {
a.push(SimulateAction::ReceivePacket(i, true));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
}
a.push(SimulateAction::ReceivePacket(4, false));
a.push(SimulateAction::ReceivePacket(3, false));
for _ in 0..4 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
#[test]
fn duplicate() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
a.push(SimulateAction::ReceivePacket(0, true));
a.push(SimulateAction::ReceivePacket(0, false));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(0)));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
simulate(a)
}
#[test]
fn big_whole() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
for i in 27120..27124 {
a.push(SimulateAction::ReceivePacket(i, true));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
}
a.push(SimulateAction::ReceiveRaw(27124, vec![2]));
for _ in 0..10 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
for i in 27339..27349 {
a.push(SimulateAction::ReceivePacket(i, true));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
for _ in 0..4 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
#[test]
fn end_packet() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
for i in 0..10 {
a.push(SimulateAction::ReceivePacket(i, true));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
}
a.push(SimulateAction::ReceiveRaw(10, vec![]));
for _ in 0..4 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
#[test]
fn packet_loss() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
a.push(SimulateAction::ReceivePacket(50, true));
a.push(SimulateAction::ReceivePacket(53, true));
for _ in 0..8 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
#[test]
fn packet_wrapping_loss() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
a.push(SimulateAction::ReceivePacket(65534, true));
a.push(SimulateAction::ReceivePacket(0, true));
for _ in 0..7 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
/// The talker is the key of the queues, and a new one is reported once.
#[test]
fn talkers_have_their_own_queues() -> TestResult {
let mut encoder = Encoder::new(48_000, opus2::Channels::Mono, opus2::Application::Voip)?;
let mut out = [0; 1275];
let len = encoder.encode_float(&vec![0.1; USUAL_FRAME_SIZE], &mut out)?;
let from = |talker: u16, seq: u16| VoicePacket {
talker: TalkerId(talker),
seq,
codec: VoiceCodec::Voice,
whisper: false,
payload: out[..len].to_vec(),
};
let mut handler = AudioHandler::new();
assert_eq!(handler.handle_packet(from(7, 100))?, Some(TalkerId(7)));
assert_eq!(handler.handle_packet(from(7, 101))?, None);
assert_eq!(handler.handle_packet(from(9, 5))?, Some(TalkerId(9)));
let mut talkers: Vec<_> = handler.get_queues().keys().map(|t| t.0).collect();
talkers.sort_unstable();
assert_eq!(talkers, [7, 9]);
// A talker that only says goodbye never gets a queue.
let end = VoicePacket { payload: vec![], ..from(11, 0) };
assert_eq!(handler.handle_packet(end)?, None);
assert_eq!(handler.get_queues().len(), 2);
Ok(())
}
/// A queue knows whether the last packet it played was a whisper.
#[test]
fn whisper_flag_follows_the_packets() -> TestResult {
let mut encoder = Encoder::new(48_000, opus2::Channels::Mono, opus2::Application::Voip)?;
let mut out = [0; 1275];
let len = encoder.encode_float(&vec![0.1; USUAL_FRAME_SIZE], &mut out)?;
let packet = |seq: u16, whisper: bool| VoicePacket {
talker: ID,
seq,
codec: VoiceCodec::Voice,
whisper,
payload: out[..len].to_vec(),
};
let mut handler = AudioHandler::new();
handler.handle_packet(packet(0, true))?;
assert!(handler.get_queues()[&ID].is_whispering());
handler.handle_packet(packet(1, false))?;
// One packet is played per call.
let mut buf = [0.0; USUAL_FRAME_SIZE * 2];
handler.fill_buffer(&mut buf);
handler.fill_buffer(&mut buf);
assert!(!handler.get_queues()[&ID].is_whispering());
Ok(())
}
}
+11 -5
View File
@@ -1,14 +1,17 @@
//! Voice pipeline building blocks.
//!
//! - [`pcm`]: sample-rate constants, tone generation and detection helpers
//! - [`encode`]: Opus encoding of 20 ms frames into TeamSpeak voice packets
//! - [`packet`]: the voice packet types the pipeline takes and produces
//! ([`VoicePacket`], [`EncodedVoice`]), independent of the transport
//! - [`encode`]: Opus encoding of 20 ms frames into [`EncodedVoice`]
//! - [`framer`]: slice an arbitrary sample stream into codec frames
//! - [`resample`]: sample-rate conversion to the 48 kHz the codec uses
//! - [`wav`]: WAV file input/output
//! - [`process`]: echo cancellation, noise suppression and gain control
//! - [`vad`]: voice activity detection
//! - [`mixer`]: per-client jitter buffer, decoder, volume and mixing (on the
//! vendored `tsclientlib::audio::AudioHandler`)
//! - [`jitter`]: the per-talker jitter buffer and Opus decoder
//! - [`mixer`]: per-talker volume, mute and priority dimming over the jitter
//! buffer, mixing to stereo
//! - [`settings`]: all user audio settings in one serde struct
//! - [`tap`]: the processed microphone for other consumers (the stream
//! mixer), free while nobody listens
@@ -17,7 +20,9 @@
pub mod encode;
pub mod framer;
pub mod jitter;
pub mod mixer;
pub mod packet;
pub mod pcm;
pub mod process;
pub mod resample;
@@ -29,12 +34,13 @@ pub mod wav;
#[cfg(feature = "device")]
pub mod device;
pub use encode::{VoiceCodec, VoiceEncoder};
pub use encode::VoiceEncoder;
pub use framer::Framer;
pub use jitter::AudioHandler;
pub use mixer::Mixer;
pub use packet::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
pub use process::{ProcessingSettings, Processor};
pub use settings::AudioSettings;
pub use tsclientlib::audio::AudioHandler;
pub use vad::{Vad, VadSettings};
#[derive(Debug, thiserror::Error)]
+62 -67
View File
@@ -1,9 +1,9 @@
//! Incoming voice: per-client jitter buffer, decoder and mixer, with a
//! volume and mute per client, and everyone else dimmed while a priority
//! Incoming voice: per-talker jitter buffer, decoder and mixer, with a
//! volume and mute per talker, and everyone else dimmed while a priority
//! speaker talks.
//!
//! The jitter buffer is the vendored `tsclientlib::audio::AudioHandler`. Per
//! sender it keeps a queue of Opus packets and adapts its length:
//! The jitter buffer is [`AudioHandler`]. Per sender it keeps a queue of Opus
//! packets and adapts its length:
//!
//! - a new talker starts after a pre-buffer derived from the queue lengths of
//! the other talkers (none for the first one);
@@ -21,13 +21,11 @@
use std::collections::{HashMap, HashSet};
use tsclientlib::ClientId;
use tsclientlib::audio::{AudioHandler, Error as QueueError};
use tsproto_packets::packets::InAudioBuf;
use crate::jitter::{AudioHandler, Error as QueueError};
use crate::packet::{TalkerId, VoicePacket};
use crate::pcm::FRAME_SAMPLES;
/// Loudest per-client volume: +12 dB.
/// Loudest per-talker volume: +12 dB.
pub const MAX_CLIENT_VOLUME: f32 = 4.0;
/// Most a priority speaker dims the others (dB).
const MAX_DIMM_DB: f32 = -60.0;
@@ -35,14 +33,14 @@ const MAX_DIMM_DB: f32 = -60.0;
/// samples (5 frames, 100 ms) instead of jumping.
const DIMM_RAMP_SAMPLES: usize = 5 * FRAME_SAMPLES;
/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender.
/// Jitter buffer, decoder and mixer for incoming voice, keyed by talker.
/// Output is interleaved stereo at 48 kHz.
pub struct Mixer {
handler: AudioHandler<ClientId>,
volumes: HashMap<ClientId, f32>,
muted: HashSet<ClientId>,
handler: AudioHandler,
volumes: HashMap<TalkerId, f32>,
muted: HashSet<TalkerId>,
/// While one of them talks, everyone else is dimmed.
priority: HashSet<ClientId>,
priority: HashSet<TalkerId>,
/// Linear gain of the others while a priority speaker talks (1: none).
dimm: f32,
/// How far the dimming has faded in (0..=1).
@@ -70,21 +68,17 @@ impl Mixer {
Self::default()
}
/// Queue a voice packet from `id`. Returns `Some(id)` when this client
/// just started talking. Late, duplicate and malformed packets are
/// errors; on UDP they are expected and can be ignored.
pub fn handle_packet(
&mut self,
id: ClientId,
packet: InAudioBuf,
) -> Result<Option<ClientId>, QueueError> {
self.handler.handle_packet(id, packet)
/// Queue a voice packet for its talker. Returns `Some(talker)` when this
/// talker just started talking. Late, duplicate and malformed packets are
/// errors; on datagrams they are expected and can be ignored.
pub fn handle_packet(&mut self, packet: VoicePacket) -> Result<Option<TalkerId>, QueueError> {
self.handler.handle_packet(packet)
}
/// Add the next `buf.len() / 2` stereo frames of all talkers to `buf`
/// (not cleared first), each scaled by its volume, and dimmed while a
/// priority speaker talks. Returns the clients that stopped talking.
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<ClientId> {
/// priority speaker talks. Returns the talkers that stopped talking.
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<TalkerId> {
let queues = self.handler.get_mut_queues();
// A priority speaker with a queue (talking or buffering) dims all
// other queues, streams too, unless we muted it.
@@ -141,9 +135,9 @@ impl Mixer {
stopped
}
/// Linear gain for one client, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
/// Kept when the client stops and starts talking again.
pub fn set_volume(&mut self, id: ClientId, volume: f32) {
/// Linear gain for one talker, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
/// Kept when the talker stops and starts talking again.
pub fn set_volume(&mut self, id: TalkerId, volume: f32) {
let volume = if volume.is_finite() { volume.clamp(0.0, MAX_CLIENT_VOLUME) } else { 1.0 };
if volume == 1.0 {
self.volumes.remove(&id);
@@ -153,15 +147,15 @@ impl Mixer {
}
/// Like [`set_volume`](Self::set_volume), in dB (0 dB = unchanged).
pub fn set_volume_db(&mut self, id: ClientId, db: f32) {
pub fn set_volume_db(&mut self, id: TalkerId, db: f32) {
self.set_volume(id, 10f32.powf(db / 20.0));
}
pub fn volume(&self, id: ClientId) -> f32 {
pub fn volume(&self, id: TalkerId) -> f32 {
self.volumes.get(&id).copied().unwrap_or(1.0)
}
pub fn set_muted(&mut self, id: ClientId, muted: bool) {
pub fn set_muted(&mut self, id: TalkerId, muted: bool) {
if muted {
self.muted.insert(id);
} else {
@@ -169,30 +163,30 @@ impl Mixer {
}
}
pub fn is_muted(&self, id: ClientId) -> bool {
pub fn is_muted(&self, id: TalkerId) -> bool {
self.muted.contains(&id)
}
/// The priority speakers, and how much everyone else is dimmed while
/// one of them talks: dB, clamped to -60..=0 (NaN: not at all).
/// Replaces the previous set; [`forget`](Self::forget) leaves it alone,
/// the caller sends a new set when the clients change.
pub fn set_priority(&mut self, clients: impl IntoIterator<Item = ClientId>, dimm_db: f32) {
self.priority = clients.into_iter().collect();
/// the caller sends a new set when the talkers change.
pub fn set_priority(&mut self, talkers: impl IntoIterator<Item = TalkerId>, dimm_db: f32) {
self.priority = talkers.into_iter().collect();
let db = if dimm_db.is_nan() { 0.0 } else { dimm_db.clamp(MAX_DIMM_DB, 0.0) };
self.dimm = 10f32.powf(db / 20.0);
}
/// Forget volume and mute of a client (e.g. it left the server; client
/// ids are reused).
pub fn forget(&mut self, id: ClientId) {
/// Forget volume and mute of a talker (e.g. it left the server; ids may
/// be reused).
pub fn forget(&mut self, id: TalkerId) {
self.volumes.remove(&id);
self.muted.remove(&id);
self.handler.get_mut_queues().remove(&id);
}
/// Clients with a queue, i.e. currently talking or buffering.
pub fn talkers(&self) -> impl Iterator<Item = ClientId> + '_ {
/// Talkers with a queue, i.e. currently talking or buffering.
pub fn talkers(&self) -> impl Iterator<Item = TalkerId> + '_ {
self.handler.get_queues().keys().copied()
}
@@ -202,7 +196,7 @@ impl Mixer {
}
/// The underlying jitter buffer.
pub fn handler(&self) -> &AudioHandler<ClientId> {
pub fn handler(&self) -> &AudioHandler {
&self.handler
}
}
@@ -221,23 +215,26 @@ impl std::fmt::Debug for Mixer {
#[cfg(test)]
mod tests {
use tsproto_packets::packets::{AudioData, CodecType, Direction, OutAudio};
use super::*;
use crate::VoiceEncoder;
use crate::encode::VoiceCodec;
use crate::packet::VoiceCodec;
use crate::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
fn packet(from: u16, id: u16, data: &[u8]) -> InAudioBuf {
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap()
fn packet(from: u16, seq: u16, data: &[u8]) -> VoicePacket {
VoicePacket {
talker: TalkerId(from),
seq,
codec: VoiceCodec::Voice,
whisper: false,
payload: data.to_vec(),
}
}
/// Two clients send tones at the same level; after setting volumes the
/// mix carries each at its own gain, and a muted one not at all.
#[test]
fn volume_per_client() {
let (a, b) = (ClientId(3), ClientId(4));
let (a, b) = (TalkerId(3), TalkerId(4));
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut enc_b = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone_a = pcm::sine(500.0, 2.0, 0.2);
@@ -251,11 +248,11 @@ mod tests {
let frames = tone_a.chunks_exact(FRAME_SAMPLES).zip(tone_b.chunks_exact(FRAME_SAMPLES));
for (i, (fa, fb)) in frames.enumerate() {
let id = i as u16;
let started = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
let started = mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
if i == 0 {
assert_eq!(started.unwrap(), Some(a));
}
mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
mixer.handle_packet(packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
out.extend(pcm::to_mono(&buf, 2));
@@ -274,8 +271,8 @@ mod tests {
let id = 100 + i;
let fa = &tone_a[..FRAME_SAMPLES];
let fb = &tone_b[..FRAME_SAMPLES];
let _ = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
let _ = mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
let _ = mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
let _ = mixer.handle_packet(packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
out.extend(pcm::to_mono(&buf, 2));
@@ -289,7 +286,7 @@ mod tests {
/// in and out, but not itself, and not while we muted it.
#[test]
fn priority_speaker_dims_others() {
let (a, p) = (ClientId(3), ClientId(5));
let (a, p) = (TalkerId(3), TalkerId(5));
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone_a = pcm::sine(500.0, 4.0, 0.2);
@@ -308,14 +305,12 @@ mod tests {
let mut out = Vec::new();
for _ in 0..frames {
let fa = frame(&tone_a, id_a);
mixer
.handle_packet(a, packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap()))
.unwrap();
mixer.handle_packet(packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap())).unwrap();
id_a += 1;
if with_p {
let fp = frame(&tone_p, id_p);
let data = enc_p.encode_to_bytes(&fp).unwrap();
mixer.handle_packet(p, packet(5, id_p, data)).unwrap();
mixer.handle_packet(packet(5, id_p, data)).unwrap();
id_p += 1;
}
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
@@ -359,7 +354,7 @@ mod tests {
/// frame: the other talker's level (per period of its tone) never jumps.
#[test]
fn priority_dimming_ramps_per_sample() {
let (a, p) = (ClientId(3), ClientId(5));
let p = TalkerId(5);
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone = pcm::sine(500.0, 2.0, 0.2);
@@ -371,10 +366,10 @@ mod tests {
// p talks from frame 30 to 59.
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
let id = i as u16;
mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap();
mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap();
if let Some(j) = i.checked_sub(30).filter(|j| *j < 30) {
let data = enc_p.encode_to_bytes(frame).unwrap();
mixer.handle_packet(p, packet(5, j as u16, data)).unwrap();
mixer.handle_packet(packet(5, j as u16, data)).unwrap();
}
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
@@ -400,17 +395,17 @@ mod tests {
fn priority_dimm_bounds() {
let mut mixer = Mixer::new();
assert_eq!(mixer.dimm, 1.0);
mixer.set_priority([ClientId(1)], -18.0);
mixer.set_priority([TalkerId(1)], -18.0);
assert!((mixer.dimm - 0.1259).abs() < 1e-3);
mixer.set_priority([ClientId(1)], 6.0);
mixer.set_priority([TalkerId(1)], 6.0);
assert_eq!(mixer.dimm, 1.0);
mixer.set_priority([ClientId(1)], f32::NEG_INFINITY);
mixer.set_priority([TalkerId(1)], f32::NEG_INFINITY);
assert!((mixer.dimm - 0.001).abs() < 1e-6);
mixer.set_priority([ClientId(1)], f32::NAN);
mixer.set_priority([TalkerId(1)], f32::NAN);
assert_eq!(mixer.dimm, 1.0);
// Forgetting a client keeps the set: the caller replaces it.
mixer.forget(ClientId(1));
assert!(mixer.priority.contains(&ClientId(1)));
mixer.forget(TalkerId(1));
assert!(mixer.priority.contains(&TalkerId(1)));
mixer.set_priority([], -18.0);
assert!(mixer.priority.is_empty());
}
@@ -418,7 +413,7 @@ mod tests {
#[test]
fn volume_bounds_and_forget() {
let mut mixer = Mixer::new();
let id = ClientId(9);
let id = TalkerId(9);
mixer.set_volume(id, 100.0);
assert_eq!(mixer.volume(id), MAX_CLIENT_VOLUME);
mixer.set_volume(id, -1.0);
+101
View File
@@ -0,0 +1,101 @@
//! Voice packets as the audio pipeline sees them, whatever transport carries
//! them (the TeamSpeak connection today, a Voelin server later).
//!
//! The transport adapter turns what it receives into a [`VoicePacket`] and
//! what [`VoiceEncoder`](crate::VoiceEncoder) produces ([`EncodedVoice`])
//! into its own wire format; nothing in this crate knows either format.
use crate::pcm::FRAME_SAMPLES;
/// Who is talking: a sender id, unique among the talkers of one voice
/// connection. A transport maps its own client ids onto it (TeamSpeak's
/// 16-bit client id is used as is).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TalkerId(pub u16);
/// The two Opus flavours voice is sent in.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VoiceCodec {
/// Mono, tuned for speech.
Voice,
/// Stereo, tuned for music.
Music,
}
impl VoiceCodec {
pub fn channels(self) -> usize {
match self {
VoiceCodec::Voice => 1,
VoiceCodec::Music => 2,
}
}
/// Samples (all channels) in one 20 ms frame.
pub fn frame_len(self) -> usize {
FRAME_SAMPLES * self.channels()
}
}
/// A voice packet received from a talker.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct VoicePacket {
pub talker: TalkerId,
/// Packet number of this talker, counting up by one per 20 ms frame and
/// wrapping at 65536; the jitter buffer orders by it and finds gaps.
pub seq: u16,
pub codec: VoiceCodec,
/// Sent to us as a whisper instead of to the whole channel.
pub whisper: bool,
/// One Opus packet. An empty one ends the talk (a single byte counts as
/// empty too: some servers send one).
pub payload: Vec<u8>,
}
impl VoicePacket {
/// Whether this packet only ends the talk and carries no audio.
pub fn is_end(&self) -> bool {
self.payload.len() <= 1
}
}
/// One encoded frame to send. The transport assigns the packet number.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EncodedVoice {
pub codec: VoiceCodec,
/// One Opus packet; empty: the transmission ended.
pub payload: Vec<u8>,
}
impl EncodedVoice {
/// Whether this only tells listeners the transmission ended.
pub fn is_end(&self) -> bool {
self.payload.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn codec_frames() {
assert_eq!(VoiceCodec::Voice.frame_len(), FRAME_SAMPLES);
assert_eq!(VoiceCodec::Music.frame_len(), FRAME_SAMPLES * 2);
}
#[test]
fn end_of_talk() {
let voice = |payload: &[u8]| VoicePacket {
talker: TalkerId(1),
seq: 0,
codec: VoiceCodec::Voice,
whisper: false,
payload: payload.to_vec(),
};
assert!(voice(&[]).is_end());
assert!(voice(&[2]).is_end());
assert!(!voice(&[2, 3]).is_end());
assert!(EncodedVoice { codec: VoiceCodec::Voice, payload: vec![] }.is_end());
assert!(!EncodedVoice { codec: VoiceCodec::Voice, payload: vec![0] }.is_end());
}
}
+10 -12
View File
@@ -7,10 +7,8 @@
//! loss. Every 30 s it sends a loud marker frame instead of the quiet one;
//! the latency is the time from generating a marker to it leaving the mixer.
use tsclientlib::ClientId;
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio};
use voelin_audio::pcm::{FRAME_SAMPLES, SAMPLE_RATE, energy, sine, white_noise};
use voelin_audio::{Mixer, VoiceCodec, VoiceEncoder};
use voelin_audio::{Mixer, TalkerId, VoiceCodec, VoiceEncoder, VoicePacket};
/// The receiver pulls 10 ms at a time, like a playback loop.
const PULL: usize = SAMPLE_RATE as usize / 100;
@@ -38,7 +36,7 @@ fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
let mut rng = Rng(ppm.to_bits());
let mut mixer = Mixer::new();
let client = ClientId(5);
let talker = TalkerId(5);
let total = (hours * 3600.0 * SAMPLE_RATE as f64) as u64;
// Sender frame n is made at n * 20 ms of the sender's clock.
let frame_time = |n: u64| n as f64 * FRAME_SAMPLES as f64 / (1.0 + ppm * 1e-6);
@@ -68,15 +66,15 @@ fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
let arrived = in_flight.partition_point(|&(t, _)| t <= now as f64);
for (_, n) in in_flight.drain(..arrived) {
let data = if n % MARKER_EVERY == MARKER_EVERY / 2 { &marker } else { &quiet };
let packet = OutAudio::new(&AudioData::S2C {
id: n as u16,
codec: CodecType::OpusVoice,
from: 5,
data,
});
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
let packet = VoicePacket {
talker,
seq: n as u16,
codec: VoiceCodec::Voice,
whisper: false,
payload: data.clone(),
};
// Late packets are dropped by the jitter buffer, as on a real network.
let _ = mixer.handle_packet(client, packet);
let _ = mixer.handle_packet(packet);
}
out.fill(0.0);
+17 -6
View File
@@ -14,8 +14,9 @@ default = ["audio-device"]
audio-device = ["voelin-audio/device"]
# The `media` module: capture and video codecs for streams, with whatever
# voelin-media backends are enabled (e.g. MediaCodec and a registered capture
# source on Android).
media = ["dep:voelin-media"]
# source on Android), and the studio's WHIP output. The crate itself is always
# there: the stream types in the API (`EncodedFrame`, `LayerSpec`) are its.
media = ["voelin-media/whip"]
# `media` with voelin-media's desktop backends: libvpx, dav1d, OpenH264 and
# FFmpeg loaded at runtime, X11 and PipeWire on Linux. Not for Android
# (libvpx does not cross-compile there).
@@ -24,6 +25,8 @@ media-desktop = ["media", "voelin-media/default"]
[dependencies]
anyhow = "1"
base64 = "0.22"
# The RTP packets of the session seam (`voelin_proto::link::MediaPacket`).
bytes = "1"
dirs = "6"
futures = "0.3"
# Finding a server's gateway in DNS (the voice resolver's version).
@@ -49,11 +52,17 @@ toml = "1.1.6"
tracing = "0.1"
voelin-audio = { path = "../voelin-audio", default-features = false }
voelin-gateway-proto = { path = "../voelin-gateway-proto", features = ["client"] }
voelin-media = { path = "../voelin-media", default-features = false, features = ["str0m", "whip"], optional = true }
voelin-model = { path = "../voelin-model" }
# `IdentityBlob`, the identity of the API (a TeamSpeak identity as the key store
# keeps it, or a Voelin key).
voelin-identity = { workspace = true }
voelin-media = { path = "../voelin-media", default-features = false }
voelin-model = { workspace = true }
voelin-observer = { path = "../voelin-observer" }
# Paths only (the cache directory).
voelin-platform = { path = "../voelin-platform", default-features = false }
# The backend-neutral session seam the engine consumes (`voelin_proto::link`)
# and the v1 messages it speaks.
voelin-proto = { workspace = true }
voelin-query = { path = "../voelin-query" }
voelin-store = { path = "../voelin-store" }
voelin-stream = { path = "../voelin-stream" }
@@ -64,13 +73,15 @@ tsproto-packets = { path = "../proto/tsproto-packets" }
tsproto-types = { path = "../proto/tsproto-types" }
[dev-dependencies]
# An HTTP/2 connection in a test (both already in the tree through h2).
bytes = "1"
# An HTTP/2 connection in a test (already in the tree through h2).
http = "1"
# Already in the app's graph (reqwest); for one_rustls_crypto_provider.
rustls = { version = "0.23", default-features = false }
# `process`: the browser interop test drives Chromium through Node.js.
tokio = { version = "1", features = ["macros", "net", "process", "rt-multi-thread", "test-util"] }
# The fakes of the session seam (`FakeHost`, `FakeSession`, the conformance
# suite).
voelin-proto = { workspace = true, features = ["test-util"] }
[lints]
workspace = true
+46 -49
View File
@@ -16,16 +16,18 @@ use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use tracing::{debug, warn};
use tsclientlib::ClientId;
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio, OutPacket};
use voelin_audio::pcm::{self, FRAME_SAMPLES};
use voelin_audio::settings::TransmitMode;
use voelin_audio::tap;
use voelin_audio::vad::SILENCE_DB;
use voelin_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder};
use voelin_audio::{
AudioSettings, EncodedVoice, Framer, Mixer, Processor, TalkerId, Vad, VoiceCodec, VoiceEncoder,
VoicePacket,
};
pub(crate) enum AudioIn {
Packet(InAudioBuf),
/// Voice of a talker, from the voice connection.
Packet(VoicePacket),
Transmit(bool),
InputMuted(bool),
OutputMuted(bool),
@@ -33,19 +35,19 @@ pub(crate) enum AudioIn {
Settings(Box<AudioSettings>),
/// Playback volume of one client, linear (1 = unchanged, up to 4).
ClientVolume {
client: ClientId,
client: TalkerId,
volume: f32,
},
ClientMuted {
client: ClientId,
client: TalkerId,
muted: bool,
},
/// The client left; client ids are reused, so forget its volume.
ClientLeft(ClientId),
ClientLeft(TalkerId),
/// The priority speakers: while one talks, everyone else (streams too)
/// is dimmed by `dimm_db` (the server's setting, e.g. -18).
PrioritySpeakers {
clients: Vec<ClientId>,
clients: Vec<TalkerId>,
dimm_db: f32,
},
/// An Opus frame (48 kHz) of a watched stream; `time` is its RTP time
@@ -111,10 +113,10 @@ pub(crate) const LEVEL_INTERVAL: Duration = Duration::from_millis(100);
/// Samples of one 20 ms Opus frame at 48 kHz: the unit of stream packet ids.
const OPUS_FRAME: u64 = 960;
/// Start the audio thread. Encoded packets go to `outgoing`; problems (e.g.
/// Start the audio thread. Encoded voice goes to `outgoing`; problems (e.g.
/// no device) and the microphone level are reported through `events`.
pub(crate) fn spawn(
outgoing: mpsc::UnboundedSender<OutPacket>,
outgoing: mpsc::UnboundedSender<EncodedVoice>,
events: mpsc::UnboundedSender<AudioEvent>,
settings: AudioSettings,
) -> AudioHandle {
@@ -126,9 +128,9 @@ pub(crate) fn spawn(
AudioHandle { tx }
}
/// Audio of a watched stream in the mixer, under a made-up client id.
/// Audio of a watched stream in the mixer, under a made-up talker id.
struct StreamAudio {
client: ClientId,
client: TalkerId,
/// RTP time and packet id of the last packet.
last: Option<(u64, u64)>,
}
@@ -190,11 +192,7 @@ impl Pipeline {
fn handle(&mut self, msg: AudioIn) {
match msg {
AudioIn::Packet(packet) => {
let from = match packet.data().data() {
AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from,
_ => return,
};
if let Err(error) = self.mixer.handle_packet(ClientId(from), packet) {
if let Err(error) = self.mixer.handle_packet(packet) {
debug!(%error, "dropped voice packet");
}
}
@@ -241,8 +239,8 @@ impl Pipeline {
let client = match self.streams.get(&stream) {
Some(s) => s.client,
None => {
let used: Vec<ClientId> = self.streams.values().map(|s| s.client).collect();
let Some(client) = (0..=u16::MAX).rev().map(ClientId).find(|c| !used.contains(c))
let used: Vec<TalkerId> = self.streams.values().map(|s| s.client).collect();
let Some(client) = (0..=u16::MAX).rev().map(TalkerId).find(|c| !used.contains(c))
else {
return;
};
@@ -263,19 +261,15 @@ impl Pipeline {
}
};
entry.last = Some((time, id));
let packet = OutAudio::new(&AudioData::S2C {
id: id as u16,
codec: CodecType::OpusMusic,
from: client.0,
data,
});
match InAudioBuf::try_new(Direction::S2C, packet.into_vec()) {
Ok(packet) => {
if let Err(error) = self.mixer.handle_packet(client, packet) {
debug!(%error, "dropped stream audio packet");
}
}
Err(error) => debug!(?error, "stream audio packet"),
let packet = VoicePacket {
talker: client,
seq: id as u16,
codec: VoiceCodec::Music,
whisper: false,
payload: data.to_vec(),
};
if let Err(error) = self.mixer.handle_packet(packet) {
debug!(%error, "dropped stream audio packet");
}
}
@@ -286,7 +280,7 @@ impl Pipeline {
/// Microphone audio in (mono, 48 kHz, any length); voice packets out.
/// `delay_ms` is the playback-to-capture delay hint for the echo canceller.
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(OutPacket)) {
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(EncodedVoice)) {
self.processor.set_delay_ms(delay_ms);
self.processed.clear();
self.processor.capture(samples, &mut self.processed);
@@ -308,7 +302,7 @@ impl Pipeline {
}
}
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(OutPacket)) {
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(EncodedVoice)) {
// Always analysed, so the detector's state is current when needed.
let voice = self.vad.process(&frame);
let level = self.vad.level_db().max(SILENCE_DB);
@@ -369,7 +363,7 @@ fn sanitize(mut settings: AudioSettings) -> AudioSettings {
fn run(
rx: std_mpsc::Receiver<AudioIn>,
outgoing: mpsc::UnboundedSender<OutPacket>,
outgoing: mpsc::UnboundedSender<EncodedVoice>,
events: mpsc::UnboundedSender<AudioEvent>,
settings: AudioSettings,
) {
@@ -445,11 +439,10 @@ fn run(
#[cfg(feature = "audio-device")]
mod devices {
use tracing::debug;
use tsproto_packets::packets::OutPacket;
use voelin_audio::AudioSettings;
use voelin_audio::device::{Capture, DeviceEvent, Managed, Playback};
use voelin_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
use voelin_audio::resample::Linear;
use voelin_audio::{AudioSettings, EncodedVoice};
use super::{DEVICE_LATENCY_MS, PLAYBACK_CAPACITY_MS, Pipeline};
@@ -509,7 +502,7 @@ mod devices {
pub fn step(
&mut self,
pipeline: &mut Pipeline,
send: &mut impl FnMut(OutPacket),
send: &mut impl FnMut(EncodedVoice),
error: &impl Fn(String),
) -> bool {
if let Some(event) = self.playback.poll() {
@@ -575,16 +568,20 @@ mod tests {
/// end-of-stream packets).
fn capture(p: &mut Pipeline, samples: &[f32]) -> (usize, usize) {
let (mut voice, mut end) = (0, 0);
p.capture(samples, 0, &mut |packet: OutPacket| {
// Header of 3 bytes (id + codec) for C2S audio.
if packet.content().len() > 3 { voice += 1 } else { end += 1 }
p.capture(samples, 0, &mut |packet: EncodedVoice| {
if packet.is_end() { end += 1 } else { voice += 1 }
});
(voice, end)
}
fn incoming(from: u16, id: u16, data: &[u8]) -> AudioIn {
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
AudioIn::Packet(InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap())
fn incoming(from: u16, seq: u16, data: &[u8]) -> AudioIn {
AudioIn::Packet(VoicePacket {
talker: TalkerId(from),
seq,
codec: VoiceCodec::Voice,
whisper: false,
payload: data.to_vec(),
})
}
#[test]
@@ -667,14 +664,14 @@ mod tests {
energy(&out[out.len() / 2..])
};
let full = play(&mut p, 1);
p.handle(AudioIn::ClientVolume { client: ClientId(2), volume: 0.5 });
p.handle(AudioIn::ClientVolume { client: TalkerId(2), volume: 0.5 });
let half = play(&mut p, 2);
let ratio_db = 10.0 * (half / full).log10();
assert!((ratio_db + 6.0).abs() < 1.0, "volume 0.5 gave {ratio_db} dB");
p.handle(AudioIn::ClientMuted { client: ClientId(3), muted: true });
p.handle(AudioIn::ClientMuted { client: TalkerId(3), muted: true });
assert!(play(&mut p, 3) < 1e-8);
p.handle(AudioIn::ClientLeft(ClientId(3)));
assert!(!p.mixer.is_muted(ClientId(3)));
p.handle(AudioIn::ClientLeft(TalkerId(3)));
assert!(!p.mixer.is_muted(TalkerId(3)));
}
/// While a priority speaker talks, another talker and a watched stream
@@ -682,7 +679,7 @@ mod tests {
#[test]
fn priority_speaker() {
let mut p = pipeline(TransmitMode::PushToTalk);
p.handle(AudioIn::PrioritySpeakers { clients: vec![ClientId(2)], dimm_db: -12.0 });
p.handle(AudioIn::PrioritySpeakers { clients: vec![TalkerId(2)], dimm_db: -12.0 });
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut priority = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();
+25 -5
View File
@@ -4,21 +4,21 @@
//! id (the CRC32 of the image, as TeamSpeak assigns them), so a lookup is a
//! map access, and the same image seen on several servers or under
//! several clients is one file. Pictures from the web (banners,
//! [`crate::web`]) are named by the MD5 hash of their address. Keys are
//! `web`) are named by the MD5 hash of their address. Keys are
//! relative paths (`avatars/<md5>`, `icons/<id>`, `pictures/<md5>`).
//!
//! The cache is bounded by `cache.max_mb` (read on every insert; 0: no
//! limit): the least recently used files go first. Use times survive
//! restarts as the files' modification times.
//!
//! Downloads are deduplicated: [`Cache::fetch`] tells the first asker to
//! Downloads are deduplicated: `Cache::fetch` tells the first asker to
//! download (into a temporary path), later askers wait for the same
//! download ([`Cache::finish`] answers them all).
//! download (`Cache::finish` answers them all).
//!
//! A picture from the web keeps its host's validators (`ETag`,
//! `Last-Modified`) next to it, in `validators/pictures/<md5>`: asked for
//! again, it is downloaded only if it changed ([`Cache::validators`],
//! [`Arrived::Unchanged`]).
//! again, it is downloaded only if it changed (`Cache::validators`,
//! `Arrived::Unchanged`).
use std::collections::{BTreeMap, HashMap};
use std::fmt;
@@ -184,6 +184,17 @@ pub(crate) const MAX_PICTURE_BYTES: u64 = 128 << 20;
/// does not hold a download slot.
pub(crate) const MIN_PICTURE_RATE: u64 = 8 << 10;
/// How long a picture of `size` bytes may take to arrive: a minute, plus
/// its size at [`MIN_PICTURE_RATE`], so large banners arrive on slow
/// links while a stalled transfer still ends.
pub(crate) fn image_download_time(size: u64) -> std::time::Duration {
std::time::Duration::from_secs(60 + size / MIN_PICTURE_RATE)
}
/// How long the server may take to start an image transfer (a busy server
/// answers the requests of a large channel tree in turn).
pub(crate) const IMAGE_NEGOTIATION: std::time::Duration = std::time::Duration::from_secs(30);
/// The cache key of a picture on the web: only `http` and `https`
/// addresses (blanks around one are not part of it).
pub(crate) fn picture_key(url: &str) -> Option<String> {
@@ -489,6 +500,15 @@ mod tests {
use super::*;
#[test]
fn large_pictures_get_time_to_arrive() {
let secs = std::time::Duration::from_secs;
assert_eq!(image_download_time(0), secs(60));
assert_eq!(image_download_time(100 << 10), secs(72));
// The largest picture, at the slowest rate allowed.
assert_eq!(image_download_time(MAX_PICTURE_BYTES), secs(60 + 16384));
}
fn temp_dir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"voelin-cache-{tag}-{}-{:?}",
+7 -2
View File
@@ -453,10 +453,15 @@ mod tests {
lookups
}
/// `lookups` asking the real `/.well-known/tsgw` at `port`.
/// `lookups` asking the real `/.well-known/tsgw` at `port`. A name is
/// connected to through the system's resolver, except `localhost`: the
/// servers of the tests listen on 127.0.0.1, and some machines resolve
/// `localhost` to `::1` only. (The test cares that the gateway is asked at
/// the name `localhost`, not what the resolver makes of it.)
fn probing(mut lookups: Lookups, port: u16) -> Lookups {
lookups.probe = Arc::new(move |name| {
async move { timeout(PROBE_TIMEOUT, well_known(&name, port)).await.ok()?.ok() }.boxed()
let host = if name == "localhost" { "127.0.0.1".to_owned() } else { name };
async move { timeout(PROBE_TIMEOUT, well_known(&host, port)).await.ok()?.ok() }.boxed()
});
lookups
}
+43 -32
View File
@@ -32,13 +32,13 @@
//! never downloaded). [`crate::Command::SetAvatar`] uploads our own.
use std::fmt;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use serde::Serialize;
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt, AsyncWrite, AsyncWriteExt};
/// Picked by the caller; the answer carries it back.
pub type RequestId = u64;
@@ -106,11 +106,11 @@ impl TransferState {
}
/// Reports a transfer's states.
pub(crate) type Report = Arc<dyn Fn(TransferState) + Send + Sync>;
pub type Report = Arc<dyn Fn(TransferState) + Send + Sync>;
/// Where a running download writes.
#[derive(Clone, Debug)]
pub(crate) enum Sink {
pub enum Sink {
/// Write `part` (appending with `append`), then rename it to `dest`.
File {
part: PathBuf,
@@ -168,9 +168,10 @@ impl Progress<'_> {
const CHUNK: usize = 64 * 1024;
/// Receive a file: `size` bytes in total, `offset` of them already in the
/// sink. Reports `Started`, `Progress` and the final state.
pub(crate) async fn download(
mut stream: TcpStream,
/// sink; `stream` carries the rest. Reports `Started`, `Progress` and the
/// final state.
pub(crate) async fn download<R: AsyncRead + Unpin>(
mut stream: R,
size: u64,
offset: u64,
sink: Sink,
@@ -185,8 +186,8 @@ pub(crate) async fn download(
});
}
async fn receive(
stream: &mut TcpStream,
async fn receive<R: AsyncRead + Unpin>(
stream: &mut R,
size: u64,
offset: u64,
sink: &Sink,
@@ -198,19 +199,22 @@ async fn receive(
let mut done = offset;
match sink {
Sink::File { part, dest, append } => {
// The directory and the file are made in one step, without a pause in
// which the task could be stopped: a cancel stops the task, waits for
// it and then removes the part file, so what the task made must be
// there by then (a pending open on the blocking pool would not be).
if let Some(dir) = part.parent().filter(|d| !d.as_os_str().is_empty()) {
tokio::fs::create_dir_all(dir)
.await
.map_err(|e| format!("{}: {e}", dir.display()))?;
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
}
let mut file = tokio::fs::OpenOptions::new()
.create(true)
.write(true)
.append(*append)
.truncate(!*append)
.open(part)
.await
.map_err(|e| format!("{}: {e}", part.display()))?;
let mut file = tokio::fs::File::from_std(
std::fs::OpenOptions::new()
.create(true)
.write(true)
.append(*append)
.truncate(!*append)
.open(part)
.map_err(|e| format!("{}: {e}", part.display()))?,
);
let received = async {
while done < size {
let n = stream.read(&mut buf).await.map_err(|e| e.to_string())?;
@@ -253,26 +257,34 @@ async fn receive(
}
}
/// Send `file` from `offset` (`size` bytes in total). Reports `Started`,
/// `Progress` and the final state.
pub(crate) async fn upload(
mut stream: TcpStream,
/// Send `file` from `offset` (`size` bytes in total) into `writer`, then end
/// it and wait for `stored`, which resolves once the server has the file.
/// Reports `Started`, `Progress` and the final state.
pub(crate) async fn upload_to<W, F>(
mut writer: W,
stored: F,
file: PathBuf,
size: u64,
offset: u64,
progress_every: Duration,
report: Report,
) {
) where
W: AsyncWrite + Unpin,
F: Future<Output = Result<(), String>>,
{
report(TransferState::Started { size, offset });
let result = send(&mut stream, &file, size, offset, progress_every, &report).await;
let result = match send(&mut writer, &file, size, offset, progress_every, &report).await {
Ok(()) => stored.await,
Err(e) => Err(e),
};
report(match result {
Ok(()) => TransferState::Done { size, path: Some(file), data: None },
Err(e) => TransferState::Failed(e),
});
}
async fn send(
stream: &mut TcpStream,
async fn send<W: AsyncWrite + Unpin>(
stream: &mut W,
path: &Path,
size: u64,
offset: u64,
@@ -300,8 +312,6 @@ async fn send(
}
stream.flush().await.map_err(|e| e.to_string())?;
stream.shutdown().await.map_err(|e| e.to_string())?;
// The server closes the connection once it has everything.
let _ = tokio::time::timeout(Duration::from_secs(30), stream.read(&mut buf[..1])).await;
Ok(())
}
@@ -421,7 +431,7 @@ fn percent_decode(text: &str) -> Option<String> {
mod tests {
use std::sync::Mutex;
use tokio::net::TcpListener;
use tokio::net::{TcpListener, TcpStream};
use super::*;
@@ -562,7 +572,8 @@ mod tests {
});
let (report, states) = recorder();
let stream = TcpStream::connect(addr).await.unwrap();
upload(stream, file.clone(), 10, 4, Duration::ZERO, report).await;
let (_, write) = tokio::io::split(stream);
upload_to(write, async { Ok(()) }, file.clone(), 10, 4, Duration::ZERO, report).await;
assert_eq!(server.await.unwrap(), b"456789");
assert!(matches!(states.lock().unwrap().last(), Some(TransferState::Done { .. })));
assert_eq!(md5_file(&file).unwrap(), "781e5e245d69b566979b86e28d23f2c7");
+44 -19
View File
@@ -61,6 +61,7 @@ use voelin_gateway_proto::{
HistoryEntry, HistoryQuery, PermRule, PermRuleInfo, PinInfo, RsvpStatus, StreamEntry,
StreamSpec, TopicInfo, UserRef,
};
use voelin_identity::IdentityBlob;
use voelin_model::{ChannelId, ChatTarget, Presence};
use voelin_store::WriteOutcome;
@@ -91,13 +92,23 @@ pub(crate) enum GatewayEvent {
Disconnected(Option<String>),
}
/// The TeamSpeak identity of a blob, or why a gateway cannot be logged in to
/// with it.
fn login_identity(blob: &IdentityBlob) -> Result<tsclientlib::Identity, String> {
crate::ts::identity::from_blob(blob).map_err(|e| e.to_string())
}
/// Connect to a gateway (`ws://…/v1` or `wss://…/v1`) and log in with a
/// TeamSpeak identity.
/// TeamSpeak identity (a blob of kind `teamspeak`, see
/// [`crate::ts::identity::to_blob`]; one that is none is refused as
/// [`ErrorCode::AuthFailed`], the way the gateway would).
pub async fn connect(
url: &str,
identity: &tsclientlib::Identity,
identity: &IdentityBlob,
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
connect_watched(url, identity, &Progress::default()).await
let identity = login_identity(identity)
.map_err(|message| ClientError::Gateway { code: ErrorCode::AuthFailed, message })?;
connect_watched(url, &identity, &Progress::default()).await
}
/// [`connect`], telling `progress` each step (for the log).
@@ -114,10 +125,19 @@ async fn connect_watched(
/// logs in.
pub(crate) async fn run(
mut urls: Vec<String>,
identity: tsclientlib::Identity,
identity: IdentityBlob,
mut commands: mpsc::UnboundedReceiver<GatewayCmd>,
events: mpsc::UnboundedSender<GatewayEvent>,
) {
// An identity that cannot be read will not be tomorrow: like a refused login.
let identity = match login_identity(&identity) {
Ok(identity) => identity,
Err(reason) => {
debug!(%reason, "gateway: the identity cannot be read");
let _ = events.send(GatewayEvent::Disconnected(Some(reason)));
return;
}
};
// A gateway that is away (down, restarting, a network change, a proxy
// in front of it that fails) or cannot log us in yet (it does not know
// the identity before voice connected once, its server is restarting)
@@ -274,20 +294,24 @@ pub(crate) struct Observed {
}
impl Observed {
pub(crate) fn new(urls: &[String], identity: &tsclientlib::Identity) -> Self {
Self {
urls: urls.to_vec(),
key: identity.key().to_pub().to_ts(),
counter: identity.counter(),
nudged: None,
pub(crate) fn new(urls: &[String], identity: &IdentityBlob) -> Self {
let (key, counter) = Self::of(identity);
Self { urls: urls.to_vec(), key, counter, nudged: None }
}
/// The public key and the counter of an identity: an identity that cannot be
/// read has neither (and so is the same as any other that cannot).
fn of(identity: &IdentityBlob) -> (String, u64) {
match login_identity(identity) {
Ok(identity) => (identity.key().to_pub().to_ts(), identity.counter()),
Err(_) => (String::new(), 0),
}
}
/// Whether this is what is observed with.
pub(crate) fn same(&self, urls: &[String], identity: &tsclientlib::Identity) -> bool {
self.urls == urls
&& self.counter == identity.counter()
&& self.key == identity.key().to_pub().to_ts()
pub(crate) fn same(&self, urls: &[String], identity: &IdentityBlob) -> bool {
let (key, counter) = Self::of(identity);
self.urls == urls && self.counter == counter && self.key == key
}
/// Whether to try again now ([`GatewayCmd::RetryNow`]): not twice
@@ -1182,15 +1206,16 @@ mod tests {
#[test]
fn the_same_observation_is_nudged_at_most_every_5_s() {
let blob = crate::ts::identity::to_blob;
let identity = tsclientlib::Identity::create();
let urls = vec!["ws://gw.example.test:7788/v1".to_owned()];
let mut observed = Observed::new(&urls, &identity);
assert!(observed.same(&urls, &identity));
assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &identity));
assert!(!observed.same(&urls, &tsclientlib::Identity::create()));
let mut observed = Observed::new(&urls, &blob(&identity));
assert!(observed.same(&urls, &blob(&identity)));
assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &blob(&identity)));
assert!(!observed.same(&urls, &blob(&tsclientlib::Identity::create())));
// Its security level raised: logged in with the new counter.
let raised = tsclientlib::Identity::new(identity.key().clone(), identity.counter() + 1);
assert!(!observed.same(&urls, &raised));
assert!(!observed.same(&urls, &blob(&raised)));
let now = Instant::now();
assert!(observed.nudge_at(now));
assert!(!observed.nudge_at(now + Duration::from_secs(4)));
+88 -62
View File
@@ -3,7 +3,10 @@
//! The UI talks to an [`Engine`] with [`Command`]s and receives [`Event`]s.
//! Each server the user works with is a session with up to three sources:
//!
//! - **voice**: a normal client connection (visible, can talk)
//! - **voice**: a normal client connection (visible, can talk): a
//! `voelin_proto::link::Session` that the connector of the server's address
//! makes ([`Backends`], and [`ts::TsConnector`] for TeamSpeak servers; see
//! [`link`])
//! - **gateway**: a `tsgw` gateway (invisible presence, relayed chat)
//! - **query**: the user's own ServerQuery credentials (same, without a gateway)
//!
@@ -16,9 +19,9 @@
//! [`Engine::subscribe_frames`] for the frames of watched streams. The audio
//! of watched streams plays through the session's speakers by itself
//! ([`Command::SetStreamVolume`]); capture, encoding and decoding of video
//! are in [`media`] (feature `media`), and the Stream Studio (scenes of
//! are in `media` (feature `media`), and the Stream Studio (scenes of
//! sources composited into one stream, recording, a replay buffer, WHIP) in
//! [`studio`].
//! `studio`.
//!
//! Settings are a [`settings::Settings`] service: typed keys, runtime
//! values stored in the client database ahead of command line, config file
@@ -45,14 +48,13 @@
//! volume) are engine-wide ([`contacts`]).
mod audio;
mod book;
pub mod cache;
pub mod contacts;
pub mod discover;
pub mod files;
pub mod gateway;
pub mod history;
pub mod identity;
pub mod link;
#[cfg(feature = "media")]
pub mod media;
pub mod offline;
@@ -61,22 +63,21 @@ mod route;
mod session;
pub mod settings;
pub mod stream;
mod stream_types;
#[cfg(feature = "media")]
pub mod studio;
pub mod versions;
mod voice;
pub mod ts;
mod web;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::{broadcast, mpsc, watch};
use tokio::sync::{broadcast, mpsc};
pub use voelin_audio::settings::TransmitMode;
pub use voelin_audio::{AudioSettings, ProcessingSettings, VadSettings};
use voelin_model::{
Capabilities, ChannelId, ChatMessage, ChatTarget, FileRef, GroupInfo, Presence, ServerDetails,
ServerFlavor,
};
use crate::audio::{AudioEvent, AudioHandle, AudioIn};
@@ -88,14 +89,14 @@ pub use files::{Bytes, DownloadTo, FileEntry, RequestId, TransferId, TransferSta
pub use gateway::{GatewayRequest, GatewayUpdate};
use history::SharedHistory;
pub use history::{History, HistoryMessage, HistorySource};
pub use link::{Backends, VoiceOptions};
pub use offline::{OfflineMessage, OfflineMessageInfo};
pub use query::{QueryLogin, QueryTransport};
pub use route::{ChatRoute, Dedup, route_chat};
use settings::{SettingChange, Settings, SharedSettings};
use stream::{EncodedFrame, LayerId, LayerSpec, StreamInfo, StreamSetup, ViewerInfo};
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
use voelin_stream::{
EncodedFrame, LayerId, LayerSpec, SrtpProfile, StreamInfo, StreamSetup, ViewerInfo,
};
pub use voice::VoiceOptions;
pub use voelin_identity::IdentityBlob;
/// Banners are downloaded and shown by the same rule.
pub use web::is_svg;
/// Pictures from the web go through the desktop's proxy (set at startup).
@@ -110,13 +111,6 @@ pub const POKE_MESSAGE_MAX: usize = 100;
/// What the UI asks for.
#[derive(Clone, Debug)]
pub enum Command {
/// Main account proof for every current and future voice connection.
SetMytsIdentity(Option<Arc<tsproto::myts::Identity>>),
/// What voice servers are shown of the main account (its avatar and
/// badges with their certificates, its User Tag; TeamSpeak 6): sent to
/// every connection that presents the account's myTS ID, once connected
/// and when it changes; cleared on a sign-out.
SetMytsData(Option<Arc<tsclientlib::MytsData>>),
ConnectVoice {
session: SessionId,
options: Box<VoiceOptions>,
@@ -132,12 +126,15 @@ pub enum Command {
ObserveGateway {
session: SessionId,
urls: Vec<String>,
identity: Box<tsclientlib::Identity>,
/// The TeamSpeak identity to log in with ([`ts::identity::to_blob`]).
/// One that is none, or cannot be read, ends the observation with
/// its reason.
identity: Box<IdentityBlob>,
},
/// Invisible presence and relay chat with own ServerQuery credentials.
ObserveQuery {
session: SessionId,
connect: Box<voelin_query::Connect>,
connect: Box<QueryLogin>,
},
StopObserving {
session: SessionId,
@@ -248,11 +245,13 @@ pub enum Command {
session: SessionId,
layers: Vec<LayerSpec>,
},
/// SRTP protection profiles for stream connections, in order of
/// preference (a user setting; empty: the default,
/// `SrtpProfile::DEFAULT_ORDER`). Applies to connections made from now
/// on, in all sessions and those started later.
SetSrtpProfiles(Vec<SrtpProfile>),
/// SRTP protection profiles for stream connections by name (RFC 5764 and
/// RFC 7714: `AEAD_AES_128_GCM`, `AES128_CM_SHA1_80`, ...; names the stream
/// transport does not know are left out), in order of preference (the
/// `stream.srtp_profiles` setting). Empty: the transport's default order.
/// Applies to connections made from now on, in all sessions and those
/// started later.
SetSrtpProfiles(Vec<String>),
/// Watch a stream from [`Event::StreamsChanged`]. Frames arrive through
/// [`Engine::subscribe_frames`].
WatchStream {
@@ -270,7 +269,7 @@ pub enum Command {
},
/// The video of a watched stream arrives, but none of it decodes: watch
/// it in another codec the streamer offered, if there is one (a new
/// connection without this one). [`media::Viewer`] sends it.
/// connection without this one). `media::Viewer` sends it.
StreamUndecodable {
session: SessionId,
stream_id: String,
@@ -507,6 +506,30 @@ pub enum JoinFailure {
Other(String),
}
/// The software on the other end of a session, as its link names it. It is
/// for people to read; nothing branches on it (what the server can do is
/// [`Capabilities`]).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct BackendInfo {
/// What it is called ("TeamSpeak 6"); empty when it was not recognised.
pub product: String,
/// Its version as the product shows it ("6.0.0-beta13.1"); what the
/// server said, as it is, when `product` is empty.
pub version: String,
}
impl BackendInfo {
/// For a sentence: the product and the version, whichever there are
/// ("TeamSpeak 6 6.0.0-beta13.1", "TeamSpeak 3", "custom 9").
pub fn label(&self) -> String {
match (self.product.is_empty(), self.version.is_empty()) {
(false, false) => format!("{} {}", self.product, self.version),
(false, true) => self.product.clone(),
(true, _) => self.version.clone(),
}
}
}
/// What the engine reports.
#[derive(Clone, Debug)]
pub enum Event {
@@ -514,10 +537,12 @@ pub enum Event {
session: SessionId,
state: SessionState,
},
/// The server answered: its name, the software it runs and what that
/// software can do (the UI hides what it cannot).
ServerInfo {
session: SessionId,
name: String,
flavor: ServerFlavor,
backend: BackendInfo,
capabilities: Capabilities,
},
/// Full presence of the session (the UI rebuilds its view from it).
@@ -760,8 +785,18 @@ impl Engine {
}
/// Start the engine on the current tokio runtime with `settings` and
/// chat `history`.
/// chat `history`, connecting voice with the engine's own connectors
/// ([`Backends::default`]: TeamSpeak 3 and 6).
pub fn start_with(settings: Settings, history: History) -> Self {
Self::start_with_backends(settings, history, Backends::default())
}
/// Start the engine on the current tokio runtime with `settings` and
/// chat `history`, connecting voice with the connectors in `backends`:
/// the one for the scheme of a session's address makes its
/// `voelin_proto::link::Session`.
pub fn start_with_backends(settings: Settings, history: History, backends: Backends) -> Self {
let link = Arc::new(link::SessionLink::new(backends));
let (commands, rx) = mpsc::unbounded_channel();
let (events, _) = broadcast::channel(4096);
// About a minute of one watched stream.
@@ -773,7 +808,7 @@ impl Engine {
history,
cache: SharedCache::new(Cache::new(Cache::default_dir())),
};
tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone()));
tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone(), link));
Self { commands, events, frames, runtime: tokio::runtime::Handle::current(), shared }
}
@@ -857,19 +892,18 @@ async fn run(
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
engine: Shared,
link: Arc<link::SessionLink>,
) {
let Shared { settings: shared, history, cache, contacts } = engine.clone();
// Before any command: a contact set meanwhile would be lost.
contacts.load().await;
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
let (myts_identity, _) = watch::channel(None);
let (myts_data, _) = watch::channel(None);
let mut current = shared.current();
// Pruning: at start, then hourly (and when the setting changes).
let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600));
let mut changes = current.subscribe();
let mut settings = AudioSettings::default();
let mut srtp_profiles: Option<Vec<SrtpProfile>> = None;
let mut srtp_profiles: Option<Vec<String>> = None;
let mut mic_test: Option<AudioHandle> = None;
loop {
let input = tokio::select! {
@@ -908,29 +942,6 @@ async fn run(
},
};
let id = match command {
Command::SetMytsIdentity(identity) => {
// Still no account is no change: every notification restarts
// handshakes and sends `updatemytsid` on every connection. Any
// account is (each connection's proof is signed anew).
myts_identity.send_if_modified(|current| {
if current.is_none() && identity.is_none() {
return false;
}
*current = identity;
true
});
continue;
}
Command::SetMytsData(data) => {
myts_data.send_if_modified(|current| {
if *current == data {
return false;
}
*current = data;
true
});
continue;
}
Command::SetAudioSettings(new) => {
settings = (*new).clone();
for s in sessions.values() {
@@ -1006,8 +1017,7 @@ async fn run(
frames.clone(),
settings.clone(),
engine.clone(),
myts_identity.subscribe(),
myts_data.subscribe(),
link.clone(),
);
if let Some(profiles) = &srtp_profiles {
s.send(Command::SetSrtpProfiles(profiles.clone()));
@@ -1086,9 +1096,7 @@ fn command_session(command: &Command) -> SessionId {
| Command::DeleteOfflineMessage { session, .. }
| Command::SetOfflineMessageRead { session, .. }
| Command::CloseSession { session } => *session,
Command::SetMytsIdentity(_)
| Command::SetMytsData(_)
| Command::SetAudioSettings(_)
Command::SetAudioSettings(_)
| Command::SetSrtpProfiles(_)
| Command::TestMicrophone { .. }
| Command::SetSetting { .. }
@@ -1111,3 +1119,21 @@ fn command_session(command: &Command) -> SessionId {
fn one_rustls_crypto_provider() {
let _ = rustls::ClientConfig::builder();
}
#[cfg(test)]
mod tests {
use super::BackendInfo;
#[test]
fn a_backend_reads_as_its_product_and_version() {
let backend = |product: &str, version: &str| BackendInfo {
product: product.into(),
version: version.into(),
};
assert_eq!(backend("TeamSpeak 6", "6.0.0-beta13.1").label(), "TeamSpeak 6 6.0.0-beta13.1");
assert_eq!(backend("TeamSpeak 3", "").label(), "TeamSpeak 3");
// Not recognised: the version string alone, or nothing.
assert_eq!(backend("", "custom 9").label(), "custom 9");
assert_eq!(BackendInfo::default().label(), "");
}
}
+265
View File
@@ -0,0 +1,265 @@
//! The registry of the engine's connectors, by address scheme.
//!
//! A session's voice source is a `voelin_proto::link::Session`
//! (`docs/session-seam.md` section 4.1). Which backend makes it is the
//! scheme of the address: [`Backends`] holds the plain connectors of
//! `voelin_proto::link::Connectors` (the Voelin protocol's QUIC connector
//! later, `FakeConnector` in tests) and the in-process connectors, which
//! also hand the engine what a `Session` has no room for yet (the TeamSpeak 6
//! stream task, [`StreamPort`]).
use std::sync::Arc;
use tokio::sync::mpsc;
use voelin_proto::link::{
AccountAgent, BoxFuture, ConnectParams, Connected, Connector, Connectors, HostIdentity,
HostTrust, SessionError,
};
use voelin_stream::PeerConfig;
use super::LinkCtx;
use crate::stream::{OwnStreamEvent, StreamCmd};
use crate::ts::TsConnector;
/// The scheme of the TeamSpeak servers a bookmark names without one.
pub(crate) const TEAMSPEAK_SCHEME: &str = "ts3server";
/// What comes back from the stream task of a connection that has one.
#[derive(Debug)]
pub(crate) enum StreamEvent {
/// Our own stream's life, for the gateway directory.
OwnStream(OwnStreamEvent),
/// An Opus frame of a watched stream, for the audio thread.
Audio { stream: String, time: u64, data: Arc<[u8]> },
/// A watched stream ended.
AudioEnded(String),
}
/// The in-process channel of TeamSpeak 6 streams past the `Session` trait
/// (`docs/session-seam.md` section 6.4): TeamSpeak 6 streams are peer to peer
/// and not v1 entities yet, so the commands go to the connection's stream
/// task and its events come back here.
pub(crate) struct StreamPort {
send: Box<dyn Fn(StreamCmd) + Send + Sync>,
/// What the stream task reports.
pub(crate) events: mpsc::UnboundedReceiver<StreamEvent>,
}
impl StreamPort {
/// A port whose commands go to `send`.
pub(crate) fn new(
send: impl Fn(StreamCmd) + Send + Sync + 'static,
events: mpsc::UnboundedReceiver<StreamEvent>,
) -> Self {
Self { send: Box::new(send), events }
}
/// Give the stream task a command.
pub(crate) fn send(&self, cmd: StreamCmd) {
(self.send)(cmd);
}
}
/// What an in-process backend needs besides the connect parameters.
#[derive(Clone)]
pub(crate) struct LocalCtx {
/// The session's side of the engine: its id, event bus, frames and
/// settings.
pub(crate) link: LinkCtx,
/// Open the audio devices (the stream task plays what streams carry).
pub(crate) audio: bool,
/// Network settings for stream peer connections.
pub(crate) stream_peer: PeerConfig,
}
impl LocalCtx {
pub(crate) fn new(link: LinkCtx, audio: bool, stream_peer: PeerConfig) -> Self {
Self { link, audio, stream_peer }
}
/// A context for a connection made outside an engine (a test or a tool
/// that calls a connector itself): a session of its own that nobody
/// listens to.
pub(crate) fn standalone() -> Self {
let (events, _) = tokio::sync::broadcast::channel(16);
let (frames, _) = tokio::sync::broadcast::channel(16);
let link = LinkCtx {
session: 0,
events,
frames,
settings: crate::settings::SharedSettings::new(crate::settings::Settings::in_memory()),
};
Self { link, audio: false, stream_peer: PeerConfig::default() }
}
}
/// A connection an in-process connector made.
pub(crate) struct LocalConnected {
pub(crate) connected: Connected,
/// The stream task's port, for a backend that runs one.
pub(crate) streams: Option<StreamPort>,
}
/// A connector that runs in this process and can use the engine's context
/// ([`LocalCtx`]); its sessions may come with a [`StreamPort`].
pub(crate) trait LocalConnector: Connector {
/// Whether this connector serves addresses of `scheme`. By default, the
/// schemes it names.
fn accepts(&self, scheme: &str) -> bool {
self.schemes().contains(&scheme)
}
/// Connect with the engine's context.
fn connect_local(
&self,
params: ConnectParams,
ctx: LocalCtx,
) -> BoxFuture<Result<LocalConnected, SessionError>>;
}
/// The connectors of an engine, found by the scheme of an address.
///
/// A scheme served by an in-process connector goes to it, one served by a
/// plain connector ([`Backends::register`]) to that. An address without a
/// scheme is a TeamSpeak bookmark and is taken for a `ts3server` one.
#[derive(Clone)]
pub struct Backends {
connectors: Connectors,
locals: Vec<Arc<dyn LocalConnector>>,
account: Option<Arc<dyn AccountAgent>>,
/// The connections' trust in hosts that are neither valid nor pinned.
trust: Option<Arc<dyn HostTrust>>,
}
impl Default for Backends {
/// The engine's connectors: TeamSpeak 3 and 6 (`ts3server://` and
/// `teamspeak://`, and an address without a scheme).
fn default() -> Self {
let mut backends = Self::empty();
backends.register_teamspeak(TsConnector::new());
backends
}
}
impl Backends {
/// No connector at all. ([`Backends::default`] has the TeamSpeak one.)
pub fn empty() -> Self {
Self { connectors: Connectors::default(), locals: Vec::new(), account: None, trust: None }
}
/// Register a connector for the schemes it names.
pub fn register(&mut self, connector: Arc<dyn Connector>) {
self.connectors.register(connector);
}
pub(crate) fn register_local(&mut self, connector: Arc<dyn LocalConnector>) {
self.locals.push(connector);
}
/// Register the TeamSpeak connector for the schemes it names
/// (`ts3server`, `teamspeak`, and addresses without a scheme).
/// [`Backends::default`] registers one of its own; register yours to keep a
/// clone of it, whose [`TsConnector::set_myts_identity`] and
/// [`TsConnector::set_myts_data`] set the main myTeamSpeak account for every
/// connection it makes.
pub fn register_teamspeak(&mut self, connector: TsConnector) {
self.register_local(Arc::new(connector));
}
/// The device's Voelin account, which every connect hands the connector as
/// `ConnectParams::account`. No connector reads it yet: the TeamSpeak
/// connector takes the myTeamSpeak account it presents from its own setters
/// ([`TsConnector::set_myts_identity`], [`TsConnector::set_myts_data`]), and a
/// Voelin host's connector (the QUIC one, for its certificate) does not exist
/// yet. Follow-up H4 of `docs/session-seam.md` (11.2) moves the myTeamSpeak
/// proof from those setters to this hook. None is the default.
pub fn set_account(&mut self, agent: Option<Arc<dyn AccountAgent>>) {
self.account = agent;
}
/// The account agent, if one was set ([`Backends::set_account`]).
pub fn account(&self) -> Option<Arc<dyn AccountAgent>> {
self.account.clone()
}
/// Decide about hosts that are neither valid nor pinned. The default
/// refuses them: there is no trust dialog yet, and TeamSpeak has no host
/// key.
pub fn set_trust(&mut self, trust: Option<Arc<dyn HostTrust>>) {
self.trust = trust;
}
pub(crate) fn trust(&self) -> Arc<dyn HostTrust> {
self.trust.clone().unwrap_or_else(|| Arc::new(RefuseUnknownHosts))
}
/// The scheme of an address, lowercase; a TeamSpeak bookmark's when there
/// is none.
pub(crate) fn scheme(address: &str) -> String {
match address.split_once("://") {
Some((scheme, _)) => scheme.to_ascii_lowercase(),
None => TEAMSPEAK_SCHEME.to_owned(),
}
}
/// Open a session to `params.address` with the connector of its scheme.
pub(crate) fn connect(
&self,
params: ConnectParams,
ctx: LocalCtx,
) -> BoxFuture<Result<LocalConnected, SessionError>> {
let scheme = Self::scheme(&params.address);
if let Some(local) = self.locals.iter().find(|c| c.accepts(&scheme)) {
return local.connect_local(params, ctx);
}
// Not `Connectors::connect`, which names the whole address when none serves it:
// the text is shown, and a TeamSpeak link carries a channel password.
let Some(connector) = self.connectors.for_address(&params.address) else {
let shown = without_query(&params.address).to_owned();
return Box::pin(async move {
Err(SessionError::Protocol(format!("no connector for {shown}")))
});
};
let connect = connector.connect(params);
Box::pin(async move {
let connected = connect.await?;
Ok(LocalConnected { connected, streams: None })
})
}
}
/// An address as it may be shown or logged: without its query and fragment,
/// where a link keeps a channel password or a host pin.
pub(crate) fn without_query(address: &str) -> &str {
address.split(['?', '#']).next().unwrap_or_default()
}
/// Refuses every host that asks to be trusted.
struct RefuseUnknownHosts;
impl HostTrust for RefuseUnknownHosts {
fn confirm(&self, _host: HostIdentity) -> BoxFuture<bool> {
Box::pin(async { false })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_bookmark_without_a_scheme_is_a_teamspeak_server() {
assert_eq!(Backends::scheme("ts.example.com:9987"), "ts3server");
assert_eq!(Backends::scheme("[::1]:9987"), "ts3server");
assert_eq!(Backends::scheme("TS3Server://ts.example.com"), "ts3server");
assert_eq!(Backends::scheme("teamspeak://x"), "teamspeak");
assert_eq!(Backends::scheme("voelin://host/i/code"), "voelin");
}
#[test]
fn an_address_is_shown_without_its_secrets() {
assert_eq!(without_query("ts3server://h?port=1&channelpassword=hunter2"), "ts3server://h");
assert_eq!(without_query("voelin://h/i/code#h=abcd"), "voelin://h/i/code");
assert_eq!(without_query("host:9987"), "host:9987");
}
}
+261
View File
@@ -0,0 +1,261 @@
//! What a session hands the connector of an address: the `ConnectParams` of
//! a [`VoiceOptions`] (`docs/session-seam.md` section 4.2).
//!
//! The options are the engine's own, and a connector reads them back: the
//! address is the link of the bookmark (a `ts3server://` link for a
//! bookmark that names a TeamSpeak server by `host[:port]`), the nickname,
//! the server password and the privilege key are in the hello, the identity
//! is the credential. What v1 has no field for yet (the channel to join and
//! its password, the client version a TeamSpeak server is shown) rides in
//! the address, as parameters of the link.
use std::sync::Arc;
use std::time::Duration;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use bytes::Bytes;
use voelin_identity::{IdentityBlob, KIND_TEAMSPEAK};
use voelin_model::Link;
use voelin_proto::link::{ConnectParams, Credential, IssuerTrust, MediaSink, SessionError};
use voelin_proto::v1;
use super::{Backends, VoiceOptions, without_query};
/// The link parameter that carries the client version to impersonate: the
/// user's spec (`VoiceOptions::client_version`), in unpadded URL-safe base64.
/// The connector for TeamSpeak resolves it; other connectors never read it.
pub(crate) const VERSION_PARAM: &str = "client_version";
/// The connect parameters of a connection, from the options the session was
/// asked to connect with.
///
/// The address is the link of the bookmark (the channel and its password
/// ride in it, and so does the client version to claim, until v1 has fields
/// for them), the server password is `Hello.password` and the privilege key
/// `Hello.invite_code`. The identity goes as the credential of its kind; no
/// account is used yet.
///
/// An address a link cannot carry is refused here ([`bookmark`]), and so is
/// an identity that is of no kind a connector can use.
pub(crate) fn connect_params(
options: &VoiceOptions,
media: Arc<dyn MediaSink>,
backends: &Backends,
) -> Result<ConnectParams, SessionError> {
let hello = v1::Hello {
version: 1,
client: Some(v1::ClientInfo {
name: "Voelin".into(),
version: voelin_platform::crash::app_version().to_owned(),
platform: std::env::consts::OS.into(),
kind: v1::ClientKind::User as i32,
}),
nickname: options.nickname.clone(),
password: options.server_password.clone().unwrap_or_default(),
invite_code: options.token.clone().unwrap_or_default(),
..Default::default()
};
Ok(ConnectParams {
address: address_link(options)?,
credential: credential(options.identity.as_ref())?,
linked: Vec::new(),
account: backends.account(),
issuer_trust: IssuerTrust::Unknown,
hello,
host_pin: None,
trust: backends.trust(),
media,
push_capacity: 1024,
timeout: Duration::from_secs(35),
})
}
/// The credential of an identity (`docs/session-seam.md` section 7). A
/// TeamSpeak identity goes as the JSON the key store keeps, and none at all as
/// an empty one, for which the TeamSpeak connector makes an identity up (the
/// protocol's convention for "generate one", follow-up P11); a Voelin key
/// signs. A TeamSpeak identity that holds no JSON is refused: sent as it is,
/// it would be that same empty blob and be taken for the request to make one
/// up, which only the absence of an identity may be.
fn credential(identity: Option<&IdentityBlob>) -> Result<Credential, SessionError> {
let Some(blob) = identity else {
return Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: Bytes::new() });
};
if blob.is_teamspeak() {
if blob.json.trim().is_empty() {
return Err(SessionError::Protocol(
"the TeamSpeak identity cannot be read: it is empty".into(),
));
}
let json = Bytes::copy_from_slice(blob.json.as_bytes());
Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: json })
} else if blob.is_voelin() {
let key = blob.voelin_key().map_err(|e| {
SessionError::Protocol(format!("the Voelin identity cannot be read: {e}"))
})?;
Ok(Credential::Voelin(Arc::new(key)))
} else {
Err(SessionError::Protocol(format!(
"an identity of kind {:?} cannot be used to connect",
blob.kind
)))
}
}
/// The `ts3server://` link of the options' address, with the channel to join
/// and the client version to claim.
fn address_link(options: &VoiceOptions) -> Result<String, SessionError> {
let mut link = match Link::parse(&options.address) {
Some(Link::Server(link)) => link,
// Not a TeamSpeak link, or none: a bookmark's `host[:port]`.
_ if !options.address.contains("://") => bookmark(&options.address)?,
// Some other scheme: as given, for the connector of that scheme.
_ => return Ok(options.address.clone()),
};
link.channel = options.channel.clone().filter(|c| !c.is_empty()).or(link.channel);
link.channel_password =
options.channel_password.clone().filter(|p| !p.is_empty()).or(link.channel_password);
let mut url = link.to_url();
if let Some(spec) = &options.client_version {
url.push(if url.contains('?') { '&' } else { '?' });
url.push_str(VERSION_PARAM);
url.push('=');
url.push_str(&URL_SAFE_NO_PAD.encode(spec));
}
Ok(url)
}
/// The link to a bookmark's `host[:port]`.
///
/// A link cannot say everything an address can: it drops a port that is no
/// port (`ServerLink::new` takes `host:99999` for the host `host` and joins
/// the default port), and it ends the host at a `?`, `#` or `/` and decodes a
/// `%` (so that a `?` in the host would hide the channel behind the next
/// one). The TeamSpeak library refuses such an address when it resolves it;
/// so does this, in words, instead of connecting to something else.
fn bookmark(address: &str) -> Result<voelin_model::ServerLink, SessionError> {
let address = address.trim();
// Without the query: a link keeps secrets in it.
let shown = without_query(address);
let not_an_address = || SessionError::Protocol(format!("not a server address: {shown}"));
if address.is_empty()
|| address
.chars()
.any(|c| matches!(c, '?' | '#' | '/' | '%') || c.is_whitespace() || c.is_control())
{
return Err(not_an_address());
}
// The text after the port's colon: `[v6]:port`, or `host:port` with the one
// colon (more colons are an IPv6 address without a port).
let port = if let Some(rest) = address.strip_prefix('[') {
let (_, after) = rest.split_once(']').ok_or_else(not_an_address)?;
(!after.is_empty()).then(|| after.strip_prefix(':').unwrap_or(after))
} else {
address.rsplit_once(':').filter(|(host, _)| !host.contains(':')).map(|(_, port)| port)
};
if let Some(port) = port
&& !port.parse::<u16>().is_ok_and(|port| port != 0)
{
return Err(SessionError::Protocol(format!(
"the port in {shown} is not a number from 1 to 65535"
)));
}
Ok(voelin_model::ServerLink::new(address))
}
#[cfg(test)]
mod tests {
use super::*;
use voelin_identity::IdentityKey;
fn params(options: &VoiceOptions) -> Result<ConnectParams, SessionError> {
let (media, _rx) = voelin_proto::test_util::media_channel();
connect_params(options, media, &Backends::empty())
}
/// The identity of the options is the credential of its kind: a TeamSpeak
/// identity as the JSON the key store keeps, none as the empty blob a
/// connector makes an identity up for, a Voelin key as its signer.
#[test]
fn an_identity_is_the_credential_of_its_kind() {
let mut options = VoiceOptions::new("ts.example.com", "nick");
let none = params(&options).unwrap();
assert!(matches!(
&none.credential,
Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty()
));
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, r#"{"key":"k"}"#));
let sent = params(&options).unwrap();
assert!(matches!(
&sent.credential,
Credential::Foreign { kind: "teamspeak", blob } if &blob[..] == br#"{"key":"k"}"#
));
let key = IdentityKey::generate().unwrap();
options.identity = Some(IdentityBlob::voelin(&key).unwrap());
let Credential::Voelin(signer) = params(&options).unwrap().credential else {
panic!("a Voelin credential")
};
assert_eq!(signer.public_key(), key.public_key());
assert_eq!(signer.sign(b"hello"), key.sign(b"hello"));
// A Voelin blob whose key cannot be read, and a kind that connects to
// nothing: refused in words, without the JSON.
options.identity = Some(IdentityBlob::new("voelin", "x", 0, "hunter2"));
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
assert!(
text.starts_with("the Voelin identity cannot be read") && !text.contains("hunter2")
);
options.identity = Some(IdentityBlob::new("account", "x", 0, "hunter2"));
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
assert_eq!(text, "an identity of kind \"account\" cannot be used to connect");
}
/// A TeamSpeak identity with no JSON is no identity. The empty blob is
/// what asks the TeamSpeak connector to make one up (`identity: None`), so
/// it is refused here instead of being sent as that request.
#[test]
fn a_teamspeak_identity_without_json_is_refused() {
let mut options = VoiceOptions::new("ts.example.com", "nick");
for json in ["", " \n\t"] {
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, json));
let Err(SessionError::Protocol(text)) = params(&options) else {
panic!("a refusal for {json:?}")
};
assert_eq!(text, "the TeamSpeak identity cannot be read: it is empty");
}
// No identity at all is the request to make one up, as before.
options.identity = None;
assert!(matches!(
params(&options).unwrap().credential,
Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty()
));
}
/// The client version spec rides the link as it was typed, whatever it
/// holds, and only for an address that is a TeamSpeak bookmark or link.
#[test]
fn the_client_version_spec_rides_the_link_unchanged() {
let spec = |address: &str, spec: &str| {
let mut options = VoiceOptions::new(address, "nick");
options.client_version = Some(spec.into());
params(&options).unwrap().address
};
let address = spec("ts.example.com:9988", "windows@3.6.2 [Build: 1]&x=#");
let (_, query) = address.split_once('?').unwrap();
let text = query
.split('&')
.find_map(|pair| pair.strip_prefix("client_version="))
.expect("the parameter");
let decoded = URL_SAFE_NO_PAD.decode(text).unwrap();
assert_eq!(decoded, b"windows@3.6.2 [Build: 1]&x=#");
// Another scheme is left as it is: its connector has no use for a TeamSpeak
// client's version.
assert_eq!(spec("voelin://host/i/code", "generic"), "voelin://host/i/code");
// No spec, no parameter.
let options = VoiceOptions::new("ts.example.com", "nick");
assert!(!params(&options).unwrap().address.contains(VERSION_PARAM));
}
}
@@ -0,0 +1,363 @@
//! The session through an in-memory [`ServerLink`]: a `FakeLink` hands each
//! connection the test asks for to the test, which plays the server by
//! sending scripted [`LinkEvent`]s and reads the [`LinkCmd`]s the session
//! gives. These are the tests that need the inner link itself:
//!
//! - the stream commands, which travel on the in-process port of the link
//! and which a `voelin_proto::link::Session` has no part in until the
//! stream task moves (`docs/session-seam.md` sections 6.4 and 9.2);
//! - the order in which a reconnect shuts the streams and the old connection
//! down, which is the order of the one queue `LinkSession` keeps;
//! - a link that keeps talking after the engine replaced its connection,
//! which a closed `FakeSession` cannot do on purpose.
//!
//! (They were integration tests while the inner link was public; it is the
//! TeamSpeak module's now, and so are these.)
//!
//! Presence, chat, the dedup of a message that comes twice, history, transfers
//! and the rest of what the engine does with a session are tested on the
//! protocol repository's fake host in `tests/session_fake.rs`. Nothing here
//! needs a TeamSpeak server or a TeamSpeak type.
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::{broadcast, mpsc};
use super::{Backends, LinkCmd, LinkCtx, LinkEvent};
use crate::settings::Settings;
use crate::stream::{StreamCmd, StreamSetup};
use crate::ts::ts_session::LinkConnector;
use crate::ts::{ConnectOptions, ServerLink};
use crate::{
BackendInfo, Command, Engine, Event, History, SessionId, SessionState, VoiceOptions, VoiceState,
};
use voelin_model::{
Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence,
ServerDetails,
};
/// A connection the session asked the link for.
struct Conn {
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
}
impl Conn {
/// Play `script`, the server's side, in order.
fn play(&self, script: impl IntoIterator<Item = LinkEvent>) {
for event in script {
self.events.send(event).expect("the session listens");
}
}
/// The next command the session gave.
async fn cmd(&mut self) -> LinkCmd {
tokio::time::timeout(Duration::from_secs(10), self.cmds.recv())
.await
.expect("a command in time")
.expect("the session keeps the connection")
}
}
/// Hands every connection to the test.
struct FakeLink {
conns: mpsc::UnboundedSender<Conn>,
}
impl FakeLink {
fn new() -> (Self, mpsc::UnboundedReceiver<Conn>) {
let (conns, rx) = mpsc::unbounded_channel();
(Self { conns }, rx)
}
}
impl ServerLink for FakeLink {
fn spawn(
&self,
_options: ConnectOptions,
_ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
) {
let _ = self.conns.send(Conn { cmds, events });
}
}
const SESSION: SessionId = 1;
const SERVER_UID: &str = "fake-server=";
const ME: u16 = 7;
const ME_UID: &str = "me=";
const LOBBY: ChannelId = 1;
const GAMES: ChannelId = 2;
struct Harness {
engine: Engine,
events: broadcast::Receiver<Event>,
conns: mpsc::UnboundedReceiver<Conn>,
}
impl Harness {
fn start() -> Self {
let (link, conns) = FakeLink::new();
let mut backends = Backends::empty();
backends.register_local(Arc::new(LinkConnector::any(Arc::new(link))));
let engine =
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
let events = engine.subscribe();
Self { engine, events, conns }
}
/// Ask for a voice connection and take it from the link.
async fn connect(&mut self) -> Conn {
let options = VoiceOptions::new("fake.test:9987", "tester");
self.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) });
tokio::time::timeout(Duration::from_secs(10), self.conns.recv())
.await
.expect("the session spawns the link")
.expect("the link lives")
}
/// The next event `f` picks, skipping the others.
async fn next<T>(&mut self, mut f: impl FnMut(Event) -> Option<T>) -> T {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
if let Some(t) = f(self.events.recv().await.expect("engine events")) {
return t;
}
}
})
.await
.expect("event in time")
}
/// The next state of the session that `ok` accepts.
async fn state(&mut self, mut ok: impl FnMut(&SessionState) -> bool) -> SessionState {
self.next(|e| match e {
Event::State { state, .. } if ok(&state) => Some(state),
_ => None,
})
.await
}
/// The next live chat message.
async fn chat(&mut self) -> ChatMessage {
self.next(|e| match e {
Event::Chat { message, .. } => Some(message),
_ => None,
})
.await
}
}
fn now_ms() -> i64 {
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64
}
fn capabilities(streams: bool) -> Capabilities {
Capabilities { streams, file_transfer: true, ..Default::default() }
}
fn backend() -> BackendInfo {
BackendInfo { product: "Fake".into(), version: "1.2".into() }
}
fn connected(streams: bool) -> LinkEvent {
LinkEvent::Connected {
name: "Fake Server".into(),
backend: backend(),
capabilities: capabilities(streams),
own_client: ME,
server_uid: SERVER_UID.into(),
own_uid: Some(ME_UID.into()),
}
}
/// A client as a TeamSpeak link reports one: with its database id, and not
/// talking (who talks comes from the media, which the session derives).
fn client(id: u16, nickname: &str, channel: ChannelId) -> ClientInfo {
ClientInfo {
id,
uid: Some(format!("{nickname}=")),
nickname: nickname.into(),
channel,
talking: Some(false),
database_id: Some(1_000 + u64::from(id)),
..Default::default()
}
}
/// Two channels, three clients; we are in the second channel. The shape is
/// what a TeamSpeak link reports: sibling channels form an order chain, the
/// server is named and has its unique id.
fn presence() -> Presence {
let channel =
|id, name: &str, order| ChannelInfo { id, name: name.into(), order, ..Default::default() };
let mut presence = Presence { server_name: "Fake Server".into(), ..Default::default() };
presence.server = ServerDetails {
name: "Fake Server".into(),
uid: Some(SERVER_UID.into()),
version: backend().version,
..Default::default()
};
presence.channels.insert(LOBBY, channel(LOBBY, "Lobby", 0));
presence.channels.insert(GAMES, channel(GAMES, "Games", LOBBY));
let me = ClientInfo { uid: Some(ME_UID.into()), ..client(ME, "tester", GAMES) };
for c in [me, client(8, "alice", GAMES), client(9, "bob", LOBBY)] {
presence.clients.insert(c.id, c);
}
presence
}
fn message(author: &str, text: &str, ts_ms: i64) -> ChatMessage {
ChatMessage {
target: ChatTarget::Channel(GAMES),
author_name: author.into(),
author_uid: Some(format!("{author}=")),
author_id: None,
text: text.into(),
ts_ms,
via_relay: false,
blocked: false,
}
}
/// Stream commands reach a link that has streams in its capabilities, and
/// end with the connection; a link without them is spared. (The rest of what
/// the user asks for is checked on the fake host in `session_fake.rs`.)
#[tokio::test(flavor = "multi_thread")]
async fn stream_commands_reach_a_link_with_streams() {
let mut h = Harness::start();
let mut conn = h.connect().await;
conn.play([
connected(false),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
h.state(|s| s.own_channel == Some(GAMES)).await;
// No streams in the capabilities: the session refuses them itself.
let engine = h.engine.clone();
let setup = || StreamSetup { name: "screen".into(), ..Default::default() };
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
let error = h
.next(|e| match e {
Event::Error { message, .. } => Some(message),
_ => None,
})
.await;
assert!(error.contains("streams"), "{error}");
assert!(conn.cmds.try_recv().is_err(), "nothing reached the link");
// A link with streams: stream commands go to it, and end with the connection.
let mut with_streams = {
let link_engine = h.engine.clone();
link_engine.send(Command::ConnectVoice {
session: SESSION,
options: Box::new(VoiceOptions::new("fake.test:9987", "tester")),
});
h.conns.recv().await.expect("the second connection")
};
// The replaced connection is told to go.
assert!(matches!(conn.cmd().await, LinkCmd::Disconnect));
with_streams.play([connected(true)]);
h.next(|e| match e {
Event::ServerInfo { capabilities, .. } if capabilities.streams => Some(()),
_ => None,
})
.await;
// A connection with streams is given the (empty) stream directory first.
let LinkCmd::Stream(StreamCmd::Directory(directory)) = with_streams.cmd().await else {
panic!("the stream directory")
};
assert!(directory.is_empty());
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
let LinkCmd::Stream(StreamCmd::Start { setup, auto_accept }) = with_streams.cmd().await else {
panic!("a stream start")
};
assert_eq!((setup.name.as_str(), auto_accept), ("screen", true));
engine.send(Command::StopStream { session: SESSION });
assert!(matches!(with_streams.cmd().await, LinkCmd::Stream(StreamCmd::Stop)));
engine.send(Command::DisconnectVoice { session: SESSION });
assert!(matches!(with_streams.cmd().await, LinkCmd::Disconnect));
}
/// A reconnect ends the streams of the connection it replaces through that
/// connection, before the connection itself: the old link is given
/// `StreamCmd::Shutdown` and only then `Disconnect`. A link that ends its
/// connection on `Disconnect` (the TeamSpeak one stops reading commands
/// there) relies on this order for the streams to hear of their end.
#[tokio::test(flavor = "multi_thread")]
async fn a_reconnect_shuts_the_streams_down_before_the_old_connection() {
let mut h = Harness::start();
let mut old = h.connect().await;
old.play([
connected(true),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
h.state(|s| s.own_channel == Some(GAMES)).await;
let LinkCmd::Stream(StreamCmd::Directory(directory)) = old.cmd().await else {
panic!("the stream directory")
};
assert!(directory.is_empty());
// Connecting again replaces the connection.
let _new = h.connect().await;
let LinkCmd::Stream(StreamCmd::Shutdown(reason)) = old.cmd().await else {
panic!("the streams end first")
};
assert_eq!(reason, "voice reconnecting");
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
}
/// Events of a connection the session replaced do not reach it.
#[tokio::test(flavor = "multi_thread")]
async fn a_replaced_connection_is_ignored() {
let mut h = Harness::start();
let mut old = h.connect().await;
old.play([
connected(false),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
h.state(|s| s.own_channel == Some(GAMES)).await;
let new = h.connect().await;
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
// The old connection winds down, and says more than it should.
let mut stale = presence();
stale.clients.insert(10, client(10, "ghost", LOBBY));
old.play([
LinkEvent::Presence(Box::new(stale)),
LinkEvent::Chat(message("ghost", "boo", now_ms())),
LinkEvent::Disconnected(None),
]);
let mut fresh = presence();
fresh.clients.remove(&9);
// A link that says we are in the lobby shows us in the lobby.
fresh.clients.get_mut(&ME).expect("we are on the server").channel = LOBBY;
new.play([
connected(false),
LinkEvent::Presence(Box::new(fresh.clone())),
LinkEvent::OwnChannel(LOBBY),
]);
// Only the new connection's presence is shown (nobody else has 2 clients).
let shown = h
.next(|e| match e {
Event::Presence { presence, .. } if presence.clients.len() == fresh.clients.len() => {
Some(presence)
}
_ => None,
})
.await;
assert_eq!(*shown, fresh);
let state = h.state(|s| s.own_channel == Some(LOBBY)).await;
assert_eq!(state.voice, VoiceState::Connected, "the old disconnect did not count");
// Channel chat reaches the channel we are in (the lobby, now).
new.play([LinkEvent::Chat(ChatMessage {
target: ChatTarget::Channel(LOBBY),
..message("alice", "hello", now_ms())
})]);
assert_eq!(h.chat().await.text, "hello", "the old connection's chat never showed");
}
+322
View File
@@ -0,0 +1,322 @@
//! The engine's side of the seam against the protocol repository's fake host
//! (`docs/session-seam.md` sections 9.2 and 16): the voice path through a
//! `SessionLink` that talks to a `FakeSession`, and the link conformance
//! suite run against the session the engine's registry hands over.
//!
//! The tests that need only the engine's public API are in
//! `tests/session_fake.rs`; these need what is private to the crate: the
//! `LinkCmd`/`LinkEvent` vocabulary between `session.rs` and `SessionLink`,
//! the registry's `connect` and the context of a connector called outside an
//! engine.
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
use voelin_proto::link::{FlowId, MediaClass, MediaPacket, voice_sub};
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
use voelin_proto::media::{RtpHeader, RtpView};
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
use voelin_proto::test_util::{
FAKE_HOST_UID, FakeConnector, FakeHandle, connect_params, eventually,
};
use voelin_proto::v1::{self, entity::Kind};
use super::*;
const WAIT: Duration = Duration::from_secs(10);
/// An Opus frame of 20 ms, mono (TOC `0xf8`), and the same as stereo (`0xfc`).
const MONO: [u8; 3] = [0xf8, 0xff, 0xfe];
const STEREO: [u8; 3] = [0xfc, 0xff, 0xfe];
const ALICE: u32 = 50;
const ALICE_SLOT: u32 = 90;
const BOB: u32 = 51;
const BOB_SLOT: u32 = 91;
fn put(connector: &FakeConnector, kind: Kind) {
connector.host().put(v1::Entity { kind: Some(kind) }).expect("the fake host stores it");
}
/// A host with one server, a lobby, and alice and bob talking in it.
fn host() -> FakeConnector {
let connector = FakeConnector::new();
put(
&connector,
Kind::Server(v1::Server {
id: 1,
name: "Fake Host".into(),
uid: "fake-host".into(),
default_channel_id: 10,
..Default::default()
}),
);
put(
&connector,
Kind::Channel(v1::Channel {
id: 10,
server_id: 1,
kind: v1::ChannelKind::Voice as i32,
name: "Lobby".into(),
..Default::default()
}),
);
for (user, participant, slot, name) in
[(2, ALICE, ALICE_SLOT, "alice"), (3, BOB, BOB_SLOT, "bob")]
{
put(
&connector,
Kind::User(v1::User {
id: user,
uid: vec![user as u8; 32].into(),
uid_kind: v1::IdKind::Voelin as i32,
name: name.into(),
..Default::default()
}),
);
put(
&connector,
Kind::Voice(v1::VoiceState {
server_id: 1,
participant_id: participant,
user_id: user,
channel_id: 10,
slot,
nick: name.into(),
..Default::default()
}),
);
}
connector
}
/// A `SessionLink` over a fake host, driven the way `session.rs` drives it.
struct HostRig {
handle: FakeHandle,
cmds: mpsc::UnboundedSender<LinkCmd>,
events: mpsc::UnboundedReceiver<LinkEvent>,
/// Our participant and voice slot, as the host gave them.
own_client: u16,
own_slot: u32,
/// The clients the link told started talking, in order.
talking: Vec<u16>,
}
/// The next event `f` picks from `events`, skipping the others.
async fn event_of<T>(
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
mut f: impl FnMut(LinkEvent) -> Option<T>,
) -> T {
tokio::time::timeout(WAIT, async {
loop {
if let Some(t) = f(events.recv().await.expect("the link lives")) {
return t;
}
}
})
.await
.expect("an event in time")
}
impl HostRig {
async fn connect() -> Self {
let connector = host();
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
let link = SessionLink::new(backends);
let (cmds, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
let ctx = LocalCtx::standalone().link;
link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
let own_client = event_of(&mut events, |e| match e {
LinkEvent::Connected { own_client, .. } => Some(own_client),
_ => None,
})
.await;
event_of(&mut events, |e| matches!(e, LinkEvent::OwnChannel(10)).then_some(())).await;
let own_slot = connector
.host()
.entities(&v1::Scope { kind: v1::ScopeKind::Live as i32, id: 1 })
.into_iter()
.find_map(|e| match e.kind? {
Kind::Voice(v) if v.participant_id == u32::from(own_client) => Some(v.slot),
_ => None,
})
.expect("the host seated us in voice");
let handle = connector.last_session().expect("the connector made a session");
Self { handle, cmds, events, own_client, own_slot, talking: Vec::new() }
}
/// The next voice packet the audio thread would get; who started to talk on
/// the way is kept in `talking`.
async fn audio(&mut self) -> VoicePacket {
let talking = &mut self.talking;
event_of(&mut self.events, |e| match e {
LinkEvent::Talking { client, talking: true } => {
talking.push(client);
None
}
LinkEvent::Audio(packet) => Some(packet),
_ => None,
})
.await
}
fn give(&self, cmd: LinkCmd) {
self.cmds.send(cmd).expect("the link listens");
}
}
/// A voice packet of `slot` on sub-flow `sub`, as a host delivers it.
fn voice_packet(slot: u32, sub: u8, sequence: u16, payload: &[u8]) -> MediaPacket {
let flow = FlowId::new(slot, sub);
let mut out = bytes::BytesMut::new();
RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960)
.write(flow, &mut out)
.expect("a header");
out.extend_from_slice(payload);
MediaPacket { flow, rtp: out.freeze() }
}
fn voice(payload: &[u8]) -> EncodedVoice {
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
}
/// Our voice leaves as RTP on the slot the host gave us: the sequence counts
/// every packet, the timestamp advances by the duration of the previous one,
/// the marker is on the first packet of a spurt, the end of a spurt is an
/// empty payload sent once, and the SSRC is the flow (protocol section 6).
#[tokio::test(flavor = "multi_thread")]
async fn our_voice_is_rtp_on_the_slot_the_host_gave_us() {
let rig = HostRig::connect().await;
// The fake host loops accepted media back; this test looks at what left.
rig.handle.set_loopback(false);
for n in 1..=3 {
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, n])));
}
rig.give(LinkCmd::Audio(voice(&[])));
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, 9])));
let handle = rig.handle.clone();
eventually(WAIT, "the five packets", || handle.sent_media().len() == 5).await;
let flow = FlowId::new(rig.own_slot, voice_sub::CHANNEL);
let sent = rig.handle.sent_media();
let seen: Vec<_> = sent
.iter()
.map(|(class, packet)| {
let view = RtpView::parse(&packet.rtp).expect("RTP");
assert_eq!(*class, MediaClass::Voice);
assert_eq!(packet.flow, flow);
assert_eq!((view.payload_type(), view.ssrc()), (PT_OPUS, flow.0));
(view.sequence(), view.marker(), view.timestamp(), view.payload().to_vec())
})
.collect();
let ticks = OPUS_20_MS_TICKS;
assert_eq!(
seen,
[
(0, true, 0, vec![0xf8, 0xff, 0xfe, 1]),
(1, false, ticks, vec![0xf8, 0xff, 0xfe, 2]),
(2, false, 2 * ticks, vec![0xf8, 0xff, 0xfe, 3]),
// The end of the spurt: no payload, no marker, once.
(3, false, 3 * ticks, vec![]),
// The next spurt marks its first packet again.
(4, true, 3 * ticks, vec![0xf8, 0xff, 0xfe, 9]),
]
);
}
/// The RTP of other slots becomes the packets of the audio thread: the talker
/// is the participant of the slot, a whisper sub-flow is a whisper, a stereo
/// Opus frame is music, an empty payload ends the spurt; what is no voice of a
/// slot the host told about is dropped.
#[tokio::test(flavor = "multi_thread")]
async fn the_voice_of_other_slots_reaches_the_audio_thread() {
let mut rig = HostRig::connect().await;
let handle = rig.handle.clone();
// A slot nobody has, a probe and feedback: nothing. Then alice, mono.
handle.inject_media(voice_packet(777, voice_sub::CHANNEL, 1, &MONO));
handle.inject_media(MediaPacket { flow: FlowId::PROBE, rtp: bytes::Bytes::from_static(&[1]) });
handle.inject_media(MediaPacket {
flow: FlowId::FEEDBACK,
rtp: bytes::Bytes::from_static(&[1, 2]),
});
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 5, &MONO));
let packet = rig.audio().await;
assert_eq!(
(packet.talker.0, packet.seq, packet.codec, packet.whisper, packet.payload.as_slice()),
(ALICE as u16, 5, VoiceCodec::Voice, false, MONO.as_slice())
);
// Bob whispers (sub-flow 1) in stereo: music, a whisper.
handle.inject_media(voice_packet(BOB_SLOT, 1, 6, &STEREO));
let packet = rig.audio().await;
assert_eq!(
(packet.talker.0, packet.seq, packet.codec, packet.whisper),
(BOB as u16, 6, VoiceCodec::Music, true)
);
// Alice stops: an empty payload.
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 7, &[]));
let packet = rig.audio().await;
assert_eq!((packet.talker.0, packet.seq, packet.payload.len()), (ALICE as u16, 7, 0));
// Who talks comes from the same packets: alice started, then bob, once each
// (the slot nobody has started nobody).
assert_eq!(rig.talking, [ALICE as u16, BOB as u16]);
}
/// A host whose session loops our own voice back (the fake one does, so that
/// the conformance suite can see media move) does not make the engine play us
/// our own voice or show us as talking: the engine never plays itself.
#[tokio::test(flavor = "multi_thread")]
async fn our_own_voice_coming_back_is_not_played_back() {
let mut rig = HostRig::connect().await;
// The fake host loops accepted media back into the sink (the default).
rig.give(LinkCmd::Audio(voice(&MONO)));
let handle = rig.handle.clone();
eventually(WAIT, "the packet to leave", || handle.sent_media().len() == 1).await;
// A packet of alice behind it: when this one is out, ours has been through.
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 1, &MONO));
let own = rig.own_client;
let mut heard = Vec::new();
while heard.last().is_none_or(|talker| *talker != ALICE as u16) {
heard.push(rig.audio().await.talker.0);
}
assert!(!heard.contains(&own), "the engine played our own voice back: {heard:?}");
}
/// The link conformance suite of the protocol repository against the session
/// the engine's registry hands over: the registry adds nothing to a plain
/// connector's session (`Backends::connect` returns it untouched), so the 17
/// cases pass as they do in the protocol repository, none skipped.
#[tokio::test(flavor = "multi_thread")]
async fn the_conformance_suite_passes_on_a_session_of_the_registry() {
async fn through_the_registry() -> Fixture {
let connector = FakeConnector::new();
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
let (params, media) = connect_params("fake://conformance");
let local = backends
.connect(params, LocalCtx::standalone())
.await
.unwrap_or_else(|e| panic!("the registry connects: {e}"));
assert_eq!(local.connected.host_uid, FAKE_HOST_UID, "the connector's own answer");
assert!(local.streams.is_none(), "a plain connector has no stream port");
let backend = connector.last_session().expect("the connector made a session");
// The session is the connector's own, so a request id means the same to both.
Fixture {
shared_request_ids: true,
..Fixture::new(local.connected.session, local.connected.pushes, media, backend)
}
}
let report = conformance::run(&through_the_registry).await;
assert_eq!(report.cases.len(), conformance::CASES.len());
assert_eq!(report.cases.len(), 17, "the suite of v0.2.0 has 17 cases");
assert!(
report.cases.iter().all(|(_, verdict)| *verdict == Verdict::Passed),
"{:?}",
report.cases
);
}
+310
View File
@@ -0,0 +1,310 @@
//! Voice across the seam, engine side (`docs/session-seam.md` section 6.1):
//! our encoded frames as RTP on our voice slot, the RTP of other slots as
//! the audio thread's packets, and who is talking from the media.
//!
//! `voelin-audio`'s [`EncodedVoice`] and [`VoicePacket`] stay what the audio
//! thread speaks; this is the framing in the v1 media codec
//! (`voelin_proto::media`, protocol section 6).
use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant};
use bytes::BytesMut;
use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
use voelin_proto::media::opus::{self, Toc};
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
use voelin_proto::media::{RtpHeader, RtpView};
/// A talker is silent after this long without a packet.
pub(crate) const TALK_SILENCE: Duration = Duration::from_millis(400);
/// Our voice as RTP: the sequence number counts every packet from 0, the
/// timestamp starts at 0 and advances by the duration of the previous
/// packet, the marker is set on the first packet of a spurt, and the end of a
/// spurt is a packet with an empty payload, sent once.
#[derive(Default)]
pub(crate) struct Uplink {
sequence: u16,
timestamp: u32,
/// The ticks the last voice packet spans.
ticks: u32,
in_spurt: bool,
}
impl Uplink {
/// `voice` as the RTP packet of our voice slot.
pub(crate) fn frame(&mut self, slot: u32, voice: &EncodedVoice) -> Option<MediaPacket> {
let flow = FlowId::new(slot, voice_sub::CHANNEL);
// The previous packet's duration has passed.
self.timestamp = self.timestamp.wrapping_add(self.ticks);
let end = voice.is_end();
let mut header = RtpHeader::new(PT_OPUS, self.sequence, self.timestamp);
header.marker = !end && !self.in_spurt;
self.ticks =
if end { 0 } else { opus::packet_ticks(&voice.payload).unwrap_or(OPUS_20_MS_TICKS) };
self.in_spurt = !end;
self.sequence = self.sequence.wrapping_add(1);
let mut out = BytesMut::with_capacity(header.encoded_len() + voice.payload.len());
header.write(flow, &mut out).ok()?;
out.extend_from_slice(&voice.payload);
Some(MediaPacket { flow, rtp: out.freeze() })
}
}
/// A voice packet of some slot, taken from its RTP.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Incoming {
pub(crate) slot: u32,
/// Sent on a whisper sub-flow (1 to 6).
pub(crate) whisper: bool,
pub(crate) sequence: u16,
pub(crate) codec: VoiceCodec,
/// Empty: the spurt ends.
pub(crate) payload: Vec<u8>,
}
impl Incoming {
/// Parse a media packet. `None` for what is not the voice of a slot:
/// feedback, probes, a flow that is no media, a packet that is no RTP.
pub(crate) fn parse(packet: &MediaPacket) -> Option<Incoming> {
if !packet.flow.is_media() {
return None;
}
let view = RtpView::parse(&packet.rtp).ok()?;
let payload = view.payload();
// Stereo Opus is music; the jitter buffer decodes both the same way.
let codec = match Toc::parse(payload) {
Ok(toc) if toc.stereo() => VoiceCodec::Music,
_ => VoiceCodec::Voice,
};
Some(Incoming {
slot: packet.flow.slot(),
whisper: (voice_sub::FIRST_TALK_TARGET..=voice_sub::LAST_TALK_TARGET)
.contains(&packet.flow.sub()),
sequence: view.sequence(),
codec,
payload: payload.to_vec(),
})
}
/// The packet for the audio thread, from `talker`.
pub(crate) fn voice(self, talker: u16) -> VoicePacket {
VoicePacket {
talker: TalkerId(talker),
seq: self.sequence,
codec: self.codec,
whisper: self.whisper,
payload: self.payload,
}
}
}
/// Who is talking: derived from the media (protocol section 6.4). A talker
/// starts with its first packet and stops after [`TALK_SILENCE`] without one.
///
/// A host can also say that someone talks whose voice it does not carry as
/// media (a `Speaking` signal; TeamSpeak's Speex and CELT talkers are such):
/// that is a hint, which holds until the host says it is over.
#[derive(Default)]
pub(crate) struct TalkTracker {
last: HashMap<u16, Instant>,
hinted: HashSet<u16>,
}
impl TalkTracker {
/// A packet of `client` arrived; whether this starts its talking.
pub(crate) fn heard(&mut self, client: u16, now: Instant) -> bool {
let was = self.is_talking(client);
self.last.insert(client, now);
!was
}
/// The host says `client` talks or has stopped; whether this changes
/// whether it is talking.
pub(crate) fn hint(&mut self, client: u16, talking: bool) -> bool {
let was = self.is_talking(client);
if talking {
self.hinted.insert(client);
} else {
self.hinted.remove(&client);
}
was != self.is_talking(client)
}
/// Forget the hints about clients `present` does not hold any more: a
/// client that left cannot say it stopped.
pub(crate) fn retain_hints(&mut self, present: impl Fn(u16) -> bool) {
self.hinted.retain(|client| present(*client));
}
/// The talkers that have been silent long enough, no longer talking.
pub(crate) fn expire(&mut self, now: Instant) -> Vec<u16> {
let mut silent: Vec<u16> = self
.last
.iter()
.filter(|(_, last)| now.saturating_duration_since(**last) >= TALK_SILENCE)
.map(|(client, _)| *client)
.collect();
silent.sort_unstable();
for client in &silent {
self.last.remove(client);
}
silent.retain(|client| !self.hinted.contains(client));
silent
}
pub(crate) fn is_talking(&self, client: u16) -> bool {
self.last.contains_key(&client) || self.hinted.contains(&client)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// 20 ms of CELT, mono, one frame.
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
fn voice(payload: &[u8]) -> EncodedVoice {
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
}
fn view(packet: &MediaPacket) -> RtpView<'_> {
RtpView::parse(&packet.rtp).unwrap()
}
#[test]
fn our_voice_is_sequenced_stamped_and_marked() {
let mut up = Uplink::default();
let first = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
let second = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
assert_eq!((first.flow.slot(), first.flow.sub()), (8, 0));
let (a, b) = (view(&first), view(&second));
assert_eq!((a.sequence(), a.timestamp(), a.marker()), (0, 0, true));
assert_eq!((b.sequence(), b.timestamp(), b.marker()), (1, OPUS_20_MS_TICKS, false));
assert_eq!((a.ssrc(), a.payload_type()), (first.flow.0, PT_OPUS));
assert_eq!(a.payload(), OPUS_20_MS);
}
#[test]
fn the_end_is_one_empty_packet_and_the_next_spurt_has_a_marker() {
let mut up = Uplink::default();
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
let end = up.frame(8, &voice(&[])).unwrap();
assert!(view(&end).payload().is_empty() && !view(&end).marker());
assert_eq!(view(&end).sequence(), 1);
let next = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
assert!(view(&next).marker());
assert_eq!(view(&next).sequence(), 2);
}
#[test]
fn the_sequence_wraps() {
let mut up = Uplink { sequence: u16::MAX, ..Default::default() };
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
let wrapped = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
assert_eq!(view(&wrapped).sequence(), 0);
}
#[test]
fn received_voice_is_split_into_slot_sub_flow_sequence_and_codec() {
let flow = FlowId::new(9, 0);
let mut header = RtpHeader::new(PT_OPUS, 513, 0);
header.marker = true;
let mut rtp = BytesMut::new();
header.write(flow, &mut rtp).unwrap();
rtp.extend_from_slice(&OPUS_20_MS);
let packet = MediaPacket { flow, rtp: rtp.freeze() };
let got = Incoming::parse(&packet).unwrap();
assert_eq!(
got,
Incoming {
slot: 9,
whisper: false,
sequence: 513,
codec: VoiceCodec::Voice,
payload: OPUS_20_MS.to_vec()
}
);
let voice = got.voice(8);
assert_eq!((voice.talker, voice.seq, voice.whisper), (TalkerId(8), 513, false));
}
#[test]
fn whispers_stereo_ends_and_what_is_no_voice() {
let packet = |flow: FlowId, payload: &[u8]| {
let mut rtp = BytesMut::new();
RtpHeader::new(PT_OPUS, 1, 0).write(flow, &mut rtp).unwrap();
rtp.extend_from_slice(payload);
MediaPacket { flow, rtp: rtp.freeze() }
};
assert!(Incoming::parse(&packet(FlowId::new(9, 3), &OPUS_20_MS)).unwrap().whisper);
assert!(!Incoming::parse(&packet(FlowId::new(9, 7), &OPUS_20_MS)).unwrap().whisper);
let stereo = [OPUS_20_MS[0] | 0x04, 1, 2];
assert_eq!(
Incoming::parse(&packet(FlowId::new(9, 0), &stereo)).unwrap().codec,
VoiceCodec::Music
);
let end = Incoming::parse(&packet(FlowId::new(9, 0), &[])).unwrap();
assert!(end.payload.is_empty() && end.voice(8).is_end());
// Feedback and probes are no voice.
assert!(
Incoming::parse(&MediaPacket { flow: FlowId::FEEDBACK, rtp: Default::default() })
.is_none()
);
assert!(
Incoming::parse(&MediaPacket { flow: FlowId::PROBE, rtp: Default::default() })
.is_none()
);
assert!(
Incoming::parse(&MediaPacket { flow: FlowId::new(9, 0), rtp: vec![1, 2].into() })
.is_none()
);
}
#[test]
fn a_talker_starts_with_a_packet_and_stops_400_ms_after_its_last() {
let mut talk = TalkTracker::default();
let t0 = Instant::now();
assert!(talk.heard(8, t0));
assert!(!talk.heard(8, t0 + Duration::from_millis(100)), "already talking");
assert!(talk.heard(9, t0 + Duration::from_millis(150)));
assert!(talk.is_talking(8));
// 399 ms after 8's last packet: still talking.
assert!(talk.expire(t0 + Duration::from_millis(499)).is_empty());
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [8]);
assert!(!talk.is_talking(8) && talk.is_talking(9));
assert_eq!(talk.expire(t0 + Duration::from_millis(551)), [9]);
// A packet after the silence starts it again.
assert!(talk.heard(8, t0 + Duration::from_secs(2)));
}
#[test]
fn a_host_that_says_someone_talks_is_believed_until_it_says_otherwise() {
let mut talk = TalkTracker::default();
let t0 = Instant::now();
// A talker whose voice is no media: on, and no silence ends it.
assert!(talk.hint(8, true));
assert!(!talk.hint(8, true), "already talking");
assert!(talk.is_talking(8));
assert!(talk.expire(t0 + Duration::from_secs(60)).is_empty());
assert!(talk.hint(8, false));
assert!(!talk.is_talking(8));
// A talker with media that the host also names: the media ends it, when
// the host has said it is over (in either order).
assert!(talk.heard(9, t0));
assert!(!talk.hint(9, true), "heard already");
assert!(talk.expire(t0 + Duration::from_millis(500)).is_empty(), "the host still says so");
assert!(talk.is_talking(9));
assert!(talk.hint(9, false));
assert!(!talk.is_talking(9));
assert!(talk.heard(10, t0));
assert!(!talk.hint(10, false), "the media goes on");
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [10]);
// A hint about somebody who is gone is forgotten.
assert!(talk.hint(11, true));
talk.retain_hints(|client| client != 11);
assert!(!talk.is_talking(11));
}
}
+330
View File
@@ -0,0 +1,330 @@
//! The engine's seam to the server its voice source talks to.
//!
//! A session merges up to three sources (voice, gateway, query). The *voice*
//! source is the connection that is visible on the server, can talk and
//! carries chat, files, pokes, offline messages and streams. The engine holds
//! it as a `voelin_proto::link::Session`, the backend-neutral interface of the
//! protocol repository, and knows nothing else of the server software behind
//! it: which backend makes the `Session` is the scheme of the address, and
//! [`Backends`] is the registry of connectors by scheme
//! ([`Backends::default`] has the TeamSpeak one,
//! [`crate::ts::TsConnector`]; a Voelin host's QUIC connector will be
//! another). [`VoiceOptions`] says what to connect to and as whom.
//!
//! Inside the crate `session.rs` merges and routes, and an adapter below it
//! turns what it asks into `Session` calls and what the `Session` pushes into
//! what it hears (`link/session_link.rs`, with `project.rs` and `media.rs`);
//! `docs/session-seam.md` describes the mapping row by row.
mod backends;
mod connect;
#[cfg(test)]
mod fake_link_tests;
#[cfg(test)]
mod fake_tests;
pub(crate) mod media;
pub(crate) mod project;
mod session_link;
#[cfg(test)]
mod tests;
pub use backends::Backends;
pub(crate) use backends::{
LocalConnected, LocalConnector, LocalCtx, StreamEvent, StreamPort, without_query,
};
pub(crate) use connect::{VERSION_PARAM, connect_params};
pub(crate) use session_link::SessionLink;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::sync::{broadcast, oneshot};
use voelin_audio::{EncodedVoice, VoicePacket};
use voelin_identity::IdentityBlob;
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence};
use voelin_stream::PeerConfig;
use crate::files::{Report, RequestId, Sink, TransferId};
use crate::settings::SharedSettings;
use crate::stream::{OwnStreamEvent, StreamCmd, StreamFrame};
use crate::{BackendInfo, Event, SessionId};
/// What a voice connection needs to know: the server, who to be, where to
/// join ([`Command::ConnectVoice`](crate::Command::ConnectVoice)).
///
/// Nothing in it belongs to one kind of server: what a connector needs of it
/// that is its own (a TeamSpeak identity, the client version to claim) is in
/// the `identity` blob and the `client_version` spec, which the connector of
/// the address reads.
#[derive(Clone, Debug)]
pub struct VoiceOptions {
/// The server: `host[:port]` of a TeamSpeak bookmark, or an address with a
/// scheme (`ts3server://`, `teamspeak://`, a Voelin host's `voelin://`)
/// that picks the connector ([`Backends`]).
pub address: String,
/// The name shown on the server: `Hello.nickname` to a Voelin host, the
/// client name on a TeamSpeak server (which may refuse or change it). When
/// it is empty, the `nickname` parameter of an `address` that is a
/// TeamSpeak link applies.
pub nickname: String,
/// The identity to connect with: a TeamSpeak identity
/// ([`crate::ts::identity::to_blob`]) for a TeamSpeak server, a Voelin key
/// for a Voelin host. None lets the connector make one up (a TeamSpeak
/// connection generates an identity, which a server then knows as a new
/// client).
pub identity: Option<IdentityBlob>,
/// The client version a TeamSpeak server is shown, as a spec for
/// [`crate::ts::versions::resolve`] (`default`, `generic`, an index, or
/// `<platform>@<version>`); `None` is the native platform's. A spec that is
/// none ends the connect with the reason. Other backends ignore it.
pub client_version: Option<String>,
/// The password of the server (`Hello.password`), for one that has a
/// password. When it is `None` or empty, the `password` parameter of an
/// `address` that is a TeamSpeak link applies. Not the password of
/// `channel` (that is `channel_password`).
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
/// The password of `channel`.
pub channel_password: Option<String>,
/// A privilege key to use when connecting.
pub token: Option<String>,
/// Open the audio devices (capture and playback).
pub audio: bool,
/// Network settings for stream peer connections (TeamSpeak 6).
pub stream_peer: PeerConfig,
}
impl VoiceOptions {
/// Options for `address` and `nickname`; everything else is left to the
/// connector.
pub fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
Self {
address: address.into(),
nickname: nickname.into(),
identity: None,
client_version: None,
server_password: None,
channel: None,
channel_password: None,
token: None,
audio: false,
stream_peer: PeerConfig::default(),
}
}
}
/// What the engine gives a link besides the options: where the connection
/// answers the requests the session need not see, and what it shares with
/// the session's other parts.
#[derive(Clone)]
pub(crate) struct LinkCtx {
pub(crate) session: SessionId,
pub(crate) events: broadcast::Sender<Event>,
/// The frames of watched streams (kept off the event bus).
pub(crate) frames: broadcast::Sender<StreamFrame>,
pub(crate) settings: SharedSettings,
}
impl LinkCtx {
/// The session this connection belongs to.
pub(crate) fn session(&self) -> SessionId {
self.session
}
/// Tell the engine's event bus something (a request's answer, a
/// transfer's progress).
pub(crate) fn emit(&self, event: Event) {
let _ = self.events.send(event);
}
pub(crate) fn done(&self, request: RequestId, result: Result<(), String>) {
self.emit(Event::RequestDone { session: self.session, request, result });
}
}
/// A file on the server: channel, its password, path.
#[derive(Clone, Debug)]
pub(crate) struct Remote {
pub channel: ChannelId,
pub password: Option<String>,
pub path: String,
}
/// A boxed stream of bytes to read: the body of a file the server sends.
pub(crate) type BoxRead = Pin<Box<dyn AsyncRead + Send>>;
/// A connection that can be read and written: a file transfer connection.
pub(crate) trait Duplex: AsyncRead + AsyncWrite + Send {}
impl<T: AsyncRead + AsyncWrite + Send> Duplex for T {}
/// A boxed [`Duplex`].
pub(crate) type BoxDuplex = Pin<Box<dyn Duplex>>;
/// What the session asks of a connection.
pub(crate) enum LinkCmd {
SendChat(ChatTarget, String),
Move(ChannelId, Option<String>),
SetInputMuted(bool),
SetOutputMuted(bool),
/// An encoded voice frame from the audio thread.
Audio(EncodedVoice),
/// A stream command; the link answers on the event bus. Only sent while
/// the connection's capabilities include streams.
Stream(StreamCmd),
Poke {
client: u16,
message: String,
},
ListFiles {
request: RequestId,
dir: Remote,
},
/// Download `file`; `transfer` if the user can cancel it.
Download {
transfer: Option<TransferId>,
file: Remote,
sink: Sink,
report: Report,
},
Upload {
transfer: Option<TransferId>,
file: Remote,
from: PathBuf,
overwrite: bool,
resume: bool,
report: Report,
},
CancelTransfer(TransferId),
/// Open a file of the server for reading, from `offset`: the transfer
/// connection itself, and the file's size in all, once the server has
/// agreed (the text of the failure otherwise). The engine copies the
/// bytes, reports the progress and cancels by dropping the connection, so
/// this does not use [`LinkCmd::Download`]'s sink and report.
OpenRead {
file: Remote,
offset: u64,
reply: oneshot::Sender<Result<(u64, BoxRead), String>>,
},
/// Open a file of the server for writing: the transfer connection and the
/// position the server wants the bytes from (the size it already has, if
/// `resume`). The engine writes the bytes and ends the connection.
OpenWrite {
file: Remote,
/// The file's size in all.
size: u64,
overwrite: bool,
resume: bool,
reply: oneshot::Sender<Result<(u64, BoxDuplex), String>>,
},
DeleteFiles {
/// `None`: best effort, nobody waits for the answer.
request: Option<RequestId>,
channel: ChannelId,
password: Option<String>,
paths: Vec<String>,
},
RenameFile {
request: RequestId,
from: Remote,
to: Remote,
},
CreateDirectory {
request: RequestId,
dir: Remote,
},
/// Announce our avatar's hash (empty: no avatar).
SetAvatarHash {
request: Option<RequestId>,
hash: String,
},
OfflineList {
request: RequestId,
},
OfflineGet {
request: RequestId,
id: u32,
},
OfflineAdd {
request: RequestId,
to_uid: String,
subject: String,
text: String,
},
OfflineDelete {
request: RequestId,
id: u32,
},
OfflineFlag {
request: RequestId,
id: u32,
read: bool,
},
Disconnect,
}
/// What a connection tells the session.
pub(crate) enum LinkEvent {
Connected {
name: String,
/// The server software, and what it can do (the connection knows
/// both from the server's version).
backend: BackendInfo,
capabilities: Capabilities,
/// Our client id when the link connected. TeamSpeak's own reconnect gives
/// a new one, which is not announced; the engine follows it in the
/// snapshots by our unique id.
own_client: u16,
/// The server's unique id.
server_uid: String,
/// Our unique id as the server knows it.
own_uid: Option<String>,
},
/// The server's channels and clients as they are now.
Presence(Box<Presence>),
/// The channel we are in, after every [`LinkEvent::Presence`]. The engine
/// derives it itself, from our own voice state in the snapshots of the
/// `Session` it talks to, and so follows us when TeamSpeak's reconnect makes
/// us another client. What an in-process link such as `TsLink` says here only
/// tells the TeamSpeak `Session` made of it that a move has arrived.
OwnChannel(ChannelId),
Chat(ChatMessage),
Poke {
from: u16,
from_uid: Option<String>,
from_name: String,
message: String,
},
/// Incoming voice for the audio thread.
Audio(VoicePacket),
/// Who is talking (on, and off again when it stopped). The engine derives
/// it from the media of its `Session` (protocol section 6.4). What an
/// in-process link such as `TsLink` says here reaches the engine as a
/// speaking hint next to the media: that is what shows the talkers whose
/// packets the link does not forward as Opus (Speex, CELT).
Talking {
client: u16,
talking: bool,
},
/// Our own stream's life, for the gateway directory.
OwnStream(OwnStreamEvent),
/// An Opus frame (48 kHz) of a watched stream, for the audio thread
/// ([`VoiceOptions::audio`]); `time` is its RTP time on the 48 kHz
/// clock.
StreamAudio {
stream: String,
time: u64,
data: Arc<[u8]>,
},
/// A watched stream ended: its audio leaves the mixer.
StreamAudioEnded(String),
/// A command failed (the connection stays).
Error(String),
/// The connection ended; the reason if it was not asked for. Sent once;
/// the stream task's closing reports may still follow (see the module
/// documentation).
Disconnected(Option<String>),
}
+214
View File
@@ -0,0 +1,214 @@
//! The engine's view of a session's replica, in the client's older model
//! (`docs/session-seam.md` section 5.3).
//!
//! The UI and `session.rs` still speak `Presence`, `ChannelInfo`,
//! `ClientInfo`, `ServerDetails` and `ChatMessage`. [`presence`] and
//! [`chat_message`] project the replica into them with
//! `voelin_model::replica::convert`, and fix up where that says less than the
//! older model does (F1 to F10 of the design). The fix-ups apply the
//! TeamSpeak gateway's id rules of protocol section 11.1, so the UI keeps the
//! ids it has; they go when the UI reads the replica.
use std::collections::BTreeMap;
use voelin_model::replica::{Replica, convert};
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails};
use voelin_proto::link::Features;
use voelin_proto::v1::{self, ChannelKind, MessageFlag, RoleScope};
use super::media::TalkTracker;
use crate::ts::ts_session::entities::user_uid;
use crate::ts::ts_session::ids::{self, FOREIGN_SYSTEM};
/// What the projection needs to know besides the replica.
pub(crate) struct View<'a> {
pub(crate) replica: &'a Replica,
/// The server of the session.
pub(crate) server: u64,
/// The backend is TeamSpeak (`Welcome.host.backend.product`): its id rules
/// (channel groups) are undone.
pub(crate) teamspeak: bool,
/// The version the host said (`Welcome.host.backend.version`).
pub(crate) version: &'a str,
pub(crate) features: &'a Features,
/// Whether the connection has streams (a port, not just the feature).
pub(crate) streams: bool,
pub(crate) talking: &'a TalkTracker,
}
/// What a `Foreign` of TeamSpeak holds under `key`.
fn foreign_value(
foreign: Option<&v1::Foreign>,
kind: &str,
key: &str,
) -> Option<serde_json::Value> {
let foreign = foreign.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == kind)?;
serde_json::from_slice::<serde_json::Value>(&foreign.json).ok()?.get(key).cloned()
}
/// The server's unique id as the client keys its history and aliases by it:
/// the host's without the `ts:` of protocol section 11.2 (F3).
pub(crate) fn server_key(uid: &str) -> String {
uid.strip_prefix("ts:").unwrap_or(uid).to_owned()
}
/// The client's older model of the server (what `LinkEvent::Presence` holds).
pub(crate) fn presence(view: &View<'_>) -> Presence {
let replica = view.replica;
let server = view.server;
// F1: only what the older model calls channels.
let channels: Vec<&v1::Channel> = replica
.channels(server)
.filter(|channel| {
!matches!(
ChannelKind::try_from(channel.kind),
Ok(ChannelKind::ServerChat
| ChannelKind::Dm
| ChannelKind::GroupDm
| ChannelKind::Thread)
)
})
.collect();
let by_id: BTreeMap<u64, &v1::Channel> = channels.iter().map(|c| (c.id, *c)).collect();
let channel_infos = convert::channel_infos(&channels)
.into_iter()
.map(|mut info| {
// F7: a limit of 0 is a limit, not "unlimited".
let zero = by_id
.get(&info.id)
.and_then(|c| foreign_value(c.foreign.as_ref(), "channel", "max_clients"));
if zero.and_then(|v| v.as_i64()) == Some(0) {
info.max_clients = Some(0);
}
(info.id, info)
})
.collect();
let clients = replica
.voice_states(server)
.filter_map(|voice| {
let user = replica.user(voice.user_id);
let member = replica.member(server, voice.user_id);
let mut client =
convert::client_info(voice, user, member, replica.presence_of(voice.user_id))?;
// F10: a unique id that is no base64 rides in `Foreign`.
client.uid = user.and_then(user_uid);
// F2: the client's channel group is TeamSpeak's own number.
if view.teamspeak {
client.channel_group = client.channel_group.map(ids::channel_group);
}
// F6: the client's icon.
client.icon = foreign_value(member.and_then(|m| m.foreign.as_ref()), "client", "icon")
.and_then(|v| v.as_u64())
.and_then(|v| u32::try_from(v).ok())
.unwrap_or(0);
// F8: who is talking comes from the media.
client.talking = view.features.has("voice").then(|| view.talking.is_talking(client.id));
// F9: the stream flag only where there are streams.
if !view.streams {
client.streaming = None;
}
Some((client.id, client))
})
.collect();
let mut server_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
let mut channel_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
for role in replica.roles(server) {
let mut info = convert::group_info(role);
if role.scope == RoleScope::Channel as i32 {
if view.teamspeak {
info.id = ids::channel_group(info.id);
}
channel_groups.insert(info.id, info);
} else {
server_groups.insert(info.id, info);
}
}
let details = replica.server(server).map(|stub| server_details(view, stub)).unwrap_or_default();
Presence {
server_name: details.name.clone(),
channels: channel_infos,
clients,
server: details,
server_groups,
channel_groups,
}
}
/// `convert::server_details` with F2 to F5.
fn server_details(view: &View<'_>, server: &v1::Server) -> ServerDetails {
let mut details = convert::server_details(server);
// F3: the unique id as the client keys it.
details.uid = details.uid.as_deref().map(server_key);
let foreign = server.foreign.as_ref();
// F4: the version the server sent, else the one the host reports.
details.version = foreign_value(foreign, "server", "version")
.and_then(|v| v.as_str().map(str::to_owned))
.filter(|v| !v.is_empty())
.unwrap_or_else(|| view.version.to_owned());
// F5: the server's platform.
details.platform = foreign_value(foreign, "server", "platform")
.and_then(|v| v.as_str().map(str::to_owned))
.unwrap_or_default();
// F2: the default channel group is TeamSpeak's own number.
if view.teamspeak {
details.default_channel_group = details.default_channel_group.map(ids::channel_group);
}
details
}
/// Where the older model files the messages of a channel (the replica's
/// `chat_target`, with the unique id of F10).
fn chat_target(replica: &Replica, channel: u64) -> ChatTarget {
let Some(info) = replica.channel(channel) else { return ChatTarget::Channel(channel) };
match ChannelKind::try_from(info.kind) {
Ok(ChannelKind::ServerChat) => ChatTarget::Server,
Ok(ChannelKind::Dm | ChannelKind::GroupDm) => {
let own = replica.own_user();
info.recipients
.iter()
.copied()
.find(|id| *id != own)
.and_then(|id| replica.user(id))
.and_then(user_uid)
.map_or(ChatTarget::Channel(channel), ChatTarget::Private)
}
_ => ChatTarget::Channel(channel),
}
}
/// A message of the replica as the older model has it.
pub(crate) fn chat_message(replica: &Replica, channel: u64, id: u64) -> Option<ChatMessage> {
let message = replica.message(channel, id)?;
let author = replica.user(message.author_id);
let name = Some(message.author_name.as_str())
.filter(|name| !name.is_empty())
.or_else(|| author.map(|u| u.name.as_str()).filter(|name| !name.is_empty()))
.unwrap_or_default();
Some(ChatMessage {
target: chat_target(replica, channel),
author_name: name.to_owned(),
author_uid: author.and_then(user_uid),
author_id: (message.author_participant != 0)
.then(|| u16::try_from(message.author_participant).ok())
.flatten(),
text: message.text.clone(),
ts_ms: message.ts_ms,
via_relay: message.flags & MessageFlag::Relayed as u32 != 0,
blocked: false,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_ts_prefix_of_a_server_uid_goes() {
assert_eq!(server_key("ts:abc="), "abc=");
assert_eq!(server_key("abc="), "abc=");
assert_eq!(server_key(""), "");
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+141 -54
View File
@@ -56,16 +56,16 @@ use voelin_media::mix::{
};
pub use voelin_media::mix::{Level, SourceState};
use voelin_media::scale::Pyramid;
use voelin_media::stream::EncodedFrame;
use voelin_media::studio::Studio;
use voelin_media::studio::output::{Packet, Track};
use voelin_media::{
Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, H264Profile,
VideoEncoder, VideoFrame,
LayerId, LayerSet, LayerSpec, VideoEncoder, VideoFrame,
};
pub use voelin_media::{DecoderBackend, DecoderPreference, EncoderBackend, EncoderPreference};
use voelin_stream::{
EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind,
MediaTime, PeerConfig, VideoCodec, VideoFormat,
FrameSource, Frequency, MediaFrame, MediaKind, MediaTime, PeerConfig, VideoCodec, VideoFormat,
};
use crate::settings::{AudioSourceKindSetting, AudioSourceSetting};
@@ -127,13 +127,7 @@ fn spawn(name: &str, f: impl FnOnce() + Send + 'static) -> Result<JoinHandle<()>
/// The `voelin_media` codec of a negotiated video codec.
pub fn media_codec(codec: VideoCodec) -> Codec {
match codec {
VideoCodec::Vp8 => Codec::Vp8,
VideoCodec::Vp9 => Codec::Vp9,
VideoCodec::H264 => Codec::H264,
VideoCodec::Av1 => Codec::Av1,
VideoCodec::H265 => Codec::H265,
}
crate::stream::media_codec(codec)
}
/// The H.264 profile an encoder of `format` makes (Constrained High for
@@ -2686,7 +2680,7 @@ pub struct DecodeStats {
pub bytes: u64,
/// Pictures decoded per second and video received in bit/s, over the
/// time since the previous [`VideoPipeline::stats`] (at least
/// [`RATE_WINDOW`]; the watch screen asks once a second).
/// `RATE_WINDOW`; the watch screen asks once a second).
pub fps: u32,
pub bitrate: u64,
}
@@ -3263,9 +3257,13 @@ impl LocalPreview {
}
/// The first and last column of the rectangle in the middle row of a
/// decoded test pattern. Checks that pixels further than two columns from
/// its edges (which the codec blurs) have the colour of the rectangle or
/// the background.
/// decoded test pattern, after checking the row's structure: background, one
/// run of the rectangle, background. A pixel is whichever of the pattern's two
/// colours it is nearer to; it is not asked to be within some distance of one,
/// because an encoder that falls behind lowers its quality (the VP8 speed
/// control of the streamer does) and then moves a flat colour by 30 and more
/// per channel, still nowhere near the other colour. The two columns at each
/// edge, which the codec blurs, may be either.
#[cfg(all(test, feature = "media-desktop"))]
pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
use voelin_media::capture::synthetic::{BACKGROUND, RECT_COLOR};
@@ -3276,15 +3274,23 @@ pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
let i = ((y * picture.width + x) * 4) as usize;
[rgba[i], rgba[i + 1], rgba[i + 2]]
};
let close = |p: [u8; 3], c: [u8; 3]| p.iter().zip(c).all(|(a, b)| a.abs_diff(b) <= 24);
let inside: Vec<u32> = (0..picture.width).filter(|&x| close(pixel(x), RECT_COLOR)).collect();
let (&a, &b) = inside.first().zip(inside.last()).expect("no rectangle in the middle row");
for x in 0..picture.width {
if x + 2 < a || x > b + 2 {
assert!(close(pixel(x), BACKGROUND), "pixel {x},{y} is {:?}", pixel(x));
} else if (a + 2..=b.saturating_sub(2)).contains(&x) {
assert!(close(pixel(x), RECT_COLOR), "pixel {x},{y} is {:?}", pixel(x));
}
let distance = |p: [u8; 3], c: [u8; 3]| -> u32 {
p.iter().zip(c).map(|(a, b)| u32::from(a.abs_diff(b)).pow(2)).sum()
};
let rectangle = |x: u32| {
let p = pixel(x);
distance(p, RECT_COLOR) < distance(p, BACKGROUND)
};
let a = (0..picture.width).find(|&x| rectangle(x)).expect("no rectangle in the middle row");
let b = (0..picture.width).rfind(|&x| rectangle(x)).unwrap();
// One run: everything between its ends, but the blurred edges, is the
// rectangle's. Whatever is outside is the background by the choice of a and b.
for x in a + 2..=b.saturating_sub(2) {
assert!(
rectangle(x),
"pixel {x},{y} is {:?}, in the middle of the rectangle (columns {a} to {b})",
pixel(x)
);
}
(a, b)
}
@@ -3416,7 +3422,14 @@ mod tests {
assert!(all.is_hardware(backend), "{codec} offered in software");
}
if all.encoder_codecs().contains(&Codec::H264) && !offer.contains(&Codec::H264) {
assert_eq!(offer_codecs(&all, Codec::H264)[..2], [Codec::H264, Codec::Vp8]);
// H.264 in software only (so not in `offer`): it leads the same
// codecs as with VP8 as the stream codec, whichever hardware
// encoders this machine has (a hardware AV1 or VP9 encoder ranks
// before VP8, so VP8 is not always second).
let h264 = offer_codecs(&all, Codec::H264);
assert_eq!(h264[0], Codec::H264, "{h264:?}");
assert_eq!(h264.len(), offer.len() + 1, "{h264:?} against {offer:?}");
assert!(offer.iter().all(|c| h264.contains(c)), "{h264:?} against {offer:?}");
}
// Whatever this machine has: codecs every TeamSpeak client decodes
// come before H.264, HEVC last, and the automatic stream codec is
@@ -3429,10 +3442,23 @@ mod tests {
let ranks: Vec<_> = offer[1..].iter().map(rank).collect();
assert!(ranks.is_sorted(), "{offer:?}");
assert!(preferred_codec(&all, None).is_some_and(decoded_everywhere), "{all:?}");
assert_eq!(
preferred_codec(&all, Some(Codec::H264)).is_some(),
all.encoder_codecs().contains(&Codec::H264)
);
// A configured codec is the stream codec when this machine can encode
// it; otherwise the result is the automatic choice,
// `preferred_codec(&all, None)` (some codec on any machine that
// encodes anything). Whether H.264 is encodable depends on the
// machine (a desktop with FFmpeg or a GPU has an encoder, a CI
// runner has none), so the expectation follows `all.encoder_codecs()`.
let h264 = preferred_codec(&all, Some(Codec::H264));
if all.encoder_codecs().contains(&Codec::H264) {
assert_eq!(h264, Some(Codec::H264), "{all:?}");
} else {
assert_eq!(h264, preferred_codec(&all, None), "{all:?}");
}
// The built-in codecs are the same everywhere (no OpenH264 loaded):
// VP9 is encodable and wins, H.264 is not and falls back to VP8.
assert_eq!(preferred_codec(&codecs, Some(Codec::Vp9)), Some(Codec::Vp9));
assert_eq!(preferred_codec(&codecs, Some(Codec::H264)), preferred_codec(&codecs, None));
assert_eq!(preferred_codec(&codecs, None), Some(Codec::Vp8));
}
/// A sink whose viewers chose `codecs`; keeps every video frame with its
@@ -3522,11 +3548,30 @@ mod tests {
};
told(30).await;
assert_eq!(streamer.bitrate_kbps(), 1105);
// Not per frame.
let count = lock(&sink.formats).len();
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(lock(&sink.formats).len(), count);
assert_eq!(streamer.stats().layers[0].bitrate, auto_bitrate(640, 480, 30));
// Not per frame. The sink is told when it is attached and again by the
// encoder before its first frame (the same format twice), so the count is
// taken once a frame has been handed over and compared after more have;
// the frames, not a pause, are what "per frame" counts.
let frames_by = |frames: u64| {
let streamer = &streamer;
async move {
let deadline = Instant::now() + Duration::from_secs(30);
while streamer.stats().layers[0].frames < frames {
assert!(Instant::now() < deadline, "{frames} frames: {:?}", streamer.stats());
tokio::time::sleep(Duration::from_millis(20)).await;
}
}
};
frames_by(1).await;
let (count, seen) = (lock(&sink.formats).len(), streamer.stats().layers[0].frames);
frames_by(seen + 5).await;
assert_eq!(lock(&sink.formats).len(), count, "told again within five frames");
// The stats follow the sink's being told, not the other way round.
let deadline = Instant::now() + Duration::from_secs(10);
while streamer.stats().layers[0].bitrate != auto_bitrate(640, 480, 30) {
assert!(Instant::now() < deadline, "{:?}", streamer.stats().layers);
tokio::time::sleep(Duration::from_millis(20)).await;
}
let update = StreamerConfigUpdate { fps: Some(15), ..StreamerConfigUpdate::default() };
streamer.reconfigure(&codecs, update).unwrap();
told(15).await;
@@ -3697,15 +3742,35 @@ mod tests {
assert!((60..=68).contains(&(b - a + 1)), "{spans:?}");
}
assert_ne!(spans.first(), spans.last(), "the rectangle moves");
let stats = preview.stats();
assert!(stats.decoded >= 10 && stats.error.is_none(), "{stats:?}");
assert_eq!(stats.codec, Some(Codec::Vp8));
let (before_first, first) = (Instant::now(), preview.stats());
let after_first = Instant::now();
assert!(first.decoded >= 10 && first.error.is_none(), "{first:?}");
assert_eq!(first.codec, Some(Codec::Vp8));
assert_eq!(preview.streamer().backend(), "synthetic");
// Rates over the second since: the pattern's rate, its bitrate.
// The rates are the counters over the time since the call before. How
// long that was the test does not say (a busy machine stretches a second,
// and the rate of pictures it manages is not what is tested), but it lies
// between the two spans the test timed around it.
tokio::time::sleep(Duration::from_secs(1)).await;
let stats = preview.stats();
assert!((20..=40).contains(&stats.fps), "{stats:?}");
assert!((100_000..5_000_000).contains(&stats.bitrate), "{stats:?}");
let before_second = Instant::now();
let second = preview.stats();
let after_second = Instant::now();
let longest = after_second.duration_since(before_first).as_secs_f64();
let shortest = before_second.duration_since(after_first).as_secs_f64();
let frames = (second.decoded - first.decoded) as f64;
let bits = (second.bytes - first.bytes) as f64 * 8.0;
assert!(frames > 0.0, "no picture in the second: {first:?} {second:?}");
// (The pictures per second are rounded, the bits per second cut off.)
let fps = f64::from(second.fps);
assert!(
(frames / longest - 0.5..=frames / shortest + 0.5).contains(&fps),
"{frames} pictures in {shortest} to {longest} s are not {fps} a second"
);
let bitrate = second.bitrate as f64;
assert!(
(bits / longest - 1.0..=bits / shortest).contains(&bitrate),
"{bits} bits in {shortest} to {longest} s are not {bitrate} a second"
);
}
/// A VP8 decoder for the pipeline tests: fails (with errors, or giving
@@ -4129,7 +4194,8 @@ mod tests {
};
let streamer = Streamer::start(&codecs, config).await.unwrap();
let wait = |what: &str, done: &dyn Fn(&StreamerStats) -> bool| {
let deadline = Instant::now() + Duration::from_secs(5);
// What is waited for is a state; the deadline only ends a hang.
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let stats = streamer.stats();
if done(&stats) {
@@ -4139,15 +4205,18 @@ mod tests {
std::thread::sleep(Duration::from_millis(20));
}
};
// The SineSource tone is 0.05; the second at half gain.
// The SineSource tone is 0.05; the second at half gain. The sources are metered
// before the mixer has made anything of them: the mix and the state of the
// sources are waited for too, not taken to be there with the meters.
let near = |level: f32, want: f32| (level - want).abs() < want * 0.1;
let stats = wait("both tones", &|s| {
let stats = wait("both tones, mixed", &|s| {
s.audio_sources.len() == 2
&& near(s.audio_sources[0].level.peak, 0.05)
&& near(s.audio_sources[1].level.peak, 0.025)
&& s.audio_sources.iter().all(|s| s.state == SourceState::Playing)
&& s.audio_level.peak > 0.05
&& s.audio_limiter == 1.0
});
assert!(stats.audio_sources.iter().all(|s| s.state == SourceState::Playing));
assert!(stats.audio_level.peak > 0.05 && stats.audio_limiter == 1.0, "{stats:?}");
let first = stats.audio_sources[0].id;
// Mute the first (kept: same id), drop the second, add the
@@ -4163,19 +4232,31 @@ mod tests {
streamer.reconfigure(&codecs, update).unwrap();
assert_eq!(streamer.audio_sources().len(), 3);
let publisher = tap::publisher_id();
let speak = std::thread::spawn(move || {
// 20 ms of a 0.2 tone every 20 ms, for a second.
let chunk: Vec<f32> = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect();
for _ in 0..50 {
tap::microphone().publish(publisher, &chunk);
std::thread::sleep(Duration::from_millis(20));
let heard = Arc::new(AtomicBool::new(false));
let speak = std::thread::spawn({
let heard = heard.clone();
move || {
// 20 ms of a 0.2 tone every 20 ms, until the test has heard it: the
// source takes what is published only from when it runs, which a
// busy machine delays by any time (the cap ends a thread whose test
// failed first).
let cap = Instant::now() + Duration::from_secs(120);
let chunk: Vec<f32> = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect();
while !heard.load(Ordering::Relaxed) && Instant::now() < cap {
tap::microphone().publish(publisher, &chunk);
std::thread::sleep(Duration::from_millis(20));
}
}
});
let stats = wait("microphone in, tone muted", &|s| {
s.audio_sources.len() == 3
&& s.audio_sources[1].level.peak > 0.15
&& s.audio_level.peak > 0.15
&& s.audio_sources[2].error.as_deref().is_some_and(|e| e.contains("no window"))
// Muted, and still metered: the tone's own level is read again.
&& near(s.audio_sources[0].level.peak, 0.05)
});
heard.store(true, Ordering::Relaxed);
speak.join().unwrap();
assert_eq!(stats.audio_sources[0].id, first, "the kept tone keeps its source");
assert!(stats.audio_sources[0].spec.muted);
@@ -4207,9 +4288,15 @@ mod tests {
assert!(streamer.has_audio(), "{:?}", streamer.audio_error());
let mut source = EncodedSource::new(streamer);
let mut frames = Vec::new();
let deadline = Instant::now() + Duration::from_secs(5);
while frames.iter().filter(|f: &&EncodedFrame| f.kind == MediaKind::Audio).count() < 10 {
assert!(Instant::now() < deadline, "no audio");
// Ten frames of audio and one of video, whichever the encoders make first:
// 20 ms of audio is quickly made, and a busy machine can keep the video
// encoder from its first frame for longer than that. The deadline only ends
// a hang.
let deadline = Instant::now() + Duration::from_secs(30);
let count =
|frames: &[EncodedFrame], kind| frames.iter().filter(|f| f.kind == kind).count();
while count(&frames, MediaKind::Audio) < 10 || count(&frames, MediaKind::Video) < 1 {
assert!(Instant::now() < deadline, "no audio or no video in {} frames", frames.len());
tokio::time::sleep(Duration::from_millis(20)).await;
source.poll_frames(Instant::now(), &mut frames);
}
+141 -1
View File
@@ -1,11 +1,94 @@
//! The query source: own ServerQuery credentials, in-process observer and relays.
use std::fmt;
use tokio::sync::{broadcast, mpsc};
use voelin_model::{ChatMessage, ChatTarget, Presence};
use voelin_observer::{
Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool,
};
/// How a ServerQuery connection talks to the server.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QueryTransport {
/// The raw text protocol (TeamSpeak 3; port 10011).
Raw,
/// SSH.
Ssh,
/// The HTTP query (TeamSpeak 6; a WebQuery API key is the secret).
Http,
}
/// The user's own ServerQuery credentials for a server
/// ([`Command::ObserveQuery`](crate::Command::ObserveQuery)): what the
/// engine logs in with to observe a server invisibly and to relay its
/// channels' chat. The connection's own tuning (flood protection, timeouts)
/// is the engine's.
#[derive(Clone, PartialEq, Eq)]
pub struct QueryLogin {
/// The protocol of the query interface at `address`.
pub transport: QueryTransport,
/// `host:port` of the query interface.
pub address: String,
/// The login name (raw and SSH; ignored for HTTP).
pub user: String,
/// The password (raw and SSH) or API key (HTTP, optional for guest access).
pub secret: Option<String>,
/// Select the virtual server by its voice port...
pub server_port: Option<u16>,
/// ...or by id (the first server when neither is given).
pub server_id: Option<u32>,
/// This machine's address is on the server's query allowlist, which the
/// server's flood protection skips: the engine then sends its commands
/// without the limit it keeps for a server that has not said so (a command
/// the server refuses as a flood slows the connection down all the same).
/// The application usually cannot know, and says `false`; the development
/// servers of the tests allowlist their clients.
pub allowlisted: bool,
}
impl fmt::Debug for QueryLogin {
// The secret is kept out of logs.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("QueryLogin")
.field("transport", &self.transport)
.field("address", &self.address)
.field("user", &self.user)
.field("secret", &self.secret.as_ref().map(|_| "[secret]"))
.field("server_port", &self.server_port)
.field("server_id", &self.server_id)
.field("allowlisted", &self.allowlisted)
.finish()
}
}
impl QueryLogin {
/// The connection the observer and the relays open.
fn connect(&self) -> voelin_query::Connect {
voelin_query::Connect {
transport: match self.transport {
QueryTransport::Raw => voelin_query::Transport::Raw,
QueryTransport::Ssh => voelin_query::Transport::Ssh,
QueryTransport::Http => voelin_query::Transport::Http,
},
addr: self.address.clone(),
user: self.user.clone(),
secret: self.secret.clone(),
server_port: self.server_port,
server_id: self.server_id,
line: voelin_query::LineOptions {
// Off the client-side limit only where the server skips it.
rate_limit: if self.allowlisted {
None
} else {
voelin_query::LineOptions::default().rate_limit
},
..Default::default()
},
}
}
}
pub(crate) enum QueryCmd {
OpenChat(ChatTarget),
CloseChat(ChatTarget),
@@ -21,10 +104,11 @@ pub(crate) enum QueryEvent {
}
pub(crate) async fn run(
connect: voelin_query::Connect,
login: QueryLogin,
mut commands: mpsc::UnboundedReceiver<QueryCmd>,
events: mpsc::UnboundedSender<QueryEvent>,
) {
let connect = login.connect();
let observer = Observer::spawn(ObserverConfig::new(connect.clone()));
let relays = RelayPool::new(RelayConfig::new(connect));
let mut observed = observer.subscribe();
@@ -88,3 +172,59 @@ pub(crate) async fn run(
relays.close_all().await;
let _ = events.send(QueryEvent::Disconnected);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_login_is_the_connection_the_query_crate_opens() {
let login = QueryLogin {
transport: QueryTransport::Ssh,
address: "ts.example.com:10022".into(),
user: "serveradmin".into(),
secret: Some("hunter2".into()),
server_port: Some(9987),
server_id: Some(3),
allowlisted: false,
};
let connect = login.connect();
assert_eq!(connect.transport, voelin_query::Transport::Ssh);
assert_eq!(
(connect.addr.as_str(), connect.user.as_str(), connect.secret.as_deref()),
("ts.example.com:10022", "serveradmin", Some("hunter2"))
);
assert_eq!((connect.server_port, connect.server_id), (Some(9987), Some(3)));
for (ours, theirs) in [
(QueryTransport::Raw, voelin_query::Transport::Raw),
(QueryTransport::Http, voelin_query::Transport::Http),
] {
let connect = QueryLogin { transport: ours, ..login.clone() }.connect();
assert_eq!(connect.transport, theirs);
}
// The line options are the query crate's defaults, as the UI always
// gave them, unless the server allowlists the client.
let line = voelin_query::LineOptions::default();
assert!(line.rate_limit.is_some());
assert_eq!(connect.line.rate_limit, line.rate_limit);
assert_eq!(connect.line.timeout, line.timeout);
let allowlisted = QueryLogin { allowlisted: true, ..login.clone() }.connect();
assert_eq!(allowlisted.line.rate_limit, None);
assert_eq!(allowlisted.line.timeout, line.timeout);
}
#[test]
fn the_secret_stays_out_of_the_debug_text() {
let login = QueryLogin {
transport: QueryTransport::Raw,
address: "h:1".into(),
user: "u".into(),
secret: Some("hunter2".into()),
server_port: None,
server_id: None,
allowlisted: false,
};
let text = format!("{login:?}");
assert!(!text.contains("hunter2") && text.contains("[secret]"), "{text}");
}
}
+146 -185
View File
@@ -16,11 +16,9 @@ use tokio::time::Instant;
use tokio::sync::{broadcast, mpsc, watch};
use tracing::{debug, info, warn};
use tsclientlib::ClientId;
use voelin_audio::AudioSettings;
use voelin_audio::{AudioSettings, EncodedVoice, TalkerId};
use voelin_gateway_proto::{ErrorCode, HistoryEntry, StreamEntry, StreamSpec, feature};
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails, badges};
use voelin_stream::ClientState;
use crate::audio::{self, AudioEvent, AudioHandle, AudioIn};
use crate::cache::{self, Fetch, FetchError, RetryHint, SharedCache, Waiter};
@@ -31,6 +29,7 @@ use crate::gateway::{
Push, ReactionPush,
};
use crate::history::{self, ChatCtx, HistoryMessage, MessageSource, SharedHistory};
use crate::link::{LinkCmd, LinkCtx, LinkEvent, Remote, SessionLink};
use crate::query::{self, QueryCmd, QueryEvent};
use crate::route::{ChatRoute, Dedup, route_chat};
use crate::settings::{
@@ -38,10 +37,9 @@ use crate::settings::{
PRIVACY_PRIVATE_MESSAGES, SharedSettings,
};
use crate::stream::{
LayerSpec, OwnStreamEvent, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInfo,
StreamInput, StreamKind, kind_name, parse_kind,
LayerSpec, OwnStreamEvent, StreamCmd, StreamFrame, StreamInfo, StreamKind, kind_name,
parse_kind, parse_srtp_profiles,
};
use crate::voice::{self, Remote, VoiceCmd, VoiceEvent, VoiceLink};
use crate::web;
use crate::{Command, Event, ObserveState, SessionId, SessionState, Shared, Source, VoiceState};
@@ -86,14 +84,10 @@ impl SessionHandle {
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
shared: Shared,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
link: Arc<SessionLink>,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
tokio::spawn(
Session::new(id, events, frames, audio_settings, shared, myts_identity, myts_data)
.run(rx),
);
tokio::spawn(Session::new(id, events, frames, audio_settings, shared, link).run(rx));
Self { tx }
}
@@ -105,13 +99,11 @@ impl SessionHandle {
/// Events from sources, tagged with the generation of the source so events
/// of a replaced source are ignored.
enum SourceEvent {
Voice(u64, VoiceEvent),
Voice(u64, LinkEvent),
Gateway(u64, GatewayEvent),
Query(u64, QueryEvent),
AudioOut(u64, tsproto_packets::packets::OutPacket),
AudioOut(u64, EncodedVoice),
Audio(u64, AudioEvent),
/// Our own stream (from the stream task of that voice connection).
OwnStream(u64, OwnStreamEvent),
/// The gateway's stream directory after subscribing.
Directory(u64, Result<Vec<StreamEntry>, ClientError>),
/// The server's unique id the database remembers for an address.
@@ -290,13 +282,13 @@ struct OwnStream {
}
struct Session {
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
/// Starts the voice connections.
link: Arc<SessionLink>,
id: SessionId,
events: broadcast::Sender<Event>,
state: SessionState,
generation: u64,
voice: Option<(u64, mpsc::UnboundedSender<VoiceCmd>)>,
voice: Option<(u64, mpsc::UnboundedSender<LinkCmd>)>,
voice_address: String,
voice_presence: Option<Presence>,
nickname: String,
@@ -318,18 +310,15 @@ struct Session {
/// Other names of this server (`voice:<address>`, `gateway:<url>`),
/// remembered with its unique id once a source tells it.
aliases: Vec<String>,
/// Streams of the voice connection (TeamSpeak 6 only).
streams: Option<StreamHandle>,
stream_peer: PeerConfig,
/// The voice connection carries streams (its capabilities say so; the
/// connection runs their task, `LinkCmd::Stream` reaches it).
streams: bool,
/// Simulcast layers of our stream, for the stream task.
stream_layers: Vec<LayerSpec>,
/// The SRTP profile setting (`Command::SetSrtpProfiles`), over the voice
/// options' `stream_peer`.
srtp_profiles: Option<Vec<SrtpProfile>>,
srtp_profiles: Option<Vec<String>>,
frames: broadcast::Sender<StreamFrame>,
/// Channel and `client_is_streaming` of the voice presence, as last told
/// to the streams.
streaming_clients: BTreeMap<u16, ClientState>,
/// The gateway's stream directory, by id.
directory: BTreeMap<String, StreamEntry>,
own_stream: Option<OwnStream>,
@@ -386,15 +375,13 @@ impl Session {
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
shared: Shared,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
link: Arc<SessionLink>,
) -> Self {
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
let Shared { settings, history, cache, contacts } = shared;
let contacts_rx = Some(contacts.watch());
Self {
myts_identity,
myts_data,
link,
cache,
contacts,
contacts_rx,
@@ -434,12 +421,10 @@ impl Session {
history,
own_uid: None,
aliases: Vec::new(),
streams: None,
stream_peer: PeerConfig::default(),
streams: false,
stream_layers: Vec::new(),
srtp_profiles: None,
frames,
streaming_clients: BTreeMap::new(),
directory: BTreeMap::new(),
own_stream: None,
open_chats: HashSet::new(),
@@ -509,17 +494,19 @@ impl Session {
fn command(&mut self, cmd: Command) {
match cmd {
Command::ConnectVoice { options, .. } => {
if let Some((_, tx)) = self.voice.take() {
let _ = tx.send(VoiceCmd::Disconnect);
}
// The streams end first: their shutdown goes through the
// connection that is replaced.
self.stop_streams("voice reconnecting");
if let Some((_, tx)) = self.voice.take() {
let _ = tx.send(LinkCmd::Disconnect);
}
let mut options = *options;
let generation = self.next_generation();
self.voice_address = options.address.clone();
self.details = None;
self.nickname = options.nickname.clone();
self.stream_peer = options.stream_peer.clone();
if let Some(profiles) = &self.srtp_profiles {
self.stream_peer.srtp_profiles = profiles.clone();
options.stream_peer.srtp_profiles = parse_srtp_profiles(profiles);
}
self.known_server(format!("voice:{}", options.address));
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
@@ -532,14 +519,13 @@ impl Session {
self.forward(out_rx, move |p| SourceEvent::AudioOut(generation, p));
self.forward(audio_rx, move |e| SourceEvent::Audio(generation, e));
}
let link = VoiceLink {
myts_identity: self.myts_identity.clone(),
myts_data: self.myts_data.clone(),
let ctx = LinkCtx {
session: self.id,
events: self.events.clone(),
frames: self.frames.clone(),
settings: self.settings.clone(),
};
tokio::spawn(voice::run(*options, link, cmd_rx, ev_tx));
self.link.spawn(options, ctx, cmd_rx, ev_tx);
self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e));
self.forget_images();
self.voice = Some((generation, cmd_tx));
@@ -548,7 +534,7 @@ impl Session {
}
Command::DisconnectVoice { .. } => {
if let Some((_, tx)) = &self.voice {
let _ = tx.send(VoiceCmd::Disconnect);
let _ = tx.send(LinkCmd::Disconnect);
}
}
Command::ObserveGateway { urls, identity, .. } => {
@@ -590,7 +576,10 @@ impl Session {
// source, the history is kept under the query address.
if self.state.server_uid.is_none() {
let port = connect.server_port.map(|p| format!("/{p}")).unwrap_or_default();
self.learn_server_uid(format!("query:{}{port}", connect.addr), Source::Query);
self.learn_server_uid(
format!("query:{}{port}", connect.address),
Source::Query,
);
self.open_histories();
}
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
@@ -626,7 +615,7 @@ impl Session {
self.store_own(&target, &text, &route);
}
match route {
ChatRoute::Voice => self.voice_cmd(VoiceCmd::SendChat(target, text)),
ChatRoute::Voice => self.voice_cmd(LinkCmd::SendChat(target, text)),
ChatRoute::Gateway => {
if let Some((_, tx)) = &self.gateway {
let _ = tx.send(GatewayCmd::SendChat(target, text));
@@ -657,11 +646,11 @@ impl Session {
},
Command::Gateway { request, .. } => self.gateway_request(request),
Command::MoveToChannel { channel, password, .. } => {
self.voice_cmd(VoiceCmd::Move(channel, password));
self.voice_cmd(LinkCmd::Move(channel, password));
}
Command::SetInputMuted { muted, .. } => {
self.state.input_muted = muted;
self.voice_cmd(VoiceCmd::SetInputMuted(muted));
self.voice_cmd(LinkCmd::SetInputMuted(muted));
if let Some(a) = &self.audio {
a.send(AudioIn::InputMuted(muted));
}
@@ -669,7 +658,7 @@ impl Session {
}
Command::SetOutputMuted { muted, .. } => {
self.state.output_muted = muted;
self.voice_cmd(VoiceCmd::SetOutputMuted(muted));
self.voice_cmd(LinkCmd::SetOutputMuted(muted));
if let Some(a) = &self.audio {
a.send(AudioIn::OutputMuted(muted));
}
@@ -692,12 +681,12 @@ impl Session {
// again after connecting.
Command::SetClientVolume { client, volume, .. } => {
if let Some(a) = &self.audio {
a.send(AudioIn::ClientVolume { client: ClientId(client), volume });
a.send(AudioIn::ClientVolume { client: TalkerId(client), volume });
}
}
Command::SetClientMuted { client, muted, .. } => {
if let Some(a) = &self.audio {
a.send(AudioIn::ClientMuted { client: ClientId(client), muted });
a.send(AudioIn::ClientMuted { client: TalkerId(client), muted });
}
}
Command::SetStreamVolume { stream_id, volume, .. } => {
@@ -706,50 +695,43 @@ impl Session {
}
}
Command::StartStream { setup, auto_accept, .. } => {
self.stream_input(StreamInput::Start { setup, auto_accept });
self.stream_input(StreamCmd::Start { setup, auto_accept });
}
Command::StopStream { .. } => self.stream_input(StreamInput::Stop),
Command::StopStream { .. } => self.stream_input(StreamCmd::Stop),
Command::AcceptViewer { viewer, accept, .. } => {
self.stream_input(StreamInput::Respond { viewer, accept });
self.stream_input(StreamCmd::Respond { viewer, accept });
}
Command::KickViewer { viewer, .. } => self.stream_input(StreamInput::Kick { viewer }),
Command::KickViewer { viewer, .. } => self.stream_input(StreamCmd::Kick { viewer }),
Command::SendStreamFrame { frame, .. } => {
// Frames without a stream are dropped silently.
if let Some(s) = &self.streams {
s.send(StreamInput::Frame(frame));
}
self.stream_cmd(StreamCmd::Frame(frame));
}
Command::WatchStream { stream_id, .. } => {
self.stream_input(StreamInput::Watch { stream_id });
self.stream_input(StreamCmd::Watch { stream_id });
}
Command::LeaveStream { stream_id, .. } => {
self.stream_input(StreamInput::Leave { stream_id });
self.stream_input(StreamCmd::Leave { stream_id });
}
Command::RequestStreamKeyframe { stream_id, .. } => {
self.stream_input(StreamInput::RequestKeyframe { stream_id });
self.stream_input(StreamCmd::RequestKeyframe { stream_id });
}
Command::StreamUndecodable { stream_id, .. } => {
self.stream_input(StreamInput::Undecodable { stream_id });
self.stream_input(StreamCmd::Undecodable { stream_id });
}
Command::SetWatchLayer { stream_id, layer, .. } => {
self.stream_input(StreamInput::WatchLayer { stream_id, layer });
self.stream_input(StreamCmd::WatchLayer { stream_id, layer });
}
// Kept for streams started later, also without a connection.
Command::SetStreamLayers { layers, .. } => {
self.stream_layers = layers.clone();
if let Some(s) = &self.streams {
s.send(StreamInput::Layers(layers));
}
self.stream_cmd(StreamCmd::Layers(layers));
}
Command::SetSrtpProfiles(profiles) => {
self.stream_peer.srtp_profiles = profiles.clone();
self.srtp_profiles = Some(profiles.clone());
if let Some(s) = &self.streams {
s.send(StreamInput::SrtpProfiles(profiles));
}
self.stream_cmd(StreamCmd::SrtpProfiles(profiles));
}
Command::Poke { client, message, .. } => {
self.voice_cmd(VoiceCmd::Poke { client, message });
self.voice_cmd(LinkCmd::Poke { client, message });
}
Command::ListFiles { request, channel, password, path, .. } => {
if self.voice.is_none() {
@@ -759,7 +741,7 @@ impl Session {
return;
}
let dir = Remote { channel, password, path };
self.voice_cmd(VoiceCmd::ListFiles { request, dir });
self.voice_cmd(LinkCmd::ListFiles { request, dir });
}
Command::DownloadFile { transfer, channel, password, path, to, .. } => {
self.download(transfer, Remote { channel, password, path }, &to);
@@ -797,34 +779,27 @@ impl Session {
let report = self.transfer_report(transfer);
let file = Remote { channel, password, path };
let transfer = Some(transfer);
self.voice_cmd(VoiceCmd::Upload {
transfer,
file,
from,
overwrite,
resume,
report,
});
self.voice_cmd(LinkCmd::Upload { transfer, file, from, overwrite, resume, report });
}
Command::CancelTransfer { transfer, .. } => {
self.voice_cmd(VoiceCmd::CancelTransfer(transfer));
self.voice_cmd(LinkCmd::CancelTransfer(transfer));
}
Command::DeleteFiles { request, channel, password, paths, .. } => {
let request = Some(request);
self.voice_request(
request,
VoiceCmd::DeleteFiles { request, channel, password, paths },
LinkCmd::DeleteFiles { request, channel, password, paths },
);
}
Command::RenameFile { request, channel, password, from, to, to_channel, .. } => {
let (to_channel, to_password) = to_channel.unwrap_or((channel, password.clone()));
let from = Remote { channel, password, path: from };
let to = Remote { channel: to_channel, password: to_password, path: to };
self.voice_request(Some(request), VoiceCmd::RenameFile { request, from, to });
self.voice_request(Some(request), LinkCmd::RenameFile { request, from, to });
}
Command::CreateDirectory { request, channel, password, path, .. } => {
let dir = Remote { channel, password, path };
self.voice_request(Some(request), VoiceCmd::CreateDirectory { request, dir });
self.voice_request(Some(request), LinkCmd::CreateDirectory { request, dir });
}
Command::SetAvatar { request, image, .. } => self.set_avatar(request, image),
Command::FetchAvatar { client_uid, .. } => {
@@ -856,7 +831,7 @@ impl Session {
self.emit(Event::OfflineMessages { session: self.id, request, result });
return;
}
self.voice_cmd(VoiceCmd::OfflineList { request });
self.voice_cmd(LinkCmd::OfflineList { request });
}
Command::GetOfflineMessage { request, id, .. } => {
if self.voice.is_none() {
@@ -864,22 +839,20 @@ impl Session {
self.emit(Event::OfflineMessage { session: self.id, request, result });
return;
}
self.voice_cmd(VoiceCmd::OfflineGet { request, id });
self.voice_cmd(LinkCmd::OfflineGet { request, id });
}
Command::SendOfflineMessage { request, to_uid, subject, text, .. } => {
let cmd = VoiceCmd::OfflineAdd { request, to_uid, subject, text };
let cmd = LinkCmd::OfflineAdd { request, to_uid, subject, text };
self.voice_request(Some(request), cmd);
}
Command::DeleteOfflineMessage { request, id, .. } => {
self.voice_request(Some(request), VoiceCmd::OfflineDelete { request, id });
self.voice_request(Some(request), LinkCmd::OfflineDelete { request, id });
}
Command::SetOfflineMessageRead { request, id, read, .. } => {
self.voice_request(Some(request), VoiceCmd::OfflineFlag { request, id, read });
self.voice_request(Some(request), LinkCmd::OfflineFlag { request, id, read });
}
// Engine-wide.
Command::SetMytsIdentity(_)
| Command::SetMytsData(_)
| Command::CloseSession { .. }
Command::CloseSession { .. }
| Command::TestMicrophone { .. }
| Command::SetSetting { .. }
| Command::ResetSetting { .. }
@@ -894,7 +867,7 @@ impl Session {
// Files, avatars, icons
/// A request to the voice connection; without one it fails at once.
fn voice_request(&self, request: Option<RequestId>, cmd: VoiceCmd) {
fn voice_request(&self, request: Option<RequestId>, cmd: LinkCmd) {
match (&self.voice, request) {
(Some(_), _) => self.voice_cmd(cmd),
(None, Some(request)) => self.emit(Event::RequestDone {
@@ -925,7 +898,7 @@ impl Session {
}
let report = self.transfer_report(transfer);
let sink = Sink::from_target(to);
self.voice_cmd(VoiceCmd::Download { transfer: Some(transfer), file, sink, report });
self.voice_cmd(LinkCmd::Download { transfer: Some(transfer), file, sink, report });
}
/// Upload our avatar and announce its hash, or remove it.
@@ -938,7 +911,7 @@ impl Session {
let Some(image) = image else {
// The file too (best effort), then no hash.
if let Some(path) = self.own_uid.as_deref().and_then(files::avatar_path) {
let cmd = VoiceCmd::DeleteFiles {
let cmd = LinkCmd::DeleteFiles {
request: None,
channel: 0,
password: None,
@@ -947,7 +920,7 @@ impl Session {
self.voice_cmd(cmd);
}
let hash = String::new();
self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash });
self.voice_cmd(LinkCmd::SetAvatarHash { request: Some(request), hash });
return;
};
let (sources, cache, settings) =
@@ -983,7 +956,7 @@ impl Session {
let _ = sources.send(SourceEvent::AvatarUploaded(generation, request, result));
});
let file = Remote { channel: 0, password: None, path: "/avatar".into() };
let upload = VoiceCmd::Upload {
let upload = LinkCmd::Upload {
transfer: None,
file,
from: image,
@@ -1403,7 +1376,7 @@ impl Session {
let sink = Sink::File { part: temp.clone(), dest: temp, append: false };
let file = Remote { channel, password: None, path };
let failed = report.clone();
if voice.send(VoiceCmd::Download { transfer: None, file, sink, report }).is_err() {
if voice.send(LinkCmd::Download { transfer: None, file, sink, report }).is_err() {
failed(TransferState::Failed(NO_VOICE.into()));
}
}
@@ -1436,24 +1409,22 @@ impl Session {
if let Some(a) = &self.audio {
for (client, (volume, muted)) in &wanted {
if self.contact_audio.get(client) != Some(&(*volume, *muted)) {
a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: *volume });
a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: *muted });
a.send(AudioIn::ClientVolume { client: TalkerId(*client), volume: *volume });
a.send(AudioIn::ClientMuted { client: TalkerId(*client), muted: *muted });
}
}
// No contact setting any more: back to normal.
for client in self.contact_audio.keys().filter(|c| !wanted.contains_key(c)) {
if p.clients.contains_key(client) {
a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: 1.0 });
a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: false });
a.send(AudioIn::ClientVolume { client: TalkerId(*client), volume: 1.0 });
a.send(AudioIn::ClientMuted { client: TalkerId(*client), muted: false });
}
}
self.contact_audio = wanted;
}
if friends != self.stream_friends {
self.stream_friends = friends.clone();
if let Some(s) = &self.streams {
s.send(StreamInput::Friends(friends));
}
self.stream_cmd(StreamCmd::Friends(friends));
}
}
@@ -1464,7 +1435,7 @@ impl Session {
let clients = p.clients.values().filter(|c| c.priority_speaker).map(|c| c.id).collect();
let wanted = (clients, p.server.priority_speaker_dimm_db);
if wanted != self.priority_audio {
let clients = wanted.0.iter().map(|c| ClientId(*c)).collect();
let clients = wanted.0.iter().map(|c| TalkerId(*c)).collect();
a.send(AudioIn::PrioritySpeakers { clients, dimm_db: wanted.1 as f32 });
self.priority_audio = wanted;
}
@@ -1502,26 +1473,36 @@ impl Session {
allows(self.settings.current().get(key), uid.map(|u| self.contacts.relation(u)))
}
fn stream_input(&self, input: StreamInput) {
match &self.streams {
Some(s) => s.send(input),
None if self.state.voice == VoiceState::Connected => {
self.error("streams need a TeamSpeak 6 server");
}
None => self.error("not connected with voice"),
/// A stream command of the user: an error where the connection has no
/// streams.
fn stream_input(&self, cmd: StreamCmd) {
if self.streams {
self.stream_cmd(cmd);
} else if self.state.voice == VoiceState::Connected {
self.error("streams need a TeamSpeak 6 server");
} else {
self.error("not connected with voice");
}
}
/// A command for the streams of the voice connection; dropped where it
/// has none.
fn stream_cmd(&self, cmd: StreamCmd) {
if let (true, Some((_, tx))) = (self.streams, &self.voice) {
let _ = tx.send(LinkCmd::Stream(cmd));
}
}
fn stop_streams(&mut self, reason: &str) {
if let Some(s) = self.streams.take() {
s.send(StreamInput::Shutdown(reason.into()));
if self.streams {
self.stream_cmd(StreamCmd::Shutdown(reason.into()));
self.streams = false;
}
self.streaming_clients.clear();
// The stream task's report comes from a replaced source.
self.own_stream_ended();
}
fn voice_cmd(&self, cmd: VoiceCmd) {
fn voice_cmd(&self, cmd: LinkCmd) {
match &self.voice {
Some((_, tx)) => {
let _ = tx.send(cmd);
@@ -1710,14 +1691,16 @@ impl Session {
/// The registered streams of the directory, for the stream task.
fn feed_directory(&self) {
let Some(streams) = &self.streams else { return };
if !self.streams {
return;
}
let entries = self
.directory
.values()
.filter_map(|e| {
Some(StreamInfo {
id: e.stream_id.clone()?,
streamer: ClientId(e.client_id?),
streamer: e.client_id?,
name: e.title.clone(),
kind: parse_kind(&e.kind),
// Not in the directory; the stream's offer tells.
@@ -1729,7 +1712,7 @@ impl Session {
})
})
.collect();
streams.send(StreamInput::Directory(entries));
self.stream_cmd(StreamCmd::Directory(entries));
}
fn register_own_stream(&mut self) {
@@ -1834,7 +1817,7 @@ impl Session {
}
self.stop_streams("session closed");
if let Some((_, tx)) = self.voice.take() {
let _ = tx.send(VoiceCmd::Disconnect);
let _ = tx.send(LinkCmd::Disconnect);
}
self.audio = None;
self.stop_observing();
@@ -1858,7 +1841,7 @@ impl Session {
SourceEvent::Query(g, e) if self.is_current(Source::Query, g) => self.query_event(e),
SourceEvent::AudioOut(g, packet) if self.is_current(Source::Voice, g) => {
if let Some((_, tx)) = &self.voice {
let _ = tx.send(VoiceCmd::Audio(packet));
let _ = tx.send(LinkCmd::Audio(packet));
}
}
SourceEvent::Audio(g, event) if self.is_current(Source::Voice, g) => match event {
@@ -1867,9 +1850,6 @@ impl Session {
self.emit(Event::InputLevel { session: Some(self.id), level_db: db, sending })
}
},
SourceEvent::OwnStream(g, e) if self.is_current(Source::Voice, g) => {
self.own_stream_event(e)
}
SourceEvent::Directory(g, result) if self.is_current(Source::Gateway, g) => {
match result {
Ok(streams) => {
@@ -1895,7 +1875,7 @@ impl Session {
}
SourceEvent::AvatarUploaded(g, request, result) => match result {
Ok(hash) if self.is_current(Source::Voice, g) => {
self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash });
self.voice_cmd(LinkCmd::SetAvatarHash { request: Some(request), hash });
}
Ok(_) => self.emit(Event::RequestDone {
session: self.id,
@@ -1923,9 +1903,16 @@ impl Session {
}
}
fn voice_event(&mut self, e: VoiceEvent) {
fn voice_event(&mut self, e: LinkEvent) {
match e {
VoiceEvent::Connected { name, flavor, own_client, server_uid, own_uid } => {
LinkEvent::Connected {
name,
backend,
capabilities,
own_client,
server_uid,
own_uid,
} => {
self.state.voice = VoiceState::Connected;
self.state.own_client = Some(own_client);
if own_uid.is_some() {
@@ -1940,50 +1927,26 @@ impl Session {
{
let _ = tx.send(GatewayCmd::RetryNow);
}
let capabilities = flavor.capabilities();
if capabilities.streams
&& let Some((generation, voice)) = &self.voice
{
let generation = *generation;
let (own_tx, own_rx) = mpsc::unbounded_channel();
self.forward(own_rx, move |e| SourceEvent::OwnStream(generation, e));
let streams = StreamHandle::spawn(
self.id,
own_client,
self.stream_peer.clone(),
voice.clone(),
self.events.clone(),
self.frames.clone(),
self.audio.clone(),
self.settings.clone(),
own_tx,
);
if capabilities.streams {
self.streams = true;
if !self.stream_layers.is_empty() {
streams.send(StreamInput::Layers(self.stream_layers.clone()));
self.stream_cmd(StreamCmd::Layers(self.stream_layers.clone()));
}
// The setting may have changed since the connection was asked for.
if let Some(profiles) = self.srtp_profiles.clone() {
self.stream_cmd(StreamCmd::SrtpProfiles(profiles));
}
self.streams = Some(streams);
self.feed_directory();
}
self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities });
self.emit(Event::ServerInfo { session: self.id, name, backend, capabilities });
self.reopen_relayed_chats();
self.open_histories();
}
VoiceEvent::Presence(p) => {
LinkEvent::Presence(p) => {
// Client ids are reused: forget the volumes of those who left.
if let (Some(a), Some(old)) = (&self.audio, &self.voice_presence) {
for id in old.clients.keys().filter(|id| !p.clients.contains_key(id)) {
a.send(AudioIn::ClientLeft(ClientId(*id)));
}
}
if let Some(s) = &self.streams {
let clients: BTreeMap<_, _> = p
.clients
.values()
.map(|c| (c.id, ClientState { channel: c.channel, streaming: c.streaming }))
.collect();
if clients != self.streaming_clients {
self.streaming_clients = clients.clone();
s.send(StreamInput::Clients(clients));
a.send(AudioIn::ClientLeft(TalkerId(*id)));
}
}
self.report_details(&p);
@@ -1993,7 +1956,7 @@ impl Session {
self.voice_presence = Some(*p);
self.publish_presence();
}
VoiceEvent::Poke { from, from_uid, from_name, message } => {
LinkEvent::Poke { from, from_uid, from_name, message } => {
let blocked = self.contacts.is_blocked(from_uid.as_deref());
if blocked && self.block_mode() == BlockMode::Hide {
debug!(?from_uid, "poke of a blocked contact hidden");
@@ -2006,35 +1969,37 @@ impl Session {
let session = self.id;
self.emit(Event::Poke { session, from, from_uid, from_name, message, blocked });
}
VoiceEvent::Error(message) => self.error(message),
VoiceEvent::Stream(n) => {
if let Some(s) = &self.streams {
s.send(StreamInput::Notification(n));
LinkEvent::Error(message) => self.error(message),
LinkEvent::OwnStream(e) => self.own_stream_event(e),
LinkEvent::StreamAudio { stream, time, data } => {
if let Some(a) = &self.audio {
a.send(AudioIn::StreamAudio { stream, time, data });
}
}
VoiceEvent::StreamRequestFailed(request, error) => {
if let Some(s) = &self.streams {
s.send(StreamInput::RequestFailed(request, error));
LinkEvent::StreamAudioEnded(stream) => {
if let Some(a) = &self.audio {
a.send(AudioIn::StreamEnded(stream));
}
}
VoiceEvent::OwnChannel(cid) => {
LinkEvent::OwnChannel(cid) => {
if self.state.own_channel != Some(cid) {
self.state.own_channel = Some(cid);
self.emit_state();
}
}
VoiceEvent::Chat(msg) => self.chat(msg, MessageSource::Voice, None),
VoiceEvent::Audio(packet) => {
LinkEvent::Chat(msg) => self.chat(msg, MessageSource::Voice, None),
LinkEvent::Audio(packet) => {
if let Some(a) = &self.audio {
a.send(AudioIn::Packet(packet));
}
}
VoiceEvent::Talking { client, talking } => {
LinkEvent::Talking { client, talking } => {
self.emit(Event::Talking { session: self.id, client, talking });
}
VoiceEvent::Disconnected(reason) => {
self.stop_streams("voice disconnected");
LinkEvent::Disconnected(reason) => {
// The connection ended its streams itself.
self.voice = None;
self.stop_streams("voice disconnected");
self.voice_presence = None;
self.audio = None;
self.forget_images();
@@ -2288,18 +2253,13 @@ mod banner_tests {
cache: SharedCache::new(Cache::new(dir)),
contacts: Contacts::new(events.clone(), history),
};
// No myTeamSpeak account; its source stays open, as the engine's does
// (a closed one ends voice connections).
let myts_identity = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
let myts_data = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
let session = Session::new(
1,
events,
frames,
AudioSettings::default(),
shared,
myts_identity,
myts_data,
Arc::new(SessionLink::new(crate::Backends::empty())),
);
(session, receiver)
}
@@ -2386,7 +2346,7 @@ mod banner_tests {
Err("temporarily unavailable".into()),
);
session.retry_images(session.image_retries[&request].due.unwrap());
let VoiceCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
let LinkCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
commands.try_recv().unwrap()
else {
panic!("expected an image download");
@@ -2433,7 +2393,7 @@ mod banner_tests {
session.state.server_uid = Some("server-a".into());
session.fetch_pictures(&presence);
assert!(session.pictures.contains(url));
let VoiceCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
let LinkCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
commands.try_recv().unwrap()
else {
panic!("expected a file download");
@@ -2975,9 +2935,10 @@ mod banner_tests {
let (mut session, _events) = session("gateway-wake");
let (tx, mut rx) = mpsc::unbounded_channel();
session.gateway = Some((session.next_generation(), tx));
let connected = || VoiceEvent::Connected {
let connected = || LinkEvent::Connected {
name: "test".into(),
flavor: voelin_model::ServerFlavor::Unknown(String::new()),
backend: crate::BackendInfo::default(),
capabilities: voelin_model::Capabilities::default(),
own_client: 1,
server_uid: "server=".into(),
own_uid: None,
+2 -2
View File
@@ -50,8 +50,8 @@ use serde_json::{Value, json};
use tokio::sync::{broadcast, watch};
use tracing::{debug, warn};
use voelin_audio::AudioSettings;
use voelin_media::{LayerId, LayerSpec};
use voelin_store::Store;
use voelin_stream::{LayerId, LayerSpec};
/// A value of any key, typed (`Arc<T>` of the key's `T`).
type Stored = Arc<dyn Any + Send + Sync>;
@@ -1135,7 +1135,7 @@ pub static CACHE_FETCH_IMAGES: Key<bool> = Key::new(
);
/// Import identities from the official TeamSpeak clients when the app
/// starts ([`crate::identity::import_new`]; their files are only read).
/// starts ([`crate::ts::identity::import_new`]; their files are only read).
pub static IDENTITY_IMPORT: Key<bool> = Key::new(
"identity.import_from_teamspeak",
Kind::Bool,
File diff suppressed because it is too large. Load diff
+155
View File
@@ -0,0 +1,155 @@
//! The stream types of the engine's API, owned by the core: what the UI is
//! told about streams ([`StreamInfo`], [`ViewerInfo`], why a stream
//! [ended](EndReason)) and what it asks for ([`StreamSetup`]).
//!
//! They carry plain fields only: client ids are `u16`, an SRTP profile is its
//! name, a video codec is `voelin_media`'s. What a server link speaks (the
//! TeamSpeak 6 stream crate today) is converted to and from them at the
//! boundary in [`crate::stream`], so the UI does not depend on the link's
//! types. The frame and simulcast layer types (`EncodedFrame`, `LayerSpec`,
//! `LayerId`) are `voelin-media`'s.
use voelin_media::{Codec, LayerId};
/// What a stream shows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StreamKind {
Camera,
Screen,
Window,
/// A kind this client does not know, by its number on the server.
Other(u8),
}
impl StreamKind {
/// From the number servers use: 2 camera, 3 screen, 4 window.
pub fn from_u8(v: u8) -> Self {
match v {
2 => Self::Camera,
3 => Self::Screen,
4 => Self::Window,
v => Self::Other(v),
}
}
/// [`from_u8`](Self::from_u8) back.
pub fn to_u8(self) -> u8 {
match self {
Self::Camera => 2,
Self::Screen => 3,
Self::Window => 4,
Self::Other(v) => v,
}
}
}
/// What we announce when we start a stream ([`crate::Command::StartStream`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StreamSetup {
pub name: String,
pub kind: StreamKind,
/// The stream's video bitrate in kbit/s (the single layer's without
/// simulcast). TeamSpeak 6 servers keep it in 16 bits, so it is
/// announced as at most 65535; the stream sends its real rate whatever
/// the announcement says.
pub bitrate: u32,
/// `accessibility`: the official client sends 1.
pub accessibility: u8,
/// `mode`: 1 (none) is what clients send today; 2 is P2P, 3 SFU.
pub mode: u8,
/// 0 = unlimited.
pub viewer_limit: u32,
pub audio: bool,
}
impl Default for StreamSetup {
fn default() -> Self {
Self {
name: String::new(),
kind: StreamKind::Screen,
bitrate: 4608,
accessibility: 1,
mode: 1,
viewer_limit: 0,
audio: true,
}
}
}
/// A stream on the server ([`crate::Event::StreamsChanged`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StreamInfo {
pub id: String,
/// The client id of the streamer.
pub streamer: u16,
pub name: String,
pub kind: StreamKind,
pub bitrate: u32,
pub viewer_limit: u32,
pub audio: bool,
/// How many watch it; `None` where nothing told (e.g. a gateway's
/// directory entry).
pub viewers: Option<u32>,
}
/// A viewer of our stream, as we see it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ViewerState {
/// Asked to watch, waiting for our decision.
Requested,
/// Offer sent; waiting for the answer and the connection.
Connecting,
Connected,
}
/// A viewer of our stream ([`crate::Event::StreamViewers`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ViewerInfo {
/// The client id of the viewer.
pub client: u16,
pub state: ViewerState,
/// The message of the join request.
pub message: String,
/// The simulcast layer the viewer receives (it moves at a keyframe of the
/// new layer); `None` before we offered, and with RID simulcast (all
/// layers).
pub layer: Option<LayerId>,
/// The latest bandwidth estimate of the connection (bit/s).
pub estimate: Option<u64>,
/// The SRTP profile of the connection by its name (as in RFC 5764 and
/// WebRTC statistics, e.g. `AEAD_AES_128_GCM`), once the key exchange is
/// done.
pub srtp_profile: Option<String>,
/// The video codec the viewer's answer chose (it gets video in that
/// codec).
pub codec: Option<Codec>,
}
/// Why a viewer left a stream.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LeaveReason {
None,
Left,
Denied,
Failed,
Kicked,
Banned,
/// A reason this client does not know, by its number on the server.
Other(u8),
}
/// Why a stream ended for us ([`crate::StreamState::Ended`],
/// [`crate::WatchState::Ended`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EndReason {
/// We stopped streaming or watching.
Local,
/// The streamer denied our join request.
Denied,
/// The stream was stopped (or its streamer disconnected).
Stopped,
/// The streamer or the server ended our viewing session.
Removed(Option<LeaveReason>),
/// A command failed or no connection could be established.
Failed(String),
}
@@ -331,4 +331,301 @@ mod tests {
let p = presence_from_book(&book, None, |_| false);
assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png"));
}
// ---- across the session seam ---------------------------------------------
/// A presence made into the entities the TeamSpeak session writes
/// (`ts_session::entities`), pushed the way a host syncs them, and
/// projected back by the engine (`link::project`): what the UI is shown
/// of what a TeamSpeak link reported (`docs/session-seam.md` section 5.1).
fn through_the_seam(presence: &Presence, ts6: bool, own: Option<u16>) -> Presence {
use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId};
use voelin_proto::link::Features;
use voelin_proto::v1::{self, push::Body};
use crate::link::media::TalkTracker;
use crate::link::project::{View, presence as project};
use crate::ts::ts_session::entities::build;
let built = build(presence, ts6, own);
let mut replica = Replica::new(SCHEMA_GENERATION);
for (scope, layer) in [(ScopeId::Server(1), &built.server), (ScopeId::Live(1), &built.live)]
{
replica.subscribe(scope);
let pushes = [
Body::SyncBegin(v1::SyncBegin {
scope: Some(scope.to_proto()),
mode: v1::SyncMode::Full as i32,
epoch: 1,
}),
Body::Change(v1::Change {
scope: Some(scope.to_proto()),
rev: 1,
put: layer.values().cloned().collect(),
del: Vec::new(),
}),
Body::SyncEnd(v1::SyncEnd {
scope: Some(scope.to_proto()),
cursor: Some(v1::Cursor { epoch: 1, rev: 1 }),
gap: false,
}),
];
for body in pushes {
replica.apply_push(&v1::Push { body: Some(body) });
}
}
let features = Features::new(["voice"]);
let talking = TalkTracker::default();
project(&View {
replica: &replica,
server: 1,
teamspeak: true,
version: "",
features: &features,
streams: ts6,
talking: &talking,
})
}
/// A TeamSpeak 6 server and some clients with what the book holds of them.
fn ts6_presence() -> Presence {
let mut book = ts6_book();
let list = format!(
"channellist {}|{}|{}",
channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"),
channel(
12,
1,
"Raid",
r"channel_banner_gfx_url=http:\/\/127.0.0.1:1\/d.png channel_banner_mode=2"
),
channel(20, 12, "Last", "channel_banner_gfx_url channel_banner_mode=0"),
);
book.handle_command(&message(&list)).unwrap();
let enter = |clid: u16, channel: u64, groups: &str, away: &str, avatar: &str| {
format!(
"notifycliententerview reasonid=0 ctid={channel} clid={clid} \
client_database_id={} client_nickname=c{clid} client_type=0 cfid=0 \
client_unique_identifier=u{clid}= client_flag_avatar=abcdef \
client_description=about\\sme client_icon_id=777 client_input_muted=1 \
client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \
client_output_hardware=1 client_meta_data client_is_recording=1 \
client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \
client_servergroups={groups} client_away={} client_away_message={away} \
client_talk_power=75 client_talk_request=0 client_talk_request_msg \
client_is_talker=1 client_is_priority_speaker=1 client_unread_messages=0 \
client_nickname_phonetic client_needed_serverquery_view_power=75 \
client_is_channel_commander=1 client_country=RU client_badges \
client_myteamspeak_id=m{clid} client_integrations{avatar}",
100 + u64::from(clid),
u8::from(!away.is_empty()),
)
};
for text in [
enter(5, 1, "8", "", r" client_myteamspeak_avatar=2,https:\/\/a.example\/on.png"),
enter(6, 12, "8,9", "gone\\sfishing", ""),
enter(7, 12, "", "", " client_myteamspeak_avatar"),
] {
book.handle_command(&message(&text)).unwrap();
}
presence_from_book(&book, Some("ibhejBRSRRI7v+fSsUzpQ33JGK6rf5xKOLelpWUr0sE="), |_| false)
}
#[test]
fn a_book_is_what_the_ui_is_shown_across_the_seam() {
let p = ts6_presence();
assert_eq!(p.clients.len(), 3, "the fixture has clients");
assert!(p.clients.values().any(|c| c.away.is_some()), "one is away");
// A TeamSpeak 6 client the book has no streaming flag of (it was not
// sent) is not streaming: v1 has no "unknown" for it.
let mut expected = p.clone();
for client in expected.clients.values_mut() {
client.streaming = Some(client.streaming.unwrap_or(false));
}
assert_eq!(through_the_seam(&p, true, Some(5)), expected);
// The same server as a TeamSpeak 3 one has no streams to tell of.
let mut ts3 = p.clone();
for client in ts3.clients.values_mut() {
client.streaming = None;
}
assert_eq!(through_the_seam(&ts3, false, Some(5)), ts3);
}
/// A deterministic stream of numbers for the generated presences.
struct Numbers(u64);
impl Numbers {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
fn flag(&mut self) -> bool {
self.below(2) == 0
}
fn text(&mut self, prefix: &str) -> String {
format!("{prefix}{}", self.below(1000))
}
}
/// A presence of the shape a TeamSpeak link reports: sibling channels in an
/// order chain, every client with a database id, unique ids that are base64
/// (TeamSpeak 3 and 6) or login names, groups of both kinds.
fn generated(seed: u64, ts6: bool) -> Presence {
use base64::Engine as _;
use voelin_model::{
BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
HostMessageMode,
};
let mut n = Numbers(seed | 1);
let mut p = Presence::default();
let name = n.text("Server ");
p.server_name = name.clone();
p.server = voelin_model::ServerDetails {
name,
uid: Some(n.text("uid")),
welcome_message: n.text("welcome "),
host_message: n.text("host "),
host_message_mode: [
HostMessageMode::None,
HostMessageMode::Log,
HostMessageMode::Modal,
][n.below(3) as usize],
banner_url: if n.flag() { n.text("https://b/") } else { String::new() },
banner_gfx_url: if n.flag() { n.text("https://g/") } else { String::new() },
banner_gfx_interval_s: n.below(100),
banner_mode: [BannerMode::NoAdjust, BannerMode::IgnoreAspect, BannerMode::KeepAspect]
[n.below(3) as usize],
host_button_tooltip: if n.flag() { n.text("tip ") } else { String::new() },
host_button_url: String::new(),
host_button_gfx_url: String::new(),
icon: n.below(5) as u32 * 1000,
platform: "Linux".into(),
version: n.text("6.0."),
max_clients: n.below(500) as u16,
priority_speaker_dimm_db: -(n.below(30) as i32),
default_server_group: Some(1 + n.below(9)),
default_channel_group: Some(1 + n.below(9)),
};
// Groups.
for id in 1..=(2 + n.below(4)) {
let group = |id: u64, n: &mut Numbers| GroupInfo {
id,
name: n.text("group "),
icon: n.below(3) as u32 * 100,
sort_id: n.below(1000) as i32 - 500,
naming_mode: [
GroupNamingMode::None,
GroupNamingMode::Before,
GroupNamingMode::After,
][n.below(3) as usize],
group_type: [GroupType::Regular, GroupType::Template, GroupType::Query]
[n.below(3) as usize],
};
p.server_groups.insert(id, group(id, &mut n));
p.channel_groups.insert(id, group(id, &mut n));
}
// Channels: a tree whose siblings follow each other.
let mut parents = vec![0u64];
for id in 1..=(3 + n.below(8)) {
let parent = parents[n.below(parents.len() as u64) as usize];
let order = p
.channels
.values()
.filter(|c| c.parent == parent)
.map(|c| c.id)
.next_back()
.unwrap_or(0);
parents.push(id);
p.channels.insert(
id,
ChannelInfo {
id,
parent,
order,
name: n.text("channel "),
topic: n.flag().then(|| n.text("topic ")),
has_password: n.flag(),
max_clients: match n.below(3) {
0 => None,
1 => Some(0),
_ => Some(1 + n.below(50) as i32),
},
needed_subscribe_power: n.below(3) as i32 * 10,
needed_talk_power: n.below(3) as i32 * 25,
is_default: id == 1,
icon: n.below(3) as u32 * 500,
banner_gfx_url: n.flag().then(|| n.text("https://c/")),
banner_mode: [
BannerMode::NoAdjust,
BannerMode::IgnoreAspect,
BannerMode::KeepAspect,
][n.below(3) as usize],
},
);
}
// Clients.
let channels: Vec<u64> = p.channels.keys().copied().collect();
for id in 1..=(1 + n.below(12)) {
let id = id as u16;
let uid = match n.below(4) {
0 => None,
1 => Some(n.text("login")),
_ => {
let bytes: Vec<u8> =
(0..if ts6 { 32 } else { 20 }).map(|_| n.below(256) as u8).collect();
Some(base64::engine::general_purpose::STANDARD.encode(bytes))
}
};
let channel = channels[n.below(channels.len() as u64) as usize];
p.clients.insert(
id,
ClientInfo {
id,
uid,
nickname: n.text("nick "),
channel,
is_query: n.below(5) == 0,
away: n.flag().then(|| if n.flag() { n.text("away ") } else { String::new() }),
input_muted: n.flag(),
output_muted: n.flag(),
talking: Some(false),
streaming: ts6.then(|| n.flag()),
server_groups: (0..n.below(3)).map(|_| 1 + n.below(9)).collect(),
country: n.flag().then(|| "DE".into()),
avatar: n.flag().then(|| n.text("hash")),
myts_avatar: n.flag().then(|| n.text("https://a/")),
description: n.flag().then(|| n.text("about ")),
talk_power: n.below(100) as i32,
talker: n.flag(),
channel_group: n.flag().then(|| 1 + n.below(9)),
badges: (0..n.below(3)).map(|_| n.text("badge")).collect(),
icon: n.below(3) as u32 * 111,
recording: n.flag(),
priority_speaker: n.flag(),
channel_commander: n.flag(),
database_id: Some(1_000 + u64::from(id)),
},
);
}
p
}
#[test]
fn generated_presences_survive_the_seam() {
for seed in 1..=200u64 {
for ts6 in [false, true] {
let p = generated(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15), ts6);
let own = p.clients.keys().next().copied();
assert_eq!(through_the_seam(&p, ts6, own), p, "seed {seed}, ts6 {ts6}");
}
}
}
}
@@ -32,6 +32,7 @@ use std::{fs, str};
use rusqlite::{Connection, OpenFlags, OptionalExtension};
use tsclientlib::Identity;
use voelin_gateway_proto::UniqueIds;
use voelin_identity::IdentityBlob;
use voelin_store::{IdentityOrigin, Store};
/// Name given to an identity whose source kept none.
@@ -55,6 +56,9 @@ pub enum IdentityError {
NoIdentity { path: String },
#[error("client database: {0}")]
Store(String),
/// An [`IdentityBlob`] that is no TeamSpeak identity ([`from_blob`]).
#[error("{0}")]
Blob(String),
}
impl IdentityError {
@@ -230,6 +234,77 @@ pub fn import_new(store: &Store, paths: &[PathBuf]) -> Result<LaunchImport, Iden
Ok(report)
}
/// A TeamSpeak identity as the API takes it
/// ([`VoiceOptions::identity`](crate::VoiceOptions::identity),
/// [`Command::ObserveGateway`](crate::Command::ObserveGateway)) and the key
/// store keeps it: kind `teamspeak`, the unique id TeamSpeak 3 servers know it
/// by (also how [`voelin_store`] keys it), its security level, and the JSON
/// the store writes.
pub fn to_blob(identity: &Identity) -> IdentityBlob {
// An identity is a key and two counters: writing it cannot fail. (A blob with
// no JSON is refused when it is used, in words.)
let json = serde_json::to_string(identity).unwrap_or_default();
IdentityBlob::teamspeak(identity.key().to_pub().get_uid(), identity.level(), json)
}
/// The TeamSpeak identity of a blob (the reverse of [`to_blob`]).
pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
if !blob.is_teamspeak() {
return Err(IdentityError::Blob(format!(
"the identity is of kind {:?}, not a TeamSpeak one",
blob.kind
)));
}
from_json(&blob.json)
}
/// The TeamSpeak identity in `json`, the text [`to_blob`] writes and the key
/// store keeps; voelin-core reads that text only through here (voelin-store
/// parses it too, for its own checks of a stored row).
///
/// What does not read is refused in words that say how it is wrong
/// (malformed, cut short, not an identity, unreadable) and where (line and
/// column), and never what it holds: the text holds a private key, and the
/// message of the JSON reader quotes a value it refuses (`tsproto` reports a
/// key that does not import as an invalid value, the key string and all), so
/// that message is never shown, not in an error, an event or a log.
pub(crate) fn from_json(json: &str) -> Result<Identity, IdentityError> {
serde_json::from_str(json).map_err(|e| {
let what = match e.classify() {
serde_json::error::Category::Syntax => "malformed",
serde_json::error::Category::Eof => "cut short",
serde_json::error::Category::Data => "not an identity",
serde_json::error::Category::Io => "unreadable",
};
IdentityError::Blob(format!(
"the TeamSpeak identity cannot be read: {what} at line {}, column {}",
e.line(),
e.column()
))
})
}
/// The JSON of a fresh identity whose key lost its last two characters (a key
/// that does not import), and that cut key.
#[cfg(test)]
pub(crate) fn json_with_a_cut_key() -> (String, String) {
let mut json = serde_json::to_value(Identity::create()).unwrap();
let key = json["key"].as_str().unwrap().to_owned();
let cut = key[..key.len() - 2].to_owned();
json["key"] = cut.clone().into();
(json.to_string(), cut)
}
/// Fail if `text` holds any 8 characters in a row of `secret`.
#[cfg(test)]
pub(crate) fn assert_holds_no_piece_of(text: &str, secret: &str) {
assert!(secret.len() >= 8 && secret.is_ascii());
for piece in secret.as_bytes().windows(8) {
let piece = std::str::from_utf8(piece).unwrap();
assert!(!text.contains(piece), "{text:?} holds {piece:?} of the key");
}
}
/// The TeamSpeak 3 `.ini` export of an identity, which the official client
/// and every other tool reads.
pub fn export(nickname: &str, identity: &Identity) -> String {
@@ -548,18 +623,69 @@ mod tests {
Identity::create()
}
/// The blob of an identity is how the key store keeps it, and reads back as
/// the same identity; what is no TeamSpeak identity is refused without
/// quoting its JSON.
#[test]
fn an_identity_goes_through_its_blob() {
let identity = synthetic();
let blob = to_blob(&identity);
assert!(blob.is_teamspeak());
assert_eq!(blob.uid, identity.key().to_pub().get_uid());
assert_eq!(blob.level, identity.level());
assert_eq!(blob.json, serde_json::to_string(&identity).unwrap());
let back = from_blob(&blob).unwrap();
assert_eq!(serde_json::to_value(&back).unwrap(), serde_json::to_value(&identity).unwrap());
// Another kind.
let other = IdentityBlob::new("voelin", "x", 0, blob.json.clone());
let error = from_blob(&other).unwrap_err().to_string();
assert!(error.contains("\"voelin\""), "{error}");
// Not an identity: the text says where, and nothing of what it holds.
for json in ["", "{", r#"{"key":"hunter2-key","counter":"hunter2"}"#, "[1]"] {
let error = from_blob(&IdentityBlob::teamspeak("x", 0, json)).unwrap_err().to_string();
assert!(error.starts_with("the TeamSpeak identity cannot be read"), "{error}");
assert!(!error.contains("hunter2"), "{error}");
}
}
/// The JSON reader's own message quotes a key that does not import, so the
/// refusal is worded by `from_json` and holds none of the key.
#[test]
fn a_key_that_does_not_import_is_refused_without_quoting_it() {
let (json, cut) = json_with_a_cut_key();
let raw = serde_json::from_str::<Identity>(&json).unwrap_err().to_string();
assert!(raw.contains(&cut), "the reader's own message quotes the key: {raw}");
for error in [
from_json(&json).unwrap_err().to_string(),
from_blob(&IdentityBlob::teamspeak("x", 8, json.clone())).unwrap_err().to_string(),
] {
assert!(
error.starts_with(
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
),
"{error}"
);
assert_holds_no_piece_of(&error, &cut);
}
}
#[test]
fn improve_level_keeps_the_key() {
let identity = synthetic();
// A fresh identity stops at the first counter whose level is 8 or more,
// and about one in 32 has 13 or more already, which `improve_level`
// returns as it is: ask for more than this one has, whatever it has.
let target = identity.level() + 3;
let levels = std::sync::Mutex::new(Vec::new());
let better = improve_level(&identity, 13, &AtomicBool::new(false), |l| {
let better = improve_level(&identity, target, &AtomicBool::new(false), |l| {
levels.lock().unwrap().push(l);
})
.unwrap();
assert!(better.level() >= 13);
assert!(better.level() >= target);
assert_eq!(better.key().to_pub().get_uid(), identity.key().to_pub().get_uid());
assert!(better.counter() > identity.counter());
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= 13));
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= target));
// Cancelled: nothing.
assert!(improve_level(&identity, 60, &AtomicBool::new(true), |_| {}).is_none());
// Already there: the same identity.
+30
View File
@@ -0,0 +1,30 @@
//! The TeamSpeak implementation of the session seam.
//!
//! Everything of the engine that is TeamSpeak's lives here, so that it can
//! leave this crate for the TeamSpeak gateway (`voelin-gateway-ts` of
//! VoelinGateWay) as one piece (`docs/session-seam.md`, H9):
//!
//! - `ts_link.rs` and `voice.rs` are the connection of `tsclientlib`
//! (chat, voice, files, pokes, offline messages, the stream task's
//! requests) with `book.rs`, its presence from the library's book;
//! - `ts_session/` makes a `voelin_proto::link::Session` of such a connection
//! ([`TsConnector`] is the `Connector` the engine registers for
//! `ts3server://` and `teamspeak://`);
//! - [`versions`] and [`identity`] are what a TeamSpeak client has to know
//! about itself: the signed compatibility versions it can claim, and the
//! identities (reading, importing from the official clients, the security
//! level).
//!
//! The TeamSpeak crates' types (`tsclientlib::Identity`, `Version`, ...) are
//! named in the public items of this module and nowhere else of the crate's
//! API.
mod book;
pub mod identity;
mod ts_link;
pub(crate) mod ts_session;
pub mod versions;
mod voice;
pub(crate) use ts_link::{ConnectOptions, ServerLink, TsLink};
pub use ts_session::TsConnector;
+256
View File
@@ -0,0 +1,256 @@
//! The inner link of the TeamSpeak side: [`ServerLink`], the trait that
//! [`TsLink`] implements, and the [`ConnectOptions`] it connects with.
//!
//! The engine does not know this vocabulary: it talks to a
//! `voelin_proto::link::Session`. The `ts_session` module makes a `Session`
//! of a [`ServerLink`] (`LinkSession`), and the engine's tests give it a link
//! of their own, an in-memory one. [`TsLink`] connects as a normal TeamSpeak 3
//! or 6 client with `tsclientlib` and
//! runs the connection ([`super::voice`]) with everything that rides on it:
//! chat, voice, files, pokes, offline messages and, on TeamSpeak 6, the
//! stream task. Which product the server is (and what it can do) is decided
//! there, from the version it sends, and reported in
//! [`LinkEvent::Connected`](crate::link::LinkEvent::Connected).
//!
//! Everything it uses (`voice.rs`, `book.rs`, `stream.rs`, `versions.rs`,
//! `identity.rs`) is TeamSpeak's and leaves this crate together with it:
//! the plan moves `TsLink` into the TeamSpeak gateway, `voelin-gateway-ts`
//! of VoelinGateWay.
use std::sync::Arc;
use tokio::sync::{mpsc, watch};
use voelin_stream::PeerConfig;
use super::voice;
use crate::link::{LinkCmd, LinkCtx, LinkEvent};
/// Starts the connection of a link: the contract of `crate::link` for the
/// vocabulary ([`LinkCmd`] in, [`LinkEvent`] out) holds for what a link does
/// with them, and the module documentation of `link/session_link.rs` states
/// it.
///
/// One link serves every session of an engine; [`spawn`](Self::spawn) starts
/// one connection.
pub(crate) trait ServerLink: Send + Sync + 'static {
/// Connect to the server `options` names and run the connection on its
/// own task: take commands from `cmds`, report through `events`, and end
/// the connection with [`LinkEvent::Disconnected`]. Does not block.
fn spawn(
&self,
options: ConnectOptions,
ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
);
}
/// What a TeamSpeak connection needs to know: the server, who to be, where
/// to join. The reverse of what the engine's `ConnectParams` carry
/// (`ts_session::inner_options`).
#[derive(Clone, Debug)]
pub(crate) struct ConnectOptions {
pub address: String,
pub nickname: String,
/// The identity to connect with; none generates one.
pub identity: Option<tsclientlib::Identity>,
/// Signed compatibility version; `None` selects the native platform's tuple.
pub client_version: Option<tsclientlib::Version>,
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
/// The password of `channel`.
pub channel_password: Option<String>,
/// A privilege key to use when connecting.
pub token: Option<String>,
/// Open the audio devices (capture and playback).
pub audio: bool,
/// Network settings for stream peer connections.
pub stream_peer: PeerConfig,
}
impl ConnectOptions {
/// Options for `address` and `nickname`, the rest as a test leaves it.
#[cfg(test)]
pub(crate) fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
Self {
address: address.into(),
nickname: nickname.into(),
identity: None,
client_version: None,
server_password: None,
channel: None,
channel_password: None,
token: None,
audio: false,
stream_peer: PeerConfig::default(),
}
}
}
/// The main myTeamSpeak account of an application, as its connections show
/// it to the servers: the proof of the myTS ID, and what servers are shown
/// of it (its avatar and badges with their certificates, its User Tag).
///
/// The senders live here, one pair for every connection of a [`TsLink`]; each
/// connection watches the pair through [`Watches`], presents the account it
/// finds when it connects, and follows the changes.
pub(crate) struct Account {
identity: watch::Sender<Option<Arc<tsproto::myts::Identity>>>,
data: watch::Sender<Option<Arc<tsclientlib::MytsData>>>,
}
impl Default for Account {
/// No account is signed in.
fn default() -> Self {
Self { identity: watch::Sender::new(None), data: watch::Sender::new(None) }
}
}
impl Account {
/// The account proof for every current and future connection. Still no
/// account is no change: every notification restarts the handshakes and
/// sends `updatemytsid` on every connection. Any account is (each
/// connection's proof is signed anew).
pub(crate) fn set_identity(&self, identity: Option<Arc<tsproto::myts::Identity>>) {
self.identity.send_if_modified(|current| {
if current.is_none() && identity.is_none() {
return false;
}
*current = identity;
true
});
}
/// What the servers are shown of the account: sent to every connection
/// that presents the account's myTS ID, once connected and when it
/// changes; cleared on a sign-out. The same data is no change.
pub(crate) fn set_data(&self, data: Option<Arc<tsclientlib::MytsData>>) {
self.data.send_if_modified(|current| {
if *current == data {
return false;
}
*current = data;
true
});
}
/// What one connection watches. It keeps the senders alive for as long as
/// it runs: a connection ends with "account source closed" when its
/// watches have lost them, so the account outlives the connector that
/// made the connection.
pub(crate) fn watches(self: &Arc<Self>) -> Watches {
Watches {
identity: self.identity.subscribe(),
data: self.data.subscribe(),
_keep: Some(self.clone()),
}
}
}
/// The account a connection presents and follows ([`Account::watches`]).
pub(crate) struct Watches {
pub(super) identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
pub(super) data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
_keep: Option<Arc<Account>>,
}
impl Watches {
/// Watches of senders that someone else keeps (a test's).
#[cfg(test)]
pub(super) fn of(
identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
) -> Self {
Self { identity, data, _keep: None }
}
}
/// Connects to TeamSpeak 3 and 6 servers. The link of [`TsConnector`](super::TsConnector).
#[derive(Clone, Default)]
pub(crate) struct TsLink {
account: Arc<Account>,
}
impl TsLink {
/// A link that presents no account until it is given one.
pub(crate) fn new() -> Self {
Self::default()
}
/// The account the link's connections present.
pub(crate) fn account(&self) -> &Arc<Account> {
&self.account
}
}
impl ServerLink for TsLink {
fn spawn(
&self,
options: ConnectOptions,
ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
) {
tokio::spawn(voice::run(options, ctx, self.account.watches(), cmds, events));
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A myTS ID's proof (the standard Ed25519 base point as the public key).
fn identity() -> Arc<tsproto::myts::Identity> {
let mut private = [0; 32];
private[0] = 1;
let mut public = [0x66; 32];
public[0] = 0x58;
Arc::new(
tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap(),
)
}
/// An account sets what it holds only when it changes: every notification
/// of a watch restarts the handshake of a connection.
#[test]
fn a_watch_hears_of_a_change_and_not_of_the_same_account_again() {
let account = Arc::new(Account::default());
let mut watches = account.watches();
// No account, still none: nothing.
account.set_identity(None);
account.set_data(None);
assert!(!watches.identity.has_changed().unwrap());
assert!(!watches.data.has_changed().unwrap());
let proof = identity();
account.set_identity(Some(proof.clone()));
assert!(watches.identity.borrow_and_update().is_some());
// An account again is a change (each connection signs its proof anew), the
// same data is none.
account.set_identity(Some(proof));
assert!(watches.identity.has_changed().unwrap());
watches.identity.borrow_and_update();
let data = Arc::new(tsclientlib::MytsData::default());
account.set_data(Some(data.clone()));
assert!(watches.data.has_changed().unwrap());
watches.data.borrow_and_update();
account.set_data(Some(Arc::new(tsclientlib::MytsData::default())));
assert!(!watches.data.has_changed().unwrap(), "equal data is no change");
// A sign-out is a change.
account.set_identity(None);
assert!(watches.identity.has_changed().unwrap());
assert!(watches.identity.borrow_and_update().is_none());
}
/// A connection outlives the connector that made it (a session handed out
/// by a connector that was dropped): its watches keep their senders.
#[test]
fn a_connection_keeps_the_account_open_when_its_link_is_gone() {
let link = TsLink::new();
let watches = link.account().watches();
drop(link);
assert!(watches.identity.has_changed().is_ok(), "the identity watch lost its sender");
assert!(watches.data.has_changed().is_ok(), "the data watch lost its sender");
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,537 @@
//! The TeamSpeak connection's presence as v1 entities (protocol section
//! 11.1, "Ids and entities"): the client's older model on one side, the
//! protocol's `Server`, `Channel`, `Role`, `User`, `Member`, `Presence` and
//! `VoiceState` on the other.
//!
//! [`build`] is the translation the TeamSpeak `Session` makes of every
//! snapshot its link reports; the engine's projection (`link/project.rs`)
//! is its reverse, and `docs/session-seam.md` section 5.1 states the rule
//! both keep: projecting what was built gives back the snapshot (up to the
//! normalisations of section 5.4). What v1 has no field for rides in
//! [`Foreign`](v1::Foreign) under [`FOREIGN_SYSTEM`].
use std::collections::{BTreeMap, HashMap, HashSet};
use serde_json::json;
use voelin_model::replica::Key;
use voelin_model::{
BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
HostMessageMode, Presence, ServerDetails,
};
use voelin_proto::v1::{self, Entity, entity::Kind};
use super::ids::{self, FOREIGN_SYSTEM, SERVER_CHAT, SERVER_ID};
/// Entities by key, as a scope holds them.
pub(crate) type Layer = BTreeMap<Key, Entity>;
/// The entities one snapshot stands for, by scope.
#[derive(Debug, Default)]
pub(crate) struct Built {
/// SERVER (1): the server, its channels and its roles.
pub server: Layer,
/// LIVE (1): who is online and where.
pub live: Layer,
/// The own user, for HOME, when the snapshot holds our client.
pub own_user: Option<v1::User>,
/// Clients by unique id: their user id and participant id.
pub by_uid: HashMap<String, (u64, u32)>,
}
/// The `Foreign` of something v1 has no field for.
pub(crate) fn foreign(kind: &str, json: &serde_json::Value) -> v1::Foreign {
v1::Foreign {
system: FOREIGN_SYSTEM.into(),
kind: kind.into(),
json: serde_json::to_vec(json).unwrap_or_default().into(),
}
}
fn entity(kind: Kind) -> Entity {
Entity { kind: Some(kind) }
}
/// A picture known by its id (an icon CRC).
fn icon(id: u32) -> Option<v1::Image> {
(id != 0).then(|| v1::Image { hash: id.to_string(), ..Default::default() })
}
fn banner_mode(mode: BannerMode) -> v1::BannerMode {
match mode {
BannerMode::NoAdjust => v1::BannerMode::NoAdjust,
BannerMode::IgnoreAspect => v1::BannerMode::IgnoreAspect,
BannerMode::KeepAspect => v1::BannerMode::KeepAspect,
}
}
fn host_message_mode(mode: HostMessageMode) -> v1::HostMessageMode {
match mode {
HostMessageMode::None => v1::HostMessageMode::None,
HostMessageMode::Log => v1::HostMessageMode::Log,
HostMessageMode::Modal => v1::HostMessageMode::Modal,
HostMessageMode::ModalQuit => v1::HostMessageMode::ModalQuit,
}
}
/// The `Server` entity of a connection.
pub(crate) fn server(details: &ServerDetails, name: &str, default_channel: u64) -> v1::Server {
let gfx =
|url: &str| (!url.is_empty()).then(|| v1::Image { url: url.into(), ..Default::default() });
let banner = (!details.banner_url.is_empty()
|| !details.banner_gfx_url.is_empty()
|| details.banner_gfx_interval_s != 0
|| details.banner_mode != BannerMode::NoAdjust)
.then(|| v1::Banner {
image: gfx(&details.banner_gfx_url),
link: details.banner_url.clone(),
reload_s: u32::try_from(details.banner_gfx_interval_s).unwrap_or(u32::MAX),
mode: banner_mode(details.banner_mode) as i32,
});
let host_button = (!details.host_button_tooltip.is_empty()
|| !details.host_button_url.is_empty()
|| !details.host_button_gfx_url.is_empty())
.then(|| v1::HostButton {
tooltip: details.host_button_tooltip.clone(),
url: details.host_button_url.clone(),
icon: gfx(&details.host_button_gfx_url),
});
v1::Server {
id: SERVER_ID,
name: name.to_owned(),
icon: icon(details.icon),
banner,
host_button,
welcome: details.welcome_message.clone(),
host_message: details.host_message.clone(),
host_message_mode: host_message_mode(details.host_message_mode) as i32,
default_channel_id: default_channel,
default_role_id: details.default_server_group.unwrap_or(0),
default_channel_role_id: details.default_channel_group.map_or(0, ids::channel_role),
priority_dim_db: details.priority_speaker_dimm_db,
max_members: u32::from(details.max_clients),
uid: details.uid.as_deref().map(|uid| format!("ts:{uid}")).unwrap_or_default(),
foreign: Some(foreign(
"server",
&json!({ "platform": details.platform, "version": details.version }),
)),
..Default::default()
}
}
/// The server group or channel group `info` as a role.
fn role(info: &GroupInfo, channel: bool) -> v1::Role {
v1::Role {
id: if channel { ids::channel_role(info.id) } else { info.id },
server_id: SERVER_ID,
name: info.name.clone(),
icon: icon(info.icon),
position: info.sort_id.saturating_neg(),
scope: if channel { v1::RoleScope::Channel } else { v1::RoleScope::Server } as i32,
name_mode: match info.naming_mode {
GroupNamingMode::None => v1::NameMode::None,
GroupNamingMode::Before => v1::NameMode::Before,
GroupNamingMode::After => v1::NameMode::After,
} as i32,
kind: match info.group_type {
GroupType::Template => v1::RoleKind::Template,
GroupType::Regular => v1::RoleKind::Regular,
GroupType::Query => v1::RoleKind::Query,
} as i32,
..Default::default()
}
}
/// The sibling chain of each parent as positions: `order` names the sibling
/// above, so the chain is followed from 0; siblings that no chain reaches
/// (a snapshot with broken orders) follow by id.
fn positions(channels: &BTreeMap<ChannelId, ChannelInfo>) -> HashMap<ChannelId, i64> {
let mut by_parent: BTreeMap<ChannelId, Vec<&ChannelInfo>> = BTreeMap::new();
for channel in channels.values() {
by_parent.entry(channel.parent).or_default().push(channel);
}
let mut positions = HashMap::new();
for siblings in by_parent.values() {
let mut placed: HashSet<ChannelId> = HashSet::new();
let mut next = 0;
let mut above = 0;
// The sibling whose `order` is the one placed last (lowest id first, so
// that two claiming the same place do not depend on map order).
while let Some(channel) = siblings
.iter()
.filter(|c| c.order == above && !placed.contains(&c.id))
.min_by_key(|c| c.id)
{
positions.insert(channel.id, next * 1024);
placed.insert(channel.id);
above = channel.id;
next += 1;
}
for channel in siblings.iter().filter(|c| !placed.contains(&c.id)) {
positions.insert(channel.id, next * 1024);
next += 1;
}
}
positions
}
fn channel(info: &ChannelInfo, position: i64) -> v1::Channel {
let mut needed = HashMap::new();
if info.needed_talk_power != 0 {
needed.insert(v1::Power::Talk as u32, info.needed_talk_power);
}
if info.needed_subscribe_power != 0 {
needed.insert(v1::Power::Subscribe as u32, info.needed_subscribe_power);
}
let banner =
(info.banner_gfx_url.is_some() || info.banner_mode != BannerMode::NoAdjust).then(|| {
v1::Banner {
image: info
.banner_gfx_url
.as_ref()
.map(|url| v1::Image { url: url.clone(), ..Default::default() }),
mode: banner_mode(info.banner_mode) as i32,
..Default::default()
}
});
v1::Channel {
id: info.id,
server_id: SERVER_ID,
parent_id: info.parent,
kind: v1::ChannelKind::Voice as i32,
name: info.name.clone(),
topic: info.topic.clone().unwrap_or_default(),
position,
has_password: info.has_password,
// A limit of 0 cannot be said with `max_members` (0 is unlimited).
max_members: info.max_clients.map_or(0, |n| u32::try_from(n).unwrap_or(0)),
needed,
icon: icon(info.icon),
banner,
is_default: info.is_default,
foreign: (info.max_clients == Some(0))
.then(|| foreign("channel", &json!({ "max_clients": 0 }))),
..Default::default()
}
}
/// The user a client is. `Foreign` carries a unique id that is no base64.
fn user(client: &ClientInfo, id: u64, ts6: bool) -> v1::User {
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
let bytes = uid.and_then(ids::uid_bytes);
let avatar = (client.avatar.is_some() || client.myts_avatar.is_some()).then(|| v1::Image {
hash: client.avatar.clone().unwrap_or_default(),
url: client.myts_avatar.clone().unwrap_or_default(),
..Default::default()
});
v1::User {
id,
uid: bytes.clone().unwrap_or_default().into(),
uid_kind: if ts6 { v1::IdKind::Ts6 } else { v1::IdKind::Ts3 } as i32,
name: client.nickname.clone(),
avatar,
badges: client.badges.clone(),
country: client.country.clone().unwrap_or_default(),
foreign: uid.filter(|_| bytes.is_none()).map(|uid| foreign("user", &json!({ "uid": uid }))),
..Default::default()
}
}
/// A user who is on no snapshot (the sender of a message or a poke): its
/// unique id and name only. `None` for a unique id with no content.
pub(crate) fn bare_user(uid: &str, name: &str, ts6: bool) -> v1::User {
user(
&ClientInfo { uid: Some(uid.to_owned()), nickname: name.to_owned(), ..Default::default() },
ids::synthetic_user(uid),
ts6,
)
}
/// A user who is on no snapshot and has no unique id (the sender of a poke
/// or a message that the link names by its client id only): `id` and name.
pub(crate) fn client_user(id: u64, name: &str, ts6: bool) -> v1::User {
user(&ClientInfo { nickname: name.to_owned(), ..Default::default() }, id, ts6)
}
/// Everything the snapshot `presence` says, as entities of the scopes of
/// server 1. `ts6`: the server is TeamSpeak 6 (the kind of its unique ids).
pub(crate) fn build(presence: &Presence, ts6: bool, own_client: Option<u16>) -> Built {
let mut built = Built::default();
let name =
if presence.server.name.is_empty() { &presence.server_name } else { &presence.server.name };
let default_channel =
presence.channels.values().find(|c| c.is_default).map_or(0, |channel| channel.id);
let put = |layer: &mut Layer, kind: Kind| {
let entity = entity(kind);
if let Some(key) = Key::of(&entity) {
layer.insert(key, entity);
}
};
put(&mut built.server, Kind::Server(server(&presence.server, name, default_channel)));
put(
&mut built.server,
Kind::Channel(v1::Channel {
id: SERVER_CHAT,
server_id: SERVER_ID,
kind: v1::ChannelKind::ServerChat as i32,
name: "Server chat".into(),
..Default::default()
}),
);
let positions = positions(&presence.channels);
for info in presence.channels.values() {
let position = positions.get(&info.id).copied().unwrap_or_default();
put(&mut built.server, Kind::Channel(channel(info, position)));
}
for info in presence.server_groups.values() {
put(&mut built.server, Kind::Role(role(info, false)));
}
for info in presence.channel_groups.values() {
put(&mut built.server, Kind::Role(role(info, true)));
}
// The own client first, then by client id.
let mut clients: Vec<&ClientInfo> = presence.clients.values().collect();
clients.sort_by_key(|client| (Some(client.id) != own_client, client.id));
let mut used: HashSet<u64> = HashSet::new();
for client in clients {
// The same identity twice on a server has one database id: the own
// client keeps it (it must stay the user we are, also while a ghost of
// our old connection lingers), else the lower client id; the other is a
// user of its own.
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
let mut id = client.database_id.unwrap_or_else(|| {
ids::synthetic_user(&uid.map_or_else(|| format!("client:{}", client.id), str::to_owned))
});
if !used.insert(id) {
id = ids::synthetic_user(&format!("client:{}", client.id));
used.insert(id);
}
let participant = u32::from(client.id);
if let Some(uid) = uid {
built.by_uid.entry(uid.to_owned()).or_insert((id, participant));
}
let user = user(client, id, ts6);
if Some(client.id) == own_client {
built.own_user = Some(user.clone());
}
put(&mut built.live, Kind::User(user));
put(
&mut built.live,
Kind::Member(v1::Member {
server_id: SERVER_ID,
user_id: id,
roles: client.server_groups.clone(),
channel_roles: client
.channel_group
.map(|group| (client.channel, ids::channel_role(group)))
.into_iter()
.collect(),
description: client.description.clone().unwrap_or_default(),
foreign: (client.icon != 0)
.then(|| foreign("client", &json!({ "icon": client.icon }))),
..Default::default()
}),
);
put(
&mut built.live,
Kind::Presence(v1::Presence {
user_id: id,
status: if client.away.is_some() { v1::Status::Idle } else { v1::Status::Online }
as i32,
text: client.away.clone().unwrap_or_default(),
..Default::default()
}),
);
put(
&mut built.live,
Kind::Voice(v1::VoiceState {
server_id: SERVER_ID,
participant_id: participant,
user_id: id,
channel_id: client.channel,
slot: slot(client.id),
nick: client.nickname.clone(),
kind: if client.is_query {
v1::ParticipantKind::Query
} else {
v1::ParticipantKind::User
} as i32,
self_mute: client.input_muted,
self_deaf: client.output_muted,
priority_speaker: client.priority_speaker,
channel_commander: client.channel_commander,
talker: client.talker,
talk_power: client.talk_power,
recording: client.recording,
streaming: client.streaming.unwrap_or(false),
..Default::default()
}),
);
}
built
}
/// The unique id of a user as the client's older model writes it: base64 for
/// a TeamSpeak id, or the text kept in `Foreign` when it was no base64 (a
/// ServerQuery client's login name). `None` for a user without one.
pub(crate) fn user_uid(user: &v1::User) -> Option<String> {
let kept = user
.foreign
.as_ref()
.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == "user")
.and_then(|f| serde_json::from_slice::<serde_json::Value>(&f.json).ok())
.and_then(|json| json.get("uid")?.as_str().map(str::to_owned));
kept.or_else(|| voelin_model::replica::convert::uid_text(user))
}
/// The media slot of a client: its id plus one (slot 0 is not a media source).
pub(crate) fn slot(client: u16) -> u32 {
u32::from(client) + 1
}
/// The key of an entity, as a `Change` deletes it: the key fields only.
pub(crate) fn key_only(entity: &Entity) -> Entity {
let kind = match entity.kind.as_ref() {
Some(Kind::Server(s)) => Kind::Server(v1::Server { id: s.id, ..Default::default() }),
Some(Kind::Channel(c)) => Kind::Channel(v1::Channel { id: c.id, ..Default::default() }),
Some(Kind::Role(r)) => {
Kind::Role(v1::Role { server_id: r.server_id, id: r.id, ..Default::default() })
}
Some(Kind::Member(m)) => Kind::Member(v1::Member {
server_id: m.server_id,
user_id: m.user_id,
..Default::default()
}),
Some(Kind::User(u)) => Kind::User(v1::User { id: u.id, ..Default::default() }),
Some(Kind::Presence(p)) => {
Kind::Presence(v1::Presence { user_id: p.user_id, ..Default::default() })
}
Some(Kind::Voice(v)) => Kind::Voice(v1::VoiceState {
server_id: v.server_id,
participant_id: v.participant_id,
..Default::default()
}),
Some(Kind::Message(m)) => {
Kind::Message(v1::Message { channel_id: m.channel_id, id: m.id, ..Default::default() })
}
Some(Kind::Mail(m)) => Kind::Mail(v1::Mail { id: m.id, ..Default::default() }),
_ => return entity.clone(),
};
Entity { kind: Some(kind) }
}
/// What changed from `old` to `new`: the entities to put (new or different)
/// and the keys to delete.
pub(crate) fn diff(old: &Layer, new: &Layer) -> (Vec<Entity>, Vec<Entity>) {
let put = new.iter().filter(|(key, entity)| old.get(*key) != Some(*entity));
let del = old.iter().filter(|(key, _)| !new.contains_key(*key));
(put.map(|(_, e)| e.clone()).collect(), del.map(|(_, e)| key_only(e)).collect())
}
#[cfg(test)]
mod tests {
use super::*;
fn channel_info(id: u64, parent: u64, order: u64) -> ChannelInfo {
ChannelInfo { id, parent, order, name: format!("c{id}"), ..Default::default() }
}
#[test]
fn the_order_chain_becomes_positions() {
// 3 first, then 1, then 2 under the same parent; 5 alone under 3.
let channels: BTreeMap<_, _> = [
channel_info(1, 0, 3),
channel_info(2, 0, 1),
channel_info(3, 0, 0),
channel_info(5, 3, 0),
]
.into_iter()
.map(|c| (c.id, c))
.collect();
let positions = positions(&channels);
assert!(positions[&3] < positions[&1] && positions[&1] < positions[&2]);
assert_eq!(positions[&5], 0);
}
#[test]
fn siblings_a_chain_does_not_reach_follow_by_id() {
// Both claim the first place, and 4 follows nobody.
let channels: BTreeMap<_, _> =
[channel_info(1, 0, 0), channel_info(2, 0, 0), channel_info(4, 0, 77)]
.into_iter()
.map(|c| (c.id, c))
.collect();
let positions = positions(&channels);
assert_eq!((positions[&1], positions[&2], positions[&4]), (0, 1024, 2048));
}
#[test]
fn the_same_identity_twice_keeps_both_clients() {
let client = |id, db| ClientInfo {
id,
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
nickname: format!("n{id}"),
database_id: Some(db),
..Default::default()
};
let mut presence = Presence::default();
for c in [client(3, 77), client(4, 77)] {
presence.clients.insert(c.id, c);
}
let built = build(&presence, false, None);
let voices = built.live.keys().filter(|k| matches!(k, Key::Voice { .. })).count();
let users = built.live.keys().filter(|k| matches!(k, Key::User { .. })).count();
assert_eq!((voices, users), (2, 2));
}
/// The own client is the user whose database id the identity has, also when a
/// ghost of the old connection (the lower client id) lingers.
#[test]
fn the_own_client_keeps_the_database_id_of_an_identity_that_is_there_twice() {
let client = |id| ClientInfo {
id,
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
nickname: format!("n{id}"),
database_id: Some(77),
..Default::default()
};
let mut presence = Presence::default();
for c in [client(3), client(4)] {
presence.clients.insert(c.id, c);
}
let user_of = |built: &Built, client: u32| {
let key = Key::Voice { server_id: SERVER_ID, participant_id: client };
let Some(Entity { kind: Some(Kind::Voice(voice)) }) = built.live.get(&key) else {
panic!("no voice state")
};
voice.user_id
};
// Nobody is us: the lower client id keeps it.
let built = build(&presence, false, None);
assert_eq!(user_of(&built, 3), 77);
assert_ne!(user_of(&built, 4), 77);
// The later client is us: it keeps it, and the ghost has the made-up id.
let built = build(&presence, false, Some(4));
assert_eq!(user_of(&built, 4), 77);
assert_ne!(user_of(&built, 3), 77);
assert_eq!(built.own_user.map(|u| u.id), Some(77));
assert_eq!(built.by_uid["uXDkxSZbv0IoA0z/toW3guGpUbI="], (77, 4));
}
#[test]
fn a_change_deletes_by_key_and_puts_what_differs() {
let mut presence = Presence::default();
presence.channels.insert(1, channel_info(1, 0, 0));
let before = build(&presence, false, None);
presence.channels.insert(2, channel_info(2, 0, 1));
presence.channels.get_mut(&1).unwrap().name = "renamed".into();
let after = build(&presence, false, None);
let (put, del) = diff(&before.server, &after.server);
assert_eq!(put.len(), 2, "the renamed channel and the new one");
assert!(del.is_empty());
let (put, del) = diff(&after.server, &before.server);
assert_eq!(put.len(), 1, "channel 1 is back to its old name");
assert_eq!(del.len(), 1);
let Some(Kind::Channel(gone)) = &del[0].kind else { panic!("a channel") };
assert_eq!((gone.id, gone.name.as_str()), (2, ""));
}
}
+115
View File
@@ -0,0 +1,115 @@
//! Ids and unique ids as the TeamSpeak gateway writes them (protocol
//! section 11.1, "Ids"): TeamSpeak's numbers as they are, and a few
//! synthetic ones with bit 63 set.
//!
//! Both sides of the seam use these rules: the TeamSpeak `Session`
//! ([`super::LinkSession`]) writes entities with them, and the engine's
//! projection (`link/project.rs`) undoes the few that the client's older
//! model has no room for.
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
/// The only server of a TeamSpeak connection (its virtual server).
pub(crate) const SERVER_ID: u64 = 1;
/// Marks the ids the gateway makes up: the server chat, direct-message
/// channels and users it knows by their unique id only.
pub(crate) const SYNTHETIC: u64 = 1 << 63;
/// The channel of the server chat, in the SERVER scope.
pub(crate) const SERVER_CHAT: u64 = SYNTHETIC;
/// Set on the id of a channel group, so that a role id does not mean a server
/// group and a channel group at once.
pub(crate) const CHANNEL_ROLE: u64 = 1 << 62;
/// The `Foreign.system` of what the protocol has no field for.
pub(crate) const FOREIGN_SYSTEM: &str = "teamspeak";
/// The role id of a channel group.
pub(crate) fn channel_role(group: u64) -> u64 {
group | CHANNEL_ROLE
}
/// The channel group a role id stands for (the reverse of [`channel_role`]).
pub(crate) fn channel_group(role: u64) -> u64 {
role & !CHANNEL_ROLE
}
/// FNV-1a, 64 bits.
fn fnv1a(bytes: &[u8]) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in bytes {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
hash
}
/// A synthetic id for something known by a name only: bit 63 set and the
/// hash of `name` in the low 63 bits (1 if they come out 0, so it is never
/// [`SERVER_CHAT`]).
fn synthetic(name: &str) -> u64 {
let low = fnv1a(name.as_bytes()) & !SYNTHETIC;
SYNTHETIC | low.max(1)
}
/// The direct-message channel with the client of this unique id.
pub(crate) fn dm_channel(uid: &str) -> u64 {
synthetic(uid)
}
/// The user id of a client that has no database id (or that the snapshot
/// does not hold): by unique id, else by whatever names it.
pub(crate) fn synthetic_user(uid: &str) -> u64 {
synthetic(uid)
}
/// The bytes of a unique id, when it is canonical base64 (what TeamSpeak
/// writes): decoding and encoding again gives the same text. A ServerQuery
/// client's login name, or anything else, is not, and goes into
/// [`Foreign`](voelin_proto::v1::Foreign) instead.
pub(crate) fn uid_bytes(uid: &str) -> Option<Vec<u8>> {
let bytes = STANDARD.decode(uid).ok()?;
(STANDARD.encode(&bytes) == uid && !bytes.is_empty()).then_some(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn channel_groups_keep_their_number_below_the_flag() {
assert_eq!(channel_role(8), 8 | (1 << 62));
assert_eq!(channel_group(channel_role(8)), 8);
assert_eq!(channel_group(channel_role(0)), 0);
}
#[test]
fn synthetic_ids_have_bit_63_and_are_never_the_server_chat() {
for name in ["", "alice=", "client:7", "a-very-long-name-that-hashes-to-something"] {
let id = dm_channel(name);
assert_ne!(id & SYNTHETIC, 0, "{name}");
assert_ne!(id, SERVER_CHAT, "{name}");
}
assert_eq!(dm_channel("alice="), dm_channel("alice="));
assert_ne!(dm_channel("alice="), dm_channel("bob="));
}
#[test]
fn only_canonical_base64_is_a_unique_id() {
// A TeamSpeak 3 unique id (SHA-1) and a TeamSpeak 6 one (SHA-256).
assert_eq!(uid_bytes("uXDkxSZbv0IoA0z/toW3guGpUbI=").map(|b| b.len()), Some(20));
assert_eq!(
uid_bytes("xEZDkyeGdZ4bOSBCKqzTw8jVz2jsZCrJDRl9F8WWd3M=").map(|b| b.len()),
Some(32)
);
// A ServerQuery login name, a fixture's name, the empty string.
for not in ["serveradmin", "alice=", "me=", "", "Af4"] {
assert_eq!(uid_bytes(not), None, "{not:?}");
}
// Non-canonical trailing bits decode but do not round trip.
assert_eq!(uid_bytes("Af5="), None);
}
}
@@ -0,0 +1,862 @@
//! The TeamSpeak `Session` against the development servers
//! (`dev/docker-compose.yml`; `docs/session-seam.md` sections 9.3 and 16).
//! Runs only with `VOELIN_LIVE=1`:
//!
//! ```text
//! VOELIN_LIVE=1 cargo test -p voelin-core --lib ts_session::live_tests -- --test-threads=1
//! ```
//!
//! Two kinds of test, each on TeamSpeak 3 and on TeamSpeak 6:
//!
//! - the link conformance suite of the protocol repository, the cases that
//! apply to a TeamSpeak session, with the verdict of every case asserted
//! and the reason of every case that cannot pass or cannot run in
//! [`EXPECTED`];
//! - what the suite cannot reach, as a session of its own does it: a message
//! in the own channel answered, then pushed to the other session and back to
//! ours, the refusals of a move, a poke between two sessions, voice RTP from
//! one session's slot to the other's media sink, and a channel file written
//! and read back from an offset.
//!
//! The sessions are made by [`TsConnector`] through the plain `Connector`
//! interface, as a client of the seam outside an engine would make them.
//!
//! The servers ban an address that connects as often as these tests do
//! (`ConnectFailedBanned` after three or four connections) unless their
//! anti-flood limits are raised first. `scripts/it-smoke.sh` raises them when it
//! prepares its admin identity; this module raises them itself, once per server
//! and run, through the ServerQuery admin login that `refused_moves` uses
//! ([`raise_flood_limits`]), so that the command above works on a freshly
//! started stack. It needs that login (the development servers of
//! `dev/docker-compose.yml` have it) and does not lower the limits again.
use std::collections::BTreeMap;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::mpsc;
use voelin_proto::link::{Connector, FlowId, MediaClass, MediaPacket, voice_sub};
use voelin_proto::media::payload::PT_OPUS;
use voelin_proto::media::{RtpHeader, RtpView};
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
use voelin_proto::test_util::{FakeConnector, MediaReceiver, media_channel};
use voelin_proto::v1::request::Op;
use voelin_proto::v1::{self, entity::Kind};
use super::*;
use crate::link::{Backends, VoiceOptions, connect_params};
fn live() -> bool {
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
}
/// How long a test waits for the server.
const WAIT: Duration = Duration::from_secs(20);
async fn within<T>(what: &str, future: impl Future<Output = T>) -> T {
match tokio::time::timeout(WAIT, future).await {
Ok(value) => value,
Err(_) => panic!("timed out after {WAIT:?} waiting for {what}"),
}
}
/// A development server: where to connect, and how to ask it as the admin.
#[derive(Clone, Copy)]
struct Dev {
name: &'static str,
voice: &'static str,
ssh: bool,
query: &'static str,
}
const TS3: Dev = Dev { name: "ts3", voice: "127.0.0.1:9987", ssh: false, query: "127.0.0.1:10011" };
const TS6: Dev = Dev { name: "ts6", voice: "127.0.0.1:9988", ssh: true, query: "127.0.0.1:10022" };
impl Dev {
fn query(&self) -> voelin_query::Connect {
voelin_query::Connect {
transport: if self.ssh {
voelin_query::Transport::Ssh
} else {
voelin_query::Transport::Raw
},
addr: self.query.into(),
user: "serveradmin".into(),
secret: Some("voelin-dev-admin".into()),
server_port: Some(9987),
server_id: None,
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
}
}
/// A nickname no other client of this run has.
fn nick(&self, role: &str) -> String {
static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let n = COUNT.fetch_add(1, Ordering::Relaxed);
format!("{role}-{}-{n}", std::process::id() % 10_000)
}
}
/// Raise the anti-flood limits of a development server, once per run, and
/// lift the bans an earlier run left behind. The tests connect many times in
/// a few seconds from one address, which a server with its default limits
/// bans (`ConnectFailedBanned`); `scripts/it-smoke.sh` sets the same two
/// values in `admin_args`. Done through the ServerQuery login of the admin,
/// which the tests that create channels and keys use as well.
async fn raise_flood_limits(dev: &Dev) {
use tokio::sync::OnceCell;
use voelin_query::{Command as Query, QueryClient};
static TS3_READY: OnceCell<()> = OnceCell::const_new();
static TS6_READY: OnceCell<()> = OnceCell::const_new();
let ready = if dev.ssh { &TS6_READY } else { &TS3_READY };
ready
.get_or_init(|| async {
let (admin, _) = within("the query login", QueryClient::connect(&dev.query()))
.await
.unwrap_or_else(|e| panic!("the query login of {}: {e}", dev.name));
for key in [
"virtualserver_antiflood_points_needed_ip_block",
"virtualserver_antiflood_points_needed_command_block",
] {
let edit = Query::new("serveredit").arg(key, 100_000);
within("the anti-flood limits", admin.send(&edit))
.await
.unwrap_or_else(|e| panic!("{} refused {key}: {e}", dev.name));
}
// A ban of an earlier run outlives the change of the limit.
within("the ban list", admin.send(&Query::new("bandelall")))
.await
.unwrap_or_else(|e| panic!("{} did not lift its bans: {e}", dev.name));
})
.await;
}
/// A TeamSpeak session as a client of the seam sees it: made by the
/// connector, with its push channel and media sink.
async fn session(
dev: &Dev,
options: &VoiceOptions,
) -> (Arc<dyn Session>, mpsc::Receiver<v1::Push>, MediaReceiver) {
raise_flood_limits(dev).await;
let (sink, media) = media_channel();
let params = connect_params(options, sink, &Backends::empty()).expect("connect parameters");
let connected =
within(&format!("a connection to {}", dev.name), TsConnector::new().connect(params))
.await
.unwrap_or_else(|e| panic!("{} did not connect: {e}", dev.name));
(connected.session, connected.pushes, media)
}
/// A client of the TeamSpeak session that has done what an engine does after
/// it connects (`docs/session-seam.md` 4.2, without the replica): the server
/// listed, HOME, SERVER and LIVE subscribed and synced, a seat in voice.
struct Client {
session: Arc<dyn Session>,
pushes: mpsc::Receiver<v1::Push>,
media: MediaReceiver,
server: u64,
default_channel: u64,
/// Our seat in voice (participant, slot, channel).
seat: v1::VoiceState,
/// The voice states of the server, as the pushes told them.
voices: BTreeMap<u32, v1::VoiceState>,
}
fn scope(kind: v1::ScopeKind, id: u64) -> v1::Scope {
v1::Scope { kind: kind as i32, id }
}
impl Client {
async fn connect(dev: &Dev, nick: &str) -> Self {
Self::connect_with(dev, VoiceOptions::new(dev.voice, nick)).await
}
async fn connect_with(dev: &Dev, options: VoiceOptions) -> Self {
let (session, pushes, media) = session(dev, &options).await;
let mut client = Self {
session,
pushes,
media,
server: 0,
default_channel: 0,
seat: v1::VoiceState::default(),
voices: BTreeMap::new(),
};
let list = Op::List(v1::List { kind: v1::EntityKind::Server as i32, ..Default::default() });
let Answer::Entities(servers) = client.ask(list).await.expect("the server list") else {
panic!("the server list is not entities")
};
let server = servers
.items
.iter()
.find_map(|e| match &e.kind {
Some(Kind::Server(server)) => Some(server.clone()),
_ => None,
})
.expect("the host lists its server");
client.server = server.id;
client.default_channel = server.default_channel_id;
for scope in [
scope(v1::ScopeKind::Home, 0),
scope(v1::ScopeKind::Server, server.id),
scope(v1::ScopeKind::Live, server.id),
] {
client.subscribe(scope).await;
}
client.seat = client.join(client.default_channel, "").await.expect("a seat in voice");
client.settle().await;
client
}
/// A request, answered within [`WAIT`].
async fn ask(&self, op: Op) -> Result<Answer, SessionError> {
within("an answer", self.session.request(op)).await
}
/// Subscribe `scope` and take its sync off the push channel.
async fn subscribe(&mut self, scope: v1::Scope) {
let op = Op::Subscribe(v1::Subscribe { scope: Some(scope), ..Default::default() });
self.ask(op).await.expect("a subscription");
self.until("the end of the sync", |push| match &push.body {
Some(v1::push::Body::SyncEnd(end)) if end.scope == Some(scope) => Some(()),
_ => None,
})
.await;
}
/// `JoinVoice`: our seat, or why not.
async fn join(&self, channel: u64, password: &str) -> Result<v1::VoiceState, SessionError> {
let join = v1::JoinVoice {
server_id: self.server,
channel_id: channel,
password: password.into(),
..Default::default()
};
match self.ask(Op::JoinVoice(join)).await? {
Answer::Entities(entities) => entities
.items
.into_iter()
.find_map(|e| match e.kind {
Some(Kind::Voice(voice)) => Some(voice),
_ => None,
})
.ok_or_else(|| SessionError::Protocol("no voice state in the answer".into())),
other => Err(SessionError::Protocol(format!("unexpected answer {other:?}"))),
}
}
/// Keep track of what a push says about the server and its voice states.
fn absorb(&mut self, push: &v1::Push) {
let Some(v1::push::Body::Change(change)) = &push.body else { return };
for entity in &change.put {
match &entity.kind {
Some(Kind::Voice(voice)) => {
self.voices.insert(voice.participant_id, voice.clone());
}
Some(Kind::Server(server)) if server.default_channel_id != 0 => {
self.default_channel = server.default_channel_id;
}
_ => {}
}
}
for entity in &change.del {
if let Some(Kind::Voice(voice)) = &entity.kind {
self.voices.remove(&voice.participant_id);
}
}
}
/// The next push `f` picks, skipping (and keeping track of) the others.
async fn until<T>(&mut self, what: &str, mut f: impl FnMut(&v1::Push) -> Option<T>) -> T {
within(what, async {
loop {
let push = self.pushes.recv().await.expect("the session lives");
self.absorb(&push);
if let Some(t) = f(&push) {
return t;
}
}
})
.await
}
/// Wait until the host shows our seat in LIVE: the first snapshot of the
/// TeamSpeak link may come after the session was handed out, so the syncs
/// can be empty and the voice states follow as changes. The seat then
/// names the channel we are in.
async fn settle(&mut self) {
let participant = self.seat.participant_id;
within("our voice state to appear", async {
while !self.voices.contains_key(&participant) {
let push = self.pushes.recv().await.expect("the session lives");
self.absorb(&push);
}
})
.await;
self.seat = self.voices[&participant].clone();
}
/// The next message `Change` of the CHAT scope of `channel` with `text`.
async fn message(&mut self, channel: u64, text: &str) -> v1::Message {
let chat = Some(scope(v1::ScopeKind::Chat, channel));
self.until(&format!("the message {text:?}"), |push| match &push.body {
Some(v1::push::Body::Change(change)) if change.scope == chat => {
change.put.iter().find_map(|e| match &e.kind {
Some(Kind::Message(message)) if message.text == text => Some(message.clone()),
_ => None,
})
}
_ => None,
})
.await
}
async fn close(self) {
self.session.close(v1::CloseCode::Normal, "");
within("the session to close", self.session.closed()).await;
}
}
// ---- the conformance suite ----------------------------------------------------
/// What a case is expected to do against a TeamSpeak session, and why.
enum Expect {
/// Every assertion of the case holds.
Passes,
/// The session lacks the feature the case needs (`Verdict::Skipped`).
Skipped(&'static str),
/// The case does not apply: it cannot run, or cannot pass, for this reason
/// (`cases_that_do_not_apply_fail` runs them and watches them fail).
NotRun(&'static str),
}
use Expect::{NotRun, Passes, Skipped};
/// Every case of the suite of the protocol repository at `v0.2.0`, in its
/// order, with what a TeamSpeak session does with it. A case the suite gains
/// fails `the_suite_is_known` until it is listed here.
///
/// The suite is written for a backend that is a `FakeHost`. A case that needs
/// the backend gets the `FakeHandle` of an unrelated fake host, so the cases
/// that hold, kill or read it, or push into it, cannot run against a session of
/// a TeamSpeak server; the others write to places a TeamSpeak server does not
/// have (the suite's channels, a server with another id, `ScheduledEvent`,
/// `Emoji`, attachments). Each reason is what the case did when it was run.
const EXPECTED: [(&str, Expect); 17] = [
("welcome_matches_features", Passes),
(
"subscribe_syncs_the_scope",
NotRun("writes to channel 4001: rejected (NotFound) no such channel"),
),
(
"subscribe_resumes_from_a_cursor",
NotRun("writes to channel 4002: rejected (NotFound) no such channel"),
),
(
"put_answers_entities_and_pushes_the_change_with_the_same_rev",
NotRun("writes to channel 4003: rejected (NotFound) no such channel"),
),
(
"delete_answers_an_ack_and_pushes_the_removal",
NotRun(
"writes to channel 4004 first (no such channel); and TeamSpeak cannot delete a message, \
where the case needs only `chat`, not `chat.delete` (P8)",
),
),
(
"a_key_names_an_entity_without_its_server",
NotRun(
"rejected (NotFound) no such server; and it creates a ScheduledEvent and an Emoji, \
which TeamSpeak lacks, though it needs no feature (P8)",
),
),
("a_stale_rev_conflicts_and_a_patch_writes_only_its_paths", Skipped("chat.edit")),
("requests_apply_in_the_order_they_were_issued", Skipped("chat.edit")),
("list_pages_history", Skipped("chat.history")),
(
"cancel_before_apply_is_cancelled",
NotRun("holds the unrelated fake host, so the request is answered while it \"holds\""),
),
("idempotency_keys_apply_a_put_once", Skipped("idempotency")),
(
"notifications_are_fire_and_forget",
NotRun("reads the request log of the unrelated fake host: the notification never arrives"),
),
(
"renew_account_follows_the_feature",
NotRun("pushes a HostUpdate into the unrelated fake session's closed push channel"),
),
(
"media_loops_back",
NotRun(
"a TeamSpeak server does not return a client's own voice: the packet never loops back",
),
),
(
"files_round_trip",
NotRun(
"writes an AttachmentSlot: rejected (Unsupported) attachments are not offered; \
TeamSpeak has channel files, and the case needs `files`, not `chat.attachments` (P8)",
),
),
("close_ends_the_session", Passes),
(
"the_backend_can_end_the_session",
NotRun(
"kills the unrelated fake session, so closed() of this one never resolves; and a \
kick is Network(text), not Remote{KICKED}, until H1",
),
),
];
/// A fixture on a TeamSpeak session. The suite wants a `FakeHandle` on the
/// backend behind the session; a TeamSpeak server has none, so it gets the one
/// of an unrelated fake host, which the cases that are run never touch.
async fn fixture(dev: Dev) -> Fixture {
let (session, pushes, media) =
session(&dev, &VoiceOptions::new(dev.voice, dev.nick("conf"))).await;
let unrelated = FakeConnector::new();
let (params, _media) = voelin_proto::test_util::connect_params("fake://unrelated");
unrelated.connect(params).await.expect("a fake session");
let backend = unrelated.last_session().expect("a fake session");
Fixture::new(session, pushes, media, backend)
}
fn the_suite_is_known() {
let known: Vec<_> = EXPECTED.iter().map(|(name, _)| *name).collect();
let cases: Vec<_> = conformance::CASES.iter().map(|case| case.name).collect();
assert_eq!(known, cases, "the suite changed: list the new cases in EXPECTED");
}
/// The cases that apply run and pass, the ones that need a feature the session
/// lacks are skipped, and the rest are not run (their reason is in
/// [`EXPECTED`]).
async fn conformance_subset(dev: Dev) {
the_suite_is_known();
let harness = move || fixture(dev);
let (mut passed, mut skipped) = (0, 0);
for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) {
match expect {
Passes => {
let verdict = conformance::run_case(&harness, case).await;
assert_eq!(verdict, Verdict::Passed, "{name} on {}", dev.name);
passed += 1;
}
Skipped(feature) => {
let verdict = conformance::run_case(&harness, case).await;
assert_eq!(verdict, Verdict::Skipped(feature), "{name} on {}", dev.name);
skipped += 1;
}
NotRun(reason) => eprintln!("{} {name}: not run: {reason}", dev.name),
}
}
assert_eq!((passed, skipped), (2, 4));
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_conformance_subset() {
if live() {
conformance_subset(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_conformance_subset() {
if live() {
conformance_subset(TS6).await;
}
}
// ---- what the suite cannot reach ----------------------------------------------
/// A message in the own channel is answered with the message as written, and
/// pushed to the CHAT scope of every session in the channel: to the other one
/// as a `Change`, and back to ours (the ids agree only with the native
/// session of H1: the answer has a local id, the echo the one of the
/// `Change`).
async fn chat_in_the_own_channel(dev: Dev) {
let mut a = Client::connect(&dev, &dev.nick("chat-a")).await;
let mut b = Client::connect(&dev, &dev.nick("chat-b")).await;
assert_eq!(a.seat.channel_id, b.seat.channel_id, "both sessions are in the default channel");
let channel = a.seat.channel_id;
a.subscribe(scope(v1::ScopeKind::Chat, channel)).await;
b.subscribe(scope(v1::ScopeKind::Chat, channel)).await;
let text = format!("live-chat-{}", std::process::id());
let message = v1::Message { channel_id: channel, text: text.clone(), ..Default::default() };
let write = v1::Write {
entity: Some(v1::Entity { kind: Some(Kind::Message(message)) }),
paths: Vec::new(),
};
let put = Op::Put(v1::Put { writes: vec![write], ..Default::default() });
let Answer::Entities(answer) = a.ask(put).await.expect("the message is accepted") else {
panic!("a message is answered with entities")
};
let written = match &answer.items[..] {
[v1::Entity { kind: Some(Kind::Message(message)) }] => message.clone(),
other => panic!("one message expected, got {other:?}"),
};
assert_eq!((written.channel_id, written.text.as_str()), (channel, text.as_str()));
let heard = b.message(channel, &text).await;
assert_ne!(heard.id, 0);
assert_eq!(heard.channel_id, channel);
// And ours, back from the server: the same words, once.
let echo = a.message(channel, &text).await;
assert_ne!(echo.id, 0);
a.close().await;
b.close().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_chat_in_the_own_channel() {
if live() {
chat_in_the_own_channel(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_chat_in_the_own_channel() {
if live() {
chat_in_the_own_channel(TS6).await;
}
}
/// A move into a channel with a password or without room is refused with the
/// code the seam names: `PASSWORD` and `FULL`.
async fn refused_moves(dev: Dev) {
use voelin_query::{Command as Query, QueryClient};
let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login");
let tag = std::process::id() % 10_000;
let create = |name: &str| {
Query::new("channelcreate")
.arg("channel_name", format!("{name}-{tag}"))
.arg("channel_flag_semi_permanent", 1)
};
let locked =
admin.send(&create("seam-locked").arg("channel_password", "secret")).await.unwrap()[0]
.parse::<u64>("cid")
.unwrap();
let full = create("seam-full")
.arg("channel_maxclients", 0)
.arg("channel_flag_maxclients_unlimited", 0);
let full = admin.send(&full).await.unwrap()[0].parse::<u64>("cid").unwrap();
// A key for the Normal group, which has to keep to passwords and limits.
let token = group_token(&admin, "Normal").await;
let check = {
let token = token.clone();
tokio::spawn(async move {
let mut options = VoiceOptions::new(dev.voice, dev.nick("moves"));
options.token = Some(token);
let client = Client::connect_with(&dev, options).await;
let code = |result: Result<v1::VoiceState, SessionError>| match result {
Err(SessionError::Rejected(error)) => error.code(),
other => panic!("expected a refusal, got {other:?}"),
};
assert_eq!(code(client.join(locked, "").await), v1::ErrorCode::Password);
assert_eq!(code(client.join(locked, "wrong").await), v1::ErrorCode::Password);
let seat = client.join(locked, "secret").await.expect("the right password");
assert_eq!(seat.channel_id, locked);
assert_eq!(code(client.join(full, "").await), v1::ErrorCode::Full);
client.close().await;
})
};
let result = check.await;
// Clean up before reporting a failure; the key is gone once used.
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
for cid in [locked, full] {
admin.send(&Query::new("channeldelete").arg("cid", cid).arg("force", 1)).await.unwrap();
}
if let Err(error) = result {
std::panic::resume_unwind(error.into_panic());
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_refused_moves() {
if live() {
refused_moves(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_refused_moves() {
if live() {
refused_moves(TS6).await;
}
}
/// A poke is a `Signal` to a participant: the other session gets it, with
/// the participant and the words of the sender.
async fn poke_between_sessions(dev: Dev) {
let a = Client::connect(&dev, &dev.nick("poke-a")).await;
let mut b = Client::connect(&dev, &dev.nick("poke-b")).await;
let text = format!("live-poke-{}", std::process::id());
let target = v1::SignalTarget {
server_id: a.server,
participant_id: b.seat.participant_id,
..Default::default()
};
let signal = v1::Signal {
to: Some(target),
body: Some(v1::signal::Body::Poke(v1::Poke { message: text.clone() })),
..Default::default()
};
a.ask(Op::Signal(signal)).await.expect("the poke is accepted");
let from = b
.until("the poke", |push| match &push.body {
Some(v1::push::Body::Signal(signal)) => match &signal.body {
Some(v1::signal::Body::Poke(poke)) if poke.message == text => {
Some(signal.from_participant)
}
_ => None,
},
_ => None,
})
.await;
assert_eq!(from, a.seat.participant_id);
a.close().await;
b.close().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_poke_between_sessions() {
if live() {
poke_between_sessions(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_poke_between_sessions() {
if live() {
poke_between_sessions(TS6).await;
}
}
/// One frame of Opus (20 ms, mono, fullband).
const OPUS: [u8; 3] = [0xf8, 0xff, 0xfe];
fn rtp(flow: FlowId, sequence: u16, marker: bool, payload: &[u8]) -> MediaPacket {
let mut header = RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960);
header.marker = marker;
let mut out = bytes::BytesMut::new();
header.write(flow, &mut out).expect("a header");
out.extend_from_slice(payload);
MediaPacket { flow, rtp: out.freeze() }
}
/// Voice sent on our slot arrives on the sender's slot at the other session's
/// media sink: the frames in order (the sequence is TeamSpeak's packet id, so
/// it only has to count up), the marker on the first, and an empty payload at
/// the end.
async fn voice_between_sessions(dev: Dev) {
let a = Client::connect(&dev, &dev.nick("voice-a")).await;
let mut b = Client::connect(&dev, &dev.nick("voice-b")).await;
assert_eq!(a.seat.channel_id, b.seat.channel_id);
let flow = FlowId::new(a.seat.slot, voice_sub::CHANNEL);
for n in 0..5u8 {
let frame = [0xf8, 0xff, 0xfe, n];
let packet = rtp(flow, u16::from(n), n == 0, &frame);
a.session.send_media(MediaClass::Voice, packet).expect("our own slot");
tokio::time::sleep(Duration::from_millis(20)).await;
}
a.session.send_media(MediaClass::Voice, rtp(flow, 5, false, &[])).expect("the end");
let mut heard = Vec::new();
while let Some(packet) = b.media.recv_within(Duration::from_secs(5)).await {
let view = RtpView::parse(&packet.rtp).expect("RTP");
heard.push((packet.flow, view.sequence(), view.marker(), view.payload().to_vec()));
if view.payload().is_empty() {
break;
}
}
assert!(heard.len() >= 2, "{heard:?}");
assert!(heard.iter().all(|(heard_flow, ..)| *heard_flow == flow), "{heard:?}");
let (_, _, first_marker, first_payload) = &heard[0];
assert!(*first_marker, "the first packet of the spurt carries the marker: {heard:?}");
assert_eq!(&first_payload[..3], &OPUS[..], "{heard:?}");
let (end_flow, _, end_marker, end_payload) = heard.last().expect("an end");
assert!(
end_payload.is_empty() && !*end_marker,
"the spurt ends with an empty payload: {heard:?}"
);
assert_eq!(*end_flow, flow);
let sequences: Vec<_> = heard.iter().map(|(_, sequence, ..)| *sequence).collect();
assert!(
sequences.windows(2).all(|pair| pair[1] == pair[0].wrapping_add(1)),
"the sequence counts up by one: {sequences:?}"
);
// Voice on a slot that is not ours is refused before it reaches the server.
let other = FlowId::new(a.seat.slot + 1000, voice_sub::CHANNEL);
assert!(a.session.send_media(MediaClass::Voice, rtp(other, 0, true, &OPUS)).is_err());
a.close().await;
b.close().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_voice_between_sessions() {
if live() {
voice_between_sessions(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_voice_between_sessions() {
if live() {
voice_between_sessions(TS6).await;
}
}
/// A channel file written with `write_file` and read back from an offset with
/// `read_file`: the head names the file and its size, the body starts where
/// the offset says.
async fn channel_file_from_an_offset(dev: Dev) {
use voelin_query::{Command as Query, QueryClient};
// Guests may not upload: a key for the Server Admin group.
let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login");
let token = group_token(&admin, "Server Admin").await;
let check = tokio::spawn({
let token = token.clone();
async move { channel_file_with_a_key(dev, token).await }
});
let result = check.await;
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
if let Err(error) = result {
std::panic::resume_unwind(error.into_panic());
}
}
/// A one-time key for the server group `name` (a template group, type 1).
async fn group_token(admin: &voelin_query::QueryClient, name: &str) -> String {
use voelin_query::Command as Query;
let groups = admin.send(&Query::new("servergrouplist")).await.unwrap();
let group = groups
.iter()
.find(|g| g.get("name") == Some(name) && g.get("type") == Some("1"))
.and_then(|g| g.parse::<u64>("sgid"))
.unwrap_or_else(|| panic!("a {name} server group"));
let key =
Query::new("privilegekeyadd").arg("tokentype", 0).arg("tokenid1", group).arg("tokenid2", 0);
admin.send(&key).await.unwrap()[0].get("token").unwrap().to_owned()
}
async fn channel_file_with_a_key(dev: Dev, token: String) {
let mut options = VoiceOptions::new(dev.voice, dev.nick("files"));
options.token = Some(token);
let a = Client::connect_with(&dev, options).await;
let channel = a.seat.channel_id;
let name = format!("seam-{}.bin", std::process::id());
let path = format!("/{name}");
let data: Vec<u8> = (0..3_000usize).map(|i| (i * 7 % 251) as u8).collect();
let target = v1::FilePath { channel_id: channel, path: path.clone(), password: String::new() };
let write = v1::FileWrite {
target: Some(v1::file_write::Target::Path(target.clone())),
size: data.len() as u64,
offset: 0,
overwrite: true,
sha256: Default::default(),
};
let mut upload =
within("the upload to open", a.session.write_file(write)).await.expect("an upload");
upload.body.write_all(&data).await.expect("the body");
upload.body.shutdown().await.expect("the end of the body");
let stored = within("the server to keep it", upload.done).await.expect("the file is stored");
assert!(
stored.items.iter().any(|e| matches!(&e.kind, Some(Kind::File(f)) if f.name == name)),
"{stored:?}"
);
let read = v1::FileRead {
target: Some(v1::file_read::Target::Path(target.clone())),
offset: 1_000,
length: 0,
};
let mut download =
within("the download to open", a.session.read_file(read)).await.expect("a download");
let size = download.head.items.iter().find_map(|e| match &e.kind {
Some(Kind::File(file)) => Some(file.size),
_ => None,
});
assert_eq!(size, Some(3_000), "{:?}", download.head);
let mut body = Vec::new();
within("the body", download.body.read_to_end(&mut body)).await.expect("the body");
assert_eq!(body, data[1_000..], "the body starts at the offset");
// Clean up what we put on the server.
let key = v1::FileEntry { channel_id: channel, path: "/".into(), name, ..Default::default() };
let delete = Op::Delete(v1::Delete {
keys: vec![v1::Entity { kind: Some(Kind::File(key)) }],
..Default::default()
});
let _ = a.ask(delete).await;
a.close().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_channel_file_from_an_offset() {
if live() {
channel_file_from_an_offset(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_channel_file_from_an_offset() {
if live() {
channel_file_from_an_offset(TS6).await;
}
}
// ---- the cases that do not apply ----------------------------------------------
/// The cases of [`EXPECTED`] that do not apply fail against a session of a
/// TeamSpeak server, each with a panic of its own (its first line is printed):
/// the reasons of the table are what they did when they were run. A case that
/// passes one day (with the native session of H1) is to be moved to `Passes`.
///
/// Ignored by default: the cases that wait for a backend that is not there
/// take their three seconds each.
async fn cases_that_do_not_apply_fail(dev: Dev) {
// A case the suite gained is not in `EXPECTED`, and the zip below would leave
// it out without a word.
the_suite_is_known();
for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) {
let NotRun(reason) = expect else { continue };
let harness = move || async move {
let mut fixture = fixture(dev).await;
fixture.step = Duration::from_secs(3);
fixture
};
match tokio::spawn(async move { conformance::run_case(&harness, case).await }).await {
Err(error) if error.is_panic() => {
let payload = error.into_panic();
let message = payload
.downcast_ref::<String>()
.cloned()
.or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned()))
.unwrap_or_default();
let first = message.lines().next().unwrap_or_default();
eprintln!("{} {name}: failed as expected ({reason}): {first}", dev.name);
}
other => panic!("{name} on {} was expected to fail, and: {other:?}", dev.name),
}
}
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"]
async fn ts3_cases_that_do_not_apply_fail() {
if live() {
cases_that_do_not_apply_fail(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"]
async fn ts6_cases_that_do_not_apply_fail() {
if live() {
cases_that_do_not_apply_fail(TS6).await;
}
}
@@ -0,0 +1,245 @@
//! Voice across the seam, TeamSpeak side (`docs/session-seam.md` section
//! 6.2): TeamSpeak's Opus packets as RTP on the talker's slot, and RTP on our
//! own slot as TeamSpeak's `EncodedVoice`. Nothing is transcoded
//! (protocol section 1.2): the Opus payload is the same bytes both ways.
use std::collections::HashMap;
use std::time::{Duration, Instant};
use bytes::BytesMut;
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
use voelin_proto::media::opus::{self, Toc};
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, OPUS_CLOCK_RATE, PT_OPUS};
use voelin_proto::media::{RtpHeader, RtpView};
use super::entities::slot;
/// Silence this long between two packets of a talker starts a new talk spurt
/// (the marker bit is set on the first packet of it).
const SPURT_GAP: Duration = Duration::from_millis(250);
/// What is kept of the last packet of a talker.
struct Talker {
timestamp: u32,
sequence: u16,
at: Instant,
/// The 48 kHz ticks the last packet spans.
ticks: u32,
/// The last packet ended the spurt.
ended: bool,
}
/// Wraps what a TeamSpeak connection receives into RTP.
#[derive(Default)]
pub(super) struct Downlink {
talkers: HashMap<u16, Talker>,
}
impl Downlink {
/// `packet` as the RTP packet of its talker's slot. The sequence number is
/// TeamSpeak's packet id (both 16 bits); the timestamp advances by each
/// packet's duration (its Opus table-of-contents byte) on the packet id's
/// counter, so it never goes back when the id wraps, and by wall-clock time
/// across silences, so a silence is not compressed. The marker is set on
/// the first packet after an end or a gap, and an end is an empty payload.
pub(super) fn wrap(&mut self, packet: &VoicePacket, now: Instant) -> Option<MediaPacket> {
let id = packet.talker.0;
let sub = if packet.whisper { voice_sub::FIRST_TALK_TARGET } else { voice_sub::CHANNEL };
let flow = FlowId::new(slot(id), sub);
let end = packet.is_end();
let (timestamp, marker) = match self.talkers.get(&id) {
None => (0, !end),
Some(last) => {
let gap = now.saturating_duration_since(last.at);
if last.ended || gap > SPURT_GAP {
// A new spurt: the time that passed since the last packet.
let wall = (gap.as_micros() * u128::from(OPUS_CLOCK_RATE) / 1_000_000) as u32;
(last.timestamp.wrapping_add(last.ticks.max(wall)), !end)
} else {
let ahead = packet.seq.wrapping_sub(last.sequence);
if ahead == 0 || ahead >= 0x8000 {
// A duplicate or a late packet: where it belongs, and the
// state keeps what the latest packet said.
let back = u32::from(last.sequence.wrapping_sub(packet.seq));
let at = last.timestamp.wrapping_sub(back * last.ticks);
return self.finish(flow, packet, at, false);
}
(last.timestamp.wrapping_add(u32::from(ahead) * last.ticks), false)
}
}
};
let ticks =
if end { 0 } else { opus::packet_ticks(&packet.payload).unwrap_or(OPUS_20_MS_TICKS) };
self.talkers
.insert(id, Talker { timestamp, sequence: packet.seq, at: now, ticks, ended: end });
self.finish(flow, packet, timestamp, marker)
}
fn finish(
&self,
flow: FlowId,
packet: &VoicePacket,
timestamp: u32,
marker: bool,
) -> Option<MediaPacket> {
let mut header = RtpHeader::new(PT_OPUS, packet.seq, timestamp);
header.marker = marker;
// An end is an empty payload, also where the server sent one byte.
let payload = if packet.is_end() { &[][..] } else { &packet.payload[..] };
let mut out = BytesMut::with_capacity(header.encoded_len() + payload.len());
header.write(flow, &mut out).ok()?;
out.extend_from_slice(payload);
Some(MediaPacket { flow, rtp: out.freeze() })
}
/// Forget a talker (it left the server).
pub(super) fn forget(&mut self, client: u16) {
self.talkers.remove(&client);
}
}
/// The voice a media packet of our own slot carries, for TeamSpeak: its
/// payload, and `Music` when the Opus packet is stereo. `None` for a packet
/// that is no RTP.
pub(super) fn uplink(packet: &MediaPacket) -> Option<EncodedVoice> {
let view = RtpView::parse(&packet.rtp).ok()?;
let payload = view.payload();
let codec = match Toc::parse(payload) {
Ok(toc) if toc.stereo() => VoiceCodec::Music,
_ => VoiceCodec::Voice,
};
Some(EncodedVoice { codec, payload: payload.to_vec() })
}
/// An RTP packet of voice, for tests of both sides.
#[cfg(test)]
pub(super) fn rtp_packet(
flow: FlowId,
sequence: u16,
timestamp: u32,
marker: bool,
payload: &[u8],
) -> bytes::Bytes {
let mut header = RtpHeader::new(PT_OPUS, sequence, timestamp);
header.marker = marker;
let mut out = BytesMut::new();
header.write(flow, &mut out).unwrap();
out.extend_from_slice(payload);
out.freeze()
}
#[cfg(test)]
mod tests {
use bytes::Bytes;
use voelin_audio::TalkerId;
use super::*;
fn voice(talker: u16, seq: u16, payload: &[u8], whisper: bool) -> VoicePacket {
VoicePacket {
talker: TalkerId(talker),
seq,
codec: VoiceCodec::Voice,
whisper,
payload: payload.to_vec(),
}
}
/// An Opus packet of 20 ms in a CELT-only frame (config 16 is 2.5 ms; 19
/// is 20 ms), mono, one frame.
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
fn view(packet: &MediaPacket) -> RtpView<'_> {
RtpView::parse(&packet.rtp).unwrap()
}
#[test]
fn a_spurt_is_sequenced_by_the_packet_id_with_a_marker_on_its_first_packet() {
let mut down = Downlink::default();
let t0 = Instant::now();
let first = down.wrap(&voice(7, 65_534, &OPUS_20_MS, false), t0).unwrap();
let v = view(&first);
assert!(v.marker());
assert_eq!((v.ssrc(), first.flow), (FlowId::new(8, 0).0, FlowId::new(8, 0)));
assert_eq!((v.sequence(), v.timestamp()), (65_534, 0));
// The id wraps; the timestamp keeps counting.
let t1 = t0 + Duration::from_millis(20);
let second = down.wrap(&voice(7, 65_535, &OPUS_20_MS, false), t1).unwrap();
let third =
down.wrap(&voice(7, 0, &OPUS_20_MS, false), t1 + Duration::from_millis(20)).unwrap();
assert!(!view(&second).marker() && !view(&third).marker());
assert_eq!(view(&second).timestamp(), OPUS_20_MS_TICKS);
assert_eq!((view(&third).sequence(), view(&third).timestamp()), (0, 2 * OPUS_20_MS_TICKS));
}
#[test]
fn the_end_is_an_empty_payload_and_the_next_packet_has_a_marker() {
let mut down = Downlink::default();
let t0 = Instant::now();
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
let end = down.wrap(&voice(7, 2, &[], false), t0 + Duration::from_millis(20)).unwrap();
assert!(view(&end).payload().is_empty() && !view(&end).marker());
// TeamSpeak's single byte after a talk is an end too.
let mut down = Downlink::default();
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
let end = down.wrap(&voice(7, 2, &[0], false), t0 + Duration::from_millis(20)).unwrap();
assert!(view(&end).payload().is_empty());
let next =
down.wrap(&voice(7, 3, &OPUS_20_MS, false), t0 + Duration::from_millis(60)).unwrap();
assert!(view(&next).marker());
}
#[test]
fn a_silence_is_not_compressed() {
let mut down = Downlink::default();
let t0 = Instant::now();
let first = down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
let again =
down.wrap(&voice(7, 2, &OPUS_20_MS, false), t0 + Duration::from_secs(2)).unwrap();
assert!(view(&again).marker(), "a gap starts a spurt");
// Two seconds of wall-clock time are 96,000 ticks of the 48 kHz clock.
assert_eq!(view(&again).timestamp() - view(&first).timestamp(), 96_000);
}
#[test]
fn whispers_ride_sub_flow_1_and_talkers_have_slots_of_their_own() {
let mut down = Downlink::default();
let now = Instant::now();
let whisper = down.wrap(&voice(300, 1, &OPUS_20_MS, true), now).unwrap();
assert_eq!((whisper.flow.slot(), whisper.flow.sub()), (301, 1));
let channel = down.wrap(&voice(300, 2, &OPUS_20_MS, false), now).unwrap();
assert_eq!((channel.flow.slot(), channel.flow.sub()), (301, 0));
}
#[test]
fn a_packet_that_is_not_in_order_keeps_the_state_of_the_latest() {
let mut down = Downlink::default();
let t0 = Instant::now();
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0).unwrap();
down.wrap(&voice(7, 11, &OPUS_20_MS, false), t0 + Duration::from_millis(20)).unwrap();
let late =
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0 + Duration::from_millis(25)).unwrap();
assert_eq!(view(&late).timestamp(), 0, "where packet 10 belongs");
let next =
down.wrap(&voice(7, 12, &OPUS_20_MS, false), t0 + Duration::from_millis(40)).unwrap();
assert_eq!(view(&next).timestamp(), 2 * OPUS_20_MS_TICKS);
}
#[test]
fn our_voice_loses_its_header_and_stereo_is_music() {
let flow = FlowId::new(8, 0);
let mono = MediaPacket { flow, rtp: rtp_packet(flow, 0, 0, true, &OPUS_20_MS) };
let voice = uplink(&mono).unwrap();
assert_eq!((voice.codec, voice.payload.as_slice()), (VoiceCodec::Voice, &OPUS_20_MS[..]));
// The same TOC with the stereo bit.
let stereo_toc = [OPUS_20_MS[0] | 0x04, 1, 2];
let stereo = MediaPacket { flow, rtp: rtp_packet(flow, 1, 960, false, &stereo_toc) };
assert_eq!(uplink(&stereo).unwrap().codec, VoiceCodec::Music);
// The end of a spurt: an empty payload.
let end = MediaPacket { flow, rtp: rtp_packet(flow, 2, 1920, false, &[]) };
assert!(uplink(&end).unwrap().is_end());
// Not RTP.
assert!(uplink(&MediaPacket { flow, rtp: Bytes::from_static(&[1, 2, 3]) }).is_none());
}
}
+887
View File
@@ -0,0 +1,887 @@
//! A TeamSpeak connection as a `voelin_proto::link::Session`
//! (`docs/session-seam.md`, "the TeamSpeak side").
//!
//! [`LinkSession`] is a `Session` over any [`ServerLink`]:
//! it turns the link's `LinkCmd`s and `LinkEvent`s (the client's older,
//! TeamSpeak-shaped vocabulary) into v1 entities, pushes and answers. With
//! `TsLink` inside it is the in-process TeamSpeak `Session`; with a fake link
//! inside it is what the link tests of the engine run through. [`TsConnector`]
//! is the `Connector` that makes them for `ts3server://` and `teamspeak://`
//! addresses.
//!
//! This module and the files it is made of are TeamSpeak's: they keep the
//! TeamSpeak types (`tsclientlib`'s identity and client version) in
//! [`inner_options`], the reverse of what the engine's `connect_params` wrote,
//! and everything else is v1 and the client's own model. In the second half
//! of the decoupling plan they move, with `TsLink`, to the TeamSpeak gateway
//! (`voelin-gateway-ts` of VoelinGateWay).
mod driver;
pub(crate) mod entities;
pub(crate) mod ids;
#[cfg(test)]
mod live_tests;
mod media;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::task::{Context, Poll};
use std::time::Duration;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use bytes::Bytes;
use tokio::io::{AsyncReadExt, AsyncWrite};
use tokio::sync::{broadcast, mpsc, oneshot, watch};
use voelin_model::{Link, ServerDetails};
use voelin_proto::link::{
BoxFuture, CloseReason, ConnectParams, Connected, Connector, Credential, Download, Features,
LinkStats, MAX_RTP, MediaClass, MediaError, MediaPacket, Placement, Sent, Session,
SessionError, Upload, placement, voice_sub,
};
use voelin_proto::v1::{self, response::Result as Answer};
use self::driver::{Cmd, Config, Driver, Parts, rejected};
use super::{ConnectOptions, ServerLink, TsLink, identity, versions};
use crate::BackendInfo;
use crate::link::{
BoxDuplex, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalConnector, LocalCtx, StreamPort,
VERSION_PARAM,
};
/// The `Credential::Foreign` kind of a stored TeamSpeak identity.
const IDENTITY_KIND: &str = voelin_identity::KIND_TEAMSPEAK;
/// How long the link may take to report its first snapshot after it said it
/// is connected; the snapshot gives the `Welcome` its own user.
const FIRST_SNAPSHOT: Duration = Duration::from_millis(250);
static SESSIONS: AtomicU64 = AtomicU64::new(1);
fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or_default()
}
// ---- what the engine hands a connector ------------------------------------
/// The options a TeamSpeak link is connected with: the reverse of
/// `link::connect_params`. A client version spec that [`versions::resolve`]
/// refuses fails the connect, in words.
fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result<ConnectOptions, SessionError> {
let link = match Link::parse(&params.address) {
Some(Link::Server(link)) => link,
_ => {
// Without the query: a channel password rides in it.
let shown = crate::link::without_query(&params.address);
return Err(SessionError::Protocol(format!("not a TeamSpeak server address: {shown}")));
}
};
let identity = match &params.credential {
Credential::Foreign { kind: IDENTITY_KIND, blob } if blob.is_empty() => None,
Credential::Foreign { kind: IDENTITY_KIND, blob } => {
// The refusal never quotes the JSON: it holds the private key, and the
// JSON reader's own message would show a key that does not import.
let json = std::str::from_utf8(blob).map_err(|_| {
SessionError::Protocol(
"the TeamSpeak identity cannot be read: it is not text".into(),
)
})?;
Some(identity::from_json(json).map_err(|e| SessionError::Protocol(e.to_string()))?)
}
_ => {
return Err(SessionError::Protocol(
"a TeamSpeak server needs a TeamSpeak identity".into(),
));
}
};
let spec = params
.address
.split_once('?')
.and_then(|(_, query)| {
query.split('&').find_map(|pair| pair.strip_prefix(&format!("{VERSION_PARAM}=")))
})
.map(|text| {
URL_SAFE_NO_PAD
.decode(text)
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok())
.ok_or_else(|| SessionError::Protocol("the client version cannot be read".into()))
})
.transpose()?;
let client_version = match spec {
None => None,
Some(spec) => versions::resolve(&spec).map_err(|e| {
SessionError::Protocol(format!("invalid client compatibility version: {e}"))
})?,
};
let nonempty = |text: &str| (!text.is_empty()).then(|| text.to_owned());
Ok(ConnectOptions {
address: link.address(),
nickname: nonempty(&params.hello.nickname).or(link.nickname.clone()).unwrap_or_default(),
identity,
client_version,
server_password: nonempty(&params.hello.password).or(link.password.clone()),
channel: link.channel.clone(),
channel_password: link.channel_password.clone(),
token: nonempty(&params.hello.invite_code).or(link.token.clone()),
audio: ctx.audio,
stream_peer: ctx.stream_peer.clone(),
})
}
// ---- backend and features ---------------------------------------------------
/// The server software as v1 names it (table 4.7): `teamspeak` with the
/// flavor `ts3` or `ts6`; what is not a TeamSpeak product as it is.
pub(crate) fn backend_to_v1(backend: &BackendInfo) -> v1::BackendInfo {
let (product, flavor) = match backend.product.as_str() {
"TeamSpeak 3" => ("teamspeak", "ts3"),
"TeamSpeak 6" => ("teamspeak", "ts6"),
// A TeamSpeak server the engine does not recognise: the version it
// sent, no flavor.
"" => ("teamspeak", ""),
other => (other, ""),
};
v1::BackendInfo {
product: product.into(),
version: backend.version.clone(),
flavor: flavor.into(),
}
}
/// The features a TeamSpeak connection offers, from what its link can do
/// (`docs/session-seam.md` section 4.7).
pub(crate) fn features_of(capabilities: &voelin_model::Capabilities) -> Vec<&'static str> {
let mut features =
vec!["voice", "chat", "chat.bbcode", "dm", "sync.delta", "roles", "roles.channel"];
if capabilities.file_transfer {
features.extend(["files", "files.upload"]);
}
if capabilities.offline_messages {
features.push("mailbox");
}
if capabilities.streams {
features.extend(["streams", "streams.p2p", "streams.audio", "streams.approval"]);
}
features
}
// ---- the session ------------------------------------------------------------
/// A `Session` over a [`ServerLink`]: the TeamSpeak side of the seam.
pub(crate) struct LinkSession {
welcome: v1::Welcome,
features: Features,
cmds: mpsc::UnboundedSender<Cmd>,
closed: watch::Receiver<Option<CloseReason>>,
/// The media slot of our client; the driver changes it when we are another
/// client after TeamSpeak's own reconnect.
own_slot: Arc<AtomicU32>,
}
fn closed_reason(closed: &watch::Receiver<Option<CloseReason>>) -> CloseReason {
closed.borrow().clone().unwrap_or_else(|| CloseReason::Network("the connection ended".into()))
}
impl Session for LinkSession {
fn welcome(&self) -> &v1::Welcome {
&self.welcome
}
fn features(&self) -> Features {
self.features.clone()
}
fn request(&self, op: v1::request::Op) -> BoxFuture<Result<Answer, SessionError>> {
let closed = self.closed.clone();
match placement(&op) {
Placement::Invalid => {
return Box::pin(async {
Err(SessionError::Protocol("a Hello is part of connecting".into()))
});
}
Placement::OwnStream
if matches!(op, v1::request::Op::FileRead(_) | v1::request::Op::FileWrite(_)) =>
{
return Box::pin(async {
Err(SessionError::Protocol("files go through read_file and write_file".into()))
});
}
_ => {}
}
// Queued now, in the order of the calls, not when the future is polled.
let (reply, answer) = oneshot::channel();
if self.cmds.send(Cmd::Request { op, reply }).is_err() {
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
}
Box::pin(async move {
match answer.await {
Ok(answer) => answer,
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
}
})
}
fn notify(&self, op: v1::request::Op) -> Result<(), SessionError> {
// Only an op of the control stream can go without an answer: a Hello is
// part of connecting, and a List and the file transfers have streams
// (and answers) of their own.
match placement(&op) {
Placement::Control => {}
Placement::Invalid => {
return Err(SessionError::Protocol("a Hello is part of connecting".into()));
}
Placement::OwnStream => {
return Err(SessionError::Protocol(
"a List and the file transfers have a stream and an answer of their own, \
they cannot be sent without one"
.into(),
));
}
}
// The task may be on its way out and not have dropped its queue yet.
if self.closed.borrow().is_some() {
return Err(SessionError::Closed(closed_reason(&self.closed)));
}
self.cmds
.send(Cmd::Notify(op))
.map_err(|_| SessionError::Closed(closed_reason(&self.closed)))
}
fn read_file(&self, request: v1::FileRead) -> BoxFuture<Result<Download, SessionError>> {
let closed = self.closed.clone();
let (reply, answer) = oneshot::channel();
if self.cmds.send(Cmd::Read { request, reply }).is_err() {
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
}
Box::pin(async move {
match answer.await {
Ok(answer) => answer,
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
}
})
}
fn write_file(&self, request: v1::FileWrite) -> BoxFuture<Result<Upload, SessionError>> {
let closed = self.closed.clone();
let (reply, answer) = oneshot::channel();
if self.cmds.send(Cmd::Write { request, reply }).is_err() {
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
}
Box::pin(async move {
match answer.await {
Ok(answer) => answer,
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
}
})
}
fn send_media(&self, class: MediaClass, packet: MediaPacket) -> Result<Sent, MediaError> {
let flow = packet.flow;
if self.closed.borrow().is_some() {
return Err(MediaError::Closed);
}
if packet.rtp.len() > MAX_RTP {
return Err(MediaError::TooLarge { len: packet.rtp.len(), max: MAX_RTP });
}
// Only our voice to the channel: TeamSpeak whispers and priority voice,
// like video, are not offered here.
if class != MediaClass::Voice
|| flow.slot() != self.own_slot.load(Ordering::Relaxed)
|| flow.sub() != voice_sub::CHANNEL
{
return Err(MediaError::NotOwned(flow));
}
let voice = media::uplink(&packet).ok_or(MediaError::NotOwned(flow))?;
self.cmds.send(Cmd::Audio(voice)).map_err(|_| MediaError::Closed)?;
Ok(Sent::Queued)
}
fn stats(&self) -> LinkStats {
LinkStats { max_rtp: MAX_RTP, ..Default::default() }
}
fn close(&self, code: v1::CloseCode, reason: &str) {
let _ = self.cmds.send(Cmd::Close { code, reason: reason.to_owned() });
}
fn closed(&self) -> BoxFuture<CloseReason> {
let mut closed = self.closed.clone();
Box::pin(async move {
let reason = closed.wait_for(Option::is_some).await.ok().and_then(|r| r.clone());
reason.unwrap_or_else(|| closed_reason(&closed))
})
}
}
/// The write half of an upload: ending it tells the other half of the
/// upload that the file is all there.
struct UploadBody {
inner: tokio::io::WriteHalf<BoxDuplex>,
ended: Option<oneshot::Sender<()>>,
}
impl AsyncWrite for UploadBody {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.inner).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
let done = Pin::new(&mut self.inner).poll_shutdown(cx);
if matches!(done, Poll::Ready(Ok(())))
&& let Some(ended) = self.ended.take()
{
let _ = ended.send(());
}
done
}
}
/// An upload over the transfer connection `stream`: the body writes to it,
/// and `done` resolves once the body is shut down and the server has closed
/// the connection (or 30 s passed), with the file as `stored`.
fn upload(stream: BoxDuplex, stored: v1::FileEntry) -> Upload {
let (mut read, write) = tokio::io::split(stream);
let (ended, shut) = oneshot::channel();
let done: BoxFuture<Result<v1::Entities, SessionError>> = Box::pin(async move {
if shut.await.is_err() {
return Err(rejected(v1::ErrorCode::Cancelled, "the upload was dropped"));
}
// The server closes the connection once it has everything.
let _ = tokio::time::timeout(Duration::from_secs(30), read.read(&mut [0u8; 1])).await;
Ok(v1::Entities {
items: vec![v1::Entity { kind: Some(v1::entity::Kind::File(stored)) }],
..Default::default()
})
});
Upload { body: Box::pin(UploadBody { inner: write, ended: Some(ended) }), done }
}
// ---- the connector ----------------------------------------------------------
/// The `Connector` of a [`ServerLink`]: its sessions are [`LinkSession`]s.
#[derive(Clone)]
pub(crate) struct LinkConnector {
link: Arc<dyn ServerLink>,
schemes: &'static [&'static str],
/// Serves every scheme (the engine's tests give a link of their own).
any: bool,
}
impl LinkConnector {
/// A connector for `schemes`.
pub(crate) fn new(link: Arc<dyn ServerLink>, schemes: &'static [&'static str]) -> Self {
Self { link, schemes, any: false }
}
/// A connector for addresses of every scheme.
#[cfg(test)]
pub(crate) fn any(link: Arc<dyn ServerLink>) -> Self {
Self { link, schemes: &[], any: true }
}
}
impl Connector for LinkConnector {
fn schemes(&self) -> &'static [&'static str] {
self.schemes
}
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
let connect = connect_link(self.link.clone(), params, LocalCtx::standalone());
Box::pin(async move { Ok(connect.await?.connected) })
}
}
impl LocalConnector for LinkConnector {
fn accepts(&self, scheme: &str) -> bool {
self.any || self.schemes.contains(&scheme)
}
fn connect_local(
&self,
params: ConnectParams,
ctx: LocalCtx,
) -> BoxFuture<Result<LocalConnected, SessionError>> {
Box::pin(connect_link(self.link.clone(), params, ctx))
}
}
/// Connects to TeamSpeak 3 and 6 servers (`ts3server://` and `teamspeak://`)
/// with `tsclientlib`: a `LinkSession` over a `TsLink` for every connection.
///
/// Clones share one account: the main myTeamSpeak account that every
/// connection of the connector presents ([`TsConnector::set_myts_identity`],
/// [`TsConnector::set_myts_data`]), also those made before it was set.
/// Register a connector in the engine's registry with
/// [`Backends::register_teamspeak`](crate::Backends::register_teamspeak) and
/// keep a clone to set the account.
#[derive(Clone)]
pub struct TsConnector {
connector: LinkConnector,
link: Arc<TsLink>,
}
impl Default for TsConnector {
fn default() -> Self {
Self::new()
}
}
impl TsConnector {
/// A connector that presents no account until it is given one.
pub fn new() -> Self {
let link = Arc::new(TsLink::new());
Self { connector: LinkConnector::new(link.clone(), &["ts3server", "teamspeak"]), link }
}
/// The main account's proof for every current and future connection of
/// this connector (and its clones): a myTS ID signed with the account's
/// key. Connections that are up show the server the new proof, and those
/// that connect later present it from the start; `None` is a sign-out.
pub fn set_myts_identity(&self, identity: Option<Arc<tsproto::myts::Identity>>) {
self.link.account().set_identity(identity);
}
/// What servers are shown of the main account: its avatar and badges with
/// their certificates, its User Tag (TeamSpeak 6). It is sent to every
/// connection that presents the account's myTS ID, once connected and when
/// it changes; cleared on a sign-out (`None`).
pub fn set_myts_data(&self, data: Option<Arc<tsclientlib::MytsData>>) {
self.link.account().set_data(data);
}
}
impl Connector for TsConnector {
fn schemes(&self) -> &'static [&'static str] {
self.connector.schemes()
}
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
self.connector.connect(params)
}
}
impl LocalConnector for TsConnector {
fn connect_local(
&self,
params: ConnectParams,
ctx: LocalCtx,
) -> BoxFuture<Result<LocalConnected, SessionError>> {
self.connector.connect_local(params, ctx)
}
}
/// What the link told when it connected.
struct Joined {
name: String,
backend: BackendInfo,
capabilities: voelin_model::Capabilities,
own_client: u16,
server_uid: String,
own_uid: Option<String>,
}
fn ended_error(reason: Option<String>) -> SessionError {
SessionError::Closed(match reason {
Some(reason) => CloseReason::Network(reason),
None => CloseReason::Remote { code: v1::CloseCode::Normal as u64, reason: String::new() },
})
}
/// Wait for the link to say it is connected (or that it failed).
async fn wait_connected(
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
) -> Result<Joined, SessionError> {
loop {
match events.recv().await {
Some(LinkEvent::Connected {
name,
backend,
capabilities,
own_client,
server_uid,
own_uid,
}) => {
return Ok(Joined { name, backend, capabilities, own_client, server_uid, own_uid });
}
Some(LinkEvent::Disconnected(reason)) => return Err(ended_error(reason)),
Some(_) => {}
None => return Err(ended_error(Some("the connection ended".into()))),
}
}
}
/// Open a [`LinkSession`] over `link` to the address in `params`.
async fn connect_link(
link: Arc<dyn ServerLink>,
params: ConnectParams,
ctx: LocalCtx,
) -> Result<LocalConnected, SessionError> {
let options = inner_options(&params, &ctx)?;
let nickname = options.nickname.clone();
let (inner_tx, inner_rx) = mpsc::unbounded_channel();
let (events_tx, mut events) = mpsc::unbounded_channel();
// The link answers requests on a bus of its own: this session reads the
// answers, and passes on the rest to the engine's.
let (bus_tx, bus) = broadcast::channel(4096);
let inner_ctx = LinkCtx { events: bus_tx, ..ctx.link.clone() };
link.spawn(options, inner_ctx, inner_rx, events_tx);
let joined = match tokio::time::timeout(params.timeout, wait_connected(&mut events)).await {
Ok(joined) => joined?,
Err(_) => {
let _ = inner_tx.send(LinkCmd::Disconnect);
return Err(SessionError::Timeout);
}
};
// The link reports its first snapshot right after it says it is connected;
// the session needs it to know the own user.
let mut early: Vec<LinkEvent> = Vec::new();
let _ = tokio::time::timeout(FIRST_SNAPSHOT, async {
while let Some(event) = events.recv().await {
let stop = matches!(event, LinkEvent::Presence(_) | LinkEvent::Disconnected(_));
early.push(event);
if stop {
break;
}
}
})
.await;
if let Some(LinkEvent::Disconnected(reason)) = early.last() {
return Err(ended_error(reason.clone()));
}
let own_database_id = early.iter().find_map(|event| match event {
LinkEvent::Presence(presence) => {
presence.clients.get(&joined.own_client).and_then(|c| c.database_id)
}
_ => None,
});
let ts6 = joined.backend.product == "TeamSpeak 6";
let own_user =
own_database_id.or_else(|| joined.own_uid.as_deref().map(ids::synthetic_user)).unwrap_or(0);
let features = features_of(&joined.capabilities);
let welcome = v1::Welcome {
user_id: own_user,
session_id: SESSIONS.fetch_add(1, Ordering::Relaxed),
uid: joined.own_uid.as_deref().and_then(ids::uid_bytes).unwrap_or_default().into(),
host: Some(v1::HostInfo {
host_key: Bytes::new(),
name: joined.name.clone(),
product: joined.backend.product.clone(),
version: joined.backend.version.clone(),
backend: Some(backend_to_v1(&joined.backend)),
icon: None,
}),
features: features.iter().map(|f| (*f).to_owned()).collect(),
limits: Some(v1::Limits {
max_message_chars: 1024,
max_page: 100,
// HOME, SERVER and LIVE, and the chats.
max_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS + 3,
max_chat_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS,
max_live_subscriptions: 8,
..Default::default()
}),
time_ms: now_ms(),
..Default::default()
};
let (cmds_tx, cmds_rx) = mpsc::unbounded_channel();
let own_slot = Arc::new(AtomicU32::new(entities::slot(joined.own_client)));
let (pushes_tx, pushes_rx) = mpsc::channel(params.push_capacity.max(16));
let (closed_tx, closed_rx) = watch::channel(None);
let (port, streams) = if joined.capabilities.streams {
let (events_tx, events_rx) = mpsc::unbounded_channel();
let cmds = cmds_tx.clone();
let send = move |cmd| {
let _ = cmds.send(Cmd::Stream(cmd));
};
(Some(events_tx), Some(StreamPort::new(send, events_rx)))
} else {
(None, None)
};
let details = ServerDetails { uid: Some(joined.server_uid.clone()), ..Default::default() };
let driver = Driver::new(Parts {
cfg: Config {
ts6,
own_client: joined.own_client,
nickname,
own_uid: joined.own_uid.clone(),
files: joined.capabilities.file_transfer,
mail: joined.capabilities.offline_messages,
},
inner: inner_tx,
events,
early,
bus,
engine_bus: ctx.link.events.clone(),
pushes: pushes_tx,
media: params.media.clone(),
port,
closed: closed_tx,
own_slot: own_slot.clone(),
server: entities::server(&details, &joined.name, 0),
epoch: u64::try_from(now_ms()).unwrap_or(1).max(1),
});
let session = LinkSession {
welcome,
features: Features::new(features),
cmds: cmds_tx,
closed: closed_rx,
own_slot,
};
tokio::spawn(driver.run(cmds_rx));
Ok(LocalConnected {
connected: Connected {
session: Arc::new(session),
pushes: pushes_rx,
// A TeamSpeak server has no host key to pin.
host_uid: [0; 32],
},
streams,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::link::{Backends, VoiceOptions, connect_params};
use voelin_proto::link::IssuerTrust;
fn params(options: &VoiceOptions) -> ConnectParams {
let (media, _rx) = voelin_proto::test_util::media_channel();
connect_params(options, media, &Backends::empty()).unwrap()
}
fn back(options: &VoiceOptions) -> ConnectOptions {
inner_options(&params(options), &LocalCtx::standalone()).unwrap()
}
#[test]
fn the_options_of_a_bookmark_come_back_as_they_went() {
let mut options = VoiceOptions::new("ts.example.com:9988", "nick");
let same = back(&options);
assert_eq!(
(same.address.as_str(), same.nickname.as_str()),
("ts.example.com:9988", "nick")
);
assert!(same.identity.is_none() && same.client_version.is_none());
assert!(same.channel.is_none() && same.server_password.is_none() && same.token.is_none());
// Everything a connection can be told: the server password and the
// privilege key go in the hello, the channel and its password in the
// link, the identity as a credential.
options.server_password = Some("s3cret pass&word".into());
options.channel = Some("Games/Raid Night".into());
options.channel_password = Some("p w+%".into());
options.token = Some("tokenvalue".into());
let identity = tsclientlib::Identity::create();
options.identity = Some(crate::ts::identity::to_blob(&identity));
// A spec the user can give; the connector resolves it.
options.client_version = Some("generic".into());
options.audio = false;
let sent = params(&options);
assert_eq!(sent.hello.password, "s3cret pass&word");
assert_eq!(sent.hello.invite_code, "tokenvalue");
assert_eq!(sent.hello.nickname, "nick");
assert!(
sent.address.starts_with("ts3server://ts.example.com?port=9988"),
"{}",
sent.address
);
assert!(!sent.address.contains("s3cret") && !sent.address.contains("tokenvalue"));
let got = back(&options);
assert_eq!(got.address, "ts.example.com:9988");
assert_eq!(got.server_password, options.server_password);
assert_eq!(got.channel.as_deref(), Some("Games/Raid Night"));
assert_eq!(got.channel_password, options.channel_password);
assert_eq!(got.token.as_deref(), Some("tokenvalue"));
assert_eq!(got.client_version, versions::resolve("generic").unwrap());
assert!(got.client_version.is_some());
// The identity is the same key and counters.
let b = got.identity.as_ref().unwrap();
assert_eq!(serde_json::to_value(&identity).unwrap(), serde_json::to_value(b).unwrap());
}
#[test]
fn a_channel_by_id_and_an_address_that_is_a_link_are_kept() {
let mut options = VoiceOptions::new("[::1]:9987", "nick");
options.channel = Some("/12".into());
let got = back(&options);
assert_eq!(got.address, "[::1]:9987");
assert_eq!(got.channel.as_deref(), Some("/12"));
// A bookmark that is a link keeps its own parameters.
let options = VoiceOptions::new("ts3server://ts.example.com?port=1&channel=Lobby", "nick");
let got = back(&options);
assert_eq!(
(got.address.as_str(), got.channel.as_deref()),
("ts.example.com:1", Some("Lobby"))
);
// Another scheme is left as it is for the connector of that scheme.
let options = VoiceOptions::new("voelin://host/i/code", "nick");
assert_eq!(params(&options).address, "voelin://host/i/code");
}
#[test]
fn what_is_no_teamspeak_identity_is_refused() {
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
sent.credential = Credential::Voelin(Arc::new(voelin_proto::test_util::FakeSigner));
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
assert!(matches!(error, SessionError::Protocol(_)));
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
sent.credential =
Credential::Account { kind: "teamspeak", integration_id: Bytes::from_static(b"id") };
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
sent.credential =
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(b"not json") };
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
// A host that wants trust is refused: TeamSpeak has no host key.
let backends = Backends::empty();
let confirm = backends.trust().confirm(voelin_proto::link::HostIdentity {
address: "x".into(),
uid: [0; 32],
previous: None,
});
assert!(!futures::executor::block_on(confirm));
}
/// An identity that cannot be read ends the connect with words that say
/// where it is wrong and hold none of the key: the JSON reader's own
/// message quotes a key that does not import, and this text reaches the
/// event bus and the status line.
#[test]
fn an_identity_that_cannot_be_read_is_refused_without_the_key() {
let (json, cut) = identity::json_with_a_cut_key();
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
sent.credential = Credential::Foreign { kind: "teamspeak", blob: Bytes::from(json) };
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
let SessionError::Protocol(text) = error else { panic!("a protocol error: {error:?}") };
assert!(
text.starts_with(
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
),
"{text}"
);
identity::assert_holds_no_piece_of(&text, &cut);
// Not even text.
sent.credential =
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(&[b'{', 0xff]) };
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
let SessionError::Protocol(text) = error else { panic!("a protocol error: {error:?}") };
assert_eq!(text, "the TeamSpeak identity cannot be read: it is not text");
}
#[test]
fn the_params_carry_what_the_session_needs_and_no_account_yet() {
let sent = params(&VoiceOptions::new("ts.example.com", "nick"));
assert!(sent.account.is_none());
assert_eq!(sent.issuer_trust, IssuerTrust::Unknown);
assert!(sent.linked.is_empty() && sent.host_pin.is_none());
assert_eq!((sent.push_capacity, sent.timeout), (1024, Duration::from_secs(35)));
let client = sent.hello.client.unwrap();
assert_eq!(client.name, "Voelin");
assert_eq!(sent.hello.version, 1);
}
/// Why `connect_params` refused an address, if it did.
fn refused(address: &str) -> Option<String> {
let (media, _rx) = voelin_proto::test_util::media_channel();
match connect_params(&VoiceOptions::new(address, "nick"), media, &Backends::empty()) {
Ok(_) => None,
Err(SessionError::Protocol(text)) => Some(text),
Err(other) => panic!("{address}: {other}"),
}
}
#[test]
fn a_bookmark_the_link_would_change_is_refused() {
// A port that is no port, in any shape: the link would drop it and the
// connection would go to the default port.
for address in [
"ts.example.com:99999",
"ts.example.com:65536",
"ts.example.com:0",
"ts.example.com:abc",
"ts.example.com:",
"[::1]:70000",
"[::1]:",
"[::1]x",
] {
let text = refused(address).unwrap_or_else(|| panic!("{address} was accepted"));
assert!(text.contains("65535") && text.contains(address), "{text}");
}
// A host the link would cut or decode: a `?` hides the channel behind the
// next one, a `/` or `#` ends the host, a `%` is decoded.
for address in [
"",
" ",
"ts.example.com?x",
"ts.example.com#x",
"ts.example.com/x",
"a b",
"h%41",
"[::1",
] {
let text = refused(address).unwrap_or_else(|| panic!("{address:?} was accepted"));
assert!(text.starts_with("not a server address"), "{text}");
}
// The text names no query: a link keeps secrets in it.
let text = refused("ts.example.com?password=hunter2").unwrap();
assert!(!text.contains("hunter2"), "{text}");
}
#[test]
fn the_bookmarks_a_server_has_come_back_with_their_channel() {
for (address, host) in [
("ts.example.com", "ts.example.com"),
("ts.example.com:9987", "ts.example.com:9987"),
(" ts.example.com:1 ", "ts.example.com:1"),
("127.0.0.1:65535", "127.0.0.1:65535"),
("[::1]:9987", "[::1]:9987"),
// The brackets of a v6 address without a port are the link's to drop;
// the TeamSpeak library reads both forms.
("[::1]", "::1"),
("::1", "::1"),
("2001:db8::1", "2001:db8::1"),
] {
let mut options = VoiceOptions::new(address, "nick");
options.channel = Some("Games/Raid".into());
let got = back(&options);
assert_eq!((got.address.as_str(), got.channel.as_deref()), (host, Some("Games/Raid")));
}
}
/// The normalisations of the round trip, listed in `docs/session-seam.md`
/// (13): an empty option is none, and an empty nickname stays empty.
#[test]
fn empty_options_come_back_as_none() {
let mut options = VoiceOptions::new("ts.example.com", "");
options.server_password = Some(String::new());
options.channel = Some(String::new());
options.channel_password = Some(String::new());
options.token = Some(String::new());
let got = back(&options);
assert!(got.nickname.is_empty());
assert!(
got.server_password.is_none()
&& got.channel.is_none()
&& got.channel_password.is_none()
&& got.token.is_none()
);
}
}
@@ -8,7 +8,7 @@ use anyhow::{Context, Result, bail};
use base64::prelude::*;
use tsclientlib::Version;
const VERSIONS_CSV: &str = include_str!("../../proto/tsproto-structs/declarations/Versions.csv");
const VERSIONS_CSV: &str = include_str!("../../../proto/tsproto-structs/declarations/Versions.csv");
/// The signed generic version of every platform, tsclientlib's default.
const GENERIC_VERSION: &str = "3.?.? [Build: 5680278000]";
File diff suppressed because it is too large. Load diff
+71 -10
View File
@@ -960,11 +960,27 @@ pub(crate) mod tests {
/// What `f` logs at info (and above) on this thread: each line its
/// message, then its fields (` name=value`).
///
/// One recording subscriber is installed for the whole test process, the
/// first time this is called, and each call records into a buffer of its
/// own thread. A scoped one (`tracing::subscriber::with_default`) loses
/// lines: while it is the only subscriber alive, a callsite that another
/// test's thread meets first is registered against that thread's own
/// default, which is none, and stays disabled for every thread, so the
/// lines of the test that reads them are gone
/// (`session::banner_tests::a_failing_banner_is_logged_once_with_its_address`
/// failed with no lines at all, once in about thirty runs of the suite).
pub(crate) fn info_lines<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
use std::cell::RefCell;
use std::sync::Once;
use tracing::field::{Field, Visit};
use tracing::span;
struct Lines(Arc<Mutex<Vec<String>>>);
thread_local! {
/// The lines of the `info_lines` running on this thread, if any.
static LINES: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
}
#[derive(Default)]
struct Line(String, String);
impl Visit for Line {
@@ -975,7 +991,8 @@ pub(crate) mod tests {
}
}
}
impl tracing::Subscriber for Lines {
struct Recorder;
impl tracing::Subscriber for Recorder {
fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool {
*metadata.level() <= tracing::Level::INFO
}
@@ -985,19 +1002,57 @@ pub(crate) mod tests {
fn record(&self, _: &span::Id, _: &span::Record<'_>) {}
fn record_follows_from(&self, _: &span::Id, _: &span::Id) {}
fn event(&self, event: &tracing::Event<'_>) {
let mut line = Line::default();
event.record(&mut line);
self.0.lock().unwrap().push(line.0 + &line.1);
LINES.with(|lines| {
if let Some(lines) = lines.borrow_mut().as_mut() {
let mut line = Line::default();
event.record(&mut line);
lines.push(line.0 + &line.1);
}
});
}
fn enter(&self, _: &span::Id) {}
fn exit(&self, _: &span::Id) {}
}
let lines = Arc::new(Mutex::new(Vec::new()));
let result = tracing::subscriber::with_default(Lines(lines.clone()), f);
let lines = lines.lock().unwrap().clone();
/// Ends the recording of this thread, also when `f` panics.
struct Recording;
impl Drop for Recording {
fn drop(&mut self) {
LINES.with(|lines| lines.borrow_mut().take());
}
}
static INSTALL: Once = Once::new();
INSTALL.call_once(|| {
tracing::subscriber::set_global_default(Recorder)
.expect("no other global tracing subscriber in the tests");
// Makes every callsite decide again with the subscriber in place, also
// one that a thread was registering while it was being installed
// (creating a `Dispatch` rebuilds the cached interest of all of them).
drop(tracing::Dispatch::new(Recorder));
});
LINES.with(|lines| *lines.borrow_mut() = Some(Vec::new()));
let _recording = Recording;
let result = f();
let lines = LINES.with(|lines| lines.borrow_mut().take().unwrap_or_default());
(result, lines)
}
/// The lines of `info_lines` do not depend on which thread met a callsite
/// first: this one is met on another thread, which records nothing, before
/// the thread that reads the lines meets it.
#[test]
fn info_lines_see_a_callsite_another_thread_met_first() {
fn log() {
tracing::info!("met");
}
let ((), lines) = info_lines(|| {
std::thread::spawn(log).join().unwrap();
log();
});
assert_eq!(lines, ["met"]);
}
fn temp_dir(tag: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("voelin-web-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
@@ -1375,9 +1430,15 @@ pub(crate) mod tests {
};
let mut port = [0u8; 2];
client.read_exact(&mut port).await.unwrap();
let target = format!("{host}:{}", u16::from_be_bytes(port));
let port = u16::from_be_bytes(port);
let target = format!("{host}:{port}");
targets.send(target.clone()).unwrap();
let mut server = TcpStream::connect(target).await.unwrap();
// The proxy resolves the name it is given (SOCKS5h). `localhost` is
// 127.0.0.1 to it, whatever this machine's resolver says: some answer
// `::1` only, and the servers of the tests listen on 127.0.0.1.
let dial =
if host == "localhost" { format!("127.0.0.1:{port}") } else { target };
let mut server = TcpStream::connect(dial).await.unwrap();
client.write_all(&[5, 0, 0, 1, 0, 0, 0, 0, 0, 0]).await.unwrap();
let _ = tokio::io::copy_bidirectional(&mut client, &mut server).await;
});
+28
View File
@@ -0,0 +1,28 @@
//! What more than one integration test of this crate needs (a test binary
//! that uses it declares `mod common;`).
use std::path::{Path, PathBuf};
use std::time::Duration;
/// Wait until nothing has the SQLite database at `path` open any more, as when
/// the process that had it has ended: SQLite deletes the write-ahead log
/// (`<path>-wal`) when the last connection closes.
///
/// A dropped `Engine` is not that yet. Its task ends later, the history writer
/// is joined there, and closing the connection checkpoints the log under an
/// exclusive lock, with fsyncs. A connection opened meanwhile waits for the
/// lock only as long as the busy timeout (5 s) and then fails with
/// `DatabaseBusy`, which a loaded disk makes happen (with every fsync taking
/// 6 s it happens every time).
pub async fn closed(path: &Path) {
let mut wal = path.as_os_str().to_owned();
wal.push("-wal");
let wal = PathBuf::from(wal);
tokio::time::timeout(Duration::from_secs(120), async {
while wal.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the engine's database connection closed");
}
+59 -6
View File
@@ -16,6 +16,7 @@ use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
use voelin_core::gateway::{GatewayRequest, GatewayUpdate};
use voelin_core::history::MessageSource;
use voelin_core::settings::Settings;
use voelin_core::ts::identity::to_blob;
use voelin_core::{Command, Engine, Event, History, HistoryMessage, HistorySource, ObserveState};
use voelin_gateway_proto::{
ClientMsg, Envelope, ErrorCode, HistoryEntry, HistoryPage, PinInfo, ReactionCount, ServerMsg,
@@ -23,6 +24,8 @@ use voelin_gateway_proto::{
};
use voelin_model::{ChatMessage, ChatTarget, PresenceSnapshot};
mod common;
const LOBBY: ChatTarget = ChatTarget::Channel(1);
const ME: &str = "me-uid";
@@ -448,7 +451,7 @@ fn observe(engine: &Engine, session: u64, gw: &FakeGateway) {
engine.send(Command::ObserveGateway {
session,
urls: vec![gw.url.clone()],
identity: Box::new(identity),
identity: Box::new(to_blob(&identity)),
});
}
@@ -528,6 +531,8 @@ async fn history_on_open_paging_and_offline_messages() {
assert_eq!(texts(&stored), ["m1", "m2", "m3", "m4", "m5", "while away 1", "while away 2"]);
history.flush();
drop((engine, history));
// Dropping the engine does not close the database yet (see `closed`).
common::closed(&path).await;
// After a restart, with the gateway down: the stored page, found by the
// gateway's URL, which is remembered with the server's id.
@@ -742,7 +747,7 @@ async fn an_unreachable_gateway_is_tried_again_quietly() {
engine.send(Command::ObserveGateway {
session: 3,
urls: vec![format!("ws://127.0.0.1:{port}/v1")],
identity: Box::new(tsclientlib::Identity::create()),
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
});
// The first attempts fail (the next ones about 1 s, then 2 s later):
// still connecting, and the user is told nothing.
@@ -811,7 +816,16 @@ async fn not_found_proxy() -> String {
#[tokio::test(flavor = "multi_thread")]
async fn the_next_published_gateway_is_used_when_one_fails() {
let proxy = not_found_proxy().await;
let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
// A port that is taken and never listened on: connecting is refused at once,
// and no other test of this process can be given it meanwhile (one that was
// only free for a moment could be, the listeners of the others bind port 0).
let reserved = tokio::net::TcpSocket::new_v4().unwrap();
reserved.bind("127.0.0.1:0".parse().unwrap()).unwrap();
let closed = reserved.local_addr().unwrap().port();
assert!(
tokio::net::TcpStream::connect(("127.0.0.1", closed)).await.is_err(),
"something listens on port {closed}"
);
let gw = FakeGateway::start().await;
let path = temp_db("fallback");
let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap());
@@ -819,7 +833,7 @@ async fn the_next_published_gateway_is_used_when_one_fails() {
engine.send(Command::ObserveGateway {
session: 4,
urls: vec![proxy, format!("ws://127.0.0.1:{closed}/v1"), gw.url.clone()],
identity: Box::new(tsclientlib::Identity::create()),
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
});
// Within one round: sooner than the shortest wait after a failed round
// (1 s, less 30 %).
@@ -904,7 +918,7 @@ async fn a_login_the_gateway_cannot_do_yet_is_tried_again() {
engine.send(Command::ObserveGateway {
session,
urls: vec![gw.url.clone()],
identity: Box::new(tsclientlib::Identity::create()),
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
});
// After the first wait: about 1 s.
quietly_until(&mut rx, session, Duration::from_secs(3), "observing", observing(session))
@@ -932,6 +946,45 @@ async fn a_refused_login_ends_observing() {
assert_eq!(gw.logins(), 1);
}
/// An identity that cannot be read will not be better tomorrow: like a refused
/// login, observing ends, and the gateway is not even asked.
#[tokio::test(flavor = "multi_thread")]
async fn an_identity_that_cannot_be_read_ends_observing_without_a_login() {
let gw = FakeGateway::start().await;
let engine = Engine::start();
let mut rx = engine.subscribe();
let not_an_identity = voelin_core::IdentityBlob::teamspeak("x", 0, "not an identity");
engine.send(Command::ObserveGateway {
session: 10,
urls: vec![gw.url.clone()],
identity: Box::new(not_an_identity),
});
wait(&mut rx, "connecting", |e| match e {
Event::State { session: 10, state } if state.observe == ObserveState::Connecting => {
Some(())
}
_ => None,
})
.await;
wait(&mut rx, "observing off", |e| match e {
Event::State { session: 10, state } if state.observe == ObserveState::Off => Some(()),
_ => None,
})
.await;
tokio::time::sleep(Duration::from_millis(500)).await;
assert_eq!(gw.logins(), 0);
// The public entry refuses it the same way.
let error = voelin_core::gateway::connect(
&gw.url,
&voelin_core::IdentityBlob::new("voelin", "x", 0, "{}"),
)
.await
.err()
.expect("a refusal");
assert_eq!(error.code(), Some(ErrorCode::AuthFailed), "{error}");
assert_eq!(gw.logins(), 0);
}
/// Selecting the server again while its gateway is still connecting does
/// not start it over, and ends the wait for the next attempt.
#[tokio::test(flavor = "multi_thread")]
@@ -944,7 +997,7 @@ async fn asking_again_while_connecting_tries_at_once() {
let ask = || Command::ObserveGateway {
session: 9,
urls: vec![gw.url.clone()],
identity: Box::new(identity.clone()),
identity: Box::new(to_blob(&identity)),
};
engine.send(ask());
// Three logins fail (waits of about 1 and 2 s); the next wait is about 5 s.
+40 -2
View File
@@ -1,17 +1,33 @@
//! Engine against the development servers (dev/docker-compose.yml).
//! Runs only with `VOELIN_LIVE=1`; `scripts/it-smoke.sh` sets it.
use std::sync::LazyLock;
use std::time::Duration;
use tokio::sync::RwLock;
use tokio::sync::broadcast::Receiver;
use tokio::time::{Instant, timeout_at};
use voelin_core::{Command, Engine, Event, ObserveState, Source, VoiceOptions, VoiceState};
use voelin_core::{
Command, Engine, Event, ObserveState, QueryLogin, QueryTransport, Source, VoiceOptions,
VoiceState,
};
use voelin_model::ChatTarget;
fn live() -> bool {
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
}
/// The TeamSpeak 6 server's banners are the server's, and `ts6_banners` sets and
/// unsets them there. While it does, whatever else connects to the server is
/// told the addresses of those banners, and an engine fetches what it is told
/// (as it should): the requests of such an engine reached the HTTP server of
/// `ts6_banners`, which counts the requests of the engine under test, and the
/// test failed on `disabled policy must prevent HTTP requests` in every run
/// that had the tests of this file run side by side (as they do). The tests
/// that connect to the server hold this shared, `ts6_banners` exclusively: it
/// runs with the server to itself, and the others before or after it.
static TS6: LazyLock<RwLock<()>> = LazyLock::new(|| RwLock::new(()));
/// Wait for an event matching `f`, failing after 20 s.
async fn wait_for(
rx: &mut Receiver<Event>,
@@ -45,7 +61,7 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) {
.await;
// Session 2: invisible, through own query credentials.
engine.send(Command::ObserveQuery { session: 2, connect: Box::new(query) });
engine.send(Command::ObserveQuery { session: 2, connect: Box::new(login(&query)) });
let (mut observing, mut sees_voice_client) = (false, false);
wait_for(&mut events, "query presence with the voice client", |e| {
match e {
@@ -93,6 +109,24 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) {
tokio::time::sleep(Duration::from_millis(500)).await;
}
/// The credentials of a query connection, as the engine takes them.
fn login(connect: &voelin_query::Connect) -> QueryLogin {
QueryLogin {
transport: match connect.transport {
voelin_query::Transport::Raw => QueryTransport::Raw,
voelin_query::Transport::Ssh => QueryTransport::Ssh,
voelin_query::Transport::Http => QueryTransport::Http,
},
address: connect.addr.clone(),
user: connect.user.clone(),
secret: connect.secret.clone(),
server_port: connect.server_port,
server_id: connect.server_id,
// The development servers allowlist their clients.
allowlisted: connect.line.rate_limit.is_none(),
}
}
fn query(transport: voelin_query::Transport, addr: &str) -> voelin_query::Connect {
voelin_query::Connect {
transport,
@@ -110,6 +144,7 @@ async fn ts6_engine() {
if !live() {
return;
}
let _server = TS6.read().await;
engine_roundtrip("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022"))
.await;
}
@@ -237,6 +272,7 @@ async fn ts6_channel_joins() {
if !live() {
return;
}
let _server = TS6.read().await;
channel_joins("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022")).await;
}
@@ -308,6 +344,7 @@ async fn ts6_banners() {
if !live() {
return;
}
let _server = TS6.write().await;
let voice_addr =
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
let query_addr =
@@ -491,6 +528,7 @@ async fn ts6_avatars() {
if !live() {
return;
}
let _server = TS6.read().await;
let voice_addr =
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
let dir = std::env::temp_dir().join(format!("voelin-live-avatars-{}", std::process::id()));
@@ -0,0 +1,124 @@
//! The engine on a `voelin_proto::link::Session` that no TeamSpeak code
//! made: `Engine::start_with_backends` takes the connector registry, and the
//! scheme of a session's address picks the connector. The fake host of the
//! protocol repository stands for a Voelin host here (the fuller tests of the
//! seam on the fake host come with the next slice of
//! `docs/session-seam.md`).
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::broadcast;
use voelin_core::settings::Settings;
use voelin_core::{
Backends, Command, Engine, Event, History, SessionState, VoiceOptions, VoiceState,
};
use voelin_proto::test_util::FakeConnector;
use voelin_proto::v1::{self, entity::Kind};
const SESSION: u64 = 1;
async fn next<T>(
events: &mut broadcast::Receiver<Event>,
mut f: impl FnMut(Event) -> Option<T>,
) -> T {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
if let Some(t) = f(events.recv().await.expect("engine events")) {
return t;
}
}
})
.await
.expect("an event in time")
}
fn host_with_two_channels(connector: &FakeConnector) {
let host = connector.host();
let put = |kind: Kind| host.put(v1::Entity { kind: Some(kind) }).unwrap();
put(Kind::Server(v1::Server {
id: 1,
name: "Fake Host".into(),
uid: "fake-host".into(),
default_channel_id: 10,
..Default::default()
}));
for (id, name, position) in [(10, "Lobby", 0), (11, "Games", 1024)] {
put(Kind::Channel(v1::Channel {
id,
server_id: 1,
kind: v1::ChannelKind::Voice as i32,
name: name.into(),
position,
..Default::default()
}));
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_session_of_a_registered_connector_is_the_engines_voice_source() {
let connector = FakeConnector::new();
host_with_two_channels(&connector);
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
let engine = Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
let mut events = engine.subscribe();
engine.send(Command::ConnectVoice {
session: SESSION,
options: Box::new(VoiceOptions::new("fake://host", "tester")),
});
let (name, backend) = next(&mut events, |e| match e {
Event::ServerInfo { name, backend, .. } => Some((name, backend)),
_ => None,
})
.await;
assert_eq!((name.as_str(), backend.product.as_str()), ("Fake Host", "voelin-fake"));
let presence = next(&mut events, |e| match e {
Event::Presence { presence, .. } if !presence.channels.is_empty() => Some(presence),
_ => None,
})
.await;
let channels: Vec<_> =
presence.channels.values().map(|c| (c.id, c.name.as_str(), c.order)).collect();
assert_eq!(channels, [(10, "Lobby", 0), (11, "Games", 10)]);
// The host was asked once, with the nickname and the TeamSpeak-shaped
// credential the engine makes of its options for now.
let connects = connector.connects();
assert_eq!(connects.len(), 1);
assert_eq!(connects[0].address, "fake://host");
assert_eq!(connects[0].hello.nickname, "tester");
// A move is a request to the host; the host's voice state is where we are.
engine.send(Command::MoveToChannel { session: SESSION, channel: 11, password: None });
let state: SessionState = next(&mut events, |e| match e {
Event::State { state, .. } if state.own_channel == Some(11) => Some(state),
_ => None,
})
.await;
assert_eq!(state.voice, VoiceState::Connected);
engine.send(Command::DisconnectVoice { session: SESSION });
next(&mut events, |e| match e {
Event::State { state, .. } if state.voice == VoiceState::Disconnected => Some(()),
_ => None,
})
.await;
}
#[tokio::test(flavor = "multi_thread")]
async fn an_address_no_connector_serves_fails_with_the_registry_s_words() {
let engine =
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), Backends::empty());
let mut events = engine.subscribe();
engine.send(Command::ConnectVoice {
session: SESSION,
options: Box::new(VoiceOptions::new("voelin://host/i/code", "tester")),
});
let error = next(&mut events, |e| match e {
Event::Error { message, .. } => Some(message),
_ => None,
})
.await;
assert_eq!(error, "voice: no connector for voelin://host/i/code");
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -167,7 +167,7 @@ async fn ts6_stream_between_sessions() {
Event::StreamViewers { session: 1, viewers }
if viewers
.iter()
.any(|v| v.client.0 == viewer && v.state == ViewerState::Connected) =>
.any(|v| v.client == viewer && v.state == ViewerState::Connected) =>
{
Some(())
}
@@ -10,6 +10,10 @@ use voelin_core::settings::Settings;
use voelin_core::{Command, Contact, DownloadTo, Engine, Event, History, Relation, TransferState};
use voelin_model::FileRef;
mod common;
use common::closed;
async fn next<T>(rx: &mut broadcast::Receiver<Event>, mut f: impl FnMut(Event) -> Option<T>) -> T {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
@@ -165,6 +169,7 @@ async fn contacts_are_kept_in_the_database() {
engine.history().flush();
}
// A new engine attaches the database later: the contacts come back.
closed(&path).await;
let engine = Engine::start();
let mut rx = engine.subscribe();
engine.send(Command::AttachHistory(History::open(&path).unwrap()));
+1 -1
View File
@@ -24,7 +24,7 @@ tokio = { version = "1", features = ["macros", "net", "rt", "sync"], optional =
# TLS (`wss://`, as gateways run behind a proxy) with the system's
# certificates; rustls and its crates are in the tree already (reqwest).
tokio-tungstenite = { version = "0.30", optional = true, features = ["rustls-tls-native-roots"] }
voelin-model = { path = "../voelin-model" }
voelin-model = { workspace = true }
tsproto-types = { path = "../proto/tsproto-types" }
[lints]
+1 -1
View File
@@ -29,7 +29,7 @@ toml = "1.1.6"
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
voelin-model = { path = "../voelin-model" }
voelin-model = { workspace = true }
voelin-observer = { path = "../voelin-observer" }
voelin-query = { path = "../voelin-query" }
+24 -4
View File
@@ -1,14 +1,34 @@
# Build: docker build -f crates/voelin-gateway/Dockerfile -t tsgw .
# syntax=docker/dockerfile:1
# Build: docker build --ssh default -f crates/voelin-gateway/Dockerfile -t tsgw .
# (--ssh default hands the build your ssh-agent, which must hold a key that
# can read the private VoelinProtocol repository: docs/building.md,
# "Depending on VoelinProtocol". The gateway itself does not use it, but
# Cargo resolves the whole workspace, which includes voelin-identity.)
# Run: docker run -d --name tsgw --init --restart unless-stopped \
# -v ./tsgw.toml:/etc/tsgw/tsgw.toml:ro -v tsgw-data:/var/lib/tsgw \
# -e TSGW_QUERY_PASSWORD=… -p 7788:7788 tsgw
# Logs: docker logs -f tsgw (more: -e TSGW_LOG_LEVEL=debug; also to a file in
# the volume: -e TSGW_LOG_FILE=logs/tsgw.log). See docs/gateway-admin.md.
FROM rust:1.94-bookworm AS build
FROM rust:1.95-bookworm AS build
WORKDIR /src
RUN apt-get update && apt-get install -y --no-install-recommends cmake libasound2-dev && rm -rf /var/lib/apt/lists/*
RUN apt-get update && apt-get install -y --no-install-recommends cmake git libasound2-dev openssh-client && rm -rf /var/lib/apt/lists/*
# voelin-identity comes from the private VoelinProtocol repository, fetched
# over SSH by Cargo through the system git, with the agent that
# `docker build --ssh default` forwards (scripts/docker-build.sh passes it):
# the key stays in the agent and never reaches a layer. The host key is the
# reviewed line from .gitea/known_hosts. Cargo resolves the whole workspace, so
# the first cargo command needs this, although this crate does not use
# voelin-identity: the `cargo fetch` below, the only step that is given the agent.
COPY .gitea/known_hosts /etc/ssh/ssh_known_hosts
ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
COPY . .
RUN cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
# Only this step is given the agent, and it only fetches: no build script,
# procedural macro or test of the workspace runs in it. The build below has no
# ssh mount (so no agent socket and no key in reach of the code it compiles and
# runs) and is --offline, so it uses what this step fetched or fails.
RUN --mount=type=ssh,required=true \
cargo fetch --locked
RUN cargo build --release --locked --offline -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
FROM gcr.io/distroless/cc-debian12:nonroot
COPY --from=build /tsgw /usr/local/bin/tsgw
+57
View File
@@ -0,0 +1,57 @@
[package]
name = "voelin-gpui"
version = "0.0.1-alpha"
description = "The GPUI front end of the desktop app, under construction: it runs on the same engine as the Slint front end (voelin-ui) until it reaches parity."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[lib]
name = "voelin_gpui"
path = "src/lib.rs"
[[bin]]
name = "voelin-gpui"
path = "src/main.rs"
[dependencies]
anyhow = "1.0.104"
# GPUI, gpui-component and gpui-kit-assets behind one pinned dependency.
gpui-kit = { workspace = true }
# The engine's runtime and the channel of its events (a tokio receiver needs no
# reactor, so GPUI's executor can await it); `macros` for the hotkey task's
# `select!`.
tokio = { version = "1.53.1", features = ["macros", "rt-multi-thread", "sync", "time"] }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
# The TeamSpeak identity a connection is made with (the store hands it out).
tsclientlib = { path = "../proto/tsclientlib" }
# The engine, with the desktop's capture and codecs: ashpd on async-io (the
# commit that moved voelin-media and voelin-platform to it) lets this binary
# hold both the portals and gpui-kit.
voelin-core = { path = "../voelin-core", default-features = false, features = ["audio-device", "media-desktop"] }
# The app's name and id, the hotkeys and portals of the slices to come.
voelin-platform = { path = "../voelin-platform" }
# The client's database (bookmarks, identities, settings, chat reads) and the
# secrets: the OS keyring, as the Slint front end keeps them.
voelin-store = { path = "../voelin-store", features = ["keyring"] }
# The view models and the state, shared with the Slint front end.
voelin-ui-vm = { path = "../voelin-ui-vm" }
# The meter reads /proc/self (CPU ticks per second, the page size).
[target.'cfg(target_os = "linux")'.dependencies]
rustix = { version = "1.1.5", features = ["param"] }
[dev-dependencies]
# GPUI's test platform (`#[gpui::test]`, `TestAppContext`): the front end's tests
# need no display. gpui-kit's own `test-support` feature is not used: it names
# the optional `gpui-fast` backend in weak features, which puts gpui-fast and
# its tree into Cargo.lock and pins taffy to 0.15.0 for every build. gpui-kit
# pins `gpui-pre` exactly, so this line moves with its `=` pin (a mismatch does
# not resolve).
gpui = { package = "gpui-pre", version = "=0.3.10", features = ["test-support"] }
[lints]
workspace = true
+34
View File
@@ -0,0 +1,34 @@
//! Embeds the client's Lucide icons: `crates/voelin-ui/ui/assets/icons/*.svg`
//! (Lucide 1.48, the set the Slint front end draws) become a sorted table of
//! `include_bytes!` in `$OUT_DIR/icons.rs`, which `assets.rs` serves as
//! gpui-component's `icons/<name>.svg` paths before gpui-kit-assets' own
//! (Lucide 1.43) catalogue. No dependency: the directory is read and the
//! table written with `std`.
use std::fmt::Write as _;
use std::path::PathBuf;
fn main() {
let manifest =
PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
let dir = manifest.join("../voelin-ui/ui/assets/icons");
println!("cargo:rerun-if-changed={}", dir.display());
let mut names: Vec<String> = std::fs::read_dir(&dir)
.unwrap_or_else(|e| panic!("the client's icons are at {}: {e}", dir.display()))
.filter_map(|entry| entry.ok()?.file_name().into_string().ok())
.filter(|name| name.ends_with(".svg"))
.collect();
names.sort();
assert!(!names.is_empty(), "no icons in {}", dir.display());
let mut table = String::from(
"/// The client's icons by file name, sorted.\npub static ICONS: &[(&str, &[u8])] = &[\n",
);
for name in &names {
let path = dir.join(name);
let path = path.canonicalize().unwrap_or(path);
let _ = writeln!(table, "\t({name:?}, include_bytes!({:?})),", path.display().to_string());
}
table.push_str("];\n");
let out = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR")).join("icons.rs");
std::fs::write(out, table).expect("write icons.rs");
}
File diff suppressed because it is too large. Load diff
+85
View File
@@ -0,0 +1,85 @@
//! What `svg()` and gpui-component's `Icon` load by path. The client's own
//! Lucide 1.48 icons (the 147 SVGs of the Slint front end, embedded by
//! `build.rs`) answer `icons/<name>.svg` first, so every widget draws the
//! icons the client draws; anything else (the rest of gpui-kit-assets'
//! Lucide 1.43 catalogue, which gpui-component's `IconName` names) comes from
//! gpui-kit-assets.
use std::borrow::Cow;
use gpui_kit::{AssetSource, Result, SharedString};
include!(concat!(env!("OUT_DIR"), "/icons.rs"));
/// The client's icons first, then gpui-kit-assets'.
#[derive(Clone, Copy, Debug, Default)]
pub struct Assets;
/// The client's icon of a file name (`mic.svg`), if it has one.
pub fn client_icon(name: &str) -> Option<&'static [u8]> {
ICONS.binary_search_by_key(&name, |(n, _)| n).ok().map(|i| ICONS[i].1)
}
/// The names of the client's icons, sorted.
pub fn client_icon_names() -> impl Iterator<Item = &'static str> {
ICONS.iter().map(|(name, _)| *name)
}
/// The app's mark, the Slint front end's `logo.svg`.
const LOGO: &[u8] = include_bytes!("../../voelin-ui/ui/assets/logo.svg");
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
if let Some(bytes) = path.strip_prefix("icons/").and_then(client_icon) {
return Ok(Some(Cow::Borrowed(bytes)));
}
if path == "logo.svg" {
return Ok(Some(Cow::Borrowed(LOGO)));
}
gpui_kit::assets::AllAssets.load(path)
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
gpui_kit::assets::AllAssets.list(path)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_client_set_is_embedded_and_sorted() {
assert!(ICONS.len() >= 140, "{} icons", ICONS.len());
assert!(ICONS.windows(2).all(|pair| pair[0].0 < pair[1].0));
for (name, bytes) in ICONS {
assert!(std::str::from_utf8(bytes).is_ok_and(|text| text.contains("<svg")), "{name}");
}
}
#[test]
fn the_client_icon_answers_before_gpui_kit_assets() {
let name = client_icon_names().find(|n| *n == "mic.svg").expect("the client has a mic");
let ours = client_icon(name).unwrap();
let kit = gpui_kit::assets::AllAssets
.load(&format!("icons/{name}"))
.unwrap()
.expect("gpui-kit-assets has a mic too");
let served = Assets.load(&format!("icons/{name}")).unwrap().unwrap();
assert_eq!(&*served, ours);
assert_ne!(&*kit, ours, "Lucide 1.43 and 1.48 draw it differently, or this test is moot");
}
#[test]
fn other_icons_and_other_paths_fall_through_to_gpui_kit_assets() {
let kit = gpui_kit::assets::AllAssets.list("icons/").unwrap();
let only_in_kit = kit
.iter()
.find(|path| client_icon(path.trim_start_matches("icons/")).is_none())
.expect("the catalogue has icons the client lacks");
assert!(Assets.load(only_in_kit).unwrap().is_some(), "{only_in_kit}");
// gpui-kit-assets answers a path it does not have with an error, so do we.
assert!(Assets.load("icons/no-such-icon.svg").is_err());
assert!(Assets.load("nothing/here").is_err());
}
}
+264
View File
@@ -0,0 +1,264 @@
//! What the window keeps besides the engine and the state, and opens at start
//! as the Slint front end's `run()` does (`crates/voelin-ui/src/app.rs`): the
//! client's database (the bookmarks, the identities, the chats' read marks),
//! the settings service on the same file, the secrets, and the identity a
//! connection is made with. The directory is the platform's data directory
//! (`voelin_platform::paths::data_dir`, which `VOELIN_DATA_DIR` overrides, so
//! that the two front ends share the store); everything below [`Backend::open`]
//! takes the directory, so that no test reaches the user's own.
//!
//! Left out against the Slint front end: importing the identities of the
//! official TeamSpeak clients at start (it reads the user's own files; the
//! slice with the identities page brings it), the crash reports and the
//! configuration of `--set` on the command line.
use std::path::{Path, PathBuf};
use anyhow::{Context as _, Result};
use tracing::warn;
use tsclientlib::Identity;
use voelin_core::settings::{AUDIO, Settings};
use voelin_core::{AudioSettings, Command, Engine, History, IdentityBlob};
use voelin_store::{Bookmark, IdentityOrigin, MemorySecrets, Secrets, Store};
use voelin_ui_vm::servers::logic::CREATED_IDENTITY;
use voelin_ui_vm::settings::{
CLIENT_PLAYBACK, ClientPlaybackMap, UI, UI_TREE, UI_WINDOW, UiSettings,
};
/// The client's database, its settings and its secrets.
pub struct Backend {
/// The bookmarks, the identities and the chats' read marks.
pub store: Store,
/// The settings service, on the same file as the store (its own
/// connection); shared with the engine once [`Backend::attach`] ran.
pub prefs: Settings,
/// The servers' passwords.
pub secrets: Box<dyn Secrets>,
/// The identity of a server whose bookmark names none that exists, and
/// the store has no default for.
identity: Identity,
/// The database file, for the engine's chat history.
database: Option<PathBuf>,
}
/// What the store and the settings hold at start, for the state.
#[derive(Debug)]
pub struct Loaded {
/// The saved servers, in the rail's order.
pub bookmarks: Vec<Bookmark>,
/// The UI's own settings (the `ui` key).
pub settings: UiSettings,
/// The audio settings.
pub audio: AudioSettings,
/// The clients' local volumes.
pub playback: ClientPlaybackMap,
}
/// The data directory of this process: `VOELIN_DATA_DIR`, else the platform's.
pub fn data_dir() -> PathBuf {
voelin_platform::paths::data_dir()
}
/// The settings service on the client database in `dir`
/// ([`voelin_ui_vm::settings::open_settings`], which the Slint front end opens
/// the same way): the UI's keys and this front end's own, then a config file
/// (`VOELIN_CONFIG`, else `<dir>/config.toml` if it exists) and
/// `VOELIN_SETTING_*` variables below the stored values. Without the database
/// the settings live in memory.
fn open_settings(dir: &Path) -> Settings {
voelin_ui_vm::settings::open_settings(dir, &[], register_own_keys)
}
/// The keys that only this front end uses: where the window was
/// (`ui.window`) and what the channel trees remember (`ui.tree`).
fn register_own_keys(prefs: &Settings) {
prefs.register(&UI_WINDOW);
prefs.register(&UI_TREE);
}
impl Backend {
/// Open the database in `dir` (created if need be), its settings and the
/// default identity (made, and kept, when the store has none). `secrets`
/// are where passwords go.
pub fn open(dir: &Path, secrets: Box<dyn Secrets>) -> Result<Self> {
let database = dir.join("client.db");
let store = Store::open(&database).context("failed to open the client database")?;
let prefs = open_settings(dir);
let identity = match store.default_identity()? {
Some(entry) => store.identity(entry.id)?,
None => {
let identity = Identity::create();
store.add_identity(CREATED_IDENTITY, &identity, IdentityOrigin::Created)?;
identity
}
};
Ok(Self { store, prefs, secrets, identity, database: Some(database) })
}
/// A backend that stores nothing and keeps its secrets in memory, with a
/// fresh identity: the tests', and the sample data's.
pub fn in_memory() -> Result<Self> {
let prefs = Settings::in_memory();
voelin_ui_vm::settings::register_keys(&prefs);
register_own_keys(&prefs);
Ok(Self {
store: Store::open_in_memory()?,
prefs,
secrets: Box::new(MemorySecrets::default()),
identity: Identity::create(),
database: None,
})
}
/// What the store and the settings hold now.
pub fn load(&self) -> Loaded {
Loaded {
bookmarks: self.store.bookmarks().unwrap_or_else(|e| {
warn!(%e, "the bookmarks cannot be read");
Vec::new()
}),
settings: (*self.prefs.get_arc(&UI)).clone(),
audio: self.prefs.get(&AUDIO),
playback: self.prefs.get(&CLIENT_PLAYBACK),
}
}
/// Hand the engine what it keeps for the window: the chat history in the
/// same database (without it the engine keeps chats for this run only),
/// the settings service and the audio settings.
pub fn attach(&self, engine: &Engine) {
if let Some(database) = &self.database {
match History::open(database) {
Ok(history) => engine.send(Command::AttachHistory(history)),
Err(e) => warn!(%e, "chat history is not stored this time"),
}
}
engine.send(Command::AttachSettings(self.prefs.clone()));
engine.send(Command::SetAudioSettings(Box::new(self.prefs.get(&AUDIO))));
}
/// The identity a connection to the bookmark `bookmark` uses: its own if
/// it names one the store has, else the store's default, else the one made
/// at start ([`Store::identity_for`]).
pub fn identity_for(&self, bookmark: Option<&Bookmark>) -> Identity {
self.store.identity_for(bookmark.and_then(|b| b.identity), &self.identity)
}
/// The identity of [`Backend::identity_for`] as the engine takes it, for a
/// bookmark that names the identity `named`.
pub fn identity_blob(&self, named: Option<i64>) -> IdentityBlob {
voelin_core::ts::identity::to_blob(&self.store.identity_for(named, &self.identity))
}
/// Write what the settings service holds to the database.
pub fn flush(&self) {
if let Err(e) = self.prefs.flush() {
warn!(%e, "could not store settings");
}
}
}
/// The secrets of this run: the OS keyring, and memory for what the keyring
/// refuses (no Secret Service on a headless Linux); the sample data's never
/// reach the keyring.
pub fn default_secrets(demo: bool) -> Box<dyn Secrets> {
if demo {
Box::new(MemorySecrets::default())
} else {
Box::new(voelin_store::FallbackSecrets::new("voelin"))
}
}
/// What the tests of this crate need to open a store of their own.
#[cfg(test)]
pub(crate) mod testing {
use std::path::PathBuf;
/// A directory of its own under the temporary one (`TMPDIR`), removed with
/// the guard: no test reaches the user's data directory.
pub(crate) struct TempDir(pub PathBuf);
impl TempDir {
/// An empty directory path named `name` and this process.
pub(crate) fn new(name: &str) -> Self {
let dir =
std::env::temp_dir().join(format!("voelin-gpui-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
Self(dir)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
}
#[cfg(test)]
mod tests {
use voelin_ui_vm::settings::WindowState;
use super::testing::TempDir;
use super::*;
fn bookmark(name: &str, address: &str) -> Bookmark {
Bookmark { name: name.into(), address: address.into(), ..Default::default() }
}
/// What a run leaves in the directory is what the next one starts from: the
/// bookmarks, the identity (the same one, not a new one) and the settings.
#[test]
fn a_second_start_finds_what_the_first_kept() {
let dir = TempDir::new("backend");
let first = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap();
assert_eq!(first.load().bookmarks, Vec::new(), "a new store has no servers");
let id = first.store.add_bookmark(&bookmark("Nightfall", "ts.example")).unwrap();
let uid = first.identity_for(None).key().to_pub().get_uid();
let window = WindowState { width: 1000, height: 700, x: None, y: None, maximized: false };
first.prefs.set(&UI_WINDOW, Some(window)).unwrap();
first.flush();
drop(first);
let second = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap();
let loaded = second.load();
assert_eq!(
loaded.bookmarks.iter().map(|b| (b.id, b.name.as_str())).collect::<Vec<_>>(),
[(id, "Nightfall")]
);
assert_eq!(second.identity_for(None).key().to_pub().get_uid(), uid, "the identity is kept");
assert_eq!(second.prefs.get(&UI_WINDOW), Some(window));
assert!(dir.0.join("client.db").is_file(), "the database is in the directory given");
}
/// A new server's nickname is the default identity's (one imported from
/// TeamSpeak keeps the nickname used there), not the name the app gave the
/// identity it made.
#[test]
fn a_new_servers_nickname_is_the_default_identitys_unless_the_app_named_it() {
use voelin_ui_vm::servers::sequence::default_nickname;
let backend = Backend::in_memory().unwrap();
let made = Identity::create();
backend.store.add_identity(CREATED_IDENTITY, &made, IdentityOrigin::Created).unwrap();
let nickname = default_nickname(&backend.store);
assert!(nickname != CREATED_IDENTITY && !nickname.trim().is_empty(), "{nickname}");
let imported =
backend.store.add_identity("Nova", &Identity::create(), IdentityOrigin::Imported);
backend.store.set_default_identity(imported.unwrap(), false).unwrap();
assert_eq!(default_nickname(&backend.store), "Nova");
}
#[test]
fn a_server_names_its_identity_and_the_default_serves_the_rest() {
let backend = Backend::in_memory().unwrap();
let (default, alt) = (Identity::create(), Identity::create());
let uid = |identity: &Identity| identity.key().to_pub().get_uid();
backend.store.add_identity("Default", &default, IdentityOrigin::Created).unwrap();
let alt_id = backend.store.add_identity("Alt", &alt, IdentityOrigin::Created).unwrap();
assert_eq!(uid(&backend.identity_for(None)), uid(&default), "the first is the default");
let named = Bookmark { identity: Some(alt_id), ..bookmark("a", "a.test") };
assert_eq!(uid(&backend.identity_for(Some(&named))), uid(&alt));
let gone = Bookmark { identity: Some(alt_id + 100), ..bookmark("b", "b.test") };
assert_eq!(uid(&backend.identity_for(Some(&gone))), uid(&default));
}
}
+222
View File
@@ -0,0 +1,222 @@
//! The development switches of the GPUI front end, read from the
//! environment. They are the Slint front end's (docs/ui.md, "Development
//! switches and screenshots") where the GPUI one has the same thing to
//! switch, so that one recipe serves both; the rest are new.
//!
//! - `VOELIN_OPEN=swatch`: the swatch page (every theme token, a few
//! components, the icons) in place of the shell. The Slint front end's
//! other pages do not exist here yet; they are named in a warning and
//! skipped.
//! - `VOELIN_OPEN=voice` (`voice:compact`): the voice channel page on screen
//! once voice is connected, in place of the server page; `voice:compact`
//! with the smaller stage, which is not stored.
//! - `VOELIN_DEMO_UI=1`: the Slint front end's sample servers, shown through
//! the app's own events, with their pictures as files of a folder in the
//! temporary directory (removed when the window closes); nothing is sent to
//! the engine or kept in the store.
//! - `VOELIN_DEMO_SERVER=2`: with `VOELIN_DEMO_UI`, the sample server on
//! screen, counting from 0 (the first, which is connected and populated, is
//! the default; the second is observed, the third not connected).
//! - `VOELIN_DEMO_TALK=10`: with `VOELIN_DEMO_UI`, one of the sample people
//! starts and stops talking this many times a second, through the app's own
//! events (what the meter measures while someone talks).
//! - `VOELIN_DEV_THEME=dark|light|system`: the theme mode, in place of the
//! one the settings give (`ui.theme`).
//! - `VOELIN_FONT_SCALE=1.25`: the text size factor, in place of the
//! settings' (`ui.font_scale`).
//! - `VOELIN_WINDOW_SIZE=1440x960`: the window's size, in place of the
//! remembered one (`ui.window`), which it then leaves alone.
//! - `VOELIN_METER=1`: the cost meter, one log line a second
//! ([`crate::meter`]).
use crate::theme::Choice;
/// A page the window can be opened on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Page {
/// The desktop shell.
Shell,
/// Every theme token, a few components and the icons.
Swatch,
}
/// What the environment switched.
#[derive(Clone, Debug, PartialEq)]
pub struct Switches {
/// The page to open on.
pub open: Page,
/// The voice channel page is asked for (`VOELIN_OPEN=voice`): it shows
/// once voice is connected.
pub voice: bool,
/// With the voice page, the smaller stage, as the switch says (it is not
/// stored, as the Slint front end's `voice:compact`).
pub voice_compact: bool,
/// Show the sample servers instead of the stored ones.
pub demo_ui: bool,
/// Write the sample servers' pictures to a folder of the temporary
/// directory and deliver them: what the binary does with the sample
/// servers, and what a test asks for by name (a test that does not leaves
/// nothing behind).
pub demo_pictures: bool,
/// The sample server to show, by its place in the list, when the switch
/// names one.
pub demo_server: Option<usize>,
/// How many times a second a sample person starts or stops talking (with
/// the sample servers), when the switch names a rate.
pub demo_talk: Option<f32>,
/// The theme mode, when the switch names one.
pub theme: Option<Choice>,
/// The text size factor, when the switch names one.
pub font_scale: Option<f32>,
/// The window's size in pixels, when the switch names one.
pub window: Option<(f32, f32)>,
/// Log the cost meter.
pub meter: bool,
}
impl Default for Switches {
fn default() -> Self {
Self {
open: Page::Shell,
voice: false,
voice_compact: false,
demo_ui: false,
demo_pictures: false,
demo_server: None,
demo_talk: None,
theme: None,
font_scale: None,
window: None,
meter: false,
}
}
}
impl Switches {
/// The switches of this process's environment.
pub fn from_env() -> Self {
Self::parse(|name| std::env::var(name).ok())
}
/// The switches `get` answers for; what it does not understand is logged
/// and left out.
pub fn parse(get: impl Fn(&str) -> Option<String>) -> Self {
let mut switches = Self::default();
if let Some(list) = get("VOELIN_OPEN") {
for what in list.split(',').map(str::trim).filter(|w| !w.is_empty()) {
match what {
"swatch" => switches.open = Page::Swatch,
"voice" => switches.voice = true,
"voice:compact" => (switches.voice, switches.voice_compact) = (true, true),
other => tracing::warn!(
"VOELIN_OPEN={other}: this page is not in the GPUI front end yet (swatch and voice are)"
),
}
}
}
if let Some(name) = get("VOELIN_DEV_THEME") {
match Choice::parse(name.trim()) {
Some(choice) => switches.theme = Some(choice),
None => tracing::warn!("VOELIN_DEV_THEME={name}: dark, light or system"),
}
}
if let Some(text) = get("VOELIN_FONT_SCALE") {
match text.trim().parse::<f32>() {
Ok(scale) if (0.5..=3.0).contains(&scale) => switches.font_scale = Some(scale),
_ => tracing::warn!("VOELIN_FONT_SCALE={text}: a number from 0.5 to 3"),
}
}
if let Some(text) = get("VOELIN_WINDOW_SIZE") {
match parse_size(&text) {
Some(size) => switches.window = Some(size),
None => tracing::warn!("VOELIN_WINDOW_SIZE={text}: WIDTHxHEIGHT, such as 1440x960"),
}
}
if let Some(text) = get("VOELIN_DEMO_SERVER") {
match text.trim().parse::<usize>() {
Ok(place) if place < 3 => switches.demo_server = Some(place),
_ => tracing::warn!("VOELIN_DEMO_SERVER={text}: 0, 1 or 2 (a sample server)"),
}
}
if let Some(text) = get("VOELIN_DEMO_TALK") {
match text.trim().parse::<f32>() {
Ok(rate) if (0.1..=100.0).contains(&rate) => switches.demo_talk = Some(rate),
_ => tracing::warn!("VOELIN_DEMO_TALK={text}: a rate from 0.1 to 100 a second"),
}
}
let flag = |name: &str| get(name).is_some_and(|v| !matches!(v.trim(), "" | "0"));
switches.demo_ui = flag("VOELIN_DEMO_UI");
switches.demo_pictures = switches.demo_ui;
switches.meter = flag("VOELIN_METER");
switches
}
}
/// `WIDTHxHEIGHT` in pixels, at least 320 by 240 and at most 16384 each way.
fn parse_size(text: &str) -> Option<(f32, f32)> {
let (w, h) = text.trim().split_once('x')?;
let (w, h): (u32, u32) = (w.parse().ok()?, h.parse().ok()?);
((320..=16384).contains(&w) && (240..=16384).contains(&h)).then_some((w as f32, h as f32))
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::*;
fn env(pairs: &[(&str, &str)]) -> Switches {
let map: HashMap<String, String> =
pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
Switches::parse(|name| map.get(name).cloned())
}
#[test]
fn nothing_switched_is_the_shell_in_the_settings_theme() {
assert_eq!(env(&[]), Switches::default());
}
#[test]
fn every_switch_is_read() {
let s = env(&[
("VOELIN_OPEN", "swatch,voice:compact"),
("VOELIN_DEMO_UI", "1"),
("VOELIN_DEMO_SERVER", "2"),
("VOELIN_DEMO_TALK", "10"),
("VOELIN_DEV_THEME", "light"),
("VOELIN_FONT_SCALE", "1.25"),
("VOELIN_WINDOW_SIZE", "1440x960"),
("VOELIN_METER", "1"),
]);
assert_eq!(s.open, Page::Swatch);
assert!(s.voice && s.voice_compact, "the voice page, with the smaller stage");
assert!(s.demo_ui && s.demo_pictures, "the sample servers come with their pictures");
assert_eq!(s.demo_server, Some(2));
assert_eq!(s.demo_talk, Some(10.0));
assert_eq!(s.theme, Some(Choice::Light));
assert_eq!(s.font_scale, Some(1.25));
assert_eq!(s.window, Some((1440.0, 960.0)));
assert!(s.meter);
}
#[test]
fn the_voice_page_alone_has_the_larger_stage() {
let s = env(&[("VOELIN_OPEN", "voice")]);
assert_eq!((s.open, s.voice, s.voice_compact), (Page::Shell, true, false));
}
#[test]
fn what_makes_no_sense_is_left_out() {
let s = env(&[
("VOELIN_OPEN", "settings:voice,home"),
("VOELIN_DEV_THEME", "blue"),
("VOELIN_FONT_SCALE", "9"),
("VOELIN_WINDOW_SIZE", "10x10"),
("VOELIN_DEMO_UI", "0"),
("VOELIN_DEMO_SERVER", "7"),
("VOELIN_DEMO_TALK", "fast"),
("VOELIN_METER", "0"),
]);
assert_eq!(s, Switches::default());
}
}
+64
View File
@@ -0,0 +1,64 @@
//! The engine this front end runs on, the same one the Slint front end
//! hosts (`voelin_ui::HostedEngine`, `crates/voelin-ui/src/app.rs`): started
//! on a tokio runtime, its events forwarded into a channel the window reads.
//! The Slint crate cannot be a dependency here (it brings Slint in), so the
//! few lines are repeated; both go into `voelin-ui-vm` when the Slint front
//! end is retired.
use tokio::runtime::{Handle, Runtime};
use tokio::sync::{broadcast, mpsc};
use voelin_core::settings::Settings;
use voelin_core::{Backends, Engine, Event, History};
/// An engine owned by the caller of [`crate::run`].
pub struct HostedEngine {
/// The handle: commands go in through it.
pub engine: Engine,
/// The runtime the engine runs on; the window's helpers run there too.
pub runtime: Handle,
/// The engine's events for the window: first those that rebuild the
/// current state of every session, then new ones. Reading them needs no
/// reactor, so the window's foreground executor can await it.
pub events: mpsc::UnboundedReceiver<Event>,
}
impl HostedEngine {
/// A new engine on `runtime`, all of whose events go to the window.
pub fn start(runtime: &Runtime) -> Self {
Self::forward(runtime, runtime.block_on(async { Engine::start() }))
}
/// A new engine on `runtime` that connects with `backends` only, and keeps
/// nothing (settings and chat history in memory): the tests' (with
/// [`Backends::empty`] a connect ends at once, saying that no connector
/// serves the address, and touches neither the network nor the sound
/// devices).
pub fn start_with_backends(runtime: &Runtime, backends: Backends) -> Self {
Self::forward(
runtime,
runtime.block_on(async {
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends)
}),
)
}
/// Forward the events of `engine` into the channel the window reads.
fn forward(runtime: &Runtime, engine: Engine) -> Self {
let (tx, events) = mpsc::unbounded_channel();
let mut rx = engine.subscribe();
runtime.spawn(async move {
loop {
match rx.recv().await {
Ok(event) => {
if tx.send(event).is_err() {
break;
}
}
Err(broadcast::error::RecvError::Lagged(_)) => continue,
Err(_) => break,
}
}
});
Self { engine, runtime: runtime.handle().clone(), events }
}
}
+39
View File
@@ -0,0 +1,39 @@
//! Inter, the UI font, as the Slint front end bundles it
//! (`crates/voelin-ui/ui/assets/fonts`, OFL): the five files go into GPUI's
//! text system and are used by family name ([`crate::theme::FONT_FAMILY`]),
//! so nothing depends on what fontconfig finds for Latin text. Colour emoji
//! come later (the chat slice; docs/design/gpui-spikes.md, "Open choices for step 3").
use std::borrow::Cow;
use gpui_kit::App;
/// The files of the family: regular, medium, semibold, bold, italic.
const INTER: [&[u8]; 5] = [
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Regular.ttf"),
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Medium.ttf"),
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-SemiBold.ttf"),
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Bold.ttf"),
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Italic.ttf"),
];
/// Add Inter to GPUI's text system.
pub fn load(cx: &mut App) {
let fonts: Vec<Cow<'static, [u8]>> = INTER.iter().map(|bytes| Cow::Borrowed(*bytes)).collect();
if let Err(error) = cx.text_system().add_fonts(fonts) {
tracing::warn!(%error, "cannot add Inter to the text system");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_files_are_fonts() {
for bytes in INTER {
assert!(bytes.len() > 100_000, "a font file, not {} bytes", bytes.len());
assert!(matches!(&bytes[..4], [0, 1, 0, 0] | b"OTTO" | b"true"), "an sfnt header");
}
}
}
+361
View File
@@ -0,0 +1,361 @@
//! Global push-to-talk: a task owns the [`voelin_platform::HotkeyManager`] (the
//! desktop's portal on Wayland, XInput2 on X11, a hook on Windows) and reports
//! the key's presses and releases, whichever window has the focus.
//!
//! It is the Slint front end's `GlobalPtt` (`crates/voelin-ui/src/hotkey.rs`),
//! repeated here as `engine.rs` repeats `HostedEngine`: the loop needs the
//! engine's runtime and the front end's own way back to its state, and the
//! Slint crate cannot be a dependency (it brings Slint in); both go into one
//! place when the Slint front end is retired.
//!
//! **The task runs on the engine's runtime** ([`GlobalPtt::start`] spawns on
//! it), not from a foreground task of GPUI: the portal's backend calls
//! `tokio::spawn` when it is made (`voelin-platform`, `hotkey/portal.rs`), which
//! panics where no tokio runtime is current, and GPUI's executor has none.
use std::future::Future;
use tokio::runtime::Handle;
use tokio::sync::mpsc;
use voelin_platform::{BackendKind, Hotkey, HotkeyEvent, HotkeyEvents, HotkeyManager};
/// The id of the push-to-talk registration (the portal remembers the user's
/// choice by it).
const PTT_ID: &str = "push-to-talk";
/// The handle to the hotkey task.
pub struct GlobalPtt {
tx: mpsc::UnboundedSender<Option<String>>,
}
impl GlobalPtt {
/// Start the task on `runtime`. `status` gets a line that says how the key
/// stands ("Active: Ctrl+Shift+T (X11)", why it could not be registered),
/// `transmit` the key's state; both are called on the runtime, so they hand
/// over to GPUI's thread ([`crate::app::Later`]).
pub fn start(
runtime: &Handle,
status: impl Fn(String) + Send + 'static,
transmit: impl Fn(bool) + Send + 'static,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
runtime.spawn(run(rx, status, transmit));
Self { tx }
}
/// Register `key` (such as `Ctrl+Shift+T`) in place of the one registered,
/// or nothing.
pub fn set(&self, key: Option<String>) {
let _ = self.tx.send(key);
}
}
/// A stream of press and release events for one registered hotkey (`None` once
/// the desktop removes it).
trait EventStream: Send {
fn recv(&mut self) -> impl Future<Output = Option<HotkeyEvent>> + Send;
}
impl EventStream for HotkeyEvents {
fn recv(&mut self) -> impl Future<Output = Option<HotkeyEvent>> + Send {
HotkeyEvents::recv(self)
}
}
/// Registers and unregisters the global push-to-talk hotkey with the platform
/// (or a test double).
trait Registrar: Send {
type Events: EventStream;
fn register(
&mut self,
key: String,
hotkey: Hotkey,
) -> impl Future<Output = Result<(Self::Events, String), String>> + Send;
fn unregister(&mut self) -> impl Future<Output = ()> + Send;
}
/// The real platform hotkey manager, opened lazily on the first registration.
struct PlatformRegistrar {
manager: Option<HotkeyManager>,
}
impl Registrar for PlatformRegistrar {
type Events = HotkeyEvents;
async fn register(
&mut self,
key: String,
hotkey: Hotkey,
) -> Result<(Self::Events, String), String> {
if self.manager.is_none() {
match HotkeyManager::new().await {
Ok(m) => self.manager = Some(m),
Err(e) => return Err(format!("Global hotkeys are not available: {e}")),
}
}
let Some(m) = &mut self.manager else {
return Err("Global hotkeys are not available.".into());
};
match m.register(PTT_ID, "Push to talk", hotkey).await {
Ok(registered) => {
let line = match m.backend() {
BackendKind::Portal => format!(
"Registered with the desktop: {}",
m.trigger_description(PTT_ID).unwrap_or(key)
),
BackendKind::X11 => format!("Active: {hotkey} (X11)"),
BackendKind::WindowsHook => format!("Active: {hotkey}"),
};
Ok((registered, line))
}
Err(e) => Err(format!("Could not register {key}: {e}")),
}
}
async fn unregister(&mut self) {
if let Some(m) = &mut self.manager {
let _ = m.unregister(PTT_ID).await;
}
}
}
/// The next event of the registration, or never while there is none.
async fn next_event<E: EventStream>(events: &mut Option<E>) -> Option<HotkeyEvent> {
match events {
Some(events) => events.recv().await,
None => std::future::pending().await,
}
}
/// The task: a key to register (or none) arrives on `rx`, the registered key's
/// events are reported through `transmit`, and `status` says what happened.
async fn run(
rx: mpsc::UnboundedReceiver<Option<String>>,
status: impl Fn(String),
transmit: impl Fn(bool),
) {
run_loop(rx, PlatformRegistrar { manager: None }, status, transmit).await;
}
/// The event loop of [`run`], parameterised over `registrar` so the
/// fail-closed release paths are tested without a portal or display.
async fn run_loop<R: Registrar>(
mut rx: mpsc::UnboundedReceiver<Option<String>>,
mut registrar: R,
status: impl Fn(String),
transmit: impl Fn(bool),
) {
let mut events: Option<R::Events> = None;
loop {
tokio::select! {
key = rx.recv() => {
let Some(key) = key else {
// Fail closed on task exit: drop any hold that was still down.
transmit(false);
break;
};
events = None;
// Whatever was held no longer counts.
transmit(false);
registrar.unregister().await;
let Some(key) = key else {
status("Off.".into());
continue;
};
let hotkey: Hotkey = match key.parse() {
Ok(h) => h,
Err(e) => {
status(format!("{e}"));
continue;
}
};
match registrar.register(key, hotkey).await {
Ok((registered, line)) => {
events = Some(registered);
status(line);
}
Err(line) => status(line),
}
}
event = next_event(&mut events) => match event {
Some(HotkeyEvent::Pressed) => transmit(true),
Some(HotkeyEvent::Released) => transmit(false),
None => {
events = None;
// Fail closed if the desktop removes the shortcut mid-hold.
transmit(false);
status("The hotkey was removed by the desktop.".into());
}
},
}
}
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use std::time::Duration;
use super::*;
/// A channel-backed event stream for testing [`run_loop`] without a display.
struct FakeEvents(mpsc::UnboundedReceiver<HotkeyEvent>);
impl EventStream for FakeEvents {
async fn recv(&mut self) -> Option<HotkeyEvent> {
self.0.recv().await
}
}
/// A registrar that hands out a prepared [`FakeEvents`] stream once.
struct FakeRegistrar {
stream: Option<FakeEvents>,
}
impl Registrar for FakeRegistrar {
type Events = FakeEvents;
async fn register(
&mut self,
_key: String,
hotkey: Hotkey,
) -> Result<(Self::Events, String), String> {
let events = self.stream.take().ok_or_else(|| "no fake stream left".to_owned())?;
Ok((events, format!("Active: {hotkey} (test)")))
}
async fn unregister(&mut self) {}
}
/// Next recorded message from the task, bounded only against a hang.
async fn recv_log(rx: &mut mpsc::UnboundedReceiver<String>) -> String {
tokio::time::timeout(Duration::from_secs(30), rx.recv())
.await
.expect("hotkey loop timed out")
.expect("log channel closed unexpectedly")
}
/// A key that is not one is said so and registers nothing, and the held
/// state is let go first; no display or desktop is needed to say it.
#[test]
fn a_key_that_cannot_be_parsed_is_reported_and_lets_go_of_the_hold() {
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
let log = Arc::new(Mutex::new(Vec::<String>::new()));
let (said, held) = (log.clone(), log.clone());
let ptt = GlobalPtt::start(
runtime.handle(),
move |line| said.lock().unwrap().push(format!("status: {line}")),
move |on| held.lock().unwrap().push(format!("transmit: {on}")),
);
ptt.set(Some("Ctrl+Hyper+Banana".into()));
ptt.set(None);
// The task answers in order: the last answer says the end of the list.
let deadline = std::time::Instant::now() + Duration::from_secs(30);
while log.lock().unwrap().len() < 4 {
assert!(std::time::Instant::now() < deadline, "{:?}", log.lock().unwrap());
std::thread::sleep(Duration::from_millis(5));
}
let log = log.lock().unwrap().clone();
assert_eq!(log[0], "transmit: false", "{log:?}");
assert!(log[1].starts_with("status: "), "the parse error: {log:?}");
assert_eq!(log[2], "transmit: false", "{log:?}");
assert_eq!(log[3], "status: Off.", "{log:?}");
drop(ptt);
runtime.shutdown_timeout(Duration::from_secs(2));
}
/// When the desktop removes the registered hotkey while it is pressed, the
/// loop releases transmit before reporting the removal.
#[test]
fn desktop_removal_mid_hold_releases_transmit_before_reporting_status() {
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
runtime.block_on(async {
let (tx_key, rx_key) = mpsc::unbounded_channel();
let (tx_evt, rx_evt) = mpsc::unbounded_channel();
let (tx_log, mut rx_log) = mpsc::unbounded_channel();
let (said, held) = (tx_log.clone(), tx_log);
let registrar = FakeRegistrar { stream: Some(FakeEvents(rx_evt)) };
let task = tokio::spawn(run_loop(
rx_key,
registrar,
move |line| {
let _ = said.send(format!("status: {line}"));
},
move |on| {
let _ = held.send(format!("transmit: {on}"));
},
));
tx_key.send(Some("Ctrl+Shift+T".into())).unwrap();
assert_eq!(recv_log(&mut rx_log).await, "transmit: false");
assert!(recv_log(&mut rx_log).await.starts_with("status: Active: "));
tx_evt.send(HotkeyEvent::Pressed).unwrap();
assert_eq!(recv_log(&mut rx_log).await, "transmit: true");
// Desktop removes the shortcut while held.
drop(tx_evt);
assert_eq!(
recv_log(&mut rx_log).await,
"transmit: false",
"transmit must fail closed before reporting removal"
);
assert_eq!(
recv_log(&mut rx_log).await,
"status: The hotkey was removed by the desktop."
);
drop(tx_key);
tokio::time::timeout(Duration::from_secs(30), task)
.await
.expect("task exit timed out")
.unwrap();
});
}
/// When the command channel closes (task exit) while the hotkey is pressed,
/// the loop releases transmit before exiting.
#[test]
fn closing_command_channel_mid_hold_releases_transmit_before_exiting() {
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
runtime.block_on(async {
let (tx_key, rx_key) = mpsc::unbounded_channel();
let (tx_evt, rx_evt) = mpsc::unbounded_channel();
let (tx_log, mut rx_log) = mpsc::unbounded_channel();
let (said, held) = (tx_log.clone(), tx_log);
let registrar = FakeRegistrar { stream: Some(FakeEvents(rx_evt)) };
let task = tokio::spawn(run_loop(
rx_key,
registrar,
move |line| {
let _ = said.send(format!("status: {line}"));
},
move |on| {
let _ = held.send(format!("transmit: {on}"));
},
));
tx_key.send(Some("Ctrl+Shift+T".into())).unwrap();
assert_eq!(recv_log(&mut rx_log).await, "transmit: false");
assert!(recv_log(&mut rx_log).await.starts_with("status: Active: "));
tx_evt.send(HotkeyEvent::Pressed).unwrap();
assert_eq!(recv_log(&mut rx_log).await, "transmit: true");
// Keep the event stream open while the handle drops (task exit).
drop(tx_key);
tokio::time::timeout(Duration::from_secs(30), task)
.await
.expect("task exit timed out")
.unwrap();
assert_eq!(
rx_log.try_recv().ok().as_deref(),
Some("transmit: false"),
"closing rx mid-hold must release transmit before breaking"
);
drop(tx_evt);
});
}
}
+273
View File
@@ -0,0 +1,273 @@
//! The GPUI front end of the desktop app, under construction (plan section 6
//! of the migration from Slint; docs/ui.md, "The GPUI front end"). The Slint
//! front end (`voelin-ui`, the `voelin` binary) stays the app until this one
//! reaches parity; both run on the same engine.
#![warn(missing_docs)]
pub mod app;
pub mod assets;
pub mod backend;
pub mod dev;
pub mod engine;
pub mod fonts;
pub mod hotkey;
pub mod meter;
pub mod pictures;
pub mod shell;
pub mod signals;
pub mod swatch;
pub mod theme;
pub mod view;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::time::Duration;
use anyhow::{Context as _, Result};
use gpui_kit::{
App, AppContext as _, Bounds, TitlebarOptions, WindowBounds, WindowOptions, point, px, size,
};
use tracing_subscriber::{EnvFilter, fmt, prelude::*};
use voelin_ui_vm::settings::WindowState;
use crate::app::{AppState, Setup, appearance};
use crate::assets::Assets;
use crate::backend::Backend;
use crate::dev::Switches;
use crate::engine::HostedEngine;
use crate::meter::Counters;
use crate::theme::VoelinTheme;
use crate::view::MainView;
/// The smallest size the window can be given.
const MIN_SIZE: (f32, f32) = (640.0, 480.0);
/// The size of a window that has no remembered one.
const DEFAULT_SIZE: (f32, f32) = (1280.0, 800.0);
/// How long the engine gets, after the window closed, to act on the
/// `CloseSession` commands the close sent (the Slint front end waits as long):
/// its tasks run on the runtime, and shutting the runtime down drops them.
const CLOSE_GRACE: Duration = Duration::from_millis(500);
/// What the log gets without `VOELIN_LOG` or `RUST_LOG`: warnings of every
/// crate, this front end's information, and what GPUI says about the display
/// and the GPU adapter it picked (which device a run used). Two warnings are
/// left out because they are harmless: zbus's, as in the Slint front end (it
/// warns when a desktop portal's request object is gone before it reads its
/// properties), and GPUI's "failed to load font .SystemUIFont" (gpui-component
/// asks for the platform's UI font, which Linux has no name for, before the
/// theme names Inter; the text system falls back).
const LOG_FILTER: &str =
"warn,zbus=error,gpui::text_system=error,voelin_gpui=info,gpui_wgpu=info,gpui_linux=info";
/// Log to the terminal: `VOELIN_LOG`, else `RUST_LOG`, else [`LOG_FILTER`].
/// GPUI logs through the `log` crate; the subscriber carries those records.
pub fn init_logging() {
let filter = EnvFilter::try_from_env("VOELIN_LOG")
.or_else(|_| EnvFilter::try_from_default_env())
.unwrap_or_else(|_| EnvFilter::new(LOG_FILTER));
let _ = tracing_subscriber::registry()
.with(fmt::layer().with_writer(std::io::stderr).with_filter(filter))
.try_init();
}
/// Where the window opens: the size a development switch names, else the
/// remembered place if a screen still shows its corner (a monitor can have
/// gone since), else the middle of the screen at the default size. A place
/// that has no position (Wayland does not tell one) is the remembered size
/// in the middle. A window left maximized is asked for as maximized here, and
/// again by [`MainView`] once it is shown (an X11 window manager loses this
/// request: it manages a window only from its map).
fn window_bounds(switches: &Switches, remembered: Option<WindowState>, cx: &App) -> WindowBounds {
let sized = |(width, height): (f32, f32)| size(px(width), px(height));
if let Some(forced) = switches.window {
return WindowBounds::centered(sized(forced), cx);
}
let Some(state) = remembered else {
return WindowBounds::centered(sized(DEFAULT_SIZE), cx);
};
let remembered_size =
sized(((state.width as f32).max(MIN_SIZE.0), (state.height as f32).max(MIN_SIZE.1)));
let at = state.x.zip(state.y).map(|(x, y)| point(px(x as f32), px(y as f32)));
let bounds = match at {
Some(origin)
if cx.displays().iter().any(|display| {
display.bounds().intersects(&Bounds::new(origin, size(px(64.0), px(32.0))))
}) =>
{
Bounds::new(origin, remembered_size)
}
_ => Bounds::centered(None, remembered_size, cx),
};
if state.maximized { WindowBounds::Maximized(bounds) } else { WindowBounds::Windowed(bounds) }
}
/// The main window's options: titled with the app's name (and the server
/// shown), grouped by its id, opened where [`window_bounds`] says.
fn window_options(
switches: &Switches,
remembered: Option<WindowState>,
title: String,
cx: &App,
) -> WindowOptions {
WindowOptions {
titlebar: Some(TitlebarOptions { title: Some(title.into()), ..Default::default() }),
app_id: Some(voelin_platform::APP_ID.to_owned()),
window_min_size: Some(size(px(MIN_SIZE.0), px(MIN_SIZE.1))),
window_bounds: Some(window_bounds(switches, remembered, cx)),
..Default::default()
}
}
/// Open the main window on the root state; closing it leaves the servers and
/// ends the app. `closed_sessions` is set to how many sessions the close told
/// the engine to close, which [`run`] needs after GPUI's loop has ended.
fn open_main_window(
cx: &mut App,
switches: &Switches,
engine: HostedEngine,
backend: Backend,
counters: Counters,
closed_sessions: Rc<Cell<usize>>,
) -> Result<()> {
// Without a display server GPUI falls back to a headless platform, which
// opens windows that draw nothing and runs until it is stopped.
if cx.compositor_name() == "headless" {
return Err(anyhow::anyhow!(
"no display: neither DISPLAY nor WAYLAND_DISPLAY names a display server"
))
.context("cannot open the main window");
}
let HostedEngine { engine, events, .. } = engine;
let app = cx.new({
let setup = Setup {
engine: Some(engine),
events,
counters: counters.clone(),
backend,
switches: switches.clone(),
};
move |cx| AppState::new(setup, cx)
});
// The global push-to-talk key, on the engine's runtime (docs/ui.md): once the
// state exists, and never from a test of the state.
app.update(cx, |app, _| app.start_global_ptt());
let options = {
let app = app.read(cx);
window_options(switches, app.remembered_window(), app.window_title(), cx)
};
let page = switches.open;
gpui_kit::open_window(options, cx, {
let app = app.clone();
move |window, cx| {
// The window's own appearance, which may differ from the system's before
// the window exists.
VoelinTheme::set_system_appearance(cx, window.appearance());
window.on_window_should_close(cx, {
let app = app.clone();
move |_, cx| {
closed_sessions.set(app.update(cx, |app, cx| app.shutdown(cx)));
cx.quit();
true
}
});
cx.new(|cx| MainView::new(app, page, counters, window, cx))
}
})
.context("cannot open the main window")?;
Ok(())
}
/// Wait `grace` on `runtime`, so that the engine's tasks run (they send the
/// closes of the sessions) before the runtime drops them. The sleep is made
/// inside the runtime: a `Sleep` made outside it, as an argument of
/// `block_on`, panics ("there is no reactor running").
fn give_the_engine_time(runtime: &tokio::runtime::Runtime, grace: Duration) {
runtime.block_on(async move { tokio::time::sleep(grace).await });
}
/// Run the app on the current thread until its window closes.
pub fn run() -> Result<()> {
init_logging();
let switches = Switches::from_env();
tracing::info!(
version = env!("CARGO_PKG_VERSION"),
os = std::env::consts::OS,
"Voelin (GPUI) starting"
);
let counters = Counters::default();
if switches.meter {
meter::start(counters.clone());
}
// The engine runs on tokio threads of its own; the window is GPUI's.
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.context("cannot start the engine's runtime")?;
let hosted = HostedEngine::start(&runtime);
// The store and the settings, in the platform's data directory
// (`VOELIN_DATA_DIR` moves it: every run of this binary that is not the
// user's own sets it, and the XDG directories with it).
let backend = Backend::open(&backend::data_dir(), backend::default_secrets(switches.demo_ui))
.context("cannot open the client's store")?;
backend.attach(&hosted.engine);
let (theme, font_scale) = appearance(&backend.prefs, &switches);
let failure: Rc<RefCell<Option<anyhow::Error>>> = Rc::default();
let closed_sessions: Rc<Cell<usize>> = Rc::default();
gpui_kit::application().with_assets(Assets).run({
let failure = failure.clone();
let closed_sessions = closed_sessions.clone();
move |cx| {
gpui_kit::init(cx);
shell::bind_keys(cx);
fonts::load(cx);
// The mode and the text size are the settings', or a development
// switch's.
VoelinTheme::init(cx, theme, cx.window_appearance(), font_scale);
if let Err(e) =
open_main_window(cx, &switches, hosted, backend, counters, closed_sessions)
{
*failure.borrow_mut() = Some(e);
// Not `cx.quit()` here: GPUI's Linux platform runs this callback
// before it starts its event loop, and the loop forgets a stop
// asked for earlier (calloop clears its stop signal when it
// starts), so the process would stay with no window and no
// message. A task runs inside the loop.
cx.spawn(async move |cx| cx.update(|cx| cx.quit())).detach();
}
}
});
// The close told the engine to close the sessions; give its tasks time to
// send that before the runtime drops them (`shutdown_timeout` waits for
// blocking tasks only), as the Slint front end does, or ghost clients stay
// on the servers until they time out. Any other way to end the app that
// the slices add must call `AppState::shutdown` too.
if closed_sessions.get() > 0 {
give_the_engine_time(&runtime, CLOSE_GRACE);
}
runtime.shutdown_timeout(Duration::from_secs(2));
match failure.take() {
Some(e) => Err(e),
None => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The grace after a close with open sessions is a wait on the engine's
/// runtime from the GPUI thread, which is no runtime thread: it must not
/// panic, and it must wait. (The first end-to-end close against a server,
/// the first slice that opens a session, found the panic.)
#[test]
fn the_close_grace_waits_on_the_runtime_from_a_thread_that_is_none() {
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
let started = std::time::Instant::now();
give_the_engine_time(&runtime, Duration::from_millis(30));
assert!(started.elapsed() >= Duration::from_millis(30));
runtime.shutdown_timeout(Duration::from_secs(2));
}
}
+6
View File
@@ -0,0 +1,6 @@
//! `voelin-gpui`: the GPUI front end of the desktop app (docs/ui.md, "The
//! GPUI front end").
fn main() -> anyhow::Result<()> {
voelin_gpui::run()
}
+357
View File
@@ -0,0 +1,357 @@
//! What the app costs, once a second, in the log: the CPU of the process and
//! of each group of threads, the resident memory, and the app's own counters
//! (a development switch, `VOELIN_METER=1`, so that every slice can say what
//! it costs). It is `spike_common::meter` of the GPUI spikes
//! (`spikes/gpui/common/src/meter.rs`, docs/design/gpui-spikes.md) without the
//! measuring run's summary and exit, writing log lines instead of JSON.
//!
//! CPU is in percent of one core (200 means two cores busy). Threads are
//! grouped by name without a trailing number (`llvmpipe-12` becomes
//! `llvmpipe`), which tells the software renderer's share (Mesa's `llvmpipe-*`
//! threads, work a GPU would take over) from GPUI's thread, the engine's
//! runtime and the codecs. The numbers come from `/proc/self`: on other
//! systems the meter says it cannot read them and stops.
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
/// A number the app counts up (events handled, frames drawn) or sets (open
/// connections); the meter reports counters per second and gauges as they
/// are.
#[derive(Clone, Default, Debug)]
pub struct Counter(Arc<AtomicU64>);
impl Counter {
/// Add one.
pub fn incr(&self) {
self.0.fetch_add(1, Ordering::Relaxed);
}
/// Set (gauges).
pub fn set(&self, value: u64) {
self.0.store(value, Ordering::Relaxed);
}
/// The current value.
pub fn get(&self) -> u64 {
self.0.load(Ordering::Relaxed)
}
}
/// How many times each pane of the window was rendered (per second). A pane
/// is an entity of its own that the window draws again only when it was
/// notified (`Entity::cached`), or when something below it was; the figures
/// say which panes a change of the state cost.
#[derive(Clone, Default, Debug)]
pub struct Panes {
/// The server rail.
pub rail: Counter,
/// The top bar.
pub topbar: Counter,
/// The sidebar (the server card, the voice and user cards; the tree is
/// inside it).
pub sidebar: Counter,
/// The channel tree.
pub tree: Counter,
/// The main area.
pub main: Counter,
/// The members panel.
pub members: Counter,
/// The voice channel page.
pub voice: Counter,
}
impl Panes {
/// The counters with the names the meter reports them under.
pub fn named(&self) -> [(&'static str, Counter); 7] {
[
("rail", self.rail.clone()),
("topbar", self.topbar.clone()),
("sidebar", self.sidebar.clone()),
("tree", self.tree.clone()),
("main", self.main.clone()),
("members", self.members.clone()),
("voice", self.voice.clone()),
]
}
}
/// The app's own numbers the meter reports besides the process's.
#[derive(Clone, Default, Debug)]
pub struct Counters {
/// Engine events handled by the root state (per second).
pub engine_events: Counter,
/// One-second ticks of the root state (per second: 1).
pub ticks: Counter,
/// Windows drawn (frames, per second).
pub renders: Counter,
/// Renders of each pane of the window (per second).
pub panes: Panes,
/// Jobs other threads handed to the foreground through
/// [`crate::app::Later`] (per second).
pub later_jobs: Counter,
/// Voice connections that are up (a gauge).
pub connections: Counter,
}
/// CPU ticks of the process and of each thread group, and the resident
/// memory, at one moment.
#[derive(Clone, Debug)]
pub struct Snapshot {
at: Instant,
process: u64,
threads: BTreeMap<String, u64>,
rss_bytes: u64,
}
/// The size of a page of memory, for `statm`'s page counts.
#[cfg(target_os = "linux")]
fn page_size() -> u64 {
rustix::param::page_size() as u64
}
/// The size of a page of memory (Linux only matters: `/proc`).
#[cfg(not(target_os = "linux"))]
fn page_size() -> u64 {
4096
}
/// The unit of the CPU times in `stat`.
#[cfg(target_os = "linux")]
fn clock_ticks_per_second() -> u64 {
rustix::param::clock_ticks_per_second()
}
/// The unit of the CPU times in `stat` (Linux only matters: `/proc`).
#[cfg(not(target_os = "linux"))]
fn clock_ticks_per_second() -> u64 {
100
}
/// `utime + stime` and the name of a `/proc/.../stat` line.
fn ticks_of(stat: &str) -> Option<(String, u64)> {
let open = stat.find('(')?;
let close = stat.rfind(')')?;
let name = stat.get(open + 1..close)?.to_owned();
let fields: Vec<&str> = stat.get(close + 1..)?.split_whitespace().collect();
// Fields 14 and 15 of proc(5); the remainder starts at field 3.
let utime: u64 = fields.get(11)?.parse().ok()?;
let stime: u64 = fields.get(12)?.parse().ok()?;
Some((name, utime + stime))
}
/// A thread's group: its name without a trailing number or separator.
pub fn group_of(name: &str) -> String {
let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit());
let trimmed = trimmed.trim_end_matches(['-', '_', ':', ' ', '#']);
if trimmed.is_empty() { name.to_owned() } else { trimmed.to_owned() }
}
impl Snapshot {
/// Read `/proc/self` now; `None` where there is none.
pub fn now() -> Option<Self> {
let process = std::fs::read_to_string("/proc/self/stat").ok().and_then(|s| ticks_of(&s))?.1;
let mut threads = BTreeMap::new();
if let Ok(dir) = std::fs::read_dir("/proc/self/task") {
for entry in dir.flatten() {
let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else { continue };
if let Some((name, ticks)) = ticks_of(&stat) {
*threads.entry(group_of(&name)).or_insert(0) += ticks;
}
}
}
let rss_bytes = std::fs::read_to_string("/proc/self/statm")
.ok()
.and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
.map_or(0, |pages| pages * page_size());
Some(Self { at: Instant::now(), process, threads, rss_bytes })
}
/// Resident memory in MiB.
pub fn rss_mib(&self) -> f64 {
self.rss_bytes as f64 / (1024.0 * 1024.0)
}
}
/// CPU in percent of one core between two snapshots: the process's and each
/// thread group's that used any (groups that exited in between count from
/// zero).
pub fn cpu_between(a: &Snapshot, b: &Snapshot) -> (f64, BTreeMap<String, f64>) {
let hz = clock_ticks_per_second() as f64;
let secs = b.at.duration_since(a.at).as_secs_f64().max(1e-6);
let pct = |ticks: u64| ticks as f64 / hz / secs * 100.0;
let process = pct(b.process.saturating_sub(a.process));
let threads = b
.threads
.iter()
.map(|(name, &t)| (name.clone(), pct(t.saturating_sub(*a.threads.get(name).unwrap_or(&0)))))
.filter(|(_, p)| *p > 0.0)
.collect();
(process, threads)
}
/// One second of the meter as a log line: `cpu 42.0% rss 210.4 MiB threads
/// llvmpipe 31.0 main 5.0 | engine_events 0.0/s ... | connections 1`.
pub fn line(
cpu: f64,
rss_mib: f64,
threads: &BTreeMap<String, f64>,
rates: &[(&str, f64)],
gauges: &[(&str, u64)],
) -> String {
let mut text = format!("cpu {cpu:.1}% rss {rss_mib:.1} MiB");
// The busiest groups first; a thread group under 0.5 % is noise.
let mut busy: Vec<(&String, &f64)> = threads.iter().filter(|(_, p)| **p >= 0.5).collect();
busy.sort_by(|a, b| b.1.total_cmp(a.1).then_with(|| a.0.cmp(b.0)));
if !busy.is_empty() {
text.push_str(" | threads");
for (name, pct) in busy {
let _ = write!(text, " {name} {pct:.1}");
}
}
text.push_str(" |");
for (name, rate) in rates {
let _ = write!(text, " {name} {rate:.1}/s");
}
if !gauges.is_empty() {
text.push_str(" |");
for (name, value) in gauges {
let _ = write!(text, " {name} {value}");
}
}
text
}
/// Start the meter on a thread of its own: once a second, a log line (target
/// `voelin_gpui::meter`, level info) with the process's CPU and memory and
/// `counters`' rates. It ends with the process.
pub fn start(counters: Counters) {
let spawned = std::thread::Builder::new().name("voelin-meter".into()).spawn(move || {
let Some(mut last) = Snapshot::now() else {
tracing::warn!(target: "voelin_gpui::meter", "the meter reads /proc/self; there is none here");
return;
};
let rated: Vec<(&str, Counter)> = [
("engine_events", counters.engine_events.clone()),
("ticks", counters.ticks.clone()),
("renders", counters.renders.clone()),
]
.into_iter()
.chain(counters.panes.named())
.chain([("later_jobs", counters.later_jobs.clone())])
.collect();
let mut last_counts: Vec<u64> = rated.iter().map(|(_, c)| c.get()).collect();
tracing::info!(target: "voelin_gpui::meter", "meter on: one line a second (VOELIN_METER)");
loop {
std::thread::sleep(Duration::from_secs(1));
let Some(now) = Snapshot::now() else { return };
let secs = now.at.duration_since(last.at).as_secs_f64().max(1e-6);
let (cpu, threads) = cpu_between(&last, &now);
let counts: Vec<u64> = rated.iter().map(|(_, c)| c.get()).collect();
let rates: Vec<(&str, f64)> = rated
.iter()
.zip(counts.iter().zip(&last_counts))
.map(|((name, _), (c, l))| (*name, c.saturating_sub(*l) as f64 / secs))
.collect();
let gauges = [("connections", counters.connections.get())];
tracing::info!(
target: "voelin_gpui::meter",
"{}",
line(cpu, now.rss_mib(), &threads, &rates, &gauges)
);
last = now;
last_counts = counts;
}
});
if let Err(error) = spawned {
tracing::warn!(target: "voelin_gpui::meter", %error, "no meter thread");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_panes_are_counted_by_name() {
let panes = Panes::default();
panes.members.incr();
let named = panes.named();
let names: Vec<&str> = named.iter().map(|(name, _)| *name).collect();
assert_eq!(names, ["rail", "topbar", "sidebar", "tree", "main", "members", "voice"]);
let seen: Vec<u64> = named.iter().map(|(_, counter)| counter.get()).collect();
assert_eq!(seen, [0, 0, 0, 0, 0, 1, 0], "the counters are the panes' own");
}
#[test]
fn groups_drop_trailing_numbers() {
assert_eq!(group_of("llvmpipe-12"), "llvmpipe");
assert_eq!(group_of("tokio-runtime-w"), "tokio-runtime-w");
assert_eq!(group_of("voelin-meter"), "voelin-meter");
assert_eq!(group_of("1234"), "1234");
}
#[test]
fn stat_lines_parse_with_spaces_in_names() {
let line = "42 (a b) c) S 1 2 3 4 5 6 7 8 9 10 100 23 0 0 20 0 1 0 0";
assert_eq!(ticks_of(line), Some(("a b) c".to_owned(), 123)));
}
#[test]
fn the_line_names_the_busiest_threads_first_and_hides_the_idle_ones() {
let threads = BTreeMap::from([
("main".to_owned(), 5.04),
("llvmpipe".to_owned(), 310.0),
("idle".to_owned(), 0.2),
]);
let text = line(
317.0,
210.44,
&threads,
&[("engine_events", 0.0), ("renders", 59.96)],
&[("connections", 1)],
);
assert_eq!(
text,
"cpu 317.0% rss 210.4 MiB | threads llvmpipe 310.0 main 5.0 | engine_events 0.0/s renders 60.0/s | connections 1"
);
}
#[test]
fn this_process_can_be_read_on_linux() {
if !cfg!(target_os = "linux") {
return;
}
let a = Snapshot::now().expect("/proc/self");
// The kernel counts a process's CPU in ticks of 10 ms, and on a busy
// machine this thread gets a tick's worth of CPU only after a long wall
// time: burn CPU until a second reading shows the process's ticks above
// the first, and in a thread group (the process's total and a thread's
// own are rounded separately). The deadline only ends a hang
// (docs/testing/load.md); it never decides the result.
let deadline = Instant::now() + Duration::from_secs(30);
let (b, cpu) = loop {
let burn = Instant::now();
let mut x = 0u64;
while burn.elapsed() < Duration::from_millis(2) {
x = x.wrapping_mul(31).wrapping_add(7);
}
std::hint::black_box(x);
let b = Snapshot::now().expect("/proc/self");
let (cpu, threads) = cpu_between(&a, &b);
if b.process > a.process && !threads.is_empty() {
break (b, cpu);
}
assert!(
Instant::now() < deadline,
"no CPU tick showed in 30 s: {} -> {}",
a.process,
b.process
);
};
assert!(cpu > 0.0 && b.rss_mib() > 1.0, "{cpu} {}", b.rss_mib());
}
}
+205
View File
@@ -0,0 +1,205 @@
//! Pictures of the engine's cache on screen.
//!
//! The engine writes a picture that arrives again into the same file in its
//! cache (an avatar or a server icon that changed), and GPUI's `img(path)`
//! keeps what it decoded in the asset cache under the path alone, so the new
//! picture would never show. Here the key of a decoded picture is the file
//! and what the file was when the reference to it was made
//! ([`PictureKey`]: the path and the [`Stamp`] of `voelin_ui_vm::image`, its
//! length and time), so a reference made after the file changed is another
//! picture: it is decoded, and the lists that show it compare unequal and
//! draw the row again. What a changed file left in the cache (the decoded
//! copy under the old key, and the texture the atlas made of it) is dropped
//! when the engine says the file was written again
//! ([`forget_stale`], for `Update::reloaded`).
use std::collections::HashMap;
use std::future::Future;
use std::path::Path;
use std::sync::Arc;
use gpui_kit::{
App, Asset, Global, ImageAssetLoader, ImageCacheError, ImageSource, Img, RenderImage, Resource,
img,
};
use voelin_ui_vm::image::{ImageRef, ImageSource as Picture, Stamp};
/// What identifies a decoded picture: the file in the engine's cache and what
/// it was when the picture was referred to.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PictureKey {
path: Arc<Path>,
stamp: Stamp,
}
impl PictureKey {
/// The key of a reference to a file of the cache; none for no picture, a
/// picture that cannot be shown (missing or damaged: the reference's
/// size is none) and the pictures that are not files, which the slices
/// that decode them show.
pub fn of(image: &ImageRef) -> Option<Self> {
match &**image {
Picture::File { path, stamp } if image.size().width > 0 => {
Some(Self { path: Arc::from(path.as_path()), stamp: *stamp })
}
_ => None,
}
}
/// The file.
pub fn path(&self) -> &Path {
&self.path
}
}
/// Decodes the file of a [`PictureKey`] as `img(path)` does, keeping the
/// result under the whole key.
enum PictureLoader {}
impl Asset for PictureLoader {
type Source = PictureKey;
type Output = Result<Arc<RenderImage>, ImageCacheError>;
fn load(
source: PictureKey,
cx: &mut App,
) -> impl Future<Output = Self::Output> + Send + 'static {
<ImageAssetLoader as Asset>::load(Resource::Path(source.path), cx)
}
}
/// The keys that were drawn, by file: what [`forget_stale`] has to look at.
#[derive(Default)]
struct Drawn(HashMap<Arc<Path>, Vec<PictureKey>>);
impl Global for Drawn {}
/// Note that `key` is being drawn.
fn note(key: &PictureKey, cx: &mut App) {
let known = cx.has_global::<Drawn>()
&& cx.global::<Drawn>().0.get(key.path()).is_some_and(|keys| keys.contains(key));
if !known {
cx.default_global::<Drawn>().0.entry(key.path.clone()).or_default().push(key.clone());
}
}
/// The picture at `key` as an image element: decoded once per key, and again
/// when the file is another by the stamp. Give it a size and an object fit.
pub fn picture(key: PictureKey) -> Img {
img(ImageSource::Custom(Arc::new(move |window, cx| {
note(&key, cx);
window.use_asset::<PictureLoader>(&key, cx)
})))
}
/// The engine wrote the file at `path` again: drop what was decoded of it
/// under a stamp it no longer has, and the textures the atlas made of that.
/// The picture under the stamp it has now (a reference made after the write)
/// is kept; one that is made from the old file is drawn again when it is next
/// asked for.
pub fn forget_stale(path: &Path, cx: &mut App) {
if !cx.has_global::<Drawn>() {
return;
}
let now = Stamp::of(path);
let stale: Vec<PictureKey> = {
let Some(keys) = cx.global_mut::<Drawn>().0.get_mut(path) else { return };
let (stale, kept) = std::mem::take(keys).into_iter().partition(|key| key.stamp != now);
*keys = kept;
stale
};
for key in stale {
if let Some(Ok(image)) = cx.fetch_asset::<PictureLoader>(&key) {
cx.drop_image(image, None);
}
cx.remove_asset::<PictureLoader>(&key);
}
}
/// Whether the decoded copy of `key` is in the asset cache (the tests ask).
#[cfg(test)]
pub(crate) fn is_cached(key: &PictureKey, cx: &App) -> bool {
cx.has_asset::<PictureLoader>(key)
}
#[cfg(test)]
mod tests {
use gpui::TestAppContext;
use voelin_ui_vm::image::ImageSource as Source;
use super::*;
use crate::backend::testing::TempDir;
/// A PNG of `width` by 2 pixels.
fn png(width: u32) -> Vec<u8> {
voelin_ui_vm::dev::logic::demo_picture(width, 2, 1)
}
/// The key of a picture follows the file: a reference made after the
/// engine wrote the file again is another picture, one made before still
/// refers to the old, and what is not a file of the cache has none.
#[test]
fn the_key_of_a_picture_changes_when_the_file_does() {
let dir = TempDir::new("picture-key");
std::fs::create_dir_all(&dir.0).unwrap();
let path = dir.0.join("avatar");
std::fs::write(&path, png(3)).unwrap();
let first = Source::file(&path);
let key = PictureKey::of(&first).expect("a picture in the cache");
assert_eq!(key.path(), path);
assert_eq!(PictureKey::of(&Source::file(&path)), Some(key.clone()), "same file, same key");
std::fs::write(&path, png(7)).unwrap();
let second = PictureKey::of(&Source::file(&path)).unwrap();
assert_ne!(second, key, "the file was written again");
assert_eq!(PictureKey::of(&first), Some(key), "a reference made before keeps its own");
assert_eq!(PictureKey::of(&Source::none()), None);
assert_eq!(PictureKey::of(&Source::file(dir.0.join("missing"))), None);
std::fs::write(dir.0.join("damaged"), b"not a picture").unwrap();
assert_eq!(PictureKey::of(&Source::file(dir.0.join("damaged"))), None);
assert_eq!(PictureKey::of(&Source::rgba(1, 1, vec![0; 4])), None, "not a file");
}
/// A picture rewritten into the same file is decoded again under its new
/// key, and what was decoded of the old one is dropped when the engine says
/// the file was written again; the key of the file as it is stays.
#[gpui::test]
fn a_picture_written_again_is_decoded_again_and_the_old_copy_goes(cx: &mut TestAppContext) {
let dir = TempDir::new("picture-reload");
std::fs::create_dir_all(&dir.0).unwrap();
let path = dir.0.join("avatar");
std::fs::write(&path, png(3)).unwrap();
let old = PictureKey::of(&Source::file(&path)).unwrap();
let width = |cx: &mut TestAppContext, key: &PictureKey| {
cx.update(|cx| match cx.fetch_asset::<PictureLoader>(key) {
Some(Ok(image)) => Some(image.size(0).width.0),
_ => None,
})
};
cx.update(|cx| note(&old, cx));
assert_eq!(width(cx, &old), None, "loading");
cx.run_until_parked();
assert_eq!(width(cx, &old), Some(3));
// The engine writes the file again, and the window draws the picture
// under the key of the file as it is now, before it is told so.
std::fs::write(&path, png(7)).unwrap();
let new = PictureKey::of(&Source::file(&path)).unwrap();
cx.update(|cx| note(&new, cx));
assert_eq!(width(cx, &new), None, "loading");
cx.run_until_parked();
assert_eq!(width(cx, &new), Some(7), "the new bytes, not the old ones");
assert_eq!(width(cx, &old), Some(3), "the old copy is still there");
cx.update(|cx| forget_stale(&path, cx));
assert!(!cx.update(|cx| cx.has_asset::<PictureLoader>(&old)), "the old copy is dropped");
assert!(cx.update(|cx| cx.has_asset::<PictureLoader>(&new)), "the current key is kept");
assert_eq!(width(cx, &new), Some(7));
// Nothing more to forget; a file nobody drew is nothing to forget.
cx.update(|cx| forget_stale(&path, cx));
cx.update(|cx| forget_stale(&dir.0.join("never-drawn"), cx));
assert!(cx.update(|cx| cx.has_asset::<PictureLoader>(&new)));
}
}
+206
View File
@@ -0,0 +1,206 @@
//! What the user can ask of the shell, as GPUI actions: the callbacks of the
//! Slint front end's `bind/servers.rs` that the desktop shell has (the first
//! eleven below), and the shell's own affordances. A click dispatches the
//! action ([`gpui_kit::Window::dispatch_action`]), the window's root view
//! ([`crate::view::MainView`]) handles it, and the handler asks the root state
//! ([`crate::app::AppState`]) for what the callback did in Slint: key bindings
//! and menus come to the same handlers later.
//!
//! The voice page and the call bar add `show_voice_view`, the page's own
//! buttons (the smaller stage, Leave) and the two affordances of the call bar
//! whose pages come with later slices (Share, the voice settings), which are
//! logged.
//!
//! The channel tree and the members panel add `join_channel`,
//! `join_with_password`, `toggle_collapse`, `search_members`, `open_member` and
//! `open_client` (the last one only logs: the client's volume dialog is a
//! dialog of its own slice). The callbacks of `bind/servers.rs` that are
//! still not here belong to the slices after: `client_audio_changed` to the
//! dialogs (the member card has the volume and the mute of a person,
//! [`SetMemberVolume`] and [`SetMemberMuted`]), and `copied` (the toast that
//! follows a copy) to whichever copies: [`Invite`] sets it itself.
use gpui_kit::{Action, actions};
actions!(
voelin,
[
/// `connect_voice`: connect the server on screen with voice, into its default channel.
ConnectVoice,
/// `disconnect_voice`: leave voice on the server on screen.
DisconnectVoice,
/// `invite`: copy a link to the voice channel we are in.
Invite,
/// `save_bookmark`: save the server form (the form's own Save button).
SaveServer,
/// `save_and_connect`: save the server form, then connect.
SaveAndConnect,
/// Open the empty server form (the rail's plus button).
AddServer,
/// Close the server form without saving.
CancelServerForm,
/// The top bar's search box: the search comes with its slice, today it is logged.
OpenSearch,
/// The settings buttons: the settings come with their slice, today it is logged.
OpenSettings,
/// `join_with_password`: the password prompt's Join, with what it holds.
SubmitChannelPassword,
/// Close the password prompt without joining.
CancelChannelPassword,
/// The voice page's Leave (`Nav.show-voice(false)` then `disconnect_voice`).
LeaveVoice,
/// The voice page's Smaller stage / Larger stage (`ui.voice_compact`).
ToggleVoiceCompact,
/// The call bar's Share: the share menu comes with the stream slices, today it is logged.
OpenShare,
/// The call bar's voice settings: the settings come with their slice, today it is logged.
OpenVoiceSettings,
]
);
/// `show_voice_view`: the voice channel page on (the main area) or off (back to
/// the server page, where the chat will be).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct ShowVoiceView {
/// Shown from now on.
pub on: bool,
}
/// The member card's volume slider: the person's playback volume, in percent
/// (`member_volume` of the Slint card).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SetMemberVolume {
/// The client's id on the server.
pub client: u16,
/// 0 to 200.
pub percent: f32,
}
/// The member card's Mute for me: stop playing the person (local only).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SetMemberMuted {
/// The client's id on the server.
pub client: u16,
/// Muted from now on.
pub muted: bool,
}
/// `select_server`: show a server (and observe it).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SelectServer {
/// The bookmark's id.
pub id: i64,
}
/// `edit_bookmark`: open the server form with a saved server.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct EditServer {
/// The bookmark's id.
pub id: i64,
}
/// `delete_bookmark`: remove a server.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct DeleteServer {
/// The bookmark's id.
pub id: i64,
}
/// `set_input_muted`: mute or unmute our microphone.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SetInputMuted {
/// Muted from now on.
pub muted: bool,
}
/// `set_output_muted`: mute or unmute the sound.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SetOutputMuted {
/// Muted from now on.
pub muted: bool,
}
/// `push_to_talk`: transmit while the hold-to-talk button is held.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct PushToTalk {
/// Transmitting from now on.
pub on: bool,
}
/// `join_channel`: join a channel of the server on screen (a double-click on
/// its row, the context menu's Join).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct JoinChannel {
/// The channel's id on the server.
pub channel: u64,
}
/// A click on a channel's row: select it (the Slint tree opens the channel's
/// chat, which comes with the chat slice).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SelectChannel {
/// The channel's id on the server.
pub channel: u64,
}
/// `toggle_collapse`: fold or unfold a channel of the tree.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct ToggleChannel {
/// The channel's id on the server.
pub channel: u64,
}
/// The context menu's Edit channel: the channel editor is a slice of its own,
/// today it is logged.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct EditChannel {
/// The channel's id on the server.
pub channel: u64,
}
/// The context menu's Move to my channel: moving another client needs a command
/// the engine does not have yet, so today it is logged.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct MoveClient {
/// The client's id on the server.
pub client: u16,
}
/// `open_client`: a click on a person in the tree opens their volume dialog,
/// which is a dialog of its own slice: today it is logged.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct OpenClient {
/// The client's id on the server.
pub client: u16,
}
/// `search_members`: the members panel's search text.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SearchMembers {
/// What the box holds; empty shows everyone.
pub text: String,
}
/// `open_member`: open the card of a person over the members panel; -1 closes it.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct OpenMember {
/// The client's id on the server, or -1.
pub client: i32,
}
+502
View File
@@ -0,0 +1,502 @@
//! The channel tree of the sidebar (`ChannelTree` of `screens/channels.slint`):
//! the channels of the server on screen with the people in them, nested, with
//! their spacers, pictures, passwords and counts, and the person's marks.
//!
//! A cached pane ([`gpui_kit::Entity::cached`], which needs the size the
//! sidebar gives it) over a virtual list ([`gpui_kit::list`]: only the rows in
//! view are built, the rows differ in height) that follows [`TreeModel`]: the
//! model says which rows changed ([`TreeEvent::Rows`]) and the pane tells its
//! list, so a person who joins is a row inserted and the scroll stays where it
//! was. The pane reads nothing but its own fields while it renders, so
//! nothing but its own notify draws it again. A click selects a channel, a
//! double-click joins it, the chevron folds it, a right-click offers the
//! same; a click on a person is logged (their volume dialog is a slice of
//! its own).
use std::sync::Arc;
use gpui_kit::component::menu::ContextMenuExt as _;
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
AnyElement, Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ListAlignment,
ListState, ObjectFit, ParentElement as _, Render, SharedString,
StatefulInteractiveElement as _, Styled as _, StyledImage as _, Subscription, Window, div,
list, px,
};
use voelin_ui_vm::bridge::TreeItem;
use voelin_ui_vm::tree::ChannelId;
use super::actions::{
EditChannel, JoinChannel, MoveClient, OpenClient, OpenMember, SelectChannel, ToggleChannel,
};
use super::tree_model::{Emptiness, TreeEvent, TreeModel, debug_check};
use super::widgets::{Avatar, banner_scrim, icon, live_badge, small_picture, speaking_bars};
use crate::meter::Counters;
use crate::pictures::{PictureKey, picture};
use crate::theme::{VoelinTheme, hsla};
/// How far each level of the tree is indented.
const INDENT: f32 = 14.0;
/// How opaque the hover and selection tints of a row with a banner are over
/// the banner and its veil: the hover is `channels.slint`'s (`Theme.surface-3.
/// transparentize(0.5)`), the selection, which Slint has no state for, is a
/// stronger one of the same colour.
const BANNER_HOVER: f32 = 0.5;
const BANNER_SELECTED: f32 = 0.75;
/// The channel tree.
pub struct ChannelTree {
rows: Arc<Vec<TreeItem>>,
selected: Option<ChannelId>,
emptiness: Emptiness,
list: ListState,
/// The text size factor the list measured its rows at.
measured_at: f32,
counters: Counters,
_subscription: Subscription,
}
impl ChannelTree {
/// A tree that follows `model`.
pub fn new(model: &Entity<TreeModel>, counters: Counters, cx: &mut Context<Self>) -> Self {
let (rows, selected, emptiness) = {
let model = model.read(cx);
(model.rows().clone(), model.selected(), model.emptiness())
};
let subscription = cx.subscribe(model, |this: &mut Self, model, event: &TreeEvent, cx| {
match event {
TreeEvent::Rows(changes, rows) => this.apply(changes, rows.clone()),
TreeEvent::Selection => this.selected = model.read(cx).selected(),
// The count of people is the members panel's.
TreeEvent::Lists => {
let emptiness = model.read(cx).emptiness();
if emptiness == this.emptiness {
return;
}
this.emptiness = emptiness;
}
TreeEvent::People(..) | TreeEvent::Voice(_) | TreeEvent::Card => return,
}
cx.notify();
});
Self {
list: ListState::new(rows.len(), ListAlignment::Top, px(240.0)),
rows,
selected,
emptiness,
measured_at: 0.0,
counters,
_subscription: subscription,
}
}
/// The rows it shows.
pub fn rows(&self) -> &[TreeItem] {
&self.rows
}
/// The channel it shows selected.
pub fn selected(&self) -> Option<ChannelId> {
self.selected
}
/// Why it shows no rows, were it empty.
pub fn emptiness(&self) -> Emptiness {
self.emptiness
}
/// Take the new rows in (the rows `changes` lead to, carried by the event),
/// telling the list which rows came, went or changed their height (a
/// channel row and a person's differ).
fn apply(&mut self, changes: &voelin_ui_vm::list::Changes, new: Arc<Vec<TreeItem>>) {
use voelin_ui_vm::list::Change;
debug_check(self.rows.len(), changes, new.len());
let mut channels: Vec<bool> = self.rows.iter().map(|row| row.is_channel).collect();
for change in &changes.0 {
match *change {
Change::Update(i) => {
if channels[i] != new[i].is_channel {
self.list.splice(i..i + 1, 1);
}
channels[i] = new[i].is_channel;
}
Change::Remove(i) => {
channels.remove(i);
self.list.splice(i..i + 1, 0);
}
Change::Insert(i) => {
channels.insert(i, new[i].is_channel);
self.list.splice(i..i, 1);
}
}
}
self.rows = new;
}
/// The row at `ix`, for the list.
fn row(&mut self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
let theme = VoelinTheme::global(cx).clone();
match self.rows.get(ix) {
Some(item) if item.is_channel => {
channel_row(&theme, item, self.selected == Some(item.id as ChannelId))
}
Some(item) => client_row(&theme, item),
None => div().into_any_element(),
}
}
}
/// The words of a tree with no rows.
fn empty_words(emptiness: Emptiness) -> &'static str {
match emptiness {
Emptiness::NoServer => "No server yet.",
Emptiness::Loading => "Loading the channels…",
// The tree is not searched, so it is never `NoMatch` (the members
// panel's, `TreeModel::people_emptiness`): the model gives it
// `Emptiness::of`, which does not say it.
Emptiness::Connect | Emptiness::NoMatch => "Connect to see the channels.",
}
}
/// The chevron of a channel, which folds it.
fn chevron(item: &TreeItem, covered: bool, theme: &VoelinTheme) -> impl IntoElement {
let c = &theme.colors;
let id = item.id as ChannelId;
div()
.id(("tree-toggle", id))
.debug_selector(move || format!("tree-toggle-{id}"))
.w(px(18.0))
.h(px(18.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.on_click(move |_, window, cx| {
cx.stop_propagation();
window.dispatch_action(Box::new(ToggleChannel { channel: id }), cx);
})
.child(icon(
if item.collapsed { "chevron-right" } else { "chevron-down" },
14.0,
if covered { c.text } else { c.text_muted },
))
}
/// One channel: its icon (or a speaker, or a lock), its name as the server
/// set it out, how many are in it, and the chevron.
fn channel_row(theme: &VoelinTheme, item: &TreeItem, selected: bool) -> AnyElement {
let (c, m) = (&theme.colors, &theme.metrics);
let id = item.id as ChannelId;
let indent = item.depth as f32 * INDENT;
let banner = PictureKey::of(&item.banner);
let covered = banner.is_some();
let strong = item.own || covered;
let (hover, accent_soft, accent, selected_fill) =
(hsla(c.surface_3), hsla(c.accent_soft), hsla(c.accent), hsla(c.surface_3));
let own = item.own;
let has_icon = PictureKey::of(&item.icon).is_some();
let name_color = if strong { c.text } else { c.text_secondary };
let weight = if strong { FontWeight::SEMIBOLD } else { FontWeight::MEDIUM };
let name = div()
.flex_1()
.min_w_0()
.text_size(px(m.font_body))
.font_weight(weight)
.text_color(hsla(name_color))
.when(item.spacer == 2, |name| name.text_center())
.when(item.spacer == 3, |name| name.text_right())
// A line is cut where the row ends; it does not widen the list.
.when(item.spacer == 4, |name| name.overflow_hidden().whitespace_nowrap())
.when(item.spacer != 4, |name| name.truncate())
.child(item.name.to_string());
let counted = item.spacer == 0 && (item.members > 0 || item.max_members >= 0);
let count = if item.max_members >= 0 {
format!("{}/{}", item.members, item.max_members)
} else {
item.members.to_string()
};
let group = SharedString::from(format!("tree-row-{id}"));
let row = div()
.id(("tree-channel", id))
.debug_selector(move || format!("tree-channel-{id}"))
.group(group.clone())
.relative()
.w_full()
.h(px(34.0 * m.font_scale))
.flex_none()
.overflow_hidden()
.rounded(px(m.radius_md))
.cursor_pointer()
.when(own, |row| row.bg(accent_soft).border_1().border_color(accent))
.when(!own && selected, |row| row.bg(selected_fill))
.when(!own && !selected, |row| row.hover(move |style| style.bg(hover)))
// Artwork behind the same compact row as its title, from the indent on,
// under a veil of the surface colour that keeps the text readable over
// any picture, and under the tints of the row: our own channel's, the
// selected one and the one the pointer is over. The artwork covers the
// row's own background (which only the indent shows), so the tints
// are translucent children above the veil, as `channels.slint` does
// for the hover.
.when_some(banner, |row, key| {
let tint = || {
div()
.absolute()
.top(px(0.0))
.bottom(px(0.0))
.left(px(indent))
.right(px(0.0))
.rounded(px(m.radius_md))
};
row.child(
div()
.absolute()
.top(px(0.0))
.bottom(px(0.0))
.left(px(indent))
.right(px(0.0))
.child(picture(key).size_full().object_fit(ObjectFit::Cover)),
)
.child(
div()
.id(("tree-scrim", id))
.debug_selector(move || format!("tree-scrim-{id}"))
.absolute()
.top(px(0.0))
.bottom(px(0.0))
.left(px(indent))
.right(px(0.0))
.bg(banner_scrim(theme)),
)
.when(own, |row| {
row.child(
div()
.absolute()
.top(px(0.0))
.bottom(px(0.0))
.left(px(indent))
.right(px(0.0))
.rounded(px(m.radius_md))
.bg(accent_soft.opacity(0.65)),
)
})
.when(!own && selected, |row| {
row.child(
tint()
.debug_selector(move || format!("tree-selected-{id}"))
.bg(selected_fill.opacity(BANNER_SELECTED)),
)
})
.when(!own && !selected, |row| {
row.child(
tint().group_hover(group, move |style| style.bg(hover.opacity(BANNER_HOVER))),
)
})
})
.flex()
.flex_row()
.items_center()
.pl(px(m.space_2 + indent))
.pr(px(m.space_3))
.gap(px(m.space_2))
// A centred spacer is balanced against the chevron.
.when(item.spacer == 2, |row| row.child(div().w(px(18.0)).flex_none()))
.when(item.spacer == 0, |row| match small_picture(&item.icon, 16.0) {
Some(picture) => row.child(picture),
None => row.child(icon(
if item.locked { "lock" } else { "volume-2" },
18.0,
if strong { c.text } else { c.icon },
)),
})
.child(name)
.when(item.locked && (has_icon || item.spacer != 0), |row| {
row.child(icon("lock", 14.0, if covered { c.text } else { c.icon }))
})
.when(counted, |row| {
row.child(
div()
.flex_none()
.flex()
.flex_row()
.items_center()
.gap(px(3.0))
.when(own, |count| count.child(icon("users", 14.0, c.text_secondary)))
.child(
div()
.text_size(px(m.font_sm))
.text_color(hsla(if strong { c.text } else { c.text_muted }))
.child(count),
),
)
})
.child(chevron(item, covered, theme))
.on_click(move |event, window, cx| {
if event.click_count() >= 2 {
window.dispatch_action(Box::new(JoinChannel { channel: id }), cx);
} else {
window.dispatch_action(Box::new(SelectChannel { channel: id }), cx);
}
})
.context_menu(move |menu, _, _| {
menu.menu("Join channel", Box::new(JoinChannel { channel: id }))
.menu("Fold or unfold", Box::new(ToggleChannel { channel: id }))
.separator()
.menu("Edit channel…", Box::new(EditChannel { channel: id }))
});
row.into_any_element()
}
/// One person: their avatar, name and badges, and the marks of what they do.
fn client_row(theme: &VoelinTheme, item: &TreeItem) -> AnyElement {
let (c, m) = (&theme.colors, &theme.metrics);
let id = item.id as u64;
let indent = item.depth as f32 * INDENT;
let (hover, myself) = (hsla(c.surface_3), item.myself);
let name_color = if item.away {
c.text_muted
} else if myself {
c.accent_text
} else {
c.text_secondary
};
let mark = |name: &'static str, color| icon(name, 14.0, color);
div()
.id(("tree-client", id))
.debug_selector(move || format!("tree-client-{id}"))
.w_full()
.h(px(30.0 * m.font_scale))
.flex_none()
.rounded(px(m.radius_md))
.cursor_pointer()
.hover(move |style| style.bg(hover))
.flex()
.flex_row()
.items_center()
.pl(px(m.space_2 + indent + 12.0))
.pr(px(m.space_3))
.gap(px(m.space_3))
.child(
Avatar::new(("tree-avatar", id), 22.0, &item.initials, item.tint)
.image(item.avatar.clone())
.speaking(item.talking),
)
.child(
div()
.min_w_0()
.truncate()
.text_size(px(m.font_body))
.font_weight(if myself { FontWeight::SEMIBOLD } else { FontWeight::NORMAL })
.text_color(hsla(name_color))
.child(item.name.to_string()),
)
// Badges after the name, then the free room.
.child(
div().flex_1().min_w_0().flex().flex_row().items_center().gap(px(2.0)).children(
[&item.badge, &item.badge_2, &item.badge_3]
.into_iter()
.filter_map(|badge| small_picture(badge, 14.0)),
),
)
// The Slint bars move; these stand still (nothing here draws the window
// anew with the clock).
.when(item.talking, |row| {
row.child(
div()
.debug_selector(move || format!("tree-speaking-{id}"))
.flex_none()
.child(speaking_bars(theme, 14.0)),
)
})
.when(item.streaming, |row| row.child(live_badge(theme)))
.when(item.local_muted, |row| row.child(mark("volume-x", c.warning)))
.when(!item.local_muted && item.local_volume != 100, |row| {
row.child(
div()
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(format!("{}%", item.local_volume)),
)
})
.when(item.muted, |row| row.child(mark("mic-off", c.danger)))
.when(item.sound_off, |row| row.child(mark("headphone-off", c.danger)))
.when(item.away, |row| {
row.child(div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child("away"))
})
.children(
[&item.icon, &item.icon_2, &item.icon_3]
.into_iter()
.filter_map(|i| small_picture(i, 16.0)),
)
.on_click(move |_, window, cx| {
if !myself {
window.dispatch_action(Box::new(OpenClient { client: id as u16 }), cx);
}
})
.context_menu(move |menu, _, _| {
menu.menu("Show the card", Box::new(OpenMember { client: id as i32 }))
.menu("Volume…", Box::new(OpenClient { client: id as u16 }))
.separator()
.menu("Move to my channel", Box::new(MoveClient { client: id as u16 }))
})
.into_any_element()
}
impl Render for ChannelTree {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.tree.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
// A new text size makes the rows another height.
if (self.measured_at - m.font_scale).abs() > f32::EPSILON {
if self.measured_at != 0.0 {
self.list.remeasure();
}
self.measured_at = m.font_scale;
}
div()
.id("sidebar-channels")
.debug_selector(|| "sidebar-channels".into())
.size_full()
.flex()
.flex_col()
.gap(px(m.space_2))
.px(px(m.space_2))
.child(
div()
.min_h(px(24.0))
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.text_size(px(m.font_sm))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text_secondary))
.child(icon("volume-2", m.icon_sm, c.text_secondary))
.child("Channels"),
)
.map(|pane| {
if self.rows.is_empty() {
pane.child(
div()
.id("tree-empty")
.debug_selector(|| "tree-empty".into())
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(empty_words(self.emptiness)),
)
} else {
pane.child(
list(
self.list.clone(),
cx.processor(|this, ix, _window, cx| this.row(ix, cx)),
)
.flex_1()
.w_full()
.min_h_0(),
)
}
})
}
}
+211
View File
@@ -0,0 +1,211 @@
//! The server form: where a server is added or edited (the server dialog of
//! the Slint front end, `bookmark_form` / `save_bookmark` /
//! `save_and_connect` / `delete_bookmark` of `bind/servers.rs`). The dialogs
//! come with their slice; until then the form takes the place of the main
//! area, with gpui-component's text inputs: the address (the only thing a
//! server needs), a name (empty: the server's own), the nickname and the
//! server's password.
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
App, AppContext as _, Context, Entity, FontWeight, InteractiveElement as _, IntoElement,
ParentElement as _, Render, SharedString, Styled as _, Window, div, px,
};
use voelin_ui_vm::bridge::BookmarkForm;
use super::actions::{CancelServerForm, DeleteServer, SaveAndConnect, SaveServer};
use super::widgets::{panel, tagged};
use crate::theme::{VoelinTheme, hsla};
/// The form.
pub struct ServerForm {
id: i64,
connected: bool,
address: Entity<InputState>,
name: Entity<InputState>,
nickname: Entity<InputState>,
password: Entity<InputState>,
confirm_remove: bool,
}
impl ServerForm {
/// A form filled in with `form` (id -1: a new server). The address has the
/// focus; Enter in any field saves.
pub fn new(form: &BookmarkForm, window: &mut Window, cx: &mut Context<Self>) -> Self {
let field = |window: &mut Window,
cx: &mut Context<Self>,
placeholder: &str,
value: &str,
masked: bool| {
let input = cx.new(|cx| {
InputState::new(window, cx)
.placeholder(SharedString::from(placeholder.to_owned()))
.default_value(SharedString::from(value.to_owned()))
.masked(masked)
});
cx.subscribe_in(&input, window, |_, _, event: &InputEvent, window, cx| {
if matches!(event, InputEvent::PressEnter { .. }) {
window.dispatch_action(Box::new(SaveServer), cx);
}
})
.detach();
input
};
let address =
field(window, cx, "ts.example.com or ts.example.com:9987", &form.address, false);
let name = field(window, cx, "Optional: the server tells its own", &form.name, false);
let nickname = field(window, cx, "The name others see", &form.nickname, false);
let password = field(window, cx, "Optional", &form.server_password, true);
address.update(cx, |input, cx| input.focus(window, cx));
Self {
id: i64::from(form.id),
connected: form.connected,
address,
name,
nickname,
password,
confirm_remove: false,
}
}
/// The bookmark this form edits; -1 for a new server.
pub fn id(&self) -> i64 {
self.id
}
/// The form as the fields hold it now, for `AppState::save_bookmark`.
pub fn to_form(&self, cx: &App) -> BookmarkForm {
let text = |input: &Entity<InputState>| input.read(cx).value().to_string();
BookmarkForm {
id: self.id as i32,
name: text(&self.name).into(),
address: text(&self.address).into(),
nickname: text(&self.nickname).into(),
server_password: text(&self.password).into(),
connected: self.connected,
..Default::default()
}
}
/// Put `text` in the address field (a link that fills the form comes with
/// its slice; the tests type here).
pub fn set_address(&self, text: &str, window: &mut Window, cx: &mut App) {
self.address.update(cx, |input, cx| input.set_value(text.to_owned(), window, cx));
}
}
fn labelled(
theme: &VoelinTheme,
label: &'static str,
input: &Entity<InputState>,
) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.flex()
.flex_col()
.gap(px(m.space_2))
.child(
div()
.text_size(px(m.font_sm))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(c.text_secondary))
.child(label),
)
.child(Input::new(input))
}
impl Render for ServerForm {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let new = self.id < 0;
let id = self.id;
let confirm = self.confirm_remove;
panel(&theme)
.id("server-form")
.debug_selector(|| "server-form".into())
.flex_1()
.min_w_0()
.h_full()
.items_center()
.justify_center()
.child(
div()
.w_full()
.max_w(px(440.0))
.flex()
.flex_col()
.gap(px(m.space_4))
.p(px(m.space_5))
.child(
div()
.text_size(px(m.font_xl))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(if new { "Add a server" } else { "Edit the server" }),
)
.child(labelled(&theme, "Address", &self.address))
.child(labelled(&theme, "Name", &self.name))
.child(labelled(&theme, "Nickname", &self.nickname))
.child(labelled(&theme, "Server password", &self.password))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(tagged(
"form-save",
Button::new("form-save").primary().label("Save").on_click(
|_, window, cx| {
window.dispatch_action(Box::new(SaveServer), cx)
},
),
))
.when(!self.connected, |row| {
row.child(tagged(
"form-connect",
Button::new("form-connect").label("Save and connect").on_click(
|_, window, cx| {
window.dispatch_action(Box::new(SaveAndConnect), cx)
},
),
))
})
.child(tagged(
"form-cancel",
Button::new("form-cancel").ghost().label("Cancel").on_click(
|_, window, cx| {
window.dispatch_action(Box::new(CancelServerForm), cx)
},
),
))
.when(!new, |row| {
row.child(div().flex_1()).child(tagged(
"form-remove",
Button::new("form-remove")
.danger()
.label(if confirm {
"Click again to remove"
} else {
"Remove"
})
.on_click(cx.listener(move |this, _, window, cx| {
if this.confirm_remove {
window.dispatch_action(
Box::new(DeleteServer { id }),
cx,
);
} else {
this.confirm_remove = true;
cx.notify();
}
})),
))
}),
),
)
}
}
+234
View File
@@ -0,0 +1,234 @@
//! The main area. Until the voice page, the chat and the rest come, it is the
//! empty page: the "no server selected" state with the way to add one, and for
//! a server on screen its name, address and state with the buttons that
//! connect, disconnect and edit it. An entity of its own, drawn as a cached
//! pane: it listens to the servers' signal and tells the window only when
//! what it shows changed.
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render,
Styled as _, Subscription, Window, div, px,
};
use voelin_ui_vm::bridge::ServerItem;
use voelin_ui_vm::servers::logic;
use super::actions::{AddServer, ConnectVoice, DisconnectVoice, EditServer, ShowVoiceView};
use super::widgets::{Avatar, Presence, icon, panel, tagged};
use crate::app::AppState;
use crate::meter::Counters;
use crate::signals::Area;
use crate::theme::{VoelinTheme, hsla};
/// What the main area shows.
#[derive(Clone, Debug, PartialEq)]
pub enum MainState {
/// No server is on screen.
NoServer,
/// A server is.
Server(ServerItem),
}
impl MainState {
/// The main area for the state.
pub fn of(app: &AppState) -> Self {
let current = app.vm.current;
logic::rail(&app.vm, |bookmark| app.server_icon(bookmark))
.into_iter()
.find(|item| Some(i64::from(item.id)) == current)
.map_or(Self::NoServer, Self::Server)
}
}
/// The words for a server's state.
fn state_words(status: &str) -> &'static str {
match status {
"connected" => "Connected with voice",
"connecting" => "Connecting…",
"observing" => "Observed without joining",
_ => "Not connected",
}
}
/// The main area.
pub struct MainPanel {
state: MainState,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl MainPanel {
/// A main area that follows the server on screen in `app`.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let (state, counters, signals) = {
let shown = app.read(cx);
(MainState::of(shown), shown.counters().clone(), shown.signals().clone())
};
let subscriptions = signals.watch(app, &[Area::Servers], cx, |this: &mut Self, app, cx| {
let state = MainState::of(app.read(cx));
if state != this.state {
this.state = state;
cx.notify();
}
});
Self { state, counters, _subscriptions: subscriptions }
}
/// What it shows now.
pub fn state(&self) -> &MainState {
&self.state
}
}
impl Render for MainPanel {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.main.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let body = match &self.state {
MainState::NoServer => div()
.id("main-empty")
.debug_selector(|| "main-empty".into())
.flex()
.flex_col()
.items_center()
.gap(px(m.space_4))
.child(
div()
.size(px(72.0))
.rounded(px(m.radius_xl))
.bg(hsla(c.surface_2))
.border_1()
.border_color(hsla(c.border))
.flex()
.items_center()
.justify_center()
.child(icon("server", 32.0, c.text_muted)),
)
.child(
div()
.text_size(px(m.font_xl))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child("No server selected"),
)
.child(
div()
.max_w(px(360.0))
.text_center()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("Pick a server in the list, or add one to start talking."),
)
.child(tagged(
"main-add",
Button::new("main-add")
.primary()
.label("Add a server")
.on_click(|_, window, cx| window.dispatch_action(Box::new(AddServer), cx)),
)),
MainState::Server(item) => {
let id = i64::from(item.id);
let connected = item.status.as_ref() == "connected";
let connecting = item.status.as_ref() == "connecting";
div()
.id("main-server")
.debug_selector(|| "main-server".into())
.flex()
.flex_col()
.items_center()
.gap(px(m.space_4))
.child(
Avatar::new("main-server-avatar", 72.0, &item.initials, item.tint)
.image(item.icon.clone())
.square()
.presence(Presence::of_server(&item.status)),
)
.child(
div()
.max_w(px(480.0))
.truncate()
.text_size(px(m.font_2xl))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(item.name.to_string()),
)
.child(
div()
.text_size(px(m.font_body))
.text_color(hsla(c.text_secondary))
.child(item.address.to_string()),
)
.child(
div()
.id("main-server-state")
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(state_words(&item.status)),
)
.child(
div()
.max_w(px(360.0))
.text_center()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("Its chat comes with a later slice."),
)
.child(
div()
.flex()
.flex_row()
.gap(px(m.space_3))
.when(connected || connecting, |row| {
row.child(tagged(
"main-disconnect",
Button::new("main-disconnect")
.danger()
.label("Disconnect")
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(DisconnectVoice), cx);
}),
))
})
.when(!connected && !connecting, |row| {
row.child(tagged(
"main-connect",
Button::new("main-connect")
.primary()
.label("Connect")
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(ConnectVoice), cx);
}),
))
})
.when(connected, |row| {
row.child(tagged(
"main-voice",
Button::new("main-voice")
.primary()
.label("Voice channel")
.on_click(|_, window, cx| {
window.dispatch_action(
Box::new(ShowVoiceView { on: true }),
cx,
);
}),
))
})
.child(tagged(
"main-edit",
Button::new("main-edit").label("Edit").on_click(
move |_, window, cx| {
window.dispatch_action(Box::new(EditServer { id }), cx);
},
),
)),
)
}
};
// The root of a cached pane takes the size its place gives it: laid out
// on its own, `flex_1` would be as wide as its contents.
panel(&theme).id("main").size_full().items_center().justify_center().child(body)
}
}
+768
View File
@@ -0,0 +1,768 @@
//! The members panel (`MembersPanel` and `MemberCardPopup` of
//! `screens/members.slint`): everyone on the server in sections (those
//! streaming first, then each server group), a search, and the card of one
//! person over the panel.
//!
//! [`MembersPane`] is a cached pane over a virtual list that follows
//! [`TreeModel`] as the tree does ([`TreeEvent::People`]: the row operations
//! the list applies). A talker redraws it, with the tree: a person's row has
//! the speaking ring, "Speaking" and the bars, and no other pane of the window
//! is told. [`MemberCardView`] is the card, a card over the window with a scrim
//! that a click outside closes; it has the volume and the mute of the person for
//! us (`SetMemberVolume`, `SetMemberMuted`), and its other buttons (a message, a
//! poke, friends, blocking) come with the slices that have those dialogs.
use std::sync::Arc;
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::component::slider::{Slider, SliderEvent, SliderState};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
AnyElement, AppContext as _, Context, Entity, FontWeight, InteractiveElement as _, IntoElement,
ListAlignment, ListState, ParentElement as _, Render, SharedString,
StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, list, px,
};
use voelin_ui_vm::bridge::{MemberCard, MemberItem};
use voelin_ui_vm::list::Changes;
use super::actions::{OpenMember, SearchMembers, SetMemberMuted, SetMemberVolume};
use super::tree_model::{Emptiness, TreeEvent, TreeModel, debug_check};
use super::widgets::{
Avatar, IconButton, Presence, chip, icon, live_badge, small_picture, speaking_bars,
};
use crate::meter::Counters;
use crate::theme::tokens::Rgba;
use crate::theme::{VoelinTheme, hsla};
/// The colour of the shield of a moderator's role.
const ROLE: Rgba = Rgba(0xc06c_ffff);
/// The members panel.
pub struct MembersPane {
rows: Arc<Vec<MemberItem>>,
total: i32,
emptiness: Emptiness,
/// The person whose card is open.
open: Option<i32>,
list: ListState,
search: Entity<InputState>,
searching: bool,
/// The text size factor the list measured its rows at.
measured_at: f32,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl MembersPane {
/// A panel that follows `model`.
pub fn new(
model: &Entity<TreeModel>,
counters: Counters,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let (rows, total, emptiness, open) = {
let model = model.read(cx);
(
model.people().clone(),
model.total(),
model.people_emptiness(),
model.card().map(|c| c.id),
)
};
let search = cx.new(|cx| {
InputState::new(window, cx).placeholder(SharedString::from("Search members…"))
});
let subscriptions = vec![
cx.subscribe(model, |this: &mut Self, model, event: &TreeEvent, cx| {
match event {
TreeEvent::People(changes, rows) => this.apply(changes, rows.clone()),
TreeEvent::Lists => {
let model = model.read(cx);
let now = (model.total(), model.people_emptiness());
if now == (this.total, this.emptiness) {
return;
}
(this.total, this.emptiness) = now;
}
TreeEvent::Card => this.open = model.read(cx).card().map(|card| card.id),
TreeEvent::Rows(..) | TreeEvent::Voice(_) | TreeEvent::Selection => return,
}
cx.notify();
}),
cx.subscribe_in(&search, window, |_, input, event: &InputEvent, window, cx| {
if matches!(event, InputEvent::Change) {
let text = input.read(cx).value().to_string();
window.dispatch_action(Box::new(SearchMembers { text }), cx);
}
}),
];
Self {
list: ListState::new(rows.len(), ListAlignment::Top, px(240.0)),
rows,
total,
emptiness,
open,
search,
searching: false,
measured_at: 0.0,
counters,
_subscriptions: subscriptions,
}
}
/// The rows it shows.
pub fn rows(&self) -> &[MemberItem] {
&self.rows
}
/// The person whose card is open, as the panel marks them.
pub fn open(&self) -> Option<i32> {
self.open
}
/// Why it shows no one, were it empty.
pub fn emptiness(&self) -> Emptiness {
self.emptiness
}
/// Whether the search box is shown.
pub fn searching(&self) -> bool {
self.searching
}
/// Take the new rows in (the rows `changes` lead to, carried by the event),
/// telling the list which rows came, went or changed their height (the
/// first row of a section has the heading above it).
fn apply(&mut self, changes: &Changes, new: Arc<Vec<MemberItem>>) {
use voelin_ui_vm::list::Change;
debug_check(self.rows.len(), changes, new.len());
let mut headed: Vec<bool> = self.rows.iter().map(|row| row.first_in_group).collect();
for change in &changes.0 {
match *change {
Change::Update(i) => {
if headed[i] != new[i].first_in_group {
self.list.splice(i..i + 1, 1);
}
headed[i] = new[i].first_in_group;
}
Change::Remove(i) => {
headed.remove(i);
self.list.splice(i..i + 1, 0);
}
Change::Insert(i) => {
headed.insert(i, new[i].first_in_group);
self.list.splice(i..i, 1);
}
}
}
self.rows = new;
}
/// The search box was opened or closed: closing it shows everyone again.
fn toggle_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.searching = !self.searching;
if self.searching {
self.search.update(cx, |input, cx| input.focus(window, cx));
} else {
self.search.update(cx, |input, cx| input.set_value("", window, cx));
window.dispatch_action(Box::new(SearchMembers { text: String::new() }), cx);
}
cx.notify();
}
/// The entry at `ix` for the list: the heading of its section if it opens
/// one, then the person.
fn entry(&mut self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
let theme = VoelinTheme::global(cx).clone();
let Some(item) = self.rows.get(ix) else { return div().into_any_element() };
let m = &theme.metrics;
div()
.w_full()
.px(px(m.space_3))
.flex()
.flex_col()
.when(item.first_in_group, |entry| entry.child(group_header(&theme, item)))
.child(member_row(&theme, item, self.open == Some(item.id)))
.into_any_element()
}
}
/// The words of a panel with nobody in it.
fn empty_words(emptiness: Emptiness) -> &'static str {
match emptiness {
Emptiness::Loading => "Loading who is here…",
Emptiness::NoMatch => "Nobody matches.",
Emptiness::NoServer | Emptiness::Connect => "Connect to see who is here.",
}
}
/// The heading above the first person of a section: "Moderator — 3".
fn group_header(theme: &VoelinTheme, item: &MemberItem) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let words = if item.group_count > 0 {
format!("{} — {}", item.group, item.group_count)
} else {
item.group.to_string()
};
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.pt(px(m.space_5))
.pb(px(m.space_2))
.pl(px(m.space_2))
.children(small_picture(&item.group_icon, 16.0))
.child(
div()
.flex_1()
.min_w_0()
.truncate()
.text_size(px(m.font_md))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(c.text_secondary))
.child(words),
)
}
/// One person: avatar, name with their badges and role, what they are doing.
fn member_row(theme: &VoelinTheme, item: &MemberItem, open: bool) -> AnyElement {
let (c, m) = (&theme.colors, &theme.metrics);
let id = item.id;
let hover = hsla(c.surface_3);
let presence = if item.away {
Presence::Idle
} else if item.sound_off {
Presence::Dnd
} else {
Presence::Online
};
let name_color = if item.myself {
c.accent_text
} else if !item.role.is_empty() {
c.name_text
} else {
c.text
};
let crowns = div()
.flex()
.flex_row()
.items_center()
.gap(px(3.0))
.when(item.admin, |row| row.child(icon("crown", 14.0, c.gold)))
.when(item.priority, |row| row.child(icon("star", 14.0, c.accent_text)))
.when(item.commander, |row| row.child(icon("flag", 14.0, c.info)))
.when(item.recording, |row| row.child(icon("circle-dot", 14.0, c.danger)));
let badges = div().flex().flex_row().items_center().gap(px(2.0)).children(
[&item.badge, &item.badge_2, &item.badge_3]
.into_iter()
.filter_map(|b| small_picture(b, 14.0)),
);
div()
.id(("member", id as u64))
.debug_selector(move || format!("member-{id}"))
.w_full()
.h(px(52.0 * m.font_scale))
.flex_none()
.rounded(px(m.radius_md))
.cursor_pointer()
.when(open, |row| row.bg(hsla(c.accent_soft)))
.when(!open, |row| row.hover(move |style| style.bg(hover)))
.when(item.away, |row| row.opacity(0.6))
.flex()
.flex_row()
.items_center()
.px(px(m.space_2))
.gap(px(m.space_3))
.child(
Avatar::new(("member-avatar", id as u64), 40.0, &item.initials, item.tint)
.image(item.avatar.clone())
.presence(presence)
.speaking(item.talking),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.gap(px(1.0))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(
div()
.min_w_0()
.truncate()
.text_size(px(m.font_md))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(name_color))
.child(item.name.to_string()),
)
.child(crowns)
.child(badges),
)
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(
div()
.min_w_0()
.truncate()
.text_size(px(m.font_sm))
.text_color(hsla(if item.talking {
c.success
} else {
c.text_muted
}))
.child(item.status.to_string()),
)
.when(item.talking, |row| row.child(speaking_bars(theme, 12.0)))
.when(item.streaming, |row| {
row.child(icon("monitor", 14.0, c.text_secondary))
}),
),
)
.when(!item.role.is_empty(), |row| {
row.child(icon("shield-check", 18.0, ROLE)).child(chip(
theme,
item.role.to_string(),
None,
None,
))
})
.when(item.streaming, |row| row.child(live_badge(theme)))
.when(item.muted, |row| row.child(icon("mic-off", 16.0, c.danger)))
.when(item.sound_off, |row| row.child(icon("headphone-off", 16.0, c.danger)))
// A hand, as TeamSpeak asks for talk power; the card has the number.
.when(item.cannot_talk, |row| {
row.child(
div()
.id(("member-hand", id as u64))
.tooltip(|window, cx| {
gpui_kit::component::tooltip::Tooltip::new("Needs talk power to speak")
.build(window, cx)
})
.child(icon("hand", 16.0, c.text_muted)),
)
})
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(OpenMember { client: id }), cx)
})
.into_any_element()
}
impl Render for MembersPane {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.members.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
if (self.measured_at - m.font_scale).abs() > f32::EPSILON {
if self.measured_at != 0.0 {
self.list.remeasure();
}
self.measured_at = m.font_scale;
}
let searching = self.searching;
let this = cx.entity();
let search_button = IconButton::new("members-search", "search", "Search members")
.size(32.0)
.checked(searching)
.on_click(move |_, window, cx| {
this.update(cx, |pane, cx| pane.toggle_search(window, cx));
});
div()
.id("members")
.debug_selector(|| "members".into())
.size_full()
.flex()
.flex_col()
.gap(px(m.space_2))
.pt(px(m.space_4))
.pb(px(m.space_2))
.rounded(px(m.radius_xl))
.border_1()
.border_color(hsla(c.border))
.bg(hsla(c.surface.with_alpha(235)))
.overflow_hidden()
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.pl(px(m.space_5))
.pr(px(m.space_3))
.child(
div()
.id("members-title")
.flex_1()
.min_w_0()
.truncate()
.text_size(px(m.font_lg))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(c.text))
.child(format!("Members — {}", self.total)),
)
.child(search_button),
)
.when(searching, |pane| {
pane.child(
div()
.id("members-search-box")
.debug_selector(|| "members-search-box".into())
.px(px(m.space_4))
.child(Input::new(&self.search)),
)
})
.map(|pane| {
if self.rows.is_empty() {
pane.child(
div()
.id("members-empty")
.debug_selector(|| "members-empty".into())
.px(px(m.space_5))
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(empty_words(self.emptiness)),
)
} else {
pane.child(
list(
self.list.clone(),
cx.processor(|this, ix, _window, cx| this.entry(ix, cx)),
)
.flex_1()
.w_full()
.min_h_0(),
)
}
})
}
}
/// The card over a member row, over the window: a scrim that a click outside
/// the card closes, and the card with what is known of the person, and the
/// volume and the mute of their voice for us (the Slint card's Volume rows).
pub struct MemberCardView {
card: Option<MemberCard>,
/// How wide the members panel is: the card stands beside it.
panel_width: f32,
/// The volume slider, in percent (0 to 200, as the Slint card's).
slider: Entity<SliderState>,
_subscriptions: Vec<Subscription>,
}
/// The loudest the card's slider plays a person, in percent.
const LOUDEST: f32 = 200.0;
impl MemberCardView {
/// A card that follows `model`, beside a panel `panel_width` pixels wide.
pub fn new(
model: &Entity<TreeModel>,
panel_width: f32,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let card = model.read(cx).card().cloned();
let slider = cx.new(|_| {
SliderState::new()
.min(0.0)
.max(LOUDEST)
.step(5.0)
.default_value(card.as_ref().map_or(100.0, |card| card.volume))
});
let subscriptions = vec![
cx.subscribe_in(
model,
window,
|this: &mut Self, model, event: &TreeEvent, window, cx| {
if matches!(event, TreeEvent::Card) {
this.card = model.read(cx).card().cloned();
// The slider shows the person's volume as it is now (a change
// the slider itself made comes back the same).
if let Some(card) = &this.card {
let volume = card.volume.clamp(0.0, LOUDEST);
this.slider
.update(cx, |slider, cx| slider.set_value(volume, window, cx));
}
cx.notify();
}
},
),
cx.subscribe_in(
&slider,
window,
|this: &mut Self, _, event: &SliderEvent, window, cx| {
if let (SliderEvent::Change(value), Some(card)) = (event, &this.card) {
let client = u16::try_from(card.id).unwrap_or_default();
let percent = value.end();
window.dispatch_action(Box::new(SetMemberVolume { client, percent }), cx);
}
},
),
];
Self { card, panel_width, slider, _subscriptions: subscriptions }
}
/// The card that is open.
pub fn card(&self) -> Option<&MemberCard> {
self.card.as_ref()
}
}
/// The heading of a part of the card: "Groups", "Badges".
fn caption(theme: &VoelinTheme, text: &'static str) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.text_size(px(m.font_xs))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text_muted))
.child(text)
}
/// The card's Volume rows: what the person is played at, a mute for us and
/// the slider. Both need a person the server gave a unique id (the choice is
/// kept by it), as the Slint card's do.
fn volume(
theme: &VoelinTheme,
person: &MemberCard,
slider: &Entity<SliderState>,
) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let client = u16::try_from(person.id).unwrap_or_default();
let (muted, known) = (person.muted, person.known);
div()
.id("member-volume")
.debug_selector(|| "member-volume".into())
.flex()
.flex_col()
.gap(px(m.space_2))
.pt(px(m.space_3))
.border_t_1()
.border_color(hsla(c.border_popup))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(
div()
.flex_1()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_secondary))
.child("Volume"),
)
.child(
div()
.id("member-volume-percent")
.debug_selector(|| "member-volume-percent".into())
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(format!("{}%", person.volume.round() as i32)),
),
)
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(
IconButton::new(
"member-mute",
if muted { "volume-x" } else { "volume-2" },
if muted { "Unmute for me" } else { "Mute for me" },
)
.size(30.0)
.danger()
.checked(muted)
.enabled(known)
.on_click(move |_, window, cx| {
window
.dispatch_action(Box::new(SetMemberMuted { client, muted: !muted }), cx)
}),
)
.child(
div()
.id("member-slider")
.debug_selector(|| "member-slider".into())
.flex_1()
.child(Slider::new(slider).disabled(!known || muted)),
),
)
}
impl Render for MemberCardView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let Some(person) = self.card.clone() else { return div().into_any_element() };
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let facts = div()
.flex()
.flex_row()
.flex_wrap()
.gap(px(m.space_2))
.when(person.talk_power > 0, |row| {
row.child(chip(
&theme,
format!("talk power {}", person.talk_power),
Some("mic"),
None,
))
})
.when(!person.country.is_empty(), |row| {
row.child(chip(&theme, person.country.to_string(), Some("globe"), None))
});
let body = div()
.id("member-card")
.debug_selector(|| "member-card".into())
.w(px(300.0))
.flex()
.flex_col()
.gap(px(m.space_3))
.p(px(m.space_4))
.rounded(px(m.radius_lg))
.border_1()
.border_color(hsla(c.border_popup))
.bg(hsla(c.surface_3))
// Clicks inside stay inside.
.on_click(|_, _, cx| cx.stop_propagation())
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(
Avatar::new("member-card-avatar", 52.0, &person.initials, person.tint)
.image(person.avatar.clone()),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.truncate()
.text_size(px(m.font_lg))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(person.name.to_string()),
)
.child(
div()
.truncate()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(person.status.to_string()),
),
)
.child(IconButton::new("member-card-close", "x", "Close").size(26.0).on_click(
|_, window, cx| {
window.dispatch_action(Box::new(OpenMember { client: -1 }), cx)
},
)),
)
.when(!person.description.is_empty(), |card| {
card.child(
div()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_secondary))
.child(person.description.to_string()),
)
})
.when(!person.groups.is_empty(), |card| {
card.child(
div()
.flex()
.flex_col()
.gap(px(m.space_2))
.child(caption(&theme, "Groups"))
.children(person.groups.iter().map(|group| {
div()
.truncate()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_secondary))
.child(group.to_string())
})),
)
})
.when(!person.badges.is_empty(), |card| {
card.child(
div()
.flex()
.flex_col()
.gap(px(m.space_2))
.child(caption(&theme, "Badges"))
.child(div().flex().flex_row().flex_wrap().gap(px(m.space_2)).children(
person.badges.iter().enumerate().map(|(i, badge)| {
let description = badge.description.clone();
div()
.id(("member-badge", i as u64))
.tooltip(move |window, cx| {
gpui_kit::component::tooltip::Tooltip::new(
description.to_string(),
)
.build(window, cx)
})
.child(chip(
&theme,
badge.name.to_string(),
None,
small_picture(&badge.icon, 14.0),
))
}),
)),
)
})
.child(facts)
.child(volume(&theme, &person, &self.slider));
// The card stands beside the panel, near the top.
div()
.id("member-card-scrim")
.debug_selector(|| "member-card-scrim".into())
.absolute()
.top(px(0.0))
.left(px(0.0))
.size_full()
.bg(hsla(c.scrim_light))
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(OpenMember { client: -1 }), cx)
})
.flex()
.flex_row()
.justify_end()
.items_start()
.pt(px(120.0))
.pr(px(self.panel_width + 24.0))
.child(body)
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use super::*;
/// What an empty panel says for each reason it can be empty.
#[test]
fn an_empty_panel_says_why() {
assert_eq!(empty_words(Emptiness::NoServer), "Connect to see who is here.");
assert_eq!(empty_words(Emptiness::Connect), "Connect to see who is here.");
assert_eq!(empty_words(Emptiness::Loading), "Loading who is here…");
assert_eq!(empty_words(Emptiness::NoMatch), "Nobody matches.");
}
}
+42
View File
@@ -0,0 +1,42 @@
//! The desktop shell of the GPUI front end (`ui/shells/desktop.slint` and
//! the server callbacks of `bind/servers.rs`): the server rail, the top bar,
//! the sidebar, the main area, the voice channel page that takes its place
//! while voice is on screen, the server form and the toast, each an entity
//! that listens to the per-area signals of the root state
//! ([`crate::signals`]) and tells the window only when what it shows changed,
//! and the actions the user's moves are ([`actions`]). The rail, the top bar,
//! the main area and the voice page are embedded cached (they have a size of
//! their own), so gpui-pre 0.3.10 renders them again only when they were told
//! something changed; [`crate::view::MainView`] puts them in the window.
pub mod actions;
mod channels;
mod form;
mod main_panel;
mod members;
mod password;
mod rail;
mod sidebar;
mod toast;
mod topbar;
mod tree_model;
mod voice;
pub mod widgets;
pub use channels::ChannelTree;
pub use form::ServerForm;
pub use main_panel::{MainPanel, MainState};
pub use members::{MemberCardView, MembersPane};
pub use password::ChannelPassword;
/// Bind the shell's keys (Escape in the password prompt): once, after the
/// widget library's own are (`gpui_kit::init`).
pub fn bind_keys(cx: &mut gpui_kit::App) {
password::bind_keys(cx);
}
pub use rail::{RailView, ServerRail};
pub use sidebar::{Sidebar, SidebarView};
pub use toast::{TOAST_TIME, Toast};
pub use topbar::TopBar;
pub use tree_model::{Emptiness, TreeEvent, TreeModel};
pub use voice::{SHORT_WINDOW, VoiceHead, VoicePage};
+171
View File
@@ -0,0 +1,171 @@
//! The password prompt of a locked channel (`ChannelPasswordDialog` of
//! `screens/dialogs.slint`): what the transitions ask for with
//! `Update::password` when a channel with a password is joined and the one
//! given this connection (if any) is not at hand, or was refused. It is a
//! card over the window with a scrim; until the dialogs slice makes every
//! dialog one, it is this view's own. As in the Slint dialog, Join (and Enter)
//! do nothing while the field is empty, and Escape closes the prompt.
//!
//! Escape is a key binding of the prompt's key context ([`bind_keys`]) that
//! dispatches [`CancelChannelPassword`], and the prompt is a focus target of
//! its own (its scrim, which the card is on): a click on the card, off the
//! field, takes the focus from the field, and a click outside any focus target
//! would hand it to the window's root, which the prompt is not under, so
//! without a target the context would not be on the dispatch path and Escape
//! would do nothing. With the field focused its own Escape (which has nothing
//! to undo in a password) passes the key on, and the binding closes the prompt.
use gpui_kit::component::Disableable as _;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
App, AppContext as _, Context, Entity, FocusHandle, FontWeight, InteractiveElement as _,
IntoElement, KeyBinding, ParentElement as _, Render, SharedString,
StatefulInteractiveElement as _, Styled as _, Window, div, px,
};
use voelin_ui_vm::host::PasswordPrompt;
use super::actions::{CancelChannelPassword, SubmitChannelPassword};
use super::widgets::tagged;
use crate::theme::{VoelinTheme, hsla};
/// The key context of the prompt.
const CONTEXT: &str = "ChannelPassword";
/// The keys of the prompt: Escape closes it. Bound once, at start, with the
/// widget library's own.
pub fn bind_keys(cx: &mut App) {
cx.bind_keys([KeyBinding::new("escape", CancelChannelPassword, Some(CONTEXT))]);
}
/// The prompt for the password of one channel.
pub struct ChannelPassword {
channel: String,
wrong: bool,
input: Entity<InputState>,
/// What the prompt's scrim holds the focus with, so that Escape reaches the
/// prompt wherever in it the last click was.
focus: FocusHandle,
}
impl ChannelPassword {
/// A prompt for what `ask` names, with the field focused: Enter joins.
pub fn new(ask: &PasswordPrompt, window: &mut Window, cx: &mut Context<Self>) -> Self {
let input = cx.new(|cx| {
InputState::new(window, cx).placeholder(SharedString::from("Password")).masked(true)
});
cx.subscribe_in(&input, window, |_, _, event: &InputEvent, window, cx| match event {
InputEvent::PressEnter { .. } => {
window.dispatch_action(Box::new(SubmitChannelPassword), cx);
}
// Join is there while there is something to join with.
InputEvent::Change => cx.notify(),
_ => {}
})
.detach();
input.update(cx, |input, cx| input.focus(window, cx));
Self { channel: ask.name.clone(), wrong: ask.wrong, input, focus: cx.focus_handle() }
}
/// The channel it asks for.
pub fn channel(&self) -> &str {
&self.channel
}
/// Whether it says that the last password was refused.
pub fn wrong(&self) -> bool {
self.wrong
}
/// What the field holds. The prompt joins only with something in it.
pub fn text(&self, cx: &App) -> String {
self.input.read(cx).value().to_string()
}
/// Type `text` in the field (the tests type here).
pub fn set_text(&self, text: &str, window: &mut Window, cx: &mut App) {
self.input.update(cx, |input, cx| input.set_value(text.to_owned(), window, cx));
}
}
impl Render for ChannelPassword {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let empty = self.text(cx).is_empty();
div()
.id("password-prompt")
.debug_selector(|| "password-prompt".into())
.key_context(CONTEXT)
.track_focus(&self.focus)
.absolute()
.top(px(0.0))
.left(px(0.0))
.size_full()
.flex()
.items_center()
.justify_center()
.bg(hsla(c.scrim))
// A click outside the card closes the prompt.
.on_click(|_, window, cx| window.dispatch_action(Box::new(CancelChannelPassword), cx))
.child(
div()
.id("password-card")
.debug_selector(|| "password-card".into())
.w(px(380.0))
.flex()
.flex_col()
.gap(px(m.space_4))
.p(px(m.space_5))
.rounded(px(m.radius_lg))
.border_1()
.border_color(hsla(c.border_popup))
.bg(hsla(c.surface_3))
.on_click(|_, _, cx| cx.stop_propagation())
.child(
div()
.text_size(px(m.font_lg))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(format!("{} has a password", self.channel)),
)
.when(self.wrong, |card| {
card.child(
div()
.id("password-wrong")
.debug_selector(|| "password-wrong".into())
.text_size(px(m.font_sm))
.text_color(hsla(c.danger))
.child("That password was not accepted. Try again."),
)
})
.child(Input::new(&self.input))
.child(
div()
.flex()
.flex_row()
.justify_end()
.gap(px(m.space_3))
.child(tagged(
"password-cancel",
Button::new("password-cancel").ghost().label("Cancel").on_click(
|_, window, cx| {
window.dispatch_action(Box::new(CancelChannelPassword), cx)
},
),
))
.child(tagged(
"password-join",
Button::new("password-join")
.primary()
.label("Join")
.disabled(empty)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(SubmitChannelPassword), cx)
}),
)),
),
)
}
}
+250
View File
@@ -0,0 +1,250 @@
//! The server rail: the saved servers as avatars with their state, the
//! selection, the add-server button and the settings button (`ServerRail` of
//! `ui/shells/desktop.slint`). An entity of its own, drawn as a cached pane:
//! it listens to the servers' signal ([`crate::signals`]) and tells the window
//! only when the servers it lists changed.
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render,
StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, px,
};
use voelin_ui_vm::bridge::ServerItem;
use voelin_ui_vm::servers::logic;
use super::actions::{AddServer, EditServer, OpenSettings, SelectServer};
use super::widgets::{Avatar, IconButton, Presence};
use crate::app::AppState;
use crate::meter::Counters;
use crate::signals::Area;
use crate::theme::{VoelinTheme, hsla};
/// What the rail shows: the servers in order, and which is on screen.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RailView {
/// The saved servers, as `voelin_ui_vm::servers::logic::rail` has them.
pub servers: Vec<ServerItem>,
/// The bookmark on screen.
pub current: Option<i64>,
}
impl RailView {
/// The rail for the state.
pub fn of(app: &AppState) -> Self {
Self {
servers: logic::rail(&app.vm, |bookmark| app.server_icon(bookmark)),
current: app.vm.current,
}
}
}
/// The rail.
pub struct ServerRail {
view: RailView,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl ServerRail {
/// A rail that follows the servers of `app`.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let (view, counters, signals) = {
let state = app.read(cx);
(RailView::of(state), state.counters().clone(), state.signals().clone())
};
let subscriptions = signals.watch(app, &[Area::Servers], cx, |this: &mut Self, app, cx| {
let view = RailView::of(app.read(cx));
if view != this.view {
this.view = view;
cx.notify();
}
});
Self { view, counters, _subscriptions: subscriptions }
}
/// What it shows now.
pub fn view(&self) -> &RailView {
&self.view
}
}
/// One server of the rail: the selection pill, the ring of the one on screen,
/// the avatar with its state, the unread count and the live mark.
fn server(theme: &VoelinTheme, item: &ServerItem, selected: bool) -> impl IntoElement + use<> {
let (c, m) = (&theme.colors, &theme.metrics);
let id = i64::from(item.id);
let group = format!("rail-server-{id}");
let name = item.name.to_string();
let tooltip = format!("{name}\n{}", item.address);
let pill = div()
.absolute()
.left(px(0.0))
.w(px(4.0))
.h(px(if selected { 36.0 } else { 0.0 }))
.rounded(px(2.0))
.bg(hsla(c.text))
.when(!selected, |pill| {
let group = group.clone();
pill.group_hover(group, |style| style.h(px(18.0)))
});
div()
.id(("rail-server", id as u64))
.group(group)
.relative()
.w_full()
.h(px(56.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.debug_selector(|| format!("rail-server-{id}"))
.tooltip(move |window, cx| {
gpui_kit::component::tooltip::Tooltip::new(tooltip.clone()).build(window, cx)
})
.on_click(move |event, window, cx| {
// A second click on the server is the Slint rail's double click.
if event.click_count() >= 2 {
window.dispatch_action(Box::new(EditServer { id }), cx);
} else {
window.dispatch_action(Box::new(SelectServer { id }), cx);
}
})
.child(pill)
.when(selected, |row| {
row.child(
div()
.absolute()
.size(px(52.0))
.rounded(px(m.radius_lg + 2.0))
.border_2()
.border_color(hsla(c.accent))
.bg(hsla(c.glow.with_alpha(0x66))),
)
})
.child(
Avatar::new(("rail-avatar", id as u64), 46.0, &item.initials, item.tint)
.image(item.icon.clone())
.square()
.presence(Presence::of_server(&item.status)),
)
.when(item.unread > 0, |row| {
row.child(
div()
.absolute()
.top(px(0.0))
.left(px(50.0))
.min_w(px(18.0))
.h(px(18.0))
.px(px(5.0))
.rounded(px(9.0))
.bg(hsla(c.live))
.border_2()
.border_color(hsla(c.bg_rail))
.flex()
.items_center()
.justify_center()
.text_size(px(m.font_xs))
.font_weight(FontWeight::BOLD)
.text_color(hsla(c.on_accent))
.child(item.unread.to_string()),
)
})
.when(item.live && item.unread == 0, |row| {
row.child(
div()
.absolute()
.top(px(4.0))
.left(px(52.0))
.size(px(12.0))
.rounded(px(6.0))
.bg(hsla(c.live))
.border_2()
.border_color(hsla(c.bg_rail)),
)
})
}
impl Render for ServerRail {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.rail.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let current = self.view.current;
let servers: Vec<_> = self
.view
.servers
.iter()
.map(|item| server(&theme, item, current == Some(i64::from(item.id))))
.collect();
div()
.id("rail")
.w(px(m.rail_width))
.h_full()
.flex_none()
.flex()
.flex_col()
.items_center()
.py(px(m.space_3))
.gap(px(m.space_2))
.bg(hsla(c.bg_rail.with_alpha(230)))
.border_r_1()
.border_color(hsla(c.border))
// The app's mark. (Home, which the Slint rail opens from it, comes
// with its slice.)
.child(
div()
.size(px(48.0))
.flex_none()
.rounded(px(m.radius_lg))
.border_1()
.border_color(hsla(c.border))
.bg(hsla(c.surface_2))
.flex()
.items_center()
.justify_center()
.child(gpui_kit::img("logo.svg").size(px(30.0))),
)
.child(
div()
.w(px(32.0))
.h(px(2.0))
.my(px(m.space_2))
.rounded(px(1.0))
.bg(hsla(c.border_strong)),
)
.child(
div()
.id("rail-servers")
.flex_1()
.min_h_0()
.w_full()
.overflow_y_scroll()
.flex()
.flex_col()
.items_center()
.gap(px(m.space_2))
.children(servers)
.child(
div().pt(px(m.space_2)).child(
IconButton::new("rail-add", "plus", "Add a server")
.size(46.0)
.round()
.filled()
.tint(c.success)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(AddServer), cx);
}),
),
),
)
.child(
IconButton::new("rail-settings", "settings", "Settings")
.size(46.0)
.round()
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(OpenSettings), cx);
}),
)
}
}
+494
View File
@@ -0,0 +1,494 @@
//! The sidebar (`Sidebar` of `ui/shells/desktop.slint`, with the cards of
//! `shells/common.slint`): the server on screen (its card has the server's
//! banner behind it, under the same veil as the tree's rows), its channel tree
//! ([`super::ChannelTree`], a cached pane of its own), the voice card while
//! voice is connecting or connected, and the user's own card with the voice
//! buttons. An entity of its own: it listens to the servers' and the toolbar's
//! signals and tells the window only when what it shows changed.
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, MouseButton, MouseUpEvent,
ObjectFit, ParentElement as _, Render, StatefulInteractiveElement as _, StyleRefinement,
Styled as _, StyledImage as _, Subscription, Window, div, px,
};
use voelin_core::TransmitMode;
use voelin_ui_vm::Rgb;
use voelin_ui_vm::bridge::ServerItem;
use voelin_ui_vm::image::ImageRef;
use voelin_ui_vm::servers::logic;
use super::actions::{
DisconnectVoice, Invite, OpenSettings, PushToTalk, SetInputMuted, SetOutputMuted,
};
use super::channels::ChannelTree;
use super::widgets::{Avatar, IconButton, Presence, banner_scrim, card, icon, panel};
use crate::app::AppState;
use crate::meter::Counters;
use crate::pictures::{PictureKey, picture};
use crate::signals::Area;
use crate::theme::{VoelinTheme, hsla};
/// What the sidebar shows.
#[derive(Clone, Debug, PartialEq)]
pub struct SidebarView {
/// The server on screen, as the rail has it.
pub server: Option<ServerItem>,
/// "9 online · 7 channels" once its presence is known, else empty.
pub stats: String,
/// The server's banner, behind its card; empty without one.
pub server_banner: ImageRef,
/// Our nickname there; empty without a server.
pub nickname: String,
/// The channel we are in; empty while connecting.
pub own_channel: String,
/// Our picture on the server.
pub own_avatar: ImageRef,
/// Voice is connected.
pub voice_connected: bool,
/// Voice is connecting.
pub voice_connecting: bool,
/// The server is observed.
pub observing: bool,
/// Our microphone is muted.
pub input_muted: bool,
/// Our sound is muted.
pub output_muted: bool,
/// Voice goes out.
pub transmitting: bool,
/// The transmit mode is push-to-talk, so the card has a hold-to-talk button.
pub hold_to_talk: bool,
/// How our voice is sent, as the audio settings say: the card has the
/// button for push-to-talk and says the mode otherwise.
pub transmit: TransmitMode,
}
impl SidebarView {
/// The sidebar for the state.
pub fn of(app: &AppState) -> Self {
let card = logic::toolbar(&app.vm, |bookmark| app.server_icon(bookmark));
let server = app.vm.current.and_then(|id| {
logic::rail(&app.vm, |bookmark| app.server_icon(bookmark))
.into_iter()
.find(|item| i64::from(item.id) == id)
});
Self {
server,
stats: card.server_stats,
server_banner: card.server_banner,
nickname: card.nickname,
own_channel: card.own_channel,
own_avatar: card.own_avatar,
voice_connected: card.voice_connected,
voice_connecting: card.voice_connecting,
observing: card.observing,
input_muted: card.input_muted,
output_muted: card.output_muted,
transmitting: card.transmitting,
hold_to_talk: app.vm.audio.transmit == TransmitMode::PushToTalk,
transmit: app.vm.audio.transmit,
}
}
}
/// The sidebar.
pub struct Sidebar {
view: SidebarView,
/// The channel tree, a pane of its own between the server card and the
/// voice card.
tree: Entity<ChannelTree>,
/// The hold-to-talk button is held down.
holding: bool,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl Sidebar {
/// A sidebar that follows the server on screen and the voice state in
/// `app`, with `tree` between its cards.
pub fn new(app: &Entity<AppState>, tree: Entity<ChannelTree>, cx: &mut Context<Self>) -> Self {
let (view, counters, signals) = {
let state = app.read(cx);
(SidebarView::of(state), state.counters().clone(), state.signals().clone())
};
let subscriptions =
signals.watch(app, &[Area::Servers, Area::Toolbar], cx, |this: &mut Self, app, cx| {
let state = app.read(cx);
let view = SidebarView::of(state);
// The button goes away when voice leaves `Connected`, transmit
// leaves push-to-talk, or another server is shown; and a drop
// and reconnect inside one batch ends the hold in `AppState`
// while `view.voice_connected` stays true. Keep `holding` in
// sync with the root state's own button hold (this observer
// only sets its own fields).
let same_server =
view.server.as_ref().map(|s| s.id) == this.view.server.as_ref().map(|s| s.id);
let held_here = view
.server
.as_ref()
.is_some_and(|s| state.button_held() == Some(i64::from(s.id)));
if !view.voice_connected || !view.hold_to_talk || !same_server || !held_here {
this.holding = false;
}
if view != this.view {
this.view = view;
cx.notify();
}
});
Self { view, tree, holding: false, counters, _subscriptions: subscriptions }
}
/// What it shows now.
pub fn view(&self) -> &SidebarView {
&self.view
}
/// Whether the hold-to-talk button is currently held down.
#[cfg(test)]
pub(crate) fn is_holding(&self) -> bool {
self.holding
}
/// Let go of the hold-to-talk button if it is held (the window lost the
/// focus: the release will not come to it): whether it was held. The caller
/// tells the session.
pub fn release(&mut self) -> bool {
std::mem::take(&mut self.holding)
}
/// The hold-to-talk button was released, if it was held.
fn let_go(&mut self, _: &MouseUpEvent, window: &mut Window, cx: &mut Context<Self>) {
if std::mem::take(&mut self.holding) {
window.dispatch_action(Box::new(PushToTalk { on: false }), cx);
}
}
}
/// The server's name, its icon and how many are there, over its banner when it
/// has one (`ServerHeader` of `channels.slint`: the picture covers the card,
/// the surface veil of `banner-picture.slint` lies over it, and the stats read
/// in the text colour instead of the secondary one).
fn server_card(theme: &VoelinTheme, view: &SidebarView, item: &ServerItem) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let stats = if view.stats.is_empty() { item.address.to_string() } else { view.stats.clone() };
let banner = PictureKey::of(&view.server_banner);
let ink = if banner.is_some() { c.text } else { c.text_muted };
card(theme, 0xff)
.id("sidebar-server")
.debug_selector(|| "sidebar-server".into())
.relative()
.overflow_hidden()
.p(px(m.space_3))
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.when_some(banner, |card, key| {
card.child(
div()
.id("sidebar-server-banner")
.debug_selector(|| "sidebar-server-banner".into())
.absolute()
.top(px(0.0))
.left(px(0.0))
.size_full()
// The picture covers the card and is cropped to it, not past
// its border.
.overflow_hidden()
.child(picture(key).size_full().object_fit(ObjectFit::Cover)),
)
.child(div().absolute().top(px(0.0)).left(px(0.0)).size_full().bg(banner_scrim(theme)))
})
.child(
Avatar::new("sidebar-server-avatar", 40.0, &item.initials, item.tint)
.image(item.icon.clone())
.square(),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.truncate()
.text_size(px(m.font_lg))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(item.name.to_string()),
)
.child(
div().truncate().text_size(px(m.font_sm)).text_color(hsla(ink)).child(stats),
),
)
}
/// How our voice is sent, in words, for the modes that have no button.
fn transmit_words(mode: TransmitMode) -> &'static str {
match mode {
TransmitMode::PushToTalk => "Push to talk",
TransmitMode::VoiceActivation => "Voice activity",
TransmitMode::Continuous => "Open microphone",
}
}
/// "Voice Connected" and our channel, disconnect, and Hold to talk in the
/// push-to-talk mode (the other modes say themselves).
fn voice_card(
theme: &VoelinTheme,
view: &SidebarView,
cx: &mut Context<Sidebar>,
) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let (dot, words) = if view.voice_connected {
(c.success, "Voice Connected")
} else {
(c.warning, "Connecting…")
};
let talking = view.transmitting;
card(theme, 0xff)
.id("sidebar-voice")
.debug_selector(|| "sidebar-voice".into())
.p(px(m.space_3))
.flex()
.flex_col()
.gap(px(m.space_3))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(div().size(px(10.0)).flex_none().rounded(px(5.0)).bg(hsla(dot)))
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.text_size(px(m.font_sm))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(dot))
.child(words),
)
.when(!view.own_channel.is_empty(), |column| {
column.child(
div()
.truncate()
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(view.own_channel.clone()),
)
}),
)
.when(view.voice_connected && !view.own_channel.is_empty(), |row| {
row.child(
IconButton::new("voice-invite", "link", "Copy an invite to this channel")
.size(32.0)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(Invite), cx);
}),
)
})
.child(
IconButton::new("voice-disconnect", "phone-off", "Disconnect")
.size(32.0)
.tint(c.danger)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(DisconnectVoice), cx);
}),
),
)
.when(view.voice_connected && !view.hold_to_talk, |card| {
card.child(
div()
.id("transmit-mode")
.debug_selector(|| "transmit-mode".into())
.h(px(m.control_height_sm))
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(m.space_2))
.child(icon("mic", m.icon_sm, c.text_muted))
.child(
div()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(transmit_words(view.transmit)),
),
)
})
.when(view.voice_connected && view.hold_to_talk, |card| {
card.child(
div()
.id("hold-to-talk")
.debug_selector(|| "hold-to-talk".into())
.h(px(m.control_height))
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(m.space_2))
.rounded(px(m.radius_md))
.border_1()
.border_color(hsla(if talking { c.success } else { c.border }))
.bg(hsla(if talking { c.success.with_alpha(0xcc) } else { c.surface_2 }))
.cursor_pointer()
.hover(move |style| {
style.bg(hsla(if talking { c.success } else { c.surface_3 }))
})
.on_mouse_down(
MouseButton::Left,
cx.listener(|this, _, window, cx| {
this.holding = true;
window.dispatch_action(Box::new(PushToTalk { on: true }), cx);
}),
)
// Let go on the button or off it: the end of what was started.
.on_mouse_up(MouseButton::Left, cx.listener(Sidebar::let_go))
.on_mouse_up_out(MouseButton::Left, cx.listener(Sidebar::let_go))
.child(icon(
"mic",
m.icon_sm,
if talking { c.on_accent } else { c.text_secondary },
))
.child(
div()
.text_size(px(m.font_sm))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(if talking { c.on_accent } else { c.text_secondary }))
.child(if talking { "Talking…" } else { "Hold to talk" }),
),
)
})
}
/// Who we are, and the buttons for the microphone and the sound.
fn user_card(theme: &VoelinTheme, view: &SidebarView) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let (words, presence) = if view.voice_connected {
("Online", Presence::Online)
} else if view.observing {
("Observing", Presence::Info)
} else {
("Offline", Presence::Offline)
};
let name = if view.nickname.is_empty() {
voelin_platform::APP_NAME.to_owned()
} else {
view.nickname.clone()
};
let (input_muted, output_muted) = (view.input_muted, view.output_muted);
card(theme, 0xb3)
.id("sidebar-user")
.debug_selector(|| "sidebar-user".into())
.min_h(px(60.0))
.p(px(m.space_2))
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(
div()
.id("sidebar-profile")
.flex_1()
.min_w_0()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.px(px(m.space_2))
.py(px(m.space_2))
.rounded(px(m.radius_md))
.cursor_pointer()
.hover(|style| style.bg(hsla(c.surface_3)))
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSettings), cx))
.child(
Avatar::new("sidebar-own-avatar", 38.0, &name_initials(&name), Rgb(0x2d6bff))
.image(view.own_avatar.clone())
.presence(presence)
.speaking(view.transmitting),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.truncate()
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(name),
)
.child(
div()
.truncate()
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(words),
),
),
)
.child(
IconButton::new(
"user-mic",
if input_muted { "mic-off" } else { "mic" },
if input_muted { "Microphone off" } else { "Microphone on" },
)
.danger()
.checked(input_muted)
.enabled(view.voice_connected)
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(SetInputMuted { muted: !input_muted }), cx);
}),
)
.child(
IconButton::new(
"user-sound",
if output_muted { "headphone-off" } else { "headphones" },
if output_muted { "Sound off" } else { "Sound on" },
)
.danger()
.checked(output_muted)
.enabled(view.voice_connected)
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(SetOutputMuted { muted: !output_muted }), cx);
}),
)
}
/// The initials of a nickname, for the avatar.
fn name_initials(name: &str) -> String {
voelin_ui_vm::avatar::initials(name)
}
impl Render for Sidebar {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.sidebar.incr();
let theme = VoelinTheme::global(cx).clone();
let m = &theme.metrics;
let view = &self.view;
panel(&theme)
.id("sidebar")
.w(px(m.sidebar_width))
.h_full()
.flex_none()
.p(px(m.space_3))
.gap(px(m.space_3))
.when_some(view.server.as_ref(), |sidebar, item| {
sidebar.child(server_card(&theme, view, item))
})
// The tree has the room the cards leave, whatever their height.
.child(self.tree.clone().cached(StyleRefinement::default().flex_1().min_h_0().w_full()))
.when(view.voice_connected || view.voice_connecting, |sidebar| {
sidebar.child(voice_card(&theme, view, cx))
})
.child(user_card(&theme, view))
}
}
+88
View File
@@ -0,0 +1,88 @@
//! The status line as a toast: what the last move did ("Connecting to
//! ts.example…", why a server was not saved), shown at the bottom of the
//! window for a few seconds. It watches the root state's status line and its
//! generation, so that the same words said twice are two toasts.
use std::time::Duration;
use gpui_kit::{
Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, Styled as _,
Subscription, Window, div, px,
};
use crate::app::AppState;
use crate::theme::{VoelinTheme, hsla};
/// How long a toast stays.
pub const TOAST_TIME: Duration = Duration::from_secs(5);
/// The toast.
pub struct Toast {
text: String,
generation: u64,
_subscription: Subscription,
}
impl Toast {
/// A toast that follows `app`'s status line from now on (what it said
/// before is not shown).
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let generation = app.read(cx).status_generation;
let subscription = cx.observe(app, |this: &mut Self, app, cx| {
let (generation, text) = {
let app = app.read(cx);
(app.status_generation, app.vm.status.clone())
};
if generation == this.generation {
return;
}
this.generation = generation;
this.text = text;
cx.notify();
if this.text.is_empty() {
return;
}
cx.spawn(async move |this, cx| {
cx.background_executor().timer(TOAST_TIME).await;
let _ = this.update(cx, |this, cx| {
if this.generation == generation && !this.text.is_empty() {
this.text.clear();
cx.notify();
}
});
})
.detach();
});
Self { text: String::new(), generation, _subscription: subscription }
}
/// What it shows now; empty when nothing is.
pub fn text(&self) -> &str {
&self.text
}
}
impl Render for Toast {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let toast =
div().id("toast").absolute().bottom(px(m.space_7)).w_full().flex().justify_center();
if self.text.is_empty() {
return toast;
}
toast.child(
div()
.max_w(px(560.0))
.px(px(m.space_5))
.py(px(m.space_3))
.rounded(px(m.radius_md))
.border_1()
.border_color(hsla(c.border_popup))
.bg(hsla(c.surface_3))
.text_size(px(m.font_body))
.text_color(hsla(c.text))
.child(self.text.clone()),
)
}
}
+119
View File
@@ -0,0 +1,119 @@
//! The bar at the top of the window: the page's title, the search box and the
//! settings button (`TopBar` of `ui/shells/desktop.slint`; the bell comes
//! with the notifications). The search and the settings are affordances until
//! their slices: a click is logged ([`OpenSearch`], [`OpenSettings`]).
use gpui_kit::{
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render,
StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, px,
};
use super::actions::{OpenSearch, OpenSettings};
use super::widgets::{IconButton, icon};
use crate::app::AppState;
use crate::meter::Counters;
use crate::signals::Area;
use crate::theme::{VoelinTheme, hsla};
/// The page title: the server on screen, else the app's name.
pub fn title(app: &AppState) -> String {
match app.current_bookmark() {
Some(bookmark) => bookmark.name.clone(),
None => voelin_platform::APP_NAME.to_owned(),
}
}
/// The top bar.
pub struct TopBar {
title: String,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl TopBar {
/// A top bar that follows the server on screen in `app`.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let (shown, counters, signals) = {
let state = app.read(cx);
(title(state), state.counters().clone(), state.signals().clone())
};
let subscriptions = signals.watch(app, &[Area::Servers], cx, |this: &mut Self, app, cx| {
let shown = title(app.read(cx));
if shown != this.title {
this.title = shown;
cx.notify();
}
});
Self { title: shown, counters, _subscriptions: subscriptions }
}
/// The title it shows now.
pub fn title(&self) -> &str {
&self.title
}
}
impl Render for TopBar {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.topbar.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
div()
.id("topbar")
.w_full()
.h(px(m.topbar_height))
.flex_none()
.flex()
.flex_row()
.items_center()
// The main panel starts where the sidebar and the gaps around it end.
.pl(px(m.sidebar_width + 2.0 * m.space_3))
.pr(px(m.space_4))
.gap(px(m.space_4))
.child(
div()
.id("topbar-title")
.max_w(px(280.0 * m.font_scale.max(1.0)))
.flex_none()
.truncate()
.text_size(px(m.font_lg))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(self.title.clone()),
)
.child(
div().flex_1().min_w_0().flex().justify_center().child(
div()
.id("topbar-search")
.w_full()
.max_w(px(680.0))
.h(px(m.control_height))
.px(px(m.space_3))
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.rounded(px(m.radius_md))
.border_1()
.border_color(hsla(c.border))
.bg(hsla(c.surface_2))
.cursor_text()
.hover(|style| style.border_color(hsla(c.border_strong)))
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSearch), cx))
.child(icon("search", m.icon_sm, c.text_muted))
.child(
div()
.flex_1()
.truncate()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("Search servers, channels, people or settings…"),
),
),
)
.child(
IconButton::new("topbar-settings", "settings", "Settings")
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSettings), cx)),
)
}
}
+319
View File
@@ -0,0 +1,319 @@
//! The narrow entity behind the channel tree and the members panel: what
//! `voelin_ui_vm::servers::logic::tree_view` makes of the state, kept between
//! one change and the next so that the two panes can be told what changed.
//!
//! It listens to the tree, toolbar and member-card signals
//! ([`crate::signals`]), builds the rows once for both panes, compares them
//! with the rows it had ([`voelin_ui_vm::list::diff`], the row operations the
//! Slint front end applies to its `VecModel`) and emits what differs
//! ([`TreeEvent`], with the rows the operations lead to): a pane applies the
//! operations to its list state, so a person who joins is a row that is
//! inserted, not a list that starts again at the top. A change that moves none
//! of what a pane shows emits nothing.
//!
//! The people of our voice channel (`TreeView::members`, the voice page's
//! rows) come out of the same build as the other two lists: the model keeps
//! them and emits them when they differ ([`TreeEvent::Voice`]), so the voice
//! page needs no build of its own.
//!
//! **The tree marks who is talking**, as the Slint tree does (the ring on the
//! avatar and the speaking bars on the row): someone who starts or stops
//! talking changes one row of the tree and one of the members panel, so each
//! of the two panes is drawn again once for it, and no other pane is
//! (docs/ui.md, "What a change costs").
use std::sync::Arc;
use gpui_kit::{App, Context, Entity, EventEmitter, Subscription};
use voelin_core::{ObserveState, VoiceState};
use voelin_ui_vm::bridge::{MemberCard, MemberItem, TreeItem};
use voelin_ui_vm::list::{Changes, diff};
use voelin_ui_vm::servers::logic;
use voelin_ui_vm::tree::{ChannelId, member_card};
use crate::app::{AppState, VmState};
use crate::signals::Area;
/// Why a list has no rows, which the pane says in words.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Emptiness {
/// No server is on screen.
NoServer,
/// The server is observed or being connected to, and its presence is on
/// the way.
Loading,
/// Nothing is known of the server until it is connected.
Connect,
/// The server has people and the members' search matches none of them (the
/// members panel's only: the tree is not searched).
NoMatch,
}
impl Emptiness {
/// Why the lists of the server on screen are empty: never
/// [`Emptiness::NoMatch`], which is [`Emptiness::of_people`]'s.
pub fn of(vm: &VmState) -> Self {
match vm.current {
None => Self::NoServer,
Some(id) => match vm.sessions.get(&id) {
Some(view)
if view.state.observe != ObserveState::Off
|| view.state.voice == VoiceState::Connecting =>
{
Self::Loading
}
_ => Self::Connect,
},
}
}
/// Why the members panel is empty: as [`Emptiness::of`], except that a
/// search that leaves nobody of the `total` on the server (`shown` rows
/// are left) is [`Emptiness::NoMatch`], where "Connect to see who is here"
/// would be false.
pub fn of_people(vm: &VmState, shown: usize, total: i32) -> Self {
if shown == 0 && total > 0 && !vm.member_filter.trim().is_empty() {
Self::NoMatch
} else {
Self::of(vm)
}
}
}
/// What changed in the model, as the panes need it.
///
/// The list events carry the rows their operations lead to. A model that
/// refreshed twice before the first event is delivered (an observer that
/// changes the state inside a flush makes it) holds the second rows by the
/// time a pane hears of the first operations, and operations applied to rows
/// they were not made for index past their end. A pane applies them to the
/// rows it has and keeps the rows the event carries, so the events, in the
/// order they are delivered, lead from the rows the pane started with to the
/// model's last.
#[derive(Clone, Debug, PartialEq)]
pub enum TreeEvent {
/// The tree's rows: the operations from the rows the pane has to the rows
/// carried (the model's [`TreeModel::rows`] when it made them).
Rows(Changes, Arc<Vec<TreeItem>>),
/// The members panel's rows: the operations from the rows the pane has to
/// the rows carried (the model's [`TreeModel::people`] when it made them).
People(Changes, Arc<Vec<MemberItem>>),
/// The people of our voice channel, the voice page's rows, as they are
/// now (the whole list: the page lays its people out in a wrapping row, not
/// a virtual list, and takes them as they come).
Voice(Arc<Vec<MemberItem>>),
/// The card over a member row opened, changed or closed
/// ([`TreeModel::card`]).
Card,
/// The selected channel ([`TreeModel::selected`]).
Selection,
/// Why the lists are empty, or how many people there are
/// ([`TreeModel::emptiness`], [`TreeModel::people_emptiness`],
/// [`TreeModel::total`]).
Lists,
}
/// The areas the model listens to.
const AREAS: [Area; 3] = [Area::Tree, Area::Toolbar, Area::MemberCard];
/// How many times each of [`AREAS`] was raised.
fn generations(app: &Entity<AppState>, cx: &App) -> [u64; 3] {
let signals = app.read(cx).signals();
AREAS.map(|area| signals.of(area).read(cx).generation())
}
/// The rows of the tree and of the members panel, the member card and the
/// selection of the server on screen.
pub struct TreeModel {
app: Entity<AppState>,
/// The generations of its signals it last built the rows at: a batch that
/// raises several of them (a picture that arrives raises three) has them
/// all raised before the first is heard, so the first refresh builds the
/// rows and the others find nothing new.
seen: [u64; 3],
refreshes: u64,
rows: Arc<Vec<TreeItem>>,
people: Arc<Vec<MemberItem>>,
voice: Arc<Vec<MemberItem>>,
total: i32,
card: Option<MemberCard>,
selected: Option<ChannelId>,
emptiness: Emptiness,
people_emptiness: Emptiness,
_subscriptions: Vec<Subscription>,
}
impl EventEmitter<TreeEvent> for TreeModel {}
/// Check that `changes` lead from a list of `old` rows to one of `new` rows
/// (debug builds): a pane that applies operations to rows they were not made
/// for finds the counts out of step, where a release build would index past
/// the end or leave its list state out of step with its rows.
pub(super) fn debug_check(old: usize, changes: &Changes, new: usize) {
debug_assert_eq!(
old + changes.inserted(),
new + changes.removed(),
"{changes:?} do not lead from {old} rows to {new}: applied to rows they were not made \
for? (docs/ui.md, \"For the next slices\": no state change from a signal's observer \
inside a flush)"
);
}
/// Everything the model keeps, as the state gives it now.
struct Snapshot {
rows: Vec<TreeItem>,
people: Vec<MemberItem>,
voice: Vec<MemberItem>,
total: i32,
card: Option<MemberCard>,
selected: Option<ChannelId>,
emptiness: Emptiness,
people_emptiness: Emptiness,
}
impl Snapshot {
fn of(app: &AppState) -> Self {
let vm = &app.vm;
let view = vm.current.and_then(|id| vm.sessions.get(&id));
let (rows, people, voice, total) = match logic::tree_view(vm, false) {
Some(tree) => (tree.rows, tree.server_members, tree.members, tree.member_total),
None => (Vec::new(), Vec::new(), Vec::new(), 0),
};
Self {
people_emptiness: Emptiness::of_people(vm, people.len(), total),
rows,
people,
voice,
total,
card: view
.and_then(|view| view.member_card.map(|id| (view, id)))
.and_then(|(view, id)| member_card(view, id, &vm.contacts, &vm.playback)),
selected: app.selected_channel(),
emptiness: Emptiness::of(vm),
}
}
}
impl TreeModel {
/// A model of what `app` shows now, following its tree signals.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let (snapshot, signals) = {
let state = app.read(cx);
(Snapshot::of(state), state.signals().clone())
};
let subscriptions =
signals.watch(app, &AREAS, cx, |this: &mut Self, _, cx| this.refresh(cx));
Self {
app: app.clone(),
seen: generations(app, cx),
refreshes: 0,
rows: Arc::new(snapshot.rows),
people: Arc::new(snapshot.people),
voice: Arc::new(snapshot.voice),
total: snapshot.total,
card: snapshot.card,
selected: snapshot.selected,
emptiness: snapshot.emptiness,
people_emptiness: snapshot.people_emptiness,
_subscriptions: subscriptions,
}
}
/// The rows of the channel tree: channels with the clients in them.
pub fn rows(&self) -> &Arc<Vec<TreeItem>> {
&self.rows
}
/// The rows of the members panel: everyone on the server, in sections.
pub fn people(&self) -> &Arc<Vec<MemberItem>> {
&self.people
}
/// The people of our voice channel, in the voice page's order (empty while
/// voice is not connected).
pub fn voice(&self) -> &Arc<Vec<MemberItem>> {
&self.voice
}
/// How many are on the server (the query clients not counted).
pub fn total(&self) -> i32 {
self.total
}
/// The card over a member row, when one is open.
pub fn card(&self) -> Option<&MemberCard> {
self.card.as_ref()
}
/// The channel selected in the tree.
pub fn selected(&self) -> Option<ChannelId> {
self.selected
}
/// Why the tree is empty, were it.
pub fn emptiness(&self) -> Emptiness {
self.emptiness
}
/// Why the members panel is empty, were it: the same as
/// [`TreeModel::emptiness`], or that the search matches nobody.
pub fn people_emptiness(&self) -> Emptiness {
self.people_emptiness
}
/// How many times the rows were built again since the model was made: one
/// for each batch of changes, not one for each signal it raised.
pub fn refreshes(&self) -> u64 {
self.refreshes
}
/// Build the rows again, and tell the panes what differs. Nothing, when
/// none of the signals was raised since the last time.
fn refresh(&mut self, cx: &mut Context<Self>) {
let now = generations(&self.app, cx);
if now == self.seen {
return;
}
self.seen = now;
self.refreshes += 1;
let new = Snapshot::of(self.app.read(cx));
let rows = diff(&self.rows, &new.rows);
let people = diff(&self.people, &new.people);
if !rows.is_empty() {
self.rows = Arc::new(new.rows);
}
if !people.is_empty() {
self.people = Arc::new(new.people);
}
let voice = *self.voice != new.voice;
if voice {
self.voice = Arc::new(new.voice);
}
let lists = (self.emptiness, self.people_emptiness, self.total)
!= (new.emptiness, new.people_emptiness, new.total);
(self.emptiness, self.people_emptiness, self.total) =
(new.emptiness, new.people_emptiness, new.total);
let card = self.card != new.card;
self.card = new.card;
let selection = self.selected != new.selected;
self.selected = new.selected;
if !rows.is_empty() {
cx.emit(TreeEvent::Rows(rows, self.rows.clone()));
}
if !people.is_empty() {
cx.emit(TreeEvent::People(people, self.people.clone()));
}
if voice {
cx.emit(TreeEvent::Voice(self.voice.clone()));
}
if lists {
cx.emit(TreeEvent::Lists);
}
if card {
cx.emit(TreeEvent::Card);
}
if selection {
cx.emit(TreeEvent::Selection);
}
}
}
+657
View File
@@ -0,0 +1,657 @@
//! The voice channel page (`VoiceView` of `screens/voice.slint`, with its
//! `Participant` of `voice-parts.slint` and the `CallBar`): the channel we are
//! in, who is there and who talks, and the call's controls under them.
//!
//! [`VoicePage`] is a cached pane of its own, a sibling of the server page
//! ([`super::MainPanel`]) that [`crate::view::MainView`] puts in the main
//! area in its place while the page is asked for and voice is connected
//! ([`crate::app::AppState::voice_page_shown`]). It takes its people from the
//! tree model ([`TreeEvent::Voice`]: the rows `TreeView::members` gave the one
//! build the tree and the members panel come from, so the page builds nothing
//! of its own) and the header and the call bar from the servers' and the
//! toolbar's signals, compares what it would show with what it showed, and
//! tells the window only when they differ. A person who starts or stops
//! talking, or mutes, is one row of the page and one render of this pane.
//!
//! The larger stage lays the people out as large avatars in a wrapping row;
//! the smaller stage (`ui.voice_compact`, and always in a window under 800
//! pixels tall) is one row of small avatars that scrolls sideways. The streams
//! of the Slint page come with the stream slices and its chat with the chat's.
use std::sync::Arc;
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
AnyElement, Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ObjectFit,
ParentElement as _, Render, StatefulInteractiveElement as _, Styled as _, StyledImage as _,
Subscription, Window, div, px,
};
use voelin_ui_vm::bridge::MemberItem;
use voelin_ui_vm::image::ImageRef;
use voelin_ui_vm::servers::logic;
use super::actions::{
Invite, LeaveVoice, OpenMember, OpenShare, OpenVoiceSettings, SetInputMuted, SetOutputMuted,
ShowVoiceView, ToggleVoiceCompact,
};
use super::tree_model::{TreeEvent, TreeModel};
use super::widgets::{Avatar, IconButton, banner_scrim, icon, live_badge, panel, speaking_bars_in};
use crate::app::AppState;
use crate::meter::Counters;
use crate::pictures::{PictureKey, picture};
use crate::signals::Area;
use crate::theme::tokens::Rgba;
use crate::theme::{VoelinTheme, hsla};
/// A window under this tall (pixels) has the smaller stage whatever the
/// setting says (`Nav.short` of the Slint front end).
pub const SHORT_WINDOW: f32 = 800.0;
/// What the page's header and call bar show, from the state.
#[derive(Clone, Debug, PartialEq)]
pub struct VoiceHead {
/// The channel we are in, as the tree shows it.
pub channel: String,
/// Its topic.
pub topic: String,
/// Its banner, empty without one.
pub banner: ImageRef,
/// Its client limit, -1 without one.
pub limit: i32,
/// Voice is connected.
pub connected: bool,
/// Our microphone is muted.
pub input_muted: bool,
/// Our sound is muted.
pub output_muted: bool,
/// The server can stream (TeamSpeak 6 with voice): the call bar has Share.
pub can_share: bool,
}
impl VoiceHead {
/// The header and the call bar for the state.
pub fn of(app: &AppState) -> Self {
let card = logic::toolbar(&app.vm, |_| ImageRef::default());
let can_share = app
.vm
.current
.and_then(|id| app.vm.sessions.get(&id))
.is_some_and(|view| view.streams_available());
Self {
channel: card.own_channel,
topic: card.own_channel_topic,
banner: card.own_channel_banner,
limit: card.own_channel_limit,
connected: card.voice_connected,
input_muted: card.input_muted,
output_muted: card.output_muted,
can_share,
}
}
}
/// The voice channel page.
pub struct VoicePage {
head: VoiceHead,
people: Arc<Vec<MemberItem>>,
/// The smaller stage by choice.
compact: bool,
/// The window is too short for the larger stage.
short: bool,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl VoicePage {
/// A page that follows `app` for the header and the call bar and `model` for
/// the people, on the stage the setting says (`compact`) in a window that is
/// `short` or not.
pub fn new(
app: &Entity<AppState>,
model: &Entity<TreeModel>,
compact: bool,
short: bool,
cx: &mut Context<Self>,
) -> Self {
let (head, counters, signals) = {
let state = app.read(cx);
(VoiceHead::of(state), state.counters().clone(), state.signals().clone())
};
let mut subscriptions =
signals.watch(app, &[Area::Servers, Area::Toolbar], cx, |this: &mut Self, app, cx| {
let head = VoiceHead::of(app.read(cx));
if head != this.head {
this.head = head;
cx.notify();
}
});
subscriptions.push(cx.subscribe(model, |this: &mut Self, _, event: &TreeEvent, cx| {
if let TreeEvent::Voice(people) = event {
this.people = people.clone();
cx.notify();
}
}));
let people = model.read(cx).voice().clone();
Self { head, people, compact, short, counters, _subscriptions: subscriptions }
}
/// What the header and the call bar show.
pub fn head(&self) -> &VoiceHead {
&self.head
}
/// The people it shows.
pub fn people(&self) -> &[MemberItem] {
&self.people
}
/// Whether the page is on the smaller stage now: chosen, or the window is too
/// short for the larger.
pub fn compact_shown(&self) -> bool {
self.compact || self.short
}
/// Whether the window is too short for the larger stage (the stage button is
/// off then).
pub fn short(&self) -> bool {
self.short
}
/// The setting `ui.voice_compact` is `compact`: tells the window if the stage
/// changes.
pub fn set_compact(&mut self, compact: bool, cx: &mut Context<Self>) {
if self.compact != compact {
self.compact = compact;
cx.notify();
}
}
/// The window is `short` (under [`SHORT_WINDOW`] tall) or not.
pub fn set_short(&mut self, short: bool, cx: &mut Context<Self>) {
if self.short != short {
self.short = short;
cx.notify();
}
}
}
/// The ring around a person's avatar: green while they talk, blue while they
/// stream (3 pixels, 2 on the smaller stage), else the quiet border of the
/// larger stage (2 pixels; the smaller has none).
fn ring(theme: &VoelinTheme, person: &MemberItem, compact: bool) -> (u8, Rgba) {
let c = &theme.colors;
let loud = if compact { 2 } else { 3 };
if person.talking {
(loud, c.success)
} else if person.streaming {
(loud, c.accent)
} else {
(if compact { 0 } else { 2 }, c.border_strong)
}
}
/// What the corner of a person's avatar says: the bars while they talk, else
/// that their sound or their microphone is off.
fn corner(theme: &VoelinTheme, person: &MemberItem, compact: bool) -> Option<AnyElement> {
let (c, bars) = (&theme.colors, if compact { 12.0 } else { 14.0 });
let size = if compact { 22.0 } else { 26.0 };
if !(person.talking || person.muted || person.sound_off) {
return None;
}
let (face, inside) = if person.talking {
if compact {
(c.accent, speaking_bars_in(theme, bars, c.on_accent).into_any_element())
} else {
(c.surface, speaking_bars_in(theme, bars, c.success).into_any_element())
}
} else {
let name = if person.sound_off { "headphone-off" } else { "mic-off" };
(c.surface, icon(name, if compact { 12.0 } else { 15.0 }, c.danger).into_any_element())
};
let (id, talking) = (person.id, person.talking);
let inset = if compact { 0.0 } else { 2.0 };
Some(
div()
.absolute()
.right(px(inset))
.bottom(px(inset))
.debug_selector(move || {
format!("voice-{}-{id}", if talking { "speaking" } else { "off" })
})
.size(px(size))
.rounded(px(size / 2.0))
.border_2()
.border_color(hsla(c.surface))
.bg(hsla(face))
.flex()
.items_center()
.justify_center()
.child(inside)
.into_any_element(),
)
}
/// One person: an avatar with its ring, the mark in its corner, the name with
/// the crown of an admin, and what they do. A click opens their card.
fn participant(theme: &VoelinTheme, person: &MemberItem, compact: bool) -> AnyElement {
let (c, m) = (&theme.colors, &theme.metrics);
let size = if compact { 54.0 } else { 80.0 };
let width = if compact { 68.0 } else { 120.0 };
let outer = size + 8.0;
let id = person.id;
let (ring_width, ring_color) = ring(theme, person, compact);
let client = u16::try_from(id).unwrap_or_default();
let name_width = width - if person.admin { 16.0 } else { 0.0 };
let words = if person.talking {
"Speaking"
} else if person.streaming {
"Streaming"
} else if person.away {
"Away"
} else {
""
};
let mut face = div()
.relative()
.size(px(outer))
.flex_none()
.rounded(px(outer / 2.0))
.border_color(hsla(ring_color))
.flex()
.items_center()
.justify_center();
face = match ring_width {
3 => face.border_3(),
2 => face.border_2(),
_ => face,
};
let mut face = face.child(
Avatar::new(("voice-avatar", id as u64), size, &person.initials, person.tint)
.image(person.avatar.clone()),
);
if let Some(mark) = corner(theme, person, compact) {
face = face.child(mark);
}
div()
.id(("voice-member", id as u64))
.debug_selector(move || format!("voice-member-{id}"))
.w(px(width))
.flex_none()
.flex()
.flex_col()
.items_center()
.gap(px(if compact { m.space_1 } else { m.space_2 }))
.cursor_pointer()
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(OpenMember { client: i32::from(client) }), cx)
})
.child(face)
.child(
div()
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(if compact { m.space_1 } else { m.space_2 }))
.child(
div()
.max_w(px(name_width))
.truncate()
.text_size(px(if compact { m.font_sm } else { m.font_md }))
.font_weight(if compact { FontWeight::NORMAL } else { FontWeight::MEDIUM })
.text_color(hsla(if person.myself { c.accent_text } else { c.text }))
.child(person.name.to_string()),
)
.when(person.admin, |row| {
row.child(icon("crown", if compact { 13.0 } else { 15.0 }, c.gold))
}),
)
.when(!compact, |column| {
column.child(
div()
.h(px(m.font_sm + 4.0))
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(m.space_2))
.when(person.talking, |row| row.child(speaking_bars_in(theme, 12.0, c.success)))
.child(
div()
.truncate()
.text_size(px(m.font_sm))
.text_color(hsla(if person.talking {
c.success
} else {
c.text_secondary
}))
.child(words),
)
.when(person.streaming && !person.talking, |row| {
row.child(icon("monitor", 14.0, c.text_secondary))
}),
)
})
.when(compact && person.streaming, |column| column.child(live_badge(theme)))
.into_any_element()
}
/// The channel's name, its topic and how many are in voice, over its banner.
fn header(
theme: &VoelinTheme,
head: &VoiceHead,
people: usize,
page: &VoicePage,
) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let banner = PictureKey::of(&head.banner);
let ink = if banner.is_some() { c.text } else { c.text_secondary };
let compact = page.compact_shown();
let count = if head.limit >= 0 {
format!("{people} in voice / {} total", head.limit)
} else {
format!("{people} in voice")
};
let stage = if page.short() {
"The window is too short for the larger stage"
} else if compact {
"Larger stage"
} else {
"Smaller stage"
};
div()
.id("voice-header")
.debug_selector(|| "voice-header".into())
.relative()
.w_full()
.flex_none()
.overflow_hidden()
.when_some(banner, |header, key| {
header
.child(
div()
.absolute()
.top(px(0.0))
.left(px(0.0))
.size_full()
.child(picture(key).size_full().object_fit(ObjectFit::Cover)),
)
.child(
div()
.id("voice-banner")
.debug_selector(|| "voice-banner".into())
.absolute()
.top(px(0.0))
.left(px(0.0))
.size_full()
.bg(banner_scrim(theme)),
)
})
.child(
div()
.relative()
.flex()
.flex_row()
.gap(px(m.space_5))
.pl(px(m.space_7))
.pr(px(m.space_5))
.pt(px(m.space_5))
.pb(px(m.space_3))
.child(div().pt(px(m.space_1)).child(icon("volume-2", 40.0, c.text_secondary)))
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.gap(px(m.space_1))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(
div()
.id("voice-channel")
.debug_selector(|| "voice-channel".into())
.flex_1()
.min_w_0()
.truncate()
.text_size(px(m.font_3xl))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(head.channel.clone()),
)
.child(
IconButton::new(
"voice-invite",
"user-plus",
"Copy invite link",
)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(Invite), cx)
}),
)
.child(
IconButton::new(
"voice-stage",
if compact { "chevron-down" } else { "chevron-up" },
stage,
)
.enabled(!page.short())
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(ToggleVoiceCompact), cx)
}),
)
.child(
IconButton::new(
"voice-chat-only",
"message-square",
"Chat only",
)
.on_click(|_, window, cx| {
window.dispatch_action(
Box::new(ShowVoiceView { on: false }),
cx,
)
}),
),
)
.when(!head.topic.is_empty(), |column| {
column.child(
div()
.truncate()
.text_size(px(m.font_md))
.text_color(hsla(ink))
.child(head.topic.clone()),
)
})
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(icon("users", 16.0, c.text_secondary))
.child(
div()
.id("voice-count")
.debug_selector(|| "voice-count".into())
.text_size(px(m.font_body))
.text_color(hsla(ink))
.child(count),
),
),
),
)
}
/// Mute, deafen, share, the voice settings and Leave, under the people.
fn call_bar(theme: &VoelinTheme, head: &VoiceHead) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let (input_muted, output_muted) = (head.input_muted, head.output_muted);
let leave = c.danger;
div()
.id("voice-callbar")
.debug_selector(|| "voice-callbar".into())
.w_full()
.flex_none()
.flex()
.flex_row()
.justify_center()
.items_center()
.gap(px(m.space_3))
.px(px(m.space_6))
.pb(px(m.space_3))
.child(
IconButton::new(
"call-mic",
if input_muted { "mic-off" } else { "mic" },
if input_muted { "Microphone off" } else { "Microphone on" },
)
.size(44.0)
.round()
.filled()
.danger()
.checked(input_muted)
.enabled(head.connected)
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(SetInputMuted { muted: !input_muted }), cx)
}),
)
.child(
IconButton::new(
"call-sound",
if output_muted { "headphone-off" } else { "headphones" },
if output_muted { "Sound off" } else { "Sound on" },
)
.size(44.0)
.round()
.filled()
.danger()
.checked(output_muted)
.enabled(head.connected)
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(SetOutputMuted { muted: !output_muted }), cx)
}),
)
.when(head.can_share, |bar| {
bar.child(
IconButton::new("call-share", "monitor-up", "Share or go live")
.size(44.0)
.round()
.filled()
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenShare), cx)),
)
})
.child(
IconButton::new("call-settings", "settings", "Voice Settings")
.size(44.0)
.round()
.filled()
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenVoiceSettings), cx)),
)
.child(
div()
.id("call-leave")
.debug_selector(|| "call-leave".into())
.h(px(m.control_height))
.px(px(m.space_5))
.flex_none()
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(m.space_3))
.rounded(px(m.radius_md))
.border_1()
.border_color(hsla(leave.with_alpha(0x73)))
.bg(hsla(c.danger_soft))
.cursor_pointer()
.hover(move |style| style.bg(hsla(c.danger_soft.mix(leave, 0.25))))
.on_click(|_, window, cx| window.dispatch_action(Box::new(LeaveVoice), cx))
.child(icon("phone-off", m.icon_md, leave))
.child(
div()
.text_size(px(m.font_body))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(leave))
.child("Leave"),
),
)
}
impl Render for VoicePage {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.voice.incr();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let compact = self.compact_shown();
let stage = if compact {
// One row, scrolling sideways when there are many; centred while it fits.
div()
.id("voice-people")
.debug_selector(|| "voice-people".into())
.w_full()
.h(px(112.0))
.flex_none()
.overflow_x_scroll()
.flex()
.flex_row()
.child(
div()
.h_full()
.flex_none()
.mx_auto()
.flex()
.flex_row()
.gap(px(m.space_3))
.px(px(m.space_6))
.pt(px(m.space_2))
.children(
self.people.iter().map(|person| participant(&theme, person, true)),
),
)
} else {
// Centred, wrapping into more rows when there are many.
div()
.id("voice-people")
.debug_selector(|| "voice-people".into())
.w_full()
// Rows taller than the page scroll; the header and the call bar keep
// their places.
.flex_shrink(1.0)
.min_h_0()
.overflow_y_scroll()
.flex()
.flex_row()
.flex_wrap()
.justify_center()
.gap_x(px(m.space_6))
.gap_y(px(m.space_4))
.px(px(m.space_6))
.pt(px(m.space_3))
.pb(px(m.space_4))
.children(self.people.iter().map(|person| participant(&theme, person, false)))
};
// A cached pane's root takes the size its place gives it.
panel(&theme)
.id("voice-page")
.debug_selector(|| "voice-page".into())
.size_full()
.child(header(&theme, &self.head, self.people.len(), self))
.child(stage)
.child(call_bar(&theme, &self.head))
.child(
div()
.flex_1()
.flex()
.items_center()
.justify_center()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("The channel's chat comes with a later slice."),
)
}
}
+563
View File
@@ -0,0 +1,563 @@
//! The few pieces the shell is made of, drawn from the theme's tokens
//! (`VoelinTheme`, not gpui-component's colours): the avatar of a server or a
//! person, the icon button, the panel and the Lucide icon. They are the GPUI
//! counterparts of `ui/components/avatar.slint`, `button.slint` and
//! `shells/common.slint`'s `Panel`.
use std::sync::Arc;
use gpui_kit::{
AnyElement, App, Background, ClickEvent, FontWeight, InteractiveElement as _, IntoElement,
ParentElement as _, RenderOnce, SharedString, StatefulInteractiveElement as _, Styled as _,
Window, div, linear_color_stop, linear_gradient, px, svg,
};
use gpui_kit::{ElementId, ObjectFit, StyledImage as _};
use voelin_ui_vm::Rgb;
use voelin_ui_vm::avatar::first_letter;
use voelin_ui_vm::image::ImageRef;
use crate::pictures::{PictureKey, picture};
use crate::theme::tokens::Rgba;
use crate::theme::{VoelinTheme, hsla};
/// A Lucide icon of the client's set, `size` pixels square, in `color`.
pub fn icon(name: &str, size: f32, color: Rgba) -> impl IntoElement {
svg().path(format!("icons/{name}.svg")).size(px(size)).flex_none().text_color(hsla(color))
}
/// What the dot on an avatar says (`Status` of `avatar.slint`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Presence {
/// No dot.
None,
/// Connected with voice.
Online,
/// Connecting.
Idle,
/// Observed invisibly.
Info,
/// Not connected.
Offline,
/// Their sound is off (a person who does not hear).
Dnd,
}
impl Presence {
/// The dot of a server's state as the engine names it
/// (`voelin_ui_vm::servers::status`): connected is online, observing is
/// blue, connecting is idle, offline has none.
pub fn of_server(status: &str) -> Self {
match status {
"connected" => Self::Online,
"observing" => Self::Info,
"connecting" => Self::Idle,
_ => Self::None,
}
}
/// The dot's colour.
fn color(self, theme: &VoelinTheme) -> Option<Rgba> {
let c = &theme.colors;
match self {
Self::None => None,
Self::Online => Some(c.success),
Self::Idle => Some(c.idle),
Self::Info => Some(c.info),
Self::Offline => Some(c.offline),
Self::Dnd => Some(c.dnd),
}
}
}
/// The colour a server or person is drawn in.
pub fn tint(color: Rgb) -> Rgba {
Rgba(color.0 << 8 | 0xff)
}
/// How opaque the veil over a banner is at its left edge and at its right
/// (`components/banner-picture.slint`: `transparentize(0.26)` and `(0.34)`).
const BANNER_VEIL: (f32, f32) = (0.74, 0.66);
/// The veil over a banner picture: the surface colour, left to right from 74 %
/// to 66 % opaque. A row's text (`text`) keeps more than 4.5 to 1 against it
/// whatever the picture, even white behind the dark theme's light text or
/// black behind the light theme's dark text. It lies over the picture and
/// under the row's own tint.
pub fn banner_scrim(theme: &VoelinTheme) -> Background {
let surface = hsla(theme.colors.surface);
linear_gradient(
90.0,
linear_color_stop(surface.opacity(BANNER_VEIL.0), 0.0),
linear_color_stop(surface.opacity(BANNER_VEIL.1), 1.0),
)
}
/// Under this size (pixels) an avatar shows one letter, larger (`avatar.slint`).
const SMALL_AVATAR: f32 = 28.0;
/// What an avatar of `size` pixels writes on its colour, and how large:
/// the initials at 0.38 of the size, but only the first letter at half of it
/// under 28 pixels, where two letters at 0.38 are a few pixels high and cramped
/// (`avatar.slint`'s `small`, with `Images.first-letter`).
fn initials_for(initials: &str, size: f32) -> (SharedString, f32) {
if size < SMALL_AVATAR {
(first_letter(initials).into(), size * 0.5)
} else {
(initials.to_owned().into(), size * 0.38)
}
}
/// An avatar: the picture when there is one (a file of the engine's cache),
/// else the initials on `tint` (one letter under 28 pixels), square with
/// rounded corners for a server and round for a person, with a presence dot and
/// a green ring while the person's voice goes out. The picture is keyed by the
/// file and its stamp ([`crate::pictures`]), so a picture the engine writes
/// again shows. Pictures other than files of the cache are drawn as initials
/// until the slices that decode them (the chat's).
#[derive(IntoElement)]
pub struct Avatar {
id: ElementId,
size: f32,
initials: SharedString,
tint: Rgb,
image: ImageRef,
square: bool,
presence: Presence,
speaking: bool,
}
impl Avatar {
/// An avatar of `size` pixels with these initials on `tint`.
pub fn new(id: impl Into<ElementId>, size: f32, initials: &str, tint: Rgb) -> Self {
Self {
id: id.into(),
size,
initials: initials.to_owned().into(),
tint,
image: ImageRef::default(),
square: false,
presence: Presence::None,
speaking: false,
}
}
/// Draw this picture when it is a file of the cache.
pub fn image(mut self, image: ImageRef) -> Self {
self.image = image;
self
}
/// A server's rounded square, not a person's circle.
pub fn square(mut self) -> Self {
self.square = true;
self
}
/// The dot at the corner.
pub fn presence(mut self, presence: Presence) -> Self {
self.presence = presence;
self
}
/// The green ring.
pub fn speaking(mut self, speaking: bool) -> Self {
self.speaking = speaking;
self
}
}
impl RenderOnce for Avatar {
fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = VoelinTheme::global(cx);
let (c, m) = (&theme.colors, &theme.metrics);
let radius = if self.square { m.radius_lg } else { self.size / 2.0 };
let key = PictureKey::of(&self.image);
let face = div()
.size(px(self.size))
.flex_none()
.rounded(px(radius))
.overflow_hidden()
.flex()
.items_center()
.justify_center()
.bg(hsla(if key.is_some() { c.surface_3 } else { tint(self.tint) }));
let face = match key {
// The picture rounds its own corners: a parent's `overflow_hidden`
// clips to a rectangle.
Some(key) => face
.child(picture(key).size_full().rounded(px(radius)).object_fit(ObjectFit::Cover)),
None => {
let (letters, size) = initials_for(&self.initials, self.size);
face.child(
div()
.text_size(px(size))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(Rgba(0xffff_ffff)))
.child(letters),
)
}
};
let mut avatar = div().id(self.id).relative().size(px(self.size)).flex_none();
if self.speaking {
avatar = avatar.child(
div()
.absolute()
.top(px(-3.0))
.left(px(-3.0))
.size(px(self.size + 6.0))
.rounded(px(radius + 3.0))
.border_2()
.border_color(hsla(c.success)),
);
}
avatar = avatar.child(face);
if let Some(color) = self.presence.color(theme) {
let dot = (self.size * 0.3).max(10.0);
avatar = avatar.child(
div()
.absolute()
.top(px(self.size - dot + 1.0))
.left(px(self.size - dot + 1.0))
.size(px(dot))
.rounded(px(dot / 2.0))
.border_2()
.border_color(hsla(c.surface))
.bg(hsla(color)),
);
}
avatar
}
}
type Handler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
/// A button that is an icon: 36 pixels (or `size`) square, round or with
/// rounded corners, with a tooltip. Without a handler or disabled it draws
/// dimmed and does nothing, and keeps its tooltip.
#[derive(IntoElement)]
pub struct IconButton {
id: ElementId,
icon: &'static str,
label: SharedString,
size: f32,
tint: Option<Rgba>,
danger: bool,
round: bool,
filled: bool,
checked: bool,
enabled: bool,
on_click: Option<Handler>,
}
impl IconButton {
/// The Lucide icon `icon` (a file name without `.svg`), named `label` for
/// the tooltip.
pub fn new(
id: impl Into<ElementId>,
icon: &'static str,
label: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
icon,
label: label.into(),
size: 34.0,
tint: None,
danger: false,
round: false,
filled: false,
checked: false,
enabled: true,
on_click: None,
}
}
/// The button's side in pixels.
pub fn size(mut self, size: f32) -> Self {
self.size = size;
self
}
/// The icon's colour, instead of the theme's icon colour.
pub fn tint(mut self, tint: Rgba) -> Self {
self.tint = Some(tint);
self
}
/// A button that turns danger-coloured when checked (mute).
pub fn danger(mut self) -> Self {
self.danger = true;
self
}
/// A circle.
pub fn round(mut self) -> Self {
self.round = true;
self
}
/// A button with a border and a face of its own (the rail's plus).
pub fn filled(mut self) -> Self {
self.filled = true;
self
}
/// Whether it is on.
pub fn checked(mut self, checked: bool) -> Self {
self.checked = checked;
self
}
/// Whether it can be used.
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
/// What a click does.
pub fn on_click(
mut self,
handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.on_click = Some(Box::new(handler));
self
}
}
impl RenderOnce for IconButton {
fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = VoelinTheme::global(cx);
let (c, m) = (&theme.colors, &theme.metrics);
let (face, ink, hover) = match (self.checked, self.danger, self.filled) {
(true, true, _) => (c.danger_soft, c.danger, c.danger_soft),
(true, false, _) => (c.accent_soft, c.accent_text, c.accent_soft_hover),
(false, _, true) => {
let ink = self.tint.unwrap_or(c.icon);
(c.surface_2, ink, ink.with_alpha(0x33))
}
(false, _, false) => (Rgba::TRANSPARENT, self.tint.unwrap_or(c.icon), c.surface_3),
};
let radius = if self.round { self.size / 2.0 } else { m.radius_md };
let icon_size = if self.size >= 40.0 { m.icon_md } else { m.icon_sm.max(self.size * 0.5) };
let label = self.label.clone();
let selector = self.id.to_string();
#[cfg(test)]
let tooltip_selector = selector.clone();
// Key the element by both its id and its label so GPUI drops stale
// hover/tooltip state when a toggle button's label changes, while
// keeping the debug selector stable for tests.
let id = ElementId::NamedChild(Arc::new(self.id), self.label);
let mut button = div()
.id(id)
.debug_selector(move || selector)
.size(px(self.size))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded(px(radius))
.bg(hsla(face))
.child(icon(self.icon, icon_size, ink));
if self.filled {
button = button.border_1().border_color(hsla(ink));
}
// The tooltip is there while the button is off too: it says why (the voice
// page's stage button in a window too short for the larger stage).
button = button.tooltip(move |window, cx| {
#[cfg(test)]
tests::record_tooltip(&tooltip_selector, &label);
gpui_kit::component::tooltip::Tooltip::new(label.clone()).build(window, cx)
});
if !self.enabled {
return button.opacity(0.4).into_any_element();
}
button = button.cursor_pointer().hover(move |style| style.bg(hsla(hover)));
match self.on_click {
Some(handler) => button.on_click(move |event, window, cx| handler(event, window, cx)),
None => button,
}
.into_any_element()
}
}
/// A rounded panel of the frame (sidebar, main area): `surface` a little
/// see-through over the backdrop, a border, clipped.
pub fn panel(theme: &VoelinTheme) -> gpui_kit::Div {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.flex()
.flex_col()
.rounded(px(m.radius_xl))
.border_1()
.border_color(hsla(c.border))
.bg(hsla(c.surface.with_alpha(235)))
.overflow_hidden()
}
/// What a card of the sidebar is drawn on.
pub fn card(theme: &VoelinTheme, alpha: u8) -> gpui_kit::Div {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.rounded(px(m.radius_lg))
.border_1()
.border_color(hsla(c.border))
.bg(hsla(c.surface_2.with_alpha(alpha)))
}
/// `element` in a box of its own that tests find by `selector` (a debug
/// selector costs nothing in a build without debug assertions): for the
/// components of gpui-component, which have none of their own.
pub fn tagged(selector: &'static str, element: impl IntoElement) -> impl IntoElement {
div().flex_none().debug_selector(|| selector.into()).child(element)
}
/// A picture of the cache in its own colours, `size` pixels square (a group's
/// or a client's icon, a badge); none when it is no picture that shows.
pub fn small_picture(image: &ImageRef, size: f32) -> Option<AnyElement> {
let key = PictureKey::of(image)?;
Some(
picture(key)
.w(px(size))
.h(px(size))
.flex_none()
.object_fit(ObjectFit::Contain)
.into_any_element(),
)
}
/// The red LIVE tag.
pub fn live_badge(theme: &VoelinTheme) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.h(px(18.0))
.px(px(5.0))
.flex_none()
.flex()
.items_center()
.rounded(px(m.radius_xs))
.bg(hsla(c.live))
.text_size(px(m.font_xs))
.font_weight(FontWeight::BOLD)
.text_color(hsla(Rgba(0xffff_ffff)))
.child("LIVE")
}
/// Three bars: someone speaks. (The Slint bars move; these stand still, as
/// nothing here may draw the window anew with the clock.)
pub fn speaking_bars(theme: &VoelinTheme, size: f32) -> impl IntoElement {
speaking_bars_in(theme, size, theme.colors.success)
}
/// The speaking bars in `color`, for a ground the green does not stand out on
/// (the accent of the voice page's corner badge).
pub fn speaking_bars_in(_theme: &VoelinTheme, size: f32, color: Rgba) -> impl IntoElement {
let bar = move |height: f32| {
div().w(px(size * 3.0 / 14.0)).h(px(size * height)).rounded(px(size / 9.0)).bg(hsla(color))
};
div()
.w(px(size))
.h(px(size))
.flex_none()
.flex()
.flex_row()
.items_center()
.justify_between()
.child(bar(1.0))
.child(bar(0.6))
.child(bar(0.8))
}
/// A small rounded label: a role, a fact (talk power, a country), a badge.
/// `picture` is a badge's own picture, `icon` a Lucide icon in the label's
/// colour.
pub fn chip(
theme: &VoelinTheme,
text: impl Into<SharedString>,
icon_name: Option<&'static str>,
picture: Option<AnyElement>,
) -> gpui_kit::Div {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.h(px(22.0))
.px(px(m.space_3))
.flex_none()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.rounded(px(m.radius_pill))
.border_1()
.border_color(hsla(c.border_strong))
.bg(hsla(c.surface_3))
.text_size(px(m.font_xs))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(c.text_secondary))
.children(icon_name.map(|name| icon(name, 12.0, c.text_secondary).into_any_element()))
.children(picture)
.child(text.into())
}
/// Tooltips built by [`IconButton`] since the last call, as `(selector, label)`.
#[cfg(test)]
pub(crate) fn take_tooltips() -> Vec<(String, String)> {
tests::TOOLTIPS.with(|log| std::mem::take(&mut *log.borrow_mut()))
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use super::*;
use crate::theme::Choice;
thread_local! {
pub(super) static TOOLTIPS: RefCell<Vec<(String, String)>> = const { RefCell::new(Vec::new()) };
}
pub(super) fn record_tooltip(selector: &str, label: &str) {
TOOLTIPS.with(|log| log.borrow_mut().push((selector.to_owned(), label.to_owned())));
}
#[test]
fn two_letters_are_written_large_enough_and_one_letter_under_28_pixels() {
// The tree's 22 pixel avatars: one letter, half the size.
assert_eq!(initials_for("DE", 22.0), (SharedString::from("D"), 11.0));
assert_eq!(initials_for("GP", 27.9).0, SharedString::from("G"));
// 28 pixels and up: the initials at 0.38 of the size.
let (letters, size) = initials_for("NS", 28.0);
assert_eq!((letters, size), (SharedString::from("NS"), 28.0 * 0.38));
assert_eq!(initials_for("NS", 46.0).0, SharedString::from("NS"));
// What the engine gave when there is none, and a letter with a mark.
assert_eq!(initials_for("", 22.0).0, SharedString::from(""));
assert_eq!(initials_for("A\u{308}B", 22.0).0, SharedString::from("A\u{308}"));
}
#[test]
fn the_banner_veil_keeps_the_text_readable_over_any_picture() {
for choice in [Choice::Dark, Choice::Light] {
let theme = VoelinTheme::new(choice, choice == Choice::Dark, 1.0);
let c = &theme.colors;
// The weakest end of the veil, over the two pictures that are the
// worst for light and dark text.
for picture in [Rgba(0x0000_00ff), Rgba(0xffff_ffff)] {
let seen = c.surface.mix(picture, 1.0 - BANNER_VEIL.1);
assert!(
c.text.contrast(seen) > 4.5,
"{choice:?}: text on {picture:?} under the veil is {}",
c.text.contrast(seen)
);
}
// Left to right, from the stronger end to the weaker, in the surface's colour.
let surface = hsla(c.surface);
assert_eq!(
banner_scrim(&theme),
linear_gradient(
90.0,
linear_color_stop(surface.opacity(0.74), 0.0),
linear_color_stop(surface.opacity(0.66), 1.0),
)
);
}
}
}
+150
View File
@@ -0,0 +1,150 @@
//! Per-area signals: `Update.refresh` of the transitions
//! ([`voelin_ui_vm::host::Refresh`]) turned into what the window's parts
//! listen to.
//!
//! The Slint front end draws again what a transition's `refresh` flags name.
//! Here a part of the window is an entity, and gpui-pre 0.3.10 draws a part
//! again when its entity is notified, so each area has an entity of its own,
//! a [`Signal`] with a generation, that the root state raises for the flags
//! of an update ([`Signals::raise`]) and that the parts observe
//! ([`Signals::watch`]): a change of the channel tree notifies the tree's
//! listeners, and the rail, the top bar and the main area are not asked
//! whether anything changed for them. A part still compares what it would show
//! with what it showed before it tells the window, for the many events that
//! set a flag and change nothing it shows.
//!
//! Only the flags of areas this front end has parts for are signals; the
//! others (`chat`, `streams`, ...) are dropped until their slices come, as
//! `perform` dropped all of them before.
use gpui_kit::{App, AppContext as _, Context, Entity, Subscription};
use voelin_ui_vm::host::Refresh;
use crate::app::AppState;
/// An area of the window that a change of the state can concern.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Area {
/// The servers: the rail, the top bar's title, the main area, the server
/// card (`Refresh::servers`).
Servers,
/// The voice and user cards of the sidebar (`Refresh::toolbar`).
Toolbar,
/// The channel tree and the members panel (`Refresh::tree`).
Tree,
/// The card over a member row (`Refresh::member_card`).
MemberCard,
}
impl Area {
/// Every area.
pub const ALL: [Area; 4] = [Area::Servers, Area::Toolbar, Area::Tree, Area::MemberCard];
}
/// The entity of an area: it has nothing but a count of how many times it was
/// raised, so that what observes it is told.
#[derive(Debug, Default)]
pub struct Signal {
generation: u64,
}
impl Signal {
/// How many times it was raised.
pub fn generation(&self) -> u64 {
self.generation
}
}
/// The signals of the areas, owned by the root state.
#[derive(Clone, Debug)]
pub struct Signals {
servers: Entity<Signal>,
toolbar: Entity<Signal>,
tree: Entity<Signal>,
member_card: Entity<Signal>,
}
impl Signals {
/// One signal per area, made in the entity `cx` belongs to.
pub fn new<T: 'static>(cx: &mut Context<T>) -> Self {
Self {
servers: cx.new(|_| Signal::default()),
toolbar: cx.new(|_| Signal::default()),
tree: cx.new(|_| Signal::default()),
member_card: cx.new(|_| Signal::default()),
}
}
/// The signal of an area.
pub fn of(&self, area: Area) -> &Entity<Signal> {
match area {
Area::Servers => &self.servers,
Area::Toolbar => &self.toolbar,
Area::Tree => &self.tree,
Area::MemberCard => &self.member_card,
}
}
/// The areas an update's flags name.
pub fn areas(refresh: &Refresh) -> Vec<Area> {
[
(refresh.servers, Area::Servers),
(refresh.toolbar, Area::Toolbar),
(refresh.tree, Area::Tree),
(refresh.member_card, Area::MemberCard),
]
.into_iter()
.filter_map(|(flagged, area)| flagged.then_some(area))
.collect()
}
/// Raise one area: whatever observes it is told.
pub fn raise_area(&self, area: Area, cx: &mut App) {
self.of(area).update(cx, |signal, cx| {
signal.generation += 1;
cx.notify();
});
}
/// Raise the areas `refresh` names, each once however many flags a batch
/// of events merged into it.
pub fn raise(&self, refresh: &Refresh, cx: &mut App) {
for area in Self::areas(refresh) {
self.raise_area(area, cx);
}
}
/// Run `on` whenever one of `areas` is raised, with the root state; the
/// subscriptions end with the part that holds them. `on` reads the state
/// outside of the part's render: a part that read the root entity while it
/// renders would be drawn again with every change of the root, which is
/// what the signals are for not doing.
pub fn watch<T: 'static>(
&self,
app: &Entity<AppState>,
areas: &[Area],
cx: &mut Context<T>,
on: impl Fn(&mut T, &Entity<AppState>, &mut Context<T>) + Clone + 'static,
) -> Vec<Subscription> {
areas
.iter()
.map(|&area| {
let (app, on) = (app.clone(), on.clone());
cx.observe(self.of(area), move |this, _, cx| on(this, &app, cx))
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_flags_of_an_update_name_the_areas_this_front_end_has() {
assert!(Signals::areas(&Refresh::default()).is_empty());
let refresh = Refresh { tree: true, servers: true, chat: true, ..Default::default() };
assert_eq!(Signals::areas(&refresh), [Area::Servers, Area::Tree], "chat has no part yet");
assert_eq!(Signals::areas(&Refresh::ALL), Area::ALL);
}
}
Loaded 100 of 321 files, more files were not shown because too many files have changed in this diff. Show more