Skip to content

Commit 2294709

Browse files
committed
feat(desktop): start thread-bound remote sessions from mentions
After a mention is published, pass its channel and canonical thread root to the detached agent start. For a Kubernetes provider with `sandbox: true`, native deploy binds that thread scope and the verified owner after the deployment lock, and refuses to start without a thread. Provider config fields accept bounded, nested JSON objects and arrays. Signed-off-by: Tee8z <[email protected]>
1 parent 456de66 commit 2294709

32 files changed

Lines changed: 571 additions & 30 deletions

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -824,7 +824,11 @@ async fn create_managed_agent_in<R: tauri::Runtime>(
824824
profile_sync_error =
825825
super::agent_models::flush_managed_agent_policy(&app, state, profile_sync_error).await;
826826

827-
let spawn_error = if input.spawn_after_create && input.backend != BackendKind::Local {
827+
// A thread-bound provider starts only after a mention supplies its scope.
828+
let spawn_error = if input.spawn_after_create
829+
&& input.backend != BackendKind::Local
830+
&& !input.backend.is_thread_sandbox()
831+
{
828832
if let BackendKind::Provider { ref id, ref config } = input.backend {
829833
let agent_json = {
830834
let _g = state
@@ -839,7 +843,7 @@ async fn create_managed_agent_in<R: tauri::Runtime>(
839843
build_deploy_payload(&app, state, rec)?
840844
};
841845
match deploy_to_provider(
842-
&app, state, &pubkey, id, config, agent_json, None, None, None, None,
846+
&app, state, &pubkey, id, config, agent_json, None, None, None, None, None,
843847
)
844848
.await
845849
{
@@ -888,6 +892,7 @@ pub async fn start_managed_agent(
888892
expected_relay_url: Option<String>,
889893
expected_signer_pubkey: Option<String>,
890894
replay_floor_unix: Option<u64>,
895+
session_scope: Option<provider_deploy::RemoteSessionScope>,
891896
app: AppHandle,
892897
state: State<'_, AppState>,
893898
) -> Result<ManagedAgentSummary, String> {
@@ -1014,6 +1019,7 @@ pub async fn start_managed_agent(
10141019
expected_relay_url.as_deref(),
10151020
expected_signer_pubkey.as_deref(),
10161021
replay_floor_unix,
1022+
session_scope.as_ref(),
10171023
)
10181024
.await?;
10191025

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ pub(super) fn needs_reconciliation_with_policy(
1616
owner_only_access: bool,
1717
) -> bool {
1818
(owner_only_access || record.provider_policy_pending)
19+
// Thread Sandboxes enforce their owner/thread inside the harness.
20+
// Configuration applies on the next scoped launch, never on app reopen.
21+
&& !record.backend.is_thread_sandbox()
1922
&& record.backend != BackendKind::Local
2023
&& record.backend_agent_id.is_some()
2124
}
@@ -101,6 +104,7 @@ pub(crate) async fn reconcile_on_workspace_apply(
101104
None,
102105
None,
103106
None,
107+
None,
104108
)
105109
.await
106110
{
@@ -148,6 +152,26 @@ mod tests {
148152
record
149153
}
150154

155+
#[test]
156+
fn thread_sandboxes_do_not_redeploy_during_workspace_apply() {
157+
let mut sandbox = record(
158+
BackendKind::Provider {
159+
id: "kubernetes".into(),
160+
config: serde_json::json!({"sandbox":true}),
161+
},
162+
Some("thread-workspace"),
163+
);
164+
sandbox.provider_policy_pending = true;
165+
for owner_only in [false, true] {
166+
assert!(
167+
collect_targets_with(vec![sandbox.clone()], owner_only, |_| {
168+
panic!("an app lifecycle event must not build an unscoped thread deployment")
169+
})
170+
.is_empty()
171+
);
172+
}
173+
}
174+
151175
#[test]
152176
fn upgrade_collects_existing_provider_and_builds_projected_payload() {
153177
let records = vec![

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

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,45 @@ use crate::{
1313

1414
use super::build_deploy_payload;
1515

16+
#[derive(serde::Deserialize)]
17+
#[serde(rename_all = "camelCase", deny_unknown_fields)]
18+
/// Published channel and canonical thread that own a remote workspace.
19+
pub struct RemoteSessionScope {
20+
channel_id: uuid::Uuid,
21+
thread_root: String,
22+
}
23+
24+
fn bind_sandbox_scope(
25+
config: &mut serde_json::Value,
26+
scope: Option<&RemoteSessionScope>,
27+
agent_pubkey: &str,
28+
payload: &serde_json::Value,
29+
) -> Result<(), String> {
30+
if config.get("sandbox") != Some(&serde_json::Value::Bool(true)) {
31+
return Ok(());
32+
}
33+
let scope = scope.ok_or("Mention this agent in a channel thread to start its workspace")?;
34+
if scope.thread_root.len() != 64
35+
|| !scope
36+
.thread_root
37+
.bytes()
38+
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
39+
{
40+
return Err("Remote workspace requires a canonical thread root".into());
41+
}
42+
let owner = payload
43+
.pointer("/launch/owner_pubkey")
44+
.and_then(|v| v.as_str())
45+
.ok_or("Remote workspace requires a verified owner")?;
46+
config["sandbox"] = serde_json::json!({
47+
"channel_id": scope.channel_id.to_string(), "thread_root": scope.thread_root,
48+
});
49+
config["identity_policy"] = serde_json::json!({
50+
"agent_pubkey": agent_pubkey, "owner_pubkey": owner,
51+
});
52+
Ok(())
53+
}
54+
1655
/// Deploy an agent to a provider backend. Resolves the binary, calls deploy via
1756
/// spawn_blocking, and persists the result (backend_agent_id or last_error).
1857
///
@@ -50,6 +89,7 @@ pub(crate) async fn deploy_to_provider<R: tauri::Runtime>(
5089
expected_relay_url: Option<&str>,
5190
expected_signer_pubkey: Option<&str>,
5291
replay_floor_unix: Option<u64>,
92+
session_scope: Option<&RemoteSessionScope>,
5393
) -> Result<(), String> {
5494
let deploy_lock = {
5595
let mut locks = state
@@ -66,7 +106,7 @@ pub(crate) async fn deploy_to_provider<R: tauri::Runtime>(
66106
// The payload may have waited behind another deployment. Rebuild it from
67107
// the current record so the final provider invocation always carries the
68108
// newest saved policy rather than the stale snapshot captured by its caller.
69-
let (provider_id, config, cached_binary_path, mut agent_json) = {
109+
let (provider_id, mut config, cached_binary_path, mut agent_json) = {
70110
let _store_guard = state
71111
.managed_agents_store_lock
72112
.lock()
@@ -91,6 +131,7 @@ pub(crate) async fn deploy_to_provider<R: tauri::Runtime>(
91131
// Assert the caller's captured scope against THIS payload — the exact
92132
// value invoked below — not the pre-lock snapshot its caller validated.
93133
assert_payload_scope(&agent_json, expected_relay_url, expected_signer_pubkey)?;
134+
bind_sandbox_scope(&mut config, session_scope, pubkey, &agent_json)?;
94135
// The floor is invocation state, not record state, so the post-lock
95136
// rebuild cannot restore it — inject it into the payload actually invoked.
96137
apply_replay_floor(&mut agent_json, replay_floor_unix);
@@ -262,6 +303,29 @@ fn apply_deploy_result(
262303
mod tests {
263304
use super::*;
264305

306+
#[test]
307+
fn sandbox_scope_is_required_and_bound_to_the_rebuilt_owner() {
308+
let scope = RemoteSessionScope {
309+
channel_id: uuid::Uuid::new_v4(),
310+
thread_root: "a".repeat(64),
311+
};
312+
let mut config = serde_json::json!({"sandbox":true});
313+
let payload = serde_json::json!({"launch":{"owner_pubkey":"owner"}});
314+
assert!(bind_sandbox_scope(&mut config, None, "agent", &payload).is_err());
315+
assert_eq!(config["sandbox"], true);
316+
bind_sandbox_scope(&mut config, Some(&scope), "agent", &payload).unwrap();
317+
assert_eq!(config["sandbox"]["thread_root"], scope.thread_root);
318+
assert_eq!(config["identity_policy"]["owner_pubkey"], "owner");
319+
let mut missing_owner = serde_json::json!({"sandbox":true});
320+
assert!(bind_sandbox_scope(
321+
&mut missing_owner,
322+
Some(&scope),
323+
"agent",
324+
&serde_json::json!({})
325+
)
326+
.is_err());
327+
}
328+
265329
fn record() -> crate::managed_agents::ManagedAgentRecord {
266330
serde_json::from_value(serde_json::json!({
267331
"pubkey": "agent", "name": "Agent", "relay_url": "", "acp_command": "",

‎desktop/src-tauri/src/commands/personas/inbound.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ pub async fn reconcile_inbound_persona_event(
136136
None,
137137
None,
138138
None,
139+
None,
139140
)
140141
.await
141142
.map_err(|error| {
@@ -376,7 +377,8 @@ fn reconcile_inbound_persona_event_blocking<R: tauri::Runtime>(
376377
}
377378
}
378379
crate::managed_agents::BackendKind::Provider { id, config }
379-
if record.backend_agent_id.is_some() =>
380+
if record.backend_agent_id.is_some()
381+
&& !record.backend.is_thread_sandbox() =>
380382
{
381383
// Persist the unacknowledged policy transition in the
382384
// same write as the narrowed policy. If the process
@@ -393,6 +395,8 @@ fn reconcile_inbound_persona_event_blocking<R: tauri::Runtime>(
393395
),
394396
});
395397
}
398+
// Thread Sandboxes keep their immutable owner/thread gate and
399+
// take configuration on their next explicit scoped launch.
396400
crate::managed_agents::BackendKind::Provider { .. } => {}
397401
}
398402
}

‎desktop/src-tauri/src/managed_agents/backend.rs‎

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -533,7 +533,7 @@ pub fn provider_deploy(
533533
.ok_or_else(|| "deploy response missing agent_id".to_string())
534534
}
535535

536-
/// Validate provider_config: flat object, scalar values, no secret-like keys.
536+
/// Bound public provider configuration and reject secret-like keys at every depth.
537537
pub fn validate_provider_config(config: &serde_json::Value) -> Result<(), String> {
538538
let obj = config
539539
.as_object()
@@ -545,23 +545,45 @@ pub fn validate_provider_config(config: &serde_json::Value) -> Result<(), String
545545
if json_str.len() > 65536 {
546546
return Err("provider_config: max 64KB".to_string());
547547
}
548+
validate_config_value(config, 0)
549+
}
550+
551+
fn validate_config_value(value: &serde_json::Value, depth: usize) -> Result<(), String> {
552+
if depth > 4 {
553+
return Err("provider_config: max nesting depth is 4".into());
554+
}
555+
if let Some(values) = value.as_array() {
556+
if values.len() > 64 {
557+
return Err("provider_config: max 64 array entries".into());
558+
}
559+
for entry in values {
560+
validate_config_value(entry, depth + 1)?;
561+
}
562+
return Ok(());
563+
}
564+
let Some(obj) = value.as_object() else {
565+
return Ok(());
566+
};
567+
if obj.len() > 20 {
568+
return Err("provider_config: max 20 fields per object".into());
569+
}
548570
// Split on separators AND camelCase boundaries, then check each word.
549571
// Catches: api_key, apiKey, access-token, clientSecret, etc.
550572
// Allows: keyboard, monkey_wrench (no forbidden word as a segment).
551573
let forbidden = ["secret", "password", "token", "key", "credential"];
552574
for (k, v) in obj {
553575
let words = split_config_key(k);
554576
for f in &forbidden {
577+
// Nested public maps use literal `key` fields (for example Kubernetes
578+
// tolerations). Compound credential names such as apiKey still fail.
579+
if depth > 0 && k == "key" && *f == "key" {
580+
continue;
581+
}
555582
if words.iter().any(|w| w == f) {
556583
return Err(format!("provider_config: key '{}' looks like a secret", k));
557584
}
558585
}
559-
if v.is_object() || v.is_array() {
560-
return Err(format!(
561-
"provider_config: value for '{}' must be a scalar",
562-
k
563-
));
564-
}
586+
validate_config_value(v, depth + 1)?;
565587
}
566588
Ok(())
567589
}

‎desktop/src-tauri/src/managed_agents/backend_tests.rs‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -352,9 +352,17 @@ fn validate_provider_config_rejects_secret_key() {
352352
}
353353

354354
#[test]
355-
fn validate_provider_config_rejects_nested() {
356-
let cfg = serde_json::json!({"region": {"us": "east"}});
357-
assert!(validate_provider_config(&cfg).is_err());
355+
fn validate_provider_config_bounds_nested_public_options() {
356+
let cfg = serde_json::json!({"pod_options": {
357+
"node_selector": {"workload": "agents"},
358+
"tolerations": [{"key":"workload", "value":"agents", "effect":"NoSchedule"}]
359+
}});
360+
assert!(validate_provider_config(&cfg).is_ok());
361+
let secret = serde_json::json!({"pod_options":{"nested":[{"accessToken":"secret"}]}});
362+
assert!(validate_provider_config(&secret).is_err());
363+
assert!(validate_provider_config(&serde_json::json!({"options":{"apiKey":"secret"}})).is_err());
364+
let too_deep = serde_json::json!({"a":{"b":{"c":{"d":{"e":1}}}}});
365+
assert!(validate_provider_config(&too_deep).is_err());
358366
}
359367

360368
#[test]

‎desktop/src-tauri/src/managed_agents/types.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,14 @@ pub enum BackendKind {
1212
},
1313
}
1414

15+
impl BackendKind {
16+
/// Whether launches require a published channel thread instead of app lifecycle events.
17+
pub(crate) fn is_thread_sandbox(&self) -> bool {
18+
matches!(self, Self::Provider { id, config }
19+
if id == "kubernetes" && config.get("sandbox") == Some(&serde_json::Value::Bool(true)))
20+
}
21+
}
22+
1523
#[derive(Debug, Clone, Serialize, Deserialize)]
1624
pub struct AgentDefinition {
1725
pub id: String,

‎desktop/src/features/agents/AGENTS.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,18 @@ with a TypeScript lookup table or an id comparison in a component.
350350

351351
## Channel-only runtime controls
352352

353+
Kubernetes provider configuration with `sandbox: true` launches one remote
354+
workspace per published channel thread. The mention send passes the published
355+
event's canonical scope after relay acceptance; a saved `deployed` status never
356+
suppresses that check. Native deploy binds the captured thread and verified
357+
owner after the deployment lock. Missing thread scope refuses startup.
358+
Creation and channel attachment save configuration and membership until a mention
359+
supplies that scope. Workspace apply and inbound policy updates do not redeploy
360+
thread Sandboxes; their immutable owner/thread gate remains in the harness.
361+
Provider object/array fields accept JSON, with bounded nesting and recursive
362+
secret-key rejection at the native persistence boundary. These are provider
363+
settings, not another harness capability catalog.
364+
353365
Desktop observer controls identify a channel, not a thread session. The harness
354366
rejects `cancel_turn` and `switch_model` with `ambiguous_target` when that channel
355367
has multiple known session scopes, including retained idle scopes. Do not treat

‎desktop/src/features/agents/channelAgents.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { usesThreadSandbox } from "./lib/threadSandbox";
12
import {
23
commandsMatch,
34
findReusableGenericAgent,
@@ -203,9 +204,13 @@ export async function attachManagedAgentToChannel(
203204
// pair — so this ensures the pair the caller is attaching to, never
204205
// another community's.
205206
const isRemote = input.agent.backend.type === "provider";
206-
const needsStart = isRemote
207-
? input.agent.status !== "deployed"
208-
: input.agent.status !== "running" && input.agent.status !== "deployed";
207+
// A thread Sandbox needs the accepted mention's scope. Without a
208+
// detached queue, attachment only grants membership; the mention starts it.
209+
const needsStart = usesThreadSandbox(input.agent)
210+
? Boolean(input.detachedStart)
211+
: isRemote
212+
? input.agent.status !== "deployed"
213+
: input.agent.status !== "running" && input.agent.status !== "deployed";
209214
if (needsStart) {
210215
if (input.detachedStart) {
211216
input.detachedStart(input.agent);

‎desktop/src/features/agents/hooks.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -606,6 +606,7 @@ export function useStartManagedAgentMutation() {
606606
expectedRelayUrl?: string;
607607
expectedSignerPubkey?: string;
608608
replayFloorUnix?: number;
609+
sessionScope?: import("@/shared/api/remoteAgentSession").RemoteAgentSession;
609610
},
610611
) =>
611612
typeof input === "string"
@@ -614,6 +615,7 @@ export function useStartManagedAgentMutation() {
614615
expectedRelayUrl: input.expectedRelayUrl,
615616
expectedSignerPubkey: input.expectedSignerPubkey,
616617
replayFloorUnix: input.replayFloorUnix,
618+
sessionScope: input.sessionScope,
617619
}),
618620
onSuccess: (updated) => {
619621
queryClient.setQueryData<ManagedAgent[]>(

0 commit comments

Comments
 (0)