Skip to content

Commit b88f22e

Browse files
committed
feat(desktop): add Tauri commands to end and recover remote thread sessions
Add the backend half of explicit thread-session lifecycle control for thread-sandbox providers. Providers may advertise `ops` in `info`; `provider_stop` sends the secret-bearing `stop` request only after the same staged bytes negotiated protocol v1 and advertised `stop`. New commands `end_remote_agent_session`, `recover_remote_agent_session` and `remote_agent_session_supports_lifecycle` share the deploy path's per-agent lock, post-lock payload rebuild, tenant scope assertion, and session binding. The recovery mode rides one invocation's provider config and is never persisted on the agent record. Expose typed TypeScript bindings for the three commands. Signed-off-by: Tee8z <[email protected]>
1 parent 7b1e7a7 commit b88f22e

16 files changed

Lines changed: 1147 additions & 259 deletions

File tree

‎crates/buzz-backend-kubernetes/src/main.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,10 @@ mod tests {
253253
assert_eq!(json["ok"], true);
254254
assert_eq!(json["protocol_version"], wire::PROTOCOL_VERSION);
255255
assert!(json["config_schema"]["properties"]["namespace"].is_object());
256-
assert!(json.get("ops").is_none());
256+
assert_eq!(
257+
json["ops"],
258+
serde_json::json!(["info", "deploy", "stop", "recover"])
259+
);
257260
}
258261

259262
/// `stop` is gated like a preflight: no approved identity policy, no

‎crates/buzz-backend-kubernetes/src/wire.rs‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@ use std::collections::BTreeMap;
1212
/// The wire-contract version this provider speaks (spec §Info).
1313
pub const PROTOCOL_VERSION: u32 = 1;
1414

15+
/// What this provider supports, advertised in `info.ops`. Additive within
16+
/// protocol version 1. Each entry is a request `op`, except `recover`: it
17+
/// advertises that `deploy` accepts `provider_config.sandbox.recovery`. A
18+
/// desktop gates its session end/recover actions on `recover`.
19+
pub const OPS: &[&str] = &["info", "deploy", "stop", "recover"];
20+
1521
/// Request envelope. `op` discriminates; unknown ops are an in-band error.
1622
///
1723
/// `request_id` is deliberately absent from every variant. The desktop sends
@@ -108,6 +114,7 @@ pub struct InfoResponse {
108114
pub name: &'static str,
109115
pub version: &'static str,
110116
pub protocol_version: u32,
117+
pub ops: &'static [&'static str],
111118
pub description: &'static str,
112119
pub config_schema: serde_json::Value,
113120
}
@@ -267,6 +274,7 @@ impl Response {
267274
name: "kubernetes",
268275
version: env!("CARGO_PKG_VERSION"),
269276
protocol_version: PROTOCOL_VERSION,
277+
ops: OPS,
270278
description: "Runs agents as pods in a Kubernetes cluster",
271279
config_schema: crate::config::config_schema(),
272280
})
@@ -335,9 +343,12 @@ mod tests {
335343
}
336344

337345
#[test]
338-
fn info_remains_compatible_until_the_desktop_accepts_ops() {
346+
fn info_advertises_stop_and_recover() {
339347
let v = serde_json::to_value(Response::info()).unwrap();
340-
assert!(v.get("ops").is_none());
348+
assert_eq!(
349+
v["ops"],
350+
serde_json::json!(["info", "deploy", "stop", "recover"])
351+
);
341352
}
342353

343354
#[test]

‎crates/buzz-backend-kubernetes/tests/wire_fixtures.rs‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -149,9 +149,12 @@ fn info_response_carries_the_contract_fields() {
149149
assert_eq!(info["ok"], true);
150150
assert_eq!(info["protocol_version"], 1);
151151
assert_eq!(info["name"], "kubernetes");
152-
// `ops` is not advertised yet: a desktop that predates it must keep
153-
// accepting `info`. A later change adds it, additive within version 1.
154-
assert!(info.get("ops").is_none());
152+
// Additive within protocol version 1; the desktop gates its session
153+
// end/recover actions on `recover`.
154+
assert_eq!(
155+
info["ops"],
156+
serde_json::json!(["info", "deploy", "stop", "recover"])
157+
);
155158
let schema = &info["config_schema"];
156159
assert_eq!(
157160
schema["required"],

‎desktop/src-tauri/src/commands/agent_providers.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ pub async fn probe_backend_provider(binary_path: String) -> Result<serde_json::V
5858
});
5959
tokio::task::spawn_blocking(move || {
6060
invoke_provider(&canonical, &request, std::time::Duration::from_secs(10))
61+
.map_err(String::from)
6162
})
6263
.await
6364
.map_err(|e| format!("spawn_blocking failed: {e}"))?

‎desktop/src-tauri/src/commands/agents.rs‎

Lines changed: 44 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,9 @@ use crate::{
1212
save_managed_agents, start_managed_agent_process, stop_managed_agent_process,
1313
stop_managed_agent_workspace_pair, sync_managed_agent_processes, try_regenerate_nest,
1414
validate_provider_config, BackendKind, CreateManagedAgentRequest,
15-
CreateManagedAgentResponse, ManagedAgentRecord, ManagedAgentSummary, RelayMeshConfig,
16-
DEFAULT_ACP_COMMAND, DEFAULT_AGENT_PARALLELISM, DEFAULT_AGENT_TURN_TIMEOUT_SECONDS,
15+
CreateManagedAgentResponse, ManagedAgentRecord, ManagedAgentSummary, ProviderFailure,
16+
RelayMeshConfig, DEFAULT_ACP_COMMAND, DEFAULT_AGENT_PARALLELISM,
17+
DEFAULT_AGENT_TURN_TIMEOUT_SECONDS,
1718
},
1819
relay::relay_ws_url_with_override,
1920
util::now_iso,
@@ -332,6 +333,7 @@ where
332333
}
333334

334335
pub(crate) use provider_deploy::deploy_to_provider;
336+
use provider_deploy::{InvocationScope, ProviderAction};
335337

336338
// Async so the blocking body (disk reads of agent/persona records, per-agent
337339
// process-liveness syscalls, and a possible save) runs on Tauri's worker pool
@@ -829,8 +831,10 @@ async fn create_managed_agent_in<R: tauri::Runtime>(
829831
&& input.backend != BackendKind::Local
830832
&& !input.backend.is_thread_sandbox()
831833
{
832-
if let BackendKind::Provider { ref id, ref config } = input.backend {
833-
let agent_json = {
834+
if let BackendKind::Provider { .. } = input.backend {
835+
{
836+
// Fail create on a payload that cannot be built; deploy
837+
// rebuilds it after its lock.
834838
let _g = state
835839
.managed_agents_store_lock
836840
.lock()
@@ -840,15 +844,11 @@ async fn create_managed_agent_in<R: tauri::Runtime>(
840844
.iter()
841845
.find(|r| r.pubkey == pubkey)
842846
.ok_or_else(|| "agent disappeared".to_string())?;
843-
build_deploy_payload(&app, state, rec)?
844-
};
845-
match deploy_to_provider(
846-
&app, state, &pubkey, id, config, agent_json, None, None, None, None, None,
847-
)
848-
.await
849-
{
847+
build_deploy_payload(&app, state, rec)?;
848+
}
849+
match deploy_to_provider(&app, state, &pubkey, &Default::default(), None).await {
850850
Ok(()) => spawn_error,
851-
Err(e) => Some(e),
851+
Err(e) => Some(e.message),
852852
}
853853
} else {
854854
spawn_error
@@ -895,7 +895,7 @@ pub async fn start_managed_agent(
895895
session_scope: Option<provider_deploy::RemoteSessionScope>,
896896
app: AppHandle,
897897
state: State<'_, AppState>,
898-
) -> Result<ManagedAgentSummary, String> {
898+
) -> Result<ManagedAgentSummary, ProviderFailure> {
899899
// Snapshot the workspace owner pubkey for the legacy auth_tag fallback.
900900
// Read outside the records lock to keep lock ordering simple.
901901
let owner_hex = workspace_owner_hex(&state)?;
@@ -926,11 +926,7 @@ pub async fn start_managed_agent(
926926
)?;
927927
enum StartTarget {
928928
Local,
929-
Provider {
930-
backend: BackendKind,
931-
cached_binary_path: Option<String>,
932-
agent_json: serde_json::Value,
933-
},
929+
Provider { backend: BackendKind },
934930
}
935931

936932
// Collect backend info under lock; async preflight/spawn happens below.
@@ -973,33 +969,31 @@ pub async fn start_managed_agent(
973969
let target = if record.backend == BackendKind::Local {
974970
StartTarget::Local
975971
} else {
972+
// Fail before the deploy lock on a payload that cannot be
973+
// built; deploy rebuilds it after the lock.
974+
build_deploy_payload(&app, &state, record)?;
976975
StartTarget::Provider {
977976
backend: record.backend.clone(),
978-
cached_binary_path: record.provider_binary_path.clone(),
979-
agent_json: build_deploy_payload(&app, &state, record)?,
980977
}
981978
};
982979

983980
(target, reconcile)
984981
};
985982

986983
let result = match target {
987-
StartTarget::Local => {
988-
start_local_agent_with_preflight(
989-
&app,
990-
&state,
991-
&pubkey,
992-
false,
993-
expected_relay_url.as_deref(),
994-
expected_signer_pubkey.as_deref(),
995-
replay_floor_unix,
996-
)
997-
.await
998-
}
984+
StartTarget::Local => start_local_agent_with_preflight(
985+
&app,
986+
&state,
987+
&pubkey,
988+
false,
989+
expected_relay_url.as_deref(),
990+
expected_signer_pubkey.as_deref(),
991+
replay_floor_unix,
992+
)
993+
.await
994+
.map_err(ProviderFailure::from),
999995
StartTarget::Provider {
1000-
backend: BackendKind::Provider { id, config },
1001-
cached_binary_path,
1002-
agent_json,
996+
backend: BackendKind::Provider { .. },
1003997
} => {
1004998
// The caller's captured scope is asserted INSIDE deploy_to_provider
1005999
// against the payload rebuilt after the deploy lock — the exact
@@ -1008,20 +1002,13 @@ pub async fn start_managed_agent(
10081002
// The replay floor rides along so a publish-first mention send's
10091003
// remote harness replays past the already-published message, same
10101004
// as the local spawn path.
1011-
deploy_to_provider(
1012-
&app,
1013-
&state,
1014-
&pubkey,
1015-
&id,
1016-
&config,
1017-
agent_json,
1018-
cached_binary_path.as_deref(),
1019-
expected_relay_url.as_deref(),
1020-
expected_signer_pubkey.as_deref(),
1021-
replay_floor_unix,
1022-
session_scope.as_ref(),
1023-
)
1024-
.await?;
1005+
let scope = InvocationScope {
1006+
expected_relay_url: expected_relay_url.as_deref(),
1007+
expected_signer_pubkey: expected_signer_pubkey.as_deref(),
1008+
session: session_scope.as_ref(),
1009+
action: ProviderAction::Deploy,
1010+
};
1011+
deploy_to_provider(&app, &state, &pubkey, &scope, replay_floor_unix).await?;
10251012

10261013
// Return updated summary.
10271014
let _store_guard = state
@@ -1037,11 +1024,11 @@ pub async fn start_managed_agent(
10371024
.iter()
10381025
.find(|r| r.pubkey == pubkey)
10391026
.ok_or_else(|| format!("agent {pubkey} not found"))?;
1040-
summarize_from_disk(&app, record, &runtimes)
1027+
Ok(summarize_from_disk(&app, record, &runtimes)?)
1028+
}
1029+
StartTarget::Provider { backend } => {
1030+
Err(format!("agent {pubkey} has unsupported backend kind: {backend:?}").into())
10411031
}
1042-
StartTarget::Provider { backend, .. } => Err(format!(
1043-
"agent {pubkey} has unsupported backend kind: {backend:?}"
1044-
)),
10451032
};
10461033

10471034
// ── Profile reconciliation (fire-and-forget) ────────────────────────────
@@ -1229,11 +1216,15 @@ pub async fn delete_managed_agent(
12291216
mod deploy;
12301217
pub(super) mod provider_access;
12311218
mod provider_deploy;
1219+
mod remote_session;
12321220
pub(super) use deploy::build_deploy_payload;
12331221
#[cfg(test)]
12341222
use deploy::{deploy_payload_json, DeployProjections};
12351223
#[cfg(test)]
12361224
use deploy::{ensure_remote_provider_supported, resolve_deploy_model_provider};
1225+
pub use remote_session::{
1226+
end_remote_agent_session, recover_remote_agent_session, remote_agent_session_supports_lifecycle,
1227+
};
12371228

12381229
#[path = "agents_profile.rs"]
12391230
mod profile;

‎desktop/src-tauri/src/commands/agents/provider_access.rs‎

Lines changed: 11 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,6 @@ pub(super) fn needs_reconciliation_with_policy(
2626
#[derive(Debug)]
2727
struct ProviderAccessTarget {
2828
pubkey: String,
29-
provider_id: String,
30-
config: serde_json::Value,
31-
cached_binary_path: Option<String>,
3229
agent_json: Result<serde_json::Value, String>,
3330
}
3431

@@ -40,13 +37,10 @@ fn collect_targets_with(
4037
records
4138
.into_iter()
4239
.filter(|record| needs_reconciliation_with_policy(record, owner_only_access))
43-
.map(|record| match record.backend.clone() {
44-
BackendKind::Provider { id, config } => ProviderAccessTarget {
40+
.map(|record| match record.backend {
41+
BackendKind::Provider { .. } => ProviderAccessTarget {
4542
agent_json: build_payload(&record),
4643
pubkey: record.pubkey,
47-
provider_id: id,
48-
config,
49-
cached_binary_path: record.provider_binary_path,
5044
},
5145
BackendKind::Local => {
5246
unreachable!("provider access reconciliation selected a local agent")
@@ -77,36 +71,15 @@ pub(crate) async fn reconcile_on_workspace_apply(
7771
};
7872

7973
for target in targets {
80-
let ProviderAccessTarget {
81-
pubkey,
82-
provider_id,
83-
config,
84-
cached_binary_path,
85-
agent_json,
86-
} = target;
87-
let agent_json = match agent_json {
88-
Ok(agent_json) => agent_json,
89-
Err(error) => {
90-
persist_failure(app, state, &pubkey, &error)?;
91-
return Err(format!(
92-
"provider access reconciliation failed for agent {pubkey}: {error}"
93-
));
94-
}
95-
};
96-
if let Err(error) = super::deploy_to_provider(
97-
app,
98-
state,
99-
&pubkey,
100-
&provider_id,
101-
&config,
102-
agent_json,
103-
cached_binary_path.as_deref(),
104-
None,
105-
None,
106-
None,
107-
None,
108-
)
109-
.await
74+
let ProviderAccessTarget { pubkey, agent_json } = target;
75+
if let Err(error) = agent_json {
76+
persist_failure(app, state, &pubkey, &error)?;
77+
return Err(format!(
78+
"provider access reconciliation failed for agent {pubkey}: {error}"
79+
));
80+
}
81+
if let Err(error) =
82+
super::deploy_to_provider(app, state, &pubkey, &Default::default(), None).await
11083
{
11184
return Err(format!(
11285
"provider access reconciliation failed for agent {pubkey}: {error}"
@@ -198,8 +171,6 @@ mod tests {
198171

199172
assert_eq!(targets.len(), 1);
200173
assert_eq!(targets[0].pubkey, "agent");
201-
assert_eq!(targets[0].provider_id, "provider");
202-
assert_eq!(targets[0].config["region"], "test");
203174
assert_eq!(
204175
targets[0].agent_json.as_ref().unwrap()["respond_to"],
205176
"owner-only"
@@ -231,7 +202,6 @@ mod tests {
231202

232203
assert_eq!(targets.len(), 1);
233204
assert_eq!(targets[0].pubkey, "pending-agent");
234-
assert_eq!(targets[0].provider_id, "pending-provider");
235205
assert_eq!(
236206
targets[0].agent_json.as_ref().unwrap()["pubkey"],
237207
"pending-agent"

0 commit comments

Comments
 (0)