Skip to content

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

Release system 0.1.67 with synchronized SDK contracts

zohayrslileh3c285d14e8cc
diff --git a/bun.lock b/bun.lock
index 8fcb44a..c104545 100644
--- a/bun.lock
+++ b/bun.lock
@@ -7,8 +7,8 @@
"dependencies": {
"@fontsource/roboto": "^5.3.0",
"@hono/node-server": "^2.1.1",
- "@phreshos/core": "^0.1.45",
- "@phreshos/react-ui": "^0.1.19",
+ "@phreshos/core": "^0.1.47",
+ "@phreshos/react-ui": "^0.1.20",
"@the-link/core": "^0.3.0",
"@the-link/http": "^0.1.1",
"@the-link/ipc": "^0.2.1",
@@ -235,9 +235,9 @@
"@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-nuhZIOLuI6TFQ32I/WnUx+SCPY7SdSKwgnFHydAuoS1+Z4BRcaP+RRJmGzl9lw+0OFF7UmaESf7KQRXaNLHypg=="],
- "@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-u/P6GJynoC8IaOjIHGCzsA1a2Mhwkg5qstuAKN70PsiHQ/ioE2inOUpEuL2JPhmvjcQslZnbLpZhfwMYIUW0+A=="],
+ "@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-/0TrNk+7k8kHpMvnhzP1IS+tbdEILtCaE2gyewLIXl1oLfIzGeiBCTBqJhQ4E1i/iAgftlEYv9BQSwrn2P3PrA=="],
- "@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "@phreshos/core": "^0.1.43", "colorjs.io": "^0.7.1", "motion": "^13.2.0", "react-aria-components": "^1.20.0" }, "peerDependencies": { "react": "^19.2.0", "react-dom": "^19.2.0" } }, "sha512-F4xiDGvOrgEomSSy3HwieFOI3eiyhDQAbJeQNWHVXXVekT1lUonr86z0crEQigXEIqdFWBQg+GKf9mkcjlYKOw=="],
+ "@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "@phreshos/core": "^0.1.47", "colorjs.io": "^0.7.1", "motion": "^13.2.0", "react-aria-components": "^1.20.0" }, "peerDependencies": { "react": "^19.2.0", "react-dom": "^19.2.0" } }, "sha512-jbXaXF4wac+a6e6iJxJrNMseG84FW4kKBsBKCbfQ3DADrUbJ+jc17cAM/zJBo1/fVco3rzZ5PEHXFmD7/rVntw=="],
"@react-types/shared": ["@react-types/[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" } }, "sha512-AzsuD9OfxTOZMMvTRhlN3oHBwOmFN7tDh27LzqmHt4+uOgPhJT7ZM7/kVs/8/o0WxayMUIk3hBmCFRHv1FUoag=="],
@@ -559,8 +559,6 @@
"yallist": ["[email protected]", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
- "@phreshos/react-ui/@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-0Qo4SlNg9fi2xfpDMbMucHQrDhzE8hhzOy7n5rQPjpj4UIWPUU5ZuEGEON6bfQM6nKJ4ogNJF7KFp4RhMxf5PA=="],
-
"@tailwindcss/node/lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="],
diff --git a/package.json b/package.json
index b2b8a9e..a7d42d8 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "phreshos",
"displayName": "PhreshOS",
- "version": "0.1.66",
+ "version": "0.1.67",
"description": "The PhreshOS server, desktop, and authoritative system runtime.",
"type": "module",
"private": true,
@@ -36,8 +36,8 @@
"dependencies": {
"@fontsource/roboto": "^5.3.0",
"@hono/node-server": "^2.1.1",
- "@phreshos/core": "^0.1.45",
- "@phreshos/react-ui": "^0.1.19",
+ "@phreshos/core": "^0.1.47",
+ "@phreshos/react-ui": "^0.1.20",
"@the-link/core": "^0.3.0",
"@the-link/http": "^0.1.1",
"@the-link/ipc": "^0.2.1",
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 b50ab52..733cd25 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
@@ -1,5 +1,5 @@
import { ProgramRecord } from "@server/core/link-manager/auth-manager/program-manager/entry"
-import { type Launch } from "@phreshos/core"
+import { type Launch, type ProgramInstallOptions, type ProgramUninstallOptions } from "@phreshos/core"
import ProgramManager from "./program-manager"
/**
@@ -80,16 +80,14 @@ export default class Program {
await this.createProcess(launch ?? {})
}
- public install(asker: string) {
+ public install(options: ProgramInstallOptions = {}, asker = "") {
- return this.programManager.command(this.address, "install", undefined, asker)
+ return this.programManager.command(this.address, "install", options, asker)
}
- // False removes only installed program files. True removes everything
- // owned by the system and forgets the runtime Program.
- public uninstall(everything = false, asker = "") {
+ public uninstall(options: ProgramUninstallOptions = {}, asker = "") {
- return this.programManager.command(this.address, "uninstall", everything, asker)
+ return this.programManager.command(this.address, "uninstall", options, asker)
}
public async forget(asker: string) {
diff --git a/source/client/view/components/desktop-host/announcements.ts b/source/client/view/components/desktop-host/announcements.ts
index 9b28802..e7eee0d 100644
--- a/source/client/view/components/desktop-host/announcements.ts
+++ b/source/client/view/components/desktop-host/announcements.ts
@@ -71,22 +71,22 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
}, [authManager, post]))
- const programEvent = useCallback((event: "create" | "install" | "uninstall" | "forget", entry: ProgramRecord | null, everything?: boolean) => {
+ const programEvent = useCallback((event: "create" | "install" | "uninstall" | "forget", entry: ProgramRecord | null, purge?: boolean) => {
if (!entry) return
const record = sdkProgram(entry)
- post(entry.identity, "host-program", event, entry.identity, record, everything === true)
+ post(entry.identity, "host-program", event, entry.identity, record, purge === true)
- if (event === "uninstall") post(entry.identity, "program-host", event, entry.reference, everything === true)
+ if (event === "uninstall") post(entry.identity, "program-host", event, entry.reference, purge === true)
if (event === "forget") post(entry.identity, "program-host", event, entry.reference)
}, [post])
programs.useSubscribe("/create", useCallback((entry: ProgramRecord | null) => programEvent("create", entry), [programEvent]))
programs.useSubscribe("/install", useCallback((entry: ProgramRecord | null) => programEvent("install", entry), [programEvent]))
- programs.useSubscribe("/uninstall", useCallback((entry: ProgramRecord | null, everything: boolean) => programEvent("uninstall", entry, everything), [programEvent]))
+ programs.useSubscribe("/uninstall", useCallback((entry: ProgramRecord | null, purge: boolean) => programEvent("uninstall", entry, purge), [programEvent]))
programs.useSubscribe("/forgotten", useCallback((entry: ProgramRecord | null) => programEvent("forget", entry), [programEvent]))
}
diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.ts
index e8d50b7..87dd50b 100644
--- a/source/client/view/components/desktop-host/client-process-boundary.ts
+++ b/source/client/view/components/desktop-host/client-process-boundary.ts
@@ -4,7 +4,7 @@ import host, { TransferredAnswer } 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 { isServiceKey, type DesktopViewportSnapshot, type ServiceKey, type ShellOptions } from "@phreshos/core"
+import { isServiceKey, parseProgramInstallOptions, type DesktopViewportSnapshot, type ServiceKey, type ShellOptions } from "@phreshos/core"
import { type LocalWindowHost } from "./local-window"
import messagepack from "@the-link/messagepack"
import { sdkProcess, type SdkProcessSource } from "./sdk-records"
@@ -667,7 +667,14 @@ export default class ClientProcessBoundary extends TheLink {
await this.systemAccess.program(program)
- const value = args[0] === "run" ? await this.systemAccess.launch(args[2]) : args[2]
+ 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 : {
+ ...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]()
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 65a6ef8..12435f8 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
@@ -19,6 +19,8 @@ import OutsideQuestions from "./outside-questions"
import {
isServiceKey,
parsePermissionName,
+ parseProgramInstallOptions,
+ parseProgramUninstallOptions,
type ClientLaunch,
type Launch,
type Permission,
@@ -32,7 +34,7 @@ import {
type WindowLayer,
type WindowState
} from "@phreshos/core"
-import type { ServerRuntime } from "@server/core/server-runtime"
+import type { ServerRuntime, ServerRuntimeFactory } from "@server/core/server-runtime"
import { permissionCatalog } from "@server/core/permissions"
/**
@@ -907,7 +909,21 @@ export default class ProcessManager extends TheLink {
return new Window(shown, shape.position, shape.size, ++this.highest, shape.minimize, shape.maximize)
}
- /** Checks and claims the wallpaper role in one synchronous activation. */
+ private wallpaperChanges: Promise<unknown> = Promise.resolve()
+
+ private serializeClientLayer<Result>(layer: string | undefined, work: () => Promise<Result>): Promise<Result> {
+ if (layer !== "wallpaper") return work()
+ const next = this.wallpaperChanges.catch(() => undefined).then(work)
+ this.wallpaperChanges = next.catch(() => undefined)
+ return next
+ }
+
+ private async replaceWallpaper() {
+ const occupied = [...this.processes.values()].filter(process => process.client?.window.layer === "wallpaper")
+ for (const process of occupied) await this.exitProcess(process.identity, "complete")
+ }
+
+ /** Claims the role after serialized replacement has released its previous owner. */
private activateClient(process: Process, window: Window, service: boolean) {
if (window.layer === "wallpaper" && [...this.processes.values()].some(
current => current.client?.window.layer === "wallpaper"
@@ -916,22 +932,26 @@ export default class ProcessManager extends TheLink {
process.startClient(window, service)
}
- public async register(identity: string, name: string | null, program: Program, options: Options, launch: ProcessLaunch, runtime: ServerRuntime | null, client: boolean, shape: Shape | null, parent: Process | null, registration?: ProcessRegistration) {
+ public async register(identity: string, name: string | null, program: Program, options: Options, launch: ProcessLaunch, runtime: ServerRuntimeFactory<Program> | null, client: boolean, shape: Shape | null, parent: Process | null, registration?: ProcessRegistration) {
- if (this.processes.has(identity)) {
+ return await this.serializeClientLayer(client ? shape?.layer : undefined, () =>
+ this.registerProcess(identity, name, program, options, launch, runtime, client, shape, parent, registration))
+ }
- runtime?.stop()
+ private async registerProcess(identity: string, name: string | null, program: Program, options: Options, launch: ProcessLaunch, createRuntime: ServerRuntimeFactory<Program> | null, client: boolean, shape: Shape | null, parent: Process | null, registration?: ProcessRegistration) {
+
+ if (this.processes.has(identity)) {
throw new Error("The host already knows this process identity")
}
if (name !== null && [...this.processes.values()].some(process => process.program === program && process.name === name)) {
- runtime?.stop()
-
throw new Error("This program already has a process with that name")
}
+ if (client && shape?.layer === "wallpaper") await this.replaceWallpaper()
+
// Who had focus before this one opened, in the layer it is
// opening into. A window is born on top of its own layer and
// takes focus from whoever held it there; the other layers
@@ -965,10 +985,14 @@ export default class ProcessManager extends TheLink {
process.onExit((code, signal) => { this.remove(identity, code, signal).catch(() => undefined) })
+ let runtime: ServerRuntime | null = null
+
try {
registration?.prepare?.(process)
+ runtime = createRuntime?.(program) ?? null
+
// Initial activation is one endpoint transition too. A server that
// exits immediately is queued behind it, preserving the only coherent
// order: Process creation, endpoint start, endpoint stop, Process exit.
@@ -1183,6 +1207,15 @@ export default class ProcessManager extends TheLink {
const process = this.find(identity)
+ const layer = launch.layer ?? process.program.client?.layer
+
+ return await this.serializeClientLayer(layer, () => this.startClientInLayer(identity, launch))
+ }
+
+ private async startClientInLayer(identity: string, launch: ClientLaunch) {
+
+ const process = this.find(identity)
+
await this.transition(process, async () => {
if (!process.program.client) throw new Error("This program declared no client half")
@@ -1197,6 +1230,8 @@ export default class ProcessManager extends TheLink {
const before = this.front(window.layer)
+ if (window.layer === "wallpaper") await this.replaceWallpaper()
+
this.activateClient(process, window, launch.service ?? process.program.client.service)
try {
@@ -2382,9 +2417,9 @@ export default class ProcessManager extends TheLink {
}
const stream = operation === "install"
- ? this.system.installProgram(program, process.identity)
+ ? this.system.installProgram(program, parseProgramInstallOptions(args[2] ?? {}), process.identity)
: operation === "uninstall"
- ? this.system.uninstallProgram(program, args[2] === true, process.identity)
+ ? this.system.uninstallProgram(program, parseProgramUninstallOptions(args[2] ?? {}), process.identity)
: null
if (!stream) throw new Error(`The host does not know the stream operation "${String(operation)}"`)
diff --git a/source/server/core/link-manager/auth-manager/program-manager/logs.ts b/source/server/core/link-manager/auth-manager/program-manager/logs.ts
index db8c7d3..1a1871d 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/logs.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/logs.ts
@@ -18,7 +18,7 @@ import { dirname } from "node:path"
* It lives at `storage/logs.sqlite`, beside the `store.sqlite` this
* copies: a thing the system manages, that the program has no word for,
* that survives an update because everything under `storage` does, and
- * that goes with `uninstall(true)`. Nothing new had to be said anywhere
+ * that goes with `uninstall({ purge: true })`. Nothing new had to be said anywhere
* for any of that.
*
* **The system is the only writer.** Every process of every program
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 9de9385..d039618 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
@@ -11,7 +11,7 @@ import { dirname, isAbsolute, join } from "node:path"
import { isDeepStrictEqual } from "node:util"
import Logs, { type LogSource } from "./logs"
import { isValue, layers } from "./config"
-import { parseLaunch, parseProgramDefinition, type ClientLaunch, type Launch, type ProgramCommandChunk, type ProgramDefinition } from "@phreshos/core"
+import { parseLaunch, parseProgramDefinition, parseProgramInstallOptions, parseProgramUninstallOptions, type ProgramInstallOptions, type ProgramUninstallOptions, type ClientLaunch, type Launch, type ProgramCommandChunk, type ProgramDefinition } from "@phreshos/core"
import { type default as Process, type ProcessLaunch, type Stream } from "../process-manager/process"
import { type StandardShape } from "../process-manager/process-manager"
import Program, { type CommandOutput, type InstallOutput } from "./program"
@@ -542,7 +542,7 @@ export default class ProgramManager extends TheLink {
}
// What this program has said. Its own file under `storage`, so it
- // survives an update and goes with everything.
+ // survives an update and is removed by purge.
public logsOf(program: Program) {
const already = this.said.get(program.identity)
@@ -911,9 +911,9 @@ export default class ProgramManager extends TheLink {
}
const command = operation === "install"
- ? this.installStreaming(program, asker)
+ ? this.installStreaming(program, parseProgramInstallOptions(value ?? {}), asker)
: operation === "uninstall"
- ? this.uninstallStreaming(program, value === true, asker)
+ ? this.uninstallStreaming(program, parseProgramUninstallOptions(value ?? {}), asker)
: null
if (!command) throw new Error(`The Program command API does not know "${operation}"`)
@@ -938,15 +938,15 @@ export default class ProgramManager extends TheLink {
}
/** Install while exposing command output with consumer-driven backpressure. */
- public installStreaming(source: Program, asker: string | null = null) {
+ public installStreaming(source: Program, options: ProgramInstallOptions = {}, asker: string | null = null) {
- return this.commandStreaming(output => this.install(source, asker, output))
+ return this.commandStreaming(output => this.install(source, options, asker, output))
}
/** Uninstall a held Program while exposing cleanup command output. */
- public uninstallStreaming(program: Program, everything = false, asker: string | null = null) {
+ public uninstallStreaming(program: Program, options: ProgramUninstallOptions = {}, asker: string | null = null) {
- return this.commandStreaming(output => this.uninstall(program, everything, asker, output))
+ return this.commandStreaming(output => this.uninstall(program, options, asker, output))
}
/** Runs one lifecycle command while preserving output order and backpressure. */
@@ -1024,7 +1024,9 @@ export default class ProgramManager extends TheLink {
}
}
- public async install(source: Program, asker: string | null = null, output: InstallOutput = () => undefined) {
+ public async install(source: Program, options: ProgramInstallOptions = {}, asker: string | null = null, output: InstallOutput = () => undefined) {
+
+ const decision = parseProgramInstallOptions(options)
return await this.change(source.identity, async () => {
@@ -1050,6 +1052,8 @@ export default class ProgramManager extends TheLink {
let restoreSettings: (() => void) | undefined
+ let purgedStorage = false
+
try {
copyProgram(source, staged)
@@ -1064,13 +1068,8 @@ export default class ProgramManager extends TheLink {
await stagedProgram.validate()
this.declaredLaunch(stagedProgram, "startup")
this.declaredLaunch(stagedProgram, "launch")
-
- // A process may have retained an absolute server,
- // client, or storage path. Its ending is part of the
- // install operation, not advice for the caller.
- if (this.programs.has(source.identity)) await this.authManager.processManager.exitAll(source.identity, asker)
-
- await this.release(source.identity)
+ const requestedLaunch = decision.launch === true ? {} : decision.launch
+ if (requestedLaunch !== undefined) this.resolveLaunch(stagedProgram, requestedLaunch)
swapping = true
@@ -1091,6 +1090,15 @@ export default class ProgramManager extends TheLink {
let entry = this.programs.get(source.identity)
+ // Active callers can consume installation output until activation.
+ if (entry) await this.authManager.processManager.exitAll(source.identity, asker)
+ await this.release(source.identity)
+
+ if (decision.purge && existsSync(installed.storagePath)) {
+ renameSync(installed.storagePath, join(backup, "storage"))
+ purgedStorage = true
+ }
+
if (entry) {
restoreSettings = this.applyDeclaration(installed)
@@ -1122,6 +1130,10 @@ export default class ProgramManager extends TheLink {
// yesterday's list.
await this.$outbound.publish("/install", entry.record())
+ if (requestedLaunch !== undefined) {
+ await this.start(entry.program, requestedLaunch, undefined, null, true)
+ }
+
try {
const launch = await this.startup(entry.program, "get")
if (launch) await this.start(entry.program, launch, undefined, null, true)
@@ -1135,15 +1147,16 @@ export default class ProgramManager extends TheLink {
catch (exception) {
- // Restore the prior program files and declaration settings after
- // any failure before commit. Other storage
- // never enters the transaction and is neither copied nor moved.
+ // Restore the prior files, declaration settings, and any storage
+ // set aside for purge after a failure before commit.
if (swapping && !committed) {
restoreSettings?.()
for (const what of installedParts) rmSync(join(home, what), { recursive: true, force: true })
+ if (purgedStorage) rmSync(join(home, "storage"), { recursive: true, force: true })
+
for (const what of readdirSync(backup)) renameSync(join(backup, what), join(home, what))
if (!already && !readdirSync(home).length) rmSync(home, { recursive: true, force: true })
@@ -1161,11 +1174,10 @@ export default class ProgramManager extends TheLink {
})
}
- // Without `everything`, only the installed description and program
- // 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, output: CommandOutput = () => undefined) {
+ // Purge also ends Processes and removes storage and the runtime entry.
+ public async uninstall(program: Program, options: ProgramUninstallOptions = {}, asker: string | null = null, output: CommandOutput = () => undefined) {
+
+ const { purge = false } = parseProgramUninstallOptions(options)
return await this.change(program.identity, async () => {
@@ -1173,13 +1185,13 @@ export default class ProgramManager extends TheLink {
const entry = this.find(program.identity)
- return await this.uninstallEntry(entry, everything, asker, output)
+ return await this.uninstallEntry(entry, purge, asker, output)
})
}
- private async uninstallEntry(entry: Entry, everything: boolean, asker: string | null, output: CommandOutput) {
+ private async uninstallEntry(entry: Entry, purge: boolean, asker: string | null, output: CommandOutput) {
- if (everything) {
+ if (purge) {
await this.authManager.processManager.exitAll(entry.identity, asker)
@@ -1190,7 +1202,7 @@ export default class ProgramManager extends TheLink {
const home = this.fileManager.join(entry.identity)
- if (everything) rmSync(home, { recursive: true, force: true })
+ if (purge) rmSync(home, { recursive: true, force: true })
else {
@@ -1201,13 +1213,13 @@ export default class ProgramManager extends TheLink {
entry.installed = false
- await this.authManager.processManager.announceHost("program", "uninstall", entry.identity, entry, everything)
+ await this.authManager.processManager.announceHost("program", "uninstall", entry.identity, entry, purge)
- await this.authManager.processManager.announceSubject("program", "uninstall", entry.program.reference, everything)
+ await this.authManager.processManager.announceSubject("program", "uninstall", entry.program.reference, purge)
- await this.$outbound.publish("/uninstall", entry.record(), everything)
+ await this.$outbound.publish("/uninstall", entry.record(), purge)
- if (everything) await this.forgetEntry(entry)
+ if (purge) await this.forgetEntry(entry)
return entry.identity
}
@@ -1318,7 +1330,7 @@ export default class ProgramManager extends TheLink {
const existing = [...this.authManager.processManager.processes.values()].find(process => process.program === program && process.name === launch.name)
- if (existing) {
+ if (existing && !launch.replace) {
if (!isDeepStrictEqual(existing.launch, resolved.intent)) throw new Error(`The process "${launch.name}" already exists with a different launch`)
@@ -1340,7 +1352,7 @@ export default class ProgramManager extends TheLink {
const launch = parseLaunch(value)
- const options = Object.fromEntries(Object.entries({ ...program.config.options, ...launch.options }).sort(([left], [right]) => left.localeCompare(right)))
+ const options = Object.fromEntries(Object.entries(launch.options ?? {}).sort(([left], [right]) => left.localeCompare(right)))
const askedServer = typeof launch.server === "object" ? launch.server : {}
const askedClient = typeof launch.client === "object" ? launch.client : {}
@@ -1389,7 +1401,7 @@ export default class ProgramManager extends TheLink {
if (!transitionOwnsIdentity && this.changing.has(program.identity)) throw new Error("This program is changing and cannot create a process")
- // A retained Program survives uninstall(false), but its declared
+ // A retained Program survives uninstall(), but its declared
// files do not. Refuse before a process identity or window is
// allocated, so a failed launch never briefly exists.
await program.validate()
@@ -1400,16 +1412,20 @@ export default class ProgramManager extends TheLink {
const shape = client ? resolved.shape : null
- // Recheck the program-local name immediately before registration,
- // then create and register without yielding so concurrent launches
- // cannot both claim it.
- if (launch.name !== undefined && [...this.authManager.processManager.processes.values()].some(process => process.program === program && process.name === launch.name)) throw new Error("This program already has a process with that name")
+ // Program-local creation is serialized. Release a requested name before
+ // allocating its replacement, while retaining ownership of that queue.
+ if (launch.name !== undefined) {
+ const existing = [...this.authManager.processManager.processes.values()].find(process => process.program === program && process.name === launch.name)
+ if (existing) {
+ if (!launch.replace) throw new Error("This program already has a process with that name")
+ await this.authManager.processManager.exit(existing.identity)
+ }
+ }
// Capacity belongs to the Program being executed, not to whichever
// Process requested the launch. This is the final gate before identity
- // allocation, endpoint spawning, and synchronous registration; no
- // concurrent launch can pass it without the preceding one entering the
- // authoritative Process map first.
+ // allocation and registration. The Program-local queue prevents another
+ // launch from passing before this one enters the authoritative map.
let active = 0
for (const process of this.authManager.processManager.processes.values()) {
@@ -1430,7 +1446,7 @@ export default class ProgramManager extends TheLink {
// server incarnation attaches to the same Process-level listeners.
const logs = this.logsOf(program)
- const runtime = server ? this.serverRuntime(program) : null
+ const runtime = server ? (owner: Program) => this.serverRuntime(owner) : null
// Lifecycle consumers are attached before either initial endpoint is
// activated, so even a server command that exits immediately has a
diff --git a/source/server/core/system.ts b/source/server/core/system.ts
index 238b8c4..f298913 100644
--- a/source/server/core/system.ts
+++ b/source/server/core/system.ts
@@ -5,6 +5,8 @@ import type Process from "./link-manager/auth-manager/process-manager/process"
import type {
ClientLaunch,
Launch,
+ ProgramInstallOptions,
+ ProgramUninstallOptions,
PermissionInput,
PermissionName,
Position,
@@ -390,14 +392,14 @@ export default class System {
return this.programManager.forget(program, asker)
}
- public installProgram(program: Program, asker: string | null = null) {
+ public installProgram(program: Program, options: ProgramInstallOptions = {}, asker: string | null = null) {
- return this.programManager.installStreaming(program, asker)
+ return this.programManager.installStreaming(program, options, asker)
}
- public uninstallProgram(program: Program, everything = false, asker: string | null = null) {
+ public uninstallProgram(program: Program, options: ProgramUninstallOptions = {}, asker: string | null = null) {
- return this.programManager.uninstallStreaming(program, everything, asker)
+ return this.programManager.uninstallStreaming(program, options, asker)
}
public programArea(program: Program, area: Area, operation: string, args: unknown[]) {
diff --git a/source/server/view/http/program/program.ts b/source/server/view/http/program/program.ts
index e9534fb..b24d150 100644
--- a/source/server/view/http/program/program.ts
+++ b/source/server/view/http/program/program.ts
@@ -69,7 +69,7 @@ export default function (application: Application) {
const root = found.clientPath
- // A retained Program may outlive files removed by uninstall(false).
+ // A retained Program may outlive files removed by uninstall().
if (!root || !existsSync(root)) return context.text("The program has no assets", 404)
return await serveStatic({
diff --git a/tests/process-find-or-create.test.ts b/tests/process-find-or-create.test.ts
index 4dd9c94..eb026f4 100644
--- a/tests/process-find-or-create.test.ts
+++ b/tests/process-find-or-create.test.ts
@@ -20,7 +20,7 @@ test("process find or create contract", async () => {
const processes = new Map<string, FixtureProcess>()
const program = {
identity: "example",
- config: { options: { language: "en", document: "default.txt" }, launch: { options: { document: "icon.txt" } } },
+ config: { launch: { options: { document: "icon.txt" } } },
reference: "example-reference",
server: { start: true },
client: {
@@ -91,9 +91,8 @@ test("process find or create contract", async () => {
)
const omitted = fixture.resolveLaunch(program, { name: "defaults" }).intent
- assert.deepEqual(fixture.resolveLaunch(program, {}).options, { document: "default.txt", language: "en" })
- assert.deepEqual(fixture.resolveLaunch(program, { options: { document: "chosen.txt", extra: "" } }).options, { document: "chosen.txt", extra: "", language: "en" })
- assert.deepEqual(program.config.options, { document: "default.txt", language: "en" })
+ assert.deepEqual(fixture.resolveLaunch(program, {}).options, {})
+ assert.deepEqual(fixture.resolveLaunch(program, { options: { document: "chosen.txt", extra: "" } }).options, { document: "chosen.txt", extra: "" })
processes.set("unrelated", { identity: "unrelated", name: null, program, launch: null })
const explicit = fixture.resolveLaunch(program, {
name: "defaults",
diff --git a/tests/process-lifecycle.test.ts b/tests/process-lifecycle.test.ts
index a844250..934c83c 100644
--- a/tests/process-lifecycle.test.ts
+++ b/tests/process-lifecycle.test.ts
@@ -77,8 +77,8 @@ test("process lifecycle contract", async () => {
// unattached runtime behind in the registry.
{
const manager = processManager()
- let stops = 0
- const runtime = { stop() { stops++ } } as unknown as ServerRuntime
+ let starts = 0
+ const runtime = () => { starts++; return {} as ServerRuntime }
await assert.rejects(manager.register(
"failed-registration",
@@ -94,7 +94,7 @@ test("process lifecycle contract", async () => {
), /configuration failed/)
assert.equal(manager.processes.has("failed-registration"), false)
- assert.equal(stops, 1)
+ assert.equal(starts, 0)
}
// Failure after an endpoint has been activated still retracts the partially
diff --git a/tests/process-replacement.test.ts b/tests/process-replacement.test.ts
new file mode 100644
index 0000000..5bf8808
--- /dev/null
+++ b/tests/process-replacement.test.ts
@@ -0,0 +1,40 @@
+import { expect, test, vi } from "vitest"
+import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import type Program from "@server/core/link-manager/auth-manager/program-manager/program"
+
+test("named replacement is Program-scoped, validated before exit, and serialized", async () => {
+ const program = {
+ identity: "example", reference: "reference", config: {}, title: "Example",
+ server: null, client: { start: true }, async validate() {}
+ } as unknown as Program
+ const other = { ...program, identity: "other", reference: "other-reference" } as unknown as Program
+ const processes = new Map<string, { identity: string; name: string | null; program: Program; launch: unknown }>()
+ processes.set("old", { identity: "old", name: "editor", program, launch: {} })
+ processes.set("unrelated", { identity: "unrelated", name: "editor", program: other, launch: {} })
+ const events: string[] = []
+ const exit = vi.fn(async (identity: string) => { await Promise.resolve(); events.push(`exit:${identity}`); processes.delete(identity) })
+ const register = vi.fn(async (identity: string, name: string | null, owner: Program, _options: unknown, launch: unknown) => {
+ events.push(`create:${identity}`)
+ processes.set(identity, { identity, name, program: owner, launch })
+ })
+ const manager = Object.assign(Object.create(ProgramManager.prototype), {
+ authManager: { processManager: { processes, exit, register } },
+ creating: new Map(), changing: new Map(),
+ reach: (identity: string) => identity === program.identity ? program : null,
+ logsOf: () => ({}),
+ $outbound: { async publish() {} }
+ }) as ProgramManager
+
+ await expect(manager.createProcess(program, { name: "editor" })).rejects.toThrow("already has a process")
+ await expect(manager.createProcess(program, { name: "editor", replace: true, server: true })).rejects.toThrow("no server")
+ expect(exit).not.toHaveBeenCalled()
+ const [first, second] = await Promise.all([
+ manager.createProcess(program, { name: "editor", replace: true }),
+ manager.createProcess(program, { name: "editor", replace: true })
+ ])
+ expect(events).toEqual(["exit:old", `create:${first}`, `exit:${first}`, `create:${second}`])
+ expect([...processes.keys()]).toEqual(["unrelated", second])
+ const third = await manager.findOrCreateProcess(program, { name: "editor", replace: true })
+ expect(processes.has(second)).toBe(false)
+ expect(processes.has(third)).toBe(true)
+})
diff --git a/tests/program-creation.test.ts b/tests/program-creation.test.ts
index 4c4496f..4ea8dc0 100644
--- a/tests/program-creation.test.ts
+++ b/tests/program-creation.test.ts
@@ -99,7 +99,7 @@ test("boot reconstruction preserves all stored settings and launches the saved s
test("creation applies explicit launch decisions and preserves omitted ones", async context => {
const { manager, definition } = fixture(context)
const intent = { client: { layer: "over" as const }, options: { document: "icon.txt" } }
- let program = await manager.create({ ...definition(), options: { language: "en" }, launch: intent, startup: intent })
+ let program = await manager.create({ ...definition(), launch: intent, startup: intent })
expect(await manager.launch(program, "get")).toEqual(intent)
expect(await manager.startup(program, "get")).toEqual(intent)
expect(manager.authManager.processManager.processes.size).toBe(0)
diff --git a/tests/program-installation-lifecycle.test.ts b/tests/program-installation-lifecycle.test.ts
new file mode 100644
index 0000000..1d35084
--- /dev/null
+++ b/tests/program-installation-lifecycle.test.ts
@@ -0,0 +1,110 @@
+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+import { TheLink } from "@the-link/core"
+import { expect, test, vi, type TestContext } from "vitest"
+import type { Launch } from "@phreshos/core"
+import FileManager from "@libs/file-manager"
+import type AuthManager from "@server/core/link-manager/auth-manager/auth-manager"
+import Program from "@server/core/link-manager/auth-manager/program-manager/program"
+import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+
+function fixture(context: TestContext) {
+ const directory = mkdtempSync(join(tmpdir(), "phresh-install-lifecycle-"))
+ context.onTestFinished(() => { vi.restoreAllMocks(); rmSync(directory, { recursive: true, force: true }) })
+ const server = join(directory, "source", "server")
+ mkdirSync(server, { recursive: true })
+ const exitAll = vi.fn()
+ const auth = Object.assign(new TheLink(), {
+ linkManager: { application: { storage: new FileManager(directory, "system"), defaultProgramIcon: "" } },
+ processManager: { processes: new Map(), exitAll, announceHost: vi.fn(), announceSubject: vi.fn() }
+ }) as unknown as AuthManager
+ const manager = new ProgramManager(auth)
+ const definition = (installCommand = `node -e "process.stdout.write('preparing')"`) => new Program({
+ identity: "example", storage: join(directory, "source", "storage"),
+ startup: { name: "startup" },
+ server: { location: server, installCommand, startCommand: "node main.js" }
+ })
+ return { directory, manager, exitAll, definition }
+}
+
+test("installation output precedes Process exit and handle switch; explicit launch precedes startup", async context => {
+ const { manager, exitAll, definition } = fixture(context)
+ const source = definition()
+ const old = await manager.create({ ...source.config, storage: source.storagePath } as import("@phreshos/core").ProgramDefinition)
+ const oldRoot = old.root
+ const events: string[] = []
+ const original = old.replace.bind(old)
+ vi.spyOn(old, "replace").mockImplementation(next => { events.push("switch"); original(next) })
+ exitAll.mockImplementation(async () => { events.push("exit"); expect(old.root).toBe(oldRoot) })
+ vi.spyOn(manager as unknown as { start(program: Program, launch: Launch): Promise<string> }, "start")
+ .mockImplementation(async (program, launch) => {
+ expect(program).toBe(old)
+ expect(program.root).not.toBe(oldRoot)
+ events.push(launch.name!)
+ return launch.name!
+ })
+ const result = await manager.install(old, { launch: { name: "explicit" } }, "self", chunk => {
+ expect(chunk.text).toBe("preparing")
+ expect(exitAll).not.toHaveBeenCalled()
+ expect(old.root).toBe(oldRoot)
+ events.push("output")
+ })
+ expect(result.program).toBe(old)
+ expect(events).toEqual(["output", "exit", "switch", "explicit", "startup"])
+ expect(exitAll).toHaveBeenCalledWith("example", "self")
+})
+
+test("failed preparation leaves the handle and its Processes intact", async context => {
+ const { manager, exitAll, definition } = fixture(context)
+ const source = definition(`node -e "process.exit(1)"`)
+ const old = await manager.create({ ...source.config, storage: source.storagePath } as import("@phreshos/core").ProgramDefinition)
+ const root = old.root
+ await expect(manager.install(old, { launch: true })).rejects.toThrow("exited with 1")
+ expect(exitAll).not.toHaveBeenCalled()
+ expect(old.root).toBe(root)
+})
+
+test("System completes the requested launch after the installation output consumer detaches", async context => {
+ const { manager, definition } = fixture(context)
+ const start = vi.spyOn(manager as unknown as { start(program: Program, launch: Launch): Promise<string> }, "start").mockResolvedValue("process")
+ const install = manager.install.bind(manager)
+ let completion: ReturnType<typeof install> | undefined
+ vi.spyOn(manager, "install").mockImplementation((...args) => completion = install(...args))
+ const stream = manager.installStreaming(definition(), { launch: { name: "explicit" } })
+ expect((await stream.next()).value).toEqual({ stream: "stdout", text: "preparing" })
+ await stream.return(undefined as never)
+ await completion
+ expect(start.mock.calls.map(([, launch]) => launch.name)).toEqual(["explicit", "startup"])
+ expect(manager.find("example").installed).toBe(true)
+})
+
+test("purge resets installed storage before launching and preserves source storage", async context => {
+ const { directory, manager, definition } = fixture(context)
+ const start = vi.spyOn(manager as unknown as { start(program: Program, launch: Launch): Promise<string> }, "start").mockResolvedValue("process")
+ let entry = await manager.install(definition())
+ const installedNote = join(entry.program.storagePath, "note.txt")
+ writeFileSync(installedNote, "installed data")
+ const sourceStorage = join(directory, "source", "storage")
+ mkdirSync(sourceStorage, { recursive: true })
+ writeFileSync(join(sourceStorage, "note.txt"), "development data")
+ entry = await manager.install(definition())
+ expect(readFileSync(installedNote, "utf8")).toBe("installed data")
+ start.mockImplementation(async program => {
+ expect(existsSync(join(program.storagePath, "note.txt"))).toBe(false)
+ return "process"
+ })
+ entry = await manager.install(definition(), { purge: true, launch: true })
+ expect(existsSync(installedNote)).toBe(false)
+ expect(readFileSync(join(sourceStorage, "note.txt"), "utf8")).toBe("development data")
+ expect(JSON.parse(readFileSync(join(entry.program.storagePath, "startup.json"), "utf8"))).toEqual({ name: "startup" })
+})
+
+test("explicit launch errors propagate without rolling back the installed Program", async context => {
+ const { manager, definition } = fixture(context)
+ const start = vi.spyOn(manager as unknown as { start(program: Program, launch: Launch): Promise<string> }, "start")
+ .mockRejectedValue(new Error("launch failed"))
+ await expect(manager.install(definition(), { launch: true })).rejects.toThrow("launch failed")
+ expect(manager.find("example").installed).toBe(true)
+ expect(start).toHaveBeenCalledTimes(1)
+})
diff --git a/tests/program-startup.test.ts b/tests/program-startup.test.ts
index e1d029b..34ea977 100644
--- a/tests/program-startup.test.ts
+++ b/tests/program-startup.test.ts
@@ -32,7 +32,7 @@ test("installation applies declared settings and launches the resulting stored s
})
function definition(setting?: true | Launch) {
return new Program({
- identity: "example", startup: setting, options: { language: "en" },
+ identity: "example", startup: setting,
client: { location: client, permissions: { network: ["https://new.example.test"] } }
})
}
@@ -47,7 +47,6 @@ test("installation applies declared settings and launches the resulting stored s
new LaunchStorage(entry.program, "startup").set(configured)
entry = await manager.install(definition(configured))
expect(launches).toEqual([{}, configured])
- expect(JSON.parse(readFileSync(join(entry.program.root, "program.json"), "utf8")).options).toEqual({ language: "en" })
expect(readFileSync(note, "utf8")).toBe("keep this")
expect(readPermissions(entry.program)).toEqual({ network: ["https://new.example.test"], appearance: [] })
@@ -67,7 +66,7 @@ test("installation applies declared settings and launches the resulting stored s
start.mockRejectedValueOnce(new Error("cannot start"))
await manager.startup(entry.program, "enable", configured)
const warnings: string[] = []
- entry = await manager.install(definition(true), null, chunk => { warnings.push(chunk.text) })
+ entry = await manager.install(definition(true), {}, null, chunk => { warnings.push(chunk.text) })
expect(entry.installed).toBe(true)
expect(new LaunchStorage(entry.program, "startup").get()).toEqual({})
expect(warnings.join("")).toContain("Program installed, but startup failed: cannot start")
diff --git a/tests/wallpaper-lifecycle.test.ts b/tests/wallpaper-lifecycle.test.ts
index 9ec6ea1..2604c53 100644
--- a/tests/wallpaper-lifecycle.test.ts
+++ b/tests/wallpaper-lifecycle.test.ts
@@ -4,6 +4,7 @@ import type { ClientLaunch, Layer } from "@phreshos/core"
import type AuthManager from "@server/core/link-manager/auth-manager/auth-manager"
import Program from "@server/core/link-manager/auth-manager/program-manager/program"
import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"
+import type { ServerRuntimeFactory } from "@server/core/server-runtime"
function fixture() {
const auth = new TheLink() as unknown as AuthManager
@@ -20,29 +21,46 @@ function fixture() {
clientShape(_program: Program, launch: ClientLaunch) { return shape(launch.layer) }
}
})
- const register = (identity: string, layer: Layer | null = "wallpaper") => manager.register(
+ const register = (identity: string, layer: Layer | null = "wallpaper", runtime: ServerRuntimeFactory<Program> | null = null) => manager.register(
identity, null, program, {}, { server: null, client: null, options: {} },
- null, layer !== null, layer === null ? null : shape(layer), null
+ runtime, layer !== null, layer === null ? null : shape(layer), null
)
return { manager, register }
}
-test("concurrent wallpaper launches have one winner without stopping the incumbent", async () => {
+test("concurrent wallpaper launches replace the incumbent Process in order", async () => {
const { manager, register } = fixture()
const results = await Promise.allSettled([register("first"), register("second")])
- expect(results.map(result => result.status).sort()).toEqual(["fulfilled", "rejected"])
- const failure = results.find(result => result.status === "rejected") as PromiseRejectedResult
- expect(failure.reason.message).toMatch(/already running in the wallpaper layer/)
+ expect(results.map(result => result.status)).toEqual(["fulfilled", "fulfilled"])
+ expect(manager.processes.has("first")).toBe(false)
+ expect(manager.processes.has("second")).toBe(true)
expect(manager.processes.size).toBe(1)
const incumbent = [...manager.processes.values()][0]!
expect(incumbent.client?.window.layer).toBe("wallpaper")
incumbent.client!.window.minimized = true
- await expect(register("third")).rejects.toThrow(/already running/)
- expect(incumbent.client).not.toBeNull()
+ await register("third")
+ expect(manager.processes.has(incumbent.identity)).toBe(false)
+ expect(incumbent.client).toBeNull()
await register("ordinary", "window")
await register("overlay", "over")
- await manager.remove(incumbent.identity)
expect((await register("replacement")).client?.window.layer).toBe("wallpaper")
+ expect(manager.processes.has("third")).toBe(false)
+ expect(manager.processes.has("ordinary")).toBe(true)
+ expect(manager.processes.has("overlay")).toBe(true)
+})
+
+test("wallpaper replacement finishes before the new Server runtime is created", async () => {
+ const { manager, register } = fixture()
+ await register("incumbent")
+ const runtime = vi.fn(() => {
+ expect(manager.processes.has("incumbent")).toBe(false)
+ throw new Error("runtime creation failed")
+ })
+ await expect(register("replacement", "wallpaper", runtime)).rejects.toThrow("runtime creation failed")
+ expect(runtime).toHaveBeenCalledOnce()
+ expect(manager.processes.size).toBe(0)
+ await register("next")
+ expect(manager.processes.has("next")).toBe(true)
})
test("starting an existing Client and creating a Process share the wallpaper claim", async () => {
@@ -51,19 +69,12 @@ test("starting an existing Client and creating a Process share the wallpaper cla
const results = await Promise.allSettled([
manager.startClient("existing", { layer: "wallpaper" }), register("new")
])
- expect(results.filter(result => result.status === "fulfilled")).toHaveLength(1)
+ expect(results.filter(result => result.status === "fulfilled")).toHaveLength(2)
expect([...manager.processes.values()].filter(process => process.client?.window.layer === "wallpaper")).toHaveLength(1)
- const incumbent = [...manager.processes.values()].find(process => process.client)!
- if (incumbent.identity === "existing") {
- await register("waiting", null)
- await expect(manager.startClient("waiting", { layer: "wallpaper" })).rejects.toThrow(/already running/)
- expect(manager.processes.get("waiting")!.client).toBeNull()
- } else {
- expect(manager.processes.get("existing")!.client).toBeNull()
- }
- await manager.remove(incumbent.identity)
- const waiting = [...manager.processes.values()].find(process => !process.client)!
- await manager.startClient(waiting.identity, { layer: "wallpaper" })
+ expect(manager.processes.has("existing")).toBe(false)
+ const waiting = await register("waiting", null)
+ await manager.startClient("waiting", { layer: "wallpaper" })
+ expect(manager.processes.has("new")).toBe(false)
expect(waiting.client?.window.layer).toBe("wallpaper")
})