Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(config): cache the active workspace and give it an opaque handle

Shanua98d24561746
diff --git a/src/core/bus.rs b/src/core/bus.rs
index 111092ee70..a402413548 100644
--- a/src/core/bus.rs
+++ b/src/core/bus.rs
@@ -60,7 +60,8 @@ pub const EVENTS_INTERFACE: &str = "ai.tinyhumans.openhuman.Events";
/// both numbers rather than as a decode failure later.
///
/// `1.1.0` added the MCP reconnect-supervisor variants (#5931).
-pub const EVENTS_VERSION: Version = Version::new(1, 1, 0);
+/// `1.2.0` added `ActiveWorkspaceChanged` (#5966).
+pub const EVENTS_VERSION: Version = Version::new(1, 2, 0);
/// The bus. Initialised once by [`init`]; safe to touch before that.
pub static BUS: OnceBus<DomainEvent> = OnceBus::new();
diff --git a/src/core/events.rs b/src/core/events.rs
index f20ae94734..f5adb2363e 100644
--- a/src/core/events.rs
+++ b/src/core/events.rs
@@ -1256,6 +1256,24 @@ pub enum DomainEvent {
/// `SecurityPolicy` is hot-swapped in-band; this broadcast lets other
/// listeners observe the change.
AgentPathsChanged,
+ /// The process switched to a different workspace (#5966).
+ ///
+ /// One process serves more than one workspace over its life — desktop
+ /// login, logout and pending-session revalidation all re-resolve it — and
+ /// until now that happened silently. Long-lived consumers had no way to
+ /// learn about a switch other than to re-read the marker on a timer, and a
+ /// process-wide stream like the Event Log had no way at all: it would keep
+ /// presenting the previous workspace's rows as the current ones.
+ ///
+ /// Published by the config loader's cached-workspace write-through, and
+ /// only when the value actually changes — the loader itself runs on far
+ /// more than switches, and announcing every load would bury the real ones.
+ ///
+ /// `workspace_dir` is for in-process consumers. Anything crossing to a
+ /// 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 },
/// A component's health status changed.
HealthChanged {
component: String,
@@ -1484,6 +1502,7 @@ impl DomainEvent {
| Self::SystemShutdownRequested { .. }
| Self::AutonomyConfigChanged
| Self::AgentPathsChanged
+ | Self::ActiveWorkspaceChanged { .. }
| Self::HealthChanged { .. }
| Self::HealthRestarted { .. }
| Self::HarnessInitProgress { .. }
@@ -1625,6 +1644,7 @@ impl DomainEvent {
Self::SystemShutdownRequested { .. } => "SystemShutdownRequested",
Self::AutonomyConfigChanged => "AutonomyConfigChanged",
Self::AgentPathsChanged => "AgentPathsChanged",
+ Self::ActiveWorkspaceChanged { .. } => "ActiveWorkspaceChanged",
Self::HealthChanged { .. } => "HealthChanged",
Self::HealthRestarted { .. } => "HealthRestarted",
Self::HarnessInitProgress { .. } => "HarnessInitProgress",
@@ -1787,6 +1807,70 @@ impl DomainEvent {
_ => None,
}
}
+
+ /// The workspace this event belongs to, for the variants bound to one.
+ ///
+ /// One process serves more than one workspace over its life, so a
+ /// process-wide consumer — the Event Log, the `core_notification`
+ /// broadcast — has to be able to ask which workspace a given event came
+ /// from. Three families already carry the answer and each used to be read
+ /// by whoever happened to need it: `desktop::notifications` matched the
+ /// MCP arms in a private helper of its own, and silently did not gate the
+ /// channel and artifact families that carry the same field. This is the
+ /// one place that question is answered, so a consumer cannot cover a
+ /// subset by accident and a new workspace-bound variant has one arm to
+ /// add rather than several to find (#5966).
+ ///
+ /// `None` means "not workspace-bound", which is the common case and is
+ /// **not** the same as "unknown workspace": a consumer filtering by
+ /// workspace should let these through rather than drop them.
+ ///
+ /// The value is an absolute path under the user's home directory. It is
+ /// for in-process comparison only — anything that reaches a client or an
+ /// export sends
+ /// [`workspace_handle`](crate::openhuman::config::workspace_handle)
+ /// instead.
+ #[must_use]
+ pub fn workspace_dir(&self) -> Option<&std::path::Path> {
+ match self {
+ // Channel — the workspace the inbound message was received under.
+ Self::ChannelMessageReceived { workspace_dir, .. }
+ | Self::ChannelMessageProcessed { workspace_dir, .. } => Some(workspace_dir.as_path()),
+
+ // Artifact — carried as a `String` because the producer takes it
+ // from a config field it already has as text; same meaning.
+ //
+ // An empty string reads back as "bound to the empty path", which
+ // matches no workspace and would therefore hide the event from
+ // every scoped consumer — a worse failure than not knowing. Today
+ // the producers pass a real `Path`, so this is a guard against a
+ // future one that does not, not a case that occurs.
+ Self::ArtifactReady { workspace_dir, .. }
+ | Self::ArtifactFailed { workspace_dir, .. }
+ | Self::ArtifactPending { workspace_dir, .. } => {
+ if workspace_dir.is_empty() {
+ None
+ } else {
+ Some(std::path::Path::new(workspace_dir))
+ }
+ }
+
+ // MCP reconnect supervisor (#5931).
+ Self::McpServerProbeTimedOut { workspace_dir, .. }
+ | Self::McpServerTransportDropped { workspace_dir, .. }
+ | Self::McpServerReconnected { workspace_dir, .. }
+ | Self::McpServerReconnectFailed { workspace_dir, .. }
+ | Self::McpServerParked { workspace_dir, .. } => Some(workspace_dir.as_path()),
+
+ // The switch itself is *about* a workspace rather than bound to
+ // one: it is what tells a consumer the active workspace changed,
+ // so filtering it out by the very rule it announces would hide
+ // the announcement from everyone who is not already up to date.
+ Self::ActiveWorkspaceChanged { .. } => None,
+
+ _ => None,
+ }
+ }
}
#[cfg(test)]
diff --git a/src/core/events_tests.rs b/src/core/events_tests.rs
index d628452b2a..4da6cd6288 100644
--- a/src/core/events_tests.rs
+++ b/src/core/events_tests.rs
@@ -852,3 +852,194 @@ fn events_outside_the_supervisor_have_no_event_log_detail() {
.log_detail()
.is_none());
}
+
+// ── workspace_dir ────────────────────────────────────────────────────────
+
+/// A workspace that is not [`mcp_workspace`], so a test can tell "the
+/// accessor returned *a* path" apart from "the accessor returned *this*
+/// path".
+fn other_workspace() -> std::path::PathBuf {
+ std::path::PathBuf::from("/tmp/openhuman-other-ws")
+}
+
+/// Every variant that carries a workspace must be reachable through the one
+/// accessor. The bug this guards is not a missing arm in the abstract: before
+/// #5966 the notification bridge kept its own list, it named only the MCP
+/// family, and the channel and artifact families — which carry the same field
+/// — were silently ungated. A consumer that filters by workspace must be able
+/// to ask one question and get every bound event, or it covers a subset and
+/// nothing says which.
+#[test]
+fn every_workspace_bound_variant_is_reachable_through_one_accessor() {
+ let ws = other_workspace();
+ let cases: Vec<DomainEvent> = vec![
+ DomainEvent::ChannelMessageReceived {
+ channel: "c".into(),
+ message_id: "m1".into(),
+ sender: "s".into(),
+ reply_target: "r".into(),
+ content: "hi".into(),
+ thread_ts: None,
+ inbound_envelope: None,
+ workspace_dir: ws.clone(),
+ },
+ DomainEvent::ChannelMessageProcessed {
+ channel: "c".into(),
+ message_id: "m1".into(),
+ sender: "s".into(),
+ reply_target: "r".into(),
+ content: "hi".into(),
+ thread_ts: None,
+ response: "ok".into(),
+ provider: "p".into(),
+ model: "m".into(),
+ elapsed_ms: 1,
+ success: true,
+ workspace_dir: ws.clone(),
+ },
+ DomainEvent::ArtifactReady {
+ artifact_id: "a1".into(),
+ kind: "document".into(),
+ title: "t".into(),
+ workspace_dir: ws.to_string_lossy().into_owned(),
+ path: "a1/doc.docx".into(),
+ size_bytes: 1,
+ thread_id: None,
+ client_id: None,
+ },
+ DomainEvent::ArtifactFailed {
+ artifact_id: "a1".into(),
+ kind: "document".into(),
+ title: "t".into(),
+ workspace_dir: ws.to_string_lossy().into_owned(),
+ error: "boom".into(),
+ thread_id: None,
+ client_id: None,
+ },
+ DomainEvent::ArtifactPending {
+ artifact_id: "a1".into(),
+ kind: "document".into(),
+ title: "t".into(),
+ workspace_dir: ws.to_string_lossy().into_owned(),
+ path: "a1/doc.docx".into(),
+ thread_id: None,
+ client_id: None,
+ },
+ DomainEvent::McpServerProbeTimedOut {
+ server_id: "srv-1".into(),
+ qualified_name: "ac.inference.sh/mcp".into(),
+ probe_timeout_secs: 8,
+ consecutive_timeouts: 1,
+ teardown_after: 3,
+ workspace_dir: ws.clone(),
+ },
+ DomainEvent::McpServerTransportDropped {
+ server_id: "srv-1".into(),
+ qualified_name: "ac.inference.sh/mcp".into(),
+ outcome: "timed_out".into(),
+ detail: None,
+ elapsed_ms: Some(8_000),
+ consecutive_timeouts: 3,
+ workspace_dir: ws.clone(),
+ },
+ DomainEvent::McpServerReconnected {
+ server_id: "srv-1".into(),
+ qualified_name: "ac.inference.sh/mcp".into(),
+ tool_count: 4,
+ after_failures: 1,
+ workspace_dir: ws.clone(),
+ },
+ DomainEvent::McpServerReconnectFailed {
+ server_id: "srv-1".into(),
+ qualified_name: "ac.inference.sh/mcp".into(),
+ error: "refused".into(),
+ failures: 1,
+ retry_in_secs: 30,
+ workspace_dir: ws.clone(),
+ },
+ DomainEvent::McpServerParked {
+ server_id: "srv-1".into(),
+ qualified_name: "ac.inference.sh/mcp".into(),
+ error: "refused".into(),
+ workspace_dir: ws.clone(),
+ },
+ ];
+
+ for event in cases {
+ assert_eq!(
+ event.workspace_dir(),
+ Some(ws.as_path()),
+ "{} carries a workspace but the accessor did not return it",
+ event.variant_name()
+ );
+ }
+}
+
+/// `None` here means "not bound to a workspace", which a consumer filtering
+/// by workspace must let through rather than drop. Getting this backwards
+/// would silence cron, webhook and sub-agent notifications entirely.
+#[test]
+fn events_without_a_workspace_report_none() {
+ assert_eq!(
+ DomainEvent::AgentPathsChanged.workspace_dir(),
+ None,
+ "a process-wide event must not claim a workspace"
+ );
+ assert_eq!(
+ DomainEvent::CronJobCompleted {
+ job_id: "job-1".into(),
+ success: true,
+ output: "done".into(),
+ }
+ .workspace_dir(),
+ None
+ );
+ assert_eq!(
+ DomainEvent::ChannelReactionReceived {
+ channel: "c".into(),
+ sender: "s".into(),
+ target_message_id: "m1".into(),
+ emoji: "👍".into(),
+ }
+ .workspace_dir(),
+ None,
+ "a channel event with no workspace field must not borrow one"
+ );
+}
+
+/// The artifact family carries its workspace as a `String`, so it is the one
+/// place an *empty* value is representable. Reading that back as the empty
+/// path would bind the event to a workspace nothing matches, hiding it from
+/// every scoped consumer — strictly worse than reporting it unbound, which at
+/// least shows it everywhere.
+#[test]
+fn an_empty_artifact_workspace_reads_as_unbound_not_as_a_workspace() {
+ assert_eq!(
+ DomainEvent::ArtifactReady {
+ artifact_id: "a1".into(),
+ kind: "document".into(),
+ title: "t".into(),
+ workspace_dir: String::new(),
+ path: "a1/doc.docx".into(),
+ size_bytes: 1,
+ thread_id: None,
+ client_id: None,
+ }
+ .workspace_dir(),
+ None
+ );
+}
+
+/// The switch announcement names a workspace but is deliberately not *bound*
+/// to one: it is what tells a consumer the active workspace changed, so
+/// filtering it by the rule it announces would hide the announcement from
+/// exactly the consumers that are still out of date.
+#[test]
+fn the_workspace_switch_announcement_is_not_itself_workspace_bound() {
+ let event = DomainEvent::ActiveWorkspaceChanged {
+ workspace_dir: other_workspace(),
+ };
+ assert_eq!(event.workspace_dir(), None);
+ assert_eq!(event.variant_name(), "ActiveWorkspaceChanged");
+ assert_eq!(DomainEvent::domain(&event), "system");
+}
diff --git a/src/openhuman/config/mod.rs b/src/openhuman/config/mod.rs
index d58dcb96d4..0e42ad9cca 100644
--- a/src/openhuman/config/mod.rs
+++ b/src/openhuman/config/mod.rs
@@ -16,6 +16,7 @@ mod schemas;
pub mod settings_cli;
pub mod tools;
pub mod workspace;
+pub mod workspace_handle;
#[allow(unused_imports)]
pub use daemon::DaemonConfig;
@@ -25,11 +26,12 @@ pub use ops as rpc;
pub use ops::*;
pub use schema::{
- 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,
- read_active_user_id, resolve_action_dir, user_openhuman_dir, write_active_user_id,
- PRE_LOGIN_USER_ID,
+ 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,
};
+pub use workspace_handle::workspace_handle;
// Crate-internal: workspace→config-dir resolver reused by the cloud embedder.
pub(crate) use schema::resolve_config_dir_for_workspace;
pub(crate) use schema::set_cli_inference_overrides;
diff --git a/src/openhuman/config/schema/load/active_workspace.rs b/src/openhuman/config/schema/load/active_workspace.rs
new file mode 100644
index 0000000000..ae0fe4323b
--- /dev/null
+++ b/src/openhuman/config/schema/load/active_workspace.rs
@@ -0,0 +1,161 @@
+//! The active workspace, cached in memory (#5966).
+//!
+//! [`active_workspace_dir`](super::dirs::active_workspace_dir) resolves the
+//! workspace through the loader's own path, which means reading a marker
+//! file. That is the right cost for a *decision* — the notification bridge
+//! pays it for the handful of workspace-bound events a supervisor tick
+//! produces — and the wrong cost for a *stream*. The developer Event Log in
+//! [`crate::core::jsonrpc`] has to stamp every domain event the process
+//! publishes, and its `tokio_stream` `filter_map` closure is synchronous, so
+//! it could not await a disk read even if the cost were acceptable.
+//!
+//! This module is the cheap answer: a process-global slot holding the last
+//! workspace the loader resolved, readable synchronously and without I/O.
+//!
+//! # The disk stays the source of truth
+//!
+//! The cache is never authoritative. It is written *through* — every
+//! successful resolution publishes its own answer here — and cleared
+//! whenever one of the markers that decides the answer is rewritten, so the
+//! next reader that can afford a resolve refills it. A stale value is
+//! therefore not a thing this can hold: the marker writes and the resolves
+//! are the only two ways the answer changes, and both touch this slot.
+//!
+//! `None` means "not resolved since the last change", not "no workspace".
+//! Callers that cannot resolve must treat it as unknown rather than as a
+//! mismatch — see the Event Log's handling in `core::jsonrpc`.
+//!
+//! # Why the env-injectable loader does not publish
+//!
+//! [`Config::load_or_init_with_env_lookup`](crate::openhuman::config::Config)
+//! takes an [`EnvLookup`](super::env::EnvLookup) so tests can exercise the
+//! `OPENHUMAN_WORKSPACE` branch without mutating the process environment.
+//! Publishing from there would let one test's fixture directory become the
+//! whole binary's idea of the active workspace. Only the two `ProcessEnv`
+//! entry points publish: `Config::load_or_init` and `active_workspace_dir`.
+
+use std::path::{Path, PathBuf};
+use std::sync::RwLock;
+
+use once_cell::sync::Lazy;
+
+const LOG_PREFIX: &str = "[config:active-workspace]";
+
+/// The state machine, separated from the process-global slot that holds it.
+///
+/// The decisions here — when a resolve is a *change*, what invalidation does
+/// and does not clear — are the part worth asserting, and asserting them on
+/// the global would be unsound: `Config::load_or_init` publishes into that
+/// global, and the test binary runs thousands of tests in parallel, many of
+/// which load a config. A test that pinned the global would pass alone and
+/// fail whenever it happened to interleave with one of those.
+#[derive(Default)]
+struct ActiveWorkspace {
+ /// The last resolved workspace, or `None` when a marker write has
+ /// invalidated it and nothing has resolved since.
+ current: Option<PathBuf>,
+ /// The workspace last announced on the bus.
+ ///
+ /// Kept separately from `current`, and deliberately **not** cleared by
+ /// invalidation. A marker write does not always change the answer —
+ /// signing in as the user who is already active rewrites
+ /// `active_user.toml` with the same id — and without this the re-resolve
+ /// that follows would announce a switch that never happened, putting a
+ /// phantom row in the Event Log and making a real switch harder to spot.
+ announced: Option<PathBuf>,
+}
+
+impl ActiveWorkspace {
+ /// Record `workspace_dir` as current. Returns `true` when this is a
+ /// change the bus has not been told about yet.
+ fn publish(&mut self, workspace_dir: &Path) -> bool {
+ self.current = Some(workspace_dir.to_path_buf());
+ if self.announced.as_deref() == Some(workspace_dir) {
+ return false;
+ }
+ self.announced = Some(workspace_dir.to_path_buf());
+ true
+ }
+
+ /// Forget the resolved answer because a marker that decides it was
+ /// written. Leaves `announced` alone — see the field's own note.
+ fn invalidate(&mut self) -> bool {
+ self.current.take().is_some()
+ }
+}
+
+static ACTIVE_WORKSPACE: Lazy<RwLock<ActiveWorkspace>> =
+ Lazy::new(|| RwLock::new(ActiveWorkspace::default()));
+
+/// Record `workspace_dir` as the workspace this process is serving.
+///
+/// Called after a resolution that used the real process environment.
+/// Publishes [`DomainEvent::ActiveWorkspaceChanged`](crate::core::events::DomainEvent)
+/// when the value actually changes, so consumers of a long-lived stream learn
+/// about a switch without polling — and so the switch itself becomes a
+/// visible row in the Event Log rather than an invisible reason its contents
+/// changed.
+pub(crate) fn publish_active_workspace(workspace_dir: &Path) {
+ let announce = match ACTIVE_WORKSPACE.write() {
+ Ok(mut guard) => guard.publish(workspace_dir),
+ Err(error) => {
+ log::warn!("{LOG_PREFIX} active workspace slot poisoned: {error}");
+ return;
+ }
+ };
+
+ if !announce {
+ return;
+ }
+
+ log::info!(
+ "{LOG_PREFIX} active workspace is now {}",
+ workspace_dir.display()
+ );
+ // Published with no lock held: a subscriber is free to reach back into
+ // the config layer, and holding the slot across the publish would make
+ // that a deadlock.
+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::ActiveWorkspaceChanged {
+ workspace_dir: workspace_dir.to_path_buf(),
+ });
+}
+
+/// The active workspace as last resolved, or `None` when a marker has been
+/// rewritten since and nothing has resolved yet.
+///
+/// Synchronous and I/O-free — safe on a hot path. A caller that can afford
+/// the disk read should use
+/// [`active_workspace_dir`](super::dirs::active_workspace_dir) instead,
+/// which is authoritative and refills this slot as a side effect.
+pub fn active_workspace_dir_cached() -> Option<PathBuf> {
+ match ACTIVE_WORKSPACE.read() {
+ Ok(guard) => guard.current.clone(),
+ Err(error) => {
+ log::warn!("{LOG_PREFIX} active workspace slot poisoned: {error}");
+ None
+ }
+ }
+}
+
+/// Drop the cached value because a marker that decides it was just written.
+///
+/// Clearing rather than overwriting is deliberate: a marker write says the
+/// answer changed, not what it changed *to*. `active_user.toml` names a user
+/// id, and turning that into a workspace is the resolver's job, including
+/// the fallbacks that apply when the marker is absent or unreadable.
+/// Guessing here would put a second, subtly different resolution rule in the
+/// codebase — the failure mode #5334 came from.
+pub(crate) fn invalidate_active_workspace() {
+ match ACTIVE_WORKSPACE.write() {
+ Ok(mut guard) => {
+ if guard.invalidate() {
+ log::debug!("{LOG_PREFIX} cleared after a workspace marker write");
+ }
+ }
+ Err(error) => log::warn!("{LOG_PREFIX} active workspace slot poisoned: {error}"),
+ }
+}
+
+#[cfg(test)]
+#[path = "active_workspace_tests.rs"]
+mod tests;
diff --git a/src/openhuman/config/schema/load/active_workspace_tests.rs b/src/openhuman/config/schema/load/active_workspace_tests.rs
new file mode 100644
index 0000000000..e95e632ec4
--- /dev/null
+++ b/src/openhuman/config/schema/load/active_workspace_tests.rs
@@ -0,0 +1,128 @@
+//! The active-workspace state machine.
+//!
+//! These drive a local [`ActiveWorkspace`] rather than the process-global
+//! slot, and that is load-bearing rather than stylistic. `Config::load_or_init`
+//! publishes into the global, thousands of tests in this binary load a config,
+//! and they run in parallel — a test that pinned the global would pass on its
+//! own and fail whenever it happened to interleave with one of them. Driving
+//! an owned instance makes each case deterministic and independent.
+
+use std::path::PathBuf;
+
+use super::ActiveWorkspace;
+
+fn ws(name: &str) -> PathBuf {
+ PathBuf::from(format!(
+ "{}tmp{}oh-{name}{}workspace",
+ std::path::MAIN_SEPARATOR,
+ std::path::MAIN_SEPARATOR,
+ std::path::MAIN_SEPARATOR
+ ))
+}
+
+#[test]
+fn starts_unknown_rather_than_guessing() {
+ let state = ActiveWorkspace::default();
+ assert_eq!(state.current, None);
+ assert_eq!(state.announced, None);
+}
+
+#[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_eq!(state.current, Some(ws("a")));
+}
+
+#[test]
+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_eq!(state.current, Some(ws("b")));
+}
+
+/// The loader runs on far more than switches — every `Config::load_or_init` —
+/// so announcing each one would fill the Event Log with phantom workspace
+/// changes and make a real one impossible to spot.
+#[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_eq!(state.current, Some(ws("a")));
+}
+
+/// A marker write says the answer changed, not what it changed *to*, so the
+/// readable value goes back to "unknown" and the next resolve refills it.
+/// Leaving the previous value in place is the bug this guards: a
+/// switched-away workspace would keep reading as active.
+#[test]
+fn invalidation_clears_the_readable_value() {
+ let mut state = ActiveWorkspace::default();
+ state.publish(&ws("a"));
+ assert!(state.invalidate(), "there was something to clear");
+ assert_eq!(state.current, None);
+}
+
+#[test]
+fn invalidating_an_already_empty_slot_is_harmless() {
+ let mut state = ActiveWorkspace::default();
+ assert!(!state.invalidate());
+ assert!(!state.invalidate());
+ assert_eq!(state.current, None);
+}
+
+/// Invalidation says "the answer may have changed", not "the answer changed".
+/// Signing in as the user who is already active rewrites `active_user.toml`
+/// with the same id, so the resolve that follows lands on the workspace that
+/// was already current. Announcing that would put a switch in the Event Log
+/// that never happened.
+#[test]
+fn re_resolving_the_same_workspace_after_invalidation_does_not_re_announce() {
+ let mut state = ActiveWorkspace::default();
+ state.publish(&ws("a"));
+ state.invalidate();
+
+ assert!(
+ !state.publish(&ws("a")),
+ "the workspace never actually changed"
+ );
+ assert_eq!(state.current, Some(ws("a")));
+}
+
+/// The other half of that rule: a marker write that *does* change the
+/// workspace must still announce, or a consumer holding a long-lived stream
+/// never learns it switched.
+#[test]
+fn a_different_workspace_after_invalidation_is_announced() {
+ let mut state = ActiveWorkspace::default();
+ state.publish(&ws("a"));
+ state.invalidate();
+
+ assert!(state.publish(&ws("b")));
+ assert_eq!(state.current, Some(ws("b")));
+}
+
+/// Invalidation must not reset the announce memory, or the pair
+/// invalidate-then-republish would announce a phantom switch every time.
+#[test]
+fn invalidation_leaves_the_announce_memory_intact() {
+ let mut state = ActiveWorkspace::default();
+ state.publish(&ws("a"));
+ state.invalidate();
+ assert_eq!(state.announced, Some(ws("a")));
+}
+
+/// The global wrapper reaches for the event bus, which no unit test stands
+/// up. `BUS.publish` is documented as a no-op before `init`; this pins that
+/// the cache does not depend on the bus being up, and that the wrapper does
+/// not panic on the path every boot takes.
+#[test]
+fn the_global_publish_survives_an_uninitialised_bus() {
+ super::publish_active_workspace(&ws("no-bus"));
+ // No assertion on the readable value: other tests in this binary load
+ // configs concurrently and publish into the same slot. The contract under
+ // test is only that this path does not panic without a bus.
+}
diff --git a/src/openhuman/config/schema/load/dirs.rs b/src/openhuman/config/schema/load/dirs.rs
index 234432a1cc..886a48ff97 100644
--- a/src/openhuman/config/schema/load/dirs.rs
+++ b/src/openhuman/config/schema/load/dirs.rs
@@ -190,6 +190,13 @@ pub(crate) async fn persist_active_workspace_config_dir(config_dir: &Path) -> Re
let default_config_dir = default_config_dir()?;
let state_path = active_workspace_state_path(&default_config_dir);
+ // Before the write, not after: this marker is one of the inputs the
+ // resolver reads, so from here until the next resolve the cached answer
+ // is no longer known to be current — including if the write below fails
+ // partway. Clearing early costs one resolve; clearing late leaves a
+ // window in which a stale workspace reads as active.
+ super::active_workspace::invalidate_active_workspace();
+
if config_dir == default_config_dir {
if state_path.exists() {
fs::remove_file(&state_path).await.with_context(|| {
@@ -305,13 +312,21 @@ pub(crate) async fn resolve_runtime_config_dirs(
/// workspace marker, then the pre-login directory — so a caller cannot
/// disagree with the loader about which workspace is active.
///
-/// This is deliberately not cached. One process serves more than one
+/// The answer is never pinned at boot. One process serves more than one
/// workspace over its life and the switch is a change to an on-disk marker,
-/// so anything a subscriber pinned at boot goes stale exactly when it
+/// so anything a subscriber captured once goes stale exactly when it
/// matters. The cost is one small marker read, which is why callers should
/// reach for this per *decision*, not per event: `desktop::notifications`
/// asks only for the handful of workspace-bound events a supervisor tick
/// produces, and returns before calling it for everything else.
+///
+/// A caller that cannot afford even that — the Event Log stamps every domain
+/// event the process publishes, from a synchronous stream closure — reads
+/// [`active_workspace_dir_cached`](super::active_workspace::active_workspace_dir_cached)
+/// instead. Both arms below refill that cache, so the two cannot disagree
+/// about a workspace either of them has seen, and the embedder arm is
+/// included deliberately: an embedding host's chosen workspace is the
+/// authoritative answer for its process too.
pub async fn active_workspace_dir() -> Result<PathBuf> {
// An embedding host that supplied its own `Config` is authoritative, and
// `config::ops::load_config_with_timeout` already short-circuits on it for
@@ -323,6 +338,7 @@ pub async fn active_workspace_dir() -> Result<PathBuf> {
// with only a `debug!` line to say so. See AGENTS.md, "CoreBuilder::config
// alone configures boot and nothing else".
if let Some(config) = crate::core::runtime::context::CoreContext::current_embedder_config() {
+ super::active_workspace::publish_active_workspace(&config.workspace_dir);
return Ok(config.workspace_dir);
}
let (default_openhuman_dir, default_workspace_dir) = default_config_and_workspace_dirs()?;
@@ -332,6 +348,7 @@ pub async fn active_workspace_dir() -> Result<PathBuf> {
source = source.as_str(),
"active workspace resolved for a workspace-bound decision"
);
+ super::active_workspace::publish_active_workspace(&workspace_dir);
Ok(workspace_dir)
}
diff --git a/src/openhuman/config/schema/load/impl_load.rs b/src/openhuman/config/schema/load/impl_load.rs
index c6a20ce9f1..e2ae641f1b 100644
--- a/src/openhuman/config/schema/load/impl_load.rs
+++ b/src/openhuman/config/schema/load/impl_load.rs
@@ -261,12 +261,24 @@ async fn describe_config_ownership(_path: &Path) -> String {
impl Config {
pub async fn load_or_init() -> Result<Self> {
let (default_openhuman_dir, default_workspace_dir) = default_config_and_workspace_dirs()?;
- Self::load_or_init_with_env_lookup(
+ let config = Self::load_or_init_with_env_lookup(
&default_openhuman_dir,
&default_workspace_dir,
&ProcessEnv,
)
- .await
+ .await?;
+ // Write-through for the cached active workspace (#5966). This is the
+ // process's real load path, so it is also the earliest and most
+ // frequent moment the answer is known — the Event Log's synchronous
+ // stream can then stamp events without resolving anything itself.
+ //
+ // Deliberately here rather than inside `load_or_init_with_env_lookup`:
+ // that one takes an injected `EnvLookup` so tests can drive the
+ // `OPENHUMAN_WORKSPACE` branch against a fixture, and publishing from
+ // it would make one test's temp directory the whole binary's idea of
+ // the active workspace.
+ super::active_workspace::publish_active_workspace(&config.workspace_dir);
+ Ok(config)
}
pub(crate) async fn load_or_init_with_env_lookup(
diff --git a/src/openhuman/config/schema/load/mod.rs b/src/openhuman/config/schema/load/mod.rs
index 391bc8fd3a..7faa0c1b54 100644
--- a/src/openhuman/config/schema/load/mod.rs
+++ b/src/openhuman/config/schema/load/mod.rs
@@ -1,5 +1,6 @@
//! Config load/save and environment variable overrides.
+mod active_workspace;
mod dirs;
mod env;
mod env_overlay;
@@ -7,6 +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 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.rs
index 614a76f0ac..2231d0663e 100644
--- a/src/openhuman/config/schema/load_user_state.rs
+++ b/src/openhuman/config/schema/load_user_state.rs
@@ -148,7 +148,14 @@ pub fn read_active_user_id(default_openhuman_dir: &Path) -> Option<String> {
}
/// Writes the active user id to `{default_openhuman_dir}/active_user.toml`.
+///
+/// This marker outranks the workspace marker in the resolver, so writing it
+/// changes which workspace is active. The cached answer is dropped up front,
+/// before the write rather than after, so a failure partway through cannot
+/// leave a stale workspace reading as current — see
+/// `load::active_workspace` for the rest of that reasoning (#5966).
pub fn write_active_user_id(default_openhuman_dir: &Path, user_id: &str) -> Result<()> {
+ crate::openhuman::config::schema::invalidate_active_workspace();
std::fs::create_dir_all(default_openhuman_dir).with_context(|| {
format!(
"Failed to create active user state directory: {}",
@@ -199,7 +206,13 @@ pub fn write_active_user_id(default_openhuman_dir: &Path, user_id: &str) -> Resu
/// Removes the active user marker. After this, the next config load will
/// use the default (unauthenticated) openhuman directory.
+///
+/// Sign-out is a workspace switch like any other, so the cached active
+/// workspace is dropped here too — unconditionally, not only when the file
+/// turned out to exist, because a caller reaching for this has already
+/// decided the previous answer should stop applying.
pub fn clear_active_user(default_openhuman_dir: &Path) -> Result<()> {
+ crate::openhuman::config::schema::invalidate_active_workspace();
let path = active_user_marker_path(default_openhuman_dir);
if path.exists() {
std::fs::remove_file(&path)
diff --git a/src/openhuman/config/schema/mod.rs b/src/openhuman/config/schema/mod.rs
index 1a7bb1f35a..1b160e978c 100644
--- a/src/openhuman/config/schema/mod.rs
+++ b/src/openhuman/config/schema/mod.rs
@@ -33,11 +33,16 @@ mod identity_cost;
mod learning;
mod load;
pub use load::{
- 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,
- read_active_user_id, resolve_action_dir, user_openhuman_dir, write_active_user_id,
- PRE_LOGIN_USER_ID,
+ 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,
};
+// Crate-internal: the invalidation half of the cached active workspace. The
+// marker writers in `load_user_state` call it from outside `load`; the
+// write-through half stays inside `load`, where the two resolvers live. Every
+// other caller reads through `active_workspace_dir_cached`.
+pub(crate) use load::invalidate_active_workspace;
// Crate-internal: the workspace→config-dir resolver, reused by the cloud
// embedder's keyless credential-scope resolution (mirrors `config::load`).
pub(crate) use load::resolve_config_dir_for_workspace;
diff --git a/src/openhuman/config/workspace_handle.rs b/src/openhuman/config/workspace_handle.rs
new file mode 100644
index 0000000000..b52ecb1f54
--- /dev/null
+++ b/src/openhuman/config/workspace_handle.rs
@@ -0,0 +1,93 @@
+//! Opaque, stable identity for a workspace directory (#5966).
+//!
+//! One process serves more than one workspace over its life, so a
+//! process-wide stream — the developer Event Log, the `core_notification`
+//! broadcast — has to say *which* workspace each row belongs to or the
+//! reader cannot tell a row from the workspace they are in from a row left
+//! over from one they switched away from.
+//!
+//! The obvious identity is the `workspace_dir` those events already carry.
+//! It cannot go on the wire. It is an absolute path under the user's home
+//! directory, and both surfaces are shared and exportable: the Event Log
+//! renders in a settings panel and downloads as NDJSON. Forwarding the path
+//! would print `/Users/<name>/…` into a file the user is likely to paste
+//! into an issue.
+//!
+//! So the wire carries a handle instead — a short digest that answers the
+//! only question the consumer actually asks ("same workspace or not?") and
+//! nothing else.
+//!
+//! # Why the path is normalised lexically, not canonicalised
+//!
+//! [`std::fs::canonicalize`] would be the stricter comparison: it resolves
+//! symlinks, so two spellings of one directory would agree. It is wrong
+//! here for two reasons. It is blocking I/O, and the primary caller is the
+//! SSE stream in [`crate::core::jsonrpc`], whose `tokio_stream` `filter_map`
+//! closure is synchronous — a disk hit per streamed event is exactly the
+//! cost this handle exists to avoid. And it fails on a directory that no
+//! longer exists, which a *stale-workspace* event is precisely the case
+//! for: the surface that most needs the handle is the one whose directory
+//! may already be gone.
+//!
+//! Lexical normalisation is sufficient because every producer takes its
+//! `workspace_dir` from the same source — the config loader — so the
+//! spellings being compared are already the loader's own output rather than
+//! arbitrary user input.
+
+use std::path::Path;
+
+use sha2::{Digest, Sha256};
+
+/// Prefix on every handle. Present so a handle is self-describing in a log
+/// line or an exported row, and so a bare digest cannot be mistaken for one.
+const HANDLE_PREFIX: &str = "ws_";
+
+/// Hex characters of SHA-256 kept. 16 hex characters is 64 bits: collision
+/// odds stay negligible for the handful of workspaces one machine holds,
+/// while the handle stays short enough to sit in a log row without
+/// wrapping.
+const HANDLE_HEX_LEN: usize = 16;
+
+/// Stable opaque handle for `workspace_dir`.
+///
+/// The same directory always produces the same handle, in this process and
+/// the next, so a consumer can compare a row's handle against the active
+/// workspace's without either side learning the path. Different directories
+/// produce different handles.
+///
+/// This is a *privacy* boundary, not a security one: the digest is not
+/// keyed, so someone who already knows a candidate path can confirm it by
+/// hashing it themselves. That is fine for what it protects against —
+/// accidental disclosure of a home directory in a pasted log — and a keyed
+/// digest would trade that for a per-install secret to manage and a handle
+/// that changes when the secret is lost.
+pub fn workspace_handle(workspace_dir: &Path) -> String {
+ let normalized = normalize(workspace_dir);
+ let digest = Sha256::digest(normalized.as_bytes());
+ let hex = hex::encode(digest);
+ format!("{HANDLE_PREFIX}{}", &hex[..HANDLE_HEX_LEN])
+}
+
+/// Lexical normalisation applied before hashing, so spellings that differ
+/// only in trailing separators agree.
+///
+/// Deliberately minimal. It does not resolve `..`, symlinks or case: a
+/// producer's `workspace_dir` comes from the config loader, which does not
+/// emit those, and inventing more normalisation here would make the handle
+/// disagree with the plain path comparison the notification bridge's
+/// [`announces_to`](crate::openhuman::desktop::notifications) rule performs
+/// on the same two values.
+fn normalize(workspace_dir: &Path) -> String {
+ let raw = workspace_dir.to_string_lossy();
+ let trimmed = raw.trim_end_matches(std::path::MAIN_SEPARATOR);
+ // A root path trims to empty; keep it distinguishable from "no path".
+ if trimmed.is_empty() {
+ raw.into_owned()
+ } else {
+ trimmed.to_string()
+ }
+}
+
+#[cfg(test)]
+#[path = "workspace_handle_tests.rs"]
+mod tests;
diff --git a/src/openhuman/config/workspace_handle_tests.rs b/src/openhuman/config/workspace_handle_tests.rs
new file mode 100644
index 0000000000..15da13d953
--- /dev/null
+++ b/src/openhuman/config/workspace_handle_tests.rs
@@ -0,0 +1,80 @@
+use std::path::{Path, PathBuf};
+
+use super::{workspace_handle, HANDLE_HEX_LEN, HANDLE_PREFIX};
+
+#[test]
+fn handle_is_stable_for_the_same_directory() {
+ let dir = Path::new("/Users/someone/.openhuman/users/abc/workspace");
+ assert_eq!(workspace_handle(dir), workspace_handle(dir));
+}
+
+#[test]
+fn different_directories_get_different_handles() {
+ let a = Path::new("/Users/someone/.openhuman/users/abc/workspace");
+ let b = Path::new("/Users/someone/.openhuman/users/def/workspace");
+ assert_ne!(workspace_handle(a), workspace_handle(b));
+}
+
+#[test]
+fn trailing_separator_does_not_change_the_handle() {
+ let bare = PathBuf::from(format!(
+ "{}tmp{}ws",
+ std::path::MAIN_SEPARATOR,
+ std::path::MAIN_SEPARATOR
+ ));
+ let trailing = PathBuf::from(format!("{}{}", bare.display(), std::path::MAIN_SEPARATOR));
+ assert_eq!(workspace_handle(&bare), workspace_handle(&trailing));
+}
+
+#[test]
+fn handle_shape_is_prefix_plus_fixed_width_hex() {
+ let handle = workspace_handle(Path::new("/Users/someone/.openhuman/users/abc/workspace"));
+ let hex = handle
+ .strip_prefix(HANDLE_PREFIX)
+ .expect("handle carries its prefix");
+ assert_eq!(hex.len(), HANDLE_HEX_LEN);
+ assert!(
+ hex.chars().all(|c| c.is_ascii_hexdigit()),
+ "handle body must be hex, got {hex}"
+ );
+}
+
+/// The whole point of the handle: it is what goes on the wire *instead of*
+/// the path, so no component of the path may survive into it. A regression
+/// that forwarded the path — or appended it "for debugging" — would leak a
+/// home directory into the Event Log's NDJSON export.
+#[test]
+fn handle_leaks_no_component_of_the_path() {
+ let handle = workspace_handle(Path::new(
+ "/Users/rumpelstiltskin/.openhuman/users/abc/workspace",
+ ));
+ for component in [
+ "Users",
+ "rumpelstiltskin",
+ ".openhuman",
+ "users",
+ "abc",
+ "workspace",
+ ] {
+ assert!(
+ !handle.contains(component),
+ "handle {handle} leaked path component {component}"
+ );
+ }
+ assert!(
+ !handle.contains(std::path::MAIN_SEPARATOR),
+ "handle {handle} contains a path separator"
+ );
+}
+
+/// A root path normalises to the empty string if the trailing-separator trim
+/// is applied blindly, which would collapse `/` and any other
+/// all-separator spelling onto one handle *and* hash the empty string. The
+/// guard in `normalize` keeps the raw value in that case.
+#[test]
+fn root_path_still_produces_a_handle() {
+ let root = PathBuf::from(std::path::MAIN_SEPARATOR.to_string());
+ let handle = workspace_handle(&root);
+ assert!(handle.starts_with(HANDLE_PREFIX));
+ assert_ne!(handle, workspace_handle(Path::new("")));
+}