diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 00000000..47dc3e3d --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/apps/desktop/scripts/check-file-sizes.mjs b/apps/desktop/scripts/check-file-sizes.mjs index 72e77124..6e112d69 100644 --- a/apps/desktop/scripts/check-file-sizes.mjs +++ b/apps/desktop/scripts/check-file-sizes.mjs @@ -28,13 +28,14 @@ const ALLOWLIST = { // Cloud REST helpers (auth + conversations + agents). sendConversationMessage removed; // further split to minos-cloud helpers planned (freeze above current LOC). "shared/lib/minos-cloud.ts": 1100, - // Mock fixtures + Conversation types; extract mock-conversations.ts planned. + // Mock fixtures + presentation maps; domain types live in shared/domain. "shared/lib/mock-data.ts": 850, - // Outbox posts + per-lane worker share one module; split to im-outbox-worker.ts next. - "shared/lib/im-cloud-sync.ts": 950, - // Cloud IM bridge (lifecycle + mark-read + timeline merge). Split mark-read / - // lifecycle helpers next; cap raised after Hub→Cloud rename (im-hub-bridge @784→~826). - "shared/lib/im-cloud-bridge.ts": 850, + // Durable outbox machine + account ownership; split persist backend next. + "shared/lib/im-outbox.ts": 850, + // Outbox posts + per-lane worker (store ownership). Split worker lanes next. + "store/im/im-cloud-sync.ts": 1050, + // Cloud IM bridge (lifecycle + mark-read + timeline merge) under store/im. + "store/im/im-cloud-bridge.ts": 850, }; /** diff --git a/apps/desktop/src-tauri/src/commands/host_link.rs b/apps/desktop/src-tauri/src/commands/host_link.rs index a90afe43..dbfa075f 100644 --- a/apps/desktop/src-tauri/src/commands/host_link.rs +++ b/apps/desktop/src-tauri/src/commands/host_link.rs @@ -1,7 +1,9 @@ //! Tauri commands for same-account Host Link (D02). use crate::app_state::AppState; -use crate::daemon::{HostApplyLinkTokenDto, HostPrepareLinkDto, HostSignLinkProofDto}; +use crate::daemon::{ + HostApplyLinkTokenDto, HostClearCredentialDto, HostPrepareLinkDto, HostSignLinkProofDto, +}; use tauri::State; #[tauri::command] @@ -39,3 +41,14 @@ pub async fn daemon_host_apply_link_token( .await .map_err(|e| e.to_string()) } + +#[tauri::command] +pub async fn daemon_host_clear_credential( + state: State<'_, AppState>, +) -> Result { + state + .daemon + .host_clear_credential() + .await + .map_err(|e| e.to_string()) +} diff --git a/apps/desktop/src-tauri/src/daemon.rs b/apps/desktop/src-tauri/src/daemon.rs index 0d738b41..49c0943d 100644 --- a/apps/desktop/src-tauri/src/daemon.rs +++ b/apps/desktop/src-tauri/src/daemon.rs @@ -19,11 +19,12 @@ use minos_protocol::local_rpc::{ use minos_protocol::{ AppendConversationMessageParams, ApprovalDecisionRequest, CreateConversationParams, CreateProjectRequest, HostApplyLinkTokenParams, HostApplyLinkTokenResponse, - HostPrepareLinkResponse, HostSignLinkProofParams, HostSignLinkProofResponse, ListClisResponse, - ListConversationAgentSessionsParams, ListConversationMessagesParams, ListConversationsParams, - ListProjectsResponse, LocalConversationMessage, LocalConversationSummary, LocalReactionGroup, - ProjectSummary, ReadSessionParams, RemoveConversationAgentParams, SendUserMessageRequest, - SessionState, SessionSummary, StartAgentInConversationRequest, StartAgentResponse, + HostClearCredentialResponse, HostPrepareLinkResponse, HostSignLinkProofParams, + HostSignLinkProofResponse, ListClisResponse, ListConversationAgentSessionsParams, + ListConversationMessagesParams, ListConversationsParams, ListProjectsResponse, + LocalConversationMessage, LocalConversationSummary, LocalReactionGroup, ProjectSummary, + ReadSessionParams, RemoveConversationAgentParams, SendUserMessageRequest, SessionState, + SessionSummary, StartAgentInConversationRequest, StartAgentResponse, ToggleConversationMessageReactionParams, ToggleConversationMessageReactionResponse, UpdateConversationParams, }; @@ -403,6 +404,12 @@ pub struct HostApplyLinkTokenDto { pub linked: bool, } +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HostClearCredentialDto { + pub cleared: bool, +} + pub struct DaemonBridge { inner: Mutex, /// Serialize connect/bootstrap so React StrictMode double-mount cannot @@ -421,6 +428,9 @@ struct BridgeInner { source: String, /// Keep alive for the app lifetime when we started local RPC ourselves. managed: Option>, + /// True while stop is in progress — new connect must wait/refuse so we + /// never start a second daemon against a still-tearing-down handle. + teardown_in_progress: bool, /// Generation of the pumps currently running for this client. pumps_running_for: u64, } @@ -434,6 +444,7 @@ impl DaemonBridge { last_error: None, source: "none".into(), managed: None, + teardown_in_progress: false, pumps_running_for: 0, }), connect_lock: Mutex::new(()), @@ -460,6 +471,25 @@ impl DaemonBridge { let _gate = self.connect_lock.lock().await; let explicit = override_url.is_some(); + // Refuse concurrent start while managed stop still owns the handle. + { + let guard = self.inner.lock().await; + if guard.teardown_in_progress { + return ConnectionDto { + connected: false, + endpoint: None, + error: Some("managed daemon is shutting down".into()), + source: "error".into(), + managed: guard.managed.is_some(), + cloud_online: false, + has_host_token: minos_daemon::device_secret_store::read() + .ok() + .flatten() + .is_some(), + }; + } + } + // Already healthy? Reuse (and ensure push pumps are armed). { let guard = self.inner.lock().await; @@ -691,13 +721,19 @@ impl DaemonBridge { /// After success the bridge owns neither a client nor a managed handle; /// a later [`Self::connect`] starts a fresh managed daemon (used by /// `restore_after_failed_update`). + /// + /// The managed handle stays owned until `stop` reaches a terminal state so + /// an outer timeout cannot drop the only reference mid-teardown. Concurrent + /// `connect` is refused while `teardown_in_progress`. pub async fn shutdown_managed(&self) -> Result<(), String> { // Drop the WS client first so subscription pumps exit promptly. + // Keep `managed` until stop finishes — clone Arc, clear only after. let managed = { let mut guard = self.inner.lock().await; guard.client = None; guard.endpoint = None; - guard.managed.take() + guard.teardown_in_progress = true; + guard.managed.clone() }; // Invalidate discovery so a concurrent connect does not attach to a // port that is about to close (or already closed). @@ -706,12 +742,15 @@ impl DaemonBridge { self.pump_generation.fetch_add(1, Ordering::SeqCst); if let Some(handle) = managed { - match handle.stop().await { - Ok(()) => { + // Detach stop onto a join handle so an outer timeout cancels only + // our await, not the stop future itself (providers still terminate). + let stop_task = tokio::spawn(async move { handle.stop().await }); + let result = match stop_task.await { + Ok(Ok(())) => { info!(target: "minos_desktop", "managed daemon stopped"); Ok(()) } - Err(e) => { + Ok(Err(e)) => { warn!( target: "minos_desktop", error = %e, @@ -719,8 +758,22 @@ impl DaemonBridge { ); Err(e.to_string()) } - } + Err(join_err) => { + warn!( + target: "minos_desktop", + error = %join_err, + "managed daemon stop task panicked" + ); + Err(join_err.to_string()) + } + }; + let mut guard = self.inner.lock().await; + guard.managed = None; + guard.teardown_in_progress = false; + result } else { + let mut guard = self.inner.lock().await; + guard.teardown_in_progress = false; Ok(()) } } @@ -1277,6 +1330,18 @@ impl DaemonBridge { }) } + /// Drop local host credential so the next account cannot inherit `/ws/host`. + pub async fn host_clear_credential(&self) -> Result { + let client = self.client().await?; + let response: HostClearCredentialResponse = client + .request("minos_local_host_clear_credential", ArrayParams::new()) + .await + .context("minos_local_host_clear_credential")?; + Ok(HostClearCredentialDto { + cleared: response.cleared, + }) + } + /// Reattach a suspended/persisted session. When `auto_continue` is true and /// the store has `needs_continue`, injects a one-shot CONTINUE prompt. pub async fn resume_session(&self, session_id: String, auto_continue: bool) -> Result<()> { diff --git a/apps/desktop/src-tauri/src/im_outbox_store.rs b/apps/desktop/src-tauri/src/im_outbox_store.rs index 6703e305..538082bf 100644 --- a/apps/desktop/src-tauri/src/im_outbox_store.rs +++ b/apps/desktop/src-tauri/src/im_outbox_store.rs @@ -8,7 +8,7 @@ use std::path::PathBuf; use std::sync::Mutex; use anyhow::{anyhow, Context, Result}; -use rusqlite::{params, Connection}; +use rusqlite::{params, Connection, OptionalExtension}; use serde::{Deserialize, Serialize}; const MAX_ENTRIES: usize = 2_000; @@ -20,6 +20,9 @@ pub struct ImOutboxEntryDto { pub kind: String, pub conversation_id: String, pub client_message_id: String, + /// Immutable owner account. Empty = legacy quarantine (never claim). + #[serde(default)] + pub account_id: String, pub text: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub title: Option, @@ -73,6 +76,7 @@ impl ImOutboxStore { id TEXT NOT NULL, kind TEXT NOT NULL, conversation_id TEXT NOT NULL, + account_id TEXT NOT NULL DEFAULT '', text TEXT NOT NULL, title TEXT, reply_to_message_id TEXT, @@ -93,11 +97,23 @@ impl ImOutboxStore { CREATE INDEX IF NOT EXISTS idx_im_outbox_status_due ON im_outbox(status, next_attempt_at); CREATE INDEX IF NOT EXISTS idx_im_outbox_conversation - ON im_outbox(conversation_id, created_at_ms);", + ON im_outbox(conversation_id, created_at_ms); + CREATE INDEX IF NOT EXISTS idx_im_outbox_account_status_due + ON im_outbox(account_id, status, next_attempt_at);", )?; // Optional structured mentions JSON (AppendMessage wire targets). // ALTER is idempotent: ignore "duplicate column" on existing DBs. let _ = conn.execute("ALTER TABLE im_outbox ADD COLUMN mentions_json TEXT", []); + // Account ownership (empty = legacy quarantine). Idempotent ALTER. + let _ = conn.execute( + "ALTER TABLE im_outbox ADD COLUMN account_id TEXT NOT NULL DEFAULT ''", + [], + ); + let _ = conn.execute( + "CREATE INDEX IF NOT EXISTS idx_im_outbox_account_status_due + ON im_outbox(account_id, status, next_attempt_at)", + [], + ); Ok(Self { conn: Mutex::new(conn), }) @@ -109,7 +125,7 @@ impl ImOutboxStore { .lock() .map_err(|_| anyhow!("im_outbox lock poisoned"))?; let mut stmt = conn.prepare( - "SELECT client_message_id, id, kind, conversation_id, text, title, + "SELECT client_message_id, id, kind, conversation_id, account_id, text, title, reply_to_message_id, agent_runtimes_json, agent_id, agent_session_id, client_sent_at_ms, message_source, mentions_json, status, attempts, next_attempt_at, last_error, created_at_ms, updated_at_ms @@ -177,17 +193,50 @@ impl ImOutboxStore { .conn .lock() .map_err(|_| anyhow!("im_outbox lock poisoned"))?; - conn.execute( + // Capacity check + insert in one transaction so a rejected row never + // remains durable (and later drainable) after the caller saw an error. + let tx = conn + .unchecked_transaction() + .map_err(|e| anyhow!("im_outbox begin tx: {e}"))?; + + let existing: Option = tx + .query_row( + "SELECT status FROM im_outbox WHERE client_message_id = ?1", + params![entry.client_message_id], + |r| r.get(0), + ) + .optional()?; + + // New rows that would push unacked over the cap must fail before insert. + // Updates of existing unacked rows are allowed (status/backoff churn). + if existing.is_none() { + let unacked: i64 = tx.query_row( + "SELECT COUNT(*) FROM im_outbox WHERE status != 'acked'", + [], + |r| r.get(0), + )?; + let inserting_unacked = entry.status != "acked"; + if inserting_unacked && unacked >= MAX_ENTRIES as i64 { + return Err(anyhow!( + "im_outbox_capacity: {} unacked intents already at max {}", + unacked, + MAX_ENTRIES + )); + } + } + + tx.execute( "INSERT INTO im_outbox ( - client_message_id, id, kind, conversation_id, text, title, + client_message_id, id, kind, conversation_id, account_id, text, title, reply_to_message_id, agent_runtimes_json, agent_id, agent_session_id, client_sent_at_ms, message_source, mentions_json, status, attempts, next_attempt_at, last_error, created_at_ms, updated_at_ms - ) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19) + ) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20) ON CONFLICT(client_message_id) DO UPDATE SET id=excluded.id, kind=excluded.kind, conversation_id=excluded.conversation_id, + account_id=excluded.account_id, text=excluded.text, title=excluded.title, reply_to_message_id=excluded.reply_to_message_id, @@ -207,6 +256,7 @@ impl ImOutboxStore { entry.id, entry.kind, entry.conversation_id, + entry.account_id, entry.text, entry.title, entry.reply_to_message_id, @@ -225,19 +275,21 @@ impl ImOutboxStore { ], )?; // Compact oldest acked rows when over cap; never delete unacked. - Self::compact_acked_locked(&conn)?; - let unacked: i64 = conn.query_row( + Self::compact_acked_locked(&tx)?; + let unacked: i64 = tx.query_row( "SELECT COUNT(*) FROM im_outbox WHERE status != 'acked'", [], |r| r.get(0), )?; if unacked > MAX_ENTRIES as i64 { + // Defensive: should not happen after pre-check; abort without commit. return Err(anyhow!( "im_outbox_capacity: {} unacked intents exceed max {}", unacked, MAX_ENTRIES )); } + tx.commit()?; Ok(()) } @@ -272,16 +324,17 @@ impl ImOutboxStore { fn insert_entry(tx: &rusqlite::Transaction<'_>, entry: &ImOutboxEntryDto) -> Result<()> { tx.execute( "INSERT INTO im_outbox ( - client_message_id, id, kind, conversation_id, text, title, + client_message_id, id, kind, conversation_id, account_id, text, title, reply_to_message_id, agent_runtimes_json, agent_id, agent_session_id, client_sent_at_ms, message_source, mentions_json, status, attempts, next_attempt_at, last_error, created_at_ms, updated_at_ms - ) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19)", + ) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20)", params![ entry.client_message_id, entry.id, entry.kind, entry.conversation_id, + entry.account_id, entry.text, entry.title, entry.reply_to_message_id, @@ -318,30 +371,31 @@ fn mentions_json(v: &Option>) -> Option { } fn map_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { - let runtimes_raw: Option = row.get(7)?; + let runtimes_raw: Option = row.get(8)?; let agent_runtimes = runtimes_raw.and_then(|s| serde_json::from_str(&s).ok()); - let mentions_raw: Option = row.get(12)?; + let mentions_raw: Option = row.get(13)?; let mentions = mentions_raw.and_then(|s| serde_json::from_str(&s).ok()); Ok(ImOutboxEntryDto { client_message_id: row.get(0)?, id: row.get(1)?, kind: row.get(2)?, conversation_id: row.get(3)?, - text: row.get(4)?, - title: row.get(5)?, - reply_to_message_id: row.get(6)?, + account_id: row.get(4)?, + text: row.get(5)?, + title: row.get(6)?, + reply_to_message_id: row.get(7)?, agent_runtimes, - agent_id: row.get(8)?, - agent_session_id: row.get(9)?, - client_sent_at_ms: row.get(10)?, - message_source: row.get(11)?, + agent_id: row.get(9)?, + agent_session_id: row.get(10)?, + client_sent_at_ms: row.get(11)?, + message_source: row.get(12)?, mentions, - status: row.get(13)?, - attempts: row.get(14)?, - next_attempt_at: row.get(15)?, - last_error: row.get(16)?, - created_at_ms: row.get(17)?, - updated_at_ms: row.get(18)?, + status: row.get(14)?, + attempts: row.get(15)?, + next_attempt_at: row.get(16)?, + last_error: row.get(17)?, + created_at_ms: row.get(18)?, + updated_at_ms: row.get(19)?, }) } @@ -361,6 +415,7 @@ mod tests { kind: "user_message".into(), conversation_id: "c1".into(), client_message_id: id.into(), + account_id: "acct-a".into(), text: "hi".into(), title: None, reply_to_message_id: None, @@ -444,4 +499,21 @@ mod tests { .iter() .all(|e| e.status != "acked" || e.client_message_id != "a0")); } + + #[test] + fn upsert_capacity_rejects_without_persisting() { + let dir = tempdir().unwrap(); + let store = ImOutboxStore::open_path(dir.path().join("t.db")).unwrap(); + for i in 0..MAX_ENTRIES { + store.upsert(&sample(&format!("p{i}"), "pending")).unwrap(); + } + let err = store.upsert(&sample("overflow", "pending")).unwrap_err(); + assert!( + err.to_string().contains("im_outbox_capacity"), + "expected capacity error, got {err}" + ); + let all = store.list_all().unwrap(); + assert_eq!(all.len(), MAX_ENTRIES); + assert!(!all.iter().any(|e| e.client_message_id == "overflow")); + } } diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index e6e9d5c1..fbd2e177 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -144,6 +144,7 @@ pub fn run() { daemon_host_prepare_link, daemon_host_sign_link_proof, daemon_host_apply_link_token, + daemon_host_clear_credential, is_auto_update_supported, is_updater_plugin_enabled, prepare_for_app_update, diff --git a/apps/desktop/src-tauri/src/shutdown.rs b/apps/desktop/src-tauri/src/shutdown.rs index a5792f67..b58e2154 100644 --- a/apps/desktop/src-tauri/src/shutdown.rs +++ b/apps/desktop/src-tauri/src/shutdown.rs @@ -29,7 +29,13 @@ pub fn shutdown_managed_once(daemon: &Arc, done: &AtomicBool) { // Block until stop finishes (or times out) — Exit is the last chance before // process teardown drops the runtime without group signals to provider children. tauri::async_runtime::block_on(async move { - match tokio::time::timeout(SHUTDOWN_TIMEOUT, daemon.shutdown_managed()).await { + // Prefer completing stop; only race a wall-clock budget so Cmd+Q cannot + // hang forever. `shutdown_managed` detaches stop onto a join task and + // keeps the managed handle until that task finishes, so a timeout here + // must still wait for the in-flight stop (providers terminate inside). + let stop = daemon.shutdown_managed(); + tokio::pin!(stop); + match tokio::time::timeout(SHUTDOWN_TIMEOUT, &mut stop).await { Ok(Ok(())) => { info!("desktop host managed daemon shutdown complete"); } @@ -42,8 +48,16 @@ pub fn shutdown_managed_once(daemon: &Arc, done: &AtomicBool) { Err(_) => { warn!( timeout_secs = SHUTDOWN_TIMEOUT.as_secs(), - "managed daemon shutdown timed out; continuing process exit" + "managed daemon shutdown exceeded budget; awaiting terminal stop" ); + // Do not drop the stop future — finish provider terminate first. + match stop.await { + Ok(()) => info!("desktop host managed daemon shutdown complete after budget"), + Err(e) => warn!( + error = %e, + "managed daemon shutdown failed after budget" + ), + } } } }); diff --git a/apps/desktop/src/features/agents/AgentsView.tsx b/apps/desktop/src/features/agents/AgentsView.tsx index 50ea9dd8..fdd81c40 100644 --- a/apps/desktop/src/features/agents/AgentsView.tsx +++ b/apps/desktop/src/features/agents/AgentsView.tsx @@ -15,9 +15,9 @@ import { Plus, RefreshCw, Trash2, - X, } from "lucide-react"; -import { agentMeta, type AgentRuntime } from "@/shared/lib/mock-data"; +import type { AgentRuntime } from "@/shared/domain/collaboration"; +import { agentMeta } from "@/shared/lib/mock-data"; import { useWorkspaceStore } from "@/store/workspace-store"; import { useAccountStore } from "@/store/account-store"; import { daemonApi, isTauriRuntime } from "@/shared/lib/daemon"; @@ -44,7 +44,14 @@ import { type ModelCatalogEntry, type RuntimeCliDescriptor, } from "./lib/agentConfigProjection"; -import { MODAL_BACKDROP_CLASS } from "@/shared/ui/modalBackdrop"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/shared/ui/dialog"; import { PageHeader, PageHeaderPrimaryButton, @@ -133,6 +140,8 @@ export function AgentsView() { const [createOpen, setCreateOpen] = useState(false); const [editBot, setEditBot] = useState(null); + const [deleteBot, setDeleteBot] = useState(null); + const [deleting, setDeleting] = useState(false); const [error, setError] = useState(null); const bots = useMemo((): BotRow[] => { @@ -434,41 +443,7 @@ export function AgentsView() { + + + + ); } @@ -707,38 +758,21 @@ function CreateAgentDialog({ }; return ( -
{ - if (e.target === e.currentTarget) onClose(); - }} - > -
-
-
-

- Create agent -

-

- {cloudOnline - ? "Creates a global Hub bot (identity SSOT). Digital body is shared across conversations." - : "Offline: Host profile cache only. Sign in to create a Hub bot."} -

-
- -
+ !open && !saving && onClose()}> + + + + Create agent + + + {cloudOnline + ? "Creates a global Hub bot (identity SSOT). Digital body is shared across conversations." + : "Offline: Host profile cache only. Sign in to create a Hub bot."} + +
@@ -916,11 +950,12 @@ function CreateAgentDialog({ {err ?

{err}

: null}
-
+ @@ -932,9 +967,9 @@ function CreateAgentDialog({ > {saving ? "Creating…" : "Create agent"} -
-
-
+ + + ); } @@ -1046,38 +1081,21 @@ function EditAgentDialog({ }; return ( -
{ - if (e.target === e.currentTarget) onClose(); - }} - > -
-
-
-

- Edit digital body -

-

- {bot.source === "hub" - ? "Updates Hub bot identity (system_prompt / default_reasoning_effort)." - : "Updates local Host cache only."} -

-
- -
+ !open && !saving && onClose()}> + + + + Edit digital body + + + {bot.source === "hub" + ? "Updates Hub bot identity (system_prompt / default_reasoning_effort)." + : "Updates local Host cache only."} + +
@@ -1138,11 +1156,12 @@ function EditAgentDialog({ {err ?

{err}

: null}
-
+ @@ -1154,9 +1173,9 @@ function EditAgentDialog({ > {saving ? "Saving…" : "Save"} -
-
-
+ + + ); } diff --git a/apps/desktop/src/features/chat/Composer.tsx b/apps/desktop/src/features/chat/Composer.tsx index 9c4bd5c5..56d8b501 100644 --- a/apps/desktop/src/features/chat/Composer.tsx +++ b/apps/desktop/src/features/chat/Composer.tsx @@ -7,8 +7,8 @@ import { type MentionHuman, type MentionProfile, } from "@/shared/lib/agent-route"; -import type { TimelineMessage } from "@/shared/lib/mock-data"; -import { membershipTokensOfBots } from "@/shared/lib/mock-data"; +import type { TimelineMessage } from "@/shared/domain/collaboration"; +import { membershipTokensOfBots } from "@/shared/domain/collaboration"; import { hasPrimaryShortcutModifier } from "@/shared/lib/platform"; import { cn } from "@/shared/lib/utils"; import { toast } from "@/shared/lib/toast"; diff --git a/apps/desktop/src/features/chat/GitActivityCard.tsx b/apps/desktop/src/features/chat/GitActivityCard.tsx index 2a1be127..7a529771 100644 --- a/apps/desktop/src/features/chat/GitActivityCard.tsx +++ b/apps/desktop/src/features/chat/GitActivityCard.tsx @@ -8,7 +8,7 @@ import { Layers, XCircle, } from "lucide-react"; -import type { TimelineGitActivity } from "@/shared/lib/mock-data"; +import type { TimelineGitActivity } from "@/shared/domain/collaboration"; import { cn } from "@/shared/lib/utils"; import { shortWorktree } from "./lib/format"; diff --git a/apps/desktop/src/features/chat/MessageList.tsx b/apps/desktop/src/features/chat/MessageList.tsx index 7b17368b..f046e979 100644 --- a/apps/desktop/src/features/chat/MessageList.tsx +++ b/apps/desktop/src/features/chat/MessageList.tsx @@ -8,7 +8,7 @@ import { } from "react"; import { ArrowDown, Loader2 } from "lucide-react"; import { VList, type VListHandle } from "virtua"; -import type { TimelineMessage } from "@/shared/lib/mock-data"; +import type { TimelineMessage } from "@/shared/domain/collaboration"; import { useStableArrayShallow, useStableMap, diff --git a/apps/desktop/src/features/chat/MessageRow.tsx b/apps/desktop/src/features/chat/MessageRow.tsx index 7fc91c0e..a026b336 100644 --- a/apps/desktop/src/features/chat/MessageRow.tsx +++ b/apps/desktop/src/features/chat/MessageRow.tsx @@ -1,6 +1,7 @@ import { memo, useState } from "react"; import { Wrench } from "lucide-react"; -import { agentMeta, type TimelineMessage } from "@/shared/lib/mock-data"; +import type { TimelineMessage } from "@/shared/domain/collaboration"; +import { agentMeta } from "@/shared/lib/mock-data"; import { shortSessionId, type KnownAgent } from "@/shared/lib/agent-route"; import { Avatar } from "@/shared/ui/Avatar"; import { diff --git a/apps/desktop/src/features/chat/ReplyPreview.tsx b/apps/desktop/src/features/chat/ReplyPreview.tsx index 3a845032..01b0552b 100644 --- a/apps/desktop/src/features/chat/ReplyPreview.tsx +++ b/apps/desktop/src/features/chat/ReplyPreview.tsx @@ -1,4 +1,4 @@ -import type { TimelineMessage } from "@/shared/lib/mock-data"; +import type { TimelineMessage } from "@/shared/domain/collaboration"; import { replyAuthorLabel, replyPreviewBody } from "./lib/format"; export function ReplyPreview({ diff --git a/apps/desktop/src/features/chat/TimelineHeader.tsx b/apps/desktop/src/features/chat/TimelineHeader.tsx index e01c90ad..0705e943 100644 --- a/apps/desktop/src/features/chat/TimelineHeader.tsx +++ b/apps/desktop/src/features/chat/TimelineHeader.tsx @@ -1,6 +1,6 @@ import { useEffect, useRef, useState } from "react"; import { GitBranch, Layers } from "lucide-react"; -import type { Conversation } from "@/shared/lib/mock-data"; +import type { Conversation } from "@/shared/domain/collaboration"; import { MetaChip, PriorityPlaceholder, @@ -141,27 +141,38 @@ export function TimelineHeader({ { - if (conversationId) { - void cycleConversationPriority(conversationId); - } + if (!conversationId) return; + void (async () => { + await cycleConversationPriority(conversationId); + const actionError = + useWorkspaceStore.getState().actionError; + if (actionError) toast.error(actionError); + })(); }} title="Click to cycle priority" /> ) : ( { - if (conversationId) { - void cycleConversationPriority(conversationId); - } + if (!conversationId) return; + void (async () => { + await cycleConversationPriority(conversationId); + const actionError = + useWorkspaceStore.getState().actionError; + if (actionError) toast.error(actionError); + })(); }} /> )} { - if (conversationId) { - void cycleConversationProgress(conversationId); - } + if (!conversationId) return; + void (async () => { + await cycleConversationProgress(conversationId); + const actionError = useWorkspaceStore.getState().actionError; + if (actionError) toast.error(actionError); + })(); }} title="Click to cycle progress" /> diff --git a/apps/desktop/src/features/chat/lib/format.ts b/apps/desktop/src/features/chat/lib/format.ts index 1b54ff3b..b0d702cd 100644 --- a/apps/desktop/src/features/chat/lib/format.ts +++ b/apps/desktop/src/features/chat/lib/format.ts @@ -1,4 +1,5 @@ -import { agentMeta, type TimelineMessage } from "@/shared/lib/mock-data"; +import type { TimelineMessage } from "@/shared/domain/collaboration"; +import { agentMeta } from "@/shared/lib/mock-data"; import { shortSessionId, type KnownAgent } from "@/shared/lib/agent-route"; /** Truncate a worktree path for header meta chips. */ diff --git a/apps/desktop/src/features/chat/lib/message-grouping.ts b/apps/desktop/src/features/chat/lib/message-grouping.ts index 9f845fd2..9f352942 100644 --- a/apps/desktop/src/features/chat/lib/message-grouping.ts +++ b/apps/desktop/src/features/chat/lib/message-grouping.ts @@ -1,4 +1,4 @@ -import type { TimelineMessage } from "@/shared/lib/mock-data"; +import type { TimelineMessage } from "@/shared/domain/collaboration"; /** Default continuity window (Slack-like). */ export const MESSAGE_GROUP_WINDOW_MS = 10 * 60 * 1000; diff --git a/apps/desktop/src/features/chat/lib/virtual-timeline-items.test.ts b/apps/desktop/src/features/chat/lib/virtual-timeline-items.test.ts index 84725657..002e4d10 100644 --- a/apps/desktop/src/features/chat/lib/virtual-timeline-items.test.ts +++ b/apps/desktop/src/features/chat/lib/virtual-timeline-items.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { describe, it } from "node:test"; -import type { TimelineMessage } from "@/shared/lib/mock-data"; +import type { TimelineMessage } from "@/shared/domain/collaboration"; import { buildVirtualTimelineItems, estimateVirtualTimelineItemSize, diff --git a/apps/desktop/src/features/chat/lib/virtual-timeline-items.ts b/apps/desktop/src/features/chat/lib/virtual-timeline-items.ts index b3f1e5a5..b0b6f459 100644 --- a/apps/desktop/src/features/chat/lib/virtual-timeline-items.ts +++ b/apps/desktop/src/features/chat/lib/virtual-timeline-items.ts @@ -1,4 +1,4 @@ -import type { TimelineMessage } from "@/shared/lib/mock-data"; +import type { TimelineMessage } from "@/shared/domain/collaboration"; import { isMessageGroupContinuation, shouldShowDayDivider, diff --git a/apps/desktop/src/features/chat/reaction-store.ts b/apps/desktop/src/features/chat/reaction-store.ts index 8e2d15ea..0229a967 100644 --- a/apps/desktop/src/features/chat/reaction-store.ts +++ b/apps/desktop/src/features/chat/reaction-store.ts @@ -9,7 +9,7 @@ import { create } from "zustand"; import { daemonApi, isTauriRuntime } from "@/shared/lib/daemon"; import { toast } from "@/shared/lib/toast"; import { isCloudImMode } from "@/shared/lib/cloud-timeline"; -import { syncReactionToggleToCloud } from "@/shared/lib/im-cloud-sync"; +import { syncReactionToggleToCloud } from "@/store/im/im-cloud-sync"; import { useAccountStore } from "@/store/account-store"; import { hasInFlightToggleCount, 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 736fd5c8..73b0dc12 100644 --- a/apps/desktop/src/features/host/lib/ensure-host-connection.ts +++ b/apps/desktop/src/features/host/lib/ensure-host-connection.ts @@ -60,15 +60,38 @@ function errorMessage(error: unknown): string { return String(error); } +export type RegisterHostCredentialOptions = { + /** + * Re-checked after every await and again immediately before applyLinkToken. + * Account leave/switch must return false so a deferred prior register never + * writes hit_ under a newer account. + */ + isCurrent?: () => boolean; +}; + +function abortedOutcome(): EnsureHostFailure { + return { + ok: false, + stage: "apply", + message: "Host registration superseded by account leave/switch", + }; +} + /** * Register this Mac with the account and apply a fresh `hit_`. * Call only when local credential is absent or known-invalid — not every poll. + * + * Generation checks: every await boundary + immediately before applyLinkToken. */ export async function registerHostCredential( ports: EnsureHostPorts, hostDisplayName: string, + opts?: RegisterHostCredentialOptions, ): Promise { const displayName = hostDisplayName.trim() || "This Mac"; + const stillCurrent = () => opts?.isCurrent?.() ?? true; + + if (!stillCurrent()) return abortedOutcome(); let prepared: { installationId: string; @@ -85,6 +108,7 @@ export async function registerHostCredential( cause: error, }; } + if (!stillCurrent()) return abortedOutcome(); let signature: string; try { @@ -101,6 +125,7 @@ export async function registerHostCredential( cause: error, }; } + if (!stillCurrent()) return abortedOutcome(); let cloud: Awaited>; try { @@ -119,9 +144,17 @@ export async function registerHostCredential( cause: error, }; } + if (!stillCurrent()) return abortedOutcome(); try { + // Final guard immediately before the only write that mutates daemon hit_. + if (!stillCurrent()) return abortedOutcome(); const applied = await ports.applyLinkToken(cloud.hostInstallationToken); + if (!stillCurrent()) { + // Applied under a race — caller must clear; surface as aborted so setState + // does not claim ownership for the superseded account. + return abortedOutcome(); + } if (!applied.linked) { return { ok: false, 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 new file mode 100644 index 00000000..67a6313b --- /dev/null +++ b/apps/desktop/src/features/host/lib/host-connection-machine.test.ts @@ -0,0 +1,147 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { + decideHostEnsure, + runHostEnsure, + type HostEnsureEffectPorts, +} from "./host-connection-machine.ts"; + +describe("decideHostEnsure", () => { + it("matching online → no-op", () => { + assert.deepEqual( + decideHostEnsure({ + forceReregister: false, + sessionAccountId: "acc-1", + hostCredentialAccountId: "acc-1", + cloudOnline: true, + hasHostToken: true, + }), + { action: "noop-online" }, + ); + }); + + it("mismatch account + hasHostToken → force re-register", () => { + assert.deepEqual( + decideHostEnsure({ + forceReregister: false, + sessionAccountId: "acc-2", + hostCredentialAccountId: "acc-1", + cloudOnline: true, + hasHostToken: true, + }), + { action: "register" }, + ); + }); + + it("matching hasHostToken offline → wait dial", () => { + assert.deepEqual( + decideHostEnsure({ + forceReregister: false, + sessionAccountId: "acc-1", + hostCredentialAccountId: "acc-1", + cloudOnline: false, + hasHostToken: true, + }), + { action: "wait-dial" }, + ); + }); + + it("forceReregister always registers", () => { + assert.deepEqual( + decideHostEnsure({ + forceReregister: true, + sessionAccountId: "acc-1", + hostCredentialAccountId: "acc-1", + cloudOnline: true, + hasHostToken: true, + }), + { action: "register" }, + ); + }); + + it("no ownership and no token → register", () => { + assert.deepEqual( + decideHostEnsure({ + forceReregister: false, + sessionAccountId: "acc-1", + hostCredentialAccountId: null, + cloudOnline: false, + hasHostToken: false, + }), + { action: "register" }, + ); + }); +}); + +describe("runHostEnsure", () => { + function ports( + overrides: Partial = {}, + ): HostEnsureEffectPorts { + return { + refreshFlags: async () => ({ cloudOnline: false, hasHostToken: false }), + isOnline: async () => false, + registerPorts: { + prepareLink: async () => ({ + installationId: "host-1", + publicKey: "pk", + nonce: "n", + }), + signLinkProof: async () => ({ signature: "sig" }), + applyLinkToken: async () => ({ linked: true }), + registerHost: async () => ({ + hostInstallationId: "host-1", + hostInstallationToken: "hit_x", + pairId: "pair-1", + accountId: "acc-1", + hostDisplayName: "This Mac", + linkedAtMs: 1, + }), + }, + hostDisplayName: "This Mac", + waitOpts: { timeoutMs: 10, intervalMs: 1 }, + ...overrides, + }; + } + + it("returns online without register when matching online", async () => { + let registered = false; + const result = await runHostEnsure( + { + forceReregister: false, + sessionAccountId: "acc-1", + hostCredentialAccountId: "acc-1", + }, + ports({ + refreshFlags: async () => ({ cloudOnline: true, hasHostToken: true }), + registerPorts: { + prepareLink: async () => { + registered = true; + throw new Error("should not prepare"); + }, + signLinkProof: async () => ({ signature: "x" }), + applyLinkToken: async () => ({ linked: true }), + registerHost: async () => { + throw new Error("should not register"); + }, + }, + }), + ); + assert.equal(result.kind, "online"); + assert.equal(registered, false); + }); + + it("registers when account ownership mismatches despite token", async () => { + const result = await runHostEnsure( + { + forceReregister: false, + sessionAccountId: "acc-2", + hostCredentialAccountId: "acc-1", + }, + ports({ + refreshFlags: async () => ({ cloudOnline: true, hasHostToken: true }), + isOnline: async () => true, + }), + ); + assert.equal(result.kind, "registered-online"); + }); +}); diff --git a/apps/desktop/src/features/host/lib/host-connection-machine.ts b/apps/desktop/src/features/host/lib/host-connection-machine.ts new file mode 100644 index 00000000..130b307d --- /dev/null +++ b/apps/desktop/src/features/host/lib/host-connection-machine.ts @@ -0,0 +1,204 @@ +/** + * Pure host-connection ensure decision + effect orchestration. + * + * account-store owns session + generation counters; this module decides whether + * to no-op, wait for dial, or force re-register, then runs the effect ports. + */ + +import { + registerHostCredential, + waitForCloudOnline, + type EnsureHostPorts, + type EnsureHostOutcome, + type RegisterHostCredentialOptions, +} from "./ensure-host-connection.ts"; +import { + enqueueHostCredentialOp, + isHostCredentialCurrent, + getHostCredentialGeneration, +} from "./host-credential-controller.ts"; + +export type HostEnsureInput = { + forceReregister: boolean; + sessionAccountId: string; + hostCredentialAccountId: string | null; + cloudOnline: boolean; + hasHostToken: boolean; +}; + +export type HostEnsureDecision = + | { action: "noop-online" } + | { action: "wait-dial" } + | { action: "register" }; + +/** + * Decide host ensure path. + * - mismatch account + hasHostToken (or no ownership) → register + * - matching ownership + online → no-op + * - matching ownership + hasHostToken → wait dial + * - otherwise → register + */ +export function decideHostEnsure(input: HostEnsureInput): HostEnsureDecision { + const accountId = input.sessionAccountId.trim(); + if (!accountId) return { action: "register" }; + + const hostOwnedBySession = input.hostCredentialAccountId === accountId; + + if (input.forceReregister) { + return { action: "register" }; + } + + // Foreign or missing ownership with a lingering hit_ must re-register. + if (!hostOwnedBySession) { + return { action: "register" }; + } + + if (input.cloudOnline) { + return { action: "noop-online" }; + } + + if (input.hasHostToken) { + return { action: "wait-dial" }; + } + + return { action: "register" }; +} + +export type HostEnsureEffectPorts = { + refreshFlags: () => Promise<{ cloudOnline: boolean; hasHostToken: boolean }>; + isOnline: () => Promise; + registerPorts: EnsureHostPorts; + hostDisplayName: string; + waitOpts?: { timeoutMs?: number; intervalMs?: number }; + /** When false mid-register, apply is skipped (account leave/switch). */ + isCurrent?: () => boolean; +}; + +export type HostEnsureRunResult = + | { kind: "online" } + | { kind: "offline"; message: string; hostCredentialAccountId?: null } + | { + kind: "registered-online"; + hostInstallationId: string; + hostDisplayName: string; + linkedAtMs: number; + pairId: string; + } + | { + kind: "registered-offline"; + hostInstallationId: string; + hostDisplayName: string; + linkedAtMs: number; + pairId: string; + message: string; + } + | { + kind: "register-failed"; + stage: string; + message: string; + }; + +/** + * Run ensure decision against live flags + register/wait ports. + * Caller supplies current ownership snapshot; generation checks stay outside. + */ +export async function runHostEnsure( + decisionInput: Omit, + ports: HostEnsureEffectPorts, +): Promise { + const flags = await ports.refreshFlags(); + const decision = decideHostEnsure({ + ...decisionInput, + cloudOnline: flags.cloudOnline, + hasHostToken: flags.hasHostToken, + }); + + if (decision.action === "noop-online") { + return { kind: "online" }; + } + + if (decision.action === "wait-dial") { + const online = await waitForCloudOnline(ports.isOnline, ports.waitOpts); + if (online) return { kind: "online" }; + return { + kind: "offline", + message: + "Has local host credential but server is unreachable. Check minos-backend, then Retry.", + }; + } + + // Serialize with leave/clear so deferred register never races apply. + const credGen = getHostCredentialGeneration(); + const stillCurrent: NonNullable = + () => + isHostCredentialCurrent(credGen) && (ports.isCurrent?.() ?? true); + + if (!stillCurrent()) { + return { + kind: "register-failed", + stage: "apply", + message: "Host registration superseded by account leave/switch", + }; + } + + const outcome: EnsureHostOutcome = await enqueueHostCredentialOp( + async (genAtEnqueue) => { + if ( + !isHostCredentialCurrent(genAtEnqueue) || + !(ports.isCurrent?.() ?? true) + ) { + return { + ok: false as const, + stage: "apply" as const, + message: "Host registration superseded by account leave/switch", + }; + } + return registerHostCredential(ports.registerPorts, ports.hostDisplayName, { + isCurrent: stillCurrent, + }); + }, + ); + + if (!outcome.ok) { + return { + kind: "register-failed", + stage: outcome.stage, + message: outcome.message, + }; + } + + if (!stillCurrent()) { + return { + kind: "register-failed", + stage: "apply", + message: "Host registration superseded by account leave/switch", + }; + } + + const online = await waitForCloudOnline(ports.isOnline, ports.waitOpts); + if (!stillCurrent()) { + return { + kind: "register-failed", + stage: "apply", + message: "Host registration superseded by account leave/switch", + }; + } + if (online) { + return { + kind: "registered-online", + hostInstallationId: outcome.hostInstallationId, + hostDisplayName: outcome.hostDisplayName, + linkedAtMs: outcome.linkedAtMs, + pairId: outcome.pairId, + }; + } + return { + kind: "registered-offline", + hostInstallationId: outcome.hostInstallationId, + hostDisplayName: outcome.hostDisplayName, + linkedAtMs: outcome.linkedAtMs, + pairId: outcome.pairId, + message: + "Signed in but not connected to the server yet. Retry or check that minos-backend is running.", + }; +} 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 new file mode 100644 index 00000000..4efba29f --- /dev/null +++ b/apps/desktop/src/features/host/lib/host-credential-controller.test.ts @@ -0,0 +1,144 @@ +import assert from "node:assert/strict"; +import { describe, it, beforeEach } from "node:test"; +import { + bumpHostCredentialGeneration, + enqueueHostCredentialOp, + getHostCredentialGeneration, + isHostCredentialCurrent, + resetHostCredentialControllerForTests, + revokeHostCredential, +} from "./host-credential-controller.ts"; +import { registerHostCredential } from "./ensure-host-connection.ts"; + +describe("host-credential-controller", () => { + beforeEach(() => { + resetHostCredentialControllerForTests(); + }); + + it("serializes ops and aborts stale apply after revoke", async () => { + const applied: string[] = []; + let releaseA!: () => void; + const aGate = new Promise((r) => { + releaseA = r; + }); + + const a = enqueueHostCredentialOp(async (gen) => { + await aGate; + if (!isHostCredentialCurrent(gen)) { + return "aborted-a"; + } + applied.push("hit_a"); + return "applied-a"; + }); + + revokeHostCredential(async () => { + applied.push("clear"); + }); + + const b = enqueueHostCredentialOp(async (gen) => { + if (!isHostCredentialCurrent(gen)) { + return "aborted-b"; + } + applied.push("hit_b"); + return "applied-b"; + }); + + releaseA(); + assert.equal(await a, "aborted-a"); + assert.equal(await b, "applied-b"); + assert.deepEqual(applied, ["clear", "hit_b"]); + }); + + it("deferred registerHost never applies token after leave", async () => { + let releaseRegister!: () => void; + const registerGate = new Promise((r) => { + releaseRegister = r; + }); + const applied: string[] = []; + const gen = getHostCredentialGeneration(); + + const registerPromise = enqueueHostCredentialOp(async (opGen) => { + return registerHostCredential( + { + prepareLink: async () => ({ + installationId: "host-a", + publicKey: "pk", + nonce: "n", + }), + signLinkProof: async () => ({ signature: "sig" }), + registerHost: async () => { + await registerGate; + return { + hostInstallationId: "host-a", + hostInstallationToken: "hit_account_a", + pairId: "pair-a", + accountId: "acc-a", + hostDisplayName: "Mac A", + linkedAtMs: 1, + }; + }, + applyLinkToken: async (token) => { + applied.push(token); + return { linked: true }; + }, + }, + "Mac", + { + isCurrent: () => + isHostCredentialCurrent(opGen) && isHostCredentialCurrent(gen), + }, + ); + }); + + // Switch accounts while A is mid-registerHost. + revokeHostCredential(async () => { + applied.push("cleared"); + }); + + const bOutcome = await enqueueHostCredentialOp(async (opGen) => { + return registerHostCredential( + { + prepareLink: async () => ({ + installationId: "host-b", + publicKey: "pk", + nonce: "n", + }), + signLinkProof: async () => ({ signature: "sig" }), + registerHost: async () => ({ + hostInstallationId: "host-b", + hostInstallationToken: "hit_account_b", + pairId: "pair-b", + accountId: "acc-b", + hostDisplayName: "Mac B", + linkedAtMs: 2, + }), + applyLinkToken: async (token) => { + if (!isHostCredentialCurrent(opGen)) { + throw new Error("stale apply"); + } + applied.push(token); + return { linked: true }; + }, + }, + "Mac", + { isCurrent: () => isHostCredentialCurrent(opGen) }, + ); + }); + + releaseRegister(); + const aOutcome = await registerPromise; + + assert.equal(aOutcome.ok, false); + assert.equal(bOutcome.ok, true); + assert.ok(!applied.includes("hit_account_a")); + assert.ok(applied.includes("hit_account_b")); + assert.ok(applied.includes("cleared")); + }); + + it("bump invalidates prior generation", () => { + const g0 = getHostCredentialGeneration(); + assert.equal(isHostCredentialCurrent(g0), true); + bumpHostCredentialGeneration(); + assert.equal(isHostCredentialCurrent(g0), false); + }); +}); diff --git a/apps/desktop/src/features/host/lib/host-credential-controller.ts b/apps/desktop/src/features/host/lib/host-credential-controller.ts new file mode 100644 index 00000000..6ff36ba2 --- /dev/null +++ b/apps/desktop/src/features/host/lib/host-credential-controller.ts @@ -0,0 +1,62 @@ +/** + * Serial host-credential controller. + * + * clear / apply must never interleave: a deferred account-A register must not + * write hit_ after account-B already owns the daemon, and leave must close the + * authorization boundary before the next account registers. + */ + +let credentialGeneration = 0; +let opChain: Promise = Promise.resolve(); + +export function getHostCredentialGeneration(): number { + return credentialGeneration; +} + +/** Bump generation so in-flight register/apply abort before writing hit_. */ +export function bumpHostCredentialGeneration(): number { + credentialGeneration += 1; + return credentialGeneration; +} + +/** + * Enqueue a credential mutation. Operations run strictly in order. + * Callers must re-check generation inside `op` before side effects. + */ +export function enqueueHostCredentialOp( + op: (generation: number) => Promise, +): Promise { + const genAtEnqueue = credentialGeneration; + const run = opChain.catch(() => undefined).then(() => op(genAtEnqueue)); + opChain = run.then( + () => undefined, + () => undefined, + ); + return run; +} + +/** + * Account leave/switch: invalidate in-flight ensure and clear daemon hit_. + * Clear is serialized so a subsequent register waits for it. + */ +export function revokeHostCredential(clear: () => Promise): void { + bumpHostCredentialGeneration(); + void enqueueHostCredentialOp(async () => { + try { + await clear(); + } catch { + /* daemon may be offline; next login force-registers */ + } + }); +} + +/** True when the captured ensure generation is still current. */ +export function isHostCredentialCurrent(generation: number): boolean { + return generation === credentialGeneration; +} + +/** Test helper — reset serial chain + generation. */ +export function resetHostCredentialControllerForTests(): void { + credentialGeneration = 0; + opChain = Promise.resolve(); +} diff --git a/apps/desktop/src/features/work/ConversationList.tsx b/apps/desktop/src/features/work/ConversationList.tsx index 4e01bbd9..6df0df87 100644 --- a/apps/desktop/src/features/work/ConversationList.tsx +++ b/apps/desktop/src/features/work/ConversationList.tsx @@ -1,6 +1,6 @@ import { memo, useCallback, useEffect, useMemo, useState } from "react"; import { ChevronDown, ListFilter, MessageSquare, PanelLeftClose } from "lucide-react"; -import type { Conversation } from "@/shared/lib/mock-data"; +import type { Conversation } from "@/shared/domain/collaboration"; import { matchesProgressFilter, progressFilterLabel, diff --git a/apps/desktop/src/features/work/ProjectBoard.tsx b/apps/desktop/src/features/work/ProjectBoard.tsx index fb59f904..3e3d26ca 100644 --- a/apps/desktop/src/features/work/ProjectBoard.tsx +++ b/apps/desktop/src/features/work/ProjectBoard.tsx @@ -1,10 +1,10 @@ import { useMemo } from "react"; import { MessageSquare } from "lucide-react"; -import { - boardColumns, - type Conversation, - type ConversationBoardColumn, -} from "@/shared/lib/mock-data"; +import { boardColumns } from "@/shared/lib/mock-data"; +import type { + Conversation, + ConversationBoardColumn, +} from "@/shared/domain/collaboration"; import { PriorityTag, ProgressTag } from "@/shared/ui/Tag"; import { useUiStore } from "@/store/ui-store"; import { useWorkspaceStore } from "@/store/workspace-store"; diff --git a/apps/desktop/src/features/work/SessionInspector.tsx b/apps/desktop/src/features/work/SessionInspector.tsx index 90a6d54a..514a4af2 100644 --- a/apps/desktop/src/features/work/SessionInspector.tsx +++ b/apps/desktop/src/features/work/SessionInspector.tsx @@ -4,7 +4,8 @@ import { AuxiliaryPanel, type AuxiliaryPanelLayout, } from "@/shared/layout/AuxiliaryPanel"; -import { agentMeta, type AgentSession } from "@/shared/lib/mock-data"; +import type { AgentSession } from "@/shared/domain/collaboration"; +import { agentMeta } from "@/shared/lib/mock-data"; import { projectSessionFromEntity } from "@/shared/lib/session-entity"; import { Avatar } from "@/shared/ui/Avatar"; import { StatusPill } from "@/shared/ui/StatusPill"; @@ -66,8 +67,9 @@ export function SessionInspector({ void loadInspector(conversationId); }, [conversationId, detailsOpen, source, loadInspector, bootEpoch]); - // While any session is live (or mid-recovery), quiet-relist even if livePush - // is healthy — recovery windows must not catch-22 on Paused-only status. + // Degraded poll only when live push is off. livePush===true is the SSOT for + // session status — never setInterval refresh project sessions (architecture). + const livePush = useWorkspaceStore((s) => s.livePush); const hasLiveSession = sessions.some( (s) => s.status === "running" || @@ -76,12 +78,20 @@ export function SessionInspector({ ); useEffect(() => { if (source !== "daemon" || !conversationId || !detailsOpen) return; + if (livePush) return; if (!hasLiveSession) return; const id = window.setInterval(() => { void loadInspector(conversationId, { quiet: true }); }, 2000); return () => window.clearInterval(id); - }, [conversationId, detailsOpen, source, hasLiveSession, loadInspector]); + }, [ + conversationId, + detailsOpen, + source, + livePush, + hasLiveSession, + loadInspector, + ]); const conversation = conversations.find((c) => c.id === conversationId); const project = projects.find((p) => p.id === projectId); diff --git a/apps/desktop/src/features/work/WorkView.tsx b/apps/desktop/src/features/work/WorkView.tsx index 666459a0..b8544636 100644 --- a/apps/desktop/src/features/work/WorkView.tsx +++ b/apps/desktop/src/features/work/WorkView.tsx @@ -27,7 +27,6 @@ export function WorkView() { const projectId = useUiStore((s) => s.projectId); const conversationId = useUiStore((s) => s.conversationId); const selectProject = useUiStore((s) => s.selectProject); - const selectConversation = useUiStore((s) => s.selectConversation); const listCollapsed = useUiStore((s) => s.conversationListCollapsed); const lastConversationByProject = useUiStore( (s) => s.lastConversationByProject, @@ -63,7 +62,12 @@ export function WorkView() { : undefined; const listPhase = listStatus?.phase ?? "idle"; + const ensureConversationSelection = useUiStore( + (s) => s.ensureConversationSelection, + ); + // Auto-select conversation when list is ready (not while still loading/idle). + // Uses ensureConversationSelection so Sessions/Board is not forced away. useEffect(() => { if (!resolvedProjectId) return; if (listPhase === "loading" || listPhase === "idle") return; @@ -71,20 +75,20 @@ export function WorkView() { (c) => c.projectId === resolvedProjectId, ); if (list.length === 0) { - if (conversationId) selectConversation(null); + if (conversationId) ensureConversationSelection(null); return; } if (conversationId && list.some((c) => c.id === conversationId)) return; const remembered = lastConversationByProject[resolvedProjectId]; const pick = (remembered && list.find((c) => c.id === remembered)?.id) || list[0]!.id; - selectConversation(pick); + ensureConversationSelection(pick); }, [ resolvedProjectId, conversations, conversationId, lastConversationByProject, - selectConversation, + ensureConversationSelection, listPhase, ]); diff --git a/apps/desktop/src/features/work/lib/create-conversation-form.ts b/apps/desktop/src/features/work/lib/create-conversation-form.ts index 491be3be..666656bf 100644 --- a/apps/desktop/src/features/work/lib/create-conversation-form.ts +++ b/apps/desktop/src/features/work/lib/create-conversation-form.ts @@ -3,7 +3,7 @@ * Keeps form defaults / validation out of the React component. */ -import type { ConversationPriority } from "@/shared/lib/mock-data"; +import type { ConversationPriority } from "@/shared/domain/collaboration"; /** How the conversation binds to git on create. */ export type ConversationGitMode = "worktree" | "inherit"; diff --git a/apps/desktop/src/features/work/ui/CreateConversationDialog.tsx b/apps/desktop/src/features/work/ui/CreateConversationDialog.tsx index 8aaa8fed..df2d2d4a 100644 --- a/apps/desktop/src/features/work/ui/CreateConversationDialog.tsx +++ b/apps/desktop/src/features/work/ui/CreateConversationDialog.tsx @@ -23,7 +23,8 @@ import { type CreateConversationFormInput, type ProfileBriefSource, } from "@/features/work/lib/create-conversation-form"; -import { agentMeta, type AgentRuntime } from "@/shared/lib/mock-data"; +import type { AgentRuntime } from "@/shared/domain/collaboration"; +import { agentMeta } from "@/shared/lib/mock-data"; import { cn } from "@/shared/lib/utils"; import { Button } from "@/shared/ui/button"; import { diff --git a/apps/desktop/src/shared/api/hooks.ts b/apps/desktop/src/shared/api/hooks.ts index b31d4c8c..0e0d5a22 100644 --- a/apps/desktop/src/shared/api/hooks.ts +++ b/apps/desktop/src/shared/api/hooks.ts @@ -12,36 +12,6 @@ function useDaemonEnabled() { return source === "daemon"; } -export function useProjectsQuery() { - const enabled = useDaemonEnabled(); - const bootEpoch = useWorkspaceStore((s) => s.bootEpoch); - return useQuery({ - queryKey: [...queryKeys.projects, bootEpoch], - queryFn: () => daemonApi.listProjects(), - enabled, - }); -} - -export function useConversationsQuery(projectId: string) { - const enabled = useDaemonEnabled() && Boolean(projectId); - const bootEpoch = useWorkspaceStore((s) => s.bootEpoch); - return useQuery({ - queryKey: [...queryKeys.conversations(projectId), bootEpoch], - queryFn: () => daemonApi.listConversations(projectId), - enabled, - }); -} - -export function useClisQuery() { - const enabled = useDaemonEnabled(); - const bootEpoch = useWorkspaceStore((s) => s.bootEpoch); - return useQuery({ - queryKey: [...queryKeys.clis, bootEpoch], - queryFn: () => daemonApi.listClis(), - enabled, - }); -} - /** * Host daemon agent profile cache. * Offline buffer / session launch helper — **not** bot identity SSOT. @@ -90,28 +60,6 @@ export function useModelsQuery(runtime: string | null | undefined) { }); } -/** Project-scoped agent session index (Sessions tab left rail). */ -export function useProjectSessionsQuery(projectId: string) { - const enabled = useDaemonEnabled() && Boolean(projectId); - const bootEpoch = useWorkspaceStore((s) => s.bootEpoch); - return useQuery({ - queryKey: [...queryKeys.projectSessions(projectId), bootEpoch], - queryFn: () => daemonApi.listProjectSessions(projectId), - enabled, - }); -} - -/** Conversation-scoped session index (Inspector). */ -export function useInspectorSessionsQuery(conversationId: string) { - const enabled = useDaemonEnabled() && Boolean(conversationId); - const bootEpoch = useWorkspaceStore((s) => s.bootEpoch); - return useQuery({ - queryKey: [...queryKeys.inspectorSessions(conversationId), bootEpoch], - queryFn: () => daemonApi.listSessions(conversationId), - enabled, - }); -} - /** Invalidate catalog caches after mutations or reconnect. */ export function invalidateCatalogQueries(opts?: { projectId?: string; diff --git a/apps/desktop/src/shared/domain/collaboration.ts b/apps/desktop/src/shared/domain/collaboration.ts new file mode 100644 index 00000000..056ce2f3 --- /dev/null +++ b/apps/desktop/src/shared/domain/collaboration.ts @@ -0,0 +1,279 @@ +/** Desktop collaboration domain types (not fixtures). */ + +export type AgentRuntime = + | "codex" + | "claude" + | "gemini" + | "opencode" + | "grok"; + +export type SessionStatus = + | "idle" + | "running" + | "needs_approval" + | "suspended" + | "failed" + | "done"; + +export type ConversationBoardColumn = + | "backlog" + | "running" + | "needs_you" + | "done"; + +export type ConversationPriority = "high" | "medium" | "low"; + +export type ConversationProgress = + | "todo" + | "in_progress" + | "in_review" + | "done"; + +export type AvatarTone = + | "green" + | "blue" + | "pink" + | "orange" + | "purple" + | "slate" + | "amber"; + +export type Project = { + id: string; + name: string; + workspacePath: string; + conversationCount: number; + runningAgents: number; + needsAttention: number; + /** Last activity timestamp (ms) for WeChat-style list sort. */ + updatedAtMs: number; + /** True when any conversation has unread or pending approval. */ + hasUnread: boolean; + /** + * Max `updatedAtMs` among conversations that currently need attention. + * Sort uses `hasUnread` + project `updatedAtMs` only — this is diagnostic / + * aggregate metadata, not a separate sort key. + */ + lastAttentionMs: number; + /** + * Which host owns this project (plane C). + * Omit for this Mac (default). Multi-device rows set a device display name. + */ + hostName?: string; +}; + +/** Conversation bot member card (membership key = botId). */ +export type ParticipatingBot = { + botId: string; + name: string; + runtime: string; +}; + +/** Derive unique runtime labels from structured bots (host-runtime ensure / badges). */ +export function runtimesOfBots(bots: readonly ParticipatingBot[] | undefined): string[] { + const out: string[] = []; + const seen = new Set(); + for (const b of bots ?? []) { + const r = b.runtime.trim().toLowerCase(); + if (!r || seen.has(r)) continue; + seen.add(r); + out.push(r); + } + return out; +} + +/** Membership tokens for @ resolve: botId ∪ name ∪ runtime (all lowercased). */ +export function membershipTokensOfBots( + bots: readonly ParticipatingBot[] | undefined, +): string[] { + const out: string[] = []; + const seen = new Set(); + for (const b of bots ?? []) { + for (const raw of [b.botId, b.name, b.runtime]) { + const t = raw.trim().toLowerCase(); + if (!t || seen.has(t)) continue; + seen.add(t); + out.push(t); + } + } + return out; +} + +export type Conversation = { + id: string; + projectId: string; + title: string; + preview: string; + /** + * Last activity epoch ms (sort + list clock SSOT). + * Format at render with `formatListActivityTime` — never store display strings. + */ + updatedAtMs: number; + unread?: number; + /** Aggregated message count in the conversation timeline. */ + messageCount: number; + boardColumn: ConversationBoardColumn; + agentSessionCount: number; + /** + * Bot participants on the conversation roster (membership SSOT). + * Membership key is `botId`; `runtime` is launch/badge only. + */ + participatingBots: ParticipatingBot[]; + /** + * @deprecated Derived runtime labels from `participatingBots` for host-runtime + * ensure / badges. Do not use as membership SSOT. + */ + participatingAgents: string[]; + runningCount: number; + approvalCount: number; + /** Git branch for this conversation work unit. */ + branch?: string; + /** Optional linked git worktree path. */ + worktree?: string; + /** Git isolation mode: inherit | worktree. */ + gitMode?: string; + /** Cached dirty flag from last git status refresh. */ + gitDirty?: boolean; + /** Cached HEAD from last git status refresh. */ + gitHead?: string; + /** User priority tag; omit when unset. */ + priority?: ConversationPriority; + /** Workflow progress (default todo). */ + progress?: ConversationProgress; +}; + +export type TimelineMention = { + /** Runtime agent name when kind is agent (legacy workbench rows). */ + agent?: string; + sessionId?: string; + sessionShortId?: string; + /** Structured mention kind from Hub SSOT. */ + kind?: "account" | "agent"; + /** account_id or agent_id depending on kind. */ + targetId?: string; +}; + +export type DeliveryStatus = "sending" | "sent" | "failed"; + +/** Git milestone shown as a dedicated timeline card. */ +export type TimelineGitActivity = { + kind: + | "worktree_created" + | "commits_made" + | "pr_opened" + | "checks_failed" + | "ready_for_review" + | "merged"; + branch?: string; + worktreePath?: string; + baseBranch?: string; + count?: number; + subjects?: string[]; + head?: string; + url?: string; + number?: number; + title?: string; + summary?: string; + mergeCommit?: string; +}; + +/** Viewer-resolved reaction aggregate carried from Hub cold pull / live frames. */ +export type TimelineReactionActor = { + id: string; + displayName: string; +}; + +export type TimelineReactionGroup = { + emoji: string; + count: number; + reactedByMe: boolean; + actors: TimelineReactionActor[]; +}; + +export type TimelineMessage = { + id: string; + /** + * Social total-order key: Hub `message_seq` when linked, host daemon seq only + * for local-only (unlinked) workbench chat. Host tool/git cards must not use + * this field for cross-source order — use `anchorCloudMessageSeq` + `suborder`. + */ + messageSeq?: number; + /** + * Host-only cards: place after the Hub bubble with this social seq. + * Undefined = unanchored (sort after social rows, before optimistic tail). + */ + anchorCloudMessageSeq?: number; + /** Among host cards with the same anchor (or unanchored), local order. */ + suborder?: number; + /** Daemon host seq for host-only pagination (never mixed into Hub before_seq). */ + hostMessageSeq?: number; + role: "user" | "agent" | "system"; + /** Runtime family (codex/claude/…) for badges / tone; not bot identity. */ + agent?: AgentRuntime; + /** + * Hub bot display name (MessageSender::Bot) or human display name when known. + * Prefer this over runtime-keyed `agentMeta` for author labels. + */ + senderDisplayName?: string; + /** Global bot id when role=agent (MessageSender::Bot.bot_id). */ + botId?: string; + sessionId?: string; + body: string; + time: string; + createdAtMs?: number; + kind?: "text" | "tool_summary" | "approval" | "git_activity" | "system"; + replyToMessageId?: string; + delegationId?: string; + mentions?: TimelineMention[]; + gitActivity?: TimelineGitActivity; + /** + * Hub (or daemon) reaction aggregates for cold hydrate into reaction-store. + * Optional — live frames may omit until a reaction event arrives. + */ + reactions?: TimelineReactionGroup[]; + /** + * Local delivery lifecycle for user messages. + * - `sending`: optimistic bubble shown immediately, awaiting append/RPC ack. + * - `failed`: append or send pipeline threw; row stays until retry succeeds. + * - `sent`: append succeeded (durable). Omitted on durable rows loaded from + * daemon — absence is treated as `sent` by render. + */ + deliveryStatus?: DeliveryStatus; +}; + +export type AgentSession = { + id: string; + conversationId: string; + agent: AgentRuntime; + shortId: string; + status: SessionStatus; + model: string; + parentId?: string; + summary: string; + lastTool?: string; + /** Host should auto-continue after process-death recovery. */ + needsContinue?: boolean; +}; + +export type HostStatus = { + relay: "connected" | "disconnected"; + daemonVersion: string; + pairedDevices: number; +}; + +export type InstalledRuntime = { + agent: AgentRuntime; + installed: boolean; + path?: string; + version?: string; +}; + +/** Session list row: AgentSession plus host list metadata. */ +export type ProjectSession = AgentSession & { + conversationTitle?: string; + firstTsMs?: number; + lastTsMs?: number; + /** Session last_seq — used to seek transcript tail. */ + messageCount?: number; +}; + diff --git a/apps/desktop/src/shared/domain/index.ts b/apps/desktop/src/shared/domain/index.ts new file mode 100644 index 00000000..bae0beaf --- /dev/null +++ b/apps/desktop/src/shared/domain/index.ts @@ -0,0 +1 @@ +export * from "./collaboration"; diff --git a/apps/desktop/src/shared/lib/account-scope-generation.test.ts b/apps/desktop/src/shared/lib/account-scope-generation.test.ts new file mode 100644 index 00000000..33335c34 --- /dev/null +++ b/apps/desktop/src/shared/lib/account-scope-generation.test.ts @@ -0,0 +1,22 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { + bumpAccountScopeGeneration, + getAccountScopeGeneration, +} from "./account-scope-generation.ts"; + +describe("account scope generation", () => { + it("bump advances generation for stale async detection", () => { + const before = getAccountScopeGeneration(); + const next = bumpAccountScopeGeneration(); + assert.equal(next, before + 1); + assert.equal(getAccountScopeGeneration(), next); + assert.notEqual(getAccountScopeGeneration(), before); + }); + + it("captured gen becomes stale after leave bump", () => { + const captured = getAccountScopeGeneration(); + bumpAccountScopeGeneration(); + assert.notEqual(captured, getAccountScopeGeneration()); + }); +}); diff --git a/apps/desktop/src/shared/lib/account-scope-generation.ts b/apps/desktop/src/shared/lib/account-scope-generation.ts new file mode 100644 index 00000000..647a472a --- /dev/null +++ b/apps/desktop/src/shared/lib/account-scope-generation.ts @@ -0,0 +1,15 @@ +/** + * Process-local generation for account-scoped async writers. + * Bumped on leave/switch so mid-flight work can no-op at setState time. + */ + +let accountScopeGeneration = 0; + +export function getAccountScopeGeneration(): number { + return accountScopeGeneration; +} + +export function bumpAccountScopeGeneration(): number { + accountScopeGeneration += 1; + return accountScopeGeneration; +} diff --git a/apps/desktop/src/shared/lib/cloud-auth.ts b/apps/desktop/src/shared/lib/cloud-auth.ts new file mode 100644 index 00000000..3a9c5ddf --- /dev/null +++ b/apps/desktop/src/shared/lib/cloud-auth.ts @@ -0,0 +1,42 @@ +/** + * Process-local cloud auth snapshot for Hub transport. + * + * Registered once from account-store so pure shared/lib transport helpers + * never import Zustand stores. Ownership of the session remains account-store. + */ + +export type CloudAuthSnapshot = { + deviceId: string; + accessToken: string; + accountId: string; + authPhase: string; +}; + +type CloudAuthProvider = () => CloudAuthSnapshot | null; + +let provider: CloudAuthProvider | null = null; + +/** Wire account-store (or tests) as the sole auth source for shared transport. */ +export function registerCloudAuthProvider(next: CloudAuthProvider): void { + provider = next; +} + +/** Current Hub credentials, or null when signed out / incomplete. */ +export function getCloudAuth(): CloudAuthSnapshot | null { + if (!provider) return null; + try { + return provider(); + } catch { + return null; + } +} + +/** True when authenticated with a usable access token (Hub IM mode gate). */ +export function isCloudAuthReady(): boolean { + const auth = getCloudAuth(); + return Boolean( + auth?.accessToken?.trim() && + auth.accountId.trim() && + auth.authPhase === "authenticated", + ); +} diff --git a/apps/desktop/src/shared/lib/cloud-cursors.test.ts b/apps/desktop/src/shared/lib/cloud-cursors.test.ts index 4ba873b0..65795be3 100644 --- a/apps/desktop/src/shared/lib/cloud-cursors.test.ts +++ b/apps/desktop/src/shared/lib/cloud-cursors.test.ts @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { describe, it } from "node:test"; import { advanceTopicCursor, + clearAllTopicCursors, clearTopicCursor, conversationTopic, accountTopic, @@ -98,3 +99,22 @@ describe("topic helpers + storage", () => { ); }); }); + +describe("clearAllTopicCursors", () => { + it("wipes storage for account leave", () => { + const store = new Map(); + const storage = { + getItem: (k: string) => store.get(k) ?? null, + setItem: (k: string, v: string) => { + store.set(k, v); + }, + removeItem: (k: string) => { + store.delete(k); + }, + }; + saveTopicCursors({ "account:a": 1, "conversation:c": 2 }, storage); + assert.equal(loadTopicCursors(storage)["account:a"], 1); + clearAllTopicCursors(storage); + assert.deepEqual(loadTopicCursors(storage), {}); + }); +}); diff --git a/apps/desktop/src/shared/lib/cloud-cursors.ts b/apps/desktop/src/shared/lib/cloud-cursors.ts index 2f06127f..efe2e7a3 100644 --- a/apps/desktop/src/shared/lib/cloud-cursors.ts +++ b/apps/desktop/src/shared/lib/cloud-cursors.ts @@ -138,6 +138,26 @@ export function saveTopicCursors( } } +/** Drop all Hub topic cursors (account leave — never resume under another account). */ +export function clearAllTopicCursors( + storage: + | (Pick & Partial>) + | null + | undefined = defaultStorage(), +): void { + if (!storage) return; + try { + storage.removeItem?.(CLOUD_CURSOR_STORAGE_KEY); + storage.removeItem?.(LEGACY_CLOUD_CURSOR_STORAGE_KEY); + } catch { + try { + storage.setItem?.(CLOUD_CURSOR_STORAGE_KEY, "{}"); + } catch { + /* quota / private mode */ + } + } +} + function defaultStorage(): Storage | null { try { if (typeof localStorage === "undefined") return null; diff --git a/apps/desktop/src/shared/lib/cloud-digest-cache.test.ts b/apps/desktop/src/shared/lib/cloud-digest-cache.test.ts index 3185fe25..a8afb3f3 100644 --- a/apps/desktop/src/shared/lib/cloud-digest-cache.test.ts +++ b/apps/desktop/src/shared/lib/cloud-digest-cache.test.ts @@ -43,6 +43,28 @@ describe("cloudDigestCache", () => { assert.equal(row?.title, "One"); }); + it("isHydratedFor requires matching owner account", () => { + cloudDigestCache.hydrate( + [ + { + conversationId: "c1", + title: "One", + preview: null, + lastMessageAtMs: 1, + unreadCount: 0, + unreadMentionCount: 0, + kind: "group", + memberCount: 1, + }, + ], + "acct-a", + ); + assert.equal(cloudDigestCache.isHydratedFor("acct-a"), true); + assert.equal(cloudDigestCache.isHydratedFor("acct-b"), false); + cloudDigestCache.invalidate(); + assert.equal(cloudDigestCache.isHydratedFor("acct-a"), false); + }); + it("invalidate clears hydrate flag", () => { cloudDigestCache.hydrate([ { diff --git a/apps/desktop/src/shared/lib/cloud-digest-cache.ts b/apps/desktop/src/shared/lib/cloud-digest-cache.ts index a90c442e..a65132ed 100644 --- a/apps/desktop/src/shared/lib/cloud-digest-cache.ts +++ b/apps/desktop/src/shared/lib/cloud-digest-cache.ts @@ -38,16 +38,22 @@ type DigestDelta = Partial< let digestsById: Map = new Map(); let hydrated = false; +/** Account that owns the current hydrate; mismatch ⇒ treat as cold. */ +let ownerAccountId: string | null = null; export const cloudDigestCache = { /** Sole HTTP fill path. Replaces all digests. */ - hydrate(digests: readonly CloudConversationDigest[]): void { + hydrate( + digests: readonly CloudConversationDigest[], + accountId?: string | null, + ): void { digestsById = new Map( digests .filter((d) => d.conversationId.trim()) .map((d) => [d.conversationId, { ...d }]), ); hydrated = true; + ownerAccountId = accountId?.trim() || null; }, /** Live Account* / mark-read writer after hydrate. */ @@ -90,12 +96,23 @@ export const cloudDigestCache = { invalidate(): void { digestsById = new Map(); hydrated = false; + ownerAccountId = null; }, isHydrated(): boolean { return hydrated; }, + /** True only when cache is warm for this account. */ + isHydratedFor(accountId: string): boolean { + const id = accountId.trim(); + return hydrated && !!id && ownerAccountId === id; + }, + + ownerAccountId(): string | null { + return ownerAccountId; + }, + get(conversationId: string): CloudConversationDigest | undefined { return digestsById.get(conversationId); }, @@ -108,5 +125,6 @@ export const cloudDigestCache = { _resetForTests(): void { digestsById = new Map(); hydrated = false; + ownerAccountId = null; }, }; diff --git a/apps/desktop/src/shared/lib/cloud-digest-ensure.ts b/apps/desktop/src/shared/lib/cloud-digest-ensure.ts deleted file mode 100644 index 41915c4a..00000000 --- a/apps/desktop/src/shared/lib/cloud-digest-ensure.ts +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Single-flight ensure for CloudDigestCache hydrate. - */ - -import { cloudDigestCache } from "@/shared/lib/cloud-digest-cache"; -import { listCloudConversations } from "@/shared/lib/minos-cloud"; -import { useAccountStore } from "@/store/account-store"; -import { isCloudImMode } from "@/shared/lib/cloud-timeline"; - -let hydrateInFlight: Promise | null = null; - -/** Hydrate CloudDigestCache once (or after invalidate). Concurrent callers share one request. */ -export async function ensureCloudDigestHydrated( - opts?: { force?: boolean }, -): Promise { - const { deviceId, session, authPhase } = useAccountStore.getState(); - if ( - !isCloudImMode({ - authPhase, - accessToken: session?.accessToken, - }) || - !session?.accessToken - ) { - return; - } - - if (!opts?.force && cloudDigestCache.isHydrated()) { - return; - } - - // Force after concurrent hydrate: wait then re-query so SnapshotRequired - // never leaves a stale cache behind a no-op await. - if (hydrateInFlight) { - await hydrateInFlight; - if (!opts?.force) { - return; - } - } - - if (!opts?.force && cloudDigestCache.isHydrated()) { - return; - } - - hydrateInFlight = (async () => { - try { - if (opts?.force) { - cloudDigestCache.invalidate(); - } - const digests = await listCloudConversations( - deviceId, - session.accessToken, - ); - cloudDigestCache.hydrate(digests); - } finally { - hydrateInFlight = null; - } - })(); - - await hydrateInFlight; -} diff --git a/apps/desktop/src/shared/lib/cloud-realtime-map.ts b/apps/desktop/src/shared/lib/cloud-realtime-map.ts new file mode 100644 index 00000000..a680a810 --- /dev/null +++ b/apps/desktop/src/shared/lib/cloud-realtime-map.ts @@ -0,0 +1,161 @@ +/** + * Pure durable-frame mappers for Account `/ws/client` realtime. + * Kept free of WebSocket session lifecycle (size / test isolation). + */ + +import type { CloudChatMessage } from "@/shared/lib/minos-cloud"; + +export type DurableMessagePayload = { + kind?: string; + account_id?: string; + conversation_id?: string; + message_id?: string; + at_ms?: number; + /** Account thin digest fields (no nested full message). */ + preview?: string; + sender_display_name?: string; + mentioned?: boolean; + message_seq?: number; + sender?: { + kind?: string; + account_id?: string; + agent_id?: string; + }; + message?: { + message_id: string; + conversation_id: string; + text: string; + created_at_ms: number; + message_seq?: number; + sender_type?: string; + sender: { + kind?: string; + account_id?: string; + minos_id?: string; + display_name?: string; + bot_id?: string; + runtime_agent?: string; + name?: string | null; + }; + reply_to?: { message_id: string } | null; + recalled_at_ms?: number | null; + mentioned_account_ids?: string[] | null; + mentioned_agent_ids?: string[] | null; + }; +}; + +/** Account-topic T2 digest for rail/inbox only (R3). */ +export type CloudInboxDigest = { + conversationId: string; + messageId: string; + preview: string; + atMs: number; + senderAccountId: string; + senderDisplayName: string; + mentioned: boolean; + messageSeq?: number; + isRecall: boolean; +}; + +export function mapMessage( + raw: NonNullable, +): CloudChatMessage { + const s = raw.sender; + const isBot = + s.kind === "bot" || + raw.sender_type === "agent" || + Boolean(s.bot_id && !s.account_id); + const botId = (s.bot_id ?? s.account_id ?? "").trim(); + const accountId = (s.account_id ?? "").trim(); + return { + messageId: raw.message_id, + conversationId: raw.conversation_id, + text: raw.text, + createdAtMs: raw.created_at_ms, + messageSeq: raw.message_seq, + senderType: isBot ? "agent" : "user", + // For bots, identity is bot_id (stored in senderAccountId field for less UI churn). + senderAccountId: isBot ? botId : accountId, + senderMinosId: isBot + ? (s.name?.trim() || botId) + : (s.minos_id ?? "").trim(), + senderDisplayName: (s.display_name ?? "").trim(), + runtimeAgent: isBot + ? (s.runtime_agent?.trim() || undefined) + : undefined, + replyToMessageId: raw.reply_to?.message_id ?? null, + recalledAtMs: raw.recalled_at_ms ?? null, + mentionedAccountIds: Array.isArray(raw.mentioned_account_ids) + ? raw.mentioned_account_ids.filter( + (id): id is string => typeof id === "string" && id.length > 0, + ) + : undefined, + mentionedAgentIds: Array.isArray(raw.mentioned_agent_ids) + ? raw.mentioned_agent_ids.filter( + (id): id is string => typeof id === "string" && id.length > 0, + ) + : undefined, + }; +} + +/** Conversation topic T1 full message (open chat). */ +export const CONVERSATION_APPEND_KINDS = new Set([ + "conversation_message_appended", + "ConversationMessageAppended", +]); + +export const CONVERSATION_RECALL_KINDS = new Set([ + "conversation_message_recalled", + "ConversationMessageRecalled", +]); + +/** Account topic T2 thin digest (inbox/rail only). */ +export const ACCOUNT_APPEND_KINDS = new Set([ + "account_conversation_message_appended", + "AccountConversationMessageAppended", +]); + +export const ACCOUNT_RECALL_KINDS = new Set([ + "account_conversation_message_recalled", + "AccountConversationMessageRecalled", +]); + +export const REACTION_KINDS = new Set([ + "conversation_message_reaction_updated", + "ConversationMessageReactionUpdated", +]); + +export function mapAccountDigest( + payload: DurableMessagePayload, + isRecall: boolean, +): CloudInboxDigest | null { + const conversationId = payload.conversation_id?.trim(); + const messageId = payload.message_id?.trim(); + if (!conversationId || !messageId) return null; + const sender = payload.sender; + const senderAccountId = + sender?.account_id?.trim() || sender?.agent_id?.trim() || ""; + const preview = isRecall + ? (payload.preview?.trim() || "Message recalled") + : (payload.preview?.trim() ?? ""); + // 0 = omit activity bump (never invent client Date.now()). + const atMs = + typeof payload.at_ms === "number" && + Number.isFinite(payload.at_ms) && + payload.at_ms > 0 + ? payload.at_ms + : 0; + return { + conversationId, + messageId, + preview, + atMs, + senderAccountId, + senderDisplayName: payload.sender_display_name?.trim() || "", + mentioned: Boolean(payload.mentioned), + messageSeq: + typeof payload.message_seq === "number" ? payload.message_seq : undefined, + isRecall, + }; +} + diff --git a/apps/desktop/src/shared/lib/cloud-realtime.test.ts b/apps/desktop/src/shared/lib/cloud-realtime.test.ts index d4de11a4..ac651e4a 100644 --- a/apps/desktop/src/shared/lib/cloud-realtime.test.ts +++ b/apps/desktop/src/shared/lib/cloud-realtime.test.ts @@ -51,6 +51,43 @@ describe("cloud-realtime account thin digest (R3)", () => { }); }); +describe("cloud-realtime connection epoch", () => { + it("stale epoch must not clear current socket state", () => { + // Mirrors CloudRealtimeSession connect/onclose guards: + // only the live epoch may null this.ws and schedule reconnect. + type Sock = { id: number }; + let connectionEpoch = 0; + let current: Sock | null = null; + let reconnectScheduled = 0; + + const connect = (): { sock: Sock; onClose: () => void } => { + const epoch = ++connectionEpoch; + const sock: Sock = { id: epoch }; + current = sock; + return { + sock, + onClose: () => { + // Stale epoch or superseded socket must no-op. + if (epoch !== connectionEpoch || current !== sock) return; + current = null; + reconnectScheduled += 1; + }, + }; + }; + + const first = connect(); + const second = connect(); + // Out-of-order: first ticket's close after second owns the socket. + first.onClose(); + assert.equal(current, second.sock); + assert.equal(second.sock.id, 2); + assert.equal(reconnectScheduled, 0); + second.onClose(); + assert.equal(current, null); + assert.equal(reconnectScheduled, 1); + }); +}); + describe("cloud-realtime conversation subscription LRU (R4)", () => { it("evicts oldest when over cap", async () => { const { diff --git a/apps/desktop/src/shared/lib/cloud-realtime.ts b/apps/desktop/src/shared/lib/cloud-realtime.ts index ae42c085..99aba504 100644 --- a/apps/desktop/src/shared/lib/cloud-realtime.ts +++ b/apps/desktop/src/shared/lib/cloud-realtime.ts @@ -24,6 +24,21 @@ import { type CloudChatMessage, } from "@/shared/lib/minos-cloud"; +import { + mapAccountDigest, + mapMessage, + ACCOUNT_APPEND_KINDS, + ACCOUNT_RECALL_KINDS, + CONVERSATION_APPEND_KINDS, + CONVERSATION_RECALL_KINDS, + REACTION_KINDS, + type CloudInboxDigest, + type DurableMessagePayload, +} from "@/shared/lib/cloud-realtime-map"; + +export type { CloudInboxDigest } from "@/shared/lib/cloud-realtime-map"; + + export { MAX_OPEN_CONVERSATION_SUBSCRIPTIONS, conversationSubscriptionLruTouch, @@ -51,58 +66,6 @@ export type AppendMessageWsResult = message?: string; }; -type DurableMessagePayload = { - kind?: string; - account_id?: string; - conversation_id?: string; - message_id?: string; - at_ms?: number; - /** Account thin digest fields (no nested full message). */ - preview?: string; - sender_display_name?: string; - mentioned?: boolean; - message_seq?: number; - sender?: { - kind?: string; - account_id?: string; - agent_id?: string; - }; - message?: { - message_id: string; - conversation_id: string; - text: string; - created_at_ms: number; - message_seq?: number; - sender_type?: string; - sender: { - kind?: string; - account_id?: string; - minos_id?: string; - display_name?: string; - bot_id?: string; - runtime_agent?: string; - name?: string | null; - }; - reply_to?: { message_id: string } | null; - recalled_at_ms?: number | null; - mentioned_account_ids?: string[] | null; - mentioned_agent_ids?: string[] | null; - }; -}; - -/** Account-topic T2 digest for rail/inbox only (R3). */ -export type CloudInboxDigest = { - conversationId: string; - messageId: string; - preview: string; - atMs: number; - senderAccountId: string; - senderDisplayName: string; - mentioned: boolean; - messageSeq?: number; - isRecall: boolean; -}; - export type CloudRealtimeHandlers = { onChatMessage: (message: CloudChatMessage) => void; /** Multi-end recall: remove or mark recalled in Hub timeline. */ @@ -165,111 +128,11 @@ export type CloudRealtimeHandlers = { }) => void; }; -function mapMessage( - raw: NonNullable, -): CloudChatMessage { - const s = raw.sender; - const isBot = - s.kind === "bot" || - raw.sender_type === "agent" || - Boolean(s.bot_id && !s.account_id); - const botId = (s.bot_id ?? s.account_id ?? "").trim(); - const accountId = (s.account_id ?? "").trim(); - return { - messageId: raw.message_id, - conversationId: raw.conversation_id, - text: raw.text, - createdAtMs: raw.created_at_ms, - messageSeq: raw.message_seq, - senderType: isBot ? "agent" : "user", - // For bots, identity is bot_id (stored in senderAccountId field for less UI churn). - senderAccountId: isBot ? botId : accountId, - senderMinosId: isBot - ? (s.name?.trim() || botId) - : (s.minos_id ?? "").trim(), - senderDisplayName: (s.display_name ?? "").trim(), - runtimeAgent: isBot - ? (s.runtime_agent?.trim() || undefined) - : undefined, - replyToMessageId: raw.reply_to?.message_id ?? null, - recalledAtMs: raw.recalled_at_ms ?? null, - mentionedAccountIds: Array.isArray(raw.mentioned_account_ids) - ? raw.mentioned_account_ids.filter( - (id): id is string => typeof id === "string" && id.length > 0, - ) - : undefined, - mentionedAgentIds: Array.isArray(raw.mentioned_agent_ids) - ? raw.mentioned_agent_ids.filter( - (id): id is string => typeof id === "string" && id.length > 0, - ) - : undefined, - }; -} - -/** Conversation topic T1 full message (open chat). */ -const CONVERSATION_APPEND_KINDS = new Set([ - "conversation_message_appended", - "ConversationMessageAppended", -]); - -const CONVERSATION_RECALL_KINDS = new Set([ - "conversation_message_recalled", - "ConversationMessageRecalled", -]); - -/** Account topic T2 thin digest (inbox/rail only). */ -const ACCOUNT_APPEND_KINDS = new Set([ - "account_conversation_message_appended", - "AccountConversationMessageAppended", -]); - -const ACCOUNT_RECALL_KINDS = new Set([ - "account_conversation_message_recalled", - "AccountConversationMessageRecalled", -]); - -const REACTION_KINDS = new Set([ - "conversation_message_reaction_updated", - "ConversationMessageReactionUpdated", -]); - -function mapAccountDigest( - payload: DurableMessagePayload, - isRecall: boolean, -): CloudInboxDigest | null { - const conversationId = payload.conversation_id?.trim(); - const messageId = payload.message_id?.trim(); - if (!conversationId || !messageId) return null; - const sender = payload.sender; - const senderAccountId = - sender?.account_id?.trim() || sender?.agent_id?.trim() || ""; - const preview = isRecall - ? (payload.preview?.trim() || "Message recalled") - : (payload.preview?.trim() ?? ""); - // 0 = omit activity bump (never invent client Date.now()). - const atMs = - typeof payload.at_ms === "number" && - Number.isFinite(payload.at_ms) && - payload.at_ms > 0 - ? payload.at_ms - : 0; - return { - conversationId, - messageId, - preview, - atMs, - senderAccountId, - senderDisplayName: payload.sender_display_name?.trim() || "", - mentioned: Boolean(payload.mentioned), - messageSeq: - typeof payload.message_seq === "number" ? payload.message_seq : undefined, - isRecall, - }; -} - export class CloudRealtimeSession { private ws: WebSocket | null = null; private stopped = false; + /** Bumped on each start/force/stop/connect so stale ticket callbacks cannot own state. */ + private connectionEpoch = 0; private reconnectTimer: ReturnType | null = null; private reconnectAttempt = 0; private pingTimer: ReturnType | null = null; @@ -445,6 +308,7 @@ export class CloudRealtimeSession { start(deviceId: string, accessToken: string, accountId?: string): void { this.stopped = false; + this.connectionEpoch += 1; this.auth = { deviceId, accessToken, @@ -471,6 +335,7 @@ export class CloudRealtimeSession { this.clearTimers(); this.reconnectAttempt = 0; this.pendingSubscribeTopics.clear(); + this.connectionEpoch += 1; if (this.ws) { try { // Detach onclose so we do not schedule the backoff path. @@ -505,11 +370,15 @@ export class CloudRealtimeSession { stop(): void { this.stopped = true; + this.connectionEpoch += 1; this.clearTimers(); this.conversationIds.clear(); this.pendingSubscribeTopics.clear(); if (this.ws) { try { + this.ws.onclose = null; + this.ws.onerror = null; + this.ws.onmessage = null; this.ws.close(); } catch { /* ignore */ @@ -652,32 +521,66 @@ export class CloudRealtimeSession { private async connect(): Promise { if (this.stopped || !this.auth) 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. + if (this.ws) { + try { + this.ws.onclose = null; + this.ws.onerror = null; + this.ws.onmessage = null; + this.ws.close(); + } catch { + /* ignore */ + } + this.ws = null; + } this.setState("connecting"); try { - const ticket = await createWsTicket( - this.auth.deviceId, - this.auth.accessToken, - ); - if (this.stopped) return; + const auth = this.auth; + const ticket = await createWsTicket(auth.deviceId, auth.accessToken); + if (this.stopped || epoch !== this.connectionEpoch) return; const url = cloudClientWsUrl(ticket.gatewayUrl, ticket.ticket); const ws = new WebSocket(url); + if (this.stopped || epoch !== this.connectionEpoch) { + try { + ws.close(); + } catch { + /* ignore */ + } + return; + } this.ws = ws; ws.onopen = () => { + if (epoch !== this.connectionEpoch || this.ws !== ws) { + try { + ws.close(); + } catch { + /* ignore */ + } + return; + } this.reconnectAttempt = 0; // Wait for Hello before Subscribe; account is auto-subscribed by gateway. this.ensurePingTimer(); }; ws.onmessage = (ev) => { + if (epoch !== this.connectionEpoch || this.ws !== ws) return; this.handleRaw(String(ev.data ?? "")); }; ws.onerror = () => { + if (epoch !== this.connectionEpoch || this.ws !== ws) return; this.setState("error"); }; ws.onclose = () => { + if (epoch !== this.connectionEpoch || this.ws !== ws) { + // Stale socket — do not clear current connection or schedule reconnect. + return; + } this.ws = null; this.clearTimers(); this.pendingSubscribeTopics.clear(); @@ -685,6 +588,7 @@ export class CloudRealtimeSession { this.scheduleReconnect(); }; } catch (error) { + if (this.stopped || epoch !== this.connectionEpoch) return; console.warn("[cloud-realtime] connect failed", error); this.setState("error"); this.scheduleReconnect(); diff --git a/apps/desktop/src/shared/lib/cloud-timeline.test.ts b/apps/desktop/src/shared/lib/cloud-timeline.test.ts index eba95af5..71aa18e0 100644 --- a/apps/desktop/src/shared/lib/cloud-timeline.test.ts +++ b/apps/desktop/src/shared/lib/cloud-timeline.test.ts @@ -8,7 +8,7 @@ import { sessionIdFromAgentResultId, upsertCloudMessageIntoTimeline, } from "./cloud-timeline.ts"; -import type { TimelineMessage } from "./mock-data.ts"; +import type { TimelineMessage } from "../domain/collaboration.ts"; import type { CloudChatMessage } from "./minos-cloud.ts"; function local( diff --git a/apps/desktop/src/shared/lib/cloud-timeline.ts b/apps/desktop/src/shared/lib/cloud-timeline.ts index faea51d8..50c8f7a9 100644 --- a/apps/desktop/src/shared/lib/cloud-timeline.ts +++ b/apps/desktop/src/shared/lib/cloud-timeline.ts @@ -10,7 +10,7 @@ * fuzzy `*:sessionId` keys. */ -import type { AgentRuntime, TimelineMessage } from "./mock-data.ts"; +import type { AgentRuntime, TimelineMessage } from "../domain/collaboration.ts"; import type { CloudChatMessage } from "./minos-cloud.ts"; import { formatLocalClock } from "./time.ts"; import { normalizeHostRuntime } from "./im-cloud-sync-helpers.ts"; diff --git a/apps/desktop/src/shared/lib/conversation-list-merge.ts b/apps/desktop/src/shared/lib/conversation-list-merge.ts index 2454a6a0..8f91f73f 100644 --- a/apps/desktop/src/shared/lib/conversation-list-merge.ts +++ b/apps/desktop/src/shared/lib/conversation-list-merge.ts @@ -18,8 +18,8 @@ * - Display strings are **not** stored; UI formats `updatedAtMs` at render. */ -import type { Conversation } from "./mock-data.ts"; -import { runtimesOfBots } from "./mock-data.ts"; +import type { Conversation } from "../domain/collaboration.ts"; +import { runtimesOfBots } from "../domain/collaboration.ts"; import type { CloudConversationDigest } from "./cloud-digest-cache.ts"; import { positiveMs } from "./rail-activity.ts"; diff --git a/apps/desktop/src/shared/lib/conversation-meta.ts b/apps/desktop/src/shared/lib/conversation-meta.ts index 5fb007f9..df9c3af6 100644 --- a/apps/desktop/src/shared/lib/conversation-meta.ts +++ b/apps/desktop/src/shared/lib/conversation-meta.ts @@ -4,7 +4,7 @@ import type { ConversationBoardColumn, ConversationPriority, ConversationProgress, -} from "@/shared/lib/mock-data"; +} from "../domain/collaboration.ts"; export const PRIORITY_CYCLE: Array = [ null, diff --git a/apps/desktop/src/shared/lib/daemon.ts b/apps/desktop/src/shared/lib/daemon.ts index ddf2a2b4..215ba644 100644 --- a/apps/desktop/src/shared/lib/daemon.ts +++ b/apps/desktop/src/shared/lib/daemon.ts @@ -314,6 +314,9 @@ export const daemonApi = { call<{ linked: boolean }>("daemon_host_apply_link_token", { hostInstallationToken, }), + /** Drop local hit_ so account leave cannot inherit previous host dial. */ + hostClearCredential: () => + call<{ cleared: boolean }>("daemon_host_clear_credential"), createConversation: ( projectId: string, title: string, diff --git a/apps/desktop/src/shared/lib/im-outbox.test.ts b/apps/desktop/src/shared/lib/im-outbox.test.ts index ad512bde..ee0ae3ba 100644 --- a/apps/desktop/src/shared/lib/im-outbox.test.ts +++ b/apps/desktop/src/shared/lib/im-outbox.test.ts @@ -15,6 +15,7 @@ import { markAcked, markFailed, markInflight, + MAX_OUTBOX_ENTRIES, outboxLaneKey, reclaimStaleInflight, resetImOutboxForTests, @@ -22,30 +23,66 @@ import { STALE_INFLIGHT_MS, } from "./im-outbox.ts"; +const TEST_ACCOUNT = "acct-test"; + describe("im-outbox", () => { beforeEach(async () => { enableMemoryOutboxForTests(); await resetImOutboxForTests(); }); + it("capacity failure leaves no memory or drainable row", async () => { + for (let i = 0; i < MAX_OUTBOX_ENTRIES; i++) { + await enqueueUserMessage({ + accountId: TEST_ACCOUNT, + conversationId: "c-cap", + clientMessageId: `cap-${i}`, + text: "x", + }); + } + await assert.rejects( + () => + enqueueUserMessage({ + accountId: TEST_ACCOUNT, + conversationId: "c-cap", + clientMessageId: "cap-overflow", + text: "overflow", + }), + /im_outbox_capacity/, + ); + const snap = await getOutboxSnapshotForTests(); + assert.equal(snap.length, MAX_OUTBOX_ENTRIES); + assert.equal( + snap.some((e) => e.clientMessageId === "cap-overflow"), + false, + ); + const due = await listDuePending(undefined, TEST_ACCOUNT); + assert.equal( + due.some((e) => e.clientMessageId === "cap-overflow"), + false, + ); + }); + it("enqueues pending user messages and acks prevent re-project", async () => { await enqueueUserMessage({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "m1", text: "hello", }); assert.equal(await isAcked("m1"), false); - const due = await listDuePending(); + const due = await listDuePending(undefined, TEST_ACCOUNT); assert.equal(due.length, 1); assert.equal(due[0]!.clientMessageId, "m1"); await markInflight("m1"); await markAcked("m1"); assert.equal(await isAcked("m1"), true); - assert.equal((await listDuePending()).length, 0); + assert.equal((await listDuePending(undefined, TEST_ACCOUNT)).length, 0); // Re-enqueue after ack is a no-op for status const again = await enqueueUserMessage({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "m1", text: "hello", @@ -64,13 +101,14 @@ describe("im-outbox", () => { }, ]; const entry = await enqueueUserMessage({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "m-mentions", text: "@codex @alice hi", mentions, }); assert.deepEqual(entry.mentions, mentions); - const due = await listDuePending(); + const due = await listDuePending(undefined, TEST_ACCOUNT); const row = due.find((e) => e.clientMessageId === "m-mentions"); assert.ok(row); assert.deepEqual(row!.mentions, mentions); @@ -78,6 +116,7 @@ describe("im-outbox", () => { it("network errors stay pending after many attempts (no terminal burn)", async () => { await enqueueUserMessage({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "m2", text: "x", @@ -96,6 +135,7 @@ describe("im-outbox", () => { it("permanent client errors terminal after enough attempts", async () => { await enqueueUserMessage({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "m-perm", text: "x", @@ -109,7 +149,7 @@ describe("im-outbox", () => { ); assert.ok(row); assert.equal(row!.status, "failed_terminal"); - assert.equal((await listDuePending()).length, 0); + assert.equal((await listDuePending(undefined, TEST_ACCOUNT)).length, 0); }); it("classifyOutboxFailure separates transient vs permanent", async () => { @@ -124,6 +164,7 @@ describe("im-outbox", () => { it("reclaims stale inflight so kill mid-flight becomes due again", async () => { await enqueueUserMessage({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "m-stale", text: "in flight", @@ -134,7 +175,7 @@ describe("im-outbox", () => { assert.equal(row!.status, "inflight"); // Fresh inflight is not due - assert.equal((await listDuePending()).length, 0); + assert.equal((await listDuePending(undefined, TEST_ACCOUNT)).length, 0); // Simulate process kill: updatedAt far in the past const old = Date.now() - STALE_INFLIGHT_MS - 1_000; @@ -146,19 +187,46 @@ describe("im-outbox", () => { (e) => e.clientMessageId === "m-stale", ); assert.equal(after!.status, "pending"); - assert.equal((await listDuePending()).length, 1); - assert.equal((await listDuePending())[0]!.clientMessageId, "m-stale"); + assert.equal((await listDuePending(undefined, TEST_ACCOUNT)).length, 1); + assert.equal((await listDuePending(undefined, TEST_ACCOUNT))[0]!.clientMessageId, "m-stale"); + }); + + it("reclaimStaleInflight scopes by accountId when provided", async () => { + await enqueueUserMessage({ + accountId: "acct-a", + conversationId: "c1", + clientMessageId: "m-a", + text: "a", + }); + await enqueueUserMessage({ + accountId: "acct-b", + conversationId: "c1", + clientMessageId: "m-b", + text: "b", + }); + await markInflight("m-a"); + await markInflight("m-b"); + const old = Date.now() - STALE_INFLIGHT_MS - 1_000; + await forceUpdatedAtForTests("m-a", old); + await forceUpdatedAtForTests("m-b", old); + + const reclaimed = await reclaimStaleInflight(Date.now(), "acct-a"); + assert.equal(reclaimed, 1); + const snap = await getOutboxSnapshotForTests(); + assert.equal(snap.find((e) => e.clientMessageId === "m-a")!.status, "pending"); + assert.equal(snap.find((e) => e.clientMessageId === "m-b")!.status, "inflight"); }); it("listDuePending includes reclaim of stale inflight inline", async () => { await enqueueUserMessage({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "m-inline", text: "x", }); await markInflight("m-inline"); await forceUpdatedAtForTests("m-inline", Date.now() - STALE_INFLIGHT_MS - 5_000); - const due = await listDuePending(); + const due = await listDuePending(undefined, TEST_ACCOUNT); assert.equal(due.length, 1); assert.equal(due[0]!.clientMessageId, "m-inline"); assert.equal(due[0]!.status, "pending"); @@ -166,6 +234,7 @@ describe("im-outbox", () => { it("enqueues agent_result kind into the same status machine", async () => { const entry = await enqueueAgentResult({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "agent-result:c1:s1:origin1", text: "done", @@ -175,22 +244,23 @@ describe("im-outbox", () => { assert.equal(entry.kind, "agent_result"); assert.equal(entry.status, "pending"); assert.equal(entry.messageSource, "host_projection"); - assert.equal((await listDuePending()).length, 1); - assert.equal((await listDuePending())[0]!.kind, "agent_result"); + assert.equal((await listDuePending(undefined, TEST_ACCOUNT)).length, 1); + assert.equal((await listDuePending(undefined, TEST_ACCOUNT))[0]!.kind, "agent_result"); await markInflight(entry.clientMessageId); await markAcked(entry.clientMessageId); assert.equal(await isAcked(entry.clientMessageId), true); - assert.equal((await listDuePending()).length, 0); + assert.equal((await listDuePending(undefined, TEST_ACCOUNT)).length, 0); }); it("includes reaction_toggle in due queue", async () => { await enqueueReactionToggle({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "react-1", text: JSON.stringify({ messageId: "m1", emoji: "👍" }), }); - const due = await listDuePending(); + const due = await listDuePending(undefined, TEST_ACCOUNT); assert.equal(due.length, 1); assert.equal(due[0]!.kind, "reaction_toggle"); assert.equal(due[0]!.clientMessageId, "react-1"); @@ -200,6 +270,7 @@ describe("im-outbox", () => { it("earliestPendingAttemptAt tracks backoff beyond 60s", async () => { const entry = await enqueueUserMessage({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "late-1", text: "hi", @@ -212,13 +283,14 @@ describe("im-outbox", () => { await markInflight(entry.clientMessageId); } await markFailed(entry.clientMessageId, "network error"); - const next = await earliestPendingAttemptAt(); + const next = await earliestPendingAttemptAt(undefined, TEST_ACCOUNT); assert.ok(next != null); assert.ok((next as number) > Date.now() + 10_000); }); it("includes approval_resolve in due queue with stable client op id", async () => { const first = await enqueueApprovalResolve({ + accountId: TEST_ACCOUNT, conversationId: "session-1", clientMessageId: "approval-op-1", text: JSON.stringify({ @@ -230,10 +302,11 @@ describe("im-outbox", () => { assert.equal(first.kind, "approval_resolve"); assert.equal(first.clientMessageId, "approval-op-1"); assert.equal(first.id, "outbox:approval-op-1"); - assert.equal((await listDuePending()).length, 1); + assert.equal((await listDuePending(undefined, TEST_ACCOUNT)).length, 1); // Re-enqueue same logical op id keeps one entry (retry same id). const again = await enqueueApprovalResolve({ + accountId: TEST_ACCOUNT, conversationId: "session-1", clientMessageId: "approval-op-1", text: JSON.stringify({ @@ -248,34 +321,37 @@ describe("im-outbox", () => { .length, 1, ); - assert.equal((await listDuePending()).length, 1); - assert.equal((await listDuePending())[0]!.clientMessageId, "approval-op-1"); + assert.equal((await listDuePending(undefined, TEST_ACCOUNT)).length, 1); + assert.equal((await listDuePending(undefined, TEST_ACCOUNT))[0]!.clientMessageId, "approval-op-1"); await markInflight("approval-op-1"); await markAcked("approval-op-1"); assert.equal(await isAcked("approval-op-1"), true); - assert.equal((await listDuePending()).length, 0); + assert.equal((await listDuePending(undefined, TEST_ACCOUNT)).length, 0); }); it("listDuePendingLanes enforces per-conversation FIFO (no tail overtake)", async () => { // Two conversations; c1 has two due messages; c2 has one. await enqueueUserMessage({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "c1-a", text: "first", }); await enqueueUserMessage({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "c1-b", text: "second", }); await enqueueUserMessage({ + accountId: TEST_ACCOUNT, conversationId: "c2", clientMessageId: "c2-a", text: "other", }); - const lanes = await listDuePendingLanes(); + const lanes = await listDuePendingLanes(undefined, TEST_ACCOUNT); assert.equal(lanes.length, 2); // Lanes sorted by conversationId. assert.equal(lanes[0]![0]!.conversationId, "c1"); @@ -291,23 +367,25 @@ describe("im-outbox", () => { // Put c1 head into backoff — lane must omit tail even if it is due. await markInflight("c1-a"); await markFailed("c1-a", "network error"); - const afterFail = await listDuePendingLanes(); + const afterFail = await listDuePendingLanes(undefined, TEST_ACCOUNT); // c1 blocked (head not due); c2 still drains. assert.equal(afterFail.length, 1); assert.equal(afterFail[0]![0]!.clientMessageId, "c2-a"); // Flat due still includes c1-b (due) but lanes correctly hide it. - const flat = await listDuePending(); + const flat = await listDuePending(undefined, TEST_ACCOUNT); assert.ok(flat.some((e) => e.clientMessageId === "c1-b")); assert.ok(!afterFail.some((lane) => lane.some((e) => e.clientMessageId === "c1-b"))); }); it("listDuePendingLanes skips lane when head is fresh inflight", async () => { await enqueueUserMessage({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "m-head", text: "a", }); await enqueueUserMessage({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "m-tail", text: "b", @@ -318,34 +396,64 @@ describe("im-outbox", () => { ); assert.equal(head!.status, "inflight"); // Inflight head blocks the whole lane (no tail overtake). - assert.equal((await listDuePendingLanes()).length, 0); + assert.equal((await listDuePendingLanes(undefined, TEST_ACCOUNT)).length, 0); // Flat due still lists the pending tail; flush must use lanes. - const flat = await listDuePending(); + const flat = await listDuePending(undefined, TEST_ACCOUNT); assert.equal(flat.length, 1); assert.equal(flat[0]!.clientMessageId, "m-tail"); }); it("reaction lane is independent of blocked message lane", async () => { await enqueueUserMessage({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "msg-a", text: "first", }); await enqueueUserMessage({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "msg-b", text: "second", }); await enqueueReactionToggle({ + accountId: TEST_ACCOUNT, conversationId: "c1", clientMessageId: "rx-1", text: JSON.stringify({ messageId: "msg-a", emoji: "👍" }), }); await markInflight("msg-a"); - const lanes = await listDuePendingLanes(); + const lanes = await listDuePendingLanes(undefined, TEST_ACCOUNT); // Message lane blocked; reaction lane still due. assert.equal(lanes.length, 1); assert.equal(lanes[0]![0]!.clientMessageId, "rx-1"); assert.equal(outboxLaneKey(lanes[0]![0]!), "reaction:c1"); }); + + it("only claims rows for the current account and quarantines empty accountId", async () => { + await enqueueUserMessage({ + accountId: "acct-a", + conversationId: "c1", + clientMessageId: "a1", + text: "from-a", + }); + await enqueueUserMessage({ + accountId: "acct-b", + conversationId: "c1", + clientMessageId: "b1", + text: "from-b", + }); + // Legacy/quarantine row + const snap = await getOutboxSnapshotForTests(); + assert.equal(snap.length, 2); + const dueA = await listDuePending(undefined, "acct-a"); + assert.equal(dueA.length, 1); + assert.equal(dueA[0]!.clientMessageId, "a1"); + const dueB = await listDuePending(undefined, "acct-b"); + assert.equal(dueB.length, 1); + assert.equal(dueB[0]!.clientMessageId, "b1"); + assert.equal((await listDuePending(undefined, "")).length, 0); + assert.equal((await listDuePending()).length, 0); + }); + }); diff --git a/apps/desktop/src/shared/lib/im-outbox.ts b/apps/desktop/src/shared/lib/im-outbox.ts index 77725d55..f218d83a 100644 --- a/apps/desktop/src/shared/lib/im-outbox.ts +++ b/apps/desktop/src/shared/lib/im-outbox.ts @@ -41,6 +41,8 @@ const BASE_BACKOFF_MS = 1_500; const MAX_BACKOFF_MS = 5 * 60_000; /** Inflight rows older than this are reclaimed to pending (kill mid-flight). */ export const STALE_INFLIGHT_MS = 45_000; +/** Max unacked intents (pending+inflight+failed_terminal). Matches Tauri store. */ +export const MAX_OUTBOX_ENTRIES = 2_000; export type OutboxStatus = | "pending" @@ -79,6 +81,11 @@ export type ImOutboxEntry = { kind: OutboxKind; conversationId: string; clientMessageId: string; + /** + * Immutable owner account at enqueue. Empty/missing rows are quarantined and + * never claimed by any account's worker. + */ + accountId: string; text: string; title?: string | null; replyToMessageId?: string | null; @@ -103,6 +110,7 @@ type ImOutboxWire = { kind: string; conversationId: string; clientMessageId: string; + accountId?: string | null; text: string; title?: string | null; replyToMessageId?: string | null; @@ -160,6 +168,7 @@ function entryToWire(e: ImOutboxEntry): ImOutboxWire { kind: e.kind, conversationId: e.conversationId, clientMessageId: e.clientMessageId, + accountId: e.accountId || "", text: e.text, title: e.title ?? null, replyToMessageId: e.replyToMessageId ?? null, @@ -184,6 +193,7 @@ function wireToEntry(w: ImOutboxWire): ImOutboxEntry { kind: w.kind as OutboxKind, conversationId: w.conversationId, clientMessageId: w.clientMessageId, + accountId: typeof w.accountId === "string" ? w.accountId.trim() : "", text: w.text, title: w.title, replyToMessageId: w.replyToMessageId, @@ -216,8 +226,20 @@ function memoryBackend(seed: ImOutboxEntry[] = []): OutboxBackend { }, async upsert(entry) { const idx = rows.findIndex((e) => e.clientMessageId === entry.clientMessageId); - if (idx >= 0) rows[idx] = entry; - else rows.push(entry); + if (idx >= 0) { + rows[idx] = entry; + return; + } + // Capacity before insert — failed enqueue must leave no durable/memory row. + if (entry.status !== "acked") { + const unacked = rows.filter((e) => e.status !== "acked").length; + if (unacked >= MAX_OUTBOX_ENTRIES) { + throw new Error( + `im_outbox_capacity: ${unacked} unacked intents already at max ${MAX_OUTBOX_ENTRIES}`, + ); + } + } + rows.push(entry); }, }; } @@ -387,10 +409,20 @@ export function classifyOutboxFailure(error: string): OutboxFailureClass { return "transient"; } +function ownedByAccount( + entry: Pick, + accountId: string, +): boolean { + const aid = accountId.trim(); + const owner = entry.accountId?.trim() ?? ""; + return !!aid && !!owner && owner === aid; +} + async function upsertPendingEntry(input: { kind: OutboxKind; conversationId: string; clientMessageId: string; + accountId: string; text: string; title?: string | null; replyToMessageId?: string | null; @@ -404,7 +436,11 @@ async function upsertPendingEntry(input: { return withMutation(async () => { const clientMessageId = input.clientMessageId.trim(); const conversationId = input.conversationId.trim(); + const accountId = input.accountId.trim(); const text = input.text.trim(); + if (!accountId) { + throw new Error("outbox enqueue requires accountId"); + } const t = nowMs(); const mentions = input.mentions && input.mentions.length > 0 @@ -418,9 +454,14 @@ async function upsertPendingEntry(input: { if (prev.status === "acked") { return prev; } + // Immutable owner: never reassign a row to another account. + if (prev.accountId?.trim() && prev.accountId.trim() !== accountId) { + return prev; + } const next: ImOutboxEntry = { ...prev, kind: input.kind, + accountId: prev.accountId?.trim() || accountId, text, title: input.title ?? prev.title, replyToMessageId: input.replyToMessageId ?? prev.replyToMessageId, @@ -438,8 +479,8 @@ async function upsertPendingEntry(input: { updatedAtMs: t, lastError: null, }; - entries[existingIdx] = next; await persistEntry(next); + entries[existingIdx] = next; return next; } @@ -448,6 +489,7 @@ async function upsertPendingEntry(input: { kind: input.kind, conversationId, clientMessageId, + accountId, text, title: input.title, replyToMessageId: input.replyToMessageId, @@ -466,8 +508,16 @@ async function upsertPendingEntry(input: { createdAtMs: t, updatedAtMs: t, }; - entries.push(entry); + // Pre-check so capacity failures never leave a memory-only row. + const unacked = entries.filter((e) => e.status !== "acked").length; + if (unacked >= MAX_OUTBOX_ENTRIES) { + throw new Error( + `im_outbox_capacity: ${unacked} unacked intents already at max ${MAX_OUTBOX_ENTRIES}`, + ); + } + // Persist first; only then mirror into memory (fail-closed). await persistEntry(entry); + entries.push(entry); return entry; }); } @@ -475,6 +525,7 @@ async function upsertPendingEntry(input: { export async function enqueueUserMessage(input: { conversationId: string; clientMessageId: string; + accountId: string; text: string; title?: string | null; replyToMessageId?: string | null; @@ -492,6 +543,7 @@ export async function enqueueUserMessage(input: { export async function enqueueAgentResult(input: { conversationId: string; clientMessageId: string; + accountId: string; text: string; agentId?: string | null; agentSessionId?: string | null; @@ -502,6 +554,7 @@ export async function enqueueAgentResult(input: { kind: "agent_result", conversationId: input.conversationId, clientMessageId: input.clientMessageId, + accountId: input.accountId, text: input.text, agentId: input.agentId, agentSessionId: input.agentSessionId, @@ -514,12 +567,14 @@ export async function enqueueAgentResult(input: { export async function enqueueReactionToggle(input: { conversationId: string; clientMessageId: string; + accountId: string; text: string; }): Promise { return upsertPendingEntry({ kind: "reaction_toggle", conversationId: input.conversationId, clientMessageId: input.clientMessageId, + accountId: input.accountId, text: input.text, messageSource: "client_live", }); @@ -528,12 +583,14 @@ export async function enqueueReactionToggle(input: { export async function enqueueApprovalResolve(input: { conversationId: string; clientMessageId: string; + accountId: string; text: string; }): Promise { return upsertPendingEntry({ kind: "approval_resolve", conversationId: input.conversationId, clientMessageId: input.clientMessageId, + accountId: input.accountId, text: input.text, messageSource: "client_live", }); @@ -624,7 +681,15 @@ export async function markFailed( }); } -export async function reclaimStaleInflight(now = nowMs()): Promise { +/** + * Reclaim stale inflight → pending. + * When `accountId` is non-empty, only that account's rows are reclaimed + * (account leave / worker must not touch foreign outbox ownership). + */ +export async function reclaimStaleInflight( + now = nowMs(), + accountId = "", +): Promise { return withMutation(async () => { const cutoff = now - STALE_INFLIGHT_MS; let n = 0; @@ -632,6 +697,7 @@ export async function reclaimStaleInflight(now = nowMs()): Promise { for (const e of entries) { if (e.status !== "inflight") continue; if (e.updatedAtMs >= cutoff) continue; + if (accountId && !ownedByAccount(e, accountId)) continue; e.status = "pending"; e.nextAttemptAt = now; e.updatedAtMs = now; @@ -646,10 +712,16 @@ export async function reclaimStaleInflight(now = nowMs()): Promise { }); } -export async function listDuePending(now = nowMs()): Promise { - await reclaimStaleInflight(now); +export async function listDuePending( + now = nowMs(), + accountId = "", +): Promise { + await reclaimStaleInflight(now, accountId); return entries.filter( - (e) => e.status === "pending" && e.nextAttemptAt <= now, + (e) => + e.status === "pending" && + e.nextAttemptAt <= now && + ownedByAccount(e, accountId), ); } @@ -665,11 +737,13 @@ export function compareOutboxFifo(a: ImOutboxEntry, b: ImOutboxEntry): number { */ export async function listDuePendingLanes( now = nowMs(), + accountId = "", ): Promise { - await reclaimStaleInflight(now); + await reclaimStaleInflight(now, accountId); const byLane = new Map(); for (const e of entries) { if (e.status !== "pending" && e.status !== "inflight") continue; + if (!ownedByAccount(e, accountId)) continue; const key = outboxLaneKey(e); const list = byLane.get(key); if (list) list.push(e); @@ -696,34 +770,39 @@ export async function listDuePendingLanes( export async function earliestPendingAttemptAt( now = nowMs(), + accountId = "", ): Promise { - await reclaimStaleInflight(now); + await reclaimStaleInflight(now, accountId); let min: number | null = null; for (const e of entries) { if (e.status !== "pending") continue; + if (!ownedByAccount(e, accountId)) continue; if (min == null || e.nextAttemptAt < min) min = e.nextAttemptAt; } return min; } -export async function listUnsynced(): Promise { +export async function listUnsynced(accountId = ""): Promise { await ensureReady(); return entries.filter( (e) => - e.status === "pending" || - e.status === "inflight" || - e.status === "failed_terminal", + ownedByAccount(e, accountId) && + (e.status === "pending" || + e.status === "inflight" || + e.status === "failed_terminal"), ); } export async function listPendingForConversation( conversationId: string, + accountId = "", ): Promise { await ensureReady(); const cid = conversationId.trim(); return entries.filter( (e) => e.conversationId === cid && + ownedByAccount(e, accountId) && (e.status === "pending" || e.status === "inflight"), ); } diff --git a/apps/desktop/src/shared/lib/im-timeline-sync.test.ts b/apps/desktop/src/shared/lib/im-timeline-sync.test.ts index 30de3e65..d6b8bbd1 100644 --- a/apps/desktop/src/shared/lib/im-timeline-sync.test.ts +++ b/apps/desktop/src/shared/lib/im-timeline-sync.test.ts @@ -4,7 +4,7 @@ */ import assert from "node:assert/strict"; import { describe, it } from "node:test"; -import type { TimelineMessage } from "./mock-data.ts"; +import type { TimelineMessage } from "../domain/collaboration.ts"; import { firstMessageSeq, lastMessageSeq, diff --git a/apps/desktop/src/shared/lib/message-history.test.ts b/apps/desktop/src/shared/lib/message-history.test.ts index e00e8af9..4e755a45 100644 --- a/apps/desktop/src/shared/lib/message-history.test.ts +++ b/apps/desktop/src/shared/lib/message-history.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { describe, it } from "node:test"; -import type { TimelineMessage } from "./mock-data.ts"; +import type { TimelineMessage } from "../domain/collaboration.ts"; import { firstMessageCreatedAtMs, firstMessageSeq, diff --git a/apps/desktop/src/shared/lib/message-history.ts b/apps/desktop/src/shared/lib/message-history.ts index aea0a5e3..c4e5daf9 100644 --- a/apps/desktop/src/shared/lib/message-history.ts +++ b/apps/desktop/src/shared/lib/message-history.ts @@ -1,4 +1,4 @@ -import type { TimelineMessage } from "./mock-data.ts"; +import type { TimelineMessage } from "../domain/collaboration.ts"; import { sortTimelineMessages } from "./timeline-order.ts"; import { timelineMessageEqual } from "./list-identity.ts"; diff --git a/apps/desktop/src/shared/lib/mock-data.ts b/apps/desktop/src/shared/lib/mock-data.ts index 9ef31f67..8bc660ef 100644 --- a/apps/desktop/src/shared/lib/mock-data.ts +++ b/apps/desktop/src/shared/lib/mock-data.ts @@ -1,272 +1,43 @@ -/** Mock fixtures for the Minos desktop shell (TUI-parity IA). */ +/** Mock fixtures + presentation maps for the Minos desktop shell. */ -export type AgentRuntime = - | "codex" - | "claude" - | "gemini" - | "opencode" - | "grok"; - -export type SessionStatus = - | "idle" - | "running" - | "needs_approval" - | "suspended" - | "failed" - | "done"; - -export type ConversationBoardColumn = - | "backlog" - | "running" - | "needs_you" - | "done"; - -export type ConversationPriority = "high" | "medium" | "low"; - -export type ConversationProgress = - | "todo" - | "in_progress" - | "in_review" - | "done"; - -export type AvatarTone = - | "green" - | "blue" - | "pink" - | "orange" - | "purple" - | "slate" - | "amber"; - -export type Project = { - id: string; - name: string; - workspacePath: string; - conversationCount: number; - runningAgents: number; - needsAttention: number; - /** Last activity timestamp (ms) for WeChat-style list sort. */ - updatedAtMs: number; - /** True when any conversation has unread or pending approval. */ - hasUnread: boolean; - /** - * Max `updatedAtMs` among conversations that currently need attention. - * Sort uses `hasUnread` + project `updatedAtMs` only — this is diagnostic / - * aggregate metadata, not a separate sort key. - */ - lastAttentionMs: number; - /** - * Which host owns this project (plane C). - * Omit for this Mac (default). Multi-device rows set a device display name. - */ - hostName?: string; -}; - -/** Conversation bot member card (membership key = botId). */ -export type ParticipatingBot = { - botId: string; - name: string; - runtime: string; -}; - -/** Derive unique runtime labels from structured bots (host-runtime ensure / badges). */ -export function runtimesOfBots(bots: readonly ParticipatingBot[] | undefined): string[] { - const out: string[] = []; - const seen = new Set(); - for (const b of bots ?? []) { - const r = b.runtime.trim().toLowerCase(); - if (!r || seen.has(r)) continue; - seen.add(r); - out.push(r); - } - return out; -} - -/** Membership tokens for @ resolve: botId ∪ name ∪ runtime (all lowercased). */ -export function membershipTokensOfBots( - bots: readonly ParticipatingBot[] | undefined, -): string[] { - const out: string[] = []; - const seen = new Set(); - for (const b of bots ?? []) { - for (const raw of [b.botId, b.name, b.runtime]) { - const t = raw.trim().toLowerCase(); - if (!t || seen.has(t)) continue; - seen.add(t); - out.push(t); - } - } - return out; -} - -export type Conversation = { - id: string; - projectId: string; - title: string; - preview: string; - /** - * Last activity epoch ms (sort + list clock SSOT). - * Format at render with `formatListActivityTime` — never store display strings. - */ - updatedAtMs: number; - unread?: number; - /** Aggregated message count in the conversation timeline. */ - messageCount: number; - boardColumn: ConversationBoardColumn; - agentSessionCount: number; - /** - * Bot participants on the conversation roster (membership SSOT). - * Membership key is `botId`; `runtime` is launch/badge only. - */ - participatingBots: ParticipatingBot[]; - /** - * @deprecated Derived runtime labels from `participatingBots` for host-runtime - * ensure / badges. Do not use as membership SSOT. - */ - participatingAgents: string[]; - runningCount: number; - approvalCount: number; - /** Git branch for this conversation work unit. */ - branch?: string; - /** Optional linked git worktree path. */ - worktree?: string; - /** Git isolation mode: inherit | worktree. */ - gitMode?: string; - /** Cached dirty flag from last git status refresh. */ - gitDirty?: boolean; - /** Cached HEAD from last git status refresh. */ - gitHead?: string; - /** User priority tag; omit when unset. */ - priority?: ConversationPriority; - /** Workflow progress (default todo). */ - progress?: ConversationProgress; -}; - -export type TimelineMention = { - /** Runtime agent name when kind is agent (legacy workbench rows). */ - agent?: string; - sessionId?: string; - sessionShortId?: string; - /** Structured mention kind from Hub SSOT. */ - kind?: "account" | "agent"; - /** account_id or agent_id depending on kind. */ - targetId?: string; -}; - -export type DeliveryStatus = "sending" | "sent" | "failed"; - -/** Git milestone shown as a dedicated timeline card. */ -export type TimelineGitActivity = { - kind: - | "worktree_created" - | "commits_made" - | "pr_opened" - | "checks_failed" - | "ready_for_review" - | "merged"; - branch?: string; - worktreePath?: string; - baseBranch?: string; - count?: number; - subjects?: string[]; - head?: string; - url?: string; - number?: number; - title?: string; - summary?: string; - mergeCommit?: string; -}; - -/** Viewer-resolved reaction aggregate carried from Hub cold pull / live frames. */ -export type TimelineReactionActor = { - id: string; - displayName: string; -}; - -export type TimelineReactionGroup = { - emoji: string; - count: number; - reactedByMe: boolean; - actors: TimelineReactionActor[]; -}; - -export type TimelineMessage = { - id: string; - /** - * Social total-order key: Hub `message_seq` when linked, host daemon seq only - * for local-only (unlinked) workbench chat. Host tool/git cards must not use - * this field for cross-source order — use `anchorCloudMessageSeq` + `suborder`. - */ - messageSeq?: number; - /** - * Host-only cards: place after the Hub bubble with this social seq. - * Undefined = unanchored (sort after social rows, before optimistic tail). - */ - anchorCloudMessageSeq?: number; - /** Among host cards with the same anchor (or unanchored), local order. */ - suborder?: number; - /** Daemon host seq for host-only pagination (never mixed into Hub before_seq). */ - hostMessageSeq?: number; - role: "user" | "agent" | "system"; - /** Runtime family (codex/claude/…) for badges / tone; not bot identity. */ - agent?: AgentRuntime; - /** - * Hub bot display name (MessageSender::Bot) or human display name when known. - * Prefer this over runtime-keyed `agentMeta` for author labels. - */ - senderDisplayName?: string; - /** Global bot id when role=agent (MessageSender::Bot.bot_id). */ - botId?: string; - sessionId?: string; - body: string; - time: string; - createdAtMs?: number; - kind?: "text" | "tool_summary" | "approval" | "git_activity" | "system"; - replyToMessageId?: string; - delegationId?: string; - mentions?: TimelineMention[]; - gitActivity?: TimelineGitActivity; - /** - * Hub (or daemon) reaction aggregates for cold hydrate into reaction-store. - * Optional — live frames may omit until a reaction event arrives. - */ - reactions?: TimelineReactionGroup[]; - /** - * Local delivery lifecycle for user messages. - * - `sending`: optimistic bubble shown immediately, awaiting append/RPC ack. - * - `failed`: append or send pipeline threw; row stays until retry succeeds. - * - `sent`: append succeeded (durable). Omitted on durable rows loaded from - * daemon — absence is treated as `sent` by render. - */ - deliveryStatus?: DeliveryStatus; -}; - -export type AgentSession = { - id: string; - conversationId: string; - agent: AgentRuntime; - shortId: string; - status: SessionStatus; - model: string; - parentId?: string; - summary: string; - lastTool?: string; - /** Host should auto-continue after process-death recovery. */ - needsContinue?: boolean; -}; - -export type HostStatus = { - relay: "connected" | "disconnected"; - daemonVersion: string; - pairedDevices: number; -}; +import type { + AgentRuntime, + AgentSession, + AvatarTone, + Conversation, + ConversationBoardColumn, + HostStatus, + InstalledRuntime, + Project, + SessionStatus, + TimelineMessage, +} from "../domain/collaboration.ts"; -export type InstalledRuntime = { - agent: AgentRuntime; - installed: boolean; - path?: string; - version?: string; -}; +export type { + AgentRuntime, + SessionStatus, + ConversationBoardColumn, + ConversationPriority, + ConversationProgress, + AvatarTone, + Project, + ParticipatingBot, + Conversation, + TimelineMention, + DeliveryStatus, + TimelineGitActivity, + TimelineReactionActor, + TimelineReactionGroup, + TimelineMessage, + AgentSession, + HostStatus, + InstalledRuntime, + ProjectSession, +} from "../domain/collaboration.ts"; +export { + runtimesOfBots, + membershipTokensOfBots, +} from "../domain/collaboration.ts"; export const hostStatus: HostStatus = { relay: "connected", diff --git a/apps/desktop/src/shared/lib/rail-activity.test.ts b/apps/desktop/src/shared/lib/rail-activity.test.ts index 26fa77d9..ed4e48f4 100644 --- a/apps/desktop/src/shared/lib/rail-activity.test.ts +++ b/apps/desktop/src/shared/lib/rail-activity.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { describe, it } from "node:test"; -import type { TimelineMessage } from "./mock-data.ts"; +import type { TimelineMessage } from "../domain/collaboration.ts"; import { positiveMs, railActivityFromTimeline, diff --git a/apps/desktop/src/shared/lib/rail-activity.ts b/apps/desktop/src/shared/lib/rail-activity.ts index f16f8bdf..07d5f59d 100644 --- a/apps/desktop/src/shared/lib/rail-activity.ts +++ b/apps/desktop/src/shared/lib/rail-activity.ts @@ -6,7 +6,7 @@ * the recalled row's original timestamp). */ -import type { TimelineMessage } from "./mock-data.ts"; +import type { TimelineMessage } from "../domain/collaboration.ts"; export type RailActivity = { lastMessageAtMs: number; diff --git a/apps/desktop/src/shared/lib/session-entity.ts b/apps/desktop/src/shared/lib/session-entity.ts index 42bb280c..cc8a3d9c 100644 --- a/apps/desktop/src/shared/lib/session-entity.ts +++ b/apps/desktop/src/shared/lib/session-entity.ts @@ -10,7 +10,7 @@ * lifecycle without a newer lastTsMs (or an authoritative manager path). */ -import type { AgentRuntime, SessionStatus } from "./mock-data.ts"; +import type { AgentRuntime, SessionStatus } from "../domain/collaboration.ts"; import type { ApprovalStatusPolicy } from "./session-status.ts"; export type SessionEntity = { diff --git a/apps/desktop/src/shared/lib/session-list-group.test.ts b/apps/desktop/src/shared/lib/session-list-group.test.ts index 4eaa213c..c0aeae64 100644 --- a/apps/desktop/src/shared/lib/session-list-group.test.ts +++ b/apps/desktop/src/shared/lib/session-list-group.test.ts @@ -6,7 +6,7 @@ import { groupSessionsByConversation, sessionIsExecuting, } from "./session-list-group.ts"; -import type { ProjectSession } from "../../store/workspace-store.ts"; +import type { ProjectSession } from "../domain/collaboration.ts"; function sess( partial: Partial & diff --git a/apps/desktop/src/shared/lib/session-list-group.ts b/apps/desktop/src/shared/lib/session-list-group.ts index cd1a1978..a737cc47 100644 --- a/apps/desktop/src/shared/lib/session-list-group.ts +++ b/apps/desktop/src/shared/lib/session-list-group.ts @@ -1,5 +1,7 @@ -import type { SessionStatus } from "@/shared/lib/mock-data"; -import type { ProjectSession } from "@/store/workspace-store"; +import type { + ProjectSession, + SessionStatus, +} from "../domain/collaboration.ts"; export type ConversationSessionGroup = { conversationId: string; diff --git a/apps/desktop/src/shared/lib/session-status.ts b/apps/desktop/src/shared/lib/session-status.ts index 68a1174f..f9e8e768 100644 --- a/apps/desktop/src/shared/lib/session-status.ts +++ b/apps/desktop/src/shared/lib/session-status.ts @@ -1,4 +1,4 @@ -import type { SessionStatus } from "./mock-data"; +import type { SessionStatus } from "../domain/collaboration.ts"; /** * Derive UI session status from daemon session status + optional pending-approval diff --git a/apps/desktop/src/shared/lib/timeline-order.test.ts b/apps/desktop/src/shared/lib/timeline-order.test.ts index 4070a97d..021565e8 100644 --- a/apps/desktop/src/shared/lib/timeline-order.test.ts +++ b/apps/desktop/src/shared/lib/timeline-order.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { describe, it } from "node:test"; -import type { TimelineMessage } from "./mock-data.ts"; +import type { TimelineMessage } from "../domain/collaboration.ts"; import { sortTimelineMessages } from "./timeline-order.ts"; function msg(partial: Partial & Pick): TimelineMessage { diff --git a/apps/desktop/src/shared/lib/timeline-order.ts b/apps/desktop/src/shared/lib/timeline-order.ts index f5480ae9..ef6203ff 100644 --- a/apps/desktop/src/shared/lib/timeline-order.ts +++ b/apps/desktop/src/shared/lib/timeline-order.ts @@ -1,4 +1,4 @@ -import type { TimelineMessage } from "@/shared/lib/mock-data"; +import type { TimelineMessage } from "../domain/collaboration.ts"; /** Host workbench cards that hang off Hub social order via anchor+suborder. */ export function isHostOnlyTimelineCard(message: TimelineMessage): boolean { diff --git a/apps/desktop/src/shared/lib/user-message-settlement.test.ts b/apps/desktop/src/shared/lib/user-message-settlement.test.ts new file mode 100644 index 00000000..47ced2ca --- /dev/null +++ b/apps/desktop/src/shared/lib/user-message-settlement.test.ts @@ -0,0 +1,17 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { deliveryStatusAfterUserSettlement } from "./user-message-settlement.ts"; + +describe("deliveryStatusAfterUserSettlement", () => { + it("acked → sent", () => { + assert.equal(deliveryStatusAfterUserSettlement("acked"), "sent"); + }); + + it("timeout → failed (retry affordance; never false sent)", () => { + assert.equal(deliveryStatusAfterUserSettlement("timeout"), "failed"); + }); + + it("failed_terminal → failed", () => { + assert.equal(deliveryStatusAfterUserSettlement("failed_terminal"), "failed"); + }); +}); diff --git a/apps/desktop/src/shared/lib/user-message-settlement.ts b/apps/desktop/src/shared/lib/user-message-settlement.ts new file mode 100644 index 00000000..b3a1245b --- /dev/null +++ b/apps/desktop/src/shared/lib/user-message-settlement.ts @@ -0,0 +1,13 @@ +/** + * Map outbox settlement → UI delivery for user bubbles. + * + * Only `acked` may become `sent`. Timeout and terminal failure both surface as + * `failed` so the user sees a retry affordance (WeChat-style red `!`), even when + * the durable outbox may still retry in the background. + */ +export function deliveryStatusAfterUserSettlement( + settlement: "acked" | "failed_terminal" | "timeout", +): "sent" | "failed" { + if (settlement === "acked") return "sent"; + return "failed"; +} diff --git a/apps/desktop/src/shared/ui/Avatar.tsx b/apps/desktop/src/shared/ui/Avatar.tsx index c932846d..18540b33 100644 --- a/apps/desktop/src/shared/ui/Avatar.tsx +++ b/apps/desktop/src/shared/ui/Avatar.tsx @@ -1,5 +1,6 @@ import { cn } from "@/shared/lib/utils"; -import { initials, toneClasses, type AvatarTone } from "@/shared/lib/mock-data"; +import type { AvatarTone } from "../domain/collaboration.ts"; +import { initials, toneClasses } from "@/shared/lib/mock-data"; type AvatarProps = { name: string; diff --git a/apps/desktop/src/shared/ui/StatusPill.tsx b/apps/desktop/src/shared/ui/StatusPill.tsx index 6eda405f..ff642f05 100644 --- a/apps/desktop/src/shared/ui/StatusPill.tsx +++ b/apps/desktop/src/shared/ui/StatusPill.tsx @@ -1,6 +1,7 @@ import { Loader2 } from "lucide-react"; import { cn } from "@/shared/lib/utils"; -import { statusMeta, type SessionStatus } from "@/shared/lib/mock-data"; +import type { SessionStatus } from "../domain/collaboration.ts"; +import { statusMeta } from "@/shared/lib/mock-data"; export function StatusPill({ status, diff --git a/apps/desktop/src/shared/ui/Tag.tsx b/apps/desktop/src/shared/ui/Tag.tsx index 752166e3..96a7afc2 100644 --- a/apps/desktop/src/shared/ui/Tag.tsx +++ b/apps/desktop/src/shared/ui/Tag.tsx @@ -3,7 +3,7 @@ import { cn } from "@/shared/lib/utils"; import type { ConversationPriority, ConversationProgress, -} from "@/shared/lib/mock-data"; +} from "../domain/collaboration.ts"; const priorityStyles: Record< ConversationPriority, diff --git a/apps/desktop/src/store/account-store.ts b/apps/desktop/src/store/account-store.ts index 2487c2ba..c24ba5f2 100644 --- a/apps/desktop/src/store/account-store.ts +++ b/apps/desktop/src/store/account-store.ts @@ -40,11 +40,14 @@ import { type CloudMode, } from "@/shared/lib/host-status"; import { daemonApi } from "@/shared/lib/daemon"; -import { - registerHostCredential, - waitForCloudOnline, -} from "@/features/host/lib/ensure-host-connection"; +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 { + bumpAccountScopeGeneration, + leaveAccountScope, +} from "@/store/leave-account-scope"; +import { refreshDaemonCloudFlags } from "@/store/daemon-status-port"; export type AuthMode = "login" | "register"; @@ -55,6 +58,11 @@ type AccountState = { session: MinosSession | null; /** Internal bind snapshot (diagnostics); not a product "Link" flag. */ hostBind: HostBindState; + /** + * Account that owns the live host credential for this process. + * Null after leave; Host online requires match with session.accountId. + */ + hostCredentialAccountId: string | null; /** * Host runtime readiness (`/ws/host`): online | connecting | offline | unknown. * Secondary signal — bot execution on this Mac. Not product primary Online. @@ -113,29 +121,8 @@ function isCloudConfigured(): boolean { let ensureInFlight: Promise | null = null; let ensureGeneration = 0; - -type DaemonCloudFlags = { - cloudOnline: boolean; - hasHostToken: boolean; -}; - -async function refreshDaemonCloudFlags(): Promise { - try { - const { useWorkspaceStore } = await import("@/store/workspace-store"); - await useWorkspaceStore.getState().refreshDaemonStatus(); - const connection = useWorkspaceStore.getState().connection; - return { - cloudOnline: connection?.cloudOnline === true, - hasHostToken: connection?.hasHostToken === true, - }; - } catch { - return { cloudOnline: false, hasHostToken: false }; - } -} - -async function refreshCloudOnlineFlag(): Promise { - return (await refreshDaemonCloudFlags()).cloudOnline; -} +let hydrateInFlight: Promise | null = null; +let hydrateGeneration = 0; function applyAuthSuccess( set: ( @@ -146,11 +133,24 @@ function applyAuthSuccess( get: () => AccountState, session: MinosSession, ): void { + const prevAccountId = get().session?.accountId?.trim() ?? null; + const nextAccountId = session.accountId.trim(); + if (prevAccountId && prevAccountId !== nextAccountId) { + ensureGeneration += 1; + ensureInFlight = null; + hydrateGeneration += 1; + hydrateInFlight = null; + leaveAccountScope("account-switch"); + } saveStoredSession(session); const hostBind = loadStoredHostBind(session.accountId); + const hostOwned = + get().hostCredentialAccountId === nextAccountId && hostBind.bound; set({ session, hostBind, + // New account (or unbound) must re-establish host ownership before online. + hostCredentialAccountId: hostOwned ? nextAccountId : null, cloudStatus: "connecting", accountSyncStatus: "connecting", cloudError: null, @@ -159,16 +159,21 @@ function applyAuthSuccess( error: null, hydrated: true, }); - void import("@/shared/lib/im-cloud-bridge").then(({ ensureImCloudBridge }) => + void import("@/store/im/im-cloud-bridge").then(({ ensureImCloudBridge }) => ensureImCloudBridge(), ); - void get().ensureCloudConnection(); + const forceReregister = + !hostOwned || prevAccountId !== nextAccountId || !hostBind.bound; + void get().ensureCloudConnection( + forceReregister ? { forceReregister: true } : undefined, + ); } export const useAccountStore = create()((set, get) => ({ deviceId: ensureDesktopDeviceId(), session: null, hostBind: { ...EMPTY_HOST_BIND }, + hostCredentialAccountId: null, cloudStatus: "unknown", accountSyncStatus: "unknown", cloudError: null, @@ -185,64 +190,86 @@ export const useAccountStore = create()((set, get) => ({ isSupabaseReady: () => isSupabaseConfigured(), hydrateAuth: async () => { - set({ authPhase: "booting", error: null }); - const stored = loadStoredSession(); - if (!stored) { - set({ - session: null, - hostBind: { ...EMPTY_HOST_BIND }, - cloudStatus: "unknown", - accountSyncStatus: "unknown", - cloudError: null, - authPhase: "unauthenticated", - hydrated: true, - }); - return; - } + if (hydrateInFlight) return hydrateInFlight; + const gen = ++hydrateGeneration; + hydrateInFlight = (async () => { + set({ authPhase: "booting", error: null }); + const stored = loadStoredSession(); + if (!stored) { + if (gen !== hydrateGeneration) return; + set({ + session: null, + hostBind: { ...EMPTY_HOST_BIND }, + hostCredentialAccountId: null, + cloudStatus: "unknown", + accountSyncStatus: "unknown", + cloudError: null, + authPhase: "unauthenticated", + hydrated: true, + }); + return; + } - if (isAccessTokenFresh(stored)) { - set({ - session: stored, - hostBind: loadStoredHostBind(stored.accountId), - cloudStatus: "connecting", - accountSyncStatus: "connecting", - cloudError: null, - authPhase: "authenticated", - hydrated: true, - }); - void import("@/shared/lib/im-cloud-bridge").then(({ ensureImCloudBridge }) => - ensureImCloudBridge(), - ); - void get().ensureCloudConnection(); - return; - } + if (isAccessTokenFresh(stored)) { + if (gen !== hydrateGeneration) return; + const hostBind = loadStoredHostBind(stored.accountId); + set({ + session: stored, + hostBind, + hostCredentialAccountId: hostBind.bound ? stored.accountId : null, + cloudStatus: "connecting", + accountSyncStatus: "connecting", + cloudError: null, + authPhase: "authenticated", + hydrated: true, + }); + void import("@/store/im/im-cloud-bridge").then(({ ensureImCloudBridge }) => + ensureImCloudBridge(), + ); + void get().ensureCloudConnection( + hostBind.bound ? undefined : { forceReregister: true }, + ); + return; + } - try { - const tokens = await refreshSession( - get().deviceId, - stored.refreshToken, - ); - const session: MinosSession = { - ...stored, - accessToken: tokens.access_token, - refreshToken: tokens.refresh_token, - expiresInSec: tokens.expires_in, - issuedAtMs: Date.now(), - }; - applyAuthSuccess(set, get, session); - } catch { - clearStoredSession(); - set({ - session: null, - hostBind: { ...EMPTY_HOST_BIND }, - cloudStatus: "unknown", - accountSyncStatus: "unknown", - cloudError: null, - authPhase: "unauthenticated", - hydrated: true, - error: null, - }); - } + try { + const tokens = await refreshSession( + get().deviceId, + stored.refreshToken, + ); + if (gen !== hydrateGeneration) return; + const session: MinosSession = { + ...stored, + accessToken: tokens.access_token, + refreshToken: tokens.refresh_token, + expiresInSec: tokens.expires_in, + issuedAtMs: Date.now(), + }; + applyAuthSuccess(set, get, session); + } 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, + }); + } + })().finally(() => { + if (gen === hydrateGeneration) { + hydrateInFlight = null; + } + }); + return hydrateInFlight; }, signIn: async (email, password) => { @@ -289,6 +316,10 @@ export const useAccountStore = create()((set, get) => ({ const { session, deviceId } = get(); set({ busy: true, error: null }); ensureGeneration += 1; + ensureInFlight = null; + hydrateGeneration += 1; + hydrateInFlight = null; + bumpAccountScopeGeneration(); if (session) { try { await logoutSession(deviceId, session.accessToken, session.refreshToken); @@ -298,12 +329,11 @@ export const useAccountStore = create()((set, get) => ({ } await signOutSupabase(); clearStoredSession(); - void import("@/shared/lib/im-cloud-bridge").then(({ stopImCloudBridge }) => - stopImCloudBridge(), - ); + leaveAccountScope("sign-out"); set({ session: null, hostBind: { ...EMPTY_HOST_BIND }, + hostCredentialAccountId: null, cloudStatus: "unknown", accountSyncStatus: "unknown", cloudError: null, @@ -336,87 +366,79 @@ export const useAccountStore = create()((set, get) => ({ set({ cloudStatus: "connecting", cloudError: null }); - // ── Steady state: never re-register if we already have hit_ ──────── - // Product has no "Link". Protocol only needs hit_ once. Calling - // POST /v1/hosts/link again revokes the live token → 401 races. - const flags = await refreshDaemonCloudFlags(); + const accountId = session.accountId.trim(); + const result = await runHostEnsure( + { + forceReregister, + sessionAccountId: accountId, + hostCredentialAccountId: get().hostCredentialAccountId, + }, + { + refreshFlags: refreshDaemonCloudFlags, + isOnline: async () => + (await refreshDaemonCloudFlags()).cloudOnline, + registerPorts: { + prepareLink: () => daemonApi.hostPrepareLink(), + signLinkProof: (installationId, nonce) => + daemonApi.hostSignLinkProof(installationId, nonce), + applyLinkToken: (token) => daemonApi.hostApplyLinkToken(token), + registerHost: (input) => + cloudLinkHost(get().deviceId, session.accessToken, input), + }, + hostDisplayName: PROJECT_HOST_THIS_MAC, + waitOpts: { timeoutMs: 20_000, intervalMs: 500 }, + // Account leave/switch bumps ensureGeneration; also reject if the + // session account changed mid-flight (deferred A after B logged in). + isCurrent: () => + gen === ensureGeneration && + get().session?.accountId?.trim() === accountId, + }, + ); + if (gen !== ensureGeneration) return; + if (get().session?.accountId?.trim() !== accountId) return; - if (flags.cloudOnline) { + if (result.kind === "online") { set({ cloudStatus: "online", cloudError: null }); return; } - if (!forceReregister && flags.hasHostToken) { - // Credential exists — only wait for dialer; do not mint/revoke. - const online = await waitForCloudOnline(refreshCloudOnlineFlag, { - timeoutMs: 20_000, - intervalMs: 500, - }); - if (gen !== ensureGeneration) return; - if (online) { - set({ cloudStatus: "online", cloudError: null }); - return; - } - // Still offline with a local hit_: backend down or token dead. - // Do **not** auto-rotate here (would thrash). Retry uses forceReregister. + if (result.kind === "offline") { set({ cloudStatus: "offline", - cloudError: - "Has local host credential but server is unreachable. Check minos-backend, then Retry.", + cloudError: result.message, }); return; } - // ── Missing hit_ or explicit Retry: one silent register ──────────── - const outcome = await registerHostCredential( - { - prepareLink: () => daemonApi.hostPrepareLink(), - signLinkProof: (installationId, nonce) => - daemonApi.hostSignLinkProof(installationId, nonce), - applyLinkToken: (token) => daemonApi.hostApplyLinkToken(token), - registerHost: (input) => - cloudLinkHost(get().deviceId, session.accessToken, input), - }, - PROJECT_HOST_THIS_MAC, - ); - - if (gen !== ensureGeneration) return; - - if (!outcome.ok) { + if (result.kind === "register-failed") { set({ cloudStatus: "offline", - cloudError: `Connect failed (${outcome.stage}): ${outcome.message}`, + hostCredentialAccountId: null, + cloudError: `Connect failed (${result.stage}): ${result.message}`, }); return; } const hostBind: HostBindState = { bound: true, - hostInstallationId: outcome.hostInstallationId, - hostDisplayName: outcome.hostDisplayName, - boundAtMs: outcome.linkedAtMs, - pairId: outcome.pairId, + hostInstallationId: result.hostInstallationId, + hostDisplayName: result.hostDisplayName, + boundAtMs: result.linkedAtMs, + pairId: result.pairId, }; saveStoredHostBind(session.accountId, hostBind); - set({ hostBind }); - - const online = await waitForCloudOnline(refreshCloudOnlineFlag, { - timeoutMs: 20_000, - intervalMs: 500, - }); - - if (gen !== ensureGeneration) return; + set({ hostBind, hostCredentialAccountId: accountId }); - if (online) { + if (result.kind === "registered-online") { set({ cloudStatus: "online", cloudError: null }); - } else { - set({ - cloudStatus: "offline", - cloudError: - "Signed in but not connected to the server yet. Retry or check that minos-backend is running.", - }); + return; } + + set({ + cloudStatus: "offline", + cloudError: result.message, + }); }; ensureInFlight = run().finally(() => { @@ -432,8 +454,10 @@ export const useAccountStore = create()((set, get) => ({ }, syncCloudFromCloud: (cloudOnline) => { - const { session, cloudStatus } = get(); + const { session, cloudStatus, hostCredentialAccountId } = get(); if (!session) return; + // Foreign or cleared host ownership must never paint Host online. + if (hostCredentialAccountId !== session.accountId) return; // Do not clobber an in-flight ensure. if (cloudStatus === "connecting") return; if (cloudOnline === true) { @@ -464,3 +488,17 @@ export const useAccountStore = create()((set, get) => ({ } }, })); + +// Shared transport reads auth via this port — never imports account-store. +registerCloudAuthProvider(() => { + const { deviceId, session, authPhase } = useAccountStore.getState(); + const accessToken = session?.accessToken?.trim() ?? ""; + const accountId = session?.accountId?.trim() ?? ""; + if (!accessToken || !accountId) return null; + return { + deviceId, + accessToken, + accountId, + authPhase, + }; +}); diff --git a/apps/desktop/src/store/daemon-status-port.ts b/apps/desktop/src/store/daemon-status-port.ts new file mode 100644 index 00000000..d6b197b2 --- /dev/null +++ b/apps/desktop/src/store/daemon-status-port.ts @@ -0,0 +1,32 @@ +/** + * Narrow port for Host readiness flags without account↔workspace import cycles. + * + * Workspace connection registers the live refresh implementation at bootstrap. + * Account ensure reads only this port (never dynamic-imports workspace-store). + */ + +export type DaemonCloudFlags = { + cloudOnline: boolean; + hasHostToken: boolean; +}; + +type RefreshDaemonCloudFlags = () => Promise; + +let refreshProvider: RefreshDaemonCloudFlags | null = null; + +export function registerDaemonCloudFlagsProvider( + next: RefreshDaemonCloudFlags, +): void { + refreshProvider = next; +} + +export async function refreshDaemonCloudFlags(): Promise { + if (!refreshProvider) { + return { cloudOnline: false, hasHostToken: false }; + } + try { + return await refreshProvider(); + } catch { + return { cloudOnline: false, hasHostToken: false }; + } +} diff --git a/apps/desktop/src/store/im/cloud-digest-ensure.ts b/apps/desktop/src/store/im/cloud-digest-ensure.ts new file mode 100644 index 00000000..ed703802 --- /dev/null +++ b/apps/desktop/src/store/im/cloud-digest-ensure.ts @@ -0,0 +1,75 @@ +/** + * Single-flight ensure for CloudDigestCache hydrate. + */ + +import { getCloudAuth } from "@/shared/lib/cloud-auth"; +import { cloudDigestCache } from "@/shared/lib/cloud-digest-cache"; +import { listCloudConversations } from "@/shared/lib/minos-cloud"; +import { isCloudImMode } from "@/shared/lib/cloud-timeline"; + +let hydrateInFlight: Promise | null = null; +let hydrateGeneration = 0; + +/** Cancel in-flight digest hydrate (account leave). */ +export function cancelCloudDigestHydrate(): void { + hydrateGeneration += 1; + hydrateInFlight = null; +} + +/** Hydrate CloudDigestCache once (or after invalidate). Concurrent callers share one request. */ +export async function ensureCloudDigestHydrated( + opts?: { force?: boolean }, +): Promise { + const auth = getCloudAuth(); + const accountId = auth?.accountId?.trim() ?? ""; + if ( + !auth || + !isCloudImMode({ + authPhase: auth.authPhase, + accessToken: auth.accessToken, + }) || + !auth.accessToken || + !accountId + ) { + return; + } + + if (!opts?.force && cloudDigestCache.isHydratedFor(accountId)) { + return; + } + + // Force after concurrent hydrate: wait then re-query so SnapshotRequired + // never leaves a stale cache behind a no-op await. + if (hydrateInFlight) { + await hydrateInFlight; + if (!opts?.force) { + return; + } + } + + if (!opts?.force && cloudDigestCache.isHydratedFor(accountId)) { + return; + } + + const gen = hydrateGeneration; + const deviceId = auth.deviceId; + const accessToken = auth.accessToken; + hydrateInFlight = (async () => { + try { + if (opts?.force) { + cloudDigestCache.invalidate(); + } + const digests = await listCloudConversations(deviceId, accessToken); + if (gen !== hydrateGeneration) return; + const still = getCloudAuth()?.accountId?.trim() ?? ""; + if (still !== accountId) return; + cloudDigestCache.hydrate(digests, accountId); + } finally { + if (gen === hydrateGeneration) { + hydrateInFlight = null; + } + } + })(); + + await hydrateInFlight; +} diff --git a/apps/desktop/src/store/im/im-cloud-agents.ts b/apps/desktop/src/store/im/im-cloud-agents.ts new file mode 100644 index 00000000..bf46b60f --- /dev/null +++ b/apps/desktop/src/store/im/im-cloud-agents.ts @@ -0,0 +1,152 @@ +/** + * Resolve host runtime → Hub agent_id and conversation shell upsert. + */ + +import { getCloudAuth } from "@/shared/lib/cloud-auth"; +import { + addAgentToConversation, + ensureHostRuntimeAgent, + upsertConversation, +} from "@/shared/lib/minos-cloud"; +import { + displayNameForRuntime, + normalizeHostRuntime, +} from "@/shared/lib/im-cloud-sync-helpers"; + +const runtimeAgentIdCache = new Map(); + +export function clearRuntimeAgentIdCache(): void { + runtimeAgentIdCache.clear(); +} + +function cloudAuth(): { + deviceId: string; + accessToken: string; + accountId: string; +} | null { + const auth = getCloudAuth(); + if (!auth) return null; + const accessToken = auth.accessToken.trim(); + const accountId = auth.accountId.trim(); + if (!accessToken || !accountId) return null; + return { + deviceId: auth.deviceId, + accessToken, + accountId, + }; +} + +function normalizeRuntime(runtime: string | null | undefined): string | null { + return normalizeHostRuntime(runtime); +} + +export async function resolveCloudAgentId( + runtimeAgent: string, +): Promise { + const runtime = normalizeRuntime(runtimeAgent); + if (!runtime) return null; + const cached = runtimeAgentIdCache.get(runtime); + if (cached) return cached; + + const auth = cloudAuth(); + if (!auth) return null; + + try { + const agent = await ensureHostRuntimeAgent(auth.deviceId, auth.accessToken, { + runtimeAgent: runtime, + name: displayNameForRuntime(runtime), + }); + runtimeAgentIdCache.set(runtime, agent.agentId); + return agent.agentId; + } catch (error) { + console.warn("[im-cloud-sync] ensure host runtime agent failed", runtime, error); + return null; + } +} + +export async function resolveCloudAgentIds( + runtimes: Array, +): Promise { + const unique = new Set(); + for (const r of runtimes) { + const n = normalizeRuntime(r); + if (n) unique.add(n); + } + const ids: string[] = []; + for (const runtime of unique) { + const id = await resolveCloudAgentId(runtime); + if (id) ids.push(id); + } + return ids; +} + +/** Register / refresh a Desktop work conversation on the hub (shell + roster). */ +export async function syncConversationToCloud(input: { + conversationId: string; + title: string; + memberAccountIds?: string[]; + /** Local runtime names (codex/claude/…); resolved to cloud agent ids. */ + agentRuntimes?: Array; + /** Pre-resolved cloud agent ids (optional; merged with agentRuntimes). */ + agentIds?: string[]; +}): Promise { + const auth = cloudAuth(); + if (!auth) return; + const title = input.title.trim(); + if (!title || !input.conversationId.trim()) return; + + const fromRuntimes = await resolveCloudAgentIds(input.agentRuntimes ?? []); + const agentIds = [ + ...new Set([...(input.agentIds ?? []), ...fromRuntimes].filter(Boolean)), + ]; + + try { + await upsertConversation(auth.deviceId, auth.accessToken, { + conversationId: input.conversationId, + title, + memberAccountIds: input.memberAccountIds ?? [], + agentIds, + }); + } catch (error) { + console.warn("[im-cloud-sync] upsert conversation failed", error); + } +} + +/** + * Attach host-runtime agents to an existing hub conversation without touching + * the title (used when starting a session mid-conversation). + */ +export async function attachAgentsToConversationCloud(input: { + conversationId: string; + agentRuntimes: Array; +}): Promise { + const auth = cloudAuth(); + if (!auth) return; + if (!input.conversationId.trim()) return; + const agentIds = await resolveCloudAgentIds(input.agentRuntimes); + for (const agentId of agentIds) { + try { + await addAgentToConversation( + auth.deviceId, + auth.accessToken, + input.conversationId, + agentId, + ); + } catch (error) { + console.warn( + "[im-cloud-sync] add agent to conversation failed", + agentId, + error, + ); + } + } +} + +export const RUNTIMES_FROM_ID = [ + "codex", + "claude", + "gemini", + "opencode", + "grok", +] as const; + diff --git a/apps/desktop/src/shared/lib/im-cloud-bridge.ts b/apps/desktop/src/store/im/im-cloud-bridge.ts similarity index 83% rename from apps/desktop/src/shared/lib/im-cloud-bridge.ts rename to apps/desktop/src/store/im/im-cloud-bridge.ts index c6b81e8f..cd4d144a 100644 --- a/apps/desktop/src/shared/lib/im-cloud-bridge.ts +++ b/apps/desktop/src/store/im/im-cloud-bridge.ts @@ -1,10 +1,9 @@ /** * Lifecycle bridge: Account session → Hub realtime → Desktop timeline store. * - * Hub chat messages update `messagesByConversation` directly. - * Sync Engine: conversation subscribe, resume cursors, SnapshotRequired range rebuild. - * Cold hydrate is owned by loadTimeline (subscribe-only here on open). - * No daemon_append of cloud IM into Host SQLite. + * Timeline body writes go through the sole funnel (`timeline-write`), not + * raw `messagesByConversation` setState. Cold hydrate is owned by + * loadTimeline (subscribe-only here on open). No daemon_append of cloud IM. */ import { conversationTopic } from "@/shared/lib/cloud-cursors"; @@ -12,38 +11,39 @@ import { CloudRealtimeSession, type CloudRealtimeSyncState, } from "@/shared/lib/cloud-realtime"; -import { mapCloudChatMessageToTimeline } from "@/shared/lib/im-cloud-inbound"; +import { mapCloudChatMessageToTimeline } from "@/store/im/im-cloud-inbound"; +import { isCloudImMode } from "@/shared/lib/cloud-timeline"; import { - isCloudImMode, - mergeCloudAndLocalTimeline, - removeMessageFromTimeline, - upsertCloudMessageIntoTimeline, -} from "@/shared/lib/cloud-timeline"; -import { startImOutboxWorker } from "@/shared/lib/im-cloud-sync"; + startImOutboxWorker, + stopImOutboxWorker, +} from "@/store/im/im-cloud-sync"; import { pullCloudConversationMessagePage, pullCloudForwardGap, -} from "@/shared/lib/im-cloud-inbound"; +} from "@/store/im/im-cloud-inbound"; import { - EMPTY_MESSAGE_HISTORY, MESSAGE_PAGE_SIZE, firstMessageSeq, lastMessageSeq, - mergeMessagesQuietTail, - messageHistoryFromWindow, - trimMessagesHardMax, } from "@/shared/lib/message-history"; import { cloudDigestCache } from "@/shared/lib/cloud-digest-cache"; -import { ensureCloudDigestHydrated } from "@/shared/lib/cloud-digest-ensure"; +import { ensureCloudDigestHydrated } from "@/store/im/cloud-digest-ensure"; import { positiveMs, railActivityFromTimeline, resolveDigestLastActivityMs, } from "@/shared/lib/rail-activity"; +import { getCloudAuth } from "@/shared/lib/cloud-auth"; import { useAccountStore } from "@/store/account-store"; +import { getAccountScopeGeneration } from "@/shared/lib/account-scope-generation"; import { useWorkspaceStore } from "@/store/workspace-store"; +import { + applyHubMessage, + removeRecalledMessage, + replaceWindowFromHydrate, +} from "@/store/workspace/timeline-write"; import type { CloudChatMessage } from "@/shared/lib/minos-cloud"; -import type { TimelineMessage } from "@/shared/lib/mock-data"; +import type { TimelineMessage } from "@/shared/domain/collaboration"; let session: CloudRealtimeSession | null = null; let startedForToken: string | null = null; @@ -182,8 +182,10 @@ async function onCloudChatMessage(message: CloudChatMessage): Promise { await onCloudChatMessageRecalled(message); return; } + const accountScopeGen = getAccountScopeGeneration(); const ui = await mapCloudChatMessageToTimeline(message); if (!ui) return; + if (accountScopeGen !== getAccountScopeGeneration()) return; const ws = useWorkspaceStore.getState(); const conversationId = message.conversationId; @@ -199,35 +201,16 @@ async function onCloudChatMessage(message: CloudChatMessage): Promise { // Open/focused window: apply body. Background: next open loadTimeline always // cold-pulls Hub (no separate dirty flag). if (focused || hasWindow) { - useWorkspaceStore.setState((s) => { - const prev = s.messagesByConversation[conversationId] ?? []; - const merged = upsertCloudMessageIntoTimeline(prev, ui); - const trimmed = trimMessagesHardMax(merged); - const prevHist = - s.messageHistoryByConversation[conversationId] ?? EMPTY_MESSAGE_HISTORY; - return { - messagesByConversation: { - ...s.messagesByConversation, - [conversationId]: trimmed.messages, - }, - messageHistoryByConversation: { - ...s.messageHistoryByConversation, - [conversationId]: messageHistoryFromWindow(trimmed.messages, { - prev: prevHist, - hasOlderCloud: prevHist.hasOlderCloud || trimmed.trimmed, - hasOlderHost: prevHist.hasOlderHost, - loadingOlder: false, - }), - }, - }; - }); + applyHubMessage(conversationId, ui, { accountScopeGen }); } // Live patch Hub digest + rail row (no per-project Hub re-query). - patchRailFromCloudMessage(message, { isRecall: false }); + if (accountScopeGen === getAccountScopeGeneration()) { + patchRailFromCloudMessage(message, { isRecall: false }); + } // Focused live inbound: debounce Hub mark-read (not only on open). - if (focused) { + if (focused && accountScopeGen === getAccountScopeGeneration()) { scheduleFocusedMarkRead(conversationId); } } @@ -300,8 +283,7 @@ function patchRailFromDigest(input: { preview = input.preview?.trim() || prevDigest?.preview || null; } - const myAccountId = - useAccountStore.getState().session?.accountId?.trim() ?? ""; + const myAccountId = getCloudAuth()?.accountId?.trim() ?? ""; const isOwn = Boolean(myAccountId) && input.senderAccountId === myAccountId; let unread = prevDigest?.unreadCount ?? 0; @@ -397,27 +379,12 @@ async function onCloudChatMessageRecalled(message: CloudChatMessage): Promise { - if ( - !Object.prototype.hasOwnProperty.call( - s.messagesByConversation, - conversationId, - ) - ) { - return s; - } - const prev = s.messagesByConversation[conversationId]; - const next = removeMessageFromTimeline(prev, messageId); - if (next === prev) return s; - return { - messagesByConversation: { - ...s.messagesByConversation, - [conversationId]: next, - }, - }; - }); - patchRailFromCloudMessage(message, { isRecall: true }); + removeRecalledMessage(conversationId, messageId, { accountScopeGen }); + if (accountScopeGen === getAccountScopeGeneration()) { + patchRailFromCloudMessage(message, { isRecall: true }); + } } function conversationIdFromTopic(topic: string): string | null { @@ -463,6 +430,7 @@ async function onSnapshotRequired(topic: string): Promise { async function reconcileConversationFromCloud( conversationId: string, ): Promise { + const accountScopeGen = getAccountScopeGeneration(); const prev = useWorkspaceStore.getState().messagesByConversation[conversationId] ?? []; const maxSeq = lastMessageSeq(prev); @@ -542,51 +510,36 @@ async function reconcileConversationFromCloud( /* reaction store optional in tests */ } - useWorkspaceStore.setState((s) => { - const localPrev = s.messagesByConversation[conversationId] ?? []; - const prevHist = - s.messageHistoryByConversation[conversationId] ?? EMPTY_MESSAGE_HISTORY; - // Quiet-tail union keeps previously loaded older pages across snapshot. - const withTail = - localPrev.length > 0 - ? mergeMessagesQuietTail(localPrev, cloudRows) - : cloudRows; - const merged = mergeCloudAndLocalTimeline({ - cloudMessages: cloudRows, - localMessages: withTail, - }); - const trimmed = trimMessagesHardMax(merged); - const cloudHasOlder = - latestPage.nextBeforeSeq != null || - latestPage.rawCount >= MESSAGE_PAGE_SIZE || - trimmed.trimmed; - return { - messagesByConversation: { - ...s.messagesByConversation, - [conversationId]: trimmed.messages, - }, - messageHistoryByConversation: { - ...s.messageHistoryByConversation, - [conversationId]: messageHistoryFromWindow(trimmed.messages, { - prev: prevHist, - hasOlderCloud: prevHist.hasOlderCloud || cloudHasOlder, - hasOlderHost: prevHist.hasOlderHost || trimmed.trimmed, - loadingOlder: false, - }), - }, - }; + // Quiet-tail union keeps previously loaded older pages across snapshot. + if (accountScopeGen !== getAccountScopeGeneration()) return; + const cloudHasOlder = + latestPage.nextBeforeSeq != null || + latestPage.rawCount >= MESSAGE_PAGE_SIZE; + replaceWindowFromHydrate(conversationId, { + mode: "quiet-tail", + cloudMessages: cloudRows, + history: { + hasOlderCloud: cloudHasOlder, + loadingOlder: false, + }, + accountScopeGen, }); } /** Start or refresh hub WS when Minos account session is available. */ export function ensureImCloudBridge(): void { - const { deviceId, session: account, authPhase } = useAccountStore.getState(); - if (authPhase !== "authenticated" || !account?.accessToken?.trim()) { + const auth = getCloudAuth(); + if ( + !auth || + auth.authPhase !== "authenticated" || + !auth.accessToken.trim() + ) { stopImCloudBridge(); return; } - const token = account.accessToken; - const accountId = account.accountId ?? ""; + const deviceId = auth.deviceId; + const token = auth.accessToken; + const accountId = auth.accountId; if (session && startedForToken === token) { session.updateAuth(deviceId, token, accountId); // Keep focused conversation subscribed. @@ -610,8 +563,7 @@ export function ensureImCloudBridge(): void { onMessageReactions: ({ messageId, reactions }) => { void import("@/features/chat/reaction-store").then(({ useReactionStore }) => { // Durable wire is viewer-neutral; recompute reactedByMe from local account. - const myAccountId = - useAccountStore.getState().session?.accountId?.trim() ?? ""; + const myAccountId = getCloudAuth()?.accountId?.trim() ?? ""; useReactionStore.getState().applyServerReactions( messageId, reactions.map((g) => { @@ -658,12 +610,20 @@ export function ensureImCloudBridge(): void { } export function stopImCloudBridge(): void { + stopImOutboxWorker(); session?.stop(); session = null; startedForToken = null; lastSyncState = "disconnected"; useAccountStore.getState().syncAccountFromCloud("disconnected"); cancelPendingFocusedMarkRead(); + // Account leave / stop must not keep unread id set across sessions. + unreadCountedMessageIds.clear(); +} + +/** Clear process-local unread dedupe (account leave). */ +export function clearImCloudBridgeUnreadDedupe(): void { + unreadCountedMessageIds.clear(); } export function getCloudRealtimeState(): CloudRealtimeSyncState { @@ -680,6 +640,8 @@ export async function appendMessageOnCloud(input: { conversationId: string; text: string; replyToMessageId?: string | null; + /** When set, refuse to send if the live bridge session is a different account. */ + expectedAccountId?: string; mentions?: Array< | { kind: "bot"; @@ -707,6 +669,13 @@ export async function appendMessageOnCloud(input: { if (!session) { return { ok: false, reason: "socket" }; } + const expected = input.expectedAccountId?.trim(); + if (expected) { + const liveAccount = useAccountStore.getState().session?.accountId?.trim() ?? ""; + if (!liveAccount || liveAccount !== expected) { + return { ok: false, reason: "socket" }; + } + } const result = await session.sendAppendMessage({ clientOperationId: input.clientOperationId, conversationId: input.conversationId, @@ -772,11 +741,11 @@ export function tryAppendMessageOnCloud(input: { export function ensureConversationSubscribedOnCloud(conversationId: string): void { if (!conversationId.trim()) return; ensureImCloudBridge(); - const { session: account, authPhase } = useAccountStore.getState(); + const auth = getCloudAuth(); if ( !isCloudImMode({ - authPhase, - accessToken: account?.accessToken, + authPhase: auth?.authPhase, + accessToken: auth?.accessToken, }) ) { return; @@ -800,20 +769,21 @@ export async function recallMessageOnCloud( conversationId: string, messageId: string, ): Promise { - const { deviceId, session, authPhase } = useAccountStore.getState(); + const auth = getCloudAuth(); if ( + !auth || !isCloudImMode({ - authPhase, - accessToken: session?.accessToken, + authPhase: auth.authPhase, + accessToken: auth.accessToken, }) || - !session?.accessToken + !auth.accessToken ) { throw new Error("Hub recall requires authenticated account"); } const { recallCloudMessage } = await import("@/shared/lib/minos-cloud"); const recalled = await recallCloudMessage( - deviceId, - session.accessToken, + auth.deviceId, + auth.accessToken, conversationId, messageId, ); diff --git a/apps/desktop/src/shared/lib/im-cloud-inbound.ts b/apps/desktop/src/store/im/im-cloud-inbound.ts similarity index 93% rename from apps/desktop/src/shared/lib/im-cloud-inbound.ts rename to apps/desktop/src/store/im/im-cloud-inbound.ts index 2ef7fdfa..d1e9be6e 100644 --- a/apps/desktop/src/shared/lib/im-cloud-inbound.ts +++ b/apps/desktop/src/store/im/im-cloud-inbound.ts @@ -14,10 +14,10 @@ import { type CloudChatMessage, type CloudMessagePage, } from "@/shared/lib/minos-cloud"; +import { getCloudAuth } from "@/shared/lib/cloud-auth"; import { cloudChatMessageToTimeline } from "@/shared/lib/cloud-timeline"; -import { useAccountStore } from "@/store/account-store"; -import { markMessageProjected } from "@/shared/lib/im-cloud-sync"; -import type { TimelineMessage } from "@/shared/lib/mock-data"; +import { markMessageProjected } from "@/store/im/im-cloud-sync"; +import type { TimelineMessage } from "@/shared/domain/collaboration"; import { MESSAGE_PAGE_SIZE } from "@/shared/lib/message-history"; /** cloud agent_id → runtime bin name (codex/claude/…) */ @@ -26,9 +26,9 @@ let agentsLoadedAt = 0; const AGENTS_TTL_MS = 60_000; function cloudAuth(): { deviceId: string; accessToken: string } | null { - const { deviceId, session } = useAccountStore.getState(); - if (!session?.accessToken?.trim()) return null; - return { deviceId, accessToken: session.accessToken }; + const auth = getCloudAuth(); + if (!auth?.accessToken?.trim()) return null; + return { deviceId: auth.deviceId, accessToken: auth.accessToken }; } export async function ensureAgentRuntimeMap(): Promise> { diff --git a/apps/desktop/src/store/im/im-cloud-outbox-posts.ts b/apps/desktop/src/store/im/im-cloud-outbox-posts.ts new file mode 100644 index 00000000..5246bea7 --- /dev/null +++ b/apps/desktop/src/store/im/im-cloud-outbox-posts.ts @@ -0,0 +1,351 @@ +/** + * Per-kind outbox post implementations (Account WS / Hub REST / daemon). + */ + +import { getCloudAuth } from "@/shared/lib/cloud-auth"; +import { getAccountScopeGeneration } from "@/shared/lib/account-scope-generation"; +import { isCloudImMode } from "@/shared/lib/cloud-timeline"; +import { sessionIdFromAgentResultId } from "@/shared/lib/cloud-timeline"; +import { + respondCloudApproval, + sendAgentConversationMessage, + toggleCloudReaction, +} from "@/shared/lib/minos-cloud"; +import type { ImOutboxEntry } from "@/shared/lib/im-outbox"; +import { daemonApi } from "@/shared/lib/daemon"; +import { appendMessageOnCloud } from "@/store/im/im-cloud-bridge"; +import { + attachAgentsToConversationCloud, + resolveCloudAgentId, + RUNTIMES_FROM_ID, + syncConversationToCloud, +} from "@/store/im/im-cloud-agents"; + +function cloudAuth(): { + deviceId: string; + accessToken: string; + accountId: string; +} | null { + const auth = getCloudAuth(); + if (!auth) return null; + const accessToken = auth.accessToken.trim(); + const accountId = auth.accountId.trim(); + if (!accessToken || !accountId) return null; + return { + deviceId: auth.deviceId, + accessToken, + accountId, + }; +} + +export type CloudUserMessageAck = { + messageId: string; + messageSeq: number; + conversationId: string; +}; + +async function postUserMessageFromOutbox( + entry: ImOutboxEntry, + scope: { accountId: string; scopeGeneration: number }, +): Promise { + const auth = cloudAuth(); + if (!auth) { + throw new Error("Not signed in — message not synced to cloud"); + } + if ( + auth.accountId !== scope.accountId || + entry.accountId.trim() !== scope.accountId || + getAccountScopeGeneration() !== scope.scopeGeneration + ) { + throw new Error("Outbox send aborted: account scope changed"); + } + + // Never upsert Hub with the "Conversation" placeholder — that clobbers real + // titles on every host_projection message. Only push a real title; agents-only + // attach uses attachAgentsToConversationCloud when title is missing. + const realTitle = entry.title?.trim() ?? ""; + const isPlaceholder = + !realTitle || realTitle.toLowerCase() === "conversation"; + if (!isPlaceholder) { + await syncConversationToCloud({ + conversationId: entry.conversationId, + title: realTitle, + agentRuntimes: entry.agentRuntimes, + }); + } else if ((entry.agentRuntimes?.length ?? 0) > 0) { + await attachAgentsToConversationCloud({ + conversationId: entry.conversationId, + agentRuntimes: entry.agentRuntimes ?? [], + }); + } + + if ( + getAccountScopeGeneration() !== scope.scopeGeneration || + cloudAuth()?.accountId !== scope.accountId + ) { + throw new Error("Outbox send aborted: account scope changed"); + } + + // Linked Hub-first sends use client_live so Hub can @-dispatch. + // Entries without explicit source default to client_live. + const messageSource = entry.messageSource ?? "client_live"; + + // Account WS AppendMessage only (no REST collaboration write path). + // Wait for ChatSendAck before treating outbox as success. + // Socket/timeout → retry via outbox; definitive nack fails the entry. + if (messageSource !== "client_live") { + // host_projection / system user rows are not collaboration writes here. + // Agent final text uses postAgentResultFromOutbox. + throw new Error( + `Unsupported user-message source for Hub uplink: ${messageSource}`, + ); + } + + const wsResult = await appendMessageOnCloud({ + clientOperationId: entry.clientMessageId, + conversationId: entry.conversationId, + text: entry.text, + replyToMessageId: entry.replyToMessageId, + expectedAccountId: scope.accountId, + mentions: entry.mentions, + }); + if (wsResult.ok) { + if ( + getAccountScopeGeneration() !== scope.scopeGeneration || + cloudAuth()?.accountId !== scope.accountId + ) { + throw new Error("Outbox send aborted: account scope changed"); + } + return { + messageId: wsResult.messageId, + messageSeq: wsResult.messageSeq, + conversationId: wsResult.conversationId, + }; + } + if (wsResult.reason === "nack") { + throw new Error( + `ChatSendNack: ${wsResult.code ?? "nack"}${ + wsResult.message ? ` — ${wsResult.message}` : "" + }`, + ); + } + throw new Error( + wsResult.reason === "timeout" + ? "AppendMessage timed out waiting for ChatSendAck" + : "AppendMessage unavailable (Account WS not live)", + ); +} + +async function postAgentResultFromOutbox(entry: ImOutboxEntry): Promise { + const auth = cloudAuth(); + if (!auth) { + throw new Error("Not signed in — agent result not synced to cloud"); + } + + let agentId = entry.agentId?.trim() || null; + if (!agentId) { + const runtime = + entry.agentRuntimes?.find((r) => !!r?.trim()) ?? + RUNTIMES_FROM_ID.find((r) => + entry.clientMessageId.toLowerCase().includes(r), + ) ?? + null; + if (runtime) { + agentId = await resolveCloudAgentId(runtime); + } + } + if (!agentId) { + throw new Error("agent_result uplink: no cloud agent id"); + } + + const sessionId = + entry.agentSessionId?.trim() || + sessionIdFromAgentResultId(entry.clientMessageId) || + undefined; + + await sendAgentConversationMessage( + auth.deviceId, + auth.accessToken, + entry.conversationId, + { + agentId, + text: entry.text, + clientMessageId: entry.clientMessageId, + agentSessionId: sessionId, + replyToMessageId: entry.replyToMessageId ?? undefined, + messageSource: "host_projection", + }, + ); +} + +export type CloudReactionToggleResult = { + messageId: string; + conversationId: string; + action: string; + reactions: Array<{ + emoji: string; + count: number; + reactedByMe: boolean; + actors: Array<{ + actorId: string; + actorKind: string; + displayName: string; + }>; + }>; +}; + +async function postReactionToggleFromOutbox( + entry: ImOutboxEntry, +): Promise { + const auth = cloudAuth(); + if (!auth) { + throw new Error("not authenticated"); + } + let payload: { messageId?: string; emoji?: string }; + try { + payload = JSON.parse(entry.text) as { messageId?: string; emoji?: string }; + } catch { + throw new Error("invalid_payload: reaction_toggle text is not JSON"); + } + const messageId = payload.messageId?.trim() ?? ""; + const emoji = payload.emoji?.trim() ?? ""; + if (!messageId || !emoji) { + throw new Error("invalid_payload: reaction_toggle requires messageId+emoji"); + } + // clientMessageId == wire client_op_id; retries reuse the same id. + return toggleCloudReaction( + auth.deviceId, + auth.accessToken, + entry.conversationId, + messageId, + emoji, + entry.clientMessageId, + ); +} + +/** + * Treat daemon/Hub "already resolved" as success so outbox retries after a + * successful-but-unacked first attempt do not burn the entry. + */ +function isApprovalAlreadyResolvedError(error: unknown): boolean { + const code = + error && typeof error === "object" && "code" in error + ? String((error as { code: unknown }).code ?? "").toLowerCase() + : ""; + const msg = (error instanceof Error ? error.message : String(error)).toLowerCase(); + // Only treat explicit already-resolved / approval_not_found as success. + // Broad "not found" would mask unrelated 404s and burn retries incorrectly. + return ( + code.includes("already_resolved") || + code.includes("approval_already") || + code.includes("approval_not_found") || + msg.includes("already_resolved") || + msg.includes("already resolved") || + msg.includes("approval_already") || + msg.includes("approval_not_found") || + msg.includes("approval not found") + ); +} + +/** + * Branch by auth mode (no dual SSOT): + * - Hub IM mode: POST /v1/approvals/respond + top-level client_request_id + * - Local-only: daemon resolveApproval; decision JSON never carries client_request_id + */ +async function postApprovalResolveFromOutbox( + entry: ImOutboxEntry, +): Promise { + let payload: { + requestId?: string; + sessionId?: string; + decision?: string | Record; + /** Explicit route stamped at enqueue (`hub` | `daemon`). */ + route?: string; + }; + try { + payload = JSON.parse(entry.text) as typeof payload; + } catch { + throw new Error("invalid_payload: approval_resolve text is not JSON"); + } + const requestId = payload.requestId?.trim() ?? ""; + const sessionId = payload.sessionId?.trim() ?? ""; + if (!requestId || !sessionId || payload.decision == null) { + throw new Error( + "invalid_payload: approval_resolve requires requestId+sessionId+decision", + ); + } + // Clean agent decision only — never nest client_request_id in decision JSON. + const decision = + typeof payload.decision === "string" + ? { decision: payload.decision } + : { ...payload.decision }; + delete (decision as Record).client_request_id; + + const authSnap = getCloudAuth(); + const cloudRoute = + payload.route === "hub" || + (payload.route !== "daemon" && + isCloudImMode({ + authPhase: authSnap?.authPhase, + accessToken: authSnap?.accessToken, + })); + + try { + if (cloudRoute) { + const auth = cloudAuth(); + if (!auth) { + throw new Error("not authenticated"); + } + // Top-level client_request_id = outbox logical op id (Intent Outbox). + await respondCloudApproval(auth.deviceId, auth.accessToken, { + requestId, + decision, + clientRequestId: entry.clientMessageId, + }); + } else { + await daemonApi.resolveApproval(requestId, sessionId, decision); + } + } catch (error) { + if (isApprovalAlreadyResolvedError(error)) { + return; + } + throw error; + } +} + +export type OutboxScope = { accountId: string; scopeGeneration: number }; + +export async function postOutboxEntry( + entry: ImOutboxEntry, + scope: OutboxScope, +): Promise { + if ( + entry.accountId.trim() !== scope.accountId || + getAccountScopeGeneration() !== scope.scopeGeneration || + cloudAuth()?.accountId !== scope.accountId + ) { + throw new Error("Outbox send aborted: account scope changed"); + } + switch (entry.kind) { + case "user_message": + return postUserMessageFromOutbox(entry, scope); + case "agent_result": + await postAgentResultFromOutbox(entry); + return; + case "reaction_toggle": + return postReactionToggleFromOutbox(entry); + case "approval_resolve": + await postApprovalResolveFromOutbox(entry); + return; + default: { + const _exhaustive: never = entry.kind; + throw new Error(`unknown outbox kind: ${_exhaustive}`); + } + } +} + +/** + * Single path: enqueue reaction_toggle then drain via lane worker. + * Returns Hub aggregate for generation-gated apply (from worker side map). + * Logical op id = clientOpId (= wire client_op_id); row id = outbox:${clientOpId}. + */ diff --git a/apps/desktop/src/shared/lib/im-cloud-sync.ts b/apps/desktop/src/store/im/im-cloud-sync.ts similarity index 54% rename from apps/desktop/src/shared/lib/im-cloud-sync.ts rename to apps/desktop/src/store/im/im-cloud-sync.ts index 17d4030e..d79644e4 100644 --- a/apps/desktop/src/shared/lib/im-cloud-sync.ts +++ b/apps/desktop/src/store/im/im-cloud-sync.ts @@ -9,23 +9,36 @@ * Conversation shell upsert + host-runtime agent resolve remain. */ -import { useAccountStore } from "@/store/account-store"; +import { getCloudAuth } from "@/shared/lib/cloud-auth"; import { - addAgentToConversation, - ensureHostRuntimeAgent, - respondCloudApproval, - sendAgentConversationMessage, - toggleCloudReaction, - upsertConversation, -} from "@/shared/lib/minos-cloud"; + getAccountScopeGeneration, +} from "@/shared/lib/account-scope-generation"; import { isCloudImMode } from "@/shared/lib/cloud-timeline"; -import { appendMessageOnCloud } from "@/shared/lib/im-cloud-bridge"; import { - displayNameForRuntime, isCanonicalAgentResultId, isProjectableAgentMessage, normalizeHostRuntime, } from "@/shared/lib/im-cloud-sync-helpers"; + +import { + clearRuntimeAgentIdCache, + resolveCloudAgentId, + RUNTIMES_FROM_ID, +} from "@/store/im/im-cloud-agents"; +import { + postOutboxEntry, + type CloudUserMessageAck, + type CloudReactionToggleResult, + type OutboxScope, +} from "@/store/im/im-cloud-outbox-posts"; +export type { CloudUserMessageAck, CloudReactionToggleResult } from "@/store/im/im-cloud-outbox-posts"; +export { + resolveCloudAgentId, + resolveCloudAgentIds, + syncConversationToCloud, + attachAgentsToConversationCloud, +} from "@/store/im/im-cloud-agents"; + import { sessionIdFromAgentResultId } from "@/shared/lib/cloud-timeline"; import { enqueueAgentResult, @@ -45,9 +58,8 @@ import { reclaimStaleInflight, type ImOutboxEntry, } from "@/shared/lib/im-outbox"; -import { daemonApi } from "@/shared/lib/daemon"; import { toast } from "@/shared/lib/toast"; -import type { TimelineMessage } from "@/shared/lib/mock-data"; +import type { TimelineMessage } from "@/shared/domain/collaboration"; export { displayNameForRuntime, @@ -56,8 +68,6 @@ export { } from "@/shared/lib/im-cloud-sync-helpers"; /** In-memory runtime → cloud agent_id for this process. */ -const runtimeAgentIdCache = new Map(); - /** Track acked / seen hub message ids (user outbox + inbound echo). */ const projectedMessageIds = new Set(); const MAX_PROJECTED_CACHE = 4000; @@ -65,8 +75,12 @@ const MAX_PROJECTED_CACHE = 4000; /** Per-lane drain chains — different conversations / intent classes parallelize. */ const laneChains = new Map>(); let outboxWorkerTimer: ReturnType | null = null; +/** Bumped on account leave so scheduled drains cannot flush under a new session. */ +let outboxWorkerGeneration = 0; /** Last successful reaction toggle payload by client op id (for waiters). */ +const userMessageAcks = new Map(); + const reactionResults = new Map< string, { @@ -86,10 +100,25 @@ const reactionResults = new Map< } >(); -function cloudAuth(): { deviceId: string; accessToken: string } | null { - const { deviceId, session } = useAccountStore.getState(); - if (!session?.accessToken?.trim()) return null; - return { deviceId, accessToken: session.accessToken }; +function cloudAuth(): { + deviceId: string; + accessToken: string; + accountId: string; +} | null { + const auth = getCloudAuth(); + if (!auth) return null; + const accessToken = auth.accessToken.trim(); + const accountId = auth.accountId.trim(); + if (!accessToken || !accountId) return null; + return { + deviceId: auth.deviceId, + accessToken, + accountId, + }; +} + +function currentOutboxAccountId(): string { + return cloudAuth()?.accountId ?? ""; } function normalizeRuntime(runtime: string | null | undefined): string | null { @@ -121,397 +150,6 @@ export function markMessageProjected(messageId: string): void { * Resolve local agent bin name → cloud agent_id via ensure-host-runtime. * Never treats the bin name itself as a cloud agent_id. */ -export async function resolveCloudAgentId( - runtimeAgent: string, -): Promise { - const runtime = normalizeRuntime(runtimeAgent); - if (!runtime) return null; - const cached = runtimeAgentIdCache.get(runtime); - if (cached) return cached; - - const auth = cloudAuth(); - if (!auth) return null; - - try { - const agent = await ensureHostRuntimeAgent(auth.deviceId, auth.accessToken, { - runtimeAgent: runtime, - name: displayNameForRuntime(runtime), - }); - runtimeAgentIdCache.set(runtime, agent.agentId); - return agent.agentId; - } catch (error) { - console.warn("[im-cloud-sync] ensure host runtime agent failed", runtime, error); - return null; - } -} - -export async function resolveCloudAgentIds( - runtimes: Array, -): Promise { - const unique = new Set(); - for (const r of runtimes) { - const n = normalizeRuntime(r); - if (n) unique.add(n); - } - const ids: string[] = []; - for (const runtime of unique) { - const id = await resolveCloudAgentId(runtime); - if (id) ids.push(id); - } - return ids; -} - -/** Register / refresh a Desktop work conversation on the hub (shell + roster). */ -export async function syncConversationToCloud(input: { - conversationId: string; - title: string; - memberAccountIds?: string[]; - /** Local runtime names (codex/claude/…); resolved to cloud agent ids. */ - agentRuntimes?: Array; - /** Pre-resolved cloud agent ids (optional; merged with agentRuntimes). */ - agentIds?: string[]; -}): Promise { - const auth = cloudAuth(); - if (!auth) return; - const title = input.title.trim(); - if (!title || !input.conversationId.trim()) return; - - const fromRuntimes = await resolveCloudAgentIds(input.agentRuntimes ?? []); - const agentIds = [ - ...new Set([...(input.agentIds ?? []), ...fromRuntimes].filter(Boolean)), - ]; - - try { - await upsertConversation(auth.deviceId, auth.accessToken, { - conversationId: input.conversationId, - title, - memberAccountIds: input.memberAccountIds ?? [], - agentIds, - }); - } catch (error) { - console.warn("[im-cloud-sync] upsert conversation failed", error); - } -} - -/** - * Attach host-runtime agents to an existing hub conversation without touching - * the title (used when starting a session mid-conversation). - */ -export async function attachAgentsToConversationCloud(input: { - conversationId: string; - agentRuntimes: Array; -}): Promise { - const auth = cloudAuth(); - if (!auth) return; - if (!input.conversationId.trim()) return; - const agentIds = await resolveCloudAgentIds(input.agentRuntimes); - for (const agentId of agentIds) { - try { - await addAgentToConversation( - auth.deviceId, - auth.accessToken, - input.conversationId, - agentId, - ); - } catch (error) { - console.warn( - "[im-cloud-sync] add agent to conversation failed", - agentId, - error, - ); - } - } -} - -const RUNTIMES_FROM_ID = [ - "codex", - "claude", - "gemini", - "opencode", - "grok", -] as const; - -export type CloudUserMessageAck = { - messageId: string; - messageSeq: number; - conversationId: string; -}; - -const userMessageAcks = new Map(); - -async function postUserMessageFromOutbox( - entry: ImOutboxEntry, -): Promise { - const auth = cloudAuth(); - if (!auth) { - throw new Error("Not signed in — message not synced to cloud"); - } - - // Never upsert Hub with the "Conversation" placeholder — that clobbers real - // titles on every host_projection message. Only push a real title; agents-only - // attach uses attachAgentsToConversationCloud when title is missing. - const realTitle = entry.title?.trim() ?? ""; - const isPlaceholder = - !realTitle || realTitle.toLowerCase() === "conversation"; - if (!isPlaceholder) { - await syncConversationToCloud({ - conversationId: entry.conversationId, - title: realTitle, - agentRuntimes: entry.agentRuntimes, - }); - } else if ((entry.agentRuntimes?.length ?? 0) > 0) { - await attachAgentsToConversationCloud({ - conversationId: entry.conversationId, - agentRuntimes: entry.agentRuntimes ?? [], - }); - } - - // Linked Hub-first sends use client_live so Hub can @-dispatch. - // Entries without explicit source default to client_live. - const messageSource = entry.messageSource ?? "client_live"; - - // Account WS AppendMessage only (no REST collaboration write path). - // Wait for ChatSendAck before treating outbox as success. - // Socket/timeout → retry via outbox; definitive nack fails the entry. - if (messageSource !== "client_live") { - // host_projection / system user rows are not collaboration writes here. - // Agent final text uses postAgentResultFromOutbox. - throw new Error( - `Unsupported user-message source for Hub uplink: ${messageSource}`, - ); - } - - const wsResult = await appendMessageOnCloud({ - clientOperationId: entry.clientMessageId, - conversationId: entry.conversationId, - text: entry.text, - replyToMessageId: entry.replyToMessageId, - mentions: entry.mentions, - }); - if (wsResult.ok) { - return { - messageId: wsResult.messageId, - messageSeq: wsResult.messageSeq, - conversationId: wsResult.conversationId, - }; - } - if (wsResult.reason === "nack") { - throw new Error( - `ChatSendNack: ${wsResult.code ?? "nack"}${ - wsResult.message ? ` — ${wsResult.message}` : "" - }`, - ); - } - throw new Error( - wsResult.reason === "timeout" - ? "AppendMessage timed out waiting for ChatSendAck" - : "AppendMessage unavailable (Account WS not live)", - ); -} - -async function postAgentResultFromOutbox(entry: ImOutboxEntry): Promise { - const auth = cloudAuth(); - if (!auth) { - throw new Error("Not signed in — agent result not synced to cloud"); - } - - let agentId = entry.agentId?.trim() || null; - if (!agentId) { - const runtime = - entry.agentRuntimes?.find((r) => !!r?.trim()) ?? - RUNTIMES_FROM_ID.find((r) => - entry.clientMessageId.toLowerCase().includes(r), - ) ?? - null; - if (runtime) { - agentId = await resolveCloudAgentId(runtime); - } - } - if (!agentId) { - throw new Error("agent_result uplink: no cloud agent id"); - } - - const sessionId = - entry.agentSessionId?.trim() || - sessionIdFromAgentResultId(entry.clientMessageId) || - undefined; - - await sendAgentConversationMessage( - auth.deviceId, - auth.accessToken, - entry.conversationId, - { - agentId, - text: entry.text, - clientMessageId: entry.clientMessageId, - agentSessionId: sessionId, - replyToMessageId: entry.replyToMessageId ?? undefined, - messageSource: "host_projection", - }, - ); -} - -export type CloudReactionToggleResult = { - messageId: string; - conversationId: string; - action: string; - reactions: Array<{ - emoji: string; - count: number; - reactedByMe: boolean; - actors: Array<{ - actorId: string; - actorKind: string; - displayName: string; - }>; - }>; -}; - -async function postReactionToggleFromOutbox( - entry: ImOutboxEntry, -): Promise { - const auth = cloudAuth(); - if (!auth) { - throw new Error("not authenticated"); - } - let payload: { messageId?: string; emoji?: string }; - try { - payload = JSON.parse(entry.text) as { messageId?: string; emoji?: string }; - } catch { - throw new Error("invalid_payload: reaction_toggle text is not JSON"); - } - const messageId = payload.messageId?.trim() ?? ""; - const emoji = payload.emoji?.trim() ?? ""; - if (!messageId || !emoji) { - throw new Error("invalid_payload: reaction_toggle requires messageId+emoji"); - } - // clientMessageId == wire client_op_id; retries reuse the same id. - return toggleCloudReaction( - auth.deviceId, - auth.accessToken, - entry.conversationId, - messageId, - emoji, - entry.clientMessageId, - ); -} - -/** - * Treat daemon/Hub "already resolved" as success so outbox retries after a - * successful-but-unacked first attempt do not burn the entry. - */ -function isApprovalAlreadyResolvedError(error: unknown): boolean { - const code = - error && typeof error === "object" && "code" in error - ? String((error as { code: unknown }).code ?? "").toLowerCase() - : ""; - const msg = (error instanceof Error ? error.message : String(error)).toLowerCase(); - // Only treat explicit already-resolved / approval_not_found as success. - // Broad "not found" would mask unrelated 404s and burn retries incorrectly. - return ( - code.includes("already_resolved") || - code.includes("approval_already") || - code.includes("approval_not_found") || - msg.includes("already_resolved") || - msg.includes("already resolved") || - msg.includes("approval_already") || - msg.includes("approval_not_found") || - msg.includes("approval not found") - ); -} - -/** - * Branch by auth mode (no dual SSOT): - * - Hub IM mode: POST /v1/approvals/respond + top-level client_request_id - * - Local-only: daemon resolveApproval; decision JSON never carries client_request_id - */ -async function postApprovalResolveFromOutbox( - entry: ImOutboxEntry, -): Promise { - let payload: { - requestId?: string; - sessionId?: string; - decision?: string | Record; - /** Explicit route stamped at enqueue (`hub` | `daemon`). */ - route?: string; - }; - try { - payload = JSON.parse(entry.text) as typeof payload; - } catch { - throw new Error("invalid_payload: approval_resolve text is not JSON"); - } - const requestId = payload.requestId?.trim() ?? ""; - const sessionId = payload.sessionId?.trim() ?? ""; - if (!requestId || !sessionId || payload.decision == null) { - throw new Error( - "invalid_payload: approval_resolve requires requestId+sessionId+decision", - ); - } - // Clean agent decision only — never nest client_request_id in decision JSON. - const decision = - typeof payload.decision === "string" - ? { decision: payload.decision } - : { ...payload.decision }; - delete (decision as Record).client_request_id; - - const { session, authPhase } = useAccountStore.getState(); - const cloudRoute = - payload.route === "hub" || - (payload.route !== "daemon" && - isCloudImMode({ - authPhase, - accessToken: session?.accessToken, - })); - - try { - if (cloudRoute) { - const auth = cloudAuth(); - if (!auth) { - throw new Error("not authenticated"); - } - // Top-level client_request_id = outbox logical op id (Intent Outbox). - await respondCloudApproval(auth.deviceId, auth.accessToken, { - requestId, - decision, - clientRequestId: entry.clientMessageId, - }); - } else { - await daemonApi.resolveApproval(requestId, sessionId, decision); - } - } catch (error) { - if (isApprovalAlreadyResolvedError(error)) { - return; - } - throw error; - } -} - -async function postOutboxEntry( - entry: ImOutboxEntry, -): Promise { - switch (entry.kind) { - case "user_message": - return postUserMessageFromOutbox(entry); - case "agent_result": - await postAgentResultFromOutbox(entry); - return; - case "reaction_toggle": - return postReactionToggleFromOutbox(entry); - case "approval_resolve": - await postApprovalResolveFromOutbox(entry); - return; - default: { - const _exhaustive: never = entry.kind; - throw new Error(`unknown outbox kind: ${_exhaustive}`); - } - } -} - -/** - * Single path: enqueue reaction_toggle then drain via lane worker. - * Returns Hub aggregate for generation-gated apply (from worker side map). - * Logical op id = clientOpId (= wire client_op_id); row id = outbox:${clientOpId}. - */ export async function syncReactionToggleToCloud(input: { conversationId: string; messageId: string; @@ -528,13 +166,14 @@ export async function syncReactionToggleToCloud(input: { if (await isAcked(clientOpId)) { return reactionResults.get(clientOpId) ?? null; } - if (!cloudAuth()) { + const auth = cloudAuth(); + if (!auth) { throw new Error("not authenticated"); } - const entry = await enqueueReactionToggle({ conversationId, clientMessageId: clientOpId, + accountId: auth.accountId, text: JSON.stringify({ messageId, emoji }), }); if (entry.status === "acked" || (await isAcked(clientOpId))) { @@ -575,17 +214,22 @@ export async function syncApprovalResolve(input: { const decision = { ...input.decision }; delete decision.client_request_id; - const { session, authPhase } = useAccountStore.getState(); + const authSnap = getCloudAuth(); const route = input.route ?? (isCloudImMode({ - authPhase, - accessToken: session?.accessToken, + authPhase: authSnap?.authPhase, + accessToken: authSnap?.accessToken, }) ? "hub" : "daemon"); - if (route === "hub" && !cloudAuth()) { + const auth = cloudAuth(); + if (route === "hub" && !auth) { + throw new Error("not authenticated"); + } + const accountId = auth?.accountId ?? authSnap?.accountId?.trim() ?? ""; + if (!accountId) { throw new Error("not authenticated"); } @@ -593,6 +237,7 @@ export async function syncApprovalResolve(input: { // Scope key for local storage only (not a Hub conversation id). conversationId: `approval-session:${sessionId}`, clientMessageId: clientOpId, + accountId, text: JSON.stringify({ requestId, sessionId, @@ -609,9 +254,12 @@ export async function syncApprovalResolve(input: { }); } +export { deliveryStatusAfterUserSettlement } from "@/shared/lib/user-message-settlement"; + /** * Enqueue a user timeline message then drain via per-conversation message lane. * Surfaces toast on terminal failure (multi-end intent must not silent-succeed). + * Resolves only when outbox is acked — never treats timeout as success. */ export async function syncUserMessageToCloud(input: { conversationId: string; @@ -631,10 +279,14 @@ export async function syncUserMessageToCloud(input: { mentions?: ImOutboxEntry["mentions"]; }): Promise { const auth = cloudAuth(); - if (!auth) return null; + if (!auth) { + throw new Error("not authenticated"); + } const text = input.text.trim(); const messageId = input.messageId.trim(); - if (!text || !input.conversationId.trim() || !messageId) return null; + if (!text || !input.conversationId.trim() || !messageId) { + throw new Error("invalid user message for cloud sync"); + } if (await isAcked(messageId)) { return userMessageAcks.get(messageId) ?? null; } @@ -642,6 +294,7 @@ export async function syncUserMessageToCloud(input: { await enqueueUserMessage({ conversationId: input.conversationId, clientMessageId: messageId, + accountId: auth.accountId, text, title: input.title, replyToMessageId: input.replyToMessageId, @@ -651,7 +304,16 @@ export async function syncUserMessageToCloud(input: { mentions: input.mentions, }); - await waitForOutboxSettlement(messageId, { throwOnTerminal: true }); + const settlement = await waitForOutboxSettlement(messageId, { + throwOnTerminal: true, + }); + if (settlement !== "acked") { + // timeout (failed_terminal already throws when throwOnTerminal) + throw new Error( + "Cloud sync timed out — message still pending delivery to other devices", + ); + } + // Acked may lack ChatSendAck payload (seq) — still durable success. return userMessageAcks.get(messageId) ?? null; } @@ -665,10 +327,34 @@ async function flushOutboxEntry( ): Promise { if (entry.status === "acked") return; if (await isAcked(entry.clientMessageId)) return; + const auth = cloudAuth(); + if (!auth || entry.accountId.trim() !== auth.accountId) { + // Never send under a different (or missing) account identity. + return; + } + // Capture scope at lane start; re-validate after every await / before Hub write. + const scope: OutboxScope = { + accountId: auth.accountId, + scopeGeneration: getAccountScopeGeneration(), + }; await markInflight(entry.clientMessageId); + if ( + getAccountScopeGeneration() !== scope.scopeGeneration || + cloudAuth()?.accountId !== scope.accountId + ) { + // Leave mid-flight: do not post under the new account. Reclaim via stale TTL. + return; + } try { - const result = await postOutboxEntry(entry); + const result = await postOutboxEntry(entry, scope); + if ( + getAccountScopeGeneration() !== scope.scopeGeneration || + cloudAuth()?.accountId !== scope.accountId + ) { + // Sent under race — do not mark acked for the wrong scope; reclaim later. + return; + } await markAcked(entry.clientMessageId); if (entry.kind === "user_message" || entry.kind === "agent_result") { rememberProjected(entry.clientMessageId); @@ -682,8 +368,42 @@ async function flushOutboxEntry( if (entry.kind === "user_message" && result && "messageSeq" in result) { userMessageAcks.set(entry.clientMessageId, result as CloudUserMessageAck); } + // Waiter may have already timed out and marked the bubble failed. When the + // durable outbox later acks, upgrade UI so a background success is visible + // without requiring a manual retry. + if (entry.kind === "user_message") { + const ack = + result && "messageSeq" in result + ? (result as CloudUserMessageAck) + : userMessageAcks.get(entry.clientMessageId); + try { + const { patchMessageDelivery } = await import( + "@/store/workspace/timeline-write" + ); + const row = ( + await import("@/store/workspace-store") + ).useWorkspaceStore.getState().messagesByConversation[ + entry.conversationId + ]?.find((m) => m.id === entry.clientMessageId); + if ( + row && + (row.deliveryStatus === "sending" || row.deliveryStatus === "failed") + ) { + patchMessageDelivery(entry.conversationId, entry.clientMessageId, { + deliveryStatus: "sent", + ...(ack?.messageSeq != null ? { messageSeq: ack.messageSeq } : {}), + }); + } + } catch { + /* timeline store optional in pure unit tests */ + } + } } catch (error) { const msg = error instanceof Error ? error.message : String(error); + // Scope abort is not a delivery failure — leave inflight for reclaim. + if (msg.includes("account scope changed")) { + return; + } const status = await markFailed(entry.clientMessageId, msg); console.warn("[im-cloud-sync] outbox flush failed", entry.kind, error); const isMessageKind = @@ -716,8 +436,10 @@ async function drainLaneKey(laneKey: string): Promise { ); await prev.catch(() => undefined); try { + const accountId = currentOutboxAccountId(); + if (!accountId) return; // Re-list so we only take this lane's current due head-run. - const lanes = await listDuePendingLanes(); + const lanes = await listDuePendingLanes(Date.now(), accountId); const lane = lanes.find( (l) => l[0] != null && outboxLaneKey(l[0]) === laneKey, ); @@ -739,7 +461,9 @@ async function drainLaneKey(laneKey: string): Promise { * Public sync APIs must only enqueue + wait — never call flushOutboxEntry. */ export async function flushImOutbox(): Promise { - const lanes = await listDuePendingLanes(); + const accountId = currentOutboxAccountId(); + if (!accountId) return; + const lanes = await listDuePendingLanes(Date.now(), accountId); if (lanes.length === 0) return; await Promise.all( lanes.map(async (lane) => { @@ -789,6 +513,9 @@ async function waitForOutboxSettlement( scheduleOutboxWorker(); } if (await isAcked(id)) return "acked"; + if (opts?.throwOnTerminal) { + throw new Error("outbox settlement timeout"); + } return "timeout"; } @@ -841,6 +568,7 @@ export async function syncAgentResultToCloud(input: { await enqueueAgentResult({ conversationId, clientMessageId: messageId, + accountId: auth.accountId, text, agentId, agentSessionId: sessionId, @@ -892,19 +620,33 @@ export async function projectMissingLocalAgentResultsToCloud( /** Schedule a background outbox drain until no pending rows remain. */ export function scheduleOutboxWorker(): void { if (outboxWorkerTimer != null) return; + const gen = outboxWorkerGeneration; outboxWorkerTimer = setTimeout(() => { outboxWorkerTimer = null; + if (gen !== outboxWorkerGeneration) return; void (async () => { + if (gen !== outboxWorkerGeneration) return; + const accountId = currentOutboxAccountId(); + if (!accountId) return; const now = Date.now(); - const dueNow = await listDuePending(now); - const nextAt = await earliestPendingAttemptAt(now); + const dueNow = await listDuePending(now, accountId); + const nextAt = await earliestPendingAttemptAt(now, accountId); if (dueNow.length === 0 && nextAt == null) return; + if (gen !== outboxWorkerGeneration) return; if (dueNow.length === 0 && nextAt != null) { const delay = Math.max(50, Math.min(nextAt - Date.now(), 5 * 60_000)); + if (outboxWorkerTimer != null) return; outboxWorkerTimer = setTimeout(() => { outboxWorkerTimer = null; + if (gen !== outboxWorkerGeneration) return; void flushImOutbox().then(async () => { - if ((await earliestPendingAttemptAt()) != null) { + if (gen !== outboxWorkerGeneration) return; + if ( + (await earliestPendingAttemptAt( + Date.now(), + currentOutboxAccountId(), + )) != null + ) { scheduleOutboxWorker(); } }); @@ -912,27 +654,56 @@ export function scheduleOutboxWorker(): void { return; } await flushImOutbox(); - if ((await earliestPendingAttemptAt()) != null) { + if (gen !== outboxWorkerGeneration) return; + if ( + (await earliestPendingAttemptAt( + Date.now(), + currentOutboxAccountId(), + )) != null + ) { scheduleOutboxWorker(); } })(); }, 50); } +/** Stop background outbox drain (account leave). */ +export function stopImOutboxWorker(): void { + outboxWorkerGeneration += 1; + if (outboxWorkerTimer != null) { + clearTimeout(outboxWorkerTimer); + outboxWorkerTimer = null; + } +} + /** Start background outbox drain (call once when account session is ready). */ export function startImOutboxWorker(): void { + const gen = outboxWorkerGeneration; void (async () => { await initImOutbox(); - await reclaimStaleInflight(); + if (gen !== outboxWorkerGeneration) return; + const accountId = currentOutboxAccountId(); + await reclaimStaleInflight(Date.now(), accountId); + if (gen !== outboxWorkerGeneration) return; await flushImOutbox(); - if ((await earliestPendingAttemptAt()) != null) { + if (gen !== outboxWorkerGeneration) return; + if ( + (await earliestPendingAttemptAt( + Date.now(), + currentOutboxAccountId(), + )) != null + ) { scheduleOutboxWorker(); } })(); } -/** Clear process caches (tests / account switch). */ -export function resetImCloudSyncStateForTests(): void { - runtimeAgentIdCache.clear(); +/** Clear process caches (account leave / tests). */ +export function resetImCloudSyncState(): void { + stopImOutboxWorker(); + clearRuntimeAgentIdCache(); projectedMessageIds.clear(); + reactionResults.clear(); + userMessageAcks.clear(); + laneChains.clear(); } diff --git a/apps/desktop/src/store/leave-account-scope.ts b/apps/desktop/src/store/leave-account-scope.ts new file mode 100644 index 00000000..6978d4af --- /dev/null +++ b/apps/desktop/src/store/leave-account-scope.ts @@ -0,0 +1,95 @@ +/** + * Sole account-boundary teardown for Desktop. + * + * Logout / account switch / auth-invalid must call this before another account + * may observe product state. Workspace bootstrap reset remains daemon-scoped; + * this owner tears down account-scoped caches and invalidates in-flight work. + * + * Note: im-cloud-* imports form a mild cycle with account-store through this + * module. ESM evaluates fine as long as we only call stop helpers after init. + */ + +import { minosQueryClient } from "@/shared/api/queryClient"; +import { bumpAccountScopeGeneration } from "@/shared/lib/account-scope-generation"; +import { cloudDigestCache } from "@/shared/lib/cloud-digest-cache"; +import { clearAllTopicCursors } from "@/shared/lib/cloud-cursors"; +import { cancelCloudDigestHydrate } from "@/store/im/cloud-digest-ensure"; +import { daemonApi, isTauriRuntime } from "@/shared/lib/daemon"; +import { revokeHostCredential } from "@/features/host/lib/host-credential-controller"; +import { stopImCloudBridge } from "@/store/im/im-cloud-bridge"; +import { + resetImCloudSyncState, + stopImOutboxWorker, +} from "@/store/im/im-cloud-sync"; +import { useUiStore } from "@/store/ui-store"; +import { emptyWorkspace } from "@/store/workspace/empty-workspace"; +import { resetWorkspaceModuleState } from "@/store/workspace/reset-workspace-state"; +import { useWorkspaceStore } from "@/store/workspace-store"; + +export type LeaveAccountScopeReason = + | "sign-out" + | "account-switch" + | "auth-invalid"; + +export { + bumpAccountScopeGeneration, + getAccountScopeGeneration, +} from "@/shared/lib/account-scope-generation"; + +/** + * Tear down every account-scoped process surface. + * Safe to call multiple times; idempotent for workers/caches. + */ +export function leaveAccountScope( + _reason: LeaveAccountScopeReason = "sign-out", +): void { + bumpAccountScopeGeneration(); + + // 1) Stop realtime + outbox before wiping caches (prevents late writes). + stopImOutboxWorker(); + stopImCloudBridge(); + resetImCloudSyncState(); + // stopImCloudBridge already clears unreadCountedMessageIds. + + // 2) Hub list / resume state must not carry across accounts. + cancelCloudDigestHydrate(); + cloudDigestCache.invalidate(); + clearAllTopicCursors(); + minosQueryClient.clear(); + + // 3) Workspace module singletons + entity plane. + resetWorkspaceModuleState({ + stopEventBridge: true, + reactions: "durable-empty", + clearUiEphemeral: true, + }); + useWorkspaceStore.setState({ + ...emptyWorkspace, + booting: false, + bootPhase: "Signed out", + bootProgress: 100, + bootEpoch: 0, + workspaceAccountId: null, + livePush: false, + focusedConversationId: null, + readMessageCountById: {}, + loading: false, + error: null, + actionError: null, + }); + + // 4) Navigation selection is account-scoped (not reconnect-scoped). + useUiStore.getState().clearAccountScopedUi(); + + // 5) Drop host hit_ on the serial credential controller so in-flight + // register/apply for the previous account aborts and clear runs before any + // subsequent apply. Leave stays sync for setState callers. + if (isTauriRuntime()) { + revokeHostCredential(async () => { + await daemonApi.hostClearCredential(); + }); + } else { + // Web / tests: still bump generation so deferred apply is rejected. + revokeHostCredential(async () => {}); + } +} diff --git a/apps/desktop/src/store/ui-store.ts b/apps/desktop/src/store/ui-store.ts index 8054afd9..aaf7d0a1 100644 --- a/apps/desktop/src/store/ui-store.ts +++ b/apps/desktop/src/store/ui-store.ts @@ -28,6 +28,11 @@ type UiState = { setPrimaryNav: (nav: PrimaryNav) => void; selectProject: (projectId: string) => void; selectConversation: (conversationId: string | null) => void; + /** + * Restore/default conversation when a project list arrives. Unlike + * selectConversation, does not force projectView to "conversations". + */ + ensureConversationSelection: (conversationId: string | null) => void; setProjectView: (view: ProjectView) => void; selectSession: (sessionId: string | null) => void; /** Jump to Sessions tab and open transcript for session. */ @@ -48,6 +53,11 @@ type UiState = { * so navigation restore still works after reconnect. */ clearWorkspaceEphemeralUi: () => void; + /** + * Clear every account-scoped navigation pointer. Used on logout / account switch + * so B never restores A's project/conversation selection. + */ + clearAccountScopedUi: () => void; }; export const useUiStore = create()( @@ -94,6 +104,7 @@ export const useUiStore = create()( }); }, selectConversation: (conversationId) => { + // Explicit user navigation to a conversation always opens Conversations. set((s) => ({ conversationId, selectedSessionId: null, @@ -108,6 +119,22 @@ export const useUiStore = create()( : s.lastConversationByProject, })); }, + /** + * Restore/default conversation when project list loads — must not force + * projectView to "conversations" (user may be on Sessions/Board). + */ + ensureConversationSelection: (conversationId) => { + set((s) => ({ + conversationId, + lastConversationByProject: + conversationId && s.projectId + ? { + ...s.lastConversationByProject, + [s.projectId]: conversationId, + } + : s.lastConversationByProject, + })); + }, setProjectView: (projectView) => set({ projectView, @@ -170,6 +197,16 @@ export const useUiStore = create()( replyToMessageIdByConversation: {}, commandPaletteOpen: false, }), + clearAccountScopedUi: () => + set({ + projectId: "", + conversationId: null, + selectedSessionId: null, + lastConversationByProject: {}, + draftByConversationId: {}, + replyToMessageIdByConversation: {}, + commandPaletteOpen: false, + }), }), { name: "minos.ui-store.v1", diff --git a/apps/desktop/src/store/workspace-store.ts b/apps/desktop/src/store/workspace-store.ts index ef24fb1a..97ab1fda 100644 --- a/apps/desktop/src/store/workspace-store.ts +++ b/apps/desktop/src/store/workspace-store.ts @@ -30,6 +30,7 @@ import { mergeTranscriptItems, } from "./workspace/helpers"; import { createWorkspaceActions } from "./workspace/create-actions"; +import { registerDaemonCloudFlagsProvider } from "./daemon-status-port"; export type { DataSource, @@ -51,6 +52,7 @@ export const useWorkspaceStore = create()( bootPhase: "Starting…", bootProgress: 5, bootEpoch: 0, + workspaceAccountId: null, livePush: false, source: "daemon", connection: null, @@ -72,3 +74,13 @@ export const useWorkspaceStore = create()( }, ), ); + +// Account ensure reads host flags via this port — never imports workspace-store. +registerDaemonCloudFlagsProvider(async () => { + await useWorkspaceStore.getState().refreshDaemonStatus(); + const connection = useWorkspaceStore.getState().connection; + return { + cloudOnline: connection?.cloudOnline === true, + hasHostToken: connection?.hasHostToken === true, + }; +}); diff --git a/apps/desktop/src/store/workspace/connection.ts b/apps/desktop/src/store/workspace/connection.ts index 9ba0b672..b10fdaf2 100644 --- a/apps/desktop/src/store/workspace/connection.ts +++ b/apps/desktop/src/store/workspace/connection.ts @@ -45,11 +45,16 @@ export function createConnectionActions( if (existing) { return existing; } + const { useAccountStore } = await import("@/store/account-store"); + const sessionAccountId = + useAccountStore.getState().session?.accountId?.trim() ?? null; const alreadyReady = !get().booting && get().connection?.connected && get().source === "daemon" && - get().bootEpoch > 0; + get().bootEpoch > 0 && + get().workspaceAccountId != null && + get().workspaceAccountId === sessionAccountId; if (alreadyReady) { return; } @@ -156,11 +161,17 @@ export function createConnectionActions( reactions: "skip", clearUiEphemeral: false, }); + const { useAccountStore: accountStore } = await import( + "@/store/account-store" + ); + const readyAccountId = + accountStore.getState().session?.accountId?.trim() ?? null; set({ booting: false, bootPhase: "Ready", bootProgress: 100, bootEpoch: get().bootEpoch + 1, + workspaceAccountId: readyAccountId, source: "daemon", connection, loading: false, @@ -194,7 +205,7 @@ export function createConnectionActions( void quietHydrateAllConversationLists(get); // Hub IM bridge (Mobile → Desktop) if account already authenticated. - void import("@/shared/lib/im-cloud-bridge").then(({ ensureImCloudBridge }) => + void import("@/store/im/im-cloud-bridge").then(({ ensureImCloudBridge }) => ensureImCloudBridge(), ); } catch (e) { diff --git a/apps/desktop/src/store/workspace/conversation-list.ts b/apps/desktop/src/store/workspace/conversation-list.ts index bd137f38..be57690f 100644 --- a/apps/desktop/src/store/workspace/conversation-list.ts +++ b/apps/desktop/src/store/workspace/conversation-list.ts @@ -4,7 +4,7 @@ * Hub IM mode: daemon list(project) ∥ CloudDigestCache (single account hydrate); * merge via conversation-list-merge. Never re-fetch Hub per project. */ -import type { Conversation } from "@/shared/lib/mock-data"; +import type { Conversation } from "@/shared/domain/collaboration"; import type { WorkspaceGet, WorkspaceSet, WorkspaceState } from "./types"; import { normalizeDaemonConversation, @@ -16,10 +16,10 @@ import { daemonApi } from "@/shared/lib/daemon"; import { singleFlightLoad } from "@/shared/lib/desktop-inflight"; import { minosQueryClient } from "@/shared/api/queryClient"; import { queryKeys } from "@/shared/api/queryKeys"; -import { syncConversationToCloud } from "@/shared/lib/im-cloud-sync"; +import { syncConversationToCloud } from "@/store/im/im-cloud-sync"; import { isCloudImMode } from "@/shared/lib/cloud-timeline"; import { cloudDigestCache } from "@/shared/lib/cloud-digest-cache"; -import { ensureCloudDigestHydrated } from "@/shared/lib/cloud-digest-ensure"; +import { ensureCloudDigestHydrated } from "@/store/im/cloud-digest-ensure"; import { mergeConversationList } from "@/shared/lib/conversation-list-merge"; import { reuseStableConversations } from "@/shared/lib/list-identity"; import { useAccountStore } from "@/store/account-store"; diff --git a/apps/desktop/src/store/workspace/conversation-mutations.ts b/apps/desktop/src/store/workspace/conversation-mutations.ts index 28c05719..ff5bf4a2 100644 --- a/apps/desktop/src/store/workspace/conversation-mutations.ts +++ b/apps/desktop/src/store/workspace/conversation-mutations.ts @@ -19,9 +19,9 @@ import { parseProgress, progressForBoardColumn, } from "@/shared/lib/conversation-meta"; -import type { Conversation, Project } from "@/shared/lib/mock-data"; -import { runtimesOfBots } from "@/shared/lib/mock-data"; -import { syncConversationToCloud } from "@/shared/lib/im-cloud-sync"; +import type { Conversation, Project } from "@/shared/domain/collaboration"; +import { runtimesOfBots } from "@/shared/domain/collaboration"; +import { syncConversationToCloud } from "@/store/im/im-cloud-sync"; export function createConversationMutationActions( set: WorkspaceSet, @@ -207,17 +207,29 @@ export function createConversationMutationActions( priority: next ?? undefined, }, ), + actionError: null, })); return; } - const updated = await daemonApi.updateConversation(conversationId, { - priority: priorityValue, - }); - set((s) => ({ - conversations: patchLocalConversation(s.conversations, conversationId, { - priority: parsePriority(updated.priority), - }), - })); + try { + const updated = await daemonApi.updateConversation(conversationId, { + priority: priorityValue, + }); + set((s) => ({ + conversations: patchLocalConversation( + s.conversations, + conversationId, + { + priority: parsePriority(updated.priority), + }, + ), + actionError: null, + })); + } catch (error) { + const message = + error instanceof Error ? error.message : String(error); + set({ actionError: `Failed to update priority: ${message}` }); + } }, cycleConversationProgress: async (conversationId) => { @@ -233,17 +245,29 @@ export function createConversationMutationActions( progress: next, }, ), + actionError: null, })); return; } - const updated = await daemonApi.updateConversation(conversationId, { - progress: next, - }); - set((s) => ({ - conversations: patchLocalConversation(s.conversations, conversationId, { - progress: parseProgress(updated.progress), - }), - })); + try { + const updated = await daemonApi.updateConversation(conversationId, { + progress: next, + }); + set((s) => ({ + conversations: patchLocalConversation( + s.conversations, + conversationId, + { + progress: parseProgress(updated.progress), + }, + ), + actionError: null, + })); + } catch (error) { + const message = + error instanceof Error ? error.message : String(error); + set({ actionError: `Failed to update progress: ${message}` }); + } }, setConversationProgress: async (conversationId, progress) => { diff --git a/apps/desktop/src/store/workspace/dto-map.ts b/apps/desktop/src/store/workspace/dto-map.ts index ed1c7e68..e4d51141 100644 --- a/apps/desktop/src/store/workspace/dto-map.ts +++ b/apps/desktop/src/store/workspace/dto-map.ts @@ -7,8 +7,8 @@ import type { TimelineMessage, AgentRuntime, SessionStatus, -} from "@/shared/lib/mock-data"; -import { runtimesOfBots } from "@/shared/lib/mock-data"; +} from "@/shared/domain/collaboration"; +import { runtimesOfBots } from "@/shared/domain/collaboration"; import { type DaemonConversation, type DaemonMessage, diff --git a/apps/desktop/src/store/workspace/empty-workspace.ts b/apps/desktop/src/store/workspace/empty-workspace.ts index 4c231d1d..ea9d0db2 100644 --- a/apps/desktop/src/store/workspace/empty-workspace.ts +++ b/apps/desktop/src/store/workspace/empty-workspace.ts @@ -1,7 +1,7 @@ /** * Empty workspace caches, idle fetch status, bootstrap flight, refresh timers. */ -import type { Conversation, Project, TimelineMessage } from "@/shared/lib/mock-data"; +import type { Conversation, Project, TimelineMessage } from "@/shared/domain/collaboration"; import type { TranscriptItem } from "@/shared/lib/daemon"; import type { MessageHistoryMeta } from "@/shared/lib/message-history"; import type { TranscriptHistoryMeta } from "@/shared/lib/transcript-history"; diff --git a/apps/desktop/src/store/workspace/instance-crashed-projects.test.ts b/apps/desktop/src/store/workspace/instance-crashed-projects.test.ts new file mode 100644 index 00000000..3995d3b8 --- /dev/null +++ b/apps/desktop/src/store/workspace/instance-crashed-projects.test.ts @@ -0,0 +1,51 @@ +/** + * Pure coverage for the instanceCrashed projects rollup invariant. + * Mirrors recomputeConversationAggregates + patchProjectAggregates policy + * without loading projection.ts (@/ imports are unavailable under node:test). + */ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { + conversationAggregatesFromEntities, + entityCountsAsRunning, + type SessionEntity, +} from "../../shared/lib/session-entity.ts"; + +function entity( + partial: Partial & { + sessionId: string; + daemonStatus: SessionEntity["daemonStatus"]; + }, +): SessionEntity { + const daemonStatus = partial.daemonStatus; + return { + sessionId: partial.sessionId, + conversationId: partial.conversationId ?? "c1", + agent: partial.agent ?? "codex", + shortId: partial.shortId ?? "abcd1234", + status: daemonStatus, + daemonStatus, + model: partial.model ?? "m", + summary: partial.summary ?? "", + messageCount: partial.messageCount ?? 0, + hasPendingApproval: partial.hasPendingApproval ?? false, + updatedAtMs: partial.updatedAtMs ?? 1, + }; +} + +describe("instanceCrashed project rollup invariant", () => { + it("suspended sessions stop counting as running for project badges", () => { + const running = entity({ sessionId: "s1", daemonStatus: "running" }); + assert.equal(entityCountsAsRunning(running), true); + const { runningCount } = conversationAggregatesFromEntities( + { s1: running }, + "c1", + ); + assert.equal(runningCount, 1); + + const suspended = entity({ sessionId: "s1", daemonStatus: "suspended" }); + assert.equal(entityCountsAsRunning(suspended), false); + const after = conversationAggregatesFromEntities({ s1: suspended }, "c1"); + assert.equal(after.runningCount, 0); + }); +}); diff --git a/apps/desktop/src/store/workspace/live-ingress.ts b/apps/desktop/src/store/workspace/live-ingress.ts index ef32dabf..702968a2 100644 --- a/apps/desktop/src/store/workspace/live-ingress.ts +++ b/apps/desktop/src/store/workspace/live-ingress.ts @@ -86,7 +86,7 @@ async function runConversationTurnEndRefresh( const { useAccountStore } = await import("@/store/account-store"); const { isCloudImMode } = await import("@/shared/lib/cloud-timeline"); const { projectMissingLocalAgentResultsToCloud, flushImOutbox } = - await import("@/shared/lib/im-cloud-sync"); + await import("@/store/im/im-cloud-sync"); const { toUiMessage } = await import("./helpers"); const { daemonApi } = await import("@/shared/lib/daemon"); const { session, authPhase } = useAccountStore.getState(); @@ -316,6 +316,7 @@ export function createLiveIngressActions( let projectSessionsByProject = s.projectSessionsByProject; let attentionSessions = s.attentionSessions; let conversations = s.conversations; + let projects = s.projects; const attentionStatus = s.attentionStatus; for (const id of ids) { const entity = patchSessionEntity(sessionsById[id], id, { @@ -328,6 +329,7 @@ export function createLiveIngressActions( projectSessionsByProject, attentionSessions, conversations, + projects, attentionStatus, }, entity, @@ -338,6 +340,7 @@ export function createLiveIngressActions( projectSessionsByProject = committed.projectSessionsByProject; attentionSessions = committed.attentionSessions; conversations = committed.conversations; + if (committed.projects) projects = committed.projects; } return { sessionsById, @@ -345,6 +348,7 @@ export function createLiveIngressActions( projectSessionsByProject, attentionSessions, conversations, + projects, }; }); return; diff --git a/apps/desktop/src/store/workspace/mock-bundle.ts b/apps/desktop/src/store/workspace/mock-bundle.ts index 59d6f8f9..386c8d67 100644 --- a/apps/desktop/src/store/workspace/mock-bundle.ts +++ b/apps/desktop/src/store/workspace/mock-bundle.ts @@ -6,8 +6,8 @@ import { projects as mockProjects, timelineByConversation as mockTimeline, agentSessions as mockSessions, - type TimelineMessage, } from "@/shared/lib/mock-data"; +import type { TimelineMessage } from "@/shared/domain/collaboration"; import { entityNeedsAttention, mergeSessionEntity, diff --git a/apps/desktop/src/store/workspace/projection.ts b/apps/desktop/src/store/workspace/projection.ts index d1d7ae86..aa31b904 100644 --- a/apps/desktop/src/store/workspace/projection.ts +++ b/apps/desktop/src/store/workspace/projection.ts @@ -4,7 +4,7 @@ * Sole write funnel: merge/patch Entity → commitSessionEntity → * membership lists + conversation running/approval aggregates from Entity Σ. */ -import type { Conversation, Project } from "@/shared/lib/mock-data"; +import type { Conversation, Project } from "@/shared/domain/collaboration"; import type { SessionEntity } from "@/shared/lib/session-entity"; import { conversationAggregatesFromEntities, diff --git a/apps/desktop/src/store/workspace/timeline-write.ts b/apps/desktop/src/store/workspace/timeline-write.ts new file mode 100644 index 00000000..c86ceab5 --- /dev/null +++ b/apps/desktop/src/store/workspace/timeline-write.ts @@ -0,0 +1,294 @@ +/** + * Sole write funnel for `messagesByConversation` (+ paired messageHistory). + * + * Callers (Hub bridge, loadTimeline, optimistic send) must not raw-set the + * timeline map. Pure merges stay in shared/lib; this module owns the setState. + */ + +import type { TimelineMessage } from "@/shared/domain/collaboration"; +import { + mergeCloudAndLocalTimeline, + removeMessageFromTimeline, + upsertCloudMessageIntoTimeline, +} from "@/shared/lib/cloud-timeline"; +import { + EMPTY_MESSAGE_HISTORY, + mergeMessagesOlder, + mergeMessagesQuietTail, + messageHistoryFromWindow, + trimMessagesHardMax, + type MessageHistoryMeta, +} from "@/shared/lib/message-history"; +import { getAccountScopeGeneration } from "@/shared/lib/account-scope-generation"; +import { useWorkspaceStore } from "@/store/workspace-store"; + +export type TimelineHistoryPatch = { + hasOlderCloud?: boolean; + hasOlderHost?: boolean; + loadingOlder?: boolean; +}; + +/** + * Drop account-scoped timeline writes after leave/account-switch. + * Capture gen at async start; funnel re-checks at setState time. + */ +function isStaleAccountScope(expectedGen?: number): boolean { + if (expectedGen == null) return false; + return expectedGen !== getAccountScopeGeneration(); +} + +/** Ensure a conversation window key exists (empty) without clobbering body. */ +export function ensureTimelineWindowKey( + conversationId: string, + opts?: { accountScopeGen?: number }, +): void { + const id = conversationId.trim(); + if (!id) return; + if (isStaleAccountScope(opts?.accountScopeGen)) return; + useWorkspaceStore.setState((s) => { + if (isStaleAccountScope(opts?.accountScopeGen)) return {}; + if (Object.prototype.hasOwnProperty.call(s.messagesByConversation, id)) { + return {}; + } + return { + messagesByConversation: { + ...s.messagesByConversation, + [id]: [], + }, + }; + }); +} + +/** Hub live single-frame apply (same-id supersede + hard max trim). */ +export function applyHubMessage( + conversationId: string, + message: TimelineMessage, + opts?: { accountScopeGen?: number }, +): void { + const id = conversationId.trim(); + if (!id || !message.id) return; + if (isStaleAccountScope(opts?.accountScopeGen)) return; + useWorkspaceStore.setState((s) => { + if (isStaleAccountScope(opts?.accountScopeGen)) return {}; + const prev = s.messagesByConversation[id] ?? []; + const merged = upsertCloudMessageIntoTimeline(prev, message); + const trimmed = trimMessagesHardMax(merged); + const prevHist = + s.messageHistoryByConversation[id] ?? EMPTY_MESSAGE_HISTORY; + return { + messagesByConversation: { + ...s.messagesByConversation, + [id]: trimmed.messages, + }, + messageHistoryByConversation: { + ...s.messageHistoryByConversation, + [id]: messageHistoryFromWindow(trimmed.messages, { + prev: prevHist, + hasOlderCloud: prevHist.hasOlderCloud || trimmed.trimmed, + hasOlderHost: prevHist.hasOlderHost, + loadingOlder: false, + }), + }, + }; + }); +} + +/** Drop a recalled Hub message from the open window. */ +export function removeRecalledMessage( + conversationId: string, + messageId: string, + opts?: { accountScopeGen?: number }, +): boolean { + const id = conversationId.trim(); + const mid = messageId.trim(); + if (!id || !mid) return false; + if (isStaleAccountScope(opts?.accountScopeGen)) return false; + let changed = false; + useWorkspaceStore.setState((s) => { + if (isStaleAccountScope(opts?.accountScopeGen)) return {}; + if (!Object.prototype.hasOwnProperty.call(s.messagesByConversation, id)) { + return {}; + } + const prev = s.messagesByConversation[id] ?? []; + const next = removeMessageFromTimeline(prev, mid); + if (next === prev) return {}; + changed = true; + return { + messagesByConversation: { + ...s.messagesByConversation, + [id]: next, + }, + }; + }); + return changed; +} + +/** + * Replace/merge a hydrate or snapshot window. + * - `mode: "hub-local"` — Hub SSOT chat + local workbench cards + * - `mode: "quiet-tail"` — union by id keeping older pages + * - `mode: "older-prepend"` — page older into existing window + */ +export function replaceWindowFromHydrate( + conversationId: string, + input: { + mode: "hub-local" | "quiet-tail" | "older-prepend"; + cloudMessages?: TimelineMessage[]; + localMessages?: TimelineMessage[]; + /** Existing window is read from store when omitted for older-prepend. */ + history?: TimelineHistoryPatch & { + prev?: MessageHistoryMeta; + /** Full history row override after merge (loadTimeline ready path). */ + nextHistory?: MessageHistoryMeta; + }; + accountScopeGen?: number; + }, +): void { + const id = conversationId.trim(); + if (!id) return; + if (isStaleAccountScope(input.accountScopeGen)) return; + useWorkspaceStore.setState((s) => { + if (isStaleAccountScope(input.accountScopeGen)) return {}; + const prev = s.messagesByConversation[id] ?? []; + const cloud = input.cloudMessages ?? []; + const local = input.localMessages ?? []; + let merged: TimelineMessage[]; + if (input.mode === "hub-local") { + merged = mergeCloudAndLocalTimeline({ + cloudMessages: cloud, + localMessages: local.length > 0 ? local : prev, + }); + } else if (input.mode === "quiet-tail") { + const withTail = + prev.length > 0 ? mergeMessagesQuietTail(prev, cloud) : cloud; + merged = mergeCloudAndLocalTimeline({ + cloudMessages: cloud, + localMessages: withTail, + }); + } else { + // older-prepend + let older = local; + if (cloud.length > 0) { + older = mergeCloudAndLocalTimeline({ + cloudMessages: cloud, + localMessages: local, + }); + } + merged = mergeMessagesOlder(older, prev); + } + const trimmed = trimMessagesHardMax(merged); + const prevHist = + input.history?.prev ?? + s.messageHistoryByConversation[id] ?? + EMPTY_MESSAGE_HISTORY; + const nextHistory = + input.history?.nextHistory ?? + messageHistoryFromWindow(trimmed.messages, { + prev: prevHist, + hasOlderCloud: + input.history?.hasOlderCloud ?? + (prevHist.hasOlderCloud || trimmed.trimmed), + hasOlderHost: + input.history?.hasOlderHost ?? + (prevHist.hasOlderHost || trimmed.trimmed), + loadingOlder: input.history?.loadingOlder ?? false, + }); + return { + messagesByConversation: { + ...s.messagesByConversation, + [id]: trimmed.messages, + }, + messageHistoryByConversation: { + ...s.messageHistoryByConversation, + [id]: nextHistory, + }, + }; + }); +} + +/** + * Install a fully merged window + history (loadTimeline ready path). + * Caller runs pure merges; this is the only setState for the body. + */ +export function setTimelineWindow( + conversationId: string, + messages: TimelineMessage[], + history: MessageHistoryMeta, + opts?: { accountScopeGen?: number }, +): void { + const id = conversationId.trim(); + if (!id) return; + if (isStaleAccountScope(opts?.accountScopeGen)) return; + useWorkspaceStore.setState((s) => { + if (isStaleAccountScope(opts?.accountScopeGen)) return {}; + return { + messagesByConversation: { + ...s.messagesByConversation, + [id]: messages, + }, + messageHistoryByConversation: { + ...s.messageHistoryByConversation, + [id]: history, + }, + }; + }); +} + +/** Append optimistic user bubble (send path). */ +export function applyOptimisticUserMessage( + conversationId: string, + message: TimelineMessage, + opts?: { accountScopeGen?: number }, +): void { + const id = conversationId.trim(); + if (!id || !message.id) return; + if (isStaleAccountScope(opts?.accountScopeGen)) return; + useWorkspaceStore.setState((s) => { + if (isStaleAccountScope(opts?.accountScopeGen)) return {}; + return { + messagesByConversation: { + ...s.messagesByConversation, + [id]: [...(s.messagesByConversation[id] ?? []), message], + }, + error: null, + }; + }); +} + +/** Patch delivery / clock fields on one message by id. */ +export function patchMessageDelivery( + conversationId: string, + messageId: string, + patch: Partial< + Pick< + TimelineMessage, + "deliveryStatus" | "messageSeq" | "time" | "createdAtMs" + > + >, + opts?: { accountScopeGen?: number }, +): void { + const id = conversationId.trim(); + const mid = messageId.trim(); + if (!id || !mid) return; + if (isStaleAccountScope(opts?.accountScopeGen)) return; + // Drop undefined keys so partial patches do not clobber existing fields. + const clean: Partial = {}; + if (patch.deliveryStatus !== undefined) { + clean.deliveryStatus = patch.deliveryStatus; + } + if (patch.messageSeq !== undefined) clean.messageSeq = patch.messageSeq; + if (patch.time !== undefined) clean.time = patch.time; + if (patch.createdAtMs !== undefined) clean.createdAtMs = patch.createdAtMs; + if (Object.keys(clean).length === 0) return; + useWorkspaceStore.setState((s) => { + if (isStaleAccountScope(opts?.accountScopeGen)) return {}; + return { + messagesByConversation: { + ...s.messagesByConversation, + [id]: (s.messagesByConversation[id] ?? []).map((m) => + m.id === mid ? { ...m, ...clean } : m, + ), + }, + }; + }); +} diff --git a/apps/desktop/src/store/workspace/timeline.ts b/apps/desktop/src/store/workspace/timeline.ts index b6671547..02d7565b 100644 --- a/apps/desktop/src/store/workspace/timeline.ts +++ b/apps/desktop/src/store/workspace/timeline.ts @@ -18,7 +18,6 @@ import { EMPTY_MESSAGE_HISTORY, MESSAGE_PAGE_SIZE, firstMessageCreatedAtMs, - mergeMessagesOlder, mergeMessagesQuietTail, messageHistoryFromWindow, metaAfterMessageTail, @@ -29,13 +28,19 @@ import { useReactionStore } from "@/features/chat/reaction-store"; import { flushImOutbox, projectMissingLocalAgentResultsToCloud, -} from "@/shared/lib/im-cloud-sync"; -import { pullCloudConversationMessagePage } from "@/shared/lib/im-cloud-inbound"; +} from "@/store/im/im-cloud-sync"; +import { pullCloudConversationMessagePage } from "@/store/im/im-cloud-inbound"; import { isCloudImMode, mergeCloudAndLocalTimeline, } from "@/shared/lib/cloud-timeline"; import { useAccountStore } from "@/store/account-store"; +import { getAccountScopeGeneration } from "@/shared/lib/account-scope-generation"; +import { + ensureTimelineWindowKey, + replaceWindowFromHydrate, + setTimelineWindow, +} from "./timeline-write"; function cloudImEnabled(): boolean { const { session, authPhase } = useAccountStore.getState(); @@ -66,33 +71,25 @@ export function createTimelineActions( // parity — see loadTranscript quiet path). const prev = get().timelineStatusByConversation[conversationId]; const { next, generation } = statusForLoad(prev, quiet); + const accountScopeGen = getAccountScopeGeneration(); // Quiet is stale when a hard open bumped generation past what we saw. // Hard open is stale when a newer hard open superseded us. + // Also stale after account leave/switch mid-flight. const isStale = () => get().timelineStatusByConversation[conversationId]?.generation !== - generation; + generation || + accountScopeGen !== getAccountScopeGeneration(); - set((s) => { - // Ensure messages key exists so Hub WS hasWindow during cold pull. - // focused ≠ hasWindow: hydrate-only — no focusedConversationId, no - // mark-read (open path + debounced focused inbound own those). - const hasMessagesKey = Object.prototype.hasOwnProperty.call( - s.messagesByConversation, - conversationId, - ); - return { - messagesByConversation: hasMessagesKey - ? s.messagesByConversation - : { - ...s.messagesByConversation, - [conversationId]: [], - }, - timelineStatusByConversation: { - ...s.timelineStatusByConversation, - [conversationId]: next, - }, - }; - }); + // Ensure messages key exists so Hub WS hasWindow during cold pull. + // focused ≠ hasWindow: hydrate-only — no focusedConversationId, no + // mark-read (open path + debounced focused inbound own those). + ensureTimelineWindowKey(conversationId, { accountScopeGen }); + set((s) => ({ + timelineStatusByConversation: { + ...s.timelineStatusByConversation, + [conversationId]: next, + }, + })); try { const linked = cloudImEnabled(); @@ -100,7 +97,7 @@ export function createTimelineActions( // Subscribe only — loadTimeline is the sole cold-hydrate writer. // (focusConversationOnCloud must not dual-merge the window.) if (linked) { - void import("@/shared/lib/im-cloud-bridge").then( + void import("@/store/im/im-cloud-bridge").then( ({ ensureConversationSubscribedOnCloud }) => { ensureConversationSubscribedOnCloud(conversationId); }, @@ -147,68 +144,60 @@ export function createTimelineActions( .hydrateFromMessages(messagePage.messages); } - set((s) => { - const prevMessages = s.messagesByConversation[conversationId]; - let merged: typeof localUi; - if (linked) { - // Hub SSOT for chat bubbles when present. Always include localUi so - // host agent-result appears before / without Hub uplink. - // prev window keeps optimistic sending/failed + local tool cards. - merged = mergeCloudAndLocalTimeline({ - cloudMessages: cloudRows, - localMessages: [...localUi, ...(prevMessages ?? [])], - }); - } else { - // Local-only: union-merge by id with previous window. - merged = mergeMessagesQuietTail(prevMessages, localUi); - } - const trimmed = trimMessagesHardMax(merged); - merged = trimmed.messages; - const prevHist = - s.messageHistoryByConversation[conversationId] ?? - EMPTY_MESSAGE_HISTORY; - const cloudHasOlder = - linked && - (cloudPage.nextBeforeSeq != null || - cloudPage.rawCount >= MESSAGE_PAGE_SIZE); - const hostHasOlder = messagePage.hasMore; - const firstCreated = firstMessageCreatedAtMs(merged); - const nextHist: MessageHistoryMeta = quiet - ? messageHistoryFromWindow(merged, { - prev: prevHist, - firstLoadedCreatedAtMs: - firstCreated ?? prevHist.firstLoadedCreatedAtMs, - hasOlderCloud: - prevHist.hasOlderCloud || cloudHasOlder || trimmed.trimmed, - hasOlderHost: - prevHist.hasOlderHost || hostHasOlder || trimmed.trimmed, - loadingOlder: false, - }) - : metaAfterMessageTail( - merged, - hostHasOlder || cloudHasOlder || trimmed.trimmed, - firstCreated, - { - hasMoreCloud: cloudHasOlder || trimmed.trimmed, - hasMoreHost: hostHasOlder || trimmed.trimmed, - }, - ); - return { - messagesByConversation: { - ...s.messagesByConversation, - [conversationId]: merged, - }, - messageHistoryByConversation: { - ...s.messageHistoryByConversation, - [conversationId]: nextHist, - }, - timelineStatusByConversation: { - ...s.timelineStatusByConversation, - [conversationId]: { phase: "ready", generation }, - }, - error: null, - }; - }); + const prevMessages = + get().messagesByConversation[conversationId]; + let merged: typeof localUi; + if (linked) { + // Hub SSOT for chat bubbles when present. Always include localUi so + // host agent-result appears before / without Hub uplink. + // prev window keeps optimistic sending/failed + local tool cards. + merged = mergeCloudAndLocalTimeline({ + cloudMessages: cloudRows, + localMessages: [...localUi, ...(prevMessages ?? [])], + }); + } else { + // Local-only: union-merge by id with previous window. + merged = mergeMessagesQuietTail(prevMessages, localUi); + } + const trimmed = trimMessagesHardMax(merged); + merged = trimmed.messages; + const prevHist = + get().messageHistoryByConversation[conversationId] ?? + EMPTY_MESSAGE_HISTORY; + const cloudHasOlder = + linked && + (cloudPage.nextBeforeSeq != null || + cloudPage.rawCount >= MESSAGE_PAGE_SIZE); + const hostHasOlder = messagePage.hasMore; + const firstCreated = firstMessageCreatedAtMs(merged); + const nextHist: MessageHistoryMeta = quiet + ? messageHistoryFromWindow(merged, { + prev: prevHist, + firstLoadedCreatedAtMs: + firstCreated ?? prevHist.firstLoadedCreatedAtMs, + hasOlderCloud: + prevHist.hasOlderCloud || cloudHasOlder || trimmed.trimmed, + hasOlderHost: + prevHist.hasOlderHost || hostHasOlder || trimmed.trimmed, + loadingOlder: false, + }) + : metaAfterMessageTail( + merged, + hostHasOlder || cloudHasOlder || trimmed.trimmed, + firstCreated, + { + hasMoreCloud: cloudHasOlder || trimmed.trimmed, + hasMoreHost: hostHasOlder || trimmed.trimmed, + }, + ); + setTimelineWindow(conversationId, merged, nextHist, { accountScopeGen }); + set((s) => ({ + timelineStatusByConversation: { + ...s.timelineStatusByConversation, + [conversationId]: { phase: "ready", generation }, + }, + error: null, + })); // loadTimeline is hydrate-only: never mark-read / never write focus. // Focus + Hub mark-read live on open/select (Timeline mount) and @@ -236,20 +225,14 @@ export function createTimelineActions( { limit: MESSAGE_PAGE_SIZE }, ); if (isStale()) return; - set((s) => { - const prev = s.messagesByConversation[conversationId] ?? []; - const merged = mergeCloudAndLocalTimeline({ - cloudMessages: page.messages, - localMessages: [...localUi, ...prev], - }); - const trimmed = trimMessagesHardMax(merged); - return { - messagesByConversation: { - ...s.messagesByConversation, - [conversationId]: trimmed.messages, - }, - }; - }); + const prev = + get().messagesByConversation[conversationId] ?? []; + replaceWindowFromHydrate(conversationId, { + mode: "hub-local", + cloudMessages: page.messages, + localMessages: [...localUi, ...prev], + accountScopeGen, + }); }); } } catch (e) { @@ -288,6 +271,7 @@ export function createTimelineActions( loadOlderMessages: async (conversationId) => { if (get().source !== "daemon" || !conversationId) return; + const accountScopeGen = getAccountScopeGeneration(); const hist = get().messageHistoryByConversation[conversationId] ?? EMPTY_MESSAGE_HISTORY; @@ -356,6 +340,7 @@ export function createTimelineActions( cloudPagePromise, ]); if (get().source !== "daemon") return; + if (accountScopeGen !== getAccountScopeGeneration()) return; useReactionStore .getState() .hydrateFromMessages( @@ -364,36 +349,20 @@ export function createTimelineActions( : page.messages, ); const olderLocal = page.messages.map(toUiMessage); - set((s) => { - const existingWindow = s.messagesByConversation[conversationId] ?? []; - let older = olderLocal; - if (linked) { - older = mergeCloudAndLocalTimeline({ - cloudMessages: cloudPage.messages, - localMessages: olderLocal, - }); - } - const mergedRaw = mergeMessagesOlder(older, existingWindow); - const trimmed = trimMessagesHardMax(mergedRaw); - const merged = trimmed.messages; - const cloudHasOlder = - linked && - (cloudPage.nextBeforeSeq != null || - cloudPage.rawCount >= MESSAGE_PAGE_SIZE); - return { - messagesByConversation: { - ...s.messagesByConversation, - [conversationId]: merged, - }, - messageHistoryByConversation: { - ...s.messageHistoryByConversation, - [conversationId]: messageHistoryFromWindow(merged, { - hasOlderCloud: cloudHasOlder || trimmed.trimmed, - hasOlderHost: page.hasMore || trimmed.trimmed, - loadingOlder: false, - }), - }, - }; + const cloudHasOlder = + linked && + (cloudPage.nextBeforeSeq != null || + cloudPage.rawCount >= MESSAGE_PAGE_SIZE); + replaceWindowFromHydrate(conversationId, { + mode: "older-prepend", + cloudMessages: linked ? cloudPage.messages : [], + localMessages: olderLocal, + history: { + hasOlderCloud: cloudHasOlder, + hasOlderHost: page.hasMore, + loadingOlder: false, + }, + accountScopeGen, }); } catch { set((s) => { diff --git a/apps/desktop/src/store/workspace/transcript.ts b/apps/desktop/src/store/workspace/transcript.ts index 3f20cb00..4df3ed94 100644 --- a/apps/desktop/src/store/workspace/transcript.ts +++ b/apps/desktop/src/store/workspace/transcript.ts @@ -34,7 +34,7 @@ import { trimTranscriptHardMax, hasTranscriptWorkingSet, } from "@/shared/lib/transcript-history"; -import type { SessionStatus } from "@/shared/lib/mock-data"; +import type { SessionStatus } from "@/shared/domain/collaboration"; export function createTranscriptActions( diff --git a/apps/desktop/src/store/workspace/types.ts b/apps/desktop/src/store/workspace/types.ts index 37f3e833..d756f720 100644 --- a/apps/desktop/src/store/workspace/types.ts +++ b/apps/desktop/src/store/workspace/types.ts @@ -9,10 +9,10 @@ import type { ConversationProgress, DeliveryStatus, Project, + ProjectSession, TimelineMessage, - AgentSession, ConversationBoardColumn, -} from "@/shared/lib/mock-data"; +} from "@/shared/domain/collaboration"; import type { DaemonConnection, DaemonConversationEvent, @@ -25,7 +25,7 @@ import type { ApprovalStatusPolicy } from "@/shared/lib/session-status"; import type { MessageHistoryMeta } from "@/shared/lib/message-history"; import type { TranscriptHistoryMeta } from "@/shared/lib/transcript-history"; -export type { SessionEntity }; +export type { SessionEntity, ProjectSession }; export type DataSource = "mock" | "daemon"; @@ -42,14 +42,6 @@ export type ResourceFetchStatus = { export type ConversationDetailPhase = ResourceFetchPhase; export type ConversationDetailStatus = ResourceFetchStatus; -export type ProjectSession = AgentSession & { - conversationTitle?: string; - firstTsMs?: number; - lastTsMs?: number; - /** Session last_seq — used to seek transcript tail. */ - messageCount?: number; -}; - export type SessionListSlice = { sessionsById: Record; sessionsByConversation: Record; @@ -71,6 +63,12 @@ export type WorkspaceState = { * clears workspace caches (StrictMode / reconnect). */ bootEpoch: number; + /** + * Account that last owned this workspace data plane. + * Null after leaveAccountScope; bootstrap alreadyReady requires match with + * the current session accountId. + */ + workspaceAccountId: string | null; /** * True when Tauri push subscriptions (daemon://*) are active. * Live UI should prefer events over quiet poll intervals. diff --git a/apps/desktop/src/store/workspace/use-cases.ts b/apps/desktop/src/store/workspace/use-cases.ts index 22e4d60c..c0ad5e11 100644 --- a/apps/desktop/src/store/workspace/use-cases.ts +++ b/apps/desktop/src/store/workspace/use-cases.ts @@ -9,21 +9,26 @@ import { minosQueryClient } from "@/shared/api/queryClient"; import { queryKeys } from "@/shared/api/queryKeys"; import { transcriptHasPendingApproval } from "@/shared/lib/session-status"; import type { MentionProfile } from "@/shared/lib/agent-route"; -import type { DeliveryStatus, TimelineMessage } from "@/shared/lib/mock-data"; +import type { TimelineMessage } from "@/shared/domain/collaboration"; import type { TranscriptItem } from "@/shared/lib/daemon"; import { quietRefreshConversationSlices } from "./shared"; import { buildStructuredMentions, resolveDispatchTargets, } from "./send-dispatch"; -import { syncUserMessageToCloud } from "@/shared/lib/im-cloud-sync"; +import { syncUserMessageToCloud } from "@/store/im/im-cloud-sync"; import { isCloudImMode } from "@/shared/lib/cloud-timeline"; import { formatLocalClock } from "@/shared/lib/time"; import { cloudDigestCache } from "@/shared/lib/cloud-digest-cache"; import { positiveMs } from "@/shared/lib/rail-activity"; import { useAccountStore } from "@/store/account-store"; -import type { Conversation } from "@/shared/lib/mock-data"; -import { membershipTokensOfBots } from "@/shared/lib/mock-data"; +import type { Conversation } from "@/shared/domain/collaboration"; +import { membershipTokensOfBots } from "@/shared/domain/collaboration"; +import { getAccountScopeGeneration } from "@/shared/lib/account-scope-generation"; +import { + applyOptimisticUserMessage, + patchMessageDelivery, +} from "./timeline-write"; /** * Flattened membership tokens for resolveDispatchTargets. @@ -78,6 +83,140 @@ function cloudAuthenticated(): boolean { }); } +function agentRuntimesFromConv(conv: Conversation): string[] { + const fromBots = conv.participatingBots + ?.map((b) => b.runtime.trim().toLowerCase()) + .filter(Boolean); + if (fromBots && fromBots.length > 0) return fromBots; + return conv.participatingAgents; +} + +function railPreviewFromBody(messageBody: string): string { + const text = messageBody.trim(); + return text.length > 88 ? `${text.slice(0, 88)}…` : text; +} + +/** + * Shared Hub delivery pipeline for send + retry (validate → uplink → local project). + * Caller owns optimistic row insert / deliveryStatus transitions. + */ +async function deliverMessage( + get: WorkspaceGet, + set: WorkspaceSet, + input: { + conversationId: string; + messageId: string; + messageBody: string; + replyToMessageId?: string; + createdAtMs: number; + clock: string; + accountScopeGen: number; + }, +): Promise { + const { + conversationId, + messageId, + messageBody, + replyToMessageId, + createdAtMs, + clock, + accountScopeGen, + } = input; + const conv = get().conversations.find((c) => c.id === conversationId); + const project = get().projects.find((p) => p.id === conv?.projectId); + if (!conv || !project) { + throw new Error("conversation or project not found"); + } + + const mentionProfiles = await loadMentionProfiles( + conversationId, + conv.participatingAgents, + conv.participatingBots, + ); + if (accountScopeGen !== getAccountScopeGeneration()) { + throw new Error("account scope changed"); + } + const installedAgents = new Set( + get() + .clis.filter((c) => c.installed) + .map((c) => c.agent.toLowerCase()), + ); + resolveDispatchTargets({ + messageBody, + participatingAgents: membershipTokensFromConv(conv), + installedAgents, + mentionProfiles, + }); + const structuredMentions = buildStructuredMentions( + messageBody, + mentionProfiles, + ); + if (!cloudAuthenticated()) { + throw new Error( + "Sign in to send collaboration messages. Bot delivery requires Account Hub sync.", + ); + } + + const cloudAck = await syncUserMessageToCloud({ + conversationId, + messageId, + text: messageBody, + title: conv.title, + replyToMessageId, + createdAtMs, + agentRuntimes: agentRuntimesFromConv(conv), + messageSource: "client_live", + mentions: structuredMentions.length > 0 ? structuredMentions : undefined, + }); + // Only acked settlement reaches here (sync throws on timeout/terminal). + if (accountScopeGen !== getAccountScopeGeneration()) { + throw new Error("account scope changed"); + } + patchMessageDelivery( + conversationId, + messageId, + { + deliveryStatus: "sent", + ...(cloudAck?.messageSeq != null + ? { messageSeq: cloudAck.messageSeq } + : {}), + time: clock, + createdAtMs, + }, + { accountScopeGen }, + ); + patchRailActivity( + set, + conversationId, + railPreviewFromBody(messageBody), + createdAtMs, + ); + try { + await daemonApi.appendUserMessage(conversationId, messageBody, messageId); + } catch (localErr) { + console.warn( + "[workspace] local workbench projection after Hub Ack failed", + localErr, + ); + } + if (accountScopeGen !== getAccountScopeGeneration()) return; + set({ actionError: null }); + void get().loadTimeline(conversationId, { quiet: true }); + + await quietRefreshConversationSlices(get, conversationId); + if (accountScopeGen !== getAccountScopeGeneration()) return; + await minosQueryClient.invalidateQueries({ + queryKey: queryKeys.conversations(conv.projectId), + }); + await minosQueryClient.invalidateQueries({ + queryKey: queryKeys.projectSessions(conv.projectId), + }); + await minosQueryClient.invalidateQueries({ + queryKey: queryKeys.inspectorSessions(conversationId), + }); + await get().loadConversations(conv.projectId); +} + /** * After local approval/permission resolution: patch Entity + recompute * conversation aggregates from Entity Σ (no ±1 approvalCount hacks). @@ -212,7 +351,7 @@ export function createUseCasesActions( ? `approval-${crypto.randomUUID()}` : `approval-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; const { syncApprovalResolve } = await import( - "@/shared/lib/im-cloud-sync" + "@/store/im/im-cloud-sync" ); // Optimistic demote before RPC so the card leaves the actionable state @@ -436,6 +575,7 @@ export function createUseCasesActions( // Constraint #1: generate messageId + optimistic `sending` insert BEFORE // any business validation that may throw, so the user always sees their // bubble immediately (WeChat: empty composer + sending row). + const accountScopeGen = getAccountScopeGeneration(); const resolvedId = messageId ?? `msg_${crypto.randomUUID()}`; const replyToMessageId = options?.replyToMessageId; const createdAtMs = Date.now(); @@ -451,156 +591,59 @@ export function createUseCasesActions( // yet accept reply_to — durable round-trip deferred to protocol wave. ...(replyToMessageId ? { replyToMessageId } : {}), }; - // Optimistic timeline + rail (do not wait for Hub digest / list re-merge). - set((s) => ({ - messagesByConversation: { - ...s.messagesByConversation, - [conversationId]: [ - ...(s.messagesByConversation[conversationId] ?? []), - optimistic, - ], - }, - error: null, - })); - const railPreview = - messageBody.trim().length > 88 - ? `${messageBody.trim().slice(0, 88)}…` - : messageBody.trim(); - patchRailActivity(set, conversationId, railPreview, createdAtMs); - - const patchDelivery = ( - status: DeliveryStatus, - seq?: number, - time?: string, - ) => { - set((s) => ({ - messagesByConversation: { - ...s.messagesByConversation, - [conversationId]: (s.messagesByConversation[conversationId] ?? []).map( - (m) => - m.id === resolvedId - ? { - ...m, - deliveryStatus: status, - messageSeq: seq ?? m.messageSeq, - time: time ?? m.time, - createdAtMs: m.createdAtMs ?? createdAtMs, - } - : m, - ), - }, - })); - }; + applyOptimisticUserMessage(conversationId, optimistic, { + accountScopeGen, + }); + patchRailActivity( + set, + conversationId, + railPreviewFromBody(messageBody), + createdAtMs, + ); - // Mock backend has no RPC: flip to sent synchronously. if (get().source !== "daemon") { - patchDelivery("sent", undefined, clock); + patchMessageDelivery( + conversationId, + resolvedId, + { + deliveryStatus: "sent", + time: clock, + }, + { accountScopeGen }, + ); return; } try { - const conv = get().conversations.find((c) => c.id === conversationId); - const project = get().projects.find((p) => p.id === conv?.projectId); - if (!conv || !project) { - throw new Error("conversation or project not found"); - } - - // Validate routing BEFORE durable append (same order as retry). - // mentionProfiles are roster-scoped (Hub participants preferred). - const mentionProfiles = await loadMentionProfiles( - conversationId, - conv.participatingAgents, - conv.participatingBots, - ); - const installedAgents = new Set( - get() - .clis.filter((c) => c.installed) - .map((c) => c.agent.toLowerCase()), - ); - const membershipTokens = membershipTokensFromConv(conv); - // Validate @ targets (membership / sole-route). Bot activation itself is - // Hub-only when Account is live — no local startAgent fan-out. - resolveDispatchTargets({ - messageBody, - participatingAgents: membershipTokens, - installedAgents, - mentionProfiles, - }); - // Structured mentions for AppendMessage (Hub validates membership only). - const structuredMentions = buildStructuredMentions( - messageBody, - mentionProfiles, - ); - - const convTitle = conv.title; - // Host runtime bins for cloud upsert — derived from bot roster SSOT. - const agentRuntimes = (() => { - const fromBots = conv.participatingBots - ?.map((b) => b.runtime.trim().toLowerCase()) - .filter(Boolean); - if (fromBots && fromBots.length > 0) return fromBots; - return conv.participatingAgents; - })(); - const accountOn = cloudAuthenticated(); - if (!accountOn) { - throw new Error( - "Sign in to send collaboration messages. Bot delivery requires Account Hub sync.", - ); - } - - // Collaboration write authority is Hub only. "sent" comes from ChatSendAck - // (or durable echo); local daemon workbench is a projection after Ack. - const cloudAck = await syncUserMessageToCloud({ + await deliverMessage(get, set, { conversationId, messageId: resolvedId, - text: messageBody, - title: convTitle, + messageBody, replyToMessageId, createdAtMs, - agentRuntimes, - messageSource: "client_live", - mentions: - structuredMentions.length > 0 ? structuredMentions : undefined, - }); - const messageSeq = cloudAck?.messageSeq; - patchDelivery("sent", messageSeq, clock); - patchRailActivity(set, conversationId, railPreview, createdAtMs); - // Optional local workbench projection (idempotent by message_id) — not write authority. - try { - await daemonApi.appendUserMessage( - conversationId, - messageBody, - resolvedId, - ); - } catch (localErr) { - console.warn( - "[workspace] local workbench projection after Hub Ack failed", - localErr, - ); - } - set({ actionError: null }); - void get().loadTimeline(conversationId, { quiet: true }); - - await quietRefreshConversationSlices(get, conversationId); - await minosQueryClient.invalidateQueries({ - queryKey: queryKeys.conversations(conv.projectId), + clock, + accountScopeGen, }); - await minosQueryClient.invalidateQueries({ - queryKey: queryKeys.projectSessions(conv.projectId), - }); - await minosQueryClient.invalidateQueries({ - queryKey: queryKeys.inspectorSessions(conversationId), - }); - await get().loadConversations(conv.projectId); } catch (e) { const message = e instanceof Error ? e.message : String(e); + if (accountScopeGen !== getAccountScopeGeneration()) { + throw e; + } set({ actionError: message }); - // Only mark user bubble failed when append itself failed (still "sending"). - const stillSending = (get().messagesByConversation[conversationId] ?? []) - .find((m) => m.id === resolvedId) - ?.deliveryStatus === "sending"; + const stillSending = + (get().messagesByConversation[conversationId] ?? []).find( + (m) => m.id === resolvedId, + )?.deliveryStatus === "sending"; + // Timeout, terminal, or any other failure: surface failed so the user + // can retry (WeChat-style). Never leave a permanent spinner; never + // false-sent. Background outbox may still ack later and upgrade to sent. if (stillSending) { - patchDelivery("failed"); + patchMessageDelivery( + conversationId, + resolvedId, + { deliveryStatus: "failed" }, + { accountScopeGen }, + ); } await quietRefreshConversationSlices(get, conversationId); throw e; @@ -610,6 +653,7 @@ export function createUseCasesActions( retryFailedMessage: async (conversationId, messageId) => { // Constraint #2: never insert a new optimistic row on retry. Reuse // message_id (store append is idempotent) and patch delivery in place. + const accountScopeGen = getAccountScopeGeneration(); const list = get().messagesByConversation[conversationId] ?? []; const failed = list.find((m) => m.id === messageId); if (!failed) throw new Error("message not found"); @@ -618,141 +662,54 @@ export function createUseCasesActions( } const messageBody = failed.body; const replyToMessageId = failed.replyToMessageId; + const retryAt = failed.createdAtMs ?? Date.now(); + const retryClock = + formatLocalClock(retryAt) || formatLocalClock(Date.now()); - const patchDelivery = ( - status: DeliveryStatus, - seq?: number, - ) => { - set((s) => ({ - messagesByConversation: { - ...s.messagesByConversation, - [conversationId]: (s.messagesByConversation[conversationId] ?? []).map( - (m) => - m.id === messageId - ? { - ...m, - deliveryStatus: status, - messageSeq: seq ?? m.messageSeq, - } - : m, - ), - }, - })); - }; - - patchDelivery("sending"); + patchMessageDelivery( + conversationId, + messageId, + { deliveryStatus: "sending" }, + { accountScopeGen }, + ); if (get().source !== "daemon") { - patchDelivery("sent"); + patchMessageDelivery( + conversationId, + messageId, + { deliveryStatus: "sent" }, + { accountScopeGen }, + ); return; } try { - const conv = get().conversations.find((c) => c.id === conversationId); - const project = get().projects.find((p) => p.id === conv?.projectId); - if (!conv || !project) { - throw new Error("conversation or project not found"); - } - - // Same pipeline as sendMessage: validate → append → Hub uplink. - const mentionProfiles = await loadMentionProfiles( - conversationId, - conv.participatingAgents, - conv.participatingBots, - ); - const installedAgents = new Set( - get() - .clis.filter((c) => c.installed) - .map((c) => c.agent.toLowerCase()), - ); - resolveDispatchTargets({ - messageBody, - participatingAgents: membershipTokensFromConv(conv), - installedAgents, - mentionProfiles, - }); - const structuredMentions = buildStructuredMentions( - messageBody, - mentionProfiles, - ); - if (!cloudAuthenticated()) { - throw new Error( - "Sign in to send collaboration messages. Bot delivery requires Account Hub sync.", - ); - } - - const retryAt = failed.createdAtMs ?? Date.now(); - const retryClock = formatLocalClock(retryAt) || formatLocalClock(Date.now()); - const cloudAck = await syncUserMessageToCloud({ + await deliverMessage(get, set, { conversationId, messageId, - text: messageBody, - title: conv.title, + messageBody, replyToMessageId, createdAtMs: retryAt, - agentRuntimes: (() => { - const fromBots = conv.participatingBots - ?.map((b) => b.runtime.trim().toLowerCase()) - .filter(Boolean); - if (fromBots && fromBots.length > 0) return fromBots; - return conv.participatingAgents; - })(), - messageSource: "client_live", - mentions: - structuredMentions.length > 0 ? structuredMentions : undefined, - }); - patchDelivery("sent", cloudAck?.messageSeq); - set((s) => ({ - messagesByConversation: { - ...s.messagesByConversation, - [conversationId]: (s.messagesByConversation[conversationId] ?? []).map( - (m) => - m.id === messageId - ? { ...m, time: retryClock, createdAtMs: retryAt } - : m, - ), - }, - })); - const railPreview = - messageBody.trim().length > 88 - ? `${messageBody.trim().slice(0, 88)}…` - : messageBody.trim(); - patchRailActivity(set, conversationId, railPreview, retryAt); - try { - await daemonApi.appendUserMessage( - conversationId, - messageBody, - messageId, - ); - } catch (localErr) { - console.warn( - "[workspace] local workbench projection after Hub Ack failed", - localErr, - ); - } - set({ actionError: null }); - void get().loadTimeline(conversationId, { quiet: true }); - - await quietRefreshConversationSlices(get, conversationId); - await minosQueryClient.invalidateQueries({ - queryKey: queryKeys.conversations(conv.projectId), - }); - await minosQueryClient.invalidateQueries({ - queryKey: queryKeys.projectSessions(conv.projectId), + clock: retryClock, + accountScopeGen, }); - await minosQueryClient.invalidateQueries({ - queryKey: queryKeys.inspectorSessions(conversationId), - }); - await get().loadConversations(conv.projectId); } catch (e) { const message = e instanceof Error ? e.message : String(e); + if (accountScopeGen !== getAccountScopeGeneration()) { + throw e; + } set({ actionError: message }); - // Only flip to failed when still sending (append never succeeded). - const stillSending = (get().messagesByConversation[conversationId] ?? []) - .find((m) => m.id === messageId) - ?.deliveryStatus === "sending"; + const stillSending = + (get().messagesByConversation[conversationId] ?? []).find( + (m) => m.id === messageId, + )?.deliveryStatus === "sending"; if (stillSending) { - patchDelivery("failed"); + patchMessageDelivery( + conversationId, + messageId, + { deliveryStatus: "failed" }, + { accountScopeGen }, + ); } await quietRefreshConversationSlices(get, conversationId); throw e; diff --git a/crates/minos-daemon/src/handle.rs b/crates/minos-daemon/src/handle.rs index 7dd85569..23f72982 100644 --- a/crates/minos-daemon/src/handle.rs +++ b/crates/minos-daemon/src/handle.rs @@ -368,19 +368,37 @@ impl DaemonHandle { /// calling twice is a benign no-op after the first success. /// /// Shutdown sequence: - /// 1. Best-effort `AgentGlue::shutdown` — suspend (not close) every live - /// thread and **synchronously** persist `suspended` + `needs_continue`. - /// 2. SIGTERM every provider child with a 5s grace, then SIGKILL. + /// 1. Best-effort `AgentGlue::shutdown` (bounded) — suspend live threads. + /// 2. **Always** SIGTERM/SIGKILL every provider child (even if step 1 hangs + /// or the outer caller times out mid-await — step 2 runs after the + /// agent await completes or times out locally, never gated on success). /// 3. Tear down local RPC discovery + the relay WS client. /// /// Orphan recovery for unclean kills runs on the **next** start via /// `mark_orphans_suspended` (not here). #[allow(clippy::missing_errors_doc)] pub async fn stop(&self) -> Result<(), MinosError> { - match self.inner.agent.shutdown().await { - Ok(()) | Err(MinosError::AgentNotRunning) => {} - Err(err) => return Err(err), + // Bound agent suspend so a stuck cancel cannot prevent provider kill. + const AGENT_SHUTDOWN_BUDGET: std::time::Duration = std::time::Duration::from_secs(4); + match tokio::time::timeout(AGENT_SHUTDOWN_BUDGET, self.inner.agent.shutdown()).await { + Ok(Ok(())) | Ok(Err(MinosError::AgentNotRunning)) => {} + Ok(Err(err)) => { + tracing::warn!( + target: "minos_daemon::handle", + error = %err, + "agent shutdown returned error; continuing provider terminate" + ); + } + Err(_) => { + tracing::warn!( + target: "minos_daemon::handle", + timeout_secs = AGENT_SHUTDOWN_BUDGET.as_secs(), + "agent shutdown timed out; continuing provider terminate" + ); + } } + // Provider process-group terminate is the hard authorization boundary + // for leftover CLI children — always run after the agent attempt. self.inner .agent .manager diff --git a/crates/minos-daemon/src/local_rpc.rs b/crates/minos-daemon/src/local_rpc.rs index 8dba3c8b..cadd0022 100644 --- a/crates/minos-daemon/src/local_rpc.rs +++ b/crates/minos-daemon/src/local_rpc.rs @@ -11,8 +11,8 @@ use minos_protocol::{ AppendConversationMessageParams, AppendConversationMessageResponse, ApprovalDecisionRequest, CloseSessionRequest, CreateConversationParams, CreateConversationResponse, CreateProjectRequest, CreateProjectResponse, HealthResponse, HostApplyLinkTokenParams, - HostApplyLinkTokenResponse, HostPrepareLinkResponse, HostSignLinkProofParams, - HostSignLinkProofResponse, InterruptSessionRequest, ListClisResponse, + HostApplyLinkTokenResponse, HostClearCredentialResponse, HostPrepareLinkResponse, + HostSignLinkProofParams, HostSignLinkProofResponse, InterruptSessionRequest, ListClisResponse, ListConversationAgentSessionsParams, ListConversationAgentSessionsResponse, ListConversationMessagesParams, ListConversationMessagesResponse, ListConversationsParams, ListConversationsResponse, ListProjectsResponse, LocalDaemonRpcServer, LocalSessionSnapshot, @@ -98,6 +98,15 @@ impl LocalDaemonRpcServer for LocalRpcImpl { .map_err(rpc_err) } + async fn host_clear_credential( + &self, + ) -> jsonrpsee::core::RpcResult { + let Some(relay) = self.relay.as_ref() else { + return Err(host_link_unavailable()); + }; + relay.clear_link_token().map_err(rpc_err) + } + async fn list_clis(&self) -> jsonrpsee::core::RpcResult { Ok(detect_all(self.runner.clone()).await) } diff --git a/crates/minos-daemon/src/relay_client.rs b/crates/minos-daemon/src/relay_client.rs index da32e4f6..e030bfc2 100644 --- a/crates/minos-daemon/src/relay_client.rs +++ b/crates/minos-daemon/src/relay_client.rs @@ -103,6 +103,9 @@ struct Inner { /// Wakes the dispatch loop when pairing redeem writes a new host /// installation token. secret_notify: Arc, + /// Bumped on apply/clear so a live `/ws/host` session closes immediately + /// when the credential is revoked or replaced (not only on daemon stop). + credential_epoch: watch::Sender, /// HTTP client for the backend's `/v1/*` control plane. http: Arc, /// Peer-state publisher kept so `request_pairing_token` can enter the @@ -115,6 +118,8 @@ struct Inner { out_tx: mpsc::Sender, live_tx: mpsc::Sender, backfill_tx: mpsc::Sender, + /// Link-state publisher so account leave can force `/ws/host` offline. + link_tx: watch::Sender, } pub struct RelayClient { @@ -163,6 +168,7 @@ impl RelayClient { let secret_store = Arc::new(StdMutex::new(secret)); let secret_notify = Arc::new(Notify::new()); + let (credential_epoch_tx, _credential_epoch_rx) = watch::channel(0_u64); let http = match RelayHttpClient::new(&backend_url, self_device_id, mac_name.clone()) { Ok(c) => Arc::new(c), Err(e) => { @@ -189,8 +195,9 @@ impl RelayClient { self_device_id, secret: secret_store.clone(), secret_notify: secret_notify.clone(), + credential_epoch: credential_epoch_tx.clone(), backend_url: backend_url.clone(), - link_tx, + link_tx: link_tx.clone(), peer_tx: peer_tx.clone(), out_tx: out_tx.clone(), out_rx, @@ -215,6 +222,7 @@ impl RelayClient { mac_name, secret: secret_store, secret_notify, + credential_epoch: credential_epoch_tx, http, peer_tx, peer_store, @@ -223,6 +231,7 @@ impl RelayClient { out_tx, live_tx, backfill_tx, + link_tx, }); (Arc::new(Self { inner }), link_rx, peer_rx) @@ -257,6 +266,9 @@ impl RelayClient { } /// Persist a host installation token and wake the realtime dial loop. + /// + /// Bumps the credential epoch so any already-open `/ws/host` session for a + /// prior token closes before the dialer reconnects with the new secret. pub fn apply_link_token( &self, host_installation_token: &str, @@ -271,6 +283,7 @@ impl RelayClient { if let Ok(mut guard) = self.inner.secret.lock() { *guard = Some(token); } + bump_credential_epoch(&self.inner.credential_epoch); self.inner.secret_notify.notify_waiters(); tracing::info!( target: "minos_daemon::relay_client", @@ -279,6 +292,29 @@ impl RelayClient { Ok(minos_protocol::HostApplyLinkTokenResponse { linked: true }) } + /// Drop the local host installation token and force `/ws/host` offline. + /// + /// Desktop calls this on account leave so a subsequent login cannot inherit + /// the previous account's host credential or online bit. Bumps the credential + /// epoch so a live dispatch loop closes the socket immediately (not only on + /// daemon shutdown). + pub fn clear_link_token( + &self, + ) -> Result { + if let Ok(mut guard) = self.inner.secret.lock() { + *guard = None; + } + crate::device_secret_store::delete()?; + bump_credential_epoch(&self.inner.credential_epoch); + let _ = self.inner.link_tx.send(RelayLinkState::Disconnected); + self.inner.secret_notify.notify_waiters(); + tracing::info!( + target: "minos_daemon::relay_client", + "host installation token cleared; /ws/host dialer disabled until re-link" + ); + Ok(minos_protocol::HostClearCredentialResponse { cleared: true }) + } + /// Back-compat helper for callers that still think in terms of a /// single paired device. Deletes the first currently paired row, if /// any, via the host-scoped `/v1/me/peers/{mobile_device_id}` route. @@ -372,6 +408,7 @@ struct DispatchCtx { self_device_id: DeviceId, secret: Arc>>, secret_notify: Arc, + credential_epoch: watch::Sender, backend_url: String, link_tx: watch::Sender, peer_tx: watch::Sender, @@ -392,6 +429,16 @@ struct DispatchCtx { host_topic_seq: Arc>, } +fn bump_credential_epoch(tx: &watch::Sender) { + let next = tx.borrow().wrapping_add(1); + let _ = tx.send(next); +} + +/// True when the live session's credential epoch no longer matches (clear/apply). +fn credential_epoch_changed(rx: &watch::Receiver, session_epoch: u64) -> bool { + *rx.borrow() != session_epoch +} + fn clear_peer_snapshot( peer_store: &Arc>>, peers_store: &Arc>>, @@ -424,12 +471,15 @@ fn clear_host_installation_token(ctx: &DispatchCtx) { enum CycleOutcome { Reconnect, TokenRejected, + /// Local clear/apply invalidated the session; re-read secret without backoff. + CredentialRevoked, Shutdown, } async fn run_dispatch(mut ctx: DispatchCtx, mut shutdown_rx: oneshot::Receiver<()>) { let mut attempt: u32 = 0; let mut logged_missing_token = false; + let mut epoch_rx = ctx.credential_epoch.subscribe(); loop { let Some(secret) = secret_snapshot_or_reload(&ctx.secret, &ctx.last_error) else { @@ -449,15 +499,22 @@ async fn run_dispatch(mut ctx: DispatchCtx, mut shutdown_rx: oneshot::Receiver<( return; } () = ctx.secret_notify.notified() => {} + // clear/apply may wake us before secret_notify if races reorder. + changed = epoch_rx.changed() => { + if changed.is_err() { + return; + } + } () = tokio::time::sleep(TOKEN_WAIT_POLL_INTERVAL) => {} } attempt = 0; continue; }; logged_missing_token = false; + let session_epoch = *epoch_rx.borrow(); let _ = ctx.link_tx.send(RelayLinkState::Connecting { attempt }); - let outcome = Box::pin(run_once(&mut ctx, &mut shutdown_rx, &secret)).await; + let outcome = Box::pin(run_once(&mut ctx, &mut shutdown_rx, &secret, session_epoch)).await; match outcome { CycleOutcome::Shutdown => { @@ -469,6 +526,12 @@ async fn run_dispatch(mut ctx: DispatchCtx, mut shutdown_rx: oneshot::Receiver<( let _ = ctx.link_tx.send(RelayLinkState::Disconnected); attempt = 0; } + CycleOutcome::CredentialRevoked => { + // Secret already cleared or replaced; force offline then re-enter + // the top of the loop so we only dial with a current credential. + let _ = ctx.link_tx.send(RelayLinkState::Disconnected); + attempt = 0; + } CycleOutcome::Reconnect => { attempt = attempt.saturating_add(1); let delay = delay_for_attempt(attempt); @@ -486,6 +549,13 @@ async fn run_dispatch(mut ctx: DispatchCtx, mut shutdown_rx: oneshot::Receiver<( let _ = ctx.link_tx.send(RelayLinkState::Disconnected); return; } + changed = epoch_rx.changed() => { + if changed.is_err() { + return; + } + // Credential change aborts backoff; re-read secret immediately. + attempt = 0; + } () = tokio::time::sleep(delay) => {} } } @@ -497,7 +567,9 @@ async fn run_once( ctx: &mut DispatchCtx, shutdown_rx: &mut oneshot::Receiver<()>, secret: &DeviceSecret, + session_epoch: u64, ) -> CycleOutcome { + let mut epoch_rx = ctx.credential_epoch.subscribe(); // Dial /ws/host with Authorization: Bearer hit_* (no ticket dance). let ws_url = build_host_ws_url(&ctx.backend_url); let request = match build_host_ws_request(&ws_url, secret) { @@ -513,9 +585,22 @@ async fn run_once( } }; + if credential_epoch_changed(&epoch_rx, session_epoch) { + return CycleOutcome::CredentialRevoked; + } + let ws = tokio::select! { biased; _ = &mut *shutdown_rx => return CycleOutcome::Shutdown, + changed = epoch_rx.changed() => { + if changed.is_err() { + return CycleOutcome::Shutdown; + } + if credential_epoch_changed(&epoch_rx, session_epoch) { + return CycleOutcome::CredentialRevoked; + } + return CycleOutcome::Reconnect; + } res = tokio_tungstenite::connect_async(request) => match res { Ok((stream, _resp)) => stream, Err(WsError::Http(resp)) if resp.status().as_u16() == 401 => { @@ -565,10 +650,17 @@ async fn run_once( } }; + if credential_epoch_changed(&epoch_rx, session_epoch) { + // Token was cleared/replaced during handshake; drop the new socket. + let (mut sink, _stream) = ws.split(); + let _ = sink.send(Message::Close(None)).await; + return CycleOutcome::CredentialRevoked; + } + tracing::info!(target: "minos_daemon::relay_client", "relay websocket upgraded via host bearer"); refresh_peers_from_backend(ctx, Some(secret)).await; - Box::pin(dispatch_loop(ws, ctx, shutdown_rx)).await + Box::pin(dispatch_loop(ws, ctx, shutdown_rx, session_epoch)).await } /// Cold snapshot of linked account clients (online / last_active). @@ -636,8 +728,10 @@ async fn dispatch_loop( >, ctx: &mut DispatchCtx, shutdown_rx: &mut oneshot::Receiver<()>, + session_epoch: u64, ) -> CycleOutcome { let (mut sink, mut stream) = ws.split(); + let mut epoch_rx = ctx.credential_epoch.subscribe(); let mut heartbeat = tokio::time::interval(RELAY_PING_INTERVAL); heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); let mut last_pong_at = Instant::now(); @@ -649,12 +743,34 @@ async fn dispatch_loop( // - StreamEvent kind=presence → refresh_peers_from_backend // No periodic poll (avoids dual SSOT with live presence pushes). loop { + if credential_epoch_changed(&epoch_rx, session_epoch) { + tracing::info!( + target: "minos_daemon::relay_client", + "host credential revoked/replaced; closing /ws/host" + ); + let _ = sink.send(Message::Close(None)).await; + return CycleOutcome::CredentialRevoked; + } tokio::select! { biased; _ = &mut *shutdown_rx => { let _ = sink.send(Message::Close(None)).await; return CycleOutcome::Shutdown; } + changed = epoch_rx.changed() => { + if changed.is_err() { + let _ = sink.send(Message::Close(None)).await; + return CycleOutcome::Shutdown; + } + if credential_epoch_changed(&epoch_rx, session_epoch) { + tracing::info!( + target: "minos_daemon::relay_client", + "host credential revoked/replaced; closing /ws/host" + ); + let _ = sink.send(Message::Close(None)).await; + return CycleOutcome::CredentialRevoked; + } + } out = ctx.out_rx.recv() => { let Some(frame) = out else { return CycleOutcome::Shutdown; diff --git a/crates/minos-protocol/src/local_rpc.rs b/crates/minos-protocol/src/local_rpc.rs index b7a1b150..1ab02f9a 100644 --- a/crates/minos-protocol/src/local_rpc.rs +++ b/crates/minos-protocol/src/local_rpc.rs @@ -134,6 +134,14 @@ pub trait LocalDaemonRpc { req: crate::HostApplyLinkTokenParams, ) -> jsonrpsee::core::RpcResult; + /// Drop local host installation token and disconnect `/ws/host`. + /// Used when Desktop leaves an account scope so the next account cannot + /// inherit the previous host credential. + #[method(name = "host_clear_credential")] + async fn host_clear_credential( + &self, + ) -> jsonrpsee::core::RpcResult; + #[method(name = "list_clis")] async fn list_clis(&self) -> jsonrpsee::core::RpcResult; diff --git a/crates/minos-protocol/src/messages.rs b/crates/minos-protocol/src/messages.rs index a47785be..8a214cfc 100644 --- a/crates/minos-protocol/src/messages.rs +++ b/crates/minos-protocol/src/messages.rs @@ -745,6 +745,12 @@ pub struct HostApplyLinkTokenResponse { pub linked: bool, } +/// Daemon local RPC: drop local `hit_` and disconnect `/ws/host` dialer. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct HostClearCredentialResponse { + pub cleared: bool, +} + /// Account-side request to target one paired host for a CLI scan. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct ListHostClisRequest { diff --git a/docs/architecture-desktop.md b/docs/architecture-desktop.md index aea2c1bd..3f12a2e8 100644 --- a/docs/architecture-desktop.md +++ b/docs/architecture-desktop.md @@ -41,7 +41,7 @@ | Markdown | `react-markdown` + `remark-gfm` + Shiki `CodeBlock` | 完成态 GFM;streaming 纯文本;fenced code 懒加载 Shiki 高亮 | | 主题 | Shiki theme JSON → CSS vars(`ThemeProvider`) | Host → Appearance 选主题/强调色;FOUC 用 localStorage 缓存 vars;默认 `minos`(warm) | | 长列表 | `@tanstack/react-virtual`(侧栏)+ `virtua`(conversation timeline) | ConversationList + **Sessions 左栏**(`SessionListPane` + flatten 树)用 `VirtualizedList`;主时间线 `VList` + stick-to-bottom/`shift` prepend;session **transcript** 仍分页 DOM(硬上限 2000),避免与审批/流式测高互殴。**Keep-alive 注意**:Work 三页用 CSS `hidden` 挂载;虚拟列表在 `display:none` 下 scrollport 高度为 0,切回 tab 时必须 remount 或 `measure()`(`VirtualizedList` 在 0→有高度时重测 + 仅在 tab active 时挂载侧栏 virtualizer),否则会出现空白/条目挤在底部、要点一下才出来 | -| 状态 | Zustand 5 + TanStack Query 5 | **混合**:RQ 可缓存 catalog 网络;**会 merge 进 SessionEntity 的 list**(inspector / project sessions)一律 `staleTime: 0`,禁止 30s 陈旧 lifecycle。Zustand 管 timeline/transcript/SessionEntity/乐观发送/UI 指针(L0–L6)。**SessionEntity 唯一写漏斗**:`mergeSessionEntity` / `patchSessionEntity` → `commitSessionEntity`(membership 投影 + `conversation.runningCount/approvalCount` 由 Entity Σ 重算)。list hydrate 是 sample(防 stale demote);manager / resume / resolve 为 authoritative。Inspector 列表只读投影行,禁止组件层再 overlay 全表 Entity。 |) +| 状态 | Zustand 5 + TanStack Query 5 | **混合**:RQ 是 store loader 的 transport 缓存,**不是** projects/conversations/clis UI SSOT。**会 merge 进 SessionEntity 的 list**(inspector / project sessions)一律 `staleTime: 0`,禁止 30s 陈旧 lifecycle。Zustand 管 timeline/transcript/SessionEntity/乐观发送/UI 指针(L0–L6)。**SessionEntity 唯一写漏斗**:`mergeSessionEntity` / `patchSessionEntity` → `commitSessionEntity` / `commitHydratedSessionEntities`(membership 投影 + `conversation.runningCount/approvalCount` 由 Entity Σ 重算)。list hydrate 是 sample(防 stale demote);manager / resume / resolve 为 authoritative。Inspector 列表只读投影行,禁止组件层再 overlay 全表 Entity。 |) | 图标 | Lucide React | 导航与工具栏 | | 本机 API | `@tauri-apps/api` | `invoke` → Rust | | 自动更新 | `tauri-plugin-updater` + `plugin-process` | 仅 release 构建启用;见 [desktop-auto-update.md](./desktop-auto-update.md) | @@ -161,6 +161,8 @@ apps/desktop/ lib/agentConfigProjection.ts # pure map: list_clis/list_models → UI options host/ # HostView.tsx · identity + cloud status (auto-connect; no link CTA) lib/host-link-flow.ts # pure prepare→sign→cloud→apply orchestration + lib/ensure-host-connection.ts # registerHostCredential + waitForCloudOnline ports + lib/host-connection-machine.ts # pure ensure decision (noop/wait/register) + effect run lib/host-account-presenter.ts # Local only / Linked / Error (+ defensive signed out) chat/ # Conversation chat UI (Wave 1–2) Timeline.tsx # thin container: load/poll + compose children @@ -200,18 +202,16 @@ apps/desktop/ host-status.ts # Ready · Local only / Linked / This Mac account-session.ts # MinosSession + HostLinkState localStorage minos-cloud.ts # /v1/auth/* + /v1/hosts/* + Hub IM HTTP - im-cloud-sync.ts # Hub shell upsert + user/agent_result Outbox (host_projection uplink) + cloud-auth.ts # process-local getCloudAuth port (registered by account-store) im-outbox.ts # durable Tauri SQLite Outbox (user_message | agent_result | reaction_toggle | approval_resolve); intent lanes - im-cloud-inbound.ts # Hub cold pull → TimelineMessage[] (no daemon append) cloud-timeline.ts # mergeCloudAndLocalTimeline (Hub chat + local tool/git; same-id only) cloud-cursors.ts # per-topic topic_seq resume_after (localStorage) - cloud-realtime.ts # Sync SM + account/conversation Subscribe + SnapshotRequired + cloud-realtime.ts # pure transport Sync SM (no store import) cloud-digest-cache.ts # Hub list digests: hydrate once, live patchOne - conversation-list-merge.ts # daemon rows ∥ Hub digests (isCloudImMode ≠ host-linked) - im-cloud-bridge.ts # auth → realtime → timeline + rail digest patch + conversation-list-merge.ts # daemon rows ∥ Hub digests; unreadSource hub|local # 协作气泡:Hub 是唯一权威,Desktop 只维护投影与 Outbox supabase.ts # optional Supabase email/password IdP - mock-data.ts + mock-data.ts # fixtures + presentation maps only toast.ts # sonner wrappers use-stick-to-bottom.ts scroll-restore.ts # identity-based prepend restore @@ -225,10 +225,19 @@ apps/desktop/ daemon-events.ts # listen daemon://ingest|manager|conversation|push-status initial-render-ready.ts # emit first-layout event so host can show window daemon.ts · agent-route.ts · … + domain/ + collaboration.ts # Project / Conversation / TimelineMessage / ProjectSession store/ # L0–L6 工作区契约不变;chat reactions 不进 workspace ui-store.ts # nav + drafts + replyTo + commandPaletteOpen - account-store.ts # Minos session + auto cloud ensure (sign-in / Online·Offline) - workspace-store.ts # thin create() + re-export useWorkspaceStore + account-store.ts # Minos session + host ensure delegate (sign-in / Online·Offline) + daemon-status-port.ts # narrow host flags port (breaks account↔workspace cycle) + leave-account-scope.ts # sole account-boundary teardown + workspace-store.ts # thin create() + register daemon flags provider + im/ + im-cloud-bridge.ts # auth → realtime → timeline + rail digest patch + im-cloud-sync.ts # Hub shell upsert + Outbox drain (uses getCloudAuth) + im-cloud-inbound.ts # Hub cold pull → TimelineMessage[] + cloud-digest-ensure.ts # single-flight digest hydrate workspace/ types.ts # WorkspaceState / ResourceFetchStatus / ProjectSession helpers.ts # barrel re-export (stable import path) @@ -241,7 +250,7 @@ apps/desktop/ shared.ts # quietRefresh / startNewAgentSession helpers create-actions.ts # compose L1–L6 action factories connection.ts # L1 bootstrap / livePush / refreshProjects - conversation-list.ts # L3a ConversationList + conversation-list.ts # L3a ConversationList (Hub-primary unread when IM mode) timeline.ts # L3a Timeline inspector.ts # L3a Inspector session-list.ts # L3b SessionList @@ -263,6 +272,10 @@ apps/desktop/ | 文本缩放 | `useWebviewZoomShortcuts` 挂在 **`App`**(boot + shell 始终生效):⌘/Ctrl ±/0 调 `documentElement` rem(`minos:text-scale`);Tauri webview zoom 固定为 1 | | Daemon 连接反馈 | `ConnectionToasts` 监听 `connection.connected` 边沿;**disconnect 防抖 2s**(`connection-toast-policy`)。持久侧栏卡 `SidebarConnectionCard`(同防抖 + dismiss 至本 episode;Retry → bootstrap / Host) | | Workspace 边界 reset | `resetWorkspaceModuleState`:bootstrap wipe / mock 路径统一清 timers、inflight、event bridge、reactions、composer ephemeral。**Project 切换不调用**。新模块单例必须登记于此 | +| Account 边界 leave | `leaveAccountScope`:登出 / 换号 / auth-invalid 唯一入口。停 IM bridge + outbox worker generation、invalidate digest、清 topic cursors、`minosQueryClient.clear`、empty workspace(`workspaceAccountId=null`/`bootEpoch=0`)、清 UI 选中态、best-effort `daemon_host_clear_credential`。bootstrap `alreadyReady` 要求 `workspaceAccountId === session.accountId` | +| Outbox 账户归属 | `ImOutboxEntry.accountId` 不可变;`listDuePending*` 只领取当前账户;空 accountId 隔离永不发送 | +| Host 在线归属 | `hostCredentialAccountId` 与 session 一致才可 `cloudStatus=online` / 复用 hit_;换号 force re-register | +| Timeline 写漏斗 | `store/workspace/timeline-write.ts` 是 `messagesByConversation` 唯一写入口(`applyHubMessage` / `replaceWindowFromHydrate` / `setTimelineWindow` / optimistic + delivery)。Hub bridge、loadTimeline、send/retry 必须经此;daemon live-ingress 只 quiet re-list | | Inspector 辅面板 | `AuxiliaryPanel`:`split`(resizable)/ `rail` / `overlay`(<1100px 浮层+backdrop);`SessionInspector` 统一壳 | | Motion tokens | `modalMotion` / `popoverSurface` 统一 Dialog / Popover / Dropdown enter-exit | | Modal backdrop | `modalBackdrop`:`backdrop-blur-[10px]` + `bg-black/[0.04] dark:bg-black/25`(偏透毛玻璃,能看清背景结构;禁止 `bg-ink/…` 当 scrim) | @@ -276,7 +289,8 @@ apps/desktop/ | Reply draft(Wave 2) | `ui-store.replyToMessageIdByConversation`;Composer 显示 reply chip;`sendMessage(..., { replyToMessageId })` 写乐观行;daemon append 尚未持久化 reply_to | | Follow 迟滞 | unfollow 80px / re-follow 12px;wheel-up 后 ~320ms 禁止 re-follow 与 pin,减轻到底回弹再上滑的抢滚动 | | Project tab 切换 | Conversations / Sessions / Board **keep-alive**(`hidden` + `inert`,不 unmount);有缓存时 transcript **quiet append**;`useLayoutEffect` 首帧 pin 到底。**Sessions keep-alive 不得**在 Conversations 下 `selectSession(null)` / auto-select(否则抹掉 Inspector 点选 SessionDetail)。`loadTranscript` quiet peek **不 bump** generation,避免与 hard open 竞态丢弃整页;打开 session 必建 `transcriptsBySession` key 供 ingest 合并 | -| Session 状态 | **L4 `sessionsById`(SessionEntity)为 status / hasPendingApproval 唯一真相**;`sessionsByConversation` / `projectSessionsByProject` / Attention 经 `projectEntityIntoLists` 投影。hydrate:RQ 缓存 list 索引 → upsert Entity → `rowsFromEntities` 同步兄弟 list。无 `projectSessions` 全局镜像。SessionList **只** `listProjectSessions(projectId)`(`queryKeys.projectSessions`);Inspector **只** `listSessions(conversationId)`(`queryKeys.inspectorSessions`);Attention 打开再跨 project hydrate(**不**驱动侧栏 badge) | +| Session 状态 | **L4 `sessionsById`(SessionEntity)为 status / hasPendingApproval 唯一真相**;`sessionsByConversation` / `projectSessionsByProject` / Attention 经 `projectEntityIntoLists` 投影。hydrate:store loader 经 RQ `fetchQuery`(`staleTime: 0`)拉 list → upsert Entity → **必须** `commitHydratedSessionEntities` / `commitSessionEntity` 写回(禁止 ad-hoc `sessionsById` 旁路)。无 `projectSessions` 全局镜像。SessionList **只** `listProjectSessions(projectId)`(`queryKeys.projectSessions`);Inspector **只** `listSessions(conversationId)`(`queryKeys.inspectorSessions`);Attention 打开再跨 project hydrate(**不**驱动侧栏 badge) | +| Conversation rail unread | Authenticated Hub IM:`unreadSource: "hub"`(digest / live patch 为 SSOT);daemon 只补 host-local 字段,不得覆盖 Hub unread。未登录 / daemon-only:`unreadSource: "local"` | | Live status | Manager / ingest 经 Entity 写入;`hasPendingApproval` 抬 `needs_approval`,manager 不得在 pending 时降级。Transcript 淘汰后审批 fallback 看 Entity。**`livePush===true` 时不 setInterval 盲刷**;pump 结束 emit `daemon://push-status` → `livePush=false` 恢复 Timeline/Sessions 降级 quiet poll | | Attention badge | Σ `project.needsAttention`;bootstrap / refreshProjects 后 **quiet** `loadConversations` 全 known projects(有界并发),用 DTO `approvalCount`+unread 聚合;**不**常驻 Attention 队列 | | ensureLoaded | per-key single-flight(`shared/lib/desktop-inflight.ts`);Timeline hardMax 500 / Transcript hardMax 2000;resume 去重用模块 Set(禁止 `window.__minos*`) |