Skip to main content

agentmux_srv/server/
jekt_files.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Files sent with a jekt (`docs/specs/SPEC_JEKT_FILE_TRANSFER_2026_10_05.md`):
5//! whether a request's files belong to it (§3.3), what the agent gets for
6//! them (§6), and how they travel to another instance (§4).
7//!
8//! On the sender's instance the files are already in its attachment store:
9//! the sender's MCP uploaded them before sending (§3.1). Another instance on
10//! the same machine or the LAN gets them in the same request as the jekt,
11//! after it, at `POST /agentmux/reactive/inject-files`; it checks the jekt
12//! before reading a single file byte.
13
14use agentmux_common::jekt_files;
15
16use crate::backend::attachments::{self, prompt};
17use crate::backend::reactive::sanitize::quote_in_jekt;
18use crate::backend::reactive::types::{FilesDelivery, InjectionRequest, WanInstanceStatus};
19use super::agent_handlers::turn_steps::rehome_for_container;
20use std::sync::Arc;
21
22/// Why a request's files can't be accepted at all, before anything is
23/// delivered: they're malformed, the msgid doesn't bind them, or they
24/// would have to come from another instance. The text is for the sender.
25pub(crate) fn check(req: &InjectionRequest) -> Result<(), String> {
26    if req.files.is_none() {
27        return Ok(());
28    }
29    check_manifest(req)?;
30    // `/inject` names files by hash, so only this instance's own senders may
31    // use it. Another instance's files come with them (`inject-files`).
32    if req.delivery_tier.as_deref() != Some("host") {
33        return Err("files refused: files from another AgentMux come with the request, not by name".to_string());
34    }
35    Ok(())
36}
37
38/// A request's manifest is well formed, within the limits of the tier it
39/// arrived on, and its msgid binds it. Nothing has been read or written yet.
40fn check_manifest(req: &InjectionRequest) -> Result<(), String> {
41    let files = req.files.as_deref().unwrap_or_default();
42    jekt_files::validate(files).map_err(|e| format!("files refused: {e}"))?;
43    // A tier with no limits takes no files at all: the caller says so in its own words.
44    let tier = req.delivery_tier.as_deref().unwrap_or("host");
45    if jekt_files::tier_limits(tier).is_some() {
46        jekt_files::check_tier_limits(files, tier).map_err(|e| format!("files refused: {e}"))?;
47    }
48    let msgid = req.request_id.as_deref().unwrap_or("");
49    if !jekt_files::msgid_binds(msgid, files) {
50        return Err("files refused: they don't match the message id they were sent under".to_string());
51    }
52    Ok(())
53}
54
55/// Why trust rules out delivering a jekt's files (§6.4), or `None`.
56pub(crate) fn withheld_reason(req: &InjectionRequest) -> Option<&'static str> {
57    let failed = [req.sig_verified, req.reagent_verified, req.lan_verified, req.channel_verified, req.wan_verified]
58        .contains(&Some(false))
59        || req.wan_instance.as_ref().is_some_and(|i| i.status == WanInstanceStatus::Revoked);
60    if failed {
61        return Some("the sender's signature failed verification");
62    }
63    if req.delivery_tier.as_deref() == Some("lan") && req.lan_verified != Some(true) {
64        return Some("files over the LAN need a verified sender");
65    }
66    None
67}
68
69/// Put what the agent gets for this jekt's files in `req.files_delivery`:
70/// the list, a line saying they were withheld, or (for a msgid that binds
71/// files when none came) a line saying they didn't arrive. Leaves it `None`
72/// for a text-only jekt.
73pub(crate) async fn prepare(req: &mut InjectionRequest) {
74    let destination = destination_of(&req.target_agent);
75    prepare_for(req, attachments::get(), destination).await;
76}
77
78/// [`prepare`] with the attachment store and the target's file destination given.
79async fn prepare_for(req: &mut InjectionRequest, svc: Option<Arc<attachments::Service>>, destination: Destination) {
80    let msgid = req.request_id.as_deref().unwrap_or("");
81    let Some(files) = req.files.clone() else {
82        if jekt_files::bound_digest(msgid).is_some() {
83            req.files_delivery = Some(FilesDelivery {
84                delivered: 0,
85                text: "This message was sent with files that didn't arrive.".to_string(),
86                inline: Vec::new(),
87                inline_charge: None,
88            });
89        }
90        return;
91    };
92    let count = files.len();
93    let (noun, verb) = if count == 1 { ("file", "was") } else { ("files", "were") };
94    if let Some(reason) = withheld_reason(req) {
95        req.files_delivery = Some(FilesDelivery {
96            delivered: 0,
97            text: format!("{count} {noun} sent with this message {verb} withheld: {reason}."),
98            inline: Vec::new(),
99            inline_charge: None,
100        });
101        return;
102    }
103    let Some(svc) = svc else {
104        req.files_delivery = Some(nothing_delivered(format!("{count} {noun} sent with this message couldn't be delivered: the attachment store isn't available.")));
105        return;
106    };
107    if let Destination::Refused(why) = destination {
108        req.files_delivery = Some(nothing_delivered(format!("{count} {noun} sent with this message couldn't be delivered: {why}")));
109        return;
110    }
111    // For a proven sender: re-derive anything stored under an older
112    // fingerprint. Either way, check each file's size against the manifest:
113    // the hash names the file, the size is part of what was signed. A file
114    // from a sender that is not proven is only measured, never read.
115    let derive = derives_on_receipt(req);
116    let present = files_present(&svc, &files, derive).await;
117    // Every name the sender controls is quoted before it is used, the stored
118    // copy's name included, so neither a name nor the path it gives the copy
119    // can close the jekt block or open a list.
120    let tier = req.delivery_tier.as_deref().unwrap_or("host");
121    let sender = match req.source_agent.as_deref() {
122        // A name AgentMux reserves, from afar and unsigned, reads the way the marker shows it: with a leading `?`.
123        Some(n) if crate::backend::reactive::sanitize::validate_agent_id(n) && !crate::backend::reactive::sender::is_shown_as_agent(n, tier, req.reagent_verified) => {
124            quote_in_jekt(&format!("?{n}"))
125        }
126        other => quote_in_jekt(other.unwrap_or("Another agent")),
127    };
128    // Claude sees them inline only from a sender whose signature verified
129    // (spec §6.4), and only when it is running to take them.
130    let inline_to = sender_verified(req).then(|| inline_target(&req.target_agent)).flatten();
131    let delivery = tokio::task::spawn_blocking(move || {
132        let mut found = Vec::new();
133        let mut missing = Vec::new();
134        for (i, (f, ok)) in files.iter().zip(present).enumerate() {
135            let name = quote_in_jekt(&f.name);
136            let target = ok.then(|| if derive { svc.send_target(&f.sha256, &name) } else { svc.unread_target(&f.sha256, &name) });
137            match target.flatten() {
138                Some(t) => found.push(prompt::Resolved {
139                    number: i + 1,
140                    name,
141                    path: t.path,
142                    mime: t.mime,
143                    page_count: t.page_count,
144                    note: t.note,
145                }),
146                None => missing.push(name),
147            }
148        }
149        // A container agent can't open a path in the host's store: its copies go into its workspace.
150        let (found, missing) = match &destination {
151            Destination::Container(cwd) => rehome_for_container(found, missing, cwd),
152            _ => (found, missing),
153        };
154        let (prepared, inline_charge) = match inline_to {
155            Some(t) => {
156                let prepared = svc.with_session_inline_budget(&t.session_key, Some(&t.new_session_key), t.session_bytes, |budget| {
157                    let prepared = prompt::prepare_from(Some(&sender), &found, &missing, t.max_count, budget);
158                    let spent = prompt::inline_bytes(&prepared.inline);
159                    (prepared, spent)
160                });
161                let spent = prompt::inline_bytes(&prepared.inline);
162                (prepared, (spent > 0).then_some((t.session_key, spent)))
163            }
164            None => (prompt::prepare_from(Some(&sender), &found, &missing, 0, 0), None),
165        };
166        FilesDelivery { delivered: found.len(), text: prepared.list, inline: prepared.inline, inline_charge }
167    })
168    .await
169    .unwrap_or_else(|_| FilesDelivery {
170        delivered: 0,
171        text: format!("{count} {noun} sent with this message couldn't be delivered."),
172        inline: Vec::new(),
173        inline_charge: None,
174    });
175    req.files_delivery = Some(delivery);
176}
177
178/// Whether each of `files` is in the store at the size the manifest says. With
179/// `derive`, anything stored under an older fingerprint is derived again; without
180/// it the file is only measured, never read.
181async fn files_present(svc: &Arc<attachments::Service>, files: &[jekt_files::JektFile], derive: bool) -> Vec<bool> {
182    let mut present = Vec::with_capacity(files.len());
183    for f in files {
184        present.push(if derive {
185            svc.open_derived(&f.sha256).await.is_some_and(|meta| meta.bytes == f.size)
186        } else {
187            svc.stored_len(&f.sha256) == Some(f.size)
188        });
189    }
190    present
191}
192
193/// What the agent gets when none of a jekt's files can be delivered: the reason, no list.
194fn nothing_delivered(text: String) -> FilesDelivery {
195    FilesDelivery { text, ..Default::default() }
196}
197
198/// Where the files of a jekt must be put for its target to open them.
199enum Destination {
200    /// A host agent, or a target not resolved here: the store's own paths.
201    Host,
202    /// A container agent: the host folder behind its `/workspace`.
203    Container(String),
204    /// A container agent that has nowhere to put them; the reason is for the agent's list.
205    Refused(&'static str),
206}
207
208/// The block of the agent `target` names, as a delivery finds it.
209fn target_block(target: &str) -> Option<String> {
210    use crate::backend::reactive::handler::LookupOutcome;
211    let handler = crate::backend::reactive::get_global_handler();
212    handler.block_for_uid(target).or_else(|| match handler.lookup_delivery_target(target) {
213        LookupOutcome::One(reg) => Some(reg.block_id),
214        _ => None,
215    })
216}
217
218/// What preparing a jekt's files could learn of the agent it is for.
219enum Found {
220    /// The pane the target is bound to here, as the store has it.
221    Pane(crate::backend::obj::Block),
222    /// Bound to a pane here, but the store couldn't give the pane back.
223    PaneUnreadable,
224    /// Bound to no pane here (not running, starting, or on another instance); `container` is whether it is defined
225    /// here as a container agent.
226    Unbound { container: bool },
227}
228
229const PANE_UNREADABLE: &str = "this agent's pane couldn't be read just now, so its mounted folder can't be written: send the files again.";
230const CONTAINER_NOT_RUNNING: &str = "this container agent has no running pane yet, so its mounted folder can't be written: send the files again once it is running.";
231
232/// Where a target's files must be put. A container agent is never given the host store's paths because something
233/// couldn't be looked up: a target that is a container agent, or might be, is refused with a reason that says so
234/// (the sender's answer then counts the files as not delivered), and only a target known to be a host agent, or one
235/// this instance knows nothing of, is sent the store's own paths.
236fn destination_of(target: &str) -> Destination {
237    let destination = destination_for(found_for(target));
238    tracing::info!(destination = destination_name(&destination), "jekt files: where a target's files go");
239    destination
240}
241
242fn destination_name(destination: &Destination) -> &'static str {
243    match destination {
244        Destination::Host => "host store",
245        Destination::Container(_) => "container workspace",
246        Destination::Refused(_) => "refused",
247    }
248}
249
250fn found_for(target: &str) -> Found {
251    let Some(store) = crate::backend::identity_spawn::row_store() else {
252        return Found::Unbound { container: false };
253    };
254    match target_block(target) {
255        Some(id) => match store.get::<crate::backend::obj::Block>(&id) {
256            Ok(Some(block)) => Found::Pane(block),
257            _ => Found::PaneUnreadable,
258        },
259        None => Found::Unbound { container: defined_as_container(store, target) },
260    }
261}
262
263/// Whether `target` names an agent defined on this instance as a container agent.
264fn defined_as_container(store: &crate::backend::storage::store::Store, target: &str) -> bool {
265    super::reactive::defined_here(store, target)
266        .and_then(|(uid, _slug)| store.agent_def_get(&uid).ok().flatten())
267        .is_some_and(|def| def.runtime().is_container())
268}
269
270fn destination_for(found: Found) -> Destination {
271    match found {
272        Found::Pane(block) => destination_for_block(&block),
273        Found::PaneUnreadable => Destination::Refused(PANE_UNREADABLE),
274        Found::Unbound { container: true } => Destination::Refused(CONTAINER_NOT_RUNNING),
275        Found::Unbound { container: false } => Destination::Host,
276    }
277}
278
279fn destination_for_block(block: &crate::backend::obj::Block) -> Destination {
280    match super::agent_handlers::turn_steps::attachment_destination(block) {
281        Ok(Some(cwd)) => Destination::Container(cwd),
282        Ok(None) => Destination::Host,
283        Err(why) => Destination::Refused(why),
284    }
285}
286
287/// Deliver on this instance, settling the inline budget for the attempt.
288pub(crate) fn inject_here(state: &super::AppState, req: &InjectionRequest) -> crate::backend::reactive::types::InjectionResponse {
289    let resp = state.reactive_handler.inject_message(req.clone());
290    settle(req, resp.success);
291    resp
292}
293
294/// After a delivery attempt: give back the inline budget it was charged when
295/// it wasn't delivered (refused, rate-limited, retried later), so only a
296/// delivered jekt counts against the session the user's own attachments use.
297pub(crate) fn settle(req: &InjectionRequest, delivered: bool) {
298    let Some((key, bytes)) = req.files_delivery.as_ref().and_then(|d| d.inline_charge.clone()) else {
299        return;
300    };
301    if delivered {
302        return;
303    }
304    if let Some(svc) = attachments::get() {
305        svc.refund_session_inline(&key, bytes);
306    }
307}
308
309/// Whether this jekt's sender is proven for this message, by the same rule
310/// that relaxes `ESCALATE` (`Handler::deliver_audited`): one check verified
311/// and none failed.
312fn sender_verified(req: &InjectionRequest) -> bool {
313    let verdicts = [req.sig_verified, req.reagent_verified, req.lan_verified, req.channel_verified, req.wan_verified];
314    let wan_ok = req.wan_verified == Some(true)
315        && req.wan_instance.as_ref().is_some_and(|i| matches!(i.status, WanInstanceStatus::Approved | WanInstanceStatus::New));
316    !verdicts.contains(&Some(false))
317        && (req.sig_verified == Some(true)
318            || req.reagent_verified == Some(true)
319            || req.lan_verified == Some(true)
320            || req.channel_verified == Some(true)
321            || wan_ok)
322}
323
324/// Whether a file received with this jekt may be read for a type, preview or
325/// text when it arrives or is delivered: only when the sender is proven for
326/// this message (the marker's `host-verified`, `channel-verified`,
327/// `lan-verified`, or `wan-verified` with an approved instance). Any other
328/// file is stored as it came and read only when someone opens it.
329pub(crate) fn derives_on_receipt(req: &InjectionRequest) -> bool {
330    use crate::backend::message_origin::OriginTrust;
331    let tier = req.delivery_tier.as_deref().unwrap_or("host");
332    let wan_pinned = tier == "wan"
333        && req.wan_verified == Some(true)
334        && req.wan_instance.as_ref().is_some_and(|i| i.status == WanInstanceStatus::Approved);
335    matches!(
336        crate::backend::reactive::sanitize::jekt_trust(tier, req.sig_verified, req.lan_verified, req.channel_verified, wan_pinned.then_some(true)),
337        OriginTrust::HostVerified | OriginTrust::ChannelVerified | OriginTrust::LanVerified | OriginTrust::WanVerified
338    )
339}
340
341/// Where inline files may go: a persistent Claude agent that is running or
342/// starting, so its stdin takes the image blocks. A target that would have
343/// to be started gets a turn with the text alone, so it gets the list alone.
344struct InlineTarget {
345    max_count: usize,
346    session_bytes: u64,
347    /// The Claude session's inline budget, as the composer keys it
348    /// (`agent_handlers/input.rs`): by session id, or by block until known.
349    session_key: String,
350    new_session_key: String,
351}
352
353fn inline_target(target: &str) -> Option<InlineTarget> {
354    use crate::backend::blockcontroller::persistent::PersistentSubprocessController;
355    let block = target_block(target)?;
356    let ctrl = crate::backend::blockcontroller::get_controller(&block)?;
357    let persistent = ctrl.as_any().downcast_ref::<PersistentSubprocessController>()?;
358    let limits = attachments::get()?.limits();
359    if persistent.needs_spawn() || limits.claude_inline_max == 0 {
360        return None;
361    }
362    let new_session_key = format!("block:{block}:new");
363    let session_key = persistent
364        .session_id()
365        .filter(|s| !s.is_empty())
366        .map_or_else(|| new_session_key.clone(), |s| format!("session:{s}"));
367    Some(InlineTarget {
368        max_count: limits.claude_inline_max,
369        session_bytes: limits.claude_session_inline_bytes,
370        session_key,
371        new_session_key,
372    })
373}
374
375// ---- Moving the files to another instance (spec §4) ----
376
377/// The longest a forward with files may take: the bytes go with it.
378pub(crate) const TRANSFER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);
379/// The inject request in front of the files is small (a 10 KB message and
380/// its signatures); anything longer is refused before it is read.
381const MAX_REQUEST_JSON: u32 = 64 * 1024;
382/// How long the request in front of the files may take to arrive.
383const HEADER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
384/// Transfers a receiver takes at once; another waits for the sender's retry.
385static TRANSFERS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(4);
386/// How long a LAN files jekt's msgid is remembered, so a captured request
387/// can't be delivered twice: longer than any signature's freshness window.
388const SEEN_FOR: std::time::Duration = std::time::Duration::from_secs(15 * 60);
389static SEEN_LAN: std::sync::Mutex<Vec<(String, std::time::Instant)>> = std::sync::Mutex::new(Vec::new());
390
391/// Claim this LAN files jekt's msgid for one delivery, under one lock so two
392/// copies arriving at once can't both pass: `false` when it was delivered
393/// here before or is being delivered now.
394fn reserve(msgid: &str) -> bool {
395    let mut seen = SEEN_LAN.lock().unwrap_or_else(|e| e.into_inner());
396    seen.retain(|(_, at)| at.elapsed() < SEEN_FOR);
397    if seen.iter().any(|(id, _)| id == msgid) {
398        return false;
399    }
400    seen.push((msgid.to_string(), std::time::Instant::now()));
401    true
402}
403
404/// Give a claim back after a delivery that failed, so the sender may retry.
405fn release(msgid: &str) {
406    SEEN_LAN.lock().unwrap_or_else(|e| e.into_inner()).retain(|(id, _)| id != msgid);
407}
408
409/// The body of a forward with files: the request's JSON length (u32,
410/// big-endian), the JSON, then each file's bytes in manifest order, read
411/// from this instance's store.
412pub(crate) async fn transfer_body(req: &InjectionRequest) -> Result<reqwest::Body, String> {
413    let svc = attachments::get().ok_or("files refused: the attachment store isn't available")?;
414    Ok(reqwest::Body::wrap_stream(transfer_stream(&svc, req).await?))
415}
416
417type ByteStream = futures_util::stream::BoxStream<'static, std::io::Result<axum::body::Bytes>>;
418
419async fn transfer_stream(svc: &attachments::Service, req: &InjectionRequest) -> Result<ByteStream, String> {
420    use futures_util::StreamExt;
421    let json = serde_json::to_vec(req).map_err(|e| e.to_string())?;
422    // The receiver reads at most this much before the files; a message too
423    // long for it would be refused there on every retry.
424    if json.len() > MAX_REQUEST_JSON as usize {
425        return Err(format!(
426            "files refused: the message is too long to send with files ({} KB with its signatures; at most {} KB)",
427            json.len() / 1024,
428            MAX_REQUEST_JSON / 1024
429        ));
430    }
431    let mut head = (json.len() as u32).to_be_bytes().to_vec();
432    head.extend_from_slice(&json);
433    let mut parts = vec![futures_util::stream::once(async move { Ok::<_, std::io::Error>(axum::body::Bytes::from(head)) }).boxed()];
434    for f in req.files.as_deref().unwrap_or_default() {
435        let file = match svc.store().find_blob(&f.sha256) {
436            Some((path, _)) => tokio::fs::File::open(path).await.ok(),
437            None => None,
438        };
439        let Some(file) = file else {
440            return Err(format!("files refused: {} is no longer in this AgentMux's store", f.name));
441        };
442        if file.metadata().await.map(|m| m.len()).ok() != Some(f.size) {
443            return Err(format!("files refused: {} changed size in this AgentMux's store", f.name));
444        }
445        parts.push(tokio_util::io::ReaderStream::new(file).boxed());
446    }
447    Ok(futures_util::stream::iter(parts).flatten().boxed())
448}
449
450/// Whether the LAN peer at `url` takes files for `target`: its agent answer
451/// lists the feature (spec §3.4). `None` when the question went unanswered
452/// (unreachable, an error status, a body that isn't JSON), which says
453/// nothing about the peer's build.
454pub(crate) async fn peer_accepts_files(client: &reqwest::Client, url: &str, auth_key: &str, target: &str) -> Option<bool> {
455    let mut get = client.get(format!("{url}/agentmux/reactive/agent")).query(&[("id", target)]);
456    if !auth_key.is_empty() {
457        get = get.header(agentmux_common::AUTH_KEY_HEADER, auth_key);
458    }
459    let resp = get.send().await.ok().filter(|r| r.status().is_success())?;
460    let body = resp.json::<serde_json::Value>().await.ok()?;
461    Some(
462        body.get("jekt_features")
463            .and_then(|f| f.as_array())
464            .is_some_and(|f| f.iter().any(|v| v.as_str() == Some(jekt_files::FEATURE))),
465    )
466}
467
468/// An answer that ends the sender's search: the files were refused for a
469/// reason no other candidate would change.
470pub(crate) fn refused(req: &InjectionRequest, error: impl Into<String>) -> serde_json::Value {
471    serde_json::json!({
472        "success": false,
473        "files_refused": true,
474        "request_id": req.request_id.clone().unwrap_or_default(),
475        "error": error.into(),
476        "timestamp": agentmux_common::time::now_ms_u64(),
477    })
478}
479
480/// `POST /agentmux/reactive/inject-files`: a jekt from another instance on
481/// this machine (full key) or a LAN peer (`lan_key`), with its files after it
482/// (spec §4). The jekt is checked as `/agentmux/reactive/inject` checks one,
483/// before any file byte is read; then each file is streamed into the store,
484/// hashed as it goes, and the jekt is delivered with the ones that arrived
485/// intact. It is never forwarded on.
486pub(super) async fn handle_reactive_inject_files(
487    axum::extract::State(state): axum::extract::State<super::AppState>,
488    axum::extract::Extension(auth_via): axum::extract::Extension<super::ReactiveAuthVia>,
489    caller: Option<axum::extract::Extension<super::caller::Caller>>,
490    body: axum::body::Body,
491) -> axum::response::Response {
492    use axum::response::IntoResponse;
493    use futures_util::StreamExt;
494    // A slot before any byte is read, so no connection waits outside the cap.
495    let Ok(_slot) = TRANSFERS.try_acquire() else {
496        // Not a verdict on this candidate: the sender moves on.
497        let body = serde_json::json!({ "success": false, "error": "busy receiving other files" });
498        return (axum::http::StatusCode::SERVICE_UNAVAILABLE, axum::Json(body)).into_response();
499    };
500    super::lan_watch::stage("reading the request");
501    let stream = body.into_data_stream().map(|r| r.map_err(std::io::Error::other));
502    let mut reader = tokio_util::io::StreamReader::new(stream);
503    let header = tokio::time::timeout(HEADER_TIMEOUT, read_request(&mut reader)).await;
504    let req = match header.unwrap_or_else(|_| Err("request timed out".to_string())) {
505        Ok(req) => req,
506        Err(e) => {
507            let body = serde_json::json!({ "success": false, "error": e });
508            return (axum::http::StatusCode::BAD_REQUEST, axum::Json(body)).into_response();
509        }
510    };
511    super::lan_watch::claimed(req.source_agent.as_deref().unwrap_or(""));
512    super::lan_watch::stage("delivery");
513    super::actor::check_actor(&state, caller.as_deref(), super::actor::ActorSite::Inject, req.source_agent.as_deref());
514    let caller_uid = super::caller::attributed_uid(caller.as_deref());
515    axum::Json(receive(&state, auth_via, &caller_uid, req, &mut reader).await).into_response()
516}
517
518async fn read_request<R: tokio::io::AsyncRead + Unpin>(reader: &mut R) -> Result<InjectionRequest, String> {
519    use tokio::io::AsyncReadExt;
520    let len = reader.read_u32().await.map_err(|e| format!("no request: {e}"))?;
521    if len == 0 || len > MAX_REQUEST_JSON {
522        return Err(format!("request of {len} bytes refused"));
523    }
524    let mut json = vec![0u8; len as usize];
525    reader.read_exact(&mut json).await.map_err(|e| format!("request cut short: {e}"))?;
526    serde_json::from_slice(&json).map_err(|e| format!("request unreadable: {e}"))
527}
528
529async fn receive<R: tokio::io::AsyncRead + Unpin>(
530    state: &super::AppState,
531    auth_via: super::ReactiveAuthVia,
532    caller_uid: &str,
533    mut req: InjectionRequest,
534    reader: &mut R,
535) -> serde_json::Value {
536    use super::reactive::*;
537    // The same steps as `deliver()`, up to the local delivery.
538    req.delivery_tier = Some(resolve_delivery_tier(auth_via, req.delivery_tier.as_deref()));
539    req.audit_source_uid = caller_uid.to_string();
540    super::actor::source_from_token(&state.mstore, caller_uid, &mut req);
541    verify_jekt_signature(state, &mut req);
542    verify_reagent_signature(&mut req, agentmux_common::time::now_secs());
543    verify_lan_signature(state, &mut req).await;
544    verify_cross_channel_signature(state, &mut req);
545    let mut replay = replay::reserve(&mut req, agentmux_common::time::now_secs());
546    req.route_unsigned_target();
547    resolve_transcript_request_tier_fields(&state.mstore, &mut req);
548
549    if req.files.is_none() {
550        return refused(&req, "files refused: the request names no files");
551    }
552    if let Err(e) = check_manifest(&req) {
553        return refused(&req, e);
554    }
555    let tier = req.delivery_tier.clone().unwrap_or_default();
556    if tier != "channel" && tier != "lan" {
557        return refused(&req, format!("files refused: not taken from the {tier} tier here"));
558    }
559    let files = req.files.clone().unwrap_or_default();
560    // Not here: the sender looks further, as for any forward.
561    let target = req.target_agent.clone();
562    if !state.reactive_handler.has_live_name(&target) && !state.reactive_handler.has_uid_registration(&target) {
563        return serde_json::json!({ "success": false, "error": format!("agent not found: {target}") });
564    }
565    let withheld = withheld_reason(&req).is_some();
566    // Signed out or out of quota until a known reset (SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md §5): a
567    // verified sender's message waits for it, files and all (they are read below, then both are held for
568    // up to 24 h); any other is refused before a byte is read, as `reactive::deliver` refuses it.
569    let mut waits_for = None;
570    if let Some(unavailable) = super::jekt_hold::local_target_unavailable(state, &target).await {
571        if !super::jekt_hold::peer_files_wait(&req, withheld) {
572            return super::jekt_hold::hold_for_unavailable(state, auth_via, &req, &unavailable, &mut replay).await;
573        }
574        waits_for = Some(unavailable);
575    }
576    // Files over the LAN come only from a verified sender (spec §4.3): refuse
577    // the rest before reading a byte, rather than drain what anyone holding
578    // the broadcast LAN key chose to upload.
579    if tier == "lan" && withheld {
580        return refused(&req, format!("files refused: {}", withheld_reason(&req).unwrap_or_default()));
581    }
582    crate::backend::ack_policy::remember_arrival(&state.mstore, &req);
583    let msgid = req.request_id.clone().unwrap_or_default();
584    let claimed = tier == "lan" && !withheld;
585    if claimed && !reserve(&msgid) {
586        return refused(&req, "files refused: this message was already delivered");
587    }
588
589    // A transfer that stalls gives its slot back: what arrived whole is kept.
590    let read = read_files(reader, &files, &tier, derives_on_receipt(&req), withheld);
591    match tokio::time::timeout(TRANSFER_TIMEOUT, read).await {
592        Err(_) => tracing::warn!(target = %target, "jekt files: transfer timed out"),
593        Ok(Err(why)) => {
594            if claimed {
595                release(&msgid);
596            }
597            return refused(&req, format!("files refused: {why}"));
598        }
599        Ok(Ok(())) => {}
600    }
601    if let Some(unavailable) = waits_for {
602        // The files that arrived whole are in the store, which keeps them for the hold; the replay
603        // builds what the agent is given for them (`prepare`), and says so for any that didn't arrive.
604        let answer = super::jekt_hold::hold_for_unavailable(state, auth_via, &req, &unavailable, &mut replay).await;
605        if claimed && answer.get("held").and_then(|h| h.as_bool()) != Some(true) {
606            release(&msgid);
607        }
608        return answer;
609    }
610    prepare(&mut req).await;
611    let delivered = req.files_delivery.as_ref().map_or(0, |d| d.delivered);
612    let resp = inject_here(state, &req);
613    if resp.success {
614        replay.delivered();
615    }
616    if claimed && !resp.success {
617        release(&msgid);
618    }
619    let mut value = serde_json::to_value(&resp).unwrap_or_default();
620    if let Some(obj) = value.as_object_mut() {
621        obj.insert("files_delivered".into(), delivered.into());
622    }
623    value
624}
625
626/// Take the jekt's files off the body: into the store, or (`withheld`) read
627/// past unstored. `Err` says why the message is refused.
628async fn read_files<R: tokio::io::AsyncRead + Unpin>(
629    reader: &mut R,
630    files: &[jekt_files::JektFile],
631    tier: &str,
632    derive: bool,
633    withheld: bool,
634) -> Result<(), String> {
635    if withheld {
636        // Same machine, full key: read past the files unstored, so the
637        // sender gets this answer rather than a reset connection.
638        let total = files.iter().fold(0u64, |sum, f| sum.saturating_add(f.size));
639        let mut rest = tokio::io::AsyncReadExt::take(reader, total);
640        let _ = tokio::io::copy(&mut rest, &mut tokio::io::sink()).await;
641        return Ok(());
642    }
643    match attachments::get() {
644        Some(svc) => store_files(&svc, files, reader, tier, derive).await,
645        None => Ok(()),
646    }
647}
648
649/// A file in `incoming/` that is removed when dropped, unless taken.
650struct PartFile(Option<std::path::PathBuf>);
651
652impl Drop for PartFile {
653    fn drop(&mut self) {
654        if let Some(path) = self.0.take() {
655            let _ = std::fs::remove_file(path);
656        }
657    }
658}
659
660/// How long to wait for a byte after the last file before taking the body as ended.
661const TRAILING_WAIT: std::time::Duration = std::time::Duration::from_millis(500);
662
663/// Stream each file into the store, keeping the ones whose bytes match
664/// their hash and size. A file that doesn't is dropped, and the list says it
665/// didn't arrive; a stream that ends early leaves the rest missing.
666///
667/// Held to the limits of `tier` here as well as by the caller's manifest
668/// check: nothing is created for a file whose declared size, or the running
669/// total of the message, is over them, and a body that goes on after the last
670/// file is refused. At most the declared bytes of a file are ever written, and
671/// a partial file is removed.
672///
673/// With `derive` unset (the sender is not proven) a file is stored as it
674/// arrived and nothing is read from it: no type sniffing, preview or text.
675async fn store_files<R: tokio::io::AsyncRead + Unpin>(
676    svc: &std::sync::Arc<attachments::Service>,
677    files: &[jekt_files::JektFile],
678    reader: &mut R,
679    tier: &str,
680    derive: bool,
681) -> Result<(), String> {
682    use sha2::Digest;
683    use tokio::io::{AsyncReadExt, AsyncWriteExt};
684    jekt_files::check_tier_limits(files, tier)?;
685    let (per_file, per_jekt) = jekt_files::tier_limits(tier).unwrap_or((0, 0));
686    let mut stored = 0u64;
687    for f in files {
688        if f.size > per_file || f.size > per_jekt.saturating_sub(stored) {
689            return Err("more bytes than the limits allow were declared".to_string());
690        }
691        stored += f.size;
692        let tmp = svc.store().new_incoming_path();
693        // Removes the partial file even when the copy is dropped mid-read
694        // (the transfer's deadline); kept only once the store has it.
695        let mut guard = PartFile(Some(tmp.clone()));
696        let copied = async {
697            let mut out = tokio::fs::File::create(&tmp).await?;
698            let mut hasher = sha2::Sha256::new();
699            let mut left = f.size;
700            let mut buf = vec![0u8; 64 * 1024];
701            while left > 0 {
702                let want = buf.len().min(left as usize);
703                let n = reader.read(&mut buf[..want]).await?;
704                if n == 0 {
705                    return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "cut short"));
706                }
707                hasher.update(&buf[..n]);
708                out.write_all(&buf[..n]).await?;
709                left -= n as u64;
710            }
711            out.flush().await?;
712            Ok::<_, std::io::Error>(hex::encode(hasher.finalize()))
713        }
714        .await;
715        match copied {
716            Ok(sha) if sha == f.sha256 => {
717                let placed = if derive {
718                    svc.commit_upload(tmp.clone(), sha, f.name.clone()).await.map(|_| ())
719                } else {
720                    svc.store_undecoded(tmp.clone(), sha, f.name.clone()).await
721                };
722                match placed {
723                    Ok(()) => guard.0 = None,
724                    Err(e) => tracing::warn!(file = %f.name, error = %e.message, "jekt files: received file not stored"),
725                }
726            }
727            Ok(_) => tracing::warn!(file = %f.name, "jekt files: received bytes don't match their hash"),
728            Err(e) => {
729                tracing::warn!(file = %f.name, error = %e, "jekt files: transfer cut short");
730                return Ok(());
731            }
732        }
733    }
734    // The body ends with the last file: a byte after it was not declared.
735    let mut extra = [0u8; 1];
736    if let Ok(Ok(n)) = tokio::time::timeout(TRAILING_WAIT, reader.read(&mut extra)).await {
737        if n > 0 {
738            return Err("more bytes were sent than the message declared".to_string());
739        }
740    }
741    Ok(())
742}
743
744/// Whether a same-machine candidate can take this jekt: any can take a text
745/// jekt; one with files only if its registry entry advertises them. A
746/// candidate passed over for that sets `too_old`.
747pub(crate) fn entry_takes(req: &InjectionRequest, entry: &crate::backend::reactive::registry::AgentEntry, too_old: &mut bool) -> bool {
748    if req.files.is_none() || entry.jekt_features.iter().any(|f| f == jekt_files::FEATURE) {
749        return true;
750    }
751    // An entry whose process is gone is stale, not a running older build:
752    // pass over it without calling the target too old.
753    if crate::backend::reactive::registry::pid_alive(entry.pid) {
754        *too_old = true;
755    }
756    false
757}
758
759/// Whether the LAN peer found for this jekt can take it. A jekt with files
760/// needs the peer to advertise them (else `too_old`; a probe that went
761/// unanswered sets `candidate_seen`, so the sender is told to try again), and
762/// must be within the LAN's limits, or it is refused outright: no other
763/// route is left for it.
764pub(crate) async fn lan_peer_takes(
765    client: &reqwest::Client,
766    req: &InjectionRequest,
767    url: &str,
768    auth_key: &str,
769    too_old: &mut bool,
770    candidate_seen: &mut bool,
771) -> Result<bool, serde_json::Value> {
772    let Some(files) = req.files.as_deref() else {
773        return Ok(true);
774    };
775    match peer_accepts_files(client, url, auth_key, &req.target_agent).await {
776        Some(true) => {}
777        Some(false) => {
778            *too_old = true;
779            return Ok(false);
780        }
781        None => {
782            *candidate_seen = true;
783            return Ok(false);
784        }
785    }
786    jekt_files::check_tier_limits(files, "lan").map_err(|e| refused(req, format!("files refused: {e}")))?;
787    Ok(true)
788}
789
790/// Why files were refused: the target runs an AgentMux that can't take them, and which version fixes that.
791fn files_too_old_text(target: &str) -> String {
792    format!("files refused: {target}'s AgentMux is too old to receive files: update it to AgentMux {} or newer; nothing was sent", crate::backend::remote_panes::host::own_version())
793}
794
795/// The answer for a jekt with files that no instance on this machine or the
796/// LAN took: held for an agent defined here that isn't running, otherwise
797/// refused with the reason. Files don't go through the relay yet (spec §8).
798#[allow(clippy::too_many_arguments)]
799pub(in crate::server) async fn no_route(
800    state: &super::AppState,
801    auth_via: super::ReactiveAuthVia,
802    caller_uid: &str,
803    req: &InjectionRequest,
804    resp: &crate::backend::reactive::types::InjectionResponse,
805    candidate_seen: bool,
806    too_old: bool,
807    replay: &mut super::reactive::replay::Reservation,
808) -> serde_json::Value {
809    use super::reactive::{hold_for_absent_target, route_for_absent, AbsentRoute, HoldReason};
810    if too_old {
811        // Alive in an older build, not absent: neither held nor relayed.
812        return refused(req, files_too_old_text(&req.target_agent));
813    }
814    // As a text jekt: held here for an agent defined here that no install
815    // runs, else through the relay (spec §4.4).
816    if !candidate_seen && route_for_absent(state, auth_via, req, resp).await == AbsentRoute::HoldHere {
817        if let Some(held) = hold_for_absent_target(state, auth_via, req, resp, HoldReason::NotRunning, replay).await {
818            return held;
819        }
820    }
821    match super::jekt_cloud::relay(state, req, caller_uid).await {
822        Ok(Some(queued)) => return queued,
823        Ok(None) => {}
824        Err(why) => return refused(req, why),
825    }
826    if !candidate_seen {
827        if let Some(held) = hold_for_absent_target(state, auth_via, req, resp, HoldReason::NotRunning, replay).await {
828            return held;
829        }
830    }
831    let target = &req.target_agent;
832    refused(
833        req,
834        if candidate_seen {
835            format!("files refused: {target} couldn't take them just now; nothing was sent, try again shortly")
836        } else {
837            format!("files refused: {target} isn't on this machine or the LAN, and the cloud relay didn't take them; nothing was sent")
838        },
839    )
840}
841
842/// `answer` with how many files the agent got, when the jekt had files.
843pub(crate) fn with_count(mut answer: serde_json::Value, req: &InjectionRequest) -> serde_json::Value {
844    if let (Some(d), Some(obj)) = (req.files_delivery.as_ref(), answer.as_object_mut()) {
845        obj.insert("files_delivered".into(), d.delivered.into());
846    }
847    answer
848}
849
850#[cfg(test)]
851mod tests {
852    use super::*;
853    use agentmux_common::jekt_files::JektFile;
854
855    fn files() -> Vec<JektFile> {
856        vec![JektFile { sha256: "ab".repeat(32), name: "shot.png".into(), size: 3 }]
857    }
858
859    fn req_with(files: Vec<JektFile>, msgid: &str, tier: &str) -> InjectionRequest {
860        InjectionRequest {
861            target_agent: "agenta".into(),
862            message: "look".into(),
863            request_id: Some(msgid.into()),
864            delivery_tier: Some(tier.into()),
865            files: Some(files),
866            ..Default::default()
867        }
868    }
869
870    #[test]
871    fn a_bound_manifest_on_this_instance_passes() {
872        let f = files();
873        assert_eq!(check(&req_with(f.clone(), &jekt_files::bind_msgid("m", &f), "host")), Ok(()));
874    }
875
876    #[test]
877    fn a_manifest_the_msgid_does_not_bind_is_refused() {
878        let f = files();
879        let mut other = f.clone();
880        other[0].size = 4;
881        let err = check(&req_with(other, &jekt_files::bind_msgid("m", &f), "host")).unwrap_err();
882        assert!(err.contains("don't match the message id"), "{err}");
883        assert!(check(&req_with(f, "m", "host")).is_err(), "an unbound msgid");
884    }
885
886    #[test]
887    fn files_named_by_hash_only_come_from_this_instance() {
888        let f = files();
889        let msgid = jekt_files::bind_msgid("m", &f);
890        for tier in ["channel", "lan", "wan"] {
891            assert!(check(&req_with(f.clone(), &msgid, tier)).is_err(), "{tier}");
892        }
893    }
894
895    #[test]
896    fn a_text_jekt_passes_untouched() {
897        let req = InjectionRequest { request_id: Some("m".into()), ..Default::default() };
898        assert_eq!(check(&req), Ok(()));
899    }
900
901    #[test]
902    fn an_active_verification_failure_withholds_the_files() {
903        let f = files();
904        let mut req = req_with(f.clone(), &jekt_files::bind_msgid("m", &f), "host");
905        assert_eq!(withheld_reason(&req), None, "self-declared on this instance");
906        req.sig_verified = Some(false);
907        assert!(withheld_reason(&req).is_some());
908        req.sig_verified = Some(true);
909        req.channel_verified = Some(false);
910        assert!(withheld_reason(&req).is_some(), "any failed check withholds");
911    }
912
913    /// Inline needs proof for this message: a verified check and no failed one.
914    #[test]
915    fn only_a_verified_sender_gets_files_inline() {
916        let f = files();
917        let mut req = req_with(f.clone(), &jekt_files::bind_msgid("m", &f), "channel");
918        assert!(!sender_verified(&req), "self-declared");
919        req.channel_verified = Some(true);
920        assert!(sender_verified(&req));
921        req.lan_verified = Some(false);
922        assert!(!sender_verified(&req), "a failed check rules it out");
923        let mut wan = req_with(f.clone(), &jekt_files::bind_msgid("m", &f), "wan");
924        wan.wan_verified = Some(true);
925        assert!(!sender_verified(&wan), "a verdict with no instance proves no install");
926    }
927
928    #[test]
929    fn lan_files_need_a_verified_sender() {
930        let f = files();
931        let mut req = req_with(f.clone(), &jekt_files::bind_msgid("m", &f), "lan");
932        assert!(withheld_reason(&req).is_some());
933        req.lan_verified = Some(true);
934        assert_eq!(withheld_reason(&req), None);
935    }
936
937    #[tokio::test]
938    async fn withheld_and_missing_files_are_said_so() {
939        let f = files();
940        let mut req = req_with(f.clone(), &jekt_files::bind_msgid("m", &f), "host");
941        req.sig_verified = Some(false);
942        prepare(&mut req).await;
943        let d = req.files_delivery.unwrap();
944        assert_eq!(d.delivered, 0);
945        assert!(d.text.contains("1 file sent with this message was withheld"), "{}", d.text);
946
947        let mut bare = InjectionRequest { request_id: Some(jekt_files::bind_msgid("m", &f)), ..Default::default() };
948        prepare(&mut bare).await;
949        assert!(bare.files_delivery.unwrap().text.contains("didn't arrive"));
950
951        let mut text = InjectionRequest { request_id: Some("m".into()), ..Default::default() };
952        prepare(&mut text).await;
953        assert_eq!(text.files_delivery, None);
954    }
955
956    // ---- Transfer to another instance (spec §4) ----
957
958
959    fn service(dir: &std::path::Path) -> Arc<attachments::Service> {
960        Arc::new(attachments::Service::new(
961            attachments::store::Store::new(dir.join("attachments")),
962            Arc::new(crate::backend::mps::Broker::new()),
963            Arc::new(crate::backend::wconfig::ConfigState::new()),
964        ))
965    }
966
967    fn sha(bytes: &[u8]) -> String {
968        use sha2::Digest;
969        hex::encode(sha2::Sha256::digest(bytes))
970    }
971
972    fn manifest_entry(name: &str, bytes: &[u8]) -> JektFile {
973        JektFile { sha256: sha(bytes), name: name.into(), size: bytes.len() as u64 }
974    }
975
976    /// The framed body as a sender writes it, by hand.
977    fn framed(req: &InjectionRequest, files: &[&[u8]]) -> Vec<u8> {
978        let json = serde_json::to_vec(req).unwrap();
979        let mut out = (json.len() as u32).to_be_bytes().to_vec();
980        out.extend_from_slice(&json);
981        for f in files {
982            out.extend_from_slice(f);
983        }
984        out
985    }
986
987    #[tokio::test]
988    async fn files_cross_from_one_store_to_another_intact() {
989        let d = tempfile::tempdir().unwrap();
990        let (sender, receiver) = (service(&d.path().join("a")), service(&d.path().join("b")));
991        let bytes = b"File transfer test note.\n".to_vec();
992        let src = d.path().join("notes.txt");
993        std::fs::write(&src, &bytes).unwrap();
994        let (tmp, id, _) = sender.store().copy_in(&src, |_| true).unwrap();
995        sender.commit_upload(tmp, id.clone(), "notes.txt".into()).await.unwrap();
996
997        let files = vec![manifest_entry("notes.txt", &bytes)];
998        let req = req_with(files.clone(), &jekt_files::bind_msgid("m", &files), "channel");
999        let mut reader = tokio_util::io::StreamReader::new(transfer_stream(&sender, &req).await.unwrap());
1000        let got = read_request(&mut reader).await.unwrap();
1001        assert_eq!(got.files, Some(files.clone()));
1002        assert_eq!(got.request_id, req.request_id, "the msgid that binds them travels too");
1003        assert!(got.files_delivery.is_none(), "a sender can't supply the list");
1004
1005        store_files(&receiver, &files, &mut reader, "channel", true).await.unwrap();
1006        let (path, _) = receiver.store().find_blob(&id).expect("stored on the far side");
1007        assert_eq!(std::fs::read(path).unwrap(), bytes);
1008    }
1009
1010    #[tokio::test]
1011    async fn a_file_whose_bytes_do_not_match_is_dropped_and_the_next_still_arrives() {
1012        let d = tempfile::tempdir().unwrap();
1013        let receiver = service(d.path());
1014        let files = vec![manifest_entry("a.txt", b"hello"), manifest_entry("b.txt", b"world")];
1015        let req = req_with(files.clone(), &jekt_files::bind_msgid("m", &files), "lan");
1016        let body = framed(&req, &[b"jello", b"world"]);
1017        let mut reader = &body[..];
1018        read_request(&mut reader).await.unwrap();
1019        store_files(&receiver, &files, &mut reader, "lan", true).await.unwrap();
1020        assert!(receiver.store().find_blob(&sha(b"hello")).is_none());
1021        assert!(receiver.store().find_blob(&sha(b"jello")).is_none(), "nothing stored under another hash");
1022        assert!(receiver.store().find_blob(&sha(b"world")).is_some());
1023        assert!(reader.is_empty(), "exactly the declared bytes were read");
1024    }
1025
1026    #[tokio::test]
1027    async fn a_transfer_cut_short_stores_only_what_arrived_whole() {
1028        let d = tempfile::tempdir().unwrap();
1029        let receiver = service(d.path());
1030        let files = vec![manifest_entry("a.txt", b"hello"), manifest_entry("b.txt", b"world")];
1031        let req = req_with(files.clone(), &jekt_files::bind_msgid("m", &files), "lan");
1032        let body = framed(&req, &[b"hello", b"wor"]);
1033        let mut reader = &body[..];
1034        read_request(&mut reader).await.unwrap();
1035        store_files(&receiver, &files, &mut reader, "lan", true).await.unwrap();
1036        assert!(receiver.store().find_blob(&sha(b"hello")).is_some());
1037        assert!(receiver.store().find_blob(&sha(b"world")).is_none());
1038        let incoming = d.path().join("attachments").join("incoming");
1039        let left = std::fs::read_dir(&incoming).map(|r| r.count()).unwrap_or(0);
1040        assert_eq!(left, 0, "no partial file left behind");
1041    }
1042
1043    const MIB: u64 = 1024 * 1024;
1044
1045    fn incoming_count(dir: &std::path::Path) -> usize {
1046        std::fs::read_dir(dir.join("attachments").join("incoming")).map(|r| r.count()).unwrap_or(0)
1047    }
1048
1049    fn sized(name: &str, size: u64) -> JektFile {
1050        JektFile { sha256: "ab".repeat(32), name: name.into(), size }
1051    }
1052
1053    #[test]
1054    fn a_manifest_over_the_limit_of_its_tier_is_refused_before_anything_is_read() {
1055        for (tier, size, limit) in [("host", 101 * MIB, "100 MB"), ("channel", 101 * MIB, "100 MB"), ("lan", 51 * MIB, "50 MB")] {
1056            let f = vec![sized("big.bin", size)];
1057            let err = check_manifest(&req_with(f.clone(), &jekt_files::bind_msgid("m", &f), tier)).unwrap_err();
1058            assert!(err.contains(limit) && err.contains("big.bin"), "{tier}: {err}");
1059        }
1060        let f = vec![sized("a.bin", 40 * MIB), sized("b.bin", 40 * MIB), sized("c.bin", 40 * MIB)];
1061        let err = check_manifest(&req_with(f.clone(), &jekt_files::bind_msgid("m", &f), "lan")).unwrap_err();
1062        assert!(err.contains("100 MB limit per message"), "{err}");
1063        let ok = vec![sized("a.bin", 50 * MIB), sized("b.bin", 50 * MIB)];
1064        assert_eq!(check_manifest(&req_with(ok.clone(), &jekt_files::bind_msgid("m", &ok), "lan")), Ok(()));
1065        // The same comparison for a file named by hash on this machine.
1066        let f = vec![sized("big.bin", 101 * MIB)];
1067        assert!(check(&req_with(f.clone(), &jekt_files::bind_msgid("m", &f), "host")).is_err());
1068    }
1069
1070    #[tokio::test]
1071    async fn the_store_writes_nothing_for_files_declared_over_the_limit() {
1072        let d = tempfile::tempdir().unwrap();
1073        let receiver = service(d.path());
1074        for files in [
1075            vec![sized("big.bin", 51 * MIB)],
1076            vec![sized("a.bin", 40 * MIB), sized("b.bin", 40 * MIB), sized("c.bin", 40 * MIB)],
1077        ] {
1078            let body = vec![7u8; 4096];
1079            let mut reader = &body[..];
1080            let err = store_files(&receiver, &files, &mut reader, "lan", true).await.unwrap_err();
1081            assert!(err.contains("limit"), "{err}");
1082            assert_eq!(reader.len(), body.len(), "not a byte of the files was read");
1083            assert_eq!(incoming_count(d.path()), 0, "nothing was created");
1084        }
1085        let mut empty = &b""[..];
1086        assert!(store_files(&receiver, &[sized("a", 1)], &mut empty, "elsewhere", true).await.is_err(), "a tier with no limits takes no files");
1087    }
1088
1089    #[tokio::test]
1090    async fn bytes_beyond_the_declared_size_are_never_written_and_refuse_the_message() {
1091        let d = tempfile::tempdir().unwrap();
1092        let receiver = service(d.path());
1093        let files = vec![manifest_entry("a.txt", b"hello")];
1094        let mut body = b"hello".to_vec();
1095        body.extend_from_slice(b"and more that was never declared");
1096        let mut reader = &body[..];
1097        let err = store_files(&receiver, &files, &mut reader, "lan", true).await.unwrap_err();
1098        assert!(err.contains("more bytes were sent than the message declared"), "{err}");
1099        assert_eq!(incoming_count(d.path()), 0, "no partial file left behind");
1100        // A longer stream for a file than its declared size is never taken into that file.
1101        let (path, _) = receiver.store().find_blob(&sha(b"hello")).expect("the declared bytes arrived whole");
1102        assert_eq!(std::fs::read(path).unwrap(), b"hello");
1103    }
1104
1105    #[tokio::test]
1106    async fn a_file_from_a_sender_that_is_not_proven_is_stored_unread_and_derived_when_opened() {
1107        let d = tempfile::tempdir().unwrap();
1108        let receiver = service(d.path());
1109        let files = vec![manifest_entry("notes.txt", NOTES)];
1110        let mut reader = NOTES;
1111        store_files(&receiver, &files, &mut reader, "channel", false).await.unwrap();
1112        let id = sha(NOTES);
1113        let fp = attachments::store::fingerprint(receiver.limits().send_max_edge);
1114        assert_eq!(receiver.stored_len(&id), Some(NOTES.len() as u64), "stored");
1115        assert!(receiver.store().meta(&id, &fp).is_none(), "nothing derived on receipt");
1116        assert_eq!(incoming_count(d.path()), 0);
1117
1118        // Delivered: listed with a copy of the file, and still not derived.
1119        let mut req = req_with(files.clone(), &jekt_files::bind_msgid("m", &files), "channel");
1120        prepare_for(&mut req, Some(receiver.clone()), Destination::Host).await;
1121        let delivery = req.files_delivery.unwrap();
1122        assert_eq!(delivery.delivered, 1);
1123        assert!(delivery.text.contains("notes.txt") && delivery.text.contains("not opened"), "{}", delivery.text);
1124        assert!(!delivery.text.contains("text version") && delivery.inline.is_empty(), "{}", delivery.text);
1125        assert!(receiver.store().meta(&id, &fp).is_none(), "nothing derived on delivery");
1126        let listed = receiver.unread_target(&id, "notes.txt").unwrap();
1127        assert_eq!(std::fs::read(listed.path).unwrap(), NOTES, "the agent gets the bytes as they came");
1128
1129        // Drawing its tile, or asking for its thumbnail, derives nothing: the tile is a type icon with the size.
1130        assert!(receiver.ensure_derived(&id).await.is_none());
1131        let shown = receiver.info(std::slice::from_ref(&id)).await;
1132        assert_eq!((shown.len(), shown[0].kind.as_str(), shown[0].bytes), (1, "other", NOTES.len() as u64));
1133        assert!(receiver.store().meta(&id, &fp).is_none(), "still nothing derived");
1134
1135        // Opened (sent by the person in a message of their own): derived then.
1136        assert!(receiver.open_derived(&id).await.is_some());
1137        assert!(receiver.store().meta(&id, &fp).is_some());
1138        assert!(!receiver.store().is_unread(&id));
1139        assert!(receiver.ensure_derived(&id).await.is_some(), "and passive requests find it");
1140    }
1141
1142    #[tokio::test]
1143    async fn a_file_stored_unread_is_derived_when_a_proven_sender_sends_the_same_bytes() {
1144        let d = tempfile::tempdir().unwrap();
1145        let receiver = service(d.path());
1146        let files = vec![manifest_entry("notes.txt", NOTES)];
1147        store_files(&receiver, &files, &mut &NOTES[..], "channel", false).await.unwrap();
1148        assert!(receiver.store().is_unread(&sha(NOTES)));
1149        store_files(&receiver, &files, &mut &NOTES[..], "channel", true).await.unwrap();
1150        let mut req = req_with(files.clone(), &jekt_files::bind_msgid("m", &files), "channel");
1151        req.channel_verified = Some(true);
1152        prepare_for(&mut req, Some(receiver.clone()), Destination::Host).await;
1153        assert_eq!(req.files_delivery.unwrap().delivered, 1);
1154        assert!(!receiver.store().is_unread(&sha(NOTES)), "derived for the proven sender");
1155    }
1156
1157    #[tokio::test]
1158    async fn a_file_from_a_proven_sender_is_derived_on_receipt() {
1159        let d = tempfile::tempdir().unwrap();
1160        let receiver = service(d.path());
1161        let files = vec![manifest_entry("notes.txt", NOTES)];
1162        let mut reader = NOTES;
1163        store_files(&receiver, &files, &mut reader, "channel", true).await.unwrap();
1164        let fp = attachments::store::fingerprint(receiver.limits().send_max_edge);
1165        assert!(receiver.store().meta(&sha(NOTES), &fp).is_some());
1166    }
1167
1168    #[tokio::test]
1169    async fn a_file_derived_before_is_listed_as_derived_even_from_an_unproven_sender() {
1170        let d = tempfile::tempdir().unwrap();
1171        let (svc, mut req) = jekt_with_notes(d.path()).await;
1172        req.delivery_tier = Some("channel".into());
1173        prepare_for(&mut req, Some(svc), Destination::Host).await;
1174        let text = req.files_delivery.unwrap().text;
1175        assert!(!text.contains("not opened"), "{text}");
1176    }
1177
1178    #[test]
1179    fn only_a_sender_proven_for_the_message_has_its_files_derived_on_receipt() {
1180        let f = files();
1181        let msgid = jekt_files::bind_msgid("m", &f);
1182        let with = |tier: &str, set: &dyn Fn(&mut InjectionRequest)| {
1183            let mut r = req_with(f.clone(), &msgid, tier);
1184            set(&mut r);
1185            derives_on_receipt(&r)
1186        };
1187        assert!(!with("host", &|_| {}), "self-declared");
1188        assert!(with("host", &|r| r.sig_verified = Some(true)), "host-verified");
1189        assert!(!with("host", &|r| r.sig_verified = Some(false)), "unverified");
1190        assert!(!with("channel", &|_| {}), "self-declared over the channel");
1191        assert!(with("channel", &|r| r.channel_verified = Some(true)), "channel-verified");
1192        assert!(!with("lan", &|_| {}));
1193        assert!(!with("lan", &|r| r.lan_verified = Some(false)), "a failed check");
1194        assert!(with("lan", &|r| r.lan_verified = Some(true)), "lan-verified");
1195        assert!(!with("wan", &|r| r.wan_verified = Some(true)), "a verdict with no instance");
1196        for (status, derived) in [(WanInstanceStatus::Approved, true), (WanInstanceStatus::New, false), (WanInstanceStatus::Revoked, false)] {
1197            let got = with("wan", &|r| {
1198                r.wan_verified = Some(true);
1199                r.wan_instance = Some(crate::backend::reactive::types::WanInstanceInfo { id: "i".repeat(26), label: "host~iiiiiiii".into(), status });
1200            });
1201            assert_eq!(got, derived, "{status:?}");
1202        }
1203    }
1204
1205    #[tokio::test]
1206    async fn a_message_too_long_to_carry_files_is_refused_by_the_sender() {
1207        let d = tempfile::tempdir().unwrap();
1208        let f = files();
1209        let mut req = req_with(f.clone(), &jekt_files::bind_msgid("m", &f), "channel");
1210        req.message = "x".repeat(MAX_REQUEST_JSON as usize);
1211        let err = transfer_stream(&service(d.path()), &req).await.err().unwrap();
1212        assert!(err.contains("too long to send with files"), "{err}");
1213    }
1214
1215    #[tokio::test]
1216    async fn an_oversized_or_missing_request_header_is_refused_before_reading_on() {
1217        let big = (MAX_REQUEST_JSON + 1).to_be_bytes();
1218        assert!(read_request(&mut &big[..]).await.unwrap_err().contains("refused"));
1219        assert!(read_request(&mut &[0u8, 0, 0, 0][..]).await.is_err());
1220        assert!(read_request(&mut &[0u8, 0][..]).await.is_err());
1221    }
1222
1223    #[test]
1224    fn only_a_candidate_that_advertises_files_gets_them() {
1225        let f = files();
1226        let with_files = req_with(f.clone(), &jekt_files::bind_msgid("m", &f), "host");
1227        let text = InjectionRequest { request_id: Some("m".into()), ..Default::default() };
1228        let mut entry: crate::backend::reactive::registry::AgentEntry = serde_json::from_value(serde_json::json!({
1229            "agent_id": "agenta", "local_url": "http://127.0.0.1:1", "block_id": "b", "pid": std::process::id(), "updated_at": 0
1230        }))
1231        .unwrap();
1232        let mut too_old = false;
1233        assert!(entry_takes(&text, &entry, &mut too_old) && !too_old, "any entry takes a text jekt");
1234        assert!(!entry_takes(&with_files, &entry, &mut too_old) && too_old, "an older build's entry");
1235        entry.jekt_features = vec![jekt_files::FEATURE.into()];
1236        let mut too_old = false;
1237        assert!(entry_takes(&with_files, &entry, &mut too_old) && !too_old);
1238        entry.jekt_features.clear();
1239        entry.pid = u32::MAX - 7;
1240        assert!(!entry_takes(&with_files, &entry, &mut too_old) && !too_old, "a stale entry is no evidence of an older build");
1241    }
1242
1243    #[test]
1244    fn an_older_build_that_cannot_take_files_is_told_which_version_to_update_to() {
1245        let text = files_too_old_text("lazo");
1246        assert!(text.starts_with("files refused: lazo's AgentMux is too old to receive files: update it to AgentMux "), "{text}");
1247        assert!(text.ends_with(&format!("{} or newer; nothing was sent", crate::backend::remote_panes::host::own_version())), "{text}");
1248    }
1249
1250    #[tokio::test]
1251    async fn an_unanswered_lan_probe_is_inconclusive_not_too_old() {
1252        let f = files();
1253        let req = req_with(f.clone(), &jekt_files::bind_msgid("m", &f), "host");
1254        let client = reqwest::Client::builder().timeout(std::time::Duration::from_secs(2)).build().unwrap();
1255        let (mut too_old, mut seen) = (false, false);
1256        let takes = lan_peer_takes(&client, &req, "http://127.0.0.1:1", "", &mut too_old, &mut seen).await;
1257        assert_eq!(takes.ok(), Some(false));
1258        assert!(!too_old && seen, "a peer that didn't answer may still be up to date");
1259    }
1260
1261    #[test]
1262    fn a_lan_files_jekt_is_delivered_once() {
1263        let id = format!("m-{}", std::process::id());
1264        assert!(reserve(&id));
1265        assert!(!reserve(&id), "a copy arriving while the first is delivered, or after");
1266        release(&id);
1267        assert!(reserve(&id), "a delivery that failed may be retried");
1268        assert!(reserve(&format!("{id}-other")));
1269    }
1270
1271    // ---- Files for a container agent: opened where it can read them ----
1272
1273    const NOTES: &[u8] = b"Sent to a container agent.
1274";
1275
1276    /// A service holding `notes.txt`, and the jekt that sends it.
1277    async fn jekt_with_notes(dir: &std::path::Path) -> (Arc<attachments::Service>, InjectionRequest) {
1278        let svc = service(dir);
1279        let src = dir.join("notes.txt");
1280        std::fs::write(&src, NOTES).unwrap();
1281        let (tmp, id, _) = svc.store().copy_in(&src, |_| true).unwrap();
1282        svc.commit_upload(tmp, id, "notes.txt".into()).await.unwrap();
1283        let files = vec![manifest_entry("notes.txt", NOTES)];
1284        let req = req_with(files.clone(), &jekt_files::bind_msgid("m", &files), "host");
1285        (svc, req)
1286    }
1287
1288    fn container_block(cwd: Option<&str>) -> crate::backend::obj::Block {
1289        let mut block = crate::backend::obj::Block::default();
1290        block.meta.insert("agentMode".into(), serde_json::json!("container"));
1291        if let Some(cwd) = cwd {
1292            block.meta.insert("cmd:cwd".into(), serde_json::json!(cwd));
1293        }
1294        block
1295    }
1296
1297    fn container_list_names_the_copy(text: &str, cwd: &std::path::Path, store_root: &std::path::Path) {
1298        let sha = sha(NOTES);
1299        let want = format!("/workspace/.agentmux-attachments/named/{sha}/notes.txt");
1300        assert!(text.contains(&want), "the list names the path inside the container: {text}");
1301        assert!(!text.contains(store_root.to_str().unwrap()) && !text.contains(cwd.to_str().unwrap()), "no host path is left: {text}");
1302        let on_host = cwd.join(".agentmux-attachments").join("named").join(&sha).join("notes.txt");
1303        assert_eq!(std::fs::read(on_host).unwrap(), NOTES, "the file is in the folder the container mounts as /workspace");
1304    }
1305
1306    #[tokio::test]
1307    async fn a_file_sent_to_a_running_container_agent_is_copied_into_its_workspace() {
1308        let d = tempfile::tempdir().unwrap();
1309        let (svc, mut req) = jekt_with_notes(d.path()).await;
1310        let cwd = d.path().join("agent-workspace");
1311        std::fs::create_dir_all(&cwd).unwrap();
1312        let dest = destination_for_block(&container_block(Some(cwd.to_str().unwrap())));
1313        prepare_for(&mut req, Some(svc), dest).await;
1314        let delivery = req.files_delivery.unwrap();
1315        assert_eq!(delivery.delivered, 1);
1316        container_list_names_the_copy(&delivery.text, &cwd, &d.path().join("attachments"));
1317    }
1318
1319    #[tokio::test]
1320    async fn a_queued_or_held_file_jekt_is_prepared_afresh_for_the_container_when_it_is_delivered() {
1321        // A held jekt is rebuilt from its row (no list) and prepared again at replay, as a queued one is
1322        // prepared when it is accepted: each time the copy lands in the workspace and the list names it.
1323        let d = tempfile::tempdir().unwrap();
1324        let (svc, req) = jekt_with_notes(d.path()).await;
1325        let cwd = d.path().join("agent-workspace");
1326        std::fs::create_dir_all(&cwd).unwrap();
1327        let block = container_block(Some(cwd.to_str().unwrap()));
1328        for _ in 0..2 {
1329            let mut replay = InjectionRequest { files_delivery: None, ..req.clone() };
1330            prepare_for(&mut replay, Some(svc.clone()), destination_for_block(&block)).await;
1331            container_list_names_the_copy(&replay.files_delivery.unwrap().text, &cwd, &d.path().join("attachments"));
1332        }
1333    }
1334
1335    #[tokio::test]
1336    async fn a_container_agent_with_no_working_folder_yet_is_told_the_files_could_not_be_delivered() {
1337        let d = tempfile::tempdir().unwrap();
1338        let (svc, mut req) = jekt_with_notes(d.path()).await;
1339        prepare_for(&mut req, Some(svc), destination_for_block(&container_block(None))).await;
1340        let delivery = req.files_delivery.unwrap();
1341        assert_eq!(delivery.delivered, 0);
1342        assert!(delivery.text.contains("couldn't be delivered") && delivery.text.contains("working folder"), "{}", delivery.text);
1343        assert!(!delivery.text.contains(d.path().to_str().unwrap()), "no host path: {}", delivery.text);
1344    }
1345
1346    /// The files' list for `found`, after the lookup stage that picks where they go.
1347    async fn list_for(found: Found) -> (std::path::PathBuf, FilesDelivery) {
1348        let d = tempfile::tempdir().unwrap();
1349        let (svc, mut req) = jekt_with_notes(d.path()).await;
1350        prepare_for(&mut req, Some(svc), destination_for(found)).await;
1351        (d.path().to_path_buf(), req.files_delivery.unwrap())
1352    }
1353
1354    #[tokio::test]
1355    async fn a_container_agent_the_registry_cant_place_never_gets_the_stores_host_path() {
1356        // The case the earlier tests skipped: the lookup that finds the pane fails or finds none. A container agent
1357        // must then be refused with a reason, not handed a path it cannot open, and the sender's count says 0.
1358        for found in [Found::PaneUnreadable, Found::Unbound { container: true }] {
1359            let (dir, delivery) = list_for(found).await;
1360            assert_eq!(delivery.delivered, 0, "the sender is told no file arrived");
1361            assert!(delivery.text.contains("couldn't be delivered") && delivery.text.contains("send the files again"), "{}", delivery.text);
1362            assert!(!delivery.text.contains(dir.to_str().unwrap()) && !delivery.text.contains(&sha(NOTES)), "no host path: {}", delivery.text);
1363        }
1364    }
1365
1366    #[tokio::test]
1367    async fn a_target_known_to_be_a_host_agent_or_unknown_here_is_sent_the_stores_own_path() {
1368        for found in [Found::Unbound { container: false }, Found::Pane(crate::backend::obj::Block::default())] {
1369            let (_dir, delivery) = list_for(found).await;
1370            assert_eq!(delivery.delivered, 1);
1371            assert!(delivery.text.contains(&sha(NOTES)) && !delivery.text.contains("/workspace"), "{}", delivery.text);
1372        }
1373    }
1374
1375    #[tokio::test]
1376    async fn a_pane_the_store_returns_for_a_container_agent_is_copied_into_its_workspace_by_the_same_lookup_stage() {
1377        let d = tempfile::tempdir().unwrap();
1378        let (svc, mut req) = jekt_with_notes(d.path()).await;
1379        let cwd = d.path().join("agent-workspace");
1380        std::fs::create_dir_all(&cwd).unwrap();
1381        prepare_for(&mut req, Some(svc), destination_for(Found::Pane(container_block(Some(cwd.to_str().unwrap()))))).await;
1382        container_list_names_the_copy(&req.files_delivery.unwrap().text, &cwd, &d.path().join("attachments"));
1383    }
1384
1385    #[tokio::test]
1386    async fn a_host_agent_still_gets_the_stores_own_path() {
1387        let d = tempfile::tempdir().unwrap();
1388        let (svc, mut req) = jekt_with_notes(d.path()).await;
1389        let dest = destination_for_block(&crate::backend::obj::Block::default());
1390        prepare_for(&mut req, Some(svc), dest).await;
1391        let delivery = req.files_delivery.unwrap();
1392        assert_eq!(delivery.delivered, 1);
1393        assert!(delivery.text.contains(&sha(NOTES)) && !delivery.text.contains("/workspace"), "{}", delivery.text);
1394    }
1395}