An open-source, self-hosted system for apps built with web technologies.
Release System 0.1.81
zohayrslilehf17933f8890f
diff --git a/bun.lock b/bun.lockindex 88fe765..8c2cd82 100644--- a/bun.lock+++ b/bun.lock@@ -8,8 +8,8 @@"@fontsource/roboto": "^5.3.0","@hono/node-server": "^2.1.1","@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0",- "@phreshos/core": "^0.1.55",- "@phreshos/react-ui": "^0.1.30",+ "@phreshos/core": "^0.1.56",+ "@phreshos/react-ui": "^0.1.32","@the-link/core": "^0.3.1","@the-link/http": "^0.1.1","@the-link/ipc": "^0.2.1",@@ -199,9 +199,9 @@"@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw=="],- "@phreshos/core": ["@phreshos/[email protected]", "", { "dependencies": { "zod": "^4.6.5" } }, "sha512-xY957bQO7+/8syaaHhlWThouRU7QDzaL5HWdcV30JbuKCn9GBSkWFwanMFEIB/PQmbbD+xswFNGuXKU295GxpQ=="],+ "@phreshos/core": ["@phreshos/[email protected]", "", { "dependencies": { "zod": "^4.6.5" } }, "sha512-X5JphvijFBfhzo7JplkrIra/61dXVQFQ2Y1tzpGFHycvHA3L7g6D9FriiBZcmDFk5RzohivYzJGpXq1tPeXDQQ=="],- "@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "@base-ui/react": "^1.7.0", "@phreshos/core": "^0.1.55", "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-44UVKpJB/l8U4w+FzZs10oA/ce15+f5Onfejj9O4pB4QOWfSaJmevMbUali6/3s8Q7tTTYPXJDDbFDO1baSrNA=="],+ "@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "@base-ui/react": "^1.7.0", "@internationalized/date": "^3.12.3", "@phreshos/core": "^0.1.56", "colorjs.io": "^0.7.1", "motion": "^13.2.0", "react-aria": "^3.51.0", "react-aria-components": "^1.20.0" }, "peerDependencies": { "react": "^19.2.0", "react-dom": "^19.2.0" } }, "sha512-QmmpNTrM4lRaQPcAhmIwfMnf+g0lG83Z/jW3CG2HSEN5TQmlN86gzNFKED52xLY/XRfQ7VU+Ptj6MHgL0hX8zg=="],"@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=="],diff --git a/package.json b/package.jsonindex 7bc22e6..5222fd4 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "phreshos","displayName": "PhreshOS",- "version": "0.1.80",+ "version": "0.1.81","description": "The PhreshOS server, desktop, and authoritative system runtime.","type": "module","private": true,@@ -37,8 +37,8 @@"@fontsource/roboto": "^5.3.0","@hono/node-server": "^2.1.1","@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0",- "@phreshos/core": "^0.1.55",- "@phreshos/react-ui": "^0.1.30",+ "@phreshos/core": "^0.1.56",+ "@phreshos/react-ui": "^0.1.32","@the-link/core": "^0.3.1","@the-link/http": "^0.1.1","@the-link/ipc": "^0.2.1",diff --git a/source/client/core/link-manager/auth-manager/auth-manager.ts b/source/client/core/link-manager/auth-manager/auth-manager.tsindex 29343c6..e4cfcba 100644--- a/source/client/core/link-manager/auth-manager/auth-manager.ts+++ b/source/client/core/link-manager/auth-manager/auth-manager.ts@@ -129,12 +129,13 @@ export default class AuthManager extends TheLink {public async requestPermission<Name extends PermissionName>(process: string,+ program: unknown,request: string,name: Name,permission: PermissionRequest<Name>): Promise<Permission<Name>> {- return await this.$outbound.publishFirst("/permission/request", request, process, name, permission) as Permission<Name>+ return await this.$outbound.publishFirst("/permission/request", request, process, program, name, permission) as Permission<Name>}public async cancelPermission(process: string, request: string) {diff --git a/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/client/core/link-manager/auth-manager/process-manager/process-manager.tsindex ef92db8..23e9426 100644--- a/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts+++ b/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts@@ -99,15 +99,19 @@ export default class ProcessManager extends TheLink {await this.$outbound.publishFirst("/service/wait-ready", address, timeout)}- public async serviceProgramMetadata(address: ServiceAddress, iconSize: ProgramIconSize = "medium") {+ public async serviceProgramMetadata(address: ServiceAddress) {- return await this.$outbound.publishFirst("/service/program-metadata", address, iconSize) as {+ return await this.$outbound.publishFirst("/service/program-metadata", address) as {name: stringversion: string- icon: number[]}}+ public async serviceProgramIcon(address: ServiceAddress, iconSize: ProgramIconSize = "medium") {++ return await this.$outbound.publishFirst("/service/program-icon", address, iconSize) as number[]+ }+/** Registers one exact service interest for this frame lease. */public async followService(pane: string, owner: string, subscription: string, address: ServiceAddress, scope: ServiceScope, event: string | null) {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.tsindex 848aee9..f16d746 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@@ -6,8 +6,8 @@ import AuthManager from "../auth-manager"import Program from "./program"import {type Launch,- type PermissionInput,type PermissionName,+ type PermissionRequest,type ProgramCommandChunk,type ProgramIconSize} from "@phreshos/core"@@ -75,21 +75,21 @@ export default class ProgramManager extends TheLink {return await this.$outbound.publishFirst("/startup", subject, operation, value)}- public async launch(subject: unknown, operation: string, value?: unknown) {-- return await this.$outbound.publishFirst("/launch", subject, operation, value)- }-public async permissions<Name extends PermissionName>(subject: unknown,- operation: "all" | "get" | "allows" | "set" | "delete",+ operation: "all" | "get" | "allows" | "allow" | "deny",name?: Name,- value?: Exclude<PermissionInput<Name>, null>+ value?: PermissionRequest<Name>) {return await this.$outbound.publishFirst("/permissions", subject, operation, name, value)}+ public async pinned(subject: unknown, operation: "get" | "pin" | "unpin") {++ return await this.$outbound.publishFirst("/pinned", subject, operation) as boolean+ }+/** Atomically resolves one named Process at the authoritative host. */public async findOrCreateProcess(subject: unknown, launch: Launch & { name: string }, parent?: string) {@@ -142,6 +142,12 @@ export default class ProgramManager extends TheLink {return await this.$outbound.publishFirst("/agent", subject) as string | null}+ /** Reads the complete canonical Program definition without mixing in runtime state. */+ public async definition(subject: unknown) {++ return await this.$outbound.publishFirst("/definition", subject)+ }+@Subscribe("/install")@Publish("/programs", "inbound")protected async installed(payload: ProgramRecord | null) {@@ -172,6 +178,15 @@ export default class ProgramManager extends TheLink {return this.arrived(payload)}+ @Subscribe("/pinned")+ protected async pinnedChanged(payload: ProgramRecord | null, pinned: boolean) {++ if (!payload || typeof pinned !== "boolean") return+ const program = this.programs.get(payload.identity)+ if (!program || program.reference !== payload.reference) return+ await this.$inbound.publish("/pinned", program, pinned)+ }+@Subscribe("/command-output")protected commandOutput(stream: string, value: unknown) {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.tsindex 1f7a0de..7d9854b 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@@ -75,9 +75,7 @@ export default class Program {public async open() {- const launch = await this.programManager.launch(this.address, "get")-- await this.createProcess(launch ?? {})+ await this.createProcess()}public install(options: ProgramInstallOptions = {}, asker = "") {diff --git a/source/client/view/components/desktop-host/announcements.ts b/source/client/view/components/desktop-host/announcements.tsindex 00ed1e5..17e800e 100644--- a/source/client/view/components/desktop-host/announcements.ts+++ b/source/client/view/components/desktop-host/announcements.ts@@ -1,5 +1,6 @@import { type default as AuthManager } from "@client/core/link-manager/auth-manager/auth-manager"import { type ProgramRecord } from "@server/core/link-manager/auth-manager/program-manager/entry"+import type Program from "@client/core/link-manager/auth-manager/program-manager/program"import { ReactTunnel } from "@the-link/react"import { useCallback } from "react"import ClientProcessBoundary from "./client-process-boundary"@@ -180,6 +181,12 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<stprograms.useSubscribe("/install", useCallback((entry: ProgramRecord | null) => programEvent("install", entry), [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]))+ programs.useSubscribe("/pinned", useCallback((entry: Program | null, pinned: boolean) => {+ if (!entry || typeof pinned !== "boolean") return+ const record = sdkProgram(entry)+ post(entry.identity, "host-program", "pinned", entry.identity, record, pinned)+ post(entry.identity, "program-host", "pinned", entry.reference, pinned)+ }, [post]))}function domainIdentity(value: unknown) {diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.tsindex e9033ab..75477e8 100644--- a/source/client/view/components/desktop-host/client-process-boundary.ts+++ b/source/client/view/components/desktop-host/client-process-boundary.ts@@ -536,12 +536,12 @@ export default class ClientProcessBoundary extends TheLink {return}- if (args[0] === "context-permission-request" && typeof args[1] === "string") {+ if (args[0] === "program-permissions" && args[2] === "request" && typeof args[3] === "string") {this.answerRequest(question,host(this.authManager, this.pane, this.viewport, () => this.owner, this.presentation)(args[0], ...args.slice(1)),- () => { this.authManager.cancelPermission(this.pane, args[1] as string).catch(() => undefined) }+ () => { this.authManager.cancelPermission(this.pane, args[3] as string).catch(() => undefined) })return@@ -678,7 +678,7 @@ export default class ClientProcessBoundary extends TheLink {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 : {+ value = options.launch === undefined || options.launch === false ? options : {...options,launch: await this.systemAccess.launch(options.launch === true ? {} : options.launch)}diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.tsindex 3f52b5d..a4c6b6f 100644--- a/source/client/view/components/desktop-host/host.ts+++ b/source/client/view/components/desktop-host/host.ts@@ -15,7 +15,6 @@ import {isUploadFile,parseDesktopPreferencesUpdate,parsePermissionName,- type PermissionInput,type PermissionRequest,type ProgramIconSize} from "@phreshos/core"@@ -406,7 +405,14 @@ export default function host(authManager: AuthManager, pane: string, viewport: (const service = await permittedService(args[0])- return [await processManager.serviceProgramMetadata(service, args[1] as ProgramIconSize | undefined)]+ return [await processManager.serviceProgramMetadata(service)]+ }++ if (word === "service-program-icon") {++ const service = await permittedService(args[0])++ return [await processManager.serviceProgramIcon(service, args[1] as ProgramIconSize | undefined)]}if (word === "service-follow") {@@ -681,36 +687,31 @@ export default function host(authManager: AuthManager, pane: string, viewport: (return [sdkProgram(program)]}- if (word === "context-permission-get") return [await authManager.permission(pane, parsePermissionName(args[0]))]-- if (word === "context-permission-allows") {-- const permission = parsePermissionName(args[0])-- return [await authManager.grantsPermission(pane, permission, args[1] as PermissionRequest<typeof permission>)]- }-- if (word === "context-permission-request") {-- if (typeof args[0] !== "string") throw new Error("A permission request needs an identity")-- const permission = parsePermissionName(args[1])-- return [await authManager.requestPermission(pane, args[0], permission, args[2] as PermissionRequest<typeof permission>)]- }-if (word === "program-permissions") {const program = await permittedProgram(args[0])- await access.requireAll()-const operation = args[1]- if (operation !== "all" && operation !== "get" && operation !== "allows" && operation !== "set" && operation !== "delete") throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)+ if (operation !== "all" && operation !== "get" && operation !== "allows" && operation !== "allow" && operation !== "deny" && operation !== "request") throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)if (operation === "all") return [await programManager.permissions(address(program), operation)]+ if (operation === "request") {++ if (typeof args[2] !== "string") throw new Error("A permission request needs an identity")++ const permission = parsePermissionName(args[3])++ return [await authManager.requestPermission(+ pane,+ address(program),+ args[2],+ permission,+ args[4] as PermissionRequest<typeof permission>+ )]+ }+const permission = parsePermissionName(args[2])if (operation === "allows") return [await programManager.permissions(@@ -720,33 +721,28 @@ export default function host(authManager: AuthManager, pane: string, viewport: (args[3] as PermissionRequest<typeof permission>)]- if (operation === "set") {+ if (operation === "allow") {+ await access.requireAll()await programManager.permissions(address(program),operation,permission,- args[3] as Exclude<PermissionInput<typeof permission>, null>+ args[3] as PermissionRequest<typeof permission>)return []}- await programManager.permissions(address(program), operation, permission)+ if (operation === "deny") {- return []- }-- if (word === "launch") {+ await access.requireAll()+ await programManager.permissions(address(program), operation, permission)- const program = await permittedProgram(args[0])- const operation = String(args[1])-- if (operation === "set" && args[2] === undefined) throw new Error("A Launch is required")-- const launch = operation === "set" ? await access.launch(args[2]) : args[2]+ return []+ }- return [await programManager.launch(address(program), operation, launch)]+ return [await programManager.permissions(address(program), operation, permission)]}if (word === "startup") {@@ -759,8 +755,17 @@ export default function host(authManager: AuthManager, pane: string, viewport: (return [await programManager.startup(address(program), operation, launch)]}+ if (word === "pinned") {++ const operation = args[1]+ if (operation !== "get" && operation !== "pin" && operation !== "unpin") throw new Error(`The System does not know the pinned operation "${String(operation)}"`)+ return [await programManager.pinned(address(await permittedProgram(args[0])), operation)]+ }+if (word === "program-agent") return [await programManager.agent(address(await permittedProgram(args[0])))]+ if (word === "program-definition") return [await programManager.definition(address(await permittedProgram(args[0])))]+// Icon bytes are requested only when a concrete Program handle asks.if (word === "icon") return [await programManager.icon(address(await permittedProgram(args[0])), args[1] as ProgramIconSize)]diff --git a/source/server/core/appearance-manager.ts b/source/server/core/appearance-manager.tsindex 2dd07e4..6abb33b 100644--- a/source/server/core/appearance-manager.ts+++ b/source/server/core/appearance-manager.ts@@ -1,6 +1,6 @@import Keyv from "keyv"import { isDeepStrictEqual } from "node:util"-import { defaultAppearance, parseAppearance, type Appearance } from "@phreshos/core"+import { applyAppearanceUpdate, defaultAppearance, parseAppearance, type Appearance } from "@phreshos/core"import UploadManager from "./upload-manager"import { wallpaperKind, wallpaperSizeLimit } from "@shared/wallpaper"@@ -27,7 +27,7 @@ export default class AppearanceManager {public get value() { return this.current }public async update(value: unknown) {- const appearance = parseAppearance(value)+ const appearance = applyAppearanceUpdate(this.current, value)this.validateWallpaper(appearance.signInWallpaper.light)this.validateWallpaper(appearance.signInWallpaper.dark)diff --git a/source/server/core/dialog-manager.ts b/source/server/core/dialog-manager.tsindex 1cbe896..29b6f48 100644--- a/source/server/core/dialog-manager.ts+++ b/source/server/core/dialog-manager.ts@@ -2,6 +2,7 @@ import { Subscribe } from "@the-link/core/decorators"import { TheLink } from "@the-link/core"import { randomUUID } from "node:crypto"import { type default as Process } from "./link-manager/auth-manager/process-manager/process"+import { type default as Program } from "./link-manager/auth-manager/program-manager/program"import { permissionCatalog } from "./permissions"import type { PermissionName, PermissionValue } from "@phreshos/core"@@ -57,16 +58,17 @@ export default class DialogManager extends TheLink {await this.$outbound.publish("/created", dialog).catch(() => undefined)}- /** Waits for one authoritative owner decision for a Client Process. */+ /** Waits for one authoritative owner decision about a target Program. */public async requestPermission<Name extends PermissionName>(- process: Process,+ program: Program,request: string,permission: Name,- values: readonly PermissionValue<Name>[]+ values: readonly PermissionValue<Name>[],+ process: Process | null = null): Promise<PermissionChoice> {if (!request || this.permissionRequests.has(request)) throw new Error("A permission request needs a unique identity")- if (this.permissionProcesses.has(process.reference)) throw new Error("This Client Process already has a pending permission request")+ if (process && this.permissionProcesses.has(process.reference)) throw new Error("This Process already has a pending permission request")const definition = permissionCatalog.definition(permission)const dialog: PermissionDialog = {@@ -78,16 +80,20 @@ export default class DialogManager extends TheLink {values: [...values],title: definition.title,description: definition.description,- program: { identity: process.program.identity, name: process.program.name },- process: { identity: process.identity, name: process.name }+ program: { identity: program.identity, name: program.name },+ process: process ? { identity: process.identity, name: process.name } : null}let settle: (choice: PermissionChoice) => void = () => undefinedconst answer = new Promise<PermissionChoice>(resolve => { settle = resolve })- const stopExit = process.onExit(() => { this.cancelPermission(request, process.reference).catch(() => undefined) })-- this.permissionRequests.set(request, { request, dialog, process: process.reference, settle, stopExit })- this.permissionProcesses.set(process.reference, request)+ // Endpoint requests belong to that Process lifetime; owner-local+ // requests have no invented Process and are cancelled by their caller.+ const stopExit = process+ ? process.onExit(() => { this.cancelPermission(request, process.reference).catch(() => undefined) })+ : () => undefined++ this.permissionRequests.set(request, { request, dialog, process: process?.reference ?? null, settle, stopExit })+ if (process) this.permissionProcesses.set(process.reference, request)this.dialogs.set(dialog.identity, dialog)await this.$outbound.publish("/created", dialog).catch(() => undefined)@@ -107,18 +113,18 @@ export default class DialogManager extends TheLink {}/** Cancels one boundary-owned prompt without creating a decision. */- public async cancelPermission(request: string, process: string) {+ public async cancelPermission(request: string, process: string | null = null) {const pending = this.permissionRequests.get(request)- if (pending?.process === process) await this.finishPermission(pending, null)+ if (pending && (process === null || pending.process === process)) await this.finishPermission(pending, null)}private async finishPermission(pending: PendingPermission, choice: PermissionChoice) {if (!this.permissionRequests.delete(pending.request)) return- this.permissionProcesses.delete(pending.process)+ if (pending.process) this.permissionProcesses.delete(pending.process)this.dialogs.delete(pending.dialog.identity)pending.stopExit()pending.settle(choice)@@ -178,7 +184,7 @@ export interface PermissionDialog {readonly title: stringreadonly description: stringreadonly program: Readonly<{ identity: string, name: string }>- readonly process: Readonly<{ identity: string, name: string | null }>+ readonly process: Readonly<{ identity: string, name: string | null }> | null}export type PermissionChoice = true | false | null@@ -189,7 +195,7 @@ interface PendingPermission {readonly request: stringreadonly dialog: PermissionDialog- readonly process: string+ readonly process: string | nullreadonly settle: (choice: PermissionChoice) => voidreadonly stopExit: () => void}diff --git a/source/server/core/link-manager/auth-manager/auth-manager.ts b/source/server/core/link-manager/auth-manager/auth-manager.tsindex 5957710..72d0286 100644--- a/source/server/core/link-manager/auth-manager/auth-manager.ts+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts@@ -312,7 +312,7 @@ export default class AuthManager extends TheLink {return this.linkManager.application.system.signOutSession(domainIdentity(identity, "Session"))}- /** Replace System Appearance through the authenticated boundary. */+ /** Apply a partial System Appearance update through the authenticated boundary. */public async updateAppearance(value: unknown) {return await this.linkManager.updateAppearance(value)@@ -354,13 +354,13 @@ export default class AuthManager extends TheLink {}@Connect("/permission/request")- protected async requestPermission(request: unknown, process: unknown, name: unknown, permission: unknown) {+ protected async requestPermission(request: unknown, process: unknown, program: unknown, name: unknown, permission: unknown) {if (typeof request !== "string" || typeof process !== "string") throw new Error("A permission request is invalid")const permissionName = parsePermissionName(name)- return this.processManager.requestPermission(process, request, permissionName, permission as PermissionRequest<typeof permissionName>)+ return this.processManager.requestPermission(process, program, request, permissionName, permission as PermissionRequest<typeof permissionName>)}@Subscribe("/permission/cancel")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.tsindex 8c19528..83f95f3 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@@ -24,7 +24,6 @@ import {type ClientLaunch,type Launch,type Permission,- type PermissionInput,type PermissionName,type PermissionRequest,type PermissionValue,@@ -1546,7 +1545,7 @@ export default class ProcessManager extends TheLink {}@Connect("/service/program-metadata")- protected async serviceProgramMetadata(address: unknown, iconSize: unknown = "medium") {+ protected async serviceProgramMetadata(address: unknown) {if (!isServiceAddress(address)) throw new Error("A complete Service address is required")@@ -1555,14 +1554,30 @@ export default class ProcessManager extends TheLink {if (!target) throw new Error("The Service is unavailable")const program = target.process.program- const icon = await this.authManager.programManager.icon(program, iconSize)++ return Object.freeze({ name: program.name, version: program.version })+ }++ @Connect("/service/program-icon")+ protected async serviceProgramIcon(address: unknown, iconSize: unknown = "medium") {++ if (!isServiceAddress(address)) throw new Error("A complete Service address is required")++ const target = this.services.target(address)++ if (!target) throw new Error("The Service is unavailable")++ const icon = await this.authManager.programManager.icon(target.process.program, iconSize)++ // Rendering can outlive one provider incarnation; never return an icon+ // after the exact Service target that authorized the read has vanished.const current = this.services.target(address)if (!current || current.process !== target.process || current.endpoint !== target.endpoint) {throw new Error("The Service is unavailable")}- return Object.freeze({ name: program.name, version: program.version, icon })+ return icon}@Subscribe("/service/send")@@ -1706,29 +1721,17 @@ export default class ProcessManager extends TheLink {/** Requests owner approval and replaces the authoritative stored permission. */public async requestPermission<Name extends PermissionName>(identity: string,+ subject: unknown,request: string,name: Name,input: PermissionRequest<Name>): Promise<Permission<Name>> {const process = this.find(identity)+ const access = new SystemAccess(this, process)+ const program = access.program(this.system.holdProgram(subject, process.program))- if (!process.client) throw new Error("A permission request requires a live Client endpoint")-- const requested = permissionCatalog.resolve(name, input)-- if (!Array.isArray(requested)) throw new Error("A permission request must be true or a list of values")-- const choice = await this.authManager.dialogManager.requestPermission(process, request, name, requested)-- if (choice === true) {-- await this.authManager.programManager.setPermission(process.program, name, requested)-- return requested- }-- return choice+ return this.authManager.programManager.requestPermission(program, request, name, input, process)}/** Keeps each live Client's iframe access policy aligned with its Program. */@@ -1874,30 +1877,10 @@ export default class ProcessManager extends TheLink {if (word === "current-program") return [this.system.requireProgram(process.program.identity)]- if (word === "context-permission-get") {-- return [this.permission(process.identity, parsePermissionName(rest[0]))]- }-- if (word === "context-permission-allows") {-- const permission = parsePermissionName(rest[0])-- return [this.authManager.programManager.allowsPermission(process.program, permission, rest[1] as PermissionRequest<typeof permission>)]- }-- if (word === "context-permission-request") {-- const permission = parsePermissionName(rest[1])-- return [await this.requestPermission(process.identity, String(rest[0]), permission, rest[2] as PermissionRequest<typeof permission>)]- }-if (word === "program-permissions") {const program = heldProgram(rest[0])- access.requireAll()const operation = rest[1]if (operation === "all") return [this.authManager.programManager.permissions(program)]@@ -1908,25 +1891,40 @@ export default class ProcessManager extends TheLink {return [this.authManager.programManager.allowsPermission(program, permission, rest[3] as PermissionRequest<typeof permission>)]}- if (operation === "set") {+ if (operation === "allow") {+ access.requireAll()const permission = parsePermissionName(rest[2])await this.authManager.programManager.setPermission(program,permission,- rest[3] as Exclude<PermissionInput<typeof permission>, null>+ rest[3] as PermissionRequest<typeof permission>)return []}- if (operation === "delete") {+ if (operation === "deny") {- await this.authManager.programManager.deletePermission(program, parsePermissionName(rest[2]))+ access.requireAll()+ await this.authManager.programManager.setPermission(program, parsePermissionName(rest[2]), false)return []}+ if (operation === "request") {++ if (typeof rest[2] !== "string") throw new Error("A permission request needs a unique identity")+ const permission = parsePermissionName(rest[3])++ return [await this.authManager.programManager.requestPermission(+ program,+ rest[2],+ permission,+ rest[4] as PermissionRequest<typeof permission>,+ process+ )]+ }throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)}@@ -1937,20 +1935,16 @@ export default class ProcessManager extends TheLink {return [await this.system.programAgent(program)]}- if (word === "current-process") return [processReference(process)]-- if (word === "icon") {+ if (word === "program-definition") {- return [await this.system.programIcon(heldProgram(rest[0]), rest[1])]+ return [await this.system.programDefinition(heldProgram(rest[0]))]}- if (word === "launch") {-- const program = heldProgram(rest[0])+ if (word === "current-process") return [processReference(process)]- const value = rest[1] === "set" ? access.launch(rest[2]) : rest[2]+ if (word === "icon") {- return [await this.system.programLaunch(program, String(rest[1]), value)]+ return [await this.system.programIcon(heldProgram(rest[0]), rest[1])]}if (word === "startup") {@@ -1962,6 +1956,13 @@ export default class ProcessManager extends TheLink {return [await this.system.programStartup(program, String(rest[1]), value)]}+ if (word === "pinned") {++ const operation = rest[1]+ if (operation !== "get" && operation !== "pin" && operation !== "unpin") throw new Error(`The System does not know the pinned operation "${String(operation)}"`)+ return [await this.system.programPinned(heldProgram(rest[0]), operation)]+ }+// Which exact process made this one through `program.createProcess()`.// Parentage is immutable lineage; liveness belongs to the returned// Process handle rather than to this relationship.@@ -2158,7 +2159,9 @@ export default class ProcessManager extends TheLink {if (word === "service-wait-ready") return [await this.services.waitReady(heldService(rest[0]), rest[1])]- if (word === "service-program-metadata") return [await this.serviceProgramMetadata(heldService(rest[0]), rest[1] as ProgramIconSize | undefined)]+ if (word === "service-program-metadata") return [await this.serviceProgramMetadata(heldService(rest[0]))]++ if (word === "service-program-icon") return [await this.serviceProgramIcon(heldService(rest[0]), rest[1] as ProgramIconSize | undefined)]if (word === "service-follow") {@@ -2738,6 +2741,13 @@ export default class ProcessManager extends TheLink {// wire carries one value, so the list is that value. A// program's own endpoint answers a value directly; these are// the two shapes and they meet here.+ if (args[0] === "program-permissions" && args[2] === "request" && typeof args[3] === "string") {++ // A timed SDK request forgets its transport question. Retain+ // the matching dialog cancellation at that same boundary.+ server.retain(question, () => { this.cancelPermission(process.identity, args[3] as string).catch(() => undefined) })+ }+const result = await this.endHost(process, server, args)this.say(server, "host-end", "answer", question, succeeded(result))diff --git a/source/server/core/link-manager/auth-manager/process-manager/process.ts b/source/server/core/link-manager/auth-manager/process-manager/process.tsindex e2f9b75..04e16cb 100644--- a/source/server/core/link-manager/auth-manager/process-manager/process.ts+++ b/source/server/core/link-manager/auth-manager/process-manager/process.ts@@ -14,7 +14,7 @@ import type { ServerRuntime } from "@server/core/server-runtime"** Its immutable options are the launch state carried by this particular* life. They are available to either half without becoming part of the- * Program declaration that later launches inherit.+ * Program definition that later launches inherit.** Endpoint presence is mutable live state. Each start creates a fresh* execution context; each stop removes that context's boundary and everything@@ -314,7 +314,7 @@ export default class Process {/** Whether this Process's Program declared a Client Endpoint. */clientEndpoint: this.clientEndpoint !== null,- // These are live endpoint snapshots. Program declarations answer+ // These are live endpoint snapshots. Program definitions answer// which endpoint kinds can be started.server: this.server ? { service: this.server.service } : null,diff --git a/source/server/core/link-manager/auth-manager/program-manager/launch-storage.ts b/source/server/core/link-manager/auth-manager/program-manager/launch-storage.tsdeleted file mode 100644index a293c65..0000000--- a/source/server/core/link-manager/auth-manager/program-manager/launch-storage.ts+++ /dev/null@@ -1,56 +0,0 @@-import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"-import { randomUUID } from "node:crypto"-import { join } from "node:path"-import { isDeepStrictEqual } from "node:util"-import { parseLaunch, type Launch } from "@phreshos/core"-import type Program from "./program"--/** Persistent launch intent, without resolving Program defaults or executing it. */-export default class LaunchStorage {- public constructor(private readonly program: Program, private readonly name: "startup" | "launch") {}-- public get(): Launch | null {- if (!existsSync(this.path)) return null- return parseLaunch(JSON.parse(readFileSync(this.path, "utf8")))- }-- public set(launch: Launch) {- const parsed = parseLaunch(launch)- let current: Launch | null = null-- try { current = this.get() }- catch { /* A valid replacement repairs an invalid stored declaration. */ }-- if (isDeepStrictEqual(current, parsed)) return-- this.write(`${JSON.stringify(parsed, null, 2)}\n`)- }-- /** Replace one declaration, retaining exact bytes for operation rollback. */- public replace(launch: Launch) {- const previous = existsSync(this.path) ? readFileSync(this.path) : null- this.set(launch)- return () => {- if (previous === null) this.remove()- else this.write(previous)- }- }-- public remove() {- rmSync(this.path, { force: true })- }-- private get path() {- return join(this.program.storagePath, `${this.name}.json`)- }-- private write(content: string | Uint8Array) {- mkdirSync(this.program.storagePath, { recursive: true })- const temporary = join(this.program.storagePath, `.${this.name}.json.${randomUUID()}`)- try {- writeFileSync(temporary, content)- renameSync(temporary, this.path)- }- finally { rmSync(temporary, { force: true }) }- }-}diff --git a/source/server/core/link-manager/auth-manager/program-manager/permissions.ts b/source/server/core/link-manager/auth-manager/program-manager/permissions.tsdeleted file mode 100644index 10f3b8f..0000000--- a/source/server/core/link-manager/auth-manager/program-manager/permissions.ts+++ /dev/null@@ -1,63 +0,0 @@-import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"-import { randomUUID } from "node:crypto"-import { join } from "node:path"-import type Program from "./program"-import { permissionCatalog } from "@server/core/permissions"-import type { Permissions } from "@phreshos/core"--const file = "permissions.json"--/** Applies declared entries, retaining unrelated stored permissions and rollback bytes. */-export function applyDeclaredPermissions(program: Program): (() => void) | undefined {- const declared = program.declaredPermissions- if (Object.keys(declared).length === 0) return undefined-- const path = join(program.storagePath, file)- const previous = existsSync(path) ? readFileSync(path) : null- const stored = previous === null ? {} : permissionCatalog.stored(JSON.parse(previous.toString("utf8")))- writePermissions(program, { ...stored, ...declared })-- return () => {- if (previous === null) rmSync(path, { force: true })- else atomicWrite(program.storagePath, path, previous)- }-}--/** Reads one Program's authoritative permission state. */-export function readPermissions(program: Program): Permissions {-- const path = join(program.storagePath, file)-- if (!existsSync(path)) return {}-- try { return permissionCatalog.stored(JSON.parse(readFileSync(path, "utf8"))) }-- catch (exception) {-- if (exception instanceof SyntaxError) throw new Error("The Program permissions file is invalid")-- throw exception- }-}--/** Atomically replaces one Program's authoritative permission state. */-export function writePermissions(program: Program, permissions: Permissions) {-- const directory = program.storagePath- const path = join(directory, file)- atomicWrite(directory, path, Buffer.from(`${JSON.stringify(permissions, null, 2)}\n`))-}--function atomicWrite(directory: string, path: string, content: Uint8Array) {-- mkdirSync(directory, { recursive: true })-- const temporary = join(directory, `.${file}.${randomUUID()}`)-- try {-- writeFileSync(temporary, content)- renameSync(temporary, path)- }- finally { rmSync(temporary, { force: true }) }-}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 ee47bd1..46cb8e0 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@@ -18,9 +18,8 @@ import Program, { type CommandOutput, type InstallOutput } from "./program"import Entry, { type ProgramRecord } from "./entry"import Keyv from "keyv"import { isIconSize, ProgramIcons } from "./icon"-import LaunchStorage from "./launch-storage"import { permissionCatalog } from "@server/core/permissions"-import { applyDeclaredPermissions, readPermissions, writePermissions } from "./permissions"+import ProgramStateStorage from "./state"import {parsePermissionName,type Permission,@@ -35,7 +34,6 @@ import { windowLayerDefaults } from "@shared/window-layers"const maximumProcessesPerProgram = 20type Registration = {- origin: "creation" | "reconstruction"installed: booleantransitionOwnsIdentity?: booleanrestoreInstalled?: boolean@@ -122,7 +120,7 @@ export default class ProgramManager extends TheLink {try {- await this.register(new Program(declaration), { origin: "reconstruction", installed: true, transitionOwnsIdentity: true })+ await this.register(new Program(declaration), { installed: true, transitionOwnsIdentity: true })}catch (exception) { console.log(`programs: ${found.name} was not read — ${exception instanceof Error ? exception.message : "unreadable"}`) }@@ -166,19 +164,19 @@ export default class ProgramManager extends TheLink {return entry}- /** Reads one Program's authoritative value for an exact permission. */+ /** Resolve one permission from state first, then the Program definition. */public permission<Name extends PermissionName>(program: Program, name: Name): Permission<Name> {- return clonePermission(readPermissions(program)[name] ?? null)+ return clonePermission(this.permissions(program)[name] ?? null)}- /** Returns an independent snapshot of one Program's permission state. */+ /** Returns an independent effective snapshot without writing definition fallbacks to state. */public permissions(program: Program): Permissions {- return clonePermissions(readPermissions(program))+ return clonePermissions({ ...program.declaredPermissions, ...new ProgramStateStorage(program).permissions() })}- /** Tests one requested value against this Program's stored permissions. */+ /** Tests one requested value against this Program's effective permissions. */public allowsPermission<Name extends PermissionName>(program: Program,name: Name,@@ -189,7 +187,7 @@ export default class ProgramManager extends TheLink {if (!Array.isArray(requested)) throw new Error("A permission check must be true or a list of values")- const permissions = readPermissions(program)+ const permissions = this.permissions(program)return permissionCatalog.allows(name,@@ -198,7 +196,7 @@ export default class ProgramManager extends TheLink {)}- /** Tests one request against this Program's authoritative stored permission. */+ /** Tests one request against this Program's effective permission. */public grantsPermission<Name extends PermissionName>(program: Program,name: Name,@@ -208,7 +206,7 @@ export default class ProgramManager extends TheLink {return permissionCatalog.allows(name,requested,- readPermissions(program)+ this.permissions(program))}@@ -232,58 +230,97 @@ export default class ProgramManager extends TheLink {if (value === null) throw new Error("A stored Program permission cannot be null")- const permissions = readPermissions(program)- const before = permissions[name] ?? null+ const state = new ProgramStateStorage(program)+ const stored = state.permissions()+ const before = stored[name]const permission = permissionCatalog.resolve(name, value)- if (permissionCatalog.changed(before, permission)) {+ if (permission === null) throw new Error("A stored Program permission cannot be null")+ if (before === undefined || permissionCatalog.changed(before, permission)) {- writePermissions(program, { ...permissions, [name]: permission })+ const previousAll = this.permission(program, "all")+ state.setPermission(name, permission)- if (name === "all") await this.authManager.processManager.updateClientAccess(program)+ if (name === "all" && permissionCatalog.changed(previousAll, this.permission(program, "all"))) {+ await this.authManager.processManager.updateClientAccess(program)+ }}}- /** Removes one permission assignment from authoritative state. */- public async deletePermission<Name extends PermissionName>(program: Program, name: Name): Promise<void> {+ /** Requests one owner decision for this target Program, independently of its initiator. */+ public async requestPermission<Name extends PermissionName>(+ program: Program,+ request: string,+ name: Name,+ input: PermissionRequest<Name>,+ process: Process | null = null+ ): Promise<Permission<Name>> {++ const requested = permissionCatalog.resolve(name, input)++ if (!Array.isArray(requested)) throw new Error("A permission request must be true or a list of values")- const permissions = readPermissions(program)- if (Object.hasOwn(permissions, name)) {+ const choice = await this.authManager.dialogManager.requestPermission(program, request, name, requested, process)- delete permissions[name]- writePermissions(program, permissions)+ if (choice === true) {- if (name === "all") await this.authManager.processManager.updateClientAccess(program)+ await this.setPermission(program, name, requested)++ return requested}++ return choice}@Connect("/permissions")- protected async programPermissions(subject: unknown, operation: unknown, name?: unknown, value?: unknown) {+ protected async programPermissions(subject: unknown, operation: unknown, first?: unknown, second?: unknown, third?: unknown) {const program = this.held(subject)if (operation === "all") return this.permissions(program)- if (operation === "get") return this.permission(program, parsePermissionName(name))+ if (operation === "get") return this.permission(program, parsePermissionName(first))if (operation === "allows") {- const permission = parsePermissionName(name)+ const permission = parsePermissionName(first)- return this.allowsPermission(program, permission, value as PermissionRequest<typeof permission>)+ return this.allowsPermission(program, permission, second as PermissionRequest<typeof permission>)}- if (operation === "set") {+ if (operation === "allow") {- const permission = parsePermissionName(name)+ const permission = parsePermissionName(first)- await this.setPermission(program, permission, value as Exclude<PermissionInput<typeof permission>, null>)+ await this.setPermission(program, permission, second as PermissionRequest<typeof permission>)return}- if (operation === "delete") {+ if (operation === "deny") {- await this.deletePermission(program, parsePermissionName(name))+ await this.setPermission(program, parsePermissionName(first), false)return}+ if (operation === "request") {++ if (typeof first !== "string") throw new Error("A permission request needs a unique identity")++ const permission = parsePermissionName(second)+ const signal = this.authManager.connectionSignal()+ const cancel = () => { this.authManager.dialogManager.cancelPermission(first).catch(() => undefined) }++ signal.addEventListener("abort", cancel, { once: true })++ try {+ return await this.requestPermission(program, first, permission, third as PermissionRequest<typeof permission>)+ }+ finally {+ signal.removeEventListener("abort", cancel)+ }+ }+ if (operation === "cancel-request") {++ if (typeof first === "string") await this.authManager.dialogManager.cancelPermission(first)+ return+ }throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)}@@ -305,10 +342,10 @@ export default class ProgramManager extends TheLink {return await this.startup(this.held(subject), operation, value)}- @Connect("/launch")- protected async savedProgramLaunch(subject: unknown, operation: string, value?: unknown) {+ @Connect("/pinned")+ protected async pinnedProgram(subject: unknown, operation: "get" | "pin" | "unpin") {- return await this.launch(this.held(subject), operation, value)+ return await this.pinned(this.held(subject), operation)}public reach(identity: string) {@@ -349,7 +386,7 @@ export default class ProgramManager extends TheLink {// absolute itself.public async create(source: ProgramDefinition | string) {- const entry = await this.register(this.runtimeProgram(source), { origin: "creation", installed: false })+ const entry = await this.register(this.runtimeProgram(source), { installed: false })await this.created(entry)@@ -367,8 +404,7 @@ export default class ProgramManager extends TheLink {// that currently owns this public identity.await program.validate()- this.declaredLaunch(program, "startup")- this.declaredLaunch(program, "launch")+ this.installLaunch(program)return await this.change(program.identity, async () => {@@ -381,7 +417,7 @@ export default class ProgramManager extends TheLink {await this.forgetEntry(existing, false)}- const entry = this.remember(program, { origin: "creation", installed: false, transitionOwnsIdentity: true, restoreInstalled })+ const entry = this.remember(program, { installed: false, transitionOwnsIdentity: true, restoreInstalled })try {@@ -436,15 +472,16 @@ export default class ProgramManager extends TheLink {private async register(program: Program, registration: Registration) {await program.validate()+ this.installLaunch(program)return this.remember(program, registration)}/** Commit one already validated Program to the authoritative registry. */- private remember(program: Program, { origin, installed, transitionOwnsIdentity = false, restoreInstalled = false }: Registration) {+ private remember(program: Program, { installed, transitionOwnsIdentity = false, restoreInstalled = false }: Registration) {// The runtime map is the live registry, while an installed- // declaration is the durable reservation reconstructed on boot.+ // definition is the durable reservation reconstructed on boot.// Forgetting an installed Program removes the former but cannot// make its identity available to ordinary creation while the// latter still exists. Attached replacement is the one transition@@ -453,10 +490,6 @@ export default class ProgramManager extends TheLink {const entry = new Entry(program, installed, restoreInstalled)- // Creation applies declaration decisions before publishing the Program.- // Reconstruction reads its authoritative stored state without writes.- if (origin === "creation") this.applyDeclaration(program)-this.programs.set(entry.identity, entry)return entry@@ -616,60 +649,30 @@ export default class ProgramManager extends TheLink {return this.held(subject).agent()}- private declaredLaunch(program: Program, name: "startup" | "launch") {- const value = program.config[name]+ /** Reads the canonical definition owned by one exact Program handle. */+ @Connect("/definition")+ public async definition(subject: unknown) {++ return this.held(subject).definition()+ }++ /** Resolve the one launch owned by installation without persisting it as Program state. */+ private installLaunch(program: Program) {+ const value = program.config.installLaunchif (value === undefined) return undefinedconst launch = parseLaunch(value === true ? {} : value)this.resolveLaunch(program, launch)return launch}- /** Applies creation/installation decisions to this Program's storage as one reversible unit. */- private applyDeclaration(program: Program) {- const startup = this.declaredLaunch(program, "startup")- const launch = this.declaredLaunch(program, "launch")- const rollbacks: (() => void)[] = []- const rollback = () => {- for (let index = rollbacks.length - 1; index >= 0; index--) rollbacks[index]!()- }- try {- const permissions = applyDeclaredPermissions(program)- if (permissions) rollbacks.push(permissions)- if (startup !== undefined) rollbacks.push(new LaunchStorage(program, "startup").replace(startup))- if (launch !== undefined) rollbacks.push(new LaunchStorage(program, "launch").replace(launch))- return rollback- }- catch (error) {- rollback()- throw error- }- }-- /** Read or replace the saved icon launch without executing it. */- public async launch(program: Program, operation: string, value?: unknown): Promise<Launch | null | void> {- const storage = new LaunchStorage(program, "launch")- if (operation === "get") {- const launch = storage.get()- if (launch !== null) this.resolveLaunch(program, launch)- return launch- }- if (operation === "set") {- const launch = parseLaunch(value)- this.resolveLaunch(program, launch)- storage.set(launch)- return- }- throw new Error(`The host does not know the launch operation "${operation}"`)- }-/** Read or change the system-managed startup launch for one Program. */public async startup(program: Program, operation: string, value?: unknown): Promise<Launch | null | void> {- const storage = new LaunchStorage(program, "startup")+ const state = new ProgramStateStorage(program)if (operation === "get") {- const launch = storage.get()+ const launch = state.startup()if (launch === null) return null@@ -685,14 +688,18 @@ export default class ProgramManager extends TheLink {const launch = parseLaunch(value === undefined ? {} : value)this.resolveLaunch(program, launch)- storage.set(launch)+ // Startup is a resulting state: repeating the same request must+ // not rewrite system-managed Program state.+ if (isDeepStrictEqual(state.startup(), launch)) return+ state.setStartup(launch)return}if (operation === "disable") {- storage.remove()+ if (state.startup() === null) return+ state.setStartup(null)return}@@ -700,6 +707,22 @@ export default class ProgramManager extends TheLink {throw new Error(`The host does not know the startup operation "${operation}"`)}+ /** Read or change the pinned state and publish only effective transitions. */+ public async pinned(program: Program, operation: "get" | "pin" | "unpin"): Promise<boolean> {+ const state = new ProgramStateStorage(program)+ const current = state.pinned()+ if (operation === "get") return current++ const pinned = operation === "pin"+ if (current === pinned) return current++ state.setPinned(pinned)+ const entry = this.find(program.identity)+ await this.authManager.processManager.announceHost("program", "pinned", entry.identity, entry, pinned)+ await this.$outbound.publish("/pinned", entry.record(), pinned)+ return pinned+ }+// A store's five controls, in one place. Reached from a process// over its own channel and from a session over the link, and both// must mean the same thing. The exact handle always names a Program;@@ -1051,8 +1074,6 @@ export default class ProgramManager extends TheLink {let createdHere = false- let restoreSettings: (() => void) | undefined-let purgedStorage = falsetry {@@ -1067,9 +1088,11 @@ export default class ProgramManager extends TheLink {// because they are wherever the system puts them.const stagedProgram = new Program(join(staged, "program.json"))await stagedProgram.validate()- this.declaredLaunch(stagedProgram, "startup")- this.declaredLaunch(stagedProgram, "launch")- const requestedLaunch = decision.launch === true ? {} : decision.launch+ const declaredInstallLaunch = this.installLaunch(stagedProgram)+ const selectedLaunch = decision.launch === undefined ? declaredInstallLaunch : decision.launch+ const requestedLaunch = selectedLaunch === false || selectedLaunch === undefined+ ? undefined+ : selectedLaunch === true ? {} : selectedLaunchif (requestedLaunch !== undefined) this.resolveLaunch(stagedProgram, requestedLaunch)swapping = true@@ -1102,8 +1125,6 @@ export default class ProgramManager extends TheLink {if (entry) {- restoreSettings = this.applyDeclaration(installed)-entry.program.replace(installed)entry.installed = true@@ -1113,7 +1134,7 @@ export default class ProgramManager extends TheLink {else {- entry = await this.register(installed, { origin: "creation", installed: true, transitionOwnsIdentity: true })+ entry = await this.register(installed, { installed: true, transitionOwnsIdentity: true })createdHere = true}@@ -1135,25 +1156,15 @@ export default class ProgramManager extends TheLink {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)- }- catch (exception) {- await output({ stream: "stderr", text: `Program installed, but startup failed: ${exception instanceof Error ? exception.message : String(exception)}\n` })- }-return entry}catch (exception) {- // Restore the prior files, declaration settings, and any storage+ // Restore the prior files, definition 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 })@@ -1268,7 +1279,7 @@ export default class ProgramManager extends TheLink {if (existsSync(declaration)) {- const installed = await this.register(new Program(declaration), { origin: "reconstruction", installed: true, transitionOwnsIdentity: true })+ const installed = await this.register(new Program(declaration), { installed: true, transitionOwnsIdentity: true })await this.created(installed)}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.tsindex 51510ce..a545a42 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, normalize, relative, resolve, sep } from "node:patimport { spawn } from "node:child_process"import { randomUUID } from "node:crypto"import { validateIcon } from "./icon"-import { defaultProgramVersion, parseLaunch, parseProgramDefinition, parseWindowFrame, parseWindowTransaction, type ProgramCommandChunk, type ProgramSnapshot } from "@phreshos/core"+import { defaultProgramVersion, parseLaunch, parseProgramDefinition, parseWindowFrame, parseWindowTransaction, type ProgramCommandChunk, type ProgramDefinition, type ProgramSnapshot } from "@phreshos/core"import { permissionCatalog, type DeclaredPermissions } from "@server/core/permissions"/**@@ -108,7 +108,7 @@ export default class Program {} : null}- /** Canonical permission entries applied to storage at creation and installation. */+ /** Canonical permission fallback requested by this Program definition. */public get declaredPermissions(): DeclaredPermissions {return permissionCatalog.declarations(this.config.permissions)@@ -168,6 +168,21 @@ export default class Program {return readFileSync(this.agentPath, "utf-8")}+ /** Returns the complete public definition represented by this Program. */+ public definition(): ProgramDefinition {++ // Stored installation paths are relative to program.json, while a+ // returned definition must remain valid as direct Program creation input.+ return parseProgramDefinition({+ ...this.config,+ storage: this.storagePath,+ ...(this.iconPath ? { icon: this.iconPath } : {}),+ ...(this.agentPath ? { agent: this.agentPath } : {}),+ ...(this.config.server ? { server: { ...this.config.server, location: this.serverPath! } } : {}),+ ...(this.config.client ? { client: { ...this.config.client, location: this.clientUrl ?? this.clientPath! } } : {})+ })+ }+/** SDK Program record; internal references are consumed by the SDK boundary. */public record() {@@ -325,9 +340,7 @@ function storedDefinition(value: unknown): ProgramConfig {// not whether they are true.function coherent(config: ProgramConfig) {- for (const value of [config?.startup, config?.launch]) {- if (value !== undefined && value !== true) parseLaunch(value)- }+ if (config?.installLaunch !== undefined && config.installLaunch !== true) parseLaunch(config.installLaunch)// A name is also the name of a directory, so it is checked as a path// component before it is anything else — a program calling itselfdiff --git a/source/server/core/link-manager/auth-manager/program-manager/state.ts b/source/server/core/link-manager/auth-manager/program-manager/state.tsnew file mode 100644index 0000000..23f75ed--- /dev/null+++ b/source/server/core/link-manager/auth-manager/program-manager/state.ts@@ -0,0 +1,80 @@+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"+import { randomUUID } from "node:crypto"+import { join } from "node:path"+import { parseLaunch, type Launch, type Permission, type PermissionName, type Permissions } from "@phreshos/core"+import { permissionCatalog } from "@server/core/permissions"+import type Program from "./program"++const file = "state.json"++/** System-managed Program state sharing one atomic persistence boundary. */+export default class ProgramStateStorage {++ public constructor(private readonly program: Program) {}++ public startup(): Launch | null {+ const value = this.read().startup+ return value === undefined ? null : parseLaunch(value)+ }++ public setStartup(value: Launch | null) {+ this.change(state => {+ if (value === null) delete state.startup+ else state.startup = parseLaunch(value)+ })+ }++ public permissions(): Permissions {+ return permissionCatalog.stored(this.read().permissions ?? {})+ }++ public setPermission<Name extends PermissionName>(name: Name, value: Exclude<Permission<Name>, null>) {+ this.change(state => {+ const permissions = permissionCatalog.stored(state.permissions ?? {})+ state.permissions = { ...permissions, [name]: value }+ })+ }++ public pinned(): boolean {+ const value = this.read().pinned+ if (value === undefined) return false+ if (typeof value !== "boolean") throw new Error("The Program state contains an invalid pinned value")+ return value+ }++ public setPinned(value: boolean) {+ this.change(state => { state.pinned = value })+ }++ private read(): Record<string, unknown> {+ const path = join(this.program.storagePath, file)+ if (!existsSync(path)) return {}++ try {+ const value: unknown = JSON.parse(readFileSync(path, "utf8"))+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error()+ return { ...value }+ }+ catch {+ throw new Error("The Program state file is invalid")+ }+ }++ private change(change: (state: Record<string, unknown>) => void) {+ const state = this.read()+ change(state)++ const directory = this.program.storagePath+ const path = join(directory, file)+ const temporary = join(directory, `.${file}.${randomUUID()}`)++ // Sibling state fields must cross one atomic boundary so an interrupted+ // startup or permission change cannot discard independently owned state.+ mkdirSync(directory, { recursive: true })+ try {+ writeFileSync(temporary, `${JSON.stringify(state, null, 2)}\n`)+ renameSync(temporary, path)+ }+ finally { rmSync(temporary, { force: true }) }+ }+}diff --git a/source/server/core/link-manager/link-manager.ts b/source/server/core/link-manager/link-manager.tsindex 15b3220..d24a303 100644--- a/source/server/core/link-manager/link-manager.ts+++ b/source/server/core/link-manager/link-manager.ts@@ -313,7 +313,7 @@ export default class LinkManager extends TheLink {for (const { link } of this.boundaries.values()) await link.$outbound.publish(event, ...values)}- /** Persist and publish one authorized Appearance replacement in call order. */+ /** Merge, persist, and publish one authorized Appearance update in call order. */public updateAppearance(value: unknown) {const update = this.updatingAppearance.then(async () => {diff --git a/source/server/core/permissions.ts b/source/server/core/permissions.tsindex 4040d92..e22fd67 100644--- a/source/server/core/permissions.ts+++ b/source/server/core/permissions.ts@@ -123,9 +123,11 @@ export class PermissionCatalog {if (!Object.hasOwn(programPermissionCatalog, unknownName)) continueconst name = parsePermissionName(unknownName)- if (assignment === true) throw new Error("The Program permissions file contains unresolved shorthand")+ if (assignment === true) throw new Error("The Program permissions state contains unresolved shorthand")- permissions[name] = this.resolve(name, assignment)+ const permission = this.resolve(name, assignment)+ if (permission === null) throw new Error("The Program permissions state cannot contain an absent assignment")+ permissions[name] = permission}return permissions as Permissionsdiff --git a/source/server/core/server-runtime/factory.ts b/source/server/core/server-runtime/factory.tsindex 3eaec28..c709993 100644--- a/source/server/core/server-runtime/factory.ts+++ b/source/server/core/server-runtime/factory.ts@@ -4,7 +4,7 @@ import CommandServerRuntime from "./command"import SandboxServerRuntime from "./sandbox"import WorkerServerRuntime from "./worker"-/** Creates the Core-owned execution adapter selected by a Program declaration. */+/** Creates the Core-owned execution adapter selected by a Program definition. */export default function createServerRuntime(program: Program): ServerRuntime {const server = program.serverdiff --git a/source/server/core/system.ts b/source/server/core/system.tsindex 11ca8bc..c5f56a7 100644--- a/source/server/core/system.ts+++ b/source/server/core/system.ts@@ -109,11 +109,6 @@ export default class System {return this.programManager.setPermission(program, name, permission)}- public deleteProgramPermission<Name extends PermissionName>(program: Program, name: Name) {-- return this.programManager.deletePermission(program, name)- }-public listProcesses(program?: Program) {return [...this.processManager.processes.values()].filter(process => !program || process.program === program)@@ -463,14 +458,19 @@ export default class System {return this.programManager.agent(program)}+ public programDefinition(program: Program) {++ return this.programManager.definition(program)+ }+public programStartup(program: Program, operation: string, value?: unknown) {return this.programManager.startup(program, operation, value)}- public programLaunch(program: Program, operation: string, value?: unknown) {+ public programPinned(program: Program, operation: "get" | "pin" | "unpin") {- return this.programManager.launch(program, operation, value)+ return this.programManager.pinned(program, operation)}public programInstalled(program: Program) {diff --git a/tests/appearance.test.ts b/tests/appearance.test.tsindex a2709db..206c35c 100644--- a/tests/appearance.test.ts+++ b/tests/appearance.test.ts@@ -44,6 +44,11 @@ test("appearance contract", async () => {assert.equal(await manager.update(defaultAppearance), initial)assert.equal(manager.value, initial)+ await manager.update({ colors: { dark: { danger: "#ff0000" } } })+ assert.equal(manager.value.colors.dark.danger, "#ff0000")+ assert.deepEqual(manager.value.colors.light, initial.colors.light)+ assert.deepEqual(manager.value.material, initial.material)+for (const theme of ["light", "dark"] as const) {for (const role of ["background", "foreground", "primary", "secondary", "success", "warning", "danger", "info"] as const) {const color = "oklch(60% 0.2 260)"diff --git a/tests/client-layer-permissions.test.ts b/tests/client-layer-permissions.test.tsindex ee3df13..ffbe786 100644--- a/tests/client-layer-permissions.test.ts+++ b/tests/client-layer-permissions.test.ts@@ -17,7 +17,6 @@ function fixture() {const createProcess = vi.fn(async () => process.identity)const findOrCreateProcess = vi.fn(async () => process.identity)const startup = vi.fn()- const savedLaunch = vi.fn()const startEndpoint = vi.fn()const connections = [{ identity: "desktop-connection", connected: true, session: "desktop-session" },@@ -44,14 +43,14 @@ function fixture() {})const command = vi.fn(async function* () {})const auth = {- programManager: { programs: new Map([[program.identity, program]]), createProcess, findOrCreateProcess, startup, launch: savedLaunch, command },+ programManager: { programs: new Map([[program.identity, program]]), createProcess, findOrCreateProcess, startup, command },processManager: { processes: new Map([[process.identity, process]]), startEndpoint, ownFrame: vi.fn(), releaseFrame: vi.fn() },connection, session,grantsPermission: async <Name extends PermissionName>(_pane: string, name: Name, values: readonly PermissionValue<Name>[]) => permissionCatalog.allows(name, values, permissions)} as unknown as AuthManagerconst answer = host(auth, process.identity, () => ({ size: { width: 100, height: 100 } }), () => "frame", {} as never)return {- auth, program, process, answer, createProcess, findOrCreateProcess, startup, savedLaunch, startEndpoint, command, connection,+ auth, program, process, answer, createProcess, findOrCreateProcess, startup, startEndpoint, command, connection,permissions(value: Permissions) { permissions = value }}}@@ -67,7 +66,6 @@ test.each(restrictedLayers)("Client launch routes check %s before delegation", a["program-create-process", program, launch],["program-find-or-create-process", program, launch],["startup", program, "enable", launch],- ["launch", program, "set", launch],["start-endpoint", process, "client", { layer }]] as constconst anotherLayer = restrictedLayers.find(candidate => candidate !== layer)!@@ -76,7 +74,7 @@ test.each(restrictedLayers)("Client launch routes check %s before delegation", af.permissions(denied)for (const [operation, ...args] of operations) await expect(f.answer(operation, ...args)).rejects.toThrow("Execution is not permitted")}- const delegates = [f.createProcess, f.findOrCreateProcess, f.startup, f.savedLaunch, f.startEndpoint]+ const delegates = [f.createProcess, f.findOrCreateProcess, f.startup, f.startEndpoint]for (const delegate of delegates) expect(delegate).not.toHaveBeenCalled()const grantedPermissions: Permissions[] = [{ layers: [layer] }, { layers: [] }, { all: [] }]for (const granted of grantedPermissions) {diff --git a/tests/client-permission-boundary.test.ts b/tests/client-permission-boundary.test.tsindex 2c002e5..880fca5 100644--- a/tests/client-permission-boundary.test.ts+++ b/tests/client-permission-boundary.test.ts@@ -67,6 +67,36 @@ test("Program and Process discovery exposes only the accessible scope", async ()await expect(answer("host-process-find", hidden.identity)).resolves.toEqual([expect.objectContaining({ identity: hidden.identity })])})+test("Program permission reads and requests require Program access while direct mutation alone requires all", async () => {+ let permissions: Permissions = { programs: ["outside"] }+ const owner = program("owner")+ const outside = program("outside")+ const current = process("current", owner)+ const read = vi.fn(async (_address, operation: string) => operation === "all"+ ? { network: ["https://example.com"] }+ : ["https://example.com"])+ const requestPermission = vi.fn(async () => ["https://example.com"])+ const auth = {+ programManager: { programs: new Map([[owner.identity, owner], [outside.identity, outside]]), permissions: read },+ processManager: { processes: new Map([[current.identity, current]]) },+ grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions),+ requestPermission+ } as unknown as AuthManager+ const answer = host(auth, current.identity, () => { throw new Error("unused viewport") }, () => null, {} as never)+ const target = { identity: outside.identity, reference: outside.reference }++ await expect(answer("program-permissions", target, "get", "network")).resolves.toEqual([["https://example.com"]])+ await expect(answer("program-permissions", target, "all")).resolves.toEqual([{ network: ["https://example.com"] }])+ await expect(answer("program-permissions", target, "request", "request", "network", ["https://example.com"])).resolves.toEqual([["https://example.com"]])+ expect(requestPermission).toHaveBeenCalledWith("current", target, "request", "network", ["https://example.com"])+ await expect(answer("program-permissions", target, "allow", "network", ["https://example.com"])).rejects.toThrow("Execution is not permitted")+ await expect(answer("program-permissions", target, "deny", "network")).rejects.toThrow("Execution is not permitted")++ permissions = { all: [] }+ await expect(answer("program-permissions", target, "allow", "network", ["https://example.com"])).resolves.toEqual([])+ await expect(answer("program-permissions", target, "deny", "network")).resolves.toEqual([])+})+test.each([{owningProgram: "owner",@@ -98,7 +128,8 @@ test.each([let permissions: Permissions = {}const serviceAvailable = vi.fn(async () => true)const waitServiceReady = vi.fn()- const serviceProgramMetadata = vi.fn(async () => ({ name: "Provider", version: "0.0.0", icon: [] }))+ const serviceProgramMetadata = vi.fn(async () => ({ name: "Provider", version: "0.0.0" }))+ const serviceProgramIcon = vi.fn(async () => [])const followService = vi.fn()const sendService = vi.fn()const askService = vi.fn()@@ -109,7 +140,7 @@ test.each([["caller", { program: "owner" }],[destination, { program: owningProgram }]]),- serviceAvailable, waitServiceReady, serviceProgramMetadata, followService, sendService, askService+ serviceAvailable, waitServiceReady, serviceProgramMetadata, serviceProgramIcon, followService, sendService, askService},grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)} as unknown as AuthManager@@ -118,7 +149,8 @@ test.each([const operations = [["service-available", key],["service-wait-ready", key],- ["service-program-metadata", key, "small"],+ ["service-program-metadata", key],+ ["service-program-icon", key, "small"],["service-send", key, "change", {}],["service-ask", key, "read", {}]] as const@@ -134,7 +166,7 @@ test.each([for (const [operation, ...args] of operations) await answer(operation, ...args)await answer("service-follow", "subscription", key, "events", "change")}- for (const call of [serviceAvailable, waitServiceReady, serviceProgramMetadata, followService, sendService, askService]) {+ for (const call of [serviceAvailable, waitServiceReady, serviceProgramMetadata, serviceProgramIcon, followService, sendService, askService]) {expect(call).toHaveBeenCalledTimes(granted.length)}})diff --git a/tests/permission-requests.test.ts b/tests/permission-requests.test.tsindex 2ba332f..d04212d 100644--- a/tests/permission-requests.test.ts+++ b/tests/permission-requests.test.ts@@ -2,14 +2,14 @@ import assert from "node:assert/strict"import { mkdtempSync, rmSync } from "node:fs"import { tmpdir } from "node:os"import { join } from "node:path"-import type { PermissionName, PermissionRequest } from "@phreshos/core"+import type { Permission, PermissionName, PermissionRequest } from "@phreshos/core"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 ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"import Process from "@server/core/link-manager/auth-manager/process-manager/process"import Window from "@server/core/link-manager/auth-manager/process-manager/window"import type HostTraffic from "@server/core/link-manager/auth-manager/process-manager/host-traffic"-import { readPermissions, writePermissions } from "@server/core/link-manager/auth-manager/program-manager/permissions"+import ProgramStateStorage from "@server/core/link-manager/auth-manager/program-manager/state"import { test } from "vitest"test("permission requests contract", async () => {@@ -21,6 +21,7 @@ test("permission requests contract", async () => {let choice: boolean | null = nulllet whilePending: (() => void) | undefinedlet accessUpdates = 0+ let dialogProgram: Program | null = nullconst process = new Process("process", null, program, {}, { server: null, client: null, options: {} }, null, {} as HostTraffic, false,new Window({ title: "Client", header: true, frame: true, transaction: false, layer: "window" }, { x: 0, y: 0 }, { width: 640, height: 480 }, 1, false))@@ -28,7 +29,8 @@ test("permission requests contract", async () => {const authManager = {dialogManager: {- async requestPermission() {+ async requestPermission(target: Program) {+ dialogProgram = targetdialogs++whilePending?.()return choice@@ -47,52 +49,64 @@ test("permission requests contract", async () => {Object.assign(authManager, { programManager, processManager })const request = <Name extends PermissionName>(name: Name, value: PermissionRequest<Name> = true) => (- processManager.requestPermission("process", "request", name, value)+ programManager.requestPermission(program, "request", name, value, process)+ )+ const stored = () => new ProgramStateStorage(program).permissions()+ const assign = <Name extends PermissionName>(name: Name, value: Exclude<Permission<Name>, null>) => (+ new ProgramStateStorage(program).setPermission(name, value))// Stored authority never bypasses approval, even for a narrower request.- writePermissions(program, { services: ["browser", "editor"] })+ assign("services", ["browser", "editor"])assert.equal(await request("services", ["browser"]), null)assert.equal(dialogs, 1)- assert.deepEqual(readPermissions(program), { services: ["browser", "editor"] })+ assert.deepEqual(stored(), { services: ["browser", "editor"] })choice = falseassert.equal(await request("services", ["browser"]), false)assert.equal(dialogs, 2)- assert.deepEqual(readPermissions(program), { services: ["browser", "editor"] })+ assert.deepEqual(stored(), { services: ["browser", "editor"] })// Approval replaces the exact permission instead of widening or merging it.choice = trueassert.deepEqual(await request("services", ["browser"]), ["browser"])assert.equal(dialogs, 3)- assert.deepEqual(readPermissions(program), { services: ["browser"] })+ assert.deepEqual(stored(), { services: ["browser"] })++ // A Program handle requests for its target; the initiating Process is+ // only the request lifetime owner and never retargets the assignment.+ const target = new Program({ identity: "target", storage: join(temporary, "target"), permissions: {}, server: { location: ".", command: "node server.js" } })+ assert.deepEqual(await programManager.requestPermission(target, "owner-request", "uploads", true), [])+ assert.equal(dialogProgram, target)+ assert.deepEqual(new ProgramStateStorage(target).permissions(), { uploads: [] })+ assert.equal(stored().uploads, undefined)// A concurrent edit cannot turn one approved request into a broader grant.- whilePending = () => writePermissions(program, { services: ["editor"] })+ whilePending = () => assign("services", ["editor"])assert.deepEqual(await request("services", ["browser"]), ["browser"])- assert.deepEqual(readPermissions(program), { services: ["browser"] })+ assert.deepEqual(stored(), { services: ["browser"] })whilePending = undefined// An exact assignment restricts a broader fallback grant. Otherwise an// approved narrowing request would change the file without changing authority.- writePermissions(program, { all: [] })+ assign("all", [])assert.deepEqual(await request("network", ["https://api.example.com"]), ["https://api.example.com"])assert(programManager.grantsPermission(program, "network", ["https://api.example.com/v1"]))assert(!programManager.grantsPermission(program, "network", ["https://other.example.com"]))// Permission decisions read the authoritative stored state.const declared = new Program({ identity: "declared", storage: temporary, permissions: { programs: ["browser"] }, client: { location: "." } })- writePermissions(declared, { services: ["editor"] })+ new ProgramStateStorage(declared).setPermission("services", ["editor"])assert(!programManager.grantsPermission(declared, "services", ["browser"]))assert(programManager.grantsPermission(declared, "services", ["editor"]))// The iframe policy is synchronized independently of permission request results.- writePermissions(program, {})+ assign("all", false)assert.deepEqual(await request("all"), [])assert.equal(process.hosted().client?.sameOrigin, true)assert.equal(accessUpdates, 1)await programManager.setPermission(program, "all", [])assert.equal(accessUpdates, 1)- await programManager.deletePermission(program, "all")+ await programManager.setPermission(program, "all", false)assert.equal(process.hosted().client?.sameOrigin, false)assert.equal(accessUpdates, 2)}diff --git a/tests/process-find-or-create.test.ts b/tests/process-find-or-create.test.tsindex eb026f4..2d40595 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: { launch: { options: { document: "icon.txt" } } },+ config: {},reference: "example-reference",server: { start: true },client: {diff --git a/tests/program-creation.test.ts b/tests/program-creation.test.tsindex fa7c87b..5aeca52 100644--- a/tests/program-creation.test.ts+++ b/tests/program-creation.test.ts@@ -7,7 +7,7 @@ import type { ProgramPermissionDeclarations } from "@phreshos/core"import FileManager from "@libs/file-manager"import type AuthManager from "@server/core/link-manager/auth-manager/auth-manager"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 ProgramStateStorage from "@server/core/link-manager/auth-manager/program-manager/state"import Program from "@server/core/link-manager/auth-manager/program-manager/program"function fixture(context: TestContext) {@@ -19,7 +19,7 @@ function fixture(context: TestContext) {const announceHost = vi.fn()const auth = Object.assign(new TheLink(), {linkManager: { application: { storage: new FileManager(directory, "system"), defaultProgramIcon: "" } },- processManager: { processes: new Map(), exitAll: vi.fn(), announceHost, announceSubject: vi.fn() }+ processManager: { processes: new Map(), exitAll: vi.fn(), announceHost, announceSubject: vi.fn(), updateClientAccess: vi.fn() }}) as unknown as AuthManagerconst manager = new ProgramManager(auth)function definition(permissions?: ProgramPermissionDeclarations) {@@ -28,256 +28,120 @@ function fixture(context: TestContext) {return { directory, client, manager, announceHost, definition }}-test("creation establishes all declared settings before announcing the Program", async context => {- const { manager, definition, announceHost } = fixture(context)- announceHost.mockImplementation((_domain, event, _identity, entry) => {- if (event === "create") {- expect(readPermissions(entry.program)).toEqual({ network: ["https://api.example.test"], uploads: [] })- expect(JSON.parse(readFileSync(join(entry.program.storagePath, "startup.json"), "utf8"))).toEqual({})- expect(JSON.parse(readFileSync(join(entry.program.storagePath, "launch.json"), "utf8"))).toEqual({ name: "icon" })- }- })- const program = await manager.create({- ...definition({ network: ["https://api.example.test/**"], uploads: true }),- startup: true, launch: { name: "icon" }- })- expect(manager.find(program.identity).installed).toBe(false)- expect(JSON.parse(readFileSync(join(program.storagePath, "permissions.json"), "utf8"))).toEqual({ network: ["https://api.example.test"], uploads: [] })- expect(announceHost).toHaveBeenCalledOnce()-})--test("creation and force-create apply declared permissions without changing unrelated entries", async context => {+test("a Program definition supplies permission fallback without initializing state", async context => {const { manager, definition } = fixture(context)- const first = await manager.create(definition({ all: true }))- writePermissions(first, { appearance: [], network: [] })- const replacement = await manager.forceCreate(definition({ network: ["https://api.example.test"], services: ["example"] }))- expect(readPermissions(replacement)).toEqual({ appearance: [], network: ["https://api.example.test"], services: ["example"] })- await manager.forget(replacement)- const empty = await manager.create(definition())- expect(readPermissions(empty)).toEqual({ appearance: [], network: ["https://api.example.test"], services: ["example"] })- expect(existsSync(join(empty.storagePath, "permissions.json"))).toBe(true)-})+ const program = await manager.create(definition({ network: ["https://api.example.test/**"], uploads: true }))-test("invalid and duplicate creation leave stored authority and registry unchanged", async context => {- const { manager, definition, directory } = fixture(context)- const program = await manager.create(definition({ network: true }))- await expect(manager.create(definition({ all: true }))).rejects.toThrow("identity")- expect(readPermissions(program)).toEqual({ network: [] })- await expect(manager.forceCreate({ ...definition({ all: true }), client: { location: join(directory, "missing") } })).rejects.toThrow()- expect(manager.find(program.identity).program).toBe(program)- expect(readPermissions(program)).toEqual({ network: [] })+ expect(manager.permissions(program)).toEqual({ network: ["https://api.example.test"], uploads: [] })+ expect(existsSync(join(program.storagePath, "state.json"))).toBe(false)})-test("a permission write failure never publishes a new Program", async context => {- const { manager, definition, directory, announceHost } = fixture(context)- const storage = join(directory, "not-a-directory")- writeFileSync(storage, "keep this")- await expect(manager.create({ ...definition({ appearance: true }), storage })).rejects.toThrow()- expect(manager.programs.size).toBe(0)- expect(announceHost).not.toHaveBeenCalled()- expect(readFileSync(storage, "utf8")).toBe("keep this")-})+test("stored permission assignments override definition fallbacks by name", async context => {+ const { manager, definition } = fixture(context)+ let program = await manager.create(definition({ network: ["https://api.example.test"], uploads: true }))+ await manager.setPermission(program, "network", false)+ await manager.setPermission(program, "appearance", true)-test("boot reconstruction preserves all stored settings and launches the saved startup", async context => {- const { manager, definition, client } = fixture(context)- const directory = manager.fileManager.join("example")- mkdirSync(directory)- writeFileSync(join(directory, "program.json"), JSON.stringify({ ...definition({ all: true }), startup: true, launch: true, storage: "storage", client: { location: client } }))- mkdirSync(join(directory, "storage"))- writeFileSync(join(directory, "storage", "permissions.json"), JSON.stringify({ network: false }))- writeFileSync(join(directory, "storage", "launch.json"), JSON.stringify({ options: { document: "saved.txt" } }))- const startup = { name: "saved-startup" }- writeFileSync(join(directory, "storage", "startup.json"), JSON.stringify(startup))- const start = vi.spyOn(manager as unknown as { start(program: Program, launch: unknown): Promise<string> }, "start").mockResolvedValue("process")- await manager.initialize()- expect(readPermissions(manager.find("example").program)).toEqual({ network: false })- expect(await manager.launch(manager.find("example").program, "get")).toEqual({ options: { document: "saved.txt" } })- expect(await manager.startup(manager.find("example").program, "get")).toEqual(startup)- expect(start).toHaveBeenCalledExactlyOnceWith(manager.find("example").program, startup)-})+ expect(manager.permissions(program)).toEqual({ network: false, uploads: [], appearance: [] })-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(), 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)- program = await manager.forceCreate(definition())- expect(await manager.launch(program, "get")).toEqual(intent)- expect(await manager.startup(program, "get")).toEqual(intent)- for (const value of [true, {}] as const) {- await manager.launch(program, "set", intent)- await manager.startup(program, "enable", intent)- program = await manager.forceCreate({ ...definition(), launch: value, startup: value })- expect(await manager.launch(program, "get")).toEqual({})- expect(await manager.startup(program, "get")).toEqual({})- }- expect(manager.authManager.processManager.processes.size).toBe(0)+ program = await manager.forceCreate(definition({ network: true, services: ["editor"] }))+ expect(manager.permissions(program)).toEqual({ network: false, services: ["editor"], appearance: [] })})-test("undefined launch decisions leave existing bytes and absent files untouched", async context => {- const { manager, definition } = fixture(context)- let program = await manager.create({ ...definition(), startup: undefined, launch: undefined })- for (const name of ["startup", "launch"]) {- expect(existsSync(join(program.storagePath, `${name}.json`))).toBe(false)- }- const previous = '{ "name": "saved" }\n'- mkdirSync(program.storagePath, { recursive: true })- for (const name of ["startup", "launch"]) writeFileSync(join(program.storagePath, `${name}.json`), previous)- await manager.forget(program)- program = await manager.create({ ...definition(), startup: undefined, launch: undefined })- for (const name of ["startup", "launch"]) {- expect(readFileSync(join(program.storagePath, `${name}.json`), "utf8")).toBe(previous)- }- expect(readPermissions(program)).toEqual({})+test("a Program definition resolves System-owned paths into reusable creation input", context => {+ const { client } = fixture(context)+ const program = new Program({ identity: "example", client: { location: client } })++ expect(program.definition()).toEqual({+ identity: "example",+ version: "0.0.0",+ storage: program.storagePath,+ client: { location: client }+ })})-test("saved launch operations preserve defaults and reject invalid intent before mutation", async context => {+test("startup and pinned state share one file without overwriting each other", async context => {const { manager, definition } = fixture(context)const program = await manager.create(definition())- expect(await manager.launch(program, "get")).toBeNull()- expect(existsSync(join(program.storagePath, "launch.json"))).toBe(false)- await manager.launch(program, "set", { options: { document: "saved.txt" } })- for (const value of [undefined, false, { server: true }, { client: false }]) {- await expect(manager.launch(program, "set", value)).rejects.toThrow()- }- await expect(manager.forceCreate({ ...definition(), launch: { server: true } })).rejects.toThrow("no server")- await expect(manager.forceCreate({ ...definition(), startup: { server: true } })).rejects.toThrow("no server")- expect(manager.find("example").program).toBe(program)- expect(await manager.launch(program, "get")).toEqual({ options: { document: "saved.txt" } })-})+ const startup = { name: "background", options: { mode: "quiet" } }++ await manager.startup(program, "enable", startup)+ await manager.pinned(program, "pin")+ await manager.setPermission(program, "network", false)++ expect(await manager.startup(program, "get")).toEqual(startup)+ expect(await manager.pinned(program, "get")).toBe(true)+ expect(new ProgramStateStorage(program).permissions()).toEqual({ network: false })+ expect(JSON.parse(readFileSync(join(program.storagePath, "state.json"), "utf8"))).toEqual({+ startup,+ pinned: true,+ permissions: { network: false }+ })-test("installation applies saved launch decisions and preserves omitted ones", async context => {- const { manager, client } = fixture(context)- let entry = await manager.install(new Program({ identity: "example", client: { location: client }, launch: true }))- expect(await manager.launch(entry.program, "get")).toEqual({})- await manager.launch(entry.program, "set", { options: { document: "saved.txt" } })- entry = await manager.install(new Program({ identity: "example", client: { location: client } }))- expect(await manager.launch(entry.program, "get")).toEqual({ options: { document: "saved.txt" } })- entry = await manager.install(new Program({ identity: "example", client: { location: client }, launch: { name: "declaration" } }))- expect(await manager.launch(entry.program, "get")).toEqual({ name: "declaration" })+ await manager.startup(program, "disable")+ await manager.pinned(program, "unpin")+ expect(await manager.startup(program, "get")).toBeNull()+ expect(await manager.pinned(program, "get")).toBe(false)+ expect(new ProgramStateStorage(program).permissions()).toEqual({ network: false })})-test("failed creation restores both exact previous launch files", async context => {+test("Program state mutations do not rewrite an already-satisfied value", async context => {const { manager, definition } = fixture(context)- const storage = definition().storage- mkdirSync(join(storage, "permissions.json"), { recursive: true })- const previous = '{ "options": { "document": "previous.txt" } }\n'- writeFileSync(join(storage, "launch.json"), previous)- writeFileSync(join(storage, "startup.json"), previous)- await expect(manager.create({ ...definition({ appearance: true }), startup: true, launch: true })).rejects.toThrow()- expect(manager.programs.size).toBe(0)- expect(readFileSync(join(storage, "launch.json"), "utf8")).toBe(previous)- expect(readFileSync(join(storage, "startup.json"), "utf8")).toBe(previous)-})+ const program = await manager.create(definition())+ const startupWrite = vi.spyOn(ProgramStateStorage.prototype, "setStartup")+ const permissionWrite = vi.spyOn(ProgramStateStorage.prototype, "setPermission")+ context.onTestFinished(() => { startupWrite.mockRestore(); permissionWrite.mockRestore() })++ await manager.startup(program, "enable", { name: "background" })+ await manager.startup(program, "enable", { name: "background" })+ await manager.setPermission(program, "network", false)+ await manager.setPermission(program, "network", false)+ await manager.startup(program, "disable")+ await manager.startup(program, "disable")-test("a failed icon launch replacement rolls back startup before any announcement", async context => {- const { manager, definition, announceHost } = fixture(context)- const storage = definition().storage- mkdirSync(join(storage, "launch.json"), { recursive: true })- const previous = '{ "name": "previous-startup" }\n'- writeFileSync(join(storage, "startup.json"), previous)- await expect(manager.create({ ...definition(), startup: true, launch: true })).rejects.toThrow()- expect(readFileSync(join(storage, "startup.json"), "utf8")).toBe(previous)- expect(existsSync(join(storage, "permissions.json"))).toBe(false)- expect(manager.programs.size).toBe(0)- expect(announceHost).not.toHaveBeenCalled()+ expect(startupWrite).toHaveBeenCalledTimes(2)+ expect(permissionWrite).toHaveBeenCalledTimes(1)})-test("uninstalled Programs support startup and launch operations without creating Processes", async context => {- const { manager, definition } = fixture(context)+test("pinning emits Program and global events only when the boolean changes", async context => {+ const { manager, definition, announceHost } = fixture(context)const program = await manager.create(definition())- expect(manager.find(program.identity).installed).toBe(false)- await manager.startup(program, "enable")- expect(await manager.startup(program, "get")).toEqual({})- const intent = { name: "saved", options: { document: "file.txt" } }- await manager.startup(program, "enable", intent)- await manager.launch(program, "set", intent)- expect(await manager.startup(program, "get")).toEqual(intent)- expect(await manager.launch(program, "get")).toEqual(intent)- await expect(manager.startup(program, "enable", { server: true })).rejects.toThrow("no server")- expect(await manager.startup(program, "get")).toEqual(intent)- await manager.startup(program, "disable")- expect(await manager.startup(program, "get")).toBeNull()- expect(manager.authManager.processManager.processes.size).toBe(0)-})+ announceHost.mockClear()-test("installing an attached Program applies declarations to destination permissions", async context => {- const { manager, definition } = fixture(context)- const program = await manager.create(definition({ all: true }))- const sourceFile = join(program.storagePath, "permissions.json")- const installedStorage = manager.fileManager.join("example", "storage")- mkdirSync(installedStorage, { recursive: true })- writeFileSync(join(installedStorage, "permissions.json"), JSON.stringify({ appearance: [] }))+ await manager.pinned(program, "pin")+ await manager.pinned(program, "pin")+ await manager.pinned(program, "unpin")- const installed = await manager.install(program)- expect(installed.program.storagePath).toBe(installedStorage)- expect(readPermissions(installed.program)).toEqual({ appearance: [], all: [] })- expect(JSON.parse(readFileSync(sourceFile, "utf8"))).toEqual({ all: [] })+ expect(announceHost.mock.calls.map(([, event, , , pinned]) => [event, pinned])).toEqual([+ ["pinned", true],+ ["pinned", false]+ ])})-test("a fresh installation receives the declared permission in destination storage", async context => {- const { manager, definition } = fixture(context)- const program = await manager.create(definition({ appearance: true }))- const sourceStorage = program.storagePath- expect(readPermissions(program)).toEqual({ appearance: [] })- expect(manager.allowsPermission(program, "appearance")).toBe(true)- await manager.install(program)- expect(program.storagePath).not.toBe(sourceStorage)- expect(existsSync(join(program.storagePath, "permissions.json"))).toBe(true)- expect(readPermissions(program)).toEqual({ appearance: [] })- expect(manager.allowsPermission(program, "appearance")).toBe(true)-})+test("boot reconstruction reads startup and permissions from state", async context => {+ const { manager, definition, client } = fixture(context)+ const directory = manager.fileManager.join("example")+ mkdirSync(join(directory, "storage"), { recursive: true })+ writeFileSync(join(directory, "program.json"), JSON.stringify({ ...definition({ all: true }), storage: "storage", client: { location: client } }))+ const startup = { name: "saved-startup" }+ writeFileSync(join(directory, "storage", "state.json"), JSON.stringify({ startup, permissions: { network: false }, pinned: true }))+ const start = vi.spyOn(manager as unknown as { start(program: Program, launch: unknown): Promise<string> }, "start").mockResolvedValue("process")-test("empty permission declarations neither create nor touch permission files", async context => {- const { manager, definition } = fixture(context)- for (const permissions of [undefined, {}]) {- let program = await manager.forceCreate(definition(permissions))- const sourceFile = join(program.storagePath, "permissions.json")- expect(existsSync(sourceFile)).toBe(false)- await manager.install(program)- const destinationFile = join(program.storagePath, "permissions.json")- expect(existsSync(destinationFile)).toBe(false)- // Even unreadable stored contents must not be read or rewritten by an empty decision.- mkdirSync(program.storagePath, { recursive: true })- writeFileSync(destinationFile, "untouched destination")- await manager.install(program)- expect(readFileSync(destinationFile, "utf8")).toBe("untouched destination")- rmSync(destinationFile)- mkdirSync(definition().storage, { recursive: true })- writeFileSync(sourceFile, "untouched source")- program = await manager.forceCreate(definition(permissions))- expect(readFileSync(sourceFile, "utf8")).toBe("untouched source")- rmSync(sourceFile)- }+ await manager.initialize()+ const program = manager.find("example").program+ expect(manager.permissions(program)).toEqual({ all: [], network: false })+ expect(await manager.pinned(program, "get")).toBe(true)+ expect(start).toHaveBeenCalledExactlyOnceWith(program, startup)})-for (const previous of [false, true]) test(`failed installation rolls back declaration settings (previous files: ${previous})`, async context => {- const { manager, client } = fixture(context)- const original = new Program({ identity: "example", client: { location: client } })- const entry = await manager.install(original)- const storage = entry.program.storagePath- mkdirSync(storage, { recursive: true })- const files = {- permissions: '{ "uploads": [], "network": false }\n',- startup: '{ "name": "previous-startup" }\n',- launch: '{ "name": "previous-launch" }\n'- }- if (previous) for (const [name, bytes] of Object.entries(files)) writeFileSync(join(storage, `${name}.json`), bytes)- const declaration = readFileSync(join(entry.program.root, "program.json"), "utf8")- const replacement = vi.spyOn(entry.program, "replace").mockImplementationOnce(() => { throw new Error("registration failed") })- try {- await expect(manager.install(new Program({- identity: "example", startup: true, launch: true, permissions: { network: true },- client: { location: client }- }))).rejects.toThrow("registration failed")- }- finally { replacement.mockRestore() }- for (const [name, bytes] of Object.entries(files)) {- const path = join(storage, `${name}.json`)- if (previous) expect(readFileSync(path, "utf8")).toBe(bytes)- else expect(existsSync(path)).toBe(false)- }- expect(readFileSync(join(entry.program.root, "program.json"), "utf8")).toBe(declaration)+test("invalid creation leaves existing state and registry unchanged", async context => {+ const { manager, definition, directory } = fixture(context)+ const program = await manager.create(definition({ network: true }))+ await manager.setPermission(program, "network", false)++ await expect(manager.create(definition({ all: true }))).rejects.toThrow("identity")+ await expect(manager.forceCreate({ ...definition({ all: true }), client: { location: join(directory, "missing") } })).rejects.toThrow()++ expect(manager.find(program.identity).program).toBe(program)+ expect(manager.permissions(program)).toEqual({ network: false })})diff --git a/tests/program-icon-launch.test.ts b/tests/program-icon-launch.test.tsindex 58d6afa..84b14e7 100644--- a/tests/program-icon-launch.test.ts+++ b/tests/program-icon-launch.test.ts@@ -4,25 +4,18 @@ import type ProgramManager from "@client/core/link-manager/auth-manager/program-import RuntimeProgram from "@server/core/link-manager/auth-manager/program-manager/program"import Entry from "@server/core/link-manager/auth-manager/program-manager/entry"-test("opening a Program reads saved intent while direct creation uses its explicit request", async () => {- const intent = { options: { document: "icon.txt" }, client: { layer: "over" } }- const launch = vi.fn().mockResolvedValue(intent)+test("opening a Program uses Endpoint defaults while direct creation keeps its explicit request", async () => {const publish = vi.fn()- const manager = { launch, $outbound: { publish } } as unknown as ProgramManager+ const manager = { $outbound: { publish } } as unknown as ProgramManagerconst record = new Entry(new RuntimeProgram({ identity: "example", client: { location: "." } })).record()const program = new Program(manager, record)const address = { identity: record.identity, reference: record.reference }await program.open()- expect(launch).toHaveBeenCalledExactlyOnceWith(address, "get")- expect(publish).toHaveBeenLastCalledWith("/create-process", address, intent)- await program.createProcess()- expect(launch).toHaveBeenCalledOnce()expect(publish).toHaveBeenLastCalledWith("/create-process", address, {})- launch.mockResolvedValueOnce(null)+ await program.createProcess({ options: { document: "explicit.txt" } })+ expect(publish).toHaveBeenLastCalledWith("/create-process", address, { options: { document: "explicit.txt" } })await program.open()expect(publish).toHaveBeenLastCalledWith("/create-process", address, {})- launch.mockRejectedValueOnce(new Error("invalid stored launch"))- await expect(program.open()).rejects.toThrow("invalid stored launch")expect(publish).toHaveBeenCalledTimes(3)})diff --git a/tests/program-installation-lifecycle.test.ts b/tests/program-installation-lifecycle.test.tsindex 02eee39..3989fef 100644--- a/tests/program-installation-lifecycle.test.ts+++ b/tests/program-installation-lifecycle.test.ts@@ -21,15 +21,15 @@ function fixture(context: TestContext) {processManager: { processes: new Map(), exitAll, announceHost, announceSubject: vi.fn() }}) as unknown as AuthManagerconst manager = new ProgramManager(auth)- const definition = (installCommand = `node -e "process.stdout.write('preparing')"`) => new Program({+ const definition = (installCommand = `node -e "process.stdout.write('preparing')"`, installLaunch?: true | Launch) => new Program({identity: "example", storage: join(directory, "source", "storage"),- startup: { name: "startup" },+ installLaunch,server: { location: server, installCommand, command: "node main.js" }})return { directory, manager, exitAll, announceHost, definition }}-test("installation output precedes Process exit and handle switch; explicit launch precedes startup", async context => {+test("installation output precedes Process exit and handle switch; an explicit launch overrides the definition", 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)@@ -52,7 +52,7 @@ test("installation output precedes Process exit and handle switch; explicit launevents.push("output")})expect(result.program).toBe(old)- expect(events).toEqual(["output", "exit", "switch", "explicit", "startup"])+ expect(events).toEqual(["output", "exit", "switch", "explicit"])expect(exitAll).toHaveBeenCalledWith("example", "self")})@@ -76,7 +76,7 @@ test("System completes the requested launch after the installation output consumexpect((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(start.mock.calls.map(([, launch]) => launch.name)).toEqual(["explicit"])expect(manager.find("example").installed).toBe(true)})@@ -85,20 +85,33 @@ test("purge resets installed storage before launching and preserves source storaconst 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")+ mkdirSync(entry.program.storagePath, { recursive: true })writeFileSync(installedNote, "installed data")+ await manager.pinned(entry.program, "pin")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")+ expect(await manager.pinned(entry.program, "get")).toBe(true)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(await manager.pinned(entry.program, "get")).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("an omitted installation launch uses installLaunch and false disables it", 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")++ await manager.install(definition(undefined, { name: "welcome" }))+ await manager.install(definition(undefined, { name: "ignored" }), { launch: false })++ expect(start.mock.calls.map(([, launch]) => launch.name)).toEqual(["welcome"])})test("explicit launch errors propagate without rolling back the installed Program", async context => {@@ -115,10 +128,13 @@ test("uninstallation converges silently while its Program handle remains valid",const entry = await manager.install(definition())const program = entry.programconst home = manager.fileManager.join(program.identity)+ await manager.pinned(program, "pin")await manager.uninstall(program)expect(entry.installed).toBe(false)+ expect(await manager.pinned(program, "get")).toBe(true)+ expect(existsSync(join(program.storagePath, "state.json"))).toBe(true)expect(announceHost.mock.calls.filter(([, event]) => event === "uninstall")).toHaveLength(1)await manager.uninstall(program)diff --git a/tests/program-startup.test.ts b/tests/program-startup.test.tsdeleted file mode 100644index bf1f067..0000000--- a/tests/program-startup.test.ts+++ /dev/null@@ -1,88 +0,0 @@-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 } 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 LaunchStorage from "@server/core/link-manager/auth-manager/program-manager/launch-storage"--test("installation applies declared settings and launches the resulting stored startup", 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(new LaunchStorage(program, "startup").get()).toEqual(launch)- launches.push(launch)- return "process-identity"- })- function definition(setting?: true | Launch) {- return new Program({- identity: "example", startup: setting, permissions: { network: ["https://new.example.test"] },- client: { location: client }- })- }-- let entry = await manager.install(definition(true))- expect(launches).toEqual([{}])- expect(readPermissions(entry.program)).toEqual({ network: ["https://new.example.test"] })- const note = join(entry.program.storagePath, "note.txt")- writeFileSync(note, "keep this")- writePermissions(entry.program, { network: [], appearance: [] })- const configured = { name: "welcome", options: { language: "fr" } }- new LaunchStorage(entry.program, "startup").set(configured)- entry = await manager.install(definition(configured))- expect(launches).toEqual([{}, configured])- expect(readFileSync(note, "utf8")).toBe("keep this")- expect(readPermissions(entry.program)).toEqual({ network: ["https://new.example.test"], appearance: [] })-- for (const setting of [undefined, true] as const) {- entry = await manager.install(definition(setting))- expect(new LaunchStorage(entry.program, "startup").get()).toEqual(setting === true ? {} : configured)- expect(launches.at(-1)).toEqual(setting === true ? {} : configured)- }- expect(start).toHaveBeenCalledTimes(4)-- await manager.startup(entry.program, "disable")- entry = await manager.install(definition())- expect(existsSync(join(entry.program.storagePath, "startup.json"))).toBe(false)- expect(start).toHaveBeenCalledTimes(4)-- // Startup failure is reported without undoing a valid installation.- 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) })- expect(entry.installed).toBe(true)- expect(new LaunchStorage(entry.program, "startup").get()).toEqual({})- expect(warnings.join("")).toContain("Program installed, but startup failed: cannot start")-- await expect(manager.install(definition({ server: true }))).rejects.toThrow("no server")- expect(new LaunchStorage(entry.program, "startup").get()).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 = new LaunchStorage(program, "startup").replace({})- expect(new LaunchStorage(program, "startup").get()).toEqual({})- rollback()- expect(readFileSync(file, "utf8")).toBe("invalid prior content")-})