The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(config): order workspace transitions so a stale one cannot win
Shanu4a5cdd0e2a66
diff --git a/app/src/lib/nativeNotifications/__tests__/workspaceRouting.test.ts b/app/src/lib/nativeNotifications/__tests__/workspaceRouting.test.tsindex 0c66ab5866..b76cbf4ade 100644--- a/app/src/lib/nativeNotifications/__tests__/workspaceRouting.test.ts+++ b/app/src/lib/nativeNotifications/__tests__/workspaceRouting.test.ts@@ -26,6 +26,8 @@ import {__setActiveWorkspaceForTests,} from '../service';+const WS_C = 'ws_3333333333333333';+vi.mock('../tauriBridge', () => ({ showNativeNotification: vi.fn() }));vi.mock('../../../services/socketService', () => ({@@ -35,7 +37,7 @@ vi.mock('../../../services/socketService', () => ({const WS_A = 'ws_1111111111111111';const WS_B = 'ws_2222222222222222';-function notify(overrides: { id: string; workspace?: string | null }) {+function notify(overrides: { id: string; workspace?: string | null; workspace_revision?: number }) {__handleCoreNotificationForTests({id: overrides.id,category: 'system',@@ -43,6 +45,7 @@ function notify(overrides: { id: string; workspace?: string | null }) {body: 'ac.inference.sh/mcp is not being retried.',timestamp_ms: 1,workspace: overrides.workspace,+ workspace_revision: overrides.workspace_revision,});}@@ -123,3 +126,60 @@ describe('core notification workspace routing', () => {expect(items().some(item => item.id === 'mcp:b')).toBe(true);});});++describe('core notification routing when the client is behind', () => {+ beforeEach(() => {+ __resetForTests();+ vi.clearAllMocks();+ store.dispatch({ type: 'notifications/clearAll' });+ store.dispatch(setPreference({ category: 'system', enabled: true }));+ });++ /**+ * `workspace_changed` and `core_notification` are broadcast by separate+ * tasks, so a notification for the workspace the user just switched *to* can+ * arrive before the switch that announces it. The core already verified that+ * workspace was active; dropping it here would lose a valid alert.+ */+ it('accepts a notification stamped newer than what the client knows', () => {+ __setActiveWorkspaceForTests(WS_A, 4);+ notify({ id: 'mcp:ahead', workspace: WS_B, workspace_revision: 5 });+ expect(items()).toHaveLength(1);+ });++ /** Having caught up, the client must route to the workspace it adopted. */+ it('adopts the newer workspace so later notifications route to it', () => {+ __setActiveWorkspaceForTests(WS_A, 4);+ notify({ id: 'mcp:ahead', workspace: WS_B, workspace_revision: 5 });++ notify({ id: 'mcp:b-again', workspace: WS_B });+ expect(items()).toHaveLength(2);++ notify({ id: 'mcp:stale-a', workspace: WS_A });+ expect(items()).toHaveLength(2);+ });++ /**+ * The case the check exists for. At a revision the client has already caught+ * up to, a mismatched handle is genuinely stale — it would put another+ * account's server name and transport error in front of this one.+ */+ it('drops a mismatch at a revision it has already caught up to', () => {+ __setActiveWorkspaceForTests(WS_B, 5);+ notify({ id: 'mcp:stale', workspace: WS_A, workspace_revision: 5 });+ expect(items()).toHaveLength(0);+ });++ it('drops a mismatch stamped older than what the client knows', () => {+ __setActiveWorkspaceForTests(WS_C, 9);+ notify({ id: 'mcp:older', workspace: WS_A, workspace_revision: 2 });+ expect(items()).toHaveLength(0);+ });++ /** An unstamped mismatch cannot be shown to be a catch-up, so it drops. */+ it('drops a mismatch with no revision at all', () => {+ __setActiveWorkspaceForTests(WS_A, 4);+ notify({ id: 'mcp:unstamped', workspace: WS_B });+ expect(items()).toHaveLength(0);+ });+});diff --git a/app/src/lib/nativeNotifications/service.ts b/app/src/lib/nativeNotifications/service.tsindex b2b45cc5d8..633e2e98c4 100644--- a/app/src/lib/nativeNotifications/service.ts+++ b/app/src/lib/nativeNotifications/service.ts@@ -32,6 +32,17 @@ let disconnectListener: ((...args: unknown[]) => void) | null = null;*/let activeWorkspace: string | null = null;+/**+ * Revision of the workspace transition `activeWorkspace` came from.+ *+ * The core seeds each client on connect from one task and broadcasts switches+ * from another, so a snapshot resolved before a switch can be delivered after+ * its broadcast. Keeping the highest revision seen and discarding anything+ * older stops a late snapshot talking this client back into the previous+ * workspace.+ */+let activeWorkspaceRevision = 0;+interface ChatDonePayload {thread_id?: string;request_id?: string;@@ -59,10 +70,14 @@ interface CoreNotificationPayload {// Opaque handle of the workspace this notification belongs to, absent when// it is not workspace-bound (issue #5966). See `isForActiveWorkspace`.workspace?: string | null;+ // Workspace revision the core's announcement gate checked against, set only+ // when `workspace` is. See `isForActiveWorkspace`.+ workspace_revision?: number;}interface WorkspaceChangedPayload {workspace?: string | null;+ revision?: number;}/**@@ -86,10 +101,32 @@ interface WorkspaceChangedPayload {* Failing open here is the opposite of the core's fail-closed gate, and* deliberately so: the core is the one deciding whether to *send*, this is a* second check on something already sent past that gate.+ *+ * The revision separates the two ways a handle can mismatch. This event and+ * `workspace_changed` are broadcast by separate tasks, so a notification for+ * the workspace the user just switched *to* can arrive before the switch that+ * announces it. A payload stamped with a revision newer than this client's+ * means the client is simply behind: the core verified that workspace was+ * active, so accept it and catch up rather than dropping a valid alert. Only a+ * mismatch at a revision this client has already caught up to is the stale+ * case the check exists for.*/function isForActiveWorkspace(payload: CoreNotificationPayload): boolean {if (!payload.workspace || !activeWorkspace) return true;- return payload.workspace === activeWorkspace;+ if (payload.workspace === activeWorkspace) return true;+ const revision = payload.workspace_revision;+ if (typeof revision === 'number' && revision > activeWorkspaceRevision) {+ log(+ '[socket] core_notification is ahead of this client (rev=%d > %d); adopting %s',+ revision,+ activeWorkspaceRevision,+ payload.workspace+ );+ activeWorkspace = payload.workspace;+ activeWorkspaceRevision = revision;+ return true;+ }+ return false;}function windowIsFocused(): boolean {@@ -212,8 +249,21 @@ export function startNativeNotificationsService(): void {log('[socket] workspace_changed without a handle ignored');return;}+ // A payload without a revision is treated as revision 0 and therefore+ // only accepted before anything else has been seen — an old core cannot+ // overwrite a newer switch from a current one.+ const revision = typeof p.revision === 'number' ? p.revision : 0;+ if (activeWorkspace !== null && revision < activeWorkspaceRevision) {+ log(+ '[socket] workspace_changed rev=%d discarded, already at rev=%d',+ revision,+ activeWorkspaceRevision+ );+ return;+ }+ activeWorkspaceRevision = revision;if (activeWorkspace === p.workspace) return;- log('[socket] workspace_changed %s -> %s', activeWorkspace, p.workspace);+ log('[socket] workspace_changed %s -> %s (rev=%d)', activeWorkspace, p.workspace, revision);activeWorkspace = p.workspace;};@@ -257,6 +307,13 @@ export function stopNativeNotificationsService(): void {socketService.off('workspace_changed', workspaceChangedListener);workspaceChangedListener = null;}+ // Forget which workspace was active. The core seeds a client when its+ // *socket* connects, not when this service starts, so a stop → workspace+ // switch → restart over one live socket would otherwise resume holding the+ // pre-switch handle and drop every notification for the workspace the user+ // is now in.+ activeWorkspace = null;+ activeWorkspaceRevision = 0;if (disconnectListener) {socketService.off('disconnect', disconnectListener);disconnectListener = null;@@ -299,8 +356,9 @@ export function __handleCoreNotificationForTests(payload: CoreNotificationPayloa* Exposed for tests — set the workspace this client believes is active, as if* a `workspace_changed` had arrived.*/-export function __setActiveWorkspaceForTests(workspace: string | null): void {+export function __setActiveWorkspaceForTests(workspace: string | null, revision = 0): void {activeWorkspace = workspace;+ activeWorkspaceRevision = revision;}/** Exposed for tests — resets module singletons between runs. */diff --git a/src/core/events.rs b/src/core/events.rsindex f5adb2363e..c10227640c 100644--- a/src/core/events.rs+++ b/src/core/events.rs@@ -1273,7 +1273,17 @@ pub enum DomainEvent {/// client sends/// [`workspace_handle`](crate::openhuman::config::workspace_handle)/// instead, since the path is under the user's home directory.- ActiveWorkspaceChanged { workspace_dir: std::path::PathBuf },+ ActiveWorkspaceChanged {+ workspace_dir: std::path::PathBuf,+ /// Monotonic revision of this transition.+ ///+ /// The connect-time snapshot a client is seeded with and this+ /// broadcast travel on separate tasks, so a snapshot resolved before+ /// a switch can be delivered after it. Carrying the revision lets a+ /// client keep the highest it has seen and discard anything older,+ /// rather than being talked back into the previous workspace.+ revision: u64,+ },/// A component's health status changed.HealthChanged {component: String,diff --git a/src/core/events_tests.rs b/src/core/events_tests.rsindex 4da6cd6288..0c34a90e5d 100644--- a/src/core/events_tests.rs+++ b/src/core/events_tests.rs@@ -1038,6 +1038,7 @@ fn an_empty_artifact_workspace_reads_as_unbound_not_as_a_workspace() {fn the_workspace_switch_announcement_is_not_itself_workspace_bound() {let event = DomainEvent::ActiveWorkspaceChanged {workspace_dir: other_workspace(),+ revision: 1,};assert_eq!(event.workspace_dir(), None);assert_eq!(event.variant_name(), "ActiveWorkspaceChanged");diff --git a/src/core/socketio.rs b/src/core/socketio.rsindex 29c2128ef9..0249bda198 100644--- a/src/core/socketio.rs+++ b/src/core/socketio.rs@@ -517,10 +517,20 @@ pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {match crate::openhuman::config::active_workspace_dir().await {Ok(dir) => {let handle = crate::openhuman::config::workspace_handle(&dir);+ // Read after the resolve, so the revision belongs+ // to the workspace being sent. This task and the+ // switch bridge are separate, so a snapshot+ // resolved before a switch can arrive after its+ // broadcast; the client keeps the highest+ // revision it has seen and discards this one if+ // it lost that race.+ let revision =+ crate::openhuman::config::active_workspace_revision();log::debug!(- "[socketio] emit event=workspace_changed to_client={client_id} workspace={handle}"+ "[socketio] emit event=workspace_changed to_client={client_id} workspace={handle} revision={revision}");- let payload = json!({ "workspace": handle });+ let payload =+ json!({ "workspace": handle, "revision": revision });let _ = socket.emit("workspace_changed", &payload);let _ = socket.emit("workspace:changed", &payload);}@@ -918,12 +928,16 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {let Some(event) = rx.recv().await else {break;};- if let crate::core::events::DomainEvent::ActiveWorkspaceChanged { workspace_dir } =- event+ if let crate::core::events::DomainEvent::ActiveWorkspaceChanged {+ workspace_dir,+ revision,+ } = event{let handle = crate::openhuman::config::workspace_handle(&workspace_dir);- log::info!("[socketio] broadcast workspace_changed workspace={handle}");- let payload = serde_json::json!({ "workspace": handle });+ log::info!(+ "[socketio] broadcast workspace_changed workspace={handle} revision={revision}"+ );+ let payload = serde_json::json!({ "workspace": handle, "revision": revision });let _ = io_workspace.emit("workspace_changed", &payload);let _ = io_workspace.emit("workspace:changed", &payload);}diff --git a/src/openhuman/config/mod.rs b/src/openhuman/config/mod.rsindex 0e42ad9cca..59f040b46f 100644--- a/src/openhuman/config/mod.rs+++ b/src/openhuman/config/mod.rs@@ -27,9 +27,9 @@ pub use ops::*;pub use schema::{action_dir_env_override, active_user_marker_path, active_workspace_dir,- active_workspace_dir_cached, clear_active_user, default_action_dir, default_projects_dir,- default_root_openhuman_dir, pre_login_user_dir, read_active_user_id, resolve_action_dir,- user_openhuman_dir, write_active_user_id, PRE_LOGIN_USER_ID,+ active_workspace_dir_cached, active_workspace_revision, clear_active_user, default_action_dir,+ default_projects_dir, default_root_openhuman_dir, pre_login_user_dir, read_active_user_id,+ resolve_action_dir, user_openhuman_dir, write_active_user_id, PRE_LOGIN_USER_ID,};pub use workspace_handle::workspace_handle;// Crate-internal: workspace→config-dir resolver reused by the cloud embedder.diff --git a/src/openhuman/config/schema/load/active_workspace_tests.rs b/src/openhuman/config/schema/load/active_workspace_tests.rsindex e95e632ec4..06bc434d4c 100644--- a/src/openhuman/config/schema/load/active_workspace_tests.rs+++ b/src/openhuman/config/schema/load/active_workspace_tests.rs@@ -30,7 +30,10 @@ fn starts_unknown_rather_than_guessing() {#[test]fn a_first_publish_is_readable_and_announces() {let mut state = ActiveWorkspace::default();- assert!(state.publish(&ws("a")), "the first resolve is news");+ assert!(+ state.publish(&ws("a")).is_some(),+ "the first resolve is news"+ );assert_eq!(state.current, Some(ws("a")));}@@ -38,7 +41,10 @@ fn a_first_publish_is_readable_and_announces() {fn a_later_publish_replaces_the_previous_workspace_and_announces() {let mut state = ActiveWorkspace::default();state.publish(&ws("a"));- assert!(state.publish(&ws("b")), "a different workspace is a switch");+ assert!(+ state.publish(&ws("b")).is_some(),+ "a different workspace is a switch"+ );assert_eq!(state.current, Some(ws("b")));}@@ -48,9 +54,9 @@ fn a_later_publish_replaces_the_previous_workspace_and_announces() {#[test]fn republishing_the_same_workspace_announces_once() {let mut state = ActiveWorkspace::default();- assert!(state.publish(&ws("a")));- assert!(!state.publish(&ws("a")));- assert!(!state.publish(&ws("a")));+ assert!(state.publish(&ws("a")).is_some());+ assert!(state.publish(&ws("a")).is_none());+ assert!(state.publish(&ws("a")).is_none());assert_eq!(state.current, Some(ws("a")));}@@ -86,7 +92,7 @@ fn re_resolving_the_same_workspace_after_invalidation_does_not_re_announce() {state.invalidate();assert!(- !state.publish(&ws("a")),+ state.publish(&ws("a")).is_none(),"the workspace never actually changed");assert_eq!(state.current, Some(ws("a")));@@ -101,7 +107,7 @@ fn a_different_workspace_after_invalidation_is_announced() {state.publish(&ws("a"));state.invalidate();- assert!(state.publish(&ws("b")));+ assert!(state.publish(&ws("b")).is_some());assert_eq!(state.current, Some(ws("b")));}@@ -126,3 +132,56 @@ fn the_global_publish_survives_an_uninitialised_bus() {// configs concurrently and publish into the same slot. The contract under// test is only that this path does not panic without a bus.}++/// The interleaving CodeRabbit flagged. The bus publish happens outside the+/// lock, so two resolvers can commit in one order and reach the emit in the+/// other. Without a revision, the stale emit wins and — because `announced`+/// already holds the newer workspace — no later resolution ever corrects it,+/// leaving every client on the workspace the user left.+#[test]+fn a_superseded_transition_is_not_announced() {+ let mut state = ActiveWorkspace::default();++ let first = state.publish(&ws("a")).expect("first resolve announces");+ let second = state.publish(&ws("b")).expect("a switch announces");++ // B committed after A, so only B may reach the bus.+ assert!(!state.is_current(first.revision), "A's emit is superseded");+ assert!(+ state.is_current(second.revision),+ "B's emit is the live one"+ );+}++#[test]+fn revisions_increase_only_for_announced_transitions() {+ let mut state = ActiveWorkspace::default();++ let first = state.publish(&ws("a")).expect("announces");+ assert!(+ state.publish(&ws("a")).is_none(),+ "same workspace is silent"+ );+ let second = state.publish(&ws("b")).expect("announces");++ assert!(+ second.revision > first.revision,+ "a real switch must outrank the one before it"+ );+ assert_eq!(+ state.revision, second.revision,+ "a suppressed republish must not consume a revision"+ );+}++/// Invalidation is not a transition — it says the answer is unknown, not that+/// it changed. Bumping the revision there would make every marker write look+/// newer than a switch that had already been announced.+#[test]+fn invalidation_does_not_consume_a_revision() {+ let mut state = ActiveWorkspace::default();+ let announced = state.publish(&ws("a")).expect("announces");+ state.invalidate();+ assert_eq!(state.revision, announced.revision);+ assert!(state.is_current(announced.revision));+}diff --git a/src/openhuman/config/schema/load/dirs.rs b/src/openhuman/config/schema/load/dirs.rsindex 886a48ff97..b1a6495a46 100644--- a/src/openhuman/config/schema/load/dirs.rs+++ b/src/openhuman/config/schema/load/dirs.rs@@ -205,6 +205,9 @@ pub(crate) async fn persist_active_workspace_config_dir(config_dir: &Path) -> Restate_path.display())})?;+ // Again, now that the marker is actually gone — same race as the+ // write branch below.+ super::active_workspace::invalidate_active_workspace();}return Ok(());}@@ -244,6 +247,11 @@ pub(crate) async fn persist_active_workspace_config_dir(config_dir: &Path) -> Re}super::sync_directory(&default_config_dir).await?;+ // Again, now that the marker on disk actually says the new workspace. The+ // pre-write clear alone leaves a window in which a racing resolver reads+ // the *old* marker and refills the cache with the workspace being switched+ // away from.+ super::active_workspace::invalidate_active_workspace();Ok(())}diff --git a/src/openhuman/config/schema/load/mod.rs b/src/openhuman/config/schema/load/mod.rsindex 7faa0c1b54..f241c43f45 100644--- a/src/openhuman/config/schema/load/mod.rs+++ b/src/openhuman/config/schema/load/mod.rs@@ -8,8 +8,8 @@ mod impl_load;mod migrate;mod secrets;-pub use active_workspace::active_workspace_dir_cached;pub(crate) use active_workspace::invalidate_active_workspace;+pub use active_workspace::{active_workspace_dir_cached, active_workspace_revision};pub use dirs::{action_dir_env_override, active_user_marker_path, active_workspace_dir, clear_active_user,default_action_dir, default_projects_dir, default_root_openhuman_dir, pre_login_user_dir,diff --git a/src/openhuman/config/schema/load_user_state.rs b/src/openhuman/config/schema/load_user_state.rsindex 2231d0663e..5e3bc01281 100644--- a/src/openhuman/config/schema/load_user_state.rs+++ b/src/openhuman/config/schema/load_user_state.rs@@ -200,6 +200,12 @@ pub fn write_active_user_id(default_openhuman_dir: &Path, user_id: &str) -> Resu}sync_directory(default_openhuman_dir)?;+ // Again, now that the marker actually says the new user. The pre-write+ // clear is not enough on its own: a resolver racing this call can read the+ // *old* marker after that clear and refill the cache with the workspace+ // being switched away from, which would then read as current after a+ // successful switch.+ crate::openhuman::config::schema::invalidate_active_workspace();tracing::debug!(user_id = %user_id, path = %path.display(), "active user written");Ok(())}@@ -217,6 +223,9 @@ pub fn clear_active_user(default_openhuman_dir: &Path) -> Result<()> {if path.exists() {std::fs::remove_file(&path).with_context(|| format!("Failed to remove active user state: {}", path.display()))?;+ // Again, now that the marker is actually gone — see the note in+ // `write_active_user_id` for the race the pre-clear alone leaves open.+ crate::openhuman::config::schema::invalidate_active_workspace();tracing::debug!(path = %path.display(), "active user cleared");}Ok(())diff --git a/src/openhuman/config/schema/mod.rs b/src/openhuman/config/schema/mod.rsindex 1b160e978c..d19fe09d50 100644--- a/src/openhuman/config/schema/mod.rs+++ b/src/openhuman/config/schema/mod.rs@@ -34,9 +34,9 @@ mod learning;mod load;pub use load::{action_dir_env_override, active_user_marker_path, active_workspace_dir,- active_workspace_dir_cached, clear_active_user, default_action_dir, default_projects_dir,- default_root_openhuman_dir, pre_login_user_dir, read_active_user_id, resolve_action_dir,- user_openhuman_dir, write_active_user_id, PRE_LOGIN_USER_ID,+ active_workspace_dir_cached, active_workspace_revision, clear_active_user, default_action_dir,+ default_projects_dir, default_root_openhuman_dir, pre_login_user_dir, read_active_user_id,+ resolve_action_dir, user_openhuman_dir, write_active_user_id, PRE_LOGIN_USER_ID,};// Crate-internal: the invalidation half of the cached active workspace. The// marker writers in `load_user_state` call it from outside `load`; thediff --git a/src/openhuman/desktop/app_state/ops_part_01.rs b/src/openhuman/desktop/app_state/ops_part_01.rsindex a4a2845f3f..6096bc5017 100644--- a/src/openhuman/desktop/app_state/ops_part_01.rs+++ b/src/openhuman/desktop/app_state/ops_part_01.rs@@ -661,7 +661,24 @@ async fn activate_revalidated_user_dir(user_id: &str) -> Result<Config, String>}}- Config::load_from_default_paths().await.map_err(|error| {+ let config = Config::load_from_default_paths().await.map_err(|error| {format!("failed to reload config after pending session user activation: {error}")- })+ })?;++ // The marker write above cleared the cached active workspace, and+ // `load_from_default_paths` deliberately bypasses the runtime resolver, so+ // nothing has refilled it. Resolve once through the authoritative path,+ // which republishes the cache and announces the switch — otherwise a+ // connected Event Log or notification client keeps the previous+ // workspace's handle until some unrelated later config load happens+ // (#5966). Publishing from `load_from_default_paths` itself would be+ // wrong: it ignores `OPENHUMAN_WORKSPACE`, so under that override it does+ // not know the runtime answer.+ if let Err(error) = crate::openhuman::config::active_workspace_dir().await {+ warn!(+ "{LOG_PREFIX} could not refresh the active workspace after pending session activation: {error}"+ );+ }++ Ok(config)}diff --git a/src/openhuman/desktop/notifications/bus.rs b/src/openhuman/desktop/notifications/bus.rsindex c75d43538b..069236014e 100644--- a/src/openhuman/desktop/notifications/bus.rs+++ b/src/openhuman/desktop/notifications/bus.rs@@ -247,6 +247,7 @@ fn translate(event: &DomainEvent) -> Option<CoreNotificationEvent> {timestamp_ms: ts,actions: None,workspace: None,+ workspace_revision: None,}),DomainEvent::WebhookProcessed {skill_id,@@ -275,6 +276,7 @@ fn translate(event: &DomainEvent) -> Option<CoreNotificationEvent> {timestamp_ms: ts,actions: None,workspace: None,+ workspace_revision: None,})}DomainEvent::SubagentCompleted {@@ -292,6 +294,7 @@ fn translate(event: &DomainEvent) -> Option<CoreNotificationEvent> {timestamp_ms: ts,actions: None,workspace: None,+ workspace_revision: None,}),DomainEvent::SubagentFailed {parent_session,@@ -310,6 +313,7 @@ fn translate(event: &DomainEvent) -> Option<CoreNotificationEvent> {timestamp_ms: ts,actions: None,workspace: None,+ workspace_revision: None,}),DomainEvent::NotificationTriaged {id,@@ -338,6 +342,7 @@ fn translate(event: &DomainEvent) -> Option<CoreNotificationEvent> {timestamp_ms: ts,actions: None,workspace: None,+ workspace_revision: None,})}DomainEvent::ProviderApiKeyRejected { provider, message } => Some(CoreNotificationEvent {@@ -356,6 +361,7 @@ fn translate(event: &DomainEvent) -> Option<CoreNotificationEvent> {timestamp_ms: ts,actions: None,workspace: None,+ workspace_revision: None,}),// The MCP reconnect supervisor's verdicts (#5931), published by// `mcp::registry::supervisor_events`. Only the cases a user can act on@@ -393,6 +399,7 @@ fn translate(event: &DomainEvent) -> Option<CoreNotificationEvent> {timestamp_ms: ts,actions: None,workspace: None,+ workspace_revision: None,}),DomainEvent::McpServerReconnected {server_id,@@ -412,6 +419,7 @@ fn translate(event: &DomainEvent) -> Option<CoreNotificationEvent> {timestamp_ms: ts,actions: None,workspace: None,+ workspace_revision: None,}),DomainEvent::McpServerParked {server_id,@@ -431,6 +439,7 @@ fn translate(event: &DomainEvent) -> Option<CoreNotificationEvent> {timestamp_ms: ts,actions: None,workspace: None,+ workspace_revision: None,}),_ => None,}@@ -448,7 +457,7 @@ impl EventHandler<DomainEvent> for NotificationBridgeSubscriber {// correctness boundary.async fn handle(&self, event: &DomainEvent) {- if let Some(notification) = event_to_notification(event) {+ if let Some(mut notification) = event_to_notification(event) {// #3805: persist BEFORE broadcasting so the event is durable even// when no client is currently subscribed (app closed / minimised /// disconnected) — otherwise the broadcast send finds zero@@ -476,6 +485,15 @@ impl EventHandler<DomainEvent> for NotificationBridgeSubscriber {// Persisted above under the workspace it belongs to; announced// only if that workspace is the one the user is in (#5931).if self.should_announce(event).await {+ // Stamped here, after the gate passed and before the send, so+ // the revision names the transition the gate actually checked+ // against. A receiver whose own revision is older knows it is+ // simply behind — the switch broadcast has not reached it yet+ // — rather than looking at a stale notification (#5966).+ if notification.workspace.is_some() {+ notification.workspace_revision =+ Some(crate::openhuman::config::active_workspace_revision());+ }publish_core_notification(notification);}}diff --git a/src/openhuman/desktop/notifications/bus_tests.rs b/src/openhuman/desktop/notifications/bus_tests.rsindex 9505dda2f3..1b20f38c45 100644--- a/src/openhuman/desktop/notifications/bus_tests.rs+++ b/src/openhuman/desktop/notifications/bus_tests.rs@@ -208,6 +208,7 @@ fn publish_and_subscribe_deliver_event() {timestamp_ms: 0,actions: None,workspace: None,+ workspace_revision: None,};let sent = publish_core_notification(evt.clone());@@ -245,6 +246,7 @@ fn publish_with_no_subscribers_does_not_panic() {timestamp_ms: 42,actions: None,workspace: None,+ workspace_revision: None,});// count is 0 when no subscribers, but the call itself must not panic.let _ = count;diff --git a/src/openhuman/desktop/notifications/store_tests.rs b/src/openhuman/desktop/notifications/store_tests.rsindex 5c44dfe885..01e08b0ced 100644--- a/src/openhuman/desktop/notifications/store_tests.rs+++ b/src/openhuman/desktop/notifications/store_tests.rs@@ -292,6 +292,7 @@ fn sample_core_event(id: &str, ts: u64) -> CoreNotificationEvent {timestamp_ms: ts,actions: None,workspace: None,+ workspace_revision: None,}}diff --git a/src/openhuman/desktop/notifications/types.rs b/src/openhuman/desktop/notifications/types.rsindex d7d135440d..6ff01f25ef 100644--- a/src/openhuman/desktop/notifications/types.rs+++ b/src/openhuman/desktop/notifications/types.rs@@ -65,6 +65,19 @@ pub struct CoreNotificationEvent {/// mismatch, or upgrading would silently hide every stored notification.#[serde(default, skip_serializing_if = "Option::is_none")]pub workspace: Option<String>,+ /// Workspace revision at the moment the announcement gate passed, set+ /// only when [`Self::workspace`] is (#5966).+ ///+ /// Without it a receiver cannot tell the two ways a handle mismatch+ /// happens apart. `workspace_changed` and `core_notification` are+ /// broadcast by separate tasks, so a notification for the workspace the+ /// user just switched *to* can arrive before the switch that announces+ /// it — and a strict handle check would drop a valid alert the core had+ /// already verified. Comparing revisions separates that case ("this+ /// receiver is behind, catch up and accept") from the one the check+ /// exists for ("this is from a workspace already switched away from").+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub workspace_revision: Option<u64>,}/// A single action button attached to a notification.diff --git a/src/openhuman/desktop/notifications/types_tests.rs b/src/openhuman/desktop/notifications/types_tests.rsindex 4035888825..08b3538031 100644--- a/src/openhuman/desktop/notifications/types_tests.rs+++ b/src/openhuman/desktop/notifications/types_tests.rs@@ -48,6 +48,7 @@ fn core_notification_serialize_skips_empty_actions() {timestamp_ms: 1,actions: None,workspace: None,+ workspace_revision: None,};let s = serde_json::to_string(&event).unwrap();assert!(!s.contains("actions"));diff --git a/src/openhuman/flows/ops_part_09.rs b/src/openhuman/flows/ops_part_09.rsindex 94c10ecb1e..d49dbf8f55 100644--- a/src/openhuman/flows/ops_part_09.rs+++ b/src/openhuman/flows/ops_part_09.rs@@ -538,6 +538,7 @@ fn notify_pending_approval(flow: &Flow, thread_id: &str, pending_approvals: &[Stpayload: Some(action_payload),}]),workspace: None,+ workspace_revision: None,});}diff --git a/src/openhuman/security/approval/gate.rs b/src/openhuman/security/approval/gate.rsindex 27912defdf..f5a01ceee9 100644--- a/src/openhuman/security/approval/gate.rs+++ b/src/openhuman/security/approval/gate.rs@@ -332,6 +332,7 @@ fn publish_flow_gate_notification(},]),workspace: None,+ workspace_revision: None,});}