From ad3716e8850bb7a65c5aee97c95a7c137fab923f Mon Sep 17 00:00:00 2001 From: Engineer Date: Wed, 12 Aug 2026 06:15:03 +0000 Subject: [PATCH 01/12] fix(security): harden client_message_id and attachment materialize Validate Hub client_message_id fail-closed (charset/length/path escapes) while still accepting UUID, msg_*, and agent-result:* ids. Daemon no longer uses raw origin as a path component (sha256 hex), asserts writes stay under .attachments, allowlists download hosts to configured backend origin, and streams downloads with size cap + timeout. --- .../src/conversations/use_case.rs | 5 + .../minos-backend/src/store/social/agents.rs | 1 + .../src/store/social/conversation_messages.rs | 85 ++++ crates/minos-backend/src/store/social/mod.rs | 52 ++- crates/minos-daemon/src/media_materialize.rs | 378 ++++++++++++++++-- 5 files changed, 485 insertions(+), 36 deletions(-) diff --git a/crates/minos-backend/src/conversations/use_case.rs b/crates/minos-backend/src/conversations/use_case.rs index 41f705e6..0c192b6c 100644 --- a/crates/minos-backend/src/conversations/use_case.rs +++ b/crates/minos-backend/src/conversations/use_case.rs @@ -42,6 +42,11 @@ fn map_store_write(error: BackendError) -> ConversationError { { ConversationError::IdempotencyConflict(message.clone()) } + BackendError::StoreQuery { operation, message } + if operation.ends_with("invalid_client_message_id") => + { + ConversationError::ValidationFormat(message.clone()) + } _ => ConversationError::Internal(error), } } diff --git a/crates/minos-backend/src/store/social/agents.rs b/crates/minos-backend/src/store/social/agents.rs index 3fe715a7..5a36c3af 100644 --- a/crates/minos-backend/src/store/social/agents.rs +++ b/crates/minos-backend/src/store/social/agents.rs @@ -797,6 +797,7 @@ pub async fn insert_agent_message_with_session_in_tx( ) -> Result { let message_id = match client_message_id.map(str::trim).filter(|s| !s.is_empty()) { Some(id) => { + let id = super::conversation_messages::validate_client_message_id(id)?; if let Some(existing) = super::conversation_messages::get_message_in_tx(tx, id).await? { if existing.conversation_id != conversation_id { return Err(BackendError::StoreQuery { diff --git a/crates/minos-backend/src/store/social/conversation_messages.rs b/crates/minos-backend/src/store/social/conversation_messages.rs index 0b35c4dd..b45f5846 100644 --- a/crates/minos-backend/src/store/social/conversation_messages.rs +++ b/crates/minos-backend/src/store/social/conversation_messages.rs @@ -489,6 +489,7 @@ pub async fn insert_message_with_id_in_tx( let message_id = match client_message_id.map(str::trim).filter(|s| !s.is_empty()) { Some(id) => { + let id = validate_client_message_id(id)?; // Must read on the open tx — SQLite test pools are single-connection. if let Some(existing) = get_message_in_tx(tx, id).await? { // Idempotency key is (sender, client_message_id) + request fingerprint. @@ -706,6 +707,45 @@ async fn insert_mention_rows_postgres( Ok(()) } + +/// Fail-closed validation for untrusted `client_message_id` values. +/// +/// Clients mint UUIDs / `msg_` / `react-…` keys; host projection uses +/// `agent-result:{conv}:{session}:{origin}` (colons required). Reject path +/// separators, `..`, empty/overlong, and any charset outside +/// `[A-Za-z0-9_.:-]{1,256}` so ids cannot be used as filesystem escapes +/// downstream. +pub fn validate_client_message_id(id: &str) -> Result<&str, BackendError> { + const MAX_LEN: usize = 256; + if id.is_empty() || id.len() > MAX_LEN { + return Err(invalid_client_message_id( + id, + "must be 1..=256 chars of [A-Za-z0-9_.:-]", + )); + } + if id == "." || id == ".." { + return Err(invalid_client_message_id(id, "must not be '.' or '..'")); + } + if !id + .bytes() + .all(|b| matches!(b, b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'_' | b'.' | b':' | b'-')) + { + return Err(invalid_client_message_id( + id, + "must match [A-Za-z0-9_.:-]{1,256}", + )); + } + Ok(id) +} + +fn invalid_client_message_id(id: &str, detail: &str) -> BackendError { + let preview: String = id.chars().take(64).collect(); + BackendError::StoreQuery { + operation: "social::insert_message_with_id.invalid_client_message_id".into(), + message: format!("invalid client_message_id '{preview}': {detail}"), + } +} + fn normalize_message_source(source: &str) -> &'static str { minos_protocol::MessageSource::parse(source).as_str() } @@ -1087,3 +1127,48 @@ pub async fn recall_message_in_tx( } Ok(()) } + +#[cfg(test)] +mod tests { + use super::validate_client_message_id; + + #[test] + fn accepts_uuid_and_client_prefixed_ids() { + assert!(validate_client_message_id("550e8400-e29b-41d4-a716-446655440000").is_ok()); + assert!(validate_client_message_id("msg_550e8400-e29b-41d4-a716-446655440000").is_ok()); + assert!(validate_client_message_id("msg-disabled-sole-1").is_ok()); + assert!(validate_client_message_id("react-171000-42").is_ok()); + assert!(validate_client_message_id("approval-550e8400-e29b-41d4-a716-446655440000").is_ok()); + } + + #[test] + fn accepts_agent_result_formula_with_colons() { + assert!(validate_client_message_id("agent-result:conv:sess:origin-msg").is_ok()); + assert!(validate_client_message_id( + "agent-result:550e8400-e29b-41d4-a716-446655440000:sess:msg_abc" + ) + .is_ok()); + } + + #[test] + fn rejects_path_escape_and_junk() { + let overlong = "a".repeat(257); + for bad in [ + "", + ".", + "..", + "../etc/passwd", + "/tmp/x", + "foo/bar", + "foo\\bar", + "has space", + "null\0byte", + overlong.as_str(), + ] { + assert!( + validate_client_message_id(bad).is_err(), + "expected reject for {bad:?}" + ); + } + } +} diff --git a/crates/minos-backend/src/store/social/mod.rs b/crates/minos-backend/src/store/social/mod.rs index f5c93817..fe264997 100644 --- a/crates/minos-backend/src/store/social/mod.rs +++ b/crates/minos-backend/src/store/social/mod.rs @@ -257,7 +257,7 @@ pub use conversation_messages::{ list_message_mentions, list_message_mentions_full, list_messages, list_messages_by_ids, lookup_latest_session_id_for_conversation, lookup_latest_session_id_for_conversation_agent, lookup_session_id_for_message, recall_message, recall_message_in_tx, - suppress_live_ui_fanout_for_session, InsertMessageOutcome, + suppress_live_ui_fanout_for_session, validate_client_message_id, InsertMessageOutcome, }; // Agent functions @@ -837,4 +837,54 @@ mod tests { "expected agent body fingerprint conflict, got {conflict:?}" ); } + + #[tokio::test] + async fn insert_message_rejects_path_escape_client_ids() { + let pool = memory_pool().await; + let alice = insert_account(&pool, "alice@example.com").await; + let conversation = create_group_conversation(&pool, &alice, "Sec", &[], T0) + .await + .unwrap(); + for bad in [ + "../etc/passwd", + "/tmp/x", + "foo/bar", + "has space", + "..", + ] { + let err = insert_message_with_id( + &pool, + &conversation.conversation_id, + &alice, + "hello", + T0 + 1, + None, + &[], + Some(bad), + ) + .await; + assert!( + matches!( + &err, + Err(crate::error::BackendError::StoreQuery { operation, .. }) + if operation == "social::insert_message_with_id.invalid_client_message_id" + ), + "expected invalid_client_message_id for {bad:?}, got {err:?}" + ); + } + // Good ids still accepted. + let ok = insert_message_with_id( + &pool, + &conversation.conversation_id, + &alice, + "hello", + T0 + 2, + None, + &[], + Some("msg_550e8400-e29b-41d4-a716-446655440000"), + ) + .await + .unwrap(); + assert_eq!(ok.message_id, "msg_550e8400-e29b-41d4-a716-446655440000"); + } } diff --git a/crates/minos-daemon/src/media_materialize.rs b/crates/minos-daemon/src/media_materialize.rs index dbbe4387..786b21a1 100644 --- a/crates/minos-daemon/src/media_materialize.rs +++ b/crates/minos-daemon/src/media_materialize.rs @@ -1,11 +1,21 @@ //! Download Hub media blobs into the agent workspace before prompting. use std::path::{Path, PathBuf}; +use std::time::Duration; +use futures_util::StreamExt; use minos_protocol::DispatchAttachment; +use sha2::{Digest, Sha256}; +use tokio::io::AsyncWriteExt; use tracing::{info, warn}; -/// Download attachments under `{workspace}/.minos/attachments/{origin}/` and +/// Match Hub default `MINOS_MEDIA_MAX_BYTES` (10 MiB). +const MAX_ATTACHMENT_BYTES: u64 = 10 * 1024 * 1024; +const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(60); +/// Hex chars from sha256(origin); enough entropy, filesystem-safe. +const ORIGIN_DIR_HEX_LEN: usize = 32; + +/// Download attachments under `{workspace}/.minos/attachments/{hash}/` and /// return absolute paths (for `@path` / localImage style agent prompts). pub async fn materialize_attachments( workspace: &Path, @@ -19,7 +29,26 @@ pub async fn materialize_attachments( .map(str::trim) .filter(|s| !s.is_empty()) .unwrap_or("anonymous"); - let dir = workspace.join(".minos").join("attachments").join(origin); + let attachments_root = workspace.join(".minos").join("attachments"); + if let Err(e) = tokio::fs::create_dir_all(&attachments_root).await { + warn!( + target: "minos_daemon::media", + error = %e, + path = %attachments_root.display(), + "failed to create attachments root" + ); + return Vec::new(); + } + let Ok(root_canon) = tokio::fs::canonicalize(&attachments_root).await else { + warn!( + target: "minos_daemon::media", + path = %attachments_root.display(), + "failed to canonicalize attachments root" + ); + return Vec::new(); + }; + + let dir = attachments_root.join(origin_dir_component(origin)); if let Err(e) = tokio::fs::create_dir_all(&dir).await { warn!( target: "minos_daemon::media", @@ -29,21 +58,83 @@ pub async fn materialize_attachments( ); return Vec::new(); } + let Ok(dir_canon) = tokio::fs::canonicalize(&dir).await else { + warn!( + target: "minos_daemon::media", + path = %dir.display(), + "failed to canonicalize attachment dir" + ); + return Vec::new(); + }; + if !dir_canon.starts_with(&root_canon) { + warn!( + target: "minos_daemon::media", + dir = %dir_canon.display(), + root = %root_canon.display(), + "attachment dir escaped attachments root" + ); + return Vec::new(); + } + + let client = match reqwest::Client::builder() + .timeout(DOWNLOAD_TIMEOUT) + .redirect(reqwest::redirect::Policy::none()) + .build() + { + Ok(c) => c, + Err(e) => { + warn!( + target: "minos_daemon::media", + error = %e, + "failed to build download client" + ); + return Vec::new(); + } + }; - let client = reqwest::Client::new(); let mut paths = Vec::with_capacity(attachments.len()); for (idx, att) in attachments.iter().enumerate() { let filename = safe_filename(att, idx); - let dest = dir.join(&filename); + let dest = dir_canon.join(&filename); + // Filename is sanitized to a single path component; still assert containment. + if !dest.starts_with(&dir_canon) || dest == dir_canon { + warn!( + target: "minos_daemon::media", + dest = %dest.display(), + "refusing attachment dest outside origin dir" + ); + continue; + } match download_one(&client, &att.download_url, &dest).await { Ok(()) => { - info!( - target: "minos_daemon::media", - blob_id = %att.blob_id, - path = %dest.display(), - "materialized attachment" - ); - paths.push(dest); + // After write, re-check resolved path stays under attachments root. + match tokio::fs::canonicalize(&dest).await { + Ok(canon) if canon.starts_with(&root_canon) => { + info!( + target: "minos_daemon::media", + blob_id = %att.blob_id, + path = %canon.display(), + "materialized attachment" + ); + paths.push(canon); + } + Ok(canon) => { + warn!( + target: "minos_daemon::media", + path = %canon.display(), + "materialized path escaped attachments root; removing" + ); + let _ = tokio::fs::remove_file(&canon).await; + } + Err(e) => { + warn!( + target: "minos_daemon::media", + error = %e, + path = %dest.display(), + "failed to canonicalize materialized path" + ); + } + } } Err(e) => { warn!( @@ -73,6 +164,18 @@ pub fn append_attachment_paths(text: &str, paths: &[PathBuf]) -> String { } } +/// Hex prefix of sha256(origin). Never use the remote string as a path component. +#[must_use] +pub(crate) fn origin_dir_component(origin: &str) -> String { + let digest = Sha256::digest(origin.as_bytes()); + let mut out = String::with_capacity(ORIGIN_DIR_HEX_LEN); + for b in digest.iter().take(ORIGIN_DIR_HEX_LEN / 2) { + use std::fmt::Write as _; + let _ = write!(&mut out, "{b:02x}"); + } + out +} + fn safe_filename(att: &DispatchAttachment, idx: usize) -> String { if let Some(name) = att.original_filename.as_deref() { let base = name @@ -88,7 +191,13 @@ fn safe_filename(att: &DispatchAttachment, idx: usize) -> String { } }) .collect::(); - if !base.is_empty() && base != "." && base != ".." { + let base = base.trim_matches('.').to_string(); + if !base.is_empty() + && base != "." + && base != ".." + && !base.contains("..") + && base.len() <= 180 + { return format!("{idx}_{base}"); } } @@ -101,40 +210,139 @@ fn safe_filename(att: &DispatchAttachment, idx: usize) -> String { "text/plain" => "txt", _ => "bin", }; - format!("{idx}_{}.{ext}", &att.blob_id[..8.min(att.blob_id.len())]) + let blob = att.blob_id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').collect::(); + let stem = if blob.is_empty() { + "blob".to_string() + } else { + blob[..8.min(blob.len())].to_string() + }; + format!("{idx}_{stem}.{ext}") } async fn download_one(client: &reqwest::Client, url: &str, dest: &Path) -> Result<(), String> { - let url = if url.starts_with("http://") || url.starts_with("https://") { - url.to_string() - } else { - // Relative paths need an absolute backend origin (host is not the API). - let base = std::env::var("MINOS_BACKEND_URL") - .or_else(|_| std::env::var("MINOS_MEDIA_PUBLIC_BASE_URL")) - .unwrap_or_default() - .trim() - .trim_end_matches('/') - .to_string(); - if base.is_empty() { - return Err( - "relative download_url requires MINOS_BACKEND_URL or MINOS_MEDIA_PUBLIC_BASE_URL on host" - .into(), - ); - } - format!("{base}{url}") - }; + let url = resolve_download_url(url)?; + ensure_download_url_allowed(&url)?; + let resp = client - .get(&url) + .get(url.as_str()) .send() .await .map_err(|e| format!("request: {e}"))?; if !resp.status().is_success() { return Err(format!("http {}", resp.status())); } - let bytes = resp.bytes().await.map_err(|e| format!("body: {e}"))?; - tokio::fs::write(dest, &bytes) + if let Some(len) = resp.content_length() { + if len > MAX_ATTACHMENT_BYTES { + return Err(format!( + "content-length {len} exceeds cap {MAX_ATTACHMENT_BYTES}" + )); + } + } + + let mut file = tokio::fs::File::create(dest) .await - .map_err(|e| format!("write: {e}")) + .map_err(|e| format!("create: {e}"))?; + let mut stream = resp.bytes_stream(); + let mut written: u64 = 0; + while let Some(chunk) = stream.next().await { + let chunk = chunk.map_err(|e| format!("body: {e}"))?; + written = written.saturating_add(chunk.len() as u64); + if written > MAX_ATTACHMENT_BYTES { + drop(file); + let _ = tokio::fs::remove_file(dest).await; + return Err(format!( + "body exceeded cap {MAX_ATTACHMENT_BYTES} bytes" + )); + } + file.write_all(&chunk) + .await + .map_err(|e| format!("write: {e}"))?; + } + file.flush().await.map_err(|e| format!("flush: {e}"))?; + Ok(()) +} + +fn resolve_download_url(url: &str) -> Result { + if url.starts_with("http://") || url.starts_with("https://") { + return url::Url::parse(url).map_err(|e| format!("parse url: {e}")); + } + // Relative paths need an absolute backend origin (host is not the API). + let base = configured_http_bases() + .into_iter() + .next() + .ok_or_else(|| { + "relative download_url requires MINOS_BACKEND_URL or MINOS_MEDIA_PUBLIC_BASE_URL on host" + .to_string() + })?; + base.join(url).map_err(|e| format!("join url: {e}")) +} + +/// Allowlist host == configured backend / media public origin. +pub(crate) fn ensure_download_url_allowed(url: &url::Url) -> Result<(), String> { + if url.scheme() != "http" && url.scheme() != "https" { + return Err(format!("unsupported download scheme {}", url.scheme())); + } + let Some(host) = url.host_str() else { + return Err("download url missing host".into()); + }; + let allowed = configured_http_bases(); + if allowed.is_empty() { + return Err("no allowed download origins configured".into()); + } + let ok = allowed.iter().any(|base| { + base.scheme() == url.scheme() + && base.host_str() == Some(host) + && base.port_or_known_default() == url.port_or_known_default() + }); + if ok { + Ok(()) + } else { + Err(format!("download host not in allowlist: {host}")) + } +} + +fn configured_http_bases() -> Vec { + let mut out = Vec::new(); + let mut push_raw = |raw: &str| { + let trimmed = raw.trim(); + if trimmed.is_empty() { + return; + } + if let Some(base) = crate::relay_http::http_base(trimmed) { + if let Ok(u) = url::Url::parse(&base) { + if !out.iter().any(|e| e == &u) { + out.push(u); + } + return; + } + } + if let Ok(u) = url::Url::parse(trimmed) { + if (u.scheme() == "http" || u.scheme() == "https") && u.host_str().is_some() { + // Prefer origin form (scheme/host/port only). + if let Some(base) = crate::relay_http::http_base(trimmed) { + if let Ok(b) = url::Url::parse(&base) { + if !out.iter().any(|e| e == &b) { + out.push(b); + } + return; + } + } + if !out.iter().any(|e| e == &u) { + out.push(u); + } + } + } + }; + + if let Ok(v) = std::env::var("MINOS_MEDIA_PUBLIC_BASE_URL") { + push_raw(&v); + } + if let Ok(v) = std::env::var("MINOS_BACKEND_URL") { + push_raw(&v); + } + // Bake-time fallback so relative URLs work with the compiled-in hub origin. + push_raw(crate::config::BACKEND_URL); + out } #[cfg(test)] @@ -155,4 +363,104 @@ mod tests { let text = append_attachment_paths("", &[PathBuf::from("/tmp/a.png")]); assert_eq!(text, "@/tmp/a.png"); } + + #[test] + fn origin_dir_is_hex_and_ignores_path_escape() { + let a = origin_dir_component("../etc/passwd"); + let b = origin_dir_component("/tmp/x"); + let c = origin_dir_component("msg_550e8400-e29b-41d4-a716-446655440000"); + assert_eq!(a.len(), ORIGIN_DIR_HEX_LEN); + assert!(a.chars().all(|ch| ch.is_ascii_hexdigit())); + assert_ne!(a, b); + assert_ne!(a, c); + assert!(!a.contains('.') && !a.contains('/') && !a.contains('\\')); + } + + #[test] + fn safe_filename_strips_path_parts_and_dotdot() { + let att = DispatchAttachment { + blob_id: "blobdeadbeef".into(), + content_type: "image/png".into(), + byte_size: 12, + original_filename: Some("../evil/../../x.png".into()), + download_url: "https://example.com/x".into(), + }; + let name = safe_filename(&att, 0); + assert_eq!(name, "0_x.png"); + assert!(!name.contains("..")); + assert!(!name.contains('/')); + } + + #[test] + fn safe_filename_falls_back_for_dotdot_only() { + let att = DispatchAttachment { + blob_id: "blobdeadbeef".into(), + content_type: "image/png".into(), + byte_size: 1, + original_filename: Some("..".into()), + download_url: "https://example.com/x".into(), + }; + let name = safe_filename(&att, 3); + assert_eq!(name, "3_blobdead.png"); + } + + #[test] + fn rejects_non_allowlisted_download_host() { + // BACKEND_URL bake + env may vary; force isolation via a clearly foreign host. + let url = url::Url::parse("https://evil.example/steal").unwrap(); + // If somehow evil.example were allowlisted (it isn't), this would fail the test intent. + let err = ensure_download_url_allowed(&url).unwrap_err(); + assert!( + err.contains("not in allowlist") || err.contains("no allowed"), + "unexpected err: {err}" + ); + } + + #[test] + fn allowlists_configured_backend_origin() { + let bases = configured_http_bases(); + assert!( + !bases.is_empty(), + "expected at least bake-time BACKEND_URL origin" + ); + let base = &bases[0]; + let mut allowed = base.clone(); + allowed.set_path("/v1/media/blobs/x/content"); + assert!(ensure_download_url_allowed(&allowed).is_ok()); + } + + #[tokio::test] + async fn path_escape_origin_stays_under_attachments_root() { + let tmp = tempfile::tempdir().unwrap(); + let workspace = tmp.path(); + // No network: empty attachments list short-circuits, so create dir via + // a failed download that still creates the hashed origin folder. + let evil = "../../../../etc/passwd"; + let paths = materialize_attachments( + workspace, + Some(evil), + &[DispatchAttachment { + blob_id: "blobdeadbeef".into(), + content_type: "text/plain".into(), + byte_size: 1, + original_filename: Some("a.txt".into()), + download_url: "https://evil.example/x".into(), + }], + ) + .await; + assert!(paths.is_empty()); + let attachments = workspace.join(".minos").join("attachments"); + assert!(attachments.is_dir()); + let hashed = attachments.join(origin_dir_component(evil)); + assert!( + hashed.is_dir(), + "expected hashed origin dir under attachments, got {:?}", + std::fs::read_dir(&attachments) + .map(|d| d.filter_map(|e| e.ok()).map(|e| e.path()).collect::>()) + .unwrap_or_default() + ); + // No sibling escape dirs created next to .minos + assert!(!workspace.join("etc").exists()); + assert!(!workspace.join("passwd").exists()); + } } From 28b6e47e552368627b199799eb565ede8f6924e0 Mon Sep 17 00:00:00 2001 From: Engineer Date: Wed, 12 Aug 2026 06:32:39 +0000 Subject: [PATCH 02/12] fix(realtime): durable no-drop fanout and client hole detection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P0-2: fail closed when durable delivery cannot keep order. Server: - Revoke connections on catch-up barrier overflow and try_send backpressure instead of dropping frames while still acking outbox publish paths. - Claim outbox rows ordered by (topic, topic_seq) via durable_event_log join. - Same-batch dispatch remains serial; full monotonic outbox_id migration deferred. Clients: - Desktop tryAdvanceTopicCursor refuses silent gaps and triggers SnapshotRequired. - Mobile tracks pending Dart holds, blocks AdvanceNow across holds, detects holes, and serializes inbox/conversation apply+ack chains. Document the ordered no-drop + hole-detection contract in architecture-messaging.md §4.1. --- .../src/shared/lib/cloud-cursors.test.ts | 29 ++++++++ apps/desktop/src/shared/lib/cloud-cursors.ts | 49 ++++++++++++- apps/desktop/src/shared/lib/cloud-realtime.ts | 25 +++++-- .../social/social_conversation_notifier.dart | 20 +++--- .../social/social_inbox_notifier.dart | 9 ++- crates/minos-backend/src/realtime.rs | 6 +- crates/minos-backend/src/realtime/gateway.rs | 8 +++ .../src/realtime/subscription.rs | 27 +++++--- .../minos-backend/src/store/outbox_events.rs | 32 +++++---- crates/minos-mobile/src/client.rs | 14 +++- crates/minos-mobile/src/realtime/session.rs | 66 +++++++++++++++++- .../minos-mobile/src/realtime/subscription.rs | 68 ++++++++++++++++++- docs/architecture-messaging.md | 7 ++ 13 files changed, 313 insertions(+), 47 deletions(-) diff --git a/apps/desktop/src/shared/lib/cloud-cursors.test.ts b/apps/desktop/src/shared/lib/cloud-cursors.test.ts index 65795be3..6f637ddc 100644 --- a/apps/desktop/src/shared/lib/cloud-cursors.test.ts +++ b/apps/desktop/src/shared/lib/cloud-cursors.test.ts @@ -9,6 +9,8 @@ import { resumeAfterFromCursors, loadTopicCursors, saveTopicCursors, + tryAdvanceTopicCursor, + isTopicSeqHole, CLOUD_CURSOR_STORAGE_KEY, LEGACY_CLOUD_CURSOR_STORAGE_KEY, } from "./cloud-cursors.ts"; @@ -31,6 +33,33 @@ describe("advanceTopicCursor", () => { }); }); +describe("tryAdvanceTopicCursor hole detection", () => { + it("advances continuous seq and first/zero cursor", () => { + let r = tryAdvanceTopicCursor({}, "conversation:c1", 3); + assert.equal(r.kind, "advanced"); + assert.equal(r.cursors["conversation:c1"], 3); + r = tryAdvanceTopicCursor(r.cursors, "conversation:c1", 4); + assert.equal(r.kind, "advanced"); + assert.equal(r.cursors["conversation:c1"], 4); + // After clear (0), high seq is allowed (SnapshotRequired catch-up). + r = tryAdvanceTopicCursor({ "conversation:c1": 0 }, "conversation:c1", 99); + assert.equal(r.kind, "advanced"); + }); + + it("reports hole without advancing", () => { + const base = { "conversation:c1": 5 }; + assert.equal(isTopicSeqHole(base, "conversation:c1", 7), true); + const r = tryAdvanceTopicCursor(base, "conversation:c1", 7); + assert.equal(r.kind, "hole"); + if (r.kind === "hole") { + assert.equal(r.expected, 6); + assert.equal(r.got, 7); + } + assert.equal(r.cursors, base); + assert.equal(base["conversation:c1"], 5); + }); +}); + describe("clearTopicCursor / resumeAfterFromCursors", () => { it("clears one topic and builds resume_after", () => { const m = { "conversation:c1": 10, "account:a": 2 }; diff --git a/apps/desktop/src/shared/lib/cloud-cursors.ts b/apps/desktop/src/shared/lib/cloud-cursors.ts index efe2e7a3..fad97616 100644 --- a/apps/desktop/src/shared/lib/cloud-cursors.ts +++ b/apps/desktop/src/shared/lib/cloud-cursors.ts @@ -30,7 +30,29 @@ function parseTopicCursors(raw: string | null): TopicCursorMap { } } -/** Pure: merge one topic_seq into a cursor map (monotonic). */ +/** Result of attempting to advance a topic cursor with continuity checks. */ +export type AdvanceCursorResult = + | { kind: "unchanged"; cursors: TopicCursorMap } + | { kind: "advanced"; cursors: TopicCursorMap } + | { kind: "hole"; cursors: TopicCursorMap; expected: number; got: number }; + +/** + * Pure: true when `topicSeq` skips ahead of a known applied cursor. + * Fresh/cleared cursors (missing or 0) never report a hole — SnapshotRequired + * catch-up and first-subscribe may land on a high seq after retention. + */ +export function isTopicSeqHole( + cursors: TopicCursorMap, + topic: string, + topicSeq: number, +): boolean { + if (!topic || !Number.isFinite(topicSeq) || topicSeq < 0) return false; + const prev = cursors[topic]; + if (prev == null || prev <= 0) return false; + return topicSeq > prev + 1; +} + +/** Pure: merge one topic_seq into a cursor map (monotonic, no hole check). */ export function advanceTopicCursor( cursors: TopicCursorMap, topic: string, @@ -46,6 +68,31 @@ export function advanceTopicCursor( return { ...cursors, [topic]: topicSeq }; } +/** + * Pure: advance only on continuous seq (cursor+1 or first/zero cursor). + * Holes leave the map unchanged so the caller can request SnapshotRequired. + */ +export function tryAdvanceTopicCursor( + cursors: TopicCursorMap, + topic: string, + topicSeq: number, +): AdvanceCursorResult { + if (!topic || !Number.isFinite(topicSeq) || topicSeq < 0) { + return { kind: "unchanged", cursors }; + } + const prev = cursors[topic]; + if (prev != null && topicSeq <= prev) { + return { kind: "unchanged", cursors }; + } + if (prev != null && prev > 0 && topicSeq > prev + 1) { + return { kind: "hole", cursors, expected: prev + 1, got: topicSeq }; + } + return { + kind: "advanced", + cursors: { ...cursors, [topic]: topicSeq }, + }; +} + /** Pure: drop a topic cursor (e.g. SnapshotRequired). */ export function clearTopicCursor( cursors: TopicCursorMap, diff --git a/apps/desktop/src/shared/lib/cloud-realtime.ts b/apps/desktop/src/shared/lib/cloud-realtime.ts index 99aba504..59eaedd3 100644 --- a/apps/desktop/src/shared/lib/cloud-realtime.ts +++ b/apps/desktop/src/shared/lib/cloud-realtime.ts @@ -5,16 +5,16 @@ * Disconnected → Connecting → Syncing → Live * per-topic resume_after cursors (localStorage) * Subscribe conversation:{id} when open - * SnapshotRequired → clear cursor + cold rebuild callback + * SnapshotRequired / seq hole → clear cursor + cold rebuild callback */ import { - advanceTopicCursor, clearTopicCursor, conversationTopic, loadTopicCursors, resumeAfterFromCursors, saveTopicCursors, + tryAdvanceTopicCursor, type TopicCursorMap, } from "@/shared/lib/cloud-cursors"; import { conversationSubscriptionLruTouch } from "@/shared/lib/conversation-sub-lru"; @@ -477,12 +477,27 @@ export class CloudRealtimeSession { saveTopicCursors(this.cursors); } + /** + * Advance cursor only on continuous seq. Holes trigger SnapshotRequired + * without silently jumping past missing durable events. + */ private noteTopicSeq(topic: string | undefined, topicSeq: number | undefined): void { if (!topic || topicSeq == null || !Number.isFinite(topicSeq)) return; - const next = advanceTopicCursor(this.cursors, topic, topicSeq); - if (next !== this.cursors) { - this.cursors = next; + const result = tryAdvanceTopicCursor(this.cursors, topic, topicSeq); + if (result.kind === "advanced") { + this.cursors = result.cursors; + this.persistCursors(); + return; + } + if (result.kind === "hole") { + console.warn("[cloud-realtime] durable seq hole; requesting snapshot", { + topic, + expected: result.expected, + got: result.got, + }); + this.cursors = clearTopicCursor(this.cursors, topic); this.persistCursors(); + this.handlers.onSnapshotRequired?.(topic); } } diff --git a/apps/mobile/lib/application/social/social_conversation_notifier.dart b/apps/mobile/lib/application/social/social_conversation_notifier.dart index 2d295163..376a8865 100644 --- a/apps/mobile/lib/application/social/social_conversation_notifier.dart +++ b/apps/mobile/lib/application/social/social_conversation_notifier.dart @@ -26,6 +26,8 @@ class SocialConversation extends _$SocialConversation { StreamSubscription? _eventsSub; Timer? _markReadTimer; + /// Serialize apply+ack so concurrent frames cannot race durable cursors. + Future _durableApplyChain = Future.value(); late final String _conversationId; @@ -397,11 +399,11 @@ class SocialConversation extends _$SocialConversation { if (frame.kind == 'reaction_updated') { final mid = frame.message.messageId.trim(); if (mid.isEmpty) return; - unawaited( - _applyRemoteReactions(mid, frame.message.reactions).then((_) { - return _ackDurable(frame); - }), - ); + _durableApplyChain = _durableApplyChain.catchError((_) {}).then((_) async { + await _applyRemoteReactions(mid, frame.message.reactions); + await _ackDurable(frame); + }); + unawaited(_durableApplyChain); return; } // Full T1 conversation frames only. @@ -412,9 +414,11 @@ class SocialConversation extends _$SocialConversation { if (frame.message.messageId.trim().isEmpty) { return; } - unawaited( - _applyRemoteMessage(frame.message).then((_) => _ackDurable(frame)), - ); + _durableApplyChain = _durableApplyChain.catchError((_) {}).then((_) async { + await _applyRemoteMessage(frame.message); + await _ackDurable(frame); + }); + unawaited(_durableApplyChain); } Future _ackDurable(SocialEventFrame frame) async { diff --git a/apps/mobile/lib/application/social/social_inbox_notifier.dart b/apps/mobile/lib/application/social/social_inbox_notifier.dart index 31d3dab6..b6763f32 100644 --- a/apps/mobile/lib/application/social/social_inbox_notifier.dart +++ b/apps/mobile/lib/application/social/social_inbox_notifier.dart @@ -21,6 +21,9 @@ final conversationsProvider = /// InboxSync: incremental patch; full REST only hydrate / refresh / snapshot. class ConversationsController extends AsyncNotifier { StreamSubscription? _eventsSub; + /// Serialize per-frame apply/ack so concurrent unawaited handlers cannot + /// advance durable cursors out of order across topics. + Future _socialApplyChain = Future.value(); @override Future build() async { @@ -33,7 +36,11 @@ class ConversationsController extends AsyncNotifier { .listen( (frame) { // Hot path: single-row patch — never invalidateSelf / full REST. - unawaited(_onSocialEvent(frame)); + // Chain applies so ack_durable_applied stays topic-order safe. + _socialApplyChain = _socialApplyChain + .catchError((_) {}) + .then((_) => _onSocialEvent(frame)); + unawaited(_socialApplyChain); }, onError: (Object error, StackTrace stackTrace) { // Connection errors: soft; next hydrate corrects. diff --git a/crates/minos-backend/src/realtime.rs b/crates/minos-backend/src/realtime.rs index 7612bf2c..e9b3d2bf 100644 --- a/crates/minos-backend/src/realtime.rs +++ b/crates/minos-backend/src/realtime.rs @@ -912,8 +912,9 @@ impl RealtimeFanout { conn_id = %target.conn_id, topic = %topic.topic_string(), error = ?error, - "formal gateway durable fanout dropped frame" + "formal gateway durable fanout backpressure; revoking connection" ); + target.revoke(ConnectionRevocation::Backpressure); } } } @@ -937,8 +938,9 @@ impl RealtimeFanout { conn_id = %target.conn_id, topic = %topic.topic_string(), error = ?error, - "formal gateway durable fanout dropped untracked frame" + "formal gateway durable fanout backpressure; revoking connection" ); + target.revoke(ConnectionRevocation::Backpressure); } } } diff --git a/crates/minos-backend/src/realtime/gateway.rs b/crates/minos-backend/src/realtime/gateway.rs index 9c8ce790..d6403e50 100644 --- a/crates/minos-backend/src/realtime/gateway.rs +++ b/crates/minos-backend/src/realtime/gateway.rs @@ -538,6 +538,10 @@ async fn run_session_inner( code: CLOSE_CODE_AUTH_REVOKED, reason: "auth_revoked", }, + ConnectionRevocation::Backpressure => CloseDirective { + code: CLOSE_CODE_AUTH_REVOKED, + reason: "backpressure", + }, }; close_with_directive(ws, upgrade.role, directive).await; return directive.reason; @@ -559,6 +563,10 @@ async fn run_session_inner( code: CLOSE_CODE_AUTH_REVOKED, reason: "auth_revoked", }, + ConnectionRevocation::Backpressure => CloseDirective { + code: CLOSE_CODE_AUTH_REVOKED, + reason: "backpressure", + }, }; close_with_directive(ws, upgrade.role, directive).await; return directive.reason; diff --git a/crates/minos-backend/src/realtime/subscription.rs b/crates/minos-backend/src/realtime/subscription.rs index f538ee1c..2d11e3a2 100644 --- a/crates/minos-backend/src/realtime/subscription.rs +++ b/crates/minos-backend/src/realtime/subscription.rs @@ -18,6 +18,9 @@ pub enum ConnectionRevocation { Superseded, /// Auth backing was revoked (host unlink, token revoke, process shutdown). AuthRevoked, + /// Durable outbound queue / catch-up barrier overflow — fail closed so the + /// client reconnects and resumes from its cursor instead of silently skipping. + Backpressure, } const SEEN_DURABLE_EVENT_IDS_CAPACITY: usize = 1024; @@ -222,17 +225,19 @@ impl ConnectionState { if let Ok(parsed) = RealtimeTopic::parse(topic) { let mut barriers = write_lock(&self.catchup_barriers); if let Some(barrier) = barriers.get_mut(&parsed) { - if barrier.buffer.len() >= BARRIER_BUFFER_CAPACITY { - if let Some(oldest_seq) = barrier.buffer.keys().next().copied() { - barrier.buffer.remove(&oldest_seq); - tracing::warn!( - target: "minos_backend::realtime::subscription", - conn_id = %self.conn_id, - topic = %topic, - dropped_seq = oldest_seq, - "catchup barrier buffer full; dropped oldest live frame" - ); - } + if barrier.buffer.len() >= BARRIER_BUFFER_CAPACITY + && !barrier.buffer.contains_key(&topic_seq) + { + tracing::warn!( + target: "minos_backend::realtime::subscription", + conn_id = %self.conn_id, + topic = %topic, + topic_seq, + "catchup barrier buffer full; revoking connection (no-drop)" + ); + drop(barriers); + self.revoke(ConnectionRevocation::Backpressure); + return Err(Box::new(mpsc::error::TrySendError::Full(frame))); } barrier .buffer diff --git a/crates/minos-backend/src/store/outbox_events.rs b/crates/minos-backend/src/store/outbox_events.rs index ed1f034a..fe49723c 100644 --- a/crates/minos-backend/src/store/outbox_events.rs +++ b/crates/minos-backend/src/store/outbox_events.rs @@ -221,12 +221,15 @@ async fn claim_available_sqlite( .map_err(store_err("outbox_events::claim_available.begin_sqlite"))?; let candidate_ids = sqlx::query_scalar::<_, String>( - "SELECT outbox_id - FROM outbox_events - WHERE status = 'pending' - AND lane = ? - AND available_at_ms <= ? - ORDER BY available_at_ms ASC, outbox_id ASC + "SELECT o.outbox_id + FROM outbox_events o + JOIN durable_event_log d + ON d.topic_kind = o.topic_kind + AND d.event_id = o.event_id + WHERE o.status = 'pending' + AND o.lane = ? + AND o.available_at_ms <= ? + ORDER BY d.topic ASC, d.topic_seq ASC, o.available_at_ms ASC, o.outbox_id ASC LIMIT ?", ) .bind(lane.as_str()) @@ -285,14 +288,17 @@ async fn claim_available_postgres( ) -> Result, BackendError> { let rows = sqlx::query_as::<_, OutboxEventRowTuple>( "WITH cte AS ( - SELECT outbox_id - FROM outbox_events - WHERE status = 'pending' - AND lane = $4 - AND available_at_ms <= $1 - ORDER BY available_at_ms ASC, outbox_id ASC + SELECT o.outbox_id + FROM outbox_events o + JOIN durable_event_log d + ON d.topic_kind = o.topic_kind + AND d.event_id = o.event_id + WHERE o.status = 'pending' + AND o.lane = $4 + AND o.available_at_ms <= $1 + ORDER BY d.topic ASC, d.topic_seq ASC, o.available_at_ms ASC, o.outbox_id ASC LIMIT $2 - FOR UPDATE SKIP LOCKED + FOR UPDATE OF o SKIP LOCKED ) UPDATE outbox_events o SET status = 'claimed', diff --git a/crates/minos-mobile/src/client.rs b/crates/minos-mobile/src/client.rs index 5a178a2d..500c80d2 100644 --- a/crates/minos-mobile/src/client.rs +++ b/crates/minos-mobile/src/client.rs @@ -454,7 +454,19 @@ impl MobileClient { if topic.is_empty() || topic_seq <= 0 { return; } - self.subscription_mgr.update_seq(topic, topic_seq).await; + self.subscription_mgr.clear_pending_hold(topic).await; + match self.subscription_mgr.update_seq(topic, topic_seq).await { + crate::realtime::subscription::CursorAdvance::Hole { expected } => { + tracing::warn!( + topic, + topic_seq, + expected, + "ack_durable_applied saw seq hole; clearing cursor for snapshot" + ); + self.subscription_mgr.clear_cursor(topic).await; + } + _ => {} + } } async fn send_subscribe_topics(&self, topics: Vec) { diff --git a/crates/minos-mobile/src/realtime/session.rs b/crates/minos-mobile/src/realtime/session.rs index be527f0d..77407342 100644 --- a/crates/minos-mobile/src/realtime/session.rs +++ b/crates/minos-mobile/src/realtime/session.rs @@ -276,6 +276,29 @@ fn apply_durable_event( } } + +async fn surface_snapshot_required( + topic: &str, + last_known_seq: i64, + ui_events_tx: &broadcast::Sender, + subscription_mgr: &Arc, +) { + subscription_mgr.clear_cursor(topic).await; + let _ = ui_events_tx.send(UiEventFrame { + session_id: String::new(), + seq: 0, + ui: UiEventMessage::Raw { + kind: "snapshot_required".into(), + payload_json: serde_json::json!({ + "topic": topic, + "last_known_seq": last_known_seq, + }) + .to_string(), + }, + ts_ms: chrono::Utc::now().timestamp_millis(), + }); +} + async fn dispatch_event( event: &RealtimeEvent, subscription_mgr: &Arc, @@ -322,6 +345,19 @@ async fn dispatch_event( payload, .. } => { + // Continuity: never silently jump past a hole. + let applied = subscription_mgr.applied_seq(topic).await; + if applied > 0 && *topic_seq > applied + 1 { + tracing::warn!( + topic, + topic_seq, + expected = applied + 1, + "durable seq hole; requesting snapshot" + ); + surface_snapshot_required(topic, applied, ui_events_tx, subscription_mgr).await; + return; + } + let outcome = apply_durable_event( topic, *topic_seq, @@ -332,10 +368,36 @@ async fn dispatch_event( ); match outcome { ApplyOutcome::AdvanceNow => { - subscription_mgr.update_seq(topic, *topic_seq).await; + // Do not leapfrog a smaller seq held for Dart apply. + if subscription_mgr.has_pending_hold(topic).await { + tracing::debug!( + topic, + topic_seq, + "skip AdvanceNow while topic has pending Dart hold" + ); + } else { + match subscription_mgr.update_seq(topic, *topic_seq).await { + crate::realtime::subscription::CursorAdvance::Hole { expected } => { + tracing::warn!( + topic, + topic_seq, + expected, + "durable seq hole on AdvanceNow; requesting snapshot" + ); + surface_snapshot_required( + topic, + expected - 1, + ui_events_tx, + subscription_mgr, + ) + .await; + } + _ => {} + } + } } ApplyOutcome::AwaitDartAck => { - // Cursor stays until MobileClient::ack_durable_applied. + subscription_mgr.mark_pending_hold(topic, *topic_seq).await; } ApplyOutcome::Hold => {} } diff --git a/crates/minos-mobile/src/realtime/subscription.rs b/crates/minos-mobile/src/realtime/subscription.rs index 24b4d668..dbaff439 100644 --- a/crates/minos-mobile/src/realtime/subscription.rs +++ b/crates/minos-mobile/src/realtime/subscription.rs @@ -4,6 +4,7 @@ //! - **pending**: Subscribe frame sent, SubscribeAck not yet received //! - **confirmed**: gateway acked the subscription for this connection //! - **cursors**: last **applied** durable topic_seq (advance only after apply ack) +//! - **pending_holds**: topics awaiting Dart `ack_durable_applied` (block AdvanceNow) use std::collections::{HashMap, HashSet}; use std::sync::Arc; @@ -15,6 +16,14 @@ pub struct SubscriptionManager { inner: RwLock, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CursorAdvance { + Advanced, + Unchanged, + /// `topic_seq` skipped past `cursor + 1` — caller must request snapshot. + Hole { expected: i64 }, +} + #[derive(Debug, Default)] struct SubscriptionState { desired: HashSet, @@ -22,6 +31,9 @@ struct SubscriptionState { confirmed: HashSet, /// Last successfully applied durable seq per topic. cursors: HashMap, + /// Topics with an in-flight social apply awaiting Dart ack. + /// Value is the earliest held topic_seq. + pending_holds: HashMap, } impl SubscriptionManager { @@ -103,15 +115,43 @@ impl SubscriptionManager { if let Some(existing) = state.cursors.get_mut(topic) { *existing = 0; } + state.pending_holds.remove(topic); + } + + /// Mark that a social durable frame is held pending Dart ack. + pub async fn mark_pending_hold(&self, topic: &str, seq: i64) { + let mut state = self.inner.write().await; + let entry = state.pending_holds.entry(topic.to_string()).or_insert(seq); + if seq < *entry { + *entry = seq; + } + } + + pub async fn clear_pending_hold(&self, topic: &str) { + let mut state = self.inner.write().await; + state.pending_holds.remove(topic); + } + + pub async fn has_pending_hold(&self, topic: &str) -> bool { + let state = self.inner.read().await; + state.pending_holds.contains_key(topic) } /// Advance applied cursor only after durable apply commit / intentional consume. - pub async fn update_seq(&self, topic: &str, seq: i64) { + /// Refuses to jump past holes when a positive cursor is already established. + pub async fn update_seq(&self, topic: &str, seq: i64) -> CursorAdvance { let mut state = self.inner.write().await; let entry = state.cursors.entry(topic.to_string()).or_insert(0); - if seq > *entry { - *entry = seq; + if seq <= *entry { + return CursorAdvance::Unchanged; + } + if *entry > 0 && seq > *entry + 1 { + return CursorAdvance::Hole { + expected: *entry + 1, + }; } + *entry = seq; + CursorAdvance::Advanced } pub async fn resume_after_map(&self) -> HashMap { @@ -208,4 +248,26 @@ mod tests { mgr.mark_subscription_denied("conversation:x").await; assert!(!mgr.is_desired("conversation:x").await); } + #[tokio::test] + async fn update_seq_detects_hole_and_pending_hold_blocks() { + let mgr = SubscriptionManager::new(); + mgr.desire_topic("conversation:c1", 0).await; + assert_eq!( + mgr.update_seq("conversation:c1", 5).await, + CursorAdvance::Advanced + ); + assert_eq!( + mgr.update_seq("conversation:c1", 7).await, + CursorAdvance::Hole { expected: 6 } + ); + assert_eq!(mgr.applied_seq("conversation:c1").await, 5); + mgr.mark_pending_hold("conversation:c1", 6).await; + assert!(mgr.has_pending_hold("conversation:c1").await); + mgr.clear_pending_hold("conversation:c1").await; + assert!(!mgr.has_pending_hold("conversation:c1").await); + assert_eq!( + mgr.update_seq("conversation:c1", 6).await, + CursorAdvance::Advanced + ); + } } diff --git a/docs/architecture-messaging.md b/docs/architecture-messaging.md index 4eaa045b..89656381 100644 --- a/docs/architecture-messaging.md +++ b/docs/architecture-messaging.md @@ -428,6 +428,13 @@ Minos 明确区分 **可靠性语义不同** 的消息平面——这是成熟 - 客户端用 `resume_after: { topic → last_topic_seq }` 续传;`after < retention_floor`(含空日志)→ `SnapshotRequired` - cursor **仅在 apply/commit 成功后**推进(Mobile/Desktop) +**投递契约(fail-closed / 有序)**: + +1. **Server ordered no-drop**:outbox claim 按 `(topic, topic_seq)` 排序;同批串行 dispatch。durable `try_send` / catch-up barrier 溢出时 **revoke 连接**(`Backpressure`),禁止丢帧后仍当作已投递。出站失败后客户端以 cursor 重连回放 `durable_event_log`;outbox 可在 bus publish 成功后 ack(权威在日志,不在单次 fanout)。 +2. **Client hole detection**:若已有正 cursor 且收到 `topic_seq > cursor + 1`,**不得**静默 `max` 推进;清 cursor 并走 `SnapshotRequired` / REST 重建。cursor=0(含 snapshot 后)允许落到高 seq。 +3. **Mobile hold 不越过**:`AwaitDartAck` 期间同 topic 禁止 `AdvanceNow`(含未识别 kind);`ack_durable_applied` 串行化,避免并发 ack 乱序。 +4. **单调 outbox_id**:完整 ULID/雪花迁移若未落地,不得依赖 UUID 字典序保证全局序;以 `(topic, topic_seq)` claim 序为准。 + **典型事件**: - 社交:`ConversationMessageAppended` / `Recalled`、`AccountConversationMessage*` From b4cf3e5b2fb6b81b9c5b9b7c1d42f397ab0bae15 Mon Sep 17 00:00:00 2001 From: Engineer Date: Wed, 12 Aug 2026 06:34:00 +0000 Subject: [PATCH 03/12] fix(daemon): durable host-command ledger and topic watermark P0-3: stop full host-topic replay from re-executing history after restart. - Add host_command_ledger + host_topic_cursors (migration 0002), mirroring bot_delivery_ledger restart-safe exactly-once semantics. - Hydrate host Subscribe resume cursor from SQLite; persist on durable apply. - SnapshotRequired advances resume to retention_floor (not 0) and re-subscribes so catch-up cannot loop. - Retention reclaim: dead-letter outbox rows no longer pin durable_event_log forever (ack_at_ms NULL + dead_at_ms set). Deferred: pruning old completed ledger rows / cross-process inflight fencing. --- .../src/store/durable_event_log.rs | 7 +- .../migrations/0002_host_command_ledger.sql | 27 ++ crates/minos-daemon/src/relay_client.rs | 160 +++++++++- .../src/store/host_command_ledger.rs | 273 ++++++++++++++++++ crates/minos-daemon/src/store/mod.rs | 1 + 5 files changed, 462 insertions(+), 6 deletions(-) create mode 100644 crates/minos-daemon/migrations/0002_host_command_ledger.sql create mode 100644 crates/minos-daemon/src/store/host_command_ledger.rs diff --git a/crates/minos-backend/src/store/durable_event_log.rs b/crates/minos-backend/src/store/durable_event_log.rs index 468420a4..1bc9ede7 100644 --- a/crates/minos-backend/src/store/durable_event_log.rs +++ b/crates/minos-backend/src/store/durable_event_log.rs @@ -393,6 +393,7 @@ async fn delete_ready_for_retention_sqlite( ))?; // Include topic_seq so retention_floor advances without relying on payload rows. + // Dead-letter outbox rows keep ack_at_ms NULL; treat terminal dead as reclaimable. let keys = sqlx::query_as::<_, (String, String, String, i64)>( "SELECT d.topic_kind, d.topic, d.event_id, d.topic_seq FROM durable_event_log d @@ -400,6 +401,7 @@ async fn delete_ready_for_retention_sqlite( ON o.topic_kind = d.topic_kind AND o.event_id = d.event_id AND o.ack_at_ms IS NULL + AND o.dead_at_ms IS NULL WHERE d.created_at_ms < ? AND o.outbox_id IS NULL ORDER BY d.created_at_ms ASC, d.event_id ASC @@ -420,7 +422,7 @@ async fn delete_ready_for_retention_sqlite( "DELETE FROM outbox_events WHERE topic_kind = ? AND event_id = ? - AND ack_at_ms IS NOT NULL", + AND (ack_at_ms IS NOT NULL OR dead_at_ms IS NOT NULL OR status = 'dead')", ) .bind(&topic_kind) .bind(&event_id) @@ -489,6 +491,7 @@ async fn delete_ready_for_retention_postgres( ON o.topic_kind = d.topic_kind AND o.event_id = d.event_id AND o.ack_at_ms IS NULL + AND o.dead_at_ms IS NULL WHERE d.created_at_ms < $1 AND o.outbox_id IS NULL ORDER BY d.created_at_ms ASC, d.event_id ASC @@ -509,7 +512,7 @@ async fn delete_ready_for_retention_postgres( "DELETE FROM outbox_events WHERE topic_kind = $1 AND event_id = $2 - AND ack_at_ms IS NOT NULL", + AND (ack_at_ms IS NOT NULL OR dead_at_ms IS NOT NULL OR status = 'dead')", ) .bind(&topic_kind) .bind(&event_id) diff --git a/crates/minos-daemon/migrations/0002_host_command_ledger.sql b/crates/minos-daemon/migrations/0002_host_command_ledger.sql new file mode 100644 index 00000000..1e2d7892 --- /dev/null +++ b/crates/minos-daemon/migrations/0002_host_command_ledger.sql @@ -0,0 +1,27 @@ +-- Durable host-command idempotency + host topic resume watermark. +-- Mirrors bot_delivery_ledger: transport is at-least-once; SQLite is Host authority. + +CREATE TABLE host_command_ledger ( + command_id TEXT PRIMARY KEY NOT NULL, + status TEXT NOT NULL CHECK (status IN ( + 'inflight', 'completed' + )), + succeeded INTEGER, + result_json TEXT, + error_json TEXT, + finished_at_ms INTEGER, + created_at_ms INTEGER NOT NULL, + updated_at_ms INTEGER NOT NULL, + CHECK(length(command_id) > 0) +); + +CREATE INDEX idx_host_command_ledger_status + ON host_command_ledger(status, updated_at_ms); + +CREATE TABLE host_topic_cursors ( + topic TEXT PRIMARY KEY NOT NULL, + topic_seq INTEGER NOT NULL, + updated_at_ms INTEGER NOT NULL, + CHECK(length(topic) > 0), + CHECK(topic_seq >= 0) +); diff --git a/crates/minos-daemon/src/relay_client.rs b/crates/minos-daemon/src/relay_client.rs index e030bfc2..efe514a0 100644 --- a/crates/minos-daemon/src/relay_client.rs +++ b/crates/minos-daemon/src/relay_client.rs @@ -481,6 +481,33 @@ async fn run_dispatch(mut ctx: DispatchCtx, mut shutdown_rx: oneshot::Receiver<( let mut logged_missing_token = false; let mut epoch_rx = ctx.credential_epoch.subscribe(); + // Restart-safe host topic resume watermark (memory is only a hot cache). + { + let host_topic = format!("host:{}", ctx.self_device_id); + match ctx.store.get_host_topic_cursor(&host_topic).await { + Ok(seq) => { + if let Ok(mut guard) = ctx.host_topic_seq.lock() { + *guard = seq; + } + if seq > 0 { + tracing::info!( + target: "minos_daemon::relay_client", + topic = %host_topic, + resume_after = seq, + "hydrated host topic cursor from SQLite" + ); + } + } + Err(error) => { + tracing::warn!( + target: "minos_daemon::relay_client", + error = %error, + "failed to hydrate host topic cursor" + ); + } + } + } + loop { let Some(secret) = secret_snapshot_or_reload(&ctx.secret, &ctx.last_error) else { let _ = ctx.link_tx.send(RelayLinkState::Disconnected); @@ -969,20 +996,76 @@ async fn route_server_frame(frame: ServerFrame, ctx: &DispatchCtx) { *guard = topic_seq; } } + let now_ms = chrono::Utc::now().timestamp_millis(); + if let Err(error) = ctx + .store + .set_host_topic_cursor(&host_topic, topic_seq, now_ms) + .await + { + tracing::warn!( + target: "minos_daemon::relay_client", + error = %error, + topic_seq, + "failed to persist host topic cursor" + ); + } } route_durable_event(&kind, &payload, ctx).await; } - ServerFrame::SnapshotRequired { topic, .. } => { + ServerFrame::SnapshotRequired { + topic, + last_known_seq, + retention_floor_seq, + } => { let host_topic = format!("host:{}", ctx.self_device_id); if topic == host_topic { + // Real catch-up: resume from retention floor (not 0). Clearing to 0 + // would re-trigger SnapshotRequired forever when floor > 0. + let resume_at = retention_floor_seq.max(0); if let Ok(mut guard) = ctx.host_topic_seq.lock() { - *guard = 0; + *guard = resume_at; + } + let now_ms = chrono::Utc::now().timestamp_millis(); + if let Err(error) = ctx + .store + .replace_host_topic_cursor(&host_topic, resume_at, now_ms) + .await + { + tracing::warn!( + target: "minos_daemon::relay_client", + error = %error, + "failed to persist SnapshotRequired host cursor" + ); } tracing::warn!( target: "minos_daemon::relay_client", topic, - "host topic SnapshotRequired — cursor cleared" + last_known_seq, + retention_floor_seq, + resume_at, + "host topic SnapshotRequired — resume cursor advanced to retention floor" ); + // Re-subscribe immediately with the floor cursor so catch-up continues + // without waiting for the next reconnect cycle. + let mut resume_after = HashMap::new(); + if resume_at > 0 { + resume_after.insert(host_topic.clone(), resume_at); + } + let subscribe = ClientFrame::Subscribe { + topics: vec![host_topic], + resume_after: if resume_after.is_empty() { + None + } else { + Some(resume_after) + }, + client_request_id: None, + }; + if ctx.out_tx.send(subscribe).await.is_err() { + tracing::warn!( + target: "minos_daemon::relay_client", + "failed to enqueue post-SnapshotRequired host subscribe" + ); + } } } ServerFrame::HostIngestAck { @@ -1165,7 +1248,7 @@ async fn route_durable_event(kind: &str, payload: &Value, ctx: &DispatchCtx) { let ack = build_host_command_ack(&command_id, chrono::Utc::now().timestamp_millis()); let _ = ctx.out_tx.send(ack).await; - match remember_host_command_start(&ctx.host_command_cache, &command_id).await { + match remember_host_command_start(&ctx.host_command_cache, ctx.store.as_ref(), &command_id).await { HostCommandRouteAction::Start => {} HostCommandRouteAction::InFlight => return, HostCommandRouteAction::Replay(snapshot) => { @@ -1183,6 +1266,7 @@ async fn route_durable_event(kind: &str, payload: &Value, ctx: &DispatchCtx) { let out_tx = ctx.out_tx.clone(); let host_command_cache = Arc::clone(&ctx.host_command_cache); + let store = Arc::clone(&ctx.store); tokio::spawn(async move { let result = invoke_host_command(&method, params, &rpc_server).await; let finished_at_ms = chrono::Utc::now().timestamp_millis(); @@ -1192,6 +1276,7 @@ async fn route_durable_event(kind: &str, payload: &Value, ctx: &DispatchCtx) { }; remember_host_command_result( &host_command_cache, + store.as_ref(), &command_id, HostCommandResultSnapshot { succeeded, @@ -1250,12 +1335,52 @@ async fn route_durable_event(kind: &str, payload: &Value, ctx: &DispatchCtx) { async fn remember_host_command_start( cache: &HostCommandCache, + store: &crate::store::LocalStore, command_id: &str, ) -> HostCommandRouteAction { if command_id.is_empty() { return HostCommandRouteAction::Start; } + // Durable ledger is restart authority; memory cache is a process-local fast path. + let now_ms = chrono::Utc::now().timestamp_millis(); + match store.begin_host_command(command_id, now_ms).await { + Ok(crate::store::host_command_ledger::HostCommandBegin::InFlight) => { + let mut entries = cache.lock().await; + entries.insert(command_id.to_string(), HostCommandCacheEntry::InFlight); + return HostCommandRouteAction::InFlight; + } + Ok(crate::store::host_command_ledger::HostCommandBegin::Replay { + succeeded, + result_json, + error_json, + finished_at_ms, + }) => { + let snapshot = HostCommandResultSnapshot { + succeeded, + result: result_json.and_then(|s| serde_json::from_str(&s).ok()), + error: error_json.and_then(|s| serde_json::from_str(&s).ok()), + finished_at_ms, + }; + let mut entries = cache.lock().await; + entries.insert( + command_id.to_string(), + HostCommandCacheEntry::Completed(snapshot.clone()), + ); + prune_host_command_cache(&mut entries); + return HostCommandRouteAction::Replay(snapshot); + } + Ok(crate::store::host_command_ledger::HostCommandBegin::Start) => {} + Err(error) => { + tracing::warn!( + target: "minos_daemon::relay_client", + error = %error, + command_id, + "host_command_ledger begin failed; falling back to memory cache" + ); + } + } + let mut entries = cache.lock().await; match entries.get(command_id).cloned() { Some(HostCommandCacheEntry::InFlight) => HostCommandRouteAction::InFlight, @@ -1272,6 +1397,7 @@ async fn remember_host_command_start( async fn remember_host_command_result( cache: &HostCommandCache, + store: &crate::store::LocalStore, command_id: &str, snapshot: HostCommandResultSnapshot, ) { @@ -1279,6 +1405,32 @@ async fn remember_host_command_result( return; } + let result_json = snapshot + .result + .as_ref() + .and_then(|v| serde_json::to_string(v).ok()); + let error_json = snapshot + .error + .as_ref() + .and_then(|v| serde_json::to_string(v).ok()); + if let Err(error) = store + .complete_host_command( + command_id, + snapshot.succeeded, + result_json.as_deref(), + error_json.as_deref(), + snapshot.finished_at_ms, + ) + .await + { + tracing::warn!( + target: "minos_daemon::relay_client", + error = %error, + command_id, + "failed to persist host_command_ledger completion" + ); + } + let mut entries = cache.lock().await; entries.insert( command_id.to_string(), diff --git a/crates/minos-daemon/src/store/host_command_ledger.rs b/crates/minos-daemon/src/store/host_command_ledger.rs new file mode 100644 index 00000000..e29aef22 --- /dev/null +++ b/crates/minos-daemon/src/store/host_command_ledger.rs @@ -0,0 +1,273 @@ +//! Durable host-command ledger — restart-safe effective exactly-once execution. +//! +//! Transport is at-least-once; this table is the Host authority for whether a +//! `command_id` was already started / completed so Subscribe replay cannot +//! re-execute history after daemon restart. + +use sqlx::Row; + +use super::LocalStore; + +pub const STATUS_INFLIGHT: &str = "inflight"; +pub const STATUS_COMPLETED: &str = "completed"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HostCommandLedgerRow { + pub command_id: String, + pub status: String, + pub succeeded: Option, + pub result_json: Option, + pub error_json: Option, + pub finished_at_ms: Option, + pub created_at_ms: i64, + pub updated_at_ms: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum HostCommandBegin { + Start, + InFlight, + Replay { + succeeded: bool, + result_json: Option, + error_json: Option, + finished_at_ms: i64, + }, +} + +impl LocalStore { + pub async fn get_host_command_ledger( + &self, + command_id: &str, + ) -> anyhow::Result> { + let id = command_id.trim(); + if id.is_empty() { + return Ok(None); + } + let row = sqlx::query( + "SELECT command_id, status, succeeded, result_json, error_json, + finished_at_ms, created_at_ms, updated_at_ms + FROM host_command_ledger + WHERE command_id = ?1", + ) + .bind(id) + .fetch_optional(self.pool()) + .await?; + Ok(row.map(|r| HostCommandLedgerRow { + command_id: r.get("command_id"), + status: r.get("status"), + succeeded: r.get::, _>("succeeded").map(|v| v != 0), + result_json: r.get("result_json"), + error_json: r.get("error_json"), + finished_at_ms: r.get("finished_at_ms"), + created_at_ms: r.get("created_at_ms"), + updated_at_ms: r.get("updated_at_ms"), + })) + } + + /// Record first sight of a host command. Returns whether this process should start it. + pub async fn begin_host_command( + &self, + command_id: &str, + now_ms: i64, + ) -> anyhow::Result { + let id = command_id.trim(); + if id.is_empty() { + return Ok(HostCommandBegin::Start); + } + if let Some(existing) = self.get_host_command_ledger(id).await? { + return Ok(classify_begin(&existing)); + } + let result = sqlx::query( + "INSERT INTO host_command_ledger ( + command_id, status, succeeded, result_json, error_json, + finished_at_ms, created_at_ms, updated_at_ms + ) VALUES (?1, ?2, NULL, NULL, NULL, NULL, ?3, ?3) + ON CONFLICT(command_id) DO NOTHING", + ) + .bind(id) + .bind(STATUS_INFLIGHT) + .bind(now_ms) + .execute(self.pool()) + .await?; + if result.rows_affected() > 0 { + Ok(HostCommandBegin::Start) + } else if let Some(existing) = self.get_host_command_ledger(id).await? { + Ok(classify_begin(&existing)) + } else { + Ok(HostCommandBegin::InFlight) + } + } + + pub async fn complete_host_command( + &self, + command_id: &str, + succeeded: bool, + result_json: Option<&str>, + error_json: Option<&str>, + finished_at_ms: i64, + ) -> anyhow::Result<()> { + let id = command_id.trim(); + if id.is_empty() { + return Ok(()); + } + sqlx::query( + "INSERT INTO host_command_ledger ( + command_id, status, succeeded, result_json, error_json, + finished_at_ms, created_at_ms, updated_at_ms + ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6, ?6) + ON CONFLICT(command_id) DO UPDATE SET + status = excluded.status, + succeeded = excluded.succeeded, + result_json = excluded.result_json, + error_json = excluded.error_json, + finished_at_ms = excluded.finished_at_ms, + updated_at_ms = excluded.updated_at_ms", + ) + .bind(id) + .bind(STATUS_COMPLETED) + .bind(i64::from(succeeded)) + .bind(result_json) + .bind(error_json) + .bind(finished_at_ms) + .execute(self.pool()) + .await?; + Ok(()) + } + + pub async fn get_host_topic_cursor(&self, topic: &str) -> anyhow::Result { + let topic = topic.trim(); + if topic.is_empty() { + return Ok(0); + } + let seq = sqlx::query_scalar::<_, i64>( + "SELECT topic_seq FROM host_topic_cursors WHERE topic = ?1", + ) + .bind(topic) + .fetch_optional(self.pool()) + .await?; + Ok(seq.unwrap_or(0).max(0)) + } + + pub async fn set_host_topic_cursor( + &self, + topic: &str, + topic_seq: i64, + now_ms: i64, + ) -> anyhow::Result<()> { + let topic = topic.trim(); + if topic.is_empty() || topic_seq < 0 { + return Ok(()); + } + sqlx::query( + "INSERT INTO host_topic_cursors (topic, topic_seq, updated_at_ms) + VALUES (?1, ?2, ?3) + ON CONFLICT(topic) DO UPDATE SET + topic_seq = MAX(host_topic_cursors.topic_seq, excluded.topic_seq), + updated_at_ms = excluded.updated_at_ms", + ) + .bind(topic) + .bind(topic_seq) + .bind(now_ms) + .execute(self.pool()) + .await?; + Ok(()) + } + + /// Force-set cursor (SnapshotRequired resumes from retention floor). + pub async fn replace_host_topic_cursor( + &self, + topic: &str, + topic_seq: i64, + now_ms: i64, + ) -> anyhow::Result<()> { + let topic = topic.trim(); + if topic.is_empty() || topic_seq < 0 { + return Ok(()); + } + sqlx::query( + "INSERT INTO host_topic_cursors (topic, topic_seq, updated_at_ms) + VALUES (?1, ?2, ?3) + ON CONFLICT(topic) DO UPDATE SET + topic_seq = excluded.topic_seq, + updated_at_ms = excluded.updated_at_ms", + ) + .bind(topic) + .bind(topic_seq) + .bind(now_ms) + .execute(self.pool()) + .await?; + Ok(()) + } +} + +fn classify_begin(existing: &HostCommandLedgerRow) -> HostCommandBegin { + match existing.status.as_str() { + STATUS_COMPLETED => HostCommandBegin::Replay { + succeeded: existing.succeeded.unwrap_or(false), + result_json: existing.result_json.clone(), + error_json: existing.error_json.clone(), + finished_at_ms: existing.finished_at_ms.unwrap_or(existing.updated_at_ms), + }, + _ => HostCommandBegin::InFlight, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::tempdir; + + #[tokio::test] + async fn begin_complete_replay_and_cursor() { + let dir = tempdir().unwrap(); + let store = LocalStore::open(&dir.path().join("t.sqlite")) + .await + .unwrap(); + let now = 1_700_000_000_000i64; + assert_eq!( + store.begin_host_command("cmd-1", now).await.unwrap(), + HostCommandBegin::Start + ); + assert_eq!( + store.begin_host_command("cmd-1", now + 1).await.unwrap(), + HostCommandBegin::InFlight + ); + store + .complete_host_command( + "cmd-1", + true, + Some(r#"{"ok":true}"#), + None, + now + 2, + ) + .await + .unwrap(); + match store.begin_host_command("cmd-1", now + 3).await.unwrap() { + HostCommandBegin::Replay { + succeeded, + result_json, + .. + } => { + assert!(succeeded); + assert_eq!(result_json.as_deref(), Some(r#"{"ok":true}"#)); + } + other => panic!("expected replay, got {other:?}"), + } + + store + .set_host_topic_cursor("host:abc", 10, now) + .await + .unwrap(); + store + .set_host_topic_cursor("host:abc", 8, now + 1) + .await + .unwrap(); + assert_eq!(store.get_host_topic_cursor("host:abc").await.unwrap(), 10); + store + .replace_host_topic_cursor("host:abc", 5, now + 2) + .await + .unwrap(); + assert_eq!(store.get_host_topic_cursor("host:abc").await.unwrap(), 5); + } +} diff --git a/crates/minos-daemon/src/store/mod.rs b/crates/minos-daemon/src/store/mod.rs index 5c6995a4..9953514d 100644 --- a/crates/minos-daemon/src/store/mod.rs +++ b/crates/minos-daemon/src/store/mod.rs @@ -11,6 +11,7 @@ pub mod artifacts; pub mod bot_delivery_ledger; +pub mod host_command_ledger; pub mod event_writer; pub mod migrations_loader; From c077da4b064ae06148a660449dea5b70fc845785 Mon Sep 17 00:00:00 2001 From: Engineer Date: Wed, 12 Aug 2026 06:34:53 +0000 Subject: [PATCH 04/12] fix(jobs): respawn supervised workers and wire job health P0-4: background jobs must not die permanently after a short DB outage. - JobSupervisor enters extended respawn backoff after consecutive fatals instead of exiting the task forever. - Approval timeout poller always sleeps after due-deadline ticks; skip undecodable rows; force-timeout pending approvals with NULL host so they cannot pin next_pending_deadline forever. - Expose JobHealthRegistry on AppContext and include job snapshots in GET /health/jobs. --- .../minos-backend/src/approvals/use_case.rs | 27 +++++- crates/minos-backend/src/http/health.rs | 5 ++ crates/minos-backend/src/jobs/health.rs | 9 ++ crates/minos-backend/src/jobs/supervisor.rs | 26 ++++-- crates/minos-backend/src/runtime.rs | 6 +- .../src/store/approval_requests.rs | 86 ++++++++++++++++++- 6 files changed, 151 insertions(+), 8 deletions(-) diff --git a/crates/minos-backend/src/approvals/use_case.rs b/crates/minos-backend/src/approvals/use_case.rs index 793ea9b2..ebbdd92b 100644 --- a/crates/minos-backend/src/approvals/use_case.rs +++ b/crates/minos-backend/src/approvals/use_case.rs @@ -103,9 +103,31 @@ impl DefaultApprovalService { } async fn poll_expired(&self) -> Result<(), BackendError> { + let now_ms = chrono::Utc::now().timestamp_millis(); + // Reclaim pending rows with NULL host that would otherwise pin the deadline forever. + match store::approval_requests::timeout_pending_with_null_host( + &self.store, + now_ms, + EXPIRED_BATCH_SIZE, + ) + .await + { + Ok(0) => {} + Ok(n) => tracing::warn!( + target: "minos_backend::approvals", + count = n, + "timed out pending approvals with NULL host installation" + ), + Err(error) => tracing::warn!( + target: "minos_backend::approvals", + error = %error, + "failed to timeout NULL-host pending approvals" + ), + } + let rows = store::approval_requests::list_expired_pending( &self.store, - chrono::Utc::now().timestamp_millis(), + now_ms, EXPIRED_BATCH_SIZE, ) .await?; @@ -468,6 +490,9 @@ async fn timeout_poller(service: Weak) { "approval timeout poller iteration failed" ); } + // Always sleep after a due-deadline tick. Without this, a pending + // row that cannot be decoded/resolved (e.g. NULL host) busy-loops. + tokio::time::sleep(POLLER_RETRY_DELAY).await; continue; } diff --git a/crates/minos-backend/src/http/health.rs b/crates/minos-backend/src/http/health.rs index 8a4a87cb..c151586a 100644 --- a/crates/minos-backend/src/http/health.rs +++ b/crates/minos-backend/src/http/health.rs @@ -157,8 +157,12 @@ pub async fn jobs(State(state): State) -> impl IntoResponse { session_registry_size: usize, runtime_mode: &'static str, storage_mode: &'static str, + jobs: Vec, } + let mut jobs = state.job_health.snapshot(); + jobs.sort_by(|a, b| a.name.cmp(&b.name)); + ( StatusCode::OK, [(header::CONTENT_TYPE, "application/json")], @@ -166,6 +170,7 @@ pub async fn jobs(State(state): State) -> impl IntoResponse { session_registry_size: state.registry.len(), runtime_mode: state.config.runtime_mode.as_str(), storage_mode: state.config.storage_mode.as_str(), + jobs, }), ) } diff --git a/crates/minos-backend/src/jobs/health.rs b/crates/minos-backend/src/jobs/health.rs index 48e6ce5e..e152d40a 100644 --- a/crates/minos-backend/src/jobs/health.rs +++ b/crates/minos-backend/src/jobs/health.rs @@ -75,4 +75,13 @@ impl JobHealthRegistry { let inner = self.inner.read().unwrap(); inner.get(name).map_or(0, |h| h.consecutive_failures) } + + /// Clear the consecutive-failure streak after a supervised respawn backoff. + pub fn record_respawn(&self, name: &str) { + let mut inner = self.inner.write().unwrap(); + if let Some(health) = inner.get_mut(name) { + health.consecutive_failures = 0; + health.last_error = Some("respawn_backoff".into()); + } + } } diff --git a/crates/minos-backend/src/jobs/supervisor.rs b/crates/minos-backend/src/jobs/supervisor.rs index 3d8fd96a..8787a800 100644 --- a/crates/minos-backend/src/jobs/supervisor.rs +++ b/crates/minos-backend/src/jobs/supervisor.rs @@ -6,15 +6,18 @@ use tokio::task::JoinHandle; use super::health::JobHealthRegistry; use super::job_trait::{Job, JobContext, JobError, JobOutcome}; -/// Maximum consecutive failures before a job is stopped. +/// Consecutive failures before entering extended respawn backoff (never permanent stop). const MAX_CONSECUTIVE_FATALS: u32 = 5; /// Base backoff duration for transient errors. const BASE_BACKOFF: Duration = Duration::from_secs(1); -/// Maximum backoff duration. +/// Maximum backoff duration for ordinary errors. const MAX_BACKOFF: Duration = Duration::from_secs(60); +/// Extended backoff after a burst of consecutive fatals — then the loop continues. +const RESPAWN_BACKOFF: Duration = Duration::from_secs(30); + /// Manages a set of background jobs, spawning a tokio task for each. pub struct JobSupervisor { handles: Vec>, @@ -28,7 +31,16 @@ impl JobSupervisor { ctx: Arc, mode: crate::config::RuntimeMode, ) -> Self { - let health = JobHealthRegistry::new(); + Self::spawn_all_with_health(jobs, ctx, mode, JobHealthRegistry::new()) + } + + /// Spawn jobs using a shared health registry (exposed via `/health/jobs`). + pub fn spawn_all_with_health( + jobs: Vec>, + ctx: Arc, + mode: crate::config::RuntimeMode, + health: JobHealthRegistry, + ) -> Self { let mut handles = Vec::new(); for job in jobs { @@ -126,9 +138,13 @@ async fn run_job_loop( target: "minos_backend::jobs", job = name, failures = MAX_CONSECUTIVE_FATALS, - "job stopped after too many consecutive failures" + backoff_secs = RESPAWN_BACKOFF.as_secs(), + "job entering respawn backoff after consecutive failures" ); - return; + health.record_respawn(name); + consecutive_backoff = 0; + tokio::time::sleep(RESPAWN_BACKOFF).await; + continue; } } Ok(Ok(outcome)) => { diff --git a/crates/minos-backend/src/runtime.rs b/crates/minos-backend/src/runtime.rs index 540a1e93..16dd3ac5 100644 --- a/crates/minos-backend/src/runtime.rs +++ b/crates/minos-backend/src/runtime.rs @@ -119,6 +119,8 @@ pub struct AppContext { pub outbox_wake: Arc, /// In-process wake for agent_dispatch_worker (enqueue + host online). pub agent_dispatch_wake: Arc, + /// Shared supervised-job health registry (empty when workers are disabled). + pub job_health: crate::jobs::JobHealthRegistry, } impl AppContext { @@ -236,6 +238,7 @@ impl AppContext { instance_id, outbox_wake: Arc::new(tokio::sync::Notify::new()), agent_dispatch_wake: Arc::new(tokio::sync::Notify::new()), + job_health: crate::jobs::JobHealthRegistry::new(), }) } } @@ -311,10 +314,11 @@ impl RuntimeShell { }); let jobs = crate::jobs::default_jobs(Some(Arc::clone(&app.realtime)), Some(Arc::clone(&app))); - Some(crate::jobs::JobSupervisor::spawn_all( + Some(crate::jobs::JobSupervisor::spawn_all_with_health( jobs, ctx, cfg.runtime_mode, + app.job_health.clone(), )) } else { None diff --git a/crates/minos-backend/src/store/approval_requests.rs b/crates/minos-backend/src/store/approval_requests.rs index 490ccedd..f9341cf1 100644 --- a/crates/minos-backend/src/store/approval_requests.rs +++ b/crates/minos-backend/src/store/approval_requests.rs @@ -312,7 +312,91 @@ pub async fn list_expired_pending( } .map_err(store_err("approval_requests::list_expired_pending"))?; - rows.into_iter().map(decode_row).collect() + let mut out = Vec::with_capacity(rows.len()); + for row in rows { + match decode_row(row) { + Ok(decoded) => out.push(decoded), + Err(error) => { + // NULL host / corrupt row must not fail the whole poller batch + // (that previously caused a tight busy-loop on the due deadline). + tracing::warn!( + target: "minos_backend::store::approval_requests", + error = %error, + "skipping undecodable expired approval row" + ); + } + } + } + Ok(out) +} + +pub async fn timeout_pending_with_null_host( + store: &impl AsStorePool, + now_ms: i64, + limit: u32, +) -> Result { + let resolution = serde_json::json!({ "reason": "timeout", "orphan": "null_host" }); + let resolution_json = serde_json::to_string(&resolution).map_err(|error| { + BackendError::StoreDecode { + column: "approval_requests.resolution_json".into(), + message: error.to_string(), + } + })?; + let result = match store.as_store_pool() { + StorePoolRef::Sqlite(pool) => sqlx::query( + "UPDATE approval_requests + SET state = ?, + resolved_at_ms = ?, + resolution_json = ? + WHERE request_id IN ( + SELECT ar.request_id + FROM approval_requests ar + LEFT JOIN agent_sessions s ON s.session_id = ar.agent_session_id + LEFT JOIN sessions t ON t.session_id = ar.agent_session_id + WHERE ar.state = ? + AND ar.deadline_at_ms <= ? + AND COALESCE(s.host_installation_id, t.owner_device_id) IS NULL + ORDER BY ar.deadline_at_ms ASC + LIMIT ? + )", + ) + .bind(ApprovalRequestState::Timeout.as_str()) + .bind(now_ms) + .bind(resolution_json.as_str()) + .bind(ApprovalRequestState::Pending.as_str()) + .bind(now_ms) + .bind(i64::from(limit)) + .execute(pool) + .await + .map(|r| r.rows_affected()), + StorePoolRef::Postgres(pool) => sqlx::query( + "WITH victims AS ( + SELECT ar.request_id + FROM approval_requests ar + JOIN agent_sessions s ON s.session_id = ar.agent_session_id + WHERE ar.state = 'pending'::approval_state + AND ar.deadline_at_ms <= $1 + AND s.host_installation_id IS NULL + ORDER BY ar.deadline_at_ms ASC + LIMIT $3 + ) + UPDATE approval_requests ar + SET state = 'timeout'::approval_state, + resolved_at_ms = $1, + resolution_json = CAST($2 AS JSONB) + FROM victims v + WHERE ar.request_id = v.request_id + AND ar.state = 'pending'::approval_state", + ) + .bind(now_ms) + .bind(resolution_json.as_str()) + .bind(i64::from(limit)) + .execute(pool) + .await + .map(|r| r.rows_affected()), + } + .map_err(store_err("approval_requests::timeout_pending_with_null_host"))?; + Ok(result) } pub async fn next_pending_deadline_at_ms( From 2c4563eea76b1a6779193af78e5a035baa6d9903 Mon Sep 17 00:00:00 2001 From: Engineer Date: Wed, 12 Aug 2026 06:37:27 +0000 Subject: [PATCH 05/12] fix(desktop): access-token refresh, 401 retry, focus/mark-read MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P1 Desktop: - Proactive JWT refresh before expiry; shared ensureFreshCloudAccessToken single-flight for HTTP 401 → refresh → one retry in minos-cloud. - Outbox classifies unauthorized/401 as transient (refreshable), not permanent. - Timeline clears focusedConversationId on unmount; Hub mark-read waits for auth hydrate + observed message_seq so cold-start open commits read watermark. --- apps/desktop/src/features/chat/Timeline.tsx | 14 +++- apps/desktop/src/shared/lib/cloud-auth.ts | 31 ++++++++ apps/desktop/src/shared/lib/im-outbox.test.ts | 2 + apps/desktop/src/shared/lib/im-outbox.ts | 10 ++- apps/desktop/src/shared/lib/minos-cloud.ts | 16 ++++ apps/desktop/src/store/account-store.ts | 78 ++++++++++++++++++- .../src/store/workspace/create-actions.ts | 1 + apps/desktop/src/store/workspace/types.ts | 2 + apps/desktop/src/store/workspace/use-cases.ts | 55 +++++++++---- 9 files changed, 193 insertions(+), 16 deletions(-) diff --git a/apps/desktop/src/features/chat/Timeline.tsx b/apps/desktop/src/features/chat/Timeline.tsx index 5c227ea9..dac2a984 100644 --- a/apps/desktop/src/features/chat/Timeline.tsx +++ b/apps/desktop/src/features/chat/Timeline.tsx @@ -23,6 +23,9 @@ export function Timeline({ conversationId }: { conversationId: string }) { ); const loadTimeline = useWorkspaceStore((s) => s.loadTimeline); const markConversationRead = useWorkspaceStore((s) => s.markConversationRead); + const clearFocusedConversation = useWorkspaceStore( + (s) => s.clearFocusedConversation, + ); const refreshConversationGitStatus = useWorkspaceStore( (s) => s.refreshConversationGitStatus, ); @@ -41,9 +44,18 @@ export function Timeline({ conversationId }: { conversationId: string }) { const errorRecoveryGenRef = useRef(null); // Open/select path: set focus + clear unread (not loadTimeline's job). + // Clear focus on unmount / navigate away so background digests stop auto mark-read. useEffect(() => { markConversationRead(conversationId); - }, [conversationId, markConversationRead, bootEpoch]); + return () => { + clearFocusedConversation(conversationId); + }; + }, [ + conversationId, + markConversationRead, + clearFocusedConversation, + bootEpoch, + ]); // Init: hydrate Timeline only (messages). Inspector hydrates independently when // details panel opens or @-mention needs sessions. diff --git a/apps/desktop/src/shared/lib/cloud-auth.ts b/apps/desktop/src/shared/lib/cloud-auth.ts index 3a9c5ddf..565279a6 100644 --- a/apps/desktop/src/shared/lib/cloud-auth.ts +++ b/apps/desktop/src/shared/lib/cloud-auth.ts @@ -13,14 +13,25 @@ export type CloudAuthSnapshot = { }; type CloudAuthProvider = () => CloudAuthSnapshot | null; +/** Refresh access token; returns new bearer or null if refresh failed / signed out. */ +type CloudAccessTokenRefresher = () => Promise; let provider: CloudAuthProvider | null = null; +let refresher: CloudAccessTokenRefresher | null = null; +let refreshInFlight: Promise | null = null; /** Wire account-store (or tests) as the sole auth source for shared transport. */ export function registerCloudAuthProvider(next: CloudAuthProvider): void { provider = next; } +/** Wire account-store proactive / 401 refresh implementation. */ +export function registerCloudAccessTokenRefresher( + next: CloudAccessTokenRefresher, +): void { + refresher = next; +} + /** Current Hub credentials, or null when signed out / incomplete. */ export function getCloudAuth(): CloudAuthSnapshot | null { if (!provider) return null; @@ -40,3 +51,23 @@ export function isCloudAuthReady(): boolean { auth.authPhase === "authenticated", ); } + +/** + * Ensure a fresh access token (single-flight). Used by HTTP 401 retry and + * proactive refresh. Returns null when signed out or refresh fails. + */ +export async function ensureFreshCloudAccessToken(): Promise { + if (!refresher) { + return getCloudAuth()?.accessToken?.trim() || null; + } + if (!refreshInFlight) { + refreshInFlight = (async () => { + try { + return await refresher!(); + } finally { + refreshInFlight = null; + } + })(); + } + return refreshInFlight; +} diff --git a/apps/desktop/src/shared/lib/im-outbox.test.ts b/apps/desktop/src/shared/lib/im-outbox.test.ts index ee0ae3ba..60e59c46 100644 --- a/apps/desktop/src/shared/lib/im-outbox.test.ts +++ b/apps/desktop/src/shared/lib/im-outbox.test.ts @@ -160,6 +160,8 @@ describe("im-outbox", () => { assert.equal(classifyOutboxFailure("HTTP 400"), "permanent"); assert.equal(classifyOutboxFailure("invalid_payload_json"), "permanent"); assert.equal(classifyOutboxFailure("HTTP 429 rate limit"), "transient"); + assert.equal(classifyOutboxFailure("unauthorized"), "transient"); + assert.equal(classifyOutboxFailure("HTTP 401"), "transient"); }); it("reclaims stale inflight so kill mid-flight becomes due again", async () => { diff --git a/apps/desktop/src/shared/lib/im-outbox.ts b/apps/desktop/src/shared/lib/im-outbox.ts index f218d83a..9ab6b0c7 100644 --- a/apps/desktop/src/shared/lib/im-outbox.ts +++ b/apps/desktop/src/shared/lib/im-outbox.ts @@ -384,13 +384,21 @@ export type OutboxFailureClass = "transient" | "permanent"; export function classifyOutboxFailure(error: string): OutboxFailureClass { const e = error.toLowerCase(); + // Auth expiry is recoverable via refresh + retry — never fail_terminal on first 401. + if ( + e.includes("unauthorized") || + e.includes("http 401") || + e.includes("status: 401") || + e.includes("status 401") + ) { + return "transient"; + } if ( e.includes("invalid_payload") || e.includes("empty_text") || e.includes("invalid payload") || e.includes("permission") || e.includes("forbidden") || - e.includes("unauthorized") || e.includes("not found") || e.includes("http 4") || e.includes("status: 4") || diff --git a/apps/desktop/src/shared/lib/minos-cloud.ts b/apps/desktop/src/shared/lib/minos-cloud.ts index e8c7cedf..6c8c8c54 100644 --- a/apps/desktop/src/shared/lib/minos-cloud.ts +++ b/apps/desktop/src/shared/lib/minos-cloud.ts @@ -5,6 +5,8 @@ * D02 same-account host link). Device role is `desktop-console`. */ +import { ensureFreshCloudAccessToken } from "@/shared/lib/cloud-auth"; + const DEFAULT_BACKEND_URL = "http://127.0.0.1:8787"; export type AuthResponse = { @@ -112,8 +114,22 @@ function errorFromPayload( async function requestJson( path: string, init: RequestInit, + opts?: { _retried401?: boolean }, ): Promise { const response = await fetch(`${backendHttpBase()}${path}`, init); + if ( + response.status === 401 && + !opts?._retried401 && + !path.includes("/v1/auth/refresh") && + !path.includes("/v1/auth/logout") + ) { + const nextToken = await ensureFreshCloudAccessToken(); + if (nextToken) { + const headers = new Headers(init.headers); + headers.set("authorization", `Bearer ${nextToken}`); + return requestJson(path, { ...init, headers }, { _retried401: true }); + } + } if (!response.ok) { const payload = await parseErrorPayload(response); throw errorFromPayload(response.status, payload); diff --git a/apps/desktop/src/store/account-store.ts b/apps/desktop/src/store/account-store.ts index c24ba5f2..c0924b84 100644 --- a/apps/desktop/src/store/account-store.ts +++ b/apps/desktop/src/store/account-store.ts @@ -42,7 +42,10 @@ import { import { daemonApi } from "@/shared/lib/daemon"; import { runHostEnsure } from "@/features/host/lib/host-connection-machine"; import type { DesktopAuthPhase } from "@/shared/lib/desktop-root-gate"; -import { registerCloudAuthProvider } from "@/shared/lib/cloud-auth"; +import { + registerCloudAccessTokenRefresher, + registerCloudAuthProvider, +} from "@/shared/lib/cloud-auth"; import { bumpAccountScopeGeneration, leaveAccountScope, @@ -123,6 +126,69 @@ let ensureInFlight: Promise | null = null; let ensureGeneration = 0; let hydrateInFlight: Promise | null = null; let hydrateGeneration = 0; +let accessTokenRefreshTimer: ReturnType | null = null; +let accessTokenRefreshInFlight: Promise | null = null; +type AccountStoreApi = { + getState: () => AccountState; + setState: ( + partial: + | Partial + | ((state: AccountState) => Partial), + ) => void; +}; +let accountStoreApi: AccountStoreApi | null = null; + +function clearAccessTokenRefreshTimer(): void { + if (accessTokenRefreshTimer) { + clearTimeout(accessTokenRefreshTimer); + accessTokenRefreshTimer = null; + } +} + +function scheduleAccessTokenRefresh(session: MinosSession): void { + clearAccessTokenRefreshTimer(); + const expiresAt = session.issuedAtMs + session.expiresInSec * 1000; + // Refresh 90s before expiry (isAccessTokenFresh uses 60s skew). + const delay = Math.max(5_000, expiresAt - Date.now() - 90_000); + accessTokenRefreshTimer = setTimeout(() => { + void ensureFreshAccessTokenInternal(); + }, delay); +} + +async function ensureFreshAccessTokenInternal(): Promise { + if (accessTokenRefreshInFlight) return accessTokenRefreshInFlight; + accessTokenRefreshInFlight = (async () => { + const api = accountStoreApi; + if (!api) return null; + const state = api.getState(); + const session = state.session; + if (!session?.refreshToken?.trim()) return null; + if (isAccessTokenFresh(session)) { + scheduleAccessTokenRefresh(session); + return session.accessToken; + } + try { + const tokens = await refreshSession(state.deviceId, session.refreshToken); + const next: MinosSession = { + ...session, + accessToken: tokens.access_token, + refreshToken: tokens.refresh_token, + expiresInSec: tokens.expires_in, + issuedAtMs: Date.now(), + }; + saveStoredSession(next); + api.setState({ session: next }); + scheduleAccessTokenRefresh(next); + return next.accessToken; + } catch (error) { + console.warn("[account-store] access token refresh failed", error); + return null; + } + })().finally(() => { + accessTokenRefreshInFlight = null; + }); + return accessTokenRefreshInFlight; +} function applyAuthSuccess( set: ( @@ -164,6 +230,7 @@ function applyAuthSuccess( ); const forceReregister = !hostOwned || prevAccountId !== nextAccountId || !hostBind.bound; + scheduleAccessTokenRefresh(session); void get().ensureCloudConnection( forceReregister ? { forceReregister: true } : undefined, ); @@ -223,6 +290,7 @@ export const useAccountStore = create()((set, get) => ({ authPhase: "authenticated", hydrated: true, }); + scheduleAccessTokenRefresh(stored); void import("@/store/im/im-cloud-bridge").then(({ ensureImCloudBridge }) => ensureImCloudBridge(), ); @@ -313,6 +381,7 @@ export const useAccountStore = create()((set, get) => ({ }, signOut: async () => { + clearAccessTokenRefreshTimer(); const { session, deviceId } = get(); set({ busy: true, error: null }); ensureGeneration += 1; @@ -489,6 +558,11 @@ export const useAccountStore = create()((set, get) => ({ }, })); +accountStoreApi = { + getState: () => useAccountStore.getState(), + setState: (partial) => useAccountStore.setState(partial), +}; + // Shared transport reads auth via this port — never imports account-store. registerCloudAuthProvider(() => { const { deviceId, session, authPhase } = useAccountStore.getState(); @@ -502,3 +576,5 @@ registerCloudAuthProvider(() => { authPhase, }; }); + +registerCloudAccessTokenRefresher(() => ensureFreshAccessTokenInternal()); diff --git a/apps/desktop/src/store/workspace/create-actions.ts b/apps/desktop/src/store/workspace/create-actions.ts index f4533d16..d0b53c4f 100644 --- a/apps/desktop/src/store/workspace/create-actions.ts +++ b/apps/desktop/src/store/workspace/create-actions.ts @@ -35,6 +35,7 @@ export function createWorkspaceActions( | "respondOpencodePermission" | "respondOpencodeQuestion" | "markConversationRead" + | "clearFocusedConversation" | "sendMessage" | "retryFailedMessage" | "createConversation" diff --git a/apps/desktop/src/store/workspace/types.ts b/apps/desktop/src/store/workspace/types.ts index d756f720..42abb54b 100644 --- a/apps/desktop/src/store/workspace/types.ts +++ b/apps/desktop/src/store/workspace/types.ts @@ -211,6 +211,8 @@ export type WorkspaceState = { ) => Promise; /** Mark conversation messages as read (clears unread badge). */ markConversationRead: (conversationId: string) => void; + /** Clear focus when Timeline unmounts / navigates away. */ + clearFocusedConversation: (conversationId?: string) => void; clearActionError: () => void; sendMessage: ( conversationId: string, diff --git a/apps/desktop/src/store/workspace/use-cases.ts b/apps/desktop/src/store/workspace/use-cases.ts index c0ad5e11..16ee4d9f 100644 --- a/apps/desktop/src/store/workspace/use-cases.ts +++ b/apps/desktop/src/store/workspace/use-cases.ts @@ -334,6 +334,7 @@ export function createUseCasesActions( | "respondOpencodePermission" | "respondOpencodeQuestion" | "markConversationRead" + | "clearFocusedConversation" | "sendMessage" | "retryFailedMessage" > { @@ -539,26 +540,47 @@ export function createUseCasesActions( const { isCloudImMode } = await import("@/shared/lib/cloud-timeline"); const { lastMessageSeq } = await import("@/shared/lib/message-history"); const { useAccountStore } = await import("@/store/account-store"); - const { deviceId, session, authPhase } = useAccountStore.getState(); + // Cold-start: Timeline mark-read can race hydrateAuth / loadTimeline. + // Wait briefly for auth + an observed Hub seq before giving up. + let deviceId = ""; + let accessToken = ""; + let observedSeq: number | null = null; + for (let attempt = 0; attempt < 8; attempt += 1) { + if (get().focusedConversationId !== conversationId) return; + const { deviceId: did, session, authPhase, hydrated } = + useAccountStore.getState(); + deviceId = did; + if (!hydrated) { + await new Promise((r) => setTimeout(r, 100)); + continue; + } + if ( + !isCloudImMode({ + authPhase, + accessToken: session?.accessToken, + }) || + !session?.accessToken + ) { + return; + } + accessToken = session.accessToken; + const timeline = get().messagesByConversation[conversationId] ?? []; + observedSeq = lastMessageSeq(timeline); + if (observedSeq != null && observedSeq > 0) break; + await new Promise((r) => setTimeout(r, 150)); + } if ( - !isCloudImMode({ - authPhase, - accessToken: session?.accessToken, - }) || - !session?.accessToken + !accessToken || + observedSeq == null || + observedSeq <= 0 || + get().focusedConversationId !== conversationId ) { return; } - const timeline = get().messagesByConversation[conversationId] ?? []; - const observedSeq = lastMessageSeq(timeline); - if (observedSeq == null || observedSeq <= 0) { - // No Hub seq loaded yet — skip HTTP; local rail already cleared. - return; - } try { await cloud.markCloudConversationRead( deviceId, - session.accessToken, + accessToken, conversationId, observedSeq, ); @@ -568,6 +590,13 @@ export function createUseCasesActions( }); }, + clearFocusedConversation: (conversationId) => { + const focused = get().focusedConversationId; + if (!focused) return; + if (conversationId && focused !== conversationId) return; + set({ focusedConversationId: null }); + }, + sendMessage: async (conversationId, body, messageId, options) => { const messageBody = body.trimEnd(); if (!messageBody.trim()) return; From 1f8b58d5bd0322dbb2901d1bd7b764590a1e0c3c Mon Sep 17 00:00:00 2001 From: Engineer Date: Wed, 12 Aug 2026 06:38:50 +0000 Subject: [PATCH 06/12] fix(mobile): recover Lagged streams, rebind inbox, isolate outbox P1 Mobile: - FRB ui/social event forwarders continue after broadcast Lagged instead of breaking the stream for the process lifetime. - ConversationsController rebinds socialEvents on every build so invalidate after reconnect cannot leave a dead subscription. - im_outbox gains account_id (db v8); drain filters by current account; logout clears social_cache.db (outbox + conversations + messages). - Enlarge mobile social/ui broadcast buffers to reduce lag under catch-up. --- .../mobile/lib/application/auth_provider.dart | 3 ++ .../social/social_inbox_notifier.dart | 15 +++++-- .../infrastructure/social_cache_store.dart | 40 ++++++++++++++++++- crates/minos-ffi-frb/src/api/minos.rs | 10 +++-- crates/minos-mobile/src/client.rs | 8 ++-- 5 files changed, 63 insertions(+), 13 deletions(-) diff --git a/apps/mobile/lib/application/auth_provider.dart b/apps/mobile/lib/application/auth_provider.dart index d047b44c..5a9d5e42 100644 --- a/apps/mobile/lib/application/auth_provider.dart +++ b/apps/mobile/lib/application/auth_provider.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:minos/data/repositories/auth_repository.dart'; +import 'package:minos/data/services/social_cache_store_service.dart'; import 'package:minos/domain/auth_state.dart'; import 'package:minos/src/rust/api/minos.dart' show @@ -96,5 +97,7 @@ class AuthController extends _$AuthController { /// Dual-session logout: Minos revoke + local wipe + best-effort Supabase. Future logout() async { await _repository.logout(); + // Account-scope: drop social cache + im_outbox so drafts cannot send as B. + await ref.read(socialCacheStoreProvider).clearAllForLogout(); } } diff --git a/apps/mobile/lib/application/social/social_inbox_notifier.dart b/apps/mobile/lib/application/social/social_inbox_notifier.dart index b6763f32..2bfd6c52 100644 --- a/apps/mobile/lib/application/social/social_inbox_notifier.dart +++ b/apps/mobile/lib/application/social/social_inbox_notifier.dart @@ -30,7 +30,10 @@ class ConversationsController extends AsyncNotifier { // Arm SnapshotRequired consumer for app lifetime (Inbox/Timeline). ref.watch(imSnapshotSyncProvider); - _eventsSub ??= ref + // Always (re)bind on build so provider invalidate after reconnect does not + // leave a cancelled/completed subscription (C1). + await _eventsSub?.cancel(); + _eventsSub = ref .read(socialRepositoryProvider) .socialEvents .listen( @@ -45,9 +48,15 @@ class ConversationsController extends AsyncNotifier { onError: (Object error, StackTrace stackTrace) { // Connection errors: soft; next hydrate corrects. }, - onDone: () {}, + onDone: () { + // Stream ended unexpectedly — clear so a later rebuild rebinds. + _eventsSub = null; + }, ); - ref.onDispose(() => _eventsSub?.cancel()); + ref.onDispose(() { + unawaited(_eventsSub?.cancel() ?? Future.value()); + _eventsSub = null; + }); // Start IM outbox worker once conversations hydrate; wire UI refresh hooks. final outbox = ref.read(imOutboxWorkerProvider); diff --git a/apps/mobile/lib/infrastructure/social_cache_store.dart b/apps/mobile/lib/infrastructure/social_cache_store.dart index 2b779ad2..f97e3785 100644 --- a/apps/mobile/lib/infrastructure/social_cache_store.dart +++ b/apps/mobile/lib/infrastructure/social_cache_store.dart @@ -14,7 +14,7 @@ class SocialCacheStore { SocialCacheStore(); static const _dbName = 'social_cache.db'; - static const _dbVersion = 7; + static const _dbVersion = 8; Future? _databaseFuture; @@ -126,6 +126,14 @@ class SocialCacheStore { "ALTER TABLE cached_social_messages ADD COLUMN mentioned_agent_ids_json TEXT NOT NULL DEFAULT '[]'", ); } + if (oldVersion < 8) { + await db.execute( + "ALTER TABLE im_outbox ADD COLUMN account_id TEXT NOT NULL DEFAULT ''", + ); + await db.execute( + 'CREATE INDEX IF NOT EXISTS idx_im_outbox_account_due ON im_outbox(account_id, status, next_attempt_at_ms)', + ); + } }, ); } catch (_) { @@ -137,6 +145,7 @@ class SocialCacheStore { await db.execute(''' CREATE TABLE IF NOT EXISTS im_outbox ( client_op_id TEXT PRIMARY KEY, + account_id TEXT NOT NULL DEFAULT '', kind TEXT NOT NULL, conversation_id TEXT NOT NULL, payload_json TEXT NOT NULL, @@ -151,6 +160,23 @@ class SocialCacheStore { await db.execute( 'CREATE INDEX IF NOT EXISTS idx_im_outbox_due ON im_outbox(status, next_attempt_at_ms)', ); + await db.execute( + 'CREATE INDEX IF NOT EXISTS idx_im_outbox_account_due ON im_outbox(account_id, status, next_attempt_at_ms)', + ); + } + + /// Wipe social cache + outbox on logout so drafts cannot send as another account. + Future clearAllForLogout() async { + final db = await _database(); + if (db == null) { + return; + } + await db.transaction((txn) async { + await txn.delete('im_outbox'); + await txn.delete('cached_social_messages'); + await txn.delete('cached_social_conversations'); + await txn.delete('cached_social_meta'); + }); } Future saveCurrentAccountId(String accountId) async { @@ -516,8 +542,10 @@ class SocialCacheStore { required ImOutboxKind kind, required String conversationId, required String payloadJson, + String? accountId, }) async { final now = DateTime.now().millisecondsSinceEpoch; + final owner = (accountId ?? await loadCurrentAccountId() ?? '').trim(); final existing = await txn.query( 'im_outbox', where: 'client_op_id = ?', @@ -534,6 +562,7 @@ class SocialCacheStore { await txn.update( 'im_outbox', { + 'account_id': owner, 'payload_json': payloadJson, 'kind': imOutboxKindWire(kind), 'status': imOutboxStatusWire(ImOutboxStatus.pending), @@ -548,6 +577,7 @@ class SocialCacheStore { } await txn.insert('im_outbox', { 'client_op_id': clientOpId, + 'account_id': owner, 'kind': imOutboxKindWire(kind), 'conversation_id': conversationId, 'payload_json': payloadJson, @@ -596,13 +626,19 @@ class SocialCacheStore { } final now = nowMs ?? DateTime.now().millisecondsSinceEpoch; await reclaimStaleOutbox(nowMs: now); + final accountId = (await loadCurrentAccountId() ?? '').trim(); + if (accountId.isEmpty) { + // No signed-in account — never drain foreign/legacy rows. + return const >[]; + } // Active rows only (pending + inflight) so a backoff head blocks the lane. final rows = await db.query( 'im_outbox', - where: 'status = ? OR status = ?', + where: '(status = ? OR status = ?) AND account_id = ?', whereArgs: [ imOutboxStatusWire(ImOutboxStatus.pending), imOutboxStatusWire(ImOutboxStatus.inflight), + accountId, ], orderBy: 'created_at_ms ASC, client_op_id ASC', ); diff --git a/crates/minos-ffi-frb/src/api/minos.rs b/crates/minos-ffi-frb/src/api/minos.rs index 19b38809..0c956318 100644 --- a/crates/minos-ffi-frb/src/api/minos.rs +++ b/crates/minos-ffi-frb/src/api/minos.rs @@ -580,8 +580,9 @@ impl MobileClient { } } Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => { - tracing::warn!(skipped = n, "ui_events_stream lagged"); - break; + // Continue: breaking kills the FRB stream for process lifetime. + tracing::warn!(skipped = n, "ui_events_stream lagged; continuing"); + continue; } Err(tokio::sync::broadcast::error::RecvError::Closed) => break, } @@ -601,8 +602,9 @@ impl MobileClient { } } Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => { - tracing::warn!(skipped = n, "social_events_stream lagged"); - break; + // Continue: breaking kills social realtime for process lifetime. + tracing::warn!(skipped = n, "social_events_stream lagged; continuing"); + continue; } Err(tokio::sync::broadcast::error::RecvError::Closed) => break, } diff --git a/crates/minos-mobile/src/client.rs b/crates/minos-mobile/src/client.rs index 500c80d2..8f603a68 100644 --- a/crates/minos-mobile/src/client.rs +++ b/crates/minos-mobile/src/client.rs @@ -147,8 +147,8 @@ impl MobileClient { device_id: DeviceId, ) -> Self { let (state_tx, state_rx) = watch::channel(ConnectionState::Disconnected); - let (ui_events_tx, _) = broadcast::channel(256); - let (social_events_tx, _) = broadcast::channel(256); + let (ui_events_tx, _) = broadcast::channel(1024); + let (social_events_tx, _) = broadcast::channel(1024); let (auth_state_tx, auth_state_rx) = watch::channel(AuthStateFrame::Unauthenticated); Self { store, @@ -218,8 +218,8 @@ impl MobileClient { }); let (state_tx, state_rx) = watch::channel(ConnectionState::Disconnected); - let (ui_events_tx, _) = broadcast::channel(256); - let (social_events_tx, _) = broadcast::channel(256); + let (ui_events_tx, _) = broadcast::channel(1024); + let (social_events_tx, _) = broadcast::channel(1024); let initial_auth_frame = match &live_auth { Some(s) => AuthStateFrame::Authenticated { account: s.account.clone(), From 534e6b8ebd41e28e068372119cb9f4d110f78251 Mon Sep 17 00:00:00 2001 From: Engineer Date: Wed, 12 Aug 2026 06:41:24 +0000 Subject: [PATCH 07/12] fix(daemon): avoid dispatch deadlock and harden Claude shutdown Spawn BotInboxDelivery off the dispatch loop so inject cannot self-deadlock on the uplink drain. Bound AppendBotMessage sends instead of silent try_send drops after accept. Reap Claude turns via process-group SIGTERM/SIGKILL on shutdown, and use char-boundary-safe UTF-8 prefixes to stop panics taking run_dispatch offline. --- .../minos-agent-runtime/src/claude_driver.rs | 20 +++++- crates/minos-agent-runtime/src/manager.rs | 14 ++++ crates/minos-daemon/src/agent.rs | 8 ++- .../src/conversation_completion.rs | 61 ++++++++++------ crates/minos-daemon/src/media_materialize.rs | 2 +- crates/minos-daemon/src/relay_client.rs | 70 ++++++++++--------- 6 files changed, 117 insertions(+), 58 deletions(-) diff --git a/crates/minos-agent-runtime/src/claude_driver.rs b/crates/minos-agent-runtime/src/claude_driver.rs index 4f2b3c88..4f7bd679 100644 --- a/crates/minos-agent-runtime/src/claude_driver.rs +++ b/crates/minos-agent-runtime/src/claude_driver.rs @@ -348,6 +348,14 @@ impl ClaudeControlSession { Ok(()) } + /// Leader pid of the current turn child (for process-group shutdown). + pub fn current_turn_pid(&self) -> Option { + self.current_turn_child + .as_ref() + .and_then(Child::id) + .and_then(|pid| i32::try_from(pid).ok()) + } + async fn hard_kill(&mut self) { self.process_alive.store(false, Ordering::SeqCst); // Drop stdin first so CLI notices EOF. @@ -358,8 +366,10 @@ impl ClaudeControlSession { let pid = child.id(); if let Some(pid) = pid { #[allow(clippy::cast_possible_wrap)] + let pid_i32 = pid as i32; + // Negative pid = process group (child was spawned with setpgid(0,0)). unsafe { - libc::kill(pid as i32, libc::SIGTERM); + libc::kill(-pid_i32, libc::SIGTERM); } } } @@ -370,6 +380,14 @@ impl ClaudeControlSession { session_id = %self.session_id, "claude did not exit after SIGTERM, sending SIGKILL" ); + #[cfg(unix)] + if let Some(pid) = child.id() { + #[allow(clippy::cast_possible_wrap)] + let pid_i32 = pid as i32; + unsafe { + libc::kill(-pid_i32, libc::SIGKILL); + } + } let _ = child.kill().await; } } diff --git a/crates/minos-agent-runtime/src/manager.rs b/crates/minos-agent-runtime/src/manager.rs index 840981f3..fc31a408 100644 --- a/crates/minos-agent-runtime/src/manager.rs +++ b/crates/minos-agent-runtime/src/manager.rs @@ -2719,6 +2719,14 @@ impl AgentManager { } } } + { + let g = self.claude_sessions.lock().await; + for session in g.values() { + if let Some(pid) = session.current_turn_pid() { + pgids.push(pid); + } + } + } // SIGTERM each process group (negative pid = group whose // leader is this pid; set in each driver's pre_exec setpgid). @@ -2791,6 +2799,12 @@ impl AgentManager { } } } + { + let mut g = self.claude_sessions.lock().await; + for (_, session) in std::mem::take(&mut *g) { + session.close(&self.events_tx).await; + } + } // Clear session maps so a later resume cannot target dead provider ids. self.opencode_session_map.lock().await.clear(); } diff --git a/crates/minos-daemon/src/agent.rs b/crates/minos-daemon/src/agent.rs index 9893f434..a37956d5 100644 --- a/crates/minos-daemon/src/agent.rs +++ b/crates/minos-daemon/src/agent.rs @@ -5410,8 +5410,12 @@ fn parse_conversation_mentions_from_body(body: &str) -> Vec String { + s.chars().take(max_chars).collect() +} + fn short_mcp_session_id(session_id: &str) -> String { - session_id[..8.min(session_id.len())].to_owned() + short_prefix(session_id, 8) } pub(crate) fn map_store_error(operation: &str, e: anyhow::Error) -> MinosError { @@ -5860,7 +5864,7 @@ async fn ensure_hub_collaboration_conversation( } else { let project_id = format!( "project-hub-{}", - &conversation_id[..8.min(conversation_id.len())] + short_prefix(conversation_id, 8) ); store .ensure_project(&project_id, "Hub", "hub", None, now_ms) diff --git a/crates/minos-daemon/src/conversation_completion.rs b/crates/minos-daemon/src/conversation_completion.rs index 03a40fb9..533e359a 100644 --- a/crates/minos-daemon/src/conversation_completion.rs +++ b/crates/minos-daemon/src/conversation_completion.rs @@ -873,29 +873,46 @@ impl ConversationCompletion { mentions: Vec::new(), reply_to_message_id: Some(origin_message_id.to_owned()), }; - match tx.try_send(frame) { - Ok(()) => { - info!( - target: "minos_daemon::conversation_completion", - delivery_id = %mailbox.delivery_id, - bot_id = %mailbox.bot_id, - conversation_id, - session_id, - operation_id, - "emitted AppendBotMessage for mailbox delivery" - ); - } - Err(error) => { - warn!( - target: "minos_daemon::conversation_completion", - delivery_id = %mailbox.delivery_id, - conversation_id, - session_id, - error = %error, - "failed to enqueue AppendBotMessage" - ); + let delivery_id = mailbox.delivery_id.clone(); + let bot_id = mailbox.bot_id.clone(); + let conversation_id = conversation_id.to_owned(); + let session_id = session_id.to_owned(); + let operation_id = operation_id.to_owned(); + // Never silently drop after accept — bound wait, then warn loudly. + tokio::spawn(async move { + match tokio::time::timeout(std::time::Duration::from_secs(30), tx.send(frame)).await { + Ok(Ok(())) => { + info!( + target: "minos_daemon::conversation_completion", + delivery_id = %delivery_id, + bot_id = %bot_id, + conversation_id = %conversation_id, + session_id = %session_id, + operation_id = %operation_id, + "emitted AppendBotMessage for mailbox delivery" + ); + } + Ok(Err(error)) => { + warn!( + target: "minos_daemon::conversation_completion", + delivery_id = %delivery_id, + conversation_id = %conversation_id, + session_id = %session_id, + error = %error, + "AppendBotMessage channel closed" + ); + } + Err(_) => { + warn!( + target: "minos_daemon::conversation_completion", + delivery_id = %delivery_id, + conversation_id = %conversation_id, + session_id = %session_id, + "AppendBotMessage enqueue timed out (backpressure)" + ); + } } - } + }); } /// Outbox-first source delivery: durable row with stable id before provider send. diff --git a/crates/minos-daemon/src/media_materialize.rs b/crates/minos-daemon/src/media_materialize.rs index 786b21a1..426cb16b 100644 --- a/crates/minos-daemon/src/media_materialize.rs +++ b/crates/minos-daemon/src/media_materialize.rs @@ -214,7 +214,7 @@ fn safe_filename(att: &DispatchAttachment, idx: usize) -> String { let stem = if blob.is_empty() { "blob".to_string() } else { - blob[..8.min(blob.len())].to_string() + blob.chars().take(8).collect::() }; format!("{idx}_{stem}.{ext}") } diff --git a/crates/minos-daemon/src/relay_client.rs b/crates/minos-daemon/src/relay_client.rs index efe514a0..eeff5e65 100644 --- a/crates/minos-daemon/src/relay_client.rs +++ b/crates/minos-daemon/src/relay_client.rs @@ -1118,16 +1118,28 @@ async fn route_server_frame(frame: ServerFrame, ctx: &DispatchCtx) { session, lease_expires_at_ms, } => { - Box::pin(handle_bot_inbox_delivery( - ctx, - delivery_id, - conversation_id, - message, - bot, - session, - lease_expires_at_ms, - )) - .await; + // Do not await inject on the dispatch loop — it can fill out_tx and + // self-deadlock while this branch holds the only out_rx consumer. + let store = Arc::clone(&ctx.store); + let out_tx = ctx.out_tx.clone(); + let rpc_server = ctx.rpc_server.clone(); + let self_device_id = ctx.self_device_id; + tokio::spawn(async move { + // Reconstruct a minimal ctx-like bundle via a dedicated helper. + handle_bot_inbox_delivery_spawned( + store, + out_tx, + rpc_server, + self_device_id, + delivery_id, + conversation_id, + message, + bot, + session, + lease_expires_at_ms, + ) + .await; + }); } ServerFrame::CancelDelivery { delivery_id } => { tracing::info!( @@ -1571,8 +1583,11 @@ fn build_host_command_result( // ─── Bot mailbox consumer ────────────────────────────────────────────── -async fn handle_bot_inbox_delivery( - ctx: &DispatchCtx, +async fn handle_bot_inbox_delivery_spawned( + store: Arc, + out_tx: mpsc::Sender, + rpc_server: Option>, + _self_device_id: DeviceId, delivery_id: String, conversation_id: String, message: minos_protocol::ChatMessageSummary, @@ -1593,8 +1608,7 @@ async fn handle_bot_inbox_delivery( let now_ms = chrono::Utc::now().timestamp_millis(); let session_hint = session.session_id.as_deref().filter(|s| !s.is_empty()); - let begin = match ctx - .store + let begin = match store .begin_bot_delivery( &delivery_id, &conversation_id, @@ -1612,8 +1626,7 @@ async fn handle_bot_inbox_delivery( error = %error, "bot delivery ledger begin failed" ); - let _ = ctx - .out_tx + let _ = out_tx .send(ClientFrame::DeliveryRejected { delivery_id, code: "host_ledger_error".into(), @@ -1634,8 +1647,7 @@ async fn handle_bot_inbox_delivery( return; } BotDeliveryBegin::ReplayAccepted => { - let _ = ctx - .out_tx + let _ = out_tx .send(ClientFrame::DeliveryAccepted { delivery_id: delivery_id.clone(), }) @@ -1643,8 +1655,7 @@ async fn handle_bot_inbox_delivery( return; } BotDeliveryBegin::ReplayRejected => { - let _ = ctx - .out_tx + let _ = out_tx .send(ClientFrame::DeliveryRejected { delivery_id: delivery_id.clone(), code: "already_rejected".into(), @@ -1655,18 +1666,16 @@ async fn handle_bot_inbox_delivery( } } - let Some(rpc_server) = ctx.rpc_server.clone() else { + let Some(rpc_server) = rpc_server.clone() else { tracing::warn!( target: "minos_daemon::relay_client", delivery_id = %delivery_id, "no rpc_server wired — rejecting BotInboxDelivery" ); - let _ = ctx - .store + let _ = store .mark_bot_delivery_rejected(&delivery_id, "rpc_server not wired", now_ms) .await; - let _ = ctx - .out_tx + let _ = out_tx .send(ClientFrame::DeliveryRejected { delivery_id, code: "host_not_ready".into(), @@ -1692,8 +1701,7 @@ async fn handle_bot_inbox_delivery( .await; match inject { Ok(()) => { - if let Err(error) = ctx - .store + if let Err(error) = store .mark_bot_delivery_injected(&delivery_id, session_hint, now_ms) .await { @@ -1709,8 +1717,7 @@ async fn handle_bot_inbox_delivery( delivery_id = %delivery_id, "BotInboxDelivery injected into local session" ); - let _ = ctx - .out_tx + let _ = out_tx .send(ClientFrame::DeliveryAccepted { delivery_id: delivery_id.clone(), }) @@ -1719,7 +1726,7 @@ async fn handle_bot_inbox_delivery( Err((code, detail)) => { // Retryable inject failure: clear non-terminal received so Hub requeue // can redeliver. Do not mark rejected (that would poison redelivery). - let _ = ctx.store.clear_bot_delivery_inflight(&delivery_id).await; + let _ = store.clear_bot_delivery_inflight(&delivery_id).await; tracing::warn!( target: "minos_daemon::relay_client", delivery_id = %delivery_id, @@ -1727,8 +1734,7 @@ async fn handle_bot_inbox_delivery( detail = %detail, "BotInboxDelivery inject failed" ); - let _ = ctx - .out_tx + let _ = out_tx .send(ClientFrame::DeliveryRejected { delivery_id, code, From d4d22c1217c9f3cb778e80e79e34bc7d39437789 Mon Sep 17 00:00:00 2001 From: Engineer Date: Wed, 12 Aug 2026 06:46:06 +0000 Subject: [PATCH 08/12] fix(backend): harden host-command ownership and push delivery Require owning host_installation_id on host-command ack/finish (H4). Renew mailbox leases on host Ping and delivery activity so long turns keep the 2-minute lease alive (H5). Persist provider_token alongside token_hash so APNs/FCM have send material (H6). Treat user_online, quiet_hours, and cooldown as deferred requeues that do not burn dead-letter attempts (H7/H8). --- .../0002_push_token_provider_token.sql | 3 + .../sqlite/0002_push_token_provider_token.sql | 3 + .../src/jobs/push_dispatch_worker.rs | 23 +++- .../src/notifications/channels/apns.rs | 1 + .../src/notifications/channels/fcm.rs | 1 + .../src/notifications/channels/mod.rs | 2 + .../src/notifications/use_case.rs | 29 ++++- crates/minos-backend/src/realtime/gateway.rs | 43 +++++++- .../src/store/agent_dispatch_queue.rs | 101 ++++++++++++++++++ .../minos-backend/src/store/host_commands.rs | 66 +++++++++++- .../minos-backend/src/store/outbox_events.rs | 11 +- crates/minos-backend/src/store/push_tokens.rs | 26 +++-- 12 files changed, 288 insertions(+), 21 deletions(-) create mode 100644 crates/minos-backend/migrations/postgres/0002_push_token_provider_token.sql create mode 100644 crates/minos-backend/migrations/sqlite/0002_push_token_provider_token.sql diff --git a/crates/minos-backend/migrations/postgres/0002_push_token_provider_token.sql b/crates/minos-backend/migrations/postgres/0002_push_token_provider_token.sql new file mode 100644 index 00000000..872a1d51 --- /dev/null +++ b/crates/minos-backend/migrations/postgres/0002_push_token_provider_token.sql @@ -0,0 +1,3 @@ +-- Persist provider device token alongside hash so APNs/FCM can deliver. +-- Hash remains the primary key for upsert/revoke; provider_token is the send material. +ALTER TABLE push_tokens ADD COLUMN provider_token TEXT; diff --git a/crates/minos-backend/migrations/sqlite/0002_push_token_provider_token.sql b/crates/minos-backend/migrations/sqlite/0002_push_token_provider_token.sql new file mode 100644 index 00000000..872a1d51 --- /dev/null +++ b/crates/minos-backend/migrations/sqlite/0002_push_token_provider_token.sql @@ -0,0 +1,3 @@ +-- Persist provider device token alongside hash so APNs/FCM can deliver. +-- Hash remains the primary key for upsert/revoke; provider_token is the send material. +ALTER TABLE push_tokens ADD COLUMN provider_token TEXT; diff --git a/crates/minos-backend/src/jobs/push_dispatch_worker.rs b/crates/minos-backend/src/jobs/push_dispatch_worker.rs index 60f21ce2..98712c0f 100644 --- a/crates/minos-backend/src/jobs/push_dispatch_worker.rs +++ b/crates/minos-backend/src/jobs/push_dispatch_worker.rs @@ -117,7 +117,18 @@ async fn process_row( true } Ok(crate::notifications::AccountDispatchOutcome::Transient { reason }) => { - if row.attempts >= push_dispatch_queue::MAX_ATTEMPTS { + // Presence / quiet-hours / cooldown are deferrals, not provider + // failures — do not burn attempt budget toward dead-letter. + let deferral = matches!( + reason.as_str(), + "user_online" | "quiet_hours" | "cooldown" + ); + let attempts_for_budget = if deferral { + row.attempts.saturating_sub(1) + } else { + row.attempts + }; + if !deferral && attempts_for_budget >= push_dispatch_queue::MAX_ATTEMPTS { let _ = push_dispatch_queue::mark_dead( &app.store, &row.queue_id, @@ -126,11 +137,17 @@ async fn process_row( ) .await; } else { - let next = now_ms + push_dispatch_queue::backoff_delay_ms(row.attempts); + let delay = match reason.as_str() { + "user_online" => 5_000, + "cooldown" => 5_000, + "quiet_hours" => 60_000, + _ => push_dispatch_queue::backoff_delay_ms(attempts_for_budget.max(1)), + }; + let next = now_ms + delay; let _ = push_dispatch_queue::requeue_pending( &app.store, &row.queue_id, - row.attempts, + attempts_for_budget, next, &reason, ) diff --git a/crates/minos-backend/src/notifications/channels/apns.rs b/crates/minos-backend/src/notifications/channels/apns.rs index f8e0bf84..40570f36 100644 --- a/crates/minos-backend/src/notifications/channels/apns.rs +++ b/crates/minos-backend/src/notifications/channels/apns.rs @@ -70,6 +70,7 @@ impl PushChannel for ApnsChannel { target: "minos_backend::notifications::apns", account_id = %attempt.account_id, token_hash = %attempt.token_hash, + has_provider_token = !attempt.provider_token.is_empty(), topic = %self.topic, sandbox = self.sandbox, "APNs channel NotWired: config present but production send not implemented (P5 BLOCKED on ops secrets)" diff --git a/crates/minos-backend/src/notifications/channels/fcm.rs b/crates/minos-backend/src/notifications/channels/fcm.rs index 71b0f838..141f7a26 100644 --- a/crates/minos-backend/src/notifications/channels/fcm.rs +++ b/crates/minos-backend/src/notifications/channels/fcm.rs @@ -50,6 +50,7 @@ impl PushChannel for FcmChannel { target: "minos_backend::notifications::fcm", account_id = %attempt.account_id, token_hash = %attempt.token_hash, + has_provider_token = !attempt.provider_token.is_empty(), project_id = %self.project_id, "FCM channel NotWired: config present but production send not implemented (P5 BLOCKED on ops secrets)" ); diff --git a/crates/minos-backend/src/notifications/channels/mod.rs b/crates/minos-backend/src/notifications/channels/mod.rs index d8536513..312ec7be 100644 --- a/crates/minos-backend/src/notifications/channels/mod.rs +++ b/crates/minos-backend/src/notifications/channels/mod.rs @@ -58,6 +58,8 @@ pub struct PushPayload { #[derive(Debug, Clone)] pub struct PushAttempt { pub token_hash: String, + /// Raw APNs/FCM device token. Empty when legacy rows lack provider_token. + pub provider_token: String, pub account_id: String, pub payload: PushPayload, } diff --git a/crates/minos-backend/src/notifications/use_case.rs b/crates/minos-backend/src/notifications/use_case.rs index bbf0e89c..1be5d6a1 100644 --- a/crates/minos-backend/src/notifications/use_case.rs +++ b/crates/minos-backend/src/notifications/use_case.rs @@ -413,8 +413,8 @@ impl NotificationService for DefaultNotificationService { .await?; if !allowed { - crate::telemetry::record_push_decision("skip", "cooldown"); - return Ok(AccountDispatchOutcome::Skipped { + crate::telemetry::record_push_decision("defer", "cooldown"); + return Ok(AccountDispatchOutcome::Transient { reason: "cooldown".into(), }); } @@ -437,8 +437,22 @@ impl NotificationService for DefaultNotificationService { _ => PushKind::Fcm, }; if let Some(channel) = self.channel_for(kind) { + let Some(provider_token) = token_row + .provider_token + .as_deref() + .map(str::trim) + .filter(|t| !t.is_empty()) + else { + tracing::warn!( + target: "minos_backend::notifications", + token_hash = %token_row.token_hash, + "push token row missing provider_token; skipping send" + ); + continue; + }; let attempt = PushAttempt { token_hash: token_row.token_hash.clone(), + provider_token: provider_token.to_owned(), account_id: account_id.to_owned(), payload: payload.clone(), }; @@ -519,6 +533,17 @@ impl NotificationService for DefaultNotificationService { DecisionReason::PreferenceDisabled => "preference_disabled", DecisionReason::NotNotifiable => "not_notifiable", }; + // Presence grace / quiet hours are temporary — requeue instead of + // terminal skip so delivery still happens once the window ends. + if matches!( + reason, + DecisionReason::UserOnline | DecisionReason::QuietHours + ) { + crate::telemetry::record_push_decision("defer", reason_label); + return Ok(AccountDispatchOutcome::Transient { + reason: reason_label.into(), + }); + } crate::telemetry::record_push_decision("skip", reason_label); Ok(AccountDispatchOutcome::Skipped { reason: reason_label.into(), diff --git a/crates/minos-backend/src/realtime/gateway.rs b/crates/minos-backend/src/realtime/gateway.rs index d6403e50..f9df153e 100644 --- a/crates/minos-backend/src/realtime/gateway.rs +++ b/crates/minos-backend/src/realtime/gateway.rs @@ -793,11 +793,33 @@ async fn handle_formal_frame( } ClientFrame::Ping { ts } => { // Activity / last_seen already noted on the inbound text frame. + let now_ms = chrono::Utc::now().timestamp_millis(); + if upgrade.role == DeviceRole::AgentHost { + // Mailbox leases are 2 minutes; long agent turns need renewal via + // host keepalive so AppendBotMessage is not rejected mid-turn. + if let Err(error) = crate::store::agent_dispatch_queue::renew_leases_for_host( + &state.store, + &upgrade.device_id.to_string(), + now_ms.saturating_add( + crate::store::agent_dispatch_queue::DEFAULT_LEASE_TTL_MS, + ), + now_ms, + ) + .await + { + tracing::warn!( + target: "minos_backend::realtime::gateway", + error = %error, + host_id = %upgrade.device_id, + "failed to renew mailbox leases on host ping" + ); + } + } let _ = send_server_frame( ws, &ServerFrame::Pong { ts, - server_time_ms: chrono::Utc::now().timestamp_millis(), + server_time_ms: now_ms, }, ) .await; @@ -817,7 +839,7 @@ async fn handle_formal_frame( .await; return Ok(None); } - match host_commands::ack(&state.store, &command_id, ack_at_ms).await { + match host_commands::ack(&state.store, &command_id, upgrade.device_id, ack_at_ms).await { Ok(_) => { if let Err(error) = outbox_events::ack_pending_host_command_events( &state.store, @@ -876,6 +898,7 @@ async fn handle_formal_frame( let finish_result = host_commands::finish( &state.store, &command_id, + upgrade.device_id, if succeeded { host_commands::HostCommandTerminalStatus::Succeeded } else { @@ -1125,6 +1148,14 @@ async fn handle_delivery_accepted( ); return Ok(()); } + let _ = crate::store::agent_dispatch_queue::renew_lease( + &state.store, + delivery_id, + &host_id, + now_ms.saturating_add(crate::store::agent_dispatch_queue::DEFAULT_LEASE_TTL_MS), + now_ms, + ) + .await; tracing::info!( target: "minos_backend::realtime", delivery_id, @@ -1230,6 +1261,14 @@ async fn handle_append_bot_message( ); return Ok(()); } + let _ = crate::store::agent_dispatch_queue::renew_lease( + &state.store, + delivery_id, + &host_id, + now_ms.saturating_add(crate::store::agent_dispatch_queue::DEFAULT_LEASE_TTL_MS), + now_ms, + ) + .await; let trimmed = text.trim(); if trimmed.is_empty() { return Ok(()); diff --git a/crates/minos-backend/src/store/agent_dispatch_queue.rs b/crates/minos-backend/src/store/agent_dispatch_queue.rs index d4ed6fb9..22855272 100644 --- a/crates/minos-backend/src/store/agent_dispatch_queue.rs +++ b/crates/minos-backend/src/store/agent_dispatch_queue.rs @@ -1100,6 +1100,107 @@ where } } +/// Extend an active mailbox lease when the owning host is still working the delivery. +pub async fn renew_lease( + store: &S, + delivery_id: &str, + host_installation_id: &str, + lease_expires_at_ms: i64, + now_ms: i64, +) -> Result +where + S: AsStorePool + ?Sized, +{ + match store.as_store_pool() { + StorePoolRef::Sqlite(pool) => { + let result = sqlx::query( + "UPDATE bot_message_deliveries + SET lease_expires_at_ms = ?1, + updated_at_ms = ?2 + WHERE dispatch_id = ?3 + AND status = ?4 + AND lease_owner_host_id = ?5", + ) + .bind(lease_expires_at_ms) + .bind(now_ms) + .bind(delivery_id) + .bind(STATUS_INFLIGHT) + .bind(host_installation_id) + .execute(pool) + .await + .map_err(store_err("agent_dispatch_queue::renew_lease"))?; + Ok(result.rows_affected() == 1) + } + StorePoolRef::Postgres(pool) => { + let result = sqlx::query( + "UPDATE bot_message_deliveries + SET lease_expires_at_ms = $1, + updated_at_ms = $2 + WHERE dispatch_id = $3 + AND status = $4 + AND lease_owner_host_id = $5", + ) + .bind(lease_expires_at_ms) + .bind(now_ms) + .bind(delivery_id) + .bind(STATUS_INFLIGHT) + .bind(host_installation_id) + .execute(pool) + .await + .map_err(store_err("agent_dispatch_queue::renew_lease"))?; + Ok(result.rows_affected() == 1) + } + } +} + +/// Renew every inflight lease owned by `host_installation_id` (host keepalive / Ping). +pub async fn renew_leases_for_host( + store: &S, + host_installation_id: &str, + lease_expires_at_ms: i64, + now_ms: i64, +) -> Result +where + S: AsStorePool + ?Sized, +{ + match store.as_store_pool() { + StorePoolRef::Sqlite(pool) => { + let result = sqlx::query( + "UPDATE bot_message_deliveries + SET lease_expires_at_ms = ?1, + updated_at_ms = ?2 + WHERE status = ?3 + AND lease_owner_host_id = ?4", + ) + .bind(lease_expires_at_ms) + .bind(now_ms) + .bind(STATUS_INFLIGHT) + .bind(host_installation_id) + .execute(pool) + .await + .map_err(store_err("agent_dispatch_queue::renew_leases_for_host"))?; + Ok(result.rows_affected()) + } + StorePoolRef::Postgres(pool) => { + let result = sqlx::query( + "UPDATE bot_message_deliveries + SET lease_expires_at_ms = $1, + updated_at_ms = $2 + WHERE status = $3 + AND lease_owner_host_id = $4", + ) + .bind(lease_expires_at_ms) + .bind(now_ms) + .bind(STATUS_INFLIGHT) + .bind(host_installation_id) + .execute(pool) + .await + .map_err(store_err("agent_dispatch_queue::renew_leases_for_host"))?; + Ok(result.rows_affected()) + } + } +} + /// Clear lease fields (e.g. after success, cancel, or reclaim). pub async fn clear_lease(store: &S, delivery_id: &str, now_ms: i64) -> Result<(), BackendError> where diff --git a/crates/minos-backend/src/store/host_commands.rs b/crates/minos-backend/src/store/host_commands.rs index 7e81ab60..304a4378 100644 --- a/crates/minos-backend/src/store/host_commands.rs +++ b/crates/minos-backend/src/store/host_commands.rs @@ -249,8 +249,10 @@ pub async fn get( pub async fn ack( store: &impl AsStorePool, command_id: &str, + host_installation_id: DeviceId, ack_at_ms: i64, ) -> Result { + let host = host_installation_id.to_string(); let result = match store.as_store_pool() { StorePoolRef::Sqlite(pool) => sqlx::query( "UPDATE host_commands @@ -260,11 +262,13 @@ pub async fn ack( END, ack_at_ms = ? WHERE command_id = ? + AND host_installation_id = ? AND status IN ('pending', 'acked', 'succeeded', 'failed') AND ack_at_ms IS NULL", ) .bind(ack_at_ms) .bind(command_id) + .bind(&host) .execute(pool) .await .map(|result| result.rows_affected()), @@ -276,11 +280,13 @@ pub async fn ack( END, ack_at_ms = $1 WHERE command_id = $2 + AND host_installation_id = $3 AND status IN ('pending', 'acked', 'succeeded', 'failed') AND ack_at_ms IS NULL", ) .bind(ack_at_ms) .bind(command_id) + .bind(&host) .execute(pool) .await .map(|result| result.rows_affected()), @@ -293,11 +299,13 @@ pub async fn ack( pub async fn finish( store: &impl AsStorePool, command_id: &str, + host_installation_id: DeviceId, status: HostCommandTerminalStatus, response_json: Option<&Value>, error_json: Option<&Value>, finished_at_ms: i64, ) -> Result { + let host = host_installation_id.to_string(); let response_json = response_json .map(|value| serialize_json(value, "host_commands::finish.response_json")) .transpose()?; @@ -310,6 +318,7 @@ pub async fn finish( "UPDATE host_commands SET status = ?, response_json = ?, error_json = ?, finished_at_ms = ? WHERE command_id = ? + AND host_installation_id = ? AND finished_at_ms IS NULL AND status IN ('pending', 'acked')", ) @@ -318,6 +327,7 @@ pub async fn finish( .bind(error_json.as_deref()) .bind(finished_at_ms) .bind(command_id) + .bind(&host) .execute(pool) .await .map(|result| result.rows_affected()), @@ -325,6 +335,7 @@ pub async fn finish( "UPDATE host_commands SET status = $1, response_json = $2, error_json = $3, finished_at_ms = $4 WHERE command_id = $5 + AND host_installation_id = $6 AND finished_at_ms IS NULL AND status IN ('pending', 'acked')", ) @@ -333,6 +344,7 @@ pub async fn finish( .bind(error_json.as_deref()) .bind(finished_at_ms) .bind(command_id) + .bind(&host) .execute(pool) .await .map(|result| result.rows_affected()), @@ -546,12 +558,13 @@ mod tests { serde_json::json!({ "decision": "approve" }) ); - assert!(ack(&pool, "cmd-1", T0 + 100).await.unwrap()); - assert!(!ack(&pool, "cmd-1", T0 + 200).await.unwrap()); + assert!(ack(&pool, "cmd-1", host, T0 + 100).await.unwrap()); + assert!(!ack(&pool, "cmd-1", host, T0 + 200).await.unwrap()); assert!(finish( &pool, "cmd-1", + host, HostCommandTerminalStatus::Succeeded, Some(&serde_json::json!({ "ok": true })), None, @@ -589,6 +602,7 @@ mod tests { assert!(finish( &pool, "cmd-finish-before-ack", + host, HostCommandTerminalStatus::Succeeded, Some(&serde_json::json!({ "ok": true })), None, @@ -596,7 +610,7 @@ mod tests { ) .await .unwrap()); - assert!(ack(&pool, "cmd-finish-before-ack", T0 + 100).await.unwrap()); + assert!(ack(&pool, "cmd-finish-before-ack", host, T0 + 100).await.unwrap()); let row = get(&pool, "cmd-finish-before-ack").await.unwrap().unwrap(); assert_eq!(row.status, HostCommandStatus::Succeeded); @@ -662,4 +676,50 @@ mod tests { .unwrap() .is_empty()); } + + #[tokio::test] + async fn ack_and_finish_require_owning_host() { + let pool = memory_pool().await; + let owner = seed_host(&pool).await; + let other = seed_host(&pool).await; + enqueue( + &pool, + "cmd-owned", + owner, + None, + "minos_health", + &serde_json::Value::Null, + None, + T0 + 5_000, + T0, + ) + .await + .unwrap(); + + assert!(!ack(&pool, "cmd-owned", other, T0 + 100).await.unwrap()); + assert!(ack(&pool, "cmd-owned", owner, T0 + 100).await.unwrap()); + assert!(!finish( + &pool, + "cmd-owned", + other, + HostCommandTerminalStatus::Succeeded, + Some(&serde_json::json!({ "ok": true })), + None, + T0 + 300, + ) + .await + .unwrap()); + assert!(finish( + &pool, + "cmd-owned", + owner, + HostCommandTerminalStatus::Succeeded, + Some(&serde_json::json!({ "ok": true })), + None, + T0 + 300, + ) + .await + .unwrap()); + } + } diff --git a/crates/minos-backend/src/store/outbox_events.rs b/crates/minos-backend/src/store/outbox_events.rs index fe49723c..76890829 100644 --- a/crates/minos-backend/src/store/outbox_events.rs +++ b/crates/minos-backend/src/store/outbox_events.rs @@ -1163,7 +1163,7 @@ mod tests { assert_eq!(row.status, OutboxStatus::Claimed); assert_eq!(row.ack_at_ms, None); - assert!(host_commands::ack(&pool, "cmd-1", T0 + 2).await.unwrap()); + assert!(host_commands::ack(&pool, "cmd-1", host_id, T0 + 2).await.unwrap()); assert!(ack(&pool, "out-host-command", T0 + 3).await.unwrap()); let row = get(&pool, "out-host-command").await.unwrap().unwrap(); @@ -1374,7 +1374,7 @@ mod tests { .len(), 1 ); - assert!(host_commands::ack(&pool, "cmd-obs-past-deadline", T0 + 5) + assert!(host_commands::ack(&pool, "cmd-obs-past-deadline", host_id, T0 + 5) .await .unwrap()); let cmd = host_commands::get(&pool, "cmd-obs-past-deadline") @@ -1445,7 +1445,7 @@ mod tests { .len(), 1 ); - assert!(host_commands::ack(&pool, "cmd-expire-obs", T0 + 5) + assert!(host_commands::ack(&pool, "cmd-expire-obs", host_id, T0 + 5) .await .unwrap()); @@ -1610,6 +1610,7 @@ mod tests { assert!(host_commands::finish( &pool, "cmd-host-failed", + host_id, host_commands::HostCommandTerminalStatus::Failed, None, Some(&serde_json::json!({ "status": "failed", "message": "boom" })), @@ -1740,7 +1741,7 @@ mod tests { .unwrap(), 0 ); - assert!(host_commands::ack(&pool, "cmd-pending", T0 + 2) + assert!(host_commands::ack(&pool, "cmd-pending", host_id, T0 + 2) .await .unwrap()); assert_eq!( @@ -1810,7 +1811,7 @@ mod tests { .await .unwrap(); assert_eq!(claimed.len(), 1); - assert!(host_commands::ack(&pool, "cmd-claimed", T0 + 2) + assert!(host_commands::ack(&pool, "cmd-claimed", host_id, T0 + 2) .await .unwrap()); diff --git a/crates/minos-backend/src/store/push_tokens.rs b/crates/minos-backend/src/store/push_tokens.rs index c593e507..5951f4e6 100644 --- a/crates/minos-backend/src/store/push_tokens.rs +++ b/crates/minos-backend/src/store/push_tokens.rs @@ -1,6 +1,9 @@ //! `push_tokens` table CRUD. Supports both SQLite and Postgres via -//! `AsStorePool` dispatch. Tokens are hashed (SHA-256) before storage -//! so the raw device token never persists. +//! `AsStorePool` dispatch. +//! +//! Rows keep a SHA-256 `token_hash` as the stable primary key for upsert/revoke +//! and a `provider_token` column with the raw APNs/FCM device token required +//! for delivery. Hash-only storage made push structurally undeliverable. use sha2::{Digest, Sha256}; use sqlx::{PgPool, SqlitePool}; @@ -18,6 +21,9 @@ pub struct PushTokenRow { pub created_at_ms: i64, pub last_used_at_ms: i64, pub revoked_at_ms: Option, + /// Raw provider device token used at send time. May be NULL for rows + /// registered before the provider_token migration. + pub provider_token: Option, } /// Hash a raw push token for storage. Uses SHA-256 so the same token @@ -52,6 +58,7 @@ where installation_id, kind, locale, + token, at_ms, ) .await @@ -64,6 +71,7 @@ where installation_id, kind, locale, + token, at_ms, ) .await @@ -122,14 +130,16 @@ async fn upsert_sqlite( installation_id: &str, kind: &str, locale: Option<&str>, + provider_token: &str, at_ms: i64, ) -> Result { sqlx::query_as::<_, PushTokenRow>( - "INSERT INTO push_tokens (token_hash, account_id, installation_id, kind, locale, created_at_ms, last_used_at_ms) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6) + "INSERT INTO push_tokens (token_hash, account_id, installation_id, kind, locale, created_at_ms, last_used_at_ms, provider_token) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6, ?7) ON CONFLICT(token_hash) DO UPDATE SET installation_id = excluded.installation_id, last_used_at_ms = excluded.last_used_at_ms, + provider_token = excluded.provider_token, revoked_at_ms = NULL RETURNING *", ) @@ -139,6 +149,7 @@ async fn upsert_sqlite( .bind(kind) .bind(locale) .bind(at_ms) + .bind(provider_token) .fetch_one(pool) .await .map_err(|e| BackendError::StoreQuery { @@ -218,14 +229,16 @@ async fn upsert_postgres( installation_id: &str, kind: &str, locale: Option<&str>, + provider_token: &str, at_ms: i64, ) -> Result { sqlx::query_as::<_, PushTokenRow>( - "INSERT INTO push_tokens (token_hash, account_id, installation_id, kind, locale, created_at_ms, last_used_at_ms) - VALUES ($1, $2, $3, $4, $5, $6, $6) + "INSERT INTO push_tokens (token_hash, account_id, installation_id, kind, locale, created_at_ms, last_used_at_ms, provider_token) + VALUES ($1, $2, $3, $4, $5, $6, $6, $7) ON CONFLICT(token_hash) DO UPDATE SET installation_id = EXCLUDED.installation_id, last_used_at_ms = EXCLUDED.last_used_at_ms, + provider_token = EXCLUDED.provider_token, revoked_at_ms = NULL RETURNING *", ) @@ -235,6 +248,7 @@ async fn upsert_postgres( .bind(kind) .bind(locale) .bind(at_ms) + .bind(provider_token) .fetch_one(pool) .await .map_err(|e| BackendError::StoreQuery { From 1d5696f03eac51dc8d6e891a51a5eb6228a28146 Mon Sep 17 00:00:00 2001 From: Engineer Date: Wed, 12 Aug 2026 06:48:50 +0000 Subject: [PATCH 09/12] chore: rustfmt and clippy cleanups for adversarial-review fixes Apply cargo fmt across prior P0/P1 edits and resolve clippy -D warnings (single_match / collapsible_else_if on mobile hole detection; Box::pin large BotInboxDelivery future on daemon dispatch). --- .../minos-backend/src/approvals/use_case.rs | 9 ++--- .../src/jobs/push_dispatch_worker.rs | 5 +-- crates/minos-backend/src/realtime/gateway.rs | 7 ++-- .../src/store/approval_requests.rs | 11 +++--- .../minos-backend/src/store/host_commands.rs | 5 +-- .../minos-backend/src/store/outbox_events.rs | 12 ++++--- .../src/store/social/conversation_messages.rs | 5 +-- crates/minos-backend/src/store/social/mod.rs | 8 +---- crates/minos-daemon/src/agent.rs | 5 +-- crates/minos-daemon/src/media_materialize.rs | 26 +++++++------- crates/minos-daemon/src/relay_client.rs | 12 +++++-- .../src/store/host_command_ledger.rs | 8 +---- crates/minos-daemon/src/store/mod.rs | 2 +- crates/minos-mobile/src/client.rs | 21 ++++++----- crates/minos-mobile/src/realtime/session.rs | 36 +++++++++---------- .../minos-mobile/src/realtime/subscription.rs | 4 ++- 16 files changed, 83 insertions(+), 93 deletions(-) diff --git a/crates/minos-backend/src/approvals/use_case.rs b/crates/minos-backend/src/approvals/use_case.rs index ebbdd92b..73acfcf6 100644 --- a/crates/minos-backend/src/approvals/use_case.rs +++ b/crates/minos-backend/src/approvals/use_case.rs @@ -125,12 +125,9 @@ impl DefaultApprovalService { ), } - let rows = store::approval_requests::list_expired_pending( - &self.store, - now_ms, - EXPIRED_BATCH_SIZE, - ) - .await?; + let rows = + store::approval_requests::list_expired_pending(&self.store, now_ms, EXPIRED_BATCH_SIZE) + .await?; for row in rows { self.resolve_automatically(row, ApprovalRequestState::Timeout) diff --git a/crates/minos-backend/src/jobs/push_dispatch_worker.rs b/crates/minos-backend/src/jobs/push_dispatch_worker.rs index 98712c0f..188ba496 100644 --- a/crates/minos-backend/src/jobs/push_dispatch_worker.rs +++ b/crates/minos-backend/src/jobs/push_dispatch_worker.rs @@ -119,10 +119,7 @@ async fn process_row( Ok(crate::notifications::AccountDispatchOutcome::Transient { reason }) => { // Presence / quiet-hours / cooldown are deferrals, not provider // failures — do not burn attempt budget toward dead-letter. - let deferral = matches!( - reason.as_str(), - "user_online" | "quiet_hours" | "cooldown" - ); + let deferral = matches!(reason.as_str(), "user_online" | "quiet_hours" | "cooldown"); let attempts_for_budget = if deferral { row.attempts.saturating_sub(1) } else { diff --git a/crates/minos-backend/src/realtime/gateway.rs b/crates/minos-backend/src/realtime/gateway.rs index f9df153e..b0ea96c9 100644 --- a/crates/minos-backend/src/realtime/gateway.rs +++ b/crates/minos-backend/src/realtime/gateway.rs @@ -800,9 +800,7 @@ async fn handle_formal_frame( if let Err(error) = crate::store::agent_dispatch_queue::renew_leases_for_host( &state.store, &upgrade.device_id.to_string(), - now_ms.saturating_add( - crate::store::agent_dispatch_queue::DEFAULT_LEASE_TTL_MS, - ), + now_ms.saturating_add(crate::store::agent_dispatch_queue::DEFAULT_LEASE_TTL_MS), now_ms, ) .await @@ -839,7 +837,8 @@ async fn handle_formal_frame( .await; return Ok(None); } - match host_commands::ack(&state.store, &command_id, upgrade.device_id, ack_at_ms).await { + match host_commands::ack(&state.store, &command_id, upgrade.device_id, ack_at_ms).await + { Ok(_) => { if let Err(error) = outbox_events::ack_pending_host_command_events( &state.store, diff --git a/crates/minos-backend/src/store/approval_requests.rs b/crates/minos-backend/src/store/approval_requests.rs index f9341cf1..336edf03 100644 --- a/crates/minos-backend/src/store/approval_requests.rs +++ b/crates/minos-backend/src/store/approval_requests.rs @@ -336,12 +336,11 @@ pub async fn timeout_pending_with_null_host( limit: u32, ) -> Result { let resolution = serde_json::json!({ "reason": "timeout", "orphan": "null_host" }); - let resolution_json = serde_json::to_string(&resolution).map_err(|error| { - BackendError::StoreDecode { + let resolution_json = + serde_json::to_string(&resolution).map_err(|error| BackendError::StoreDecode { column: "approval_requests.resolution_json".into(), message: error.to_string(), - } - })?; + })?; let result = match store.as_store_pool() { StorePoolRef::Sqlite(pool) => sqlx::query( "UPDATE approval_requests @@ -395,7 +394,9 @@ pub async fn timeout_pending_with_null_host( .await .map(|r| r.rows_affected()), } - .map_err(store_err("approval_requests::timeout_pending_with_null_host"))?; + .map_err(store_err( + "approval_requests::timeout_pending_with_null_host", + ))?; Ok(result) } diff --git a/crates/minos-backend/src/store/host_commands.rs b/crates/minos-backend/src/store/host_commands.rs index 304a4378..b775b73d 100644 --- a/crates/minos-backend/src/store/host_commands.rs +++ b/crates/minos-backend/src/store/host_commands.rs @@ -610,7 +610,9 @@ mod tests { ) .await .unwrap()); - assert!(ack(&pool, "cmd-finish-before-ack", host, T0 + 100).await.unwrap()); + assert!(ack(&pool, "cmd-finish-before-ack", host, T0 + 100) + .await + .unwrap()); let row = get(&pool, "cmd-finish-before-ack").await.unwrap().unwrap(); assert_eq!(row.status, HostCommandStatus::Succeeded); @@ -721,5 +723,4 @@ mod tests { .await .unwrap()); } - } diff --git a/crates/minos-backend/src/store/outbox_events.rs b/crates/minos-backend/src/store/outbox_events.rs index 76890829..92025439 100644 --- a/crates/minos-backend/src/store/outbox_events.rs +++ b/crates/minos-backend/src/store/outbox_events.rs @@ -1163,7 +1163,9 @@ mod tests { assert_eq!(row.status, OutboxStatus::Claimed); assert_eq!(row.ack_at_ms, None); - assert!(host_commands::ack(&pool, "cmd-1", host_id, T0 + 2).await.unwrap()); + assert!(host_commands::ack(&pool, "cmd-1", host_id, T0 + 2) + .await + .unwrap()); assert!(ack(&pool, "out-host-command", T0 + 3).await.unwrap()); let row = get(&pool, "out-host-command").await.unwrap().unwrap(); @@ -1374,9 +1376,11 @@ mod tests { .len(), 1 ); - assert!(host_commands::ack(&pool, "cmd-obs-past-deadline", host_id, T0 + 5) - .await - .unwrap()); + assert!( + host_commands::ack(&pool, "cmd-obs-past-deadline", host_id, T0 + 5) + .await + .unwrap() + ); let cmd = host_commands::get(&pool, "cmd-obs-past-deadline") .await .unwrap() diff --git a/crates/minos-backend/src/store/social/conversation_messages.rs b/crates/minos-backend/src/store/social/conversation_messages.rs index b45f5846..961cd9d6 100644 --- a/crates/minos-backend/src/store/social/conversation_messages.rs +++ b/crates/minos-backend/src/store/social/conversation_messages.rs @@ -707,7 +707,6 @@ async fn insert_mention_rows_postgres( Ok(()) } - /// Fail-closed validation for untrusted `client_message_id` values. /// /// Clients mint UUIDs / `msg_` / `react-…` keys; host projection uses @@ -1138,7 +1137,9 @@ mod tests { assert!(validate_client_message_id("msg_550e8400-e29b-41d4-a716-446655440000").is_ok()); assert!(validate_client_message_id("msg-disabled-sole-1").is_ok()); assert!(validate_client_message_id("react-171000-42").is_ok()); - assert!(validate_client_message_id("approval-550e8400-e29b-41d4-a716-446655440000").is_ok()); + assert!( + validate_client_message_id("approval-550e8400-e29b-41d4-a716-446655440000").is_ok() + ); } #[test] diff --git a/crates/minos-backend/src/store/social/mod.rs b/crates/minos-backend/src/store/social/mod.rs index fe264997..ae0a47ce 100644 --- a/crates/minos-backend/src/store/social/mod.rs +++ b/crates/minos-backend/src/store/social/mod.rs @@ -845,13 +845,7 @@ mod tests { let conversation = create_group_conversation(&pool, &alice, "Sec", &[], T0) .await .unwrap(); - for bad in [ - "../etc/passwd", - "/tmp/x", - "foo/bar", - "has space", - "..", - ] { + for bad in ["../etc/passwd", "/tmp/x", "foo/bar", "has space", ".."] { let err = insert_message_with_id( &pool, &conversation.conversation_id, diff --git a/crates/minos-daemon/src/agent.rs b/crates/minos-daemon/src/agent.rs index a37956d5..20a49ec5 100644 --- a/crates/minos-daemon/src/agent.rs +++ b/crates/minos-daemon/src/agent.rs @@ -5862,10 +5862,7 @@ async fn ensure_hub_collaboration_conversation( project_id } } else { - let project_id = format!( - "project-hub-{}", - short_prefix(conversation_id, 8) - ); + let project_id = format!("project-hub-{}", short_prefix(conversation_id, 8)); store .ensure_project(&project_id, "Hub", "hub", None, now_ms) .await?; diff --git a/crates/minos-daemon/src/media_materialize.rs b/crates/minos-daemon/src/media_materialize.rs index 426cb16b..ebdc2d95 100644 --- a/crates/minos-daemon/src/media_materialize.rs +++ b/crates/minos-daemon/src/media_materialize.rs @@ -210,7 +210,11 @@ fn safe_filename(att: &DispatchAttachment, idx: usize) -> String { "text/plain" => "txt", _ => "bin", }; - let blob = att.blob_id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').collect::(); + let blob = att + .blob_id + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') + .collect::(); let stem = if blob.is_empty() { "blob".to_string() } else { @@ -250,9 +254,7 @@ async fn download_one(client: &reqwest::Client, url: &str, dest: &Path) -> Resul if written > MAX_ATTACHMENT_BYTES { drop(file); let _ = tokio::fs::remove_file(dest).await; - return Err(format!( - "body exceeded cap {MAX_ATTACHMENT_BYTES} bytes" - )); + return Err(format!("body exceeded cap {MAX_ATTACHMENT_BYTES} bytes")); } file.write_all(&chunk) .await @@ -267,13 +269,10 @@ fn resolve_download_url(url: &str) -> Result { return url::Url::parse(url).map_err(|e| format!("parse url: {e}")); } // Relative paths need an absolute backend origin (host is not the API). - let base = configured_http_bases() - .into_iter() - .next() - .ok_or_else(|| { - "relative download_url requires MINOS_BACKEND_URL or MINOS_MEDIA_PUBLIC_BASE_URL on host" - .to_string() - })?; + let base = configured_http_bases().into_iter().next().ok_or_else(|| { + "relative download_url requires MINOS_BACKEND_URL or MINOS_MEDIA_PUBLIC_BASE_URL on host" + .to_string() + })?; base.join(url).map_err(|e| format!("join url: {e}")) } @@ -456,7 +455,10 @@ mod tests { hashed.is_dir(), "expected hashed origin dir under attachments, got {:?}", std::fs::read_dir(&attachments) - .map(|d| d.filter_map(|e| e.ok()).map(|e| e.path()).collect::>()) + .map(|d| d + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .collect::>()) .unwrap_or_default() ); // No sibling escape dirs created next to .minos diff --git a/crates/minos-daemon/src/relay_client.rs b/crates/minos-daemon/src/relay_client.rs index eeff5e65..67b44428 100644 --- a/crates/minos-daemon/src/relay_client.rs +++ b/crates/minos-daemon/src/relay_client.rs @@ -1126,7 +1126,7 @@ async fn route_server_frame(frame: ServerFrame, ctx: &DispatchCtx) { let self_device_id = ctx.self_device_id; tokio::spawn(async move { // Reconstruct a minimal ctx-like bundle via a dedicated helper. - handle_bot_inbox_delivery_spawned( + Box::pin(handle_bot_inbox_delivery_spawned( store, out_tx, rpc_server, @@ -1137,7 +1137,7 @@ async fn route_server_frame(frame: ServerFrame, ctx: &DispatchCtx) { bot, session, lease_expires_at_ms, - ) + )) .await; }); } @@ -1260,7 +1260,13 @@ async fn route_durable_event(kind: &str, payload: &Value, ctx: &DispatchCtx) { let ack = build_host_command_ack(&command_id, chrono::Utc::now().timestamp_millis()); let _ = ctx.out_tx.send(ack).await; - match remember_host_command_start(&ctx.host_command_cache, ctx.store.as_ref(), &command_id).await { + match remember_host_command_start( + &ctx.host_command_cache, + ctx.store.as_ref(), + &command_id, + ) + .await + { HostCommandRouteAction::Start => {} HostCommandRouteAction::InFlight => return, HostCommandRouteAction::Replay(snapshot) => { diff --git a/crates/minos-daemon/src/store/host_command_ledger.rs b/crates/minos-daemon/src/store/host_command_ledger.rs index e29aef22..23fec6ba 100644 --- a/crates/minos-daemon/src/store/host_command_ledger.rs +++ b/crates/minos-daemon/src/store/host_command_ledger.rs @@ -234,13 +234,7 @@ mod tests { HostCommandBegin::InFlight ); store - .complete_host_command( - "cmd-1", - true, - Some(r#"{"ok":true}"#), - None, - now + 2, - ) + .complete_host_command("cmd-1", true, Some(r#"{"ok":true}"#), None, now + 2) .await .unwrap(); match store.begin_host_command("cmd-1", now + 3).await.unwrap() { diff --git a/crates/minos-daemon/src/store/mod.rs b/crates/minos-daemon/src/store/mod.rs index 9953514d..50255486 100644 --- a/crates/minos-daemon/src/store/mod.rs +++ b/crates/minos-daemon/src/store/mod.rs @@ -11,8 +11,8 @@ pub mod artifacts; pub mod bot_delivery_ledger; -pub mod host_command_ledger; pub mod event_writer; +pub mod host_command_ledger; pub mod migrations_loader; use artifacts::{ArtifactRange, ArtifactStore}; diff --git a/crates/minos-mobile/src/client.rs b/crates/minos-mobile/src/client.rs index 8f603a68..f7a06408 100644 --- a/crates/minos-mobile/src/client.rs +++ b/crates/minos-mobile/src/client.rs @@ -455,17 +455,16 @@ impl MobileClient { return; } self.subscription_mgr.clear_pending_hold(topic).await; - match self.subscription_mgr.update_seq(topic, topic_seq).await { - crate::realtime::subscription::CursorAdvance::Hole { expected } => { - tracing::warn!( - topic, - topic_seq, - expected, - "ack_durable_applied saw seq hole; clearing cursor for snapshot" - ); - self.subscription_mgr.clear_cursor(topic).await; - } - _ => {} + if let crate::realtime::subscription::CursorAdvance::Hole { expected } = + self.subscription_mgr.update_seq(topic, topic_seq).await + { + tracing::warn!( + topic, + topic_seq, + expected, + "ack_durable_applied saw seq hole; clearing cursor for snapshot" + ); + self.subscription_mgr.clear_cursor(topic).await; } } diff --git a/crates/minos-mobile/src/realtime/session.rs b/crates/minos-mobile/src/realtime/session.rs index 77407342..a904e28c 100644 --- a/crates/minos-mobile/src/realtime/session.rs +++ b/crates/minos-mobile/src/realtime/session.rs @@ -276,7 +276,6 @@ fn apply_durable_event( } } - async fn surface_snapshot_required( topic: &str, last_known_seq: i64, @@ -375,25 +374,22 @@ async fn dispatch_event( topic_seq, "skip AdvanceNow while topic has pending Dart hold" ); - } else { - match subscription_mgr.update_seq(topic, *topic_seq).await { - crate::realtime::subscription::CursorAdvance::Hole { expected } => { - tracing::warn!( - topic, - topic_seq, - expected, - "durable seq hole on AdvanceNow; requesting snapshot" - ); - surface_snapshot_required( - topic, - expected - 1, - ui_events_tx, - subscription_mgr, - ) - .await; - } - _ => {} - } + } else if let crate::realtime::subscription::CursorAdvance::Hole { expected } = + subscription_mgr.update_seq(topic, *topic_seq).await + { + tracing::warn!( + topic, + topic_seq, + expected, + "durable seq hole on AdvanceNow; requesting snapshot" + ); + surface_snapshot_required( + topic, + expected - 1, + ui_events_tx, + subscription_mgr, + ) + .await; } } ApplyOutcome::AwaitDartAck => { diff --git a/crates/minos-mobile/src/realtime/subscription.rs b/crates/minos-mobile/src/realtime/subscription.rs index dbaff439..18a04c41 100644 --- a/crates/minos-mobile/src/realtime/subscription.rs +++ b/crates/minos-mobile/src/realtime/subscription.rs @@ -21,7 +21,9 @@ pub enum CursorAdvance { Advanced, Unchanged, /// `topic_seq` skipped past `cursor + 1` — caller must request snapshot. - Hole { expected: i64 }, + Hole { + expected: i64, + }, } #[derive(Debug, Default)] From 564581b2f964eed52744287b130a680831c71bb5 Mon Sep 17 00:00:00 2001 From: Engineer Date: Wed, 12 Aug 2026 08:43:19 +0000 Subject: [PATCH 10/12] chore(mobile): dart format adversarial-review notifier edits Keep CI dart format --set-exit-if-changed green after social apply-chain fixes. --- apps/mobile/lib/application/auth_provider.g.dart | 2 +- .../lib/application/social/social_conversation_notifier.dart | 5 ++++- .../application/social/social_conversation_notifier.g.dart | 2 +- .../mobile/lib/application/social/social_inbox_notifier.dart | 1 + 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/apps/mobile/lib/application/auth_provider.g.dart b/apps/mobile/lib/application/auth_provider.g.dart index f107ef1f..630069a6 100644 --- a/apps/mobile/lib/application/auth_provider.g.dart +++ b/apps/mobile/lib/application/auth_provider.g.dart @@ -125,7 +125,7 @@ final class AuthControllerProvider } } -String _$authControllerHash() => r'984259c9c2d825c7d93ad41a088ddd4a198ea0f1'; +String _$authControllerHash() => r'a212c349da0ddec6d4727983bd46947f1a4e637e'; /// Mirrors the Rust-side `AuthState` watch-channel into the Dart UI tier. /// diff --git a/apps/mobile/lib/application/social/social_conversation_notifier.dart b/apps/mobile/lib/application/social/social_conversation_notifier.dart index 376a8865..ef255555 100644 --- a/apps/mobile/lib/application/social/social_conversation_notifier.dart +++ b/apps/mobile/lib/application/social/social_conversation_notifier.dart @@ -26,6 +26,7 @@ class SocialConversation extends _$SocialConversation { StreamSubscription? _eventsSub; Timer? _markReadTimer; + /// Serialize apply+ack so concurrent frames cannot race durable cursors. Future _durableApplyChain = Future.value(); @@ -399,7 +400,9 @@ class SocialConversation extends _$SocialConversation { if (frame.kind == 'reaction_updated') { final mid = frame.message.messageId.trim(); if (mid.isEmpty) return; - _durableApplyChain = _durableApplyChain.catchError((_) {}).then((_) async { + _durableApplyChain = _durableApplyChain.catchError((_) {}).then(( + _, + ) async { await _applyRemoteReactions(mid, frame.message.reactions); await _ackDurable(frame); }); diff --git a/apps/mobile/lib/application/social/social_conversation_notifier.g.dart b/apps/mobile/lib/application/social/social_conversation_notifier.g.dart index af84ca79..6871f4b3 100644 --- a/apps/mobile/lib/application/social/social_conversation_notifier.g.dart +++ b/apps/mobile/lib/application/social/social_conversation_notifier.g.dart @@ -59,7 +59,7 @@ final class SocialConversationProvider } String _$socialConversationHash() => - r'64771e181d3a87eef524c0f81b032d1b1ea6c608'; + r'32e4fffbaa9f33065cfea6eff7bed4b020b94eeb'; final class SocialConversationFamily extends $Family with diff --git a/apps/mobile/lib/application/social/social_inbox_notifier.dart b/apps/mobile/lib/application/social/social_inbox_notifier.dart index 2bfd6c52..7b29e88b 100644 --- a/apps/mobile/lib/application/social/social_inbox_notifier.dart +++ b/apps/mobile/lib/application/social/social_inbox_notifier.dart @@ -21,6 +21,7 @@ final conversationsProvider = /// InboxSync: incremental patch; full REST only hydrate / refresh / snapshot. class ConversationsController extends AsyncNotifier { StreamSubscription? _eventsSub; + /// Serialize per-frame apply/ack so concurrent unawaited handlers cannot /// advance durable cursors out of order across topics. Future _socialApplyChain = Future.value(); From db8c16164a72de65e86cb481d4168f62dde9645f Mon Sep 17 00:00:00 2001 From: peter rich Date: Thu, 13 Aug 2026 15:44:18 +0800 Subject: [PATCH 11/12] refactor(hub): rename installations to devices and bind host_token Replace device_installations / host_installation_tokens with devices / host_tokens and rename the wire fields to device_id / host_device_id. Desktop login now issues a host_token bound to (account_id, DeviceId). The realtime registry keys by (rail, DeviceId) so Account IM and Host runtime can share one Mac without kicking each other. Native /ws/client accepts Authorization: Bearer; host WS has no ticket. --- .../lib/application/minos_providers.dart | 6 +- apps/mobile/lib/data/cloud/hosts_mapper.dart | 6 +- .../test/data/cloud/hosts_mapper_test.dart | 12 +- apps/web/src/lib/minos.ts | 6 +- .../migrations/postgres/0001_initial.sql | 51 +-- .../migrations/sqlite/0001_initial.sql | 47 +-- .../minos-backend/src/agent_sessions/dto.rs | 4 +- .../src/agent_sessions/use_case.rs | 18 +- crates/minos-backend/src/app/repositories.rs | 301 ++++++++---------- .../minos-backend/src/auth/host_bootstrap.rs | 82 +++-- .../src/auth/host_installation.rs | 37 ++- crates/minos-backend/src/auth/use_case.rs | 104 ++++-- crates/minos-backend/src/error.rs | 6 +- .../src/host_commands/use_case.rs | 22 +- crates/minos-backend/src/host_link/mod.rs | 138 ++++---- crates/minos-backend/src/http/auth.rs | 11 +- crates/minos-backend/src/http/mod.rs | 10 +- .../src/http/v1/agent_sessions.rs | 8 +- crates/minos-backend/src/http/v1/auth.rs | 4 + crates/minos-backend/src/http/v1/host.rs | 97 +++--- .../src/http/v1/host_commands.rs | 28 +- crates/minos-backend/src/http/v1/hosts.rs | 44 +-- .../src/http/v1/notifications.rs | 4 +- crates/minos-backend/src/http/v1/realtime.rs | 35 +- crates/minos-backend/src/http/v1/social.rs | 6 +- crates/minos-backend/src/ingest/mod.rs | 2 +- .../src/jobs/stale_session_sweeper.rs | 27 +- .../src/notifications/use_case.rs | 24 +- crates/minos-backend/src/realtime/auth.rs | 20 +- .../src/realtime/connection_registry.rs | 121 +++++-- crates/minos-backend/src/realtime/gateway.rs | 137 +++++++- crates/minos-backend/src/realtime/presence.rs | 8 +- .../src/store/agent_dispatch_queue.rs | 20 +- .../minos-backend/src/store/agent_sessions.rs | 44 +-- .../src/store/approval_requests.rs | 30 +- .../{device_installations.rs => devices.rs} | 216 ++++++------- .../minos-backend/src/store/host_commands.rs | 86 ++--- crates/minos-backend/src/store/host_links.rs | 122 +++---- ..._installation_tokens.rs => host_tokens.rs} | 88 ++--- crates/minos-backend/src/store/mod.rs | 66 +++- .../minos-backend/src/store/outbox_events.rs | 12 +- crates/minos-backend/src/store/push_tokens.rs | 26 +- crates/minos-backend/src/store/raw_events.rs | 4 +- .../minos-backend/src/store/refresh_tokens.rs | 17 +- crates/minos-backend/src/store/sessions.rs | 52 +-- .../minos-backend/src/store/social/agents.rs | 14 +- crates/minos-backend/tests/auth_endpoints.rs | 4 +- crates/minos-backend/tests/auth_helper.rs | 2 +- .../tests/formal_account_contract.rs | 24 +- .../tests/formal_host_contract.rs | 14 +- crates/minos-backend/tests/http_handshake.rs | 2 +- .../minos-backend/tests/pg_contract_smoke.rs | 12 +- crates/minos-backend/tests/pg_migration.rs | 2 +- crates/minos-backend/tests/store_smoke.rs | 4 +- .../minos-backend/tests/v1_agent_sessions.rs | 12 +- crates/minos-backend/tests/v1_hosts_link.rs | 52 ++- crates/minos-backend/tests/v1_pairing.rs | 2 +- crates/minos-backend/tests/v1_projects.rs | 10 +- crates/minos-backend/tests/v1_social.rs | 12 +- crates/minos-backend/tests/ws_devices.rs | 26 +- crates/minos-backend/tests/ws_gateway.rs | 6 +- crates/minos-daemon/src/local_rpc.rs | 2 +- crates/minos-daemon/src/relay_client.rs | 10 +- crates/minos-daemon/src/relay_http.rs | 12 +- crates/minos-daemon/tests/agent_e2e.rs | 3 +- crates/minos-daemon/tests/e2e.rs | 9 +- .../minos-daemon/tests/relay_client_smoke.rs | 5 +- crates/minos-domain/src/role.rs | 20 +- crates/minos-mobile/src/bin/fake-peer.rs | 12 +- crates/minos-mobile/src/client.rs | 16 +- crates/minos-mobile/src/http.rs | 21 +- crates/minos-mobile/src/realtime/session.rs | 4 +- crates/minos-protocol/src/local_rpc.rs | 2 +- crates/minos-protocol/src/messages.rs | 20 +- crates/minos-protocol/src/realtime.rs | 30 +- crates/minos-protocol/src/ws_ticket.rs | 13 +- docs/architecture-backend.md | 10 +- docs/architecture-business-flow.md | 15 +- docs/architecture-daemon.md | 2 +- docs/architecture-messaging.md | 27 +- 80 files changed, 1428 insertions(+), 1212 deletions(-) rename crates/minos-backend/src/store/{device_installations.rs => devices.rs} (80%) rename crates/minos-backend/src/store/{host_installation_tokens.rs => host_tokens.rs} (69%) diff --git a/apps/mobile/lib/application/minos_providers.dart b/apps/mobile/lib/application/minos_providers.dart index d3bab2da..73ffc3b0 100644 --- a/apps/mobile/lib/application/minos_providers.dart +++ b/apps/mobile/lib/application/minos_providers.dart @@ -38,7 +38,7 @@ final hostPresenceSyncProvider = Provider((ref) { final kind = map['principal_kind']?.toString(); // Only host device rows live in pairedMacs; account_client is for hosts. if (kind != null && kind != 'host') return; - final id = map['installation_id']?.toString().trim() ?? ''; + final id = map['device_id']?.toString().trim() ?? ''; if (id.isEmpty) return; final online = map['online'] == true; final lastSeen = map['last_seen_at_ms']; @@ -61,7 +61,7 @@ final hostPresenceSyncProvider = Provider((ref) { if (ui.kind == 'host_linked') { final map = jsonDecode(ui.payloadJson); if (map is! Map) return; - final id = map['host_installation_id']?.toString().trim() ?? ''; + final id = map['host_device_id']?.toString().trim() ?? ''; if (id.isEmpty) return; final display = map['host_display_name']?.toString().trim().isNotEmpty == true @@ -87,7 +87,7 @@ final hostPresenceSyncProvider = Provider((ref) { if (ui.kind == 'host_unlinked') { final map = jsonDecode(ui.payloadJson); if (map is! Map) return; - final id = map['host_installation_id']?.toString().trim() ?? ''; + final id = map['host_device_id']?.toString().trim() ?? ''; if (id.isEmpty) return; unawaited( ref diff --git a/apps/mobile/lib/data/cloud/hosts_mapper.dart b/apps/mobile/lib/data/cloud/hosts_mapper.dart index 0895df75..5f6384c4 100644 --- a/apps/mobile/lib/data/cloud/hosts_mapper.dart +++ b/apps/mobile/lib/data/cloud/hosts_mapper.dart @@ -8,7 +8,7 @@ import 'package:minos/domain/linked_host.dart'; /// "data": { /// "hosts": [ /// { -/// "host_installation_id": "...", +/// "host_device_id": "...", /// "host_display_name": "My Mac", /// "linked_at_ms": 123, /// "online": true @@ -42,9 +42,9 @@ LinkedHost mapHostSummaryJson(Object? json) { throw FormatException('host row expected object, got ${json.runtimeType}'); } final map = Map.from(json); - final id = map['host_installation_id']?.toString().trim() ?? ''; + final id = map['host_device_id']?.toString().trim() ?? ''; if (id.isEmpty) { - throw const FormatException('host row missing host_installation_id'); + throw const FormatException('host row missing host_device_id'); } final name = map['host_display_name']?.toString() ?? ''; final linkedRaw = map['linked_at_ms'] ?? map['paired_at_ms']; diff --git a/apps/mobile/test/data/cloud/hosts_mapper_test.dart b/apps/mobile/test/data/cloud/hosts_mapper_test.dart index 14f9623e..567d07a1 100644 --- a/apps/mobile/test/data/cloud/hosts_mapper_test.dart +++ b/apps/mobile/test/data/cloud/hosts_mapper_test.dart @@ -8,13 +8,13 @@ void main() { 'data': { 'hosts': [ { - 'host_installation_id': '11111111-1111-1111-1111-111111111111', + 'host_device_id': '11111111-1111-1111-1111-111111111111', 'host_display_name': 'MacBook Pro', 'linked_at_ms': 1700000000000, 'online': true, }, { - 'host_installation_id': '22222222-2222-2222-2222-222222222222', + 'host_device_id': '22222222-2222-2222-2222-222222222222', 'host_display_name': 'Studio', 'linked_at_ms': 1700000001000, 'online': false, @@ -39,7 +39,7 @@ void main() { test('maps last_seen_at_ms for offline device display', () { final host = mapHostSummaryJson({ - 'host_installation_id': 'cccccccc-cccc-cccc-cccc-cccccccccccc', + 'host_device_id': 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'host_display_name': 'Idle', 'linked_at_ms': 100, 'online': false, @@ -53,7 +53,7 @@ void main() { final hosts = mapHostsListResponse({ 'hosts': [ { - 'host_installation_id': 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', + 'host_device_id': 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'host_display_name': 'Bare', 'linked_at_ms': 1, 'online': true, @@ -66,7 +66,7 @@ void main() { test('accepts paired_at_ms alias for linked_at_ms', () { final host = mapHostSummaryJson({ - 'host_installation_id': 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', + 'host_device_id': 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'host_display_name': 'Legacy', 'paired_at_ms': 42, 'online': false, @@ -74,7 +74,7 @@ void main() { expect(host.linkedAtMs, 42); }); - test('throws when host_installation_id missing', () { + test('throws when host_device_id missing', () { expect( () => mapHostSummaryJson({ 'host_display_name': 'x', diff --git a/apps/web/src/lib/minos.ts b/apps/web/src/lib/minos.ts index 2701330e..8213e605 100644 --- a/apps/web/src/lib/minos.ts +++ b/apps/web/src/lib/minos.ts @@ -59,7 +59,7 @@ export interface MeHostsResponse { } interface FormalHostSummary { - host_installation_id: string + host_device_id: string host_display_name: string | null linked_at_ms: number online: boolean @@ -613,7 +613,7 @@ export async function createWsTicket( }>>('/v1/realtime/ws-ticket', { method: 'POST', headers: deviceHeaders(deviceId, accessToken), - body: JSON.stringify({ installation_id: deviceId }), + body: JSON.stringify({ device_id: deviceId }), }) return { ticket: envelope.data.ticket, @@ -646,7 +646,7 @@ export async function listHosts( }) return { hosts: envelope.data.hosts.map((host) => ({ - host_device_id: host.host_installation_id, + host_device_id: host.host_device_id, host_display_name: host.host_display_name ?? 'Mac', paired_at_ms: host.linked_at_ms, paired_via_device_id: '', diff --git a/crates/minos-backend/migrations/postgres/0001_initial.sql b/crates/minos-backend/migrations/postgres/0001_initial.sql index 82e42169..7598b656 100644 --- a/crates/minos-backend/migrations/postgres/0001_initial.sql +++ b/crates/minos-backend/migrations/postgres/0001_initial.sql @@ -15,43 +15,46 @@ CREATE TABLE accounts ( last_login_at_ms BIGINT ); -CREATE TYPE installation_kind AS ENUM ('mobile', 'browser', 'desktop', 'host'); +CREATE TYPE device_kind AS ENUM ('mobile', 'browser', 'desktop', 'host'); -CREATE TABLE device_installations ( - installation_id TEXT PRIMARY KEY, - kind installation_kind NOT NULL, +CREATE TABLE devices ( + device_id TEXT PRIMARY KEY, + kind device_kind NOT NULL, platform TEXT, public_key TEXT, account_id TEXT REFERENCES accounts(account_id) ON DELETE CASCADE, display_name TEXT, created_at_ms BIGINT NOT NULL, last_seen_at_ms BIGINT NOT NULL, - CONSTRAINT installation_kind_account_consistency CHECK ( + CONSTRAINT device_kind_account_consistency CHECK ( (kind IN ('mobile', 'browser', 'desktop') AND account_id IS NOT NULL AND public_key IS NULL) OR (kind = 'host' AND account_id IS NULL AND public_key IS NOT NULL) ) ); -CREATE INDEX idx_installations_account - ON device_installations(account_id) +CREATE INDEX idx_devices_account + ON devices(account_id) WHERE account_id IS NOT NULL; -CREATE TABLE host_installation_tokens ( +CREATE TABLE host_tokens ( token_hash TEXT PRIMARY KEY, - host_installation_id TEXT NOT NULL REFERENCES device_installations(installation_id) ON DELETE CASCADE, + host_device_id TEXT NOT NULL REFERENCES devices(device_id) ON DELETE CASCADE, + -- Bound account; required for Desktop login-issued tokens. Host WS auth + -- rejects a live token that cannot resolve to exactly one account. + account_id TEXT REFERENCES accounts(account_id) ON DELETE CASCADE, issued_at_ms BIGINT NOT NULL, last_used_at_ms BIGINT, revoked_at_ms BIGINT ); -CREATE INDEX idx_host_token_active - ON host_installation_tokens(host_installation_id) +CREATE INDEX idx_host_tokens_device + ON host_tokens(host_device_id) WHERE revoked_at_ms IS NULL; CREATE TABLE refresh_tokens ( token_hash TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE, - installation_id TEXT NOT NULL REFERENCES device_installations(installation_id) ON DELETE CASCADE, + device_id TEXT NOT NULL REFERENCES devices(device_id) ON DELETE CASCADE, issued_at_ms BIGINT NOT NULL, expires_at_ms BIGINT NOT NULL, revoked_at_ms BIGINT, @@ -59,14 +62,14 @@ CREATE TABLE refresh_tokens ( ); CREATE INDEX idx_refresh_active - ON refresh_tokens(account_id, installation_id) + ON refresh_tokens(account_id, device_id) WHERE revoked_at_ms IS NULL; CREATE TABLE host_links ( pair_id TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE, - host_installation_id TEXT NOT NULL UNIQUE REFERENCES device_installations(installation_id) ON DELETE CASCADE, - linked_via_installation_id TEXT NOT NULL REFERENCES device_installations(installation_id) ON DELETE CASCADE, + host_device_id TEXT NOT NULL UNIQUE REFERENCES devices(device_id) ON DELETE CASCADE, + linked_via_device_id TEXT NOT NULL REFERENCES devices(device_id) ON DELETE CASCADE, link_display_name TEXT, acl_json JSONB NOT NULL DEFAULT '{}'::jsonb, paired_at_ms BIGINT NOT NULL @@ -314,7 +317,7 @@ CREATE TABLE agent_sessions ( session_id TEXT PRIMARY KEY, conversation_id TEXT NOT NULL REFERENCES conversations(conversation_id) ON DELETE CASCADE, project_id TEXT REFERENCES projects(project_id) ON DELETE SET NULL, - host_installation_id TEXT REFERENCES device_installations(installation_id) ON DELETE SET NULL, + host_device_id TEXT REFERENCES devices(device_id) ON DELETE SET NULL, agent_id TEXT REFERENCES agents(agent_id) ON DELETE SET NULL, status agent_session_status NOT NULL, started_at_ms BIGINT NOT NULL, @@ -387,7 +390,7 @@ CREATE UNIQUE INDEX idx_approval_client_request_id CREATE TABLE sessions ( session_id TEXT PRIMARY KEY, agent TEXT NOT NULL CHECK (agent IN ('codex', 'claude', 'gemini', 'opencode', 'grok')), - owner_device_id TEXT NOT NULL REFERENCES device_installations(installation_id) ON DELETE CASCADE, + owner_device_id TEXT NOT NULL REFERENCES devices(device_id) ON DELETE CASCADE, title TEXT, first_ts_ms BIGINT NOT NULL, last_ts_ms BIGINT NOT NULL, @@ -444,7 +447,7 @@ CREATE TYPE host_command_status AS ENUM ('pending', 'acked', 'succeeded', 'faile CREATE TABLE host_commands ( command_id TEXT PRIMARY KEY, - host_installation_id TEXT NOT NULL REFERENCES device_installations(installation_id) ON DELETE CASCADE, + host_device_id TEXT NOT NULL REFERENCES devices(device_id) ON DELETE CASCADE, agent_session_id TEXT REFERENCES agent_sessions(session_id) ON DELETE SET NULL, method TEXT NOT NULL, params_json JSONB NOT NULL, @@ -459,7 +462,7 @@ CREATE TABLE host_commands ( ); CREATE INDEX idx_host_commands_host_status_deadline - ON host_commands(host_installation_id, status, deadline_at_ms); + ON host_commands(host_device_id, status, deadline_at_ms); CREATE TABLE durable_event_log ( event_id TEXT NOT NULL, @@ -531,7 +534,7 @@ CREATE TABLE audit_events ( audit_id TEXT PRIMARY KEY, actor_kind TEXT NOT NULL, account_id TEXT REFERENCES accounts(account_id) ON DELETE SET NULL, - installation_id TEXT REFERENCES device_installations(installation_id) ON DELETE SET NULL, + device_id TEXT REFERENCES devices(device_id) ON DELETE SET NULL, event_type TEXT NOT NULL, metadata JSONB, at_ms BIGINT NOT NULL @@ -547,7 +550,7 @@ CREATE TYPE push_kind AS ENUM ('apns', 'fcm'); CREATE TABLE push_tokens ( token_hash TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE, - installation_id TEXT NOT NULL REFERENCES device_installations(installation_id) ON DELETE CASCADE, + device_id TEXT NOT NULL REFERENCES devices(device_id) ON DELETE CASCADE, kind push_kind NOT NULL, locale TEXT, created_at_ms BIGINT NOT NULL, @@ -719,13 +722,13 @@ CREATE INDEX idx_bot_revisions_agent_created CREATE TABLE bot_deployments ( agent_id TEXT NOT NULL REFERENCES agents(agent_id) ON DELETE CASCADE, - host_installation_id TEXT NOT NULL REFERENCES device_installations(installation_id) ON DELETE CASCADE, + host_device_id TEXT NOT NULL REFERENCES devices(device_id) ON DELETE CASCADE, status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'disabled')), updated_at_ms BIGINT NOT NULL, - PRIMARY KEY (agent_id, host_installation_id) + PRIMARY KEY (agent_id, host_device_id) ); CREATE INDEX idx_bot_deployments_host - ON bot_deployments(host_installation_id, status); + ON bot_deployments(host_device_id, status); diff --git a/crates/minos-backend/migrations/sqlite/0001_initial.sql b/crates/minos-backend/migrations/sqlite/0001_initial.sql index c3438aec..28a82223 100644 --- a/crates/minos-backend/migrations/sqlite/0001_initial.sql +++ b/crates/minos-backend/migrations/sqlite/0001_initial.sql @@ -23,8 +23,8 @@ CREATE UNIQUE INDEX idx_accounts_supabase_sub -- Client/host installations. Wire DeviceRole maps: -- mobile-client→mobile, browser-admin→browser, desktop-console→desktop, agent-host→host. -CREATE TABLE device_installations ( - installation_id TEXT PRIMARY KEY, +CREATE TABLE devices ( + device_id TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK (kind IN ('mobile', 'browser', 'desktop', 'host')), platform TEXT, public_key TEXT, @@ -33,31 +33,34 @@ CREATE TABLE device_installations ( created_at_ms INTEGER NOT NULL, last_seen_at_ms INTEGER NOT NULL, -- Strict parity with Postgres: clients require account_id; hosts require public_key. - CONSTRAINT installation_kind_account_consistency CHECK ( + CONSTRAINT device_kind_account_consistency CHECK ( (kind IN ('mobile', 'browser', 'desktop') AND account_id IS NOT NULL AND public_key IS NULL) OR (kind = 'host' AND account_id IS NULL AND public_key IS NOT NULL) ) ) STRICT; -CREATE INDEX idx_installations_account - ON device_installations(account_id) +CREATE INDEX idx_devices_account + ON devices(account_id) WHERE account_id IS NOT NULL; -CREATE TABLE host_installation_tokens ( +CREATE TABLE host_tokens ( token_hash TEXT PRIMARY KEY, - host_installation_id TEXT NOT NULL REFERENCES device_installations(installation_id) ON DELETE CASCADE, + host_device_id TEXT NOT NULL REFERENCES devices(device_id) ON DELETE CASCADE, + -- Bound account; required for Desktop login-issued tokens. Host WS auth + -- rejects a live token that cannot resolve to exactly one account. + account_id TEXT REFERENCES accounts(account_id) ON DELETE CASCADE, issued_at_ms INTEGER NOT NULL, last_used_at_ms INTEGER, revoked_at_ms INTEGER ) STRICT; -CREATE INDEX idx_host_installation_tokens_host_active - ON host_installation_tokens(host_installation_id, revoked_at_ms); +CREATE INDEX idx_host_tokens_host_active + ON host_tokens(host_device_id, revoked_at_ms); CREATE TABLE refresh_tokens ( token_hash TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE, - installation_id TEXT NOT NULL REFERENCES device_installations(installation_id) ON DELETE CASCADE, + device_id TEXT NOT NULL REFERENCES devices(device_id) ON DELETE CASCADE, issued_at_ms INTEGER NOT NULL, expires_at_ms INTEGER NOT NULL, revoked_at_ms INTEGER, @@ -68,15 +71,15 @@ CREATE INDEX idx_refresh_tokens_account ON refresh_tokens(account_id) WHERE revoked_at_ms IS NULL; CREATE INDEX idx_refresh_tokens_device - ON refresh_tokens(installation_id) + ON refresh_tokens(device_id) WHERE revoked_at_ms IS NULL; CREATE TABLE host_links ( pair_id TEXT NOT NULL PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE, -- Exclusive host ownership: one account per host installation (Host Link). - host_installation_id TEXT NOT NULL UNIQUE REFERENCES device_installations(installation_id) ON DELETE CASCADE, - linked_via_installation_id TEXT NOT NULL REFERENCES device_installations(installation_id) ON DELETE CASCADE, + host_device_id TEXT NOT NULL UNIQUE REFERENCES devices(device_id) ON DELETE CASCADE, + linked_via_device_id TEXT NOT NULL REFERENCES devices(device_id) ON DELETE CASCADE, link_display_name TEXT, acl_json TEXT NOT NULL DEFAULT '{}', paired_at_ms INTEGER NOT NULL @@ -325,7 +328,7 @@ CREATE TABLE agent_sessions ( session_id TEXT PRIMARY KEY, conversation_id TEXT NOT NULL REFERENCES conversations(conversation_id) ON DELETE CASCADE, project_id TEXT REFERENCES projects(project_id) ON DELETE SET NULL, - host_installation_id TEXT REFERENCES device_installations(installation_id) ON DELETE SET NULL, + host_device_id TEXT REFERENCES devices(device_id) ON DELETE SET NULL, agent_id TEXT REFERENCES agents(agent_id) ON DELETE SET NULL, status TEXT NOT NULL CHECK (status IN ('pending', 'running', 'stopping', 'stopped', 'ended', 'failed')), started_at_ms INTEGER NOT NULL, @@ -393,7 +396,7 @@ CREATE UNIQUE INDEX idx_approval_client_request_id CREATE TABLE sessions ( session_id TEXT PRIMARY KEY, agent TEXT NOT NULL CHECK (agent IN ('codex', 'claude', 'gemini', 'opencode', 'grok')), - owner_device_id TEXT NOT NULL REFERENCES device_installations(installation_id) ON DELETE CASCADE, + owner_device_id TEXT NOT NULL REFERENCES devices(device_id) ON DELETE CASCADE, title TEXT, first_ts_ms INTEGER NOT NULL, last_ts_ms INTEGER NOT NULL, @@ -450,7 +453,7 @@ CREATE TABLE thread_sync_state ( CREATE TABLE host_commands ( command_id TEXT PRIMARY KEY, - host_installation_id TEXT NOT NULL REFERENCES device_installations(installation_id) ON DELETE CASCADE, + host_device_id TEXT NOT NULL REFERENCES devices(device_id) ON DELETE CASCADE, agent_session_id TEXT REFERENCES agent_sessions(session_id) ON DELETE SET NULL, method TEXT NOT NULL, params_json TEXT NOT NULL, @@ -465,7 +468,7 @@ CREATE TABLE host_commands ( ) STRICT; CREATE INDEX idx_host_commands_host_status_deadline - ON host_commands(host_installation_id, status, deadline_at_ms); + ON host_commands(host_device_id, status, deadline_at_ms); CREATE TABLE durable_event_log ( event_id TEXT NOT NULL, @@ -525,7 +528,7 @@ CREATE TABLE audit_events ( audit_id TEXT PRIMARY KEY, actor_kind TEXT NOT NULL, account_id TEXT REFERENCES accounts(account_id) ON DELETE SET NULL, - installation_id TEXT REFERENCES device_installations(installation_id) ON DELETE SET NULL, + device_id TEXT REFERENCES devices(device_id) ON DELETE SET NULL, event_type TEXT NOT NULL, metadata TEXT, at_ms INTEGER NOT NULL @@ -539,7 +542,7 @@ CREATE INDEX idx_audit_account_at CREATE TABLE push_tokens ( token_hash TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE, - installation_id TEXT NOT NULL REFERENCES device_installations(installation_id) ON DELETE CASCADE, + device_id TEXT NOT NULL REFERENCES devices(device_id) ON DELETE CASCADE, kind TEXT NOT NULL CHECK (kind IN ('apns', 'fcm')), locale TEXT, created_at_ms INTEGER NOT NULL, @@ -712,13 +715,13 @@ CREATE INDEX idx_bot_revisions_agent_created CREATE TABLE bot_deployments ( agent_id TEXT NOT NULL REFERENCES agents(agent_id) ON DELETE CASCADE, - host_installation_id TEXT NOT NULL REFERENCES device_installations(installation_id) ON DELETE CASCADE, + host_device_id TEXT NOT NULL REFERENCES devices(device_id) ON DELETE CASCADE, status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'disabled')), updated_at_ms INTEGER NOT NULL, - PRIMARY KEY (agent_id, host_installation_id) + PRIMARY KEY (agent_id, host_device_id) ) STRICT; CREATE INDEX idx_bot_deployments_host - ON bot_deployments(host_installation_id, status); + ON bot_deployments(host_device_id, status); diff --git a/crates/minos-backend/src/agent_sessions/dto.rs b/crates/minos-backend/src/agent_sessions/dto.rs index 975823cb..c754184a 100644 --- a/crates/minos-backend/src/agent_sessions/dto.rs +++ b/crates/minos-backend/src/agent_sessions/dto.rs @@ -14,7 +14,7 @@ pub struct StartAgentSessionInput { pub conversation_id: String, pub project_id: Option, pub agent_id: String, - pub host_installation_id: Option, + pub host_device_id: Option, pub workspace_path: Option, pub initial_user_message: Option, /// User Hub message id that triggered this turn (frozen agent-result suffix). @@ -31,7 +31,7 @@ pub struct StartAgentSessionInput { pub struct StartAgentSessionOutput { pub session_id: String, pub conversation_id: String, - pub host_installation_id: String, + pub host_device_id: String, pub started_at_ms: i64, pub initial_turn_id: Option, pub host_command_id: String, diff --git a/crates/minos-backend/src/agent_sessions/use_case.rs b/crates/minos-backend/src/agent_sessions/use_case.rs index e62fdda2..84ca8b8b 100644 --- a/crates/minos-backend/src/agent_sessions/use_case.rs +++ b/crates/minos-backend/src/agent_sessions/use_case.rs @@ -353,7 +353,7 @@ impl AgentSessionService for DefaultAgentSessionService { return Ok(StartAgentSessionOutput { session_id: existing.session_id, conversation_id: existing.conversation_id, - host_installation_id: existing + host_device_id: existing .host_device_id .ok_or(AgentSessionError::HostUnavailable)?, started_at_ms: existing.started_at_ms, @@ -362,7 +362,7 @@ impl AgentSessionService for DefaultAgentSessionService { }); } - let host_device_id = match input.host_installation_id.as_deref() { + let host_device_id = match input.host_device_id.as_deref() { Some(host_id) => { let host_device_id = Self::parse_host_device_id(host_id)?; if !self @@ -427,7 +427,7 @@ impl AgentSessionService for DefaultAgentSessionService { session_id: session_id.clone(), conversation_id: input.conversation_id.clone(), project_id: input.project_id.clone(), - host_installation_id: host_device_id.to_string(), + host_device_id: host_device_id.to_string(), agent_id: resolved_agent_id.clone(), at_ms: started_at_ms, }; @@ -453,7 +453,7 @@ impl AgentSessionService for DefaultAgentSessionService { &mut tx, NewHostCommand { command_id: host_command_id.clone(), - host_installation_id: host_device_id, + host_device_id, agent_session_id: Some(session_id.clone()), method: START_COMMAND_METHOD.into(), params_json: serde_json::json!({ @@ -487,7 +487,7 @@ impl AgentSessionService for DefaultAgentSessionService { Ok(StartAgentSessionOutput { session_id, conversation_id: input.conversation_id, - host_installation_id: host_device_id.to_string(), + host_device_id: host_device_id.to_string(), started_at_ms, initial_turn_id, host_command_id, @@ -590,7 +590,7 @@ impl AgentSessionService for DefaultAgentSessionService { &mut tx, NewHostCommand { command_id: host_command_id, - host_installation_id: host_device_id, + host_device_id, agent_session_id: Some(session.session_id.clone()), method: SEND_INPUT_COMMAND_METHOD.into(), params_json: serde_json::json!({ @@ -698,7 +698,7 @@ impl AgentSessionService for DefaultAgentSessionService { &mut tx, NewHostCommand { command_id: format!("cmd-agent-session-stop-{}", session.session_id), - host_installation_id: host_device_id, + host_device_id, agent_session_id: Some(session.session_id.clone()), method: STOP_COMMAND_METHOD.into(), params_json: serde_json::json!({ @@ -908,7 +908,7 @@ async fn insert_agent_session_in_tx( DbTx::Sqlite(tx) => { sqlx::query( "INSERT INTO agent_sessions - (session_id, conversation_id, project_id, host_installation_id, agent_id, status, started_at_ms, ended_at_ms, idempotency_account_id, idempotency_key) + (session_id, conversation_id, project_id, host_device_id, agent_id, status, started_at_ms, ended_at_ms, idempotency_account_id, idempotency_key) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ) .bind(session_id) @@ -928,7 +928,7 @@ async fn insert_agent_session_in_tx( DbTx::Postgres(tx) => { sqlx::query( "INSERT INTO agent_sessions - (session_id, conversation_id, project_id, host_installation_id, agent_id, status, started_at_ms, ended_at_ms, idempotency_account_id, idempotency_key) + (session_id, conversation_id, project_id, host_device_id, agent_id, status, started_at_ms, ended_at_ms, idempotency_account_id, idempotency_key) VALUES ($1, $2, $3, $4, $5, $6::agent_session_status, $7, $8, $9, $10)", ) .bind(session_id) diff --git a/crates/minos-backend/src/app/repositories.rs b/crates/minos-backend/src/app/repositories.rs index cd666f0d..5a94a60c 100644 --- a/crates/minos-backend/src/app/repositories.rs +++ b/crates/minos-backend/src/app/repositories.rs @@ -39,7 +39,7 @@ pub struct AccountRow { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct InstallationRow { - pub installation_id: String, + pub device_id: String, pub kind: String, pub platform: Option, pub public_key: Option, @@ -53,7 +53,7 @@ pub struct InstallationRow { pub struct RefreshTokenRow { pub token_hash: String, pub account_id: String, - pub installation_id: String, + pub device_id: String, pub issued_at_ms: i64, pub expires_at_ms: i64, pub revoked_at_ms: Option, @@ -63,7 +63,7 @@ pub struct RefreshTokenRow { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HostTokenRow { pub token_hash: String, - pub host_installation_id: String, + pub host_device_id: String, pub issued_at_ms: i64, pub last_used_at_ms: Option, pub revoked_at_ms: Option, @@ -73,8 +73,8 @@ pub struct HostTokenRow { pub struct HostLinkRow { pub pair_id: String, pub account_id: String, - pub host_installation_id: String, - pub linked_via_installation_id: String, + pub host_device_id: String, + pub linked_via_device_id: String, pub link_display_name: Option, pub acl_json: String, pub paired_at_ms: i64, @@ -166,7 +166,7 @@ pub struct AuditRow { pub audit_id: String, pub actor_kind: String, pub account_id: Option, - pub installation_id: Option, + pub device_id: Option, pub event_type: String, pub metadata: Option, pub at_ms: i64, @@ -176,7 +176,7 @@ pub struct AuditRow { pub struct PushTokenRow { pub token_hash: String, pub account_id: String, - pub installation_id: String, + pub device_id: String, pub kind: String, pub locale: Option, pub created_at_ms: i64, @@ -295,7 +295,7 @@ pub trait AccountsRepository: Send + Sync { pub trait InstallationsRepository: Send + Sync { async fn upsert( &self, - installation_id: &str, + device_id: &str, kind: &str, platform: Option<&str>, public_key: Option<&str>, @@ -304,9 +304,9 @@ pub trait InstallationsRepository: Send + Sync { at_ms: i64, ) -> Result; - async fn find(&self, installation_id: &str) -> Result, BackendError>; + async fn find(&self, device_id: &str) -> Result, BackendError>; - async fn touch_last_seen(&self, installation_id: &str, at_ms: i64) -> Result<(), BackendError>; + async fn touch_last_seen(&self, device_id: &str, at_ms: i64) -> Result<(), BackendError>; } #[async_trait] @@ -315,7 +315,7 @@ pub trait RefreshTokensRepository: Send + Sync { &self, plaintext: &str, account_id: &str, - installation_id: &str, + device_id: &str, ttl_ms: i64, at_ms: i64, ) -> Result; @@ -339,7 +339,7 @@ pub trait RefreshTokensRepository: Send + Sync { #[async_trait] pub trait HostInstallationTokensRepository: Send + Sync { - async fn insert(&self, host_installation_id: &str, at_ms: i64) -> Result; + async fn insert(&self, host_device_id: &str, at_ms: i64) -> Result; async fn find_active(&self, token_hash: &str) -> Result, BackendError>; @@ -351,33 +351,22 @@ pub trait HostLinksRepository: Send + Sync { async fn insert( &self, account_id: &str, - host_installation_id: &str, + host_device_id: &str, linked_via: &str, display_name: Option<&str>, acl_json: &str, at_ms: i64, ) -> Result; - async fn exists( - &self, - account_id: &str, - host_installation_id: &str, - ) -> Result; + async fn exists(&self, account_id: &str, host_device_id: &str) -> Result; async fn list_for_account(&self, account_id: &str) -> Result, BackendError>; - async fn list_for_host( - &self, - host_installation_id: &str, - ) -> Result, BackendError>; + async fn list_for_host(&self, host_device_id: &str) -> Result, BackendError>; async fn pick_default_host(&self, account_id: &str) -> Result, BackendError>; - async fn remove( - &self, - account_id: &str, - host_installation_id: &str, - ) -> Result; + async fn remove(&self, account_id: &str, host_device_id: &str) -> Result; } #[async_trait] @@ -547,7 +536,7 @@ pub trait AuditRepository: Send + Sync { &self, actor_kind: &str, account_id: Option<&str>, - installation_id: Option<&str>, + device_id: Option<&str>, event_type: &str, metadata: Option<&str>, at_ms: i64, @@ -566,7 +555,7 @@ pub trait PushTokensRepository: Send + Sync { async fn upsert( &self, account_id: &str, - installation_id: &str, + device_id: &str, kind: &str, token: &str, locale: Option<&str>, @@ -594,7 +583,7 @@ pub struct RepositorySet { pub accounts: Arc, pub installations: Arc, pub refresh_tokens: Arc, - pub host_installation_tokens: Arc, + pub host_tokens: Arc, pub host_links: Arc, pub agents: Arc, pub projects: Arc, @@ -634,7 +623,7 @@ impl RepositorySet { refresh_tokens: Arc::new(StoreBackedRefreshTokensRepository { store: store.clone(), }), - host_installation_tokens: Arc::new(StoreBackedHostInstallationTokensRepository { + host_tokens: Arc::new(StoreBackedHostInstallationTokensRepository { store: store.clone(), }), host_links: Arc::new(StoreBackedHostLinksRepository { @@ -872,11 +861,11 @@ impl AccountsRepository for StoreBackedAccountsRepository { // Store-backed implementations — InstallationsRepository // --------------------------------------------------------------------------- -fn convert_installation_row(row: store::device_installations::DeviceRow) -> InstallationRow { +fn convert_installation_row(row: store::devices::DeviceRow) -> InstallationRow { InstallationRow { - installation_id: row.device_id.to_string(), + device_id: row.device_id.to_string(), // Storage vocabulary (mobile/browser/desktop/host), not wire role. - kind: row.role.to_installation_kind().to_string(), + kind: row.role.to_device_kind().to_string(), platform: None, public_key: row.public_key, account_id: row.account_id, @@ -894,7 +883,7 @@ struct StoreBackedInstallationsRepository { impl InstallationsRepository for StoreBackedInstallationsRepository { async fn upsert( &self, - installation_id: &str, + device_id: &str, kind: &str, _platform: Option<&str>, public_key: Option<&str>, @@ -902,14 +891,15 @@ impl InstallationsRepository for StoreBackedInstallationsRepository { display_name: Option<&str>, at_ms: i64, ) -> Result { - let device_id = Uuid::parse_str(installation_id) - .map(DeviceId) - .map_err(|e| BackendError::StoreDecode { - column: "installation_id".into(), - message: e.to_string(), - })?; - // Accept either installation_kind (`mobile`) or wire role (`mobile-client`). - let role = minos_domain::DeviceRole::from_installation_kind(kind) + let device_id = + Uuid::parse_str(device_id) + .map(DeviceId) + .map_err(|e| BackendError::StoreDecode { + column: "device_id".into(), + message: e.to_string(), + })?; + // Accept either device_kind (`mobile`) or wire role (`mobile-client`). + let role = minos_domain::DeviceRole::from_device_kind(kind) .or_else(|_| kind.parse::()) .map_err(|e| BackendError::StoreQuery { operation: "installations.upsert".into(), @@ -917,7 +907,7 @@ impl InstallationsRepository for StoreBackedInstallationsRepository { })?; let name = display_name.unwrap_or("device"); - if store::device_installations::get_device(&self.store, device_id) + if store::devices::get_device(&self.store, device_id) .await? .is_none() { @@ -927,7 +917,7 @@ impl InstallationsRepository for StoreBackedInstallationsRepository { operation: "installations.upsert".into(), message: "account_id required for client installation kinds".into(), })?; - store::device_installations::insert_client_for_account( + store::devices::insert_client_for_account( &self.store, device_id, name, @@ -941,7 +931,7 @@ impl InstallationsRepository for StoreBackedInstallationsRepository { operation: "installations.upsert".into(), message: "public_key required for host installations".into(), })?; - store::device_installations::insert_host_with_public_key( + store::devices::insert_host_with_public_key( &self.store, device_id, name, @@ -957,27 +947,19 @@ impl InstallationsRepository for StoreBackedInstallationsRepository { } } else { if let Some(pk) = public_key { - let _ = store::device_installations::set_public_key_if_absent( - &self.store, - &device_id, - pk, - ) - .await; + let _ = store::devices::set_public_key_if_absent(&self.store, &device_id, pk).await; } if let Some(aid) = account_id { if role.is_account_client() { - let _ = - store::device_installations::set_account_id(&self.store, &device_id, aid) - .await; + let _ = store::devices::set_account_id(&self.store, &device_id, aid).await; } } if let Some(dn) = display_name { - let _ = store::device_installations::set_display_name(&self.store, &device_id, dn) - .await; + let _ = store::devices::set_display_name(&self.store, &device_id, dn).await; } } - match store::device_installations::get_device(&self.store, device_id).await? { + match store::devices::get_device(&self.store, device_id).await? { Some(row) => Ok(convert_installation_row(row)), None => Err(BackendError::StoreQuery { operation: "installations.upsert".into(), @@ -986,47 +968,42 @@ impl InstallationsRepository for StoreBackedInstallationsRepository { } } - async fn find(&self, installation_id: &str) -> Result, BackendError> { - let device_id = Uuid::parse_str(installation_id) - .map(DeviceId) - .map_err(|e| BackendError::StoreDecode { - column: "installation_id".into(), - message: e.to_string(), - })?; - Ok( - store::device_installations::get_device(&self.store, device_id) - .await? - .map(convert_installation_row), - ) + async fn find(&self, device_id: &str) -> Result, BackendError> { + let device_id = + Uuid::parse_str(device_id) + .map(DeviceId) + .map_err(|e| BackendError::StoreDecode { + column: "device_id".into(), + message: e.to_string(), + })?; + Ok(store::devices::get_device(&self.store, device_id) + .await? + .map(convert_installation_row)) } - async fn touch_last_seen(&self, installation_id: &str, at_ms: i64) -> Result<(), BackendError> { + async fn touch_last_seen(&self, device_id: &str, at_ms: i64) -> Result<(), BackendError> { match self.store.as_store_pool() { StorePoolRef::Sqlite(pool) => { - sqlx::query( - "UPDATE device_installations SET last_seen_at_ms = ? WHERE installation_id = ?", - ) - .bind(at_ms) - .bind(installation_id) - .execute(pool) - .await - .map_err(|e| BackendError::StoreQuery { - operation: "installations.touch_last_seen".into(), - message: e.to_string(), - })?; + sqlx::query("UPDATE devices SET last_seen_at_ms = ? WHERE device_id = ?") + .bind(at_ms) + .bind(device_id) + .execute(pool) + .await + .map_err(|e| BackendError::StoreQuery { + operation: "installations.touch_last_seen".into(), + message: e.to_string(), + })?; } StorePoolRef::Postgres(pool) => { - sqlx::query( - "UPDATE device_installations SET last_seen_at_ms = $1 WHERE installation_id = $2", - ) - .bind(at_ms) - .bind(installation_id) - .execute(pool) - .await - .map_err(|e| BackendError::StoreQuery { - operation: "installations.touch_last_seen".into(), - message: e.to_string(), - })?; + sqlx::query("UPDATE devices SET last_seen_at_ms = $1 WHERE device_id = $2") + .bind(at_ms) + .bind(device_id) + .execute(pool) + .await + .map_err(|e| BackendError::StoreQuery { + operation: "installations.touch_last_seen".into(), + message: e.to_string(), + })?; } } Ok(()) @@ -1041,7 +1018,7 @@ fn convert_refresh_token_row(row: store::refresh_tokens::RefreshTokenRow) -> Ref RefreshTokenRow { token_hash: row.token_hash, account_id: row.account_id, - installation_id: row.device_id, + device_id: row.device_id, issued_at_ms: row.issued_at, expires_at_ms: row.expires_at, revoked_at_ms: row.revoked_at, @@ -1059,13 +1036,12 @@ impl RefreshTokensRepository for StoreBackedRefreshTokensRepository { &self, plaintext: &str, account_id: &str, - installation_id: &str, + device_id: &str, _ttl_ms: i64, _at_ms: i64, ) -> Result { let row = - store::refresh_tokens::insert(&self.store, plaintext, account_id, installation_id) - .await?; + store::refresh_tokens::insert(&self.store, plaintext, account_id, device_id).await?; Ok(convert_refresh_token_row(row)) } @@ -1119,12 +1095,10 @@ impl RefreshTokensRepository for StoreBackedRefreshTokensRepository { // Store-backed implementations — HostInstallationTokensRepository // --------------------------------------------------------------------------- -fn convert_host_token_row( - row: store::host_installation_tokens::HostInstallationTokenRow, -) -> HostTokenRow { +fn convert_host_token_row(row: store::host_tokens::HostInstallationTokenRow) -> HostTokenRow { HostTokenRow { token_hash: row.token_hash, - host_installation_id: row.host_installation_id.to_string(), + host_device_id: row.host_device_id.to_string(), issued_at_ms: row.issued_at_ms, last_used_at_ms: row.last_used_at_ms, revoked_at_ms: row.revoked_at_ms, @@ -1137,13 +1111,13 @@ struct StoreBackedHostInstallationTokensRepository { #[async_trait] impl HostInstallationTokensRepository for StoreBackedHostInstallationTokensRepository { - async fn insert(&self, host_installation_id: &str, at_ms: i64) -> Result { - let device_id = Uuid::parse_str(host_installation_id) - .map(DeviceId) - .map_err(|e| BackendError::StoreDecode { - column: "host_installation_id".into(), + async fn insert(&self, host_device_id: &str, at_ms: i64) -> Result { + let device_id = Uuid::parse_str(host_device_id).map(DeviceId).map_err(|e| { + BackendError::StoreDecode { + column: "host_device_id".into(), message: e.to_string(), - })?; + } + })?; // Generate a random 32-byte token and hash it. let mut bytes = [0u8; 32]; getrandom::fill(&mut bytes).expect("OS CSPRNG must be available"); @@ -1153,19 +1127,21 @@ impl HostInstallationTokensRepository for StoreBackedHostInstallationTokensRepos match self.store.as_store_pool() { StorePoolRef::Sqlite(pool) => { - store::host_installation_tokens::insert_token_with_executor( + store::host_tokens::insert_token_with_executor( pool, &token_hash_hex, device_id, + None, at_ms, ) .await?; } StorePoolRef::Postgres(pool) => { - store::host_installation_tokens::insert_token_with_postgres_executor( + store::host_tokens::insert_token_with_postgres_executor( pool, &token_hash_hex, device_id, + None, at_ms, ) .await?; @@ -1179,7 +1155,7 @@ impl HostInstallationTokensRepository for StoreBackedHostInstallationTokensRepos // which is acceptable for the host authentication flow. let now_ms = chrono::Utc::now().timestamp_millis(); Ok( - store::host_installation_tokens::verify_active_token(&self.store, token_hash, now_ms) + store::host_tokens::verify_active_token(&self.store, token_hash, now_ms) .await? .map(convert_host_token_row), ) @@ -1188,7 +1164,7 @@ impl HostInstallationTokensRepository for StoreBackedHostInstallationTokensRepos async fn revoke(&self, token_hash: &str, at_ms: i64) -> Result { let affected = match self.store.as_store_pool() { StorePoolRef::Sqlite(pool) => sqlx::query( - "UPDATE host_installation_tokens SET revoked_at_ms = ? \ + "UPDATE host_tokens SET revoked_at_ms = ? \ WHERE token_hash = ? AND revoked_at_ms IS NULL", ) .bind(at_ms) @@ -1197,7 +1173,7 @@ impl HostInstallationTokensRepository for StoreBackedHostInstallationTokensRepos .await .map(|r| r.rows_affected()), StorePoolRef::Postgres(pool) => sqlx::query( - "UPDATE host_installation_tokens SET revoked_at_ms = $1 \ + "UPDATE host_tokens SET revoked_at_ms = $1 \ WHERE token_hash = $2 AND revoked_at_ms IS NULL", ) .bind(at_ms) @@ -1208,7 +1184,7 @@ impl HostInstallationTokensRepository for StoreBackedHostInstallationTokensRepos }; affected .map_err(|e| BackendError::StoreQuery { - operation: "host_installation_tokens.revoke".into(), + operation: "host_tokens.revoke".into(), message: e.to_string(), }) .map(|n| n == 1) @@ -1223,8 +1199,8 @@ fn convert_pair_row_to_host_link(row: store::host_links::PairRow, acl_json: &str HostLinkRow { pair_id: row.pair_id, account_id: row.mobile_account_id, - host_installation_id: row.host_device_id.to_string(), - linked_via_installation_id: row.paired_via_device_id.to_string(), + host_device_id: row.host_device_id.to_string(), + linked_via_device_id: row.paired_via_device_id.to_string(), link_display_name: None, acl_json: acl_json.to_string(), paired_at_ms: row.paired_at_ms, @@ -1240,18 +1216,18 @@ impl HostLinksRepository for StoreBackedHostLinksRepository { async fn insert( &self, account_id: &str, - host_installation_id: &str, + host_device_id: &str, linked_via: &str, _display_name: Option<&str>, acl_json: &str, at_ms: i64, ) -> Result { - let host_id = Uuid::parse_str(host_installation_id) - .map(DeviceId) - .map_err(|e| BackendError::StoreDecode { - column: "host_installation_id".into(), + let host_id = Uuid::parse_str(host_device_id).map(DeviceId).map_err(|e| { + BackendError::StoreDecode { + column: "host_device_id".into(), message: e.to_string(), - })?; + } + })?; let via_id = Uuid::parse_str(linked_via) .map(DeviceId) @@ -1263,25 +1239,21 @@ impl HostLinksRepository for StoreBackedHostLinksRepository { Ok(HostLinkRow { pair_id: Uuid::new_v4().to_string(), account_id: account_id.to_string(), - host_installation_id: host_installation_id.to_string(), - linked_via_installation_id: linked_via.to_string(), + host_device_id: host_device_id.to_string(), + linked_via_device_id: linked_via.to_string(), link_display_name: None, acl_json: acl_json.to_string(), paired_at_ms: at_ms, }) } - async fn exists( - &self, - account_id: &str, - host_installation_id: &str, - ) -> Result { - let host_id = Uuid::parse_str(host_installation_id) - .map(DeviceId) - .map_err(|e| BackendError::StoreDecode { - column: "host_installation_id".into(), + async fn exists(&self, account_id: &str, host_device_id: &str) -> Result { + let host_id = Uuid::parse_str(host_device_id).map(DeviceId).map_err(|e| { + BackendError::StoreDecode { + column: "host_device_id".into(), message: e.to_string(), - })?; + } + })?; store::host_links::exists(&self.store, host_id, account_id).await } @@ -1293,16 +1265,13 @@ impl HostLinksRepository for StoreBackedHostLinksRepository { .collect()) } - async fn list_for_host( - &self, - host_installation_id: &str, - ) -> Result, BackendError> { - let host_id = Uuid::parse_str(host_installation_id) - .map(DeviceId) - .map_err(|e| BackendError::StoreDecode { - column: "host_installation_id".into(), + async fn list_for_host(&self, host_device_id: &str) -> Result, BackendError> { + let host_id = Uuid::parse_str(host_device_id).map(DeviceId).map_err(|e| { + BackendError::StoreDecode { + column: "host_device_id".into(), message: e.to_string(), - })?; + } + })?; let rows = store::host_links::list_accounts_for_host(&self.store, host_id).await?; Ok(rows .into_iter() @@ -1315,17 +1284,13 @@ impl HostLinksRepository for StoreBackedHostLinksRepository { Ok(rows.first().map(|r| r.host_device_id.to_string())) } - async fn remove( - &self, - account_id: &str, - host_installation_id: &str, - ) -> Result { - let host_id = Uuid::parse_str(host_installation_id) - .map(DeviceId) - .map_err(|e| BackendError::StoreDecode { - column: "host_installation_id".into(), + async fn remove(&self, account_id: &str, host_device_id: &str) -> Result { + let host_id = Uuid::parse_str(host_device_id).map(DeviceId).map_err(|e| { + BackendError::StoreDecode { + column: "host_device_id".into(), message: e.to_string(), - })?; + } + })?; let deleted = store::host_links::delete_pair(&self.store, host_id, account_id).await?; Ok(deleted == 1) } @@ -2214,7 +2179,7 @@ impl AuditRepository for StoreBackedAuditRepository { &self, actor_kind: &str, account_id: Option<&str>, - installation_id: Option<&str>, + device_id: Option<&str>, event_type: &str, metadata: Option<&str>, at_ms: i64, @@ -2224,13 +2189,13 @@ impl AuditRepository for StoreBackedAuditRepository { StorePoolRef::Sqlite(pool) => { sqlx::query( "INSERT INTO audit_events \ - (audit_id, actor_kind, account_id, installation_id, event_type, metadata, at_ms) \ + (audit_id, actor_kind, account_id, device_id, event_type, metadata, at_ms) \ VALUES (?, ?, ?, ?, ?, ?, ?)", ) .bind(&audit_id) .bind(actor_kind) .bind(account_id) - .bind(installation_id) + .bind(device_id) .bind(event_type) .bind(metadata) .bind(at_ms) @@ -2244,13 +2209,13 @@ impl AuditRepository for StoreBackedAuditRepository { StorePoolRef::Postgres(pool) => { sqlx::query( "INSERT INTO audit_events \ - (audit_id, actor_kind, account_id, installation_id, event_type, metadata, at_ms) \ + (audit_id, actor_kind, account_id, device_id, event_type, metadata, at_ms) \ VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7)", ) .bind(&audit_id) .bind(actor_kind) .bind(account_id) - .bind(installation_id) + .bind(device_id) .bind(event_type) .bind(metadata) .bind(at_ms) @@ -2266,7 +2231,7 @@ impl AuditRepository for StoreBackedAuditRepository { audit_id, actor_kind: actor_kind.to_string(), account_id: account_id.map(str::to_string), - installation_id: installation_id.map(str::to_string), + device_id: device_id.map(str::to_string), event_type: event_type.to_string(), metadata: metadata.map(str::to_string), at_ms, @@ -2293,7 +2258,7 @@ impl AuditRepository for StoreBackedAuditRepository { i64, ), >( - "SELECT audit_id, actor_kind, account_id, installation_id, \ + "SELECT audit_id, actor_kind, account_id, device_id, \ event_type, metadata, at_ms \ FROM audit_events \ WHERE account_id = ? AND at_ms >= ? \ @@ -2315,7 +2280,7 @@ impl AuditRepository for StoreBackedAuditRepository { audit_id, actor_kind, account_id, - installation_id, + device_id, event_type, metadata, at_ms, @@ -2323,7 +2288,7 @@ impl AuditRepository for StoreBackedAuditRepository { audit_id, actor_kind, account_id, - installation_id, + device_id, event_type, metadata, at_ms, @@ -2344,7 +2309,7 @@ impl AuditRepository for StoreBackedAuditRepository { i64, ), >( - "SELECT audit_id, actor_kind, account_id, installation_id, \ + "SELECT audit_id, actor_kind, account_id, device_id, \ event_type, metadata::text, at_ms \ FROM audit_events \ WHERE account_id = $1 AND at_ms >= $2 \ @@ -2367,7 +2332,7 @@ impl AuditRepository for StoreBackedAuditRepository { audit_id, actor_kind, account_id: acc_id, - installation_id: inst_id, + device_id: inst_id, event_type, metadata, at_ms, @@ -2393,7 +2358,7 @@ impl PushTokensRepository for StoreBackedPushTokensRepository { async fn upsert( &self, account_id: &str, - installation_id: &str, + device_id: &str, kind: &str, token: &str, locale: Option<&str>, @@ -2402,7 +2367,7 @@ impl PushTokensRepository for StoreBackedPushTokensRepository { let row = store::push_tokens::upsert( &self.store, account_id, - installation_id, + device_id, kind, token, locale, @@ -2412,7 +2377,7 @@ impl PushTokensRepository for StoreBackedPushTokensRepository { Ok(PushTokenRow { token_hash: row.token_hash, account_id: row.account_id, - installation_id: row.installation_id, + device_id: row.device_id, kind: row.kind, locale: row.locale, created_at_ms: row.created_at_ms, @@ -2432,7 +2397,7 @@ impl PushTokensRepository for StoreBackedPushTokensRepository { .map(|r| PushTokenRow { token_hash: r.token_hash, account_id: r.account_id, - installation_id: r.installation_id, + device_id: r.device_id, kind: r.kind, locale: r.locale, created_at_ms: r.created_at_ms, @@ -2451,7 +2416,7 @@ impl PushTokensRepository for StubPushTokensRepository { async fn upsert( &self, _account_id: &str, - _installation_id: &str, + _device_id: &str, _kind: &str, _token: &str, _locale: Option<&str>, diff --git a/crates/minos-backend/src/auth/host_bootstrap.rs b/crates/minos-backend/src/auth/host_bootstrap.rs index 52873589..0fc7d9d7 100644 --- a/crates/minos-backend/src/auth/host_bootstrap.rs +++ b/crates/minos-backend/src/auth/host_bootstrap.rs @@ -8,7 +8,7 @@ use minos_domain::{DeviceId, DeviceRole}; use uuid::Uuid; use crate::error::BackendError; -use crate::store::{device_installations, AsStorePool}; +use crate::store::{devices, AsStorePool}; pub const BOOTSTRAP_NONCE_TTL: Duration = Duration::from_secs(60); const PUBLIC_KEY_PREFIX: &str = "ed25519:"; @@ -22,7 +22,7 @@ pub struct BootstrapNonce { #[derive(Debug, Clone)] struct NonceEntry { - installation_id: String, + device_id: String, expires_at_ms: i64, } @@ -68,7 +68,7 @@ impl BootstrapNonceStore { pub async fn issue( &self, - installation_id: &str, + device_id: &str, now_ms: i64, ) -> Result { let nonce = generate_nonce(); @@ -78,7 +78,7 @@ impl BootstrapNonceStore { entries.insert( nonce.clone(), NonceEntry { - installation_id: installation_id.to_string(), + device_id: device_id.to_string(), expires_at_ms, }, ); @@ -95,7 +95,7 @@ impl BootstrapNonceStore { let ttl_secs = BOOTSTRAP_NONCE_TTL.as_secs().max(1); let _: () = redis::cmd("SET") .arg(nonce_key(&nonce)) - .arg(installation_id) + .arg(device_id) .arg("EX") .arg(ttl_secs) .query_async(&mut conn) @@ -114,11 +114,11 @@ impl BootstrapNonceStore { pub async fn consume( &self, - installation_id: &str, + device_id: &str, nonce: &str, now_ms: i64, ) -> Result<(), HostBootstrapError> { - let entry_installation_id = match &self.backend { + let entry_device_id = match &self.backend { BootstrapNonceBackend::InMemory(entries) => { let Some((_, entry)) = entries.remove(nonce) else { return Err(HostBootstrapError::NonceInvalid); @@ -126,7 +126,7 @@ impl BootstrapNonceStore { if entry.expires_at_ms <= now_ms { return Err(HostBootstrapError::NonceInvalid); } - entry.installation_id + entry.device_id } BootstrapNonceBackend::Redis { client } => { let mut conn = @@ -153,7 +153,7 @@ impl BootstrapNonceStore { } }; - if entry_installation_id != installation_id { + if entry_device_id != device_id { return Err(HostBootstrapError::NonceInvalid); } Ok(()) @@ -165,7 +165,7 @@ fn nonce_key(nonce: &str) -> String { } pub struct HostBootstrapProof<'a> { - pub installation_id: &'a str, + pub device_id: &'a str, pub nonce: &'a str, pub public_key: Option<&'a str>, pub signature: &'a str, @@ -194,14 +194,14 @@ pub async fn verify_and_register( where S: AsStorePool, { - let installation_id = Uuid::parse_str(proof.installation_id) + let device_id = Uuid::parse_str(proof.device_id) .map(DeviceId) .map_err(|_| HostBootstrapError::ProofInvalid)?; nonce_store - .consume(proof.installation_id, proof.nonce, now_ms) + .consume(proof.device_id, proof.nonce, now_ms) .await?; - let existing = device_installations::get_device(store, installation_id).await?; + let existing = devices::get_device(store, device_id).await?; if let Some(row) = existing.as_ref() { if row.role != DeviceRole::AgentHost { return Err(HostBootstrapError::ProofInvalid); @@ -221,7 +221,7 @@ where verify_signature( public_key_text, proof.signature, - proof.installation_id, + proof.device_id, proof.nonce, path, )?; @@ -229,26 +229,25 @@ where if existing.is_none() { // Postgres CHECK requires host rows to have public_key NOT NULL. // Insert key atomically at TOFU register rather than insert-then-patch. - device_installations::insert_host_with_public_key( + devices::insert_host_with_public_key( store, - installation_id, + device_id, display_name, public_key_text, now_ms, ) .await?; } else if stored_public_key.is_none() { - device_installations::set_public_key_if_absent(store, &installation_id, public_key_text) - .await?; + devices::set_public_key_if_absent(store, &device_id, public_key_text).await?; } - Ok(installation_id) + Ok(device_id) } fn verify_signature( public_key_text: &str, signature_text: &str, - installation_id: &str, + device_id: &str, nonce: &str, path: &str, ) -> Result<(), HostBootstrapError> { @@ -262,7 +261,7 @@ fn verify_signature( let signature = decode_prefixed(signature_text, SIGNATURE_PREFIX, 64)?; let signature = Signature::from_slice(&signature).map_err(|_| HostBootstrapError::ProofInvalid)?; - let payload = format!("{installation_id}:{nonce}:{path}"); + let payload = format!("{device_id}:{nonce}:{path}"); verifying_key .verify(payload.as_bytes(), &signature) .map_err(|_| HostBootstrapError::ProofInvalid) @@ -309,8 +308,8 @@ mod tests { ) } - fn signature(signing_key: &SigningKey, installation_id: &str, nonce: &str) -> String { - let payload = format!("{installation_id}:{nonce}:{LINK_PATH}"); + fn signature(signing_key: &SigningKey, device_id: &str, nonce: &str) -> String { + let payload = format!("{device_id}:{nonce}:{LINK_PATH}"); format!( "{SIGNATURE_PREFIX}{}", URL_SAFE_NO_PAD.encode(signing_key.sign(payload.as_bytes()).to_bytes()) @@ -321,17 +320,17 @@ mod tests { async fn verify_and_register_tofu_stores_public_key() { let pool = crate::store::test_support::memory_pool().await; let store = BootstrapNonceStore::default(); - let installation_id = DeviceId::new().to_string(); - let nonce = store.issue(&installation_id, 100).await.unwrap().nonce; + let device_id = DeviceId::new().to_string(); + let nonce = store.issue(&device_id, 100).await.unwrap().nonce; let host_signing_key = keypair(); let host_public_key = public_key(&host_signing_key); - let host_signature = signature(&host_signing_key, &installation_id, &nonce); + let host_signature = signature(&host_signing_key, &device_id, &nonce); let id = verify_and_register( &pool, &store, HostBootstrapProof { - installation_id: &installation_id, + device_id: &device_id, nonce: &nonce, public_key: Some(&host_public_key), signature: &host_signature, @@ -343,10 +342,7 @@ mod tests { .await .unwrap(); - let row = device_installations::get_device(&pool, id) - .await - .unwrap() - .unwrap(); + let row = devices::get_device(&pool, id).await.unwrap().unwrap(); assert_eq!(row.public_key.as_deref(), Some(host_public_key.as_str())); assert_eq!(row.role, DeviceRole::AgentHost); } @@ -355,17 +351,17 @@ mod tests { async fn nonce_is_single_use() { let pool = crate::store::test_support::memory_pool().await; let store = BootstrapNonceStore::default(); - let installation_id = DeviceId::new().to_string(); - let nonce = store.issue(&installation_id, 100).await.unwrap().nonce; + let device_id = DeviceId::new().to_string(); + let nonce = store.issue(&device_id, 100).await.unwrap().nonce; let host_signing_key = keypair(); let host_public_key = public_key(&host_signing_key); - let host_signature = signature(&host_signing_key, &installation_id, &nonce); + let host_signature = signature(&host_signing_key, &device_id, &nonce); verify_and_register( &pool, &store, HostBootstrapProof { - installation_id: &installation_id, + device_id: &device_id, nonce: &nonce, public_key: Some(&host_public_key), signature: &host_signature, @@ -381,7 +377,7 @@ mod tests { &pool, &store, HostBootstrapProof { - installation_id: &installation_id, + device_id: &device_id, nonce: &nonce, public_key: Some(&host_public_key), signature: &host_signature, @@ -399,17 +395,17 @@ mod tests { async fn public_key_mismatch_is_rejected() { let pool = crate::store::test_support::memory_pool().await; let store = BootstrapNonceStore::default(); - let installation_id = DeviceId::new().to_string(); + let device_id = DeviceId::new().to_string(); let host_signing_key = keypair(); let host_public_key = public_key(&host_signing_key); - let nonce = store.issue(&installation_id, 100).await.unwrap().nonce; - let host_signature = signature(&host_signing_key, &installation_id, &nonce); + let nonce = store.issue(&device_id, 100).await.unwrap().nonce; + let host_signature = signature(&host_signing_key, &device_id, &nonce); verify_and_register( &pool, &store, HostBootstrapProof { - installation_id: &installation_id, + device_id: &device_id, nonce: &nonce, public_key: Some(&host_public_key), signature: &host_signature, @@ -423,14 +419,14 @@ mod tests { let different_key = SigningKey::from_bytes(&[9_u8; 32]); let different_public_key = public_key(&different_key); - let nonce = store.issue(&installation_id, 200).await.unwrap().nonce; - let signature = signature(&different_key, &installation_id, &nonce); + let nonce = store.issue(&device_id, 200).await.unwrap().nonce; + let signature = signature(&different_key, &device_id, &nonce); let err = verify_and_register( &pool, &store, HostBootstrapProof { - installation_id: &installation_id, + device_id: &device_id, nonce: &nonce, public_key: Some(&different_public_key), signature: &signature, diff --git a/crates/minos-backend/src/auth/host_installation.rs b/crates/minos-backend/src/auth/host_installation.rs index 254eefa8..0f206bd4 100644 --- a/crates/minos-backend/src/auth/host_installation.rs +++ b/crates/minos-backend/src/auth/host_installation.rs @@ -8,11 +8,13 @@ use axum::http::{HeaderMap, StatusCode}; use minos_domain::{DeviceId, DeviceRole}; use crate::http::BackendState; -use crate::store::{device_installations, host_installation_tokens}; +use crate::store::{devices, host_tokens}; +/// Authenticated Host rail: this Mac (`device_id`) bound to one account. #[derive(Debug, Clone)] -pub struct HostInstallationPrincipal { - pub host_installation_id: DeviceId, +pub struct HostPrincipal { + pub device_id: DeviceId, + pub account_id: String, } #[derive(Debug)] @@ -41,10 +43,10 @@ impl HostInstallationAuthError { pub async fn require( state: &BackendState, headers: &HeaderMap, -) -> Result { +) -> Result { let token = bearer_token(headers)?; let token_hash = crate::host_link::sha256_hex(token); - let row = host_installation_tokens::verify_active_token( + let row = host_tokens::verify_active_token( &state.store, &token_hash, chrono::Utc::now().timestamp_millis(), @@ -53,16 +55,33 @@ pub async fn require( .map_err(|error| HostInstallationAuthError::Internal(error.to_string()))? .ok_or(HostInstallationAuthError::Invalid)?; - let host = device_installations::get_device(&state.store, row.host_installation_id) + let host = devices::get_device(&state.store, row.host_device_id) .await .map_err(|error| HostInstallationAuthError::Internal(error.to_string()))? .ok_or(HostInstallationAuthError::Invalid)?; - if host.role != DeviceRole::AgentHost { + // Desktop login binds host_token to the same DeviceId as the account + // installation (kind=desktop). Standalone daemons remain AgentHost. + if host.role != DeviceRole::AgentHost && host.role != DeviceRole::DesktopConsole { return Err(HostInstallationAuthError::Invalid); } - Ok(HostInstallationPrincipal { - host_installation_id: host.device_id, + let account_id = match row.account_id.filter(|id| !id.is_empty()) { + Some(id) => id, + None => { + let links = + crate::store::host_links::list_accounts_for_host(&state.store, row.host_device_id) + .await + .map_err(|error| HostInstallationAuthError::Internal(error.to_string()))?; + match links.as_slice() { + [only] => only.mobile_account_id.clone(), + _ => return Err(HostInstallationAuthError::Invalid), + } + } + }; + + Ok(HostPrincipal { + device_id: host.device_id, + account_id, }) } diff --git a/crates/minos-backend/src/auth/use_case.rs b/crates/minos-backend/src/auth/use_case.rs index 5e71ff4f..24ad8bfd 100644 --- a/crates/minos-backend/src/auth/use_case.rs +++ b/crates/minos-backend/src/auth/use_case.rs @@ -75,6 +75,9 @@ pub struct AuthSession { pub access_token: String, pub refresh_token: String, pub expires_in: i64, + /// Desktop login: opaque host token bound to `(account_id, device_id)`. + /// Other account-client roles leave this unset. + pub host_token: Option, } #[derive(Debug, Clone)] @@ -405,8 +408,16 @@ impl AuthUseCase { self.ensure_device_for_account(&device_id, device_role, device_name, &account.account_id) .await?; - self.issue_auth_session(&account.account_id, &account.email, &device_id) - .await + let mut session = self + .issue_auth_session(&account.account_id, &account.email, &device_id) + .await?; + if device_role == DeviceRole::DesktopConsole { + session.host_token = Some( + self.issue_desktop_host_token(&device_id, &account.account_id) + .await?, + ); + } + Ok(session) } async fn upsert_account_from_supabase( @@ -515,14 +526,14 @@ impl AuthUseCase { .map(str::trim) .filter(|s| !s.is_empty()) .unwrap_or("unnamed"); - let existing = crate::store::device_installations::get_device(&self.store, *device_id) + let existing = crate::store::devices::get_device(&self.store, *device_id) .await .map_err(|error| Self::log_internal("auth.get_device", error))?; match existing { None => { let now = chrono::Utc::now().timestamp_millis(); - crate::store::device_installations::insert_client_for_account( + crate::store::devices::insert_client_for_account( &self.store, *device_id, display_name, @@ -549,12 +560,8 @@ impl AuthUseCase { .filter(|s| !s.is_empty()) .filter(|s| *s != row.display_name.as_str()) { - if let Err(error) = crate::store::device_installations::set_display_name( - &self.store, - device_id, - name, - ) - .await + if let Err(error) = + crate::store::devices::set_display_name(&self.store, device_id, name).await { tracing::warn!( target: "minos_backend::auth", @@ -667,16 +674,21 @@ impl AuthUseCase { ) -> Result<(), AuthUseCaseError> { self.limits.check_refresh_per_account(account_id)?; - match self.refresh_tokens.find_active(refresh_token).await { - Ok(Some(row)) if row.account_id == account_id => {} + let device_id = match self.refresh_tokens.find_active(refresh_token).await { + Ok(Some(row)) if row.account_id == account_id => row.device_id, Ok(Some(_)) | Ok(None) => return Ok(()), Err(error) => return Err(Self::log_internal("logout.find_active", error)), - } + }; self.refresh_tokens .revoke_one(refresh_token) .await .map_err(|error| Self::log_internal("logout.revoke_one", error))?; + if let Ok(device_id) = uuid::Uuid::parse_str(&device_id).map(DeviceId) { + let now = chrono::Utc::now().timestamp_millis(); + let _ = + crate::store::host_tokens::revoke_all_for_host(&self.store, device_id, now).await; + } Ok(()) } @@ -690,7 +702,7 @@ impl AuthUseCase { return Err(AuthUseCaseError::UnsupportedWsTicketRole); } - let existing = crate::store::device_installations::get_device(&self.store, device_id) + let existing = crate::store::devices::get_device(&self.store, device_id) .await .map_err(|error| Self::log_internal("ws_ticket.get_device", error))?; match existing.as_ref().and_then(|row| row.account_id.as_deref()) { @@ -718,11 +730,11 @@ impl AuthUseCase { pub async fn issue_host_ws_ticket( &self, - host_installation_id: DeviceId, + host_device_id: DeviceId, ) -> Result { self.issue_tracked_ws_ticket( - &host_installation_id.to_string(), - host_installation_id, + &host_device_id.to_string(), + host_device_id, DeviceRole::AgentHost, ) .await @@ -758,13 +770,12 @@ impl AuthUseCase { device_id: &DeviceId, account_id: &str, ) -> Result<(), AuthUseCaseError> { - let previous_account_id = - crate::store::device_installations::get_device(&self.store, *device_id) - .await - .map_err(|error| Self::log_internal("bind_device.get_device", error))? - .and_then(|device| device.account_id); + let previous_account_id = crate::store::devices::get_device(&self.store, *device_id) + .await + .map_err(|error| Self::log_internal("bind_device.get_device", error))? + .and_then(|device| device.account_id); - crate::store::device_installations::set_account_id(&self.store, device_id, account_id) + crate::store::devices::set_account_id(&self.store, device_id, account_id) .await .map_err(|error| Self::log_internal("bind_device.set_account_id", error))?; @@ -803,9 +814,56 @@ impl AuthUseCase { access_token, refresh_token, expires_in: jwt::ACCESS_TTL_SECS, + host_token: None, }) } + /// Bind this Desktop DeviceId as the account's Host and mint a host_token. + /// + /// Signing into Desktop owns this Mac: a prior account's link on the same + /// DeviceId is replaced. + async fn issue_desktop_host_token( + &self, + device_id: &DeviceId, + account_id: &str, + ) -> Result { + let svc = crate::host_link::HostLinkService::new(self.store.clone()); + match svc + .link_host(*device_id, account_id, *device_id, Some("This Mac")) + .await + { + Ok(outcome) => Ok(outcome.host_installation_token), + Err(crate::host_link::HostLinkError::HostLinkedElsewhere { .. }) => { + let links = + crate::store::host_links::list_accounts_for_host(&self.store, *device_id) + .await + .map_err(|error| Self::log_internal("desktop_host.list_links", error))?; + let now = chrono::Utc::now().timestamp_millis(); + for link in links { + let _ = crate::store::host_links::delete_pair( + &self.store, + link.host_device_id, + &link.mobile_account_id, + ) + .await; + } + let _ = + crate::store::host_tokens::revoke_all_for_host(&self.store, *device_id, now) + .await; + svc.link_host(*device_id, account_id, *device_id, Some("This Mac")) + .await + .map(|outcome| outcome.host_installation_token) + .map_err(|error| { + Self::log_internal("desktop_host.relink", format!("{error:?}")) + }) + } + Err(error) => Err(Self::log_internal( + "desktop_host.link", + format!("{error:?}"), + )), + } + } + fn log_internal(operation: &'static str, error: impl std::fmt::Display) -> AuthUseCaseError { tracing::warn!( target: "minos_backend::auth", diff --git a/crates/minos-backend/src/error.rs b/crates/minos-backend/src/error.rs index af26d7a5..a62ec1e8 100644 --- a/crates/minos-backend/src/error.rs +++ b/crates/minos-backend/src/error.rs @@ -26,7 +26,7 @@ pub enum BackendError { /// A row returned by the store failed to parse back into a domain type. /// /// The store writes ids/kinds as TEXT and parses on read - /// (see `store/device_installations.rs`). Corrupt rows — or schema drift + /// (see `store/devices.rs`). Corrupt rows — or schema drift /// between migrations and domain types — surface here. #[error("store decode failed for column `{column}`: {message}")] StoreDecode { column: String, message: String }, @@ -65,10 +65,10 @@ pub enum BackendError { /// Host installation is already linked to a different account. /// - /// Enforced by `UNIQUE (host_installation_id)` on `host_links` and by + /// Enforced by `UNIQUE (host_device_id)` on `host_links` and by /// in-transaction exclusivity checks (Host Link + QR confirm). #[error("host already linked to another account")] - HostLinkedElsewhere { host_installation_id: String }, + HostLinkedElsewhere { host_device_id: String }, /// HS256 JWT signing failed (e.g. malformed key). #[error("jwt sign error: {message}")] diff --git a/crates/minos-backend/src/host_commands/use_case.rs b/crates/minos-backend/src/host_commands/use_case.rs index e2110176..75b1c34d 100644 --- a/crates/minos-backend/src/host_commands/use_case.rs +++ b/crates/minos-backend/src/host_commands/use_case.rs @@ -19,7 +19,7 @@ const COMMAND_STATUS_POLL_INTERVAL: Duration = Duration::from_millis(100); #[derive(Debug, Clone)] pub struct NewHostCommand { pub command_id: String, - pub host_installation_id: DeviceId, + pub host_device_id: DeviceId, pub agent_session_id: Option, pub method: String, pub params_json: Value, @@ -101,7 +101,7 @@ impl RuntimeHostCommandService { pub async fn enqueue_if_missing( &self, command_id: &str, - host_installation_id: DeviceId, + host_device_id: DeviceId, agent_session_id: Option<&str>, method: &str, params_json: &Value, @@ -115,7 +115,7 @@ impl RuntimeHostCommandService { &mut tx, NewHostCommand { command_id: command_id.to_string(), - host_installation_id, + host_device_id, agent_session_id: agent_session_id.map(str::to_string), method: method.to_string(), params_json: params_json.clone(), @@ -135,7 +135,7 @@ impl RuntimeHostCommandService { pub async fn enqueue( &self, command_id: &str, - host_installation_id: DeviceId, + host_device_id: DeviceId, agent_session_id: Option<&str>, method: &str, params_json: &Value, @@ -148,7 +148,7 @@ impl RuntimeHostCommandService { &mut tx, NewHostCommand { command_id: command_id.to_string(), - host_installation_id, + host_device_id, agent_session_id: agent_session_id.map(str::to_string), method: method.to_string(), params_json: params_json.clone(), @@ -172,7 +172,7 @@ impl RuntimeHostCommandService { host_commands::enqueue_in_tx( tx, &command.command_id, - command.host_installation_id, + command.host_device_id, command.agent_session_id.as_deref(), &command.method, &command.params_json, @@ -184,7 +184,7 @@ impl RuntimeHostCommandService { let durable_event = DurableEvent::HostCommandIssued { command_id: command.command_id, - host_installation_id: command.host_installation_id.to_string(), + host_device_id: command.host_device_id.to_string(), agent_session_id: command.agent_session_id, method: command.method, params: command.params_json, @@ -228,12 +228,12 @@ impl RuntimeHostCommandService { method: method.to_string(), message: format!("host command row missing: {command_id}"), })?; - if row.host_installation_id != target_device_id { + if row.host_device_id != target_device_id { return Err(BackendError::ForwardRpc { method: method.to_string(), message: format!( "host command {command_id} belongs to {} not {target_device_id}", - row.host_installation_id + row.host_device_id ), }); } @@ -275,12 +275,12 @@ impl RuntimeHostCommandService { method: method.to_string(), message: format!("host command row missing after timeout: {command_id}"), })?; - if row.host_installation_id != target_device_id { + if row.host_device_id != target_device_id { return Err(BackendError::ForwardRpc { method: method.to_string(), message: format!( "host command {command_id} belongs to {} not {target_device_id}", - row.host_installation_id + row.host_device_id ), }); } diff --git a/crates/minos-backend/src/host_link/mod.rs b/crates/minos-backend/src/host_link/mod.rs index 89a97168..36d64bb3 100644 --- a/crates/minos-backend/src/host_link/mod.rs +++ b/crates/minos-backend/src/host_link/mod.rs @@ -1,6 +1,6 @@ //! Same-account host link service (D02). //! -//! Owns account↔host binding via `host_links` + `host_installation_tokens`. +//! Owns account↔host binding via `host_links` + `host_tokens`. //! QR pairing was removed; this is the only bind path. //! //! Multi-end roster: every successful link/unlink records `HostLinked` / @@ -20,15 +20,15 @@ use crate::{ error::BackendError, realtime::{ConnectionRevocation, RealtimeConnectionRegistry}, store::{ - durable_event_log, host_installation_tokens, host_links, outbox_events, AsStorePool, - StoreHandle, StorePoolRef, + durable_event_log, host_links, host_tokens, outbox_events, AsStorePool, StoreHandle, + StorePoolRef, }, }; /// Outcome of a successful [`HostLinkService::link_host`]. #[derive(Debug, Clone)] pub struct HostLinkOutcome { - pub host_installation_id: DeviceId, + pub host_device_id: DeviceId, pub host_installation_token: String, pub link: host_links::PairRow, /// Deterministic durable event id enqueued for account roster fanout. @@ -53,18 +53,14 @@ fn map_host_link_store_err(error: BackendError) -> HostLinkError { /// Deterministic HostLinked event id (idempotent re-link same pair_id). #[must_use] -pub fn host_linked_event_id(account_id: &str, host_installation_id: &str, pair_id: &str) -> String { - format!("host-linked-{account_id}-{host_installation_id}-{pair_id}") +pub fn host_linked_event_id(account_id: &str, host_device_id: &str, pair_id: &str) -> String { + format!("host-linked-{account_id}-{host_device_id}-{pair_id}") } /// Deterministic HostUnlinked event id (pair_id from pre-delete row). #[must_use] -pub fn host_unlinked_event_id( - account_id: &str, - host_installation_id: &str, - pair_id: &str, -) -> String { - format!("host-unlinked-{account_id}-{host_installation_id}-{pair_id}") +pub fn host_unlinked_event_id(account_id: &str, host_device_id: &str, pair_id: &str) -> String { + format!("host-unlinked-{account_id}-{host_device_id}-{pair_id}") } /// Idempotent on deterministic `event_id`: same-account re-link keeps token @@ -138,15 +134,15 @@ impl HostLinkService { /// /// Rejects hosts already linked to a different account (`HostLinkedElsewhere`). /// Exclusivity is checked **inside** the write transaction (with - /// `UNIQUE (host_installation_id)` as belt-and-suspenders). Re-linking the + /// `UNIQUE (host_device_id)` as belt-and-suspenders). Re-linking the /// same account rotates tokens (revoke all then issue a fresh `hit_*`). /// /// On success, records `DurableEvent::HostLinked` + outbox in the same tx. pub async fn link_host( &self, - host_installation_id: DeviceId, + host_device_id: DeviceId, account_id: &str, - linked_via_installation_id: DeviceId, + linked_via_device_id: DeviceId, host_display_name: Option<&str>, ) -> Result { let now = Utc::now().timestamp_millis(); @@ -162,49 +158,43 @@ impl HostLinkService { })?; host_links::assert_host_available_or_same_account_sqlite( &mut *raw_tx, - host_installation_id, + host_device_id, account_id, ) .await .map_err(map_host_link_store_err)?; let link = host_links::upsert_link_with_executor( &mut *raw_tx, - host_installation_id, + host_device_id, account_id, - linked_via_installation_id, + linked_via_device_id, host_display_name, now, ) .await .map_err(map_host_link_store_err)?; - host_installation_tokens::revoke_all_for_host_with_executor( - &mut *raw_tx, - host_installation_id, - now, - ) - .await - .map_err(HostLinkError::Internal)?; - host_installation_tokens::insert_token_with_executor( + host_tokens::revoke_all_for_host_with_executor(&mut *raw_tx, host_device_id, now) + .await + .map_err(HostLinkError::Internal)?; + host_tokens::insert_token_with_executor( &mut *raw_tx, &token_hash, - host_installation_id, + host_device_id, + Some(account_id), now, ) .await .map_err(HostLinkError::Internal)?; - let event_id = host_linked_event_id( - account_id, - &host_installation_id.to_string(), - &link.pair_id, - ); + let event_id = + host_linked_event_id(account_id, &host_device_id.to_string(), &link.pair_id); let display = link .link_display_name .clone() .or_else(|| host_display_name.map(str::to_string)); let event = DurableEvent::HostLinked { account_id: account_id.to_string(), - host_installation_id: host_installation_id.to_string(), + host_device_id: host_device_id.to_string(), pair_id: link.pair_id.clone(), at_ms: now, host_display_name: display, @@ -222,49 +212,47 @@ impl HostLinkService { .map_err(HostLinkError::Internal)?; host_links::assert_host_available_or_same_account_postgres( &mut *raw_tx, - host_installation_id, + host_device_id, account_id, ) .await .map_err(map_host_link_store_err)?; let link = host_links::upsert_link_with_postgres_executor( &mut *raw_tx, - host_installation_id, + host_device_id, account_id, - linked_via_installation_id, + linked_via_device_id, host_display_name, now, ) .await .map_err(map_host_link_store_err)?; - host_installation_tokens::revoke_all_for_host_with_postgres_executor( + host_tokens::revoke_all_for_host_with_postgres_executor( &mut *raw_tx, - host_installation_id, + host_device_id, now, ) .await .map_err(HostLinkError::Internal)?; - host_installation_tokens::insert_token_with_postgres_executor( + host_tokens::insert_token_with_postgres_executor( &mut *raw_tx, &token_hash, - host_installation_id, + host_device_id, + Some(account_id), now, ) .await .map_err(HostLinkError::Internal)?; - let event_id = host_linked_event_id( - account_id, - &host_installation_id.to_string(), - &link.pair_id, - ); + let event_id = + host_linked_event_id(account_id, &host_device_id.to_string(), &link.pair_id); let display = link .link_display_name .clone() .or_else(|| host_display_name.map(str::to_string)); let event = DurableEvent::HostLinked { account_id: account_id.to_string(), - host_installation_id: host_installation_id.to_string(), + host_device_id: host_device_id.to_string(), pair_id: link.pair_id.clone(), at_ms: now, host_display_name: display, @@ -278,11 +266,11 @@ impl HostLinkService { } }; - let _ = crate::ingest::invalidate_peer_targets_for_host(host_installation_id).await; + let _ = crate::ingest::invalidate_peer_targets_for_host(host_device_id).await; let _ = crate::ingest::invalidate_peer_targets_for_account(&self.pool, account_id).await; Ok(HostLinkOutcome { - host_installation_id, + host_device_id, host_installation_token: token, link, durable_event_id, @@ -297,7 +285,7 @@ impl HostLinkService { pub async fn unlink_host( &self, registry: &RealtimeConnectionRegistry, - host_installation_id: DeviceId, + host_device_id: DeviceId, account_id: &str, ) -> Result { let now = Utc::now().timestamp_millis(); @@ -309,42 +297,32 @@ impl HostLinkService { message: e.to_string(), }) })?; - let existing = host_links::get_pair_with_executor( - &mut *raw_tx, - host_installation_id, - account_id, - ) - .await - .map_err(HostLinkError::Internal)?; + let existing = + host_links::get_pair_with_executor(&mut *raw_tx, host_device_id, account_id) + .await + .map_err(HostLinkError::Internal)?; let Some(existing) = existing else { return Err(HostLinkError::NotFound); }; - let deleted = host_links::delete_pair_with_executor( - &mut *raw_tx, - host_installation_id, - account_id, - ) - .await - .map_err(HostLinkError::Internal)?; + let deleted = + host_links::delete_pair_with_executor(&mut *raw_tx, host_device_id, account_id) + .await + .map_err(HostLinkError::Internal)?; if deleted == 0 { return Err(HostLinkError::NotFound); } - host_installation_tokens::revoke_all_for_host_with_executor( - &mut *raw_tx, - host_installation_id, - now, - ) - .await - .map_err(HostLinkError::Internal)?; + host_tokens::revoke_all_for_host_with_executor(&mut *raw_tx, host_device_id, now) + .await + .map_err(HostLinkError::Internal)?; let event_id = host_unlinked_event_id( account_id, - &host_installation_id.to_string(), + &host_device_id.to_string(), &existing.pair_id, ); let event = DurableEvent::HostUnlinked { account_id: account_id.to_string(), - host_installation_id: host_installation_id.to_string(), + host_device_id: host_device_id.to_string(), at_ms: now, }; let mut db_tx = DbTx::Sqlite(raw_tx); @@ -360,7 +338,7 @@ impl HostLinkService { .map_err(HostLinkError::Internal)?; let existing = host_links::get_pair_with_postgres_executor( &mut *raw_tx, - host_installation_id, + host_device_id, account_id, ) .await @@ -370,7 +348,7 @@ impl HostLinkService { }; let deleted = host_links::delete_pair_with_postgres_executor( &mut *raw_tx, - host_installation_id, + host_device_id, account_id, ) .await @@ -378,9 +356,9 @@ impl HostLinkService { if deleted == 0 { return Err(HostLinkError::NotFound); } - host_installation_tokens::revoke_all_for_host_with_postgres_executor( + host_tokens::revoke_all_for_host_with_postgres_executor( &mut *raw_tx, - host_installation_id, + host_device_id, now, ) .await @@ -388,12 +366,12 @@ impl HostLinkService { let event_id = host_unlinked_event_id( account_id, - &host_installation_id.to_string(), + &host_device_id.to_string(), &existing.pair_id, ); let event = DurableEvent::HostUnlinked { account_id: account_id.to_string(), - host_installation_id: host_installation_id.to_string(), + host_device_id: host_device_id.to_string(), at_ms: now, }; let mut db_tx = DbTx::Postgres(raw_tx); @@ -405,9 +383,9 @@ impl HostLinkService { } }; - let _ = crate::ingest::invalidate_peer_targets_for_host(host_installation_id).await; + let _ = crate::ingest::invalidate_peer_targets_for_host(host_device_id).await; let _ = crate::ingest::invalidate_peer_targets_for_account(&self.pool, account_id).await; - let _ = registry.revoke_device(host_installation_id, ConnectionRevocation::AuthRevoked); + let _ = registry.revoke_device(host_device_id, ConnectionRevocation::AuthRevoked); Ok(durable_event_id) } } diff --git a/crates/minos-backend/src/http/auth.rs b/crates/minos-backend/src/http/auth.rs index 88daf07b..2941be44 100644 --- a/crates/minos-backend/src/http/auth.rs +++ b/crates/minos-backend/src/http/auth.rs @@ -7,7 +7,7 @@ //! `account_id` for clients and `public_key` for hosts. Clients are //! inserted at login/register/exchange via `insert_client_for_account`; //! hosts at bootstrap via `insert_host_with_public_key`. Device-secret -//! verification has been removed (hosts use `host_installation_tokens`; +//! verification has been removed (hosts use `host_tokens`; //! clients use bearer access tokens). use axum::http::{HeaderMap, StatusCode}; @@ -15,7 +15,7 @@ use minos_domain::{DeviceId, DeviceRole}; use std::str::FromStr; use uuid::Uuid; -use crate::store::{self, device_installations::DeviceRow}; +use crate::store::{self, devices::DeviceRow}; pub const HDR_DEVICE_ID: &str = "x-device-id"; pub const HDR_DEVICE_ROLE: &str = "x-device-role"; @@ -71,7 +71,7 @@ pub async fn authenticate( .map(|name| name.trim().to_owned()) .filter(|name| !name.is_empty()); - let existing = store::device_installations::get_device(store, device_id) + let existing = store::devices::get_device(store, device_id) .await .map_err(|e| AuthError::Internal(e.to_string()))?; let should_backfill_display_name = existing.as_ref().is_some_and(|row| { @@ -86,8 +86,7 @@ pub async fn authenticate( if should_backfill_display_name { if let Some(new_display_name) = provided_display_name.as_deref() { if let Err(e) = - store::device_installations::set_display_name(store, &device_id, new_display_name) - .await + store::devices::set_display_name(store, &device_id, new_display_name).await { tracing::warn!( target: "minos_backend::http::auth", @@ -136,7 +135,7 @@ pub fn classify( role: DeviceRole, ) -> Result { // Device-secret rail removed with `secret_hash` column. Provided secrets - // are ignored; host steady-state auth uses host_installation_tokens. + // are ignored; host steady-state auth uses host_tokens. let _ = (provided_secret, role); match row { None => Ok(Classification::FirstConnect), diff --git a/crates/minos-backend/src/http/mod.rs b/crates/minos-backend/src/http/mod.rs index bc4b2d8f..4a99f20b 100644 --- a/crates/minos-backend/src/http/mod.rs +++ b/crates/minos-backend/src/http/mod.rs @@ -897,7 +897,7 @@ async fn touch_device_last_seen( device_id: minos_domain::DeviceId, operation: &'static str, ) { - if let Err(error) = crate::store::device_installations::touch_last_seen( + if let Err(error) = crate::store::devices::touch_last_seen( &state.store, &device_id, chrono::Utc::now().timestamp_millis(), @@ -1003,7 +1003,7 @@ pub mod test_support { let (tx, rx) = mpsc::channel::(8); let principal = match role { minos_domain::DeviceRole::AgentHost => ConnectionPrincipal::Host { - host_installation_id: device_id.to_string(), + host_device_id: device_id.to_string(), }, _ => ConnectionPrincipal::Account { account_id: account_id.unwrap_or("acct-test").to_string(), @@ -1185,7 +1185,7 @@ mod tests { .uri("/v1/host/bootstrap/nonce") .header("content-type", "application/json") .body(Body::from( - r#"{"installation_id":"00000000-0000-0000-0000-000000000001"}"#, + r#"{"device_id":"00000000-0000-0000-0000-000000000001"}"#, )) .expect("request builder"), ) @@ -1201,7 +1201,7 @@ mod tests { .uri("/v1/hosts/link") .header("content-type", "application/json") .body(Body::from( - r#"{"installation_id":"00000000-0000-0000-0000-000000000001","nonce":"nonce_x","signature":"ed25519-sig:x"}"#, + r#"{"device_id":"00000000-0000-0000-0000-000000000001","nonce":"nonce_x","signature":"ed25519-sig:x"}"#, )) .expect("request builder"), ) @@ -1217,7 +1217,7 @@ mod tests { .uri("/v1/realtime/ws-ticket") .header("content-type", "application/json") .body(Body::from( - r#"{"installation_id":"00000000-0000-0000-0000-000000000001"}"#, + r#"{"device_id":"00000000-0000-0000-0000-000000000001"}"#, )) .expect("request builder"), ) diff --git a/crates/minos-backend/src/http/v1/agent_sessions.rs b/crates/minos-backend/src/http/v1/agent_sessions.rs index 4e348c6e..cc7624bf 100644 --- a/crates/minos-backend/src/http/v1/agent_sessions.rs +++ b/crates/minos-backend/src/http/v1/agent_sessions.rs @@ -32,7 +32,7 @@ struct StartAgentSessionRequest { conversation_id: String, project_id: Option, agent_id: String, - host_installation_id: Option, + host_device_id: Option, workspace_path: Option, initial_user_message: Option, /// Optional Hub user message id (collab agent-result suffix). Pass-through when present. @@ -45,7 +45,7 @@ struct StartAgentSessionRequest { struct StartAgentSessionResponse { session_id: String, conversation_id: String, - host_installation_id: String, + host_device_id: String, started_at_ms: i64, initial_turn_id: Option, host_command_id: String, @@ -171,7 +171,7 @@ async fn start_session( conversation_id: request.conversation_id, project_id: request.project_id, agent_id: request.agent_id, - host_installation_id: request.host_installation_id, + host_device_id: request.host_device_id, workspace_path: request.workspace_path, initial_user_message: request.initial_user_message, origin_message_id: request @@ -189,7 +189,7 @@ async fn start_session( Ok(Json(StartAgentSessionResponse { session_id: output.session_id, conversation_id: output.conversation_id, - host_installation_id: output.host_installation_id, + host_device_id: output.host_device_id, started_at_ms: output.started_at_ms, initial_turn_id: output.initial_turn_id, host_command_id: output.host_command_id, diff --git a/crates/minos-backend/src/http/v1/auth.rs b/crates/minos-backend/src/http/v1/auth.rs index 956891df..9efc1d8b 100644 --- a/crates/minos-backend/src/http/v1/auth.rs +++ b/crates/minos-backend/src/http/v1/auth.rs @@ -51,6 +51,9 @@ pub struct AuthResp { pub access_token: String, pub refresh_token: String, pub expires_in: i64, + /// Present for Desktop login: host_token bound to this DeviceId + account. + #[serde(skip_serializing_if = "Option::is_none")] + pub host_token: Option, } #[derive(Debug, Serialize, utoipa::ToSchema)] @@ -142,6 +145,7 @@ fn auth_session_response(session: AuthSession) -> Response { access_token: session.access_token, refresh_token: session.refresh_token, expires_in: session.expires_in, + host_token: session.host_token, }), ) .into_response() diff --git a/crates/minos-backend/src/http/v1/host.rs b/crates/minos-backend/src/http/v1/host.rs index 5cff29cd..dd4399ff 100644 --- a/crates/minos-backend/src/http/v1/host.rs +++ b/crates/minos-backend/src/http/v1/host.rs @@ -17,7 +17,7 @@ use crate::http::BackendState; #[derive(Debug, Serialize)] struct HostSelfData { - host_installation_id: String, + host_device_id: String, display_name: String, link_count: usize, links: Vec, @@ -25,7 +25,7 @@ struct HostSelfData { #[derive(Debug, Serialize)] struct HostSelfLinkSummary { - linked_via_installation_id: String, + linked_via_device_id: String, link_display_name: String, paired_at_ms: i64, last_active_at_ms: i64, @@ -34,7 +34,7 @@ struct HostSelfLinkSummary { #[derive(Debug, Deserialize)] struct BootstrapNonceRequest { - installation_id: String, + device_id: String, } #[derive(Debug, Serialize)] @@ -55,18 +55,18 @@ async fn post_bootstrap_nonce( headers: HeaderMap, Json(req): Json, ) -> Result>, (StatusCode, Json)> { - if uuid::Uuid::parse_str(&req.installation_id).is_err() { + if uuid::Uuid::parse_str(&req.device_id).is_err() { return Err((StatusCode::BAD_REQUEST, err("bad_request"))); } let nonce = state .bootstrap_nonces - .issue(&req.installation_id, chrono::Utc::now().timestamp_millis()) + .issue(&req.device_id, chrono::Utc::now().timestamp_millis()) .await .map_err(|error| { tracing::warn!( target: "minos_backend::v1::host", error = %error, - installation_id = %req.installation_id, + device_id = %req.device_id, "bootstrap nonce issue failed", ); (StatusCode::INTERNAL_SERVER_ERROR, err("internal")) @@ -86,65 +86,58 @@ async fn post_installations_self( headers: HeaderMap, ) -> Result>, (StatusCode, Json)> { let outcome = require_host(&state, &headers).await?; - let host = - crate::store::device_installations::get_device(&state.store, outcome.host_installation_id) + let host = crate::store::devices::get_device(&state.store, outcome.device_id) + .await + .map_err(|error| { + tracing::warn!( + target: "minos_backend::v1::host", + error = %error, + device_id = %outcome.device_id, + "get_device(host) failed", + ); + (StatusCode::INTERNAL_SERVER_ERROR, err("internal")) + })? + .ok_or_else(|| (StatusCode::UNAUTHORIZED, err("unauthorized")))?; + + let pairs = crate::store::host_links::list_accounts_for_host(&state.store, outcome.device_id) + .await + .map_err(|error| { + tracing::warn!( + target: "minos_backend::v1::host", + error = %error, + device_id = %outcome.device_id, + "list_accounts_for_host failed", + ); + (StatusCode::INTERNAL_SERVER_ERROR, err("internal")) + })?; + + let mut links = Vec::with_capacity(pairs.len()); + for pair in pairs { + let mobile = crate::store::devices::get_device(&state.store, pair.paired_via_device_id) .await .map_err(|error| { tracing::warn!( target: "minos_backend::v1::host", error = %error, - host_installation_id = %outcome.host_installation_id, - "get_device(host) failed", + linked_via_device_id = %pair.paired_via_device_id, + "get_device(linked_via) failed", ); (StatusCode::INTERNAL_SERVER_ERROR, err("internal")) - })? - .ok_or_else(|| (StatusCode::UNAUTHORIZED, err("unauthorized")))?; - - let pairs = crate::store::host_links::list_accounts_for_host( - &state.store, - outcome.host_installation_id, - ) - .await - .map_err(|error| { - tracing::warn!( - target: "minos_backend::v1::host", - error = %error, - host_installation_id = %outcome.host_installation_id, - "list_accounts_for_host failed", - ); - (StatusCode::INTERNAL_SERVER_ERROR, err("internal")) - })?; + })?; - let mut links = Vec::with_capacity(pairs.len()); - for pair in pairs { - let mobile = - crate::store::device_installations::get_device(&state.store, pair.paired_via_device_id) + let latest_mobile = + crate::store::devices::latest_mobile_for_account(&state.store, &pair.mobile_account_id) .await .map_err(|error| { tracing::warn!( target: "minos_backend::v1::host", error = %error, - linked_via_installation_id = %pair.paired_via_device_id, - "get_device(linked_via) failed", + mobile_account_id = %pair.mobile_account_id, + "latest_mobile_for_account failed", ); (StatusCode::INTERNAL_SERVER_ERROR, err("internal")) })?; - let latest_mobile = crate::store::device_installations::latest_mobile_for_account( - &state.store, - &pair.mobile_account_id, - ) - .await - .map_err(|error| { - tracing::warn!( - target: "minos_backend::v1::host", - error = %error, - mobile_account_id = %pair.mobile_account_id, - "latest_mobile_for_account failed", - ); - (StatusCode::INTERNAL_SERVER_ERROR, err("internal")) - })?; - let (display_name, last_active_at_ms) = if let Some(row) = mobile { let last_active_at_ms = latest_mobile .as_ref() @@ -153,7 +146,7 @@ async fn post_installations_self( } else { tracing::warn!( target: "minos_backend::v1::host", - linked_via_installation_id = %pair.paired_via_device_id, + linked_via_device_id = %pair.paired_via_device_id, "host link references mobile device with no devices row; using placeholder name", ); latest_mobile.map_or_else( @@ -163,7 +156,7 @@ async fn post_installations_self( }; links.push(HostSelfLinkSummary { - linked_via_installation_id: pair.paired_via_device_id.to_string(), + linked_via_device_id: pair.paired_via_device_id.to_string(), link_display_name: display_name, paired_at_ms: pair.paired_at_ms, last_active_at_ms, @@ -173,7 +166,7 @@ async fn post_installations_self( Ok(Json(ResponseEnvelope::new( HostSelfData { - host_installation_id: outcome.host_installation_id.to_string(), + host_device_id: outcome.device_id.to_string(), display_name: host.display_name, link_count: links.len(), links, @@ -193,7 +186,7 @@ fn is_account_online(state: &BackendState, account_id: &str) -> bool { async fn require_host( state: &BackendState, headers: &HeaderMap, -) -> Result)> { +) -> Result)> { host_installation::require(state, headers) .await .map_err(|error| { diff --git a/crates/minos-backend/src/http/v1/host_commands.rs b/crates/minos-backend/src/http/v1/host_commands.rs index 8efac12e..20e4019d 100644 --- a/crates/minos-backend/src/http/v1/host_commands.rs +++ b/crates/minos-backend/src/http/v1/host_commands.rs @@ -47,8 +47,7 @@ async fn list_clis( Json(request): Json, ) -> Result, (StatusCode, Json)> { let (_caller_device_id, account_id) = super::require_authed_session(&state, &headers).await?; - let host_device_id = - require_paired_host(&state, &account_id, &request.host_installation_id).await?; + let host_device_id = require_paired_host(&state, &account_id, &request.host_device_id).await?; let response = state .host_commands @@ -75,8 +74,7 @@ async fn list_host_skills( Json(request): Json, ) -> Result, (StatusCode, Json)> { let (_caller_device_id, account_id) = super::require_authed_session(&state, &headers).await?; - let host_device_id = - require_paired_host(&state, &account_id, &request.host_installation_id).await?; + let host_device_id = require_paired_host(&state, &account_id, &request.host_device_id).await?; let params = serde_json::to_value(ListHostSkillsRequest { workspace: request.workspace, force_reload: request.force_reload, @@ -108,8 +106,7 @@ async fn list_host_workspaces( Json(request): Json, ) -> Result, (StatusCode, Json)> { let (_caller_device_id, account_id) = super::require_authed_session(&state, &headers).await?; - let host_device_id = - require_paired_host(&state, &account_id, &request.host_installation_id).await?; + let host_device_id = require_paired_host(&state, &account_id, &request.host_device_id).await?; let params = serde_json::to_value(ListHostWorkspacesRequest { root: request.root, limit: request.limit, @@ -141,8 +138,7 @@ async fn write_host_skill_config( Json(request): Json, ) -> Result, (StatusCode, Json)> { let (_caller_device_id, account_id) = super::require_authed_session(&state, &headers).await?; - let host_device_id = - require_paired_host(&state, &account_id, &request.host_installation_id).await?; + let host_device_id = require_paired_host(&state, &account_id, &request.host_device_id).await?; let params = serde_json::to_value(WriteHostSkillConfigRequest { workspace: request.workspace, path: request.path, @@ -172,16 +168,14 @@ async fn write_host_skill_config( async fn require_paired_host( state: &BackendState, account_id: &str, - host_installation_id: &str, + host_device_id: &str, ) -> Result)> { - let host_device_id = Uuid::parse_str(host_installation_id) - .map(DeviceId) - .map_err(|_| { - ( - StatusCode::BAD_REQUEST, - err_json("bad_request", "invalid host_installation_id"), - ) - })?; + let host_device_id = Uuid::parse_str(host_device_id).map(DeviceId).map_err(|_| { + ( + StatusCode::BAD_REQUEST, + err_json("bad_request", "invalid host_device_id"), + ) + })?; let paired = state .data diff --git a/crates/minos-backend/src/http/v1/hosts.rs b/crates/minos-backend/src/http/v1/hosts.rs index 9cb4ebb3..b6edd0aa 100644 --- a/crates/minos-backend/src/http/v1/hosts.rs +++ b/crates/minos-backend/src/http/v1/hosts.rs @@ -26,7 +26,7 @@ pub fn router() -> Router { #[derive(Debug, Deserialize)] struct LinkHostRequest { - installation_id: String, + device_id: String, nonce: String, public_key: Option, signature: String, @@ -35,7 +35,7 @@ struct LinkHostRequest { #[derive(Debug, Serialize)] struct LinkHostData { - host_installation_id: String, + host_device_id: String, host_installation_token: String, link: LinkSummary, } @@ -50,7 +50,7 @@ struct LinkSummary { #[derive(Debug, Deserialize)] struct UnlinkHostRequest { - host_installation_id: String, + host_device_id: String, } #[derive(Debug, Serialize)] @@ -60,11 +60,11 @@ struct ListHostsData { #[derive(Debug, Serialize)] struct HostSummary { - host_installation_id: String, + host_device_id: String, host_display_name: String, linked_at_ms: i64, online: bool, - /// Durable last activity from `device_installations.last_seen_at_ms`. + /// Durable last activity from `devices.last_seen_at_ms`. /// Live online is `registry`; cold path is this timestamp. last_seen_at_ms: i64, } @@ -79,7 +79,7 @@ async fn post_link( (s, err_body("unauthorized", m)) })?; - let caller_installation_id = uuid::Uuid::parse_str(&bearer_outcome.device_id) + let caller_device_id = uuid::Uuid::parse_str(&bearer_outcome.device_id) .map(DeviceId) .map_err(|_| { ( @@ -87,7 +87,7 @@ async fn post_link( err_body("unauthorized", "invalid bearer device id"), ) })?; - ensure_account_client(&state, caller_installation_id, &bearer_outcome.account_id).await?; + ensure_account_client(&state, caller_device_id, &bearer_outcome.account_id).await?; let display_name = req .host_display_name @@ -96,11 +96,11 @@ async fn post_link( .filter(|name| !name.is_empty()) .unwrap_or("host"); - let installation_id = host_bootstrap::verify_and_register( + let device_id = host_bootstrap::verify_and_register( &state.store, state.bootstrap_nonces.as_ref(), HostBootstrapProof { - installation_id: &req.installation_id, + device_id: &req.device_id, nonce: &req.nonce, public_key: req.public_key.as_deref(), signature: &req.signature, @@ -115,9 +115,9 @@ async fn post_link( let outcome = state .host_link .link_host( - installation_id, + device_id, &bearer_outcome.account_id, - caller_installation_id, + caller_device_id, Some(display_name), ) .await @@ -128,7 +128,7 @@ async fn post_link( Ok(Json(ResponseEnvelope::new( LinkHostData { - host_installation_id: outcome.host_installation_id.to_string(), + host_device_id: outcome.host_device_id.to_string(), host_installation_token: outcome.host_installation_token, link: LinkSummary { pair_id: outcome.link.pair_id, @@ -154,12 +154,12 @@ async fn post_unlink( (s, err_body("unauthorized", m)) })?; - let host_installation_id = uuid::Uuid::parse_str(&req.host_installation_id) + let host_device_id = uuid::Uuid::parse_str(&req.host_device_id) .map(DeviceId) .map_err(|_| { ( StatusCode::BAD_REQUEST, - err_body("bad_request", "invalid host_installation_id"), + err_body("bad_request", "invalid host_device_id"), ) })?; @@ -167,7 +167,7 @@ async fn post_unlink( .host_link .unlink_host( state.registry.as_ref(), - host_installation_id, + host_device_id, &bearer_outcome.account_id, ) .await @@ -206,13 +206,13 @@ async fn get_hosts( let mut hosts = Vec::with_capacity(pairs.len()); for pair in pairs { - let row = crate::store::device_installations::get_device(&state.store, pair.host_device_id) + let row = crate::store::devices::get_device(&state.store, pair.host_device_id) .await .map_err(|e| { tracing::warn!( target: "minos_backend::v1::hosts", error = %e, - host_installation_id = %pair.host_device_id, + host_device_id = %pair.host_device_id, "get_device(host) failed", ); ( @@ -227,11 +227,11 @@ async fn get_hosts( .or_else(|| row.map(|r| r.display_name)) .unwrap_or_else(|| "unknown".to_string()); hosts.push(HostSummary { - host_installation_id: pair.host_device_id.to_string(), + host_device_id: pair.host_device_id.to_string(), host_display_name, linked_at_ms: pair.paired_at_ms, // **device online**: host installation has live `/ws/host`. - online: state.registry.get(pair.host_device_id).is_some(), + online: state.registry.get_host(pair.host_device_id).is_some(), last_seen_at_ms, }); } @@ -244,16 +244,16 @@ async fn get_hosts( async fn ensure_account_client( state: &BackendState, - installation_id: DeviceId, + device_id: DeviceId, account_id: &str, ) -> Result<(), (StatusCode, Json)> { - let row = crate::store::device_installations::get_device(&state.store, installation_id) + let row = crate::store::devices::get_device(&state.store, device_id) .await .map_err(|e| { tracing::warn!( target: "minos_backend::v1::hosts", error = %e, - installation_id = %installation_id, + device_id = %device_id, "get_device(account caller) failed", ); ( diff --git a/crates/minos-backend/src/http/v1/notifications.rs b/crates/minos-backend/src/http/v1/notifications.rs index 87c8c5f3..d6f721e2 100644 --- a/crates/minos-backend/src/http/v1/notifications.rs +++ b/crates/minos-backend/src/http/v1/notifications.rs @@ -34,7 +34,7 @@ pub fn router() -> Router { #[derive(Debug, Deserialize)] struct RegisterTokenRequest { - installation_id: String, + device_id: String, kind: String, token: String, locale: Option, @@ -106,7 +106,7 @@ async fn register_token( .notifications .register_token(RegisterTokenInput { account_id, - installation_id: request.installation_id, + device_id: request.device_id, kind, token: request.token, locale: request.locale, diff --git a/crates/minos-backend/src/http/v1/realtime.rs b/crates/minos-backend/src/http/v1/realtime.rs index 70f066ad..efc048a9 100644 --- a/crates/minos-backend/src/http/v1/realtime.rs +++ b/crates/minos-backend/src/http/v1/realtime.rs @@ -20,7 +20,7 @@ use crate::http::BackendState; #[derive(Debug, Deserialize)] pub struct RealtimeWsTicketRequest { - pub installation_id: String, + pub device_id: String, } #[derive(Debug, Serialize)] @@ -42,25 +42,24 @@ async fn post_ws_ticket( let Ok(bearer_outcome) = bearer::require_account(&state, &headers) else { return (StatusCode::UNAUTHORIZED, err("unauthorized")).into_response(); }; - let installation_id = match Uuid::parse_str(&req.installation_id).map(DeviceId) { + let device_id = match Uuid::parse_str(&req.device_id).map(DeviceId) { Ok(id) => id, Err(_) => return (StatusCode::BAD_REQUEST, err("bad_request")).into_response(), }; - let row = - match crate::store::device_installations::get_device(&state.store, installation_id).await { - Ok(Some(row)) => row, - Ok(None) => return (StatusCode::UNAUTHORIZED, err("unauthorized")).into_response(), - Err(error) => { - tracing::warn!( - target: "minos_backend::v1::realtime", - error = %error, - installation_id = %req.installation_id, - "get_device failed while issuing formal ws ticket", - ); - return (StatusCode::INTERNAL_SERVER_ERROR, err("internal")).into_response(); - } - }; + let row = match crate::store::devices::get_device(&state.store, device_id).await { + Ok(Some(row)) => row, + Ok(None) => return (StatusCode::UNAUTHORIZED, err("unauthorized")).into_response(), + Err(error) => { + tracing::warn!( + target: "minos_backend::v1::realtime", + error = %error, + device_id = %req.device_id, + "get_device failed while issuing formal ws ticket", + ); + return (StatusCode::INTERNAL_SERVER_ERROR, err("internal")).into_response(); + } + }; if row.account_id.as_deref() != Some(&bearer_outcome.account_id) || !row.role.is_account_client() @@ -70,7 +69,7 @@ async fn post_ws_ticket( match state .auth - .issue_ws_ticket(&bearer_outcome.account_id, installation_id, row.role) + .issue_ws_ticket(&bearer_outcome.account_id, device_id, row.role) .await { Ok(session) => { @@ -90,7 +89,7 @@ async fn post_ws_ticket( tracing::warn!( target: "minos_backend::v1::realtime", error = ?error, - installation_id = %req.installation_id, + device_id = %req.device_id, account_id = %bearer_outcome.account_id, "issue_ws_ticket failed", ); diff --git a/crates/minos-backend/src/http/v1/social.rs b/crates/minos-backend/src/http/v1/social.rs index c7677a17..01fa2f75 100644 --- a/crates/minos-backend/src/http/v1/social.rs +++ b/crates/minos-backend/src/http/v1/social.rs @@ -258,7 +258,7 @@ async fn runtime_port_inject( conversation_id: conversation_id.to_string(), project_id, agent_id: agent.agent_id.clone(), - host_installation_id: Some(host_device_id.to_string()), + host_device_id: Some(host_device_id.to_string()), workspace_path: agent.workspace_path.clone(), initial_user_message: Some(text.to_string()), origin_message_id: Some(origin_message_id.to_string()), @@ -390,7 +390,7 @@ async fn select_live_host_for_account( ) -> Result { let hosts = crate::store::host_links::list_hosts_for_account(&state.store, account_id).await?; for host in hosts { - if state.registry.get(host.host_device_id).is_some() { + if state.registry.get_host(host.host_device_id).is_some() { return Ok(host.host_device_id); } } @@ -2298,7 +2298,7 @@ async fn deliver_bot_inbox( tracing::warn!( target: "minos_backend::social", delivery_id = %row.dispatch_id, - host_installation_id = %host_device_id, + host_device_id = %host_device_id, error = %error, "failed to push BotInboxDelivery to host connection" ); diff --git a/crates/minos-backend/src/ingest/mod.rs b/crates/minos-backend/src/ingest/mod.rs index 948edbaf..133c568f 100644 --- a/crates/minos-backend/src/ingest/mod.rs +++ b/crates/minos-backend/src/ingest/mod.rs @@ -606,7 +606,7 @@ fn sanitize_title(text: &str) -> Option { #[cfg(test)] mod tests { use super::*; - use crate::store::device_installations::set_account_id; + use crate::store::devices::set_account_id; use crate::store::host_links; use crate::store::test_support::{ insert_account, insert_ios_device, insert_test_client, insert_test_host, memory_pool, T0, diff --git a/crates/minos-backend/src/jobs/stale_session_sweeper.rs b/crates/minos-backend/src/jobs/stale_session_sweeper.rs index 85584dfe..e492b3d3 100644 --- a/crates/minos-backend/src/jobs/stale_session_sweeper.rs +++ b/crates/minos-backend/src/jobs/stale_session_sweeper.rs @@ -16,8 +16,7 @@ use crate::config::RuntimeMode; use crate::http::BackendState; use crate::runtime::AppContext; use crate::store::{ - agent_sessions, device_installations, durable_event_log, outbox_events, AsStorePool, - StorePoolRef, + agent_sessions, devices, durable_event_log, outbox_events, AsStorePool, StorePoolRef, }; /// Host must be offline (no live WS) and last_seen older than this before @@ -84,7 +83,7 @@ impl Job for SessionLifecycleJob { struct OpenHostSession { session_id: String, conversation_id: String, - host_installation_id: String, + host_device_id: String, status: String, } @@ -98,22 +97,22 @@ async fn end_stale_host_sessions( let mut ended = 0u32; for row in rows { - let Ok(host_id) = Uuid::parse_str(&row.host_installation_id).map(DeviceId) else { + let Ok(host_id) = Uuid::parse_str(&row.host_device_id).map(DeviceId) else { tracing::warn!( target: "minos_backend::session_lifecycle", session_id = %row.session_id, - host = %row.host_installation_id, - "skip session with invalid host_installation_id" + host = %row.host_device_id, + "skip session with invalid host_device_id" ); continue; }; // Live WS ⇒ host is present; never force-end. - if state.registry.get(host_id).is_some() { + if state.registry.get_host(host_id).is_some() { continue; } - let last_seen = match device_installations::get_device(&state.store, host_id).await? { + let last_seen = match devices::get_device(&state.store, host_id).await? { Some(dev) => dev.last_seen_at, None => 0, }; @@ -127,7 +126,7 @@ async fn end_stale_host_sessions( target: "minos_backend::session_lifecycle", session_id = %row.session_id, conversation_id = %row.conversation_id, - host = %row.host_installation_id, + host = %row.host_device_id, status_was = %row.status, last_seen_at_ms = last_seen, "ended stale host agent session" @@ -145,10 +144,10 @@ async fn list_open_host_sessions( match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { sqlx::query_as::<_, OpenHostSession>( - "SELECT session_id, conversation_id, host_installation_id, status + "SELECT session_id, conversation_id, host_device_id, status FROM agent_sessions WHERE status IN ('pending', 'running', 'stopping') - AND host_installation_id IS NOT NULL + AND host_device_id IS NOT NULL AND ended_at_ms IS NULL ORDER BY started_at_ms ASC LIMIT ?", @@ -159,10 +158,10 @@ async fn list_open_host_sessions( } StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, OpenHostSession>( - "SELECT session_id, conversation_id, host_installation_id, status + "SELECT session_id, conversation_id, host_device_id, status FROM agent_sessions WHERE status IN ('pending', 'running', 'stopping') - AND host_installation_id IS NOT NULL + AND host_device_id IS NOT NULL AND ended_at_ms IS NULL ORDER BY started_at_ms ASC LIMIT $1", @@ -367,7 +366,7 @@ mod tests { let (tx, _rx) = tokio::sync::mpsc::channel(8); let conn = std::sync::Arc::new(crate::realtime::ConnectionState::new( minos_protocol::realtime::ConnectionPrincipal::Host { - host_installation_id: host.to_string(), + host_device_id: host.to_string(), }, host, DeviceRole::AgentHost, diff --git a/crates/minos-backend/src/notifications/use_case.rs b/crates/minos-backend/src/notifications/use_case.rs index 1be5d6a1..f90ce29f 100644 --- a/crates/minos-backend/src/notifications/use_case.rs +++ b/crates/minos-backend/src/notifications/use_case.rs @@ -24,7 +24,7 @@ use crate::store::{ /// window so flaky reconnects do not flood the user. /// /// Grace is based on registry-stamped disconnect time (real WS leave edge), -/// **not** throttled `device_installations.last_seen` (which can lag 30s+). +/// **not** throttled `devices.last_seen` (which can lag 30s+). pub const DISCONNECT_GRACE_MS: i64 = 15_000; // ── Presence port ────────────────────────────────────────────────────── @@ -65,7 +65,7 @@ impl PresencePort for OfflinePresence { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RegisterTokenInput { pub account_id: String, - pub installation_id: String, + pub device_id: String, pub kind: PushKind, pub token: String, pub locale: Option, @@ -92,7 +92,7 @@ pub struct UpdatePreferencesInput { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PushTokenDto { pub token_hash: String, - pub installation_id: String, + pub device_id: String, pub kind: PushKind, pub locale: Option, pub created_at_ms: i64, @@ -255,7 +255,7 @@ impl NotificationService for DefaultNotificationService { push_tokens::upsert( &self.store, &input.account_id, - &input.installation_id, + &input.device_id, input.kind.as_str(), &input.token, input.locale.as_deref(), @@ -281,7 +281,7 @@ impl NotificationService for DefaultNotificationService { .into_iter() .map(|r| PushTokenDto { token_hash: r.token_hash, - installation_id: r.installation_id, + device_id: r.device_id, kind: match r.kind.as_str() { "apns" => PushKind::Apns, _ => PushKind::Fcm, @@ -661,16 +661,16 @@ mod tests { async fn seed_account_with_token( store: &StoreHandle, email: &str, - ) -> (String, String /* installation_id */) { + ) -> (String, String /* device_id */) { let account_id = insert_account(store.sqlite_pool().unwrap(), email).await; - let installation_id = DeviceId::new().to_string(); + let device_id = DeviceId::new().to_string(); // Minimal installation so FK on push_tokens / device tables hold if needed. sqlx::query( - "INSERT INTO device_installations - (installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) + "INSERT INTO devices + (device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) VALUES (?, 'mobile', 'phone', NULL, ?, ?, ?)", ) - .bind(&installation_id) + .bind(&device_id) .bind(T0) .bind(T0 - 60_000) // outside grace .bind(&account_id) @@ -681,7 +681,7 @@ mod tests { push_tokens::upsert( store, &account_id, - &installation_id, + &device_id, "fcm", "test-fcm-token-value-xxxxxxxxxxxxxxxx", None, @@ -690,7 +690,7 @@ mod tests { .await .unwrap(); - (account_id, installation_id) + (account_id, device_id) } fn account_message_envelope(account_id: &str, event_id: &str) -> DurableEventEnvelope { diff --git a/crates/minos-backend/src/realtime/auth.rs b/crates/minos-backend/src/realtime/auth.rs index 735d643a..4dcc5004 100644 --- a/crates/minos-backend/src/realtime/auth.rs +++ b/crates/minos-backend/src/realtime/auth.rs @@ -75,27 +75,17 @@ pub async fn authorize_subscription( Err(SubscriptionDenied::Forbidden.into()) } } - ( - ConnectionPrincipal::Host { - host_installation_id, - }, - RealtimeTopic::Host(target_host_id), - ) => { - if target_host_id == host_installation_id { + (ConnectionPrincipal::Host { host_device_id }, RealtimeTopic::Host(target_host_id)) => { + if target_host_id == host_device_id { Ok(()) } else { Err(SubscriptionDenied::Forbidden.into()) } } - ( - ConnectionPrincipal::Host { - host_installation_id, - }, - RealtimeTopic::AgentSession(session_id), - ) => { + (ConnectionPrincipal::Host { host_device_id }, RealtimeTopic::AgentSession(session_id)) => { let session = store::agent_sessions::get(store, session_id).await?; if session.and_then(|row| row.host_device_id).as_deref() - == Some(host_installation_id.as_str()) + == Some(host_device_id.as_str()) { Ok(()) } else { @@ -205,7 +195,7 @@ mod tests { .unwrap(); let principal = ConnectionPrincipal::Host { - host_installation_id: host_id.to_string(), + host_device_id: host_id.to_string(), }; authorize_subscription(&pool, &principal, &RealtimeTopic::Host(host_id.to_string())) diff --git a/crates/minos-backend/src/realtime/connection_registry.rs b/crates/minos-backend/src/realtime/connection_registry.rs index 12d81c02..34d2e80c 100644 --- a/crates/minos-backend/src/realtime/connection_registry.rs +++ b/crates/minos-backend/src/realtime/connection_registry.rs @@ -12,15 +12,40 @@ use std::sync::Arc; use dashmap::DashMap; use minos_domain::{DeviceId, DeviceRole}; +use minos_protocol::realtime::ConnectionPrincipal; use super::subscription::ConnectionState; pub use super::subscription::ConnectionRevocation; -/// Concurrent map of `DeviceId →` current formal connection. +/// One physical DeviceId may hold both an Account IM socket and a Host +/// runtime socket. Kick-old is per rail, not per UUID. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ConnectionRail { + Account, + Host, +} + +impl ConnectionRail { + #[must_use] + pub fn from_principal(principal: &ConnectionPrincipal) -> Self { + match principal { + ConnectionPrincipal::Account { .. } => Self::Account, + ConnectionPrincipal::Host { .. } => Self::Host, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +struct RegistryKey { + rail: ConnectionRail, + device_id: DeviceId, +} + +/// Concurrent map of `(rail, DeviceId) →` current formal connection. #[derive(Debug, Clone, Default)] pub struct RealtimeConnectionRegistry { - connections: Arc>>, + connections: Arc>>, /// account_id → wall-clock ms of last "last mobile client left" edge. last_mobile_disconnect_at_ms: Arc>, } @@ -42,7 +67,11 @@ impl RealtimeConnectionRegistry { self.last_mobile_disconnect_at_ms.remove(account_id); } } - let previous = self.connections.insert(conn.device_id, conn); + let key = RegistryKey { + rail: ConnectionRail::from_principal(&conn.principal), + device_id: conn.device_id, + }; + let previous = self.connections.insert(key, conn); crate::telemetry::set_session_registry_size(self.len()); if let Some(ref prev) = previous { self.note_mobile_connection_left(prev); @@ -50,9 +79,15 @@ impl RealtimeConnectionRegistry { previous } - /// Remove and return the connection for `id`, or `None` if none was live. - pub fn remove(&self, id: DeviceId) -> Option> { - let removed = self.connections.remove(&id).map(|(_k, v)| v); + /// Remove and return the connection for `id` on `rail`, or `None`. + pub fn remove_rail(&self, rail: ConnectionRail, id: DeviceId) -> Option> { + let removed = self + .connections + .remove(&RegistryKey { + rail, + device_id: id, + }) + .map(|(_k, v)| v); if let Some(ref conn) = removed { crate::telemetry::set_session_registry_size(self.len()); self.note_mobile_connection_left(conn); @@ -60,14 +95,24 @@ impl RealtimeConnectionRegistry { removed } + /// Remove the Account-rail connection for `id` (tests / mobile grace). + pub fn remove(&self, id: DeviceId) -> Option> { + self.remove_rail(ConnectionRail::Account, id) + .or_else(|| self.remove_rail(ConnectionRail::Host, id)) + } + /// Remove and return `current` only if it is still the live entry. /// /// ABA-safe disconnect cleanup: an old socket may close after a /// reconnect already inserted a replacement for the same `DeviceId`. pub fn remove_current(&self, current: &ConnectionState) -> Option> { + let key = RegistryKey { + rail: ConnectionRail::from_principal(¤t.principal), + device_id: current.device_id, + }; let removed = self .connections - .remove_if(¤t.device_id, |_, live| live.same_connection(current)) + .remove_if(&key, |_, live| live.same_connection(current)) .map(|(_k, v)| v); if let Some(ref conn) = removed { crate::telemetry::set_session_registry_size(self.len()); @@ -76,23 +121,44 @@ impl RealtimeConnectionRegistry { removed } - /// Clone the current connection for `id` if live. + /// Clone the current connection for `rail` + `id` if live. + #[must_use] + pub fn get_rail(&self, rail: ConnectionRail, id: DeviceId) -> Option> { + self.connections + .get(&RegistryKey { + rail, + device_id: id, + }) + .map(|r| Arc::clone(r.value())) + } + + /// Live Host-rail socket for this DeviceId (bot execution / host online). + #[must_use] + pub fn get_host(&self, id: DeviceId) -> Option> { + self.get_rail(ConnectionRail::Host, id) + } + + /// Live Account-rail socket for this DeviceId. + #[must_use] + pub fn get_account(&self, id: DeviceId) -> Option> { + self.get_rail(ConnectionRail::Account, id) + } + + /// Prefer Host rail, then Account — used by tests that insert a single role. #[must_use] pub fn get(&self, id: DeviceId) -> Option> { - self.connections.get(&id).map(|r| Arc::clone(r.value())) + self.get_host(id).or_else(|| self.get_account(id)) } - /// True when a formal connection is live for `id`. + /// True when a Host-rail connection is live for `id`. #[must_use] pub fn is_online(&self, id: DeviceId) -> bool { - self.connections.contains_key(&id) + self.get_host(id).is_some() } - /// Revoke and remove the live connection for `device_id` if present. - /// - /// Returns `true` when a connection was revoked. + /// Revoke the Host-rail connection (unlink / token revoke). pub fn revoke_device(&self, device_id: DeviceId, reason: ConnectionRevocation) -> bool { - let Some(conn) = self.remove(device_id) else { + let Some(conn) = self.remove_rail(ConnectionRail::Host, device_id) else { return false; }; conn.revoke(reason); @@ -104,9 +170,11 @@ impl RealtimeConnectionRegistry { /// Does not wait for sockets to drain; the gateway loop reacts to /// the revocation watch and closes each formal connection. pub fn revoke_all(&self, reason: ConnectionRevocation) { - let ids: Vec = self.connections.iter().map(|e| *e.key()).collect(); - for id in ids { - let _ = self.revoke_device(id, reason); + let keys: Vec = self.connections.iter().map(|e| *e.key()).collect(); + for key in keys { + if let Some(conn) = self.remove_rail(key.rail, key.device_id) { + conn.revoke(reason); + } } } @@ -193,7 +261,7 @@ mod tests { let (tx, _rx) = mpsc::channel::(8); let principal = match role { DeviceRole::AgentHost => ConnectionPrincipal::Host { - host_installation_id: device_id.to_string(), + host_device_id: device_id.to_string(), }, _ => ConnectionPrincipal::Account { account_id: account_id.unwrap_or("acct-1").to_string(), @@ -248,6 +316,21 @@ mod tests { assert_eq!(reg.mobile_client_session_count("acct"), 0); } + #[test] + fn account_and_host_share_device_id_without_kick() { + let reg = RealtimeConnectionRegistry::new(); + let id = DeviceId::new(); + let account = make_conn(id, DeviceRole::DesktopConsole, Some("acct")); + let host = make_conn(id, DeviceRole::AgentHost, None); + assert!(reg.insert(Arc::clone(&account)).is_none()); + assert!(reg.insert(Arc::clone(&host)).is_none()); + assert!(reg.get_account(id).unwrap().same_connection(&account)); + assert!(reg.get_host(id).unwrap().same_connection(&host)); + assert!(reg.remove_current(&account).is_some()); + assert!(reg.get_host(id).is_some()); + assert!(reg.get_account(id).is_none()); + } + #[test] fn revoke_device_signals_and_evicts() { let reg = RealtimeConnectionRegistry::new(); diff --git a/crates/minos-backend/src/realtime/gateway.rs b/crates/minos-backend/src/realtime/gateway.rs index b0ea96c9..2238662d 100644 --- a/crates/minos-backend/src/realtime/gateway.rs +++ b/crates/minos-backend/src/realtime/gateway.rs @@ -76,15 +76,124 @@ enum ActivationAuthError { pub async fn upgrade_client( State(state): State, Query(query): Query, + headers: HeaderMap, ws: WebSocketUpgrade, ) -> Result { - let result = upgrade_with_ticket(state, query, ws, GatewayRail::Client).await; + // Native clients (Desktop Rust) send Authorization: Bearer . + // Browsers still use a one-shot ticket in the query string. + let result = if bearer_token_from_headers(&headers).is_some() { + upgrade_client_with_bearer(state, headers, ws).await + } else { + upgrade_with_ticket(state, query, ws, GatewayRail::Client).await + }; if result.is_err() { crate::telemetry::record_ws_connect("preauth", crate::telemetry::OUTCOME_UNAUTHORIZED); } result } +async fn upgrade_client_with_bearer( + state: BackendState, + headers: HeaderMap, + ws: WebSocketUpgrade, +) -> Result { + let outcome = crate::auth::bearer::require_account(&state, &headers) + .map_err(|error| error.into_response_tuple())?; + let device_id = Uuid::parse_str(&outcome.device_id) + .map(DeviceId) + .map_err(|_| { + ( + StatusCode::UNAUTHORIZED, + "invalid bearer device_id".to_string(), + ) + })?; + let request_span = tracing::Span::current(); + let account_id = outcome.account_id; + Ok(ws.on_upgrade(move |mut socket| { + let state = state.clone(); + async move { + match revalidate_account_bearer_auth(&state.store, device_id, &account_id).await { + Ok(role) => { + Box::pin(run_session( + socket, + state, + GatewayUpgrade { + device_id, + role, + principal: ConnectionPrincipal::Account { + account_id: account_id.clone(), + }, + }, + )) + .await; + } + Err(ActivationAuthError::Unauthorized(message)) => { + close_with_directive( + &mut socket, + DeviceRole::DesktopConsole, + CloseDirective { + code: CLOSE_CODE_AUTH_REVOKED, + reason: "auth_revoked", + }, + ) + .await; + tracing::info!( + target: "minos_backend::realtime", + device_id = %device_id, + reason = %message, + "account bearer auth changed before activation; closing 4401" + ); + } + Err(ActivationAuthError::Internal(message)) => { + close_with_directive( + &mut socket, + DeviceRole::DesktopConsole, + CloseDirective { + code: CLOSE_CODE_INTERNAL_ERROR, + reason: "activation_revalidate_failed", + }, + ) + .await; + tracing::warn!( + target: "minos_backend::realtime", + device_id = %device_id, + error = %message, + "account bearer activation revalidation failed" + ); + } + } + } + .instrument(request_span) + })) +} + +async fn revalidate_account_bearer_auth( + store: &crate::store::StoreHandle, + device_id: DeviceId, + account_id: &str, +) -> Result { + let row = crate::store::devices::get_device(store, device_id) + .await + .map_err(|error| ActivationAuthError::Internal(error.to_string()))? + .ok_or_else(|| { + ActivationAuthError::Unauthorized( + "device row missing during websocket activation".to_string(), + ) + })?; + if !row.role.is_account_client() { + return Err(ActivationAuthError::Unauthorized(format!( + "device role is not an account client: {}", + row.role + ))); + } + if row.account_id.as_deref() != Some(account_id) { + return Err(ActivationAuthError::Unauthorized( + "device account changed during websocket activation".to_string(), + )); + } + Ok(row.role) +} + pub async fn upgrade_host( State(state): State, Query(_query): Query, @@ -122,8 +231,8 @@ async fn upgrade_host_with_bearer( let principal = crate::auth::host_installation::require(&state, &headers) .await .map_err(|error| error.into_response_tuple())?; - let device_id = principal.host_installation_id; - let host_installation_id = device_id.to_string(); + let device_id = principal.device_id; + let host_device_id = device_id.to_string(); let request_span = tracing::Span::current(); Ok(ws.on_upgrade(move |mut socket| { let state = state.clone(); @@ -136,9 +245,7 @@ async fn upgrade_host_with_bearer( GatewayUpgrade { device_id, role: DeviceRole::AgentHost, - principal: ConnectionPrincipal::Host { - host_installation_id, - }, + principal: ConnectionPrincipal::Host { host_device_id }, }, )) .await; @@ -244,7 +351,7 @@ async fn upgrade_with_ticket( let principal = if claims.role == DeviceRole::AgentHost { ConnectionPrincipal::Host { - host_installation_id: claims.did.clone(), + host_device_id: claims.did.clone(), } } else { ConnectionPrincipal::Account { @@ -312,7 +419,7 @@ async fn revalidate_host_installation_auth( store: &crate::store::StoreHandle, device_id: DeviceId, ) -> Result<(), ActivationAuthError> { - let row = crate::store::device_installations::get_device(store, device_id) + let row = crate::store::devices::get_device(store, device_id) .await .map_err(|error| ActivationAuthError::Internal(error.to_string()))? .ok_or_else(|| { @@ -336,7 +443,7 @@ async fn revalidate_ws_ticket_auth( let device_id = Uuid::parse_str(&claims.did) .map(DeviceId) .map_err(|_| ActivationAuthError::Unauthorized("invalid ws_ticket device_id".into()))?; - let row = crate::store::device_installations::get_device(store, device_id) + let row = crate::store::devices::get_device(store, device_id) .await .map_err(|error| ActivationAuthError::Internal(error.to_string()))? .ok_or_else(|| { @@ -384,9 +491,9 @@ impl GatewayUpgrade { ConnectionPrincipal::Account { account_id } => { RealtimeTopic::Account(account_id.clone()) } - ConnectionPrincipal::Host { - host_installation_id, - } => RealtimeTopic::Host(host_installation_id.clone()), + ConnectionPrincipal::Host { host_device_id } => { + RealtimeTopic::Host(host_device_id.clone()) + } } } } @@ -473,7 +580,9 @@ pub async fn run_session(mut ws: WebSocket, state: BackendState, upgrade: Gatewa // Skip offline fanout when a newer connection already owns the device // (connection superseded / reconnect race). Unlink/auth revoke that already // cleared the registry still publishes offline (get is None). - if state.registry.get(upgrade.device_id).is_none() { + let rail = + crate::realtime::connection_registry::ConnectionRail::from_principal(&upgrade.principal); + if state.registry.get_rail(rail, upgrade.device_id).is_none() { presence::publish_connection_presence( &state, upgrade.device_id, @@ -700,7 +809,7 @@ async fn note_connection_activity( if !liveness::should_persist_last_seen(last_db_touch.elapsed(), LAST_SEEN_DB_MIN_INTERVAL) { return; } - if let Err(error) = crate::store::device_installations::touch_last_seen( + if let Err(error) = crate::store::devices::touch_last_seen( &state.store, &upgrade.device_id, chrono::Utc::now().timestamp_millis(), diff --git a/crates/minos-backend/src/realtime/presence.rs b/crates/minos-backend/src/realtime/presence.rs index 255192cf..0dce4d84 100644 --- a/crates/minos-backend/src/realtime/presence.rs +++ b/crates/minos-backend/src/realtime/presence.rs @@ -1,7 +1,7 @@ //! Installation presence fanout for the formal IM gateway. //! //! Online is live-connection truth (`RealtimeConnectionRegistry` / active WS). -//! `last_seen_at_ms` is durable on `device_installations` and returned on +//! `last_seen_at_ms` is durable on `devices` and returned on //! HTTP list endpoints. Presence pushes are **ephemeral** `StreamEvent`s //! (`kind = presence`) — not DurableEvent log entries. @@ -25,7 +25,7 @@ pub async fn publish_connection_presence( ) { let at_ms = chrono::Utc::now().timestamp_millis(); if let Err(error) = - crate::store::device_installations::touch_last_seen(&state.store, &device_id, at_ms).await + crate::store::devices::touch_last_seen(&state.store, &device_id, at_ms).await { tracing::debug!( target: "minos_backend::realtime::presence", @@ -37,7 +37,7 @@ pub async fn publish_connection_presence( } let payload = PresencePayload { - installation_id: device_id.to_string(), + device_id: device_id.to_string(), principal_kind: presence_principal_kind(role), online, last_seen_at_ms: at_ms, @@ -125,7 +125,7 @@ mod tests { #[test] fn presence_payload_round_trips() { let payload = PresencePayload { - installation_id: "11111111-1111-1111-1111-111111111111".into(), + device_id: "11111111-1111-1111-1111-111111111111".into(), principal_kind: PresencePrincipalKind::Host, online: true, last_seen_at_ms: 100, diff --git a/crates/minos-backend/src/store/agent_dispatch_queue.rs b/crates/minos-backend/src/store/agent_dispatch_queue.rs index 22855272..74eca57a 100644 --- a/crates/minos-backend/src/store/agent_dispatch_queue.rs +++ b/crates/minos-backend/src/store/agent_dispatch_queue.rs @@ -1055,7 +1055,7 @@ where pub async fn set_lease( store: &S, delivery_id: &str, - host_installation_id: &str, + host_device_id: &str, lease_expires_at_ms: i64, now_ms: i64, ) -> Result<(), BackendError> @@ -1071,7 +1071,7 @@ where updated_at_ms = ?3 WHERE dispatch_id = ?4", ) - .bind(host_installation_id) + .bind(host_device_id) .bind(lease_expires_at_ms) .bind(now_ms) .bind(delivery_id) @@ -1088,7 +1088,7 @@ where updated_at_ms = $3 WHERE dispatch_id = $4", ) - .bind(host_installation_id) + .bind(host_device_id) .bind(lease_expires_at_ms) .bind(now_ms) .bind(delivery_id) @@ -1104,7 +1104,7 @@ where pub async fn renew_lease( store: &S, delivery_id: &str, - host_installation_id: &str, + host_device_id: &str, lease_expires_at_ms: i64, now_ms: i64, ) -> Result @@ -1125,7 +1125,7 @@ where .bind(now_ms) .bind(delivery_id) .bind(STATUS_INFLIGHT) - .bind(host_installation_id) + .bind(host_device_id) .execute(pool) .await .map_err(store_err("agent_dispatch_queue::renew_lease"))?; @@ -1144,7 +1144,7 @@ where .bind(now_ms) .bind(delivery_id) .bind(STATUS_INFLIGHT) - .bind(host_installation_id) + .bind(host_device_id) .execute(pool) .await .map_err(store_err("agent_dispatch_queue::renew_lease"))?; @@ -1153,10 +1153,10 @@ where } } -/// Renew every inflight lease owned by `host_installation_id` (host keepalive / Ping). +/// Renew every inflight lease owned by `host_device_id` (host keepalive / Ping). pub async fn renew_leases_for_host( store: &S, - host_installation_id: &str, + host_device_id: &str, lease_expires_at_ms: i64, now_ms: i64, ) -> Result @@ -1175,7 +1175,7 @@ where .bind(lease_expires_at_ms) .bind(now_ms) .bind(STATUS_INFLIGHT) - .bind(host_installation_id) + .bind(host_device_id) .execute(pool) .await .map_err(store_err("agent_dispatch_queue::renew_leases_for_host"))?; @@ -1192,7 +1192,7 @@ where .bind(lease_expires_at_ms) .bind(now_ms) .bind(STATUS_INFLIGHT) - .bind(host_installation_id) + .bind(host_device_id) .execute(pool) .await .map_err(store_err("agent_dispatch_queue::renew_leases_for_host"))?; diff --git a/crates/minos-backend/src/store/agent_sessions.rs b/crates/minos-backend/src/store/agent_sessions.rs index 55149494..0619ce5f 100644 --- a/crates/minos-backend/src/store/agent_sessions.rs +++ b/crates/minos-backend/src/store/agent_sessions.rs @@ -32,7 +32,7 @@ pub async fn create( StorePoolRef::Sqlite(pool) => { sqlx::query( "INSERT INTO agent_sessions - (session_id, conversation_id, project_id, host_installation_id, agent_id, status, started_at_ms, ended_at_ms) + (session_id, conversation_id, project_id, host_device_id, agent_id, status, started_at_ms, ended_at_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", ) .bind(session_id) @@ -50,7 +50,7 @@ pub async fn create( StorePoolRef::Postgres(pool) => { sqlx::query( "INSERT INTO agent_sessions - (session_id, conversation_id, project_id, host_installation_id, agent_id, status, started_at_ms, ended_at_ms) + (session_id, conversation_id, project_id, host_device_id, agent_id, status, started_at_ms, ended_at_ms) VALUES ($1, $2, $3, $4, $5, $6::agent_session_status, $7, $8)", ) .bind(session_id) @@ -83,7 +83,7 @@ pub async fn get( match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT session_id, conversation_id, project_id, host_installation_id AS host_device_id, agent_id, status, started_at_ms, ended_at_ms + "SELECT session_id, conversation_id, project_id, host_device_id AS host_device_id, agent_id, status, started_at_ms, ended_at_ms FROM agent_sessions WHERE session_id = ?", ) @@ -93,7 +93,7 @@ pub async fn get( } StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT session_id, conversation_id, project_id, host_installation_id AS host_device_id, agent_id, status::text, started_at_ms, ended_at_ms + "SELECT session_id, conversation_id, project_id, host_device_id AS host_device_id, agent_id, status::text, started_at_ms, ended_at_ms FROM agent_sessions WHERE session_id = $1", ) @@ -113,7 +113,7 @@ pub async fn get_for_account( match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT s.session_id, s.conversation_id, s.project_id, s.host_installation_id AS host_device_id, s.agent_id, s.status, s.started_at_ms, s.ended_at_ms + "SELECT s.session_id, s.conversation_id, s.project_id, s.host_device_id AS host_device_id, s.agent_id, s.status, s.started_at_ms, s.ended_at_ms FROM agent_sessions s JOIN conversation_members cm ON cm.conversation_id = s.conversation_id @@ -127,7 +127,7 @@ pub async fn get_for_account( } StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT s.session_id, s.conversation_id, s.project_id, s.host_installation_id AS host_device_id, s.agent_id, s.status::text, s.started_at_ms, s.ended_at_ms + "SELECT s.session_id, s.conversation_id, s.project_id, s.host_device_id AS host_device_id, s.agent_id, s.status::text, s.started_at_ms, s.ended_at_ms FROM agent_sessions s JOIN conversation_members cm ON cm.conversation_id = s.conversation_id @@ -151,7 +151,7 @@ pub async fn latest_for_account_conversation( match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT s.session_id, s.conversation_id, s.project_id, s.host_installation_id AS host_device_id, s.agent_id, s.status, s.started_at_ms, s.ended_at_ms + "SELECT s.session_id, s.conversation_id, s.project_id, s.host_device_id AS host_device_id, s.agent_id, s.status, s.started_at_ms, s.ended_at_ms FROM agent_sessions s JOIN conversation_members cm ON cm.conversation_id = s.conversation_id @@ -167,7 +167,7 @@ pub async fn latest_for_account_conversation( } StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT s.session_id, s.conversation_id, s.project_id, s.host_installation_id AS host_device_id, s.agent_id, s.status::text, s.started_at_ms, s.ended_at_ms + "SELECT s.session_id, s.conversation_id, s.project_id, s.host_device_id AS host_device_id, s.agent_id, s.status::text, s.started_at_ms, s.ended_at_ms FROM agent_sessions s JOIN conversation_members cm ON cm.conversation_id = s.conversation_id @@ -194,7 +194,7 @@ pub async fn list_for_account( match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT s.session_id, s.conversation_id, s.project_id, s.host_installation_id AS host_device_id, s.agent_id, s.status, s.started_at_ms, s.ended_at_ms + "SELECT s.session_id, s.conversation_id, s.project_id, s.host_device_id AS host_device_id, s.agent_id, s.status, s.started_at_ms, s.ended_at_ms FROM agent_sessions s JOIN conversation_members cm ON cm.conversation_id = s.conversation_id @@ -212,7 +212,7 @@ pub async fn list_for_account( } StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT s.session_id, s.conversation_id, s.project_id, s.host_installation_id AS host_device_id, s.agent_id, s.status::text, s.started_at_ms, s.ended_at_ms + "SELECT s.session_id, s.conversation_id, s.project_id, s.host_device_id AS host_device_id, s.agent_id, s.status::text, s.started_at_ms, s.ended_at_ms FROM agent_sessions s JOIN conversation_members cm ON cm.conversation_id = s.conversation_id @@ -242,7 +242,7 @@ pub async fn list_for_account_conversation( match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT s.session_id, s.conversation_id, s.project_id, s.host_installation_id AS host_device_id, s.agent_id, s.status, s.started_at_ms, s.ended_at_ms + "SELECT s.session_id, s.conversation_id, s.project_id, s.host_device_id AS host_device_id, s.agent_id, s.status, s.started_at_ms, s.ended_at_ms FROM agent_sessions s JOIN conversation_members cm ON cm.conversation_id = s.conversation_id @@ -262,7 +262,7 @@ pub async fn list_for_account_conversation( } StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT s.session_id, s.conversation_id, s.project_id, s.host_installation_id AS host_device_id, s.agent_id, s.status::text, s.started_at_ms, s.ended_at_ms + "SELECT s.session_id, s.conversation_id, s.project_id, s.host_device_id AS host_device_id, s.agent_id, s.status::text, s.started_at_ms, s.ended_at_ms FROM agent_sessions s JOIN conversation_members cm ON cm.conversation_id = s.conversation_id @@ -294,7 +294,7 @@ pub async fn list_for_account_project( match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT s.session_id, s.conversation_id, s.project_id, s.host_installation_id AS host_device_id, s.agent_id, s.status, s.started_at_ms, s.ended_at_ms + "SELECT s.session_id, s.conversation_id, s.project_id, s.host_device_id AS host_device_id, s.agent_id, s.status, s.started_at_ms, s.ended_at_ms FROM agent_sessions s JOIN conversation_members cm ON cm.conversation_id = s.conversation_id @@ -314,7 +314,7 @@ pub async fn list_for_account_project( } StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT s.session_id, s.conversation_id, s.project_id, s.host_installation_id AS host_device_id, s.agent_id, s.status::text, s.started_at_ms, s.ended_at_ms + "SELECT s.session_id, s.conversation_id, s.project_id, s.host_device_id AS host_device_id, s.agent_id, s.status::text, s.started_at_ms, s.ended_at_ms FROM agent_sessions s JOIN conversation_members cm ON cm.conversation_id = s.conversation_id @@ -452,7 +452,7 @@ pub async fn latest_reusable_for_conversation_agent( let rows = match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT s.session_id, s.conversation_id, s.project_id, s.host_installation_id AS host_device_id, s.agent_id, s.status, s.started_at_ms, s.ended_at_ms + "SELECT s.session_id, s.conversation_id, s.project_id, s.host_device_id AS host_device_id, s.agent_id, s.status, s.started_at_ms, s.ended_at_ms FROM agent_sessions s WHERE s.conversation_id = ? AND s.ended_at_ms IS NULL @@ -473,7 +473,7 @@ pub async fn latest_reusable_for_conversation_agent( } StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT s.session_id, s.conversation_id, s.project_id, s.host_installation_id AS host_device_id, s.agent_id, s.status::text, s.started_at_ms, s.ended_at_ms + "SELECT s.session_id, s.conversation_id, s.project_id, s.host_device_id AS host_device_id, s.agent_id, s.status::text, s.started_at_ms, s.ended_at_ms FROM agent_sessions s WHERE s.conversation_id = $1 AND s.ended_at_ms IS NULL @@ -520,7 +520,7 @@ pub async fn find_reusable_by_short_id( let rows = match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT s.session_id, s.conversation_id, s.project_id, s.host_installation_id AS host_device_id, s.agent_id, s.status, s.started_at_ms, s.ended_at_ms + "SELECT s.session_id, s.conversation_id, s.project_id, s.host_device_id AS host_device_id, s.agent_id, s.status, s.started_at_ms, s.ended_at_ms FROM agent_sessions s WHERE s.conversation_id = ? AND s.ended_at_ms IS NULL @@ -541,7 +541,7 @@ pub async fn find_reusable_by_short_id( } StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, AgentSessionRow>( - "SELECT s.session_id, s.conversation_id, s.project_id, s.host_installation_id AS host_device_id, s.agent_id, s.status::text, s.started_at_ms, s.ended_at_ms + "SELECT s.session_id, s.conversation_id, s.project_id, s.host_device_id AS host_device_id, s.agent_id, s.status::text, s.started_at_ms, s.ended_at_ms FROM agent_sessions s WHERE s.conversation_id = $1 AND s.ended_at_ms IS NULL @@ -582,9 +582,9 @@ pub async fn claim_host_if_empty( match store.as_store_pool() { StorePoolRef::Sqlite(pool) => sqlx::query( "UPDATE agent_sessions - SET host_installation_id = ? + SET host_device_id = ? WHERE session_id = ? - AND host_installation_id IS NULL", + AND host_device_id IS NULL", ) .bind(host_device_id) .bind(session_id) @@ -593,9 +593,9 @@ pub async fn claim_host_if_empty( .map(|_| ()), StorePoolRef::Postgres(pool) => sqlx::query( "UPDATE agent_sessions - SET host_installation_id = $1 + SET host_device_id = $1 WHERE session_id = $2 - AND host_installation_id IS NULL", + AND host_device_id IS NULL", ) .bind(host_device_id) .bind(session_id) diff --git a/crates/minos-backend/src/store/approval_requests.rs b/crates/minos-backend/src/store/approval_requests.rs index 336edf03..9c0fee4a 100644 --- a/crates/minos-backend/src/store/approval_requests.rs +++ b/crates/minos-backend/src/store/approval_requests.rs @@ -111,7 +111,7 @@ pub async fn get( ) -> Result, BackendError> { let row = match store.as_store_pool() { StorePoolRef::Sqlite(pool) => sqlx::query_as::<_, ApprovalRequestDbRow>( - "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, COALESCE(s.host_installation_id, t.owner_device_id), ar.method, + "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, COALESCE(s.host_device_id, t.owner_device_id), ar.method, ar.params_json, ar.state, ar.deadline_at_ms, ar.created_at_ms, ar.resolved_at_ms, ar.resolution_json, ar.client_request_id FROM approval_requests ar @@ -126,7 +126,7 @@ pub async fn get( .await, StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, ApprovalRequestDbRow>( - "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, s.host_installation_id, + "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, s.host_device_id, ar.method, ar.params_json::text, ar.state::text, ar.deadline_at_ms, ar.created_at_ms, ar.resolved_at_ms, ar.resolution_json::text, ar.client_request_id @@ -156,7 +156,7 @@ pub async fn get_by_client_request_id( } let row = match store.as_store_pool() { StorePoolRef::Sqlite(pool) => sqlx::query_as::<_, ApprovalRequestDbRow>( - "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, COALESCE(s.host_installation_id, t.owner_device_id), ar.method, + "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, COALESCE(s.host_device_id, t.owner_device_id), ar.method, ar.params_json, ar.state, ar.deadline_at_ms, ar.created_at_ms, ar.resolved_at_ms, ar.resolution_json, ar.client_request_id FROM approval_requests ar @@ -171,7 +171,7 @@ pub async fn get_by_client_request_id( .await, StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, ApprovalRequestDbRow>( - "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, s.host_installation_id, + "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, s.host_device_id, ar.method, ar.params_json::text, ar.state::text, ar.deadline_at_ms, ar.created_at_ms, ar.resolved_at_ms, ar.resolution_json::text, ar.client_request_id @@ -272,7 +272,7 @@ pub async fn list_expired_pending( ) -> Result, BackendError> { let rows = match store.as_store_pool() { StorePoolRef::Sqlite(pool) => sqlx::query_as::<_, ApprovalRequestDbRow>( - "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, COALESCE(s.host_installation_id, t.owner_device_id), ar.method, + "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, COALESCE(s.host_device_id, t.owner_device_id), ar.method, ar.params_json, ar.state, ar.deadline_at_ms, ar.created_at_ms, ar.resolved_at_ms, ar.resolution_json, ar.client_request_id FROM approval_requests ar @@ -292,7 +292,7 @@ pub async fn list_expired_pending( .await, StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, ApprovalRequestDbRow>( - "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, s.host_installation_id, + "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, s.host_device_id, ar.method, ar.params_json::text, ar.state::text, ar.deadline_at_ms, ar.created_at_ms, ar.resolved_at_ms, ar.resolution_json::text, ar.client_request_id @@ -354,7 +354,7 @@ pub async fn timeout_pending_with_null_host( LEFT JOIN sessions t ON t.session_id = ar.agent_session_id WHERE ar.state = ? AND ar.deadline_at_ms <= ? - AND COALESCE(s.host_installation_id, t.owner_device_id) IS NULL + AND COALESCE(s.host_device_id, t.owner_device_id) IS NULL ORDER BY ar.deadline_at_ms ASC LIMIT ? )", @@ -375,7 +375,7 @@ pub async fn timeout_pending_with_null_host( JOIN agent_sessions s ON s.session_id = ar.agent_session_id WHERE ar.state = 'pending'::approval_state AND ar.deadline_at_ms <= $1 - AND s.host_installation_id IS NULL + AND s.host_device_id IS NULL ORDER BY ar.deadline_at_ms ASC LIMIT $3 ) @@ -438,7 +438,7 @@ pub async fn list_pending_for_hosts( let rows = match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { let mut builder = QueryBuilder::::new( - "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, COALESCE(s.host_installation_id, t.owner_device_id), ar.method, + "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, COALESCE(s.host_device_id, t.owner_device_id), ar.method, ar.params_json, ar.state, ar.deadline_at_ms, ar.created_at_ms, ar.resolved_at_ms, ar.resolution_json, ar.client_request_id FROM approval_requests ar @@ -449,7 +449,7 @@ pub async fn list_pending_for_hosts( WHERE ar.state = ", ); builder.push_bind(ApprovalRequestState::Pending.as_str()); - builder.push(" AND COALESCE(s.host_installation_id, t.owner_device_id) IN ("); + builder.push(" AND COALESCE(s.host_device_id, t.owner_device_id) IN ("); { let mut separated = builder.separated(", "); for host_device_id in host_device_ids { @@ -465,7 +465,7 @@ pub async fn list_pending_for_hosts( } StorePoolRef::Postgres(pool) => { let mut builder = QueryBuilder::::new( - "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, s.host_installation_id, + "SELECT ar.request_id, ar.agent_session_id, ar.turn_id, s.host_device_id, ar.method, ar.params_json::text, ar.state::text, ar.deadline_at_ms, ar.created_at_ms, ar.resolved_at_ms, ar.resolution_json::text, ar.client_request_id @@ -473,7 +473,7 @@ pub async fn list_pending_for_hosts( JOIN agent_sessions s ON s.session_id = ar.agent_session_id WHERE ar.state = 'pending'::approval_state - AND s.host_installation_id IN (", + AND s.host_device_id IN (", ); { let mut separated = builder.separated(", "); @@ -526,7 +526,7 @@ fn decode_row(row: ApprovalRequestDbRow) -> Result Result, // display_name Option, // public_key @@ -27,11 +27,7 @@ type InstallationRowTuple = ( Option, // account_id ); -/// A single installation row after decoding into domain types. -/// -/// Field names keep the historical `device_*` vocabulary used across HTTP -/// auth and pairing so call sites stay stable; the underlying table is -/// `device_installations`. +/// One device row (`devices`). #[derive(Debug, Clone, PartialEq, Eq)] pub struct DeviceRow { pub device_id: DeviceId, @@ -62,12 +58,12 @@ where E: Executor<'e, Database = Sqlite>, { let id_str = id.to_string(); - let kind = DeviceRole::AgentHost.to_installation_kind(); + let kind = DeviceRole::AgentHost.to_device_kind(); sqlx::query( r#" - INSERT INTO device_installations - (installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) + INSERT INTO devices + (device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) VALUES (?, ?, ?, ?, ?, ?, NULL) "#, ) @@ -99,13 +95,13 @@ pub async fn insert_host_with_public_key( now: i64, ) -> Result<(), BackendError> { let id_str = id.to_string(); - let kind = DeviceRole::AgentHost.to_installation_kind(); + let kind = DeviceRole::AgentHost.to_device_kind(); let result = match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { sqlx::query( r#" - INSERT INTO device_installations - (installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) + INSERT INTO devices + (device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) VALUES (?, ?, ?, ?, ?, ?, NULL) "#, ) @@ -122,9 +118,9 @@ pub async fn insert_host_with_public_key( StorePoolRef::Postgres(pool) => { sqlx::query( r#" - INSERT INTO device_installations - (installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) - VALUES ($1, $2::installation_kind, $3, $4, $5, $6, NULL) + INSERT INTO devices + (device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) + VALUES ($1, $2::device_kind, $3, $4, $5, $6, NULL) "#, ) .bind(&id_str) @@ -164,13 +160,13 @@ pub async fn insert_client_for_account( }); } let id_str = id.to_string(); - let kind = role.to_installation_kind(); + let kind = role.to_device_kind(); let result = match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { sqlx::query( r#" - INSERT INTO device_installations - (installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) + INSERT INTO devices + (device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) VALUES (?, ?, ?, NULL, ?, ?, ?) "#, ) @@ -187,9 +183,9 @@ pub async fn insert_client_for_account( StorePoolRef::Postgres(pool) => { sqlx::query( r#" - INSERT INTO device_installations - (installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) - VALUES ($1, $2::installation_kind, $3, NULL, $4, $5, $6) + INSERT INTO devices + (device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) + VALUES ($1, $2::device_kind, $3, NULL, $4, $5, $6) "#, ) .bind(&id_str) @@ -222,21 +218,21 @@ pub async fn set_account_id( let id_str = device_id.to_string(); match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { - sqlx::query("UPDATE device_installations SET account_id = ? WHERE installation_id = ?") + sqlx::query("UPDATE devices SET account_id = ? WHERE device_id = ?") + .bind(account_id) + .bind(&id_str) + .execute(pool) + .await + .map(|_| ()) + } + StorePoolRef::Postgres(pool) => { + sqlx::query("UPDATE devices SET account_id = $1 WHERE device_id = $2") .bind(account_id) .bind(&id_str) .execute(pool) .await .map(|_| ()) } - StorePoolRef::Postgres(pool) => sqlx::query( - "UPDATE device_installations SET account_id = $1 WHERE installation_id = $2", - ) - .bind(account_id) - .bind(&id_str) - .execute(pool) - .await - .map(|_| ()), } .map_err(|e| BackendError::StoreQuery { operation: "set_account_id".to_string(), @@ -253,22 +249,22 @@ pub async fn set_display_name( ) -> Result<(), BackendError> { let id_str = device_id.to_string(); match store.as_store_pool() { - StorePoolRef::Sqlite(pool) => sqlx::query( - "UPDATE device_installations SET display_name = ? WHERE installation_id = ?", - ) - .bind(display_name) - .bind(&id_str) - .execute(pool) - .await - .map(|_| ()), - StorePoolRef::Postgres(pool) => sqlx::query( - "UPDATE device_installations SET display_name = $1 WHERE installation_id = $2", - ) - .bind(display_name) - .bind(&id_str) - .execute(pool) - .await - .map(|_| ()), + StorePoolRef::Sqlite(pool) => { + sqlx::query("UPDATE devices SET display_name = ? WHERE device_id = ?") + .bind(display_name) + .bind(&id_str) + .execute(pool) + .await + .map(|_| ()) + } + StorePoolRef::Postgres(pool) => { + sqlx::query("UPDATE devices SET display_name = $1 WHERE device_id = $2") + .bind(display_name) + .bind(&id_str) + .execute(pool) + .await + .map(|_| ()) + } } .map_err(|e| BackendError::StoreQuery { operation: "set_display_name".to_string(), @@ -287,22 +283,22 @@ pub async fn touch_last_seen( ) -> Result<(), BackendError> { let id_str = device_id.to_string(); let rows_affected = match store.as_store_pool() { - StorePoolRef::Sqlite(pool) => sqlx::query( - "UPDATE device_installations SET last_seen_at_ms = ? WHERE installation_id = ?", - ) - .bind(at_ms) - .bind(&id_str) - .execute(pool) - .await - .map(|result| result.rows_affected()), - StorePoolRef::Postgres(pool) => sqlx::query( - "UPDATE device_installations SET last_seen_at_ms = $1 WHERE installation_id = $2", - ) - .bind(at_ms) - .bind(&id_str) - .execute(pool) - .await - .map(|result| result.rows_affected()), + StorePoolRef::Sqlite(pool) => { + sqlx::query("UPDATE devices SET last_seen_at_ms = ? WHERE device_id = ?") + .bind(at_ms) + .bind(&id_str) + .execute(pool) + .await + .map(|result| result.rows_affected()) + } + StorePoolRef::Postgres(pool) => { + sqlx::query("UPDATE devices SET last_seen_at_ms = $1 WHERE device_id = $2") + .bind(at_ms) + .bind(&id_str) + .execute(pool) + .await + .map(|result| result.rows_affected()) + } } .map_err(|e| BackendError::StoreQuery { operation: "touch_last_seen".to_string(), @@ -340,9 +336,9 @@ where let row = sqlx::query_as::<_, InstallationRowTuple>( r#" - SELECT installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id - FROM device_installations - WHERE installation_id = ? + SELECT device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id + FROM devices + WHERE device_id = ? "#, ) .bind(&id_str) @@ -369,8 +365,8 @@ pub async fn list_by_account( StorePoolRef::Sqlite(pool) => { sqlx::query_as::<_, InstallationRowTuple>( r#" - SELECT installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id - FROM device_installations + SELECT device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id + FROM devices WHERE account_id = ? ORDER BY created_at_ms ASC "#, @@ -382,8 +378,8 @@ pub async fn list_by_account( StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, InstallationRowTuple>( r#" - SELECT installation_id, kind::text, display_name, public_key, created_at_ms, last_seen_at_ms, account_id - FROM device_installations + SELECT device_id, kind::text, display_name, public_key, created_at_ms, last_seen_at_ms, account_id + FROM devices WHERE account_id = $1 ORDER BY created_at_ms ASC "#, @@ -405,13 +401,13 @@ pub async fn latest_mobile_for_account( store: &impl AsStorePool, account_id: &str, ) -> Result, BackendError> { - let kind = DeviceRole::MobileClient.to_installation_kind(); + let kind = DeviceRole::MobileClient.to_device_kind(); let row = match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { sqlx::query_as::<_, InstallationRowTuple>( r#" - SELECT installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id - FROM device_installations + SELECT device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id + FROM devices WHERE account_id = ? AND kind = ? ORDER BY last_seen_at_ms DESC, created_at_ms DESC LIMIT 1 @@ -425,9 +421,9 @@ pub async fn latest_mobile_for_account( StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, InstallationRowTuple>( r#" - SELECT installation_id, kind::text, display_name, public_key, created_at_ms, last_seen_at_ms, account_id - FROM device_installations - WHERE account_id = $1 AND kind = $2::installation_kind + SELECT device_id, kind::text, display_name, public_key, created_at_ms, last_seen_at_ms, account_id + FROM devices + WHERE account_id = $1 AND kind = $2::device_kind ORDER BY last_seen_at_ms DESC, created_at_ms DESC LIMIT 1 "#, @@ -458,8 +454,8 @@ pub async fn set_public_key_if_absent( let id_str = device_id.to_string(); let result = match store.as_store_pool() { StorePoolRef::Sqlite(pool) => sqlx::query( - "UPDATE device_installations SET public_key = ? \ - WHERE installation_id = ? AND public_key IS NULL", + "UPDATE devices SET public_key = ? \ + WHERE device_id = ? AND public_key IS NULL", ) .bind(public_key) .bind(&id_str) @@ -467,8 +463,8 @@ pub async fn set_public_key_if_absent( .await .map(|result| result.rows_affected()), StorePoolRef::Postgres(pool) => sqlx::query( - "UPDATE device_installations SET public_key = $1 \ - WHERE installation_id = $2 AND public_key IS NULL", + "UPDATE devices SET public_key = $1 \ + WHERE device_id = $2 AND public_key IS NULL", ) .bind(public_key) .bind(&id_str) @@ -485,19 +481,18 @@ pub async fn set_public_key_if_absent( } fn decode_installation_row(row: InstallationRowTuple) -> Result { - let (installation_id, kind, display_name, public_key, created_at, last_seen_at, account_id) = - row; - let device_id = Uuid::parse_str(&installation_id) - .map(DeviceId) - .map_err(|e| BackendError::StoreDecode { - column: "device_installations.installation_id".to_string(), - message: e.to_string(), - })?; - let role = - DeviceRole::from_installation_kind(&kind).map_err(|e| BackendError::StoreDecode { - column: "device_installations.kind".to_string(), - message: e, - })?; + let (device_id, kind, display_name, public_key, created_at, last_seen_at, account_id) = row; + let device_id = + Uuid::parse_str(&device_id) + .map(DeviceId) + .map_err(|e| BackendError::StoreDecode { + column: "devices.device_id".to_string(), + message: e.to_string(), + })?; + let role = DeviceRole::from_device_kind(&kind).map_err(|e| BackendError::StoreDecode { + column: "devices.kind".to_string(), + message: e, + })?; Ok(DeviceRow { device_id, @@ -518,9 +513,9 @@ async fn get_device_postgres( let row = sqlx::query_as::<_, InstallationRowTuple>( r#" - SELECT installation_id, kind::text, display_name, public_key, created_at_ms, last_seen_at_ms, account_id - FROM device_installations - WHERE installation_id = $1 + SELECT device_id, kind::text, display_name, public_key, created_at_ms, last_seen_at_ms, account_id + FROM devices + WHERE device_id = $1 "#, ) .bind(&id_str) @@ -690,7 +685,7 @@ mod tests { } #[tokio::test] - async fn insert_device_stores_kind_as_installation_kind() { + async fn insert_device_stores_kind_as_device_kind() { let pool = memory_pool().await; let account = crate::store::accounts::create(&pool, "kind@example.com") .await @@ -708,12 +703,11 @@ mod tests { .unwrap(); let id_str = id.to_string(); - let raw_kind: String = - sqlx::query_scalar("SELECT kind FROM device_installations WHERE installation_id = ?") - .bind(&id_str) - .fetch_one(&pool) - .await - .unwrap(); + let raw_kind: String = sqlx::query_scalar("SELECT kind FROM devices WHERE device_id = ?") + .bind(&id_str) + .fetch_one(&pool) + .await + .unwrap(); assert_eq!(raw_kind, "browser"); } @@ -824,13 +818,11 @@ mod tests { .await .unwrap(); let (kind, account_id, public_key): (String, Option, Option) = - sqlx::query_as( - "SELECT kind, account_id, public_key FROM device_installations WHERE installation_id = ?", - ) - .bind(id.to_string()) - .fetch_one(&pool) - .await - .unwrap(); + sqlx::query_as("SELECT kind, account_id, public_key FROM devices WHERE device_id = ?") + .bind(id.to_string()) + .fetch_one(&pool) + .await + .unwrap(); assert_eq!(kind, "desktop"); assert_eq!(account_id.as_deref(), Some(account.account_id.as_str())); assert!(public_key.is_none()); diff --git a/crates/minos-backend/src/store/host_commands.rs b/crates/minos-backend/src/store/host_commands.rs index b775b73d..021de3e0 100644 --- a/crates/minos-backend/src/store/host_commands.rs +++ b/crates/minos-backend/src/store/host_commands.rs @@ -61,7 +61,7 @@ impl HostCommandTerminalStatus { #[derive(Debug, Clone, PartialEq)] pub struct HostCommandRow { pub command_id: String, - pub host_installation_id: DeviceId, + pub host_device_id: DeviceId, pub agent_session_id: Option, pub method: String, pub params_json: Value, @@ -106,7 +106,7 @@ impl HostCommandRow { pub async fn enqueue( store: &impl AsStorePool, command_id: &str, - host_installation_id: DeviceId, + host_device_id: DeviceId, agent_session_id: Option<&str>, method: &str, params_json: &Value, @@ -120,11 +120,11 @@ pub async fn enqueue( StorePoolRef::Sqlite(pool) => { sqlx::query( "INSERT INTO host_commands - (command_id, host_installation_id, agent_session_id, method, params_json, requested_by_account_id, status, deadline_at_ms, created_at_ms) + (command_id, host_device_id, agent_session_id, method, params_json, requested_by_account_id, status, deadline_at_ms, created_at_ms) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?)", ) .bind(command_id) - .bind(host_installation_id.to_string()) + .bind(host_device_id.to_string()) .bind(agent_session_id) .bind(method) .bind(params_json.as_str()) @@ -138,11 +138,11 @@ pub async fn enqueue( StorePoolRef::Postgres(pool) => { sqlx::query( "INSERT INTO host_commands - (command_id, host_installation_id, agent_session_id, method, params_json, requested_by_account_id, status, deadline_at_ms, created_at_ms) + (command_id, host_device_id, agent_session_id, method, params_json, requested_by_account_id, status, deadline_at_ms, created_at_ms) VALUES ($1, $2, $3, $4, $5, $6, 'pending', $7, $8)", ) .bind(command_id) - .bind(host_installation_id.to_string()) + .bind(host_device_id.to_string()) .bind(agent_session_id) .bind(method) .bind(params_json.as_str()) @@ -162,7 +162,7 @@ pub async fn enqueue( pub async fn enqueue_in_tx( tx: &mut DbTx<'_>, command_id: &str, - host_installation_id: DeviceId, + host_device_id: DeviceId, agent_session_id: Option<&str>, method: &str, params_json: &Value, @@ -176,11 +176,11 @@ pub async fn enqueue_in_tx( DbTx::Sqlite(tx) => { sqlx::query( "INSERT INTO host_commands - (command_id, host_installation_id, agent_session_id, method, params_json, requested_by_account_id, status, deadline_at_ms, created_at_ms) + (command_id, host_device_id, agent_session_id, method, params_json, requested_by_account_id, status, deadline_at_ms, created_at_ms) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?)", ) .bind(command_id) - .bind(host_installation_id.to_string()) + .bind(host_device_id.to_string()) .bind(agent_session_id) .bind(method) .bind(params_json.as_str()) @@ -194,11 +194,11 @@ pub async fn enqueue_in_tx( DbTx::Postgres(tx) => { sqlx::query( "INSERT INTO host_commands - (command_id, host_installation_id, agent_session_id, method, params_json, requested_by_account_id, status, deadline_at_ms, created_at_ms) + (command_id, host_device_id, agent_session_id, method, params_json, requested_by_account_id, status, deadline_at_ms, created_at_ms) VALUES ($1, $2, $3, $4, CAST($5 AS JSONB), $6, 'pending', $7, $8)", ) .bind(command_id) - .bind(host_installation_id.to_string()) + .bind(host_device_id.to_string()) .bind(agent_session_id) .bind(method) .bind(params_json.as_str()) @@ -218,10 +218,10 @@ pub async fn get( store: &impl AsStorePool, command_id: &str, ) -> Result, BackendError> { - let row = - match store.as_store_pool() { - StorePoolRef::Sqlite(pool) => sqlx::query_as::<_, HostCommandRowTuple>( - "SELECT command_id, host_installation_id, agent_session_id, method, params_json, + let row = match store.as_store_pool() { + StorePoolRef::Sqlite(pool) => { + sqlx::query_as::<_, HostCommandRowTuple>( + "SELECT command_id, host_device_id, agent_session_id, method, params_json, requested_by_account_id, status, response_json, error_json, deadline_at_ms, created_at_ms, ack_at_ms, finished_at_ms FROM host_commands @@ -229,9 +229,11 @@ pub async fn get( ) .bind(command_id) .fetch_optional(pool) - .await, - StorePoolRef::Postgres(pool) => sqlx::query_as::<_, HostCommandRowTuple>( - "SELECT command_id, host_installation_id, agent_session_id, method, params_json, + .await + } + StorePoolRef::Postgres(pool) => { + sqlx::query_as::<_, HostCommandRowTuple>( + "SELECT command_id, host_device_id, agent_session_id, method, params_json, requested_by_account_id, status::text, response_json, error_json, deadline_at_ms, created_at_ms, ack_at_ms, finished_at_ms FROM host_commands @@ -239,9 +241,10 @@ pub async fn get( ) .bind(command_id) .fetch_optional(pool) - .await, + .await } - .map_err(store_err("host_commands::get"))?; + } + .map_err(store_err("host_commands::get"))?; row.map(decode_row).transpose() } @@ -249,10 +252,10 @@ pub async fn get( pub async fn ack( store: &impl AsStorePool, command_id: &str, - host_installation_id: DeviceId, + host_device_id: DeviceId, ack_at_ms: i64, ) -> Result { - let host = host_installation_id.to_string(); + let host = host_device_id.to_string(); let result = match store.as_store_pool() { StorePoolRef::Sqlite(pool) => sqlx::query( "UPDATE host_commands @@ -262,7 +265,7 @@ pub async fn ack( END, ack_at_ms = ? WHERE command_id = ? - AND host_installation_id = ? + AND host_device_id = ? AND status IN ('pending', 'acked', 'succeeded', 'failed') AND ack_at_ms IS NULL", ) @@ -280,7 +283,7 @@ pub async fn ack( END, ack_at_ms = $1 WHERE command_id = $2 - AND host_installation_id = $3 + AND host_device_id = $3 AND status IN ('pending', 'acked', 'succeeded', 'failed') AND ack_at_ms IS NULL", ) @@ -299,13 +302,13 @@ pub async fn ack( pub async fn finish( store: &impl AsStorePool, command_id: &str, - host_installation_id: DeviceId, + host_device_id: DeviceId, status: HostCommandTerminalStatus, response_json: Option<&Value>, error_json: Option<&Value>, finished_at_ms: i64, ) -> Result { - let host = host_installation_id.to_string(); + let host = host_device_id.to_string(); let response_json = response_json .map(|value| serialize_json(value, "host_commands::finish.response_json")) .transpose()?; @@ -318,7 +321,7 @@ pub async fn finish( "UPDATE host_commands SET status = ?, response_json = ?, error_json = ?, finished_at_ms = ? WHERE command_id = ? - AND host_installation_id = ? + AND host_device_id = ? AND finished_at_ms IS NULL AND status IN ('pending', 'acked')", ) @@ -335,7 +338,7 @@ pub async fn finish( "UPDATE host_commands SET status = $1, response_json = $2, error_json = $3, finished_at_ms = $4 WHERE command_id = $5 - AND host_installation_id = $6 + AND host_device_id = $6 AND finished_at_ms IS NULL AND status IN ('pending', 'acked')", ) @@ -358,10 +361,10 @@ pub async fn list_timed_out_open( now_ms: i64, limit: u32, ) -> Result, BackendError> { - let rows = - match store.as_store_pool() { - StorePoolRef::Sqlite(pool) => sqlx::query_as::<_, HostCommandRowTuple>( - "SELECT command_id, host_installation_id, agent_session_id, method, params_json, + let rows = match store.as_store_pool() { + StorePoolRef::Sqlite(pool) => { + sqlx::query_as::<_, HostCommandRowTuple>( + "SELECT command_id, host_device_id, agent_session_id, method, params_json, requested_by_account_id, status, response_json, error_json, deadline_at_ms, created_at_ms, ack_at_ms, finished_at_ms FROM host_commands @@ -374,9 +377,11 @@ pub async fn list_timed_out_open( .bind(now_ms) .bind(i64::from(limit)) .fetch_all(pool) - .await, - StorePoolRef::Postgres(pool) => sqlx::query_as::<_, HostCommandRowTuple>( - "SELECT command_id, host_installation_id, agent_session_id, method, params_json, + .await + } + StorePoolRef::Postgres(pool) => { + sqlx::query_as::<_, HostCommandRowTuple>( + "SELECT command_id, host_device_id, agent_session_id, method, params_json, requested_by_account_id, status::text, response_json, error_json, deadline_at_ms, created_at_ms, ack_at_ms, finished_at_ms FROM host_commands @@ -389,9 +394,10 @@ pub async fn list_timed_out_open( .bind(now_ms) .bind(i64::from(limit)) .fetch_all(pool) - .await, + .await } - .map_err(store_err("host_commands::list_timed_out_open"))?; + } + .map_err(store_err("host_commands::list_timed_out_open"))?; rows.into_iter().map(decode_row).collect() } @@ -443,7 +449,7 @@ pub async fn mark_timed_out( fn decode_row(row: HostCommandRowTuple) -> Result { let ( command_id, - host_installation_id, + host_device_id, agent_session_id, method, params_json, @@ -459,10 +465,10 @@ fn decode_row(row: HostCommandRowTuple) -> Result Ok(HostCommandRow { command_id, - host_installation_id: Uuid::parse_str(&host_installation_id) + host_device_id: Uuid::parse_str(&host_device_id) .map(DeviceId) .map_err(|error| BackendError::StoreDecode { - column: "host_commands.host_installation_id".into(), + column: "host_commands.host_device_id".into(), message: error.to_string(), })?, agent_session_id, diff --git a/crates/minos-backend/src/store/host_links.rs b/crates/minos-backend/src/store/host_links.rs index 962bcbb7..271b8d2f 100644 --- a/crates/minos-backend/src/store/host_links.rs +++ b/crates/minos-backend/src/store/host_links.rs @@ -1,8 +1,8 @@ //! Persistence for `host_links` (account ↔ host installation). //! -//! Pair model is `(account_id, host_installation_id)`. The client +//! Pair model is `(account_id, host_device_id)`. The client //! installation that performed the link is recorded as -//! `linked_via_installation_id` for audit only — it does not participate in +//! `linked_via_device_id` for audit only — it does not participate in //! routing. //! //! Field names on [`PairRow`] keep historical `host_device_id` / @@ -32,7 +32,7 @@ pub struct PairRow { /// Upsert a host link and return the resulting row. /// -/// On conflict `host_installation_id` (exclusive ownership) refreshes +/// On conflict `host_device_id` (exclusive ownership) refreshes /// metadata **only** when the existing row belongs to the same account. /// Returns [`BackendError::HostLinkedElsewhere`] when the host is already /// bound to a different account (empty RETURNING after conflict WHERE). @@ -91,16 +91,16 @@ where let row = sqlx::query_as::<_, PairRowTuple>( r#" INSERT INTO host_links - (pair_id, account_id, host_installation_id, linked_via_installation_id, + (pair_id, account_id, host_device_id, linked_via_device_id, link_display_name, acl_json, paired_at_ms) VALUES (?, ?, ?, ?, ?, '{}', ?) - ON CONFLICT (host_installation_id) DO UPDATE SET - linked_via_installation_id = excluded.linked_via_installation_id, + ON CONFLICT (host_device_id) DO UPDATE SET + linked_via_device_id = excluded.linked_via_device_id, link_display_name = excluded.link_display_name, paired_at_ms = excluded.paired_at_ms WHERE host_links.account_id = excluded.account_id - RETURNING pair_id, host_installation_id, account_id, - linked_via_installation_id, link_display_name, paired_at_ms + RETURNING pair_id, host_device_id, account_id, + linked_via_device_id, link_display_name, paired_at_ms "#, ) .bind(&pair_id) @@ -114,7 +114,7 @@ where .map_err(|e| map_host_link_write_error("host_links::upsert_link", e))?; let Some(row) = row else { return Err(BackendError::HostLinkedElsewhere { - host_installation_id: host_s, + host_device_id: host_s, }); }; decode_pair_row(row) @@ -137,16 +137,16 @@ where let row = sqlx::query_as::<_, PairRowTuple>( r#" INSERT INTO host_links - (pair_id, account_id, host_installation_id, linked_via_installation_id, + (pair_id, account_id, host_device_id, linked_via_device_id, link_display_name, acl_json, paired_at_ms) VALUES ($1, $2, $3, $4, $5, '{}'::jsonb, $6) - ON CONFLICT (host_installation_id) DO UPDATE SET - linked_via_installation_id = EXCLUDED.linked_via_installation_id, + ON CONFLICT (host_device_id) DO UPDATE SET + linked_via_device_id = EXCLUDED.linked_via_device_id, link_display_name = EXCLUDED.link_display_name, paired_at_ms = EXCLUDED.paired_at_ms WHERE host_links.account_id = EXCLUDED.account_id - RETURNING pair_id, host_installation_id, account_id, - linked_via_installation_id, link_display_name, paired_at_ms + RETURNING pair_id, host_device_id, account_id, + linked_via_device_id, link_display_name, paired_at_ms "#, ) .bind(&pair_id) @@ -160,7 +160,7 @@ where .map_err(|e| map_host_link_write_error("host_links::upsert_link", e))?; let Some(row) = row else { return Err(BackendError::HostLinkedElsewhere { - host_installation_id: host_s, + host_device_id: host_s, }); }; decode_pair_row(row) @@ -180,7 +180,7 @@ where r#" SELECT account_id FROM host_links - WHERE host_installation_id = ? + WHERE host_device_id = ? LIMIT 1 "#, ) @@ -194,7 +194,7 @@ where if let Some(owner) = existing { if owner != account_id { return Err(BackendError::HostLinkedElsewhere { - host_installation_id: host_s, + host_device_id: host_s, }); } } @@ -215,7 +215,7 @@ where r#" SELECT account_id FROM host_links - WHERE host_installation_id = $1 + WHERE host_device_id = $1 LIMIT 1 FOR UPDATE "#, @@ -230,7 +230,7 @@ where if let Some(owner) = existing { if owner != account_id { return Err(BackendError::HostLinkedElsewhere { - host_installation_id: host_s, + host_device_id: host_s, }); } } @@ -241,7 +241,7 @@ fn map_host_link_write_error(operation: &str, error: sqlx::Error) -> BackendErro if let sqlx::Error::Database(db) = &error { if db.is_unique_violation() { return BackendError::HostLinkedElsewhere { - host_installation_id: String::new(), + host_device_id: String::new(), }; } } @@ -347,10 +347,10 @@ where let res = sqlx::query( r#" INSERT INTO host_links - (pair_id, account_id, host_installation_id, linked_via_installation_id, + (pair_id, account_id, host_device_id, linked_via_device_id, link_display_name, acl_json, paired_at_ms) VALUES (?, ?, ?, ?, NULL, '{}', ?) - ON CONFLICT (host_installation_id) DO NOTHING + ON CONFLICT (host_device_id) DO NOTHING "#, ) .bind(&pair_id) @@ -380,10 +380,10 @@ where let res = sqlx::query( r#" INSERT INTO host_links - (pair_id, account_id, host_installation_id, linked_via_installation_id, + (pair_id, account_id, host_device_id, linked_via_device_id, link_display_name, acl_json, paired_at_ms) VALUES ($1, $2, $3, $4, NULL, '{}'::jsonb, $5) - ON CONFLICT (host_installation_id) DO NOTHING + ON CONFLICT (host_device_id) DO NOTHING "#, ) .bind(&pair_id) @@ -406,8 +406,8 @@ pub async fn list_hosts_for_account( StorePoolRef::Sqlite(pool) => { sqlx::query_as::<_, PairRowTuple>( r#" - SELECT pair_id, host_installation_id, account_id, - linked_via_installation_id, link_display_name, paired_at_ms + SELECT pair_id, host_device_id, account_id, + linked_via_device_id, link_display_name, paired_at_ms FROM host_links WHERE account_id = ? ORDER BY paired_at_ms DESC @@ -420,8 +420,8 @@ pub async fn list_hosts_for_account( StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, PairRowTuple>( r#" - SELECT pair_id, host_installation_id, account_id, - linked_via_installation_id, link_display_name, paired_at_ms + SELECT pair_id, host_device_id, account_id, + linked_via_device_id, link_display_name, paired_at_ms FROM host_links WHERE account_id = $1 ORDER BY paired_at_ms DESC @@ -449,10 +449,10 @@ pub async fn list_accounts_for_host( StorePoolRef::Sqlite(pool) => { sqlx::query_as::<_, PairRowTuple>( r#" - SELECT pair_id, host_installation_id, account_id, - linked_via_installation_id, link_display_name, paired_at_ms + SELECT pair_id, host_device_id, account_id, + linked_via_device_id, link_display_name, paired_at_ms FROM host_links - WHERE host_installation_id = ? + WHERE host_device_id = ? ORDER BY paired_at_ms DESC "#, ) @@ -463,10 +463,10 @@ pub async fn list_accounts_for_host( StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, PairRowTuple>( r#" - SELECT pair_id, host_installation_id, account_id, - linked_via_installation_id, link_display_name, paired_at_ms + SELECT pair_id, host_device_id, account_id, + linked_via_device_id, link_display_name, paired_at_ms FROM host_links - WHERE host_installation_id = $1 + WHERE host_device_id = $1 ORDER BY paired_at_ms DESC "#, ) @@ -488,20 +488,20 @@ pub async fn list_account_client_targets_for_host( host_device_id: DeviceId, ) -> Result, BackendError> { let host_s = host_device_id.to_string(); - let mobile = DeviceRole::MobileClient.to_installation_kind(); - let browser = DeviceRole::BrowserAdmin.to_installation_kind(); - let desktop = DeviceRole::DesktopConsole.to_installation_kind(); + let mobile = DeviceRole::MobileClient.to_device_kind(); + let browser = DeviceRole::BrowserAdmin.to_device_kind(); + let desktop = DeviceRole::DesktopConsole.to_device_kind(); let rows = match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { sqlx::query_scalar::<_, String>( r#" - SELECT DISTINCT d.installation_id + SELECT DISTINCT d.device_id FROM host_links hl - JOIN device_installations d + JOIN devices d ON d.account_id = hl.account_id - WHERE hl.host_installation_id = ? + WHERE hl.host_device_id = ? AND d.kind IN (?, ?, ?) - ORDER BY d.installation_id ASC + ORDER BY d.device_id ASC "#, ) .bind(&host_s) @@ -514,17 +514,17 @@ pub async fn list_account_client_targets_for_host( StorePoolRef::Postgres(pool) => { sqlx::query_scalar::<_, String>( r#" - SELECT DISTINCT d.installation_id + SELECT DISTINCT d.device_id FROM host_links hl - JOIN device_installations d + JOIN devices d ON d.account_id = hl.account_id - WHERE hl.host_installation_id = $1 + WHERE hl.host_device_id = $1 AND d.kind IN ( - $2::installation_kind, - $3::installation_kind, - $4::installation_kind + $2::device_kind, + $3::device_kind, + $4::device_kind ) - ORDER BY d.installation_id ASC + ORDER BY d.device_id ASC "#, ) .bind(&host_s) @@ -540,7 +540,7 @@ pub async fn list_account_client_targets_for_host( message: e.to_string(), })?; rows.into_iter() - .map(|raw| parse_device_id(&raw, "installation_id")) + .map(|raw| parse_device_id(&raw, "device_id")) .collect() } @@ -556,10 +556,10 @@ where let host_s = host_device_id.to_string(); let row = sqlx::query_as::<_, PairRowTuple>( r#" - SELECT pair_id, host_installation_id, account_id, - linked_via_installation_id, link_display_name, paired_at_ms + SELECT pair_id, host_device_id, account_id, + linked_via_device_id, link_display_name, paired_at_ms FROM host_links - WHERE host_installation_id = ? AND account_id = ? + WHERE host_device_id = ? AND account_id = ? "#, ) .bind(&host_s) @@ -584,10 +584,10 @@ where let host_s = host_device_id.to_string(); let row = sqlx::query_as::<_, PairRowTuple>( r#" - SELECT pair_id, host_installation_id, account_id, - linked_via_installation_id, link_display_name, paired_at_ms + SELECT pair_id, host_device_id, account_id, + linked_via_device_id, link_display_name, paired_at_ms FROM host_links - WHERE host_installation_id = $1 AND account_id = $2 + WHERE host_device_id = $1 AND account_id = $2 "#, ) .bind(&host_s) @@ -614,7 +614,7 @@ pub async fn exists( r#" SELECT pair_id FROM host_links - WHERE host_installation_id = ? AND account_id = ? + WHERE host_device_id = ? AND account_id = ? LIMIT 1 "#, ) @@ -628,7 +628,7 @@ pub async fn exists( r#" SELECT pair_id FROM host_links - WHERE host_installation_id = $1 AND account_id = $2 + WHERE host_device_id = $1 AND account_id = $2 LIMIT 1 "#, ) @@ -673,7 +673,7 @@ where let res = sqlx::query( r#" DELETE FROM host_links - WHERE host_installation_id = ? AND account_id = ? + WHERE host_device_id = ? AND account_id = ? "#, ) .bind(&host_s) @@ -699,7 +699,7 @@ where let res = sqlx::query( r#" DELETE FROM host_links - WHERE host_installation_id = $1 AND account_id = $2 + WHERE host_device_id = $1 AND account_id = $2 "#, ) .bind(&host_s) @@ -724,9 +724,9 @@ fn decode_pair_row(row: PairRowTuple) -> Result { ) = row; Ok(PairRow { pair_id, - host_device_id: parse_device_id(&host_device_id, "host_installation_id")?, + host_device_id: parse_device_id(&host_device_id, "host_device_id")?, mobile_account_id, - paired_via_device_id: parse_device_id(&paired_via_device_id, "linked_via_installation_id")?, + paired_via_device_id: parse_device_id(&paired_via_device_id, "linked_via_device_id")?, link_display_name, paired_at_ms, }) diff --git a/crates/minos-backend/src/store/host_installation_tokens.rs b/crates/minos-backend/src/store/host_tokens.rs similarity index 69% rename from crates/minos-backend/src/store/host_installation_tokens.rs rename to crates/minos-backend/src/store/host_tokens.rs index 016bd15d..2826e472 100644 --- a/crates/minos-backend/src/store/host_installation_tokens.rs +++ b/crates/minos-backend/src/store/host_tokens.rs @@ -11,12 +11,20 @@ use uuid::Uuid; use crate::error::BackendError; use crate::store::{AsStorePool, StorePoolRef}; -type HostInstallationTokenRowTuple = (String, String, i64, Option, Option); +type HostInstallationTokenRowTuple = ( + String, + String, + Option, + i64, + Option, + Option, +); #[derive(Debug, Clone, PartialEq, Eq)] pub struct HostInstallationTokenRow { pub token_hash: String, - pub host_installation_id: DeviceId, + pub host_device_id: DeviceId, + pub account_id: Option, pub issued_at_ms: i64, pub last_used_at_ms: Option, pub revoked_at_ms: Option, @@ -25,27 +33,29 @@ pub struct HostInstallationTokenRow { pub(crate) async fn insert_token_with_executor<'e, E>( executor: E, token_hash: &str, - host_installation_id: DeviceId, + host_device_id: DeviceId, + account_id: Option<&str>, issued_at_ms: i64, ) -> Result<(), BackendError> where E: Executor<'e, Database = Sqlite>, { - let host = host_installation_id.to_string(); + let host = host_device_id.to_string(); sqlx::query( r#" - INSERT INTO host_installation_tokens - (token_hash, host_installation_id, issued_at_ms, last_used_at_ms, revoked_at_ms) - VALUES (?, ?, ?, NULL, NULL) + INSERT INTO host_tokens + (token_hash, host_device_id, account_id, issued_at_ms, last_used_at_ms, revoked_at_ms) + VALUES (?, ?, ?, ?, NULL, NULL) "#, ) .bind(token_hash) .bind(&host) + .bind(account_id) .bind(issued_at_ms) .execute(executor) .await .map_err(|e| BackendError::StoreQuery { - operation: "host_installation_tokens::insert_token".into(), + operation: "host_tokens::insert_token".into(), message: e.to_string(), })?; Ok(()) @@ -54,27 +64,29 @@ where pub(crate) async fn insert_token_with_postgres_executor<'e, E>( executor: E, token_hash: &str, - host_installation_id: DeviceId, + host_device_id: DeviceId, + account_id: Option<&str>, issued_at_ms: i64, ) -> Result<(), BackendError> where E: Executor<'e, Database = Postgres>, { - let host = host_installation_id.to_string(); + let host = host_device_id.to_string(); sqlx::query( r#" - INSERT INTO host_installation_tokens - (token_hash, host_installation_id, issued_at_ms, last_used_at_ms, revoked_at_ms) - VALUES ($1, $2, $3, NULL, NULL) + INSERT INTO host_tokens + (token_hash, host_device_id, account_id, issued_at_ms, last_used_at_ms, revoked_at_ms) + VALUES ($1, $2, $3, $4, NULL, NULL) "#, ) .bind(token_hash) .bind(&host) + .bind(account_id) .bind(issued_at_ms) .execute(executor) .await .map_err(|e| BackendError::StoreQuery { - operation: "host_installation_tokens::insert_token".into(), + operation: "host_tokens::insert_token".into(), message: e.to_string(), })?; Ok(()) @@ -89,11 +101,11 @@ pub async fn verify_active_token( StorePoolRef::Sqlite(pool) => { sqlx::query_as::<_, HostInstallationTokenRowTuple>( r#" - UPDATE host_installation_tokens + UPDATE host_tokens SET last_used_at_ms = ? WHERE token_hash = ? AND revoked_at_ms IS NULL - RETURNING token_hash, host_installation_id, issued_at_ms, last_used_at_ms, revoked_at_ms + RETURNING token_hash, host_device_id, account_id, issued_at_ms, last_used_at_ms, revoked_at_ms "#, ) .bind(now_ms) @@ -104,11 +116,11 @@ pub async fn verify_active_token( StorePoolRef::Postgres(pool) => { sqlx::query_as::<_, HostInstallationTokenRowTuple>( r#" - UPDATE host_installation_tokens + UPDATE host_tokens SET last_used_at_ms = $1 WHERE token_hash = $2 AND revoked_at_ms IS NULL - RETURNING token_hash, host_installation_id, issued_at_ms, last_used_at_ms, revoked_at_ms + RETURNING token_hash, host_device_id, account_id, issued_at_ms, last_used_at_ms, revoked_at_ms "#, ) .bind(now_ms) @@ -118,7 +130,7 @@ pub async fn verify_active_token( } } .map_err(|e| BackendError::StoreQuery { - operation: "host_installation_tokens::verify_active_token".into(), + operation: "host_tokens::verify_active_token".into(), message: e.to_string(), })?; row.map(decode_host_installation_token_row).transpose() @@ -126,33 +138,33 @@ pub async fn verify_active_token( pub async fn revoke_all_for_host( store: &impl AsStorePool, - host_installation_id: DeviceId, + host_device_id: DeviceId, now_ms: i64, ) -> Result { match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { - revoke_all_for_host_with_executor(pool, host_installation_id, now_ms).await + revoke_all_for_host_with_executor(pool, host_device_id, now_ms).await } StorePoolRef::Postgres(pool) => { - revoke_all_for_host_with_postgres_executor(pool, host_installation_id, now_ms).await + revoke_all_for_host_with_postgres_executor(pool, host_device_id, now_ms).await } } } pub(crate) async fn revoke_all_for_host_with_executor<'e, E>( executor: E, - host_installation_id: DeviceId, + host_device_id: DeviceId, now_ms: i64, ) -> Result where E: Executor<'e, Database = Sqlite>, { - let host = host_installation_id.to_string(); + let host = host_device_id.to_string(); let result = sqlx::query( r#" - UPDATE host_installation_tokens + UPDATE host_tokens SET revoked_at_ms = ? - WHERE host_installation_id = ? + WHERE host_device_id = ? AND revoked_at_ms IS NULL "#, ) @@ -161,7 +173,7 @@ where .execute(executor) .await .map_err(|e| BackendError::StoreQuery { - operation: "host_installation_tokens::revoke_all_for_host".into(), + operation: "host_tokens::revoke_all_for_host".into(), message: e.to_string(), })?; Ok(result.rows_affected()) @@ -169,18 +181,18 @@ where pub(crate) async fn revoke_all_for_host_with_postgres_executor<'e, E>( executor: E, - host_installation_id: DeviceId, + host_device_id: DeviceId, now_ms: i64, ) -> Result where E: Executor<'e, Database = Postgres>, { - let host = host_installation_id.to_string(); + let host = host_device_id.to_string(); let result = sqlx::query( r#" - UPDATE host_installation_tokens + UPDATE host_tokens SET revoked_at_ms = $1 - WHERE host_installation_id = $2 + WHERE host_device_id = $2 AND revoked_at_ms IS NULL "#, ) @@ -189,7 +201,7 @@ where .execute(executor) .await .map_err(|e| BackendError::StoreQuery { - operation: "host_installation_tokens::revoke_all_for_host".into(), + operation: "host_tokens::revoke_all_for_host".into(), message: e.to_string(), })?; Ok(result.rows_affected()) @@ -198,15 +210,17 @@ where fn decode_host_installation_token_row( row: HostInstallationTokenRowTuple, ) -> Result { - let (token_hash, host_installation_id, issued_at_ms, last_used_at_ms, revoked_at_ms) = row; + let (token_hash, host_device_id, account_id, issued_at_ms, last_used_at_ms, revoked_at_ms) = + row; Ok(HostInstallationTokenRow { token_hash, - host_installation_id: Uuid::parse_str(&host_installation_id) + host_device_id: Uuid::parse_str(&host_device_id) .map(DeviceId) .map_err(|e| BackendError::StoreDecode { - column: "host_installation_tokens.host_installation_id".into(), + column: "host_tokens.host_device_id".into(), message: e.to_string(), })?, + account_id: account_id.filter(|id| !id.is_empty()), issued_at_ms, last_used_at_ms, revoked_at_ms, @@ -224,7 +238,7 @@ mod tests { let host = DeviceId::new(); crate::store::test_support::insert_test_host(&pool, host, "host", T0).await; let mut tx = pool.begin().await.unwrap(); - insert_token_with_executor(&mut *tx, "hash", host, T0) + insert_token_with_executor(&mut *tx, "hash", host, None, T0) .await .unwrap(); tx.commit().await.unwrap(); @@ -234,7 +248,7 @@ mod tests { .unwrap() .unwrap(); - assert_eq!(row.host_installation_id, host); + assert_eq!(row.host_device_id, host); assert_eq!(row.last_used_at_ms, Some(T0 + 42)); } } diff --git a/crates/minos-backend/src/store/mod.rs b/crates/minos-backend/src/store/mod.rs index 604fd18e..23d60c37 100644 --- a/crates/minos-backend/src/store/mod.rs +++ b/crates/minos-backend/src/store/mod.rs @@ -1,8 +1,8 @@ //! SQLite connection pool, schema migrations, and typed CRUD helpers. //! //! Submodules: -//! - [`device_installations`] — client/host installation rows (`kind` enum). -//! - [`host_links`] — account ↔ host installation links. +//! - [`devices`] — one row per DeviceId (mobile / browser / desktop / host). +//! - [`host_links`] — account ↔ host DeviceId. //! - [`agent_sessions`] — additive agent session metadata scoped to conversations. //! - [`agent_turns`] — durable turn metadata for agent sessions. //! - [`agent_turn_events`] — per-turn cold-replay stream slices. @@ -204,11 +204,11 @@ pub mod agent_turn_events; pub mod agent_turns; pub mod approval_requests; pub mod completion_watches; -pub mod device_installations; +pub mod devices; pub mod durable_event_log; pub mod host_commands; -pub mod host_installation_tokens; pub mod host_links; +pub mod host_tokens; pub mod media_blobs; pub mod message_attachments; pub mod notification_cooldowns; @@ -224,7 +224,7 @@ pub mod sessions; pub mod social; pub mod thread_sync_state; -pub use device_installations::{get_device, DeviceRow}; +pub use devices::{get_device, DeviceRow}; #[must_use] pub const fn sqlite_backend_enabled() -> bool { @@ -470,7 +470,7 @@ pub mod test_support { /// `DeviceId`. Client auth is bearer-only (no device secret). pub async fn insert_ios_device(pool: &SqlitePool, account_id: &str) -> DeviceId { let id = DeviceId::new(); - crate::store::device_installations::insert_client_for_account( + crate::store::devices::insert_client_for_account( pool, id, "iPhone", @@ -493,7 +493,7 @@ pub mod test_support { name: &str, now: i64, ) { - crate::store::device_installations::insert_host_with_public_key( + crate::store::devices::insert_host_with_public_key( pool, id, name, @@ -504,7 +504,9 @@ pub mod test_support { .unwrap(); } - /// Issue a plaintext `hit_*` host installation token for tests and store its hash. + /// Issue a plaintext `hit_*` host token bound to one account. + /// + /// Host WS auth requires the token to resolve to exactly one account. /// Returns the bearer token string (including `hit_` prefix). pub async fn issue_test_host_token( pool: &impl crate::store::AsStorePool, @@ -513,6 +515,40 @@ pub mod test_support { ) -> String { use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine; + let existing = crate::store::host_links::list_accounts_for_host(pool, host_id) + .await + .unwrap(); + let account_id = if let Some(link) = existing.first() { + link.mobile_account_id.clone() + } else { + let email = format!("host-fixture-{host_id}@localhost"); + let account_id = crate::store::accounts::create(pool, &email) + .await + .unwrap() + .account_id; + let via = DeviceId::new(); + crate::store::devices::insert_client_for_account( + pool, + via, + "fixture-client", + DeviceRole::DesktopConsole, + &account_id, + now, + ) + .await + .unwrap(); + crate::store::host_links::upsert_link( + pool, + host_id, + &account_id, + via, + Some("fixture host"), + now, + ) + .await + .unwrap(); + account_id + }; let mut bytes = [0_u8; 24]; getrandom::fill(&mut bytes).expect("OS CSPRNG"); let token = format!("hit_{}", URL_SAFE_NO_PAD.encode(bytes)); @@ -520,10 +556,11 @@ pub mod test_support { match pool.as_store_pool() { crate::store::StorePoolRef::Sqlite(p) => { let mut tx = p.begin().await.unwrap(); - crate::store::host_installation_tokens::insert_token_with_executor( + crate::store::host_tokens::insert_token_with_executor( &mut *tx, &token_hash, host_id, + Some(&account_id), now, ) .await @@ -532,10 +569,11 @@ pub mod test_support { } crate::store::StorePoolRef::Postgres(p) => { let mut tx = p.begin().await.unwrap(); - crate::store::host_installation_tokens::insert_token_with_postgres_executor( + crate::store::host_tokens::insert_token_with_postgres_executor( &mut *tx, &token_hash, host_id, + Some(&account_id), now, ) .await @@ -566,11 +604,9 @@ pub mod test_support { name: &str, now: i64, ) { - crate::store::device_installations::insert_client_for_account( - pool, id, name, role, account_id, now, - ) - .await - .unwrap(); + crate::store::devices::insert_client_for_account(pool, id, name, role, account_id, now) + .await + .unwrap(); } } diff --git a/crates/minos-backend/src/store/outbox_events.rs b/crates/minos-backend/src/store/outbox_events.rs index 92025439..d58b1ff8 100644 --- a/crates/minos-backend/src/store/outbox_events.rs +++ b/crates/minos-backend/src/store/outbox_events.rs @@ -1119,7 +1119,7 @@ mod tests { &serde_json::json!({ "kind": "host_command_issued", "command_id": "cmd-1", - "host_installation_id": host_id.to_string(), + "host_device_id": host_id.to_string(), "method": "minos_health", "params": null, "deadline_at_ms": T0 + 1_000, @@ -1188,7 +1188,7 @@ mod tests { &serde_json::json!({ "kind": "host_command_issued", "command_id": "cmd-expired", - "host_installation_id": host_id.to_string(), + "host_device_id": host_id.to_string(), "method": "minos_health", "params": null, "deadline_at_ms": T0 + 10, @@ -1252,7 +1252,7 @@ mod tests { &serde_json::json!({ "kind": "host_command_issued", "command_id": "cmd-timeout-no-unlock", - "host_installation_id": host_id.to_string(), + "host_device_id": host_id.to_string(), "method": "minos_health", "params": null, "deadline_at_ms": T0 + 10, @@ -1336,7 +1336,7 @@ mod tests { &serde_json::json!({ "kind": "host_command_issued", "command_id": "cmd-obs-past-deadline", - "host_installation_id": host_id.to_string(), + "host_device_id": host_id.to_string(), "method": "minos_health", "params": null, "deadline_at_ms": T0 + 10, @@ -1705,7 +1705,7 @@ mod tests { &serde_json::json!({ "kind": "host_command_issued", "command_id": "cmd-pending", - "host_installation_id": host_id.to_string(), + "host_device_id": host_id.to_string(), "method": "minos_health", "params": null, "deadline_at_ms": T0 + 1_000, @@ -1778,7 +1778,7 @@ mod tests { &serde_json::json!({ "kind": "host_command_issued", "command_id": "cmd-claimed", - "host_installation_id": host_id.to_string(), + "host_device_id": host_id.to_string(), "method": "minos_health", "params": null, "deadline_at_ms": T0 + 1_000, diff --git a/crates/minos-backend/src/store/push_tokens.rs b/crates/minos-backend/src/store/push_tokens.rs index 5951f4e6..6e3f7af4 100644 --- a/crates/minos-backend/src/store/push_tokens.rs +++ b/crates/minos-backend/src/store/push_tokens.rs @@ -15,7 +15,7 @@ use crate::store::{AsStorePool, StorePoolRef}; pub struct PushTokenRow { pub token_hash: String, pub account_id: String, - pub installation_id: String, + pub device_id: String, pub kind: String, pub locale: Option, pub created_at_ms: i64, @@ -35,11 +35,11 @@ pub fn hash_token(token: &str) -> String { } /// Upsert a push token. If the token_hash already exists, refreshes -/// `last_used_at_ms` and `installation_id` (device may have reinstalled). +/// `last_used_at_ms` and `device_id` (device may have reinstalled). pub async fn upsert( store: &S, account_id: &str, - installation_id: &str, + device_id: &str, kind: &str, token: &str, locale: Option<&str>, @@ -55,7 +55,7 @@ where pool, &token_hash, account_id, - installation_id, + device_id, kind, locale, token, @@ -68,7 +68,7 @@ where pool, &token_hash, account_id, - installation_id, + device_id, kind, locale, token, @@ -127,17 +127,17 @@ async fn upsert_sqlite( pool: &SqlitePool, token_hash: &str, account_id: &str, - installation_id: &str, + device_id: &str, kind: &str, locale: Option<&str>, provider_token: &str, at_ms: i64, ) -> Result { sqlx::query_as::<_, PushTokenRow>( - "INSERT INTO push_tokens (token_hash, account_id, installation_id, kind, locale, created_at_ms, last_used_at_ms, provider_token) + "INSERT INTO push_tokens (token_hash, account_id, device_id, kind, locale, created_at_ms, last_used_at_ms, provider_token) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6, ?7) ON CONFLICT(token_hash) DO UPDATE SET - installation_id = excluded.installation_id, + device_id = excluded.device_id, last_used_at_ms = excluded.last_used_at_ms, provider_token = excluded.provider_token, revoked_at_ms = NULL @@ -145,7 +145,7 @@ async fn upsert_sqlite( ) .bind(token_hash) .bind(account_id) - .bind(installation_id) + .bind(device_id) .bind(kind) .bind(locale) .bind(at_ms) @@ -226,17 +226,17 @@ async fn upsert_postgres( pool: &PgPool, token_hash: &str, account_id: &str, - installation_id: &str, + device_id: &str, kind: &str, locale: Option<&str>, provider_token: &str, at_ms: i64, ) -> Result { sqlx::query_as::<_, PushTokenRow>( - "INSERT INTO push_tokens (token_hash, account_id, installation_id, kind, locale, created_at_ms, last_used_at_ms, provider_token) + "INSERT INTO push_tokens (token_hash, account_id, device_id, kind, locale, created_at_ms, last_used_at_ms, provider_token) VALUES ($1, $2, $3, $4, $5, $6, $6, $7) ON CONFLICT(token_hash) DO UPDATE SET - installation_id = EXCLUDED.installation_id, + device_id = EXCLUDED.device_id, last_used_at_ms = EXCLUDED.last_used_at_ms, provider_token = EXCLUDED.provider_token, revoked_at_ms = NULL @@ -244,7 +244,7 @@ async fn upsert_postgres( ) .bind(token_hash) .bind(account_id) - .bind(installation_id) + .bind(device_id) .bind(kind) .bind(locale) .bind(at_ms) diff --git a/crates/minos-backend/src/store/raw_events.rs b/crates/minos-backend/src/store/raw_events.rs index 173737e4..c0d5e236 100644 --- a/crates/minos-backend/src/store/raw_events.rs +++ b/crates/minos-backend/src/store/raw_events.rs @@ -542,7 +542,7 @@ mod tests { async fn seed_host_and_thread(pool: &SqlitePool) { sqlx::query( - r"INSERT INTO device_installations (installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) + r"INSERT INTO devices (device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) VALUES ('dev1','host','Dev','test-host-public-key-v1',0,0,NULL)", ) .execute(pool) @@ -751,7 +751,7 @@ mod tests { async fn last_seq_per_owner_groups_by_thread() { let pool = memory_pool().await; sqlx::query( - r"INSERT INTO device_installations (installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) VALUES + r"INSERT INTO devices (device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) VALUES ('host_a','host','HostA','test-host-public-key-v1',0,0,NULL), ('host_b','host','HostB','test-host-public-key-v1',0,0,NULL)", ) diff --git a/crates/minos-backend/src/store/refresh_tokens.rs b/crates/minos-backend/src/store/refresh_tokens.rs index 69d0c1cd..0321478a 100644 --- a/crates/minos-backend/src/store/refresh_tokens.rs +++ b/crates/minos-backend/src/store/refresh_tokens.rs @@ -30,13 +30,12 @@ pub struct RefreshTokenRow { pub rotated_to_hash: Option, } -const REFRESH_SELECT_SQLITE: &str = "SELECT token_hash, account_id, installation_id AS device_id, \ +const REFRESH_SELECT_SQLITE: &str = "SELECT token_hash, account_id, device_id AS device_id, \ issued_at_ms AS issued_at, expires_at_ms AS expires_at, revoked_at_ms AS revoked_at, \ rotated_to_hash \ FROM refresh_tokens"; -const REFRESH_SELECT_POSTGRES: &str = - "SELECT token_hash, account_id, installation_id AS device_id, \ +const REFRESH_SELECT_POSTGRES: &str = "SELECT token_hash, account_id, device_id AS device_id, \ issued_at_ms AS issued_at, expires_at_ms AS expires_at, revoked_at_ms AS revoked_at, \ rotated_to_hash \ FROM refresh_tokens"; @@ -284,7 +283,7 @@ pub async fn revoke_all_for_device( let now = Utc::now().timestamp_millis(); let result = match store.as_store_pool() { StorePoolRef::Sqlite(pool) => sqlx::query( - "UPDATE refresh_tokens SET revoked_at_ms = ? WHERE installation_id = ? AND revoked_at_ms IS NULL", + "UPDATE refresh_tokens SET revoked_at_ms = ? WHERE device_id = ? AND revoked_at_ms IS NULL", ) .bind(now) .bind(device_id) @@ -292,7 +291,7 @@ pub async fn revoke_all_for_device( .await .map(|result| result.rows_affected()), StorePoolRef::Postgres(pool) => sqlx::query( - "UPDATE refresh_tokens SET revoked_at_ms = $1 WHERE installation_id = $2 AND revoked_at_ms IS NULL", + "UPDATE refresh_tokens SET revoked_at_ms = $1 WHERE device_id = $2 AND revoked_at_ms IS NULL", ) .bind(now) .bind(device_id) @@ -334,7 +333,7 @@ pub async fn gc_expired(store: &impl AsStorePool, now_ms: i64) -> Result Result<(), sqlx::Error> { sqlx::query( - "INSERT INTO refresh_tokens (token_hash, account_id, installation_id, issued_at_ms, expires_at_ms) + "INSERT INTO refresh_tokens (token_hash, account_id, device_id, issued_at_ms, expires_at_ms) VALUES (?, ?, ?, ?, ?)", ) .bind(&row.token_hash) @@ -349,7 +348,7 @@ async fn insert_sqlite(pool: &SqlitePool, row: &RefreshTokenRow) -> Result<(), s async fn insert_postgres(pool: &PgPool, row: &RefreshTokenRow) -> Result<(), sqlx::Error> { sqlx::query( - "INSERT INTO refresh_tokens (token_hash, account_id, installation_id, issued_at_ms, expires_at_ms) + "INSERT INTO refresh_tokens (token_hash, account_id, device_id, issued_at_ms, expires_at_ms) VALUES ($1, $2, $3, $4, $5)", ) .bind(&row.token_hash) @@ -379,7 +378,7 @@ async fn rotate_sqlite( let new_hash = hash_plaintext(new_plaintext); let expires_at = now + REFRESH_TTL_MS; sqlx::query( - "INSERT INTO refresh_tokens (token_hash, account_id, installation_id, issued_at_ms, expires_at_ms) + "INSERT INTO refresh_tokens (token_hash, account_id, device_id, issued_at_ms, expires_at_ms) VALUES (?, ?, ?, ?, ?)", ) .bind(&new_hash) @@ -446,7 +445,7 @@ async fn rotate_postgres( let new_hash = hash_plaintext(new_plaintext); let expires_at = now + REFRESH_TTL_MS; sqlx::query( - "INSERT INTO refresh_tokens (token_hash, account_id, installation_id, issued_at_ms, expires_at_ms) + "INSERT INTO refresh_tokens (token_hash, account_id, device_id, issued_at_ms, expires_at_ms) VALUES ($1, $2, $3, $4, $5)", ) .bind(&new_hash) diff --git a/crates/minos-backend/src/store/sessions.rs b/crates/minos-backend/src/store/sessions.rs index 399baeab..b21f23d5 100644 --- a/crates/minos-backend/src/store/sessions.rs +++ b/crates/minos-backend/src/store/sessions.rs @@ -172,13 +172,13 @@ pub async fn exists_for_account( WHERE t.session_id = ? AND ( EXISTS ( - SELECT 1 FROM device_installations d - WHERE d.installation_id = t.owner_device_id + SELECT 1 FROM devices d + WHERE d.device_id = t.owner_device_id AND d.account_id = ? ) OR EXISTS ( SELECT 1 FROM host_links hl - WHERE hl.host_installation_id = t.owner_device_id + WHERE hl.host_device_id = t.owner_device_id AND hl.account_id = ? ) )", @@ -197,13 +197,13 @@ pub async fn exists_for_account( WHERE t.session_id = $1 AND ( EXISTS ( - SELECT 1 FROM device_installations d - WHERE d.installation_id = t.owner_device_id + SELECT 1 FROM devices d + WHERE d.device_id = t.owner_device_id AND d.account_id = $2 ) OR EXISTS ( SELECT 1 FROM host_links hl - WHERE hl.host_installation_id = t.owner_device_id + WHERE hl.host_device_id = t.owner_device_id AND hl.account_id = $2 ) ) @@ -254,13 +254,13 @@ pub async fn list( AND ( ?5 IS NULL OR EXISTS ( - SELECT 1 FROM device_installations d - WHERE d.installation_id = sessions.owner_device_id + SELECT 1 FROM devices d + WHERE d.device_id = sessions.owner_device_id AND d.account_id = ?5 ) OR EXISTS ( SELECT 1 FROM host_links hl - WHERE hl.host_installation_id = sessions.owner_device_id + WHERE hl.host_device_id = sessions.owner_device_id AND hl.account_id = ?5 ) ) @@ -285,13 +285,13 @@ pub async fn list( AND ( $5::TEXT IS NULL OR EXISTS ( - SELECT 1 FROM device_installations d - WHERE d.installation_id = sessions.owner_device_id + SELECT 1 FROM devices d + WHERE d.device_id = sessions.owner_device_id AND d.account_id = $5 ) OR EXISTS ( SELECT 1 FROM host_links hl - WHERE hl.host_installation_id = sessions.owner_device_id + WHERE hl.host_device_id = sessions.owner_device_id AND hl.account_id = $5 ) ) @@ -340,15 +340,15 @@ pub async fn summaries_for_ids( query.push( ") AND (\ EXISTS (\ - SELECT 1 FROM device_installations d \ - WHERE d.installation_id = sessions.owner_device_id \ + SELECT 1 FROM devices d \ + WHERE d.device_id = sessions.owner_device_id \ AND d.account_id = ", ); query.push_bind(account_id); query.push( ") OR EXISTS (\ SELECT 1 FROM host_links hl \ - WHERE hl.host_installation_id = sessions.owner_device_id \ + WHERE hl.host_device_id = sessions.owner_device_id \ AND hl.account_id = ", ); query.push_bind(account_id); @@ -370,15 +370,15 @@ pub async fn summaries_for_ids( query.push( ") AND (\ EXISTS (\ - SELECT 1 FROM device_installations d \ - WHERE d.installation_id = sessions.owner_device_id \ + SELECT 1 FROM devices d \ + WHERE d.device_id = sessions.owner_device_id \ AND d.account_id = ", ); query.push_bind(account_id); query.push( ") OR EXISTS (\ SELECT 1 FROM host_links hl \ - WHERE hl.host_installation_id = sessions.owner_device_id \ + WHERE hl.host_device_id = sessions.owner_device_id \ AND hl.account_id = ", ); query.push_bind(account_id); @@ -492,7 +492,7 @@ mod tests { async fn seed_agent_host(pool: &SqlitePool) { sqlx::query( - r"INSERT INTO device_installations (installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) + r"INSERT INTO devices (device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) VALUES ('dev1','host','Dev','test-host-public-key-v1',0,0,NULL)", ) .execute(pool) @@ -617,7 +617,7 @@ mod tests { let pool = memory_pool().await; seed_agent_host(&pool).await; sqlx::query( - r"INSERT INTO device_installations (installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) VALUES ('dev2','host','Other','test-host-public-key-v1',0,0,NULL)", + r"INSERT INTO devices (device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) VALUES ('dev2','host','Other','test-host-public-key-v1',0,0,NULL)", ) .execute(&pool) .await @@ -650,8 +650,8 @@ mod tests { .await .unwrap(); sqlx::query( - r"INSERT INTO device_installations - (installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) + r"INSERT INTO devices + (device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) VALUES ('a-phone','mobile','Phone-A',NULL,0,0,?1)", ) .bind(&acct_a.account_id) @@ -659,8 +659,8 @@ mod tests { .await .unwrap(); sqlx::query( - r"INSERT INTO device_installations - (installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) + r"INSERT INTO devices + (device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) VALUES ('b-phone','mobile','Phone-B',NULL,0,0,?1)", ) .bind(&acct_b.account_id) @@ -672,8 +672,8 @@ mod tests { .await .unwrap(); sqlx::query( - r"INSERT INTO device_installations - (installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) + r"INSERT INTO devices + (device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) VALUES ('orphan','mobile','Phone-O',NULL,0,0,?1)", ) .bind(&orphan_acct.account_id) diff --git a/crates/minos-backend/src/store/social/agents.rs b/crates/minos-backend/src/store/social/agents.rs index 5a36c3af..05ed61bb 100644 --- a/crates/minos-backend/src/store/social/agents.rs +++ b/crates/minos-backend/src/store/social/agents.rs @@ -1050,19 +1050,19 @@ pub async fn insert_bot_revision( pub async fn upsert_bot_deployment( store: &impl AsStorePool, agent_id: &str, - host_installation_id: &str, + host_device_id: &str, now_ms: i64, ) -> Result<(), BackendError> { match store.as_store_pool() { StorePoolRef::Sqlite(pool) => { sqlx::query( - "INSERT INTO bot_deployments (agent_id, host_installation_id, status, updated_at_ms) + "INSERT INTO bot_deployments (agent_id, host_device_id, status, updated_at_ms) VALUES (?, ?, 'active', ?) - ON CONFLICT(agent_id, host_installation_id) DO UPDATE SET + ON CONFLICT(agent_id, host_device_id) DO UPDATE SET status = 'active', updated_at_ms = excluded.updated_at_ms", ) .bind(agent_id) - .bind(host_installation_id) + .bind(host_device_id) .bind(now_ms) .execute(pool) .await @@ -1070,13 +1070,13 @@ pub async fn upsert_bot_deployment( } StorePoolRef::Postgres(pool) => { sqlx::query( - "INSERT INTO bot_deployments (agent_id, host_installation_id, status, updated_at_ms) + "INSERT INTO bot_deployments (agent_id, host_device_id, status, updated_at_ms) VALUES ($1, $2, 'active', $3) - ON CONFLICT(agent_id, host_installation_id) DO UPDATE SET + ON CONFLICT(agent_id, host_device_id) DO UPDATE SET status = 'active', updated_at_ms = EXCLUDED.updated_at_ms", ) .bind(agent_id) - .bind(host_installation_id) + .bind(host_device_id) .bind(now_ms) .execute(pool) .await diff --git a/crates/minos-backend/tests/auth_endpoints.rs b/crates/minos-backend/tests/auth_endpoints.rs index df5b90e3..b32b6e29 100644 --- a/crates/minos-backend/tests/auth_endpoints.rs +++ b/crates/minos-backend/tests/auth_endpoints.rs @@ -160,7 +160,7 @@ async fn auth_realtime_ws_ticket_returns_short_lived_browser_upgrade_token() { &mut app, "/v1/realtime/ws-ticket", &[("authorization", &auth_hdr)], - json!({"installation_id": device_id.clone()}), + json!({"device_id": device_id.clone()}), ) .await; assert_eq!(status, StatusCode::OK, "body={body}"); @@ -206,7 +206,7 @@ async fn auth_realtime_ws_ticket_rejects_cross_account_device_rebind() { &mut app, "/v1/realtime/ws-ticket", &[("authorization", &auth_hdr)], - json!({"installation_id": browser_device_id}), + json!({"device_id": browser_device_id}), ) .await; assert_eq!(status, StatusCode::UNAUTHORIZED, "body={body}"); diff --git a/crates/minos-backend/tests/auth_helper.rs b/crates/minos-backend/tests/auth_helper.rs index dacfb759..0cfb4aa2 100644 --- a/crates/minos-backend/tests/auth_helper.rs +++ b/crates/minos-backend/tests/auth_helper.rs @@ -31,7 +31,7 @@ async fn first_connect_resolves_role_without_inserting() { ); assert!( - minos_backend::store::device_installations::get_device(&pool, id) + minos_backend::store::devices::get_device(&pool, id) .await .unwrap() .is_none(), diff --git a/crates/minos-backend/tests/formal_account_contract.rs b/crates/minos-backend/tests/formal_account_contract.rs index a061e6a2..89e15631 100644 --- a/crates/minos-backend/tests/formal_account_contract.rs +++ b/crates/minos-backend/tests/formal_account_contract.rs @@ -4,7 +4,7 @@ use minos_backend::auth::jwt; use minos_backend::http; use minos_backend::http::test_support::{backend_state, TEST_JWT_SECRET}; use minos_backend::store::test_support::{insert_test_client, insert_test_host}; -use minos_backend::store::{device_installations, host_links}; +use minos_backend::store::{devices, host_links}; use minos_domain::{DeviceId, DeviceRole}; use serde_json::json; @@ -35,16 +35,14 @@ async fn post_json( async fn formal_realtime_ws_ticket_uses_account_bearer_without_device_headers() { let state = backend_state().await; let mut app = http::router(state.clone()); - let installation_id = uuid::Uuid::new_v4().to_string(); - let device_id = uuid::Uuid::parse_str(&installation_id) - .map(DeviceId) - .unwrap(); + let device_id = DeviceId::new(); + let device_id_str = device_id.to_string(); let account = minos_backend::store::accounts::create(&state.store, "formal-ticket@example.com") .await .unwrap(); let account_id = account.account_id.clone(); - device_installations::insert_client_for_account( + devices::insert_client_for_account( &state.store, device_id, "browser", @@ -54,17 +52,17 @@ async fn formal_realtime_ws_ticket_uses_account_bearer_without_device_headers() ) .await .unwrap(); - device_installations::touch_last_seen(&state.store, &device_id, 100) + devices::touch_last_seen(&state.store, &device_id, 100) .await .unwrap(); - let access = jwt::sign(TEST_JWT_SECRET.as_bytes(), &account_id, &installation_id).unwrap(); + let access = jwt::sign(TEST_JWT_SECRET.as_bytes(), &account_id, &device_id_str).unwrap(); let auth_header = format!("Bearer {access}"); let (status, body) = post_json( &mut app, "/v1/realtime/ws-ticket", &[("authorization", &auth_header)], - json!({"installation_id": installation_id.clone()}), + json!({"device_id": device_id_str.clone()}), ) .await; @@ -78,8 +76,8 @@ async fn formal_realtime_ws_ticket_uses_account_bearer_without_device_headers() let ticket = body["data"]["ticket"].as_str().unwrap(); let claims = jwt::verify_ws_ticket(TEST_JWT_SECRET.as_bytes(), ticket).unwrap(); assert_eq!(claims.sub, account_id); - assert_eq!(claims.did, installation_id); - let row = device_installations::get_device(&state.store, device_id) + assert_eq!(claims.did, device_id_str); + let row = devices::get_device(&state.store, device_id) .await .unwrap() .unwrap(); @@ -113,7 +111,7 @@ async fn formal_hosts_list_uses_account_bearer_without_device_headers() { ) .await; }; - device_installations::set_account_id(&state.store, &mobile, &account.account_id) + devices::set_account_id(&state.store, &mobile, &account.account_id) .await .unwrap(); host_links::insert_pair(&state.store, host, &account.account_id, mobile, 123) @@ -145,7 +143,7 @@ async fn formal_hosts_list_uses_account_bearer_without_device_headers() { assert_eq!(body["meta"]["request_id"], "req_contract_test"); let hosts = body["data"]["hosts"].as_array().unwrap(); assert_eq!(hosts.len(), 1); - assert_eq!(hosts[0]["host_installation_id"], host.to_string()); + assert_eq!(hosts[0]["host_device_id"], host.to_string()); assert_eq!(hosts[0]["host_display_name"], "Mac Studio"); assert_eq!(hosts[0]["linked_at_ms"], 123); assert_eq!(hosts[0]["online"], false); diff --git a/crates/minos-backend/tests/formal_host_contract.rs b/crates/minos-backend/tests/formal_host_contract.rs index ddaffafd..68b7122b 100644 --- a/crates/minos-backend/tests/formal_host_contract.rs +++ b/crates/minos-backend/tests/formal_host_contract.rs @@ -34,16 +34,16 @@ async fn post_json( } #[tokio::test] -async fn host_bootstrap_nonce_issues_for_valid_installation_id() { +async fn host_bootstrap_nonce_issues_for_valid_device_id() { let state = backend_state().await; - let installation_id = DeviceId::new().to_string(); + let device_id = DeviceId::new().to_string(); let mut app = http::router(state); let (status, body) = post_json( &mut app, "/v1/host/bootstrap/nonce", &[], - json!({"installation_id": installation_id}), + json!({"device_id": device_id}), ) .await; @@ -56,7 +56,7 @@ async fn host_bootstrap_nonce_issues_for_valid_installation_id() { } #[tokio::test] -async fn host_bootstrap_nonce_rejects_invalid_installation_id() { +async fn host_bootstrap_nonce_rejects_invalid_device_id() { let state = backend_state().await; let mut app = http::router(state); @@ -64,7 +64,7 @@ async fn host_bootstrap_nonce_rejects_invalid_installation_id() { &mut app, "/v1/host/bootstrap/nonce", &[], - json!({"installation_id": "not-a-uuid"}), + json!({"device_id": "not-a-uuid"}), ) .await; @@ -75,7 +75,7 @@ async fn host_bootstrap_nonce_rejects_invalid_installation_id() { async fn retired_qr_pairing_routes_return_404() { let state = backend_state().await; let mut app = http::router(state); - let installation_id = DeviceId::new().to_string(); + let device_id = DeviceId::new().to_string(); for path in [ "/v1/host/pairing/request-code", @@ -89,7 +89,7 @@ async fn retired_qr_pairing_routes_return_404() { path, &[], json!({ - "installation_id": installation_id, + "device_id": device_id, "pairing_code": "dead", "nonce": "nonce_x", "signature": "ed25519-sig:x", diff --git a/crates/minos-backend/tests/http_handshake.rs b/crates/minos-backend/tests/http_handshake.rs index f4103758..65fb2df6 100644 --- a/crates/minos-backend/tests/http_handshake.rs +++ b/crates/minos-backend/tests/http_handshake.rs @@ -228,7 +228,7 @@ async fn ws_client_ticket_connect_emits_hello_frame() { other => panic!("expected Hello, got {other:?}"), } - let row = store::device_installations::get_device(&pool, id) + let row = store::devices::get_device(&pool, id) .await .unwrap() .unwrap(); diff --git a/crates/minos-backend/tests/pg_contract_smoke.rs b/crates/minos-backend/tests/pg_contract_smoke.rs index 2a22f73f..7d55563d 100644 --- a/crates/minos-backend/tests/pg_contract_smoke.rs +++ b/crates/minos-backend/tests/pg_contract_smoke.rs @@ -40,8 +40,8 @@ async fn pg_strict_installation_check_and_projects_archive() { // Strict CHECK: host without key must fail. let bad_host = DeviceId::new(); let host_fail = sqlx::query( - r#"INSERT INTO device_installations - (installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) + r#"INSERT INTO devices + (device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) VALUES ($1, 'host', 'bad', NULL, 1, 1, NULL)"#, ) .bind(bad_host.to_string()) @@ -55,8 +55,8 @@ async fn pg_strict_installation_check_and_projects_archive() { // Strict CHECK: client without account_id must fail. let bad_client = DeviceId::new(); let client_fail = sqlx::query( - r#"INSERT INTO device_installations - (installation_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) + r#"INSERT INTO devices + (device_id, kind, display_name, public_key, created_at_ms, last_seen_at_ms, account_id) VALUES ($1, 'mobile', 'bad', NULL, 1, 1, NULL)"#, ) .bind(bad_client.to_string()) @@ -69,7 +69,7 @@ async fn pg_strict_installation_check_and_projects_archive() { // Strict host + client. let host = DeviceId::new(); - store::device_installations::insert_host_with_public_key( + store::devices::insert_host_with_public_key( &store, host, "pg-host", @@ -79,7 +79,7 @@ async fn pg_strict_installation_check_and_projects_archive() { .await .unwrap(); let client = DeviceId::new(); - store::device_installations::insert_client_for_account( + store::devices::insert_client_for_account( &store, client, "pg-phone", diff --git a/crates/minos-backend/tests/pg_migration.rs b/crates/minos-backend/tests/pg_migration.rs index 4ecd460f..b5222ece 100644 --- a/crates/minos-backend/tests/pg_migration.rs +++ b/crates/minos-backend/tests/pg_migration.rs @@ -30,7 +30,7 @@ async fn postgres_migration_applies_parity_tables() { for table in [ "accounts", - "device_installations", + "devices", "projects", "project_members", "audit_events", diff --git a/crates/minos-backend/tests/store_smoke.rs b/crates/minos-backend/tests/store_smoke.rs index da1ce73a..a5484886 100644 --- a/crates/minos-backend/tests/store_smoke.rs +++ b/crates/minos-backend/tests/store_smoke.rs @@ -10,13 +10,13 @@ async fn connect_creates_tables_and_migrates() { // Latest-only schema: host link tables without QR pairing_codes/tokens. for table in [ - "device_installations", + "devices", "accounts", "host_links", "agent_sessions", "agent_turns", "agent_turn_events", - "host_installation_tokens", + "host_tokens", "host_commands", "durable_event_log", "outbox_events", diff --git a/crates/minos-backend/tests/v1_agent_sessions.rs b/crates/minos-backend/tests/v1_agent_sessions.rs index a6b90386..b950ef00 100644 --- a/crates/minos-backend/tests/v1_agent_sessions.rs +++ b/crates/minos-backend/tests/v1_agent_sessions.rs @@ -40,13 +40,9 @@ async fn paired_pair_with_account( .await .unwrap(); // host account_id stays NULL (kind=host CHECK) - minos_backend::store::device_installations::set_account_id( - &state.store, - &ios, - &account.account_id, - ) - .await - .unwrap(); + minos_backend::store::devices::set_account_id(&state.store, &ios, &account.account_id) + .await + .unwrap(); host_links::insert_pair(&state.store, host, &account.account_id, ios, 0) .await .unwrap(); @@ -386,7 +382,7 @@ async fn start_session_dispatches_host_command_and_persists_session() { let initial_turn_id = body["initial_turn_id"].as_str().unwrap().to_string(); assert!(!session_id.is_empty()); assert_eq!(body["conversation_id"], conversation.conversation_id); - assert_eq!(body["host_installation_id"], host_id.to_string()); + assert_eq!(body["host_device_id"], host_id.to_string()); assert!(body["started_at_ms"].as_i64().unwrap() >= 1_000); assert_eq!(body["initial_turn_id"], initial_turn_id); diff --git a/crates/minos-backend/tests/v1_hosts_link.rs b/crates/minos-backend/tests/v1_hosts_link.rs index 3e235dcd..d555da4a 100644 --- a/crates/minos-backend/tests/v1_hosts_link.rs +++ b/crates/minos-backend/tests/v1_hosts_link.rs @@ -9,7 +9,7 @@ use minos_backend::http; use minos_backend::http::test_support::seed_live_connection; use minos_backend::http::test_support::{backend_state, TEST_JWT_SECRET}; use minos_backend::http::v1::hosts::LINK_PATH; -use minos_backend::store::{device_installations, host_installation_tokens, host_links}; +use minos_backend::store::{devices, host_links, host_tokens}; use minos_domain::{DeviceId, DeviceRole}; use serde_json::json; @@ -26,8 +26,8 @@ fn public_key(signing_key: &SigningKey) -> String { ) } -fn signature(signing_key: &SigningKey, installation_id: &str, nonce: &str, path: &str) -> String { - let payload = format!("{installation_id}:{nonce}:{path}"); +fn signature(signing_key: &SigningKey, device_id: &str, nonce: &str, path: &str) -> String { + let payload = format!("{device_id}:{nonce}:{path}"); format!( "ed25519-sig:{}", URL_SAFE_NO_PAD.encode(signing_key.sign(payload.as_bytes()).to_bytes()) @@ -71,15 +71,13 @@ async fn get_json( } async fn register_desktop(state: &http::BackendState, email: &str) -> (String, String, String) { - let installation_id = uuid::Uuid::new_v4().to_string(); - let device_id = uuid::Uuid::parse_str(&installation_id) - .map(DeviceId) - .unwrap(); + let device_id = DeviceId::new(); + let device_id_str = device_id.to_string(); let account = minos_backend::store::accounts::create(&state.store, email) .await .unwrap(); let account_id = account.account_id.clone(); - device_installations::insert_client_for_account( + devices::insert_client_for_account( &state.store, device_id, "desktop", @@ -89,16 +87,16 @@ async fn register_desktop(state: &http::BackendState, email: &str) -> (String, S ) .await .unwrap(); - let access = jwt::sign(TEST_JWT_SECRET.as_bytes(), &account_id, &installation_id).unwrap(); - (access, account_id, installation_id) + let access = jwt::sign(TEST_JWT_SECRET.as_bytes(), &account_id, &device_id_str).unwrap(); + (access, account_id, device_id_str) } -async fn issue_nonce(app: &mut axum::Router, installation_id: &str) -> String { +async fn issue_nonce(app: &mut axum::Router, device_id: &str) -> String { let (status, body) = post_json( app, "/v1/host/bootstrap/nonce", &[], - json!({"installation_id": installation_id}), + json!({"device_id": device_id}), ) .await; assert_eq!(status, StatusCode::OK, "body={body}"); @@ -125,7 +123,7 @@ async fn host_link_unlink_list_round_trip() { "/v1/hosts/link", &[("authorization", &auth)], json!({ - "installation_id": host_id, + "device_id": host_id, "nonce": nonce, "public_key": pubkey, "signature": sig, @@ -134,7 +132,7 @@ async fn host_link_unlink_list_round_trip() { ) .await; assert_eq!(status, StatusCode::OK, "body={body}"); - assert_eq!(body["data"]["host_installation_id"], host_id); + assert_eq!(body["data"]["host_device_id"], host_id); let token = body["data"]["host_installation_token"] .as_str() .unwrap() @@ -147,7 +145,7 @@ async fn host_link_unlink_list_round_trip() { assert!(host_links::exists(&state.store, host, &account_id) .await .unwrap()); - let host_row = device_installations::get_device(&state.store, host) + let host_row = devices::get_device(&state.store, host) .await .unwrap() .unwrap(); @@ -167,7 +165,7 @@ async fn host_link_unlink_list_round_trip() { assert_eq!(status, StatusCode::OK, "body={body}"); let hosts = body["data"]["hosts"].as_array().unwrap(); assert_eq!(hosts.len(), 1); - assert_eq!(hosts[0]["host_installation_id"], host_id); + assert_eq!(hosts[0]["host_device_id"], host_id); assert_eq!(hosts[0]["host_display_name"], "Studio Mac"); assert_eq!(hosts[0]["online"], true); @@ -175,7 +173,7 @@ async fn host_link_unlink_list_round_trip() { &mut app, "/v1/hosts/unlink", &[("authorization", &auth)], - json!({"host_installation_id": host_id}), + json!({"host_device_id": host_id}), ) .await; assert_eq!(status, StatusCode::NO_CONTENT, "body={body}"); @@ -186,7 +184,7 @@ async fn host_link_unlink_list_round_trip() { // Token must be revoked (verify_active_token returns None) let token_hash = minos_backend::host_link::sha256_hex(&token); - let active = host_installation_tokens::verify_active_token( + let active = host_tokens::verify_active_token( &state.store, &token_hash, chrono::Utc::now().timestamp_millis(), @@ -213,7 +211,7 @@ async fn multi_host_list_for_account() { "/v1/hosts/link", &[("authorization", &auth)], json!({ - "installation_id": host_id, + "device_id": host_id, "nonce": nonce, "public_key": public_key(&key), "signature": signature(&key, &host_id, &nonce, LINK_PATH), @@ -252,7 +250,7 @@ async fn bad_proof_is_rejected() { "/v1/hosts/link", &[("authorization", &auth)], json!({ - "installation_id": host_id, + "device_id": host_id, "nonce": nonce, "public_key": public_key(&key), "signature": bad_sig, @@ -284,7 +282,7 @@ async fn host_already_linked_elsewhere_returns_409() { "/v1/hosts/link", &[("authorization", &auth_a)], json!({ - "installation_id": host_id, + "device_id": host_id, "nonce": nonce, "public_key": pubkey, "signature": signature(&key, &host_id, &nonce, LINK_PATH), @@ -300,7 +298,7 @@ async fn host_already_linked_elsewhere_returns_409() { "/v1/hosts/link", &[("authorization", &auth_b)], json!({ - "installation_id": host_id, + "device_id": host_id, "nonce": nonce, "public_key": pubkey, "signature": signature(&key, &host_id, &nonce, LINK_PATH), @@ -330,7 +328,7 @@ async fn same_account_re_link_rotates_token() { "/v1/hosts/link", &[("authorization", &auth)], json!({ - "installation_id": host_id, + "device_id": host_id, "nonce": nonce, "public_key": pubkey, "signature": signature(&key, &host_id, &nonce, LINK_PATH), @@ -350,7 +348,7 @@ async fn same_account_re_link_rotates_token() { "/v1/hosts/link", &[("authorization", &auth)], json!({ - "installation_id": host_id, + "device_id": host_id, "nonce": nonce, "public_key": pubkey, "signature": signature(&key, &host_id, &nonce, LINK_PATH), @@ -369,7 +367,7 @@ async fn same_account_re_link_rotates_token() { .unwrap()); let old_hash = minos_backend::host_link::sha256_hex(&token1); - let active_old = host_installation_tokens::verify_active_token( + let active_old = host_tokens::verify_active_token( &state.store, &old_hash, chrono::Utc::now().timestamp_millis(), @@ -382,7 +380,7 @@ async fn same_account_re_link_rotates_token() { ); let new_hash = minos_backend::host_link::sha256_hex(&token2); - let active_new = host_installation_tokens::verify_active_token( + let active_new = host_tokens::verify_active_token( &state.store, &new_hash, chrono::Utc::now().timestamp_millis(), @@ -406,7 +404,7 @@ async fn invalid_nonce_is_rejected() { "/v1/hosts/link", &[("authorization", &auth)], json!({ - "installation_id": host_id, + "device_id": host_id, "nonce": "nonce_notreal", "public_key": public_key(&key), "signature": signature(&key, &host_id, "nonce_notreal", LINK_PATH), diff --git a/crates/minos-backend/tests/v1_pairing.rs b/crates/minos-backend/tests/v1_pairing.rs index 37c6e423..c8e795e1 100644 --- a/crates/minos-backend/tests/v1_pairing.rs +++ b/crates/minos-backend/tests/v1_pairing.rs @@ -55,7 +55,7 @@ async fn retired_pairing_routes_return_404() { post( &mut app, "/v1/pairing/revoke", - json!({"host_installation_id": host_id.to_string()}), + json!({"host_device_id": host_id.to_string()}), ) .await, StatusCode::NOT_FOUND diff --git a/crates/minos-backend/tests/v1_projects.rs b/crates/minos-backend/tests/v1_projects.rs index 1fe9ef66..d81d0f61 100644 --- a/crates/minos-backend/tests/v1_projects.rs +++ b/crates/minos-backend/tests/v1_projects.rs @@ -84,13 +84,9 @@ async fn formal_project_routes_expose_canonical_conversation_and_agent_session_f ) .await; }; - minos_backend::store::device_installations::set_account_id( - &state.store, - &mobile, - &account.account_id, - ) - .await - .unwrap(); + minos_backend::store::devices::set_account_id(&state.store, &mobile, &account.account_id) + .await + .unwrap(); minos_backend::store::host_links::insert_pair( &state.store, host_device_id, diff --git a/crates/minos-backend/tests/v1_social.rs b/crates/minos-backend/tests/v1_social.rs index 5de91ed1..f669dd9b 100644 --- a/crates/minos-backend/tests/v1_social.rs +++ b/crates/minos-backend/tests/v1_social.rs @@ -5,8 +5,8 @@ use minos_backend::http::test_support::seed_live_connection; use minos_backend::http::{router, test_support::backend_state, test_support::TEST_JWT_SECRET}; use minos_backend::store::test_support::{insert_test_client, insert_test_host}; use minos_backend::store::{ - agent_sessions, device_installations, durable_event_log, host_commands, host_links, raw_events, - sessions, social, + agent_sessions, devices, durable_event_log, host_commands, host_links, raw_events, sessions, + social, }; use minos_domain::{AgentName, DeviceId, DeviceRole}; use pretty_assertions::assert_eq; @@ -62,7 +62,7 @@ async fn seed_host_pair_for_account( .await; }; // host account_id stays NULL (kind=host CHECK) - device_installations::set_account_id(&state.store, &mobile_device_id, account_id) + devices::set_account_id(&state.store, &mobile_device_id, account_id) .await .unwrap(); host_links::insert_pair( @@ -479,7 +479,7 @@ async fn assert_agent_start_host_command( .unwrap() .expect("host command should be recorded for social agent session start"); - assert_eq!(row.host_installation_id, host_device_id); + assert_eq!(row.host_device_id, host_device_id); assert_eq!(row.method, "agent_session.start"); assert_eq!(row.agent_session_id.as_deref(), Some(session_id)); assert_eq!( @@ -525,7 +525,7 @@ async fn assert_agent_send_host_command( .unwrap() .expect("host command should be recorded for social agent input"); - assert_eq!(row.host_installation_id, host_device_id); + assert_eq!(row.host_device_id, host_device_id); assert_eq!(row.method, "agent_session.send_input"); assert_eq!(row.agent_session_id.as_deref(), Some(session_id)); assert_eq!( @@ -956,7 +956,7 @@ async fn delete_conversation_stops_running_agent_session_and_hides_for_caller() .await .unwrap() .expect("delete should enqueue stop for running agent session"); - assert_eq!(stop_command.host_installation_id, host_device_id); + assert_eq!(stop_command.host_device_id, host_device_id); assert_eq!(stop_command.method, "agent_session.stop"); assert_eq!(stop_command.params_json["session_id"], "sess-delete-1"); assert!( diff --git a/crates/minos-backend/tests/ws_devices.rs b/crates/minos-backend/tests/ws_devices.rs index 047e5b36..b09f31d2 100644 --- a/crates/minos-backend/tests/ws_devices.rs +++ b/crates/minos-backend/tests/ws_devices.rs @@ -60,11 +60,11 @@ fn public_key(signing_key: &SigningKey) -> String { fn signature_for_path( signing_key: &SigningKey, - installation_id: &str, + device_id: &str, nonce: &str, path: &str, ) -> String { - let payload = format!("{installation_id}:{nonce}:{path}"); + let payload = format!("{device_id}:{nonce}:{path}"); format!( "ed25519-sig:{}", URL_SAFE_NO_PAD.encode(signing_key.sign(payload.as_bytes()).to_bytes()) @@ -119,10 +119,10 @@ async fn formally_paired_host(relay: &Relay) -> anyhow::Result anyhow::Result anyhow::Result anyhow ) .await; }; - store::device_installations::set_account_id(&relay.pool, &browser_id, &account_id).await?; + store::devices::set_account_id(&relay.pool, &browser_id, &account_id).await?; let ticket = issue_client_ws_ticket(&relay, &account_id, browser_id, DeviceRole::BrowserAdmin).await?; @@ -565,7 +565,7 @@ async fn ws_client_accepts_formal_ticket_query_auth() -> anyhow::Result<()> { ) .await; }; - store::device_installations::set_account_id(&relay.pool, &browser_id, &account_id).await?; + store::devices::set_account_id(&relay.pool, &browser_id, &account_id).await?; let ticket = issue_client_ws_ticket(&relay, &account_id, browser_id, DeviceRole::BrowserAdmin).await?; @@ -604,7 +604,7 @@ async fn ws_client_rejects_reused_formal_ticket() -> anyhow::Result<()> { ) .await; }; - store::device_installations::set_account_id(&relay.pool, &browser_id, &account_id).await?; + store::devices::set_account_id(&relay.pool, &browser_id, &account_id).await?; let ticket = issue_client_ws_ticket(&relay, &account_id, browser_id, DeviceRole::BrowserAdmin).await?; @@ -697,7 +697,7 @@ async fn ws_host_last_link_revoke_closes_live_socket_with_auth_revoked() -> anyh "/v1/hosts/unlink", &[("authorization", fixture.account_auth_header.as_str())], json!({ - "host_installation_id": fixture.host.to_string() + "host_device_id": fixture.host.to_string() }), ) .await; @@ -743,12 +743,12 @@ async fn ws_client_rejects_legacy_ws_ticket_after_device_account_changes() -> an ) .await; }; - store::device_installations::set_account_id(&relay.pool, &browser_id, &account_a).await?; + store::devices::set_account_id(&relay.pool, &browser_id, &account_a).await?; let ticket = issue_client_ws_ticket(&relay, &account_a, browser_id, DeviceRole::BrowserAdmin).await?; - store::device_installations::set_account_id(&relay.pool, &browser_id, &account_b).await?; + store::devices::set_account_id(&relay.pool, &browser_id, &account_b).await?; let mut ws = connect_gateway_ws_with_legacy_ticket_query(&relay, "/ws/client", &ticket).await?; expect_close_code(&mut ws, 4401, "auth_revoked").await?; diff --git a/crates/minos-backend/tests/ws_gateway.rs b/crates/minos-backend/tests/ws_gateway.rs index a3fc2713..61bac459 100644 --- a/crates/minos-backend/tests/ws_gateway.rs +++ b/crates/minos-backend/tests/ws_gateway.rs @@ -218,7 +218,7 @@ async fn seed_session( conversation_id: conversation_id.to_string(), project_id: None, agent_id, - host_installation_id: Some(host_id.to_string()), + host_device_id: Some(host_id.to_string()), workspace_path: None, initial_user_message: initial_user_message.map(str::to_string), origin_message_id: None, @@ -375,7 +375,7 @@ async fn client_subscribe_replays_agent_session_durable_events() -> anyhow::Resu assert_eq!(topic, format!("agent_session:{}", output.session_id)); assert_eq!(kind, "agent_session_started"); assert_eq!(payload["session_id"], output.session_id); - assert_eq!(payload["host_installation_id"], host_id.to_string()); + assert_eq!(payload["host_device_id"], host_id.to_string()); } other => panic!("expected DurableEvent replay, got {other:?}"), } @@ -460,7 +460,7 @@ async fn seed_host_durable_events( let event_id = format!("seed-host-{host}-{seq}"); let payload = serde_json::json!({ "kind": "host_force_close", - "host_installation_id": host, + "host_device_id": host, "reason": "seed", "at_ms": seq * 1000, }); diff --git a/crates/minos-daemon/src/local_rpc.rs b/crates/minos-daemon/src/local_rpc.rs index cadd0022..43ecaa14 100644 --- a/crates/minos-daemon/src/local_rpc.rs +++ b/crates/minos-daemon/src/local_rpc.rs @@ -82,7 +82,7 @@ impl LocalDaemonRpcServer for LocalRpcImpl { return Err(host_link_unavailable()); }; relay - .sign_link_proof(&req.installation_id, &req.nonce) + .sign_link_proof(&req.device_id, &req.nonce) .map_err(rpc_err) } diff --git a/crates/minos-daemon/src/relay_client.rs b/crates/minos-daemon/src/relay_client.rs index 67b44428..6b3f3570 100644 --- a/crates/minos-daemon/src/relay_client.rs +++ b/crates/minos-daemon/src/relay_client.rs @@ -243,21 +243,21 @@ impl RelayClient { ) -> Result { let nonce = self.inner.http.fetch_bootstrap_nonce().await?; Ok(minos_protocol::HostPrepareLinkResponse { - installation_id: self.inner.http.device_id().to_string(), + device_id: self.inner.http.device_id().to_string(), public_key: self.inner.http.host_public_key(), nonce, }) } - /// Sign Host Link proof for the local installation. + /// Sign Host Link proof for this Mac's DeviceId. pub fn sign_link_proof( &self, - installation_id: &str, + device_id: &str, nonce: &str, ) -> Result { - if installation_id != self.inner.http.device_id().to_string() { + if device_id != self.inner.http.device_id().to_string() { return Err(MinosError::BackendInternal { - message: "installation_id does not match this host".into(), + message: "device_id does not match this host".into(), }); } Ok(minos_protocol::HostSignLinkProofResponse { diff --git a/crates/minos-daemon/src/relay_http.rs b/crates/minos-daemon/src/relay_http.rs index 2282e60e..8e7749de 100644 --- a/crates/minos-daemon/src/relay_http.rs +++ b/crates/minos-daemon/src/relay_http.rs @@ -28,7 +28,7 @@ const HOST_SELF_PATH: &str = "/v1/host/installations/self"; #[derive(Debug, serde::Serialize)] struct BootstrapNonceRequest { - installation_id: String, + device_id: String, } #[derive(Debug, Deserialize)] @@ -48,7 +48,7 @@ struct HostSelfData { #[derive(Debug, Deserialize)] struct HostSelfLinkSummary { - linked_via_installation_id: String, + linked_via_device_id: String, link_display_name: String, paired_at_ms: i64, #[serde(default)] @@ -225,7 +225,7 @@ impl RelayHttpClient { None, false, &BootstrapNonceRequest { - installation_id: self.device_id.to_string(), + device_id: self.device_id.to_string(), }, )?; let resp = self.execute(&url, request).await?; @@ -379,7 +379,7 @@ fn host_self_links_to_peer_summaries( ) -> Result, MinosError> { let mut peers = Vec::with_capacity(links.len()); for link in links { - let mobile_device_id = uuid::Uuid::parse_str(&link.linked_via_installation_id) + let mobile_device_id = uuid::Uuid::parse_str(&link.linked_via_device_id) .map(DeviceId) .map_err(|e| MinosError::BackendInternal { message: format!("decode host self linked device id: {e}"), @@ -498,7 +498,7 @@ mod tests { None, true, &serde_json::json!({ - "installation_id": client.device_id.to_string(), + "device_id": client.device_id.to_string(), }), ) .unwrap(); @@ -513,7 +513,7 @@ mod tests { fn host_self_links_preserve_presence_fields() { let mobile_device_id = DeviceId::new(); let peers = host_self_links_to_peer_summaries(vec![HostSelfLinkSummary { - linked_via_installation_id: mobile_device_id.to_string(), + linked_via_device_id: mobile_device_id.to_string(), link_display_name: "Owner Phone".into(), paired_at_ms: 100, last_active_at_ms: 900, diff --git a/crates/minos-daemon/tests/agent_e2e.rs b/crates/minos-daemon/tests/agent_e2e.rs index 539ca5ae..f072e968 100644 --- a/crates/minos-daemon/tests/agent_e2e.rs +++ b/crates/minos-daemon/tests/agent_e2e.rs @@ -301,8 +301,7 @@ async fn register_formal_host( ) .await; }; - store::device_installations::set_account_id(&relay.pool, &mobile_id, &account.account_id) - .await?; + store::devices::set_account_id(&relay.pool, &mobile_id, &account.account_id).await?; let linked = relay .state diff --git a/crates/minos-daemon/tests/e2e.rs b/crates/minos-daemon/tests/e2e.rs index 5a9c98ed..e4b96954 100644 --- a/crates/minos-daemon/tests/e2e.rs +++ b/crates/minos-daemon/tests/e2e.rs @@ -228,12 +228,7 @@ async fn register_formal_host(relay: &Relay, host_id: DeviceId) -> anyhow::Resul ) .await; }; - store::device_installations::set_account_id( - &relay.state.store, - &mobile_id, - &account.account_id, - ) - .await?; + store::devices::set_account_id(&relay.state.store, &mobile_id, &account.account_id).await?; let linked = relay .state @@ -282,7 +277,7 @@ async fn pair_and_list_clis_over_relay() -> anyhow::Result<()> { .header("content-type", "application/json") .header("authorization", format!("Bearer {}", paired.bearer)) .body(axum::body::Body::from( - json!({ "host_installation_id": host_id.to_string() }).to_string(), + json!({ "host_device_id": host_id.to_string() }).to_string(), ))?; let (status, body) = send_http(&relay, request).await; if status != axum::http::StatusCode::OK { diff --git a/crates/minos-daemon/tests/relay_client_smoke.rs b/crates/minos-daemon/tests/relay_client_smoke.rs index 45d6fcec..7c56727d 100644 --- a/crates/minos-daemon/tests/relay_client_smoke.rs +++ b/crates/minos-daemon/tests/relay_client_smoke.rs @@ -179,7 +179,7 @@ async fn register_formal_host( ) .await; }; - store::device_installations::set_account_id(pool, &mobile_id, &account.account_id).await?; + store::devices::set_account_id(pool, &mobile_id, &account.account_id).await?; let linked = HostLinkService::new(pool.clone()) .link_host(host_id, &account.account_id, mobile_id, Some("Fan's Mac")) @@ -266,8 +266,7 @@ async fn apply_link_token_persists_and_connects() -> anyhow::Result<()> { ) .await; }; - store::device_installations::set_account_id(&relay.pool, &mobile_id, &account.account_id) - .await?; + store::devices::set_account_id(&relay.pool, &mobile_id, &account.account_id).await?; let linked = HostLinkService::new(relay.pool.clone()) .link_host(host_id, &account.account_id, mobile_id, Some(&mac_name)) .await diff --git a/crates/minos-domain/src/role.rs b/crates/minos-domain/src/role.rs index 48265baf..42d12f5d 100644 --- a/crates/minos-domain/src/role.rs +++ b/crates/minos-domain/src/role.rs @@ -1,9 +1,9 @@ //! `DeviceRole` — classifies which side of the relay a device speaks from. //! //! Kebab-case string is the single **wire** format (headers, JWT, envelopes). -//! Storage uses a shorter `installation_kind` vocabulary (`mobile` / `browser` / -//! `desktop` / `host`); map via [`DeviceRole::to_installation_kind`] / -//! [`DeviceRole::from_installation_kind`]. +//! Storage uses a shorter `device_kind` vocabulary (`mobile` / `browser` / +//! `desktop` / `host`); map via [`DeviceRole::to_device_kind`] / +//! [`DeviceRole::from_device_kind`]. use serde::{Deserialize, Serialize}; use std::fmt; @@ -43,9 +43,9 @@ impl DeviceRole { ) } - /// Map wire role → `device_installations.kind` / `installation_kind`. + /// Map wire role → `devices.kind`. #[must_use] - pub const fn to_installation_kind(self) -> &'static str { + pub const fn to_device_kind(self) -> &'static str { match self { Self::AgentHost => "host", Self::MobileClient => "mobile", @@ -55,13 +55,13 @@ impl DeviceRole { } /// Map storage `kind` → wire role. - pub fn from_installation_kind(kind: &str) -> Result { + pub fn from_device_kind(kind: &str) -> Result { match kind { "host" => Ok(Self::AgentHost), "mobile" => Ok(Self::MobileClient), "browser" => Ok(Self::BrowserAdmin), "desktop" => Ok(Self::DesktopConsole), - other => Err(format!("unknown installation kind: {other}")), + other => Err(format!("unknown device kind: {other}")), } } } @@ -107,15 +107,15 @@ mod tests { } #[test] - fn installation_kind_round_trips() { + fn device_kind_round_trips() { for role in [ DeviceRole::AgentHost, DeviceRole::MobileClient, DeviceRole::BrowserAdmin, DeviceRole::DesktopConsole, ] { - let kind = role.to_installation_kind(); - let back = DeviceRole::from_installation_kind(kind).unwrap(); + let kind = role.to_device_kind(); + let back = DeviceRole::from_device_kind(kind).unwrap(); assert_eq!(back, role, "kind round-trip failed for {role:?}"); } } diff --git a/crates/minos-mobile/src/bin/fake-peer.rs b/crates/minos-mobile/src/bin/fake-peer.rs index 9e312d22..61bb4d57 100644 --- a/crates/minos-mobile/src/bin/fake-peer.rs +++ b/crates/minos-mobile/src/bin/fake-peer.rs @@ -82,7 +82,7 @@ enum Cmd { agent: String, /// Optional host installation id; default = first online, else first linked. #[arg(long)] - host_installation_id: Option, + host_device_id: Option, }, } @@ -131,7 +131,7 @@ async fn main() -> Result<()> { prompt, device_name, agent, - host_installation_id, + host_device_id, } => { let _agent = parse_agent(&agent)?; run_smoke_session( @@ -139,7 +139,7 @@ async fn main() -> Result<()> { &supabase_access_token, &prompt, &device_name, - host_installation_id.as_deref(), + host_device_id.as_deref(), ) .await } @@ -194,7 +194,7 @@ async fn run_smoke_session( supabase_access_token: &str, prompt: &str, device_name: &str, - host_installation_id: Option<&str>, + host_device_id: Option<&str>, ) -> Result<()> { let auth = exchange_account(backend, supabase_access_token, device_name).await?; let http = MobileHttpClient::new(backend, auth.device_id, device_name) @@ -203,7 +203,7 @@ async fn run_smoke_session( .list_hosts(&auth.access_token) .await .context("GET /v1/hosts")?; - let host = pick_host(&hosts.hosts, host_installation_id)?; + let host = pick_host(&hosts.hosts, host_device_id)?; eprintln!( "using host={} online={} name={}", host.host_device_id, host.online, host.host_display_name @@ -264,7 +264,7 @@ fn pick_host( .iter() .find(|h| h.host_device_id.to_string() == id) .cloned() - .with_context(|| format!("host_installation_id {id} not in GET /v1/hosts")); + .with_context(|| format!("host_device_id {id} not in GET /v1/hosts")); } Ok(hosts .iter() diff --git a/crates/minos-mobile/src/client.rs b/crates/minos-mobile/src/client.rs index f7a06408..d6d950b4 100644 --- a/crates/minos-mobile/src/client.rs +++ b/crates/minos-mobile/src/client.rs @@ -982,12 +982,12 @@ impl MobileClient { /// Detect the CLI agents available on the paired runtime. pub async fn list_clis(&self) -> Result { - let host_installation_id = self.require_active_host().await?.to_string(); + let host_device_id = self.require_active_host().await?.to_string(); auth_http_call!(self, |http, access| { http.list_clis_http( &access, minos_protocol::ListHostClisRequest { - host_installation_id: host_installation_id.clone(), + host_device_id: host_device_id.clone(), }, ) }) @@ -999,7 +999,7 @@ impl MobileClient { host_device_id: Option, force_reload: bool, ) -> Result { - let host_installation_id = if let Some(host_device_id) = host_device_id { + let host_device_id = if let Some(host_device_id) = host_device_id { if Uuid::parse_str(&host_device_id).is_err() { return Err(MinosError::RpcCallFailed { method: "minos_list_host_skills".into(), @@ -1014,7 +1014,7 @@ impl MobileClient { http.list_host_skills_http( &access, minos_protocol::ListHostSkillsCommandRequest { - host_installation_id: host_installation_id.clone(), + host_device_id: host_device_id.clone(), workspace: String::new(), force_reload, }, @@ -1029,7 +1029,7 @@ impl MobileClient { root: Option, limit: u32, ) -> Result { - let host_installation_id = if let Some(host_device_id) = host_device_id { + let host_device_id = if let Some(host_device_id) = host_device_id { if Uuid::parse_str(&host_device_id).is_err() { return Err(MinosError::RpcCallFailed { method: "minos_list_host_workspaces".into(), @@ -1044,7 +1044,7 @@ impl MobileClient { http.list_host_workspaces_http( &access, minos_protocol::ListHostWorkspacesCommandRequest { - host_installation_id: host_installation_id.clone(), + host_device_id: host_device_id.clone(), root: root.clone(), limit, }, @@ -1059,7 +1059,7 @@ impl MobileClient { path: String, enabled: bool, ) -> Result { - let host_installation_id = if let Some(host_device_id) = host_device_id { + let host_device_id = if let Some(host_device_id) = host_device_id { if Uuid::parse_str(&host_device_id).is_err() { return Err(MinosError::RpcCallFailed { method: "minos_write_host_skill_config".into(), @@ -1074,7 +1074,7 @@ impl MobileClient { http.write_host_skill_config_http( &access, minos_protocol::WriteHostSkillConfigCommandRequest { - host_installation_id: host_installation_id.clone(), + host_device_id: host_device_id.clone(), workspace: String::new(), path: path.clone(), enabled, diff --git a/crates/minos-mobile/src/http.rs b/crates/minos-mobile/src/http.rs index 93aa5af1..7f7c386a 100644 --- a/crates/minos-mobile/src/http.rs +++ b/crates/minos-mobile/src/http.rs @@ -78,7 +78,7 @@ struct ListHostsData { /// returned; callers that still need a `paired_via_device_id` get a nil id. #[derive(Debug, Deserialize)] struct FormalHostSummary { - host_installation_id: String, + host_device_id: String, host_display_name: String, linked_at_ms: i64, #[serde(default)] @@ -96,7 +96,7 @@ struct SupabaseExchangeRequest<'a> { #[derive(Debug, Serialize)] struct UnlinkHostRequest { - host_installation_id: String, + host_device_id: String, } #[derive(Debug, Serialize)] @@ -349,7 +349,7 @@ impl MobileHttpClient { let url = format!("{}{path}", self.base); let trace_id = start_http_trace(Method::POST.as_str(), path, None, None); let body = UnlinkHostRequest { - host_installation_id: host_device_id.to_string(), + host_device_id: host_device_id.to_string(), }; let request = self.request_with_json(Method::POST, &url, Some(access_token), &body)?; let resp = self.execute_with_trace(trace_id, &url, request).await?; @@ -1736,14 +1736,14 @@ impl MobileHttpClient { pub async fn fetch_ws_ticket( &self, access_token: &str, - installation_id: &str, + device_id: &str, ) -> Result { let path = "/v1/realtime/ws-ticket"; let url = format!("{}{path}", self.base); let trace_id = start_http_trace(Method::POST.as_str(), path, None, Some("ws-ticket".into())); let body = RealtimeWsTicketRequest { - installation_id: Some(installation_id.to_string()), + device_id: Some(device_id.to_string()), }; let request = self.request_with_json(Method::POST, &url, Some(access_token), &body)?; let resp = self.execute_with_trace(trace_id, &url, request).await?; @@ -2198,10 +2198,7 @@ fn formal_hosts_to_me_hosts(data: ListHostsData) -> Result jsonrpsee::core::RpcResult; - /// Sign `"{installation_id}:{nonce}:v1/hosts/link"` with the host key. + /// Sign `"{device_id}:{nonce}:v1/hosts/link"` with the host key. #[method(name = "host_sign_link_proof")] async fn host_sign_link_proof( &self, diff --git a/crates/minos-protocol/src/messages.rs b/crates/minos-protocol/src/messages.rs index 8a214cfc..b51e9973 100644 --- a/crates/minos-protocol/src/messages.rs +++ b/crates/minos-protocol/src/messages.rs @@ -40,7 +40,7 @@ pub struct HostSummary { pub paired_via_device_id: DeviceId, #[serde(default)] pub online: bool, - /// Best-effort last activity from hub (`device_installations.last_seen_at_ms`). + /// Best-effort last activity from hub (`devices.last_seen_at_ms`). #[serde(default)] pub last_seen_at_ms: i64, } @@ -717,7 +717,7 @@ pub struct HealthResponse { /// Daemon local RPC: prepare same-account host link proof material. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct HostPrepareLinkResponse { - pub installation_id: String, + pub device_id: String, pub public_key: String, pub nonce: String, } @@ -725,7 +725,7 @@ pub struct HostPrepareLinkResponse { /// Daemon local RPC: sign the Host Link Ed25519 proof. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct HostSignLinkProofParams { - pub installation_id: String, + pub device_id: String, pub nonce: String, } @@ -754,7 +754,7 @@ pub struct HostClearCredentialResponse { /// Account-side request to target one paired host for a CLI scan. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct ListHostClisRequest { - pub host_installation_id: String, + pub host_device_id: String, } pub type ListClisResponse = Vec; @@ -771,7 +771,7 @@ pub struct ListHostSkillsRequest { /// Account-side request to inspect skills on one paired host. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct ListHostSkillsCommandRequest { - pub host_installation_id: String, + pub host_device_id: String, pub workspace: String, #[serde(default)] pub force_reload: bool, @@ -791,7 +791,7 @@ pub struct ListHostWorkspacesRequest { /// Account-side request to inspect workspace directories on one paired host. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct ListHostWorkspacesCommandRequest { - pub host_installation_id: String, + pub host_device_id: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub root: Option, #[serde(default)] @@ -854,7 +854,7 @@ pub struct WriteHostSkillConfigRequest { /// Account-side request to update one host skill toggle. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct WriteHostSkillConfigCommandRequest { - pub host_installation_id: String, + pub host_device_id: String, pub workspace: String, pub path: String, pub enabled: bool, @@ -1975,7 +1975,7 @@ mod tests { #[test] fn list_host_clis_request_round_trip() { let req = ListHostClisRequest { - host_installation_id: "host-123".into(), + host_device_id: "host-123".into(), }; let json = serde_json::to_string(&req).unwrap(); let back: ListHostClisRequest = serde_json::from_str(&json).unwrap(); @@ -1985,7 +1985,7 @@ mod tests { #[test] fn list_host_skills_command_request_round_trip() { let req = ListHostSkillsCommandRequest { - host_installation_id: "host-123".into(), + host_device_id: "host-123".into(), workspace: "/tmp/workspace".into(), force_reload: true, }; @@ -1997,7 +1997,7 @@ mod tests { #[test] fn write_host_skill_config_command_request_round_trip() { let req = WriteHostSkillConfigCommandRequest { - host_installation_id: "host-123".into(), + host_device_id: "host-123".into(), workspace: String::new(), path: "/tmp/skill".into(), enabled: false, diff --git a/crates/minos-protocol/src/realtime.rs b/crates/minos-protocol/src/realtime.rs index 322f9094..51257dc5 100644 --- a/crates/minos-protocol/src/realtime.rs +++ b/crates/minos-protocol/src/realtime.rs @@ -122,7 +122,7 @@ pub enum TopicParseError { #[derive(Debug, Clone, PartialEq, Eq)] pub enum ConnectionPrincipal { Account { account_id: String }, - Host { host_installation_id: String }, + Host { host_device_id: String }, } impl ConnectionPrincipal { @@ -417,13 +417,13 @@ pub enum PresencePrincipalKind { AccountClient, } -/// Live presence of one installation. Delivered as +/// Live presence of one device. Delivered as /// `StreamEvent { kind: "presence", payload }` on interested topics /// (`account:{id}` for host presence, `host:{id}` for account-client presence). /// Ephemeral: cold path is HTTP list with `online` + `last_seen_at_ms`. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct PresencePayload { - pub installation_id: String, + pub device_id: String, pub principal_kind: PresencePrincipalKind, pub online: bool, pub last_seen_at_ms: i64, @@ -552,7 +552,7 @@ pub enum DurableEvent { /// Account roster: host paired (T2 digest on `account:{id}`). HostLinked { account_id: String, - host_installation_id: String, + host_device_id: String, pair_id: String, at_ms: i64, /// Display name for immediate list upsert without HTTP. @@ -562,7 +562,7 @@ pub enum DurableEvent { /// Account roster: host unlinked (T2 digest on `account:{id}`). HostUnlinked { account_id: String, - host_installation_id: String, + host_device_id: String, at_ms: i64, }, /// Social graph: friend request created / accepted / rejected (T2 on account). @@ -581,7 +581,7 @@ pub enum DurableEvent { conversation_id: String, #[serde(default, skip_serializing_if = "Option::is_none")] project_id: Option, - host_installation_id: String, + host_device_id: String, agent_id: String, at_ms: i64, }, @@ -679,13 +679,13 @@ pub enum DurableEvent { at_ms: i64, }, HostForceClose { - host_installation_id: String, + host_device_id: String, reason: String, at_ms: i64, }, HostCommandIssued { command_id: String, - host_installation_id: String, + host_device_id: String, #[serde(default, skip_serializing_if = "Option::is_none")] agent_session_id: Option, method: String, @@ -808,14 +808,10 @@ impl DurableEvent { | Self::ProjectArchived { project_id, .. } => { RealtimeTopic::Project(project_id.clone()) } - Self::HostForceClose { - host_installation_id, - .. + Self::HostForceClose { host_device_id, .. } + | Self::HostCommandIssued { host_device_id, .. } => { + RealtimeTopic::Host(host_device_id.clone()) } - | Self::HostCommandIssued { - host_installation_id, - .. - } => RealtimeTopic::Host(host_installation_id.clone()), } } } @@ -898,7 +894,7 @@ mod tests { topic: "account:abc".into(), topic_seq: 7, kind: "host_linked".into(), - payload: serde_json::json!({"host_installation_id": "host-1"}), + payload: serde_json::json!({"host_device_id": "host-1"}), event_id: "evt-1".into(), }; let json = serde_json::to_string(&frame).unwrap(); @@ -1137,7 +1133,7 @@ mod tests { fn durable_event_round_trip() { let event = DurableEvent::HostCommandIssued { command_id: "cmd-1".into(), - host_installation_id: "host-1".into(), + host_device_id: "host-1".into(), agent_session_id: Some("sess-1".into()), method: "start_agent".into(), params: serde_json::json!({"agent": "codex"}), diff --git a/crates/minos-protocol/src/ws_ticket.rs b/crates/minos-protocol/src/ws_ticket.rs index 690c1258..5c9385ca 100644 --- a/crates/minos-protocol/src/ws_ticket.rs +++ b/crates/minos-protocol/src/ws_ticket.rs @@ -1,15 +1,16 @@ //! WS ticket request/response types for the realtime gateway. //! -//! Before upgrading to `/ws/client` or `/ws/host`, the caller must obtain -//! a short-lived ticket via `POST /v1/realtime/ws-ticket` (account) or -//! `POST /v1/host/realtime/ws-ticket` (host). +//! Browser / JS WebSocket clients obtain a short-lived ticket via +//! `POST /v1/realtime/ws-ticket` then connect `GET /ws/client?ticket=`. +//! Desktop Rust and Host daemon send `Authorization: Bearer` and do not +//! use a host ticket (`POST /v1/host/realtime/ws-ticket` is gone). use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct RealtimeWsTicketRequest { #[serde(default, skip_serializing_if = "Option::is_none")] - pub installation_id: Option, + pub device_id: Option, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] @@ -58,9 +59,7 @@ mod tests { #[test] fn realtime_ws_ticket_request_empty_round_trip() { - let req = RealtimeWsTicketRequest { - installation_id: None, - }; + let req = RealtimeWsTicketRequest { device_id: None }; let json = serde_json::to_string(&req).unwrap(); let back: RealtimeWsTicketRequest = serde_json::from_str(&json).unwrap(); assert_eq!(req, back); diff --git a/docs/architecture-backend.md b/docs/architecture-backend.md index d2595124..2318b1a5 100644 --- a/docs/architecture-backend.md +++ b/docs/architecture-backend.md @@ -141,7 +141,7 @@ | `POST /v1/hosts/unlink` | account bearer | 删 link、**始终**撤销 host tokens、kill `/ws/host`、清 peer cache | | `GET /v1/hosts` | account bearer | 列出本账户 hosts(`online` 来自 connection registry) | -Link proof 签名载荷:`"{installation_id}:{nonce}:v1/hosts/link"`(无 leading slash)。Nonce 经 `POST /v1/host/bootstrap/nonce` 获取;多实例部署时 `BootstrapNonceStore` 走 Redis(与 `RealtimeTicketStore` 同 `MINOS_REDIS_URL`)。 +Link proof 签名载荷:`"{device_id}:{nonce}:v1/hosts/link"`(无 leading slash)。Nonce 经 `POST /v1/host/bootstrap/nonce` 获取;多实例部署时 `BootstrapNonceStore` 走 Redis(与 `RealtimeTicketStore` 同 `MINOS_REDIS_URL`)。 `host already linked elsewhere` → **409** `host_linked_elsewhere`(Host Link 路径单 account↔host)。 @@ -214,10 +214,10 @@ Postgres 集成 smoke(默认 skip):`MINOS_PG_TESTS=1 MINOS_DATABASE_URL=po | 表 | 用途 | |----|------| | `accounts` | 账户(email, supabase_sub, minos_id, display_name)— 无本地密码 | -| `device_installations` | 安装(kind: mobile/browser/desktop/host, public_key, account_id) | +| `devices` | 一台设备一行(`device_id`;kind: mobile/browser/desktop/host) | | `pairing_tokens` | 配对令牌(token_hash, issuer_device_id, expires_at) | -| `host_links` | 配对码(code_hash, host_installation_id, status) | -| `host_installation_tokens` | Host 安装令牌 | +| `host_links` | 账户 ↔ 本机 DeviceId | +| `host_tokens` | Host 票(hash + `host_device_id` + 绑定的 `account_id`) | | `refresh_tokens` | 刷新令牌 | | `host_links` | 账户-Host 关联 | | `friend_requests` | 好友请求 | @@ -246,7 +246,7 @@ Postgres 集成 smoke(默认 skip):`MINOS_PG_TESTS=1 MINOS_DATABASE_URL=po ### 30 个 Store 子模块 -涵盖: accounts, device_installations, tokens, host_links, host_installation_tokens, refresh_tokens, host_links, agent_sessions, agent_turns, agent_turn_events, approval_requests, host_commands, durable_event_log, outbox_events, sessions, raw_events, thread_sync_state, projects, push_tokens, notification_preferences, notification_cooldowns 等。 +涵盖: accounts, devices, host_tokens, host_links, refresh_tokens, agent_sessions, agent_turns, agent_turn_events, approval_requests, host_commands, durable_event_log, outbox_events, sessions, raw_events, thread_sync_state, projects, push_tokens, notification_preferences, notification_cooldowns 等。 ## Agent 会话管理 (`src/agent_sessions/`) diff --git a/docs/architecture-business-flow.md b/docs/architecture-business-flow.md index 8af64fb7..8d53e07c 100644 --- a/docs/architecture-business-flow.md +++ b/docs/architecture-business-flow.md @@ -105,16 +105,15 @@ ### Host 守护进程 -1. 调用 `POST /v1/host/realtime/ws-ticket`(HostInstallationPrincipal)→ 获得 ticket -2. WebSocket 升级: `/ws/host?ticket=` -3. 自动订阅 `host:` topic -4. 接收 host 命令(start_agent, approval_decision 等) -5. 回送命令结果: `host_command_ack`, `host_command_result` -6. Agent 输出上行: 在线发送 `HostIngestLiveBatch`;断线重连后先发送 `HostGapManifest`,历史正文由后端通过 `PullIngestRange` 主动拉取。 +1. 以 Bearer `host_token` 升级 `/ws/host`(无 host ticket) +2. 自动订阅 `host:` topic +3. 接收 host 命令(start_agent, approval_decision 等) +4. 回送命令结果: `host_command_ack`, `host_command_result` +5. Agent 输出上行: 在线发送 `HostIngestLiveBatch`;断线重连后先发送 `HostGapManifest`,历史正文由后端通过 `PullIngestRange` 主动拉取。 ### 连接策略 -同一 `(principal, installation_id)` 只保留最新连接;旧连接收到 4401 关闭码。 +同一 `(rail, DeviceId)` 只保留最新连接(Account IM 与 Host runtime 可共享一个 DeviceId);旧连接收到 4401 关闭码。 --- @@ -153,7 +152,7 @@ 1. 调用方可触发 start/send_input(或由 inbox worker 内部调用) 2. 后端事务:成员校验 → 选 host → `agent_sessions` / turns → durable → `host_commands` -3. Outbox → `host:{installation_id}` → daemon spawn / 喂入 +3. Outbox → `host:{device_id}` → daemon spawn / 喂入 ### Agent 执行与流式传输 diff --git a/docs/architecture-daemon.md b/docs/architecture-daemon.md index 26b38cbb..e2a1eea4 100644 --- a/docs/architecture-daemon.md +++ b/docs/architecture-daemon.md @@ -366,6 +366,6 @@ main.rs Desktop 在登录后调用: -1. `minos_local_host_prepare_link` — 返回 `installation_id` + `public_key` + backend nonce +1. `minos_local_host_prepare_link` — 返回 `device_id` + `public_key` + backend nonce 2. Desktop 用 account bearer 调 `POST /v1/hosts/link`(签名可由 `minos_local_host_sign_link_proof` 生成) 3. `minos_local_host_apply_link_token` — 持久化 `hit_*` 并 `secret_notify` 唤醒 relay 拨号 `/ws/host` diff --git a/docs/architecture-messaging.md b/docs/architecture-messaging.md index 89656381..1c581f2b 100644 --- a/docs/architecture-messaging.md +++ b/docs/architecture-messaging.md @@ -156,9 +156,9 @@ Desktop:主舞台是 **Timeline + Composer**;Session / Approval 是侧栏或 | 角色 | 连接入口 | Principal | 默认 Topic | |------|---------|-----------|------------| | 人类客户端(Mobile / Web / Desktop Account) | `/ws/client` | `Account { account_id }` | `account:{account_id}` | -| Host 守护进程 | `/ws/host` | `Host { host_installation_id }` | `host:{host_installation_id}` | +| Host 守护进程 | `/ws/host` | `Host { host_device_id }` | `host:{host_device_id}` | -同一 `(principal, installation_id)` **只保留最新连接**;旧连接 `4401` 强制关闭(成熟 IM 的「单设备踢旧」/ 多 tab 最新胜出策略)。 +同一 `(rail, DeviceId)` **只保留最新连接**(Account IM 与 Host runtime 可共享一个 DeviceId,互不踢);旧连接 `4401` 强制关闭(成熟 IM 的「单设备踢旧」/ 多 tab 最新胜出策略)。 ### 3.2 IM 稳态:长连接 · 心跳 · Presence · 吊销 @@ -179,19 +179,24 @@ Gateway ──推送──► 订阅方(online / offline / last_seen) | **心跳** | `Hello.heartbeat_interval_ms`(25s 建议);服务端每 15s WS `Ping` 探测;**90s 无入站活动** → close `1011 heartbeat_timeout` | | **活动定义** | 入站 text / WS Ping·Pong / 应用层 `ClientFrame::Ping` 均刷新 liveness;`last_seen_at_ms` 节流写库(≥30s) | | **Online(分层语义)** | **Account sync(人类 IM)** = 该 account 至少一条 account-client `/ws/client` live(实现上 Mobile 计数见 `mobile_client_session_count`;Desktop/Web 同轨);**Host online(设备)** = installation 有 live `/ws/host`;**Agent available** = bot 在 roster 且 bound Host online。**产品主 Online(能发能收)必须以 Account sync 为准**,不得仅用 Host 冒充 | -| **last_seen** | 耐久:`device_installations.last_seen_at_ms`;HTTP 列表返回;连接 open/close 强制 touch(冷路径展示,不冒充 online) | +| **last_seen** | 耐久:`devices.last_seen_at_ms`;HTTP 列表返回;连接 open/close 强制 touch(冷路径展示,不冒充 online) | | **Presence 推送** | ephemeral `StreamEvent{kind:presence}`:Host 上下线 → 各 linked `account:{id}`(Mobile 改设备 online);Account client 上下线 → 各 linked `host:{id}`(Host peer list) | | **吊销踢连接** | 同 installation 重连 `session_superseded`(4401);auth/unlink `auth_revoked`(4401);Host 可先收 `HostForceClose` 再 close | | **离线 Push** | presence + 偏好 + event_id 幂等 决策(见 Plane P / Backend B1);**非**「与 presence 脱钩」 | ``` -Account client (browser / mobile / desktop UI) +Account client (browser / mobile) │ Bearer access JWT ▼ -POST /v1/realtime/ws-ticket # 保留:浏览器 WS 难设 Authorization +POST /v1/realtime/ws-ticket # 浏览器 / WebView JS WebSocket 难设 Authorization │ 60s 一次性 ticket ▼ GET /ws/client?ticket=… + +Desktop Account IM (Rust host) + │ Authorization: Bearer # 无 ticket + ▼ +GET /ws/client │ 校验 + 消费 ticket + 角色匹配 ▼ ServerFrame::Hello { conn_id, server_time_ms, heartbeat_interval_ms } @@ -219,8 +224,8 @@ ServerFrame::Hello { … } │ Host ingest / 既有 host 控制帧 └─ 退出 / revoke → HostForceClose + presence offline -# 过渡期仍可能:POST /v1/host/realtime/ws-ticket → /ws/host?ticket= -# 正式删除后不得再依赖 host ticket;WS 401 不得一律清本地 hit_ +# Host 无 ticket。Desktop 登录同事务签发 host_token(绑 DeviceId + account_id)。 +# WS 401 不得一律清本地 host_token。 ``` 客户端断线后指数退避重连(典型 1s→30s 封顶);冷路径 HTTP 列表用 `online` + `last_seen_at_ms` 纠偏。 @@ -239,7 +244,7 @@ ServerFrame::Hello { … } | `conversation` | `conversation:{id}` | 对话消息 append / recall / reaction aggregate;时间线热路径 | | `project` | `project:{id}` | 项目与对话关联、归档 | | `agent_session` | `agent_session:{id}` | 会话生命周期、turn、**Approval Attention**、**UI 流式投影** | -| `host` | `host:{installation_id}` | Host 命令下发、强制关闭、链接状态 | +| `host` | `host:{device_id}` | Host 命令下发、强制关闭、链接状态 | 权限:订阅时服务端校验 membership / ownership;拒绝则 `SubscriptionDenied`。 @@ -463,7 +468,7 @@ Minos 明确区分 **可靠性语义不同** 的消息平面——这是成熟 Client HTTP (start/stop/send-input/approval/…) → 事务写 host_commands + DurableEvent::HostCommandIssued → Outbox lane=host_command(与 social_durable 分车道 claim) - → HostCommandOutboxJob publish → topic host:{installation_id} + → HostCommandOutboxJob publish → topic host:{device_id} → Daemon 执行 → ClientFrame::HostCommandAck / HostCommandResult → ack_pending_host_command_events(成功观察后 outbox acked) @@ -602,7 +607,7 @@ POST send-message ──┤ durable_event_log @ conversation:{id} │ | @mention 索引 | **写时索引** | `message_mentions`(按消息×被@人),非全文检索 | | Approval | **读扩散为主** | Durable `agent_session:*`;Push 写扩散到设备 token;演进可补 account Attention | | Agent Stream UI | **读扩散 / 订阅** | `StreamEvent` → 当前订阅 `agent_session:*` 的连接 | -| Host 命令 | **定向写** | `host:{installation_id}` 单目标(不是群 fanout) | +| Host 命令 | **定向写** | `host:{device_id}` 单目标(不是群 fanout) | **为什么当前混合合理**:Project 协作群通常 **N 很小**(几人 + 数个 Agent),对 N 做 account 摘要写扩散成本可接受,且保证「没打开对话的端」仍能刷新会话列表——这是 IM 列表体验的刚需。 @@ -637,7 +642,7 @@ POST send-message ──┤ durable_event_log @ conversation:{id} │ | ID | 作用 | |----|------| | `account_id` | 人类账户 | -| `installation_id` / `device_id` | 安装维度连接与踢旧 | +| `device_id` | 设备维度连接与踢旧(Account / Host 分轨) | | `conversation_id` | 社交会话 | | `message_id` | 单条聊天消息 | | `chat_message_mentions.(target_kind,target_id)` | 多态 @ 目标:`account`/`agent` + `ordinal` 外观序 | From 797ed4eaaca55eabe444015c1dd4972c8dc40185 Mon Sep 17 00:00:00 2001 From: peter rich Date: Thu, 13 Aug 2026 15:44:24 +0800 Subject: [PATCH 12/12] feat(desktop): move account session and /ws/client into Rust MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Own DeviceId, refresh, and host_token in Keychain (AfterFirstUnlock). Login/refresh/sign-out and Account IM now run in the Tauri host with native Bearer /ws/client — no ticket. The webview only projects UI state and forwards frames. --- Cargo.lock | 9 + apps/desktop/src-tauri/Cargo.toml | 11 + apps/desktop/src-tauri/src/account_cloud.rs | 162 ++++++++ .../desktop/src-tauri/src/account_realtime.rs | 355 ++++++++++++++++++ apps/desktop/src-tauri/src/app_state.rs | 2 + .../desktop/src-tauri/src/commands/account.rs | 162 ++++++++ .../src-tauri/src/commands/host_link.rs | 4 +- apps/desktop/src-tauri/src/commands/mod.rs | 2 + apps/desktop/src-tauri/src/daemon.rs | 22 +- apps/desktop/src-tauri/src/identity.rs | 74 ++++ apps/desktop/src-tauri/src/lib.rs | 14 + apps/desktop/src-tauri/src/secure_store.rs | 123 ++++++ apps/desktop/src/features/host/HostView.tsx | 2 +- .../host/lib/ensure-host-connection.test.ts | 10 +- .../host/lib/ensure-host-connection.ts | 18 +- .../host/lib/host-connection-machine.test.ts | 4 +- .../host/lib/host-connection-machine.ts | 8 +- .../lib/host-credential-controller.test.ts | 8 +- .../src/shared/lib/account-session.test.ts | 10 +- .../desktop/src/shared/lib/account-session.ts | 20 +- .../src/shared/lib/cloud-realtime.test.ts | 20 +- apps/desktop/src/shared/lib/cloud-realtime.ts | 106 +++++- apps/desktop/src/shared/lib/daemon.ts | 6 +- apps/desktop/src/shared/lib/minos-cloud.ts | 23 +- apps/desktop/src/store/account-store.ts | 154 +++++++- docs/architecture-desktop.md | 2 +- 26 files changed, 1248 insertions(+), 83 deletions(-) create mode 100644 apps/desktop/src-tauri/src/account_cloud.rs create mode 100644 apps/desktop/src-tauri/src/account_realtime.rs create mode 100644 apps/desktop/src-tauri/src/commands/account.rs create mode 100644 apps/desktop/src-tauri/src/identity.rs create mode 100644 apps/desktop/src-tauri/src/secure_store.rs diff --git a/Cargo.lock b/Cargo.lock index 8cae8509..db6538a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4343,10 +4343,13 @@ version = "0.1.0" dependencies = [ "anyhow", "base64 0.22.1", + "chrono", "clap", "ctrlc", "dirs 5.0.1", "futures", + "futures-util", + "http 1.5.0", "jsonrpsee", "minisign-verify", "minos-chat-store", @@ -4354,7 +4357,9 @@ dependencies = [ "minos-domain", "minos-protocol", "minos-ui-protocol", + "reqwest 0.12.28", "rusqlite", + "security-framework", "serde", "serde_json", "tauri", @@ -4366,9 +4371,13 @@ dependencies = [ "tauri-plugin-updater", "tauri-plugin-window-state", "tempfile", + "thiserror 2.0.19", "tokio", + "tokio-tungstenite 0.29.0", "tracing", "tracing-subscriber", + "url", + "uuid", ] [[package]] diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index b74a7117..a79c1c84 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -38,6 +38,14 @@ minos-chat-store = { path = "../../../crates/minos-chat-store" } minos-ui-protocol = { path = "../../../crates/minos-ui-protocol" } tracing = { workspace = true } tracing-subscriber = { workspace = true } +reqwest = { workspace = true } +tokio-tungstenite = { workspace = true } +http = { workspace = true } +url = { workspace = true } +chrono = { workspace = true } +thiserror = { workspace = true } +uuid = { workspace = true } +futures-util = { workspace = true } ctrlc = "3" minisign-verify = "0.2" base64 = "0.22" @@ -45,6 +53,9 @@ base64 = "0.22" rusqlite = { version = "0.32", features = ["bundled"] } dirs = "5" +[target.'cfg(target_os = "macos")'.dependencies] +security-framework = "3" + [[bin]] name = "verify-updater-sig" path = "src/bin/verify_updater_sig.rs" diff --git a/apps/desktop/src-tauri/src/account_cloud.rs b/apps/desktop/src-tauri/src/account_cloud.rs new file mode 100644 index 00000000..c759a8db --- /dev/null +++ b/apps/desktop/src-tauri/src/account_cloud.rs @@ -0,0 +1,162 @@ +//! Account HTTP: Supabase exchange, refresh, logout. Desktop never uses a WS ticket. + +use minos_domain::DeviceId; +use serde::{Deserialize, Serialize}; + +use crate::identity::{self, DesktopAccount}; + +fn backend_http_base() -> String { + std::env::var("MINOS_BACKEND_URL") + .ok() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .or_else(|| option_env!("VITE_MINOS_BACKEND_URL").map(str::to_string)) + .unwrap_or_else(|| "http://127.0.0.1:8787".into()) + .trim_end_matches('/') + .to_string() +} + +#[derive(Debug, Deserialize)] +struct AuthResp { + account: AccountSummary, + access_token: String, + refresh_token: String, + expires_in: i64, + #[serde(default)] + host_token: Option, +} + +#[derive(Debug, Deserialize)] +struct AccountSummary { + account_id: String, + email: String, +} + +#[derive(Debug, Deserialize)] +struct RefreshResp { + access_token: String, + refresh_token: String, + expires_in: i64, +} + +#[derive(Debug, Serialize)] +struct SupabaseBody<'a> { + access_token: &'a str, + device_name: &'a str, +} + +#[derive(Debug, Serialize)] +struct RefreshBody<'a> { + refresh_token: &'a str, +} + +#[derive(Debug, Serialize)] +struct LogoutBody<'a> { + refresh_token: &'a str, +} + +fn device_headers(device_id: DeviceId, access: Option<&str>) -> reqwest::header::HeaderMap { + let mut headers = reqwest::header::HeaderMap::new(); + headers.insert("content-type", "application/json".parse().unwrap()); + headers.insert("x-device-id", device_id.to_string().parse().unwrap()); + headers.insert("x-device-role", "desktop-console".parse().unwrap()); + headers.insert("x-device-name", "Minos Desktop".parse().unwrap()); + if let Some(token) = access { + if let Ok(value) = format!("Bearer {token}").parse() { + headers.insert(reqwest::header::AUTHORIZATION, value); + } + } + headers +} + +pub async fn exchange_supabase( + device_id: DeviceId, + supabase_access: &str, +) -> anyhow::Result { + let client = reqwest::Client::new(); + let url = format!("{}/v1/auth/supabase", backend_http_base()); + let resp = client + .post(url) + .headers(device_headers(device_id, None)) + .json(&SupabaseBody { + access_token: supabase_access, + device_name: "Minos Desktop", + }) + .send() + .await?; + if !resp.status().is_success() { + let status = resp.status(); + let body = resp.text().await.unwrap_or_default(); + anyhow::bail!("supabase exchange failed ({status}): {body}"); + } + let auth: AuthResp = resp.json().await?; + Ok(DesktopAccount { + device_id: device_id.to_string(), + account_id: auth.account.account_id, + email: auth.account.email, + access_token: auth.access_token, + refresh_token: auth.refresh_token, + expires_in: auth.expires_in, + host_token: auth.host_token, + }) +} + +pub async fn refresh(device_id: DeviceId, refresh_token: &str) -> anyhow::Result { + let client = reqwest::Client::new(); + let url = format!("{}/v1/auth/refresh", backend_http_base()); + let resp = client + .post(url) + .headers(device_headers(device_id, None)) + .json(&RefreshBody { refresh_token }) + .send() + .await?; + if !resp.status().is_success() { + let status = resp.status(); + let body = resp.text().await.unwrap_or_default(); + anyhow::bail!("refresh failed ({status}): {body}"); + } + let auth: RefreshResp = resp.json().await?; + Ok(DesktopAccount { + device_id: device_id.to_string(), + account_id: identity::load_account_id()?.unwrap_or_default(), + email: identity::load_email()?.unwrap_or_default(), + access_token: auth.access_token, + refresh_token: auth.refresh_token, + expires_in: auth.expires_in, + host_token: identity::load_host_token()?, + }) +} + +pub async fn logout( + device_id: DeviceId, + access_token: &str, + refresh_token: &str, +) -> anyhow::Result<()> { + let client = reqwest::Client::new(); + let url = format!("{}/v1/auth/logout", backend_http_base()); + let resp = client + .post(url) + .headers(device_headers(device_id, Some(access_token))) + .json(&LogoutBody { refresh_token }) + .send() + .await?; + if !resp.status().is_success() && resp.status().as_u16() != 204 { + let status = resp.status(); + let body = resp.text().await.unwrap_or_default(); + anyhow::bail!("logout failed ({status}): {body}"); + } + Ok(()) +} + +/// `ws://` / `wss://` origin for `/ws/client`. +pub fn client_ws_url() -> String { + let http = backend_http_base(); + let ws = if let Some(rest) = http.strip_prefix("https://") { + format!("wss://{rest}") + } else if let Some(rest) = http.strip_prefix("http://") { + format!("ws://{rest}") + } else { + format!("ws://{http}") + }; + format!("{ws}/ws/client") +} diff --git a/apps/desktop/src-tauri/src/account_realtime.rs b/apps/desktop/src-tauri/src/account_realtime.rs new file mode 100644 index 00000000..33e816b5 --- /dev/null +++ b/apps/desktop/src-tauri/src/account_realtime.rs @@ -0,0 +1,355 @@ +//! Account IM `/ws/client` owned by the Desktop Rust host. +//! +//! Native Bearer access JWT — no ticket. Frames are forwarded to the webview +//! as `account://frame` / `account://state` events. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use futures_util::{SinkExt, StreamExt}; +use minos_protocol::realtime::{ClientFrame, ServerFrame}; +use serde::Serialize; +use tauri::{AppHandle, Emitter}; +use tokio::sync::{mpsc, Mutex}; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::http::header::AUTHORIZATION; +use tokio_tungstenite::tungstenite::Message; +use tracing::{info, warn}; + +use crate::account_cloud; + +const EVENT_FRAME: &str = "account://frame"; +const EVENT_STATE: &str = "account://state"; + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AccountSyncState { + pub state: String, +} + +pub struct AccountRealtime { + inner: Mutex, + epoch: AtomicU64, +} + +struct Inner { + stop_tx: Option>, + out_tx: Option>, + access_token: String, + account_id: String, + conversation_ids: Vec, +} + +impl AccountRealtime { + pub fn new() -> Self { + Self { + inner: Mutex::new(Inner { + stop_tx: None, + out_tx: None, + access_token: String::new(), + account_id: String::new(), + conversation_ids: Vec::new(), + }), + epoch: AtomicU64::new(0), + } + } + + pub async fn start( + &self, + app: AppHandle, + access_token: String, + account_id: String, + ) -> anyhow::Result<()> { + self.stop().await; + let (stop_tx, stop_rx) = mpsc::channel(1); + let (out_tx, out_rx) = mpsc::channel::(64); + { + let mut inner = self.inner.lock().await; + inner.stop_tx = Some(stop_tx); + inner.out_tx = Some(out_tx); + inner.access_token = access_token.clone(); + inner.account_id = account_id.clone(); + } + let epoch = self.epoch.fetch_add(1, Ordering::SeqCst) + 1; + let conversations = { self.inner.lock().await.conversation_ids.clone() }; + tokio::spawn(run_loop( + app, + epoch, + Arc::new(AtomicU64::new(epoch)), + access_token, + account_id, + conversations, + out_rx, + stop_rx, + )); + Ok(()) + } + + pub async fn update_auth(&self, access_token: String, account_id: String) { + let mut inner = self.inner.lock().await; + inner.access_token = access_token; + inner.account_id = account_id; + } + + pub async fn stop(&self) { + self.epoch.fetch_add(1, Ordering::SeqCst); + let mut inner = self.inner.lock().await; + if let Some(tx) = inner.stop_tx.take() { + let _ = tx.send(()).await; + } + inner.out_tx = None; + } + + pub async fn subscribe_conversation(&self, conversation_id: String) { + let mut inner = self.inner.lock().await; + if !inner + .conversation_ids + .iter() + .any(|id| id == &conversation_id) + { + inner.conversation_ids.push(conversation_id.clone()); + } + if let Some(tx) = inner.out_tx.as_ref() { + let mut resume = HashMap::new(); + if let Some(seq) = load_cursor(&format!("conversation:{conversation_id}")) { + resume.insert(format!("conversation:{conversation_id}"), seq); + } + let _ = tx + .send(ClientFrame::Subscribe { + topics: vec![format!("conversation:{conversation_id}")], + resume_after: if resume.is_empty() { + None + } else { + Some(resume) + }, + client_request_id: None, + }) + .await; + } + } + + pub async fn send(&self, frame: ClientFrame) -> anyhow::Result<()> { + let inner = self.inner.lock().await; + let tx = inner + .out_tx + .as_ref() + .ok_or_else(|| anyhow::anyhow!("account ws not connected"))?; + tx.send(frame) + .await + .map_err(|_| anyhow::anyhow!("account ws send failed"))?; + Ok(()) + } +} + +fn cursor_path() -> std::path::PathBuf { + let home = dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from(".")); + home.join(".minos/desktop/topic-cursors.json") +} + +fn load_cursors() -> HashMap { + let path = cursor_path(); + std::fs::read_to_string(path) + .ok() + .and_then(|s| serde_json::from_str(&s).ok()) + .unwrap_or_default() +} + +fn load_cursor(topic: &str) -> Option { + load_cursors().get(topic).copied() +} + +fn save_cursor(topic: &str, seq: i64) { + let mut map = load_cursors(); + let prev = map.get(topic).copied().unwrap_or(0); + if seq <= prev { + return; + } + map.insert(topic.to_string(), seq); + let path = cursor_path(); + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + if let Ok(buf) = serde_json::to_vec_pretty(&map) { + let _ = std::fs::write(path, buf); + } +} + +pub fn clear_cursors() { + let _ = std::fs::remove_file(cursor_path()); +} + +#[allow(clippy::too_many_arguments)] +async fn run_loop( + app: AppHandle, + epoch: u64, + live_epoch: Arc, + access_token: String, + account_id: String, + conversation_ids: Vec, + mut out_rx: mpsc::Receiver, + mut stop_rx: mpsc::Receiver<()>, +) { + let mut attempt: u32 = 0; + loop { + if live_epoch.load(Ordering::SeqCst) != epoch { + return; + } + emit_state(&app, "connecting"); + match connect_once( + &app, + &access_token, + &account_id, + &conversation_ids, + &mut out_rx, + &mut stop_rx, + ) + .await + { + LoopEnd::Stop => { + emit_state(&app, "disconnected"); + return; + } + LoopEnd::Retry => { + emit_state(&app, "disconnected"); + attempt = attempt.saturating_add(1); + let delay = Duration::from_secs(u64::from(1u32 << attempt.min(5)).min(30)); + tokio::select! { + _ = stop_rx.recv() => { + emit_state(&app, "disconnected"); + return; + } + _ = tokio::time::sleep(delay) => {} + } + } + } + } +} + +enum LoopEnd { + Stop, + Retry, +} + +async fn connect_once( + app: &AppHandle, + access_token: &str, + account_id: &str, + conversation_ids: &[String], + out_rx: &mut mpsc::Receiver, + stop_rx: &mut mpsc::Receiver<()>, +) -> LoopEnd { + let url = account_cloud::client_ws_url(); + let mut req = match url.as_str().into_client_request() { + Ok(req) => req, + Err(error) => { + warn!(target: "minos_desktop::account_ws", %error, "invalid client ws url"); + return LoopEnd::Retry; + } + }; + let bearer = format!("Bearer {access_token}"); + match bearer.parse() { + Ok(value) => { + req.headers_mut().insert(AUTHORIZATION, value); + } + Err(error) => { + warn!(target: "minos_desktop::account_ws", %error, "invalid authorization header"); + return LoopEnd::Retry; + } + } + + let (stream, _) = match tokio_tungstenite::connect_async(req).await { + Ok(pair) => pair, + Err(error) => { + warn!(target: "minos_desktop::account_ws", %error, "account ws connect failed"); + return LoopEnd::Retry; + } + }; + info!(target: "minos_desktop::account_ws", "account ws connected"); + let (mut sink, mut stream) = stream.split(); + + loop { + tokio::select! { + _ = stop_rx.recv() => return LoopEnd::Stop, + frame = out_rx.recv() => { + let Some(frame) = frame else { return LoopEnd::Stop }; + let Ok(text) = serde_json::to_string(&frame) else { continue }; + if sink.send(Message::Text(text.into())).await.is_err() { + return LoopEnd::Retry; + } + } + incoming = stream.next() => { + match incoming { + Some(Ok(Message::Text(text))) => { + handle_server_text(app, account_id, conversation_ids, &mut sink, &text).await; + } + Some(Ok(Message::Ping(p))) => { + let _ = sink.send(Message::Pong(p)).await; + } + Some(Ok(Message::Close(_))) | None => return LoopEnd::Retry, + Some(Err(_)) => return LoopEnd::Retry, + _ => {} + } + } + } + } +} + +async fn handle_server_text( + app: &AppHandle, + account_id: &str, + conversation_ids: &[String], + sink: &mut (impl SinkExt + Unpin), + text: &str, +) { + let _ = app.emit(EVENT_FRAME, text); + let Ok(frame) = serde_json::from_str::(text) else { + return; + }; + match frame { + ServerFrame::Hello { .. } => { + emit_state(app, "syncing"); + let mut topics = vec![format!("account:{account_id}")]; + for id in conversation_ids { + topics.push(format!("conversation:{id}")); + } + let mut resume = HashMap::new(); + for topic in &topics { + if let Some(seq) = load_cursor(topic) { + resume.insert(topic.clone(), seq); + } + } + let sub = ClientFrame::Subscribe { + topics, + resume_after: if resume.is_empty() { + None + } else { + Some(resume) + }, + client_request_id: None, + }; + if let Ok(json) = serde_json::to_string(&sub) { + let _ = sink.send(Message::Text(json.into())).await; + } + } + ServerFrame::SubscribeAck { .. } => { + emit_state(app, "live"); + } + ServerFrame::DurableEvent { + topic, topic_seq, .. + } => { + save_cursor(&topic, topic_seq); + } + _ => {} + } +} + +fn emit_state(app: &AppHandle, state: &str) { + let _ = app.emit( + EVENT_STATE, + AccountSyncState { + state: state.to_string(), + }, + ); +} diff --git a/apps/desktop/src-tauri/src/app_state.rs b/apps/desktop/src-tauri/src/app_state.rs index 3ddfc566..dc5392f5 100644 --- a/apps/desktop/src-tauri/src/app_state.rs +++ b/apps/desktop/src-tauri/src/app_state.rs @@ -1,5 +1,6 @@ //! Shared Tauri managed state for command handlers. +use crate::account_realtime::AccountRealtime; use crate::daemon::DaemonBridge; use crate::im_outbox_store::ImOutboxStore; use std::sync::Arc; @@ -7,4 +8,5 @@ use std::sync::Arc; pub struct AppState { pub daemon: Arc, pub im_outbox: Arc, + pub account_ws: Arc, } diff --git a/apps/desktop/src-tauri/src/commands/account.rs b/apps/desktop/src-tauri/src/commands/account.rs new file mode 100644 index 00000000..1b2e2712 --- /dev/null +++ b/apps/desktop/src-tauri/src/commands/account.rs @@ -0,0 +1,162 @@ +//! Account session + Account IM WS commands. + +use minos_protocol::realtime::ClientFrame; +use serde::Deserialize; +use tauri::{AppHandle, State}; + +use crate::account_cloud; +use crate::app_state::AppState; +use crate::identity::{self, DesktopAccount}; + +#[tauri::command] +pub fn account_device_id() -> Result { + identity::device_id() + .map(|id| id.to_string()) + .map_err(|e| e.to_string()) +} + +#[tauri::command] +pub fn account_load_persisted() -> Result, String> { + let device_id = identity::device_id().map_err(|e| e.to_string())?; + let Some(refresh) = identity::load_refresh_token().map_err(|e| e.to_string())? else { + return Ok(None); + }; + let Some(account_id) = identity::load_account_id().map_err(|e| e.to_string())? else { + return Ok(None); + }; + Ok(Some(DesktopAccount { + device_id: device_id.to_string(), + account_id, + email: identity::load_email() + .map_err(|e| e.to_string())? + .unwrap_or_default(), + access_token: String::new(), + refresh_token: refresh, + expires_in: 0, + host_token: identity::load_host_token().map_err(|e| e.to_string())?, + })) +} + +#[tauri::command] +pub async fn account_exchange_supabase( + state: State<'_, AppState>, + supabase_access_token: String, +) -> Result { + let device_id = identity::device_id().map_err(|e| e.to_string())?; + let session = account_cloud::exchange_supabase(device_id, &supabase_access_token) + .await + .map_err(|e| e.to_string())?; + identity::persist_session(&session).map_err(|e| e.to_string())?; + apply_host_token(&state, session.host_token.as_deref()).await?; + Ok(session) +} + +#[tauri::command] +pub async fn account_refresh_session( + state: State<'_, AppState>, + refresh_token: String, +) -> Result { + let device_id = identity::device_id().map_err(|e| e.to_string())?; + let session = account_cloud::refresh(device_id, &refresh_token) + .await + .map_err(|e| e.to_string())?; + identity::persist_session(&session).map_err(|e| e.to_string())?; + apply_host_token(&state, session.host_token.as_deref()).await?; + Ok(session) +} + +#[tauri::command] +pub async fn account_sign_out( + app: AppHandle, + state: State<'_, AppState>, + access_token: String, + refresh_token: String, +) -> Result<(), String> { + let device_id = identity::device_id().map_err(|e| e.to_string())?; + let _ = account_cloud::logout(device_id, &access_token, &refresh_token).await; + state.account_ws.stop().await; + crate::account_realtime::clear_cursors(); + identity::clear_session().map_err(|e| e.to_string())?; + let _ = state.daemon.host_clear_credential().await; + let _ = app; + Ok(()) +} + +#[tauri::command] +pub async fn account_ws_start( + app: AppHandle, + state: State<'_, AppState>, + access_token: String, + account_id: String, +) -> Result<(), String> { + state + .account_ws + .start(app, access_token, account_id) + .await + .map_err(|e| e.to_string()) +} + +#[tauri::command] +pub async fn account_ws_stop(state: State<'_, AppState>) -> Result<(), String> { + state.account_ws.stop().await; + Ok(()) +} + +#[tauri::command] +pub async fn account_ws_subscribe( + state: State<'_, AppState>, + conversation_id: String, +) -> Result<(), String> { + state + .account_ws + .subscribe_conversation(conversation_id) + .await; + Ok(()) +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AppendMessageArgs { + pub client_operation_id: String, + pub conversation_id: String, + pub text: String, + pub reply_to_message_id: Option, + pub mentions: Option, +} + +#[tauri::command] +pub async fn account_ws_append( + state: State<'_, AppState>, + args: AppendMessageArgs, +) -> Result<(), String> { + let mentions = args + .mentions + .and_then(|v| serde_json::from_value(v).ok()) + .unwrap_or_default(); + state + .account_ws + .send(ClientFrame::AppendMessage { + client_operation_id: args.client_operation_id, + conversation_id: args.conversation_id, + text: args.text, + mentions, + reply_to_message_id: args.reply_to_message_id, + attachment_ids: Vec::new(), + }) + .await + .map_err(|e| e.to_string()) +} + +async fn apply_host_token(state: &AppState, host_token: Option<&str>) -> Result<(), String> { + let Some(token) = host_token.filter(|s| !s.is_empty()) else { + return Ok(()); + }; + if let Err(error) = state.daemon.host_apply_link_token(token.to_string()).await { + tracing::warn!( + target: "minos_desktop::account", + %error, + "daemon not ready to apply host_token; file store updated" + ); + } + Ok(()) +} diff --git a/apps/desktop/src-tauri/src/commands/host_link.rs b/apps/desktop/src-tauri/src/commands/host_link.rs index dbfa075f..cc2f6780 100644 --- a/apps/desktop/src-tauri/src/commands/host_link.rs +++ b/apps/desktop/src-tauri/src/commands/host_link.rs @@ -20,12 +20,12 @@ pub async fn daemon_host_prepare_link( #[tauri::command] pub async fn daemon_host_sign_link_proof( state: State<'_, AppState>, - installation_id: String, + device_id: String, nonce: String, ) -> Result { state .daemon - .host_sign_link_proof(installation_id, nonce) + .host_sign_link_proof(device_id, nonce) .await .map_err(|e| e.to_string()) } diff --git a/apps/desktop/src-tauri/src/commands/mod.rs b/apps/desktop/src-tauri/src/commands/mod.rs index 7dfad1f7..8bc4e31a 100644 --- a/apps/desktop/src-tauri/src/commands/mod.rs +++ b/apps/desktop/src-tauri/src/commands/mod.rs @@ -1,5 +1,6 @@ //! Tauri command handlers, split by domain. +mod account; mod agents; mod app; mod approvals; @@ -11,6 +12,7 @@ mod projects; mod sessions; mod updater; +pub use account::*; pub use agents::*; pub use app::*; pub use approvals::*; diff --git a/apps/desktop/src-tauri/src/daemon.rs b/apps/desktop/src-tauri/src/daemon.rs index 49c0943d..5fa8530f 100644 --- a/apps/desktop/src-tauri/src/daemon.rs +++ b/apps/desktop/src-tauri/src/daemon.rs @@ -387,7 +387,7 @@ pub struct PushStatusDto { #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct HostPrepareLinkDto { - pub installation_id: String, + pub device_id: String, pub public_key: String, pub nonce: String, } @@ -1286,23 +1286,20 @@ impl DaemonBridge { .await .context("minos_local_host_prepare_link")?; Ok(HostPrepareLinkDto { - installation_id: response.installation_id, + device_id: response.device_id, public_key: response.public_key, nonce: response.nonce, }) } - /// Host Link: Ed25519 sign `"{installation_id}:{nonce}:v1/hosts/link"`. + /// Host Link: Ed25519 sign `"{device_id}:{nonce}:v1/hosts/link"`. pub async fn host_sign_link_proof( &self, - installation_id: String, + device_id: String, nonce: String, ) -> Result { let client = self.client().await?; - let req = HostSignLinkProofParams { - installation_id, - nonce, - }; + let req = HostSignLinkProofParams { device_id, nonce }; let response: HostSignLinkProofResponse = client .request("minos_local_host_sign_link_proof", [req]) .await @@ -1481,8 +1478,15 @@ fn remove_discovery_file() { async fn start_managed_daemon() -> Result<(Arc, String)> { let minos_home = minos_daemon::paths::minos_home().map_err(|e| anyhow!(e.to_string()))?; let local_state_path = minos_home.join("local-state.json"); - let local_state = LocalState::load_or_init(&local_state_path) + let device_id = crate::identity::device_id().map_err(|e| anyhow!("load DeviceId: {e}"))?; + let mut local_state = LocalState::load_or_init(&local_state_path) .map_err(|e| anyhow!("LocalState::load_or_init: {e}"))?; + if local_state.self_device_id != device_id { + local_state.self_device_id = device_id; + local_state + .save(&local_state_path) + .map_err(|e| anyhow!("LocalState::save DeviceId: {e}"))?; + } let discovery_path = minos_daemon::paths::run_dir() .map_err(|e| anyhow!(e.to_string()))? .join("daemon-rpc.json"); diff --git a/apps/desktop/src-tauri/src/identity.rs b/apps/desktop/src-tauri/src/identity.rs new file mode 100644 index 00000000..3d84356c --- /dev/null +++ b/apps/desktop/src-tauri/src/identity.rs @@ -0,0 +1,74 @@ +//! Stable DeviceId for this Mac + durable account/host credentials. + +use minos_domain::DeviceId; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::secure_store::{self, SecureStoreError}; + +const KEY_DEVICE_ID: &str = "device_id"; +const KEY_REFRESH: &str = "refresh_token"; +const KEY_HOST_TOKEN: &str = "host_token"; +const KEY_ACCOUNT_ID: &str = "account_id"; +const KEY_EMAIL: &str = "email"; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DesktopAccount { + pub device_id: String, + pub account_id: String, + pub email: String, + pub access_token: String, + pub refresh_token: String, + pub expires_in: i64, + #[serde(skip_serializing_if = "Option::is_none")] + pub host_token: Option, +} + +pub fn device_id() -> Result { + if let Some(raw) = secure_store::get(KEY_DEVICE_ID)? { + if let Ok(uuid) = Uuid::parse_str(raw.trim()) { + return Ok(DeviceId(uuid)); + } + } + let id = DeviceId::new(); + secure_store::set(KEY_DEVICE_ID, &id.to_string())?; + Ok(id) +} + +pub fn load_refresh_token() -> Result, SecureStoreError> { + secure_store::get(KEY_REFRESH) +} + +pub fn load_host_token() -> Result, SecureStoreError> { + secure_store::get(KEY_HOST_TOKEN) +} + +pub fn load_account_id() -> Result, SecureStoreError> { + secure_store::get(KEY_ACCOUNT_ID) +} + +pub fn load_email() -> Result, SecureStoreError> { + secure_store::get(KEY_EMAIL) +} + +pub fn persist_session(session: &DesktopAccount) -> Result<(), SecureStoreError> { + secure_store::set(KEY_ACCOUNT_ID, &session.account_id)?; + secure_store::set(KEY_EMAIL, &session.email)?; + secure_store::set(KEY_REFRESH, &session.refresh_token)?; + if let Some(host) = session.host_token.as_deref().filter(|s| !s.is_empty()) { + secure_store::set(KEY_HOST_TOKEN, host)?; + let _ = + minos_daemon::device_secret_store::write(&minos_domain::DeviceSecret(host.to_string())); + } + Ok(()) +} + +pub fn clear_session() -> Result<(), SecureStoreError> { + secure_store::delete(KEY_REFRESH)?; + secure_store::delete(KEY_HOST_TOKEN)?; + secure_store::delete(KEY_ACCOUNT_ID)?; + secure_store::delete(KEY_EMAIL)?; + let _ = minos_daemon::device_secret_store::delete(); + Ok(()) +} diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index fbd2e177..2e0f55ed 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -1,9 +1,13 @@ //! Minos desktop shell — Tauri host + local daemon JSON-RPC bridge. +mod account_cloud; +mod account_realtime; mod app_state; mod commands; mod daemon; +mod identity; mod im_outbox_store; +mod secure_store; mod shutdown; mod window_reveal; @@ -102,6 +106,7 @@ pub fn run() { .manage(AppState { daemon: Arc::clone(&daemon), im_outbox: Arc::clone(&im_outbox), + account_ws: Arc::new(account_realtime::AccountRealtime::new()), }) .setup(move |app| { let handle = app.handle().clone(); @@ -114,6 +119,15 @@ pub fn run() { }) .invoke_handler(tauri::generate_handler![ app_info, + account_device_id, + account_load_persisted, + account_exchange_supabase, + account_refresh_session, + account_sign_out, + account_ws_start, + account_ws_stop, + account_ws_subscribe, + account_ws_append, daemon_connect, daemon_status, daemon_list_projects, diff --git a/apps/desktop/src-tauri/src/secure_store.rs b/apps/desktop/src-tauri/src/secure_store.rs new file mode 100644 index 00000000..81314210 --- /dev/null +++ b/apps/desktop/src-tauri/src/secure_store.rs @@ -0,0 +1,123 @@ +//! DeviceId + account/host tokens. +//! +//! macOS: Data Protection Keychain, AfterFirstUnlockThisDeviceOnly (no prompt). +//! Other targets: 0600 files under `~/.minos/secrets/desktop/` for tests. + +const SERVICE: &str = "com.minos.desktop"; + +#[derive(Debug, thiserror::Error)] +pub enum SecureStoreError { + #[error("secure store: {0}")] + Backend(String), +} + +pub fn get(account: &str) -> Result, SecureStoreError> { + platform::get(SERVICE, account) +} + +pub fn set(account: &str, value: &str) -> Result<(), SecureStoreError> { + platform::set(SERVICE, account, value) +} + +pub fn delete(account: &str) -> Result<(), SecureStoreError> { + platform::delete(SERVICE, account) +} + +#[cfg(target_os = "macos")] +mod platform { + use super::SecureStoreError; + use security_framework::access_control::{ProtectionMode, SecAccessControl}; + use security_framework::passwords::{ + delete_generic_password, get_generic_password, set_generic_password_options, + PasswordOptions, + }; + + fn write_options(service: &str, account: &str) -> Result { + let mut options = PasswordOptions::new_generic_password(service, account); + // Never sync host_token / refresh / DeviceId to iCloud Keychain. + options.set_access_synchronized(Some(false)); + let access = SecAccessControl::create_with_protection( + Some(ProtectionMode::AccessibleAfterFirstUnlockThisDeviceOnly), + 0, + ) + .map_err(|e| SecureStoreError::Backend(e.to_string()))?; + options.set_access_control(access); + Ok(options) + } + + pub fn get(service: &str, account: &str) -> Result, SecureStoreError> { + match get_generic_password(service, account) { + Ok(bytes) => String::from_utf8(bytes) + .map(Some) + .map_err(|e| SecureStoreError::Backend(e.to_string())), + Err(err) if is_not_found(&err) => Ok(None), + Err(err) => Err(SecureStoreError::Backend(err.to_string())), + } + } + + pub fn set(service: &str, account: &str, value: &str) -> Result<(), SecureStoreError> { + let _ = delete_generic_password(service, account); + let options = write_options(service, account)?; + set_generic_password_options(value.as_bytes(), options) + .map_err(|e| SecureStoreError::Backend(e.to_string())) + } + + pub fn delete(service: &str, account: &str) -> Result<(), SecureStoreError> { + match delete_generic_password(service, account) { + Ok(()) => Ok(()), + Err(err) if is_not_found(&err) => Ok(()), + Err(err) => Err(SecureStoreError::Backend(err.to_string())), + } + } + + fn is_not_found(err: &security_framework::base::Error) -> bool { + let msg = err.to_string(); + msg.contains("not found") || msg.contains("-25300") || msg.contains("errSecItemNotFound") + } +} + +#[cfg(not(target_os = "macos"))] +mod platform { + use super::SecureStoreError; + use std::fs; + use std::io::ErrorKind; + use std::path::PathBuf; + + fn path(account: &str) -> Result { + let home = dirs::home_dir() + .ok_or_else(|| SecureStoreError::Backend("home directory unavailable".into()))?; + Ok(home.join(".minos/secrets/desktop").join(account)) + } + + pub fn get(_service: &str, account: &str) -> Result, SecureStoreError> { + let p = path(account)?; + match fs::read_to_string(&p) { + Ok(s) => Ok(Some(s)), + Err(e) if e.kind() == ErrorKind::NotFound => Ok(None), + Err(e) => Err(SecureStoreError::Backend(e.to_string())), + } + } + + pub fn set(_service: &str, account: &str, value: &str) -> Result<(), SecureStoreError> { + let p = path(account)?; + if let Some(dir) = p.parent() { + fs::create_dir_all(dir).map_err(|e| SecureStoreError::Backend(e.to_string()))?; + } + fs::write(&p, value).map_err(|e| SecureStoreError::Backend(e.to_string()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = fs::set_permissions(&p, fs::Permissions::from_mode(0o600)); + } + Ok(()) + } + + pub fn delete(_service: &str, account: &str) -> Result<(), SecureStoreError> { + let p = path(account)?; + match fs::remove_file(&p) { + Ok(()) => Ok(()), + Err(e) if e.kind() == ErrorKind::NotFound => Ok(()), + Err(e) => Err(SecureStoreError::Backend(e.to_string())), + } + } +} diff --git a/apps/desktop/src/features/host/HostView.tsx b/apps/desktop/src/features/host/HostView.tsx index 13b18038..7365a968 100644 --- a/apps/desktop/src/features/host/HostView.tsx +++ b/apps/desktop/src/features/host/HostView.tsx @@ -422,7 +422,7 @@ export function HostView() { /> diff --git a/apps/desktop/src/features/host/lib/ensure-host-connection.test.ts b/apps/desktop/src/features/host/lib/ensure-host-connection.test.ts index 9107cc87..a714bbcc 100644 --- a/apps/desktop/src/features/host/lib/ensure-host-connection.test.ts +++ b/apps/desktop/src/features/host/lib/ensure-host-connection.test.ts @@ -9,14 +9,14 @@ import { function ports(overrides: Partial = {}): EnsureHostPorts { return { prepareLink: async () => ({ - installationId: "host-1", + deviceId: "host-1", publicKey: "ed25519:pk", nonce: "nonce_abc", }), signLinkProof: async () => ({ signature: "ed25519-sig:sig" }), applyLinkToken: async () => ({ linked: true }), registerHost: async () => ({ - hostInstallationId: "host-1", + hostDeviceId: "host-1", hostInstallationToken: "hit_token", pairId: "pair-1", accountId: "acc-1", @@ -35,7 +35,7 @@ describe("registerHostCredential", () => { prepareLink: async () => { calls.push("prepare"); return { - installationId: "host-1", + deviceId: "host-1", publicKey: "ed25519:pk", nonce: "nonce_abc", }; @@ -45,9 +45,9 @@ describe("registerHostCredential", () => { return { signature: "ed25519-sig:sig" }; }, registerHost: async (input) => { - calls.push(`cloud:${input.installationId}`); + calls.push(`cloud:${input.deviceId}`); return { - hostInstallationId: "host-1", + hostDeviceId: "host-1", hostInstallationToken: "hit_token", pairId: "pair-1", accountId: "acc-1", diff --git a/apps/desktop/src/features/host/lib/ensure-host-connection.ts b/apps/desktop/src/features/host/lib/ensure-host-connection.ts index 73b0dc12..b33543d0 100644 --- a/apps/desktop/src/features/host/lib/ensure-host-connection.ts +++ b/apps/desktop/src/features/host/lib/ensure-host-connection.ts @@ -12,23 +12,23 @@ export type EnsureHostPorts = { prepareLink: () => Promise<{ - installationId: string; + deviceId: string; publicKey: string; nonce: string; }>; signLinkProof: ( - installationId: string, + deviceId: string, nonce: string, ) => Promise<{ signature: string }>; applyLinkToken: (token: string) => Promise<{ linked: boolean }>; registerHost: (input: { - installationId: string; + deviceId: string; nonce: string; publicKey: string; signature: string; hostDisplayName: string; }) => Promise<{ - hostInstallationId: string; + hostDeviceId: string; hostInstallationToken: string; pairId: string; accountId: string; @@ -39,7 +39,7 @@ export type EnsureHostPorts = { export type EnsureHostSuccess = { ok: true; - hostInstallationId: string; + hostDeviceId: string; hostDisplayName: string; linkedAtMs: number; pairId: string; @@ -94,7 +94,7 @@ export async function registerHostCredential( if (!stillCurrent()) return abortedOutcome(); let prepared: { - installationId: string; + deviceId: string; publicKey: string; nonce: string; }; @@ -113,7 +113,7 @@ export async function registerHostCredential( let signature: string; try { const signed = await ports.signLinkProof( - prepared.installationId, + prepared.deviceId, prepared.nonce, ); signature = signed.signature; @@ -130,7 +130,7 @@ export async function registerHostCredential( let cloud: Awaited>; try { cloud = await ports.registerHost({ - installationId: prepared.installationId, + deviceId: prepared.deviceId, nonce: prepared.nonce, publicKey: prepared.publicKey, signature, @@ -173,7 +173,7 @@ export async function registerHostCredential( return { ok: true, - hostInstallationId: cloud.hostInstallationId, + hostDeviceId: cloud.hostDeviceId, hostDisplayName: cloud.hostDisplayName || displayName, linkedAtMs: cloud.linkedAtMs, pairId: cloud.pairId, diff --git a/apps/desktop/src/features/host/lib/host-connection-machine.test.ts b/apps/desktop/src/features/host/lib/host-connection-machine.test.ts index 67a6313b..29489e2e 100644 --- a/apps/desktop/src/features/host/lib/host-connection-machine.test.ts +++ b/apps/desktop/src/features/host/lib/host-connection-machine.test.ts @@ -82,14 +82,14 @@ describe("runHostEnsure", () => { isOnline: async () => false, registerPorts: { prepareLink: async () => ({ - installationId: "host-1", + deviceId: "host-1", publicKey: "pk", nonce: "n", }), signLinkProof: async () => ({ signature: "sig" }), applyLinkToken: async () => ({ linked: true }), registerHost: async () => ({ - hostInstallationId: "host-1", + hostDeviceId: "host-1", hostInstallationToken: "hit_x", pairId: "pair-1", accountId: "acc-1", diff --git a/apps/desktop/src/features/host/lib/host-connection-machine.ts b/apps/desktop/src/features/host/lib/host-connection-machine.ts index 130b307d..27f9af6e 100644 --- a/apps/desktop/src/features/host/lib/host-connection-machine.ts +++ b/apps/desktop/src/features/host/lib/host-connection-machine.ts @@ -79,14 +79,14 @@ export type HostEnsureRunResult = | { kind: "offline"; message: string; hostCredentialAccountId?: null } | { kind: "registered-online"; - hostInstallationId: string; + hostDeviceId: string; hostDisplayName: string; linkedAtMs: number; pairId: string; } | { kind: "registered-offline"; - hostInstallationId: string; + hostDeviceId: string; hostDisplayName: string; linkedAtMs: number; pairId: string; @@ -186,7 +186,7 @@ export async function runHostEnsure( if (online) { return { kind: "registered-online", - hostInstallationId: outcome.hostInstallationId, + hostDeviceId: outcome.hostDeviceId, hostDisplayName: outcome.hostDisplayName, linkedAtMs: outcome.linkedAtMs, pairId: outcome.pairId, @@ -194,7 +194,7 @@ export async function runHostEnsure( } return { kind: "registered-offline", - hostInstallationId: outcome.hostInstallationId, + hostDeviceId: outcome.hostDeviceId, hostDisplayName: outcome.hostDisplayName, linkedAtMs: outcome.linkedAtMs, pairId: outcome.pairId, diff --git a/apps/desktop/src/features/host/lib/host-credential-controller.test.ts b/apps/desktop/src/features/host/lib/host-credential-controller.test.ts index 4efba29f..2a63b227 100644 --- a/apps/desktop/src/features/host/lib/host-credential-controller.test.ts +++ b/apps/desktop/src/features/host/lib/host-credential-controller.test.ts @@ -61,7 +61,7 @@ describe("host-credential-controller", () => { return registerHostCredential( { prepareLink: async () => ({ - installationId: "host-a", + deviceId: "host-a", publicKey: "pk", nonce: "n", }), @@ -69,7 +69,7 @@ describe("host-credential-controller", () => { registerHost: async () => { await registerGate; return { - hostInstallationId: "host-a", + hostDeviceId: "host-a", hostInstallationToken: "hit_account_a", pairId: "pair-a", accountId: "acc-a", @@ -99,13 +99,13 @@ describe("host-credential-controller", () => { return registerHostCredential( { prepareLink: async () => ({ - installationId: "host-b", + deviceId: "host-b", publicKey: "pk", nonce: "n", }), signLinkProof: async () => ({ signature: "sig" }), registerHost: async () => ({ - hostInstallationId: "host-b", + hostDeviceId: "host-b", hostInstallationToken: "hit_account_b", pairId: "pair-b", accountId: "acc-b", diff --git a/apps/desktop/src/shared/lib/account-session.test.ts b/apps/desktop/src/shared/lib/account-session.test.ts index ee23e2fc..b4ad3a6e 100644 --- a/apps/desktop/src/shared/lib/account-session.test.ts +++ b/apps/desktop/src/shared/lib/account-session.test.ts @@ -78,7 +78,7 @@ describe("isAccessTokenFresh", () => { describe("account-scoped host bind storage", () => { const bound: HostBindState = { bound: true, - hostInstallationId: "host-a", + hostDeviceId: "host-a", hostDisplayName: "This Mac", boundAtMs: 42, pairId: "pair-a", @@ -89,14 +89,14 @@ describe("account-scoped host bind storage", () => { saveStoredHostBind("acc-1", bound); saveStoredHostBind("acc-2", { ...bound, - hostInstallationId: "host-b", + hostDeviceId: "host-b", pairId: "pair-b", }); - assert.equal(loadStoredHostBind("acc-1").hostInstallationId, "host-a"); - assert.equal(loadStoredHostBind("acc-2").hostInstallationId, "host-b"); + assert.equal(loadStoredHostBind("acc-1").hostDeviceId, "host-a"); + assert.equal(loadStoredHostBind("acc-2").hostDeviceId, "host-b"); clearStoredHostBind("acc-1"); assert.equal(loadStoredHostBind("acc-1").bound, false); - assert.equal(loadStoredHostBind("acc-2").hostInstallationId, "host-b"); + assert.equal(loadStoredHostBind("acc-2").hostDeviceId, "host-b"); }); it("returns empty without account id", () => { diff --git a/apps/desktop/src/shared/lib/account-session.ts b/apps/desktop/src/shared/lib/account-session.ts index a62bbd00..d93dc6b7 100644 --- a/apps/desktop/src/shared/lib/account-session.ts +++ b/apps/desktop/src/shared/lib/account-session.ts @@ -18,12 +18,14 @@ export type MinosSession = { issuedAtMs: number; /** Access token lifetime from exchange/refresh (`expires_in` seconds). */ expiresInSec: number; + /** Device-bound host token from login (Rust Keychain is SSOT). */ + hostToken?: string | null; }; /** Internal bind snapshot for this Mac under one Minos account. */ export type HostBindState = { bound: boolean; - hostInstallationId: string | null; + hostDeviceId: string | null; hostDisplayName: string | null; boundAtMs: number | null; pairId: string | null; @@ -31,7 +33,7 @@ export type HostBindState = { export const EMPTY_HOST_BIND: HostBindState = { bound: false, - hostInstallationId: null, + hostDeviceId: null, hostDisplayName: null, boundAtMs: null, pairId: null, @@ -122,9 +124,9 @@ function parseHostBind(raw: unknown): HostBindState | null { const parsed = raw as Record; // Accept legacy { linked } shape. const bound = parsed.bound === true || parsed.linked === true; - const hostInstallationId = - typeof parsed.hostInstallationId === "string" - ? parsed.hostInstallationId + const hostDeviceId = + typeof parsed.hostDeviceId === "string" + ? parsed.hostDeviceId : null; const hostDisplayName = typeof parsed.hostDisplayName === "string" ? parsed.hostDisplayName : null; @@ -137,7 +139,7 @@ function parseHostBind(raw: unknown): HostBindState | null { const pairId = typeof parsed.pairId === "string" ? parsed.pairId : null; return { bound, - hostInstallationId, + hostDeviceId, hostDisplayName, boundAtMs, pairId, @@ -211,7 +213,7 @@ export function saveStoredHostBind( const map = readHostBindsMap(); map[id] = { bound: bind.bound === true, - hostInstallationId: bind.hostInstallationId, + hostDeviceId: bind.hostDeviceId, hostDisplayName: bind.hostDisplayName, boundAtMs: bind.boundAtMs, pairId: bind.pairId, @@ -226,7 +228,7 @@ export function saveStoredHostLink( ): void { saveStoredHostBind(accountId, { bound: link.bound === true || (link as { linked?: boolean }).linked === true, - hostInstallationId: link.hostInstallationId, + hostDeviceId: link.hostDeviceId, hostDisplayName: link.hostDisplayName, boundAtMs: link.boundAtMs ?? @@ -268,6 +270,7 @@ export function sessionFromAuthResponse(resp: { refresh_token: string; expires_in: number; issuedAtMs?: number; + host_token?: string | null; }): MinosSession { return { accountId: resp.account.account_id, @@ -276,5 +279,6 @@ export function sessionFromAuthResponse(resp: { refreshToken: resp.refresh_token, issuedAtMs: resp.issuedAtMs ?? Date.now(), expiresInSec: resp.expires_in, + hostToken: resp.host_token ?? null, }; } diff --git a/apps/desktop/src/shared/lib/cloud-realtime.test.ts b/apps/desktop/src/shared/lib/cloud-realtime.test.ts index ac651e4a..9bf83aea 100644 --- a/apps/desktop/src/shared/lib/cloud-realtime.test.ts +++ b/apps/desktop/src/shared/lib/cloud-realtime.test.ts @@ -1,11 +1,29 @@ import assert from "node:assert/strict"; import { describe, it } from "node:test"; -import { cloudClientWsUrl } from "./minos-cloud.ts"; import { advanceTopicCursor, resumeAfterFromCursors, conversationTopic, } from "./cloud-cursors.ts"; + +function cloudClientWsUrl(gatewayUrl: string, ticket: string): string { + const httpBase = "http://127.0.0.1:8787"; + let pathOrUrl = gatewayUrl.trim(); + if (pathOrUrl.startsWith("/")) { + const origin = httpBase.replace(/^https:/i, "wss:").replace(/^http:/i, "ws:"); + pathOrUrl = `${origin.replace(/\/+$/, "")}${pathOrUrl}`; + } else if (pathOrUrl.startsWith("https://")) { + pathOrUrl = `wss://${pathOrUrl.slice("https://".length)}`; + } else if (pathOrUrl.startsWith("http://")) { + pathOrUrl = `ws://${pathOrUrl.slice("http://".length)}`; + } + if (!/[?&]ticket=/.test(pathOrUrl)) { + const sep = pathOrUrl.includes("?") ? "&" : "?"; + pathOrUrl = `${pathOrUrl}${sep}ticket=${encodeURIComponent(ticket)}`; + } + return pathOrUrl; +} + describe("cloudClientWsUrl", () => { it("resolves relative gateway path against backend base", () => { // backendHttpBase defaults to 127.0.0.1:8787 in tests without env. diff --git a/apps/desktop/src/shared/lib/cloud-realtime.ts b/apps/desktop/src/shared/lib/cloud-realtime.ts index 59eaedd3..da860580 100644 --- a/apps/desktop/src/shared/lib/cloud-realtime.ts +++ b/apps/desktop/src/shared/lib/cloud-realtime.ts @@ -23,6 +23,7 @@ import { cloudClientWsUrl, type CloudChatMessage, } from "@/shared/lib/minos-cloud"; +import { isTauriRuntime } from "@/shared/lib/runtime"; import { mapAccountDigest, @@ -114,13 +115,13 @@ export type CloudRealtimeHandlers = { onSnapshotRequired?: (topic: string) => void; /** Account roster: host linked (T2). */ onHostLinked?: (input: { - hostInstallationId: string; + hostDeviceId: string; pairId?: string; hostDisplayName?: string; atMs?: number; }) => void; /** Account roster: host unlinked (T2). */ - onHostUnlinked?: (input: { hostInstallationId: string; atMs?: number }) => void; + onHostUnlinked?: (input: { hostDeviceId: string; atMs?: number }) => void; /** Gateway subscription cap (default 128). */ onSubscriptionLimitExceeded?: (input: { limit: number; @@ -164,6 +165,7 @@ export class CloudRealtimeSession { timer: ReturnType; } >(); + private rustUnlisten: Array<() => void> = []; constructor(handlers: CloudRealtimeHandlers) { this.handlers = handlers; @@ -203,7 +205,13 @@ export class CloudRealtimeSession { }, opts?: { timeoutMs?: number }, ): Promise { - if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { + const rustLive = + isTauriRuntime() && + (this.syncState === "live" || this.syncState === "syncing"); + if ( + !rustLive && + (!this.ws || this.ws.readyState !== WebSocket.OPEN) + ) { return Promise.resolve({ ok: false, reason: "socket" }); } if (this.syncState !== "live" && this.syncState !== "syncing") { @@ -240,7 +248,21 @@ export class CloudRealtimeSession { }, timeoutMs); this.appendWaiters.set(client_operation_id, { resolve, timer }); try { - this.ws!.send(JSON.stringify(frame)); + if (isTauriRuntime()) { + void import("@tauri-apps/api/core").then(({ invoke }) => + invoke("account_ws_append", { + args: { + clientOperationId: client_operation_id, + conversationId: conversation_id, + text: input.text ?? "", + replyToMessageId: reply ?? null, + mentions: input.mentions ?? null, + }, + }), + ); + } else { + this.ws!.send(JSON.stringify(frame)); + } } catch { clearTimeout(timer); this.appendWaiters.delete(client_operation_id); @@ -371,6 +393,12 @@ export class CloudRealtimeSession { stop(): void { this.stopped = true; this.connectionEpoch += 1; + this.clearRustListeners(); + if (isTauriRuntime()) { + void import("@tauri-apps/api/core").then(({ invoke }) => + invoke("account_ws_stop"), + ); + } this.clearTimers(); this.conversationIds.clear(); this.pendingSubscribeTopics.clear(); @@ -422,6 +450,12 @@ export class CloudRealtimeSession { for (const cid of next) { this.conversationIds.set(cid, true); } + if (isTauriRuntime()) { + void import("@tauri-apps/api/core").then(({ invoke }) => + invoke("account_ws_subscribe", { conversationId: id }), + ); + return; + } this.sendSubscribe([conversationTopic(id)]); } @@ -534,8 +568,60 @@ export class CloudRealtimeSession { ); } + private clearRustListeners(): void { + for (const unlisten of this.rustUnlisten) { + try { + unlisten(); + } catch { + /* ignore */ + } + } + this.rustUnlisten = []; + } + + private async connectViaRust(): Promise { + if (!this.auth) return; + this.setState("connecting"); + this.clearRustListeners(); + try { + const { listen } = await import("@tauri-apps/api/event"); + const { invoke } = await import("@tauri-apps/api/core"); + this.rustUnlisten.push( + await listen("account://frame", (event) => { + this.handleRaw(String(event.payload ?? "")); + }), + ); + this.rustUnlisten.push( + await listen<{ state?: string }>("account://state", (event) => { + const next = event.payload?.state?.trim(); + if ( + next === "connecting" || + next === "syncing" || + next === "live" || + next === "disconnected" || + next === "error" + ) { + this.setState(next); + } + }), + ); + await invoke("account_ws_start", { + accessToken: this.auth.accessToken, + accountId: this.auth.accountId, + }); + } catch (error) { + console.warn("[cloud-realtime] rust account ws failed", error); + this.setState("error"); + this.scheduleReconnect(); + } + } + private async connect(): Promise { if (this.stopped || !this.auth) return; + if (isTauriRuntime()) { + await this.connectViaRust(); + return; + } // Each connect attempt owns an epoch; stale ticket / open / close must no-op. const epoch = ++this.connectionEpoch; // Close any prior socket without letting its onclose clear the new attempt. @@ -898,14 +984,14 @@ export class CloudRealtimeSession { eventKind === "HostLinked" ) { const p = payload as DurableMessagePayload & { - host_installation_id?: string; + host_device_id?: string; pair_id?: string; host_display_name?: string; }; - const hostId = p.host_installation_id?.trim(); + const hostId = p.host_device_id?.trim(); if (!hostId) return false; this.handlers.onHostLinked?.({ - hostInstallationId: hostId, + hostDeviceId: hostId, pairId: p.pair_id, hostDisplayName: p.host_display_name, atMs: p.at_ms, @@ -918,12 +1004,12 @@ export class CloudRealtimeSession { eventKind === "HostUnlinked" ) { const p = payload as DurableMessagePayload & { - host_installation_id?: string; + host_device_id?: string; }; - const hostId = p.host_installation_id?.trim(); + const hostId = p.host_device_id?.trim(); if (!hostId) return false; this.handlers.onHostUnlinked?.({ - hostInstallationId: hostId, + hostDeviceId: hostId, atMs: p.at_ms, }); return true; diff --git a/apps/desktop/src/shared/lib/daemon.ts b/apps/desktop/src/shared/lib/daemon.ts index 215ba644..a22ac257 100644 --- a/apps/desktop/src/shared/lib/daemon.ts +++ b/apps/desktop/src/shared/lib/daemon.ts @@ -301,13 +301,13 @@ export const daemonApi = { /** Silent host bind (D02): prepare identity + bootstrap nonce. */ hostPrepareLink: () => call<{ - installationId: string; + deviceId: string; publicKey: string; nonce: string; }>("daemon_host_prepare_link"), - hostSignLinkProof: (installationId: string, nonce: string) => + hostSignLinkProof: (deviceId: string, nonce: string) => call<{ signature: string }>("daemon_host_sign_link_proof", { - installationId, + deviceId, nonce, }), hostApplyLinkToken: (hostInstallationToken: string) => diff --git a/apps/desktop/src/shared/lib/minos-cloud.ts b/apps/desktop/src/shared/lib/minos-cloud.ts index 6c8c8c54..670639d9 100644 --- a/apps/desktop/src/shared/lib/minos-cloud.ts +++ b/apps/desktop/src/shared/lib/minos-cloud.ts @@ -14,10 +14,11 @@ export type AuthResponse = { access_token: string; refresh_token: string; expires_in: number; + host_token?: string | null; }; export type HostLinkResult = { - hostInstallationId: string; + hostDeviceId: string; hostInstallationToken: string; pairId: string; accountId: string; @@ -26,7 +27,7 @@ export type HostLinkResult = { }; export type ListedHost = { - hostInstallationId: string; + hostDeviceId: string; hostDisplayName: string; linkedAtMs: number; online: boolean; @@ -190,7 +191,7 @@ export async function linkHost( deviceId: string, accessToken: string, body: { - installationId: string; + deviceId: string; nonce: string; publicKey: string; signature: string; @@ -199,7 +200,7 @@ export async function linkHost( ): Promise { const envelope = await requestJson< ResponseEnvelope<{ - host_installation_id: string; + host_device_id: string; host_installation_token: string; link: { pair_id: string; @@ -212,7 +213,7 @@ export async function linkHost( method: "POST", headers: deviceHeaders(deviceId, accessToken), body: JSON.stringify({ - installation_id: body.installationId, + device_id: body.deviceId, nonce: body.nonce, public_key: body.publicKey, signature: body.signature, @@ -221,7 +222,7 @@ export async function linkHost( }); const data = envelope.data; return { - hostInstallationId: data.host_installation_id, + hostDeviceId: data.host_device_id, hostInstallationToken: data.host_installation_token, pairId: data.link.pair_id, accountId: data.link.account_id, @@ -233,12 +234,12 @@ export async function linkHost( export async function unlinkHost( deviceId: string, accessToken: string, - hostInstallationId: string, + hostDeviceId: string, ): Promise { await requestJson("/v1/hosts/unlink", { method: "POST", headers: deviceHeaders(deviceId, accessToken), - body: JSON.stringify({ host_installation_id: hostInstallationId }), + body: JSON.stringify({ host_device_id: hostDeviceId }), }); } @@ -249,7 +250,7 @@ export async function listHosts( const envelope = await requestJson< ResponseEnvelope<{ hosts: Array<{ - host_installation_id: string; + host_device_id: string; host_display_name: string; linked_at_ms: number; online: boolean; @@ -261,7 +262,7 @@ export async function listHosts( headers: deviceHeaders(deviceId, accessToken), }); return envelope.data.hosts.map((h) => ({ - hostInstallationId: h.host_installation_id, + hostDeviceId: h.host_device_id, hostDisplayName: h.host_display_name, linkedAtMs: h.linked_at_ms, online: h.online, @@ -973,7 +974,7 @@ export async function createWsTicket( }>("/v1/realtime/ws-ticket", { method: "POST", headers: deviceHeaders(deviceId, accessToken), - body: JSON.stringify({ installation_id: deviceId }), + body: JSON.stringify({ device_id: deviceId }), }); const data = envelope.data; // gateway_url is often a path like `/ws/client?ticket=…` (ticket already embedded). diff --git a/apps/desktop/src/store/account-store.ts b/apps/desktop/src/store/account-store.ts index c0924b84..f9275ed2 100644 --- a/apps/desktop/src/store/account-store.ts +++ b/apps/desktop/src/store/account-store.ts @@ -40,6 +40,7 @@ import { type CloudMode, } from "@/shared/lib/host-status"; import { daemonApi } from "@/shared/lib/daemon"; +import { isTauriRuntime } from "@/shared/lib/runtime"; import { runHostEnsure } from "@/features/host/lib/host-connection-machine"; import type { DesktopAuthPhase } from "@/shared/lib/desktop-root-gate"; import { @@ -210,8 +211,10 @@ function applyAuthSuccess( } saveStoredSession(session); const hostBind = loadStoredHostBind(session.accountId); + const hasHostToken = Boolean(session.hostToken?.trim()); const hostOwned = - get().hostCredentialAccountId === nextAccountId && hostBind.bound; + hasHostToken || + (get().hostCredentialAccountId === nextAccountId && hostBind.bound); set({ session, hostBind, @@ -228,8 +231,18 @@ function applyAuthSuccess( void import("@/store/im/im-cloud-bridge").then(({ ensureImCloudBridge }) => ensureImCloudBridge(), ); + if (hasHostToken) { + saveStoredHostBind(session.accountId, { + bound: true, + hostDeviceId: get().deviceId || null, + hostDisplayName: PROJECT_HOST_THIS_MAC, + boundAtMs: Date.now(), + pairId: null, + }); + } const forceReregister = - !hostOwned || prevAccountId !== nextAccountId || !hostBind.bound; + !hasHostToken && + (!hostOwned || prevAccountId !== nextAccountId || !hostBind.bound); scheduleAccessTokenRefresh(session); void get().ensureCloudConnection( forceReregister ? { forceReregister: true } : undefined, @@ -261,6 +274,73 @@ export const useAccountStore = create()((set, get) => ({ const gen = ++hydrateGeneration; hydrateInFlight = (async () => { set({ authPhase: "booting", error: null }); + if (isTauriRuntime()) { + try { + const { invoke } = await import("@tauri-apps/api/core"); + const deviceId = await invoke("account_device_id"); + if (gen !== hydrateGeneration) return; + set({ deviceId }); + const persisted = await invoke<{ + accountId: string; + email: string; + refreshToken: string; + hostToken?: string | null; + } | null>("account_load_persisted"); + if (!persisted?.refreshToken) { + if (gen !== hydrateGeneration) return; + set({ + session: null, + hostBind: { ...EMPTY_HOST_BIND }, + hostCredentialAccountId: null, + cloudStatus: "unknown", + accountSyncStatus: "unknown", + cloudError: null, + authPhase: "unauthenticated", + hydrated: true, + }); + return; + } + const tokens = await invoke<{ + accountId: string; + email: string; + accessToken: string; + refreshToken: string; + expiresIn: number; + hostToken?: string | null; + }>("account_refresh_session", { + refreshToken: persisted.refreshToken, + }); + if (gen !== hydrateGeneration) return; + applyAuthSuccess(set, get, { + accountId: tokens.accountId, + email: tokens.email, + accessToken: tokens.accessToken, + refreshToken: tokens.refreshToken, + issuedAtMs: Date.now(), + expiresInSec: tokens.expiresIn, + hostToken: tokens.hostToken, + }); + return; + } catch { + if (gen !== hydrateGeneration) return; + clearStoredSession(); + ensureGeneration += 1; + ensureInFlight = null; + leaveAccountScope("auth-invalid"); + set({ + session: null, + hostBind: { ...EMPTY_HOST_BIND }, + hostCredentialAccountId: null, + cloudStatus: "unknown", + accountSyncStatus: "unknown", + cloudError: null, + authPhase: "unauthenticated", + hydrated: true, + error: null, + }); + return; + } + } const stored = loadStoredSession(); if (!stored) { if (gen !== hydrateGeneration) return; @@ -348,8 +428,33 @@ export const useAccountStore = create()((set, get) => ({ "Supabase is required (set VITE_SUPABASE_URL and VITE_SUPABASE_ANON_KEY).", ); } - const deviceId = get().deviceId; const supabaseToken = await signInWithSupabasePassword(email, password); + if (isTauriRuntime()) { + const { invoke } = await import("@tauri-apps/api/core"); + const auth = await invoke<{ + accountId: string; + email: string; + accessToken: string; + refreshToken: string; + expiresIn: number; + hostToken?: string | null; + deviceId: string; + }>("account_exchange_supabase", { + supabaseAccessToken: supabaseToken, + }); + set({ deviceId: auth.deviceId }); + applyAuthSuccess(set, get, { + accountId: auth.accountId, + email: auth.email, + accessToken: auth.accessToken, + refreshToken: auth.refreshToken, + issuedAtMs: Date.now(), + expiresInSec: auth.expiresIn, + hostToken: auth.hostToken, + }); + return true; + } + const deviceId = get().deviceId; const auth = await exchangeSupabaseSession(deviceId, supabaseToken); applyAuthSuccess(set, get, sessionFromAuthResponse(auth)); return true; @@ -368,8 +473,33 @@ export const useAccountStore = create()((set, get) => ({ "Supabase is required (set VITE_SUPABASE_URL and VITE_SUPABASE_ANON_KEY).", ); } - const deviceId = get().deviceId; const supabaseToken = await signUpWithSupabasePassword(email, password); + if (isTauriRuntime()) { + const { invoke } = await import("@tauri-apps/api/core"); + const auth = await invoke<{ + accountId: string; + email: string; + accessToken: string; + refreshToken: string; + expiresIn: number; + hostToken?: string | null; + deviceId: string; + }>("account_exchange_supabase", { + supabaseAccessToken: supabaseToken, + }); + set({ deviceId: auth.deviceId }); + applyAuthSuccess(set, get, { + accountId: auth.accountId, + email: auth.email, + accessToken: auth.accessToken, + refreshToken: auth.refreshToken, + issuedAtMs: Date.now(), + expiresInSec: auth.expiresIn, + hostToken: auth.hostToken, + }); + return true; + } + const deviceId = get().deviceId; const auth = await exchangeSupabaseSession(deviceId, supabaseToken); applyAuthSuccess(set, get, sessionFromAuthResponse(auth)); return true; @@ -391,7 +521,15 @@ export const useAccountStore = create()((set, get) => ({ bumpAccountScopeGeneration(); if (session) { try { - await logoutSession(deviceId, session.accessToken, session.refreshToken); + if (isTauriRuntime()) { + const { invoke } = await import("@tauri-apps/api/core"); + await invoke("account_sign_out", { + accessToken: session.accessToken, + refreshToken: session.refreshToken, + }); + } else { + await logoutSession(deviceId, session.accessToken, session.refreshToken); + } } catch { // best-effort revoke } @@ -448,8 +586,8 @@ export const useAccountStore = create()((set, get) => ({ (await refreshDaemonCloudFlags()).cloudOnline, registerPorts: { prepareLink: () => daemonApi.hostPrepareLink(), - signLinkProof: (installationId, nonce) => - daemonApi.hostSignLinkProof(installationId, nonce), + signLinkProof: (deviceId, nonce) => + daemonApi.hostSignLinkProof(deviceId, nonce), applyLinkToken: (token) => daemonApi.hostApplyLinkToken(token), registerHost: (input) => cloudLinkHost(get().deviceId, session.accessToken, input), @@ -491,7 +629,7 @@ export const useAccountStore = create()((set, get) => ({ const hostBind: HostBindState = { bound: true, - hostInstallationId: result.hostInstallationId, + hostDeviceId: result.hostDeviceId, hostDisplayName: result.hostDisplayName, boundAtMs: result.linkedAtMs, pairId: result.pairId, diff --git a/docs/architecture-desktop.md b/docs/architecture-desktop.md index 3f12a2e8..af13ca28 100644 --- a/docs/architecture-desktop.md +++ b/docs/architecture-desktop.md @@ -8,7 +8,7 @@ |----|-----| | 源码路径 | `apps/desktop/` | | 产品定位 | **Conversation 协作工作台**(Timeline 主舞台;Agent 为对话内 **bot 成员**;Session/Approval 为 Attention)。**account-first** 登录即绑定本机 Host 控制权。手机远程驱动 bot 依赖 **Host online**(`/ws/host`);人类多端聊天依赖 **Account IM**(`/ws/client` + Hub)。见 [ADR 0021](adr/0021-agent-as-conversation-bot-participant.md) | -| 当前阶段 | **Daemon-backed**:Tauri 嵌 daemon。**根门禁 account-first**:`hydrateAuth` → 无 session 则 `LoginPage`。登录后 `ensureCloudConnection`(host link + dial `/ws/host`)。**双角色**:Account UI → `/ws/client` 发/收 Hub 消息;daemon → `/ws/host` 作 bot runtime。**Online 组合**:主状态 = Account IM sync(`accountSyncStatus` / `/ws/client`);次状态 = Host readiness(`cloudStatus` / `cloudOnline`)。禁止仅 Host live 显示可发送 Online。无 Link/Unlink 主路径。Hub `conversation_id` 透传 Host(禁止假 Direct session) | +| 当前阶段 | **Daemon-backed**:Tauri 嵌 daemon。**根门禁 account-first**:`hydrateAuth` → 无 session 则 `LoginPage`。登录同事务签发 `host_token`(绑本机 `DeviceId` + account)。**双角色均在 Rust**:Account IM → `/ws/client` Bearer access JWT;daemon → `/ws/host` Bearer `host_token`。Keychain 存 `DeviceId` / refresh / `host_token`(AfterFirstUnlock,不弹窗)。TS 只投影 UI。**Online 组合**:主状态 = Account IM sync;次状态 = Host readiness。禁止仅 Host live 显示可发送 Online。无 Link/Unlink 主路径。Hub `conversation_id` 透传 Host(禁止假 Direct session) | | 视觉 | 暖色多栏(参考 `res/desktop.jpeg` 气质,非客服 Inbox 语义) | | Buzz 借鉴清单 | [desktop-buzz-reference.md](./desktop-buzz-reference.md)(UI / 架构 / 组件 / 逻辑可复刻项与 P0–P2 路线图) |