~ 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
2595 lines · 92.9 KB Raw History
//! The canvases in use: the directory of every canvas's info and who is in
//! which, each person's tabs (the canvases they have open, in order) and
//! current canvas, the tiles of those in use, and the live side: each
//! change, and who is on each canvas, sent to the members' streams
//! (`watch`), one per person, covering every canvas they have open. Every
//! change goes to the `Store` first.
//!
//! A person's first use makes their first canvas, "My canvas", and moves
//! into it the one canvas they had before there were many, if there is one
//! (`settle`); a person from before tabs has every canvas they are in open,
//! by when it was made. Changes to who is in a canvas, and making and
//! deleting one, are made one at a time (`ops`); a canvas's tiles under its
//! own lock.

use super::store::{Change, Index, Store};
use super::strip::{self, Spot};
use super::{
    By, CanvasInfo, Event, FIRST_NAME, MAX_CANVASES, MAX_MEMBERS, MAX_TILES, Member, NOTICES_MAX,
    Op, Role, Tile, Width, default_title, default_width, iso_now, new_id,
};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use tokio::sync::{OnceCell, broadcast};

/// Who asks: a signed-in person.
#[derive(Clone, Copy, Debug)]
pub struct Who<'a> {
    pub did: &'a str,
    pub handle: Option<&'a str>,
}

/// What a person has in the canvases: those they own, each its id, name
/// and how many others are in it, invited ones too; how many of others'
/// they are in; and how many invitations wait for them.
#[derive(Debug, PartialEq)]
pub struct Holding {
    pub owned: Vec<(String, String, usize)>,
    pub shared: usize,
    pub invited: usize,
}

/// Why something was not done.
#[derive(Debug, PartialEq)]
pub enum Refused {
    /// What was asked is not one HUD takes: why.
    Invalid(String),
    /// No canvas of this id, or name, that the person can see.
    NoCanvas(String),
    /// The person's role does not allow it: why.
    Forbidden(String),
    /// The canvas has no tile of this id.
    NoTile(String),
    /// A limit was reached: which.
    Limit(String),
}

/// Who caused a change: a person, or an agent of theirs.
#[derive(Clone, Debug, PartialEq)]
pub struct Cause {
    pub did: String,
    pub handle: Option<String>,
    pub by: By,
}

impl Cause {
    pub fn of(who: Who<'_>, by: By) -> Cause {
        Cause {
            did: who.did.to_string(),
            handle: who.handle.map(str::to_string),
            by,
        }
    }

    /// As `place.hud.defs#by`.
    pub fn to_json(&self) -> Value {
        let mut v = json!({ "did": self.did, "kind": self.by.as_str() });
        if let Some(h) = &self.handle {
            v["handle"] = json!(h);
        }
        v
    }
}

/// What a person's streams are told.
#[derive(Clone, Debug, PartialEq)]
pub enum Notice {
    /// A change to a tile of a canvas they are in.
    Tile {
        canvas: String,
        event: Box<Event>,
        cause: Cause,
    },
    /// Who is on a canvas they are in now, DIDs and handles, each once:
    /// someone (`cause`) came or went.
    Presence {
        canvas: String,
        present: Vec<(String, Option<String>)>,
        cause: Cause,
    },
    /// Their workspace changed: a canvas of theirs (`canvas`), or all of
    /// them, by someone or by the server.
    Canvases {
        canvas: Option<String>,
        cause: Option<Cause>,
    },
}

/// A canvas in the directory: its info and how many tiles it has.
struct Entry {
    info: CanvasInfo,
    tiles: usize,
}

#[derive(Default)]
struct Directory {
    canvases: HashMap<String, Entry>,
    /// Each person's current canvas, once read from their index.
    current: HashMap<String, Option<String>>,
    /// Each person's tabs, once read from their index.
    open: HashMap<String, Vec<String>>,
    /// Those whose first use was seen to.
    settled: HashSet<String>,
}

impl Directory {
    /// The canvases a person has open that they are in, in order.
    fn tabs(&self, did: &str) -> Vec<String> {
        self.open
            .get(did)
            .into_iter()
            .flatten()
            .filter(|id| self.joined(did, id))
            .cloned()
            .collect()
    }

    fn joined(&self, did: &str, id: &str) -> bool {
        self.canvases
            .get(id)
            .and_then(|e| e.info.member(did))
            .is_some_and(|m| m.joined)
    }

    /// A canvas out of a person's tabs, and not their current one.
    fn put_away(&mut self, did: &str, id: &str) {
        if let Some(open) = self.open.get_mut(did) {
            open.retain(|c| c != id);
        }
        if let Some(c) = self.current.get_mut(did)
            && c.as_deref() == Some(id)
        {
            *c = None;
        }
    }
}

/// A canvas in use: its tiles, read when first needed; and the streams on
/// it: each its page number and person.
struct Open {
    tiles: tokio::sync::Mutex<Option<Vec<Tile>>>,
    here: Mutex<Vec<(u64, String, Option<String>)>>,
}

fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
    m.lock().unwrap_or_else(PoisonError::into_inner)
}

/// What the streams share with the engine: the directory, each person's
/// channel, the canvases in use, and whether the server is stopping.
struct Hub {
    dir: OnceCell<Mutex<Directory>>,
    people: Mutex<HashMap<String, broadcast::Sender<Notice>>>,
    open: Mutex<HashMap<String, Arc<Open>>>,
    closed: AtomicBool,
}

impl Hub {
    fn send(&self, did: &str, notice: Notice) {
        if let Some(s) = lock(&self.people).get(did) {
            // None listening is no failure.
            let _ = s.send(notice);
        }
    }

    /// Tell everyone in a canvas.
    fn tell(&self, id: &str, notice: Notice) {
        let dids: Vec<String> = self
            .dir
            .get()
            .and_then(|dir| {
                lock(dir).canvases.get(id).map(|e| {
                    e.info
                        .members
                        .iter()
                        .filter(|m| m.joined)
                        .map(|m| m.did.clone())
                        .collect()
                })
            })
            .unwrap_or_default();
        for did in dids {
            self.send(&did, notice.clone());
        }
    }

    /// Who is on a canvas: each person once.
    fn present(open: &Open) -> Vec<(String, Option<String>)> {
        let mut out: Vec<(String, Option<String>)> = Vec::new();
        for (_, did, handle) in lock(&open.here).iter() {
            if !out.iter().any(|(d, _)| d == did) {
                out.push((did.clone(), handle.clone()));
            }
        }
        out
    }

    /// A stream came on a canvas, or left it: everyone in it told.
    fn moved(&self, id: &str, open: &Open, page: u64, who: &Cause, came: bool) {
        {
            let mut here = lock(&open.here);
            if came {
                here.push((page, who.did.clone(), who.handle.clone()));
            } else {
                here.retain(|(p, _, _)| *p != page);
            }
        }
        let present = Hub::present(open);
        self.tell(
            id,
            Notice::Presence {
                canvas: id.to_string(),
                present,
                cause: who.clone(),
            },
        );
    }
}

/// Every canvas.
pub struct Canvases {
    store: Box<dyn Store>,
    hub: Arc<Hub>,
    /// Makes and deletes canvases, and changes who is in them, one at a time.
    ops: tokio::sync::Mutex<()>,
    pages: AtomicU64,
}

/// A person's stream: what they are told, and the canvases it is on,
/// which it leaves when dropped.
pub struct Watch {
    pub notices: broadcast::Receiver<Notice>,
    hub: Arc<Hub>,
    page: u64,
    who: Cause,
    on: Vec<(String, Arc<Open>)>,
}

impl Watch {
    /// Whether it covers a canvas: one of its person's tabs.
    pub fn covers(&self, id: &str) -> bool {
        self.on.iter().any(|(c, _)| c == id)
    }
}

impl Drop for Watch {
    fn drop(&mut self) {
        for (id, open) in std::mem::take(&mut self.on) {
            self.hub.moved(&id, &open, self.page, &self.who, false);
        }
    }
}

/// A person's first canvas's id: the same for them every time.
fn first_id(did: &str) -> String {
    let digest = Sha256::digest(format!("hud canvas {did}").as_bytes());
    digest[..6].iter().map(|b| format!("{b:02x}")).collect()
}

/// A new id that `taken` does not hold.
fn fresh_id(taken: impl Fn(&str) -> bool) -> String {
    std::iter::repeat_with(new_id)
        .find(|id| !taken(id))
        .expect("new ids never run out")
}

/// What of a tile a change may change, to tell which did.
type Placement = (f64, Width, Option<String>, String, String, Value);

fn placement(t: &Tile) -> Placement {
    (
        t.order,
        t.width,
        t.stack.clone(),
        t.title.clone(),
        t.tool.clone(),
        t.arguments.clone(),
    )
}

/// A person's canvases, in the order a list gives them: those they own,
/// then those shared with them, then their invitations; each by when it
/// was made.
fn group(e: &Entry, did: &str) -> u8 {
    match e.info.member(did) {
        Some(m) if m.role == Role::Owner => 0,
        Some(m) if m.joined => 1,
        _ => 2,
    }
}

impl Canvases {
    pub fn new(store: Box<dyn Store>) -> Canvases {
        Canvases {
            store,
            hub: Arc::new(Hub {
                dir: OnceCell::new(),
                people: Mutex::new(HashMap::new()),
                open: Mutex::new(HashMap::new()),
                closed: AtomicBool::new(false),
            }),
            ops: tokio::sync::Mutex::new(()),
            pages: AtomicU64::new(0),
        }
    }

    /// The directory, read from the store when first needed.
    async fn dir(&self) -> MutexGuard<'_, Directory> {
        let d = self
            .hub
            .dir
            .get_or_init(|| async {
                let canvases = self
                    .store
                    .canvases()
                    .await
                    .into_iter()
                    .map(|(info, tiles)| (info.id.clone(), Entry { info, tiles }))
                    .collect();
                Mutex::new(Directory {
                    canvases,
                    ..Directory::default()
                })
            })
            .await;
        lock(d)
    }

    /// A canvas in use, made so if it was not; those nothing holds and no
    /// stream is on let go.
    fn open(&self, id: &str) -> Arc<Open> {
        let mut open = lock(&self.hub.open);
        open.retain(|_, o| Arc::strong_count(o) > 1 || !lock(&o.here).is_empty());
        open.entry(id.to_string())
            .or_insert_with(|| {
                Arc::new(Open {
                    tiles: tokio::sync::Mutex::new(None),
                    here: Mutex::new(Vec::new()),
                })
            })
            .clone()
    }

    /// A person's channel, made if they have none; once closed, one that
    /// has ended.
    fn channel(&self, did: &str) -> broadcast::Receiver<Notice> {
        let mut people = lock(&self.hub.people);
        if self.hub.closed.load(Ordering::Relaxed) {
            return broadcast::channel(1).1;
        }
        people.retain(|_, s| s.receiver_count() > 0);
        people
            .entry(did.to_string())
            .or_insert_with(|| broadcast::channel(NOTICES_MAX).0)
            .subscribe()
    }

    /// End every stream, and any opened after, as the server stops: open,
    /// a stream would keep its connection, and so the server, from ever
    /// stopping. Its page connects again, to the server that comes next.
    pub fn close(&self) {
        let mut people = lock(&self.hub.people);
        self.hub.closed.store(true, Ordering::Relaxed);
        people.clear();
    }

    /// A person's workspace changed: their streams are told.
    fn nudge(&self, did: &str, canvas: Option<&str>, cause: Option<&Cause>) {
        self.hub.send(
            did,
            Notice::Canvases {
                canvas: canvas.map(str::to_string),
                cause: cause.cloned(),
            },
        );
    }

    /// A person's workspace changed apart from a canvas (where their
    /// canvases are kept, their theme): their streams are told.
    pub fn workspace_changed(&self, did: &str) {
        self.nudge(did, None, None);
    }

    /// Write what the store has waiting, as the server stops.
    pub async fn flush(&self) {
        self.store.flush().await;
    }

    /// Where the store keeps a person's canvases, decided once per sign-in:
    /// those it found elsewhere put in the directory, and theirs kept
    /// where they do not belong written whole again, which moves them.
    async fn place(&self, who: Who<'_>) {
        let Some(found) = self.store.person(who.did).await else {
            return;
        };
        let misplaced: Vec<String> = {
            let mut d = self.dir().await;
            for (info, tiles) in found {
                d.canvases
                    .entry(info.id.clone())
                    .or_insert(Entry { info, tiles });
            }
            d.canvases
                .values()
                .filter(|e| e.info.owner == who.did && self.store.misplaced(&e.info))
                .map(|e| e.info.id.clone())
                .collect()
        };
        for id in misplaced {
            self.rewrite(&id).await;
        }
        if self.dir().await.settled.contains(who.did) {
            self.reindex(who.did).await;
        }
        self.nudge(who.did, None, None);
    }

    /// A canvas written whole again, as it is.
    async fn rewrite(&self, id: &str) {
        let open = self.open(id);
        let mut slot = open.tiles.lock().await;
        let Some(info) = self.info_of(id).await else {
            return;
        };
        let tiles = self.loaded(&mut slot, &info).await;
        if let Err(e) = self.store.write(Change::Info { info: &info, tiles }).await {
            tracing::warn!(canvas = id, error = %e, "a canvas was not moved");
        }
    }

    /// Keep a person's index as the directory has it; their tabs as their
    /// index had them, while they have not been seen since.
    async fn reindex(&self, did: &str) {
        let (canvases, open, current) = {
            let d = self.dir().await;
            let mut canvases: Vec<&Entry> = d
                .canvases
                .values()
                .filter(|e| e.info.member(did).is_some())
                .collect();
            canvases.sort_by(|a, b| a.info.created_at.cmp(&b.info.created_at));
            (
                canvases.iter().map(|e| e.info.id.clone()).collect(),
                d.open.get(did).cloned(),
                d.current.get(did).cloned().flatten(),
            )
        };
        let open = match open {
            Some(open) => Some(open),
            None => self.store.index(did).await.and_then(|i| i.open),
        };
        let index = Index {
            canvases,
            open,
            current,
        };
        if let Err(e) = self.store.put_index(did, &index).await {
            tracing::error!(did, error = %e, "could not keep a canvas index");
        }
    }

    /// A person's first use seen to: their tabs and current canvas read,
    /// and if they have no index and own no canvas, their first made, with
    /// their canvas from before moved into it. One from before tabs has
    /// every canvas they are in open, by when it was made.
    async fn settle(&self, who: Who<'_>) {
        self.place(who).await;
        if self.dir().await.settled.contains(who.did) {
            return;
        }
        let _ops = self.ops.lock().await;
        if self.dir().await.settled.contains(who.did) {
            return;
        }
        let index = self.store.index(who.did).await;
        let owns = self
            .dir()
            .await
            .canvases
            .values()
            .any(|e| e.info.owner == who.did);
        let mut migrated = false;
        if index.is_none() && !owns {
            let legacy = self.store.legacy(who.did).await;
            let moved = legacy.is_some();
            let id = first_id(who.did);
            if !self.dir().await.canvases.contains_key(&id) {
                self.make(who, &id, FIRST_NAME, legacy.unwrap_or_default())
                    .await;
                if moved {
                    self.store.retire_legacy(who.did).await;
                    tracing::info!(did = who.did, "the canvas from before moved");
                }
            }
        } else {
            let mut d = self.dir().await;
            let (open, current) = match index {
                Some(i) => (i.open, i.current),
                None => (None, None),
            };
            let open = open.unwrap_or_else(|| {
                migrated = true;
                let mut mine: Vec<&Entry> = d
                    .canvases
                    .values()
                    .filter(|e| e.info.member(who.did).is_some_and(|m| m.joined))
                    .collect();
                mine.sort_by(|a, b| {
                    (&a.info.created_at, &a.info.id).cmp(&(&b.info.created_at, &b.info.id))
                });
                mine.iter().map(|e| e.info.id.clone()).collect()
            });
            d.open.insert(who.did.to_string(), open);
            d.current.insert(who.did.to_string(), current);
        }
        self.dir().await.settled.insert(who.did.to_string());
        if migrated {
            self.reindex(who.did).await;
            tracing::info!(did = who.did, "tabs from the canvases they are in");
        }
    }

    /// Make a canvas of `who`'s, open as their last tab and current. `ops`
    /// held.
    async fn make(&self, who: Who<'_>, id: &str, name: &str, tiles: Vec<Tile>) -> CanvasInfo {
        let now = iso_now();
        let info = CanvasInfo {
            id: id.to_string(),
            name: name.to_string(),
            owner: who.did.to_string(),
            members: vec![Member {
                did: who.did.to_string(),
                handle: who.handle.map(str::to_string),
                role: Role::Owner,
                joined: true,
                invited_by: None,
            }],
            created_at: now.clone(),
            updated_at: now,
        };
        if let Err(e) = self
            .store
            .write(Change::Info {
                info: &info,
                tiles: &tiles,
            })
            .await
        {
            tracing::error!(error = %e, "could not keep a canvas");
        }
        {
            let mut d = self.dir().await;
            d.canvases.insert(
                id.to_string(),
                Entry {
                    info: info.clone(),
                    tiles: tiles.len(),
                },
            );
            d.current.insert(who.did.to_string(), Some(id.to_string()));
            d.open
                .entry(who.did.to_string())
                .or_default()
                .push(id.to_string());
        }
        *self.open(id).tiles.lock().await = Some(tiles);
        self.reindex(who.did).await;
        info
    }

    /// A canvas's info and the person's place in it, if they are in it.
    async fn seen(&self, did: &str, id: &str) -> Result<(CanvasInfo, Member), Refused> {
        let d = self.dir().await;
        d.canvases
            .get(id)
            .and_then(|e| Some((e.info.clone(), e.info.member(did)?.clone())))
            .ok_or_else(|| Refused::NoCanvas(id.to_string()))
    }

    /// A canvas as `place.hud.defs#canvasView` has it, for `did`:
    /// its info as its record, its members, how many tiles, where it is
    /// kept, and their role and who invited them while they have not
    /// joined.
    fn view(&self, e: &Entry, did: &str) -> Value {
        let viewer = e.info.member(did).map_or(json!({}), |m| {
            let mut viewer = json!({ "role": m.role.as_str() });
            if let (false, Some(by)) = (m.joined, &m.invited_by) {
                viewer["invitedBy"] = json!(by);
            }
            viewer
        });
        json!({
            "key": e.info.id,
            "owner": e.info.owner,
            "record": e.info.record(),
            "members": e.info.members.iter().map(Member::view).collect::<Vec<_>>(),
            "tileCount": e.tiles,
            "storage": self.store.storage(&e.info),
            "viewer": viewer,
        })
    }

    /// The canvases a person sees, as `view` gives them: those they own,
    /// then those shared with them, then their invitations; each by when
    /// it was made. With each, its place in that order, for paging.
    pub async fn list(&self, who: Who<'_>) -> Vec<(String, Value)> {
        self.settle(who).await;
        let d = self.dir().await;
        let mut seen: Vec<(String, &Entry)> = d
            .canvases
            .values()
            .filter(|e| e.info.member(who.did).is_some())
            .map(|e| {
                let key = format!("{}|{}|{}", group(e, who.did), e.info.created_at, e.info.id);
                (key, e)
            })
            .collect();
        seen.sort_by(|a, b| a.0.cmp(&b.0));
        seen.into_iter()
            .map(|(key, e)| (key, self.view(e, who.did)))
            .collect()
    }

    /// A canvas of a person's as `view` gives it.
    pub async fn info(&self, who: Who<'_>, id: &str) -> Result<Value, Refused> {
        let d = self.dir().await;
        d.canvases
            .get(id)
            .filter(|e| e.info.member(who.did).is_some())
            .map(|e| self.view(e, who.did))
            .ok_or_else(|| Refused::NoCanvas(id.to_string()))
    }

    /// A person's tabs, never none (their current canvas opens, made if
    /// they have none), and their current canvas, one of them.
    pub async fn tabs(&self, who: Who<'_>) -> (Vec<String>, String) {
        self.settle(who).await;
        let mut open = self.dir().await.tabs(who.did);
        if open.is_empty() {
            let id = self.current_or_made(who).await;
            open = self.dir().await.tabs(who.did);
            if !open.contains(&id) {
                open.push(id);
                self.dir()
                    .await
                    .open
                    .insert(who.did.to_string(), open.clone());
                self.reindex(who.did).await;
            }
        }
        let current = self
            .dir()
            .await
            .current
            .get(who.did)
            .cloned()
            .flatten()
            .filter(|c| open.contains(c))
            .unwrap_or_else(|| open[0].clone());
        (open, current)
    }

    /// The tabs as `place.hud.defs#tab`s.
    pub async fn tab_views(&self, who: Who<'_>, open: &[String]) -> Vec<Value> {
        let d = self.dir().await;
        open.iter()
            .filter_map(|id| d.canvases.get(id))
            .map(|e| json!({ "canvas": self.view(e, who.did) }))
            .collect()
    }

    /// A person's current canvas, if it is one they are in: the one they
    /// last opened, else their first.
    async fn current_of(&self, who: Who<'_>) -> Option<String> {
        let d = self.dir().await;
        if let Some(Some(c)) = d.current.get(who.did)
            && d.joined(who.did, c)
        {
            return Some(c.clone());
        }
        let mut owned: Vec<&Entry> = d
            .canvases
            .values()
            .filter(|e| e.info.owner == who.did)
            .collect();
        owned.sort_by(|a, b| a.info.created_at.cmp(&b.info.created_at));
        owned
            .iter()
            .find(|e| e.info.name == FIRST_NAME)
            .or(owned.first())
            .map(|e| e.info.id.clone())
    }

    /// A person's current canvas, made if they have none.
    async fn current_or_made(&self, who: Who<'_>) -> String {
        if let Some(c) = self.current_of(who).await {
            return c;
        }
        let _ops = self.ops.lock().await;
        // Their first canvas's id, unless it is taken, or kept where
        // it is not read now, as their index says.
        let first = first_id(who.did);
        let listed = self
            .store
            .index(who.did)
            .await
            .is_some_and(|i| i.canvases.contains(&first));
        let id = if listed || self.dir().await.canvases.contains_key(&first) {
            new_id()
        } else {
            first
        };
        let id = self.make(who, &id, FIRST_NAME, Vec::new()).await.id;
        self.nudge(who.did, Some(&id), None);
        id
    }

    /// The canvas a call names: by id or by name (exactly, case aside), of
    /// those the person is in; with none, their current one, made if they
    /// have none.
    pub async fn resolve(&self, who: Who<'_>, named: Option<&str>) -> Result<String, Refused> {
        self.settle(who).await;
        let Some(named) = named.map(str::trim).filter(|n| !n.is_empty()) else {
            return Ok(self.current_or_made(who).await);
        };
        let d = self.dir().await;
        let mine: Vec<&Entry> = d
            .canvases
            .values()
            .filter(|e| e.info.member(who.did).is_some_and(|m| m.joined))
            .collect();
        if let Some(e) = mine.iter().find(|e| e.info.id == named) {
            return Ok(e.info.id.clone());
        }
        let found: Vec<&&Entry> = mine
            .iter()
            .filter(|e| e.info.name.to_lowercase() == named.to_lowercase())
            .collect();
        match found.as_slice() {
            [one] => Ok(one.info.id.clone()),
            [] => {
                let names: Vec<String> = mine
                    .iter()
                    .map(|e| format!("\"{}\"", e.info.name))
                    .collect();
                Err(Refused::NoCanvas(format!(
                    "You have no canvas named \"{named}\". Yours: {}",
                    names.join(", ")
                )))
            }
            many => Err(Refused::Invalid(format!(
                "{} canvases are named \"{named}\"; name one by its id: {}",
                many.len(),
                many.iter()
                    .map(|e| e.info.id.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ))),
        }
    }

    /// Where a canvas is kept in a space, its URI; none for a file.
    fn space_of(&self, info: &CanvasInfo) -> Option<String> {
        let storage = self.store.storage(info);
        (storage["kind"] == "space")
            .then(|| storage["uri"].as_str().map(str::to_string))
            .flatten()
    }

    /// A canvas whole, as a member reads it: its view, and its tiles in
    /// strip order as `place.hud.defs#tileView`s, their icons
    /// from the server at `origin`.
    pub async fn canvas(&self, who: Who<'_>, id: &str, origin: &str) -> Result<Value, Refused> {
        self.seen(who.did, id).await?;
        let open = self.open(id);
        let mut slot = open.tiles.lock().await;
        let (info, _) = self.seen(who.did, id).await?;
        let space = self.space_of(&info);
        let tiles = self.loaded(&mut slot, &info).await;
        let views: Vec<Value> = strip::in_order(tiles)
            .iter()
            .map(|t| t.view(space.as_deref(), origin))
            .collect();
        Ok(json!({ "canvas": self.info(who, id).await?, "tiles": views }))
    }

    /// A tile of canvas `id` as `place.hud.defs#tileView`, its
    /// icon from the server at `origin`.
    pub async fn tile_view(&self, id: &str, tile: &Tile, origin: &str) -> Value {
        let space = self.info_of(id).await.and_then(|i| self.space_of(&i));
        tile.view(space.as_deref(), origin)
    }

    /// What a stream is told, as `place.hud.defs` types it: a
    /// `#tileEvent`, `#presenceEvent` or `#canvasesEvent`, icons from the
    /// server at `origin`.
    pub async fn notice_json(&self, notice: &Notice, origin: &str) -> Value {
        const DEFS: &str = "place.hud.defs";
        match notice {
            Notice::Tile {
                canvas,
                event,
                cause,
            } => {
                let mut v = json!({ "$type": format!("{DEFS}#tileEvent"), "canvas": canvas,
                    "op": event.op, "key": event.id, "by": cause.to_json() });
                if let Some(t) = &event.tile {
                    let space = self.info_of(canvas).await.and_then(|i| self.space_of(&i));
                    v["tile"] = t.view(space.as_deref(), origin);
                }
                v
            }
            Notice::Presence {
                canvas,
                present,
                cause,
            } => {
                let present: Vec<Value> = present
                    .iter()
                    .map(|(did, handle)| match handle {
                        Some(h) => json!({ "did": did, "handle": h }),
                        None => json!({ "did": did }),
                    })
                    .collect();
                json!({ "$type": format!("{DEFS}#presenceEvent"), "canvas": canvas,
                    "present": present, "by": cause.to_json() })
            }
            Notice::Canvases { canvas, cause } => {
                let mut v = json!({ "$type": format!("{DEFS}#canvasesEvent") });
                if let Some(c) = canvas {
                    v["canvas"] = json!(c);
                }
                if let Some(c) = cause {
                    v["by"] = c.to_json();
                }
                v
            }
        }
    }

    /// The tiles of a canvas in use, read when first needed.
    async fn loaded<'s>(
        &self,
        slot: &'s mut Option<Vec<Tile>>,
        info: &CanvasInfo,
    ) -> &'s mut Vec<Tile> {
        if slot.is_none() {
            let tiles = self.store.tiles(info).await.unwrap_or_else(|e| {
                tracing::warn!(canvas = info.id, error = %e, "a canvas's tiles could not be read");
                Vec::new()
            });
            *slot = Some(tiles);
        }
        slot.get_or_insert_with(Vec::new)
    }

    /// A tile change, by a member who may make it: the tile as it now is
    /// (a removed one as it was; for a width, the column's head). What
    /// else it moved is written and told too. `title` made for an added
    /// tile with none from its tool and arguments.
    pub async fn apply(&self, who: Who<'_>, id: &str, op: Op, by: By) -> Result<Tile, Refused> {
        let open = self.open(id);
        let mut slot = open.tiles.lock().await;
        let (info, me) = self.seen(who.did, id).await?;
        may_edit(&info, &me)?;
        let tiles = self.loaded(&mut slot, &info).await;
        let before: HashMap<String, Placement> =
            tiles.iter().map(|t| (t.id.clone(), placement(t))).collect();
        let mut gone: Vec<Tile> = Vec::new();
        let answer = match op {
            Op::Add {
                tool,
                arguments,
                title,
                from,
                after,
                stack,
                width,
            } => {
                let kept = (tiles.len() >= MAX_TILES).then(|| tiles.clone());
                while tiles.len() >= MAX_TILES {
                    let oldest = tiles[0].id.clone();
                    gone.push(strip::remove(tiles, &oldest)?);
                }
                let spot =
                    match strip::spot(tiles, from.as_deref(), after.as_deref(), stack.as_deref()) {
                        Ok(spot) => spot,
                        Err(r) => {
                            if let Some(kept) = kept {
                                *tiles = kept;
                            }
                            return Err(r);
                        }
                    };
                let tid = fresh_id(|id| tiles.iter().any(|t| t.id == id));
                let title = title.unwrap_or_else(|| {
                    default_title(&tool, &arguments, None, Some(who.handle.unwrap_or(who.did)))
                });
                let (order, stack) = match spot {
                    Spot::Column { order } => (order, None),
                    Spot::Stacked { head, order } => (order, Some(head)),
                };
                let tile = Tile {
                    id: tid,
                    width: width.unwrap_or_else(|| default_width(&tool, &arguments)),
                    tool,
                    arguments,
                    title,
                    order,
                    stack,
                    by,
                    author: who.did.to_string(),
                    at: iso_now(),
                    from,
                };
                tiles.push(tile.clone());
                tile.id
            }
            Op::Remove { id: tid } => {
                let tile = strip::remove(tiles, &tid)?;
                gone.push(tile);
                tid
            }
            Op::Place { id: tid, to } => strip::place(tiles, &tid, &to)?,
            Op::Width { id: tid, width } => strip::set_width(tiles, &tid, width)?,
            Op::Stack { id: tid, into } => strip::stack(tiles, &tid, &into)?,
            Op::Unstack { id: tid } => strip::unstack(tiles, &tid)?,
            Op::Update {
                id: tid,
                title,
                call,
            } => {
                let t = tiles
                    .iter_mut()
                    .find(|t| t.id == tid)
                    .ok_or_else(|| Refused::NoTile(tid.clone()))?;
                if let Some((tool, arguments)) = call {
                    // A title made from the call follows it; one given stays.
                    let me = Some(who.handle.unwrap_or(who.did));
                    if t.title == default_title(&t.tool, &t.arguments, None, me) {
                        t.title = default_title(&tool, &arguments, None, me);
                    }
                    t.tool = tool;
                    t.arguments = arguments;
                }
                if let Some(title) = title {
                    t.title = title;
                }
                tid
            }
        };
        let (events, kept) = self.keep_tiles(&info, tiles, &before, &gone).await;
        if let Err(e) = kept {
            tracing::error!(canvas = id, error = %e, "could not keep a canvas");
        }
        let count = tiles.len();
        let tile = match tiles.iter().find(|t| t.id == answer) {
            Some(t) => t.clone(),
            None => gone
                .into_iter()
                .find(|g| g.id == answer)
                .ok_or(Refused::NoTile(answer))?,
        };
        drop(slot);
        self.dir()
            .await
            .canvases
            .get_mut(id)
            .into_iter()
            .for_each(|e| e.tiles = count);
        self.tell_tiles(id, events, &Cause::of(who, by));
        Ok(tile)
    }

    /// A change to a canvas's tiles, its lock held, kept: `gone` taken
    /// off, and each tile whose place `before` does not hold as it now is
    /// changed, or added. Its events, and whether the store kept it.
    async fn keep_tiles(
        &self,
        info: &CanvasInfo,
        tiles: &[Tile],
        before: &HashMap<String, Placement>,
        gone: &[Tile],
    ) -> (Vec<Event>, Result<(), String>) {
        let changed: Vec<&Tile> = tiles
            .iter()
            .filter(|t| before.get(&t.id) != Some(&placement(t)))
            .collect();
        let mut events: Vec<Event> = gone
            .iter()
            .map(|g| Event {
                op: "remove",
                tile: None,
                id: g.id.clone(),
            })
            .collect();
        events.extend(changed.iter().map(|t| Event {
            op: if before.contains_key(&t.id) {
                "update"
            } else {
                "add"
            },
            tile: Some((*t).clone()),
            id: t.id.clone(),
        }));
        let kept = self
            .store
            .write(Change::Tiles {
                info,
                tiles,
                changed,
                gone: gone
                    .iter()
                    .map(|g| (g.id.as_str(), g.author.as_str()))
                    .collect(),
            })
            .await;
        (events, kept)
    }

    /// Everyone in a canvas told of changes to its tiles, by `cause`.
    fn tell_tiles(&self, id: &str, events: Vec<Event>, cause: &Cause) {
        for event in events {
            self.hub.tell(
                id,
                Notice::Tile {
                    canvas: id.to_string(),
                    event: Box::new(event),
                    cause: cause.clone(),
                },
            );
        }
    }

    /// Change a canvas's info, its lock held: `f` checks and changes it.
    /// The info before and after.
    async fn change_info(
        &self,
        id: &str,
        f: impl FnOnce(&mut CanvasInfo) -> Result<(), Refused>,
    ) -> Result<(CanvasInfo, CanvasInfo), Refused> {
        let open = self.open(id);
        let mut slot = open.tiles.lock().await;
        let before = self
            .dir()
            .await
            .canvases
            .get(id)
            .map(|e| e.info.clone())
            .ok_or_else(|| Refused::NoCanvas(id.to_string()))?;
        let mut after = before.clone();
        f(&mut after)?;
        after.updated_at = iso_now();
        let tiles = self.loaded(&mut slot, &before).await;
        if let Err(e) = self
            .store
            .write(Change::Info {
                info: &after,
                tiles,
            })
            .await
        {
            tracing::error!(canvas = id, error = %e, "could not keep a canvas");
        }
        self.dir()
            .await
            .canvases
            .get_mut(id)
            .into_iter()
            .for_each(|e| e.info = after.clone());
        Ok((before, after))
    }

    /// After a change of a canvas's info: the indexes of everyone in it
    /// before or after kept, and their streams told.
    async fn told(&self, before: &CanvasInfo, after: &CanvasInfo, cause: &Cause) {
        let mut dids: Vec<&str> = before.members.iter().map(|m| m.did.as_str()).collect();
        for m in &after.members {
            if !dids.contains(&m.did.as_str()) {
                dids.push(&m.did);
            }
        }
        for did in dids {
            self.reindex(did).await;
            self.nudge(did, Some(&after.id), Some(cause));
        }
    }

    fn owner_only(info: &CanvasInfo, did: &str, what: &str) -> Result<(), Refused> {
        match info.member(did) {
            None => Err(Refused::NoCanvas(info.id.clone())),
            Some(m) if m.role != Role::Owner => Err(Refused::Forbidden(format!(
                "Only the owner of \"{}\" {what}",
                info.name
            ))),
            Some(_) => Ok(()),
        }
    }

    /// Make a canvas, open as its owner's last tab and current.
    pub async fn create(&self, who: Who<'_>, name: &str, by: By) -> Result<CanvasInfo, Refused> {
        self.settle(who).await;
        let _ops = self.ops.lock().await;
        let owned = self
            .dir()
            .await
            .canvases
            .values()
            .filter(|e| e.info.owner == who.did)
            .count();
        if owned >= MAX_CANVASES {
            return Err(Refused::Limit(format!(
                "You have {MAX_CANVASES} canvases, the most one person may: delete one first"
            )));
        }
        let id = {
            let d = self.dir().await;
            fresh_id(|id| d.canvases.contains_key(id))
        };
        let info = self.make(who, &id, name, Vec::new()).await;
        self.nudge(who.did, Some(&id), Some(&Cause::of(who, by)));
        Ok(info)
    }

    pub async fn rename(&self, who: Who<'_>, id: &str, name: &str) -> Result<CanvasInfo, Refused> {
        let _ops = self.ops.lock().await;
        let (before, after) = self
            .change_info(id, |i| {
                Self::owner_only(i, who.did, "renames it")?;
                i.name = name.to_string();
                Ok(())
            })
            .await?;
        self.told(&before, &after, &Cause::of(who, By::Person))
            .await;
        Ok(after)
    }

    /// Delete a canvas, its owner's alone: out of everyone's tabs.
    pub async fn delete(&self, who: Who<'_>, id: &str) -> Result<(), Refused> {
        let _ops = self.ops.lock().await;
        if let Err(e) = self.drop_canvas(who, id, false).await? {
            tracing::error!(canvas = id, error = %e, "could not delete a canvas");
        }
        Ok(())
    }

    /// Delete a canvas, `ops` held, as `delete` does: whether the store
    /// deleted it. Where it did not and `keep_failed`, the canvas stays as
    /// it was, everyone's tabs too, so asking again finds it to delete.
    async fn drop_canvas(
        &self,
        who: Who<'_>,
        id: &str,
        keep_failed: bool,
    ) -> Result<Result<(), String>, Refused> {
        let (info, _) = self.seen(who.did, id).await?;
        Self::owner_only(&info, who.did, "deletes it")?;
        let open = self.open(id);
        let kept = {
            let _slot = open.tiles.lock().await;
            let kept = self.store.write(Change::Deleted(&info)).await;
            if kept.is_err() && keep_failed {
                return Ok(kept);
            }
            let mut d = self.dir().await;
            d.canvases.remove(id);
            for m in &info.members {
                d.put_away(&m.did, id);
            }
            kept
        };
        self.told(&info, &info, &Cause::of(who, By::Person)).await;
        Ok(kept)
    }

    /// Invite someone (`did`, verified `handle`) to a canvas as an editor or
    /// viewer: a member who has not joined, until they accept or decline.
    pub async fn invite(
        &self,
        who: Who<'_>,
        id: &str,
        did: &str,
        handle: Option<&str>,
        role: Role,
    ) -> Result<CanvasInfo, Refused> {
        if role == Role::Owner {
            return Err(Refused::Invalid("role must be editor or viewer".into()));
        }
        let _ops = self.ops.lock().await;
        let (before, after) = self
            .change_info(id, |i| {
                Self::owner_only(i, who.did, "invites people")?;
                if i.member(did).is_some() {
                    return Err(Refused::Invalid(format!(
                        "{} is already a member of \"{}\"",
                        handle.unwrap_or(did),
                        i.name
                    )));
                }
                if i.members.len() >= MAX_MEMBERS {
                    return Err(Refused::Limit(format!(
                        "\"{}\" has {MAX_MEMBERS} members, the most a canvas may",
                        i.name
                    )));
                }
                i.members.push(Member {
                    did: did.to_string(),
                    handle: handle.map(str::to_string),
                    role,
                    joined: false,
                    invited_by: Some(who.did.to_string()),
                });
                Ok(())
            })
            .await?;
        self.told(&before, &after, &Cause::of(who, By::Person))
            .await;
        Ok(after)
    }

    /// Change a member's role, the owner's alone; never the owner's own.
    pub async fn set_role(
        &self,
        who: Who<'_>,
        id: &str,
        did: &str,
        role: Role,
    ) -> Result<CanvasInfo, Refused> {
        if role == Role::Owner {
            return Err(Refused::Invalid("role must be editor or viewer".into()));
        }
        let _ops = self.ops.lock().await;
        let (before, after) = self
            .change_info(id, |i| {
                Self::owner_only(i, who.did, "changes roles")?;
                if did == i.owner {
                    return Err(Refused::Invalid("The owner's role does not change".into()));
                }
                let m = i
                    .members
                    .iter_mut()
                    .find(|m| m.did == did)
                    .ok_or_else(|| Refused::Invalid(format!("{did} is not a member")))?;
                m.role = role;
                Ok(())
            })
            .await?;
        self.told(&before, &after, &Cause::of(who, By::Person))
            .await;
        Ok(after)
    }

    /// Take a member off: the owner removes anyone else; a member leaves, or
    /// declines an invitation, themself. The owner never leaves: they
    /// delete. It leaves the member's tabs. The info after.
    pub async fn remove(&self, who: Who<'_>, id: &str, did: &str) -> Result<CanvasInfo, Refused> {
        let _ops = self.ops.lock().await;
        let (before, after) = self
            .change_info(id, |i| {
                i.member(who.did)
                    .ok_or_else(|| Refused::NoCanvas(i.id.clone()))?;
                if did == i.owner {
                    return Err(Refused::Invalid(
                        "The owner does not leave a canvas: delete it instead".into(),
                    ));
                }
                if did != who.did {
                    Self::owner_only(i, who.did, "removes members")?;
                }
                if i.member(did).is_none() {
                    return Err(Refused::Invalid(format!("{did} is not a member")));
                }
                i.members.retain(|m| m.did != did);
                Ok(())
            })
            .await?;
        self.dir().await.put_away(did, id);
        self.told(&before, &after, &Cause::of(who, By::Person))
            .await;
        Ok(after)
    }

    /// Join, `ops` held; nothing changes for a member already in it.
    async fn join(&self, who: Who<'_>, id: &str) -> Result<CanvasInfo, Refused> {
        let (info, me) = self.seen(who.did, id).await?;
        if me.joined {
            return Ok(info);
        }
        let (before, after) = self
            .change_info(id, |i| {
                for m in i.members.iter_mut().filter(|m| m.did == who.did) {
                    m.joined = true;
                    if who.handle.is_some() {
                        m.handle = who.handle.map(str::to_string);
                    }
                }
                Ok(())
            })
            .await?;
        self.told(&before, &after, &Cause::of(who, By::Person))
            .await;
        Ok(after)
    }

    /// Open a canvas: a tab at the end of the person's, unless open
    /// already, and their current one; an invitation to it is accepted.
    pub async fn open_canvas(&self, who: Who<'_>, id: &str) -> Result<CanvasInfo, Refused> {
        self.settle(who).await;
        let info = {
            let _ops = self.ops.lock().await;
            self.join(who, id).await?
        };
        {
            let mut d = self.dir().await;
            d.current.insert(who.did.to_string(), Some(id.to_string()));
            let open = d.open.entry(who.did.to_string()).or_default();
            if !open.iter().any(|c| c == id) {
                open.push(id.to_string());
            }
        }
        self.reindex(who.did).await;
        self.nudge(who.did, Some(id), Some(&Cause::of(who, By::Person)));
        Ok(info)
    }

    /// Put a canvas away: out of the person's tabs, never the last; the
    /// current one closed, its neighbour, right else left, is current.
    pub async fn close_canvas(&self, who: Who<'_>, id: &str) -> Result<(), Refused> {
        self.settle(who).await;
        self.seen(who.did, id).await?;
        {
            let mut d = self.dir().await;
            let open = d.tabs(who.did);
            let Some(at) = open.iter().position(|c| c == id) else {
                return Ok(());
            };
            if open.len() == 1 {
                return Err(Refused::Invalid("The last open tab is not closed".into()));
            }
            let mut rest = open;
            rest.remove(at);
            let next = rest[at.min(rest.len() - 1)].clone();
            if d.current.get(who.did).cloned().flatten().as_deref() == Some(id) {
                d.current.insert(who.did.to_string(), Some(next));
            }
            d.open.insert(who.did.to_string(), rest);
        }
        self.reindex(who.did).await;
        self.nudge(who.did, Some(id), Some(&Cause::of(who, By::Person)));
        Ok(())
    }

    /// Put the person's tabs in this order: those named first, then those
    /// open but not named, as they were.
    pub async fn set_tabs(&self, who: Who<'_>, order: &[String]) -> Result<(), Refused> {
        self.settle(who).await;
        {
            let mut d = self.dir().await;
            let open = d.tabs(who.did);
            let mut new: Vec<String> = Vec::new();
            for id in order {
                if !open.contains(id) {
                    return Err(Refused::Invalid(format!("{id} is not open")));
                }
                if new.contains(id) {
                    return Err(Refused::Invalid(format!("{id} is named twice")));
                }
                new.push(id.clone());
            }
            new.extend(open.into_iter().filter(|id| !order.contains(id)));
            d.open.insert(who.did.to_string(), new);
        }
        self.reindex(who.did).await;
        self.nudge(who.did, None, Some(&Cause::of(who, By::Person)));
        Ok(())
    }

    /// A person's stream: what they are told from now on, on every canvas
    /// they have open, everyone in each told it came.
    pub async fn watch(&self, who: Who<'_>) -> Watch {
        self.tabs(who).await;
        let mut watch = Watch {
            notices: self.channel(who.did),
            hub: self.hub.clone(),
            page: self.pages.fetch_add(1, Ordering::Relaxed),
            who: Cause::of(who, By::Person),
            on: Vec::new(),
        };
        self.follow(&mut watch).await;
        watch
    }

    /// A stream on its person's tabs as they now are: off those closed, on
    /// those opened, everyone in each told.
    pub async fn follow(&self, watch: &mut Watch) {
        let open = self.dir().await.tabs(&watch.who.did);
        let (left, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut watch.on)
            .into_iter()
            .partition(|(id, _)| !open.contains(id));
        watch.on = kept;
        for (id, o) in left {
            self.hub.moved(&id, &o, watch.page, &watch.who, false);
        }
        for id in open {
            if !watch.covers(&id) {
                let o = self.open(&id);
                watch.on.push((id.clone(), o.clone()));
                self.hub.moved(&id, &o, watch.page, &watch.who, true);
            }
        }
    }

    /// Whether a person is in a canvas (invited or joined).
    pub async fn sees(&self, did: &str, id: &str) -> bool {
        self.seen(did, id).await.is_ok()
    }

    /// A canvas's info, as kept.
    pub async fn info_of(&self, id: &str) -> Option<CanvasInfo> {
        self.dir().await.canvases.get(id).map(|e| e.info.clone())
    }

    /// A canvas's tiles, for a member, in strip order.
    pub async fn tiles(&self, who: Who<'_>, id: &str) -> Result<Vec<Tile>, Refused> {
        let (info, _) = self.seen(who.did, id).await?;
        let open = self.open(id);
        let mut slot = open.tiles.lock().await;
        let tiles = self.loaded(&mut slot, &info).await;
        Ok(strip::in_order(tiles).into_iter().cloned().collect())
    }

    /// A canvas's tiles, in strip order, for a member who may change
    /// them: refused as `apply` refuses them otherwise.
    pub async fn tiles_to_edit(&self, who: Who<'_>, id: &str) -> Result<Vec<Tile>, Refused> {
        let (info, me) = self.seen(who.did, id).await?;
        may_edit(&info, &me)?;
        self.tiles(who, id).await
    }

    /// What a person has in the canvases, theirs in spaces read first, as
    /// `forget` would delete it.
    pub async fn holding(&self, who: Who<'_>) -> Holding {
        self.place(who).await;
        let d = self.dir().await;
        let mut owned: Vec<&Entry> = Vec::new();
        let (mut shared, mut invited) = (0, 0);
        for e in d.canvases.values() {
            match e.info.member(who.did) {
                Some(m) if m.role == Role::Owner => owned.push(e),
                Some(m) if m.joined => shared += 1,
                Some(_) => invited += 1,
                None => {}
            }
        }
        owned.sort_by(|a, b| {
            (&a.info.created_at, &a.info.id).cmp(&(&b.info.created_at, &b.info.id))
        });
        Holding {
            owned: owned
                .iter()
                .map(|e| {
                    let others = e.info.members.iter().filter(|m| m.did != who.did).count();
                    (e.info.id.clone(), e.info.name.clone(), others)
                })
                .collect(),
            shared,
            invited,
        }
    }

    /// Everything of a person's in the canvases deleted: each canvas they
    /// own, for everyone in it, as `delete` does; in each canvas of
    /// others, the tiles they made taken off, then they leave it (or
    /// decline it), as `remove` does; then their tabs, and what the store
    /// keeps of theirs past that (`Store::forget`). How many canvases,
    /// tiles and memberships went; else, all else done, what was not.
    pub async fn forget(&self, who: Who<'_>) -> Result<usize, String> {
        self.place(who).await;
        let (owned, others): (Vec<String>, Vec<String>) = {
            let d = self.dir().await;
            let (owned, others): (Vec<&Entry>, Vec<&Entry>) = d
                .canvases
                .values()
                .filter(|e| e.info.member(who.did).is_some())
                .partition(|e| e.info.owner == who.did);
            let ids = |es: Vec<&Entry>| es.iter().map(|e| e.info.id.clone()).collect();
            (ids(owned), ids(others))
        };
        let mut deleted = 0;
        let mut failed: Vec<String> = Vec::new();
        for id in owned {
            let _ops = self.ops.lock().await;
            match self.drop_canvas(who, &id, true).await {
                Ok(Ok(())) => deleted += 1,
                Ok(Err(e)) => failed.push(format!("canvas {id}: {e}")),
                // Deleted meanwhile: nothing of it left.
                Err(_) => {}
            }
        }
        for id in others {
            // Their tiles first: once out, nothing of theirs there is found.
            match self.retract(who, &id).await {
                Ok(n) => deleted += n,
                Err(e) => {
                    failed.push(format!("your tiles on canvas {id}: {e}"));
                    continue;
                }
            }
            // Gone or left meanwhile: nothing to count.
            deleted += usize::from(self.remove(who, &id, who.did).await.is_ok());
        }
        {
            let mut d = self.dir().await;
            d.open.remove(who.did);
            d.current.remove(who.did);
            d.settled.remove(who.did);
        }
        if let Err(lines) = self.store.forget(who.did).await {
            failed.extend(lines);
        }
        self.nudge(who.did, None, None);
        let (did, failures) = (who.did, failed.len());
        tracing::info!(did, deleted, failures, "a person's canvases deleted");
        if failed.is_empty() {
            Ok(deleted)
        } else {
            Err(failed.join("; "))
        }
    }

    /// Take off a canvas every tile `who` made there, whatever their role
    /// now, as removing each would: one change, everyone in it told. How
    /// many went.
    async fn retract(&self, who: Who<'_>, id: &str) -> Result<usize, String> {
        let open = self.open(id);
        let mut slot = open.tiles.lock().await;
        let Some(info) = self.info_of(id).await else {
            return Ok(0);
        };
        let tiles = self.loaded(&mut slot, &info).await;
        let before: HashMap<String, Placement> =
            tiles.iter().map(|t| (t.id.clone(), placement(t))).collect();
        let mine: Vec<String> = tiles
            .iter()
            .filter(|t| t.author == who.did)
            .map(|t| t.id.clone())
            .collect();
        if mine.is_empty() {
            return Ok(0);
        }
        let gone: Vec<Tile> = mine
            .iter()
            .filter_map(|tid| strip::remove(tiles, tid).ok())
            .collect();
        let (events, kept) = self.keep_tiles(&info, tiles, &before, &gone).await;
        let count = tiles.len();
        drop(slot);
        self.dir()
            .await
            .canvases
            .get_mut(id)
            .into_iter()
            .for_each(|e| e.tiles = count);
        self.tell_tiles(id, events, &Cause::of(who, By::Person));
        kept.map(|()| gone.len())
    }

    /// A tile of a canvas, for a member.
    pub async fn tile(&self, who: Who<'_>, id: &str, tid: &str) -> Result<Tile, Refused> {
        self.tiles(who, id)
            .await?
            .into_iter()
            .find(|t| t.id == tid)
            .ok_or_else(|| Refused::NoTile(tid.to_string()))
    }

    /// The canvas a call names, as `resolve` finds it: its info.
    pub async fn resolve_info(
        &self,
        who: Who<'_>,
        named: Option<&str>,
    ) -> Result<CanvasInfo, Refused> {
        let id = self.resolve(who, named).await?;
        Ok(self.seen(who.did, &id).await?.0)
    }
}

/// Whether a member may change a canvas's tiles: an editor, joined.
fn may_edit(info: &CanvasInfo, me: &Member) -> Result<(), Refused> {
    if !me.role.edits() {
        return Err(Refused::Forbidden(format!(
            "You are a viewer of \"{}\": only its owner and editors change its tiles",
            info.name
        )));
    }
    if !me.joined {
        return Err(Refused::Forbidden(format!(
            "Accept the invitation to \"{}\" first",
            info.name
        )));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::super::store::{FileStore, Fut};
    use super::*;
    use crate::canvas::Beside;
    use atproto::jose;

    fn dir() -> std::path::PathBuf {
        std::env::temp_dir().join(format!("hud-canvases-{}", jose::random(6)))
    }

    const A: Who = Who {
        did: "did:plc:alice",
        handle: Some("alice.test"),
    };
    const B: Who = Who {
        did: "did:plc:bob",
        handle: Some("bob.test"),
    };

    fn add(tool: &str) -> Op {
        opened(tool, None)
    }

    /// An add, opened from a tile or from none.
    fn opened(tool: &str, from: Option<&str>) -> Op {
        Op::Add {
            tool: tool.into(),
            arguments: json!({ "actor": "alice.test" }),
            title: None,
            from: from.map(str::to_string),
            after: None,
            stack: None,
            width: None,
        }
    }

    /// The notices waiting.
    fn heard(w: &mut Watch) -> Vec<Notice> {
        std::iter::from_fn(|| w.notices.try_recv().ok()).collect()
    }

    /// The tile changes among notices: each op, tile and who made it.
    fn tile_events(notices: Vec<Notice>) -> Vec<(&'static str, String, By)> {
        notices
            .into_iter()
            .filter_map(|n| match n {
                Notice::Tile { event, cause, .. } => Some((event.op, event.id, cause.by)),
                _ => None,
            })
            .collect()
    }

    #[tokio::test]
    async fn tiles_placed_kept_and_told() {
        let d = dir();
        let c = Canvases::new(Box::new(FileStore::new(d.clone())));
        let id = c.resolve(A, None).await.unwrap();
        let mut w = c.watch(A).await;
        let parent = c
            .apply(A, &id, add("describe_repo"), By::Person)
            .await
            .unwrap();
        assert_eq!(
            (parent.order, parent.width, parent.from.as_deref()),
            (1.0, Width::Third, None)
        );
        let first = c
            .apply(A, &id, opened("describe_repo", Some(&parent.id)), By::Agent)
            .await
            .unwrap();
        let second = c
            .apply(
                A,
                &id,
                opened("describe_repo", Some(&parent.id)),
                By::Person,
            )
            .await
            .unwrap();
        let child = c
            .apply(A, &id, opened("describe_repo", Some(&first.id)), By::Person)
            .await
            .unwrap();
        let ids = |tiles: Vec<Tile>| tiles.into_iter().map(|t| t.id).collect::<Vec<_>>();
        assert_eq!(
            ids(c.tiles(A, &id).await.unwrap()),
            [&parent.id, &first.id, &child.id, &second.id].map(String::clone)
        );
        // Told, each by who made it.
        let told = tile_events(heard(&mut w));
        assert_eq!((told[1].0, told[1].2), ("add", By::Agent));
        // A head with a tile stacked under it, taken off: the other heads
        // the column, in its place, both told.
        c.apply(
            A,
            &id,
            Op::Stack {
                id: second.id.clone(),
                into: parent.id.clone(),
            },
            By::Person,
        )
        .await
        .unwrap();
        heard(&mut w);
        c.apply(
            A,
            &id,
            Op::Remove {
                id: parent.id.clone(),
            },
            By::Person,
        )
        .await
        .unwrap();
        let ops: Vec<(&str, String)> = tile_events(heard(&mut w))
            .into_iter()
            .map(|(op, id, _)| (op, id))
            .collect();
        assert_eq!(
            ops,
            [("remove", parent.id.clone()), ("update", second.id.clone())]
        );
        // Kept, and read back by a server started again.
        let again = Canvases::new(Box::new(FileStore::new(d.clone())));
        let tiles = again.tiles(A, &id).await.unwrap();
        assert_eq!(
            ids(tiles.clone()),
            [&second.id, &first.id, &child.id].map(String::clone)
        );
        assert_eq!((tiles[0].order, tiles[0].stack.as_deref()), (1.0, None));
        // A place beside a tile that is not there is refused.
        assert_eq!(
            c.apply(
                A,
                &id,
                Op::Place {
                    id: first.id.clone(),
                    to: Beside::After("0000000000ff".into())
                },
                By::Person
            )
            .await,
            Err(Refused::NoTile("0000000000ff".into()))
        );
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn first_canvas_and_the_one_from_before_moved() {
        let d = dir();
        std::fs::create_dir_all(&d).unwrap();
        // A canvas from before there were many, and before columns.
        let old = json!({ "did": A.did, "tiles": [{ "id": "00000000000a", "tool": "describe_repo",
            "arguments": { "actor": "alice.test" }, "title": "alice.test", "x": 0.0, "y": 0.0,
            "w": 420.0, "h": 560.0, "by": "agent", "at": "2026-11-14T00:00:00.000Z" }] });
        let legacy = d.join(format!("{}.json", jose::sha256(A.did)));
        std::fs::write(&legacy, old.to_string()).unwrap();
        let c = Canvases::new(Box::new(FileStore::new(d.clone())));
        let list = c.list(A).await;
        assert_eq!(list.len(), 1);
        let first = &list[0].1;
        assert_eq!(
            (
                &first["record"]["name"],
                &first["viewer"]["role"],
                &first["tileCount"]
            ),
            (&json!("My canvas"), &json!("owner"), &json!(1))
        );
        assert_eq!(first["key"], first_id(A.did).as_str());
        assert_eq!(c.tabs(A).await, (vec![first_id(A.did)], first_id(A.did)));
        let tiles = c.tiles(A, &first_id(A.did)).await.unwrap();
        assert_eq!(
            (
                tiles[0].id.as_str(),
                tiles[0].author.as_str(),
                tiles[0].order
            ),
            ("00000000000a", A.did, 1.0)
        );
        assert!(!legacy.exists());
        assert!(legacy.with_extension("json.moved").exists());
        // Read back by a server started again: the same canvas, nothing moved twice.
        let again = Canvases::new(Box::new(FileStore::new(d.clone())));
        let list = again.list(A).await;
        assert_eq!(list.len(), 1);
        assert_eq!(list[0].1["tileCount"], 1);
        // The index rebuilt from the canvases when it is missing, its tabs
        // every canvas the person is in.
        std::fs::remove_dir_all(d.join("by-did")).unwrap();
        let rebuilt = Canvases::new(Box::new(FileStore::new(d.clone())));
        assert_eq!(rebuilt.list(A).await.len(), 1);
        let index: Value = serde_json::from_slice(
            &std::fs::read(
                d.join("by-did")
                    .join(format!("{}.json", jose::sha256(A.did))),
            )
            .unwrap(),
        )
        .unwrap();
        assert_eq!(index["canvases"], json!([first_id(A.did)]));
        assert_eq!(index["open"], json!([first_id(A.did)]));
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn tabs_opened_closed_and_ordered() {
        let d = dir();
        let c = Canvases::new(Box::new(FileStore::new(d.clone())));
        let first = c.resolve(A, None).await.unwrap();
        let trip = c.create(A, "Coast trip", By::Person).await.unwrap().id;
        let work = c.create(A, "Work", By::Agent).await.unwrap().id;
        assert_eq!(
            c.tabs(A).await,
            (
                vec![first.clone(), trip.clone(), work.clone()],
                work.clone()
            )
        );
        // Closing the current one makes its neighbour current; the last is kept.
        c.close_canvas(A, &work).await.unwrap();
        assert_eq!(
            c.tabs(A).await,
            (vec![first.clone(), trip.clone()], trip.clone())
        );
        c.close_canvas(A, &first).await.unwrap();
        assert!(matches!(
            c.close_canvas(A, &trip).await,
            Err(Refused::Invalid(_))
        ));
        // Put away, it is listed still; opening it again puts it last.
        assert_eq!(c.list(A).await.len(), 3);
        c.open_canvas(A, &first).await.unwrap();
        c.open_canvas(A, &work).await.unwrap();
        assert_eq!(
            c.tabs(A).await,
            (
                vec![trip.clone(), first.clone(), work.clone()],
                work.clone()
            )
        );
        // Reordered: those named first.
        c.set_tabs(A, std::slice::from_ref(&work)).await.unwrap();
        assert_eq!(c.tabs(A).await.0, [&work, &trip, &first].map(String::clone));
        assert!(matches!(
            c.set_tabs(A, &[work.clone(), work.clone()]).await,
            Err(Refused::Invalid(_))
        ));
        assert!(matches!(
            c.set_tabs(A, &["0123456789ab".into()]).await,
            Err(Refused::Invalid(_))
        ));
        // Deleted, it leaves the tabs; kept across a restart.
        c.delete(A, &work).await.unwrap();
        assert_eq!(
            c.tabs(A).await,
            (vec![trip.clone(), first.clone()], trip.clone())
        );
        let again = Canvases::new(Box::new(FileStore::new(d.clone())));
        assert_eq!(
            again.tabs(A).await,
            (vec![trip.clone(), first.clone()], trip.clone())
        );
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn many_canvases_shared_by_role() {
        let d = dir();
        let c = Canvases::new(Box::new(FileStore::new(d.clone())));
        let trip = c.create(A, "Coast trip", By::Person).await.unwrap();
        // Made current; the first canvas made too.
        assert_eq!(c.tabs(A).await.1, trip.id);
        assert_eq!(c.list(A).await.len(), 2);
        assert_eq!(c.resolve(A, Some("coast TRIP")).await.unwrap(), trip.id);
        assert!(
            matches!(c.resolve(A, Some("Nope")).await, Err(Refused::NoCanvas(why)) if why.contains("\"Coast trip\""))
        );
        // Bob sees nothing of it until invited; then an invitation.
        assert!(matches!(
            c.canvas(B, &trip.id, "").await,
            Err(Refused::NoCanvas(_))
        ));
        let mut bobs = c.watch(B).await;
        heard(&mut bobs);
        c.invite(A, &trip.id, B.did, B.handle, Role::Viewer)
            .await
            .unwrap();
        assert!(
            heard(&mut bobs)
                .iter()
                .any(|n| matches!(n, Notice::Canvases { canvas: Some(c), .. } if *c == trip.id)),
            "bob's stream nudged"
        );
        let list = c.list(B).await;
        let invite = &list
            .iter()
            .find(|(_, v)| v["key"] == trip.id.as_str())
            .unwrap()
            .1;
        assert_eq!(
            (&invite["viewer"]["role"], &invite["viewer"]["invitedBy"]),
            (&json!("viewer"), &json!(A.did))
        );
        assert_eq!(invite["members"][1]["pending"], true);
        // Not joined yet: not a canvas his tools name.
        assert!(c.resolve(B, Some("Coast trip")).await.is_err());
        // A viewer reads but does not change; opening accepts, a tab.
        c.open_canvas(B, &trip.id).await.unwrap();
        assert_eq!(c.resolve(B, None).await.unwrap(), trip.id);
        assert!(c.tabs(B).await.0.contains(&trip.id));
        assert!(matches!(
            c.apply(B, &trip.id, add("describe_repo"), By::Person).await,
            Err(Refused::Forbidden(_))
        ));
        assert!(matches!(
            c.rename(B, &trip.id, "Mine").await,
            Err(Refused::Forbidden(_))
        ));
        // Made an editor, his tiles are his; both streams on it hear them.
        c.set_role(A, &trip.id, B.did, Role::Editor).await.unwrap();
        let mut alices = c.watch(A).await;
        c.follow(&mut bobs).await;
        assert!(bobs.covers(&trip.id));
        let presence = heard(&mut alices);
        assert!(
            presence
                .iter()
                .any(|n| matches!(n, Notice::Presence { present, .. } if present.len() == 2)),
            "{presence:?}"
        );
        let tile = c
            .apply(B, &trip.id, add("describe_repo"), By::Agent)
            .await
            .unwrap();
        assert_eq!(tile.author, B.did);
        assert!(heard(&mut alices).iter().any(|n| matches!(n,
            Notice::Tile { event, cause, .. } if event.op == "add" && cause.by == By::Agent && cause.did == B.did)));
        // Bob's stream ends: those left are told who is here.
        drop(bobs);
        let after = heard(&mut alices);
        assert!(after.iter().any(|n| matches!(n,
            Notice::Presence { canvas, present, cause } if *canvas == trip.id && present.len() == 1 && cause.did == B.did)),
            "{after:?}");
        // Bob leaves, out of his tabs; the owner never does.
        c.remove(B, &trip.id, B.did).await.unwrap();
        assert!(!c.sees(B.did, &trip.id).await);
        assert!(!c.tabs(B).await.0.contains(&trip.id));
        assert!(matches!(
            c.remove(A, &trip.id, A.did).await,
            Err(Refused::Invalid(_))
        ));
        // Invited again and declining removes him; deleting tells the streams.
        c.invite(A, &trip.id, B.did, B.handle, Role::Editor)
            .await
            .unwrap();
        c.remove(B, &trip.id, B.did).await.unwrap();
        heard(&mut alices);
        c.delete(A, &trip.id).await.unwrap();
        assert!(
            heard(&mut alices)
                .iter()
                .any(|n| matches!(n, Notice::Canvases { canvas: Some(c), .. } if *c == trip.id))
        );
        c.follow(&mut alices).await;
        assert!(!alices.covers(&trip.id));
        assert_eq!(c.list(A).await.len(), 1);
        // Kept: read back by a server started again.
        let again = Canvases::new(Box::new(FileStore::new(d.clone())));
        assert_eq!(again.list(A).await.len(), 1);
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn limits_and_the_tile_cap() {
        let d = dir();
        let c = Canvases::new(Box::new(FileStore::new(d.clone())));
        let first = c.resolve(A, None).await.unwrap();
        for i in 1..MAX_CANVASES {
            c.create(A, &format!("c{i}"), By::Person).await.unwrap();
        }
        assert!(matches!(
            c.create(A, "one more", By::Person).await,
            Err(Refused::Limit(_))
        ));
        for i in 0..(MAX_MEMBERS - 1) {
            c.invite(A, &first, &format!("did:plc:m{i}"), None, Role::Viewer)
                .await
                .unwrap();
        }
        assert!(matches!(
            c.invite(A, &first, "did:plc:late", None, Role::Viewer)
                .await,
            Err(Refused::Limit(_))
        ));
        let mut oldest = None;
        for _ in 0..MAX_TILES {
            let t = c
                .apply(A, &first, add("describe_repo"), By::Person)
                .await
                .unwrap();
            oldest.get_or_insert(t.id);
        }
        c.apply(A, &first, add("describe_repo"), By::Person)
            .await
            .unwrap();
        let tiles = c.tiles(A, &first).await.unwrap();
        assert_eq!(tiles.len(), MAX_TILES);
        assert!(tiles.iter().all(|t| Some(&t.id) != oldest.as_ref()));
        // At the cap, an add refused leaves the oldest where they were.
        let refused = c
            .apply(
                A,
                &first,
                Op::Add {
                    tool: "describe_repo".into(),
                    arguments: json!({ "actor": "bob.test" }),
                    title: None,
                    from: None,
                    after: None,
                    stack: Some("0000000000ff".into()),
                    width: None,
                },
                By::Person,
            )
            .await;
        assert_eq!(refused, Err(Refused::NoTile("0000000000ff".into())));
        assert_eq!(c.tiles(A, &first).await.unwrap(), tiles);
        std::fs::remove_dir_all(&d).unwrap();
    }

    /// A file store whose writes fail while `failing`, whose index answers
    /// a turn late, and which says, as a space store does, that each
    /// canvas is in its owner's space, and each of theirs is to move there.
    struct Faulty {
        files: FileStore,
        failing: Arc<AtomicBool>,
    }

    impl Faulty {
        fn new(dir: std::path::PathBuf) -> (Faulty, Arc<AtomicBool>) {
            let failing = Arc::new(AtomicBool::new(false));
            let files = FileStore::new(dir);
            let store = Faulty {
                files,
                failing: failing.clone(),
            };
            (store, failing)
        }

        fn refused(&self) -> Option<String> {
            self.failing
                .load(Ordering::Relaxed)
                .then(|| "the disk is full".to_string())
        }
    }

    impl Store for Faulty {
        fn canvases(&self) -> Fut<'_, Vec<(CanvasInfo, usize)>> {
            self.files.canvases()
        }

        fn tiles<'a>(&'a self, info: &'a CanvasInfo) -> Fut<'a, Result<Vec<Tile>, String>> {
            self.files.tiles(info)
        }

        fn write<'a>(&'a self, change: Change<'a>) -> Fut<'a, Result<(), String>> {
            match self.refused() {
                Some(e) => Box::pin(async move { Err(e) }),
                None => self.files.write(change),
            }
        }

        fn index<'a>(&'a self, did: &'a str) -> Fut<'a, Option<Index>> {
            Box::pin(async move {
                tokio::task::yield_now().await;
                self.files.index(did).await
            })
        }

        fn put_index<'a>(&'a self, did: &'a str, index: &'a Index) -> Fut<'a, Result<(), String>> {
            match self.refused() {
                Some(e) => Box::pin(async move { Err(e) }),
                None => self.files.put_index(did, index),
            }
        }

        fn legacy<'a>(&'a self, did: &'a str) -> Fut<'a, Option<Vec<Tile>>> {
            self.files.legacy(did)
        }

        fn retire_legacy<'a>(&'a self, did: &'a str) -> Fut<'a, ()> {
            self.files.retire_legacy(did)
        }

        fn forget<'a>(&'a self, did: &'a str) -> Fut<'a, Result<(), Vec<String>>> {
            self.files.forget(did)
        }

        fn person<'a>(&'a self, _did: &'a str) -> Fut<'a, Option<Vec<(CanvasInfo, usize)>>> {
            Box::pin(async { Some(Vec::new()) })
        }

        fn misplaced(&self, _info: &CanvasInfo) -> bool {
            true
        }

        fn storage(&self, info: &CanvasInfo) -> Value {
            json!({ "kind": "space",
                    "uri": format!("at://{}/space/place.hud.workspace/{}", info.owner, info.id) })
        }
    }

    #[tokio::test]
    async fn kept_where_the_store_says_and_failed_writes_held_in_memory() {
        let d = dir();
        let (store, failing) = Faulty::new(d.clone());
        let c = Canvases::new(Box::new(store));
        let first = c.resolve(A, None).await.unwrap();
        let mut w = c.watch(A).await;
        heard(&mut w);
        // A canvas in a space: its tiles' views name their records there.
        let tile = c
            .apply(A, &first, add("describe_repo"), By::Person)
            .await
            .unwrap();
        let uri = format!(
            "at://{0}/space/place.hud.workspace/{first}/{0}/place.hud.tile/{1}",
            A.did, tile.id
        );
        let whole = c.canvas(A, &first, "https://hud.test").await.unwrap();
        assert_eq!(whole["tiles"][0]["uri"], uri);
        assert_eq!(c.tile_view(&first, &tile, "").await["uri"], uri);
        let told = heard(&mut w);
        let event = c.notice_json(&told[0], "").await;
        assert_eq!(event["tile"]["uri"], uri);
        assert_eq!(
            event["by"],
            json!({ "did": A.did, "handle": "alice.test", "kind": "person" })
        );
        // Writes fail: each change is made in memory all the same.
        failing.store(true, Ordering::Relaxed);
        let work = c.create(A, "Work", By::Person).await.unwrap().id;
        c.rename(A, &work, "Play").await.unwrap();
        assert_eq!(c.info(A, &work).await.unwrap()["record"]["name"], "Play");
        assert_eq!(c.list(A).await.len(), 2);
        c.delete(A, &work).await.unwrap();
        assert!(!c.sees(A.did, &work).await);
        // Nothing of it was kept.
        let again = Canvases::new(Box::new(FileStore::new(d.clone())));
        let names: Vec<Value> = again
            .list(A)
            .await
            .into_iter()
            .map(|(_, v)| v["record"]["name"].clone())
            .collect();
        assert_eq!(names, [json!("My canvas")]);
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn a_persons_canvases_forgotten_past_failures() {
        let d = dir();
        let (store, failing) = Faulty::new(d.clone());
        let c = Canvases::new(Box::new(store));
        // Hers, and Bob's, which she is in with a tile of hers.
        let mine = c.resolve(A, None).await.unwrap();
        let bobs = c.create(B, "Bob's", By::Person).await.unwrap().id;
        c.invite(B, &bobs, A.did, A.handle, Role::Editor)
            .await
            .unwrap();
        c.open_canvas(A, &bobs).await.unwrap();
        c.apply(A, &bobs, add("describe_repo"), By::Person)
            .await
            .unwrap();
        // And one she is invited to, with no tile of hers.
        let empty = c.create(B, "Empty", By::Person).await.unwrap().id;
        c.invite(B, &empty, A.did, A.handle, Role::Viewer)
            .await
            .unwrap();
        // Its writes failing: what was not deleted, said.
        failing.store(true, Ordering::Relaxed);
        assert_eq!(
            c.forget(A).await,
            Err(format!(
                "canvas {mine}: the disk is full; your tiles on canvas {bobs}: the disk is full"
            ))
        );
        // Hers, not deleted, still there to delete.
        assert!(c.sees(A.did, &mine).await);
        // Asked again, writes kept: hers deleted, her tile goes from Bob's,
        // then she leaves it.
        failing.store(false, Ordering::Relaxed);
        assert_eq!(c.forget(A).await, Ok(3));
        assert!(!c.sees(A.did, &mine).await);
        assert!(!d.join(format!("{mine}.json")).exists());
        assert!(!c.sees(A.did, &bobs).await);
        assert!(c.tiles(B, &bobs).await.unwrap().is_empty());
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn canvases_gone_while_forgetting_waits_count_for_nothing() {
        let d = dir();
        let c = Canvases::new(Box::new(FileStore::new(d.clone())));
        let mine = c.resolve(A, None).await.unwrap();
        let bobs = c.create(B, "Bob's", By::Person).await.unwrap().id;
        c.invite(B, &bobs, A.did, A.handle, Role::Editor)
            .await
            .unwrap();
        c.open_canvas(A, &bobs).await.unwrap();
        c.apply(A, &bobs, add("describe_repo"), By::Person)
            .await
            .unwrap();
        // Each deleted while forgetting waits its turn at it.
        let ops = c.ops.lock().await;
        let open = c.open(&bobs);
        let slot = open.tiles.lock().await;
        let mut forgetting = std::pin::pin!(c.forget(A));
        assert!(futures::poll!(forgetting.as_mut()).is_pending());
        c.dir().await.canvases.remove(&mine);
        drop(ops);
        assert!(futures::poll!(forgetting.as_mut()).is_pending());
        c.dir().await.canvases.remove(&bobs);
        drop(slot);
        assert_eq!(forgetting.await, Ok(0));
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn first_uses_at_once_make_one_canvas() {
        let d = dir();
        std::fs::create_dir_all(&d).unwrap();
        let old = json!({ "did": A.did, "tiles": [{ "id": "00000000000a", "tool": "describe_repo",
            "arguments": { "actor": "alice.test" }, "title": "alice.test", "x": 0.0, "y": 0.0,
            "w": 420.0, "h": 560.0, "by": "agent", "at": "2026-11-14T00:00:00.000Z" }] });
        let legacy = d.join(format!("{}.json", jose::sha256(A.did)));
        std::fs::write(&legacy, old.to_string()).unwrap();
        let (store, _) = Faulty::new(d.clone());
        let c = Canvases::new(Box::new(store));
        let (one, two) = tokio::join!(c.list(A), c.list(A));
        assert_eq!(one, two);
        assert_eq!(one.len(), 1);
        // The canvas from before moved into it once.
        assert_eq!(one[0].1["tileCount"], 1);
        assert!(legacy.with_extension("json.moved").exists());
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn the_current_canvas_found_or_made_again() {
        let d = dir();
        let c = Canvases::new(Box::new(FileStore::new(d.clone())));
        let first = c.resolve(A, None).await.unwrap();
        let trip = c.create(A, "Coast trip", By::Person).await.unwrap().id;
        let work = c.create(A, "Work", By::Person).await.unwrap().id;
        // Every tab gone: of the canvases they own, the first opens.
        c.close_canvas(A, &first).await.unwrap();
        c.close_canvas(A, &trip).await.unwrap();
        c.delete(A, &work).await.unwrap();
        assert_eq!(c.tabs(A).await, (vec![first.clone()], first.clone()));
        // None left: "My canvas" again, under its own id.
        c.delete(A, &first).await.unwrap();
        c.delete(A, &trip).await.unwrap();
        assert_eq!(c.resolve(A, None).await.unwrap(), first);
        assert_eq!(c.list(A).await[0].1["record"]["name"], FIRST_NAME);

        // Bob's first canvas's id taken by someone else's; Carol's listed in
        // her index, kept where it is not read: each gets another.
        let files = FileStore::new(d.clone());
        let carol = Who {
            did: "did:plc:carol",
            handle: None,
        };
        let theirs = CanvasInfo {
            id: first_id(B.did),
            name: "Not Bob's".into(),
            owner: carol.did.into(),
            members: vec![Member {
                did: carol.did.into(),
                handle: None,
                role: Role::Owner,
                joined: true,
                invited_by: None,
            }],
            created_at: "2026-11-14T00:00:00.000Z".into(),
            updated_at: "2026-11-14T00:00:00.000Z".into(),
        };
        files.put(&theirs, &[]).unwrap();
        let listed = Index {
            canvases: vec![first_id(carol.did)],
            open: Some(Vec::new()),
            current: None,
        };
        files.put_index(carol.did, &listed).await.unwrap();
        let again = Canvases::new(Box::new(files));
        assert!(again.list(B).await.is_empty());
        let bobs = again.resolve(B, None).await.unwrap();
        assert_ne!(bobs, first_id(B.did));
        assert_eq!(again.list(B).await[0].1["key"], bobs.as_str());
        let carols = again.resolve(carol, None).await.unwrap();
        assert_ne!(carols, first_id(carol.did));
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn an_index_lost_opens_every_canvas() {
        let d = dir();
        let c = Canvases::new(Box::new(FileStore::new(d.clone())));
        let first = c.resolve(A, None).await.unwrap();
        let trip = c.create(A, "Coast trip", By::Person).await.unwrap().id;
        c.close_canvas(A, &first).await.unwrap();
        std::fs::remove_file(
            d.join("by-did")
                .join(format!("{}.json", jose::sha256(A.did))),
        )
        .unwrap();
        let again = Canvases::new(Box::new(FileStore::new(d.clone())));
        let mut open = again.tabs(A).await.0;
        open.sort();
        let mut both = vec![first, trip];
        both.sort();
        assert_eq!(open, both);
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn refusals_invitations_and_retitles() {
        let d = dir();
        let c = Canvases::new(Box::new(FileStore::new(d.clone())));
        let trip = c.create(A, "Trip", By::Person).await.unwrap().id;
        let other = c.create(A, "trip", By::Person).await.unwrap().id;
        assert!(matches!(
            c.resolve(A, Some("TRIP")).await,
            Err(Refused::Invalid(why)) if why.contains(&trip) && why.contains(&other)
        ));
        assert_eq!(c.info(B, &trip).await, Err(Refused::NoCanvas(trip.clone())));
        assert!(matches!(
            c.invite(A, &trip, B.did, B.handle, Role::Owner).await,
            Err(Refused::Invalid(_))
        ));
        c.invite(A, &trip, B.did, B.handle, Role::Editor)
            .await
            .unwrap();
        assert!(matches!(
            c.set_role(A, &trip, B.did, Role::Owner).await,
            Err(Refused::Invalid(_))
        ));
        assert!(matches!(
            c.remove(A, &trip, "did:plc:nobody").await,
            Err(Refused::Invalid(why)) if why.contains("not a member")
        ));
        // An editor who has not accepted changes nothing yet.
        assert!(matches!(
            c.apply(B, &trip, add("describe_repo"), By::Person).await,
            Err(Refused::Forbidden(why)) if why.starts_with("Accept the invitation")
        ));
        // Not open, it is not closed.
        let tabs = c.tabs(B).await;
        c.close_canvas(B, &trip).await.unwrap();
        assert_eq!(c.tabs(B).await, tabs);
        // Accepted without a handle: the one invited with stays.
        let nameless = Who {
            did: B.did,
            handle: None,
        };
        c.open_canvas(nameless, &trip).await.unwrap();
        let info = c.info_of(&trip).await.unwrap();
        assert_eq!(info.member(B.did).unwrap().handle.as_deref(), B.handle);
        // Opened again: current, where it was.
        let (open, _) = c.tabs(A).await;
        c.open_canvas(A, &trip).await.unwrap();
        assert_eq!(c.tabs(A).await, (open, trip.clone()));
        // A title made from its call follows it; one given stays.
        let t = c
            .apply(A, &trip, add("describe_repo"), By::Person)
            .await
            .unwrap();
        assert_eq!(c.tile(B, &trip, &t.id).await, Ok(t.clone()));
        assert_eq!(
            c.tile(A, &trip, "0000000000ff").await,
            Err(Refused::NoTile("0000000000ff".into()))
        );
        assert_eq!(
            c.tile(B, &other, &t.id).await,
            Err(Refused::NoCanvas(other.clone()))
        );
        let update = |title: Option<&str>, actor: Option<&str>| Op::Update {
            id: t.id.clone(),
            title: title.map(str::to_string),
            call: actor.map(|a| ("describe_repo".to_string(), json!({ "actor": a }))),
        };
        let moved = c
            .apply(A, &trip, update(None, Some("bob.test")), By::Person)
            .await
            .unwrap();
        assert_ne!(moved.title, t.title);
        assert_eq!(
            moved.title,
            default_title(
                "describe_repo",
                &json!({ "actor": "bob.test" }),
                None,
                A.handle
            )
        );
        c.apply(A, &trip, update(Some("Bob"), None), By::Person)
            .await
            .unwrap();
        let kept = c
            .apply(A, &trip, update(None, Some("carol.test")), By::Person)
            .await
            .unwrap();
        assert_eq!(
            (kept.title.as_str(), &kept.arguments["actor"]),
            ("Bob", &json!("carol.test"))
        );
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn streams_hear_each_person_once_and_end_with_the_server() {
        let d = dir();
        let c = Canvases::new(Box::new(FileStore::new(d.clone())));
        let id = c.resolve(A, None).await.unwrap();
        let mut one = c.watch(A).await;
        let _two = c.watch(A).await;
        assert_eq!(
            heard(&mut one).last(),
            Some(&Notice::Presence {
                canvas: id.clone(),
                present: vec![(A.did.into(), A.handle.map(str::to_string))],
                cause: Cause::of(A, By::Person),
            })
        );
        // Someone with no handle, as told.
        let nameless = Notice::Presence {
            canvas: id.clone(),
            present: vec![("did:plc:x".into(), None)],
            cause: Cause::of(A, By::Agent),
        };
        assert_eq!(
            c.notice_json(&nameless, "").await,
            json!({ "$type": "place.hud.defs#presenceEvent", "canvas": id,
                    "present": [{ "did": "did:plc:x" }],
                    "by": { "did": A.did, "handle": "alice.test", "kind": "agent" } })
        );
        // Closed: every stream ends, and any opened after.
        c.close();
        assert_eq!(
            one.notices.try_recv(),
            Err(broadcast::error::TryRecvError::Closed)
        );
        let mut late = c.watch(A).await;
        assert_eq!(
            late.notices.try_recv(),
            Err(broadcast::error::TryRecvError::Closed)
        );
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn unreadable_tiles_read_as_none_and_deleted_canvases_stay_so() {
        let d = dir();
        let c = Canvases::new(Box::new(FileStore::new(d.clone())));
        let id = c.resolve(A, None).await.unwrap();
        c.apply(A, &id, add("describe_repo"), By::Person)
            .await
            .unwrap();
        let again = Canvases::new(Box::new(FileStore::new(d.clone())));
        assert_eq!(again.list(A).await[0].1["tileCount"], 1);
        std::fs::write(d.join(format!("{id}.json")), "not a canvas").unwrap();
        assert_eq!(again.tiles(A, &id).await.unwrap(), Vec::new());
        // A canvas deleted is not written again.
        let gone = c.create(A, "Gone", By::Person).await.unwrap().id;
        c.delete(A, &gone).await.unwrap();
        c.rewrite(&gone).await;
        assert!(!d.join(format!("{gone}.json")).exists());
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn tiles_stacked_unstacked_and_refused() {
        let d = dir();
        let c = Canvases::new(Box::new(FileStore::new(d.clone())));
        let id = c.resolve(A, None).await.unwrap();
        let head = c
            .apply(A, &id, add("describe_repo"), By::Person)
            .await
            .unwrap();
        let under = |stack: &str| Op::Add {
            tool: "describe_repo".into(),
            arguments: json!({ "actor": "bob.test" }),
            title: None,
            from: None,
            after: None,
            stack: Some(stack.into()),
            width: None,
        };
        // Added under a tile, and out again as a column of its own.
        let stacked = c.apply(A, &id, under(&head.id), By::Person).await.unwrap();
        assert_eq!(stacked.stack.as_deref(), Some(head.id.as_str()));
        let unstacked = c
            .apply(
                A,
                &id,
                Op::Unstack {
                    id: stacked.id.clone(),
                },
                By::Person,
            )
            .await
            .unwrap();
        assert_eq!(unstacked.stack, None);
        // Under a tile not there: refused, nothing changed.
        let before = c.tiles(A, &id).await.unwrap();
        assert_eq!(
            c.apply(A, &id, under("0000000000ff"), By::Person).await,
            Err(Refused::NoTile("0000000000ff".into()))
        );
        assert_eq!(c.tiles(A, &id).await.unwrap(), before);
        // A tile not there retitled, a canvas not there renamed, a canvas
        // left by one not in it: refused.
        let retitle = Op::Update {
            id: "0000000000ff".into(),
            title: Some("x".into()),
            call: None,
        };
        assert_eq!(
            c.apply(A, &id, retitle, By::Person).await,
            Err(Refused::NoTile("0000000000ff".into()))
        );
        assert_eq!(
            c.rename(A, "0000000000fe", "x").await,
            Err(Refused::NoCanvas("0000000000fe".into()))
        );
        assert_eq!(
            c.remove(B, &id, B.did).await,
            Err(Refused::NoCanvas(id.clone()))
        );
        // Told: who is here, by handle; a change by one with none known.
        let here = Notice::Presence {
            canvas: id.clone(),
            present: vec![(A.did.into(), A.handle.map(str::to_string))],
            cause: Cause::of(A, By::Person),
        };
        assert_eq!(
            c.notice_json(&here, "").await["present"],
            json!([{ "did": A.did, "handle": "alice.test" }])
        );
        let nameless = Who {
            did: "did:plc:x",
            handle: None,
        };
        let changed = Notice::Canvases {
            canvas: None,
            cause: Some(Cause::of(nameless, By::Agent)),
        };
        assert_eq!(
            c.notice_json(&changed, "").await,
            json!({ "$type": "place.hud.defs#canvasesEvent",
                    "by": { "did": "did:plc:x", "kind": "agent" } })
        );
        std::fs::remove_dir_all(&d).unwrap();
    }
}