Check the captured channel in the core before sending chat

This commit is contained in:
omar committed 2026-11-26 19:54:47 +03:00
1 parent 2ba2e8dda4
commit 08647b6830
11 files changed
+59 -27

No files matched your search

+1
View File
@@ -3,6 +3,7 @@
## Unreleased
- Two connections using the same identity and server now keep independent chat drafts. An acknowledgement in one tab no longer clears or unblocks a send in the other.
- Channel chat now checks the channel captured by the editor against the core's current channel before sending. A draft for a channel you have left is rejected instead of being sent to the new channel.
- Deleting the selected inactive shortcut profile now returns the editor to the active profile and its bindings.
- Switching shortcut profiles cancels a held push-to-talk key immediately; the configured release delay still applies to ordinary key-up.
- Settings checkboxes now display the value acknowledged by the application instead of retaining a local toggle state.
+23 -7
View File
@@ -120,7 +120,7 @@ pub enum Command {
Connect(ConnectArgs),
Disconnect { message: Option<String> },
JoinChannel { channel_id: u64, password: Option<String> },
SendText { target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<String>, message: String },
SendText { target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<String>, expected_channel_id: Option<u64>, message: String },
SetAudio { input_muted: Option<bool>, output_muted: Option<bool> },
/// `None` = direct transmission (push-to-talk / open microphone decided by the caller).
SetTransmit { vad: Option<GateMode> },
@@ -279,6 +279,8 @@ struct SendTextArgs {
client_id: Option<u16>,
#[serde(default)]
expected_client_uid: Option<String>,
#[serde(default)]
expected_channel_id: Option<u64>,
message: String,
}
@@ -510,7 +512,7 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
}
"send_text" => {
let a: SendTextArgs = args_owned(raw)?;
Command::SendText { target: a.target, client_id: a.client_id, expected_client_uid: a.expected_client_uid, message: a.message }
Command::SendText { target: a.target, client_id: a.client_id, expected_client_uid: a.expected_client_uid, expected_channel_id: a.expected_channel_id, message: a.message }
}
"set_audio" => {
let a: SetAudioArgs = args_owned(raw)?;
@@ -591,7 +593,10 @@ pub fn validate_command(mut command: Command) -> Result<ValidatedCommand, ErrorO
}
Command::Disconnect { message } => check_opt("message", message)?,
Command::JoinChannel { password, .. } => check_opt("password", password)?,
Command::SendText { target, client_id, expected_client_uid, message } => {
Command::SendText { target, client_id, expected_client_uid, expected_channel_id, message } => {
if expected_channel_id.is_some_and(|id| id == 0 || *target != TextTarget::Channel) {
return Err(bad("expected_channel_id must be positive and is only allowed for target channel"));
}
if message.is_empty() || message.len() > MAX_TEXT_BYTES { return Err(bad(format!("message must be 1-{MAX_TEXT_BYTES} bytes"))); }
match (*target, *client_id) {
(TextTarget::Client, None) => return Err(bad("client_id is required for target client")),
@@ -801,7 +806,7 @@ mod tests {
#[test]
fn direct_private_text_requires_exact_target_and_uid() {
let private = |client_id, expected_client_uid| Command::SendText {
target: TextTarget::Client, client_id, expected_client_uid, message: "hello".into(),
target: TextTarget::Client, client_id, expected_client_uid, expected_channel_id: None, message: "hello".into(),
};
assert_bad(private(None, Some("uid".into())));
assert_bad(private(Some(0), Some("uid".into())));
@@ -812,16 +817,27 @@ mod tests {
assert_eq!(valid.name(), "send_text");
assert_eq!(valid.into_inner(), private(Some(7), Some("uid".into())));
for target in [TextTarget::Channel, TextTarget::Server] {
assert_bad(Command::SendText { target, client_id: Some(7), expected_client_uid: None, message: "hello".into() });
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: Some("uid".into()), message: "hello".into() });
assert_bad(Command::SendText { target, client_id: Some(7), expected_client_uid: None, expected_channel_id: None, message: "hello".into() });
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: Some("uid".into()), expected_channel_id: None, message: "hello".into() });
for message in [String::new(), "я".repeat(MAX_TEXT_BYTES / 2 + 1)] {
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: None, message });
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: None, expected_channel_id: None, message });
}
}
let Input::Invalid { error, .. } = parse_line(r#"{"id":"t","cmd":"send_text","args":{"target":"client","client_id":7,"message":"hello"}}"#) else { panic!() };
assert_eq!(error, validate_command(private(Some(7), None)).unwrap_err());
}
#[test]
fn expected_channel_id_is_a_guard_only_for_channel_text() {
for (target, channel) in [(TextTarget::Channel, 0), (TextTarget::Server, 7), (TextTarget::Client, 7)] {
let private = target == TextTarget::Client;
assert_bad(Command::SendText { target, client_id: private.then_some(2), expected_client_uid: private.then(|| "peer".into()),
expected_channel_id: Some(channel), message: "draft".into() });
}
let Input::Request { cmd, .. } = parse_line(r#"{"id":"t","cmd":"send_text","args":{"target":"channel","expected_channel_id":7,"message":"draft"}}"#) else { panic!("valid guarded send rejected") };
assert!(matches!(cmd.into_inner(), Command::SendText { expected_channel_id: Some(7), .. }));
}
#[test]
fn direct_signaling_checks_objects_and_compact_byte_limit() {
let signal = |json| Command::StreamSignal { stream_id: "s1".into(), client_id: 7, json };
+7 -2
View File
@@ -436,7 +436,7 @@ impl Session {
Command::Connect(args) => self.connect(&id, args).await,
Command::Disconnect { message } => self.disconnect(Some(id.clone()), message).await,
Command::JoinChannel { channel_id, password } => self.join_channel(&id, channel_id, password),
Command::SendText { target, client_id, expected_client_uid, message } => self.send_text(&id, target, client_id, expected_client_uid.as_deref(), &message),
Command::SendText { target, client_id, expected_client_uid, expected_channel_id, message } => self.send_text(&id, target, client_id, expected_client_uid.as_deref(), expected_channel_id, &message),
Command::SetAudio { input_muted, output_muted } => self.set_audio(&id, input_muted, output_muted).await,
Command::SetTransmit { vad } => self.set_transmit(vad).await.map(Some),
Command::SetLocalVolumes(update) => self.set_local_volumes(update).map(Some),
@@ -647,7 +647,7 @@ impl Session {
Ok(None)
}
fn send_text(&mut self, id: &str, target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<&str>, message: &str) -> Result<Option<Value>, ErrorObj> {
fn send_text(&mut self, id: &str, target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<&str>, expected_channel_id: Option<u64>, message: &str) -> Result<Option<Value>, ErrorObj> {
let target = match (target, client_id) {
(TextTarget::Server, _) => MessageTarget::Server,
(TextTarget::Channel, _) => MessageTarget::Channel,
@@ -656,6 +656,11 @@ impl Session {
};
let c = self.connected_conn()?;
let book = c.con.get_state().map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
if let Some(expected) = expected_channel_id {
if book.clients.get(&book.own_client).map(|client| client.channel.0) != Some(expected) {
return Err(ErrorObj::new(ErrorCode::TargetChanged, "own channel changed before sending the message"));
}
}
if let Some(cid) = client_id {
let current = book.clients.get(&ClientId(cid)).and_then(|client| client.uid.as_ref());
if current.is_none_or(|uid| Some(uid.to_string()).as_deref() != expected_client_uid) {
+1 -1
View File
@@ -39,7 +39,7 @@ async fn native_requests_validate_before_session_dispatch() {
let profile = Profile::new();
let (core, _events) = spawn(profile.config(1)).unwrap();
let error = core.request(Command::SendText { target: TextTarget::Client, client_id: None,
expected_client_uid: None, message: "private".into() }).await.unwrap_err();
expected_client_uid: None, expected_channel_id: None, message: "private".into() }).await.unwrap_err();
assert_eq!(error.code, ErrorCode::BadRequest);
let error = core.request(Command::StreamSignal { stream_id: "s1".into(), client_id: 1, json: "[]".into() }).await.unwrap_err();
assert_eq!(error.code, ErrorCode::BadRequest);
+2 -1
View File
@@ -207,10 +207,11 @@ pending connect attempt was abandoned. `not_connected` if idle. Emits
Moves self (`clientmove`). Result `{}` after the server confirms; snapshot follows.
### 4.7 `send_text` — `{target: "channel"|"server"|"client", client_id?: number, expected_client_uid?: string, message: string}`
### 4.7 `send_text` — `{target: "channel"|"server"|"client", client_id?: number, expected_client_uid?: string, expected_channel_id?: number, message: string}`
`client_id` and `expected_client_uid` are required iff `target = "client"`. Native rechecks the UID immediately before sending, otherwise `target_changed`. Message 1–8192 bytes UTF-8;
TeamSpeak escaping is done by the core. Result `{}` after server confirmation.
For channel chat the native client supplies `expected_channel_id`. This is a positive ID checked against the core's current own channel before enqueue. A mismatch returns `target_changed`; the field never addresses another channel. Diagnostic requests may omit it to send to the current channel.
The server echoes our own messages as `text` events (verified live for private messages:
the sender receives exactly one `text` with `to_client_id` = recipient); the core adds no
synthetic echo.
+1
View File
@@ -60,6 +60,7 @@
реальном WASAPI-устройстве независимо не наблюдался, готовность сборки и приёмка не подтверждены.
- Два CLI-клиента прошли `duplex_qa -- --whisper` на закрытом beta14; 15 тестов ядра с фильтром `whisper` прошли. Проверены разрешение и запрет приёма, восстановление приёма и отбрасывание устаревшего кадра без передачи в обычный канал. Стенд остановлен. Проверка не включает окно настроек, системный ввод или физическое аудио.
- Чат на изолированном beta14: два CLI-клиента получили подтверждения и точный текст для текущего канала и личного сообщения с проверкой ID и серверного UID. Несовпадающий UID дал `target_changed`, четыре недопустимых набора аргументов дали `bad_request`; общесерверный текст гостю запрещён (TS 2568). Оба клиента отключились штатно. Отдельный тест Slint `concurrent_tabs_keep_separate_drafts_and_pending_sends` подтвердил независимость черновиков двух вкладок при одинаковой истории и ответах в обратном порядке. Это не проверка установленного клиента и не доказательство доставки в произвольный канал.
- После перехода обоих CLI-клиентов из лобби во временный канал beta14 ядро отклонило `send_text` с прежним `expected_channel_id` (`target_changed`). Сообщение с текущим ID сервер подтвердил, второй клиент получил только контрольный текст. Оба клиента отключились штатно, стенд остановлен. Прошли два теста валидации протокола и два теста нативного клиента на устаревший канал и независимость черновиков. Проверка относится к известному ядру каналу перед отправкой, не к доставке в произвольный канал.
- Нативная проверка `whisper-settings`: `target/evidence/pc5232-whisper-settings-03/result.json` и 5 кадров. Подтверждены `deny_all`, сохранение списков после перезапуска runtime, предупреждения для повреждённого файла и файла новой версии, отсутствие запуска аудио. `whisper_list_workflows` проверил отмену и подтверждение удаления, сохранность несвязанных сочетаний и восстановление при ошибке записи. В About возврат фокуса к лицензии и выпуску проверен повторной активацией через Enter. Эти проверки не подтверждают визуальное совпадение с официальным клиентом.
- `preload:setWhisperReceiveMode`: `target/evidence/pc5232-whisper-settings-05/result.json` подтверждает выбор `allow_all`, затем `deny_all` указателем в Slint. Для обоих режимов показанное значение совпало с `whisper.json`, после перезапуска runtime сохранился `deny_all`. Отдельно `target/evidence/pc5232-identity-choice-01/result.json` прошёл с тем же исправленным компонентом выбора. Доставка звука проверялась отдельным CLI-сценарием, не из этого окна.
- Профили горячих клавиш: адресный тест Slint и тест хранилища прошли на Windows. Создание второго профиля не меняет активный; имя длиннее 64 символов отклоняется. После подтверждённого удаления неактивного профиля редактор сразу показывает активный; его UUID, новое имя и локальная привязка F8 сохранились после перезапуска runtime. Системные сочетания не регистрировались.
+5 -10
View File
@@ -254,12 +254,7 @@ impl ConnectionManager {
self.capture.lock().expect("capture route poisoned").revoke();
}
pub async fn request(&self, key: &SessionKey, command: Command) -> Result<Value, ConnectionError> {
self.call(|reply| Operation::Request(key.clone(), command, None, reply)).await
}
/// Capture the conversation channel before awaiting. A local channel move
/// cannot overtake this message while its server acknowledgement is pending.
pub async fn request_in_channel(&self,key:&SessionKey,channel:u64,command:Command)->Result<Value,ConnectionError>{
self.call(|reply|Operation::Request(key.clone(),command,Some(channel),reply)).await
self.call(|reply| Operation::Request(key.clone(), command, reply)).await
}
pub async fn close(&self, key: &SessionKey) -> Result<(), ConnectionError> {
self.call(|reply| Operation::Close(key.clone(), reply)).await
@@ -300,7 +295,7 @@ enum Operation {
SelectChannel(SessionKey, u64, Reply<()>),
Workflow(WorkflowSettings, Reply<()>),
SetInput(Option<SessionKey>, InputConfiguration, Reply<Option<CapturePermit>>),
Request(SessionKey, Command, Option<u64>, Reply<Value>),
Request(SessionKey, Command, Reply<Value>),
Close(SessionKey, Reply<()>),
Restart(SessionKey, Reply<SessionKey>),
#[cfg(test)]
@@ -615,7 +610,7 @@ impl Actor {
} else { self.publish(); let _ = reply.send(Ok(None)); return; }
self.publish();
}
Operation::Request(key, command, expected_channel, reply) => {
Operation::Request(key, command, reply) => {
let index = match self.checked(&key) { Ok(index) => index, Err(error) => { let _ = reply.send(Err(error)); return; } };
if self.entries[index].worker.as_ref().expect("checked live worker").requests.len() >= COMMAND_CAPACITY {
let _ = reply.send(Err(ConnectionError::Busy)); return;
@@ -626,8 +621,8 @@ impl Actor {
let channel_lease=if matches!(command,Command::JoinChannel{..}|Command::SendText{target:teamspeach_core::protocol::TextTarget::Channel,..}){
match self.entries[index].worker.as_ref().expect("checked live worker").channel_request.clone().try_lock_owned(){Ok(lease)=>Some(lease),Err(_)=>{let _=reply.send(Err(ConnectionError::Busy));return}}
}else{None};
if let Some(channel)=expected_channel{
if !matches!(command,Command::SendText{target:teamspeach_core::protocol::TextTarget::Channel,..})||!self.entries[index].snapshot.is_connected()||self.entries[index].snapshot.server.as_deref().and_then(|s|s["own_channel_id"].as_u64())!=Some(channel){let _=reply.send(Err(ConnectionError::TargetChanged));return}
if let Command::SendText { target:teamspeach_core::protocol::TextTarget::Channel, expected_channel_id:Some(channel), .. }=&command {
if !self.entries[index].snapshot.is_connected() || self.entries[index].snapshot.server.as_deref().and_then(|s|s["own_channel_id"].as_u64())!=Some(*channel){let _=reply.send(Err(ConnectionError::TargetChanged));return}
}
let guard = match &command {
Command::Connect(args) => Guard::Connect { address: args.address.clone(), identity: args.identity_id.clone() },
+15 -1
View File
@@ -60,6 +60,20 @@ async fn channel_selection_stays_independent_until_own_channel_changes() {
stop(actor).await;
}
#[tokio::test(flavor = "current_thread")]
async fn moved_channel_draft_is_not_sent_to_the_new_channel() {
use teamspeach_core::protocol::TextTarget;
let profile = Profile::new();
let manager = ConnectionManager::start(profile.0.clone(), Arc::new(|_: ConnectionEvent| {})).unwrap();
let key = manager.create().await.unwrap();
manager.fixture_control(&key, snapshot(10, &[10, 20])).await.unwrap();
let draft = Command::SendText { target: TextTarget::Channel, expected_channel_id: Some(10),
client_id: None, expected_client_uid: None, message: "for the first channel".into() };
manager.fixture_control(&key, snapshot(20, &[10, 20])).await.unwrap();
assert!(matches!(manager.request(&key, draft).await, Err(ConnectionError::TargetChanged)));
manager.shutdown().await.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn state_transitions_revoke_sessions_and_ignore_foreign_generation_and_worker() {
let profile = Profile::new();
@@ -290,7 +304,7 @@ async fn restart_discards_an_outstanding_response_from_the_previous_worker() {
let key = actor.create().unwrap();
let other = actor.create().unwrap();
let (reply, pending) = oneshot::channel();
actor.operation(Operation::Request(key.clone(), Command::ProfileGet, None, reply));
actor.operation(Operation::Request(key.clone(), Command::ProfileGet, reply));
let response = tokio::time::timeout(Duration::from_secs(5), async {
loop {
let message = actor.events.recv().await.unwrap();
+2 -3
View File
@@ -123,9 +123,8 @@ async fn send(ctx:Arc<RuntimeServices>,target:ConversationTarget,receipt:SendRec
if receipt.target!=target||receipt.draft_key!=target.draft_key()||receipt.text.len()>8192||receipt.text.trim().is_empty(){return Err(bad("Invalid message receipt"))}
if !sendable(&ctx,&target){return Err(changed())}
{let mut state=ctx.chat_workflows.lock().await;let c=find(&mut state,&target)?;if c.sending{return Err(ServiceError::new("busy","A message is already awaiting acknowledgement"))}c.sending=true;c.error=None;claimed=true;}
let(kind,id,uid)=match &target.target{ChatTarget::Server=>(TextTarget::Server,None,None),ChatTarget::Channel(_)=>(TextTarget::Channel,None,None),ChatTarget::Client{id,uid}=>(TextTarget::Client,Some(*id),Some(uid.clone()))};
let command=Command::SendText{target:kind,client_id:id,expected_client_uid:uid,message:receipt.text.clone()};
if let ChatTarget::Channel(channel)=target.target{ctx.connected.connections.request_in_channel(&target.session,channel,command).await.map_err(super::context::connection_error)?;}else{ctx.request(&target.session,command).await?;}
let(kind,id,uid,channel)=match &target.target{ChatTarget::Server=>(TextTarget::Server,None,None,None),ChatTarget::Channel(channel)=>(TextTarget::Channel,None,None,Some(*channel)),ChatTarget::Client{id,uid}=>(TextTarget::Client,Some(*id),Some(uid.clone()),None)};
ctx.request(&target.session,Command::SendText{target:kind,client_id:id,expected_client_uid:uid,expected_channel_id:channel,message:receipt.text.clone()}).await?;
validate(&ctx,&target)?;Ok(())
}.await;
{let mut state=ctx.chat_workflows.lock().await;if let Ok(c)=find(&mut state,&target){if claimed{c.sending=false;}match &result{Ok(())=>{if c.draft_revision==receipt.draft_revision&&c.draft.trim_end()==receipt.text{c.draft.clear();}},Err(error)=>c.error=Some(error.message.clone())}}}
+1 -1
View File
@@ -44,7 +44,7 @@ impl ChatFixture {
Err(mpsc::RecvTimeoutError::Disconnected) => break,
};
if let ChatAction::Send { target, receipt } = action {
let result = rt.block_on(manager.request(&target.session, Command::SendText { target:TextTarget::Server, client_id:None, expected_client_uid:None, message:receipt.text.clone() })).map(|_|()).map_err(|error| error.to_string());
let result = rt.block_on(manager.request(&target.session, Command::SendText { target:TextTarget::Server, client_id:None, expected_client_uid:None, expected_channel_id:None, message:receipt.text.clone() })).map(|_|()).map_err(|error| error.to_string());
if complete.send((receipt,result)).is_err() { break }
}
}
+1 -1
View File
@@ -69,7 +69,7 @@ pub async fn stale_session(output: &Path) -> Result<Value, String> {
if !matches!(manager.request(&old, Command::ProfileGet).await, Err(ConnectionError::TargetChanged)) { return Err("stale core key was not rejected".to_owned()) }
let observed = manager.request(&current, Command::ProfileGet).await.map_err(|error| error.to_string())?;
if observed["uid"] != created["uid"] || current.session <= old.session { return Err("restart changed identity or reused session epoch".into()) }
let rejected = manager.request(&current, Command::SendText { target: TextTarget::Server, client_id: None, expected_client_uid: None, message: "offline rejection fixture".into() }).await;
let rejected = manager.request(&current, Command::SendText { target: TextTarget::Server, client_id: None, expected_client_uid: None, expected_channel_id: None, message: "offline rejection fixture".into() }).await;
if !matches!(rejected, Err(ConnectionError::NotConnected) | Err(ConnectionError::Core(_))) { return Err("offline core unexpectedly accepted a network message".into()) }
Ok(json!({"name":"stale-session","passed":true,"old_session":old.session,"new_session":current.session,"uid_preserved":true,"scope":"real offline core restart; no network connection"}))
}.await;