An open-source, self-hosted system for apps built with web technologies.
Opening: a request reaches the owner even when nothing opens it; defaults follow their Programs
zohayrslilehe46c1483bce2
diff --git a/source/client/view/structure/desktop/layers/shell/dialogs/open-requests.tsx b/source/client/view/structure/desktop/layers/shell/dialogs/open-requests.tsxindex b178922..b498f49 100644--- a/source/client/view/structure/desktop/layers/shell/dialogs/open-requests.tsx+++ b/source/client/view/structure/desktop/layers/shell/dialogs/open-requests.tsx@@ -53,14 +53,16 @@ function OpenRequestView({ request }: Readonly<{ request: OpenRequestSnapshot }><span className="truncate" title={request.target.uri}><Text size="small" style={{ fontWeight: 500 }}>{describe(request.target.uri)}</Text></span><Dialog.Description>{request.from ? `${request.from.process.program.name} asks to open it` : "Opened from outside the Desktop"} · {request.target.type}</Dialog.Description></div>- <div className="grid" style={{ gap: space.xsmall }}>+ {/* A request reaches the owner even when nothing here opens it: they learn it, and only close it. */}+ {!programs.length && <Text size="small" tone="secondary">No Program on this System opens this.</Text>}+ {!!programs.length && <div className="grid" style={{ gap: space.xsmall }}>{programs.map(program => <Button key={program.identity} disabled={decision.isPending} onPress={() => decision.safeExecute(program.identity)}style={{ justifyContent: "flex-start" }}><img src={programIcon(application.doors.program, program.assetId)} alt="" draggable={false} className="shrink-0 object-contain" style={{ width: space.large, height: space.large }} />{program.name}</Button>)}- </div>- <Checkbox size="small" checked={always} onChange={setAlways} label={`Always open ${request.target.type} with it`} />+ </div>}+ {!!programs.length && <Checkbox size="small" checked={always} onChange={setAlways} label={`Always open ${request.target.type} with it`} />}{decision.exception && <Alert className="text-sm">{String(decision.exception.current)}</Alert>}</Dialog.Body><Dialog.Footer>diff --git a/source/server/core/link-manager/auth-manager/auth-manager.ts b/source/server/core/link-manager/auth-manager/auth-manager.tsindex 79e5821..984c704 100644--- a/source/server/core/link-manager/auth-manager/auth-manager.ts+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts@@ -37,6 +37,8 @@ export default class AuthManager extends TheLink {this.programManager = new ProgramManager(this)+ this.openingManager.followPrograms(this.programManager)+this.processManager = new ProcessManager(this)this.shellManager = new ShellManager(this)@@ -259,7 +261,7 @@ export default class AuthManager extends TheLink {@Subscribe("/open")protected async openForOwner(target: unknown, options: unknown) {- await this.openingManager.open(target, null, options, this.linkManager.connection().signal)+ await this.openingManager.open(target, null, options)}@Subscribe("/appearance/update")diff --git a/source/server/core/opening-manager.ts b/source/server/core/opening-manager.tsindex 59825f2..b259a57 100644--- a/source/server/core/opening-manager.ts+++ b/source/server/core/opening-manager.ts@@ -3,6 +3,7 @@ import { Subscribe } from "@the-link/core/decorators"import { opensType, parseOpenOptions, parseOpenTarget, parseOpenType, type OpenRequestSnapshot, type OpenTarget, type Position } from "@phreshos/core"import shortIdentity from "@libs/short-identity"import type AuthManager from "./link-manager/auth-manager/auth-manager"+import type ProgramManager from "./link-manager/auth-manager/program-manager/program-manager"import type Process from "./link-manager/auth-manager/process-manager/process"import { endpointReference } from "./link-manager/auth-manager/process-manager/endpoint-reference"@@ -14,13 +15,21 @@ export const openRequestTimeout = 120_000/*** Opening: something to open goes to its type's default Program, else its family's (`image/*`), or- * waits as a request until the owner chooses one. The System only records requests and choices; how a request is shown is up to the- * Shell.+ * waits as a request until the owner chooses one, even when no Program opens it. The System only+ * records requests and choices; how a request is shown is up to the Shell.*/export default class OpeningManager extends TheLink {private readonly pendingRequests = new Map<string, PendingOpenRequest>()+ /**+ * The defaults that count, as last announced: no Program is known before the Programs register, so+ * none count yet, and each one that comes to count is announced as it does.+ */+ private counted: Readonly<Record<string, string>> = {}++ private settling: Promise<void> = Promise.resolve()+public constructor(private readonly authManager: AuthManager) {super()@@ -28,6 +37,15 @@ export default class OpeningManager extends TheLink {this.connectTo(authManager, "/opening")}+ /**+ * Follows every change of the Programs the System knows: one attached, installed, updated, or+ * forgotten can make a default count or stop counting.+ */+ public followPrograms(programs: ProgramManager) {++ for (const change of ["/create", "/install", "/forget"]) programs.$outbound.subscribe(change, () => this.settle())+ }+public requests() {return [...this.pendingRequests.values()].map(request => request.snapshot)@@ -38,32 +56,30 @@ export default class OpeningManager extends TheLink {return this.pendingRequests.has(identity)}- /** The installed Programs that open this exact type, or all of this family, by identity. */+ /** The Programs that open this exact type, or all of this family, by identity: installed or attached from a project. */public programsFor(type: string): string[] {return [...this.authManager.programManager.programs.values()]- .filter(entry => entry.installed && opensType(entry.program.config.opens ?? [], type))+ .filter(entry => opensType(entry.program.config.opens ?? [], type)).map(entry => entry.identity)}/**- * Opens one target for an Endpoint, or for the owner when `from` is null. It resolves once a- * Process is started for it, and rejects when no Program opens it or nothing is chosen. A request- * from outside ends with the connection that asked, through `signal`.+ * Opens one target for an Endpoint, or for the owner when `from` is null. The asker hands it over:+ * it resolves once the System has taken it, and rejects only for a target or options it cannot+ * read. What follows is between the System and the owner: a default Program opens it at once;+ * otherwise it waits as a request for the owner, even with no Program to offer.*/- public async open(value: unknown, from: Readonly<{ process: Process, endpoint: "server" | "client" }> | null, options?: unknown, signal?: AbortSignal) {+ public async open(value: unknown, from: Readonly<{ process: Process, endpoint: "server" | "client" }> | null, options?: unknown) {const target = parseOpenTarget(value)// Where the asker would have the window open, unless the Program that opens it says.const position = parseOpenOptions(options).position ?? nullconst programs = this.programsFor(target.type)- if (!programs.length) throw new Error(`No Program opens ${target.type}`)-// The exact type's default is the stronger choice; its family's applies only without one.- const defaults = await this.chosen()- const chosen = [defaults[target.type], defaults[`${target.type.slice(0, target.type.indexOf("/"))}/*`]]- .find(program => program !== undefined && programs.includes(program))+ const defaults = await this.counting()+ const chosen = [defaults[target.type], defaults[`${target.type.slice(0, target.type.indexOf("/"))}/*`]].find(program => program !== undefined)if (chosen) {await this.launch(chosen, target, position)@@ -79,14 +95,8 @@ export default class OpeningManager extends TheLink {programs: Object.freeze(programs.map(program => this.record(program)))}) satisfies OpenRequestSnapshot- let settle: (program: string | null) => void = () => undefined- const result = new Promise<string | null>(resolve => { settle = resolve })- // A request belongs to the Endpoint run that asked: when it stops, nobody waits for the answer.- const end = () => { this.cancel(identity).catch(() => undefined) }- const cancelEndpoint = from ? from.endpoint === "server" ? from.process.onServerStop(end) : from.process.onClientStop(end)- : signal ? (signal.addEventListener("abort", end), () => signal.removeEventListener("abort", end)) : () => undefined-- this.pendingRequests.set(identity, { snapshot, position, settle, cancelEndpoint, timer: null, resolving: false })+ // The request is the owner's from here: it stays until they decide, whatever becomes of the asker.+ this.pendingRequests.set(identity, { snapshot, position, timer: null, resolving: false })await Promise.all([this.authManager.processManager.announceHost("opening", null, "request", "system", snapshot).catch(() => undefined),@@ -97,8 +107,6 @@ export default class OpeningManager extends TheLink {// Observable before it can expire, as a permission request is.if (pending) pending.timer = setTimeout(() => { this.cancel(identity).catch(() => undefined) }, openRequestTimeout)-- if (await result === null) throw new Error(`Nothing was chosen to open ${target.type}`)}@Subscribe("/requests")@@ -148,13 +156,41 @@ export default class OpeningManager extends TheLink {}}- /** The default Program of each media type and family, as the Programs themselves; one no longer known is left out. */+ /**+ * The default Program of each media type and family, as the Programs themselves: only those that+ * count, whose Program the System knows and still opens that type.+ */@Subscribe("/defaults")public async defaults() {- return Object.fromEntries(Object.entries(await this.chosen())- .filter(([, program]) => this.authManager.programManager.programs.has(program))- .map(([type, program]) => [type, this.record(program)]))+ return Object.fromEntries(Object.entries(await this.counting()).map(([type, program]) => [type, this.record(program)]))+ }++ /**+ * The chosen defaults that count. One that does not stays chosen: it counts again when its Program+ * is installed again or opens that type again, unless the owner changes it or the Program is purged.+ */+ private async counting() {++ return Object.fromEntries(Object.entries(await this.chosen()).filter(([type, program]) => this.programsFor(type).includes(program)))+ }++ /** Announces each default that came to count, changed, or stopped counting since last announced. */+ private settle() {++ this.settling = this.settling.then(async () => {++ const before = this.counted+ const now = await this.counting()++ this.counted = now++ for (const type of new Set([...Object.keys(before), ...Object.keys(now)])) {+ if (before[type] !== now[type]) await this.announceDefault(type, now[type] ?? null)+ }+ }).catch(() => undefined)++ return this.settling}/** The default Program of each media type and family, by identity, as stored. */@@ -183,7 +219,7 @@ export default class OpeningManager extends TheLink {if (defaults[kept] === program) returnawait this.store.set(defaultsKey, { ...defaults, [kept]: program })- await this.announceDefault(kept, program)+ await this.settle()}@Subscribe("/clear-default")@@ -195,7 +231,21 @@ export default class OpeningManager extends TheLink {if (previous === undefined) returnawait this.store.set(defaultsKey, kept)- await this.announceDefault(cleared, null)+ await this.settle()+ }++ /**+ * Removes every default naming a Program, as purging it does: nothing in the System is to say it+ * was ever there. Each type it opened by default is then decided again, as one never chosen.+ */+ public async forgetProgram(program: string) {++ const defaults = await this.chosen()++ if (!Object.values(defaults).includes(program)) return++ await this.store.set(defaultsKey, Object.fromEntries(Object.entries(defaults).filter(([, chosen]) => chosen !== program)))+ await this.settle()}private async announceDefault(type: string, program: string | null) {@@ -227,7 +277,7 @@ export default class OpeningManager extends TheLink {const entry = this.authManager.programManager.programs.get(program)- if (!entry?.installed) throw new Error("That Program is not installed")+ if (!entry) throw new Error("The System does not know that Program")await this.authManager.programManager.open(entry.program, target, position)}@@ -251,14 +301,12 @@ export default class OpeningManager extends TheLink {if (!this.pendingRequests.delete(request.snapshot.identity)) throw new Error("The open request does not exist")if (request.timer) clearTimeout(request.timer)- request.cancelEndpoint()await Promise.all([this.authManager.processManager.announceHost("opening", null, "resolve", "system", request.snapshot, chosen).catch(() => undefined),this.$outbound.publish("/resolve", request.snapshot, chosen).catch(() => undefined)])- request.settle(program)}public toJSON() {@@ -271,8 +319,6 @@ interface PendingOpenRequest {readonly snapshot: OpenRequestSnapshot/** Where the asker would have the window open, unless its Program says. */readonly position: Position | null- readonly settle: (program: string | null) => void- readonly cancelEndpoint: () => voidtimer: ReturnType<typeof setTimeout> | nullresolving: boolean}diff --git a/tests/opening.test.ts b/tests/opening.test.tsindex a1d0f85..29d7dcc 100644--- a/tests/opening.test.ts+++ b/tests/opening.test.ts@@ -4,39 +4,62 @@ import type AuthManager from "@server/core/link-manager/auth-manager/auth-manageimport OpeningManager from "@server/core/opening-manager"function fixture() {- const program = (identity: string, opens: string[], installed = true) => [identity, { identity, installed, program: { identity, config: { opens }, record: () => ({ identity }) } }] as const+ const program = (identity: string, opens: string[], installed = true) => [identity, { identity, installed, program: { identity, config: { opens } as { opens: string[] }, record: () => ({ identity }) } }] as constconst stored = new Map<string, unknown>()const open = vi.fn(async () => "process")+ const programManager = Object.assign(new TheLink(), {+ programs: new Map([program("preview", ["image/*"]), program("paint", ["image/png"]), program("files", ["inode/directory"]), program("old", ["image/png"], false)]),+ open+ })const auth = Object.assign(new TheLink(), {linkManager: { application: { store: { get: async (key: string) => stored.get(key), set: async (key: string, value: unknown) => { stored.set(key, value) } } } },- programManager: {- programs: new Map([program("preview", ["image/*"]), program("paint", ["image/png"]), program("files", ["inode/directory"]), program("old", ["image/png"], false)]),- open- },+ programManager,processManager: { announceHost: vi.fn(async () => undefined) }}) as unknown as AuthManagerconst announceHost = (auth as unknown as { processManager: { announceHost: ReturnType<typeof vi.fn> } }).processManager.announceHost- return { manager: new OpeningManager(auth), open, stored, announceHost }+ const manager = new OpeningManager(auth)+ manager.followPrograms(programManager as never)+ // What a Program's update does: it opens other types, and the Program manager says it changed.+ async function update(identity: string, opens: string[]) {+ programManager.programs.get(identity)!.program.config.opens = opens+ await programManager.$outbound.publish("/install", { identity })+ }+ // The defaults announced, as [type, program or null].+ const announced = () => announceHost.mock.calls.filter(([, , event]) => event === "changeDefault").map(([, , , , type, record]) => [type, (record as { identity: string } | null)?.identity ?? null])+ return { manager, open, stored, announceHost, update, announced }}const png = { type: "image/png", uri: "file:///home/me/a.png" }-test("the installed Programs that open a type, wildcards included", () => {+test("the Programs that open a type, wildcards included, attached ones as installed ones", () => {const { manager } = fixture()- expect(manager.programsFor("image/png")).toEqual(["preview", "paint"])+ expect(manager.programsFor("image/png")).toEqual(["preview", "paint", "old"])expect(manager.programsFor("image/jpeg")).toEqual(["preview"])expect(manager.programsFor("text/plain")).toEqual([])})-test("nothing to open with, or a malformed target, is refused", async () => {+test("a malformed target is refused", async () => {const { manager } = fixture()- await expect(manager.open({ type: "text/plain", uri: "file:///a.txt" }, null)).rejects.toThrow(/No Program opens text\/plain/)await expect(manager.open({ type: "image/*", uri: "file:///a.png" }, null)).rejects.toThrow(/exact media type/)await expect(manager.open({ type: "image/png", uri: "not a uri" }, null)).rejects.toThrow(/URI/)})+test("what nothing opens still reaches the owner, as a request with no Program to offer", async () => {+ const { manager, open, announceHost } = fixture()+ const text = { type: "text/plain", uri: "file:///a.txt" }++ await manager.open(text, null)++ const [request] = manager.requests()+ expect(request!.programs).toEqual([])+ expect(announceHost.mock.calls.some(([, , event]) => event === "request")).toBe(true)+ await manager.cancel(request!.identity)+ expect(open).not.toHaveBeenCalled()+ expect(manager.requests()).toEqual([])+})+test("a default Program opens it at once, with no request", async () => {const { manager, open, stored } = fixture()stored.set("opening-defaults", { "image/png": "paint" })@@ -80,17 +103,16 @@ test("a family's default needs a Program that opens all of it, and each change itest("without a default, a request waits; choosing always opens it and makes the default", async () => {const { manager, open } = fixture()- const opening = manager.open(png, null)- await vi.waitFor(() => expect(manager.requests()).toHaveLength(1))+ // The asker hands it over: it does not wait for the owner's choice.+ await manager.open(png, null)const [request] = manager.requests()// Offered as the Programs themselves, so whoever decides reads them as any Program.- expect(request!.programs).toEqual([{ identity: "preview" }, { identity: "paint" }])+ expect(request!.programs).toEqual([{ identity: "preview" }, { identity: "paint" }, { identity: "old" }])await expect(manager.choose(request!.identity, "files", {})).rejects.toThrow(/does not open this/)expect(manager.pending(request!.identity)).toBe(true)await manager.choose(request!.identity, "preview", { always: true })- await openingexpect(open).toHaveBeenCalledWith(expect.objectContaining({ identity: "preview" }), png, null)expect(await manager.defaults()).toEqual({ "image/png": { identity: "preview" } })@@ -112,22 +134,50 @@ test("the asker's position goes with the opening, even once a request is decidedawait expect(manager.open(png, null, { position: { x: "beside", y: 0 } })).rejects.toThrow(/relative expression/)stored.clear()- const opening = manager.open(png, { process: asker, endpoint: "server" }, { position: beside })- await vi.waitFor(() => expect(manager.requests()).toHaveLength(1))+ await manager.open(png, { process: asker, endpoint: "server" }, { position: beside })await manager.choose(manager.requests()[0]!.identity, "preview", {})- await openingexpect(open).toHaveBeenLastCalledWith(expect.objectContaining({ identity: "preview" }), png, beside)})-test("a cancelled request opens nothing and tells the one who asked", async () => {+test("a cancelled request opens nothing", async () => {const { manager, open } = fixture()- const opening = manager.open(png, null)- await vi.waitFor(() => expect(manager.requests()).toHaveLength(1))+ await manager.open(png, null)await manager.cancel(manager.requests()[0]!.identity)- await expect(opening).rejects.toThrow(/Nothing was chosen/)expect(open).not.toHaveBeenCalled()+ expect(manager.requests()).toEqual([])+})++test("purging a Program forgets every default naming it, each announced as cleared", async () => {+ const { manager, stored, announced } = fixture()+ await manager.setDefault("image/png", "paint")+ await manager.setDefault("image/*", "preview")++ await manager.forgetProgram("paint")+ await manager.forgetProgram("paint")++ expect(stored.get("opening-defaults")).toEqual({ "image/*": "preview" })+ expect(announced()).toEqual([["image/png", "paint"], ["image/*", "preview"], ["image/png", null]])+})++test("a default counts only while its Program opens the type, and counts again once it does", async () => {+ const { manager, stored, update, announced, open } = fixture()+ await manager.setDefault("image/png", "paint")++ await update("paint", ["image/gif"])++ // Still chosen, yet left out: the owner is asked, as if none was chosen.+ expect(stored.get("opening-defaults")).toEqual({ "image/png": "paint" })+ expect(await manager.defaults()).toEqual({})+ await manager.open(png, null)+ expect(open).not.toHaveBeenCalled()+ expect(manager.requests()).toHaveLength(1)++ await update("paint", ["image/png"])++ expect(Object.keys(await manager.defaults())).toEqual(["image/png"])+ expect(announced()).toEqual([["image/png", "paint"], ["image/png", null], ["image/png", "paint"]])})test("a default whose Program is no longer known is left out", async () => {@@ -146,15 +196,11 @@ test("a default must be a Program that opens that type", async () => {expect(await manager.defaults()).toEqual({})})-test("a request from outside ends when the connection that asked closes", async () => {- const { manager, open } = fixture()- const connection = new AbortController()+test("a request stays the owner's after the one who asked is gone", async () => {+ const { manager } = fixture()+ const asker = { record: () => ({ identity: "asker" }), program: { record: () => ({ identity: "files" }) } } as never- const opening = manager.open(png, null, undefined, connection.signal)- await vi.waitFor(() => expect(manager.requests()).toHaveLength(1))- connection.abort()+ await manager.open(png, { process: asker, endpoint: "client" })- await expect(opening).rejects.toThrow(/Nothing was chosen/)- await vi.waitFor(() => expect(manager.requests()).toEqual([]))- expect(open).not.toHaveBeenCalled()+ expect(manager.requests()).toHaveLength(1)})