feat(client): finish node menu, categories, node settings and forum client wiring

This commit is contained in:
Loki 2026-11-01 16:25:25 +01:00
parent f04691c3cd
commit c2fc5529b7
Signed by: boba
GPG key ID: 253067914055423B
20 changed files with 1374 additions and 446 deletions

12
TODO.md
View file

@ -11,13 +11,13 @@
### Форумы: отдельные темы и ответы через gateway
- [ ] Сначала согласовать LNEx-контракт: список тем, создание, открытие,
- [x] Сначала согласовать LNEx-контракт: список тем, создание, открытие,
история и ответы; capability старого gateway, права узла/сообщества и лимиты.
- [ ] Добавить сетевые команды/события и состояние форума с защитой от устаревших
- [x] Добавить сетевые команды/события и состояние форума с защитой от устаревших
ответов после смены сервера/канала и понятными состояниями загрузки/ошибки.
- [ ] Показывать настоящий список тем, создание темы с первым сообщением,
открытие истории и ответы, подтверждённые gateway; не подменять форум плоским чатом.
- [ ] Сохранить безопасное поведение аудио: форум и категория никогда не
- [x] Сохранить безопасное поведение аудио: форум и категория никогда не
инициируют voice join или захват микрофона; старый gateway не получает новые пакеты.
- [ ] Проверить wire/state регрессии, отсутствие ложного успеха при отказе,
контекст узла/сообщества и headless UI только в виртуальном display/профиле.
@ -288,11 +288,11 @@ Release `20261101-f16a49f9c678`, запуск через `~/.local/bin/vnox-clie
### Меню узла, настройки и категории
- [ ] Добавить раскрытие меню по имени сервера и отдельные настройки узла
- [x] Добавить раскрытие меню по имени сервера и отдельные настройки узла
только по подтверждённым правам; настоящее сохранение имени сервера с ACK/error.
- [ ] По правой кнопке в списке каналов открыть меню «Текстовый / Голосовой /
- [x] По правой кнопке в списке каналов открыть меню «Текстовый / Голосовой /
Категория / Форум»; контекст категории сохранять, правая кнопка не входит в голос.
- [ ] Показать категории с дочерними каналами и сворачиванием; повторно проверять
- [x] Показать категории с дочерними каналами и сворачиванием; повторно проверять
capability и session fence для всех операций. Меню закрываются Escape/вне меню,
клавиатурные действия поддерживаются; никаких пустых страниц настроек.
- [ ] Проверить сохранение имени/категорий через сервер и виртуальные UI-сценарии

View file

@ -387,11 +387,23 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
window.on_channel_selected(move |id| {
let id = id.to_string();
let mut s = state.borrow_mut();
let kind = s.ui.channels.iter().find(|channel| channel.id == id && channel.guild_id == s.ui.active_guild_id).map(|channel|channel.kind.as_str()).unwrap_or("").to_owned();
if kind == "forum" { ui::forum::select(&mut s, &id); return; }
let kind =
s.ui.channels
.iter()
.find(|channel| channel.id == id && channel.guild_id == s.ui.active_guild_id)
.map(|channel| channel.kind.as_str())
.unwrap_or("")
.to_owned();
if kind == "forum" {
ui::forum::select(&mut s, &id);
return;
}
let send_join = match kind.as_str() {
"voice" => s.ui.request_voice_join(&id),
"text" => { s.ui.select_text_channel(id.clone()); true },
"text" => {
s.ui.select_text_channel(id.clone());
true
}
_ => return,
};
let net = s.net.clone();

View file

@ -4,22 +4,34 @@ use tokio::io::AsyncWrite;
use tokio::sync::mpsc;
pub fn is_mutation(request: &wire::ForumRequest) -> bool {
matches!(wire::ForumOperation::try_from(request.operation), Ok(wire::ForumOperation::Create | wire::ForumOperation::Reply))
matches!(
wire::ForumOperation::try_from(request.operation),
Ok(wire::ForumOperation::Create | wire::ForumOperation::Reply)
)
}
pub async fn unsupported(request: &wire::ForumRequest, events: &mpsc::Sender<NetEvent>) {
error(request, "This server does not support forums yet.", events).await;
}
pub async fn error(request: &wire::ForumRequest, message: &str, events: &mpsc::Sender<NetEvent>) {
let _ = events.send(NetEvent::ForumResult(wire::ForumResult {
request_id: request.request_id.clone(), operation: request.operation,
channel_id: request.channel_id.clone(), topic_id: request.topic_id.clone(),
error_code: u32::MAX, error: message.into(),
..Default::default()
})).await;
let _ = events
.send(NetEvent::ForumResult(Box::new(wire::ForumResult {
request_id: request.request_id.clone(),
operation: request.operation,
channel_id: request.channel_id.clone(),
topic_id: request.topic_id.clone(),
error_code: u32::MAX,
error: message.into(),
..Default::default()
})))
.await;
}
pub async fn write(stream: &mut (impl AsyncWrite + Unpin), seq: &mut u32, request: &wire::ForumRequest) -> anyhow::Result<()> {
pub async fn write(
stream: &mut (impl AsyncWrite + Unpin),
seq: &mut u32,
request: &wire::ForumRequest,
) -> anyhow::Result<()> {
framing::write(stream, PID_FORUM_REQUEST, seq, &wire::encode(request)?).await
}
@ -29,19 +41,41 @@ mod tests {
#[tokio::test]
async fn unsupported_server_returns_correlated_forum_error_without_join_error() {
let (tx, mut rx) = mpsc::channel(1);
let request = wire::ForumRequest { request_id: "request".into(), channel_id: "forum".into(), topic_id: "topic".into(), operation: wire::ForumOperation::Open as i32, ..Default::default() };
let request = wire::ForumRequest {
request_id: "request".into(),
channel_id: "forum".into(),
topic_id: "topic".into(),
operation: wire::ForumOperation::Open as i32,
..Default::default()
};
unsupported(&request, &tx).await;
let NetEvent::ForumResult(result) = rx.recv().await.unwrap() else { panic!("forum errors must stay separate from join errors") };
assert_eq!(result.request_id, "request"); assert_eq!(result.channel_id, "forum"); assert_eq!(result.topic_id, "topic"); assert_ne!(result.error_code, 0);
let NetEvent::ForumResult(result) = rx.recv().await.unwrap() else {
panic!("forum errors must stay separate from join errors")
};
assert_eq!(result.request_id, "request");
assert_eq!(result.channel_id, "forum");
assert_eq!(result.topic_id, "topic");
assert_ne!(result.error_code, 0);
}
#[tokio::test]
async fn request_wire_keeps_topic_message_and_pagination_fields() {
let request = wire::ForumRequest { request_id: "request".into(), operation: wire::ForumOperation::Create as i32, channel_id: "forum".into(), topic_id: "topic".into(), message_id: "message".into(), title: "Title".into(), content: "First post".into(), offset: 12, limit: 20 };
let request = wire::ForumRequest {
request_id: "request".into(),
operation: wire::ForumOperation::Create as i32,
channel_id: "forum".into(),
topic_id: "topic".into(),
message_id: "message".into(),
title: "Title".into(),
content: "First post".into(),
offset: 12,
limit: 20,
};
let (mut sender, mut receiver) = tokio::io::duplex(4096);
write(&mut sender, &mut 0, &request).await.unwrap();
let packet = framing::read(&mut receiver).await.unwrap();
assert_eq!(packet.packet_id, PID_FORUM_REQUEST);
let decoded: wire::ForumRequest = wire::decode(&packet.payload).unwrap();
assert_eq!(decoded, request); assert!(is_mutation(&decoded));
assert_eq!(decoded, request);
assert!(is_mutation(&decoded));
}
}

View file

@ -261,6 +261,9 @@ mod tests {
expires_at: 0,
node_admin: false,
live_profiles: false,
node_settings: false,
channel_structure: false,
forums: false,
};
framing::write(
&mut stream,

View file

@ -57,7 +57,8 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
.send(NetEvent::ChannelEdited {
channel_id: p.channel_id,
channel_name: p.channel_name,
parent_id: p.parent_id, position: p.position,
parent_id: p.parent_id,
position: p.position,
})
.await;
}
@ -81,7 +82,8 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
channel_name: c.channel_name,
kind: c.kind,
guild_id: c.guild_id,
parent_id: c.parent_id, position: c.position,
parent_id: c.parent_id,
position: c.position,
})
.collect(),
})
@ -230,13 +232,15 @@ mod channel_edit_tests {
let bytes = wire::encode(&ChannelEditPayload {
channel_id: "global".into(),
channel_name: "Renamed".into(),
parent_id: None,
position: None,
})
.unwrap();
super::super::incoming(PID_CHANNEL_EDIT, &bytes, &tx)
.await
.unwrap();
assert!(
matches!(rx.recv().await.unwrap(),NetEvent::ChannelEdited{channel_id,channel_name} if channel_id=="global" && channel_name=="Renamed")
matches!(rx.recv().await.unwrap(),NetEvent::ChannelEdited{channel_id,channel_name,..} if channel_id=="global" && channel_name=="Renamed")
);
}
}

View file

@ -11,8 +11,20 @@ mod social;
pub async fn incoming(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Result<()> {
match pid {
PID_FORUM_RESULT => { let _ = tx.send(NetEvent::ForumResult(crate::net::wire::decode(payload)?)).await; }
PID_FORUM_CHANGED => { let _ = tx.send(NetEvent::ForumChanged(crate::net::wire::decode(payload)?)).await; }
PID_FORUM_RESULT => {
let _ = tx
.send(NetEvent::ForumResult(Box::new(crate::net::wire::decode(
payload,
)?)))
.await;
}
PID_FORUM_CHANGED => {
let _ = tx
.send(NetEvent::ForumChanged(Box::new(crate::net::wire::decode(
payload,
)?)))
.await;
}
PID_PROFILE_UPDATED => {
let _ = tx
.send(NetEvent::ProfileUpdated(crate::net::wire::decode(payload)?))

View file

@ -76,9 +76,17 @@ pub async fn session_loop(
.await;
if outcome.node_settings || outcome.channel_structure || outcome.forums {
framing::write(&mut stream, PID_CLIENT_FEATURES, &mut seq, &wire::encode(&wire::ClientFeatures {
node_settings: outcome.node_settings, channel_structure: outcome.channel_structure, forums: outcome.forums,
})?).await?;
framing::write(
&mut stream,
PID_CLIENT_FEATURES,
&mut seq,
&wire::encode(&wire::ClientFeatures {
node_settings: outcome.node_settings,
channel_structure: outcome.channel_structure,
forums: outcome.forums,
})?,
)
.await?;
}
let node_settings = outcome.node_settings;
let mut profile_updates = crate::net::account::subscribe_profiles();
@ -362,10 +370,14 @@ mod session_fence_tests {
channel_name: "Global".into(),
kind: "text".into(),
guild_id: None,
parent_id: None,
position: 0,
},
NetCommand::ChannelEdit {
channel_id: "global".into(),
channel_name: "Renamed".into(),
parent_id: None,
position: None,
},
NetCommand::ChannelDelete {
channel_id: "global".into(),

View file

@ -41,7 +41,14 @@ fn bytes(command: &NetCommand) -> usize {
reply_to,
} => content.len() + channel_id.len() + reply_to.as_ref().map_or(0, String::len),
NetCommand::JoinChannel { channel_id } => channel_id.len(),
NetCommand::ForumRequest(request) => request.request_id.len() + request.channel_id.len() + request.topic_id.len() + request.message_id.len() + request.title.len() + request.content.len(),
NetCommand::ForumRequest(request) => {
request.request_id.len()
+ request.channel_id.len()
+ request.topic_id.len()
+ request.message_id.len()
+ request.title.len()
+ request.content.len()
}
_ => 0,
}
}
@ -106,7 +113,9 @@ pub(super) async fn actions(
) -> Result<()> {
while let Some(action) = pending.pop_front() {
match action {
NetCommand::ForumRequest(request) => { crate::net::forum::write(stream, seq, &request).await?; }
NetCommand::ForumRequest(request) => {
crate::net::forum::write(stream, seq, &request).await?;
}
NetCommand::JoinChannel { channel_id } => {
super::core::track_channel(channels, &channel_id);
framing::write(
@ -150,7 +159,9 @@ pub(super) async fn actions(
)
.await?;
}
_ => unreachable!("only chat, image, forum mutation and join commands can wait for profile refresh"),
_ => unreachable!(
"only chat, image, forum mutation and join commands can wait for profile refresh"
),
}
}
stream.flush().await?;

View file

@ -3,8 +3,8 @@ use std::net::SocketAddr;
#[derive(Debug, Clone)]
pub enum NetEvent {
ForumResult(crate::net::wire::ForumResult),
ForumChanged(crate::net::wire::ForumChanged),
ForumResult(Box<crate::net::wire::ForumResult>),
ForumChanged(Box<crate::net::wire::ForumChanged>),
/// A local profile refresh/activity warning; it is not a gateway join refusal.
ProfileWarning {
message: String,
@ -21,7 +21,10 @@ pub enum NetEvent {
WebhookResult(WebhookManagementResult),
WebhookList(crate::net::wire::WebhookListResult),
WebhookError(crate::net::wire::WebhookErrorResult),
NodeSettingsResult { session_id: String, result: crate::net::wire::NodeSettingsResult },
NodeSettingsResult {
session_id: String,
result: crate::net::wire::NodeSettingsResult,
},
Connected {
session_id: String,
node_name: String,

View file

@ -308,7 +308,10 @@ fn sync_chat(window: &MainWindow, state: &UiState, own_user_id: &str) {
window.set_e2ee_enabled(false);
window.set_dm_partner_name(dm.map_or("", |c| c.other_nickname.as_str()).into());
window.set_show_voice(state.showing_voice);
window.set_show_chat(!state.showing_voice && (dm.is_some() || channel.is_some_and(|channel| channel.kind == "text")));
window.set_show_chat(
!state.showing_voice
&& (dm.is_some() || channel.is_some_and(|channel| channel.kind == "text")),
);
window.set_show_friends(!state.showing_voice && dm.is_none() && channel.is_none());
if let Some(dm) = dm {
window.set_active_channel_name(dm.other_nickname.as_str().into());

View file

@ -131,8 +131,7 @@ fn prepare(ui: &mut UiState) -> Option<NetCommand> {
if let Dialog::Create {
kind, parent_id, ..
} = &dialog
{
if (kind == "category" && !ui.channel_structure_supported)
&& ((kind == "category" && !ui.channel_structure_supported)
|| (kind == "forum" && !ui.forum.supported)
|| parent_id.as_ref().is_some_and(|parent| {
!ui.channels.iter().any(|channel| {
@ -140,12 +139,11 @@ fn prepare(ui: &mut UiState) -> Option<NetCommand> {
&& channel.kind == "category"
&& channel.guild_id.is_none()
})
})
{
ui.channel_admin.error =
super::i18n::text("This channel type or category is no longer available.");
return None;
}
}))
{
ui.channel_admin.error =
super::i18n::text("This channel type or category is no longer available.");
return None;
}
let name = dialog.name().trim();
if !matches!(dialog, Dialog::Delete { .. })
@ -403,208 +401,6 @@ pub fn sync(window: &MainWindow, ui: &UiState) {
window.set_channel_admin_error(ui.channel_admin.error.as_str().into());
}
#[cfg(test)]
mod tests {
use super::*;
fn admin() -> UiState {
UiState {
node_admin: true,
conn: ConnState::Connected {
session_id: "fixture".into(),
node_name: "Fixture server".into(),
},
central_account: Some(crate::net::account::AccountSummary {
user_id: "fixture-account".into(),
handle: "fixture".into(),
display_name: "Fixture".into(),
avatar_url: None,
profile_complete: false,
}),
channels: vec![
crate::ui::state::Channel {
id: "global".into(),
name: "General".into(),
kind: "text".into(),
guild_id: None,
members: vec![],
},
crate::ui::state::Channel {
id: "guild-channel".into(),
name: "Guild".into(),
kind: "voice".into(),
guild_id: Some("guild".into()),
members: vec![],
},
],
..Default::default()
}
}
#[test]
fn every_management_command_is_scoped_to_the_session_that_prepared_it() {
for (operation, value) in [
("create", "text"),
("rename", "global"),
("delete", "global"),
] {
let mut ui = admin();
open(&mut ui, operation, value);
if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog {
*name = "New".into();
}
let command = prepare_for_session(&mut ui).unwrap();
ui.conn = ConnState::Connected {
session_id: "replacement-session".into(),
node_name: "Other node".into(),
};
match command {
NetCommand::ForSession {
session_id,
command,
} => {
assert_eq!(session_id, "fixture");
assert!(matches!(
*command,
NetCommand::ChannelCreate { .. }
| NetCommand::ChannelEdit { .. }
| NetCommand::ChannelDelete { .. }
));
}
_ => panic!("management command escaped its original session"),
}
}
}
#[test]
fn capability_and_global_scope_are_rechecked_for_every_action() {
let mut ui = admin();
ui.node_admin = false;
open(&mut ui, "create", "text");
assert!(ui.channel_admin.dialog.is_none());
ui.node_admin = true;
open(&mut ui, "rename", "guild-channel");
assert!(ui.channel_admin.dialog.is_none());
ui.active_guild_id = Some("guild".into());
open(&mut ui, "create", "text");
assert!(ui.channel_admin.dialog.is_none());
ui.active_guild_id = None;
open(&mut ui, "create", "text");
ui.node_admin = false;
assert!(prepare(&mut ui).is_none());
tick(&mut ui);
assert!(ui.channel_admin.dialog.is_none());
}
#[test]
fn create_keeps_stable_id_and_draft_until_matching_server_confirmation() {
let mut ui = admin();
open(&mut ui, "create", "voice");
if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog {
*name = " New room ".into();
}
let before = ui.channels.len();
let id = match prepare(&mut ui).unwrap() {
NetCommand::ChannelCreate {
channel_id,
channel_name,
kind,
guild_id,
} => {
assert_eq!(channel_name, "New room");
assert_eq!(kind, "voice");
assert!(guild_id.is_none());
channel_id
}
_ => panic!(),
};
assert_eq!(ui.channels.len(), before);
assert!(prepare(&mut ui).is_none());
receive(
&mut ui,
&NetEvent::ChannelCreated {
channel_id: "unrelated".into(),
channel_name: "Other".into(),
kind: "voice".into(),
guild_id: None,
},
);
assert!(ui.channel_admin.pending.is_some());
receive(
&mut ui,
&NetEvent::Error {
code: 1,
message: "permission denied".into(),
},
);
assert!(ui.channel_admin.pending.is_none());
assert!(!ui.channel_admin.error.is_empty());
assert_eq!(ui.channel_admin.dialog.as_ref().unwrap().id(), id);
assert!(prepare(&mut ui).is_some());
receive(
&mut ui,
&NetEvent::ChannelState {
channel_id: id,
channel_name: "New room".into(),
kind: "voice".into(),
guild_id: None,
members: vec![],
voice_endpoint: String::new(),
},
);
assert!(ui.channel_admin.dialog.is_none());
}
#[test]
fn rename_and_delete_require_submit_and_matching_ack_and_handle_disconnect() {
let mut ui = admin();
open(&mut ui, "rename", "global");
if let Some(Dialog::Rename { name, .. }) = &mut ui.channel_admin.dialog {
*name = "Renamed".into();
}
assert!(
matches!(prepare(&mut ui),Some(NetCommand::ChannelEdit{channel_name,..}) if channel_name=="Renamed")
);
receive(
&mut ui,
&NetEvent::ChannelEdited {
channel_id: "global".into(),
channel_name: "Renamed".into(),
},
);
assert!(ui.channel_admin.dialog.is_none());
open(&mut ui, "delete", "global");
assert!(ui.channel_admin.pending.is_none());
assert_eq!(ui.channels.len(), 2);
assert!(
matches!(prepare(&mut ui),Some(NetCommand::ChannelDelete{channel_id}) if channel_id=="global")
);
receive(
&mut ui,
&NetEvent::Disconnected {
reason: "fixture".into(),
will_retry: false,
},
);
assert!(!ui.node_admin);
assert!(ui.channel_admin.dialog.is_none());
}
#[test]
fn invalid_names_and_timeout_do_not_mutate_channels_or_duplicate_requests() {
let mut ui = admin();
open(&mut ui, "create", "text");
assert!(prepare(&mut ui).is_none());
if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog {
*name = "bad\nname".into();
}
assert!(prepare(&mut ui).is_none());
if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog {
*name = "Valid".into();
}
assert!(prepare(&mut ui).is_some());
ui.channel_admin.pending = Some(Instant::now() - Duration::from_secs(11));
tick(&mut ui);
assert!(ui.channel_admin.pending.is_none());
assert!(!ui.channel_admin.error.is_empty());
assert_eq!(ui.channels.len(), 2);
}
}
struct MenuAction {
text: String,
icon: &'static str,
@ -851,3 +647,288 @@ pub fn sidebar_channels(ui: &UiState) -> Vec<crate::ui::slint::ChannelItem> {
}
result
}
#[cfg(test)]
mod tests {
use super::*;
fn admin() -> UiState {
UiState {
node_admin: true,
conn: ConnState::Connected {
session_id: "fixture".into(),
node_name: "Fixture server".into(),
},
central_account: Some(crate::net::account::AccountSummary {
user_id: "fixture-account".into(),
handle: "fixture".into(),
display_name: "Fixture".into(),
avatar_url: None,
profile_complete: false,
}),
channels: vec![
crate::ui::state::Channel {
id: "global".into(),
name: "General".into(),
kind: "text".into(),
guild_id: None,
parent_id: None,
position: 0,
members: vec![],
},
crate::ui::state::Channel {
id: "guild-channel".into(),
name: "Guild".into(),
kind: "voice".into(),
guild_id: Some("guild".into()),
parent_id: None,
position: 0,
members: vec![],
},
],
..Default::default()
}
}
#[test]
fn every_management_command_is_scoped_to_the_session_that_prepared_it() {
for (operation, value) in [
("create", "text"),
("rename", "global"),
("delete", "global"),
] {
let mut ui = admin();
open(&mut ui, operation, value);
if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog {
*name = "New".into();
}
let command = prepare_for_session(&mut ui).unwrap();
ui.conn = ConnState::Connected {
session_id: "replacement-session".into(),
node_name: "Other node".into(),
};
match command {
NetCommand::ForSession {
session_id,
command,
} => {
assert_eq!(session_id, "fixture");
assert!(matches!(
*command,
NetCommand::ChannelCreate { .. }
| NetCommand::ChannelEdit { .. }
| NetCommand::ChannelDelete { .. }
));
}
_ => panic!("management command escaped its original session"),
}
}
}
#[test]
fn capability_and_global_scope_are_rechecked_for_every_action() {
let mut ui = admin();
ui.node_admin = false;
open(&mut ui, "create", "text");
assert!(ui.channel_admin.dialog.is_none());
ui.node_admin = true;
open(&mut ui, "rename", "guild-channel");
assert!(ui.channel_admin.dialog.is_none());
ui.active_guild_id = Some("guild".into());
open(&mut ui, "create", "text");
assert!(ui.channel_admin.dialog.is_none());
ui.active_guild_id = None;
open(&mut ui, "create", "text");
ui.node_admin = false;
assert!(prepare(&mut ui).is_none());
tick(&mut ui);
assert!(ui.channel_admin.dialog.is_none());
}
#[test]
fn create_keeps_stable_id_and_draft_until_matching_server_confirmation() {
let mut ui = admin();
open(&mut ui, "create", "voice");
if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog {
*name = " New room ".into();
}
let before = ui.channels.len();
let id = match prepare(&mut ui).unwrap() {
NetCommand::ChannelCreate {
channel_id,
channel_name,
kind,
guild_id,
..
} => {
assert_eq!(channel_name, "New room");
assert_eq!(kind, "voice");
assert!(guild_id.is_none());
channel_id
}
_ => panic!(),
};
assert_eq!(ui.channels.len(), before);
assert!(prepare(&mut ui).is_none());
receive(
&mut ui,
&NetEvent::ChannelCreated {
channel_id: "unrelated".into(),
channel_name: "Other".into(),
kind: "voice".into(),
guild_id: None,
parent_id: None,
position: 0,
},
);
assert!(ui.channel_admin.pending.is_some());
receive(
&mut ui,
&NetEvent::Error {
code: 1,
message: "permission denied".into(),
},
);
assert!(ui.channel_admin.pending.is_none());
assert!(!ui.channel_admin.error.is_empty());
assert_eq!(ui.channel_admin.dialog.as_ref().unwrap().id(), id);
assert!(prepare(&mut ui).is_some());
receive(
&mut ui,
&NetEvent::ChannelState {
channel_id: id,
channel_name: "New room".into(),
kind: "voice".into(),
guild_id: None,
parent_id: None,
position: 0,
members: vec![],
voice_endpoint: String::new(),
},
);
assert!(ui.channel_admin.dialog.is_none());
}
#[test]
fn rename_and_delete_require_submit_and_matching_ack_and_handle_disconnect() {
let mut ui = admin();
open(&mut ui, "rename", "global");
if let Some(Dialog::Rename { name, .. }) = &mut ui.channel_admin.dialog {
*name = "Renamed".into();
}
assert!(
matches!(prepare(&mut ui),Some(NetCommand::ChannelEdit{channel_name,..}) if channel_name=="Renamed")
);
receive(
&mut ui,
&NetEvent::ChannelEdited {
channel_id: "global".into(),
channel_name: "Renamed".into(),
parent_id: None,
position: None,
},
);
assert!(ui.channel_admin.dialog.is_none());
open(&mut ui, "delete", "global");
assert!(ui.channel_admin.pending.is_none());
assert_eq!(ui.channels.len(), 2);
assert!(
matches!(prepare(&mut ui),Some(NetCommand::ChannelDelete{channel_id}) if channel_id=="global")
);
receive(
&mut ui,
&NetEvent::Disconnected {
reason: "fixture".into(),
will_retry: false,
},
);
assert!(!ui.node_admin);
assert!(ui.channel_admin.dialog.is_none());
}
#[test]
fn invalid_names_and_timeout_do_not_mutate_channels_or_duplicate_requests() {
let mut ui = admin();
open(&mut ui, "create", "text");
assert!(prepare(&mut ui).is_none());
if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog {
*name = "bad\nname".into();
}
assert!(prepare(&mut ui).is_none());
if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog {
*name = "Valid".into();
}
assert!(prepare(&mut ui).is_some());
ui.channel_admin.pending = Some(Instant::now() - Duration::from_secs(11));
tick(&mut ui);
assert!(ui.channel_admin.pending.is_none());
assert!(!ui.channel_admin.error.is_empty());
assert_eq!(ui.channels.len(), 2);
}
fn titles(ui: &UiState) -> Vec<&'static str> {
ui.channel_admin
.menu
.as_ref()
.map(|menu| menu.actions.iter().map(|a| a.action).collect())
.unwrap_or_default()
}
#[test]
fn old_gateways_never_get_category_or_forum_dialogs_or_packets() {
let mut ui = admin();
for kind in ["category", "forum"] {
open(&mut ui, "create", kind);
assert!(
ui.channel_admin.dialog.is_none(),
"{kind} needs a capability"
);
}
ui.channel_structure_supported = true;
open(&mut ui, "create", "category");
assert!(ui.channel_admin.dialog.is_some());
if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog {
*name = "Cat".into();
}
ui.channel_structure_supported = false;
assert!(
prepare(&mut ui).is_none(),
"capability is rechecked on submit"
);
}
#[test]
fn non_admin_cannot_open_menus_or_dialogs() {
let mut ui = admin();
ui.node_admin = false;
open(&mut ui, "create", "text");
assert!(ui.channel_admin.dialog.is_none());
open_menu(&mut ui, false, "", 1.0, 1.0);
assert!(ui.channel_admin.menu.is_none());
assert!(prepare(&mut ui).is_none());
}
#[test]
fn create_inside_category_carries_parent_and_stale_session_menu_is_dropped() {
let mut ui = admin();
ui.channel_structure_supported = true;
ui.channels.push(crate::ui::state::Channel {
id: "cat".into(),
name: "Category".into(),
kind: "category".into(),
guild_id: None,
parent_id: None,
position: 0,
members: vec![],
});
open_menu(&mut ui, false, "cat", 1.0, 1.0);
let actions = titles(&ui);
assert!(actions.contains(&"text") && actions.contains(&"voice"));
create_in(&mut ui, "text", "cat");
if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog {
*name = "Inside".into();
}
let command = Box::new(prepare(&mut ui).unwrap());
assert!(
matches!(*command, NetCommand::ChannelCreate { parent_id: Some(ref p), .. } if p == "cat")
);
open_menu(&mut ui, false, "cat", 1.0, 1.0);
ui.conn = ConnState::Connected {
session_id: "other".into(),
node_name: "x".into(),
};
tick(&mut ui);
assert!(ui.channel_admin.menu.is_none());
}
}

View file

@ -238,8 +238,13 @@ pub fn tick(window: &MainWindow, state: &crate::AppState) {
window.set_image_uploading(false);
window.set_image_status("".into());
}
let visible_model = if window.get_show_forum() {window.get_forum_replies()} else {window.get_messages()};
let visible: Vec<String> = visible_model.iter()
let visible_model = if window.get_show_forum() {
window.get_forum_replies()
} else {
window.get_messages()
};
let visible: Vec<String> = visible_model
.iter()
.filter_map(|item| source_key(&item.media_source, state))
.collect();
m.cache.retain(|key, _| visible.contains(key));
@ -357,7 +362,11 @@ pub fn tick(window: &MainWindow, state: &crate::AppState) {
k.starts_with("attachment:") && e.image.is_none() && e.error == "Loading image…"
})
.count();
let model = if window.get_show_forum() {window.get_forum_replies()} else {window.get_messages()};
let model = if window.get_show_forum() {
window.get_forum_replies()
} else {
window.get_messages()
};
let mut slots = 3usize.saturating_sub(m.workers + pending_fetches);
for row in 0..model.row_count() {
let Some(mut item) = model.row_data(row) else {
@ -366,9 +375,13 @@ pub fn tick(window: &MainWindow, state: &crate::AppState) {
let previous = item.clone();
let body = item.media_source.to_string();
let source = body.as_str();
let attachment = if window.get_show_forum() { None } else { source
.strip_prefix("vnox-attachment:")
.filter(|id| uuid::Uuid::parse_str(id).is_ok()) };
let attachment = if window.get_show_forum() {
None
} else {
source
.strip_prefix("vnox-attachment:")
.filter(|id| uuid::Uuid::parse_str(id).is_ok())
};
let remote = chat_images::image_url(source);
let key = if let Some(id) = attachment {
format!(
@ -453,7 +466,9 @@ pub fn tick(window: &MainWindow, state: &crate::AppState) {
}
fn source_key(source: &str, state: &crate::AppState) -> Option<String> {
if super::forum::visible(&state.ui) && source.starts_with("vnox-attachment:") { return None; }
if super::forum::visible(&state.ui) && source.starts_with("vnox-attachment:") {
return None;
}
if let Some(id) = source
.strip_prefix("vnox-attachment:")
.filter(|id| uuid::Uuid::parse_str(id).is_ok())

View file

@ -1,126 +1,373 @@
//! Separate forum threads; all data and mutation acknowledgements come from Gateway.
mod state;
pub use state::ForumState;
use crate::{AppState, net::{NetCommand, NetEvent, NetHandle, wire}};
use super::{slint::{MainWindow, ForumTopicItem, MessageItem}, state::{ConnState, UiState}};
use super::{
slint::{ForumTopicItem, MainWindow, MessageItem},
state::{ConnState, UiState},
};
use crate::{
AppState,
net::{NetCommand, NetEvent, NetHandle, wire},
};
use slint::{Model, ModelRc, SharedString, VecModel};
pub use state::ForumState;
use std::{cell::RefCell, rc::Rc};
fn session(ui: &UiState) -> Option<String> {
if ui.connection.authentication_required { return None; }
match &ui.conn { ConnState::Connected { session_id, .. } => Some(session_id.clone()), _ => None }
if ui.connection.authentication_required {
return None;
}
match &ui.conn {
ConnState::Connected { session_id, .. } => Some(session_id.clone()),
_ => None,
}
}
fn send(ui: &UiState, net: &NetHandle, command: NetCommand) {
let Some(session_id) = session(ui) else { return; };
let net = net.clone(); tokio::spawn(async move { net.send(NetCommand::ForSession { session_id, command: Box::new(command) }).await; });
let Some(session_id) = session(ui) else {
return;
};
let net = net.clone();
tokio::spawn(async move {
net.send(NetCommand::ForSession {
session_id,
command: Box::new(command),
})
.await;
});
}
fn request(ui: &mut UiState, net: &NetHandle, operation: wire::ForumOperation, offset: u32) {
if session(ui).is_none() || !visible(ui) { return; }
if let Some(request) = ui.forum.request(operation, offset) { send(ui, net, NetCommand::ForumRequest(request)); }
if session(ui).is_none() || !visible(ui) {
return;
}
if let Some(request) = ui.forum.request(operation, offset) {
send(ui, net, NetCommand::ForumRequest(request));
}
}
pub fn visible(ui: &UiState) -> bool {
!ui.browsing_dms && !ui.showing_voice && ui.active_channel.as_ref().is_some_and(|id|
ui.channels.iter().any(|channel| &channel.id == id && channel.kind == "forum" && channel.guild_id == ui.active_guild_id))
!ui.browsing_dms
&& !ui.showing_voice
&& ui.active_channel.as_ref().is_some_and(|id| {
ui.channels.iter().any(|channel| {
&channel.id == id
&& channel.kind == "forum"
&& channel.guild_id == ui.active_guild_id
})
})
}
/// Selection never touches voice membership, credentials, audio devices or capture.
pub fn select(state: &mut AppState, id: &str) {
let channel_exists = state.ui.channels.iter().any(|channel| channel.id == id && channel.kind == "forum" && channel.guild_id == state.ui.active_guild_id);
if !channel_exists || session(&state.ui).is_none() { return; }
let channel_exists = state.ui.channels.iter().any(|channel| {
channel.id == id && channel.kind == "forum" && channel.guild_id == state.ui.active_guild_id
});
if !channel_exists || session(&state.ui).is_none() {
return;
}
state.ui.select_text_channel(id.to_owned());
if !state.ui.forum.supported {
state.ui.forum.channel_id = Some(id.to_owned());
state.ui.forum.error = super::i18n::text("This server does not support forums yet."); return;
state.ui.forum.error = super::i18n::text("This server does not support forums yet.");
return;
}
if state.ui.forum.channel_id.as_deref() == Some(id) && state.ui.forum.pending() {
return;
}
if state.ui.forum.channel_id.as_deref() == Some(id) && state.ui.forum.pending() { return; }
state.ui.forum.select(id);
send(&state.ui, &state.net, NetCommand::JoinChannel { channel_id: id.to_owned() });
send(
&state.ui,
&state.net,
NetCommand::JoinChannel {
channel_id: id.to_owned(),
},
);
}
pub fn tick(ui: &mut UiState) {
ui.forum.timeout();
}
pub fn tick(ui: &mut UiState) { ui.forum.timeout(); }
/// Observe lifecycle and a forum's view acknowledgement before issuing LIST/OPEN.
pub fn observe(ui: &mut UiState, net: &NetHandle, event: &NetEvent) {
match event {
NetEvent::Connected { forums, restored, .. } => {
if !restored { ui.forum = ForumState::default(); }
NetEvent::Connected {
forums, restored, ..
} => {
if !restored {
ui.forum = ForumState::default();
}
ui.forum.supported = *forums;
if *restored && let Some(id) = ui.forum.channel_id.clone() { ui.forum.select(&id); }
if *restored && let Some(id) = ui.forum.channel_id.clone() {
ui.forum.select(&id);
}
}
NetEvent::Disconnected { will_retry, .. } => {
if !will_retry { ui.forum = ForumState::default(); }
else { ui.forum.suspend(); }
if !will_retry {
ui.forum = ForumState::default();
} else {
ui.forum.suspend();
}
}
NetEvent::ChannelState { channel_id, kind, members, .. }
if kind == "forum" && !members.is_empty() && ui.forum.channel_id.as_deref() == Some(channel_id) && ui.forum.waiting_join.is_some() => {
ui.forum.waiting_join = None; ui.forum.joined = true;
let operation = if ui.forum.topic_id.is_some() { wire::ForumOperation::Open } else { wire::ForumOperation::List };
NetEvent::ChannelState {
channel_id,
kind,
members,
..
} if kind == "forum"
&& !members.is_empty()
&& ui.forum.channel_id.as_deref() == Some(channel_id)
&& ui.forum.waiting_join.is_some() =>
{
ui.forum.waiting_join = None;
ui.forum.joined = true;
let operation = if ui.forum.topic_id.is_some() {
wire::ForumOperation::Open
} else {
wire::ForumOperation::List
};
request(ui, net, operation, 0);
}
NetEvent::ChannelDeleted { channel_id } if ui.forum.channel_id.as_deref() == Some(channel_id) => {
NetEvent::ChannelDeleted { channel_id }
if ui.forum.channel_id.as_deref() == Some(channel_id) =>
{
ui.forum = ForumState::with_support(ui.forum.supported);
}
_ => (),
}
}
pub fn result(ui: &mut UiState, result: wire::ForumResult) {
ui.forum.result(result); remember_current_authors(ui);
ui.forum.result(result);
remember_current_authors(ui);
}
pub fn changed(ui: &mut UiState, event: wire::ForumChanged) {
ui.forum.changed(event); remember_current_authors(ui);
ui.forum.changed(event);
remember_current_authors(ui);
}
fn remember_current_authors(ui: &mut UiState) {
let authors: Vec<_> = ui.forum.topics.iter().filter_map(|topic|topic.author.clone()).chain(ui.forum.posts.iter().filter_map(|post|post.author.clone())).collect();
let authors: Vec<_> = ui
.forum
.topics
.iter()
.filter_map(|topic| topic.author.clone())
.chain(ui.forum.posts.iter().filter_map(|post| post.author.clone()))
.collect();
remember_authors(ui, authors.iter());
}
fn remember_authors<'a>(ui: &mut UiState, authors: impl Iterator<Item=&'a wire::MemberInfo>) {
fn remember_authors<'a>(ui: &mut UiState, authors: impl Iterator<Item = &'a wire::MemberInfo>) {
for author in authors {
ui.user_names.entry(author.user_id.clone()).or_insert_with(|| author.nickname.clone());
ui.member_profiles.entry(author.user_id.clone()).or_insert_with(|| (author.account_id.clone(), author.avatar_url.clone()));
ui.user_names
.entry(author.user_id.clone())
.or_insert_with(|| author.nickname.clone());
ui.member_profiles
.entry(author.user_id.clone())
.or_insert_with(|| (author.account_id.clone(), author.avatar_url.clone()));
}
}
fn author(ui: &UiState, snapshot: Option<&wire::MemberInfo>) -> String {
snapshot.map(|author|ui.user_names.get(&author.user_id).cloned().unwrap_or_else(||author.nickname.clone())).unwrap_or_default()
snapshot
.map(|author| {
ui.user_names
.get(&author.user_id)
.cloned()
.unwrap_or_else(|| author.nickname.clone())
})
.unwrap_or_default()
}
pub fn sync(window: &MainWindow, ui: &UiState, own_user_id: &str) {
let show = visible(ui); window.set_show_forum(show);
if !show { return; }
let show = visible(ui);
window.set_show_forum(show);
if !show {
return;
}
let forum = &ui.forum;
window.set_forum_channel_name(ui.channels.iter().find(|c|Some(&c.id)==ui.active_channel.as_ref()).map_or("", |c|c.name.as_str()).into());
window.set_forum_supported(forum.supported); window.set_forum_loading(forum.loading()); window.set_forum_busy(forum.busy());
window.set_forum_creating(forum.creating); window.set_forum_topic_open(forum.topic_id.is_some());
window.set_forum_title_draft(forum.title_draft.as_str().into()); window.set_forum_body_draft(forum.body_draft.as_str().into()); window.set_forum_reply_draft(forum.reply_draft.as_str().into());
window.set_forum_channel_name(
ui.channels
.iter()
.find(|c| Some(&c.id) == ui.active_channel.as_ref())
.map_or("", |c| c.name.as_str())
.into(),
);
window.set_forum_supported(forum.supported);
window.set_forum_loading(forum.loading());
window.set_forum_busy(forum.busy());
window.set_forum_creating(forum.creating);
window.set_forum_topic_open(forum.topic_id.is_some());
window.set_forum_title_draft(forum.title_draft.as_str().into());
window.set_forum_body_draft(forum.body_draft.as_str().into());
window.set_forum_reply_draft(forum.reply_draft.as_str().into());
window.set_forum_error(super::i18n::text(&forum.error).into());
window.set_forum_more_topics(forum.topics_offset.is_some()); window.set_forum_more_replies(forum.posts_offset.is_some());
window.set_forum_topic_title(forum.topics.iter().find(|t|Some(&t.topic_id)==forum.topic_id.as_ref()).map_or("", |t|t.title.as_str()).into());
window.set_forum_more_topics(forum.topics_offset.is_some());
window.set_forum_more_replies(forum.posts_offset.is_some());
window.set_forum_topic_title(
forum
.topics
.iter()
.find(|t| Some(&t.topic_id) == forum.topic_id.as_ref())
.map_or("", |t| t.title.as_str())
.into(),
);
let now = chrono::Local::now();
let topics: Vec<ForumTopicItem> = forum.topics.iter().map(|topic| ForumTopicItem { id:topic.topic_id.as_str().into(), title:topic.title.as_str().into(), author:author(ui,topic.author.as_ref()).into(), updated:super::timestamps::format_at(topic.updated_at,&now).into(), excerpt:SharedString::default(), replies:topic.reply_count.min(i32::MAX as u32) as i32 }).collect();
let posts: Vec<MessageItem> = forum.posts.iter().filter_map(|post|post.message.as_ref().map(|message| {
let avatar=ui.avatar_path_for(&message.sender_id,own_user_id).as_deref().map(super::avatar::central::image).unwrap_or_default();
let name=author(ui,post.author.as_ref());
MessageItem { message_id:message.message_id.as_str().into(), sender_id:message.sender_id.as_str().into(), sender_name:name.as_str().into(), timestamp:super::timestamps::format_at(message.timestamp,&now).into(), content:message.content.as_str().into(),media_source:message.content.as_str().into(),show_author:true,is_own:message.sender_id==own_user_id,avatar_text:super::bridge::initials(&name),has_avatar:avatar.size().width>0,avatar,media_ratio:1.0,..Default::default() }
})).collect();
if !window.get_forum_topics().iter().eq(topics.iter().cloned()) { window.set_forum_topics(ModelRc::new(VecModel::from(topics))); }
let current=window.get_forum_replies();
if current.row_count()!=posts.len() || !current.iter().zip(posts.iter()).all(|(a,b)|super::bridge::same_message(&a,b)) {window.set_forum_replies(ModelRc::new(VecModel::from(posts)));}
let topics: Vec<ForumTopicItem> = forum
.topics
.iter()
.map(|topic| ForumTopicItem {
id: topic.topic_id.as_str().into(),
title: topic.title.as_str().into(),
author: author(ui, topic.author.as_ref()).into(),
updated: super::timestamps::format_at(topic.updated_at, &now).into(),
excerpt: SharedString::default(),
replies: topic.reply_count.min(i32::MAX as u32) as i32,
})
.collect();
let posts: Vec<MessageItem> = forum
.posts
.iter()
.filter_map(|post| {
post.message.as_ref().map(|message| {
let avatar = ui
.avatar_path_for(&message.sender_id, own_user_id)
.as_deref()
.map(super::avatar::central::image)
.unwrap_or_default();
let name = author(ui, post.author.as_ref());
MessageItem {
message_id: message.message_id.as_str().into(),
sender_id: message.sender_id.as_str().into(),
sender_name: name.as_str().into(),
timestamp: super::timestamps::format_at(message.timestamp, &now).into(),
content: message.content.as_str().into(),
media_source: message.content.as_str().into(),
show_author: true,
is_own: message.sender_id == own_user_id,
avatar_text: super::bridge::initials(&name),
has_avatar: avatar.size().width > 0,
avatar,
media_ratio: 1.0,
..Default::default()
}
})
})
.collect();
if !window.get_forum_topics().iter().eq(topics.iter().cloned()) {
window.set_forum_topics(ModelRc::new(VecModel::from(topics)));
}
let current = window.get_forum_replies();
if current.row_count() != posts.len()
|| !current
.iter()
.zip(posts.iter())
.all(|(a, b)| super::bridge::same_message(&a, b))
{
window.set_forum_replies(ModelRc::new(VecModel::from(posts)));
}
}
fn perform(state: &Rc<RefCell<AppState>>, operation: wire::ForumOperation, offset: u32) {
let mut s = state.borrow_mut(); let net = s.net.clone(); request(&mut s.ui,&net,operation,offset);
let mut s = state.borrow_mut();
let net = s.net.clone();
request(&mut s.ui, &net, operation, offset);
}
pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
{ let state=state.clone(); window.on_forum_create(move || { let mut s=state.borrow_mut(); if visible(&s.ui) { s.ui.forum.create(); } }); }
{ let state=state.clone(); window.on_forum_cancel_create(move || { let mut s=state.borrow_mut(); if !s.ui.forum.pending() {s.ui.forum.creating=false;} }); }
{ let state=state.clone(); window.on_forum_back(move || { let mut s=state.borrow_mut(); if !s.ui.forum.pending() {s.ui.forum.creating=false;s.ui.forum.topic_id=None;s.ui.forum.error.clear();} }); }
{ let state=state.clone(); window.on_forum_refresh(move || {
let mut s=state.borrow_mut(); if !visible(&s.ui) || s.ui.forum.pending() { return; }
if !s.ui.forum.joined { if let Some(id)=s.ui.forum.channel_id.clone() {select(&mut s,&id);} return; }
let operation=if s.ui.forum.topic_id.is_some() {wire::ForumOperation::Open} else {wire::ForumOperation::List}; let net=s.net.clone();request(&mut s.ui,&net,operation,0);
}); }
{ let state=state.clone(); window.on_forum_open_topic(move |id| { let mut s=state.borrow_mut(); if !visible(&s.ui) {return;} if let Some(request)=s.ui.forum.open(id.as_str()) {send(&s.ui,&s.net,NetCommand::ForumRequest(request));} }); }
{ let state=state.clone(); window.on_forum_submit_topic(move ||perform(&state,wire::ForumOperation::Create,0)); }
{ let state=state.clone(); window.on_forum_submit_reply(move ||perform(&state,wire::ForumOperation::Reply,0)); }
{ let state=state.clone(); window.on_forum_load_more_topics(move || {let offset=state.borrow().ui.forum.topics_offset;if let Some(offset)=offset {perform(&state,wire::ForumOperation::List,offset);} }); }
{ let state=state.clone(); window.on_forum_load_more_replies(move || {let offset=state.borrow().ui.forum.posts_offset;if let Some(offset)=offset {perform(&state,wire::ForumOperation::Open,offset);} }); }
{ let state=state.clone(); window.on_forum_title_edited(move |value| state.borrow_mut().ui.forum.edit_title(value.to_string())); }
{ let state=state.clone(); window.on_forum_body_edited(move |value| state.borrow_mut().ui.forum.edit_body(value.to_string())); }
{ let state=state.clone(); window.on_forum_reply_edited(move |value| state.borrow_mut().ui.forum.edit_reply(value.to_string())); }
{
let state = state.clone();
window.on_forum_create(move || {
let mut s = state.borrow_mut();
if visible(&s.ui) {
s.ui.forum.create();
}
});
}
{
let state = state.clone();
window.on_forum_cancel_create(move || {
let mut s = state.borrow_mut();
if !s.ui.forum.pending() {
s.ui.forum.creating = false;
}
});
}
{
let state = state.clone();
window.on_forum_back(move || {
let mut s = state.borrow_mut();
if !s.ui.forum.pending() {
s.ui.forum.creating = false;
s.ui.forum.topic_id = None;
s.ui.forum.error.clear();
}
});
}
{
let state = state.clone();
window.on_forum_refresh(move || {
let mut s = state.borrow_mut();
if !visible(&s.ui) || s.ui.forum.pending() {
return;
}
if !s.ui.forum.joined {
if let Some(id) = s.ui.forum.channel_id.clone() {
select(&mut s, &id);
}
return;
}
let operation = if s.ui.forum.topic_id.is_some() {
wire::ForumOperation::Open
} else {
wire::ForumOperation::List
};
let net = s.net.clone();
request(&mut s.ui, &net, operation, 0);
});
}
{
let state = state.clone();
window.on_forum_open_topic(move |id| {
let mut s = state.borrow_mut();
if !visible(&s.ui) {
return;
}
if let Some(request) = s.ui.forum.open(id.as_str()) {
send(&s.ui, &s.net, NetCommand::ForumRequest(request));
}
});
}
{
let state = state.clone();
window.on_forum_submit_topic(move || perform(&state, wire::ForumOperation::Create, 0));
}
{
let state = state.clone();
window.on_forum_submit_reply(move || perform(&state, wire::ForumOperation::Reply, 0));
}
{
let state = state.clone();
window.on_forum_load_more_topics(move || {
let offset = state.borrow().ui.forum.topics_offset;
if let Some(offset) = offset {
perform(&state, wire::ForumOperation::List, offset);
}
});
}
{
let state = state.clone();
window.on_forum_load_more_replies(move || {
let offset = state.borrow().ui.forum.posts_offset;
if let Some(offset) = offset {
perform(&state, wire::ForumOperation::Open, offset);
}
});
}
{
let state = state.clone();
window.on_forum_title_edited(move |value| {
state.borrow_mut().ui.forum.edit_title(value.to_string())
});
}
{
let state = state.clone();
window.on_forum_body_edited(move |value| {
state.borrow_mut().ui.forum.edit_body(value.to_string())
});
}
{
let state = state.clone();
window.on_forum_reply_edited(move |value| {
state.borrow_mut().ui.forum.edit_reply(value.to_string())
});
}
}

View file

@ -3,7 +3,10 @@ use std::time::{Duration, Instant};
const REQUEST_TIMEOUT: Duration = Duration::from_secs(20);
struct Pending { request: wire::ForumRequest, started: Instant }
struct Pending {
request: wire::ForumRequest,
started: Instant,
}
/// View state belongs to one authenticated node session; mutations stay drafts until ACK.
#[derive(Default)]
@ -28,186 +31,524 @@ pub struct ForumState {
pending: Option<Pending>,
}
impl ForumState {
pub fn suspend(&mut self) { self.supported=false; self.joined=false; self.pending=None; self.waiting_join=None; }
pub fn with_support(supported: bool) -> Self { Self { supported, ..Default::default() } }
pub fn edit_title(&mut self, value: String) { if !self.busy() && self.title_draft != value { self.title_draft=value; self.topic_draft_id=None; self.first_message_id=None; } }
pub fn edit_body(&mut self, value: String) { if !self.busy() && self.body_draft != value { self.body_draft=value; self.topic_draft_id=None; self.first_message_id=None; } }
pub fn edit_reply(&mut self, value: String) { if !self.busy() && self.reply_draft != value { self.reply_draft=value; self.reply_message_id=None; } }
pub fn loading(&self) -> bool {
self.waiting_join.is_some() || self.pending.as_ref().is_some_and(|p| !crate::net::forum::is_mutation(&p.request))
pub fn suspend(&mut self) {
self.supported = false;
self.joined = false;
self.pending = None;
self.waiting_join = None;
}
pub fn with_support(supported: bool) -> Self {
Self {
supported,
..Default::default()
}
}
pub fn edit_title(&mut self, value: String) {
if !self.busy() && self.title_draft != value {
self.title_draft = value;
self.topic_draft_id = None;
self.first_message_id = None;
}
}
pub fn edit_body(&mut self, value: String) {
if !self.busy() && self.body_draft != value {
self.body_draft = value;
self.topic_draft_id = None;
self.first_message_id = None;
}
}
pub fn edit_reply(&mut self, value: String) {
if !self.busy() && self.reply_draft != value {
self.reply_draft = value;
self.reply_message_id = None;
}
}
pub fn loading(&self) -> bool {
self.waiting_join.is_some()
|| self
.pending
.as_ref()
.is_some_and(|p| !crate::net::forum::is_mutation(&p.request))
}
pub fn busy(&self) -> bool {
self.pending
.as_ref()
.is_some_and(|p| crate::net::forum::is_mutation(&p.request))
}
pub fn pending(&self) -> bool {
self.pending.is_some() || self.waiting_join.is_some()
}
pub fn busy(&self) -> bool { self.pending.as_ref().is_some_and(|p| crate::net::forum::is_mutation(&p.request)) }
pub fn pending(&self) -> bool { self.pending.is_some() || self.waiting_join.is_some() }
pub fn select(&mut self, channel: &str) {
if self.channel_id.as_deref() != Some(channel) { *self = Self { supported: self.supported, ..Default::default() }; }
self.channel_id = Some(channel.to_owned()); self.joined = false; self.waiting_join = Some(Instant::now()); self.error.clear();
if self.channel_id.as_deref() != Some(channel) {
*self = Self {
supported: self.supported,
..Default::default()
};
}
self.channel_id = Some(channel.to_owned());
self.joined = false;
self.waiting_join = Some(Instant::now());
self.error.clear();
}
pub fn create(&mut self) {
if self.pending() || !self.supported { return; }
self.creating = true; self.topic_id = None; self.posts.clear(); self.error.clear();
if self.pending() || !self.supported {
return;
}
self.creating = true;
self.topic_id = None;
self.posts.clear();
self.error.clear();
}
pub fn request(&mut self, operation: wire::ForumOperation, offset: u32) -> Option<wire::ForumRequest> {
if !self.supported || !self.joined || self.pending() { return None; }
pub fn request(
&mut self,
operation: wire::ForumOperation,
offset: u32,
) -> Option<wire::ForumRequest> {
if !self.supported || !self.joined || self.pending() {
return None;
}
let channel_id = self.channel_id.clone()?;
let mut request = wire::ForumRequest { request_id: uuid::Uuid::new_v4().to_string(), channel_id, operation: operation as i32, offset, limit: if operation == wire::ForumOperation::List { 20 } else { 50 }, ..Default::default() };
let mut request = wire::ForumRequest {
request_id: uuid::Uuid::new_v4().to_string(),
channel_id,
operation: operation as i32,
offset,
limit: if operation == wire::ForumOperation::List {
20
} else {
50
},
..Default::default()
};
match operation {
wire::ForumOperation::List => (),
wire::ForumOperation::Open => { request.topic_id = self.topic_id.clone()?; if offset == 0 { self.posts.clear(); self.posts_offset = None; } },
wire::ForumOperation::Open => {
request.topic_id = self.topic_id.clone()?;
if offset == 0 {
self.posts.clear();
self.posts_offset = None;
}
}
wire::ForumOperation::Create => {
let title = self.title_draft.trim(); let content = self.body_draft.trim();
if !valid_title(title) || !valid_body(content) { self.error = "Enter a title (1–160 characters) and a first message (1–16000 characters).".into(); return None; }
request.topic_id = self.topic_draft_id.get_or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone();
request.message_id = self.first_message_id.get_or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone();
request.title = title.to_owned(); request.content = content.to_owned();
let title = self.title_draft.trim();
let content = self.body_draft.trim();
if !valid_title(title) || !valid_body(content) {
self.error = "Enter a title (1–160 characters) and a first message (1–16000 characters).".into();
return None;
}
request.topic_id = self
.topic_draft_id
.get_or_insert_with(|| uuid::Uuid::new_v4().to_string())
.clone();
request.message_id = self
.first_message_id
.get_or_insert_with(|| uuid::Uuid::new_v4().to_string())
.clone();
request.title = title.to_owned();
request.content = content.to_owned();
}
wire::ForumOperation::Reply => {
if !valid_body(self.reply_draft.trim()) { self.error = "Enter a reply (1–16000 characters).".into(); return None; }
if !valid_body(self.reply_draft.trim()) {
self.error = "Enter a reply (1–16000 characters).".into();
return None;
}
request.topic_id = self.topic_id.clone()?;
request.message_id = self.reply_message_id.get_or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone();
request.message_id = self
.reply_message_id
.get_or_insert_with(|| uuid::Uuid::new_v4().to_string())
.clone();
request.content = self.reply_draft.trim().to_owned();
}
_ => return None,
}
self.error.clear(); self.pending = Some(Pending { request: request.clone(), started: Instant::now() }); Some(request)
self.error.clear();
self.pending = Some(Pending {
request: request.clone(),
started: Instant::now(),
});
Some(request)
}
pub fn open(&mut self, id: &str) -> Option<wire::ForumRequest> {
if self.pending() || !self.topics.iter().any(|topic| topic.topic_id == id) { return None; }
self.topic_id = Some(id.to_owned()); self.creating = false; self.posts.clear(); self.reply_draft.clear(); self.reply_message_id = None; self.posts_offset = None;
if self.pending() || !self.topics.iter().any(|topic| topic.topic_id == id) {
return None;
}
self.topic_id = Some(id.to_owned());
self.creating = false;
self.posts.clear();
self.reply_draft.clear();
self.reply_message_id = None;
self.posts_offset = None;
self.request(wire::ForumOperation::Open, 0)
}
pub fn timeout(&mut self) {
if self.waiting_join.is_some_and(|at| at.elapsed() >= REQUEST_TIMEOUT)
|| self.pending.as_ref().is_some_and(|p| p.started.elapsed() >= REQUEST_TIMEOUT) {
self.waiting_join = None; self.pending = None;
self.error = "The forum request timed out. Your draft has been kept; refresh or retry.".into();
if self
.waiting_join
.is_some_and(|at| at.elapsed() >= REQUEST_TIMEOUT)
|| self
.pending
.as_ref()
.is_some_and(|p| p.started.elapsed() >= REQUEST_TIMEOUT)
{
self.waiting_join = None;
self.pending = None;
self.error =
"The forum request timed out. Your draft has been kept; refresh or retry.".into();
}
}
pub fn result(&mut self, result: wire::ForumResult) {
let Some(pending) = self.pending.as_ref() else { return; };
let Some(pending) = self.pending.as_ref() else {
return;
};
let request = &pending.request;
if result.request_id != request.request_id || result.operation != request.operation || result.channel_id != request.channel_id
|| (!request.topic_id.is_empty() && result.topic_id != request.topic_id) { return; }
let request = request.clone(); self.pending = None;
if result.error_code != 0 || !result.error.is_empty() {
self.error = result.error.chars().take(500).collect();
if self.error.is_empty() { self.error = "The server refused this forum request.".into(); }
if result.request_id != request.request_id
|| result.operation != request.operation
|| result.channel_id != request.channel_id
|| (!request.topic_id.is_empty() && result.topic_id != request.topic_id)
{
return;
}
if result.topics.len() > 50 || result.posts.len() > 100
|| result.topics.iter().any(|t| t.channel_id != request.channel_id)
|| result.posts.iter().any(|p| p.topic_id != result.topic_id || p.message.as_ref().is_none_or(|m| m.channel_id != request.channel_id)) {
self.error = "The server returned an invalid forum response.".into(); return;
let request = request.clone();
self.pending = None;
if result.error_code != 0 || !result.error.is_empty() {
self.error = result.error.chars().take(500).collect();
if self.error.is_empty() {
self.error = "The server refused this forum request.".into();
}
return;
}
if result.topics.len() > 50
|| result.posts.len() > 100
|| result
.topics
.iter()
.any(|t| t.channel_id != request.channel_id)
|| result.posts.iter().any(|p| {
p.topic_id != result.topic_id
|| p.message
.as_ref()
.is_none_or(|m| m.channel_id != request.channel_id)
})
{
self.error = "The server returned an invalid forum response.".into();
return;
}
let operation = wire::ForumOperation::try_from(request.operation).ok();
if matches!(operation, Some(wire::ForumOperation::Create | wire::ForumOperation::Reply))
&& !result.posts.iter().any(|p| p.message.as_ref().is_some_and(|m| m.message_id == request.message_id)) {
self.error = "The server did not acknowledge this forum message.".into(); return;
if matches!(
operation,
Some(wire::ForumOperation::Create | wire::ForumOperation::Reply)
) && !result.posts.iter().any(|p| {
p.message
.as_ref()
.is_some_and(|m| m.message_id == request.message_id)
}) {
self.error = "The server did not acknowledge this forum message.".into();
return;
}
self.error.clear();
match operation {
Some(wire::ForumOperation::List) => {
if request.offset == 0 { self.topics.clear(); }
if request.offset == 0 {
self.topics.clear();
}
let count = result.topics.len() as u32;
for topic in result.topics { self.upsert_topic(topic); }
for topic in result.topics {
self.upsert_topic(topic);
}
self.topics_offset = next_offset(request.offset, count, result.has_more);
}
Some(wire::ForumOperation::Open) => {
let count = result.posts.len() as u32;
if result.has_more && let Some(last) = result.posts.iter().map(|p| p.ordinal).max() { self.posts.retain(|p| p.ordinal <= last); }
for topic in result.topics { self.upsert_topic(topic); }
for post in result.posts { self.upsert_post(post); }
if result.has_more
&& let Some(last) = result.posts.iter().map(|p| p.ordinal).max()
{
self.posts.retain(|p| p.ordinal <= last);
}
for topic in result.topics {
self.upsert_topic(topic);
}
for post in result.posts {
self.upsert_post(post);
}
self.posts_offset = next_offset(request.offset, count, result.has_more);
}
Some(wire::ForumOperation::Create) => {
self.creating = false; self.topic_id = Some(request.topic_id);
self.title_draft.clear(); self.body_draft.clear(); self.topic_draft_id = None; self.first_message_id = None;
self.posts.clear(); self.posts_offset = None;
for topic in result.topics { self.upsert_topic(topic); }
for post in result.posts { self.upsert_post(post); }
self.creating = false;
self.topic_id = Some(request.topic_id);
self.title_draft.clear();
self.body_draft.clear();
self.topic_draft_id = None;
self.first_message_id = None;
self.posts.clear();
self.posts_offset = None;
for topic in result.topics {
self.upsert_topic(topic);
}
for post in result.posts {
self.upsert_post(post);
}
}
Some(wire::ForumOperation::Reply) => {
self.reply_draft.clear(); self.reply_message_id = None;
for topic in result.topics { self.upsert_topic(topic); }
self.reply_draft.clear();
self.reply_message_id = None;
for topic in result.topics {
self.upsert_topic(topic);
}
// When a thread is only partially loaded, do not insert a later reply ahead
// of unseen posts: refresh/page through its chronological history instead.
if self.posts_offset.is_none() { for post in result.posts { self.upsert_post(post); } }
if self.posts_offset.is_none() {
for post in result.posts {
self.upsert_post(post);
}
}
}
_ => (),
}
}
pub fn changed(&mut self, event: wire::ForumChanged) {
if self.channel_id.as_deref() != Some(event.channel_id.as_str()) || !self.supported { return; }
if let Some(topic) = event.topic && topic.channel_id == event.channel_id { self.upsert_topic(topic); }
if self.posts_offset.is_none() && let Some(post) = event.post
if self.channel_id.as_deref() != Some(event.channel_id.as_str()) || !self.supported {
return;
}
if let Some(topic) = event.topic
&& topic.channel_id == event.channel_id
{
self.upsert_topic(topic);
}
if self.posts_offset.is_none()
&& let Some(post) = event.post
&& self.topic_id.as_deref() == Some(post.topic_id.as_str())
&& post.message.as_ref().is_some_and(|m| m.channel_id == event.channel_id) { self.upsert_post(post); }
&& post
.message
.as_ref()
.is_some_and(|m| m.channel_id == event.channel_id)
{
self.upsert_post(post);
}
}
fn upsert_topic(&mut self, topic: wire::ForumTopic) {
if let Some(current) = self.topics.iter_mut().find(|t| t.topic_id == topic.topic_id) {
if current.updated_at <= topic.updated_at { *current = topic; }
} else { self.topics.push(topic); }
self.topics.sort_by(|a,b| b.updated_at.cmp(&a.updated_at).then_with(|| a.topic_id.cmp(&b.topic_id)));
if let Some(current) = self
.topics
.iter_mut()
.find(|t| t.topic_id == topic.topic_id)
{
if current.updated_at <= topic.updated_at {
*current = topic;
}
} else {
self.topics.push(topic);
}
self.topics.sort_by(|a, b| {
b.updated_at
.cmp(&a.updated_at)
.then_with(|| a.topic_id.cmp(&b.topic_id))
});
}
fn upsert_post(&mut self, post: wire::ForumPost) {
let Some(message) = &post.message else { return; };
if !self.posts.iter().any(|p| p.message.as_ref().is_some_and(|m| m.message_id == message.message_id)) { self.posts.push(post); }
let Some(message) = &post.message else {
return;
};
if !self.posts.iter().any(|p| {
p.message
.as_ref()
.is_some_and(|m| m.message_id == message.message_id)
}) {
self.posts.push(post);
}
self.posts.sort_by_key(|post| post.ordinal);
}
}
fn next_offset(offset: u32, count: u32, has_more: bool) -> Option<u32> { (has_more && count > 0 && offset.saturating_add(count) <= 100_000).then_some(offset.saturating_add(count)) }
fn bidi_or_control(c: char) -> bool { c.is_control() || matches!(c, '\u{061c}'|'\u{200e}'|'\u{200f}'|'\u{202a}'..='\u{202e}'|'\u{2066}'..='\u{2069}') }
fn valid_title(value: &str) -> bool { !value.is_empty() && value.chars().count() <= 160 && !value.chars().any(bidi_or_control) }
fn valid_body(value: &str) -> bool { !value.is_empty() && value.chars().count() <= 16000 && value.len() <= 64*1024 && !value.chars().any(|c| bidi_or_control(c) && c != '\n' && c != '\t') }
fn next_offset(offset: u32, count: u32, has_more: bool) -> Option<u32> {
(has_more && count > 0 && offset.saturating_add(count) <= 100_000)
.then_some(offset.saturating_add(count))
}
fn bidi_or_control(c: char) -> bool {
c.is_control()
|| matches!(c, '\u{061c}'|'\u{200e}'|'\u{200f}'|'\u{202a}'..='\u{202e}'|'\u{2066}'..='\u{2069}')
}
fn valid_title(value: &str) -> bool {
!value.is_empty() && value.chars().count() <= 160 && !value.chars().any(bidi_or_control)
}
fn valid_body(value: &str) -> bool {
!value.is_empty()
&& value.chars().count() <= 16000
&& value.len() <= 64 * 1024
&& !value
.chars()
.any(|c| bidi_or_control(c) && c != '\n' && c != '\t')
}
#[cfg(test)]
mod tests {
use super::*;
fn ready() -> ForumState { ForumState { supported: true, joined: true, channel_id: Some("forum".into()), ..Default::default() } }
fn topic(id: &str) -> wire::ForumTopic { wire::ForumTopic { topic_id:id.into(),channel_id:"forum".into(),title:"A real topic".into(),..Default::default() } }
fn post(id: &str, topic: &str, ordinal: u64) -> wire::ForumPost { wire::ForumPost { topic_id:topic.into(),ordinal,message:Some(wire::ChatMessage { message_id:id.into(),channel_id:"forum".into(),content:"A real reply".into(),timestamp:1000,..Default::default() }),..Default::default() } }
fn response(request: &wire::ForumRequest) -> wire::ForumResult { wire::ForumResult { request_id:request.request_id.clone(),operation:request.operation,channel_id:request.channel_id.clone(),topic_id:request.topic_id.clone(),..Default::default() } }
fn ready() -> ForumState {
ForumState {
supported: true,
joined: true,
channel_id: Some("forum".into()),
..Default::default()
}
}
fn topic(id: &str) -> wire::ForumTopic {
wire::ForumTopic {
topic_id: id.into(),
channel_id: "forum".into(),
title: "A real topic".into(),
..Default::default()
}
}
fn post(id: &str, topic: &str, ordinal: u64) -> wire::ForumPost {
wire::ForumPost {
topic_id: topic.into(),
ordinal,
message: Some(wire::ChatMessage {
message_id: id.into(),
channel_id: "forum".into(),
content: "A real reply".into(),
timestamp: 1000,
..Default::default()
}),
..Default::default()
}
}
fn response(request: &wire::ForumRequest) -> wire::ForumResult {
wire::ForumResult {
request_id: request.request_id.clone(),
operation: request.operation,
channel_id: request.channel_id.clone(),
topic_id: request.topic_id.clone(),
..Default::default()
}
}
#[test]
fn old_server_or_unacknowledged_join_cannot_prepare_forum_packets() {
let mut state=ready();state.supported=false;assert!(state.request(wire::ForumOperation::List,0).is_none());
state.supported=true;state.joined=false;assert!(state.request(wire::ForumOperation::List,0).is_none());
let mut state = ready();
state.supported = false;
assert!(state.request(wire::ForumOperation::List, 0).is_none());
state.supported = true;
state.joined = false;
assert!(state.request(wire::ForumOperation::List, 0).is_none());
}
#[test]
fn failed_create_keeps_draft_and_stable_mutation_ids_until_matching_ack() {
let mut state=ready();state.create();state.edit_title("Topic".into());state.edit_body("Opening post".into());
let first=state.request(wire::ForumOperation::Create,0).unwrap();assert!(state.topic_id.is_none());assert_eq!(state.title_draft,"Topic");
let mut denied=response(&first);denied.error_code=5;denied.error="Permission denied".into();state.result(denied);
assert_eq!(state.body_draft,"Opening post");assert!(!state.busy());
let retry=state.request(wire::ForumOperation::Create,0).unwrap();assert_ne!(first.request_id,retry.request_id);assert_eq!(first.topic_id,retry.topic_id);assert_eq!(first.message_id,retry.message_id);
let mut stale=response(&first);stale.topics=vec![topic(&first.topic_id)];stale.posts=vec![post(&first.message_id,&first.topic_id,1)];state.result(stale);assert!(state.busy());assert_eq!(state.title_draft,"Topic");
let mut accepted=response(&retry);accepted.topics=vec![topic(&retry.topic_id)];accepted.posts=vec![post(&retry.message_id,&retry.topic_id,1)];state.result(accepted);
assert_eq!(state.topic_id.as_deref(),Some(retry.topic_id.as_str()));assert_eq!(state.posts.len(),1);assert!(state.title_draft.is_empty());assert!(state.body_draft.is_empty());assert!(!state.creating);
let mut state = ready();
state.create();
state.edit_title("Topic".into());
state.edit_body("Opening post".into());
let first = state.request(wire::ForumOperation::Create, 0).unwrap();
assert!(state.topic_id.is_none());
assert_eq!(state.title_draft, "Topic");
let mut denied = response(&first);
denied.error_code = 5;
denied.error = "Permission denied".into();
state.result(denied);
assert_eq!(state.body_draft, "Opening post");
assert!(!state.busy());
let retry = state.request(wire::ForumOperation::Create, 0).unwrap();
assert_ne!(first.request_id, retry.request_id);
assert_eq!(first.topic_id, retry.topic_id);
assert_eq!(first.message_id, retry.message_id);
let mut stale = response(&first);
stale.topics = vec![topic(&first.topic_id)];
stale.posts = vec![post(&first.message_id, &first.topic_id, 1)];
state.result(stale);
assert!(state.busy());
assert_eq!(state.title_draft, "Topic");
let mut accepted = response(&retry);
accepted.topics = vec![topic(&retry.topic_id)];
accepted.posts = vec![post(&retry.message_id, &retry.topic_id, 1)];
state.result(accepted);
assert_eq!(state.topic_id.as_deref(), Some(retry.topic_id.as_str()));
assert_eq!(state.posts.len(), 1);
assert!(state.title_draft.is_empty());
assert!(state.body_draft.is_empty());
assert!(!state.creating);
}
#[test]
fn changing_failed_draft_allocates_new_object_ids_and_stale_node_results_are_ignored() {
let mut state=ready();state.edit_title("Topic".into());state.edit_body("First".into());let old=state.request(wire::ForumOperation::Create,0).unwrap();
let mut failed=response(&old);failed.error="Denied".into();state.result(failed);state.edit_body("Changed".into());let new=state.request(wire::ForumOperation::Create,0).unwrap();assert_ne!(old.topic_id,new.topic_id);assert_ne!(old.message_id,new.message_id);
state.select("different-forum");state.result(response(&new));assert!(state.topics.is_empty());assert!(state.posts.is_empty());assert_eq!(state.channel_id.as_deref(),Some("different-forum"));
let mut state = ready();
state.edit_title("Topic".into());
state.edit_body("First".into());
let old = state.request(wire::ForumOperation::Create, 0).unwrap();
let mut failed = response(&old);
failed.error = "Denied".into();
state.result(failed);
state.edit_body("Changed".into());
let new = state.request(wire::ForumOperation::Create, 0).unwrap();
assert_ne!(old.topic_id, new.topic_id);
assert_ne!(old.message_id, new.message_id);
state.select("different-forum");
state.result(response(&new));
assert!(state.topics.is_empty());
assert!(state.posts.is_empty());
assert_eq!(state.channel_id.as_deref(), Some("different-forum"));
}
#[test]
fn pagination_uses_actual_byte_bounded_page_size_and_posts_sort_by_ordinal() {
let mut state=ready();state.topics.push(topic("topic"));let request=state.open("topic").unwrap();assert_eq!(request.limit,50);
let mut result=response(&request);result.topics=vec![topic("topic")];result.posts=vec![post("two","topic",2),post("one","topic",1)];result.has_more=true;state.result(result);
assert_eq!(state.posts_offset,Some(2));assert_eq!(state.posts.iter().map(|p|p.ordinal).collect::<Vec<_>>(),vec![1,2]);
let request=state.request(wire::ForumOperation::Open,state.posts_offset.unwrap()).unwrap();assert_eq!(request.offset,2);
let mut last=response(&request);last.posts=vec![post("three","topic",3)];state.result(last);assert!(state.posts_offset.is_none());assert_eq!(state.posts.len(),3);
let mut state = ready();
state.topics.push(topic("topic"));
let request = state.open("topic").unwrap();
assert_eq!(request.limit, 50);
let mut result = response(&request);
result.topics = vec![topic("topic")];
result.posts = vec![post("two", "topic", 2), post("one", "topic", 1)];
result.has_more = true;
state.result(result);
assert_eq!(state.posts_offset, Some(2));
assert_eq!(
state.posts.iter().map(|p| p.ordinal).collect::<Vec<_>>(),
vec![1, 2]
);
let request = state
.request(wire::ForumOperation::Open, state.posts_offset.unwrap())
.unwrap();
assert_eq!(request.offset, 2);
let mut last = response(&request);
last.posts = vec![post("three", "topic", 3)];
state.result(last);
assert!(state.posts_offset.is_none());
assert_eq!(state.posts.len(), 3);
}
#[test]
fn changed_ack_and_page_overlap_deduplicate_even_with_equal_millisecond_timestamps() {
let mut state=ready();state.topics.push(topic("topic"));state.topic_id=Some("topic".into());state.posts.push(post("first","topic",1));state.edit_reply("Own reply".into());let request=state.request(wire::ForumOperation::Reply,0).unwrap();
state.changed(wire::ForumChanged {channel_id:"forum".into(),topic:Some(topic("topic")),post:Some(post("third","topic",3))});
let mut result=response(&request);result.topics=vec![topic("topic")];result.posts=vec![post(&request.message_id,"topic",2)];state.result(result);
state.changed(wire::ForumChanged {channel_id:"forum".into(),topic:Some(topic("topic")),post:Some(post(&request.message_id,"topic",2))});
assert_eq!(state.posts.iter().map(|p|p.ordinal).collect::<Vec<_>>(),vec![1,2,3]);assert!(state.reply_draft.is_empty());
let mut state = ready();
state.topics.push(topic("topic"));
state.topic_id = Some("topic".into());
state.posts.push(post("first", "topic", 1));
state.edit_reply("Own reply".into());
let request = state.request(wire::ForumOperation::Reply, 0).unwrap();
state.changed(wire::ForumChanged {
channel_id: "forum".into(),
topic: Some(topic("topic")),
post: Some(post("third", "topic", 3)),
});
let mut result = response(&request);
result.topics = vec![topic("topic")];
result.posts = vec![post(&request.message_id, "topic", 2)];
state.result(result);
state.changed(wire::ForumChanged {
channel_id: "forum".into(),
topic: Some(topic("topic")),
post: Some(post(&request.message_id, "topic", 2)),
});
assert_eq!(
state.posts.iter().map(|p| p.ordinal).collect::<Vec<_>>(),
vec![1, 2, 3]
);
assert!(state.reply_draft.is_empty());
}
#[test]
fn timeout_keeps_text_and_retry_ids_and_invalid_reply_ack_cannot_clear_input() {
let mut state=ready();state.topic_id=Some("topic".into());state.edit_reply("Keep this".into());let request=state.request(wire::ForumOperation::Reply,0).unwrap();
state.pending.as_mut().unwrap().started=Instant::now()-REQUEST_TIMEOUT;state.timeout();assert_eq!(state.reply_draft,"Keep this");assert!(!state.error.is_empty());
let retry=state.request(wire::ForumOperation::Reply,0).unwrap();assert_eq!(request.message_id,retry.message_id);state.result(response(&retry));assert_eq!(state.reply_draft,"Keep this");assert!(!state.error.is_empty());
let mut state = ready();
state.topic_id = Some("topic".into());
state.edit_reply("Keep this".into());
let request = state.request(wire::ForumOperation::Reply, 0).unwrap();
state.pending.as_mut().unwrap().started = Instant::now() - REQUEST_TIMEOUT;
state.timeout();
assert_eq!(state.reply_draft, "Keep this");
assert!(!state.error.is_empty());
let retry = state.request(wire::ForumOperation::Reply, 0).unwrap();
assert_eq!(request.message_id, retry.message_id);
state.result(response(&retry));
assert_eq!(state.reply_draft, "Keep this");
assert!(!state.error.is_empty());
}
}

View file

@ -1,11 +1,11 @@
pub mod account;
pub mod forum;
pub mod appearance;
pub mod avatar;
pub mod bridge;
pub mod connection;
pub mod devices;
pub mod emoji;
pub mod forum;
pub mod i18n;
pub mod media;
pub mod preferences;

View file

@ -164,10 +164,12 @@ pub fn receive(ui: &mut UiState, event: &NetEvent) {
ui.server_settings = Default::default();
return;
}
let NetEvent::NodeSettingsResult {session_id,result} = event else {
let NetEvent::NodeSettingsResult { session_id, result } = event else {
return;
};
if !matches!(&ui.conn,ConnState::Connected{session_id:current,..} if current==session_id) { return; }
if !matches!(&ui.conn,ConnState::Connected{session_id:current,..} if current==session_id) {
return;
}
let matching = ui
.server_settings
.pending
@ -243,3 +245,94 @@ pub fn sync(window: &MainWindow, ui: &UiState) {
window.set_server_settings_loaded(settings.metadata.is_some());
window.set_server_settings_error(settings.error.as_str().into());
}
#[cfg(test)]
mod tests {
use super::*;
fn ui() -> UiState {
UiState {
node_admin: true,
node_settings_supported: true,
conn: ConnState::Connected {
session_id: "s".into(),
node_name: "Old".into(),
},
central_account: Some(crate::net::account::AccountSummary {
user_id: "u".into(),
handle: "h".into(),
display_name: "H".into(),
avatar_url: None,
profile_complete: false,
}),
..Default::default()
}
}
fn pending_id(ui: &UiState) -> String {
ui.server_settings.pending.as_ref().unwrap().id.clone()
}
fn result(id: &str, name: &str, code: u32) -> NetEvent {
NetEvent::NodeSettingsResult {
session_id: "s".into(),
result: wire::NodeSettingsResult {
request_id: id.into(),
display_name: name.into(),
description: String::new(),
error_code: code,
error: if code == 0 {
String::new()
} else {
"denied".into()
},
},
}
}
#[test]
fn unsupported_or_non_admin_sessions_send_nothing() {
let mut a = ui();
a.node_settings_supported = false;
assert!(open(&mut a).is_none());
let mut b = ui();
b.node_admin = false;
assert!(open(&mut b).is_none());
}
#[test]
fn name_changes_only_after_matching_ack_and_errors_keep_the_draft() {
let mut ui = ui();
assert!(matches!(open(&mut ui), Some(NetCommand::ForSession { .. })));
let load = pending_id(&ui);
receive(&mut ui, &result(&load, "Old", 0));
ui.server_settings.name = "New".into();
ui.server_settings.dirty = true;
assert!(request(&mut ui, true).is_some());
let save = pending_id(&ui);
receive(&mut ui, &result("unrelated", "Hijack", 0));
assert!(ui.server_settings.pending.is_some());
receive(&mut ui, &result(&save, "", 7));
assert!(ui.server_settings.pending.is_none());
assert_eq!(ui.server_settings.name, "New");
assert!(!ui.server_settings.error.is_empty());
assert!(request(&mut ui, true).is_some());
let retry = pending_id(&ui);
receive(&mut ui, &result(&retry, "New", 0));
assert!(matches!(&ui.conn, ConnState::Connected { node_name, .. } if node_name == "New"));
assert!(!ui.server_settings.dirty);
}
#[test]
fn results_from_another_session_are_ignored() {
let mut ui = ui();
open(&mut ui);
let id = pending_id(&ui);
let NetEvent::NodeSettingsResult { result, .. } = result(&id, "Evil", 0) else {
unreachable!()
};
receive(
&mut ui,
&NetEvent::NodeSettingsResult {
session_id: "old-session".into(),
result,
},
);
assert!(ui.server_settings.pending.is_some());
assert!(matches!(&ui.conn, ConnState::Connected { node_name, .. } if node_name == "Old"));
}
}

View file

@ -229,6 +229,8 @@ mod live_profile_tests {
name: "General".into(),
kind: "text".into(),
guild_id: None,
parent_id: None,
position: 0,
members: vec!["device-a".into(), "device-b".into()],
});
for device in ["device-a", "device-b"] {

View file

@ -24,9 +24,9 @@ pub fn process_net_events(state: &mut AppState) {
}
crate::ui::forum::observe(&mut state.ui, &state.net, &event);
match event {
NetEvent::ForumResult(result) => crate::ui::forum::result(&mut state.ui, result),
NetEvent::ForumChanged(event) => crate::ui::forum::changed(&mut state.ui, event),
NetEvent::NodeSettingsResult{..} => {},
NetEvent::ForumResult(result) => crate::ui::forum::result(&mut state.ui, *result),
NetEvent::ForumChanged(event) => crate::ui::forum::changed(&mut state.ui, *event),
NetEvent::NodeSettingsResult { .. } => {}
NetEvent::AccountRequired => {
state.ui.connection.authentication_required = true;
}
@ -424,7 +424,7 @@ fn process_net_event(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
| NetEvent::ForumResult(_)
| NetEvent::ForumChanged(_)
| NetEvent::AccountRequired
| NetEvent::NodeSettingsResult{..}
| NetEvent::NodeSettingsResult { .. }
| NetEvent::WebhookError(_) => unreachable!("handled before generic UI dispatch"),
NetEvent::Connected { .. }
| NetEvent::Disconnected { .. }
@ -507,7 +507,9 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
channel_name,
kind,
members,
guild_id, parent_id, position,
guild_id,
parent_id,
position,
..
} => {
let joined = channel_state_confirms_join(ui, &channel_id, &kind, !members.is_empty());
@ -536,7 +538,8 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
name: channel_name,
kind: kind.clone(),
guild_id: guild_id.clone(),
parent_id, position,
parent_id,
position,
members: mems,
});
}
@ -572,21 +575,27 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
channel_id,
channel_name,
kind,
guild_id, parent_id, position,
guild_id,
parent_id,
position,
} => {
if !ui.channels.iter().any(|c| c.id == channel_id) {
ui.channels.push(crate::ui::state::Channel {
id: channel_id,
name: channel_name,
kind,
guild_id, parent_id, position,
guild_id,
parent_id,
position,
members: Vec::new(),
});
}
}
NetEvent::ChannelEdited {
channel_id,
channel_name, parent_id, position,
channel_name,
parent_id,
position,
} => {
if let Some(channel) = ui
.channels
@ -594,8 +603,12 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
.find(|channel| channel.id == channel_id)
{
channel.name = channel_name;
if let Some(parent) = parent_id { channel.parent_id = (!parent.is_empty()).then_some(parent); }
if let Some(position) = position { channel.position = position; }
if let Some(parent) = parent_id {
channel.parent_id = (!parent.is_empty()).then_some(parent);
}
if let Some(position) = position {
channel.position = position;
}
}
}
NetEvent::ChannelDeleted { channel_id } => {
@ -627,7 +640,8 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
name: c.channel_name,
kind: c.kind,
guild_id: c.guild_id,
parent_id: c.parent_id, position: c.position,
parent_id: c.parent_id,
position: c.position,
members,
}
})
@ -1260,6 +1274,8 @@ mod channel_creation_regressions {
members: vec![],
voice_endpoint: "127.0.0.1:7601".into(),
guild_id: None,
parent_id: None,
position: 0,
}
}
#[tokio::test]
@ -1319,6 +1335,8 @@ mod profile_warning_regressions {
members: vec![],
voice_endpoint: "127.0.0.1:7601".into(),
guild_id: None,
parent_id: None,
position: 0,
}
}

View file

@ -81,6 +81,8 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
name: "общий".into(),
kind: "text".into(),
guild_id: None,
parent_id: None,
position: 0,
members: vec![identity.pubkey_hex.clone()],
},
ui::state::Channel {
@ -88,6 +90,8 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
name: "Общая".into(),
kind: "voice".into(),
guild_id: None,
parent_id: None,
position: 0,
members: vec![identity.pubkey_hex.clone()],
},
];
@ -520,11 +524,14 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
sync();
assert!(window.get_node_admin());
render(&window, &surface, "node-admin-sidebar");
click(&window, 307.0, 163.0);
window.invoke_open_channel_menu("".into(), 300.0, 120.0);
sync();
assert!(window.get_management_menu_open());
window.invoke_management_menu_chosen("voice".into());
sync();
assert!(
window.get_channel_admin_open(),
"voice plus must open on the first click"
"the create menu must open the voice dialog"
);
assert_eq!(window.get_channel_admin_kind(), "voice");
window.invoke_channel_admin_name_edited("QA voice room".into());
@ -551,14 +558,14 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
window.invoke_channel_admin_cancel();
sync();
render(&window, &surface, "node-admin-before-rename");
click(&window, 263.0, 117.0);
window.invoke_rename_global_channel("general".into());
sync();
assert!(window.get_channel_admin_open());
render(&window, &surface, "node-admin-rename");
window.invoke_channel_admin_cancel();
sync();
render(&window, &surface, "node-admin-before-delete");
click(&window, 299.0, 117.0);
window.invoke_delete_global_channel("general".into());
sync();
assert!(window.get_channel_admin_open());
assert!(
@ -569,7 +576,9 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
window.invoke_channel_admin_cancel();
sync();
render(&window, &surface, "node-admin-before-text");
click(&window, 307.0, 85.0);
window.invoke_open_channel_menu("".into(), 300.0, 120.0);
sync();
window.invoke_management_menu_chosen("text".into());
sync();
assert!(window.get_channel_admin_open());
assert_eq!(window.get_channel_admin_kind(), "text");
@ -579,5 +588,31 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
sync();
assert!(!window.get_node_admin());
assert!(!window.get_channel_admin_open());
// Categories and forums are navigation only: they never request voice membership.
{
let mut s = state.borrow_mut();
for (id, kind) in [("cat", "category"), ("forum", "forum"), ("odd", "unknown")] {
s.ui.channels.push(ui::state::Channel {
id: id.into(),
name: id.into(),
kind: kind.into(),
guild_id: None,
parent_id: None,
position: 0,
members: vec![],
});
}
}
let mic_before = state.borrow().ui.mic_enabled;
for id in ["cat", "forum", "odd"] {
window.invoke_channel_selected(id.into());
let s = state.borrow();
assert!(
s.ui.pending_voice_join.is_none(),
"{id} must not join voice"
);
assert!(!s.ui.showing_voice);
assert_eq!(s.ui.mic_enabled, mic_before);
}
window.hide().unwrap();
}

View file

@ -248,6 +248,8 @@ mode = "private"
channel_name: "Integrations".into(),
kind: "text".into(),
guild_id: Some(guild_id),
parent_id: None,
position: 0,
})
.await;
event(