-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlib.rs
More file actions
454 lines (414 loc) · 15.1 KB
/
lib.rs
File metadata and controls
454 lines (414 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
mod app_state;
mod commands;
mod events;
mod managed_agents;
mod migration;
mod models;
mod relay;
mod util;
use app_state::{build_app_state, resolve_persisted_identity, AppState};
use commands::*;
use managed_agents::{
find_managed_agent_mut, kill_stale_tracked_processes, load_managed_agents, save_managed_agents,
start_managed_agent_process, sync_managed_agent_processes, BackendKind, ManagedAgentProcess,
};
use tauri::{http, Manager, RunEvent};
use tauri_plugin_window_state::StateFlags;
fn restore_managed_agents_on_launch(app: &tauri::AppHandle) -> Result<(), String> {
let state = app.state::<AppState>();
let _store_guard = state
.managed_agents_store_lock
.lock()
.map_err(|error| error.to_string())?;
let mut records = load_managed_agents(app)?;
let mut runtimes = state
.managed_agent_processes
.lock()
.map_err(|error| error.to_string())?;
let mut changed = sync_managed_agent_processes(&mut records, &mut runtimes);
changed |= kill_stale_tracked_processes(&mut records, &runtimes);
// PID-file sweep: kill any orphaned agent processes we have receipts for
// that weren’t tracked in records (e.g. escaped process groups, double-forked).
let tracked_pids: Vec<u32> = records
.iter()
.filter_map(|r| r.runtime_pid)
.chain(runtimes.values().map(|rt| rt.child.id()))
.collect();
managed_agents::sweep_orphaned_agent_processes(app, &tracked_pids);
let pubkeys_to_restore = records
.iter()
.filter(|record| record.start_on_app_launch && record.backend == BackendKind::Local)
.map(|record| record.pubkey.clone())
.collect::<Vec<_>>();
for pubkey in pubkeys_to_restore {
let record = find_managed_agent_mut(&mut records, &pubkey)?;
match start_managed_agent_process(app, record, &mut runtimes) {
Ok(()) => {
changed = true;
}
Err(error) => {
record.updated_at = util::now_iso();
record.last_error = Some(error);
changed = true;
}
}
}
if changed {
save_managed_agents(app, &records)?;
}
Ok(())
}
fn shutdown_managed_agents(app: &tauri::AppHandle) -> Result<(), String> {
let state = app.state::<AppState>();
let _store_guard = state
.managed_agents_store_lock
.lock()
.map_err(|error| error.to_string())?;
let mut records = load_managed_agents(app)?;
let mut runtimes = state
.managed_agent_processes
.lock()
.map_err(|error| error.to_string())?;
let mut changed = sync_managed_agent_processes(&mut records, &mut runtimes);
changed |= kill_stale_tracked_processes(&mut records, &runtimes);
// Stop all tracked agents. Send SIGTERM to all process
// groups first, then wait for exits in parallel to avoid serial 1s waits.
struct AgentToStop {
idx: usize,
pid: u32,
runtime: Option<ManagedAgentProcess>,
}
let mut to_stop: Vec<AgentToStop> = Vec::new();
for (idx, record) in records.iter_mut().enumerate() {
if record.backend != BackendKind::Local {
continue;
}
if record.runtime_pid.is_none() && !runtimes.contains_key(&record.pubkey) {
continue;
}
let runtime = runtimes.remove(&record.pubkey);
let Some(pid) = runtime
.as_ref()
.map(|rt| rt.child.id())
.or(record.runtime_pid)
else {
continue;
};
to_stop.push(AgentToStop { idx, pid, runtime });
}
if !to_stop.is_empty() {
changed = true;
// Fan-out: send SIGTERM to all process groups at once.
#[cfg(unix)]
for agent in &to_stop {
let pgid = -(agent.pid as i32);
unsafe {
libc::kill(pgid, libc::SIGTERM);
}
}
// Wait up to 2s for all to exit, checking in a polling loop.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
loop {
if to_stop
.iter()
.all(|a| !managed_agents::process_is_running(a.pid))
{
break;
}
if std::time::Instant::now() >= deadline {
break;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
// Fan-out: SIGKILL any survivors.
#[cfg(unix)]
for agent in &to_stop {
if managed_agents::process_is_running(agent.pid) {
let pgid = -(agent.pid as i32);
unsafe {
libc::kill(pgid, libc::SIGKILL);
}
}
}
// Reap children and update records.
for mut agent in to_stop {
if let Some(ref mut rt) = agent.runtime {
// Best-effort reap — don’t block shutdown if the child is stuck
// in uninterruptible sleep. The zombie will be cleaned up when
// our process exits and launchd reaps it.
let _ = rt.child.try_wait();
// Write log marker (best-effort).
let record = &records[agent.idx];
let _ = managed_agents::append_log_marker(
&rt.log_path,
&format!(
"=== stopped {} ({}) at {} ===",
record.name,
record.pubkey,
util::now_iso()
),
);
}
let record = &mut records[agent.idx];
record.runtime_pid = None;
record.last_stopped_at = Some(util::now_iso());
record.updated_at = util::now_iso();
record.last_exit_code = None;
record.last_error = None;
}
}
// Final sweep: kill any orphaned agent processes we have PID file receipts
// for that escaped process-group kills or weren't tracked in records.
// All tracked PIDs have already been killed above, so pass an empty skip list.
managed_agents::sweep_orphaned_agent_processes(app, &[]);
if changed {
save_managed_agents(app, &records)?;
}
Ok(())
}
/// Proxy media requests through the Rust backend so they traverse the WARP tunnel.
///
/// WKWebView's networking stack bypasses WARP, causing 403s from Cloudflare Access.
/// This handler routes `sprout-media://localhost/{path}` through reqwest, which
/// runs in the Tauri process and goes through WARP.
async fn handle_sprout_media(
app: &tauri::AppHandle,
request: &http::Request<Vec<u8>>,
) -> http::Response<Vec<u8>> {
let state = app.state::<AppState>();
let base = relay::relay_api_base_url();
// Preserve path + query (thumbnails may have query params).
// Only proxy /media/ paths — reject anything else.
let path_and_query = request
.uri()
.path_and_query()
.map(|pq| pq.as_str())
.unwrap_or("/");
if !path_and_query.starts_with("/media/") {
return error_response(404, "not found");
}
let upstream_url = format!("{base}{path_and_query}");
let result = state
.http_client
.get(&upstream_url)
.timeout(std::time::Duration::from_secs(30))
.send()
.await;
match result {
Ok(resp) => {
let status = resp.status().as_u16();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream")
.to_string();
match resp.bytes().await {
Ok(bytes) => http::Response::builder()
.status(status)
.header("content-type", &content_type)
.body(bytes.to_vec())
.unwrap_or_else(|_| error_response(500, "response build failed")),
Err(_) => error_response(502, "failed to read upstream body"),
}
}
Err(_) => error_response(502, "upstream request failed"),
}
}
fn error_response(status: u16, msg: &str) -> http::Response<Vec<u8>> {
http::Response::builder()
.status(status)
.header("content-type", "text/plain")
.body(msg.as_bytes().to_vec())
.unwrap_or_else(|_| {
http::Response::builder()
.status(500)
.body(Vec::new())
.unwrap()
})
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let builder = tauri::Builder::default()
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_opener::init())
.plugin(
tauri_plugin_window_state::Builder::default()
.with_state_flags(StateFlags::all() & !StateFlags::VISIBLE)
.build(),
)
.plugin(tauri_plugin_websocket::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_process::init());
// The updater config is only generated for signed release builds.
let builder = if cfg!(debug_assertions) {
builder
} else {
builder.plugin(tauri_plugin_updater::Builder::new().build())
};
let app = builder
.register_asynchronous_uri_scheme_protocol("sprout-media", |ctx, request, responder| {
let app = ctx.app_handle().clone();
tauri::async_runtime::spawn(async move {
let response = handle_sprout_media(&app, &request).await;
responder.respond(response);
});
})
.manage(build_app_state())
.setup(|app| {
let app_handle = app.handle().clone();
// Migrate data from the legacy `com.wesb.sprout` directory before
// resolving identity, so the persisted key is available at the new
// path on first launch after the identifier change.
migration::migrate_legacy_data_dir(&app_handle);
// Resolve persisted identity key (env var → file → generate+save).
// This is fatal — the app should not start with an ephemeral identity
// that will be lost on restart, as that silently breaks channel
// memberships, DMs, and relay identity.
let state = app_handle.state::<AppState>();
resolve_persisted_identity(&app_handle, &state)
.map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
// Keep launch-time agent restoration off the synchronous setup path
// so the frontend can mount and reveal the window promptly.
tauri::async_runtime::spawn_blocking(move || {
if let Err(error) = restore_managed_agents_on_launch(&app_handle) {
eprintln!("sprout-desktop: failed to restore managed agents: {error}");
}
});
Ok(())
})
.invoke_handler(tauri::generate_handler![
get_identity,
get_profile,
update_profile,
get_user_profile,
get_users_batch,
search_users,
get_presence,
set_presence,
get_relay_ws_url,
discover_acp_providers,
discover_managed_agent_prereqs,
sign_event,
create_auth_event,
get_channels,
create_channel,
open_dm,
hide_dm,
get_channel_details,
get_channel_members,
update_channel,
set_channel_topic,
set_channel_purpose,
archive_channel,
unarchive_channel,
delete_channel,
add_channel_members,
remove_channel_member,
join_channel,
leave_channel,
get_canvas,
set_canvas,
get_feed,
search_messages,
send_channel_message,
get_forum_posts,
get_forum_thread,
edit_message,
delete_message,
add_reaction,
remove_reaction,
get_event,
upload_media,
pick_and_upload_media,
upload_media_bytes,
list_tokens,
mint_token,
revoke_token,
revoke_all_tokens,
list_relay_agents,
list_managed_agents,
create_managed_agent,
start_managed_agent,
stop_managed_agent,
set_managed_agent_start_on_app_launch,
delete_managed_agent,
mint_managed_agent_token,
get_managed_agent_log,
get_agent_models,
update_managed_agent,
discover_backend_providers,
probe_backend_provider,
list_personas,
create_persona,
update_persona,
delete_persona,
list_teams,
create_team,
update_team,
delete_team,
export_team_to_json,
parse_team_file,
parse_persona_files,
export_persona_to_json,
get_channel_workflows,
get_workflow,
create_workflow,
update_workflow,
delete_workflow,
get_workflow_runs,
get_run_approvals,
trigger_workflow,
grant_approval,
deny_approval,
])
.build(tauri::generate_context!())
.expect("error while building tauri application");
let shutdown_done = std::sync::atomic::AtomicBool::new(false);
app.run(move |app_handle, event| match event {
RunEvent::ExitRequested { .. } | RunEvent::Exit => {
if !shutdown_done.swap(true, std::sync::atomic::Ordering::SeqCst) {
if let Err(error) = shutdown_managed_agents(app_handle) {
eprintln!("sprout-desktop: failed to stop managed agents: {error}");
}
}
}
_ => {}
});
}
#[cfg(test)]
mod tests {
use serde_json::json;
use crate::{models::ChannelInfo, util::percent_encode};
#[test]
fn channel_info_defaults_is_member_for_legacy_payloads() {
let channel: ChannelInfo = serde_json::from_value(json!({
"id": "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50",
"name": "general",
"channel_type": "stream",
"visibility": "open",
"description": "General discussion",
"topic": null,
"purpose": null,
"member_count": 3,
"last_message_at": null,
"archived_at": null,
"participants": [],
"participant_pubkeys": []
}))
.expect("legacy payload should deserialize");
assert!(channel.is_member);
}
#[test]
fn percent_encode_leaves_unreserved_chars() {
assert_eq!(
percent_encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"),
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"
);
}
#[test]
fn percent_encode_escapes_unicode_and_reserved_chars() {
assert_eq!(percent_encode("👍"), "%F0%9F%91%8D");
assert_eq!(percent_encode("a/b?c"), "a%2Fb%3Fc");
}
}