Skip to content

Commit 150514f

Browse files
wpfleger96npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
andauthored
feat(desktop): add team snapshot sharing commands (#1790)
Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@sprout-oss.stage.blox.sqprod.co>
1 parent aceb5e0 commit 150514f

8 files changed

Lines changed: 735 additions & 42 deletions

File tree

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

Lines changed: 120 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,13 @@ use tauri::State;
55
use crate::app_state::AppState;
66
use crate::commands::export_util::save_bytes_with_dialog;
77
use crate::commands::media::{detect_and_validate_mime, sanitize_filename};
8-
use crate::commands::personas::{
9-
decode_snapshot_from_bytes, MAX_SNAPSHOT_JSON_BYTES, MAX_SNAPSHOT_PNG_BYTES, PNG_MAGIC,
8+
use crate::commands::{
9+
personas::{
10+
decode_snapshot_from_bytes, MAX_SNAPSHOT_JSON_BYTES, MAX_SNAPSHOT_PNG_BYTES, PNG_MAGIC,
11+
},
12+
team_snapshot::{
13+
decode_team_snapshot_from_bytes, MAX_TEAM_SNAPSHOT_JSON_BYTES, MAX_TEAM_SNAPSHOT_PNG_BYTES,
14+
},
1015
};
1116
use crate::relay::{classify_request_error, relay_api_base_url_with_override, relay_error_message};
1217

@@ -275,16 +280,35 @@ async fn fetch_blob_bytes_with_cap(
275280
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
276281
pub(crate) enum SnapshotFileKind {
277282
/// `.agent.json` — plaintext JSON; accepts memory; 5 MiB cap.
278-
Json,
283+
AgentJson,
279284
/// `.agent.png` — PNG with embedded metadata; no memory; 10 MiB cap.
280-
Png,
285+
AgentPng,
286+
/// `.team.json` — team template; 25 MiB cap.
287+
TeamJson,
288+
/// `.team.png` — team template PNG; 50 MiB cap.
289+
TeamPng,
281290
}
282291

283292
impl SnapshotFileKind {
284293
fn cap(self) -> u64 {
285294
match self {
286-
SnapshotFileKind::Json => MAX_SNAPSHOT_JSON_BYTES as u64,
287-
SnapshotFileKind::Png => MAX_SNAPSHOT_PNG_BYTES as u64,
295+
SnapshotFileKind::AgentJson => MAX_SNAPSHOT_JSON_BYTES as u64,
296+
SnapshotFileKind::AgentPng => MAX_SNAPSHOT_PNG_BYTES as u64,
297+
SnapshotFileKind::TeamJson => MAX_TEAM_SNAPSHOT_JSON_BYTES as u64,
298+
SnapshotFileKind::TeamPng => MAX_TEAM_SNAPSHOT_PNG_BYTES as u64,
299+
}
300+
}
301+
302+
fn is_png(self) -> bool {
303+
matches!(self, SnapshotFileKind::AgentPng | SnapshotFileKind::TeamPng)
304+
}
305+
306+
fn label(self) -> &'static str {
307+
match self {
308+
SnapshotFileKind::AgentJson => ".agent.json",
309+
SnapshotFileKind::AgentPng => ".agent.png",
310+
SnapshotFileKind::TeamJson => ".team.json",
311+
SnapshotFileKind::TeamPng => ".team.png",
288312
}
289313
}
290314
}
@@ -296,14 +320,18 @@ impl SnapshotFileKind {
296320
/// fails closed before any bytes reach the frontend.
297321
fn ensure_bytes_match_kind(bytes: &[u8], kind: SnapshotFileKind) -> Result<(), String> {
298322
let has_png_magic = bytes.len() >= 4 && bytes[..4] == PNG_MAGIC;
299-
match kind {
300-
SnapshotFileKind::Png if !has_png_magic => {
301-
Err("format mismatch: filename is .agent.png but bytes are not a PNG".to_string())
302-
}
303-
SnapshotFileKind::Json if has_png_magic => {
304-
Err("format mismatch: filename is .agent.json but bytes are a PNG".to_string())
305-
}
306-
_ => Ok(()),
323+
if kind.is_png() && !has_png_magic {
324+
Err(format!(
325+
"format mismatch: filename is {} but bytes are not a PNG",
326+
kind.label()
327+
))
328+
} else if !kind.is_png() && has_png_magic {
329+
Err(format!(
330+
"format mismatch: filename is {} but bytes are a PNG",
331+
kind.label()
332+
))
333+
} else {
334+
Ok(())
307335
}
308336
}
309337

@@ -312,35 +340,60 @@ fn ensure_bytes_match_kind(bytes: &[u8], kind: SnapshotFileKind) -> Result<(), S
312340
fn snapshot_kind_for_filename(filename: &str) -> Result<SnapshotFileKind, String> {
313341
let lower = filename.to_ascii_lowercase();
314342
if lower.ends_with(".agent.json") {
315-
Ok(SnapshotFileKind::Json)
343+
Ok(SnapshotFileKind::AgentJson)
316344
} else if lower.ends_with(".agent.png") {
317-
Ok(SnapshotFileKind::Png)
345+
Ok(SnapshotFileKind::AgentPng)
346+
} else if lower.ends_with(".team.json") {
347+
Ok(SnapshotFileKind::TeamJson)
348+
} else if lower.ends_with(".team.png") {
349+
Ok(SnapshotFileKind::TeamPng)
318350
} else {
319351
Err(format!(
320-
"\"{}\" is not a snapshot filename — expected .agent.json or .agent.png",
352+
"\"{}\" is not a snapshot filename — expected .agent.json, .agent.png, .team.json, or .team.png",
321353
filename
322354
))
323355
}
324356
}
325357

326-
/// Fetch and validate an agent snapshot attachment in memory.
358+
/// Reject a metadata-declared size before opening the media stream.
359+
///
360+
/// Keeping this as a pure helper makes the per-kind cap a testable production
361+
/// boundary, rather than relying on a duplicated test-side comparison.
362+
fn ensure_declared_size_within_cap(
363+
expected_size: usize,
364+
kind: SnapshotFileKind,
365+
) -> Result<(), String> {
366+
if expected_size as u64 > kind.cap() {
367+
return Err(format!(
368+
"declared size {} exceeds the {} MiB cap for this format",
369+
expected_size,
370+
kind.cap() / (1024 * 1024)
371+
));
372+
}
373+
Ok(())
374+
}
375+
376+
/// Fetch and validate an agent or team snapshot attachment in memory.
327377
///
328378
/// Input validation (before HTTP):
329379
/// - URL must be a valid same-relay `/media/` URL.
330-
/// - Filename must end with `.agent.json` or `.agent.png`.
380+
/// - Filename must end case-insensitively with `.agent.json`, `.agent.png`,
381+
/// `.team.json`, or `.team.png`.
331382
/// - `expected_sha256` and `expected_size` must be non-empty strings.
332383
///
333-
/// During fetch:
334-
/// - Enforces a format-specific cap (5 MiB JSON, 10 MiB PNG) via
335-
/// Content-Length header and streamed byte count.
384+
/// During fetch, `SnapshotFileKind::cap()` enforces the kind-specific cap via
385+
/// Content-Length and streamed byte count: 5 MiB JSON / 10 MiB PNG for agents,
386+
/// or 25 MiB JSON / 50 MiB PNG for teams.
336387
///
337388
/// Post-fetch validation (all must pass; returns an error on first failure):
338389
/// 1. Byte length equals `expected_size`.
339390
/// 2. SHA-256 hex of bytes equals `expected_sha256` (lowercase).
340-
/// 3. `decode_snapshot_from_bytes` succeeds — bytes are a well-formed snapshot.
391+
/// 3. The byte magic matches the filename-selected kind.
392+
/// 4. Agent kinds pass `decode_snapshot_from_bytes`; team kinds pass
393+
/// `decode_team_snapshot_from_bytes`.
341394
///
342395
/// Returns `tauri::ipc::Response` so bytes cross IPC as a raw buffer rather
343-
/// than a JSON number array (which would be ~3× the size at the 5–10 MiB cap).
396+
/// than a JSON number array (which would be ~3× the size at the applicable cap).
344397
#[tauri::command]
345398
pub async fn fetch_snapshot_bytes(
346399
url: String,
@@ -369,13 +422,7 @@ pub async fn fetch_snapshot_bytes(
369422
if expected_size == 0 {
370423
return Err("missing or zero expected size (imeta size field)".to_string());
371424
}
372-
if expected_size as u64 > cap {
373-
return Err(format!(
374-
"declared size {} exceeds the {} MiB cap for this format",
375-
expected_size,
376-
cap / (1024 * 1024)
377-
));
378-
}
425+
ensure_declared_size_within_cap(expected_size, kind)?;
379426

380427
// ── Bounded fetch ─────────────────────────────────────────────────────
381428
let bytes = fetch_blob_bytes_with_cap(&url, &state, cap).await?;
@@ -401,10 +448,19 @@ pub async fn fetch_snapshot_bytes(
401448
// JSON) and .agent.json delivering PNG bytes.
402449
ensure_bytes_match_kind(&bytes, kind)?;
403450

404-
// 4. Bytes must parse as a valid agent snapshot. This rejects malformed
405-
// payloads, memory-bearing PNGs, JSON with inconsistent memory fields,
406-
// and any format/extension mismatch not caught by magic-byte check.
407-
decode_snapshot_from_bytes(&bytes).map_err(|e| format!("invalid snapshot: {e}"))?;
451+
// 4. Bytes must parse as the snapshot type selected by the filename.
452+
// Team parsing rejects retired flat JSON and persona-pack ZIP inputs
453+
// before anything reaches the frontend.
454+
match kind {
455+
SnapshotFileKind::AgentJson | SnapshotFileKind::AgentPng => {
456+
decode_snapshot_from_bytes(&bytes)
457+
.map_err(|e| format!("invalid agent snapshot: {e}"))?;
458+
}
459+
SnapshotFileKind::TeamJson | SnapshotFileKind::TeamPng => {
460+
decode_team_snapshot_from_bytes(&bytes)
461+
.map_err(|e| format!("invalid team snapshot: {e}"))?;
462+
}
463+
}
408464

409465
Ok(tauri::ipc::Response::new(bytes))
410466
}
@@ -416,14 +472,14 @@ mod tests {
416472
#[test]
417473
fn snapshot_kind_json_returns_json_kind_and_correct_cap() {
418474
let kind = snapshot_kind_for_filename("analyst.agent.json").unwrap();
419-
assert_eq!(kind, SnapshotFileKind::Json);
475+
assert_eq!(kind, SnapshotFileKind::AgentJson);
420476
assert_eq!(kind.cap(), MAX_SNAPSHOT_JSON_BYTES as u64);
421477
}
422478

423479
#[test]
424480
fn snapshot_kind_png_returns_png_kind_and_correct_cap() {
425481
let kind = snapshot_kind_for_filename("analyst.agent.png").unwrap();
426-
assert_eq!(kind, SnapshotFileKind::Png);
482+
assert_eq!(kind, SnapshotFileKind::AgentPng);
427483
assert_eq!(kind.cap(), MAX_SNAPSHOT_PNG_BYTES as u64);
428484
}
429485

@@ -449,6 +505,33 @@ mod tests {
449505
assert!(snapshot_kind_for_filename("agentjson").is_err());
450506
}
451507

508+
#[test]
509+
fn snapshot_kind_team_extensions_are_case_insensitive_and_scale_caps() {
510+
let json = snapshot_kind_for_filename("review.TEAM.JSON").unwrap();
511+
let png = snapshot_kind_for_filename("review.TEAM.PNG").unwrap();
512+
assert_eq!(json, SnapshotFileKind::TeamJson);
513+
assert_eq!(png, SnapshotFileKind::TeamPng);
514+
assert_eq!(json.cap(), 25 * 1024 * 1024);
515+
assert_eq!(png.cap(), 50 * 1024 * 1024);
516+
}
517+
518+
#[test]
519+
fn fetch_boundary_team_png_filename_with_json_bytes_rejected() {
520+
let bytes = br#"{"format":"buzz-team-snapshot","version":1}"#;
521+
let kind = snapshot_kind_for_filename("review.team.png").unwrap();
522+
let error = ensure_bytes_match_kind(bytes, kind).unwrap_err();
523+
assert!(error.contains(".team.png") && error.contains("not a PNG"));
524+
}
525+
526+
#[test]
527+
fn fetch_boundary_team_declared_size_over_cap_rejected() {
528+
let kind = snapshot_kind_for_filename("review.team.json").unwrap();
529+
assert!(ensure_declared_size_within_cap(MAX_TEAM_SNAPSHOT_JSON_BYTES, kind).is_ok());
530+
let error =
531+
ensure_declared_size_within_cap(MAX_TEAM_SNAPSHOT_JSON_BYTES + 1, kind).unwrap_err();
532+
assert!(error.contains("25 MiB"));
533+
}
534+
452535
// ── Focused boundary tests: format mismatch and consistency ──────────────
453536
//
454537
// These tests exercise the guard logic that fetch_snapshot_bytes applies

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ mod project_terminal;
3838
mod relay_members;
3939
mod relay_reconnect;
4040
mod social;
41+
mod team_snapshot;
4142
mod teams;
4243
mod updater;
4344
mod window_vibrancy;
@@ -80,6 +81,7 @@ pub use project_terminal::*;
8081
pub use relay_members::*;
8182
pub use relay_reconnect::*;
8283
pub use social::*;
84+
pub use team_snapshot::*;
8385
pub use teams::*;
8486
pub use updater::*;
8587
pub use window_vibrancy::*;

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ fn trim_optional(value: Option<String>) -> Option<String> {
3131
}
3232

3333
mod pending;
34-
use pending::retain_persona_pending;
34+
pub(in crate::commands) use pending::retain_persona_pending;
3535
pub(super) use pending::tombstone_persona_pending;
3636

3737
#[tauri::command]
@@ -973,11 +973,11 @@ pub async fn set_persona_active(
973973
}
974974

975975
pub(crate) const PNG_MAGIC: [u8; 4] = [0x89, 0x50, 0x4E, 0x47];
976-
977976
mod snapshot;
978977
pub use snapshot::encode_agent_snapshot_for_send;
979978
pub use snapshot::export_agent_snapshot;
980979
pub(crate) use snapshot::import::{
981-
decode_snapshot_from_bytes, MAX_SNAPSHOT_JSON_BYTES, MAX_SNAPSHOT_PNG_BYTES,
980+
decode_snapshot_from_bytes, resolve_snapshot_import_behavior, MAX_SNAPSHOT_JSON_BYTES,
981+
MAX_SNAPSHOT_PNG_BYTES,
982982
};
983983
pub use snapshot::{confirm_agent_snapshot_import, preview_agent_snapshot_import};

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ use crate::managed_agents::AgentDefinition;
2323
/// does not retain, so the local-only `is_active` toggle never republishes, and
2424
/// a byte-identical user-save republish is harmlessly NIP-33-replaced). The
2525
/// guard is intentionally omitted.
26-
pub(in crate::commands::personas) fn retain_persona_pending(
26+
pub(in crate::commands) fn retain_persona_pending(
2727
app: &AppHandle,
2828
state: &AppState,
2929
persona: &AgentDefinition,

0 commit comments

Comments
 (0)