Skip to content

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

Release System 0.1.96

zohayrslileh1123e72d62b8
diff --git a/bun.lock b/bun.lock
index 8d0cf3a..365f802 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.62",
- "@phreshos/react-ui": "^0.1.41",
+ "@phreshos/core": "^0.1.63",
+ "@phreshos/react-ui": "^0.1.43",
"@the-link/core": "^0.3.1",
"@the-link/http": "^0.1.1",
"@the-link/ipc": "^0.2.2",
@@ -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-ifLLhfyqVGc8f/5DcDwlfMh6YKA6+1ODBD+KfvdY0BKynhr6Wbs3xPaah8+NQI4iHYyESD+v/N2qYkcfY2m0rg=="],
+ "@phreshos/core": ["@phreshos/[email protected]", "", { "dependencies": { "zod": "^4.6.5" } }, "sha512-wzIRrjok93QJQb/cpm5A/PVRm50x6FTP4Agj2l8kUsg1rkrTLZAU/iX63DlQ02hrkYypM0aEfhbpuZJn9jpV3Q=="],
- "@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "@base-ui/react": "^1.7.0", "@internationalized/date": "^3.12.3", "@phreshos/core": "^0.1.62", "colorjs.io": "^0.7.1", "lucide-react": "^1.48.0", "react-aria": "^3.51.0", "react-aria-components": "^1.20.0" }, "peerDependencies": { "react": "^19.2.0", "react-dom": "^19.2.0" } }, "sha512-jlfEuTDjcfIao+kQTR3FhEXU01WB7/gBmvcE5hZZt3/P8qN4wFlEqjDPW8Y5WhfPOrUI6TqcZI+aYazZgx0ekw=="],
+ "@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "@base-ui/react": "^1.7.0", "@internationalized/date": "^3.12.3", "@phreshos/core": "^0.1.63", "colorjs.io": "^0.7.1", "lucide-react": "^1.48.0", "react-aria": "^3.51.0", "react-aria-components": "^1.20.0" }, "peerDependencies": { "react": "^19.2.0", "react-dom": "^19.2.0" } }, "sha512-v8SFWHo3LVdBEMfIkFDdbBOnBbIlG5UB5iuOQSjbl1OB64wTdBW4R44QPZsCkKeiW/9dzYQWAVirZ68XFYdVsA=="],
"@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.json
index a0125cb..48abe81 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "phreshos",
"displayName": "PhreshOS",
- "version": "0.1.95",
+ "version": "0.1.96",
"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.62",
- "@phreshos/react-ui": "^0.1.41",
+ "@phreshos/core": "^0.1.63",
+ "@phreshos/react-ui": "^0.1.43",
"@the-link/core": "^0.3.1",
"@the-link/http": "^0.1.1",
"@the-link/ipc": "^0.2.2",
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.ts
index f629c61..88c42d7 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
@@ -101,11 +101,9 @@ export default class ProcessManager extends TheLink {
return await this.$outbound.publishFirst("/service/available", address) as boolean
}
- public async listServices(name?: string) {
+ public async listServices(options: { name?: string } = {}) {
- const route = name === undefined ? "/service/list" : "/service/search"
-
- return await this.$outbound.publishFirst(route, ...name === undefined ? [] : [name]) as ServiceAddress[]
+ return await this.$outbound.publishFirst("/service/list", options) as ServiceAddress[]
}
public async waitServiceReady(address: ServiceAddress, timeout: number | undefined) {
diff --git a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts
index e2aaa4d..3a9fd22 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
@@ -63,7 +63,7 @@ export default class ProgramManager extends TheLink {
// pane's store words with this, so a client half means the same
// thing by them as a server half does — one implementation, two
// roads to it.
- public async store(subject: unknown, operation: string, key: string, value?: unknown, ttl?: number) {
+ public async store(subject: unknown, operation: string, key: string, value?: unknown, ttl?: unknown) {
return await this.$outbound.publishFirst("/store", subject, operation, key, value, ttl)
}
diff --git a/source/client/view/components/desktop-host/announcements.ts b/source/client/view/components/desktop-host/announcements.ts
index 7581520..0709204 100644
--- a/source/client/view/components/desktop-host/announcements.ts
+++ b/source/client/view/components/desktop-host/announcements.ts
@@ -197,6 +197,12 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
post(entry.identity, "program-host", "permissions", entry.reference, record)
}, [post]))
+ programs.useSubscribe("/store-change", useCallback((reference: unknown, key: unknown, snapshot: unknown) => {
+ if (typeof reference !== "string" || typeof key !== "string") return
+ const entry = [...authManager.programManager.programs.values()].find(program => program.reference === reference)
+ if (entry) post(entry.identity, "program-host", "storeChange", reference, key, snapshot)
+ }, [authManager, post]))
+
programs.useSubscribe("/log", useCallback((reference: unknown, record: unknown) => {
if (typeof reference !== "string") return
diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.ts
index 1766825..4fc3235 100644
--- a/source/client/view/components/desktop-host/host.ts
+++ b/source/client/view/components/desktop-host/host.ts
@@ -17,6 +17,8 @@ import {
parsePermission,
parsePermissionName,
parsePermissions,
+ parseSystemProgramListOptions,
+ parseSystemServiceListOptions,
type PermissionRequestInput,
type ProgramIconSize
} from "@phreshos/core"
@@ -191,7 +193,8 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (word === "host-program-list") {
- const programs = [...programManager.programs.values()].filter(program => args[0] !== true || program.installed)
+ const { installed } = parseSystemProgramListOptions(args[0])
+ const programs = [...programManager.programs.values()].filter(program => installed === undefined || program.installed === installed)
const visible = []
for (const program of programs) if (await access.canProgram(program)) visible.push(program)
@@ -397,13 +400,11 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
return [await processManager.endpointIsService(pane, address(target), endpoint)]
}
- if (word === "host-service-list" || word === "host-service-search") {
+ if (word === "host-service-list") {
- const name = word === "host-service-search" ? args[0] : undefined
+ const options = parseSystemServiceListOptions(args[0])
- if (name !== undefined && (typeof name !== "string" || !name.trim())) throw new Error("A Service name is required")
-
- const services = await processManager.listServices(name)
+ const services = await processManager.listServices(options)
const visible = []
for (const service of services) if (await access.canService(service)) visible.push(service)
@@ -1017,7 +1018,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (word === "store") {
- const [subject, operation, key, value, ttl] = args as [unknown, string, string, unknown, number | undefined]
+ const [subject, operation, key, value, ttl] = args as [unknown, string, string, unknown, unknown]
return [await programManager.store(address(await permittedProgram(subject)), operation, key, value, ttl)]
}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
index 5142dc0..9385c33 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
@@ -21,6 +21,8 @@ import {
parsePermissionName,
parseProgramInstallOptions,
parseProgramUninstallOptions,
+ parseSystemProgramListOptions,
+ parseSystemServiceListOptions,
type ClientLaunch,
type Launch,
type Permission,
@@ -1603,14 +1605,9 @@ export default class ProcessManager extends TheLink {
}
@Subscribe("/service/list")
- protected async listServices() { return this.services.list() }
+ protected async listServices(options: unknown = {}) {
- @Subscribe("/service/search")
- protected async searchServices(name: unknown) {
-
- if (typeof name !== "string" || !name.trim()) throw new Error("A Service name is required")
-
- return this.services.list(name)
+ return this.services.list(parseSystemServiceListOptions(options).name)
}
@Subscribe("/service/wait-ready")
@@ -1874,7 +1871,7 @@ export default class ProcessManager extends TheLink {
return value
}
- if (word === "host-program-list") return [this.system.listPrograms(rest[0] === true).filter(program => access.canProgram(program))]
+ if (word === "host-program-list") return [this.system.listPrograms(parseSystemProgramListOptions(rest[0])).filter(program => access.canProgram(program))]
if (typeof word === "string" && word.startsWith("host-authentication-")) {
@@ -2272,15 +2269,11 @@ export default class ProcessManager extends TheLink {
if (word === "stop-current") return [await this.system.stopEndpoint(process, "server")]
- if (word === "host-service-list") return [this.services.list().filter(address => this.grants(process.identity, "services", [address.process]))]
-
- if (word === "host-service-search") {
-
- const name = rest[0]
+ if (word === "host-service-list") {
- if (typeof name !== "string" || !name.trim()) throw new Error("A Service name is required")
+ const { name } = parseSystemServiceListOptions(rest[0])
- return [this.grants(process.identity, "services", [name]) ? this.services.list(name) : []]
+ return [this.services.list(name).filter(address => this.grants(process.identity, "services", [address.process]))]
}
if (word === "service-available") return [this.services.available(heldService(rest[0]))]
@@ -2761,7 +2754,7 @@ export default class ProcessManager extends TheLink {
// expose only the values the application actually owns.
if (word === "store") {
- const [operation, key, value, ttl] = rest.slice(1) as [string, string, unknown, number | undefined]
+ const [operation, key, value, ttl] = rest.slice(1) as [string, string, unknown, unknown]
const whose = heldProgram(rest[0])
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
index 4445e18..24fbf52 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
@@ -5,7 +5,7 @@ import { TheLink } from "@the-link/core"
import SqliteDatabase from "@libs/sqlite-database"
import FileManager from "@libs/file-manager"
import FileArea from "@libs/file-area"
-import openStore from "@server/core/open-store"
+import ProgramStoreState, { type StoreSnapshot } from "./program-store"
import AuthManager from "../auth-manager"
import { dirname, isAbsolute, join } from "node:path"
import { isDeepStrictEqual } from "node:util"
@@ -16,7 +16,6 @@ import { type default as Process, type ProcessLaunch, type Stream } from "../pro
import { type StandardShape } from "../process-manager/process-manager"
import Program, { type CommandOutput, type InstallOutput } from "./program"
import Entry, { type ProgramRecord } from "./entry"
-import Keyv from "keyv"
import { isIconSize, ProgramIcons } from "./icon"
import { permissionCatalog } from "@server/core/permissions"
import ProgramStateStorage from "./state"
@@ -77,7 +76,7 @@ export default class ProgramManager extends TheLink {
// What each program remembers about itself, opened on first use and
// kept by the identity of the program that asked.
- private readonly opened = new Map<string, Keyv>()
+ private readonly opened = new Map<string, ProgramStoreState>()
// What each program's halves have said. Opened like the store above
// and dropped in the same place, because it is the same kind of
@@ -547,7 +546,11 @@ export default class ProgramManager extends TheLink {
if (already) return already
- const store = openStore(program.storagePath)
+ const store = new ProgramStoreState(program.storagePath, (key, snapshot) => {
+ // The System is the only publisher; endpoint adapters must consume, never echo, this fact.
+ this.authManager.processManager.announceSubject("program", "storeChange", program.reference, key, snapshot).catch(() => undefined)
+ this.$outbound.publish("/store-change", program.reference, key, snapshot).catch(() => undefined)
+ })
this.opened.set(program.identity, store)
@@ -709,18 +712,24 @@ export default class ProgramManager extends TheLink {
return pinned
}
- // A store's five controls, in one place. Reached from a process
+ // A store's 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;
// application persistence has no generic route through this manager.
@Subscribe("/store")
- public async store(subject: unknown, operation: string, key: string, value?: unknown, ttl?: number) {
+ public async store(subject: unknown, operation: string, key: string, value?: unknown, ttl?: unknown) {
const store = this.storeOf(this.held(subject))
if (operation === "get") return await store.get(key) as unknown
- if (operation === "set") return await store.set(key, value, ttl)
+ if (operation === "set") return await store.set(key, value, ttl as number | undefined)
+
+ if (operation === "getOrSet") return await store.getOrSet(key, value)
+
+ if (operation === "snapshot") return await store.snapshot(key)
+
+ if (operation === "compareAndSet") return await store.compareAndSet(key, value, ttl as StoreSnapshot)
if (operation === "delete") return await store.delete(key as string | string[])
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program-store.ts b/source/server/core/link-manager/auth-manager/program-manager/program-store.ts
new file mode 100644
index 0000000..2cfb28c
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/program-manager/program-store.ts
@@ -0,0 +1,151 @@
+import { randomUUID } from "node:crypto"
+import { isDeepStrictEqual } from "node:util"
+import openStore from "@server/core/open-store"
+
+export type StoreSnapshot = Readonly<{ run: string, revision: number, value: unknown }>
+export type StoreComparison = Readonly<{ changed: boolean, snapshot: StoreSnapshot }>
+
+type Stored = Readonly<{ value: unknown, expires?: number }>
+const maximumTimer = 2_147_483_647
+
+/** Serializes one Program's writes and publishes only authoritative store changes. */
+export default class ProgramStoreState {
+ private readonly store
+ private readonly runId = randomUUID()
+ private readonly revisions = new Map<string, number>()
+ private readonly known = new Set<string>()
+ private readonly timers = new Map<string, ReturnType<typeof setTimeout>>()
+ private queued: Promise<void> = Promise.resolve()
+
+ public constructor(directory: string, private readonly changed: (key: string, snapshot: StoreSnapshot) => void) {
+ this.store = openStore(directory)
+ }
+
+ public get(key: string) { return this.enqueue(async () => (await this.read(key))?.value) }
+
+ public has(key: string) { return this.enqueue(async () => (await this.read(key)) !== undefined) }
+
+ public snapshot(key: string) {
+ return this.enqueue(async () => this.current(key, await this.read(key)))
+ }
+
+ public set(key: string, value: unknown, ttl?: number) {
+ return this.enqueue(async () => {
+ const previous = await this.read(key)
+ const result = await this.store.set(key, value, ttl)
+ const next = await this.read(key)
+ if (!isDeepStrictEqual(previous, next)) this.publish(key, next)
+ return result
+ })
+ }
+
+ public getOrSet(key: string, initial: unknown) {
+ return this.enqueue(async () => {
+ const existing = await this.read(key)
+ if (existing) return this.current(key, existing)
+ await this.store.set(key, initial)
+ const stored = await this.read(key)
+ this.publish(key, stored)
+ return this.current(key, stored)
+ })
+ }
+
+ public compareAndSet(key: string, value: unknown, expected: Pick<StoreSnapshot, "run" | "revision">): Promise<StoreComparison> {
+ return this.enqueue(async () => {
+ const previous = await this.read(key)
+ const snapshot = this.current(key, previous)
+ if (expected?.run !== snapshot.run || expected.revision !== snapshot.revision) return { changed: false, snapshot }
+ if (previous && isDeepStrictEqual(previous.value, value)) return { changed: true, snapshot }
+
+ // An update must not silently turn an expiring value into durable state.
+ const ttl = previous?.expires === undefined ? undefined : Math.max(1, previous.expires - Date.now())
+ await this.store.set(key, value, ttl)
+ const next = await this.read(key)
+ this.publish(key, next)
+ return { changed: true, snapshot: this.current(key, next) }
+ })
+ }
+
+ public delete(keys: string | string[]) {
+ return this.enqueue(async () => {
+ let deleted = false
+ for (const key of new Set(Array.isArray(keys) ? keys : [keys])) {
+ const previous = await this.read(key)
+ if (!previous) continue
+ if (await this.store.delete(key)) {
+ deleted = true
+ this.known.delete(key)
+ this.cancel(key)
+ this.publish(key, undefined)
+ }
+ }
+ return deleted
+ })
+ }
+
+ public clear() {
+ return this.enqueue(async () => {
+ const keys = [...this.known.keys()]
+ await this.store.clear()
+ for (const key of keys) {
+ if (!this.known.has(key)) continue
+ this.known.delete(key)
+ this.cancel(key)
+ this.publish(key, undefined)
+ }
+ })
+ }
+
+ public async disconnect() {
+ await this.queued
+ for (const key of this.timers.keys()) this.cancel(key)
+ await this.store.disconnect()
+ }
+
+ private current(key: string, stored: Stored | undefined): StoreSnapshot {
+ return { run: this.runId, revision: this.revisions.get(key) ?? 0, value: stored?.value }
+ }
+
+ private async read(key: string): Promise<Stored | undefined> {
+ const raw = await this.store.getRaw(key)
+ const stored = raw === undefined ? undefined : { value: raw.value, expires: raw.expires ?? undefined }
+ if (stored) {
+ this.known.add(key)
+ this.schedule(key, stored.expires)
+ } else {
+ this.cancel(key)
+ if (this.known.delete(key)) this.publish(key, undefined)
+ }
+ return stored
+ }
+
+ private schedule(key: string, expires?: number) {
+ this.cancel(key)
+ if (expires === undefined) return
+ const delay = Math.min(maximumTimer, Math.max(1, expires - Date.now() + 1))
+ const timer = setTimeout(() => {
+ this.timers.delete(key)
+ void this.enqueue(() => this.read(key)).catch(() => undefined)
+ }, delay)
+ timer.unref?.()
+ this.timers.set(key, timer)
+ }
+
+ private cancel(key: string) {
+ const timer = this.timers.get(key)
+ if (timer) clearTimeout(timer)
+ this.timers.delete(key)
+ }
+
+ private publish(key: string, stored: Stored | undefined) {
+ const revision = (this.revisions.get(key) ?? 0) + 1
+ this.revisions.set(key, revision)
+ this.changed(key, { run: this.runId, revision, value: stored?.value })
+ }
+
+ private enqueue<Result>(operation: () => Promise<Result>): Promise<Result> {
+ const running = this.queued.then(operation)
+ this.queued = running.then(() => undefined, () => undefined)
+ return running
+ }
+}
diff --git a/source/server/core/system.ts b/source/server/core/system.ts
index a44b42d..0606b64 100644
--- a/source/server/core/system.ts
+++ b/source/server/core/system.ts
@@ -9,6 +9,7 @@ import type {
Launch,
ProgramInstallOptions,
ProgramUninstallOptions,
+ SystemProgramListOptions,
PermissionInput,
PermissionName,
Position,
@@ -42,9 +43,9 @@ export default class System {
return shell(command, options)
}
- public listPrograms(onlyInstalled = false) {
+ public listPrograms(options: SystemProgramListOptions = {}) {
- return [...this.programManager.programs.values()].filter(entry => !onlyInstalled || entry.installed)
+ return [...this.programManager.programs.values()].filter(entry => options.installed === undefined || entry.installed === options.installed)
}
public findProgram(identity: string) {
@@ -536,7 +537,7 @@ export default class System {
return this.application.home.watch(joins, recursive, signal)
}
- public programStore(program: Program, operation: string, key: string, value?: unknown, ttl?: number) {
+ public programStore(program: Program, operation: string, key: string, value?: unknown, ttl?: unknown) {
return this.programManager.store(program, operation, key, value, ttl)
}
diff --git a/tests/client-permission-boundary.test.ts b/tests/client-permission-boundary.test.ts
index 0ea1697..01a53f2 100644
--- a/tests/client-permission-boundary.test.ts
+++ b/tests/client-permission-boundary.test.ts
@@ -43,8 +43,10 @@ test("Program and Process discovery exposes only the accessible scope", async ()
let permissions: Permissions = {}
const owner = program("owner")
+ Object.defineProperty(owner, "installed", { value: true })
Object.defineProperty(owner, "permissions", { get: () => permissions })
const outside = program("outside")
+ Object.defineProperty(outside, "installed", { value: false })
outside.permissions = { network: ["https://example.com"] }
const current = process("current", owner)
const hidden = process("hidden", outside)
@@ -68,6 +70,9 @@ test("Program and Process discovery exposes only the accessible scope", async ()
expect.objectContaining({ identity: owner.identity }),
expect.objectContaining({ identity: outside.identity })
]])
+ await expect(answer("host-program-list", { installed: true })).resolves.toEqual([[expect.objectContaining({ identity: owner.identity })]])
+ await expect(answer("host-program-list", { installed: false })).resolves.toEqual([[expect.objectContaining({ identity: outside.identity })]])
+ await expect(answer("host-program-list", true)).rejects.toThrow(/object/)
await expect(answer("host-process-list")).resolves.toEqual([[
expect.objectContaining({ identity: current.identity }),
expect.objectContaining({ identity: hidden.identity })
@@ -252,7 +257,7 @@ test("Service discovery filters ready addresses only by Service-name authority",
const mainServer = { program: "notes", process: "main", endpoint: "server" } as const
const mainClient = { program: "editor", process: "main", endpoint: "client" } as const
const background = { program: "notes", process: "background", endpoint: "server" } as const
- const listServices = vi.fn(async (name?: string) => [mainServer, mainClient, background].filter(service => name === undefined || service.process === name))
+ const listServices = vi.fn(async (options: { name?: string } = {}) => [mainServer, mainClient, background].filter(service => options.name === undefined || service.process === options.name))
const auth = {
programManager: { programs: new Map([["owner", { identity: "owner", get permissions() { return permissions } }]]) },
processManager: {
@@ -264,13 +269,14 @@ test("Service discovery filters ready addresses only by Service-name authority",
const answer = host(auth, "caller", () => { throw new Error("unused viewport") }, () => "frame", moveCoordinates(), {} as never)
await expect(answer("host-service-list")).resolves.toEqual([[]])
- await expect(answer("host-service-search", "main")).resolves.toEqual([[]])
+ await expect(answer("host-service-list", { name: "main" })).resolves.toEqual([[]])
permissions = { services: ["main"] }
await expect(answer("host-service-list")).resolves.toEqual([[mainServer, mainClient]])
- await expect(answer("host-service-search", "main")).resolves.toEqual([[mainServer, mainClient]])
- await expect(answer("host-service-search", "background")).resolves.toEqual([[]])
+ await expect(answer("host-service-list", { name: "main" })).resolves.toEqual([[mainServer, mainClient]])
+ await expect(answer("host-service-list", { name: "background" })).resolves.toEqual([[]])
+ await expect(answer("host-service-list", "main")).rejects.toThrow(/object/)
permissions = { services: [] }
diff --git a/tests/host-traffic.test.ts b/tests/host-traffic.test.ts
index d4a72f6..bc63265 100644
--- a/tests/host-traffic.test.ts
+++ b/tests/host-traffic.test.ts
@@ -12,6 +12,7 @@ test("host traffic contract", async () => {
const ownSession: unknown[][] = []
const systemLogs: unknown[][] = []
const programLogs: unknown[][] = []
+ const storeChanges: unknown[][] = []
traffic.observe("program", "uninstall", null, (_delivery, event, ...values) => hostProgram.push([event, ...values]))
traffic.observe("program", "uninstall", "program-reference", (_delivery, event, ...values) => ownProgram.push([event, ...values]))
@@ -21,6 +22,7 @@ test("host traffic contract", async () => {
traffic.observe("session", "connectionAttach", "session-identity", (_delivery, event, ...values) => ownSession.push([event, ...values]))
traffic.observe("log", "log", null, (_delivery, event, ...values) => systemLogs.push([event, ...values]))
traffic.observe("programLog", "log", "program-reference", (_delivery, event, ...values) => programLogs.push([event, ...values]))
+ traffic.observe("program", "storeChange", "program-reference", (_delivery, event, ...values) => storeChanges.push([event, ...values]))
const program = { identity: "counter", reference: "program-reference" }
const process = { identity: "worker", reference: "process-reference" }
@@ -43,9 +45,11 @@ test("host traffic contract", async () => {
await traffic.emitSubject("session", "connectionAttach", "session-identity", { identity: "connection-identity" })
await traffic.emitHost("log", "log", "system", { kind: "started" })
await traffic.emitSubject("programLog", "log", "program-reference", { kind: "stdout" })
+ await traffic.emitSubject("program", "storeChange", "program-reference", "tab", { revision: 1, value: "colors" })
assert.deepEqual(hostConnection, [["create", "connection-identity", { identity: "connection-identity" }]])
assert.deepEqual(ownSession, [["connectionAttach", "session-identity", { identity: "connection-identity" }]])
assert.deepEqual(systemLogs, [["log", "system", { kind: "started" }]])
assert.deepEqual(programLogs, [["log", "program-reference", { kind: "stdout" }]])
+ assert.deepEqual(storeChanges, [["storeChange", "program-reference", "tab", { revision: 1, value: "colors" }]])
}, 120_000)
diff --git a/tests/program-creation.test.ts b/tests/program-creation.test.ts
index 987cf85..764334b 100644
--- a/tests/program-creation.test.ts
+++ b/tests/program-creation.test.ts
@@ -143,6 +143,30 @@ test("pinning emits Program and global events only when the boolean changes", as
])
})
+test("Program store changes originate once at System and retain their key revisions", async context => {
+ const { manager, definition, announceSubject } = fixture(context)
+ announceSubject.mockResolvedValue(undefined)
+ const program = await manager.create(definition())
+ const delivered: Array<[string, string, { revision: number, value: unknown }]> = []
+ const stop = manager.$outbound.subscribe("/store-change", (reference, key, snapshot) => {
+ delivered.push([reference, key, snapshot])
+ })
+ context.onTestFinished(stop)
+
+ const initial = await manager.store(program, "snapshot", "tab") as { run: string, revision: number, value: unknown }
+ expect(initial.value).toBeUndefined()
+ expect((await manager.store(program, "compareAndSet", "tab", "colors", initial) as { changed: boolean }).changed).toBe(true)
+ expect((await manager.store(program, "compareAndSet", "tab", "old", initial) as { changed: boolean }).changed).toBe(false)
+ await manager.store(program, "delete", "tab")
+
+ expect(delivered.map(([, key, snapshot]) => [key, snapshot.revision, snapshot.value])).toEqual([
+ ["tab", 1, "colors"], ["tab", 2, undefined]
+ ])
+ expect(announceSubject.mock.calls.map(([, event, subject]) => [event, subject])).toEqual([
+ ["storeChange", program.reference], ["storeChange", program.reference]
+ ])
+})
+
test("boot reconstruction reads startup and permissions from state", async context => {
const { manager, definition, client } = fixture(context)
const directory = manager.fileManager.join("example")
diff --git a/tests/program-store.test.ts b/tests/program-store.test.ts
new file mode 100644
index 0000000..eb04be8
--- /dev/null
+++ b/tests/program-store.test.ts
@@ -0,0 +1,91 @@
+import { mkdtempSync, rmSync } from "node:fs"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+import { afterEach, describe, expect, it } from "vitest"
+import ProgramStoreState, { type StoreSnapshot } from "../source/server/core/link-manager/auth-manager/program-manager/program-store.js"
+
+const opened: Array<{ directory: string, store: ProgramStoreState }> = []
+
+function store() {
+ const directory = mkdtempSync(join(tmpdir(), "phresh-program-store-"))
+ const changes: Array<{ key: string, snapshot: StoreSnapshot }> = []
+ const instance = new ProgramStoreState(directory, (key, snapshot) => changes.push({ key, snapshot }))
+ opened.push({ directory, store: instance })
+ return { instance, changes }
+}
+
+afterEach(async () => {
+ for (const { directory, store } of opened.splice(0)) {
+ await store.disconnect()
+ rmSync(directory, { recursive: true, force: true })
+ }
+})
+
+describe("ProgramStoreState", () => {
+ it("seeds only an absent key, including when an existing value is undefined", async () => {
+ const { instance, changes } = store()
+ expect((await instance.getOrSet("tab", "colors")).value).toBe("colors")
+ expect((await instance.getOrSet("tab", "layout")).value).toBe("colors")
+ await instance.set("optional", undefined)
+ expect((await instance.getOrSet("optional", "replacement")).value).toBeUndefined()
+ expect(await instance.has("optional")).toBe(true)
+ expect(changes.filter(change => change.key === "tab")).toHaveLength(1)
+ })
+
+ it("initializes one missing key atomically across competing snapshots", async () => {
+ const { instance, changes } = store()
+ const initial = await instance.snapshot("tab")
+ const [first, second] = await Promise.all([
+ instance.compareAndSet("tab", "colors", initial),
+ instance.compareAndSet("tab", "layout", initial)
+ ])
+
+ expect([first.changed, second.changed].sort()).toEqual([false, true])
+ expect(await instance.get("tab")).toBe(first.changed ? "colors" : "layout")
+ expect(changes).toHaveLength(1)
+ expect(changes[0]?.snapshot.revision).toBe(1)
+ })
+
+ it("publishes changes for set, delete, clear, and TTL expiry", async () => {
+ const { instance, changes } = store()
+ await instance.snapshot("tab")
+ await instance.set("tab", "colors")
+ await instance.delete("tab")
+ await instance.set("tab", "layout")
+ await instance.clear()
+ await instance.set("tab", "temporary", 15)
+
+ await new Promise(resolve => setTimeout(resolve, 35))
+
+ expect(changes.map(change => change.snapshot.value)).toEqual([
+ "colors", undefined, "layout", undefined, "temporary", undefined
+ ])
+ expect(await instance.get("tab")).toBeUndefined()
+ })
+
+ it("preserves an existing expiry when a compare-and-set changes its value", async () => {
+ const { instance, changes } = store()
+ await instance.set("count", 1, 25)
+ const snapshot = await instance.snapshot("count")
+ expect((await instance.compareAndSet("count", 2, snapshot)).changed).toBe(true)
+ await new Promise(resolve => setTimeout(resolve, 45))
+ expect(await instance.get("count")).toBeUndefined()
+ expect(changes.at(-1)?.snapshot.value).toBeUndefined()
+ })
+
+ it("recovers a persisted deadline and notifies when that key expires", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "phresh-program-store-restart-"))
+ const first = new ProgramStoreState(directory, () => undefined)
+ try {
+ await first.set("session", "live", 250)
+ await first.disconnect()
+ const changes: StoreSnapshot[] = []
+ const second = new ProgramStoreState(directory, (_key, snapshot) => changes.push(snapshot))
+ try {
+ expect((await second.snapshot("session")).value).toBe("live")
+ await new Promise(resolve => setTimeout(resolve, 300))
+ expect(changes.at(-1)?.value).toBeUndefined()
+ } finally { await second.disconnect() }
+ } finally { rmSync(directory, { recursive: true, force: true }) }
+ })
+})