Skip to main content

tilo_actions/tree/
walk.rs

1//! The walk of the published tree: from the workspace root to the resource an address names,
2//! over whatever provider serves it.
3//!
4//! The root is the workspace. Its children are what publishes there: each app (running or
5//! installed), the workspace's own resources (`workspace`), the host's services, the
6//! workspace's folder (`files`) and its invocations (`invocations`), each with the provider
7//! that serves it. Below a child, a name is resolved against that provider's live directory,
8//! level by level, as deep as its resources nest. Every caller resolves addresses here: the MCP
9//! tools, the REST API and the command line, each over its own [`ActionProvider`].
10
11use std::collections::HashMap;
12use std::fmt;
13use std::future::Future;
14use std::pin::Pin;
15use std::sync::{Arc, Mutex};
16use std::time::Duration;
17
18use serde_json::Value;
19use tilo_lock::MutexRecover as _;
20
21use super::level::read_on;
22use super::{
23    Address, Level, Node, Segment, TypeNames, app_meant, is_program_form, level_of, path_name,
24    pick, rank,
25};
26use crate::ActionDescriptor;
27use crate::InvocationId;
28use crate::remote::{
29    ActionCallError, ActionProvider, Caller, CataloguePage, CatalogueQuery, InvocationState,
30};
31
32/// Resource rows one directory level reads at most, across its pages.
33pub const LEVEL_PAGES: usize = 4;
34/// Times a name not found is looked for again, after pauses that double from 5 ms to 200 ms:
35/// about seven tenths of a second in all.
36const LOOKS_AGAIN: u32 = 8;
37/// The moment those looks come to. A level that was read on past its bound is looked through
38/// again only within it: one that takes longer to read whole is not read whole eight times.
39const LOOKS_MOMENT: Duration = Duration::from_millis(700);
40/// Rows asked per page.
41pub const PAGE_ROWS: u32 = 128;
42/// Containers at an app's top level whose contents the app's root also
43/// offers: a notebook's pages are the app's own.
44pub const ROOT_PEEK: usize = 3;
45/// Containers a name that is not where it was looked for reads on, one by
46/// one, before it is called missing.
47pub const DEEP_READS: usize = 16;
48/// Longest name asked of an app whole; a longer one is a key or an id.
49const NAME_BYTES: usize = 256;
50/// Resources a listing's first page holds: what a level read near is read to.
51pub const LISTED_NEAR: usize = 40;
52/// The longest pause between two reads of a directory level that keeps
53/// changing while it is read.
54pub const RESTART_PAUSE_MAX: Duration = Duration::from_millis(200);
55/// Pages of installed apps read at most: a page holds 256.
56const INSTALLED_PAGES: usize = 4;
57/// How long a level that keeps moving on, or that its app cannot read now, is read again.
58pub const LEVEL_WAIT: Duration = Duration::from_secs(5);
59/// How long starting an app is followed, over as many waits as it takes.
60pub const START_WAIT: Duration = Duration::from_secs(60);
61/// How long one wait for an invocation to settle lasts when its caller names none.
62pub const SETTLE_WAIT: Duration = Duration::from_secs(5);
63/// Paths and apps a tree keeps resolved at most: a caller naming ever new paths does not grow
64/// them without end.
65pub const RESOLVED_PATHS: usize = 256;
66/// The resolved paths a tree keeps for its listings, at most: a page of any listing reads the
67/// one its cursor names, and a caller of thousands of anything holds only these.
68const LISTING_RESOLUTIONS: usize = 32;
69/// The app that shows the workspace's folder: the folder is every workspace's own, served
70/// by the framework rather than installed into it.
71pub const FILES_APP: &str = "so.tilo.file-explorer";
72/// How long a catalogue page is waited for, and a workspace that refused it as not serving
73/// yet: a server that restarted serves one again within a minute, and a call that gave up
74/// sooner sent its caller after evidence it never had.
75pub const ANSWER_WAIT: Duration = Duration::from_secs(60);
76
77/// How a tree asks its provider for a catalogue page, when not by the provider's own
78/// `query`: a bridge on a shared runtime asks off that runtime's thread.
79pub type Asker<P> = Box<
80    dyn Fn(
81            &P,
82            &Caller,
83            CatalogueQuery,
84        ) -> crate::remote::Pending<Result<CataloguePage, ActionCallError>>
85        + Send
86        + Sync,
87>;
88
89/// `future`'s output, or none once `wait` passed first.
90pub async fn within<F: Future>(pause: &dyn Pause, wait: Duration, future: F) -> Option<F::Output> {
91    Within {
92        future: Box::pin(future),
93        timer: pause.pause(wait),
94    }
95    .await
96}
97
98struct Within<F> {
99    future: Pin<Box<F>>,
100    timer: Pin<Box<dyn Future<Output = ()> + Send>>,
101}
102
103impl<F: Future> Future for Within<F> {
104    type Output = Option<F::Output>;
105
106    fn poll(
107        mut self: Pin<&mut Self>,
108        context: &mut std::task::Context<'_>,
109    ) -> std::task::Poll<Self::Output> {
110        if let std::task::Poll::Ready(output) = self.future.as_mut().poll(context) {
111            return std::task::Poll::Ready(Some(output));
112        }
113        self.timer.as_mut().poll(context).map(|()| None)
114    }
115}
116
117/// How a tree waits: a pause between two reads of a directory that keeps moving, and the
118/// clock its deadlines are measured on. The walk itself runs on no executor of its own, so
119/// it builds wherever the provider does (a browser page included).
120pub trait Pause: Send + Sync {
121    /// Resolves once `how_long` has passed.
122    fn pause(&self, how_long: Duration) -> Pin<Box<dyn Future<Output = ()> + Send>>;
123    /// Where this clock stands, from an origin of its own: only differences are read.
124    fn now(&self) -> Duration;
125}
126
127/// The directory levels one call read, by the resource each holds.
128pub type Levels = HashMap<String, Level>;
129
130/// A path resolved against the live directory, kept for the pages that list on from it.
131pub type ListingResolution = Arc<Resolved>;
132
133/// Why an address did not resolve, or a call on it did not start. Each says what happened in
134/// the words a caller is answered with ([`fmt::Display`]); a caller that tells a refusal apart
135/// reads the variant.
136#[derive(Clone, Debug)]
137pub enum Unresolved {
138    /// The provider refused a query asked on the way.
139    Asked(ActionCallError),
140    /// The provider dropped a query without answering it.
141    Stopped,
142    /// A directory kept moving on while it was read.
143    KeptChanging,
144    /// An app cannot read its directory right now.
145    CannotListNow,
146    /// What a query named could not be listed, and why.
147    Unavailable(String),
148    /// No resource under `at` goes by `name`; `has` are the addresses of those it lists.
149    NoSuch {
150        name: String,
151        at: String,
152        has: Vec<String>,
153    },
154    /// The app `name` is installed but runs nowhere; `opens` when the caller may start it.
155    NotRunning { name: String, opens: bool },
156    /// The caller may not start the app `name`.
157    MayNotOpen { name: String },
158    /// No running app is named `name`, and the installed ones could not be read.
159    InstalledUnread {
160        name: String,
161        reason: Box<Unresolved>,
162    },
163    /// Starting `app_id` did not end in its running: how it ended instead, and the code its
164    /// start failed with (empty when it did not fail).
165    NotStarted {
166        app_id: String,
167        why: String,
168        code: String,
169    },
170    /// A name the walk could not place, said whole (one several resources or apps carry, a
171    /// window of another app, an action no resource offers).
172    Said(String),
173}
174
175impl Unresolved {
176    /// Whether this is no refusal but what the address names, said: an app that is
177    /// installed and not running. A listing answers it as its page.
178    #[must_use]
179    pub const fn is_note(&self) -> bool {
180        matches!(self, Self::NotRunning { .. })
181    }
182
183    /// Whether this says the app that was asked has gone — its provider stopped answering, or
184    /// answered that what it served is unavailable — so what a session kept of it is stale. A
185    /// decision about a name, such as no resource by it, is not.
186    #[must_use]
187    pub const fn app_gone(&self) -> bool {
188        matches!(
189            self,
190            Self::Stopped | Self::Asked(ActionCallError::Unavailable { .. })
191        )
192    }
193
194    /// What this says, without the code it starts with.
195    #[must_use]
196    pub fn words(&self) -> String {
197        let said = self.to_string();
198        match said.split_once(": ") {
199            Some((code, rest))
200                if !code.is_empty()
201                    && code
202                        .bytes()
203                        .all(|byte| byte.is_ascii_lowercase() || byte == b'_') =>
204            {
205                rest.to_owned()
206            }
207            _ => said,
208        }
209    }
210}
211
212impl From<String> for Unresolved {
213    fn from(said: String) -> Self {
214        Self::Said(said)
215    }
216}
217
218impl From<&str> for Unresolved {
219    fn from(said: &str) -> Self {
220        Self::Said(said.to_owned())
221    }
222}
223
224impl From<ActionCallError> for Unresolved {
225    fn from(refused: ActionCallError) -> Self {
226        Self::Asked(refused)
227    }
228}
229
230impl fmt::Display for Unresolved {
231    fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
232        match self {
233            Self::Asked(refused) => out.write_str(&refused.said()),
234            Self::Stopped => out.write_str("the desktop's actions stopped answering"),
235            Self::KeptChanging => {
236                out.write_str("the app's directory kept changing while it was read; try again")
237            }
238            Self::CannotListNow => {
239                out.write_str("the app cannot list what it has right now; try again")
240            }
241            Self::Unavailable(reason) | Self::Said(reason) => out.write_str(reason),
242            Self::NoSuch { name, at, has } if has.is_empty() => {
243                write!(out, "no {name} in {at}; it lists nothing here")
244            }
245            Self::NoSuch { name, at, has } => {
246                write!(out, "no {name} in {at}; it has: {}", list_names(has))
247            }
248            Self::NotRunning { name, opens: true } => write!(
249                out,
250                "not_found: {name} is installed but not running; start it with tilo_do {}#open, or run one of its actions and it starts first",
251                path_name(name)
252            ),
253            Self::NotRunning { name, opens: false } => write!(
254                out,
255                "not_found: {name} is installed but not running, and {}",
256                may_not_open(name)
257            ),
258            Self::MayNotOpen { name } => out.write_str(&may_not_open(name)),
259            Self::InstalledUnread { name, reason } => write!(
260                out,
261                "no running app is named {name}, and the installed apps could not be read: {}",
262                reason.words()
263            ),
264            // A start refused for a reason the same call is asked again for (the workspace
265            // not serving the caller yet, or not answering) keeps that code before its words,
266            // so a caller reading them is told to ask again rather than that nothing is there.
267            Self::NotStarted { app_id, why, code } if ActionCallError::ask_again_code(code) => {
268                write!(out, "{code}: {app_id} did not start: {why}")
269            }
270            Self::NotStarted { app_id, why, .. } => write!(out, "{app_id} did not start: {why}"),
271        }
272    }
273}
274
275impl std::error::Error for Unresolved {}
276
277/// Why an installed app this caller may not open stays closed, and who changes that.
278fn may_not_open(name: &str) -> String {
279    format!(
280        "this agent may not open {name}: the person decides which apps an agent may use in this workspace"
281    )
282}
283
284/// How many names an error lists before it stops, the rest counted.
285#[must_use]
286pub fn list_names(names: &[String]) -> String {
287    let mut shown: Vec<&str> = names
288        .iter()
289        .take(super::NAMES_LISTED)
290        .map(String::as_str)
291        .collect();
292    let more = names.len().saturating_sub(super::NAMES_LISTED);
293    let tail = format!("… +{more}");
294    if more > 0 {
295        shown.push(&tail);
296    }
297    shown.join(", ")
298}
299
300/// [`list_names`], or `none` for no names: an empty list reads as a sentence cut short.
301#[must_use]
302pub fn list_or_none(names: &[String]) -> String {
303    if names.is_empty() {
304        "none".to_owned()
305    } else {
306        list_names(names)
307    }
308}
309
310/// The pause before the `read`th read of a directory level that keeps changing: none before
311/// the second, then doubling from 5 ms to [`RESTART_PAUSE_MAX`].
312#[must_use]
313pub fn restart_pause(read: u32) -> Duration {
314    let Some(doublings) = read.checked_sub(2) else {
315        return Duration::ZERO;
316    };
317    Duration::from_millis(5)
318        .checked_mul(1_u32.checked_shl(doublings).unwrap_or(u32::MAX))
319        .map_or(RESTART_PAUSE_MAX, |pause| pause.min(RESTART_PAUSE_MAX))
320}
321
322/// Whether `id` is a chain's resource: the head of the items an app keeps as one list.
323#[must_use]
324pub fn is_chain(id: &str) -> bool {
325    id.strip_prefix("chain:")
326        .is_some_and(|document| !document.is_empty())
327}
328
329/// The child of the workspace root a path starts with, as it was written (`browser@4711`). A
330/// device's settings section (`devices/<id>/settings/power`) is the settings app's, as a person's
331/// (`settings/appearance`) is; any other resource a device keeps of its own names its app right
332/// after the device (`devices/<id>/<app>/…`), as a root each device keeps its own does. No app is
333/// called `devices`.
334#[must_use]
335pub fn app_of(parsed: &Address) -> String {
336    if device_section(parsed) {
337        return tilo_app_id::apps::SETTINGS.to_owned();
338    }
339    if is_device_resource(parsed)
340        && let Some(app) = parsed.segments.get(2)
341    {
342        return app.written();
343    }
344    parsed
345        .segments
346        .first()
347        .map(Segment::written)
348        .unwrap_or_default()
349}
350
351/// Whether `parsed` is a resource a device keeps of its own (`devices/<id>/…`).
352#[must_use]
353pub fn is_device_resource(parsed: &Address) -> bool {
354    parsed
355        .segments
356        .first()
357        .is_some_and(|first| first.written() == "devices")
358}
359
360/// Whether `parsed` names a device's settings section, which its app finds by its whole address.
361fn device_section(parsed: &Address) -> bool {
362    parsed
363        .segments
364        .first()
365        .is_some_and(|first| first.written() == "devices")
366        && crate::remote::settings_resources::is_section(&parsed.resource())
367}
368
369/// The segments of a path below the child of the root it starts with: below its app, which a
370/// device's own resources name after the device (`devices/<id>/<app>/…`).
371#[must_use]
372pub fn below_app(parsed: &Address) -> &[Segment] {
373    if is_device_resource(parsed) && !device_section(parsed) {
374        return parsed.segments.get(3..).unwrap_or_default();
375    }
376    parsed.segments.get(1..).unwrap_or_default()
377}
378
379/// Whether a segment of `parsed` below its root child names a type the way a program writes
380/// one (`tasks.Task`): only then are a program's type names asked for.
381#[must_use]
382pub fn names_a_type(parsed: &Address) -> bool {
383    below_app(parsed)
384        .iter()
385        .any(|segment| is_program_form(&segment.written()))
386}
387
388/// Whether `name` names Files, every workspace's own folder: its name, the last part of its id,
389/// or its id, in any case and however its words are parted (`file_explorer`).
390#[must_use]
391pub fn names_files(name: &str) -> bool {
392    let name = super::folded(name);
393    ["files", "file-explorer", FILES_APP]
394        .iter()
395        .any(|files| name == super::folded(files))
396}
397
398/// The app a name beginning with a kind names (`tasks.tracker` is the Tasks
399/// app's tracker), when the name is one kind and no app: a kind is the app's
400/// own name and one more word, and an item's kind names its collection after
401/// that (`tasks.issues.issues`, `tasks.issues.links`), where a package's id is
402/// a domain and its names.
403#[must_use]
404pub fn type_address(name: &str) -> Option<&str> {
405    let (app, kind) = name.split_once('.')?;
406    (!app.is_empty() && !kind.is_empty() && !kind.starts_with('.') && !kind.ends_with('.'))
407        .then_some(app)
408}
409
410/// The running app `name` names among `running`: its id whole, or the last part of it.
411///
412/// # Errors
413/// No running app is named so, or several are.
414pub fn app_named(name: &str, running: &[&str]) -> Result<String, String> {
415    if running.contains(&name) {
416        return Ok(name.to_owned());
417    }
418    let mut by_tail = running
419        .iter()
420        .filter(|id| {
421            id.rsplit('.')
422                .next()
423                .is_some_and(|tail| tail.eq_ignore_ascii_case(name))
424        })
425        .collect::<Vec<_>>();
426    by_tail.dedup();
427    match by_tail.as_slice() {
428        [one] => Ok((**one).to_owned()),
429        [] => Err(not_running(name, running)),
430        many => Err(format!(
431            "{name} names several running apps: {}; name one",
432            many.iter().map(|id| **id).collect::<Vec<_>>().join(", ")
433        )),
434    }
435}
436
437/// Why `app_id` cannot be addressed: what is running instead, under the
438/// name to use for each, and how to start an app that is not.
439#[must_use]
440pub fn not_running(app_id: &str, running: &[&str]) -> String {
441    let mut ids = running.to_vec();
442    ids.sort_unstable();
443    ids.dedup();
444    let listed = if ids.is_empty() {
445        "no app is running".to_owned()
446    } else {
447        format!(
448            "running: {}",
449            ids.iter()
450                .map(|id| match id.rsplit_once('.') {
451                    Some((_, tail)) => format!("{id} ({tail})"),
452                    None => (*id).to_owned(),
453                })
454                .collect::<Vec<_>>()
455                .join(", ")
456        )
457    };
458    format!(
459        "{app_id} is not running ({listed}); name a running app by its id, or start one with tilo_do <app>#open"
460    )
461}
462
463/// Whether `provider` is a window of an app, or a record a device serves whoever has it open
464/// (a host serving its workspace's records): the app, live, as opposed to a service of the
465/// host's that answers for an app id.
466#[must_use]
467pub fn is_window(provider: &str) -> bool {
468    provider.parse::<u64>().is_ok() || crate::remote::is_resource_provider(provider)
469}
470
471/// The published tree of one workspace as one caller walks it, over `P`.
472///
473/// It keeps what it read for the calls after: the directory levels of each provider, the
474/// app each name means and the paths its listings resolved, each bounded. What it kept is
475/// checked by the provider when a call reaches it, so a stale one costs a refusal, never a
476/// wrong write; a refusal drops what was kept of that app ([`Self::forget_app`]).
477pub struct Tree<P> {
478    provider: P,
479    caller: Caller,
480    workspace: String,
481    pause: Arc<dyn Pause>,
482    asker: Option<Asker<P>>,
483    /// The directory levels read, by the provider that serves them and the resource they hold.
484    dirs: Mutex<HashMap<String, Levels>>,
485    /// Where each name was found: the provider a call found or started the app on, the app an
486    /// installed name means, or a decision no grant can change — never what this caller may
487    /// open, which the workspace decides on every call.
488    apps: Mutex<HashMap<String, Looked>>,
489    /// The paths listings resolved, by the path as written and the directory revision they
490    /// were resolved at.
491    listings: Mutex<HashMap<(String, String), ListingResolution>>,
492}
493
494impl<P> Tree<P> {
495    /// The tree of `workspace` as `caller` walks it over `provider`, pausing with `pause`.
496    pub fn new(provider: P, caller: Caller, workspace: String, pause: Arc<dyn Pause>) -> Self {
497        Self {
498            provider,
499            caller,
500            workspace,
501            pause,
502            asker: None,
503            dirs: Mutex::default(),
504            apps: Mutex::default(),
505            listings: Mutex::default(),
506        }
507    }
508
509    /// The tree asking its catalogue pages with `asker` rather than the provider's `query`.
510    #[must_use]
511    pub fn asking(mut self, asker: Asker<P>) -> Self {
512        self.asker = Some(asker);
513        self
514    }
515
516    /// The provider every call of this tree goes to.
517    pub const fn provider(&self) -> &P {
518        &self.provider
519    }
520
521    /// Who walks it.
522    pub const fn caller(&self) -> &Caller {
523        &self.caller
524    }
525
526    /// The workspace it is the tree of.
527    pub fn workspace(&self) -> &str {
528        &self.workspace
529    }
530
531    /// How it waits.
532    pub fn pause(&self) -> &Arc<dyn Pause> {
533        &self.pause
534    }
535
536    /// The resolution `path` was listed by at the directory revision `revision`, when this
537    /// tree listed one: a later page reads by it instead of resolving the path again.
538    pub fn listing_resolution(&self, path: &str, revision: &str) -> Option<ListingResolution> {
539        if revision.is_empty() {
540            return None;
541        }
542        self.listings
543            .lock_recover()
544            .get(&(path.to_owned(), revision.to_owned()))
545            .cloned()
546    }
547
548    /// Keep the resolution `path` was listed by at `revision`, for the page that reads on
549    /// from it. The newest [`LISTING_RESOLUTIONS`] are kept; what was listed before those is
550    /// resolved again when it is listed again.
551    pub fn remember_listing_resolution(
552        &self,
553        path: &str,
554        revision: &str,
555        resolved: &ListingResolution,
556    ) {
557        if revision.is_empty() {
558            return;
559        }
560        let mut kept = self.listings.lock_recover();
561        if kept.len() >= LISTING_RESOLUTIONS {
562            kept.clear();
563        }
564        kept.insert((path.to_owned(), revision.to_owned()), Arc::clone(resolved));
565    }
566}
567
568impl<P: ActionProvider + Sync + Clone + Send + 'static> Tree<P> {
569    /// The provider's word on `invocation`, read off a runtime's worker
570    /// ([`observed_off_the_worker`](crate::remote::observed_off_the_worker)): a provider that
571    /// waits on a device must not wait on the worker the answer needs.
572    pub(super) async fn observed(&self, invocation: &InvocationId) -> Option<InvocationState> {
573        crate::remote::observed_off_the_worker(
574            self.provider.clone(),
575            self.caller.clone(),
576            *invocation,
577        )
578        .await
579    }
580
581    /// One catalogue page asked of the provider as this tree's caller, waited for until it
582    /// answers, for at most [`ANSWER_WAIT`]. A workspace that just started opens the documents
583    /// a listing reads before it answers, and an ask given up sooner left the caller waiting
584    /// for an answer it was already sent. A workspace a server is not serving yet refuses the
585    /// ask and takes it once it does: its session moving is the signal to ask again.
586    ///
587    /// # Errors
588    /// The provider refused it, did not answer in time, or dropped it unanswered.
589    pub async fn ask(&self, query: CatalogueQuery) -> Result<CataloguePage, Unresolved> {
590        let until = self.pause.now().saturating_add(ANSWER_WAIT);
591        let left = || until.saturating_sub(self.pause.now());
592        loop {
593            let asked = match &self.asker {
594                Some(asker) => asker(&self.provider, &self.caller, query.clone()),
595                None => self.provider.query(&self.caller, query.clone()),
596            };
597            // No answer is not an answer that nothing is there: the caller hears it went
598            // unanswered, never that the path names nothing.
599            let answer = match within(&*self.pause, left(), asked).await {
600                None => return Err(Unresolved::Asked(ActionCallError::Unanswered)),
601                Some(None) => return Err(Unresolved::Stopped),
602                Some(Some(answer)) => answer,
603            };
604            if matches!(answer, Err(ActionCallError::NotReady))
605                && let Some(moved) = self.provider.session_state_changed(&self.caller)
606                && within(&*self.pause, left(), moved).await.is_some()
607            {
608                continue;
609            }
610            return answer.map_err(Unresolved::Asked);
611        }
612    }
613
614    /// Every publisher this caller may browse in its workspace, each by its provider id with
615    /// what it is: an application's window (a numeric peer) or one of the host's own services
616    /// (`tilo.desktop`), by the app id it answers for. Host services first, then windows
617    /// oldest first, so the newest window of an app is its last entry. With them, the
618    /// revision the provider answered at.
619    ///
620    /// # Errors
621    /// The provider could not be asked.
622    pub async fn providers(&self) -> Result<(String, Vec<(String, Value)>), Unresolved> {
623        let page = self
624            .ask(CatalogueQuery {
625                max_results: 0,
626                ..CatalogueQuery::default()
627            })
628            .await?;
629        let mut listed = page
630            .providers
631            .into_iter()
632            .filter(|provider| provider.browsable && provider.workspace == self.workspace)
633            .map(|provider| {
634                let peer = provider.provider.parse::<u64>().ok();
635                let mut entry = serde_json::json!({
636                    "provider": provider.provider,
637                    "app_id": provider.app_id,
638                    "document_id": provider.document_id,
639                });
640                if let (Some(peer), Some(fields)) = (peer, entry.as_object_mut()) {
641                    fields.insert("peer_id".to_owned(), serde_json::json!(peer));
642                    fields.insert(
643                        "uri".to_owned(),
644                        serde_json::json!(format!("tilo://apps/{peer}")),
645                    );
646                }
647                (provider.provider, entry)
648            })
649            .collect::<Vec<_>>();
650        listed.sort_by_key(|(provider, _)| (provider.parse::<u64>().ok(), provider.clone()));
651        Ok((page.revision, listed))
652    }
653}
654
655/// What an app name names.
656#[derive(Clone)]
657pub enum AppRef {
658    /// A running publisher of the app: its newest window, the window the
659    /// path named (`browser@4711`, `pinned`), or the host's own service
660    /// answering for it (`desktop`).
661    Running {
662        app_id: String,
663        provider: String,
664        pinned: bool,
665    },
666    /// `opens` when this caller may start it.
667    Installed { app_id: String, opens: bool },
668}
669
670impl AppRef {
671    /// The app's id, as the workspace names it.
672    pub fn app_id(&self) -> &str {
673        match self {
674            Self::Running { app_id, .. } | Self::Installed { app_id, .. } => app_id,
675        }
676    }
677}
678
679/// What looking a name up came to, as this tree keeps it.
680///
681/// Only where an app was found or started is kept, and a decision about a name that is no
682/// permission answer (no app by it, or several). What this caller may open is never kept: the
683/// workspace decides that on every call, so a grant withdrawn since the last call is refused by
684/// the next one, and one given since is not refused from here.
685#[derive(Clone)]
686enum Looked {
687    /// The app runs on this provider: a call found it there, or a start this session made put it
688    /// there.
689    Found(AppRef),
690    /// The name means this installed app. Where the app is, never what this caller may do with
691    /// it: every call that starts it is admitted by the workspace as it makes it.
692    Named(String),
693    /// A decision about the name that no grant can change.
694    Refused(Unresolved),
695}
696
697/// The one resource an already-read level names exactly as `name`: its id
698/// first, then its label. `None` for a name several resources carry, or one
699/// none of them does.
700fn named_among(level: &Level, name: &str) -> Option<Node> {
701    let children = level.whole_children();
702    if let [only] = children
703        .iter()
704        .filter(|node| node.names_id(name))
705        .collect::<Vec<_>>()
706        .as_slice()
707    {
708        return Some((*only).clone());
709    }
710    match children
711        .iter()
712        .filter(|node| node.answers_to(name) == Some(0))
713        .collect::<Vec<_>>()
714        .as_slice()
715    {
716        [only] => Some((*only).clone()),
717        _ => None,
718    }
719}
720
721/// An app installed for the workspace, as the workspace lists it.
722pub struct InstalledApp {
723    pub app_id: String,
724    pub label: String,
725    /// Whether this caller may open it: the workspace names an app it may
726    /// not open without the action.
727    pub opens: bool,
728    /// What its signed package publishes (`surface.toml`), as the workspace's
729    /// listing carries it: the types an agent reads before the app opens.
730    pub surface: Option<String>,
731}
732
733impl InstalledApp {
734    /// The app as naming it answers: its newest window `window` while it
735    /// runs, else the app to open.
736    pub fn named(&self, window: Option<String>) -> AppRef {
737        let app_id = self.app_id.clone();
738        match window {
739            Some(provider) => AppRef::Running {
740                app_id,
741                provider,
742                pinned: false,
743            },
744            None => AppRef::Installed {
745                app_id,
746                opens: self.opens,
747            },
748        }
749    }
750}
751
752/// A path resolved against the live directory.
753pub struct Resolved {
754    pub app_id: String,
755    pub provider: String,
756    /// Written back as a path: the app and the names down to the target.
757    pub path: String,
758    /// The target resource; `None` for the app itself.
759    pub node: Option<Node>,
760    /// Actions on the target (the app's root actions for the app itself).
761    pub actions: Vec<ActionDescriptor>,
762    /// Its children (the app's resources for the app itself).
763    pub children: Vec<Node>,
764    /// The nodes this resolution passed through, root first.
765    pub chain: Vec<Node>,
766    /// The directory levels the resolution read, which what the call does
767    /// next (finding the action that reads the target) reads again from
768    /// here rather than asking the app twice.
769    pub levels: Levels,
770    /// The directory revision the target was found at.
771    pub revision: String,
772}
773
774/// Whether `page` says of itself that it is not all there is and cannot be gone on from: it
775/// stopped at a limit, is not the end and offers no cursor. An app answers so when its
776/// directory cannot be read now and when a page of it broke off.
777pub fn cannot_be_read_now(page: &crate::remote::CataloguePage) -> bool {
778    page.budget_exhausted && !page.exhausted && page.next_cursor.is_empty()
779}
780
781impl<P: ActionProvider + Sync + Clone + Send + 'static> Tree<P> {
782    /// One directory level: the resources under `parent` and their actions,
783    /// over as many pages as a bounded read takes.
784    pub async fn level(
785        &self,
786        provider: &str,
787        parent: &str,
788        levels: &mut Levels,
789    ) -> Result<Level, Unresolved> {
790        if let Some(read) = levels.get(parent) {
791            return Ok(read.clone());
792        }
793        let read = self
794            .read_level(provider, parent, None, usize::MAX)
795            .await?
796            .ok_or("the app's directory kept changing while it was read; try again")?;
797        levels.insert(parent.to_owned(), read.clone());
798        Ok(read)
799    }
800
801    /// One directory level, read as far as one page of a listing holds:
802    /// enough to name a resource and what it holds on its first page, and
803    /// extended by whoever pages past it ([`Self::level_reaching`],
804    /// [`Self::level_holding`]). A listing reads one page of a directory of
805    /// thousands per call, not a fixed stretch of it.
806    pub async fn level_near(
807        &self,
808        provider: &str,
809        parent: &str,
810        levels: &mut Levels,
811    ) -> Result<Level, Unresolved> {
812        if let Some(read) = levels.get(parent) {
813            return Ok(read.clone());
814        }
815        let read = self
816            .read_level(provider, parent, None, LISTED_NEAR)
817            .await?
818            .ok_or("the app's directory kept changing while it was read; try again")?;
819        levels.insert(parent.to_owned(), read.clone());
820        Ok(read)
821    }
822
823    /// The directory levels this session read in `provider`, as the last call
824    /// left them: what a call resolving a path there starts from.
825    pub fn levels_kept(&self, provider: &str) -> Levels {
826        self.dirs
827            .lock_recover()
828            .get(provider)
829            .cloned()
830            .unwrap_or_default()
831    }
832
833    /// Keep what a call resolving its path in `provider` read, for the calls
834    /// after it: a write on another of the app's resources is resolved from
835    /// what the workspace already answered.
836    pub fn keep_levels(&self, provider: &str, levels: &Levels) {
837        let mut dirs = self.dirs.lock_recover();
838        if dirs.len() >= RESOLVED_PATHS && !dirs.contains_key(provider) {
839            dirs.clear();
840        }
841        dirs.insert(provider.to_owned(), levels.clone());
842    }
843
844    /// Forget the app `app_id` the session found, after the workspace refused a
845    /// call as one the app does not offer: the app or its directory moved
846    /// since, so the next call looks both up again. What the workspace decided
847    /// about other names — a name several apps carry, or none — is dropped with
848    /// it: the catalogue moved, and the calls that follow read it once more.
849    pub fn forget_app(&self, app_id: &str) {
850        self.apps.lock_recover().retain(|_, looked| match looked {
851            Looked::Found(app) => app.app_id() != app_id,
852            // The binding is where the app was looked up: an app that moved is looked up again.
853            Looked::Named(known) => known != app_id,
854            Looked::Refused(_) => false,
855        });
856        self.dirs.lock_recover().clear();
857    }
858
859    /// The app `name` means: a running one by its id or last part, else an
860    /// installed one the workspace offers to open.
861    ///
862    /// Where a name was found is kept: every call in an app names it again, and
863    /// looking it up asks the workspace which apps run and which are installed
864    /// — two catalogue reads, for each call. So a running app is answered from
865    /// here after the first call, as a name that means an installed app is, and
866    /// so is a start this session made ([`Self::saw_running`]) and a decision
867    /// about a name no grant can change. What this caller may open is not kept:
868    /// an app that is not known to run here is looked up on every call, so a
869    /// grant given or withdrawn is decided by the call it reaches. A call the
870    /// app refuses drops what was kept ([`McpServer::forget_app`]), so an app
871    /// that moved is looked up again.
872    pub async fn app_ref(&self, name: &str) -> Result<AppRef, Unresolved> {
873        let known = {
874            let apps = self.apps.lock_recover();
875            match apps.get(name) {
876                Some(Looked::Found(app)) => Some(Ok(app.clone())),
877                Some(Looked::Refused(why)) => Some(Err(why.clone())),
878                // Where the name's app runs, if a call in this session found it running.
879                Some(Looked::Named(app_id)) => apps.get(app_id).and_then(|found| match found {
880                    Looked::Found(app) => Some(Ok(app.clone())),
881                    _ => None,
882                }),
883                None => None,
884            }
885        };
886        if let Some(known) = known {
887            return known;
888        }
889        let looked;
890        let answer = match self.app_ref_live(name).await {
891            // Where the app runs, and nothing this caller may do with it.
892            Ok(app @ AppRef::Running { .. }) => {
893                looked = Looked::Found(app.clone());
894                Ok(app)
895            }
896            // Where the name's app is installed. What this caller may open is not kept: every
897            // call that starts the app is admitted by the workspace as it makes it.
898            Ok(app @ AppRef::Installed { .. }) => {
899                looked = Looked::Named(app.app_id().to_owned());
900                Ok(app)
901            }
902            // A decision about the name that no grant can change: several apps carry it, or no
903            // app answers to it. Kept, as a running app is. What could not be read now — a
904            // catalogue that did not answer, a directory that kept moving — is asked again next
905            // time.
906            Err(why @ Unresolved::Said(_)) => {
907                looked = Looked::Refused(why.clone());
908                Err(why)
909            }
910            Err(other) => return Err(other),
911        };
912        let mut apps = self.apps.lock_recover();
913        if apps.len() >= RESOLVED_PATHS && !apps.contains_key(name) {
914            apps.clear();
915        }
916        apps.insert(name.to_owned(), looked);
917        answer
918    }
919
920    /// Keep `app_id` as running on `provider`: what a start this session made, or a call an app
921    /// answered at, proves. Every name this tree knew the app by is kept so too, so the call
922    /// after a start invokes the app instead of starting it again.
923    pub fn saw_running(&self, app_id: &str, provider: &str) {
924        let running = AppRef::Running {
925            app_id: app_id.to_owned(),
926            provider: provider.to_owned(),
927            pinned: false,
928        };
929        let mut apps = self.apps.lock_recover();
930        for looked in apps.values_mut() {
931            let known = match looked {
932                // A name that pinned one window of the app keeps naming that window: only the
933                // app found by its own names is what a start or a call says runs. A refusal
934                // names no app that runs.
935                Looked::Found(AppRef::Running { pinned: true, .. }) | Looked::Refused(_) => false,
936                Looked::Found(app) => app.app_id() == app_id,
937                Looked::Named(known) => known == app_id,
938            };
939            if known {
940                *looked = Looked::Found(running.clone());
941            }
942        }
943        if matches!(
944            apps.get(app_id),
945            Some(Looked::Found(AppRef::Running { pinned: true, .. }))
946        ) {
947            return;
948        }
949        if apps.len() >= RESOLVED_PATHS && !apps.contains_key(app_id) {
950            apps.clear();
951        }
952        apps.insert(app_id.to_owned(), Looked::Found(running));
953    }
954
955    /// [`Self::app_ref`] as the live directory answers it, asked of the
956    /// workspace: the app a running one is by its id or last part, else an
957    /// installed one the workspace offers to open.
958    pub async fn app_ref_live(&self, name: &str) -> Result<AppRef, Unresolved> {
959        // Files is every workspace's own folder, served by the framework
960        // rather than installed into it: `files#open` reaches it wherever the
961        // workspace is, and puts a file into its tree.
962        if names_files(name) {
963            return Ok(AppRef::Installed {
964                app_id: FILES_APP.to_owned(),
965                opens: true,
966            });
967        }
968        let (name, instance) = match name.rsplit_once('@') {
969            Some((app, instance)) if !instance.trim().is_empty() => {
970                (app.trim(), Some(instance.trim()))
971            }
972            _ => (name, None),
973        };
974        let (_, running) = self.providers().await?;
975        if let Some(instance) = instance {
976            return pinned_window(&running, name, instance);
977        }
978        // A record a device serves whoever has it open (a host serving its
979        // workspace's records) is the app, live, as a window of it is.
980        let is_window = |provider: &str| {
981            provider.parse::<u64>().is_ok() || crate::remote::is_resource_provider(provider)
982        };
983        let ids_where = |window: bool| {
984            running
985                .iter()
986                .filter(|(provider, _)| is_window(provider) == window)
987                .filter_map(|(_, app)| app["app_id"].as_str())
988                .collect::<Vec<_>>()
989        };
990        let newest = |app_id: &str, window: bool| {
991            running
992                .iter()
993                .rev()
994                .filter(|(provider, _)| is_window(provider) == window)
995                .find(|(_, app)| app["app_id"].as_str() == Some(app_id))
996                .map(|(provider, _)| provider.clone())
997        };
998        let windows = ids_where(true);
999        match app_named(name, &windows) {
1000            Ok(app_id) => {
1001                let provider =
1002                    newest(&app_id, true).ok_or_else(|| not_running(&app_id, &windows))?;
1003                return Ok(AppRef::Running {
1004                    app_id,
1005                    provider,
1006                    pinned: false,
1007                });
1008            }
1009            Err(error) if error.contains("names several") => return Err(error.into()),
1010            Err(_) => {}
1011        }
1012        // The host's own services (the desktop's layout, the workspace's
1013        // activity) answer for app ids no app installs: the app itself,
1014        // when it is installed, is what its name opens.
1015        let installed = self.installed().await;
1016        // The name the listing shows an app by (`Files`) is that app.
1017        if let Some(app) = installed
1018            .as_ref()
1019            .ok()
1020            .and_then(|apps| listed_as(apps, name))
1021        {
1022            return Ok(app.named(newest(&app.app_id, true)));
1023        }
1024        let services = ids_where(false);
1025        let service = app_named(name, &services).ok().filter(|app_id| {
1026            installed
1027                .as_ref()
1028                .is_ok_and(|installed| !installed.iter().any(|app| app.app_id == *app_id))
1029                || installed.is_err()
1030        });
1031        if let Some(app_id) = service
1032            && let Some(provider) = newest(&app_id, false)
1033        {
1034            return Ok(AppRef::Running {
1035                app_id,
1036                provider,
1037                pinned: false,
1038            });
1039        }
1040        // An installed list that could not be read is said, never taken for
1041        // an empty one: the agent would conclude the app does not exist.
1042        let installed = installed.map_err(|reason| Unresolved::InstalledUnread {
1043            name: name.to_owned(),
1044            reason: Box::new(reason),
1045        })?;
1046        let ids = installed
1047            .iter()
1048            .map(|app| app.app_id.as_str())
1049            .collect::<Vec<_>>();
1050        match app_named(name, &ids) {
1051            Ok(app_id) => {
1052                let opens = installed
1053                    .iter()
1054                    .any(|app| app.app_id == app_id && app.opens);
1055                Ok(AppRef::Installed { app_id, opens })
1056            }
1057            Err(error) if error.contains("names several") => Err(error.into()),
1058            // No app is called exactly that: the name is read once more as a model writes one.
1059            Err(_) => freely_named(name, &running, &installed),
1060        }
1061    }
1062
1063    /// The surface the app `app_id` publishes, as the workspace's catalogue carries it on the
1064    /// row the app's provider publishes: for an app that is no installed application, such as
1065    /// the workspace's own actions. `None` when no row names one.
1066    pub async fn surface_of(&self, app_id: &str) -> Option<String> {
1067        let page = self
1068            .ask(CatalogueQuery {
1069                app_id: Some(app_id.to_owned()),
1070                max_results: 8,
1071                ..CatalogueQuery::default()
1072            })
1073            .await
1074            .ok()?;
1075        page.rows.into_iter().find_map(|row| row.surface)
1076    }
1077
1078    /// The apps installed for this workspace, with their labels and whether
1079    /// this caller may open them. The workspace answers them by their kind,
1080    /// whole, wherever they fall among its other rows (governance, shortcuts),
1081    /// so a workspace with many of those still lists every app.
1082    pub async fn installed(&self) -> Result<Vec<InstalledApp>, Unresolved> {
1083        let provider = crate::remote::workspace_provider(&self.workspace);
1084        let mut apps: Vec<InstalledApp> = Vec::new();
1085        let mut cursor = Vec::new();
1086        let mut revision = None;
1087        for _ in 0..INSTALLED_PAGES {
1088            let page = self
1089                .ask(CatalogueQuery {
1090                    provider: Some(provider.clone()),
1091                    resource_name: Some(crate::remote::APPLICATION_RESOURCE_KIND.to_owned()),
1092                    max_results: crate::remote::MAX_CATALOGUE_PAGE,
1093                    cursor: std::mem::take(&mut cursor),
1094                    revision: revision.take(),
1095                    ..CatalogueQuery::default()
1096                })
1097                .await?;
1098            for row in page.rows {
1099                let Some(app_id) = row
1100                    .resource
1101                    .id
1102                    .strip_prefix(crate::remote::APPLICATION_RESOURCE_PREFIX)
1103                    .filter(|app_id| !app_id.starts_with("host:"))
1104                else {
1105                    continue;
1106                };
1107                // The workspace offers an action on an app (open, or close
1108                // while it runs) only to a caller that may use it, and names
1109                // one it may not without any: a running app shows only its
1110                // close, and is still this caller's to open.
1111                let opens = row.action.is_some();
1112                match apps.iter_mut().find(|app| app.app_id == app_id) {
1113                    Some(app) => {
1114                        app.opens |= opens;
1115                        if row.surface.is_some() {
1116                            app.surface.clone_from(&row.surface);
1117                        }
1118                    }
1119                    None => apps.push(InstalledApp {
1120                        app_id: app_id.to_owned(),
1121                        label: row.resource.label.clone(),
1122                        opens,
1123                        surface: row.surface.clone(),
1124                    }),
1125                }
1126            }
1127            if page.exhausted || page.next_cursor.is_empty() {
1128                break;
1129            }
1130            cursor = page.next_cursor;
1131            revision = Some(page.revision);
1132        }
1133        Ok(apps)
1134    }
1135
1136    /// The resources under `parent` that `name` names (by label or kind),
1137    /// asked of the app whole: one note among a notebook's thousands costs
1138    /// the rows naming it, not a page of every note. `None` when the app
1139    /// cannot say (a host from before parents were named answers about its
1140    /// top level), and the level is listed instead.
1141    pub async fn named(
1142        &self,
1143        provider: &str,
1144        parent: &str,
1145        name: &str,
1146    ) -> Result<Option<Level>, Unresolved> {
1147        let name = name.trim();
1148        if name.is_empty() || name.len() > NAME_BYTES {
1149            return Ok(None);
1150        }
1151        let Ok(page) = self
1152            .ask(CatalogueQuery {
1153                provider: Some(provider.to_owned()),
1154                parent_resource: (!parent.is_empty()).then(|| parent.to_owned()),
1155                resource_name: Some(name.to_owned()),
1156                max_results: PAGE_ROWS,
1157                ..CatalogueQuery::default()
1158            })
1159            .await
1160        else {
1161            return Ok(None);
1162        };
1163        if !page.exhausted
1164            || page.stale_cursor
1165            || page.rows.iter().any(|row| row.parent_resource != parent)
1166        {
1167            return Ok(None);
1168        }
1169        let mut named = level_of(&page.rows, parent);
1170        named.revision = page.revision;
1171        Ok(Some(named))
1172    }
1173
1174    /// What `name` may mean at the app's level, asked by name: the app's top
1175    /// level and, inside each of its containers, what `name` names there,
1176    /// less what another of them owns; `None` when one cannot be asked.
1177    pub async fn named_at_app(
1178        &self,
1179        provider: &str,
1180        name: &str,
1181        levels: &mut Levels,
1182    ) -> Result<Option<Level>, Unresolved> {
1183        // What this call already holds of the app's own level answers the name
1184        // where it names one resource exactly: the session keeps the directory
1185        // it read, so a call on another of the app's resources costs itself.
1186        if let Some(root) = levels.get("").cloned()
1187            && let Some(only) = named_among(&root, name)
1188        {
1189            return Ok(Some(Level {
1190                own: Vec::new(),
1191                children: vec![only],
1192                revision: root.revision,
1193                pages: Arc::default(),
1194            }));
1195        }
1196        // A name the app's own level carries is asked of the app by name
1197        // first: a chain it keeps is answered from the head part publishing
1198        // it, never a page of the listing built from every item the app
1199        // shows. A name no one resource there answers is listed as before.
1200        if let Some(among) = self.named(provider, "", name).await?
1201            && let [only] = among.children.as_slice()
1202        {
1203            return Ok(Some(Level {
1204                own: Vec::new(),
1205                children: vec![only.clone()],
1206                revision: among.revision,
1207                pages: Arc::default(),
1208            }));
1209        }
1210        let root = self.level(provider, "", levels).await?;
1211        let mut revision = root.revision.clone();
1212        // A name the app's own level carries exactly is answered there: its id
1213        // first, then its label. The containers hold the resource's items,
1214        // and asking each of them for a name it is not (the resource's own
1215        // name, most often) lists every item it holds.
1216        let by_id: Vec<&Node> = root
1217            .children
1218            .iter()
1219            .filter(|node| node.names_id(name))
1220            .collect();
1221        let by_label: Vec<&Node> = root
1222            .children
1223            .iter()
1224            .filter(|node| node.answers_to(name) == Some(0))
1225            .collect();
1226        for named in [by_id, by_label] {
1227            if let [only] = named.as_slice() {
1228                return Ok(Some(Level {
1229                    own: Vec::new(),
1230                    children: vec![(**only).clone()],
1231                    revision,
1232                    pages: Arc::default(),
1233                }));
1234            }
1235        }
1236        let mut pool = root.children.clone();
1237        for container in root
1238            .children
1239            .iter()
1240            .filter(|node| node.container)
1241            .take(ROOT_PEEK)
1242        {
1243            let Some(inside) = self.named(provider, &container.id, name).await? else {
1244                return Ok(None);
1245            };
1246            revision = inside.revision;
1247            for child in inside.children {
1248                if !pool.iter().any(|seen| seen.id == child.id) {
1249                    pool.push(child);
1250                }
1251            }
1252        }
1253        let all = pool.clone();
1254        pool.retain(|node| !all.iter().any(|owner| owner.beside(node)));
1255        Ok(Some(Level {
1256            own: Vec::new(),
1257            children: pool,
1258            revision,
1259            pages: Arc::default(),
1260        }))
1261    }
1262
1263    /// The resource `segment` names under `parent` (the app itself for
1264    /// `None`), and the resources it was named among. A name only one
1265    /// resource there carries is asked of the app by name; anything else (a
1266    /// key, the start of a name, a name several carry, one that is not
1267    /// there) is decided on the whole level, as listing it shows. With them
1268    /// comes the directory revision it was found at. `at` is the address the
1269    /// level is listed at, which a name not found is answered with.
1270    pub async fn step(
1271        &self,
1272        provider: &str,
1273        at: &str,
1274        parent: Option<&Node>,
1275        segment: &str,
1276        levels: &mut Levels,
1277        forms: Option<&dyn TypeNames>,
1278    ) -> Result<(Node, Level), Unresolved> {
1279        let asked = match parent {
1280            Some(owner) if !levels.contains_key(&owner.id) => {
1281                self.named(provider, &owner.id, segment).await?
1282            }
1283            None => self.named_at_app(provider, segment, levels).await?,
1284            Some(_) => None,
1285        };
1286        if let Some(among) = asked {
1287            // What the app answered is the resource the segment names: one
1288            // whose id it is, before any label, else one its label names
1289            // exactly. Either costs the answer, not a read of the level.
1290            let mut named = among.children.iter().filter(|node| node.names_id(segment));
1291            if let (Some(only), None) = (named.next(), named.next()) {
1292                let only = only.clone();
1293                return Ok((only, among));
1294            }
1295            let mut named = among
1296                .children
1297                .iter()
1298                .filter(|node| node.answers_to(segment) == Some(0));
1299            if let (Some(only), None) = (named.next(), named.next()) {
1300                let only = only.clone();
1301                return Ok((only, among));
1302            }
1303        }
1304        // An app's directory is rebuilt whenever its document changes, and for an instant it
1305        // lists less than it has. A name not found is looked for again for a moment, the
1306        // levels read anew, before the app is said not to have it.
1307        let began = self.pause().now();
1308        let mut looks: u32 = 0;
1309        loop {
1310            // A level is read as far as its bound, and a directory that holds more goes on
1311            // past it. A name the pages read first do not carry is looked for on the pages
1312            // after them, to the directory's end, before it is looked for anywhere else: what
1313            // a resource holds is found under it wherever it falls in the directory, and
1314            // only a name no page carries is not there.
1315            let (picked, here) = if let Some(owner) = parent {
1316                self.level_holding(provider, &owner.id, levels, |level| {
1317                    Ok(pick(segment, level.whole_children(), forms)?.cloned())
1318                })
1319                .await?
1320            } else {
1321                let here = self.app_children(provider, levels).await?;
1322                (pick(segment, &here.children, forms)?.cloned(), here)
1323            };
1324            let found = match picked {
1325                Some(node) => Some(node),
1326                None => self.deep(provider, segment, parent, levels, forms).await?,
1327            };
1328            if let Some(found) = found {
1329                return Ok((found, here));
1330            }
1331            if looks >= LOOKS_AGAIN
1332                || (read_on(&here) && self.pause().now().saturating_sub(began) >= LOOKS_MOMENT)
1333            {
1334                // Each name as the address that takes it, not the word alone:
1335                // a caller reading where it went wrong writes the next call
1336                // from what it is told, and a word it cannot place is no
1337                // address at all.
1338                let addresses: Vec<_> = (here.children.iter())
1339                    .map(|node| format!("{at}/{}", node.name(&here.children)))
1340                    .collect();
1341                return Err(Unresolved::NoSuch {
1342                    name: segment.to_owned(),
1343                    at: at.to_owned(),
1344                    has: addresses,
1345                });
1346            }
1347            looks = looks.saturating_add(1);
1348            self.pause()
1349                .pause(restart_pause(looks.saturating_add(1)))
1350                .await;
1351            levels.clear();
1352        }
1353    }
1354
1355    /// A resource `name` names somewhere below `within` (or anywhere in the
1356    /// app), found among the nodes this call has read and then by reading
1357    /// the containers it has not: a note's body is published beside the
1358    /// note rather than inside it, and its key says whose it is.
1359    pub async fn deep(
1360        &self,
1361        provider: &str,
1362        name: &str,
1363        within: Option<&Node>,
1364        levels: &mut Levels,
1365        forms: Option<&dyn TypeNames>,
1366    ) -> Result<Option<Node>, Unresolved> {
1367        for _ in 0..=DEEP_READS {
1368            let pool: Vec<Node> = levels
1369                .values()
1370                .flat_map(|level| level.whole_children().iter())
1371                .filter(|node| {
1372                    within.is_none_or(|owner| {
1373                        node.key.contains(owner.token()) || Self::below(node, owner, levels)
1374                    }) && rank(name, node, forms).is_some()
1375                })
1376                .cloned()
1377                .collect();
1378            if let Some(found) = pick(name, &pool, forms)? {
1379                return Ok(Some(found.clone()));
1380            }
1381            let unread = levels
1382                .values()
1383                .flat_map(|level| level.children.iter())
1384                .find(|node| node.container && !levels.contains_key(&node.id))
1385                .map(|node| node.id.clone());
1386            let Some(unread) = unread else {
1387                return Ok(None);
1388            };
1389            self.level(provider, &unread, levels).await?;
1390        }
1391        Ok(None)
1392    }
1393
1394    /// Whether `node`'s parent chain, as far as this call has read it,
1395    /// reaches `owner`.
1396    fn below(node: &Node, owner: &Node, levels: &Levels) -> bool {
1397        let mut parent = node.parent.clone();
1398        for _ in 0..8 {
1399            if parent.is_empty() {
1400                return false;
1401            }
1402            if parent == owner.id {
1403                return true;
1404            }
1405            let Some(next) = levels
1406                .values()
1407                .flat_map(|level| level.children.iter())
1408                .find(|candidate| candidate.id == parent)
1409            else {
1410                return false;
1411            };
1412            parent.clone_from(&next.parent);
1413        }
1414        false
1415    }
1416
1417    /// Resolve a whole path. A segment written the way a program types a type (`tasks.Task`)
1418    /// is read as that type first: it names the resource whose published kind the listing
1419    /// prints that name for. Only a segment written that way is asked of the task's programs,
1420    /// so a path of titles (`notes/Todo`) does not start a task's host to read a name already
1421    /// said; a form no app declares falls back to the plain reading, where it may be a title.
1422    ///
1423    /// With the resolution come the forms it was read by (`None` when it was read plainly), so
1424    /// a caller that shows what it found names the type the same way without asking again.
1425    pub async fn resolve(
1426        &self,
1427        parsed: &Address,
1428        forms: Option<&dyn TypeNames>,
1429    ) -> Result<(Resolved, bool), Unresolved> {
1430        if let Some(forms) = forms.filter(|_| names_a_type(parsed)) {
1431            match self.resolve_with(parsed, Some(forms), usize::MAX).await {
1432                // A path of segments resolves to a resource only when it walked every one: an
1433                // empty chain is a name no resource answered.
1434                Ok(found) if !found.chain.is_empty() => return Ok((found, true)),
1435                Ok(_) => {}
1436                Err(note) if note.is_note() => {}
1437                Err(other) => return Err(other),
1438            }
1439        }
1440        self.resolve_with(parsed, None, usize::MAX)
1441            .await
1442            .map(|found| (found, false))
1443    }
1444
1445    /// [`Self::resolve`] reading the names a path segment may go by as `forms` says they are
1446    /// written: a segment names a type by the name a listing prints for it (`tasks.Task`),
1447    /// which `forms` reads back as its kind. `reaching` is how many resources of an app's own
1448    /// page to read its containers for: a listing reads the page's end and one past it, and
1449    /// a read takes every one (`usize::MAX`).
1450    pub async fn resolve_with(
1451        &self,
1452        parsed: &Address,
1453        forms: Option<&dyn TypeNames>,
1454        reaching: usize,
1455    ) -> Result<Resolved, Unresolved> {
1456        let mut levels = Levels::new();
1457        let reference = match self.app_ref(&app_of(parsed)).await {
1458            Ok(reference) => reference,
1459            Err(why) => match self.app_of_type(&app_of(parsed)).await {
1460                Some((app_id, provider, _)) => {
1461                    return self
1462                        .resolve_in(parsed, app_id, provider, true, forms, &mut levels, reaching)
1463                        .await;
1464                }
1465                None => return Err(why),
1466            },
1467        };
1468        // An app this tree found running is kept for the calls after this one, which is only
1469        // right while it still answers: one that stopped since is looked up again, so the call
1470        // after this refusal asks the workspace where the app is instead of failing here again.
1471        let about = reference.app_id().to_owned();
1472        let resolved = match reference {
1473            AppRef::Running {
1474                app_id,
1475                provider,
1476                pinned: true,
1477            } => {
1478                self.resolve_in(parsed, app_id, provider, true, forms, &mut levels, reaching)
1479                    .await
1480            }
1481            AppRef::Running {
1482                app_id, provider, ..
1483            } => {
1484                self.resolve_published(parsed, app_id, provider, true, forms, &mut levels, reaching)
1485                    .await
1486            }
1487            // Reading what an installed app holds starts it without a window, as an action on
1488            // it does: a path names the app's resources, not one of its processes.
1489            AppRef::Installed {
1490                app_id,
1491                opens: true,
1492            } => {
1493                let provider = self.started_provider(&app_id, None).await?;
1494                self.resolve_published(parsed, app_id, provider, true, forms, &mut levels, reaching)
1495                    .await
1496            }
1497            AppRef::Installed { opens: false, .. } => Err(Unresolved::NotRunning {
1498                name: app_of(parsed),
1499                opens: false,
1500            }),
1501        };
1502        if let Err(why) = &resolved
1503            && why.app_gone()
1504        {
1505            self.forget_app(&about);
1506        }
1507        resolved
1508    }
1509
1510    /// [`Self::resolve_in`] the newest instance `newest` of `app_id`, or, when
1511    /// it has published nothing for the path, the app's older instances in
1512    /// turn. A path names the app, not one of its processes: an instance
1513    /// lists as running a moment before it publishes its directory, and must
1514    /// not hide an older one that has (an agent saw an app's actions, and
1515    /// the next call found none).
1516    pub async fn resolve_published(
1517        &self,
1518        parsed: &Address,
1519        app_id: String,
1520        newest: String,
1521        list: bool,
1522        forms: Option<&dyn TypeNames>,
1523        levels: &mut Levels,
1524        reaching: usize,
1525    ) -> Result<Resolved, Unresolved> {
1526        let published = |found: &Resolved| {
1527            !found.chain.is_empty() || !found.actions.is_empty() || !found.children.is_empty()
1528        };
1529        let first = self
1530            .resolve_in(
1531                parsed,
1532                app_id.clone(),
1533                newest.clone(),
1534                list,
1535                forms,
1536                levels,
1537                reaching,
1538            )
1539            .await;
1540        if first.as_ref().is_ok_and(published) {
1541            return first;
1542        }
1543        // The levels here are the newest instance's: an older one keeps its
1544        // directory, and reading it under this one's name would name the wrong
1545        // resources.
1546        levels.clear();
1547        // Only then are the running apps asked again, for the older instances.
1548        let older: Vec<String> = self
1549            .providers()
1550            .await?
1551            .1
1552            .iter()
1553            .rev()
1554            .filter(|(_, app)| app["app_id"].as_str() == Some(app_id.as_str()))
1555            .map(|(peer, _)| peer.clone())
1556            .filter(|peer| *peer != newest)
1557            .collect();
1558        for provider in older {
1559            let resolved = self
1560                .resolve_in(
1561                    parsed,
1562                    app_id.clone(),
1563                    provider,
1564                    list,
1565                    forms,
1566                    levels,
1567                    reaching,
1568                )
1569                .await;
1570            if resolved.as_ref().is_ok_and(published) {
1571                return resolved;
1572            }
1573        }
1574        first
1575    }
1576
1577    /// Resolve the segments of `parsed` in the running app `app_id`, whose
1578    /// instance is `provider`. With `list`, what the target holds and the
1579    /// actions on it are read too; without, a resource on the path is only
1580    /// found (an action named on it is resolved by its address). `forms` is how
1581    /// a path segment may name a type the way a program types it
1582    /// (`tasks.Task`), as a listing names it. `reaching` is how far what an
1583    /// app's own page merges from its containers is read: a listing's end and
1584    /// one resource past it, or every one ([`Self::app_children_listed`]).
1585    pub async fn resolve_in(
1586        &self,
1587        parsed: &Address,
1588        app_id: String,
1589        provider: String,
1590        list: bool,
1591        forms: Option<&dyn TypeNames>,
1592        levels: &mut Levels,
1593        reaching: usize,
1594    ) -> Result<Resolved, Unresolved> {
1595        let app = app_of(parsed).to_lowercase();
1596        // What an action answered is a path the next call takes as it is:
1597        // `tasks.tracker/issues/7` names one resource whole, where its parts
1598        // named one at a time would name every kind that shares a word. A resource a device
1599        // keeps is named by the address its provider answers at (`devices/<id>/<app>`), which no
1600        // level of the app's own names.
1601        if type_address(&app_of(parsed)).is_some()
1602            || device_section(parsed)
1603            || is_device_resource(parsed)
1604        {
1605            let address = parsed.resource();
1606            if let Some(found) = self
1607                .by_item_address(&app_id, &provider, &address, levels)
1608                .await?
1609            {
1610                return Ok(found);
1611            }
1612        }
1613        let mut chain: Vec<Node> = Vec::new();
1614        // What each resource on the path was named among, and the revision
1615        // the last of them was found at.
1616        let mut among: Vec<Vec<Node>> = Vec::new();
1617        let mut revision = String::new();
1618        // The address each level is listed at, as the app's own listing writes
1619        // it: what a name not found there is answered with.
1620        let mut at = app.clone();
1621        for segment in below_app(parsed) {
1622            let (found, siblings) = self
1623                .step(
1624                    &provider,
1625                    &at,
1626                    chain.last(),
1627                    &segment.written(),
1628                    levels,
1629                    forms,
1630                )
1631                .await?;
1632            at = format!("{at}/{}", found.name(&siblings.children));
1633            chain.push(found);
1634            among.push(siblings.children);
1635            revision = siblings.revision;
1636        }
1637        let mut here = match chain.last() {
1638            Some(_) if !list => Level::default(),
1639            Some(node) => self.level_near(&provider, &node.id, levels).await?,
1640            None => {
1641                // What the app's containers hold (a notebook's notes) is read for a listing.
1642                // An action named on the app is found on the app's own level first
1643                // ([`Self::pick_action_in`]): `notes#create-page` is the notebook's, and
1644                // reading every note to find it would grow with the notebook.
1645                let mut root = if list {
1646                    self.app_children_listed(&provider, levels, reaching)
1647                        .await?
1648                } else {
1649                    self.level(&provider, "", levels).await?
1650                };
1651                as_the_service(&provider, &mut root);
1652                root
1653            }
1654        };
1655        let mut written = app;
1656        if let Some(owner) = chain.last() {
1657            // Published beside the resource, not inside it, but its key says
1658            // whose it is: listed as one of its children.
1659            let token = owner.token().to_owned();
1660            let related: Vec<Node> = levels
1661                .values()
1662                .flat_map(|level| level.children.iter())
1663                .filter(|node| {
1664                    token.len() >= 8
1665                        && node.id != owner.id
1666                        && node.key.contains(&token)
1667                        && !here.children.iter().any(|child| child.id == node.id)
1668                })
1669                .cloned()
1670                .collect();
1671            here.children.extend(related);
1672        }
1673        let mut previous: Option<Node> = None;
1674        for (node, siblings) in chain.iter().zip(&among) {
1675            // Named against what it sits among and the resource it sits
1676            // under, whose title it may share.
1677            let mut named = siblings.clone();
1678            named.extend(previous.clone());
1679            written = format!("{written}/{}", node.name(&named));
1680            previous = Some(node.clone());
1681        }
1682        Ok(Resolved {
1683            app_id,
1684            provider,
1685            path: written,
1686            node: chain.last().cloned(),
1687            // A directory that hoists a resource's actions into its parent's
1688            // listing lists them there, not under the resource.
1689            actions: if here.own.is_empty() {
1690                chain
1691                    .last()
1692                    .map(|node| node.actions.clone())
1693                    .unwrap_or_default()
1694            } else {
1695                here.own
1696            },
1697            children: here.children,
1698            chain,
1699            levels: levels.clone(),
1700            revision,
1701        })
1702    }
1703}
1704
1705/// Why `name` names no app: how a running app is addressed, and the apps
1706/// running and installed.
1707fn no_app_named(name: &str, running: &[(String, Value)], installed: &[InstalledApp]) -> String {
1708    let running_ids = running
1709        .iter()
1710        .filter_map(|(_, app)| app["app_id"].as_str().map(str::to_owned))
1711        .collect::<Vec<_>>();
1712    let installed_ids = installed
1713        .iter()
1714        .map(|app| app.app_id.clone())
1715        .collect::<Vec<_>>();
1716    format!(
1717        "unknown_app: no app {name}; name a running app by its id or last part, e.g. {}. Running {}; installed {}",
1718        running_ids.first().map_or("<app_id>", String::as_str),
1719        list_or_none(&app_names(&running_ids)),
1720        list_or_none(&app_names(&installed_ids)),
1721    )
1722}
1723
1724/// The one installed app the listing shows by the name `name` (`Files` for
1725/// `file-explorer`), any case.
1726pub fn listed_as<'a>(installed: &'a [InstalledApp], name: &str) -> Option<&'a InstalledApp> {
1727    let mut named = installed
1728        .iter()
1729        .filter(|app| app.label.eq_ignore_ascii_case(name));
1730    named.next().filter(|_| named.next().is_none())
1731}
1732
1733/// The app `name` means where no app is called exactly that: the name read once more as a
1734/// model writes one (`word_processor`, `WordProcessor`, `Word`), among the installed apps as
1735/// this caller is listed them and the apps of the providers it may use, and no others. What it
1736/// finds is opened and acted in as the listing says this caller may. A word that still names
1737/// none (`host` for the Browser, `so.tilo.browser`) is a guess, so the running apps are named
1738/// as they are to be addressed.
1739fn freely_named(
1740    name: &str,
1741    running: &[(String, Value)],
1742    installed: &[InstalledApp],
1743) -> Result<AppRef, Unresolved> {
1744    let listed: Vec<(&str, &str)> = installed
1745        .iter()
1746        .map(|app| (app.app_id.as_str(), app.label.as_str()))
1747        .chain(
1748            running
1749                .iter()
1750                .filter_map(|(_, app)| Some((app["app_id"].as_str()?, ""))),
1751        )
1752        .collect();
1753    let Some(app_id) = app_meant(name, &listed)? else {
1754        return Err(no_app_named(name, running, installed).into());
1755    };
1756    // Its newest window, or else whatever answers for it without one.
1757    let newest = |window: bool| {
1758        running
1759            .iter()
1760            .rev()
1761            .filter(|(provider, _)| {
1762                (provider.parse::<u64>().is_ok() || crate::remote::is_resource_provider(provider))
1763                    == window
1764            })
1765            .find(|(_, app)| app["app_id"].as_str() == Some(app_id.as_str()))
1766            .map(|(provider, _)| provider.clone())
1767    };
1768    if let Some(app) = installed.iter().find(|app| app.app_id == app_id) {
1769        return Ok(app.named(newest(true)));
1770    }
1771    let provider = newest(true).or_else(|| newest(false));
1772    match provider {
1773        Some(provider) => Ok(AppRef::Running {
1774            app_id,
1775            provider,
1776            pinned: false,
1777        }),
1778        None => Err(no_app_named(name, running, installed).into()),
1779    }
1780}
1781
1782pub fn app_names(ids: &[String]) -> Vec<String> {
1783    let mut names: Vec<String> = ids
1784        .iter()
1785        .map(|id| id.rsplit('.').next().unwrap_or(id).to_lowercase())
1786        .collect();
1787    names.sort();
1788    names.dedup();
1789    names
1790}
1791
1792impl<P: ActionProvider + Sync + Clone + Send + 'static> Tree<P> {
1793    /// The app a kind names (`tasks.tracker` is the Tasks app's tracker), as
1794    /// the app id and the provider serving it: a kind begins with the app it
1795    /// belongs to. `None` when the name is no kind, or its app is not here or
1796    /// is not the agent's to open.
1797    ///
1798    /// An app that is installed but not running is started without a window,
1799    /// as an action on it is: a cold link addresses a resource of the app the
1800    /// device never showed, and the app that publishes it serves its kind once
1801    /// it runs.
1802    pub async fn app_of_type(&self, name: &str) -> Option<(String, String, bool)> {
1803        let app = type_address(name)?;
1804        let (app_id, provider, pinned) = match self.app_ref(app).await.ok()? {
1805            AppRef::Running {
1806                app_id,
1807                provider,
1808                pinned,
1809            } => (app_id, provider, pinned),
1810            AppRef::Installed {
1811                app_id,
1812                opens: true,
1813            } => {
1814                let provider = self.started_provider(&app_id, None).await.ok()?;
1815                (app_id, provider, false)
1816            }
1817            AppRef::Installed { opens: false, .. } => return None,
1818        };
1819        if pinned {
1820            return Some((app_id, provider, pinned));
1821        }
1822        // What the kind names, never one of the app's other documents that happens to be first:
1823        // a kind's directory lists a resource of it (`tasks.issues` is the issues' chain, and
1824        // `tasks.tracker` the tracker's own document). The app's documents are asked in turn,
1825        // newest first, and the first that lists the kind answers.
1826        let kind = name
1827            .strip_prefix(app)
1828            .and_then(|rest| rest.strip_prefix('.'))?
1829            .to_owned();
1830        let naming = |node: &Node| {
1831            node.resource_type == kind || node.resource_type.starts_with(&format!("{kind}."))
1832        };
1833        let mut candidates = vec![provider.clone()];
1834        if let Ok((_, running)) = self.providers().await {
1835            candidates.extend(
1836                running
1837                    .iter()
1838                    .rev()
1839                    .filter(|(_, app)| app["app_id"].as_str() == Some(app_id.as_str()))
1840                    .map(|(provider, _)| provider.clone()),
1841            );
1842        }
1843        candidates.dedup();
1844        for provider in candidates {
1845            let mut levels = Levels::new();
1846            let Ok(level) = self.level(&provider, "", &mut levels).await else {
1847                continue;
1848            };
1849            if level.children.iter().any(naming) {
1850                return Some((app_id, provider, false));
1851            }
1852        }
1853        Some((app_id, provider, false))
1854    }
1855}
1856
1857/// The one window `instance` (a provider an `open` or `tilo_ls` named) among `running`, which
1858/// must be of the app `name`: the agent means that window, never another of the app's.
1859fn pinned_window(
1860    running: &[(String, Value)],
1861    name: &str,
1862    instance: &str,
1863) -> Result<AppRef, Unresolved> {
1864    let (provider, entry) = running
1865        .iter()
1866        .find(|(provider, _)| provider == instance)
1867        .ok_or_else(|| format!("no running window {instance}; tilo_ls lists the running apps"))?;
1868    let app_id = entry["app_id"]
1869        .as_str()
1870        .ok_or_else(|| format!("window {instance} names no app"))?
1871        .to_owned();
1872    if app_named(name, &[app_id.as_str()]).is_err() {
1873        return Err(format!(
1874            "window {instance} is {}, not {name}",
1875            app_names(std::slice::from_ref(&app_id)).join("")
1876        )
1877        .into());
1878    }
1879    Ok(AppRef::Running {
1880        app_id,
1881        provider: provider.clone(),
1882        pinned: true,
1883    })
1884}
1885
1886/// The top level `root` of the host service `provider`, as the service itself
1887/// answers it.
1888pub fn as_the_service(provider: &str, root: &mut Level) {
1889    // A host service (the desktop's layout, on `desktop:session`)
1890    // publishes everything on its one resource: its actions are
1891    // the service's own, `desktop#<action>`. A resource's one
1892    // container (Tasks' tracker) holds what the app offers more.
1893    if provider.parse::<u64>().is_err()
1894        && root.own.is_empty()
1895        && let [only] = root.children.as_slice()
1896        && !only.container
1897    {
1898        root.own = only.actions.clone();
1899    }
1900    // A host service's one top resource holding more (a workspace's
1901    // governance, holding its servers and apps) is the service
1902    // itself: its actions are the service's own (`workspace#member.list`),
1903    // and what it holds is listed as the service's.
1904    if provider.parse::<u64>().is_err()
1905        && !crate::remote::is_resource_provider(provider)
1906        && root.own.is_empty()
1907        && let [only] = root
1908            .children
1909            .iter()
1910            .filter(|node| node.parent.is_empty())
1911            .collect::<Vec<_>>()
1912            .as_slice()
1913        && only.container
1914    {
1915        let only = (*only).clone();
1916        root.own = only.actions;
1917        root.children.retain(|node| node.id != only.id);
1918    }
1919}
1920impl From<Unresolved> for String {
1921    fn from(unresolved: Unresolved) -> Self {
1922        unresolved.to_string()
1923    }
1924}