~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
1355 lines · 47.2 KB Raw History
//! Spaces at the fake PDS, as the alpha serves them to an OAuth session
//! (`describeServer`'s `spacesAlpha`, `com.atproto.space.*` with a
//! `space:` permission, listings page by page), and the canvases kept
//! there (`canvas::space`) against it: where a person's canvases go and
//! why, moving them in, writes, moves put off, failures, deleting, and a
//! person's whole deletion (`Canvases::forget`).

use super::*;
use crate::canvas::space::grants;
use crate::canvas::store::FileStore;
use crate::canvas::{Beside, By, CanvasInfo, Member, Notice, Op, Role, Tile, Who, Width};
use crate::space::Failure;
use std::collections::BTreeMap;
use tokio::sync::Notify;

const TYPE: &str = "place.hud.workspace";
const ME: Who = Who {
    did: DID,
    handle: None,
};

/// What the account's spaces hold, and what they were asked.
#[derive(Default)]
pub(super) struct Spaces {
    /// Whether `describeServer` says it serves the spaces alpha.
    alpha: bool,
    /// The spaces, by URI: each its records, by `collection/rkey`.
    held: BTreeMap<String, BTreeMap<String, Value>>,
    /// The writes asked, each as `<method> <space or collection/rkey>`.
    writes: Vec<String>,
    /// How many writes from now on fail, with a 500.
    failing: usize,
    /// An error `listSpaces` answers, with a 400.
    refuse: Option<String>,
    /// The most a listing's page holds, below what is asked.
    page: usize,
    /// What `describeServer` answers instead, if set: its status and body.
    describe: Option<(u16, String)>,
    /// How often `describeServer` was asked.
    described: usize,
    /// What a listing answers instead, if set: its method and answer.
    answer: Option<(String, Value)>,
    /// Whether `listSpaces` answers more than HUD reads.
    huge: bool,
    /// Whether `deleteRecord` answers with no body.
    bare: bool,
    /// A write held until released.
    hold: Option<Hold>,
}

/// A write held: its method's name, the space it is to, told when it came
/// and waiting to be released.
struct Hold {
    write: &'static str,
    space: String,
    arrived: Arc<Notify>,
    release: Arc<Notify>,
}

impl Spaces {
    fn record(&self, space: &str, key: &str) -> Option<&Value> {
        self.held.get(space)?.get(key)
    }

    fn count(&self, write: &str) -> usize {
        self.writes.iter().filter(|w| w.as_str() == write).count()
    }
}

pub(super) fn routes(r: Router<Fake>) -> Router<Fake> {
    r.route(
        "/xrpc/com.atproto.server.describeServer",
        get(describe_server),
    )
    .route("/xrpc/com.atproto.space.createSpace", post(create_space))
    .route("/xrpc/com.atproto.space.deleteSpace", post(delete_space))
    .route("/xrpc/com.atproto.space.putRecord", post(put_record))
    .route("/xrpc/com.atproto.space.deleteRecord", post(delete_record))
    .route("/xrpc/com.atproto.space.listRecords", get(list_records))
    .route("/xrpc/com.atproto.space.listSpaces", get(list_spaces))
}

async fn describe_server(State(f): State<Fake>) -> Response {
    let mut w = f.lock().unwrap();
    w.spaces.described += 1;
    if let Some((status, body)) = w.spaces.describe.clone() {
        return (StatusCode::from_u16(status).unwrap(), body).into_response();
    }
    let mut v = json!({ "did": "did:web:pds.test", "availableUserDomains": [] });
    if w.spaces.alpha {
        v["spacesAlpha"] = json!(true);
    }
    json_response(StatusCode::OK, v, "-")
}

/// Hold the next write of `write` to the space `space` until released:
/// told when it comes, and the release.
fn hold(f: &Fake, write: &'static str, space: &str) -> (Arc<Notify>, Arc<Notify>) {
    let (arrived, release) = (Arc::new(Notify::new()), Arc::new(Notify::new()));
    f.lock().unwrap().spaces.hold = Some(Hold {
        write,
        space: space.to_string(),
        arrived: arrived.clone(),
        release: release.clone(),
    });
    (arrived, release)
}

/// A write, held if it is the one to hold.
async fn held(f: &Fake, write: &str, body: &str) {
    let space = serde_json::from_str::<Value>(body).unwrap()["space"]
        .as_str()
        .unwrap()
        .to_string();
    let hold = f
        .lock()
        .unwrap()
        .spaces
        .hold
        .take_if(|h| h.write == write && h.space == space);
    if let Some(h) = hold {
        h.arrived.notify_one();
        h.release.notified().await;
    }
}

/// A space call as the account: its token and proof as the PDS checks
/// them, and its grant's `space:` permission of HUD's workspace type (with
/// `manage`, that too); else the answer refusing it, as the alpha does.
fn unauthorized(
    w: &mut World,
    headers: &HeaderMap,
    htm: &str,
    method: &str,
    manage: Option<&str>,
) -> Option<Response> {
    let nonce = w.nonce.clone();
    let token = headers
        .get("authorization")
        .and_then(|a| a.to_str().ok())
        .and_then(|a| a.strip_prefix("DPoP "))
        .unwrap_or_default()
        .to_string();
    if token != w.access {
        return Some(json_response(
            StatusCode::UNAUTHORIZED,
            json!({ "error": "invalid_token" }),
            &nonce,
        ));
    }
    let htu = format!("{}/xrpc/{method}", base(headers));
    if let Some(r) = check_dpop(w, headers, htm, &htu, Some(&token)) {
        return Some(r);
    }
    let granted = w.granted.clone().unwrap_or_else(|| w.scope.clone());
    let allowed = granted.split_whitespace().any(|t| {
        t.strip_prefix("space:")
            .is_some_and(|rest| rest == TYPE || rest.starts_with(&format!("{TYPE}?")))
            && manage.is_none_or(|m| t.contains(&format!("manage={m}")))
    });
    if !allowed {
        return Some(json_response(
            StatusCode::FORBIDDEN,
            json!({ "error": "ScopeMissingError",
                    "message": format!("Missing required scope \"space:{TYPE}?authority={DID}\"") }),
            &nonce,
        ));
    }
    None
}

/// A write that is to fail, failed.
fn failing(w: &mut World) -> Option<Response> {
    if w.spaces.failing == 0 {
        return None;
    }
    w.spaces.failing -= 1;
    let nonce = w.nonce.clone();
    Some(json_response(
        StatusCode::INTERNAL_SERVER_ERROR,
        json!({ "error": "InternalServerError" }),
        &nonce,
    ))
}

fn refused(w: &World, error: &str) -> Response {
    json_response(StatusCode::BAD_REQUEST, json!({ "error": error }), &w.nonce)
}

/// Whether a value is in the data model: no number but integers.
fn whole(v: &Value) -> bool {
    match v {
        Value::Number(n) => n.is_i64() || n.is_u64(),
        Value::Array(a) => a.iter().all(whole),
        Value::Object(o) => o.values().all(whole),
        _ => true,
    }
}

async fn create_space(State(f): State<Fake>, headers: HeaderMap, body: String) -> Response {
    let mut w = f.lock().unwrap();
    let method = "com.atproto.space.createSpace";
    if let Some(r) = unauthorized(&mut w, &headers, "POST", method, Some("create")) {
        return r;
    }
    if let Some(r) = failing(&mut w) {
        return r;
    }
    let input: Value = serde_json::from_str(&body).unwrap();
    assert_eq!(input["policy"]["$type"], "com.atproto.personalspace.policy");
    let uri = format!(
        "at://{DID}/space/{}/{}",
        input["spaceType"].as_str().unwrap(),
        input["skey"].as_str().unwrap()
    );
    w.spaces.writes.push(format!("createSpace {uri}"));
    if w.spaces.held.contains_key(&uri) {
        return refused(&w, "SpaceAlreadyExists");
    }
    w.spaces.held.insert(uri.clone(), BTreeMap::new());
    json_response(StatusCode::OK, json!({ "space": uri }), &w.nonce)
}

async fn delete_space(State(f): State<Fake>, headers: HeaderMap, body: String) -> Response {
    let mut w = f.lock().unwrap();
    let method = "com.atproto.space.deleteSpace";
    if let Some(r) = unauthorized(&mut w, &headers, "POST", method, Some("delete")) {
        return r;
    }
    if let Some(r) = failing(&mut w) {
        return r;
    }
    let input: Value = serde_json::from_str(&body).unwrap();
    let uri = input["space"].as_str().unwrap().to_string();
    w.spaces.writes.push(format!("deleteSpace {uri}"));
    match w.spaces.held.remove(&uri) {
        Some(_) => json_response(StatusCode::OK, json!({}), &w.nonce),
        None => refused(&w, "SpaceNotFound"),
    }
}

async fn put_record(State(f): State<Fake>, headers: HeaderMap, body: String) -> Response {
    held(&f, "putRecord", &body).await;
    let mut w = f.lock().unwrap();
    let method = "com.atproto.space.putRecord";
    if let Some(r) = unauthorized(&mut w, &headers, "POST", method, None) {
        return r;
    }
    if let Some(r) = failing(&mut w) {
        return r;
    }
    let input: Value = serde_json::from_str(&body).unwrap();
    assert_eq!(input["repo"], DID);
    let collection = input["collection"].as_str().unwrap();
    let key = format!("{collection}/{}", input["rkey"].as_str().unwrap());
    let record = input["record"].clone();
    if record["$type"] != collection || !whole(&record) {
        return refused(&w, "InvalidRequest");
    }
    w.spaces.writes.push(format!("putRecord {key}"));
    let nonce = w.nonce.clone();
    match w.spaces.held.get_mut(input["space"].as_str().unwrap()) {
        Some(records) => {
            records.insert(key, record);
            json_response(
                StatusCode::OK,
                json!({ "uri": "at://x", "cid": CID }),
                &nonce,
            )
        }
        None => refused(&w, "SpaceNotFound"),
    }
}

async fn delete_record(State(f): State<Fake>, headers: HeaderMap, body: String) -> Response {
    held(&f, "deleteRecord", &body).await;
    let mut w = f.lock().unwrap();
    let method = "com.atproto.space.deleteRecord";
    if let Some(r) = unauthorized(&mut w, &headers, "POST", method, None) {
        return r;
    }
    if let Some(r) = failing(&mut w) {
        return r;
    }
    let input: Value = serde_json::from_str(&body).unwrap();
    let key = format!(
        "{}/{}",
        input["collection"].as_str().unwrap(),
        input["rkey"].as_str().unwrap()
    );
    w.spaces.writes.push(format!("deleteRecord {key}"));
    if let Some(records) = w.spaces.held.get_mut(input["space"].as_str().unwrap()) {
        records.remove(&key);
    }
    if w.spaces.bare {
        return StatusCode::OK.into_response();
    }
    json_response(StatusCode::OK, json!({}), &w.nonce)
}

/// A page of `keys`, in their order, after `cursor`: those of it, and the
/// cursor of the next page when this one is full.
fn page(
    keys: Vec<String>,
    q: &HashMap<String, String>,
    most: usize,
    after: impl Fn(&str, &str) -> bool,
) -> (Vec<String>, Option<String>) {
    let limit: usize = q["limit"].parse().unwrap();
    let limit = if most > 0 { limit.min(most) } else { limit };
    let page: Vec<String> = keys
        .into_iter()
        .filter(|k| q.get("cursor").is_none_or(|c| after(k, c)))
        .take(limit)
        .collect();
    let cursor = (page.len() == limit)
        .then(|| page.last().cloned())
        .flatten();
    (page, cursor)
}

async fn list_records(
    State(f): State<Fake>,
    headers: HeaderMap,
    axum::extract::RawQuery(q): axum::extract::RawQuery,
) -> Response {
    let mut w = f.lock().unwrap();
    let method = "com.atproto.space.listRecords";
    if let Some(r) = unauthorized(&mut w, &headers, "GET", method, None) {
        return r;
    }
    if let Some(r) = answered(&w, "listRecords") {
        return r;
    }
    let q = form_of(&q.unwrap_or_default());
    assert_eq!(q["repo"], DID);
    let Some(records) = w.spaces.held.get(&q["space"]) else {
        return refused(&w, "SpaceNotFound");
    };
    // Descending, as the alpha lists them.
    let keys: Vec<String> = records.keys().rev().cloned().collect();
    let (keys, cursor) = page(keys, &q, w.spaces.page, |k, c| k < c);
    let listed: Vec<Value> = keys
        .iter()
        .map(|k| {
            let (collection, rkey) = k.split_once('/').unwrap();
            json!({ "collection": collection, "rkey": rkey, "cid": CID, "value": records[k] })
        })
        .collect();
    let mut answer = json!({ "records": listed });
    if let Some(c) = cursor {
        answer["cursor"] = json!(c);
    }
    json_response(StatusCode::OK, answer, &w.nonce)
}

async fn list_spaces(
    State(f): State<Fake>,
    headers: HeaderMap,
    axum::extract::RawQuery(q): axum::extract::RawQuery,
) -> Response {
    let mut w = f.lock().unwrap();
    let method = "com.atproto.space.listSpaces";
    if let Some(r) = unauthorized(&mut w, &headers, "GET", method, None) {
        return r;
    }
    if let Some(e) = w.spaces.refuse.clone() {
        return refused(&w, &e);
    }
    if let Some(r) = answered(&w, "listSpaces") {
        return r;
    }
    if w.spaces.huge {
        let pad = "x".repeat(6 << 20);
        return json_response(
            StatusCode::OK,
            json!({ "spaces": [], "pad": pad }),
            &w.nonce,
        );
    }
    let q = form_of(&q.unwrap_or_default());
    let prefix = format!("at://{}/space/{}/", q["spaceDid"], q["spaceType"]);
    let keys: Vec<String> = w
        .spaces
        .held
        .keys()
        .filter(|k| k.starts_with(&prefix))
        .cloned()
        .collect();
    let (keys, cursor) = page(keys, &q, w.spaces.page, |k, c| k > c);
    let mut answer =
        json!({ "spaces": keys.iter().map(|k| json!({ "space": k })).collect::<Vec<_>>() });
    if let Some(c) = cursor {
        answer["cursor"] = json!(c);
    }
    json_response(StatusCode::OK, answer, &w.nonce)
}

/// The answer a listing gives in place of its own, if one is set.
fn answered(w: &World, listing: &str) -> Option<Response> {
    let (m, v) = w.spaces.answer.as_ref()?;
    (m == listing).then(|| json_response(StatusCode::OK, v.clone(), &w.nonce))
}

// The canvases kept in spaces.

/// HUD with spaces on, at a fake PDS that serves them, a page being two
/// records; and the account signed in.
async fn spaced() -> (Arc<Hud>, Fake, String) {
    let (h, f, base) = world_with(|c| {
        c.spaces = true;
        c.oauth_scope = crate::scope::asked(crate::view::views(), true, true);
    })
    .await;
    {
        let mut w = f.lock().unwrap();
        w.spaces.alpha = true;
        w.spaces.page = 2;
    }
    (h, f, base)
}

async fn sign_in(h: &Hud, f: &Fake, base: &str) {
    let id = client(h);
    signed_in(h, f, base, &id).await;
}

fn space_of(id: &str) -> String {
    format!("at://{DID}/space/{TYPE}/{id}")
}

fn add() -> Op {
    Op::Add {
        tool: "describe_repo".into(),
        arguments: json!({ "actor": "alice.test" }),
        title: None,
        from: None,
        after: None,
        stack: None,
        width: None,
    }
}

/// A canvas of the account's in a file of the server's, as from before
/// spaces, with `members` besides its owner, and two tiles.
fn file_canvas(h: &Hud, id: &str, name: &str, members: &[&str]) -> (CanvasInfo, Vec<Tile>) {
    let member = |did: &str, role| Member {
        did: did.into(),
        handle: None,
        role,
        joined: true,
        invited_by: None,
    };
    let mut all = vec![member(DID, Role::Owner)];
    all.extend(members.iter().map(|m| member(m, Role::Editor)));
    let info = CanvasInfo {
        id: id.into(),
        name: name.into(),
        owner: DID.into(),
        members: all,
        created_at: "2026-11-14T00:00:00.000Z".into(),
        updated_at: "2026-11-14T00:00:00.000Z".into(),
    };
    let tile = |n: u8| Tile {
        id: format!("00000000000{n}"),
        tool: "describe_repo".into(),
        arguments: json!({ "actor": "alice.test" }),
        title: format!("tile {n}"),
        order: f64::from(n),
        width: Width::Third,
        stack: None,
        by: By::Person,
        author: DID.into(),
        at: format!("2026-11-14T00:00:0{n}.000Z"),
        from: (n > 1).then(|| "000000000001".into()),
    };
    let tiles = vec![tile(1), tile(2)];
    FileStore::new(h.config.data_dir.join("canvas"))
        .put(&info, &tiles)
        .unwrap();
    (info, tiles)
}

/// The canvases a person's list shows, by id: each its storage.
async fn storages(h: &Hud) -> HashMap<String, Value> {
    h.canvases
        .list(ME)
        .await
        .into_iter()
        .map(|(_, c)| (c["key"].as_str().unwrap().to_string(), c["storage"].clone()))
        .collect()
}

#[tokio::test]
async fn where_canvases_go_and_why() {
    // A PDS that says nothing of spaces.
    let (h, f, base) = spaced().await;
    f.lock().unwrap().spaces.alpha = false;
    sign_in(&h, &f, &base).await;
    let kept = storages(&h).await;
    assert_eq!(
        kept.values().next().unwrap(),
        &json!({ "kind": "file", "reason": "your PDS does not offer spaces" })
    );
    assert!(f.lock().unwrap().spaces.writes.is_empty());

    // A sign-in without the space permission: told to sign in again; and
    // once it does, with it, decided again, and the canvas moves in.
    let (h, f, base) = spaced().await;
    f.lock().unwrap().granted = Some("atproto transition:generic".into());
    sign_in(&h, &f, &base).await;
    let kept = storages(&h).await;
    let (id, storage) = kept.iter().next().unwrap();
    assert!(
        storage["reason"]
            .as_str()
            .unwrap()
            .starts_with("sign in again to keep your canvases in your own PDS"),
        "{storage}"
    );
    f.lock().unwrap().granted = None;
    sign_in(&h, &f, &base).await;
    assert_eq!(
        storages(&h).await[id],
        json!({ "kind": "space", "uri": space_of(id) })
    );

    // A PDS that refuses the first call.
    let (h, f, base) = spaced().await;
    f.lock().unwrap().spaces.refuse = Some("AccountNotAuthorized".into());
    sign_in(&h, &f, &base).await;
    assert_eq!(
        storages(&h).await.values().next().unwrap(),
        &json!({ "kind": "file", "reason": "your PDS refused: AccountNotAuthorized (400)" })
    );
    assert!(f.lock().unwrap().spaces.writes.is_empty());

    // With spaces off, the scope asks for none.
    let (h, _f, _base) = world().await;
    assert!(!h.config.oauth_scope.contains("space:"));
}

#[tokio::test]
async fn canvases_moved_in_written_and_read_back() {
    let (h, f, base) = spaced().await;
    // From before: one canvas of the account's alone, one shared.
    let (mine, before) = file_canvas(&h, "0000000000aa", "Mine", &[]);
    let (shared, _) = file_canvas(&h, "0000000000bb", "Ours", &[OTHER]);
    sign_in(&h, &f, &base).await;
    let kept = storages(&h).await;
    let space = space_of(&mine.id);
    // The one alone moved in whole, its file put aside; the shared one
    // stays, and says why.
    assert_eq!(kept[&mine.id], json!({ "kind": "space", "uri": space }));
    assert_eq!(
        kept[&shared.id],
        json!({ "kind": "file", "reason": "a canvas shared with others stays on this HUD server" })
    );
    let dir = h.config.data_dir.join("canvas");
    assert!(!dir.join("0000000000aa.json").exists());
    assert!(dir.join("0000000000aa.json.moved").exists());
    assert!(dir.join("0000000000bb.json").exists());
    {
        let w = f.lock().unwrap();
        let s = &w.spaces;
        assert_eq!(s.count(&format!("createSpace {space}")), 1);
        let me = s.record(&space, "place.hud.canvas/self").unwrap();
        assert_eq!(me["name"], "Mine");
        let t = s.record(&space, "place.hud.tile/000000000002").unwrap();
        assert_eq!(
            (&t["order"], &t["from"], &t["title"]),
            (&json!("2"), &json!("000000000001"), &json!("tile 2"))
        );
        assert!(!s.held.keys().any(|k| k.ends_with("0000000000bb")));
    }
    // Writes as they are made.
    let t = h
        .canvases
        .apply(ME, &mine.id, add(), By::Agent)
        .await
        .unwrap();
    let key = format!("place.hud.tile/{}", t.id);
    assert!(f.lock().unwrap().spaces.record(&space, &key).is_some());
    // Places and widths put off: written once, a second after the last,
    // or when flushed, as they last were.
    let width = |width: Width| Op::Width {
        id: t.id.clone(),
        width,
    };
    let put = format!("putRecord {key}");
    for w in [Width::Half, Width::Full] {
        h.canvases
            .apply(ME, &mine.id, width(w), By::Person)
            .await
            .unwrap();
    }
    h.canvases
        .apply(
            ME,
            &mine.id,
            Op::Place {
                id: t.id.clone(),
                to: Beside::Before(before[0].id.clone()),
            },
            By::Person,
        )
        .await
        .unwrap();
    assert_eq!(f.lock().unwrap().spaces.count(&put), 1);
    h.canvases.flush().await;
    {
        let w = f.lock().unwrap();
        assert_eq!(w.spaces.count(&put), 2);
        let r = w.spaces.record(&space, &key).unwrap();
        assert_eq!((&r["order"], &r["width"]), (&json!("0"), &json!("full")));
    }
    h.canvases
        .apply(ME, &mine.id, width(Width::Half), By::Person)
        .await
        .unwrap();
    tokio::time::sleep(std::time::Duration::from_millis(400)).await;
    assert_eq!(f.lock().unwrap().spaces.count(&put), 2, "not yet");
    tokio::time::sleep(std::time::Duration::from_millis(1100)).await;
    assert_eq!(f.lock().unwrap().spaces.count(&put), 3, "a second after");
    // A title at once; a tile taken off, its record deleted.
    h.canvases
        .apply(
            ME,
            &mine.id,
            Op::Update {
                id: t.id.clone(),
                title: Some("Retitled".into()),
                call: None,
            },
            By::Person,
        )
        .await
        .unwrap();
    assert_eq!(f.lock().unwrap().spaces.count(&put), 4);
    h.canvases
        .apply(
            ME,
            &mine.id,
            Op::Remove {
                id: before[0].id.clone(),
            },
            By::Person,
        )
        .await
        .unwrap();
    assert_eq!(
        f.lock()
            .unwrap()
            .spaces
            .count("deleteRecord place.hud.tile/000000000001"),
        1
    );
    // Read back by a server started again: from the space, page by page,
    // every tile as it was.
    let tiles = h.canvases.tiles(ME, &mine.id).await.unwrap();
    let again = Hud::new(h.config.clone()).unwrap();
    assert_eq!(storages(&again).await[&mine.id]["kind"], "space");
    assert_eq!(again.canvases.tiles(ME, &mine.id).await.unwrap(), tiles);
    assert_eq!(tiles.len(), 2);
    // A new canvas goes in a space of its own; shared, it comes out, its
    // space deleted; alone again, it goes back in.
    let made = again
        .canvases
        .create(ME, "Fresh", By::Person)
        .await
        .unwrap();
    let fresh = space_of(&made.id);
    assert!(f.lock().unwrap().spaces.held.contains_key(&fresh));
    again
        .canvases
        .invite(ME, &made.id, OTHER, None, Role::Viewer)
        .await
        .unwrap();
    assert!(!f.lock().unwrap().spaces.held.contains_key(&fresh));
    assert_eq!(storages(&again).await[&made.id]["kind"], "file");
    again.canvases.remove(ME, &made.id, OTHER).await.unwrap();
    assert!(f.lock().unwrap().spaces.held.contains_key(&fresh));
    // Deleting a canvas deletes its space.
    again.canvases.delete(ME, &mine.id).await.unwrap();
    assert!(!f.lock().unwrap().spaces.held.contains_key(&space));
    assert!(!storages(&again).await.contains_key(&mine.id));
}

#[tokio::test]
async fn failures_tried_again_then_back_to_files() {
    let (h, f, base) = spaced().await;
    sign_in(&h, &f, &base).await;
    let id = h.canvases.resolve(ME, None).await.unwrap();
    let space = space_of(&id);
    assert_eq!(storages(&h).await[&id]["kind"], "space");
    // A write fails: the tile stays, and goes with the next change.
    f.lock().unwrap().spaces.failing = 1;
    let lost = h.canvases.apply(ME, &id, add(), By::Person).await.unwrap();
    let key = |t: &Tile| format!("place.hud.tile/{}", t.id);
    assert!(
        f.lock()
            .unwrap()
            .spaces
            .record(&space, &key(&lost))
            .is_none()
    );
    let next = h.canvases.apply(ME, &id, add(), By::Person).await.unwrap();
    {
        let w = f.lock().unwrap();
        assert!(w.spaces.record(&space, &key(&lost)).is_some());
        assert!(w.spaces.record(&space, &key(&next)).is_some());
    }
    // Three in a row: the canvas goes back to the server's files, as
    // memory holds it, and its pages are told.
    let mut told = h.canvases.watch(ME).await;
    f.lock().unwrap().spaces.failing = 100;
    for _ in 0..2 {
        h.canvases.apply(ME, &id, add(), By::Person).await.unwrap();
        assert_eq!(storages(&h).await[&id]["kind"], "space");
    }
    let last = h.canvases.apply(ME, &id, add(), By::Person).await.unwrap();
    let storage = &storages(&h).await[&id];
    assert_eq!(storage["kind"], "file");
    assert!(
        storage["reason"]
            .as_str()
            .unwrap()
            .starts_with("writing to your PDS failed 3 times in a row"),
        "{storage}"
    );
    let heard: Vec<Notice> = std::iter::from_fn(|| told.notices.try_recv().ok()).collect();
    assert!(
        heard
            .iter()
            .any(|n| matches!(n, Notice::Canvases { canvas: None, .. })),
        "{heard:?}"
    );
    let file = h.config.data_dir.join("canvas").join(format!("{id}.json"));
    let kept: Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap();
    assert_eq!(kept["tiles"].as_array().unwrap().len(), 5);
    assert_eq!(h.canvases.tiles(ME, &id).await.unwrap().last(), Some(&last));
    // From then on, to the files alone.
    let asked = f.lock().unwrap().spaces.writes.len();
    h.canvases.apply(ME, &id, add(), By::Person).await.unwrap();
    assert_eq!(f.lock().unwrap().spaces.writes.len(), asked);
}

#[tokio::test]
async fn a_persons_canvases_and_spaces_forgotten() {
    let (h, f, base) = spaced().await;
    let (mine, _) = file_canvas(&h, "0000000000aa", "Mine", &[]);
    let (shared, _) = file_canvas(&h, "0000000000bb", "Ours", &[OTHER]);
    sign_in(&h, &f, &base).await;
    let fresh = h.canvases.create(ME, "Fresh", By::Person).await.unwrap();
    assert_eq!(storages(&h).await[&fresh.id]["kind"], "space");
    // A space of theirs no canvas is read from, left from before.
    let stray = space_of("0000000000cc");
    f.lock().unwrap().spaces.held.insert(
        stray.clone(),
        BTreeMap::from([("place.hud.tile/000000000001".to_string(), json!({}))]),
    );
    let held = h.canvases.holding(ME).await;
    assert_eq!(
        held.owned,
        [
            (mine.id.clone(), "Mine".to_string(), 0),
            (shared.id.clone(), "Ours".to_string(), 1),
            (fresh.id.clone(), "Fresh".to_string(), 0),
        ]
    );
    // Its PDS failing: the canvases go, but their spaces do not, and it
    // says so.
    f.lock().unwrap().spaces.failing = 100;
    let why = h.canvases.forget(ME).await.unwrap_err();
    assert!(why.contains("was not deleted"), "{why}");
    // What is still in their spaces is read back, to be deleted again.
    let names: Vec<String> = h
        .canvases
        .holding(ME)
        .await
        .owned
        .into_iter()
        .map(|(_, name, _)| name)
        .collect();
    assert_eq!(names, ["Mine", "Fresh"]);
    // Asked again: every workspace space of theirs deleted, and every
    // file of theirs.
    f.lock().unwrap().spaces.failing = 0;
    h.canvases.forget(ME).await.unwrap();
    let w = f.lock().unwrap();
    let left: Vec<&String> = w.spaces.held.keys().filter(|k| k.contains(TYPE)).collect();
    assert!(left.is_empty(), "{left:?}");
    assert_eq!(w.spaces.count(&format!("deleteSpace {stray}")), 1);
    drop(w);
    let dir = h.config.data_dir.join("canvas");
    for file in [
        "0000000000aa.json.moved".to_string(),
        "0000000000bb.json".to_string(),
        format!("by-did/{}.json", jose::sha256(DID)),
    ] {
        assert!(!dir.join(&file).exists(), "{file}");
    }
}

#[tokio::test]
async fn a_persons_spaces_forgotten_as_their_pds_answers() {
    let (h, f, base) = spaced().await;
    sign_in(&h, &f, &base).await;
    let forget = async || h.canvases.forget(ME).await;
    // A grant that does not delete spaces: a space of theirs emptied of
    // its records instead.
    let stray = space_of("0000000000cc");
    {
        let mut w = f.lock().unwrap();
        w.spaces.held.insert(
            stray.clone(),
            BTreeMap::from([("place.hud.tile/000000000001".to_string(), json!({}))]),
        );
        w.granted = Some(format!(
            "atproto transition:generic space:{TYPE}?authority=*&manage=create&manage=update"
        ));
    }
    forget().await.unwrap();
    assert_eq!(
        f.lock().unwrap().spaces.held.get(&stray),
        Some(&BTreeMap::new())
    );
    f.lock().unwrap().granted = None;
    // Spaces listed that are not theirs, or not workspaces: left alone.
    let others = [
        format!("at://{OTHER}/space/{TYPE}/0000000000dd"),
        format!("at://{DID}/space/com.example.other/0000000000ee"),
    ];
    f.lock().unwrap().spaces.answer = Some((
        "listSpaces".into(),
        json!({ "spaces": others.iter().map(|s| json!({ "space": s })).collect::<Vec<_>>() }),
    ));
    let asked = f.lock().unwrap().spaces.writes.len();
    forget().await.unwrap();
    assert_eq!(f.lock().unwrap().spaces.writes.len(), asked);
    f.lock().unwrap().spaces.answer = None;
    // Its spaces not listed, or its PDS not reached: said so.
    f.lock().unwrap().spaces.refuse = Some("Nope".into());
    let why = forget().await.unwrap_err();
    assert!(
        why.starts_with("your workspace spaces were not listed: "),
        "{why}"
    );
    f.lock().unwrap().spaces.refuse = None;
    f.lock().unwrap().spaces.describe = Some((500, String::new()));
    assert_eq!(
        forget().await.unwrap_err(),
        "your workspace spaces were not listed: your PDS could not be reached: describeServer answered 500"
    );
    // A PDS without spaces: none to delete.
    {
        let mut w = f.lock().unwrap();
        w.spaces.describe = None;
        w.spaces.alpha = false;
    }
    forget().await.unwrap();
}

/// Every sign-in of the account ended.
async fn sign_out(h: &Hud) {
    let auth = h.auth().unwrap();
    let sids: Vec<String> = auth.lock().sessions.keys().cloned().collect();
    for sid in sids {
        auth.end(&sid).await;
    }
}

/// Signed out, then in again: a sign-in of its own.
async fn sign_in_again(h: &Hud, f: &Fake, base: &str) {
    sign_out(h).await;
    sign_in(h, f, base).await;
}

/// The account, as the canvases' store reaches it.
async fn account(h: &Hud) -> Account {
    h.auth().unwrap().reach(DID, grants).await.unwrap().account
}

/// The keys of the tile records in a space.
fn tiles_in(f: &Fake, space: &str) -> Vec<String> {
    f.lock()
        .unwrap()
        .spaces
        .held
        .get(space)
        .into_iter()
        .flat_map(|r| {
            r.keys()
                .filter(|k| k.starts_with("place.hud.tile/"))
                .cloned()
        })
        .collect()
}

/// Add a tile to a canvas, as a future of its own.
fn add_to(h: &Arc<Hud>, id: &str) -> impl Future<Output = Tile> + Send + 'static {
    let (h, id) = (h.clone(), id.to_string());
    async move { h.canvases.apply(ME, &id, add(), By::Person).await.unwrap() }
}

/// Take a tile off a canvas, as a future of its own.
fn remove_from(h: &Arc<Hud>, id: &str, tile: &str) -> impl Future<Output = Tile> + Send + 'static {
    let (h, id, tile) = (h.clone(), id.to_string(), tile.to_string());
    async move {
        let op = Op::Remove { id: tile };
        h.canvases.apply(ME, &id, op, By::Person).await.unwrap()
    }
}

#[tokio::test]
async fn space_calls_answered_and_refused() {
    let (h, f, base) = spaced().await;
    sign_in(&h, &f, &base).await;
    let me = account(&h).await;
    // A PDS that cannot be asked, or answers what cannot be read.
    assert_eq!(
        h.spaces_alpha("http://[").await,
        Err("http://[ is not a usable PDS".into())
    );
    f.lock().unwrap().spaces.describe = Some((200, "not json".into()));
    assert_eq!(
        h.spaces_alpha(&base).await,
        Err("describeServer answered something unreadable".into())
    );
    // A space made that is there already, or deleted that is gone: done.
    let space = space_of("0123456789ab");
    for _ in 0..2 {
        h.create_space(&me, TYPE, "0123456789ab").await.unwrap();
    }
    assert_eq!(
        f.lock()
            .unwrap()
            .spaces
            .count(&format!("createSpace {space}")),
        2
    );
    for _ in 0..2 {
        h.delete_space(&me, &space).await.unwrap();
    }
    assert!(!f.lock().unwrap().spaces.held.contains_key(&space));
    // An answer with nothing in it is no failure.
    f.lock().unwrap().spaces.bare = true;
    h.delete_space_record(&me, &space, "place.hud.tile", "000000000001")
        .await
        .unwrap();
    // Listings answered otherwise.
    let answer = |listing: &str, v: Value| {
        f.lock().unwrap().spaces.answer = Some((listing.into(), v));
    };
    fn failed<T>(why: &str) -> Result<T, Failure> {
        Err(Failure::Failed(why.into()))
    }
    answer("listSpaces", json!([1]));
    assert_eq!(
        h.spaces_of(&me, TYPE).await,
        failed("com.atproto.space.listSpaces answered something unreadable")
    );
    answer("listSpaces", json!({}));
    assert_eq!(
        h.spaces_of(&me, TYPE).await,
        failed("listSpaces answered no spaces")
    );
    answer("listRecords", json!({}));
    assert_eq!(
        h.space_records(&me, &space).await,
        failed("listRecords answered no records")
    );
    answer("listRecords", json!({ "records": [{ "collection": "x" }] }));
    assert_eq!(
        h.space_records(&me, &space).await,
        failed("listRecords answered a record that is not one")
    );
    f.lock().unwrap().spaces.answer = None;
    // Page by page, every one; past fifty pages, refused.
    let first = space_of("000000000000");
    {
        let mut w = f.lock().unwrap();
        w.spaces.page = 1;
        for n in 0..3 {
            w.spaces
                .held
                .insert(space_of(&format!("{n:012x}")), BTreeMap::new());
        }
    }
    assert_eq!(h.spaces_of(&me, TYPE).await.unwrap().len(), 3);
    {
        let mut w = f.lock().unwrap();
        for n in 3..=50 {
            w.spaces
                .held
                .insert(space_of(&format!("{n:012x}")), BTreeMap::new());
        }
        let records = w.spaces.held.get_mut(&first).unwrap();
        for n in 0..=50 {
            records.insert(format!("place.hud.tile/{n:012x}"), json!({}));
        }
    }
    assert_eq!(
        h.spaces_of(&me, TYPE).await,
        Err(Failure::Failed(format!("more than 5000 spaces of {TYPE}")))
    );
    assert_eq!(
        h.space_records(&me, &first).await,
        Err(Failure::Failed(format!(
            "{first} holds more than 5000 records"
        )))
    );
    // An answer too large to read: as one that never came.
    f.lock().unwrap().spaces.huge = true;
    assert!(matches!(
        h.spaces_of(&me, TYPE).await,
        Err(Failure::Failed(_))
    ));
    f.lock().unwrap().spaces.huge = false;
    // The sign-in ended at the PDS: signed out.
    {
        let mut w = f.lock().unwrap();
        w.access = "gone".into();
        w.refresh = "gone".into();
    }
    assert_eq!(h.spaces_of(&me, TYPE).await, Err(Failure::SignedOut));
}

#[tokio::test]
async fn decided_for_want_of_an_answer() {
    let (h, f, base) = spaced().await;
    f.lock().unwrap().spaces.describe = Some((500, String::new()));
    sign_in(&h, &f, &base).await;
    let unreached = json!({ "kind": "file",
        "reason": "your PDS could not be reached: describeServer answered 500" });
    assert_eq!(storages(&h).await.values().next().unwrap(), &unreached);
    // Asked again a minute later, not before.
    let asked = f.lock().unwrap().spaces.described;
    assert_eq!(storages(&h).await.values().next().unwrap(), &unreached);
    assert_eq!(f.lock().unwrap().spaces.described, asked);
    // Someone with no sign-in: their canvases in files, and why.
    let other = Who {
        did: OTHER,
        handle: None,
    };
    assert_eq!(
        h.canvases.list(other).await[0].1["storage"],
        json!({ "kind": "file", "reason": "no sign-in of yours reaches your PDS" })
    );
    // A PDS refusing the sign-in's permission to list them: sign in again.
    let (h, f, base) = spaced().await;
    f.lock().unwrap().spaces.refuse = Some("ScopeMissingError".into());
    sign_in(&h, &f, &base).await;
    let kept = storages(&h).await;
    let reason = kept.values().next().unwrap()["reason"].as_str().unwrap();
    assert!(
        reason.starts_with("sign in again to keep your canvases in your own PDS"),
        "{reason}"
    );
}

#[tokio::test]
async fn spaces_read_as_found() {
    let (h, f, base) = spaced().await;
    let info = |name: &str| {
        json!({ "$type": "place.hud.canvas", "name": name,
                "createdAt": "2026-11-14T00:00:00.000Z", "updatedAt": "2026-11-14T00:00:00.000Z" })
    };
    let old = json!({ "$type": "place.hud.tile", "tool": "describe_repo",
        "arguments": { "actor": "alice.test" }, "title": "old", "x": 0, "y": 0, "w": 420,
        "h": 560, "by": "agent", "createdAt": "2026-11-14T12:00:00.000Z" });
    let me = "place.hud.canvas/self".to_string();
    let tile = "place.hud.tile/000000000001".to_string();
    {
        let mut w = f.lock().unwrap();
        // One from before columns, two since; one with no canvas, and two
        // that are no canvas's.
        let held = &mut w.spaces.held;
        held.insert(
            space_of("0000000000a1"),
            BTreeMap::from([(me.clone(), info("Old")), (tile.clone(), old.clone())]),
        );
        // Another, made columns and written as read.
        held.insert(
            space_of("0000000000a5"),
            BTreeMap::from([
                (me.clone(), info("Also old")),
                ("place.hud.tile/000000000002".into(), old),
            ]),
        );
        held.insert(
            space_of("0000000000a2"),
            BTreeMap::from([(me.clone(), info("Two"))]),
        );
        held.insert(
            space_of("0000000000a3"),
            BTreeMap::from([(me.clone(), info("Three"))]),
        );
        held.insert(space_of("0000000000a4"), BTreeMap::new());
        held.insert(space_of("not-an-id"), BTreeMap::new());
        held.insert(format!("at://{DID}/space/{TYPE}/a/b"), BTreeMap::new());
        // Made columns as read, the first's write fails.
        w.spaces.failing = 1;
    }
    sign_in(&h, &f, &base).await;
    let kept = storages(&h).await;
    let mut ids: Vec<&String> = kept.keys().collect();
    ids.sort();
    assert_eq!(
        ids,
        [
            "0000000000a1",
            "0000000000a2",
            "0000000000a3",
            "0000000000a5"
        ]
    );
    assert_eq!(
        f.lock()
            .unwrap()
            .spaces
            .count("putRecord place.hud.tile/000000000002"),
        1
    );
    let put = format!("putRecord {tile}");
    assert_eq!(f.lock().unwrap().spaces.count(&put), 0);
    // Written with the canvas's next change: renamed, at once.
    h.canvases
        .rename(ME, "0000000000a1", "Older")
        .await
        .unwrap();
    {
        let w = f.lock().unwrap();
        let space = space_of("0000000000a1");
        assert_eq!(w.spaces.count(&put), 1);
        assert_eq!(w.spaces.record(&space, &tile).unwrap()["order"], "1");
        assert_eq!(w.spaces.record(&space, &me).unwrap()["name"], "Older");
    }
    // Signed in again: those kept, as memory holds them.
    sign_in_again(&h, &f, &base).await;
    let names: Vec<Value> = h
        .canvases
        .list(ME)
        .await
        .into_iter()
        .map(|(_, c)| c["record"]["name"].clone())
        .collect();
    assert!(names.contains(&json!("Older")), "{names:?}");
    assert_eq!(names.len(), 4);
}

#[tokio::test]
async fn canvases_back_in_files_mid_write() {
    let (h, f, base) = spaced().await;
    sign_in(&h, &f, &base).await;
    let x = h.canvases.resolve(ME, None).await.unwrap();
    let y = h.canvases.create(ME, "Other", By::Person).await.unwrap().id;
    let (xs, ys) = (space_of(&x), space_of(&y));
    assert_eq!(storages(&h).await[&y]["kind"], "space");
    // A write of X's fails, to go with the next, which the PDS holds.
    f.lock().unwrap().spaces.failing = 1;
    add_to(&h, &x).await;
    let (arrived, release) = hold(&f, "putRecord", &xs);
    let writing = tokio::spawn(add_to(&h, &x));
    arrived.notified().await;
    // Meanwhile two of Y's fail: three in a row, back to files.
    f.lock().unwrap().spaces.failing = 2;
    add_to(&h, &y).await;
    add_to(&h, &y).await;
    assert_eq!(storages(&h).await[&x]["kind"], "file");
    // The write held goes through; no more of X is written to its space.
    release.notify_one();
    writing.await.unwrap();
    assert_eq!(tiles_in(&f, &xs).len(), 1);

    // Signed in again: each back in its space, there already.
    sign_in_again(&h, &f, &base).await;
    let kept = storages(&h).await;
    assert_eq!(
        (&kept[&x]["kind"], &kept[&y]["kind"]),
        (&json!("space"), &json!("space"))
    );
    assert_eq!(tiles_in(&f, &xs).len(), 2);
    // A tile's record not deleted, to go with the next deletion, held.
    let tiles = h.canvases.tiles(ME, &x).await.unwrap();
    f.lock().unwrap().spaces.failing = 1;
    remove_from(&h, &x, &tiles[0].id).await;
    assert_eq!(tiles_in(&f, &xs).len(), 2);
    let (arrived, release) = hold(&f, "deleteRecord", &xs);
    let deleting = tokio::spawn(remove_from(&h, &x, &tiles[1].id));
    arrived.notified().await;
    f.lock().unwrap().spaces.failing = 2;
    add_to(&h, &y).await;
    add_to(&h, &y).await;
    assert_eq!(storages(&h).await[&x]["kind"], "file");
    // Its deletions go through all the same.
    release.notify_one();
    deleting.await.unwrap();
    assert!(tiles_in(&f, &xs).is_empty());

    // Y deleted while in a file: its space deleted at the next sign-in.
    h.canvases.delete(ME, &y).await.unwrap();
    assert!(f.lock().unwrap().spaces.held.contains_key(&ys));
    sign_in_again(&h, &f, &base).await;
    storages(&h).await;
    assert!(!f.lock().unwrap().spaces.held.contains_key(&ys));
}

#[tokio::test]
async fn spaces_not_deleted_deleted_later() {
    let (h, f, base) = spaced().await;
    sign_in(&h, &f, &base).await;
    let a = h.canvases.resolve(ME, None).await.unwrap();
    let b = h.canvases.create(ME, "B", By::Person).await.unwrap().id;
    let c = h.canvases.create(ME, "C", By::Person).await.unwrap().id;
    let held = |id: &str| f.lock().unwrap().spaces.held.contains_key(&space_of(id));
    // The PDS failing: A's space left, to delete later.
    f.lock().unwrap().spaces.failing = 1;
    h.canvases.delete(ME, &a).await.unwrap();
    assert!(held(&a));
    // Signed out: B's change not written, and its space left too.
    sign_out(&h).await;
    h.canvases.apply(ME, &b, add(), By::Person).await.unwrap();
    assert!(tiles_in(&f, &space_of(&b)).is_empty());
    h.canvases.delete(ME, &b).await.unwrap();
    assert!(held(&b));
    // Signed in again: both deleted then; C read as it was.
    sign_in(&h, &f, &base).await;
    assert_eq!(storages(&h).await[&c]["kind"], "space");
    assert!(!held(&a) && !held(&b));
    // A grant that does not delete spaces: their records deleted instead,
    // and where one is not, the space left to delete later.
    f.lock().unwrap().granted = Some(format!(
        "atproto transition:generic space:{TYPE}?authority=*&manage=create&manage=update"
    ));
    let d = h.canvases.create(ME, "D", By::Person).await.unwrap().id;
    add_to(&h, &d).await;
    h.canvases.delete(ME, &d).await.unwrap();
    assert_eq!(
        f.lock().unwrap().spaces.held.get(&space_of(&d)),
        Some(&BTreeMap::new())
    );
    f.lock().unwrap().spaces.failing = 1;
    h.canvases.delete(ME, &c).await.unwrap();
    assert!(held(&c));
    // Its deletion refused again at the next sign-in: left still.
    sign_in_again(&h, &f, &base).await;
    storages(&h).await;
    assert!(held(&c));
    f.lock().unwrap().granted = None;
    sign_in_again(&h, &f, &base).await;
    storages(&h).await;
    assert!(!held(&c));
}

#[tokio::test]
async fn moves_in_put_off_and_places_written_again() {
    let (h, f, base) = spaced().await;
    sign_in(&h, &f, &base).await;
    // Its space not made: in its file still, and said so.
    f.lock().unwrap().spaces.failing = 1;
    let id = h.canvases.resolve(ME, None).await.unwrap();
    assert_eq!(
        storages(&h).await[&id],
        json!({ "kind": "file", "reason": "not in your PDS yet: it moves there with its next change" })
    );
    // Signed out, it does not move with its next change.
    sign_out(&h).await;
    let t = add_to(&h, &id).await;
    let space = space_of(&id);
    assert!(!f.lock().unwrap().spaces.held.contains_key(&space));
    // Signed in again, it moves, though its file cannot be put aside.
    let file = h.config.data_dir.join("canvas").join(format!("{id}.json"));
    std::fs::create_dir_all(file.with_extension("json.moved").join("x")).unwrap();
    sign_in(&h, &f, &base).await;
    assert_eq!(storages(&h).await[&id]["kind"], "space");
    assert!(file.exists());
    // A place whose write fails: left to the next change.
    let key = format!("place.hud.tile/{}", t.id);
    let put = format!("putRecord {key}");
    let width = |width| Op::Width {
        id: t.id.clone(),
        width,
    };
    let placed = |w: Width| {
        let (h, op) = (h.clone(), width(w));
        let id = id.clone();
        async move { h.canvases.apply(ME, &id, op, By::Person).await.unwrap() }
    };
    let written = f.lock().unwrap().spaces.count(&put);
    placed(Width::Half).await;
    f.lock().unwrap().spaces.failing = 1;
    h.canvases.flush().await;
    assert_eq!(f.lock().unwrap().spaces.count(&put), written);
    // Placed again while its place is written: written again.
    placed(Width::Full).await;
    let (arrived, release) = hold(&f, "putRecord", &space);
    let flushing = {
        let h = h.clone();
        tokio::spawn(async move { h.canvases.flush().await })
    };
    arrived.notified().await;
    placed(Width::TwoThirds).await;
    release.notify_one();
    flushing.await.unwrap();
    let w = f.lock().unwrap();
    assert_eq!(w.spaces.count(&put), written + 2);
    assert_eq!(
        w.spaces.record(&space, &key).unwrap()["width"],
        "two-thirds"
    );
}

#[tokio::test]
async fn places_waiting_go_with_their_canvas() {
    let (h, f, base) = spaced().await;
    sign_in(&h, &f, &base).await;
    let a = h.canvases.resolve(ME, None).await.unwrap();
    let b = h.canvases.create(ME, "B", By::Person).await.unwrap().id;
    let (ta, tb) = (add_to(&h, &a).await, add_to(&h, &b).await);
    let placed = |id: &str, t: &Tile| {
        let op = Op::Width {
            id: t.id.clone(),
            width: Width::Full,
        };
        let (h, id) = (h.clone(), id.to_string());
        async move { h.canvases.apply(ME, &id, op, By::Person).await.unwrap() }
    };
    let puts = |t: &Tile| {
        f.lock()
            .unwrap()
            .spaces
            .count(&format!("putRecord place.hud.tile/{}", t.id))
    };
    let (put_a, put_b) = (puts(&ta), puts(&tb));
    // Shared while a place waits: out of its space, the place not written
    // there.
    placed(&a, &ta).await;
    h.canvases
        .invite(ME, &a, OTHER, None, Role::Viewer)
        .await
        .unwrap();
    assert_eq!(storages(&h).await[&a]["kind"], "file");
    // Deleted while a place waits: not written either.
    placed(&b, &tb).await;
    h.canvases.delete(ME, &b).await.unwrap();
    h.canvases.flush().await;
    assert_eq!((puts(&ta), puts(&tb)), (put_a, put_b));
    // A canvas in a file deleted: its file gone, and no space touched.
    let asked = f.lock().unwrap().spaces.writes.len();
    h.canvases.delete(ME, &a).await.unwrap();
    let file = h.config.data_dir.join("canvas").join(format!("{a}.json"));
    assert!(!file.exists());
    assert_eq!(f.lock().unwrap().spaces.writes.len(), asked);
}