An open-source, self-hosted system for apps built with web technologies.
Apply declared startup on install and preserve Endpoint contracts
zohayrslileh7995f4c01aa1
diff --git a/bun.lock b/bun.lockindex 140d9f2..7a386cf 100644--- a/bun.lock+++ b/bun.lock@@ -7,7 +7,7 @@"dependencies": {"@fontsource/roboto": "^5.3.0","@hono/node-server": "^2.1.1",- "@phreshos/core": "^0.1.43",+ "@phreshos/core": "^0.1.44","@phreshos/react-ui": "^0.1.19","@the-link/core": "^0.3.0","@the-link/http": "^0.1.1",@@ -235,7 +235,7 @@"@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-nuhZIOLuI6TFQ32I/WnUx+SCPY7SdSKwgnFHydAuoS1+Z4BRcaP+RRJmGzl9lw+0OFF7UmaESf7KQRXaNLHypg=="],- "@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-Z424mPzQ02azTsBDamBrxe+4iHW3UuromKqyvWBdZteGaPJff+XHXaRY4YJNruIXIuoe+vXz1Bni5ULTlXu/NQ=="],+ "@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-0Qo4SlNg9fi2xfpDMbMucHQrDhzE8hhzOy7n5rQPjpj4UIWPUU5ZuEGEON6bfQM6nKJ4ogNJF7KFp4RhMxf5PA=="],"@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=="],diff --git a/package.json b/package.jsonindex 7759143..8ead76a 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "phreshos","displayName": "PhreshOS",- "version": "0.1.64",+ "version": "0.1.65","description": "The PhreshOS server, desktop, and authoritative system runtime.","type": "module","private": true,@@ -36,7 +36,7 @@"dependencies": {"@fontsource/roboto": "^5.3.0","@hono/node-server": "^2.1.1",- "@phreshos/core": "^0.1.43",+ "@phreshos/core": "^0.1.44","@phreshos/react-ui": "^0.1.19","@the-link/core": "^0.3.0","@the-link/http": "^0.1.1",diff --git a/source/client/core/link-manager/auth-manager/process-manager/client-state.ts b/source/client/core/link-manager/auth-manager/process-manager/client-state.tsindex cbc22f9..313e0a8 100644--- a/source/client/core/link-manager/auth-manager/process-manager/client-state.ts+++ b/source/client/core/link-manager/auth-manager/process-manager/client-state.ts@@ -9,10 +9,14 @@ export default class ClientState {public sameOrigin: boolean+ public readonly service: NonNullable<ProcessSnapshot["client"]>["service"]+public constructor(processManager: ProcessManager, process: string, payload: NonNullable<ProcessSnapshot["client"]>) {this.window = new Window(processManager, process, payload.window)this.sameOrigin = payload.sameOrigin++ this.service = payload.service}}diff --git a/source/client/view/components/desktop-host/sdk-records.ts b/source/client/view/components/desktop-host/sdk-records.tsindex 46b1312..35fe699 100644--- a/source/client/view/components/desktop-host/sdk-records.ts+++ b/source/client/view/components/desktop-host/sdk-records.ts@@ -1,38 +1,11 @@-export interface SdkProgramSource {-- reference: string- identity: string- assetId: string- installed: boolean- name: string- version: string | null- description: string | null- hasAgent: boolean- server: unknown | null- client: unknown | null-}--export interface SdkProcessSource {-- reference: string-- identity: string-- name: string | null+import type { ProcessSnapshot, ProgramSnapshot } from "@phreshos/core"- program: string+export type SdkProgramSource = ProgramSnapshot- options: Record<string, string>-- startedAt: Date-- server: unknown | null-- client: unknown | null-}+export type SdkProcessSource = Omit<ProcessSnapshot, "program"> & { program: string }/** Plain SDK Program state carried across the iframe boundary. */-export function sdkProgram(program: SdkProgramSource) {+export function sdkProgram(program: SdkProgramSource): ProgramSnapshot {return {@@ -59,7 +32,7 @@ export function sdkProgram(program: SdkProgramSource) {}/** Plain Process state with its ownership chain embedded for synchronous navigation. */-export function sdkProcess(process: SdkProcessSource, program: SdkProgramSource) {+export function sdkProcess(process: SdkProcessSource, program: SdkProgramSource): ProcessSnapshot {return {@@ -75,8 +48,8 @@ export function sdkProcess(process: SdkProcessSource, program: SdkProgramSource)startedAt: process.startedAt,- server: process.server ? {} : null,+ server: process.server ? { service: process.server.service } : null,- client: process.client ? {} : null+ client: process.client ? { service: process.client.service } : null}}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.tsindex 749282c..0f3669d 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,14 +11,14 @@ import { dirname, isAbsolute, join } from "node:path"import { isDeepStrictEqual } from "node:util"import Logs, { type LogSource } from "./logs"import { isValue, layers } from "./config"-import { parseProgramDefinition, type ClientLaunch, type Launch, type ProgramCommandChunk, type ProgramDefinition } from "@phreshos/core"+import { parseLaunch, parseProgramDefinition, 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"import Entry, { type ProgramRecord } from "./entry"import Keyv from "keyv"import { isIconSize, ProgramIcons } from "./icon"-import { readStartup, removeStartup, writeStartup } from "./startup"+import { installStartup, readStartup, removeStartup, writeStartup } from "./startup"import { permissionCatalog } from "@server/core/permissions"import { installPermissions, readPermissions, writePermissions } from "./permissions"import {@@ -630,9 +630,10 @@ export default class ProgramManager extends TheLink {await program.validate()- this.resolveLaunch(program, value)+ const launch = parseLaunch(value === undefined ? {} : value)+ this.resolveLaunch(program, launch)- writeStartup(program, value)+ writeStartup(program, launch)return}@@ -997,6 +998,7 @@ export default class ProgramManager extends TheLink {let createdHere = falselet restorePermissions: (() => void) | null = null+ let restoreStartup: (() => void) | null = nulltry {@@ -1008,7 +1010,11 @@ export default class ProgramManager extends TheLink {// guard this and no longer can — a copied program's// description says nothing about where its parts are,// because they are wherever the system puts them.- await new Program(join(staged, "program.json")).validate()+ const stagedProgram = new Program(join(staged, "program.json"))+ await stagedProgram.validate()+ const startup = stagedProgram.config.startup+ const startupLaunch = startup === true ? {} : startup || null+ if (startupLaunch !== null) this.resolveLaunch(stagedProgram, startupLaunch)// A process may have retained an absolute server,// client, or storage path. Its ending is part of the@@ -1037,6 +1043,7 @@ export default class ProgramManager extends TheLink {// Installation establishes the only permission source of// truth. Reinstalling deliberately replaces prior owner edits.restorePermissions = installPermissions(installed)+ restoreStartup = installStartup(installed, startupLaunch)let entry = this.programs.get(source.identity)@@ -1059,6 +1066,7 @@ export default class ProgramManager extends TheLink {committed = truerestorePermissions = null+ restoreStartup = nullif (createdHere) await this.created(entry)@@ -1071,6 +1079,13 @@ export default class ProgramManager extends TheLink {// yesterday's list.await this.$outbound.publish("/install", entry.record())+ if (startupLaunch !== null) {+ try { await this.start(entry.program, startupLaunch, undefined, null, true) }+ catch (exception) {+ await output({ stream: "stderr", text: `Program installed, but startup failed: ${exception instanceof Error ? exception.message : String(exception)}\n` })+ }+ }+return entry}@@ -1081,6 +1096,7 @@ export default class ProgramManager extends TheLink {// never enters the transaction and is neither copied nor moved.if (swapping && !committed) {+ restoreStartup?.()restorePermissions?.()for (const what of installedParts) rmSync(join(home, what), { recursive: true, force: true })@@ -1279,29 +1295,13 @@ export default class ProgramManager extends TheLink {// name occupancy and capacity remain in `start`.private resolveLaunch(program: Program, value: unknown) {- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("A launch must be a named shape")-- const launch = value as Launch-- if (launch.name !== undefined && (typeof launch.name !== "string" || !launch.name)) throw new Error("A process name must be non-empty text")+ const launch = parseLaunch(value)- const suppliedOptions = launch.options ?? {}-- if (typeof suppliedOptions !== "object" || suppliedOptions === null || Array.isArray(suppliedOptions) || Object.values(suppliedOptions).some(value => typeof value !== "string")) throw new Error("A launch's options must be text values")-- const options = Object.fromEntries(Object.entries(suppliedOptions).sort(([left], [right]) => left.localeCompare(right)))-- if (launch.server !== undefined && typeof launch.server !== "boolean" && (typeof launch.server !== "object" || launch.server === null || Array.isArray(launch.server))) throw new Error("A launch's server must be true, false, or a server shape")-- if (launch.client !== undefined && typeof launch.client !== "boolean" && (typeof launch.client !== "object" || launch.client === null || Array.isArray(launch.client))) throw new Error("A launch's client must be true, false, or a client shape")+ const options = Object.fromEntries(Object.entries({ ...program.config.options, ...launch.options }).sort(([left], [right]) => left.localeCompare(right)))const askedServer = typeof launch.server === "object" ? launch.server : {}const askedClient = typeof launch.client === "object" ? launch.client : {}- if (askedServer.service !== undefined && typeof askedServer.service !== "boolean") throw new Error("A launch server's service role must be true or false")-- if (askedClient.service !== undefined && typeof askedClient.service !== "boolean") throw new Error("A launch client's service role must be true or false")-if ((launch.server === true || typeof launch.server === "object") && !program.server) throw new Error("This program declared no server half — a launch cannot add one")if ((launch.client === true || typeof launch.client === "object") && !program.client) throw new Error("This program declared no client half — a launch cannot add one")diff --git a/source/server/core/link-manager/auth-manager/program-manager/startup.ts b/source/server/core/link-manager/auth-manager/program-manager/startup.tsindex 7c18da9..e46d506 100644--- a/source/server/core/link-manager/auth-manager/program-manager/startup.ts+++ b/source/server/core/link-manager/auth-manager/program-manager/startup.ts@@ -2,21 +2,27 @@ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSyncimport { randomUUID } from "node:crypto"import { join } from "node:path"import type Program from "./program"+import { parseLaunch, type Launch } from "@phreshos/core"const file = "startup.json"-/** Read the system-managed startup declaration without interpreting it. */-export function readStartup(program: Program): unknown | null {+/** Read and validate the stored launch without resolving Program defaults. */+export function readStartup(program: Program): Launch | null {const path = join(program.storagePath, file)if (!existsSync(path)) return null- return JSON.parse(readFileSync(path, "utf8")) as unknown+ return parseLaunch(JSON.parse(readFileSync(path, "utf8")))}/** Atomically replace one Program's system-managed startup declaration. */-export function writeStartup(program: Program, launch: unknown) {+export function writeStartup(program: Program, launch: Launch) {++ write(program, `${JSON.stringify(launch, null, 2)}\n`)+}++function write(program: Program, content: string | Uint8Array) {mkdirSync(program.storagePath, { recursive: true })@@ -26,7 +32,7 @@ export function writeStartup(program: Program, launch: unknown) {try {- writeFileSync(temporary, `${JSON.stringify(launch, null, 2)}\n`)+ writeFileSync(temporary, content)renameSync(temporary, path)}@@ -34,6 +40,21 @@ export function writeStartup(program: Program, launch: unknown) {finally { rmSync(temporary, { force: true }) }}+/** Installation replaces startup, including an omitted or disabled declaration. */+export function installStartup(program: Program, launch: Launch | null) {++ const path = join(program.storagePath, file)+ const previous = existsSync(path) ? readFileSync(path) : null++ if (launch === null) removeStartup(program)+ else writeStartup(program, launch)++ return function rollbackStartupInstallation() {+ if (previous === null) removeStartup(program)+ else write(program, previous)+ }+}+/** Disable startup without touching any other Program storage. */export function removeStartup(program: Program) {diff --git a/tests/process-find-or-create.test.ts b/tests/process-find-or-create.test.tsindex d4ca909..215f535 100644--- a/tests/process-find-or-create.test.ts+++ b/tests/process-find-or-create.test.ts@@ -14,12 +14,13 @@ test("process find or create contract", async () => {interface FixtureManager {start(owner: Program, launch: Launch, watching?: unknown, parent?: unknown, transition?: boolean, prepared?: { intent: unknown }): Promise<`${string}-${string}-${string}-${string}-${string}`>- resolveLaunch(owner: Program, launch: Launch): { intent: { server: { service: boolean } | null, client: { position: unknown, size: unknown, service: boolean } | null } }+ resolveLaunch(owner: Program, launch: Launch): { options: Record<string, string>, intent: { server: { service: boolean } | null, client: { position: unknown, size: unknown, service: boolean } | null } }}const processes = new Map<string, FixtureProcess>()const program = {identity: "example",+ config: { options: { language: "en", document: "default.txt" } },reference: "example-reference",server: { start: true },client: {@@ -90,6 +91,9 @@ 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" })processes.set("unrelated", { identity: "unrelated", name: null, program, launch: null })const explicit = fixture.resolveLaunch(program, {name: "defaults",diff --git a/tests/program-install.test.ts b/tests/program-install.test.tsindex a9115ca..43f8f69 100644--- a/tests/program-install.test.ts+++ b/tests/program-install.test.ts@@ -58,6 +58,9 @@ test("program install contract", async () => {rollbackPermissions()assert.deepEqual(readPermissions(installedProgram), { network: ["https://old.example.test"], appearance: [] })installPermissions(installedProgram)+ const withoutPermissions = new Program({ ...installedProgram.config, client: { location: "client" } }, installedProgram.root)+ installPermissions(withoutPermissions)+ assert.deepEqual(readPermissions(installedProgram), {})const installation: ProgramCommandChunk[] = []const uninstallation: ProgramCommandChunk[] = []diff --git a/tests/program-startup.test.ts b/tests/program-startup.test.tsnew file mode 100644index 0000000..0864428--- /dev/null+++ b/tests/program-startup.test.ts@@ -0,0 +1,92 @@+import { 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 } 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"+import { readPermissions, writePermissions } from "@server/core/link-manager/auth-manager/program-manager/permissions"+import * as startup from "@server/core/link-manager/auth-manager/program-manager/startup"++test("installation replaces startup and permissions before launching exactly once", async context => {+ const directory = mkdtempSync(join(tmpdir(), "phresh-startup-"))+ context.onTestFinished(() => { vi.restoreAllMocks(); rmSync(directory, { recursive: true, force: true }) })+ const client = join(directory, "client")+ mkdirSync(client)+ writeFileSync(join(client, "index.html"), "<!doctype html>")++ const auth = Object.assign(new TheLink(), {+ linkManager: { application: { storage: new FileManager(directory, "system"), defaultProgramIcon: "" } },+ processManager: { processes: new Map(), exitAll: vi.fn(), announceHost: vi.fn() }+ }) as unknown as AuthManager+ const manager = new ProgramManager(auth)+ const launches: Launch[] = []+ const start = vi.spyOn(manager as unknown as { start(program: Program, launch: Launch): Promise<string> }, "start")+ .mockImplementation(async (program, launch) => {+ expect(startup.readStartup(program)).toEqual(launch)+ expect(readPermissions(program)).toEqual({ network: ["https://new.example.test"] })+ launches.push(launch)+ return "process-identity"+ })+ function definition(setting?: boolean | Launch) {+ return new Program({+ identity: "example", startup: setting, options: { language: "en" },+ client: { location: client, permissions: { network: ["https://new.example.test"] } }+ })+ }++ let entry = await manager.install(definition(true))+ expect(launches).toEqual([{}])+ const note = join(entry.program.storagePath, "note.txt")+ writeFileSync(note, "keep this")+ writePermissions(entry.program, { network: [], appearance: [] })+ startup.writeStartup(entry.program, { name: "owner-edit" })++ const configured = { name: "welcome", options: { language: "fr" } }+ 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")++ for (const disabled of [false, undefined]) {+ startup.writeStartup(entry.program, configured)+ entry = await manager.install(definition(disabled))+ expect(startup.readStartup(entry.program)).toBeNull()+ expect(start).toHaveBeenCalledTimes(2)+ }++ // A settings write failure restores permissions and leaves the old startup intact.+ writePermissions(entry.program, { appearance: [] })+ startup.writeStartup(entry.program, configured)+ const writing = vi.spyOn(startup, "installStartup").mockImplementationOnce(() => { throw new Error("write failed") })+ await expect(manager.install(definition(true))).rejects.toThrow("write failed")+ expect(readPermissions(entry.program)).toEqual({ appearance: [] })+ expect(startup.readStartup(entry.program)).toEqual(configured)+ writing.mockRestore()++ // Startup failure is reported without undoing a valid installation.+ start.mockRejectedValueOnce(new Error("cannot start"))+ const warnings: string[] = []+ entry = await manager.install(definition(true), null, chunk => { warnings.push(chunk.text) })+ expect(entry.installed).toBe(true)+ expect(startup.readStartup(entry.program)).toEqual({})+ expect(warnings.join("")).toContain("Program installed, but startup failed: cannot start")++ await expect(manager.install(definition({ server: true }))).rejects.toThrow("no server")+ expect(startup.readStartup(entry.program)).toEqual({})+})++test("startup rollback preserves the exact previous file", context => {+ const directory = mkdtempSync(join(tmpdir(), "phresh-startup-rollback-"))+ context.onTestFinished(() => rmSync(directory, { recursive: true, force: true }))+ const program = new Program({ identity: "example", storage: directory, client: { location: "." } })+ const file = join(directory, "startup.json")+ writeFileSync(file, "invalid prior content")+ const rollback = startup.installStartup(program, {})+ expect(startup.readStartup(program)).toEqual({})+ rollback()+ expect(readFileSync(file, "utf8")).toBe("invalid prior content")+})diff --git a/tests/sdk-records.test.ts b/tests/sdk-records.test.tsnew file mode 100644index 0000000..d6c552a--- /dev/null+++ b/tests/sdk-records.test.ts@@ -0,0 +1,22 @@+import { expect, test } from "vitest"+import { parseProcessSnapshot, type ProgramSnapshot } from "@phreshos/core"+import { sdkProcess, type SdkProcessSource } from "@client/view/components/desktop-host/sdk-records"++test("Desktop preserves Endpoint service roles in SDK snapshots", () => {+ const program: ProgramSnapshot = {+ identity: "example", reference: "program-reference", assetId: "program-assets",+ name: "Example", version: null, description: null, hasAgent: false,+ server: { start: true, service: false }, client: null+ }+ for (const server of [null, { service: false }, { service: true }]) {+ for (const client of [null, { service: false }, { service: true }]) {+ const source: SdkProcessSource = {+ identity: "process-identity", reference: "process-reference", program: program.identity,+ name: null, options: { language: "en" }, startedAt: new Date(0), server, client+ }+ const snapshot = parseProcessSnapshot(sdkProcess(source, program))+ expect(snapshot.server).toEqual(server)+ expect(snapshot.client).toEqual(client)+ }+ }+})