Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion crates/stdiod/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,26 @@ credential. `logout` removes authentication while retaining preferences;

</details>

## Connect to multiple backends

Keep your existing sign-in and add a named profile for each additional backend.
One daemon opens a separate WebSocket for each signed-in profile. Each profile
has its own credentials, connection state, and MCP server processes.

```sh
sealgate-stdiod login --profile staging --backend https://staging.example.com
sealgate-stdiod status --profile staging
sealgate-stdiod logout --profile staging
```

Complete browser authorization for each new backend once. A running daemon
discovers new profiles automatically. If the service is not installed, run
`sealgate-stdiod install` once after signing in. Commands without `--profile`
continue to use your existing default sign-in. Named profiles are stored under
`~/.config/sealgate-stdiod/profiles/<name>/`. Use `--profile` with `server` commands
to manage MCP servers for that backend. `uninstall --purge` removes all named
profiles. Add `--keep-profiles` to preserve their sign-ins and preferences.

## Files on disk

TLDR: the daemon keeps almost nothing durable - the backend is the source of truth.
Expand All @@ -227,7 +247,12 @@ TLDR: the daemon keeps almost nothing durable - the backend is the source of tru
config.toml # backend URL, account IDs, token, device ID, secret (mode 0600)
server_envs.json # legacy-auth local server values (mode 0600)
server_envs/<namespace>.json # client-installation-isolated server values (mode 0600)
state.json # atomic writes; snapshot consumed by the desktop tray UI
state.json # default connection snapshot for the desktop tray
profiles/<name>/ # named backend
config.toml # backend URL and credentials (mode 0600)
state.json # connection and child snapshot
server_envs.json # legacy-auth server values (mode 0600)
server_envs/<namespace>.json # client-installation server values (mode 0600)
~/Library/Logs/sealgate-stdiod/ # macOS - platform-equivalent paths elsewhere
daemon.log # rotated daily
child-<name>.log # per-child stdout/stderr capture
Expand Down
76 changes: 66 additions & 10 deletions crates/stdiod/crates/sealgate-stdiod/src/cli/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ pub struct UninstallArgs {
/// `--purge` to wipe everything stdiod-related.
#[arg(long)]
pub purge: bool,
/// Preserve named backend credentials and preferences during a default sign-in reset.
#[arg(long, requires = "purge")]
pub keep_profiles: bool,
}

pub fn install(_args: InstallArgs) -> Result<()> {
Expand All @@ -55,27 +58,56 @@ pub fn uninstall(args: UninstallArgs) -> Result<()> {
// uninstall, even without ``--purge``. config.toml stays because it
// carries the user's credentials.
if let Ok(state_path) = paths::state_file() {
match std::fs::remove_file(&state_path) {
Ok(()) => info!(path = %state_path.display(), "removed state.json"),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => {
tracing::warn!(error = %e, "failed to remove state.json; continuing");
remove_state(&state_path);
}
match paths::profile_names() {
Ok(names) => {
for name in names {
remove_state(&paths::profile_dir(&name)?.join("state.json"));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This profile-state deletion races daemon shutdown on macOS. platform::uninstall() returns before bootout has finished, so a profile session can rewrite state.json after this call; wait for all sessions to stop before deleting state, or perform the cleanup after teardown has settled.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/stdiod/crates/sealgate-stdiod/src/cli/install.rs, line 66:

<comment>This profile-state deletion races daemon shutdown on macOS. `platform::uninstall()` returns before `bootout` has finished, so a profile session can rewrite `state.json` after this call; wait for all sessions to stop before deleting state, or perform the cleanup after teardown has settled.</comment>

<file context>
@@ -55,27 +58,54 @@ pub fn uninstall(args: UninstallArgs) -> Result<()> {
+    match paths::profile_names() {
+        Ok(names) => {
+            for name in names {
+                remove_state(&paths::profile_dir(&name)?.join("state.json"));
             }
         }
</file context>

}
}
Err(error) => tracing::warn!(%error, "could not discover backend profiles"),
}
if args.purge {
purge_user_data().context("purge")?;
purge_user_data(args.keep_profiles).context("purge")?;
}
Ok(())
}

fn purge_user_data() -> Result<()> {
let config_dir = paths::config_dir()?;
if config_dir.exists() {
std::fs::remove_dir_all(&config_dir)
fn remove_state(path: &std::path::Path) {
match std::fs::remove_file(path) {
Ok(()) => info!(path = %path.display(), "removed state.json"),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => tracing::warn!(%error, path = %path.display(), "failed to remove state.json"),
}
}

fn purge_config(config_dir: &std::path::Path, keep_profiles: bool) -> Result<()> {
if keep_profiles {
for entry in std::fs::read_dir(config_dir)? {
let entry = entry?;
if entry.file_name() == paths::PROFILES_DIRECTORY {
continue;
}
let path = entry.path();
let remove = if entry.file_type()?.is_dir() {
std::fs::remove_dir_all(&path)
} else {
std::fs::remove_file(&path)
};
remove.with_context(|| format!("removing {}", path.display()))?;
}
} else if config_dir.exists() {
std::fs::remove_dir_all(config_dir)
.with_context(|| format!("removing {}", config_dir.display()))?;
info!(path = %config_dir.display(), "purged config dir");
}
Ok(())
}

fn purge_user_data(keep_profiles: bool) -> Result<()> {
let config_dir = paths::config_dir()?;
purge_config(&config_dir, keep_profiles)?;
let log_dir = paths::log_dir()?;
if log_dir.exists() {
std::fs::remove_dir_all(&log_dir)
Expand All @@ -85,3 +117,27 @@ fn purge_user_data() -> Result<()> {
println!("Purged config and logs.");
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn default_reset_preserves_named_profile_credentials() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The new test covers only purge_config. Add coverage for the profile state.json removal in uninstall and for the --keep-profiles argument wiring, since neither is exercised here.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/stdiod/crates/sealgate-stdiod/src/cli/install.rs, line 124:

<comment>The new test covers only `purge_config`. Add coverage for the profile state.json removal in `uninstall` and for the `--keep-profiles` argument wiring, since neither is exercised here.</comment>

<file context>
@@ -85,3 +115,27 @@ fn purge_user_data() -> Result<()> {
+    use super::*;
+
+    #[test]
+    fn default_reset_preserves_named_profile_credentials() {
+        let root =
+            std::env::temp_dir().join(format!("stdiod-profile-purge-{}", std::process::id()));
</file context>

let root =
std::env::temp_dir().join(format!("stdiod-profile-purge-{}", std::process::id()));
let profile = root.join(paths::PROFILES_DIRECTORY).join("staging");
std::fs::create_dir_all(&profile).unwrap();
std::fs::write(root.join("config.toml"), "default-config").unwrap();
std::fs::write(profile.join("config.toml"), "staging-config").unwrap();

purge_config(&root, true).unwrap();
assert!(!root.join("config.toml").exists());
assert_eq!(
std::fs::read_to_string(profile.join("config.toml")).unwrap(),
"staging-config"
);
purge_config(&root, false).unwrap();
assert!(!root.exists());
}
}
6 changes: 5 additions & 1 deletion crates/stdiod/crates/sealgate-stdiod/src/cli/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,11 @@ fn save_login(cfg: &PersistedConfig) -> Result<()> {
crate::power::save_keeping_power(cfg, &path)?;
info!(path = %path.display(), "wrote config.toml");
println!("Saved {}", path.display());
println!("Next: `sealgate-stdiod install` to register the supervisor service.");
if paths::profile_name().is_some() {
println!("A running daemon picks up this profile automatically. To start the service, run `sealgate-stdiod install`.");
} else {
println!("Next: `sealgate-stdiod install` to register the supervisor service.");
}
Ok(())
}

Expand Down
5 changes: 4 additions & 1 deletion crates/stdiod/crates/sealgate-stdiod/src/cli/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,11 @@ pub(crate) async fn submit(

fn format_create_result(name: &str, response: ClientCreateRequestResponse) -> String {
if response.auto_approved {
let profile_option = crate::paths::profile_name()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The new --profile suffix in the auto-approved hint has no test. Add a case that runs format_create_result inside paths::with_profile(Some("work".into()), ...) and asserts the output contains status --profile work.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/stdiod/crates/sealgate-stdiod/src/cli/server.rs, line 145:

<comment>The new `--profile` suffix in the auto-approved hint has no test. Add a case that runs `format_create_result` inside `paths::with_profile(Some("work".into()), ...)` and asserts the output contains `status --profile work`.</comment>

<file context>
@@ -142,8 +142,11 @@ pub(crate) async fn submit(
 
 fn format_create_result(name: &str, response: ClientCreateRequestResponse) -> String {
     if response.auto_approved {
+        let profile_option = crate::paths::profile_name()
+            .map(|profile| format!(" --profile {profile}"))
+            .unwrap_or_default();
</file context>

.map(|profile| format!(" --profile {profile}"))
.unwrap_or_default();
format!(
"Request '{name}' was auto-approved (request ID {}). Run `sealgate-stdiod status` to confirm it has spawned.",
"Request '{name}' was auto-approved (request ID {}). Run `sealgate-stdiod status{profile_option}` to confirm it has spawned.",
response.request_id
)
} else {
Expand Down
11 changes: 11 additions & 0 deletions crates/stdiod/crates/sealgate-stdiod/src/cli/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,17 @@ pub fn run(_args: StatusArgs) -> Result<()> {
}
}

if paths::profile_name().is_none() {
match paths::profile_names() {
Ok(names) if !names.is_empty() => println!(
"Backend profiles: {} (use `status --profile <name>`)",
names.join(", ")
),
Ok(_) => {}
Err(error) => println!("Backend profiles: (unavailable: {error})"),
}
}

// Exit codes describe HEALTH; the line printed above describes the cause.
// So "loaded but dead" and "never loaded" both map to EXIT_NOT_RUNNING
// rather than growing a fourth code - callers branch on healthy/unhealthy,
Expand Down
83 changes: 52 additions & 31 deletions crates/stdiod/crates/sealgate-stdiod/src/daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//!
//! Connection lifecycle:
//!
//! 1. Outer ``run`` loop keeps a long-lived [`Supervisor`] across WS
//! 1. ``run_backend`` loop keeps a long-lived [`Supervisor`] across WS
//! reconnects. Children survive transient disconnects - their
//! [`OutgoingHandle`] is rewired on each new WS so MCP frames keep
//! flowing without restarting subprocesses.
Expand All @@ -27,17 +27,18 @@ use tokio::sync::{mpsc, watch, Mutex};
use tokio::time::sleep;
use tracing::{debug, info, warn};

use crate::config;
pub use crate::daemon_auth::RunArgs;
use crate::daemon_auth::RunArgs;
use crate::daemon_auth::{
connection_error_message, is_auth_rejection, is_protocol_rejection, requires_child_reset,
ResolveRunError, ResolvedRun,
};
use crate::daemon_profiles::wait_for_shutdown;
use crate::env_store::EnvStore;
use crate::power::controller::{KeepAwake, ReportTarget};
use crate::state::{ConnectionState, State, StateWriter};
use crate::supervisor::Supervisor;
use crate::tunnel::{self, OutgoingHandle};
use crate::{config, paths};

// The daemon pings every 15s and considers the connection dead if no pong
// arrives within HEARTBEAT_STALE_AFTER. On stale, the WS is closed and
Expand All @@ -56,9 +57,9 @@ const BACKOFF_MIN: Duration = Duration::from_secs(1);
const BACKOFF_MAX: Duration = Duration::from_secs(30);
const CONFIG_POLL_INTERVAL: Duration = Duration::from_secs(1);

pub async fn run(args: RunArgs) -> Result<()> {
#[cfg(windows)]
crate::platform::windows::kill_children_on_exit();
pub(crate) async fn run_backend(args: RunArgs, signal: watch::Receiver<bool>) -> Result<()> {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
let shutdown_signal = wait_for_shutdown(signal);
tokio::pin!(shutdown_signal);
let initial = ResolvedRun::from_args(&args);
// The keep-awake status from the previous run: its local choice applies
// while config.toml cannot be read. Its dashboard value applies until the
Expand All @@ -67,15 +68,18 @@ pub async fn run(args: RunArgs) -> Result<()> {
let previous_keep_awake = State::load()
.ok()
.and_then(|state| previous_keep_awake(state, initial.as_ref().ok()));
let writer = StateWriter::new(State {
backend_url: initial.as_ref().ok().map(|value| value.backend.clone()),
device_id: initial.as_ref().ok().map(|value| value.device_id.clone()),
device_label: initial.as_ref().ok().map(|value| value.label.clone()),
pid: Some(std::process::id()),
..State::default()
});
let writer = StateWriter::new_at(
State {
backend_url: initial.as_ref().ok().map(|value| value.backend.clone()),
device_id: initial.as_ref().ok().map(|value| value.device_id.clone()),
device_label: initial.as_ref().ok().map(|value| value.label.clone()),
pid: Some(std::process::id()),
..State::default()
},
paths::state_file()?,
);
writer.update(|_| {}).await;
let keep_awake = KeepAwake::start(previous_keep_awake, writer.clone());
let keep_awake = KeepAwake::start(previous_keep_awake, writer.clone(), paths::config_file()?);
let mut resolved = match initial {
Ok(resolved) => resolved,
Err(ResolveRunError::AwaitingLogin) => {
Expand All @@ -88,7 +92,10 @@ pub async fn run(args: RunArgs) -> Result<()> {
})
.await;
loop {
sleep(CONFIG_POLL_INTERVAL).await;
tokio::select! {
_ = &mut shutdown_signal => return Ok(()),
_ = sleep(CONFIG_POLL_INTERVAL) => {}
}
if let Ok(resolved) = ResolvedRun::from_args(&args) {
break resolved;
}
Expand All @@ -106,11 +113,6 @@ pub async fn run(args: RunArgs) -> Result<()> {
})
.await;

// Resolve the interactive login-shell PATH once, up front, so child MCP
// servers can find version-manager node/npx (nvm/fnm/...) - the daemon's own
// (systemd/launchd) PATH doesn't include shell-rc additions. See proc.rs.
crate::proc::init_child_env().await;

// The supervisor - and the broker handle the children depend on -
// live across reconnects. ``apply_snapshot`` on each new WS will
// diff and reconcile.
Expand All @@ -125,8 +127,6 @@ pub async fn run(args: RunArgs) -> Result<()> {
)));

let mut backoff = BACKOFF_MIN;
let shutdown_signal = crate::process_shutdown::wait();
tokio::pin!(shutdown_signal);
loop {
let result = tokio::select! {
result = run_one_session(&resolved, &args, supervisor.clone(), &outgoing, &writer, &keep_awake) => result,
Expand Down Expand Up @@ -212,7 +212,13 @@ pub async fn run(args: RunArgs) -> Result<()> {
let current_env_namespace = resolved.env_namespace();
let next_env_namespace = next.env_namespace();
if current_env_namespace != next_env_namespace {
let env_store = EnvStore::open_for(next_env_namespace.as_deref())?;
let env_store = match EnvStore::open_for(next_env_namespace.as_deref()) {
Ok(store) => store,
Err(error) => {
supervisor.lock().await.shutdown_children().await;
return Err(error);
}
};
supervisor.lock().await.switch_env_store(env_store).await;
} else if reset_children {
supervisor.lock().await.shutdown_children().await;
Expand Down Expand Up @@ -321,6 +327,7 @@ async fn wait_for_config(
return current.clone();
}
let sleep_for = deadline
.filter(|_| !saw_unusable_config)
.map(|deadline| {
deadline
.saturating_duration_since(Instant::now())
Expand Down Expand Up @@ -354,6 +361,19 @@ async fn wait_for_connection_change(
}
}

// A shutdown can cancel run_one_session while any of its tasks are still
// running. Dropping a JoinHandle alone would leave that task detached.
#[derive(Default)]
struct SessionTasks(Vec<tokio::task::AbortHandle>);

impl Drop for SessionTasks {
fn drop(&mut self) {
for task in &self.0 {
task.abort();
}
}
}

/// One connect + drain pass. Returns Ok when the WS closed cleanly (we'll
/// reconnect), Err on connect failure.
async fn run_one_session(
Expand All @@ -375,9 +395,11 @@ async fn run_one_session(
let (incoming_tx, mut incoming_rx) = mpsc::channel::<TunnelFrame>(64);

// Wire the broker before any task can publish a frame.
outgoing.set(outgoing_tx.clone());
outgoing.set(outgoing_tx);

let mut tasks = SessionTasks::default();
let mut ws_task = tokio::spawn(tunnel::run_frame_loop(ws, outgoing_rx, incoming_tx));
tasks.0.push(ws_task.abort_handle());

// client_hello: announce which servers we already have running so the
// backend can reconcile.
Expand Down Expand Up @@ -420,6 +442,8 @@ async fn run_one_session(
tokio::spawn(heartbeat(outgoing, last_pong, keep_awake.clone()))
};

tasks.0.push(hb_task.abort_handle());

// Children that exit on their own are started again, with backoff
// (Supervisor::respawn_exited). Only after server_hello: a respawn sends
// frames the backend refuses before it has registered the device, and the
Expand All @@ -443,6 +467,8 @@ async fn run_one_session(
})
};

tasks.0.push(respawn_task.abort_handle());

let session = SessionContext {
keep_awake,
target: ReportTarget {
Expand All @@ -453,7 +479,7 @@ async fn run_one_session(
sent: keep_awake_sent,
resume_sent,
};
let result = tokio::select! {
tokio::select! {
biased;
r = drain_incoming(supervisor.clone(), &mut incoming_rx, last_pong, writer, &hello_tx, &session) => match r {
Ok(()) => websocket_task_result(&mut ws_task).await,
Expand All @@ -471,12 +497,7 @@ async fn run_one_session(
info!("configuration changed; restarting authenticated session");
Ok(())
}
};
hb_task.abort();
respawn_task.abort();
ws_task.abort();
drop(outgoing_tx);
result
}
}

async fn websocket_task_result(task: &mut tokio::task::JoinHandle<Result<()>>) -> Result<()> {
Expand Down
2 changes: 1 addition & 1 deletion crates/stdiod/crates/sealgate-stdiod/src/daemon_auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use thiserror::Error;

use crate::{config, tunnel};

#[derive(Debug, Args, Clone)]
#[derive(Debug, Args, Clone, Default)]
pub struct RunArgs {
/// Backend base URL (http://localhost:8000, https://dashboard.sealgate.ai, ...).
/// Falls back to `backend_url` in `~/.config/sealgate-stdiod/config.toml`.
Expand Down
Loading
Loading