Skip to content

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

Stream authoritative Program uninstallation

zohayrslileh87485b1f7956
diff --git a/scripts/verify-program-install.mjs b/scripts/verify-program-install.mjs
index 7d22a5c..538ef4c 100644
--- a/scripts/verify-program-install.mjs
+++ b/scripts/verify-program-install.mjs
@@ -19,8 +19,13 @@ try {
const program = new Program({
identity: "documented-program",
agent: join(source, "operating-guide.md"),
+ categories: ["Development"],
+ keywords: ["example"],
+ website: "https://example.test/program",
server: {
location: join(source, "server"),
+ installCommand: `node -e "process.stdout.write('install-out'); process.stderr.write('install-err')"`,
+ uninstallCommand: `node -e "process.stdout.write('uninstall-out'); process.stderr.write('uninstall-err')"`,
startCommand: "true"
},
client: {
@@ -34,7 +39,27 @@ try {
const declaration = JSON.parse(readFileSync(join(installed, "program.json"), "utf8"))
assert.equal(declaration.agent, "agent.md")
+ assert.deepEqual(declaration.categories, ["Development"])
+ assert.deepEqual(declaration.keywords, ["example"])
+ assert.equal(declaration.website, "https://example.test/program")
+ assert.equal(declaration.server.uninstallCommand, program.config.server.uninstallCommand)
assert.equal(readFileSync(join(installed, "agent.md"), "utf8"), "Program operating knowledge")
+
+ const installedProgram = new Program(join(installed, "program.json"))
+ const installation = []
+ const uninstallation = []
+
+ await installedProgram.installServer(chunk => installation.push(chunk))
+ await installedProgram.uninstallServer(chunk => uninstallation.push(chunk))
+
+ assert.deepEqual(Object.fromEntries(installation.map(chunk => [chunk.stream, chunk.text])), {
+ stdout: "install-out",
+ stderr: "install-err"
+ })
+ assert.deepEqual(Object.fromEntries(uninstallation.map(chunk => [chunk.stream, chunk.text])), {
+ stdout: "uninstall-out",
+ stderr: "uninstall-err"
+ })
}
finally {
rmSync(temporary, { recursive: true, force: true })
diff --git a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts
index 87f5506..830b8a2 100644
--- a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts
+++ b/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts
@@ -4,7 +4,7 @@ import { Publish, Subscribe } from "@libs/the-link/decorators/escript"
import TheLink from "@libs/the-link/the-link"
import AuthManager from "../auth-manager"
import Program from "./program"
-import { type ProgramIconSize } from "@phreshos/core"
+import { type ProgramCommandChunk, type ProgramIconSize } from "@phreshos/core"
/**
* The peer of the core's programs: born holding them from the
@@ -24,6 +24,8 @@ export default class ProgramManager extends TheLink {
public readonly programs = new Map<string, Program>()
+ private readonly commands = new Map<string, PendingCommand>()
+
public constructor(authManager: AuthManager, payload: TransmittedProgramManager) {
super()
@@ -63,9 +65,46 @@ export default class ProgramManager extends TheLink {
return await this.$outbound.publishFirst("/install-program", identity, asker)
}
- public async uninstall(identity: string, everything: boolean, asker: string) {
+ /** Streams one authoritative uninstall operation to its requesting View. */
+ public uninstallStreaming(identity: string, everything: boolean, asker: string) {
+ const manager = this
+
+ return (async function* (): AsyncGenerator<ProgramCommandChunk, void, void> {
+ const stream = crypto.randomUUID()
+ const state: PendingCommand = { queue: [], settled: false, failure: null, wake: null }
+
+ manager.commands.set(stream, state)
+
+ const operation = manager.$outbound.publishFirst("/uninstall-program-stream", identity, everything, asker, stream).then(
+ () => { state.settled = true },
+ error => { state.failure = error instanceof Error ? error : new Error(String(error)) }
+ ).finally(() => {
+ state.wake?.()
+ state.wake = null
+ })
+
+ try {
+ while (!state.settled || state.queue.length) {
+ const next = state.queue.shift()
+
+ if (next) {
+ yield next
+ continue
+ }
+
+ if (state.failure) throw state.failure
+
+ await new Promise<void>(resolve => { state.wake = resolve })
+ }
+
+ await operation
- return await this.$outbound.publishFirst("/uninstall-program", identity, everything, asker)
+ if (state.failure) throw state.failure
+ }
+ finally {
+ manager.commands.delete(stream)
+ }
+ })()
}
public async forget(identity: string, asker: string) {
@@ -135,6 +174,26 @@ export default class ProgramManager extends TheLink {
return this.arrived(payload)
}
+ @Subscribe("/uninstall-program-output")
+ protected commandOutput(stream: string, value: unknown) {
+ const state = this.commands.get(stream)
+
+ if (!state || state.failure) return
+
+ const chunk = value as Partial<ProgramCommandChunk> | null
+
+ if (!chunk || (chunk.stream !== "stdout" && chunk.stream !== "stderr") || typeof chunk.text !== "string") {
+ state.failure = new Error("The System returned an invalid Program command output chunk")
+ }
+ else if (state.queue.length >= maximumCommandQueue) {
+ state.failure = new Error(`Program command output exceeded its queue capacity of ${maximumCommandQueue}`)
+ }
+ else state.queue.push(Object.freeze({ stream: chunk.stream, text: chunk.text }))
+
+ state.wake?.()
+ state.wake = null
+ }
+
@Subscribe("/forget")
@Publish("/programs", "inbound")
protected async forgotten(identity: string | null) {
@@ -146,3 +205,12 @@ export default class ProgramManager extends TheLink {
return [...this.programs.values()]
}
}
+
+interface PendingCommand {
+ queue: ProgramCommandChunk[]
+ settled: boolean
+ failure: Error | null
+ wake: (() => void) | null
+}
+
+const maximumCommandQueue = 256
diff --git a/source/client/core/link-manager/auth-manager/program-manager/program.ts b/source/client/core/link-manager/auth-manager/program-manager/program.ts
index 47b2608..cf021b2 100644
--- a/source/client/core/link-manager/auth-manager/program-manager/program.ts
+++ b/source/client/core/link-manager/auth-manager/program-manager/program.ts
@@ -72,9 +72,9 @@ export default class Program {
// False removes only installed program files. True removes everything
// owned by the system and forgets the runtime Program.
- public async uninstall(everything = false, asker = "") {
+ public uninstall(everything = false, asker = "") {
- await this.programManager.uninstall(this.identity, everything, asker)
+ return this.programManager.uninstallStreaming(this.identity, everything, asker)
}
public async forget(asker: string) {
diff --git a/source/client/view/desktop/client-host/client-process-boundary.ts b/source/client/view/desktop/client-host/client-process-boundary.ts
index 8f9d78a..9c1981f 100644
--- a/source/client/view/desktop/client-host/client-process-boundary.ts
+++ b/source/client/view/desktop/client-host/client-process-boundary.ts
@@ -176,6 +176,13 @@ export default class ClientProcessBoundary extends TheLink {
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))
@@ -504,6 +511,48 @@ export default class ClientProcessBoundary extends TheLink {
)
}
+ 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.deliver("host-end", "stream", question, "open")
+
+ if (args[0] !== "uninstall") throw new Error(`The desktop does not know the stream operation "${String(args[0])}"`)
+
+ const operation = this.authManager.processManager.scope(this.pane).program().uninstall(args[2] === true, 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", 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 waitReady(question: string, target: unknown, requireCurrentIncarnation: boolean) {
const mine = this.authManager.processManager.processes.get(this.pane)
@@ -756,6 +805,8 @@ export default class ClientProcessBoundary extends TheLink {
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
diff --git a/source/client/view/desktop/client-host/host.ts b/source/client/view/desktop/client-host/host.ts
index 98748df..01fd784 100644
--- a/source/client/view/desktop/client-host/host.ts
+++ b/source/client/view/desktop/client-host/host.ts
@@ -456,13 +456,6 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
return [scope.program().installed === true]
}
- if (word === "uninstall") {
-
- const program = scope.program()
-
- return [await program.uninstall(args[1] === true, pane)]
- }
-
if (word === "forget") {
const program = scope.program()
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
index 5b84a82..5b001f2 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
@@ -1424,13 +1424,6 @@ export default class ProcessManager extends TheLink {
return [programManager.installed(this.heldProgram(rest[0]))]
}
- if (word === "uninstall") {
-
- const program = this.heldProgram(rest[0])
-
- return [await programManager.uninstall(program, rest[1] === true, process.identity)]
- }
-
if (word === "forget") {
const program = this.heldProgram(rest[0])
@@ -2018,11 +2011,17 @@ export default class ProcessManager extends TheLink {
try {
- if (args[0] !== "install") throw new Error(`The host does not know the stream operation "${String(args[0])}"`)
-
+ const operation = args[0]
const program = this.heldProgram(args[1])
+ const stream = operation === "install"
+ ? this.authManager.programManager.installStreaming(program, process.identity)
+ : operation === "uninstall"
+ ? this.authManager.programManager.uninstallStreaming(program, args[2] === true, process.identity)
+ : null
+
+ if (!stream) throw new Error(`The host does not know the stream operation "${String(operation)}"`)
- for await (const chunk of this.authManager.programManager.installStreaming(program, process.identity)) {
+ for await (const chunk of stream) {
if (!active) return
diff --git a/source/server/core/link-manager/auth-manager/program-manager/config.ts b/source/server/core/link-manager/auth-manager/program-manager/config.ts
index 22f6221..677e1e4 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/config.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/config.ts
@@ -41,6 +41,14 @@ interface Described {
// accepted here; installation canonicalizes it to agent.md.
agent?: string
+ // Optional public catalog information. These values describe a release;
+ // they do not affect whether or how the Program runs.
+ categories?: string[]
+
+ keywords?: string[]
+
+ website?: string
+
// Where it keeps what it keeps. Absent means the system decides.
storage?: string
}
@@ -56,6 +64,9 @@ export interface ServerConfig {
// Run once before the program is first started, in that directory.
installCommand?: string
+ // Run while uninstalling, before the installed files are removed.
+ uninstallCommand?: string
+
// Run to start a process, in that directory.
startCommand: string
}
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
index ccdfdb7..0d50535 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
@@ -13,10 +13,10 @@ import { dirname, isAbsolute, join } from "node:path"
import { isDeepStrictEqual } from "node:util"
import Logs, { type LogSource } from "./logs"
import { isValue, layers, type Layer, type Position, type ProgramConfig, type Size } from "./config"
-import { type PermissionName, type ProgramInstallChunk, type WallpaperLaunch } from "@phreshos/core"
+import { type PermissionName, type ProgramCommandChunk, type WallpaperLaunch } from "@phreshos/core"
import { type default as Process, type ProcessLaunch, type Stream } from "../process-manager/process"
import { type StandardShape, type WallpaperShape } from "../process-manager/process-manager"
-import Program, { type InstallOutput } from "./program"
+import Program, { type CommandOutput, type InstallOutput } from "./program"
import Entry, { type HostedEntry } from "./entry"
import Keyv from "keyv"
import { isIconSize, ProgramIcons } from "./icon"
@@ -570,14 +570,21 @@ export default class ProgramManager extends TheLink {
return await this.install(program, asker)
}
- @Connect("/uninstall-program")
- public async uninstallNamed(identity: string, everything = false, asker: string | null = null) {
+ @Connect("/uninstall-program-stream")
+ public async uninstallNamedStreaming(identity: string, everything = false, asker: string | null = null, stream: unknown) {
+
+ if (typeof stream !== "string" || !stream) throw new Error("Uninstalling needs a stream identity")
const program = this.reach(identity)
if (!program) throw new Error("The system does not know this program")
- return await this.uninstall(program, everything, asker)
+ for await (const chunk of this.uninstallStreaming(program, everything, asker)) {
+
+ await this.$outbound.publish("/uninstall-program-output", stream, chunk)
+ }
+
+ return program.identity
}
// A local project addresses the durable installation, not a handle it
@@ -585,7 +592,7 @@ export default class ProgramManager extends TheLink {
// entry while the installed declaration still exists, so this resolves
// from the installed area first and reconstructs the runtime counterpart
// only when the operation needs one.
- public async uninstallInstalled(identity: string, everything = false, asker: string | null = null) {
+ public async uninstallInstalled(identity: string, everything = false, asker: string | null = null, output: CommandOutput = () => undefined) {
return await this.change(identity, async () => {
@@ -602,10 +609,16 @@ export default class ProgramManager extends TheLink {
await this.created(entry)
}
- return await this.uninstallEntry(entry, everything, asker)
+ return await this.uninstallEntry(entry, everything, asker, output)
})
}
+ /** Uninstall an installed Program while exposing cleanup command output. */
+ public uninstallInstalledStreaming(identity: string, everything = false, asker: string | null = null) {
+
+ return this.commandStreaming(output => this.uninstallInstalled(identity, everything, asker, output))
+ }
+
@Connect("/forget-program")
public async forgetNamed(identity: string, asker: string | null = null) {
@@ -678,21 +691,33 @@ export default class ProgramManager extends TheLink {
}
/** Install while exposing command output with consumer-driven backpressure. */
- public async *installStreaming(source: Program, asker: string | null = null): AsyncGenerator<ProgramInstallChunk, Entry, void> {
+ public installStreaming(source: Program, asker: string | null = null) {
- const queue: { chunk: ProgramInstallChunk, consumed: () => void }[] = []
+ return this.commandStreaming(output => this.install(source, asker, output))
+ }
+
+ /** Uninstall a held Program while exposing cleanup command output. */
+ public uninstallStreaming(program: Program, everything = false, asker: string | null = null) {
+
+ return this.commandStreaming(output => this.uninstall(program, everything, asker, output))
+ }
+
+ /** Runs one lifecycle command while preserving output order and backpressure. */
+ private async *commandStreaming<Result>(run: (output: CommandOutput) => Promise<Result>): AsyncGenerator<ProgramCommandChunk, Result, void> {
+
+ const queue: { chunk: ProgramCommandChunk, consumed: () => void }[] = []
let wake: (() => void) | null = null
let settled = false
- let installed: Entry | undefined
+ let result: { value: Result } | undefined
let failure: unknown
let detached = false
- const operation = this.install(source, asker, chunk => {
+ const operation = run(chunk => {
if (detached) return
@@ -704,9 +729,9 @@ export default class ProgramManager extends TheLink {
wake = null
})
- }).then(entry => {
+ }).then(value => {
- installed = entry
+ result = { value }
}, error => {
failure = error
@@ -741,7 +766,7 @@ export default class ProgramManager extends TheLink {
if (failure) throw failure
- return installed!
+ return result!.value
}
finally {
@@ -874,7 +899,7 @@ export default class ProgramManager extends TheLink {
// files leave. Processes and open storage handles remain alive. With
// it, everything the system owns for this program leaves: processes,
// files, storage, and finally the runtime registry entry.
- public async uninstall(program: Program, everything = false, asker: string | null = null) {
+ public async uninstall(program: Program, everything = false, asker: string | null = null, output: CommandOutput = () => undefined) {
return await this.change(program.identity, async () => {
@@ -882,11 +907,11 @@ export default class ProgramManager extends TheLink {
const entry = this.find(program.identity)
- return await this.uninstallEntry(entry, everything, asker)
+ return await this.uninstallEntry(entry, everything, asker, output)
})
}
- private async uninstallEntry(entry: Entry, everything: boolean, asker: string | null) {
+ private async uninstallEntry(entry: Entry, everything: boolean, asker: string | null, output: CommandOutput) {
if (everything) {
@@ -895,6 +920,8 @@ export default class ProgramManager extends TheLink {
await this.release(entry.identity)
}
+ await entry.program.uninstallServer(output)
+
const home = this.fileManager.join(entry.identity)
if (everything) rmSync(home, { recursive: true, force: true })
@@ -1370,7 +1397,7 @@ export interface InstallSourceOptions {
export type InstallSourceStage =
- | { stage: "output", chunk: ProgramInstallChunk }
+ | { stage: "output", chunk: ProgramCommandChunk }
| { stage: "installed", entry: Entry, replaced: boolean }
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program.ts b/source/server/core/link-manager/auth-manager/program-manager/program.ts
index 52e4d36..0e886c5 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/program.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/program.ts
@@ -4,7 +4,7 @@ import { dirname, isAbsolute, resolve } from "node:path"
import { spawn } from "node:child_process"
import { randomUUID } from "node:crypto"
import { validateIcon } from "./icon"
-import type { ProgramInstallChunk } from "@phreshos/core"
+import type { ProgramCommandChunk } from "@phreshos/core"
/**
* A program: a description, and the things it names.
@@ -274,6 +274,18 @@ export default class Program {
await execute(command, this.serverPath!, output)
}
+
+ // Cleaning up externally installed resources happens while the installed
+ // Server directory still exists, because that directory is the command's
+ // declared working environment.
+ public async uninstallServer(output: CommandOutput = () => undefined) {
+
+ const command = this.config.server?.uninstallCommand
+
+ if (!command) return
+
+ await execute(command, this.serverPath!, output)
+ }
}
function read(path: string): [ProgramConfig, string] {
@@ -299,13 +311,31 @@ function coherent(config: ProgramConfig) {
if (!config.server && !config.client) throw new Error("A program must have a server half, a client half, or both")
- for (const field of ["name", "version", "description", "icon", "agent", "storage"] as const) {
+ for (const field of ["name", "version", "description", "icon", "agent", "storage", "website"] as const) {
if (config[field] !== undefined && typeof config[field] !== "string") throw new Error(`A program's ${field} must be text`)
}
if (config.agent !== undefined && config.agent.trim().length === 0) throw new Error("A program's agent documentation must be a non-empty path")
+ if (config.website !== undefined) {
+
+ try { new URL(config.website) }
+
+ catch { throw new Error("A program's website must be a valid URL") }
+ }
+
+ for (const [field, maximum] of [["categories", 20], ["keywords", 50]] as const) {
+
+ const values = config[field]
+
+ if (values === undefined) continue
+
+ if (!Array.isArray(values) || values.length > maximum || values.some(value => typeof value !== "string" || value.trim().length === 0 || value.trim().length > 50)) {
+ throw new Error(`A program's ${field} must contain at most ${maximum} non-empty values of at most 50 characters`)
+ }
+ }
+
for (const half of ["server", "client"] as const) {
const declared = config[half]
@@ -333,6 +363,8 @@ function coherent(config: ProgramConfig) {
if (config.server?.installCommand !== undefined && typeof config.server.installCommand !== "string") throw new Error("A server half's install command must be text")
+ if (config.server?.uninstallCommand !== undefined && typeof config.server.uninstallCommand !== "string") throw new Error("A server half's uninstall command must be text")
+
if (config.client?.title !== undefined && typeof config.client.title !== "string") throw new Error("A client half's title must be text")
if (config.client?.minimize !== undefined && typeof config.client.minimize !== "boolean") throw new Error("A client half's minimize default must be true or false")
@@ -371,9 +403,11 @@ function file(path: string) {
}
-export type InstallOutput = (chunk: ProgramInstallChunk) => void | Promise<void>
+export type CommandOutput = (chunk: ProgramCommandChunk) => void | Promise<void>
+
+export type InstallOutput = CommandOutput
-function execute(command: string, cwd: string, output: InstallOutput) {
+function execute(command: string, cwd: string, output: CommandOutput) {
return new Promise<void>(function (settle, refuse) {
@@ -383,7 +417,7 @@ function execute(command: string, cwd: string, output: InstallOutput) {
let failed = false
- const relay = function (stream: NodeJS.ReadableStream, name: ProgramInstallChunk["stream"]) {
+ const relay = function (stream: NodeJS.ReadableStream, name: ProgramCommandChunk["stream"]) {
stream.on("data", chunk => {
diff --git a/source/server/view/intake.ts b/source/server/view/intake.ts
index 391bd97..ffbcb46 100644
--- a/source/server/view/intake.ts
+++ b/source/server/view/intake.ts
@@ -211,7 +211,10 @@ async function answer(application: Application, attached: Set<string>, say: (eve
if (asked.everything !== undefined && typeof asked.everything !== "boolean") throw new Error("Uninstalling everything must be true or false")
- await programManager.uninstallInstalled(asked.identity, asked.everything === true)
+ for await (const chunk of programManager.uninstallInstalledStreaming(asked.identity, asked.everything === true)) {
+
+ say({ event: "output", ...chunk })
+ }
say({ event: "uninstalled", identity: asked.identity, everything: asked.everything === true })