Skip to content

An open-source, self-hosted system for apps built with web technologies.

44.5 KB
Raw Blame
import AuthManager from "@client/core/link-manager/auth-manager/auth-manager"
import { StreamRelay, TheLink } from "@the-link/core"
import host, { TransferredAnswer, type DesktopViewportHost, type DesktopWindowActions } from "./host"
import ClientTraffic from "./client-traffic"
import { failed, succeeded } from "@libs/request-outcome"
import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
import { isServiceAddress, parseProgramInstallOptions, type ServiceAddress, type ShellOptions, type PresentationMovePoint } from "@phreshos/core"
import { type PresentationFrame, type DesktopMovePoint, type PresentationHost } from "./presentation"
import messagepack from "@the-link/messagepack"
import { sdkProcess, type SdkProcessSource } from "./sdk-records"
import SystemAccess from "./system-access"

/** The desktop boundary around one iframe execution endpoint. */
export default class ClientProcessBoundary extends TheLink {

    public readonly pane: string

    public readonly element: HTMLIFrameElement

    private readonly authManager: AuthManager

    private readonly viewport: DesktopViewportHost

    private readonly actions: DesktopWindowActions

    private readonly traffic: ClientTraffic

    private readonly presentation: PresentationHost

    private readonly frame: PresentationFrame

    private readonly systemAccess: SystemAccess

    private readonly subscriptions = new Map<string, EndpointSubscription>()

    private readonly expected = new Set<string>()

    private readonly requests = new Map<string, () => void>()

    private readonly waiting = new Map<string, WaitingQuestion[]>()

    private readonly trafficSubscriptions = new Map<string, TrafficSubscription>()

    /** The exact System authority exercised by each routed subscription. */
    private readonly systemSubscriptions = new Map<string, SystemSubscriptionTarget>()

    // A synchronous SDK subscription is useful only if later work from that
    // same document cannot overtake its remote registration. Keep registration
    // as a narrow ordering barrier without serializing independent requests.
    private hostRegistrations: Promise<void> = Promise.resolve()

    private readonly desktopPreferencesSubscriptions = new Set<string>()

    private stopDesktopPreferences: (() => void) | null = null

    private readonly appearanceSubscriptions = new Set<string>()

    private stopAppearance: (() => void) | null = null

    private readonly presentationSubscriptions = new Set<string>()

    private stopPresentation: (() => void) | null = null

    private readonly trafficDeliveries = new WeakSet<object>()

    // A document can begin executing before its iframe load event gives the
    // desktop a server-host lease. Keep those endpoint envelopes at the near
    // boundary; once the load establishes ownership they follow the same path
    // as later ones.
    private readonly pending = new Array<unknown[]>()

    /**
     * Streams crossing to and from the current document, as references whose chunks follow as
     * boundary relay messages. Each document gets its own; its streams end with it.
     */
    public relay = this.newRelay()

    private owner: string | null = null

    private leased: string | null = null

    /** How many documents have begun in the frame, so a lease asked for one never goes to the next. */
    private documents = 0

    /** A document announced itself since the frame last finished loading. */
    private announced = false

    /** Asks the host for a lease for the document that just began. */
    private readonly onDocument: () => void

    public constructor(pane: string, element: HTMLIFrameElement, authManager: AuthManager, viewport: DesktopViewportHost, actions: DesktopWindowActions, traffic: ClientTraffic, presentation: PresentationHost, onDocument: () => void) {

        super()

        this.pane = pane

        this.element = element

        this.authManager = authManager

        this.viewport = viewport

        this.actions = actions

        this.traffic = traffic

        this.presentation = presentation

        this.onDocument = onDocument

        this.frame = new ClientFrame(element)

        this.systemAccess = new SystemAccess(authManager, pane)

        this.$outbound.forwardTo((route, ...values) => {

            this.send([route, ...values])
        })
    }

    /**
     * Gives the current document its lease. Until it holds one, what the document sends waits here;
     * then it follows in order. A lease that arrives after a newer document began is left for that
     * document's own.
     */
    public async own(owner: string) {

        const document = this.documents

        await this.authManager.processManager.ownFrame(this.pane, owner)

        this.leased = owner

        if (document !== this.documents) return

        this.owner = owner

        this.hostRegistrations = Promise.resolve()

        for (const [subscription, description] of this.subscriptions) {

            if (directSubscription(description)) this.orderHostRegistration(
                () => this.authManager.processManager.subscribeFrame(this.pane, owner, subscription, description.kind, description.event)
            ).catch(() => undefined)
        }

        for (const message of this.pending.splice(0)) this.receive(message)
    }

    /**
     * The frame finished loading a document. A document that runs the SDK has already announced
     * itself; one that did not (a page without it) ends the previous one only now. Returns whether
     * the document needs a lease.
     */
    public loaded() {

        if (this.announced) {

            this.announced = false

            return false
        }

        // What arrived without a lease belongs to the document that just loaded.
        const pending = this.pending.splice(0)

        this.leave()

        this.pending.push(...pending)

        return true
    }

    /** A new document began in the frame: the previous one ends, and what follows is the new one's. */
    private begin() {

        this.announced = true

        this.leave()

        this.onDocument()
    }

    /** Ends what the frame's document held: its subscriptions, requests, and streams. */
    private leave() {

        this.documents++

        this.relay.close(new Error("The Program's window was reloaded"))

        this.relay = this.newRelay()

        this.presentation.begin(this.pane)

        this.resetEndpoint()

        this.owner = null
    }

    public async release() {

        this.presentation.cancelMoveGestures(this.pane)

        const owner = this.leased

        this.documents++

        this.owner = null

        this.leased = null

        this.resetEndpoint()

        this.pending.length = 0

        this.relay.close(new Error("The Program's window closed"))

        if (owner) await this.authManager.processManager.releaseFrame(this.pane, owner)
    }

    /** Receive one envelope from the iframe endpoint. */
    public receive(message: unknown[]) {

        const [route, ...values] = message

        // Each document's SDK announces it first: messages from one frame arrive in order, so
        // everything before this was the previous document's, and everything after is this one's.
        if (route === "boundary" && values[0] === "document") {

            this.begin()

            return
        }

        if (route === "boundary") {

            if (!this.owner) this.pending.push(message)

            this.control(values)

            return
        }

        // The SDK reconstructs `context` from this boundary's own Process so
        // `context.server` is the exact handle at `context.process().server`.
        // A module may request that essential self-description before its
        // document reaches the iframe load event that establishes a forwarding
        // lease. It is safe to answer here: this boundary already owns `pane`,
        // and the request contains no selectable subject or outside authority.
        if (!this.owner && route === "end-host" && values[0] === "wait" && typeof values[1] === "string" && values[2] === "process") {

            this.request(values[1], values.slice(2))

            return
        }

        if (!this.owner) {

            this.pending.push(message)

            return
        }

        if (route === "end-end") {

            const asking = values[0] === "wait" && typeof values[1] === "string" ? values[1] : null

            if (asking) this.requests.set(asking, () => {

                this.authManager.processManager.cancel(this.pane, asking).catch(() => undefined)
            })

            this.afterHostRegistrations(
                () => this.authManager.processManager.processes.get(this.pane)?.endEnd(...values) ?? Promise.resolve()
            ).catch((error: Error) => {

                if (asking) {

                    this.requests.delete(asking)

                    if (typeof values[2] === "string" && typeof values[3] === "string") this.deliver("end-end", "answer", asking, values[2], values[3], failed(error)).catch(() => undefined)
                }
            })

            return
        }

        if (route !== "end-host") return

        if (values[0] === "stream" && typeof values[1] === "string") {

            this.streamRequest(values[1], values.slice(2))

            return
        }

        if (values[0] === "wait" && typeof values[1] === "string") {

            this.request(values[1], values.slice(2))

            return
        }

        if (values[0] === "ask" && typeof values[1] === "string" && typeof values[3] === "string") {

            const question = values[3]

            this.requests.set(question, () => {

                this.authManager.processManager.cancel(this.pane, question).catch(() => undefined)
            })
        }

        if (values[0] === "service-ask" && typeof values[2] === "string") {

            const question = values[2]

            this.requests.set(question, () => {

                this.authManager.processManager.cancel(this.pane, question).catch(() => undefined)
            })
        }

        this.trackSystemSubscription(values)

        this.runHost(values[0], values.slice(1)).catch((error: Error) => {

            if (values[0] === "observe" && typeof values[1] === "string" && values[6] === true) {

                this.impossible(values[1], error.message)

                return
            }

            if (values[0] === "follow" && typeof values[1] === "string" && values[5] === true) {

                this.impossible(values[1], error.message)

                return
            }

            if (values[0] === "service-follow" && typeof values[1] === "string" && values[5] === true) {

                this.impossible(values[1], error.message)

                return
            }

            if (values[0] === "ask" && typeof values[3] === "string") {

                this.requests.delete(values[3])
                this.deliver("end-end", "answer", values[3], values[4], values[5], failed(error)).catch(() => undefined)

                return
            }

            if (values[0] === "service-ask" && typeof values[2] === "string") {

                this.requests.delete(values[2])
                this.deliver("end-end", "answer", values[2], values[3], values[4], failed(error)).catch(() => undefined)
            }

        })
    }

    private runHost(word: unknown, args: unknown[]) {

        const operation = () => host(
            this.authManager,
            this.pane,
            this.viewport,
            this.actions,
            () => this.owner,
            this.frame,
            this.presentation
        )(word, ...args)

        return hostRegistrationOperation(word)
            ? this.orderHostRegistration(operation)
            : this.afterHostRegistrations(operation)
    }

    private orderHostRegistration<Result>(operation: () => Promise<Result>) {

        const ordered = this.hostRegistrations.then(operation)

        this.hostRegistrations = ordered.then(() => undefined, () => undefined)

        return ordered
    }

    private afterHostRegistrations<Result>(operation: () => Promise<Result>) {

        return this.hostRegistrations.then(operation)
    }

    /** Deliver one routed envelope only when this endpoint requested it. */
    public async deliver(route: string, ...values: unknown[]) {

        if (!await this.canDeliverSystemSubscription(route, values[0])) return

        if (values[0] === "answer" && typeof values[1] === "string") {

            if (!this.expected.has(values[1])) return

            this.requests.delete(values[1])

            await this.$outbound.publish(route, ...values)

            return
        }

        // A stream's messages answer a question this Client asked, as an answer does: they go to it
        // while it waits, never through the filter of events it subscribed to.
        if (values[0] === "stream" && typeof values[1] === "string") {

            if (!this.expected.has(values[1])) return

            await this.$outbound.publish(route, ...values)

            return
        }

        const question = values[0] === "wait" && typeof values[1] === "string" ? values[1] : null

        const eventIndex = question && route === "end-end" ? 3 : 2

        const event = String(question ? values[eventIndex] : values[0])

        const payload = question ? values.slice(eventIndex + 1) : values.slice(1)

        const kind: TrafficKind = question ? "ask" : "publish"

        if (this.accepts(kind, route, event, payload)) {

            await this.$outbound.publish(route, ...values)

            return
        }

        if (!question) return

        const key = `${route}:${event}`

        const waiting = this.waiting.get(key) ?? []

        waiting.push({ route, values, question })

        this.waiting.set(key, waiting)
    }

    public post(route: string, values: unknown[], transfer: Transferable[] = []) {

        this.send([route, ...values], transfer)
    }

    private send(message: unknown[], transfer: Transferable[] = []) {

        const target = this.element.contentWindow

        if (!target) return

        const attachments = nativeAttachments(message, transfer)

        const bytes = messagepack.serialize(message, { attachments, streams: this.relay })

        target.postMessage([bytes, ...attachments], "*", [bytes.buffer, ...transfer])
    }

    private newRelay() {

        return new StreamRelay(message => this.send(["boundary", "relay", ...message]))
    }

    public impossible(subscription: string, reason: string) {

        this.$outbound.publish("boundary", "impossible", subscription, reason).catch(() => undefined)
    }

    private trackSystemSubscription(values: unknown[]) {

        const [operation, subscription, target] = values

        if (typeof subscription !== "string") return

        if (operation === "service-follow") {

            if (isServiceAddress(target)) this.systemSubscriptions.set(subscription, { domain: "service", service: target })

            return
        }

        if (operation === "observe" || operation === "follow") {

            const process = target === null
                ? this.authManager.processManager.processes.get(this.pane)
                : isHandleAddress(target)
                    ? this.authManager.processManager.processes.get(target.identity)
                    : undefined

            if (process) this.systemSubscriptions.set(subscription, { domain: "program", program: process.program })

            return
        }

        if (operation === "service-unfollow" || operation === "unobserve" || operation === "unfollow") {

            this.systemSubscriptions.delete(subscription)
        }
    }

    private async canDeliverSystemSubscription(route: string, subscription: unknown) {

        if (route !== "observed" && route !== "emitted" && route !== "service-event") return true
        if (typeof subscription !== "string" || !this.systemSubscriptions.has(subscription)) return false

        const target = this.systemSubscriptions.get(subscription)

        // The System checks Service authority both when registering and when
        // emitting. Repeating that round-trip here would put delivery behind
        // the traffic it is supposed to authorize.
        return target?.domain === "service"
            ? true
            : target?.domain === "program"
                ? await this.systemAccess.canProgram({ identity: target.program })
                : false
    }

    private control(values: unknown[]) {

        const [operation, ...args] = values

        if (operation === "log") {

            if (typeof args[0] !== "string" || typeof args[1] !== "string") return

            // The iframe supplies only what it said. This boundary supplies
            // the Process identity, so program code has no route for naming a
            // different owner, and logging itself has no response path.
            this.authManager.processManager.log(this.pane, args[0], args[1])

            return
        }

        if (operation === "subscribe") {

            const [subscription, kind, route, event, subject, reportImpossible] = args

            if (typeof subscription !== "string" || !isTrafficKind(kind) || typeof route !== "string") return

            if (event !== null && typeof event !== "string") return

            if (subject !== null && typeof subject !== "string") return

            if (reportImpossible === true && route === "end-end") {

                const process = this.authManager.processManager.processes.get(this.pane)

                const program = process && this.authManager.programManager.programs.get(process.program)

                if (!process || !program?.server) {

                    this.impossible(subscription, process ? "This program declared no server half" : "The process no longer exists")

                    return
                }
            }

            this.removeSubscription(subscription)

            const description = { kind, route, event, subject }

            this.subscriptions.set(subscription, description)

            if (!desktopOwnedSubscription(description)) this.addTraffic(kind, route, event)

            const owner = this.owner

            if (owner && directSubscription(description)) this.orderHostRegistration(
                () => this.authManager.processManager.subscribeFrame(this.pane, owner, subscription, kind, event)
            ).catch(() => undefined)

            if (desktopPreferencesSubscription(description)) {

                this.desktopPreferencesSubscriptions.add(subscription)

                if (!this.stopDesktopPreferences) {

                    const tunnel = this.authManager.linkManager.desktopPreferences.tunnel
                    const stops = (["change", "changeResolved"] as const).map(event => tunnel.subscribe(event, (value: unknown) => {

                        this.deliver("host-desktop-preferences", event, value).catch(() => undefined)
                    }))

                    this.stopDesktopPreferences = () => stops.forEach(stop => stop())
                }

            }

            if (appearanceSubscription(description)) {

                this.appearanceSubscriptions.add(subscription)

                if (!this.stopAppearance) this.stopAppearance = this.authManager.linkManager.appearance.tunnel.subscribe("change", (appearance: unknown) => {

                    this.deliver("host-appearance", "change", appearance).catch(() => undefined)
                })

            }

            if (presentationSubscription(description)) {

                this.presentationSubscriptions.add(subscription)

                if (!this.stopPresentation) this.stopPresentation = this.followDrawing()
            }

            if (kind === "ask") this.releaseWaiting(route, event)

            return
        }

        if (operation === "unsubscribe") {

            if (typeof args[0] === "string") this.removeSubscription(args[0])

            return
        }

        if (operation === "expect") {

            if (typeof args[0] === "string") this.expected.add(args[0])

            return
        }

        if (operation === "forget") {

            if (typeof args[0] !== "string") return

            const question = args[0]

            this.expected.delete(question)

            this.requests.get(question)?.()

            this.requests.delete(question)

            this.forgetWaiting(question)

            this.forgetPending(question)
        }
    }

    private request(question: string, args: unknown[]) {

        if (!this.expected.has(question)) return

        if (args[0] === "wait-ready") {

            void this.afterHostRegistrations(() => this.waitReady(question, args[1], args[2], args[3] === true))

            return
        }

        if (args[0] === "context-permission-request" && typeof args[1] === "string") {

            this.answerRequest(
                question,
                this.runHost(args[0], args.slice(1)),
                () => { this.authManager.permissionManager.cancel(args[1] as string).catch(() => undefined) }
            )

            return
        }

        this.answerRequest(question, this.runHost(args[0], args.slice(1)))
    }

    private answerRequest(question: string, operation: Promise<unknown[] | TransferredAnswer>, cancel: () => void = () => undefined) {

        let active = true

        this.requests.set(question, () => {

            if (!active) return

            active = false

            cancel()
        })

        operation.then(

            answer => {

                if (!active || !this.expected.has(question)) return

                this.requests.delete(question)

                const transferred = answer instanceof TransferredAnswer ? answer : null

                if (transferred) this.post("host-end", ["answer", question, succeeded(transferred.result)], transferred.transfer)

                else this.deliver("host-end", "answer", question, succeeded(answer)).catch(() => undefined)
            },

            (error: Error) => {

                if (!active || !this.expected.has(question)) return

                this.requests.delete(question)

                this.deliver("host-end", "answer", question, failed(error)).catch(() => undefined)
            }
        )
    }

    private streamRequest(question: string, args: unknown[]) {
        let active = true
        let iterator: AsyncIterator<unknown> | null = null

        this.requests.set(question, () => {
            if (!active) return
            active = false
            void iterator?.return?.()
        })

        const run = async () => {
            await this.hostRegistrations
            await this.deliver("host-end", "stream", question, "open")

            if (args[0] === "shell") {

                await this.systemAccess.requireAll()
                if (typeof args[1] !== "string") throw new Error("A shell command must be text")

                const operation = this.authManager.shellManager.run(
                    args[1],
                    shellOptions(args[2]),
                    this.pane
                )

                iterator = operation[Symbol.asyncIterator]()
            }
            else if (args[0] === "storage-watch") {

                const scope = args[1]

                const path = storagePath(scope === "program" ? args[4] : args[2])

                const options = storageWatchOptions(scope === "program" ? args[5] : args[3])

                if (scope === "system") {

                    const resolved = await this.authManager.storage("path", path)

                    if (typeof resolved !== "string") throw new Error("The System returned an invalid Storage path")

                    await this.systemAccess.requireStorage(resolved, "read")

                    iterator = this.authManager.watchStorage({ scope, path, recursive: options.recursive })[Symbol.asyncIterator]()
                }

                else if (scope === "program") {

                    if (!isHandleAddress(args[2])) throw new Error("A Program handle is required")

                    if (args[3] !== "data" && args[3] !== "cache") throw new Error("A Program Storage area is data or cache")

                    const program = this.authManager.programManager.programs.get(args[2].identity)

                    if (!program || program.reference !== args[2].reference) throw new Error("The Program represented by this handle does not exist")

                    await this.systemAccess.program(program)

                    iterator = this.authManager.watchStorage({

                        scope,

                        program: args[2],

                        area: args[3],

                        path,

                        recursive: options.recursive

                    })[Symbol.asyncIterator]()
                }

                else throw new Error("A Storage watch scope is system or program")
            }
            else {

                if (args[0] !== "install" && args[0] !== "uninstall" && args[0] !== "run") throw new Error(`The desktop does not know the stream operation "${String(args[0])}"`)

                if (!isHandleAddress(args[1])) throw new Error("A Program handle is required")

                const program = this.authManager.programManager.programs.get(args[1].identity)

                if (!program || program.reference !== args[1].reference) throw new Error("The Program represented by this handle does not exist")

                await this.systemAccess.program(program)

                let value = args[0] === "run" ? await this.systemAccess.launch(args[2]) : args[2]
                if (args[0] === "install") {
                    const options = parseProgramInstallOptions(args[2] ?? {})
                    value = options.launch === undefined || options.launch === false ? options : {
                        ...options,
                        launch: await this.systemAccess.launch(options.launch === true ? {} : options.launch)
                    }
                }
                const operation = this.authManager.programManager.command(args[1], args[0], value, this.pane)

                iterator = operation[Symbol.asyncIterator]()
            }

            while (active) {
                const next = await iterator.next()

                if (next.done) break

                await this.deliver("host-end", "stream", question, "data", args[0] === "run" ? runEvent(this.authManager, next.value) : next.value)
            }

            if (active && this.expected.has(question)) {
                await this.deliver("host-end", "stream", question, "answer", succeeded(undefined))
            }
        }

        run().catch(async exception => {
            if (active && this.expected.has(question)) {
                await this.deliver("host-end", "stream", question, "answer", failed(exception))
            }
        }).finally(() => {
            active = false
            this.requests.delete(question)
        })
    }

    private async waitReady(question: string, target: unknown, endpoint: unknown, requireCurrentIncarnation: boolean) {

        const process = target === undefined || target === null
            ? this.authManager.processManager.processes.get(this.pane)
            : isHandleAddress(target)
                ? this.authManager.processManager.processes.get(target.identity)
                : undefined

        if (!process || (isHandleAddress(target) && process.reference !== target.reference)) {

            this.deliver("host-end", "answer", question, failed(new Error("The desktop does not know this process"))).catch(() => undefined)

            return
        }

        try { await this.systemAccess.process(process) }

        catch (error) {

            this.deliver("host-end", "answer", question, failed(error)).catch(() => undefined)

            return
        }

        if (endpoint !== "server" && endpoint !== "client") {

            this.deliver("host-end", "answer", question, failed(new Error("Readiness needs an Endpoint"))).catch(() => undefined)

            return
        }

        const program = this.authManager.programManager.programs.get(process.program)

        if (!program?.[endpoint]) {

            this.deliver("host-end", "answer", question, failed(new Error(`This program declared no ${endpoint} Endpoint`))).catch(() => undefined)

            return
        }

        if (requireCurrentIncarnation && !process[endpoint]) {

            this.deliver("host-end", "answer", question, failed(new Error(`This process has no live ${endpoint} Endpoint`))).catch(() => undefined)

            return
        }

        if (endpoint === "server" ? process.server?.ready : process.client) {

            this.deliver("host-end", "answer", question, succeeded([])).catch(() => undefined)

            return
        }

        let active = true
        const incarnation = requireCurrentIncarnation ? process[endpoint] : null

        const stopReady = this.authManager.processManager.$inbound.subscribe(endpoint === "server" ? "/server-ready" : "/client-start", (identity: unknown) => {

            if (!active || identity !== process.identity || this.authManager.processManager.processes.get(process.identity) !== process || !this.expected.has(question)) return

            stop()

            this.requests.delete(question)

            this.deliver("host-end", "answer", question, succeeded([])).catch(() => undefined)
        })

        const stopExit = this.authManager.processManager.$inbound.subscribe("/exited", (payload: unknown) => {

            if (!active || !payload || typeof payload !== "object" || (payload as { reference?: unknown }).reference !== process.reference) return

            stop()

            this.requests.delete(question)

            this.deliver("host-end", "answer", question, failed(new Error(`The process ended before its ${endpoint} Endpoint became ready`))).catch(() => undefined)
        })

        const endpointStopped = (identity: unknown) => {

            if (!active || identity !== process.identity || this.authManager.processManager.processes.get(process.identity) !== process) return

            stop()

            this.requests.delete(question)

            this.deliver("host-end", "answer", question, failed(new Error(`The ${endpoint} Endpoint stopped before becoming ready`))).catch(() => undefined)
        }

        const stopEndpoint = requireCurrentIncarnation
            ? this.authManager.processManager.$inbound.subscribe(`/${endpoint}-stop`, endpointStopped)
            : () => undefined

        const stop = () => {

            if (!active) return

            active = false

            stopReady()

            stopExit()

            stopEndpoint()
        }

        this.requests.set(question, stop)

        if (incarnation && process[endpoint] !== incarnation) endpointStopped(process.identity)
    }

    private accepts(kind: TrafficKind, route: string, event: string, payload: unknown[]) {

        for (const subscription of this.subscriptions.values()) {

            if (subscription.kind !== kind || subscription.route !== route) continue

            if (subscription.event !== null && subscription.event !== event) continue

            if (subscription.subject !== null && payload[0] !== subscription.subject) continue

            return true
        }

        return false
    }

    private addTraffic(kind: TrafficKind, route: string, event: string | null) {

        const key = JSON.stringify([kind, route, event])

        const current = this.trafficSubscriptions.get(key)

        if (current) {

            current.count++

            return
        }

        const stop = route === "host-client-memory" && kind === "publish"
            ? this.authManager.processManager.$inbound.subscribe("/client-memory-change", (identity: string, key: string, snapshot: unknown) => {
                if (event !== null && event !== key) return
                const target = this.authManager.processManager.processes.get(identity)
                if (!target?.client) return
                void this.systemAccess.canProcess(target).then(allowed => {
                    if (allowed) this.deliver(route, key, identity, snapshot).catch(() => undefined)
                })
            })
            : this.traffic.observe(this.pane, route, kind, event, (delivery, ...values) => {

            if (this.trafficDeliveries.has(delivery)) return

            this.trafficDeliveries.add(delivery)

            this.deliver(route, ...values).catch(() => undefined)
        })

        this.trafficSubscriptions.set(key, { count: 1, stop })
    }

    private removeSubscription(subscription: string) {

        const existing = this.subscriptions.get(subscription)

        if (!existing) return

        const owner = this.owner

        if (owner && directSubscription(existing)) this.orderHostRegistration(
            () => this.authManager.processManager.unsubscribeFrame(this.pane, owner, subscription)
        ).catch(() => undefined)

        this.subscriptions.delete(subscription)

        if (this.desktopPreferencesSubscriptions.delete(subscription) && this.desktopPreferencesSubscriptions.size === 0) {

            this.stopDesktopPreferences?.()

            this.stopDesktopPreferences = null
        }

        if (this.appearanceSubscriptions.delete(subscription) && this.appearanceSubscriptions.size === 0) {

            this.stopAppearance?.()

            this.stopAppearance = null
        }

        if (this.presentationSubscriptions.delete(subscription) && this.presentationSubscriptions.size === 0) {

            this.stopPresentation?.()

            this.stopPresentation = null
        }

        const key = JSON.stringify([existing.kind, existing.route, existing.event])

        const traffic = this.trafficSubscriptions.get(key)

        if (!traffic) return

        traffic.count--

        if (traffic.count > 0) return

        traffic.stop()

        this.trafficSubscriptions.delete(key)
    }

    private releaseWaiting(route: string, event: string | null) {

        for (const [key, waiting] of this.waiting) {

            if (!key.startsWith(`${route}:`)) continue

            const remaining: WaitingQuestion[] = []

            for (const held of waiting) {

                const eventIndex = held.route === "end-end" ? 3 : 2

                const word = String(held.values[eventIndex])

                const payload = held.values.slice(eventIndex + 1)

                if ((event === null || event === word) && this.accepts("ask", route, word, payload)) this.$outbound.publish(held.route, ...held.values).catch(() => undefined)

                else remaining.push(held)
            }

            if (remaining.length) this.waiting.set(key, remaining)

            else this.waiting.delete(key)
        }
    }

    private forgetWaiting(question: string) {

        for (const [key, waiting] of this.waiting) {

            const remaining = waiting.filter(held => held.question !== question)

            if (remaining.length) this.waiting.set(key, remaining)

            else this.waiting.delete(key)
        }
    }

    private forgetPending(question: string) {

        const remaining = this.pending.filter(message => {

            const [route, operation] = message

            if ((route === "end-end" || route === "end-host") && operation === "wait") return message[2] !== question

            if (route === "end-host" && operation === "stream") return message[2] !== question

            if (route === "end-host" && operation === "ask") return message[4] !== question

            if (route === "end-host" && operation === "service-ask") return message[3] !== question

            return true
        })

        this.pending.splice(0, this.pending.length, ...remaining)
    }

    /**
     * Tells the Client each change in how it is drawn, as it happens: whatever this Desktop draws
     * changes, its box moves a step, or the frame or the Desktop changes size. Changes within one
     * frame are told once, as they stand when it is drawn.
     */
    private followDrawing() {

        const read = () => {
            try { return this.presentation.drawing(this.pane, this.element) }
            catch { return null }
        }

        let told = read()

        let scheduled = 0

        const check = () => {

            if (scheduled) return

            scheduled = requestAnimationFrame(() => {

                scheduled = 0

                const drawing = read()

                const before = told

                told = drawing

                if (!drawing || !before) return

                if (drawing.position.x !== before.position.x || drawing.position.y !== before.position.y) this.deliver("host-presentation", "move", drawing.position).catch(() => undefined)

                if (drawing.size.width !== before.size.width || drawing.size.height !== before.size.height) this.deliver("host-presentation", "resize", drawing.size).catch(() => undefined)

                if (drawing.front !== before.front) this.deliver("host-presentation", "front", drawing.front).catch(() => undefined)

                if (drawing.focused !== before.focused) this.deliver("host-presentation", "focus", drawing.focused).catch(() => undefined)

                if (drawing.interactive !== before.interactive) this.deliver("host-presentation", "changeInteractive", drawing.interactive).catch(() => undefined)

                if (JSON.stringify(drawing.surface) !== JSON.stringify(before.surface)) this.deliver("host-presentation", "changeSurface", drawing.surface).catch(() => undefined)

                if (drawing.anchor !== before.anchor) this.deliver("host-presentation", "changeAnchor", drawing.anchor).catch(() => undefined)
            })
        }

        const stopObserving = this.presentation.observe(check)

        const resizing = new ResizeObserver(check)

        resizing.observe(this.element)

        const desktop = this.element.closest("[data-desktop-layers]")

        if (desktop) resizing.observe(desktop)

        return () => {

            stopObserving()

            resizing.disconnect()

            cancelAnimationFrame(scheduled)
        }
    }

    private resetEndpoint() {

        for (const stop of this.requests.values()) stop()

        this.requests.clear()

        const owner = this.owner

        if (owner) for (const [subscription, description] of this.subscriptions) {

            if (directSubscription(description)) this.orderHostRegistration(
                () => this.authManager.processManager.unsubscribeFrame(this.pane, owner, subscription)
            ).catch(() => undefined)
        }

        this.subscriptions.clear()

        this.desktopPreferencesSubscriptions.clear()

        this.appearanceSubscriptions.clear()

        this.stopDesktopPreferences?.()

        this.stopDesktopPreferences = null

        this.stopAppearance?.()

        this.stopAppearance = null

        this.presentationSubscriptions.clear()

        this.stopPresentation?.()

        this.stopPresentation = null

        for (const { stop } of this.trafficSubscriptions.values()) stop()

        this.trafficSubscriptions.clear()

        this.systemSubscriptions.clear()

        this.expected.clear()

        this.waiting.clear()

        this.pending.length = 0
    }

}

export function frameMovePoint(frame: HTMLIFrameElement, point: DesktopMovePoint): DesktopMovePoint {
    const bounds = frame.getBoundingClientRect()
    // Frame-local CSS pixels must enter the same physical viewport coordinate
    // space as pointer events captured directly by the Desktop.
    const scaleX = frame.clientWidth === 0 ? 1 : bounds.width / frame.clientWidth
    const scaleY = frame.clientHeight === 0 ? 1 : bounds.height / frame.clientHeight
    return { x: bounds.left + point.x * scaleX, y: bounds.top + point.y * scaleY }
}

export class ClientFrame implements PresentationFrame {
    public constructor(public readonly element: HTMLIFrameElement) {}

    public point(point: PresentationMovePoint) {
        return frameMovePoint(this.element, point)
    }
}

function storagePath(value: unknown) {

    if (!Array.isArray(value) || value.some(part => typeof part !== "string")) throw new Error("A Storage path is a list of names")

    return value as string[]
}

function storageWatchOptions(value: unknown) {

    if (value === undefined) return { recursive: false }

    if (!value || typeof value !== "object") throw new Error("Storage watch options must be an object")

    const recursive = (value as { recursive?: unknown }).recursive

    if (recursive !== undefined && typeof recursive !== "boolean") throw new Error("Storage recursive must be boolean")

    return { recursive: recursive === true }
}

function runEvent(authManager: AuthManager, value: unknown) {

    const event = value as { event?: unknown, process?: SdkProcessSource } | null

    if ((event?.event !== "started" && event?.event !== "exited") || !event.process) return value

    const program = authManager.programManager.programs.get(event.process.program)

    if (!program) throw new Error("The desktop does not know the Process Program")

    return { ...event, process: sdkProcess(event.process, program) }
}

function shellOptions(value: unknown): Omit<ShellOptions, "signal"> {

    if (value === undefined) return {}
    if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Shell options must be an object")

    const options = value as Record<string, unknown>

    if (options.cwd !== undefined && (typeof options.cwd !== "string" || !options.cwd)) throw new Error("A shell working directory must be non-empty text")
    if (options.env !== undefined && (!options.env || typeof options.env !== "object" || Array.isArray(options.env) || Object.values(options.env).some(entry => typeof entry !== "string"))) {

        throw new Error("Shell environment values must be text")
    }

    return options as Omit<ShellOptions, "signal">
}

const nativeAttachments = (value: unknown, transfer: readonly Transferable[]) => {

    const attachments: object[] = [...transfer]

    const known = new Set<object>(attachments)

    const visit = (entry: unknown) => {

        if (entry === null || typeof entry !== "object" || known.has(entry)) return

        known.add(entry)

        if (entry instanceof Blob) {

            attachments.push(entry)

            return
        }

        if (entry instanceof Date || entry instanceof RegExp || entry instanceof URL || entry instanceof Error || entry instanceof ArrayBuffer || ArrayBuffer.isView(entry)) return

        if (entry instanceof Map) {

            for (const [key, item] of entry) {

                visit(key)

                visit(item)
            }

            return
        }

        if (entry instanceof Set) {

            for (const item of entry) visit(item)

            return
        }

        for (const item of Array.isArray(entry) ? entry : Object.values(entry)) visit(item)
    }

    visit(value)

    return attachments
}

interface EndpointSubscription {

    kind: TrafficKind

    route: string

    event: string | null

    subject: string | null
}

type SystemSubscriptionTarget =
    | Readonly<{ domain: "program", program: string }>
    | Readonly<{ domain: "service", service: ServiceAddress }>

function desktopPreferencesSubscription(subscription: EndpointSubscription) {

    return subscription.kind === "publish" && subscription.route === "host-desktop-preferences" && (subscription.event === null || subscription.event === "change" || subscription.event === "changeResolved")
}

function appearanceSubscription(subscription: EndpointSubscription) {

    return subscription.kind === "publish" && subscription.route === "host-appearance" && (subscription.event === null || subscription.event === "change")
}

function presentationSubscription(subscription: EndpointSubscription) {

    return subscription.kind === "publish" && subscription.route === "host-presentation"
}

function desktopOwnedSubscription(subscription: EndpointSubscription) {

    return desktopPreferencesSubscription(subscription) || appearanceSubscription(subscription) || presentationSubscription(subscription)
}

function directSubscription(subscription: EndpointSubscription) {

    return subscription.route === "end-end" && subscription.kind === "publish"
}

function hostRegistrationOperation(value: unknown) {

    return value === "observe"
        || value === "unobserve"
        || value === "follow"
        || value === "unfollow"
        || value === "service-follow"
        || value === "service-unfollow"
}

function isTrafficKind(value: unknown): value is TrafficKind {

    return value === "publish" || value === "ask" || value === "answer"
}

function isHandleAddress(value: unknown): value is { identity: string, reference: string } {

    return typeof value === "object" && value !== null && "identity" in value && "reference" in value
        && typeof value.identity === "string" && typeof value.reference === "string"
}


interface WaitingQuestion {

    route: string

    values: unknown[]

    question: string
}

interface TrafficSubscription {

    count: number

    stop: () => void
}