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>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-27 20:05:46 +03:00
1 parent 01bf128c58
commit a77ccc0415
15 files changed
+1148 -578

No files matched your search

+89 -194
View File
@@ -29,19 +29,20 @@
//! streams' capture and decoder are for the slices that have those parts.
use std::task::Poll;
use std::time::{Duration, Instant};
use std::time::Duration;
use gpui_kit::{ClipboardItem, Context};
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use tracing::{debug, info, warn};
use tracing::{debug, warn};
use voelin_core::settings::{AUDIO, CACHE_FETCH_IMAGES, Settings};
use voelin_core::{Command, Engine, Event, ObserveState, VoiceState};
use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, QueryTransport, Store};
use voelin_core::{Command, Engine, Event, VoiceState};
use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, Store};
use voelin_ui_vm::bridge::{BookmarkForm, ChatLine};
use voelin_ui_vm::events;
use voelin_ui_vm::host::{Cx, Host, Persist, Update};
use voelin_ui_vm::image::ImageRef;
use voelin_ui_vm::servers::logic::{self, GatewayFound, ObservePlan};
use voelin_ui_vm::servers::logic;
use voelin_ui_vm::servers::sequence::{self, Backing};
use voelin_ui_vm::settings::{
CLIENT_PLAYBACK, ThemeChoice, UI, UI_FONT_SCALE, UI_IMAGE_PREVIEW_KB, UI_THEME, UI_WINDOW,
WindowState,
@@ -390,14 +391,31 @@ impl AppState {
&mut self,
cx: &mut Context<Self>,
f: impl FnOnce(&mut VmState, &mut Cx<'_>) -> R,
) -> R {
self.transition_with(cx, |state, transition, _| f(state, transition))
}
/// Like [`AppState::transition`], for a sequence that also reads and writes
/// the store and the secrets and picks the identity
/// (`voelin_ui_vm::servers::sequence`): the [`Backing`] is the backend's.
fn transition_with<R>(
&mut self,
cx: &mut Context<Self>,
f: impl FnOnce(&mut VmState, &mut Cx<'_>, &Backing<'_>) -> R,
) -> R {
let host = ShellHost {
demo_ui: self.switches.demo_ui,
store: &self.backend.store,
prefs: &self.backend.prefs,
};
let identity = |named| self.backend.identity_blob(named);
let backing = Backing {
store: &self.backend.store,
secrets: &*self.backend.secrets,
identity: &identity,
};
let mut transition = Cx::new(&host);
let result = f(&mut self.vm, &mut transition);
let result = f(&mut self.vm, &mut transition, &backing);
let update = transition.update;
self.perform(update, cx);
result
@@ -437,11 +455,14 @@ impl AppState {
/// Do what an update asks that this front end has the parts for.
fn perform(&mut self, update: Update, cx: &mut Context<Self>) {
let Update { status, commands, persist, warnings, rest, password, .. } = update;
let Update { status, commands, persist, warnings, rest, password, discover, .. } = update;
self.log_warnings(warnings);
for command in commands {
self.send(command);
}
for (id, address) in discover {
self.look_up_gateway(id, address);
}
if let Some(text) = status {
self.set_status(text);
}
@@ -616,19 +637,25 @@ impl AppState {
}
// The callbacks of `bind/servers.rs` that the shell has: what the
// actions of `crate::shell` do.
// actions of `crate::shell` do. The ones that read or write the store, the
// secrets or the engine's commands are the sequences of
// `voelin_ui_vm::servers::sequence`, the Slint front end's too.
/// Show a server, and observe it.
pub fn select_server(&mut self, id: i64, cx: &mut Context<Self>) {
self.transition(cx, |state, cx| logic::select_server(state, cx, id));
self.observe(id, cx);
self.transition_with(cx, |state, cx, backing| {
sequence::select_server(state, cx, backing, id)
});
cx.notify();
}
/// Connect the server on screen with voice, into its default channel.
pub fn connect_voice(&mut self, cx: &mut Context<Self>) {
let channel = self.current_bookmark().and_then(|b| b.default_channel.clone());
self.connect_voice_to(channel, None, None, cx);
// `stream_peer` stays the engine's default: what this front end can
// decode is for the slice with the stream viewer to say.
self.transition_with(cx, |state, cx, backing| {
sequence::connect_voice(state, cx, backing, None)
});
cx.notify();
}
@@ -642,27 +669,9 @@ impl AppState {
token: Option<String>,
cx: &mut Context<Self>,
) -> bool {
let Some(b) = self.current_bookmark().cloned() else { return false };
if self.switches.demo_ui {
return false;
}
let mut options = match logic::voice_options(&b, channel, channel_password, token) {
Ok(options) => options,
Err(error) => {
self.set_status(error);
return false;
}
};
options.identity =
Some(voelin_core::ts::identity::to_blob(&self.backend.identity_for(Some(&b))));
options.server_password = self.backend.secrets.get(&b.server_password_key()).ok().flatten();
// `options.stream_peer` stays the engine's default: what this front
// end can decode is for the slice with the stream viewer to say.
self.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) });
self.set_status(format!("Connecting to {}…", b.address));
// The admin may have published the gateway since it was added.
self.discover_gateway(b.id, cx);
true
self.transition_with(cx, |state, cx, backing| {
sequence::connect_voice_to(state, cx, backing, channel, channel_password, token, None)
})
}
/// Leave voice on the server on screen.
@@ -709,69 +718,34 @@ impl AppState {
/// The server dialog's form for a server (id -1: a new one).
pub fn bookmark_form(&self, id: i64) -> BookmarkForm {
let Some(b) = self.vm.bookmarks.iter().find(|b| b.id == id) else {
return BookmarkForm {
id: -1,
nickname: self.backend.default_nickname().into(),
..Default::default()
};
};
let password = self.backend.secrets.get(&b.server_password_key()).ok().flatten();
let state = self.vm.sessions.get(&b.id).map(|view| &view.state);
voelin_ui_vm::servers::form(b, state, password.as_deref().unwrap_or_default())
sequence::bookmark_form(&self.vm, &self.backend.store, &*self.backend.secrets, id)
}
/// Why a form is not saved here, if it is not: the sample servers are not
/// kept, and a server needs an address.
fn save_refused(&self, form: &BookmarkForm) -> Option<&'static str> {
if self.switches.demo_ui {
Some("The sample servers are not kept")
} else if form.address.trim().is_empty() {
Some("A server needs an address")
} else {
None
}
}
/// Save the server the form describes, and show it: its id, none when it
/// could not be saved (the status line says why).
pub fn save_bookmark(&mut self, form: &BookmarkForm, cx: &mut Context<Self>) -> Option<i64> {
if self.switches.demo_ui {
self.set_status("The sample servers are not kept");
if let Some(why) = self.save_refused(form) {
self.set_status(why);
cx.notify();
return None;
}
let old = self.vm.bookmarks.iter().find(|b| b.id == i64::from(form.id)).cloned();
let mut bookmark =
logic::bookmark_from_form(old.as_ref(), form, || self.backend.default_nickname());
if bookmark.address.is_empty() {
self.set_status("A server needs an address");
cx.notify();
return None;
}
let result = if bookmark.id < 0 {
self.backend.store.add_bookmark(&bookmark).map(|id| bookmark.id = id)
} else {
self.backend.store.update_bookmark(&bookmark)
};
if let Err(e) = result {
self.set_status(format!("Could not save: {e}"));
cx.notify();
return None;
}
let key = bookmark.server_password_key();
let result = if form.server_password.is_empty() {
self.backend.secrets.delete(&key)
} else {
self.backend.secrets.set(&key, &form.server_password)
};
if let Err(e) = result {
warn!(%e, "could not store secret");
}
// Another server: what was observed is the old one's, and its gateway
// is looked up anew.
if let Some(old) = old.filter(|old| old.address != bookmark.address) {
if old.query.is_some() {
let _ = self.backend.secrets.delete(&old.query_password_key());
}
self.vm.gateways_looked_up.remove(&bookmark.id);
self.send(Command::StopObserving { session: bookmark.id as u64 });
if let Some(view) = self.vm.sessions.get_mut(&bookmark.id) {
view.state.observe = ObserveState::Off;
}
}
self.vm.bookmarks = self.backend.store.bookmarks().unwrap_or_default();
let id = bookmark.id;
self.select_server(id, cx);
Some(id)
let saved = self.transition_with(cx, |state, cx, backing| {
sequence::save_bookmark(state, cx, backing, form)
});
cx.notify();
saved
}
/// The server dialog's Connect: save the server, then connect it with
@@ -779,12 +753,16 @@ impl AppState {
/// Only once saved: connecting what is shown after a failed save would
/// connect the server shown before. Whether it was saved.
pub fn save_and_connect(&mut self, form: &BookmarkForm, cx: &mut Context<Self>) -> bool {
let saved = self.save_bookmark(form, cx);
let bookmark = saved.and_then(|id| self.vm.bookmarks.iter().find(|b| b.id == id));
let Some(to) = voelin_ui_vm::servers::connect_to(form, bookmark) else { return false };
self.connect_voice_to(to.channel, to.channel_password, to.token, cx);
if let Some(why) = self.save_refused(form) {
self.set_status(why);
cx.notify();
return false;
}
let saved = self.transition_with(cx, |state, cx, backing| {
sequence::save_and_connect(state, cx, backing, form, None)
});
cx.notify();
true
saved
}
/// Remove a server: its session is closed, its passwords and the bookmark
@@ -795,95 +773,29 @@ impl AppState {
cx.notify();
return;
}
self.send(Command::CloseSession { session: id as u64 });
if let Some(b) = self.vm.bookmarks.iter().find(|b| b.id == id).cloned() {
let _ = self.backend.secrets.delete(&b.server_password_key());
let _ = self.backend.secrets.delete(&b.query_password_key());
}
let _ = self.backend.store.delete_bookmark(id);
let bookmarks = self.backend.store.bookmarks().unwrap_or_default();
self.transition(cx, |state, cx| logic::forget_server(state, cx, id, bookmarks));
self.transition_with(cx, |state, cx, backing| {
sequence::delete_bookmark(state, cx, backing, id)
});
cx.notify();
}
/// Observe the server invisibly ([`logic::observe_plan`]): through its
/// gateway, else its own query login. Without either the gateway is looked
/// up first, and observing starts when it is found.
fn observe(&mut self, id: i64, cx: &mut Context<Self>) {
let Some(b) = self.vm.bookmarks.iter().find(|b| b.id == id).cloned() else { return };
let session = b.id as u64;
let gateway = |app: &Self, urls| Command::ObserveGateway {
session,
urls,
identity: Box::new(voelin_core::ts::identity::to_blob(
&app.backend.identity_for(Some(&b)),
)),
};
match self.transition(cx, |state, cx| logic::observe_plan(state, cx, id)) {
ObservePlan::Nothing => return,
ObservePlan::Retry(urls) => {
debug!(server = %b.address, "still connecting to the gateway: try now");
self.send(gateway(self, urls));
return;
}
ObservePlan::Gateway(urls) => {
info!(server = %b.address, ?urls, "observing through the gateway");
self.send(gateway(self, urls));
// Still the one the server publishes?
self.discover_gateway(b.id, cx);
}
ObservePlan::Query(q) => {
let secret = self.backend.secrets.get(&b.query_password_key()).ok().flatten();
let transport = match q.transport {
QueryTransport::Raw => voelin_core::QueryTransport::Raw,
QueryTransport::Ssh => voelin_core::QueryTransport::Ssh,
QueryTransport::Http => voelin_core::QueryTransport::Http,
};
let connect = voelin_core::QueryLogin {
transport,
address: format!("{}:{}", q.host, q.port),
user: q.user.clone(),
secret,
server_port: q.server_port,
server_id: None,
allowlisted: false,
};
self.send(Command::ObserveQuery { session, connect: Box::new(connect) });
}
ObservePlan::Discover => {
self.discover_gateway(b.id, cx);
return;
}
}
self.set_status("Observing invisibly…");
}
/// Look up the gateway of a server ([`voelin_core::discover`]), once a run
/// ([`logic::discover_wanted`]), on the engine's runtime; what is found
/// comes back through [`Later`].
fn discover_gateway(&mut self, id: i64, cx: &mut Context<Self>) {
let Some(address) = self.transition(cx, |state, cx| logic::discover_wanted(state, cx, id))
else {
return;
};
/// Look the gateway of a server up ([`sequence::find_gateways`]) on the
/// engine's runtime, as `Update::discover` asks; what is found comes back
/// through [`Later`].
fn look_up_gateway(&self, id: i64, address: String) {
let Some(engine) = &self.engine else { return };
let later = self.later();
engine.runtime().spawn(async move {
let started = Instant::now();
let urls = voelin_core::discover::gateways(&address).await;
let elapsed_ms = started.elapsed().as_millis() as u64;
if urls.is_empty() {
info!(server = %address, elapsed_ms, "no gateway published");
} else {
later.run(move |app, cx| app.gateway_found(id, &address, urls, elapsed_ms, cx));
if let Some(found) = sequence::find_gateways(&address).await {
later.run(move |app, cx| {
app.gateway_found(id, &address, found.urls, found.elapsed_ms, cx)
});
}
});
}
/// Gateways were found for the server at `address` (best first); they are
/// kept unless the server changed meanwhile ([`logic::gateway_found`]), and
/// the server is observed through them if it is the one shown. Users never
/// hear of them (logged only).
/// Gateways were found for the server at `address`
/// ([`sequence::gateway_found`]).
fn gateway_found(
&mut self,
id: i64,
@@ -892,26 +804,9 @@ impl AppState {
elapsed_ms: u64,
cx: &mut Context<Self>,
) {
let found =
self.transition(cx, |state, cx| logic::gateway_found(state, cx, id, address, urls));
match found {
GatewayFound::Same => debug!(server = %address, elapsed_ms, "gateway found, as kept"),
GatewayFound::Kept { observe } => {
info!(server = %address, elapsed_ms, kept = true, "gateway found");
if observe {
self.observe(id, cx);
}
}
GatewayFound::Changed { stop, observe, urls } => {
info!(server = %address, ?urls, elapsed_ms, kept = false, "gateway found");
if stop {
self.send(Command::StopObserving { session: id as u64 });
}
if observe {
self.observe(id, cx);
}
}
}
self.transition_with(cx, |state, cx, backing| {
sequence::gateway_found(state, cx, backing, id, address, urls, elapsed_ms)
});
}
/// Leave the servers properly, so no ghost client stays behind until it
@@ -941,11 +836,11 @@ impl AppState {
mod tests {
use std::cell::Cell;
use std::rc::Rc;
use std::time::Duration;
use std::time::{Duration, Instant};
use gpui::TestAppContext;
use gpui_kit::{AppContext as _, Entity, Subscription, WindowAppearance};
use voelin_core::{Backends, Command, Event, SessionState, VoiceState};
use voelin_core::{Backends, Command, Event, ObserveState, SessionState, VoiceState};
use voelin_store::MemorySecrets;
use voelin_ui_vm::dev::logic as sample;
+38 -94
View File
@@ -18,12 +18,10 @@ use anyhow::{Context as _, Result};
use tracing::warn;
use tsclientlib::Identity;
use voelin_core::settings::{AUDIO, Settings};
use voelin_core::{AudioSettings, Command, Engine, History};
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_WINDOW, UiSettings, appearance_keys, page_keys,
};
use voelin_ui_vm::settings::{CLIENT_PLAYBACK, ClientPlaybackMap, UI, UI_WINDOW, UiSettings};
/// The client's database, its settings and its secrets.
pub struct Backend {
@@ -59,42 +57,20 @@ pub fn data_dir() -> PathBuf {
voelin_platform::paths::data_dir()
}
/// The settings service on the client database in `dir`: the UI's keys
/// registered, 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.
/// 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 {
let prefs = Settings::open(&dir.join("client.db")).unwrap_or_else(|e| {
warn!(%e, "settings are not stored this time");
Settings::in_memory()
});
register_keys(&prefs);
let config = std::env::var_os("VOELIN_CONFIG")
.map(PathBuf::from)
.or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists()));
let mut errors = match config.map(|path| prefs.load_config_file(&path)) {
Some(Ok(errors)) => errors,
Some(Err(e)) => vec![e],
None => Vec::new(),
};
errors.extend(prefs.apply_env(std::env::vars()));
for e in errors {
warn!(%e, "setting ignored");
}
prefs
voelin_ui_vm::settings::open_settings(dir, &[], register_own_keys)
}
/// Make the keys this front end reads known to `prefs`.
fn register_keys(prefs: &Settings) {
prefs.register(&UI);
prefs.register(&CLIENT_PLAYBACK);
/// The key that only this front end uses: where the window was
/// (`ui.window`).
fn register_own_keys(prefs: &Settings) {
prefs.register(&UI_WINDOW);
for key in appearance_keys() {
prefs.register(key);
}
for key in page_keys() {
prefs.register(key);
}
}
impl Backend {
@@ -120,7 +96,8 @@ impl Backend {
/// fresh identity: the tests', and the sample data's.
pub fn in_memory() -> Result<Self> {
let prefs = Settings::in_memory();
register_keys(&prefs);
voelin_ui_vm::settings::register_keys(&prefs);
register_own_keys(&prefs);
Ok(Self {
store: Store::open_in_memory()?,
prefs,
@@ -159,32 +136,15 @@ impl Backend {
/// 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.
/// at start ([`Store::identity_for`]).
pub fn identity_for(&self, bookmark: Option<&Bookmark>) -> Identity {
let entries = self.store.identities().unwrap_or_default();
let id = bookmark
.and_then(|b| b.identity)
.filter(|id| entries.iter().any(|e| e.id == *id))
.or_else(|| self.store.default_identity().ok().flatten().map(|e| e.id));
id.and_then(|id| self.store.identity(id).ok()).unwrap_or_else(|| self.identity.clone())
self.store.identity_for(bookmark.and_then(|b| b.identity), &self.identity)
}
/// The nickname a new server gets: the default identity's (one imported
/// from TeamSpeak keeps the nickname used there), else the system user's.
pub fn default_nickname(&self) -> String {
self.store
.default_identity()
.ok()
.flatten()
.map(|identity| identity.name)
.filter(|name| {
![CREATED_IDENTITY, voelin_core::ts::identity::DEFAULT_NICKNAME]
.contains(&name.as_str())
})
.or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok())
// Servers refuse an empty nickname.
.filter(|name| !name.trim().is_empty())
.unwrap_or_else(|| "Voelin user".to_owned())
/// 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.
@@ -202,40 +162,7 @@ pub fn default_secrets(demo: bool) -> Box<dyn Secrets> {
if demo {
Box::new(MemorySecrets::default())
} else {
Box::new(FallbackSecrets {
keyring: voelin_store::KeyringSecrets::new("voelin"),
memory: MemorySecrets::default(),
})
}
}
/// The keyring first, memory when it cannot keep a secret (the Slint front
/// end's `FallbackSecrets`, repeated: both go into `voelin-store` when the
/// Slint front end is retired).
struct FallbackSecrets {
keyring: voelin_store::KeyringSecrets,
memory: MemorySecrets,
}
impl Secrets for FallbackSecrets {
fn get(&self, key: &str) -> voelin_store::Result<Option<String>> {
match self.memory.get(key)? {
Some(v) => Ok(Some(v)),
None => Ok(self.keyring.get(key).unwrap_or(None)),
}
}
fn set(&self, key: &str, value: &str) -> voelin_store::Result<()> {
if let Err(error) = self.keyring.set(key, value) {
warn!(%error, "keyring unavailable, keeping the secret for this session only");
return self.memory.set(key, value);
}
Ok(())
}
fn delete(&self, key: &str) -> voelin_store::Result<()> {
let _ = self.keyring.delete(key);
self.memory.delete(key)
Box::new(voelin_store::FallbackSecrets::new("voelin"))
}
}
@@ -301,6 +228,23 @@ mod tests {
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();